code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
<?php
echo file_get_contents("header.inc.php");
?>
<?php
$displayedposts = 0;
$json = file_get_contents( "http://maschini.de:5001/api");
$file = json_decode($json, true);
if(isset($_GET["category"])){
$category = $_GET["category"];
$category = htmlspecialchars($category);
}
else{
$category = "";
}
if($category != ""){
foreach ($file as $entry) {
if($_GET["category"] == $entry["category"]){
echo "<table align=\"center\" width=\"1000px\" style='padding: 50px 0'>";
echo "<tr>";
echo "<td class=\"rating\" style=\"background-color:rgb(255,". floor(rand(0,255)).",0);\"></td>";
echo "<td class=\"image\"><img src=\"" . ($entry["imglink"] == "" || $entry["author"] == "FAZ" ? "../black.jpeg" : $entry["imglink"]) . "\" width=\"300px\" height=\"200px\"></td>";
echo "<td class=\"content\">";
echo "<h2><a href=\"" . $entry["link"] . "\" target='blank'>" . $entry["heading"] . "</a></h2>";
echo "<span>" . $entry["date"] . ": " . $entry["author"] . "</span><br>";
echo "<div class=\"text\">" . $entry["article"] . "</div>";
echo "</td>";
echo "</tr>";
echo "</table>";
$displayposts ++;
}
else{
}
}
}
else{
foreach ($file as $entry) {
echo "<table align=\"center\" width=\"1000px\" style='padding: 50px 0'>";
echo "<tr>";
echo "<td class=\"rating\" style=\"background-color:rgb(255,". floor(rand(0,255)).",0);\"></td>";
echo "<td class=\"image\"><img src=\"" . ($entry["imglink"] == "" || $entry["author"] == "FAZ" ? "../black.jpeg" : $entry["imglink"]) . "\" width=\"300px\" height=\"200px\"></td>";
echo "<td class=\"content\">";
echo "<h2><a href=\"" . $entry["link"] . "\" target='blank'>" . $entry["heading"] . "</a></h2>";
echo "<span>" . $entry["date"] . ": " . $entry["author"] . "</span><br>";
echo "<div class=\"text\">" . $entry["article"] . "</div>";
echo "</td>";
echo "</tr>";
echo "</table>";
}
}
if($displayedposts < 1){
echo "<h1 class='black'>In dieser Kategorie gibt es aktuell leider keine Neuigkeiten</h1>";
}
?>
</body>
</html>
|
DatenParty/Webseite
|
newWEB/index.php
|
PHP
|
mit
| 2,703
|
<?php
namespace AppBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
class ProvidedServiceTypeAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper->add('name')
->add('price', 'tbbc_money');
}
protected function configureListFields(ListMapper $listMapper)
{
$listMapper->addIdentifier('id')
->add('name')
->add('price', 'money')
->add('_action', 'actions', [
'actions' => [
'edit' => []
]
]);
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper->add('name');
}
}
|
sugatov/web-pms
|
src/AppBundle/Admin/ProvidedServiceTypeAdmin.php
|
PHP
|
mit
| 862
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_27) on Wed Nov 21 16:03:52 EST 2012 -->
<TITLE>
org.pentaho.di.ui.job.entries.ftpdelete
</TITLE>
<META NAME="date" CONTENT="2012-11-21">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<FONT size="+1" CLASS="FrameTitleFont">
<A HREF="../../../../../../../org/pentaho/di/ui/job/entries/ftpdelete/package-summary.html" target="classFrame">org.pentaho.di.ui.job.entries.ftpdelete</A></FONT>
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont">
Classes</FONT>
<FONT CLASS="FrameItemFont">
<BR>
<A HREF="JobEntryFTPDeleteDialog.html" title="class in org.pentaho.di.ui.job.entries.ftpdelete" target="classFrame">JobEntryFTPDeleteDialog</A></FONT></TD>
</TR>
</TABLE>
</BODY>
</HTML>
|
ColFusion/PentahoKettle
|
kettle-data-integration/docs/api/org/pentaho/di/ui/job/entries/ftpdelete/package-frame.html
|
HTML
|
mit
| 990
|
## /models
Put your models here and call 'grunt --model=path_to_model`
|
michalbe/SEOJC.oPP
|
models/README.md
|
Markdown
|
mit
| 71
|
'use strict';
const chai = require('chai');
const Sequelize = require('@sequelize/core');
const Op = Sequelize.Op;
const expect = chai.expect;
const Support = require('../support');
const DataTypes = require('@sequelize/core/lib/data-types');
const dialect = Support.getTestDialect();
const _ = require('lodash');
const promiseProps = require('p-props');
const sortById = function (a, b) {
return a.id < b.id ? -1 : 1;
};
describe(Support.getTestDialectTeaser('Includes with schemas'), () => {
describe('findAll', () => {
afterEach(async function () {
await this.sequelize.dropSchema('account');
});
beforeEach(async function () {
this.fixtureA = async function () {
await this.sequelize.dropSchema('account');
await this.sequelize.createSchema('account');
const AccUser = this.sequelize.define('AccUser', {}, { schema: 'account' });
const Company = this.sequelize.define('Company', {
name: DataTypes.STRING,
}, { schema: 'account' });
const Product = this.sequelize.define('Product', {
title: DataTypes.STRING,
}, { schema: 'account' });
const Tag = this.sequelize.define('Tag', {
name: DataTypes.STRING,
}, { schema: 'account' });
const Price = this.sequelize.define('Price', {
value: DataTypes.FLOAT,
}, { schema: 'account' });
const Customer = this.sequelize.define('Customer', {
name: DataTypes.STRING,
}, { schema: 'account' });
const Group = this.sequelize.define('Group', {
name: DataTypes.STRING,
}, { schema: 'account' });
const GroupMember = this.sequelize.define('GroupMember', {}, { schema: 'account' });
const Rank = this.sequelize.define('Rank', {
name: DataTypes.STRING,
canInvite: {
type: DataTypes.INTEGER,
defaultValue: 0,
},
canRemove: {
type: DataTypes.INTEGER,
defaultValue: 0,
},
canPost: {
type: DataTypes.INTEGER,
defaultValue: 0,
},
}, { schema: 'account' });
this.models = {
AccUser,
Company,
Product,
Tag,
Price,
Customer,
Group,
GroupMember,
Rank,
};
AccUser.hasMany(Product);
Product.belongsTo(AccUser);
Product.belongsToMany(Tag, { through: 'product_tag' });
Tag.belongsToMany(Product, { through: 'product_tag' });
Product.belongsTo(Tag, { as: 'Category' });
Product.belongsTo(Company);
Product.hasMany(Price);
Price.belongsTo(Product);
AccUser.hasMany(GroupMember, { as: 'Memberships' });
GroupMember.belongsTo(AccUser);
GroupMember.belongsTo(Rank);
GroupMember.belongsTo(Group);
Group.hasMany(GroupMember, { as: 'Memberships' });
await this.sequelize.sync({ force: true });
const [groups, companies, ranks, tags] = await Promise.all([
Group.bulkCreate([
{ name: 'Developers' },
{ name: 'Designers' },
{ name: 'Managers' },
]).then(() => Group.findAll()),
Company.bulkCreate([
{ name: 'Sequelize' },
{ name: 'Coca Cola' },
{ name: 'Bonanza' },
{ name: 'NYSE' },
{ name: 'Coshopr' },
]).then(() => Company.findAll()),
Rank.bulkCreate([
{ name: 'Admin', canInvite: 1, canRemove: 1, canPost: 1 },
{ name: 'Trustee', canInvite: 1, canRemove: 0, canPost: 1 },
{ name: 'Member', canInvite: 1, canRemove: 0, canPost: 0 },
]).then(() => Rank.findAll()),
Tag.bulkCreate([
{ name: 'A' },
{ name: 'B' },
{ name: 'C' },
{ name: 'D' },
{ name: 'E' },
]).then(() => Tag.findAll()),
]);
for (const i of [0, 1, 2, 3, 4]) {
const [user, products] = await Promise.all([
AccUser.create(),
Product.bulkCreate([
{ title: 'Chair' },
{ title: 'Desk' },
{ title: 'Bed' },
{ title: 'Pen' },
{ title: 'Monitor' },
]).then(() => Product.findAll()),
]);
const groupMembers = [
{ AccUserId: user.id, GroupId: groups[0].id, RankId: ranks[0].id },
{ AccUserId: user.id, GroupId: groups[1].id, RankId: ranks[2].id },
];
if (i < 3) {
groupMembers.push({ AccUserId: user.id, GroupId: groups[2].id, RankId: ranks[1].id });
}
await Promise.all([
GroupMember.bulkCreate(groupMembers),
user.setProducts([
products[i * 5 + 0],
products[i * 5 + 1],
products[i * 5 + 3],
]),
products[i * 5 + 0].setTags([
tags[0],
tags[2],
]),
products[i * 5 + 1].setTags([
tags[1],
]),
products[i * 5 + 0].setCategory(tags[1]),
products[i * 5 + 2].setTags([
tags[0],
]),
products[i * 5 + 3].setTags([
tags[0],
]),
products[i * 5 + 0].setCompany(companies[4]),
products[i * 5 + 1].setCompany(companies[3]),
products[i * 5 + 2].setCompany(companies[2]),
products[i * 5 + 3].setCompany(companies[1]),
products[i * 5 + 4].setCompany(companies[0]),
Price.bulkCreate([
{ ProductId: products[i * 5 + 0].id, value: 5 },
{ ProductId: products[i * 5 + 0].id, value: 10 },
{ ProductId: products[i * 5 + 1].id, value: 5 },
{ ProductId: products[i * 5 + 1].id, value: 10 },
{ ProductId: products[i * 5 + 1].id, value: 15 },
{ ProductId: products[i * 5 + 1].id, value: 20 },
{ ProductId: products[i * 5 + 2].id, value: 20 },
{ ProductId: products[i * 5 + 3].id, value: 20 },
]),
]);
}
};
await this.sequelize.createSchema('account');
});
it('should support an include with multiple different association types', async function () {
await this.sequelize.dropSchema('account');
await this.sequelize.createSchema('account');
const AccUser = this.sequelize.define('AccUser', {}, { schema: 'account' });
const Product = this.sequelize.define('Product', {
title: DataTypes.STRING,
}, { schema: 'account' });
const Tag = this.sequelize.define('Tag', {
name: DataTypes.STRING,
}, { schema: 'account' });
const Price = this.sequelize.define('Price', {
value: DataTypes.FLOAT,
}, { schema: 'account' });
const Group = this.sequelize.define('Group', {
name: DataTypes.STRING,
}, { schema: 'account' });
const GroupMember = this.sequelize.define('GroupMember', {}, { schema: 'account' });
const Rank = this.sequelize.define('Rank', {
name: DataTypes.STRING,
canInvite: {
type: DataTypes.INTEGER,
defaultValue: 0,
},
canRemove: {
type: DataTypes.INTEGER,
defaultValue: 0,
},
}, { schema: 'account' });
AccUser.hasMany(Product);
Product.belongsTo(AccUser);
Product.belongsToMany(Tag, { through: 'product_tag' });
Tag.belongsToMany(Product, { through: 'product_tag' });
Product.belongsTo(Tag, { as: 'Category' });
Product.hasMany(Price);
Price.belongsTo(Product);
AccUser.hasMany(GroupMember, { as: 'Memberships' });
GroupMember.belongsTo(AccUser);
GroupMember.belongsTo(Rank);
GroupMember.belongsTo(Group);
Group.hasMany(GroupMember, { as: 'Memberships' });
await this.sequelize.sync({ force: true });
const [groups, ranks, tags] = await Promise.all([
Group.bulkCreate([
{ name: 'Developers' },
{ name: 'Designers' },
]).then(() => Group.findAll()),
Rank.bulkCreate([
{ name: 'Admin', canInvite: 1, canRemove: 1 },
{ name: 'Member', canInvite: 1, canRemove: 0 },
]).then(() => Rank.findAll()),
Tag.bulkCreate([
{ name: 'A' },
{ name: 'B' },
{ name: 'C' },
]).then(() => Tag.findAll()),
]);
for (const i of [0, 1, 2, 3, 4]) {
const [user, products] = await Promise.all([
AccUser.create(),
Product.bulkCreate([
{ title: 'Chair' },
{ title: 'Desk' },
]).then(() => Product.findAll()),
]);
await Promise.all([
GroupMember.bulkCreate([
{ AccUserId: user.id, GroupId: groups[0].id, RankId: ranks[0].id },
{ AccUserId: user.id, GroupId: groups[1].id, RankId: ranks[1].id },
]),
user.setProducts([
products[i * 2 + 0],
products[i * 2 + 1],
]),
products[i * 2 + 0].setTags([
tags[0],
tags[2],
]),
products[i * 2 + 1].setTags([
tags[1],
]),
products[i * 2 + 0].setCategory(tags[1]),
Price.bulkCreate([
{ ProductId: products[i * 2 + 0].id, value: 5 },
{ ProductId: products[i * 2 + 0].id, value: 10 },
{ ProductId: products[i * 2 + 1].id, value: 5 },
{ ProductId: products[i * 2 + 1].id, value: 10 },
{ ProductId: products[i * 2 + 1].id, value: 15 },
{ ProductId: products[i * 2 + 1].id, value: 20 },
]),
]);
const users = await AccUser.findAll({
include: [
{
model: GroupMember, as: 'Memberships', include: [
Group,
Rank,
],
},
{
model: Product, include: [
Tag,
{ model: Tag, as: 'Category' },
Price,
],
},
],
order: [
[AccUser.rawAttributes.id, 'ASC'],
],
});
for (const user of users) {
expect(user.Memberships).to.be.ok;
user.Memberships.sort(sortById);
expect(user.Memberships.length).to.equal(2);
expect(user.Memberships[0].Group.name).to.equal('Developers');
expect(user.Memberships[0].Rank.canRemove).to.equal(1);
expect(user.Memberships[1].Group.name).to.equal('Designers');
expect(user.Memberships[1].Rank.canRemove).to.equal(0);
user.Products.sort(sortById);
expect(user.Products.length).to.equal(2);
expect(user.Products[0].Tags.length).to.equal(2);
expect(user.Products[1].Tags.length).to.equal(1);
expect(user.Products[0].Category).to.be.ok;
expect(user.Products[1].Category).not.to.be.ok;
expect(user.Products[0].Prices.length).to.equal(2);
expect(user.Products[1].Prices.length).to.equal(4);
}
}
});
it('should support many levels of belongsTo', async function () {
const A = this.sequelize.define('a', {}, { schema: 'account' });
const B = this.sequelize.define('b', {}, { schema: 'account' });
const C = this.sequelize.define('c', {}, { schema: 'account' });
const D = this.sequelize.define('d', {}, { schema: 'account' });
const E = this.sequelize.define('e', {}, { schema: 'account' });
const F = this.sequelize.define('f', {}, { schema: 'account' });
const G = this.sequelize.define('g', {}, { schema: 'account' });
const H = this.sequelize.define('h', {}, { schema: 'account' });
A.belongsTo(B);
B.belongsTo(C);
C.belongsTo(D);
D.belongsTo(E);
E.belongsTo(F);
F.belongsTo(G);
G.belongsTo(H);
let b;
const singles = [
B,
C,
D,
E,
F,
G,
H,
];
await this.sequelize.sync();
await A.bulkCreate([
{}, {}, {}, {}, {}, {}, {}, {},
]);
let previousInstance;
for (const model of singles) {
const instance = await model.create({});
if (previousInstance) {
await previousInstance[`set${_.upperFirst(model.name)}`](instance);
previousInstance = instance;
continue;
}
previousInstance = b = instance;
}
let as = await A.findAll();
await Promise.all(as.map(a => a.setB(b)));
as = await A.findAll({
include: [
{
model: B, include: [
{
model: C, include: [
{
model: D, include: [
{
model: E, include: [
{
model: F, include: [
{
model: G, include: [
{ model: H },
],
},
],
},
],
},
],
},
],
},
],
},
],
});
expect(as.length).to.be.ok;
for (const a of as) {
expect(a.b.c.d.e.f.g.h).to.be.ok;
}
});
it('should support ordering with only belongsTo includes', async function () {
const User = this.sequelize.define('SpecialUser', {}, { schema: 'account' });
const Item = this.sequelize.define('Item', { test: DataTypes.STRING }, { schema: 'account' });
const Order = this.sequelize.define('Order', { position: DataTypes.INTEGER }, { schema: 'account' });
User.belongsTo(Item, { as: 'itemA', foreignKey: 'itemA_id' });
User.belongsTo(Item, { as: 'itemB', foreignKey: 'itemB_id' });
User.belongsTo(Order);
await this.sequelize.sync();
await Promise.all([
User.bulkCreate([{}, {}, {}]),
Item.bulkCreate([
{ test: 'abc' },
{ test: 'def' },
{ test: 'ghi' },
{ test: 'jkl' },
]),
Order.bulkCreate([
{ position: 2 },
{ position: 3 },
{ position: 1 },
]),
]);
const [users, items, orders] = await Promise.all([
User.findAll(),
Item.findAll({ order: ['id'] }),
Order.findAll({ order: ['id'] }),
]);
await Promise.all([
users[0].setItemA(items[0]),
users[0].setItemB(items[1]),
users[0].setOrder(orders[2]),
users[1].setItemA(items[2]),
users[1].setItemB(items[3]),
users[1].setOrder(orders[1]),
users[2].setItemA(items[0]),
users[2].setItemB(items[3]),
users[2].setOrder(orders[0]),
]);
const as = await User.findAll({
include: [
{ model: Item, as: 'itemA', where: { test: 'abc' } },
{ model: Item, as: 'itemB' },
Order],
order: [
[Order, 'position'],
],
});
expect(as.length).to.eql(2);
expect(as[0].itemA.test).to.eql('abc');
expect(as[1].itemA.test).to.eql('abc');
expect(as[0].Order.position).to.eql(1);
expect(as[1].Order.position).to.eql(2);
});
it('should include attributes from through models', async function () {
const Product = this.sequelize.define('Product', {
title: DataTypes.STRING,
}, { schema: 'account' });
const Tag = this.sequelize.define('Tag', {
name: DataTypes.STRING,
}, { schema: 'account' });
const ProductTag = this.sequelize.define('ProductTag', {
priority: DataTypes.INTEGER,
}, { schema: 'account' });
Product.belongsToMany(Tag, { through: ProductTag });
Tag.belongsToMany(Product, { through: ProductTag });
await this.sequelize.sync({ force: true });
await Promise.all([
Product.bulkCreate([
{ title: 'Chair' },
{ title: 'Desk' },
{ title: 'Dress' },
]),
Tag.bulkCreate([
{ name: 'A' },
{ name: 'B' },
{ name: 'C' },
]),
]);
const [products0, tags] = await Promise.all([
Product.findAll(),
Tag.findAll(),
]);
await Promise.all([
products0[0].addTag(tags[0], { through: { priority: 1 } }),
products0[0].addTag(tags[1], { through: { priority: 2 } }),
products0[1].addTag(tags[1], { through: { priority: 1 } }),
products0[2].addTag(tags[0], { through: { priority: 3 } }),
products0[2].addTag(tags[1], { through: { priority: 1 } }),
products0[2].addTag(tags[2], { through: { priority: 2 } }),
]);
const products = await Product.findAll({
include: [
{ model: Tag },
],
order: [
['id', 'ASC'],
[Tag, 'id', 'ASC'],
],
});
expect(products[0].Tags[0].ProductTag.priority).to.equal(1);
expect(products[0].Tags[1].ProductTag.priority).to.equal(2);
expect(products[1].Tags[0].ProductTag.priority).to.equal(1);
expect(products[2].Tags[0].ProductTag.priority).to.equal(3);
expect(products[2].Tags[1].ProductTag.priority).to.equal(1);
expect(products[2].Tags[2].ProductTag.priority).to.equal(2);
});
it('should support a required belongsTo include', async function () {
const User = this.sequelize.define('User', {}, { schema: 'account' });
const Group = this.sequelize.define('Group', {}, { schema: 'account' });
User.belongsTo(Group);
await this.sequelize.sync({ force: true });
await Promise.all([
Group.bulkCreate([{}, {}]),
User.bulkCreate([{}, {}, {}]),
]);
const [groups, users0] = await Promise.all([
Group.findAll(),
User.findAll(),
]);
await users0[2].setGroup(groups[1]);
const users = await User.findAll({
include: [
{ model: Group, required: true },
],
});
expect(users.length).to.equal(1);
expect(users[0].Group).to.be.ok;
});
it('should be possible to extend the on clause with a where option on a belongsTo include', async function () {
const User = this.sequelize.define('User', {}, { schema: 'account' });
const Group = this.sequelize.define('Group', {
name: DataTypes.STRING,
}, { schema: 'account' });
User.belongsTo(Group);
await this.sequelize.sync({ force: true });
await Promise.all([
Group.bulkCreate([
{ name: 'A' },
{ name: 'B' },
]),
User.bulkCreate([{}, {}]),
]);
const [groups, users0] = await Promise.all([
Group.findAll(),
User.findAll(),
]);
await Promise.all([
users0[0].setGroup(groups[1]),
users0[1].setGroup(groups[0]),
]);
const users = await User.findAll({
include: [
{ model: Group, where: { name: 'A' } },
],
});
expect(users.length).to.equal(1);
expect(users[0].Group).to.be.ok;
expect(users[0].Group.name).to.equal('A');
});
it('should be possible to extend the on clause with a where option on a belongsTo include', async function () {
const User = this.sequelize.define('User', {}, { schema: 'account' });
const Group = this.sequelize.define('Group', {
name: DataTypes.STRING,
}, { schema: 'account' });
User.belongsTo(Group);
await this.sequelize.sync({ force: true });
await Promise.all([
Group.bulkCreate([
{ name: 'A' },
{ name: 'B' },
]),
User.bulkCreate([{}, {}]),
]);
const [groups, users0] = await Promise.all([
Group.findAll(),
User.findAll(),
]);
await Promise.all([
users0[0].setGroup(groups[1]),
users0[1].setGroup(groups[0]),
]);
const users = await User.findAll({
include: [
{ model: Group, required: true },
],
});
for (const user of users) {
expect(user.Group).to.be.ok;
}
});
it('should be possible to define a belongsTo include as required with child hasMany with limit', async function () {
const User = this.sequelize.define('User', {}, { schema: 'account' });
const Group = this.sequelize.define('Group', {
name: DataTypes.STRING,
}, { schema: 'account' });
const Category = this.sequelize.define('Category', {
category: DataTypes.STRING,
}, { schema: 'account' });
User.belongsTo(Group);
Group.hasMany(Category);
await this.sequelize.sync({ force: true });
await Promise.all([
Group.bulkCreate([
{ name: 'A' },
{ name: 'B' },
]),
User.bulkCreate([{}, {}]),
Category.bulkCreate([{}, {}]),
]);
const [groups, users0, categories] = await Promise.all([
Group.findAll(),
User.findAll(),
Category.findAll(),
]);
const promises = [
users0[0].setGroup(groups[1]),
users0[1].setGroup(groups[0]),
];
for (const group of groups) {
promises.push(group.setCategories(categories));
}
await Promise.all(promises);
const users = await User.findAll({
include: [
{
model: Group, required: true, include: [
{ model: Category },
],
},
],
limit: 1,
});
expect(users.length).to.equal(1);
for (const user of users) {
expect(user.Group).to.be.ok;
expect(user.Group.Categories).to.be.ok;
}
});
it('should be possible to define a belongsTo include as required with child hasMany with limit and aliases', async function () {
const User = this.sequelize.define('User', {}, { schema: 'account' });
const Group = this.sequelize.define('Group', {
name: DataTypes.STRING,
}, { schema: 'account' });
const Category = this.sequelize.define('Category', {
category: DataTypes.STRING,
}, { schema: 'account' });
User.belongsTo(Group, { as: 'Team' });
Group.hasMany(Category, { as: 'Tags' });
await this.sequelize.sync({ force: true });
await Promise.all([
Group.bulkCreate([
{ name: 'A' },
{ name: 'B' },
]),
User.bulkCreate([{}, {}]),
Category.bulkCreate([{}, {}]),
]);
const [groups, users0, categories] = await Promise.all([
Group.findAll(),
User.findAll(),
Category.findAll(),
]);
const promises = [
users0[0].setTeam(groups[1]),
users0[1].setTeam(groups[0]),
];
for (const group of groups) {
promises.push(group.setTags(categories));
}
await Promise.all(promises);
const users = await User.findAll({
include: [
{
model: Group, required: true, as: 'Team', include: [
{ model: Category, as: 'Tags' },
],
},
],
limit: 1,
});
expect(users.length).to.equal(1);
for (const user of users) {
expect(user.Team).to.be.ok;
expect(user.Team.Tags).to.be.ok;
}
});
it('should be possible to define a belongsTo include as required with child hasMany which is not required with limit', async function () {
const User = this.sequelize.define('User', {}, { schema: 'account' });
const Group = this.sequelize.define('Group', {
name: DataTypes.STRING,
}, { schema: 'account' });
const Category = this.sequelize.define('Category', {
category: DataTypes.STRING,
}, { schema: 'account' });
User.belongsTo(Group);
Group.hasMany(Category);
await this.sequelize.sync({ force: true });
await Promise.all([
Group.bulkCreate([
{ name: 'A' },
{ name: 'B' },
]),
User.bulkCreate([{}, {}]),
Category.bulkCreate([{}, {}]),
]);
const [groups, users0, categories] = await Promise.all([
Group.findAll(),
User.findAll(),
Category.findAll(),
]);
const promises = [
users0[0].setGroup(groups[1]),
users0[1].setGroup(groups[0]),
];
for (const group of groups) {
promises.push(group.setCategories(categories));
}
await Promise.all(promises);
const users = await User.findAll({
include: [
{
model: Group, required: true, include: [
{ model: Category, required: false },
],
},
],
limit: 1,
});
expect(users.length).to.equal(1);
for (const user of users) {
expect(user.Group).to.be.ok;
expect(user.Group.Categories).to.be.ok;
}
});
it('should be possible to extend the on clause with a where option on a hasOne include', async function () {
const User = this.sequelize.define('User', {}, { schema: 'account' });
const Project = this.sequelize.define('Project', {
title: DataTypes.STRING,
}, { schema: 'account' });
User.hasOne(Project, { as: 'LeaderOf' });
await this.sequelize.sync({ force: true });
await Promise.all([
Project.bulkCreate([
{ title: 'Alpha' },
{ title: 'Beta' },
]),
User.bulkCreate([{}, {}]),
]);
const [projects, users0] = await Promise.all([
Project.findAll(),
User.findAll(),
]);
await Promise.all([
users0[1].setLeaderOf(projects[1]),
users0[0].setLeaderOf(projects[0]),
]);
const users = await User.findAll({
include: [
{ model: Project, as: 'LeaderOf', where: { title: 'Beta' } },
],
});
expect(users.length).to.equal(1);
expect(users[0].LeaderOf).to.be.ok;
expect(users[0].LeaderOf.title).to.equal('Beta');
});
it('should be possible to extend the on clause with a where option on a hasMany include with a through model', async function () {
const Product = this.sequelize.define('Product', {
title: DataTypes.STRING,
}, { schema: 'account' });
const Tag = this.sequelize.define('Tag', {
name: DataTypes.STRING,
}, { schema: 'account' });
const ProductTag = this.sequelize.define('ProductTag', {
priority: DataTypes.INTEGER,
}, { schema: 'account' });
Product.belongsToMany(Tag, { through: ProductTag });
Tag.belongsToMany(Product, { through: ProductTag });
await this.sequelize.sync({ force: true });
await Promise.all([
Product.bulkCreate([
{ title: 'Chair' },
{ title: 'Desk' },
{ title: 'Dress' },
]),
Tag.bulkCreate([
{ name: 'A' },
{ name: 'B' },
{ name: 'C' },
]),
]);
const [products0, tags] = await Promise.all([
Product.findAll(),
Tag.findAll(),
]);
await Promise.all([
products0[0].addTag(tags[0], { priority: 1 }),
products0[0].addTag(tags[1], { priority: 2 }),
products0[1].addTag(tags[1], { priority: 1 }),
products0[2].addTag(tags[0], { priority: 3 }),
products0[2].addTag(tags[1], { priority: 1 }),
products0[2].addTag(tags[2], { priority: 2 }),
]);
const products = await Product.findAll({
include: [
{ model: Tag, where: { name: 'C' } },
],
});
expect(products.length).to.equal(1);
expect(products[0].Tags.length).to.equal(1);
});
it('should be possible to extend the on clause with a where option on nested includes', async function () {
const User = this.sequelize.define('User', {
name: DataTypes.STRING,
}, { schema: 'account' });
const Product = this.sequelize.define('Product', {
title: DataTypes.STRING,
}, { schema: 'account' });
const Tag = this.sequelize.define('Tag', {
name: DataTypes.STRING,
}, { schema: 'account' });
const Price = this.sequelize.define('Price', {
value: DataTypes.FLOAT,
}, { schema: 'account' });
const Group = this.sequelize.define('Group', {
name: DataTypes.STRING,
}, { schema: 'account' });
const GroupMember = this.sequelize.define('GroupMember', {}, { schema: 'account' });
const Rank = this.sequelize.define('Rank', {
name: DataTypes.STRING,
canInvite: {
type: DataTypes.INTEGER,
defaultValue: 0,
},
canRemove: {
type: DataTypes.INTEGER,
defaultValue: 0,
},
}, { schema: 'account' });
User.hasMany(Product);
Product.belongsTo(User);
Product.belongsToMany(Tag, { through: 'product_tag' });
Tag.belongsToMany(Product, { through: 'product_tag' });
Product.belongsTo(Tag, { as: 'Category' });
Product.hasMany(Price);
Price.belongsTo(Product);
User.hasMany(GroupMember, { as: 'Memberships' });
GroupMember.belongsTo(User);
GroupMember.belongsTo(Rank);
GroupMember.belongsTo(Group);
Group.hasMany(GroupMember, { as: 'Memberships' });
await this.sequelize.sync({ force: true });
const [groups, ranks, tags] = await Promise.all([
Group.bulkCreate([
{ name: 'Developers' },
{ name: 'Designers' },
]).then(() => Group.findAll()),
Rank.bulkCreate([
{ name: 'Admin', canInvite: 1, canRemove: 1 },
{ name: 'Member', canInvite: 1, canRemove: 0 },
]).then(() => Rank.findAll()),
Tag.bulkCreate([
{ name: 'A' },
{ name: 'B' },
{ name: 'C' },
]).then(() => Tag.findAll()),
]);
for (const i of [0, 1, 2, 3, 4]) {
const [user, products] = await Promise.all([
User.create({ name: 'FooBarzz' }),
Product.bulkCreate([
{ title: 'Chair' },
{ title: 'Desk' },
]).then(() => Product.findAll()),
]);
await Promise.all([
GroupMember.bulkCreate([
{ UserId: user.id, GroupId: groups[0].id, RankId: ranks[0].id },
{ UserId: user.id, GroupId: groups[1].id, RankId: ranks[1].id },
]),
user.setProducts([
products[i * 2 + 0],
products[i * 2 + 1],
]),
products[i * 2 + 0].setTags([
tags[0],
tags[2],
]),
products[i * 2 + 1].setTags([
tags[1],
]),
products[i * 2 + 0].setCategory(tags[1]),
Price.bulkCreate([
{ ProductId: products[i * 2 + 0].id, value: 5 },
{ ProductId: products[i * 2 + 0].id, value: 10 },
{ ProductId: products[i * 2 + 1].id, value: 5 },
{ ProductId: products[i * 2 + 1].id, value: 10 },
{ ProductId: products[i * 2 + 1].id, value: 15 },
{ ProductId: products[i * 2 + 1].id, value: 20 },
]),
]);
const users = await User.findAll({
include: [
{
model: GroupMember, as: 'Memberships', include: [
Group,
{ model: Rank, where: { name: 'Admin' } },
],
},
{
model: Product, include: [
Tag,
{ model: Tag, as: 'Category' },
{
model: Price, where: {
value: {
[Op.gt]: 15,
},
},
},
],
},
],
order: [
['id', 'ASC'],
],
});
for (const user of users) {
expect(user.Memberships.length).to.equal(1);
expect(user.Memberships[0].Rank.name).to.equal('Admin');
expect(user.Products.length).to.equal(1);
expect(user.Products[0].Prices.length).to.equal(1);
}
}
});
it('should be possible to use limit and a where with a belongsTo include', async function () {
const User = this.sequelize.define('User', {}, { schema: 'account' });
const Group = this.sequelize.define('Group', {
name: DataTypes.STRING,
}, { schema: 'account' });
User.belongsTo(Group);
await this.sequelize.sync({ force: true });
const results = await promiseProps({
groups: Group.bulkCreate([
{ name: 'A' },
{ name: 'B' },
]).then(() => {
return Group.findAll();
}),
users: User.bulkCreate([{}, {}, {}, {}]).then(() => {
return User.findAll();
}),
});
await Promise.all([
results.users[1].setGroup(results.groups[0]),
results.users[2].setGroup(results.groups[0]),
results.users[3].setGroup(results.groups[1]),
results.users[0].setGroup(results.groups[0]),
]);
const users = await User.findAll({
include: [
{ model: Group, where: { name: 'A' } },
],
limit: 2,
});
expect(users.length).to.equal(2);
for (const user of users) {
expect(user.Group.name).to.equal('A');
}
});
it('should be possible use limit, attributes and a where on a belongsTo with additional hasMany includes', async function () {
await this.fixtureA();
const products = await this.models.Product.findAll({
attributes: ['title'],
include: [
{ model: this.models.Company, where: { name: 'NYSE' } },
{ model: this.models.Tag },
{ model: this.models.Price },
],
limit: 3,
order: [
['id', 'ASC'],
],
});
expect(products.length).to.equal(3);
for (const product of products) {
expect(product.Company.name).to.equal('NYSE');
expect(product.Tags.length).to.be.ok;
expect(product.Prices.length).to.be.ok;
}
});
it('should be possible to use limit and a where on a hasMany with additional includes', async function () {
await this.fixtureA();
const products = await this.models.Product.findAll({
include: [
{ model: this.models.Company },
{ model: this.models.Tag },
{
model: this.models.Price, where: {
value: { [Op.gt]: 5 },
},
},
],
limit: 6,
order: [
['id', 'ASC'],
],
});
expect(products.length).to.equal(6);
for (const product of products) {
expect(product.Tags.length).to.be.ok;
expect(product.Prices.length).to.be.ok;
for (const price of product.Prices) {
expect(price.value).to.be.above(5);
}
}
});
it('should be possible to use limit and a where on a hasMany with a through model with additional includes', async function () {
await this.fixtureA();
const products = await this.models.Product.findAll({
include: [
{ model: this.models.Company },
{ model: this.models.Tag, where: { name: ['A', 'B', 'C'] } },
{ model: this.models.Price },
],
limit: 10,
order: [
['id', 'ASC'],
],
});
expect(products.length).to.equal(10);
for (const product of products) {
expect(product.Tags.length).to.be.ok;
expect(product.Prices.length).to.be.ok;
for (const tag of product.Tags) {
expect(['A', 'B', 'C']).to.include(tag.name);
}
}
});
it('should support including date fields, with the correct timezone', async function () {
const User = this.sequelize.define('user', {
dateField: Sequelize.DATE,
}, { timestamps: false, schema: 'account' });
const Group = this.sequelize.define('group', {
dateField: Sequelize.DATE,
}, { timestamps: false, schema: 'account' });
User.belongsToMany(Group, { through: 'group_user' });
Group.belongsToMany(User, { through: 'group_user' });
await this.sequelize.sync();
const user = await User.create({ dateField: Date.UTC(2014, 1, 20) });
const group = await Group.create({ dateField: Date.UTC(2014, 1, 20) });
await user.addGroup(group);
const users = await User.findAll({
where: {
id: user.id,
},
include: [Group],
});
if (dialect === 'sqlite') {
expect(new Date(users[0].dateField).getTime()).to.equal(Date.UTC(2014, 1, 20));
expect(new Date(users[0].groups[0].dateField).getTime()).to.equal(Date.UTC(2014, 1, 20));
} else {
expect(users[0].dateField.getTime()).to.equal(Date.UTC(2014, 1, 20));
expect(users[0].groups[0].dateField.getTime()).to.equal(Date.UTC(2014, 1, 20));
}
});
});
describe('findOne', () => {
it('should work with schemas', async function () {
const UserModel = this.sequelize.define('User', {
Id: {
type: DataTypes.INTEGER,
primaryKey: true,
},
Name: DataTypes.STRING,
UserType: DataTypes.INTEGER,
Email: DataTypes.STRING,
PasswordHash: DataTypes.STRING,
Enabled: {
type: DataTypes.BOOLEAN,
},
CreatedDatetime: DataTypes.DATE,
UpdatedDatetime: DataTypes.DATE,
}, {
schema: 'hero',
tableName: 'User',
timestamps: false,
});
const UserIdColumn = { type: Sequelize.INTEGER, references: { model: UserModel, key: 'Id' } };
const ResumeModel = this.sequelize.define('Resume', {
Id: {
type: Sequelize.INTEGER,
primaryKey: true,
},
UserId: UserIdColumn,
Name: Sequelize.STRING,
Contact: Sequelize.STRING,
School: Sequelize.STRING,
WorkingAge: Sequelize.STRING,
Description: Sequelize.STRING,
PostType: Sequelize.INTEGER,
RefreshDatetime: Sequelize.DATE,
CreatedDatetime: Sequelize.DATE,
}, {
schema: 'hero',
tableName: 'resume',
timestamps: false,
});
UserModel.hasOne(ResumeModel, {
foreignKey: 'UserId',
as: 'Resume',
});
ResumeModel.belongsTo(UserModel, {
foreignKey: 'UserId',
});
await this.sequelize.dropSchema('hero');
await this.sequelize.createSchema('hero');
await this.sequelize.sync({ force: true });
await UserModel.findOne({
where: {
Id: 1,
},
include: [{
model: ResumeModel,
as: 'Resume',
}],
});
await this.sequelize.dropSchema('hero');
});
});
});
|
sequelize/sequelize
|
test/integration/include/schema.test.js
|
JavaScript
|
mit
| 39,231
|
// Generated by CoffeeScript 1.10.0
var EsyFile;
EsyFile = (function() {
function EsyFile() {}
EsyFile.prototype["delete"] = function(filepath) {
var file;
if (File(filepath)) {
file = File(filepath);
}
return file.remove();
};
EsyFile.prototype.append = function(filepath, content) {
var file;
file = File(filepath);
file.open("a");
file.write(content);
file.close();
return file;
};
EsyFile.prototype.buildExtendScript = function(filepath, destinations) {
var content, destination, i, len, read, results;
content = this.read(filepath);
content = content.replace("debug = true", "debug = false");
read = (function(_this) {
return function(str, p1) {
return _this.read((_this.path(filepath)) + "/" + p1);
};
})(this);
content = content.replace(/#include \"(.*)\";/g, read);
if (typeof destinations === "string") {
destinations = [destinations];
}
results = [];
for (i = 0, len = destinations.length; i < len; i++) {
destination = destinations[i];
results.push(this.create("" + (destination.toString()), content));
}
return results;
};
EsyFile.prototype.create = function(filepath, content, overwrite) {
var file;
if (content == null) {
content = "";
}
if (overwrite == null) {
overwrite = true;
}
if (overwrite) {
this["delete"](filepath);
}
file = File(filepath);
file.open("w");
file.write(content);
file.close();
return file;
};
EsyFile.prototype.exists = function(filepath) {
var file;
file = File(filepath);
if (file.created) {
return file;
} else {
return false;
}
};
EsyFile.prototype.read = function(filepath) {
var content, file;
file = File(filepath);
file.open("r");
content = file.read();
file.close();
return content;
};
EsyFile.prototype.folderName = function(filepath) {
var folderName;
folderName = this.filename(filepath);
return folderName;
};
EsyFile.prototype.fileName = function(filepath) {
var filename;
filename = filepath.substr(filepath.lastIndexOf('/') + 1);
return filename;
};
EsyFile.prototype.path = function(filepath) {
var filename;
filename = filepath.substr(0, filepath.lastIndexOf('/'));
return filename;
};
return EsyFile;
})();
|
seblavoie/esy
|
lib/core/_file.js
|
JavaScript
|
mit
| 2,407
|
'use strict';
module.exports = {
'+': 'Pass',
'-': 'Fail',
'~': 'SoftFail',
'?': 'Neutral'
};
|
softvu/spf-parse
|
prefixes.js
|
JavaScript
|
mit
| 99
|
/*
* Copyright (C) 2000-2007 Carsten Haitzler, Geoff Harrison and various contributors
* Copyright (C) 2006-2013 Kim Woelders
*
* 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 of the Software, its documentation and marketing & publicity
* materials, and acknowledgment shall be given in the documentation, materials
* and software packages that this Software was used.
*
* 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "E.h"
#include "eobj.h"
#include "iclass.h"
#include "progress.h"
#include "tclass.h"
#include "xwin.h"
struct _progressbar {
EObj *win;
EObj *n_win;
EObj *p_win;
int w, h;
int value;
ImageClass *ic;
TextClass *tc, *tnc;
};
static int pnum = 0;
static Progressbar **plist = NULL;
Progressbar *
ProgressbarCreate(const char *name, int w, int h)
{
Progressbar *p;
int x, y, tw, th;
EImageBorder *pad;
p = ECALLOC(Progressbar, 1);
pnum++;
plist = EREALLOC(Progressbar *, plist, pnum);
plist[pnum - 1] = p;
p->ic = ImageclassAlloc("PROGRESS_BAR", 1);
p->tc = TextclassAlloc("PROGRESS_TEXT", 1);
p->tnc = TextclassAlloc("PROGRESS_TEXT_NUMBER", 1);
pad = ImageclassGetPadding(p->ic);
TextSize(p->tc, 0, 0, 0, name, &tw, &th, 0);
if (h < th + pad->top + pad->bottom)
h = th + pad->top + pad->bottom;
p->w = w;
p->h = h;
p->value = 0;
x = (WinGetW(VROOT) - w) / 2;
y = 32 + (pnum * h * 2);
p->win = EobjWindowCreate(EOBJ_TYPE_MISC, x, y, w - (h * 5), h, 1, name);
p->n_win =
EobjWindowCreate(EOBJ_TYPE_MISC, x + w - (h * 5), y, (h * 5), h, 1, "pn");
p->p_win = EobjWindowCreate(EOBJ_TYPE_MISC, x, y + h, 1, h, 1, "pp");
if (!p->win || !p->n_win || !p->p_win)
{
ProgressbarDestroy(p);
return NULL;
}
p->win->shadow = 1;
p->n_win->shadow = 1;
p->p_win->shadow = 1;
return p;
}
void
ProgressbarDestroy(Progressbar * p)
{
int i, j, dy;
dy = 2 * p->h;
EobjWindowDestroy(p->win);
EobjWindowDestroy(p->n_win);
EobjWindowDestroy(p->p_win);
for (i = 0; i < pnum; i++)
{
if (plist[i] != p)
continue;
for (j = i; j < pnum - 1; j++)
{
Progressbar *pp;
pp = plist[j + 1];
plist[j] = pp;
EobjMove(pp->win, EobjGetX(pp->win), EobjGetY(pp->win) - dy);
EobjMove(pp->n_win, EobjGetX(pp->n_win), EobjGetY(pp->n_win) - dy);
EobjMove(pp->p_win, EobjGetX(pp->p_win), EobjGetY(pp->p_win) - dy);
}
break;
}
ImageclassFree(p->ic);
TextclassFree(p->tc);
TextclassFree(p->tnc);
Efree(p);
pnum--;
if (pnum <= 0)
{
pnum = 0;
_EFREE(plist);
}
else
{
plist = EREALLOC(Progressbar *, plist, pnum);
}
}
void
ProgressbarSet(Progressbar * p, int progress)
{
int w;
char s[64];
EImageBorder *pad;
if (progress == p->value)
return;
p->value = progress;
w = (p->value * p->w) / 100;
if (w < 1)
w = 1;
if (w > p->w)
w = p->w;
Esnprintf(s, sizeof(s), "%i%%", p->value);
EobjResize(p->p_win, w, p->h);
ImageclassApply(p->ic, EobjGetWin(p->p_win), 1, 0, STATE_NORMAL, ST_SOLID);
EobjShapeUpdate(p->p_win, 0);
pad = ImageclassGetPadding(p->ic);
EClearWindow(EobjGetWin(p->n_win));
TextDraw(p->tnc, EobjGetWin(p->n_win), NoXID, 0, 0, STATE_CLICKED, s,
pad->left, pad->top, p->h * 5 - (pad->left + pad->right),
p->h - (pad->top + pad->bottom), p->h - (pad->top + pad->bottom),
TextclassGetJustification(p->tnc));
/* Hack - We may not be running in the event loop here */
EobjDamage(p->n_win);
}
void
ProgressbarShow(Progressbar * p)
{
EImageBorder *pad;
ImageclassApply(p->ic, EobjGetWin(p->win), 0, 0, STATE_NORMAL, ST_SOLID);
ImageclassApply(p->ic, EobjGetWin(p->n_win), 0, 0, STATE_CLICKED, ST_SOLID);
ImageclassApply(p->ic, EobjGetWin(p->p_win), 1, 0, STATE_NORMAL, ST_SOLID);
EobjMap(p->win, 0);
EobjMap(p->n_win, 0);
EobjMap(p->p_win, 0);
pad = ImageclassGetPadding(p->ic);
TextDraw(p->tc, EobjGetWin(p->win), NoXID, 0, 0, STATE_NORMAL,
EobjGetName(p->win), pad->left, pad->top,
p->w - (p->h * 5) - (pad->left + pad->right),
p->h - (pad->top + pad->bottom), p->h - (pad->top + pad->bottom),
TextclassGetJustification(p->tnc));
}
|
burzumishi/e16
|
src/progress.c
|
C
|
mit
| 5,333
|
import config from './config/env';
import Promise from 'bluebird';
import logger from './config/logger';
// import csv from 'fast-csv';
import fs from 'fs';
import request from 'request';
// import rp from 'request-promise';
import cheerio from 'cheerio';
import _ from 'lodash';
import moment from 'moment';
function downloadStockProfile(stockId, season) {
const uri = config.sinaLink.replace('{stockId}', stockId);
logger.info(`downloading ${uri}, ( ${season.year}, ${season.season})`);
const options = {
uri,
method: 'POST',
headers: config.browser.headers,
form: season,
json: true,
};
return new Promise((resolve) => {
request(options).on('response', (res) => {
if (res.statusCode !== 200) {
resolve(res.statusCode);
} else {
resolve('done');
}
}).on('error', (e) => {
logger.error(JSON.stringify(e));
resolve('skip');
})
.pipe(fs.createWriteStream(`./sample/${stockId}_${season.year}_${season.season}.html`))
.on('finish', () => {
resolve('done');
});
});
}
function isStockProfileGood(stockId, marketCapMin) {
const uri = config.tickerLink.replace('{stockId}', stockId);
logger.info(`getting ${uri}`);
const options = {
uri,
method: 'GET',
headers: config.browser.headers,
json: true,
};
return new Promise((resolve) => {
request(options, (error, response, body) => {
if (error) {
// in case ticker block my programe, any error will give as true response
resolve(true);
}
if (response && response.statusCode !== 200) {
// in case ticker block my programe, any error will give as true response
resolve(true);
} else if (body && body[0]) {
const { lastTradePrice, lastClosePrice, MktCap } = body[0];
const isHighMarkCap = parseFloat(MktCap) >= marketCapMin;
const changePer = (parseFloat(lastTradePrice) - parseFloat(lastClosePrice)) / parseFloat(lastClosePrice);
const isChangePerGood = changePer < config.marketChangePerMin[0] && changePer >= config.marketChangePerMin[1];
logger.info(`changePer, isChangePerGood : ${changePer} , ${isChangePerGood}`);
resolve(isHighMarkCap && isChangePerGood);
} else {
resolve(true);
}
});
});
}
function getLastTradeDay() {
const uri = config.tickerLink.replace('{stockId}', '5');
logger.info(`getting ${uri}`);
const options = {
uri,
method: 'GET',
headers: config.browser.headers,
json: true,
};
return new Promise((resolve) => {
const today = moment().format('YYYYMMDD');
request(options, (error, response, body) => {
if (error) {
// in case ticker block my programe, any error will try today
resolve(today);
}
if (response && response.statusCode !== 200) {
// in case ticker block my programe, any error will try today
resolve(today);
} else if (body) {
const { lastTradeDateUTC } = body[0];
resolve(moment(lastTradeDateUTC).format('YYYYMMDD'));
} else {
resolve(today);
}
});
});
}
function getDayTradeInfo(tradeDay, stockId, type) {
const uri = config.aastockTradeLink.replace('{stockId}', stockId).replace('{date}', tradeDay).replace('{type}', type);
logger.info(`getDayTradeInfo: ${uri}`);
const options = {
uri,
method: 'GET',
headers: config.browser.headers,
json: true,
};
return new Promise((resolve) => {
request(options, (error, response, body) => {
if (error) {
resolve(null);
}
if (response && response.statusCode !== 200) {
resolve(null);
} else {
// const pct = body && body.stat ? parseFloat(body.stat.pctRaw) : 0;
resolve(body || null);
}
});
});
}
async function isTradeInfoAbnormal(tradeDay, stockId, factor) {
try {
const ultraBuy = await getDayTradeInfo(tradeDay, stockId, config.aastockTradeType.buy[0]);
const ultraSell = await getDayTradeInfo(tradeDay, stockId, config.aastockTradeType.sell[0]);
const buyTurnOvers = _.map(ultraBuy.tslog, (n) => (_.parseInt(n.turnover.replace(/,/g, ''))));
const sellTurnOvers = _.map(ultraSell.tslog, (n) => (_.parseInt(n.turnover.replace(/,/g, ''))));
const topBuyTurnOver = _.max(buyTurnOvers) || 0;
const topSellTurnOver = _.max(sellTurnOvers) || 0;
logger.info(`topBuyTurnOver: ${topBuyTurnOver}, topSellTurnOver: ${topSellTurnOver}`);
return topBuyTurnOver > topSellTurnOver * factor;
} catch (ex) {
logger.error('error', ex);
return false;
}
}
// async function isDownTrend(tradeDay, stockId) {
// try {
// logger.info('isDownTrend : %s, %s', tradeDay, stockId);
// const buyResult = await Promise.reduce(
// config.aastockTradeType.buy,
// async (r, type) => {
// const dayTradeInfo = await getDayTradeInfo(tradeDay, stockId, type);
// const pctRaw = dayTradeInfo ? dayTradeInfo.stat.pctRaw : 0;
// return r + pctRaw;
// },
// 0,
// );
// const sellResult = await Promise.reduce(
// config.aastockTradeType.sell,
// async (r, type) => {
// const dayTradeInfo = await getDayTradeInfo(tradeDay, stockId, type);
// const pctRaw = dayTradeInfo ? dayTradeInfo.stat.pctRaw : 0;
// return r + pctRaw;
// },
// 0,
// );
// logger.info(`buyResult: ${buyResult}, sellResult: ${sellResult}`);
// const isSellMore = sellResult >= buyResult;
// return isSellMore || !isTradeInfoAbnormal(tradeDay, stockId, 1);
// } catch (ex) {
// logger.error('error', ex);
// return false;
// }
// }
async function isDayTradeInfoGood(tradeDay, stockId) {
try {
logger.info('isDayTradeInfoGood : %s, %s', tradeDay, stockId);
const buyResult = await Promise.reduce(
config.aastockTradeType.buy,
async (r, type) => {
const dayTradeInfo = await getDayTradeInfo(tradeDay, stockId, type);
const pctRaw = dayTradeInfo ? dayTradeInfo.stat.pctRaw : 0;
return r + pctRaw;
},
0,
);
const sellResult = await Promise.reduce(
config.aastockTradeType.sell,
async (r, type) => {
const dayTradeInfo = await getDayTradeInfo(tradeDay, stockId, type);
const pctRaw = dayTradeInfo ? dayTradeInfo.stat.pctRaw : 0;
return r + pctRaw;
},
0,
);
logger.info(`buyResult: ${buyResult}, sellResult: ${sellResult}`);
const isBuyMore = buyResult >= sellResult;
return isBuyMore;
} catch (ex) {
logger.error('error', ex);
return false;
}
}
function readSingleStock(stockId, season) {
return new Promise((resolve) => {
const cbHtml = fs.readFileSync(`./sample/${stockId}_${season.year}_${season.season}.html`).toString();
const $ = cheerio.load(cbHtml);
let result = $('.tab05 > tbody > tr').map((i, element) => ({
date: $(element).find('td:nth-of-type(1)').text()
.trim(),
volume: $(element).find('td:nth-of-type(5)').text()
.trim(),
open: $(element).find('td:nth-of-type(7)').text()
.trim(),
close: $(element).find('td:nth-of-type(2)').text()
.trim(),
})).get();
result = result.splice(1);
resolve(result);
});
}
async function getFromDataFile(stockId) {
return new Promise((resolve) => {
try {
const data = fs.readFileSync(`./data/${stockId}.dat`).toString();
const [maxVolume, avgVolume] = data.split(',');
resolve({ maxVolume: parseFloat(maxVolume), avgVolume: parseFloat(avgVolume) });
} catch (ex) {
resolve(null);
}
});
}
async function getRealTime(stockId) {
const uri = config.realTimeLink.replace('{stockId}', stockId);
logger.info(`getting ${uri}`);
const options = {
uri,
method: 'GET',
headers: config.browser.headers,
json: true,
};
return new Promise((resolve) => {
request(options, (error, response, body) => {
if (error) {
// in case ticker block my programe, any error will try today
resolve(0);
}
if (response && response.statusCode !== 200) {
// in case ticker block my programe, any error will try today
resolve(0);
} else if (body) {
const realTimeVolume = body.split(',')[12];
resolve(parseFloat(realTimeVolume));
} else {
resolve(0);
}
});
});
}
// async function writeStockData(stockId, maxVolume, avgVolume) {
// return new Promise((resolve) => {
// fs.writeFile(`./data/${stockId}.dat`, `${maxVolume},${avgVolume}`, (err) => {
// if (err) {
// logger.info('unable to write file: %s', JSON.stringify(err));
// }
// resolve();
// });
// });
// }
async function readStock(stockId, factor) {
try {
const result = await Promise.reduce(
config.stockSeasons,
async (r, season) => ([...r, ...await readSingleStock(stockId, season)]),
[],
);
// check if get highest volume
const todayVolume = _.parseInt(result[0].volume);
logger.info('stockId : %s', stockId);
logger.info('today volume : %s', todayVolume);
let cb = false;
if (todayVolume !== 0) {
const intStocks = _.map(result, (n) => _.parseInt(n.volume));
const maxVolume = _.max(intStocks);
const sortedStocks = intStocks.sort((a, b) => (b - a));
logger.info('sortedStocks : %s', JSON.stringify(sortedStocks));
const no3Volume = sortedStocks.length >= 3 ? sortedStocks.slice(2, 3) : sortedStocks[sortedStocks.length - 1];
logger.info('no3Volume : %s', no3Volume);
const isTop3Volume = (todayVolume >= no3Volume && no3Volume !== 0);
logger.info('max volume : %s', maxVolume);
const isHighestVolume = (todayVolume === maxVolume && todayVolume !== 0);
const volumesExcludeToday = intStocks.slice(1);
const avgVolume = _.mean(volumesExcludeToday);
logger.info('avgVolume : %s', avgVolume);
const isGoodAvgVolume = todayVolume >= factor * avgVolume;
logger.info(`todayVolume : ${todayVolume}`);
logger.info(`factor * avgVolume : ${factor * avgVolume}`);
logger.info(`isGoodAvgVolume : ${isGoodAvgVolume}`);
// await writeStockData(stockId, maxVolume, avgVolume);
// const isNotDrop = parseFloat(result[0].close) >= parseFloat(result[0].open);
cb = isHighestVolume || isGoodAvgVolume || isTop3Volume ? { stockId, maxVolume, isHighestVolume, todayVolume, avgVolume, isGoodAvgVolume, isTop3Volume } : false;
}
return cb;
} catch (ex) {
logger.error('error', ex);
return false;
}
}
export default {
downloadStockProfile, isStockProfileGood, readStock, getLastTradeDay, isTradeInfoAbnormal, isDayTradeInfoGood,
getRealTime, getFromDataFile,
};
|
eddielisc/sc-stock-app
|
server/stock.js
|
JavaScript
|
mit
| 10,791
|
# DSC Resource Testing Guidelines
## General Rules
- Each DSC module should contain the following Test folder structure:
```text
Tests
|---Unit
|---Integration
```
- The Tests\Unit folder must contain a Test Script for each DSC Resource in the DSC Module with the filename ```MSFT_<ResourceName>.tests.ps1```.
- The Tests\Integration folder should, whenever possible, contain a Test Script for each DSC Resource in the DSC Module with the filename ```MSFT_<ResourceName>.integration.tests.ps1```.
- Each Test Script should contain [Pester](https://github.com/pester/Pester) based tests.
- Integration tests should be created when possible, but for some DSC resources this may not be possible. For example, when integration tests would cause the testing computer configuration to be damaged.
- Unit and Integration tests should be created using the Template files that are located in the [Tests.Template](Tests.Template) folder in this repository.
- The Unit and Integration test templates require that ```Git.exe``` be installed and can be found in the ```%PATH%``` on the testing computer.
- The Unit and Integration test templates will automatically download or update the [DSCResource.Tests repository](https://github.com/PowerShell/DscResource.Tests) using Git.exe to the DSC Module folder.
- Ensure that the .gitignore file for the resource module contains **DSCResource.Tests** so that this folder is not accidentally included in a commit to your resource repository.
- Ensure that when creating or updating unit/integration tests from the Test.Templates the Version number of the test template file used remains in the test file.
## Creating DSC Resource Unit Test Instructions
1. Copy the ```\Tests.Template\unit_template.ps1``` to the ```\Tests\Unit\``` folder and rename to ```MSFT_x<ResourceName>.tests.ps1```
1. Open ```MSFT_x<ResourceName>.tests.ps1``` and customize TODO sections.
- **Note: The existing Describe blocks do not have to be used. The blocks included are a common test pattern, but may be completely replaced with a more suitable pattern.**
**Important: Please ensure that the test files created retain the version number of the template used to create them.**
## Creating DSC Resource Integration Test Instructions
1. Copy the ```\Tests.Template\integration_template.ps1``` to ```\Tests\Integration\``` folder and rename ```MSFT_x<ResourceName>.Integration.tests.ps1```
1. Open ```MSFT_x<ResourceName>.Integration.tests.ps1``` and customize TODO sections.
1. Copy the ```\Tests.Template\integration_comfig_template.ps1``` to ```\Tests\Integration\``` folder and rename ```MSFT_x<ResourceName>.config.ps1```
1. Open ```MSFT_x<ResourceName>.config.ps1``` and customize TODO sections.
**Important: Please ensure that the test files created retain the version number of the template used to create them.**
## Updating DSC Resource Tests
It is possible that the Unit and Integration test templates may change in future, either to support new functionality or fix an issue.
When a change is made to a template, it will be documented in the [Tests.Template\ChangeList.md](Tests.Template\ChangeList.md) file.
The version number in any current tests can be compared with the Change List to determine what has changed since the tests were updated.
If any unit or integration tests based on these templates require any enhancements or fixes then they will need to be updated manually.
**Important: Please ensure that when updating a test with the new Test Template content that the Template version number is also updated to match the new template.**
## Running Tests Locally
All tests are automatically run via AppVeyor when the repository is updated.
However, it is recommended that all tests be run locally before being committed.
Requirements for running all tests locally:
1. Git is installed and the ```Git.exe``` can be found in the ```%PATH%``` variable.
1. The latest [Pester Module](https://github.com/pester/Pester) is installed, either manually or via PowerShellGet.
1. An internet connection is available so that the DSCResource.Tests repository can be downloaded or updated using Git.
## Unit Testing Private Functions
If a resource contains private (non-exported) functions that need to be tested, then to allow these functions to be tested by Pester, they must be contained in an ```InModuleScope``` Pester block:
```powershell
InModuleScope $Global:DSCResourceName {
Describe "$($Global:DSCResourceName)\Get-FirewallRuleProperty" {
# Test Get-FirewallRuleProperty private/non-exported function
}
}
```
_Note: The core DSC Resource functions ```Get-TargetResource```, ```Set-TargetResource``` and ```Test-TargetResource``` must always be public functions, so do not need to be contained in an ```InModuleScope``` block._
## Using Variables Declared by the Module in Tests
It is common for modules to declare variables that are needed inside the module, but may also be required for unit testing.
One common example of this is the ```LocalizedData``` variable that contains localized messages used by the resource.
Variables declared at the module scope (private variables) can not be accessed by unit tests that are not inside an ```InModuleScope``` Pester block.
There are two solutions to this:
1. Use the ```InModuleScope``` to copy the private variable into a variable scoped to the Unit test:
```powershell
$LocalizedData = InModuleScope $Global:DSCResourceName {
$LocalizedData
}
```
2. Add any variables that are required to be accessed outside the module by unit tests to the ```Export-ModuleMember``` cmdlet in the DSC Resource:
```powershell
Export-ModuleMember -Function *-TargetResource -Variables LocalizedData
```
## Creating Mock Output Variables without InModuleScope
One useful pattern used when creating unit tests is to create variables that contain objects that will be returned when mocked cmdlets are called.
These variables are often used many times over a single unit test file and so assigning each to a variable is essential to reduce the size of the unit test as well as improve readability and maintainability.
For example:
```powershell
$MockNetAdapter = @{
Name = 'Ethernet'
PhysicalMediaType = '802.3'
Status = 'Up'
}
# Create a mock
Mock `
-CommandName Get-NetAdapter `
-MockWith { return $MockNetAdapter }
```
However, when ```InModuleScope``` is being used the variables that are defined won't be accessible from within the mocked cmdlets.
The solution to this is create a script block variable that contains the mocked object and then assign that to the Mock.
```powershell
$GetNetAdapter_PhysicalNetAdapterMock = {
return @{
Name = 'Ethernet'
PhysicalMediaType = '802.3'
Status = 'Up'
}
}
# Create a mock
Mock `
-CommandName Get-NetAdapter `
-ModuleName $script:ModuleName `
-MockWith $GetNetAdapter_PhysicalNetAdapterMock
```
## Example Unit Test Patterns
Pattern 1:
The goal of this pattern should be to describe the potential states a system could be in for each function.
```powershell
Describe 'Get-TargetResource' {
# TODO: Complete Get-TargetResource Tests...
}
Describe 'Set-TargetResource' {
# TODO: Complete Set-TargetResource Tests...
}
Describe 'Test-TargetResource' {
# TODO: Complete Test-TargetResource Tests...
}
```
Pattern 2:
The goal of this pattern should be to describe the potential states a system could be in so that the get/set/test cmdlets can be tested in those states. Any mocks that relate to that specific state can be included in the relevant Describe block. For a more detailed description of this approach please review #143
Add as many of these example 'states' as required to simulate the scenarios that the DSC resource is designed to work with, below a simple 'is in desired state' and 'is not in desired state' are used, but there may be more complex combinations of factors, depending on how complex your resource is.
```powershell
Describe 'The system is not in the desired state' {
#TODO: Mock cmdlets here that represent the system not being in the desired state
#TODO: Create a set of parameters to test your get/set/test methods in this state
$testParameters = @{
Property1 = 'value'
Property2 = 'value'
}
#TODO: Update the assertions below to align with the expected results of this state
It 'Should return something' {
Get-TargetResource @testParameters | Should -Be 'something'
}
It 'Should return false' {
Test-TargetResource @testParameters | Should -Be $false
}
It 'Should call Demo-CmdletName' {
Set-TargetResource @testParameters
#TODO: Assert that the appropriate cmdlets were called
Assert-MockCalled Demo-CmdletName
}
}
Describe 'The system is in the desired state' {
#TODO: Mock cmdlets here that represent the system being in the desired state
#TODO: Create a set of parameters to test your get/set/test methods in this state
$testParameters = @{
Property1 = 'value'
Property2 = 'value'
}
#TODO: Update the assertions below to align with the expected results of this state
It 'Should return something' {
Get-TargetResource @testParameters | Should -Be 'something'
}
It 'Should return true' {
Test-TargetResource @testParameters | Should -Be $true
}
}
```
To see examples of the Unit/Integration tests in practice, see the xNetworking MSFT_xFirewall resource:
- [Unit Tests](https://github.com/PowerShell/xNetworking/blob/dev/Tests/Unit/MSFT_xFirewall.Tests.ps1)
- [Integration Tests](https://github.com/PowerShell/xNetworking/blob/dev/Tests/Integration/MSFT_xFirewall.Integration.Tests.ps1)
- [Resource DSC Configuration](https://github.com/PowerShell/xNetworking/blob/dev/Tests/Integration/MSFT_xFirewall.config.ps1)
|
jpogran/DscResources
|
TestsGuidelines.md
|
Markdown
|
mit
| 10,288
|
window.theme = window.theme || {};
/* ================ SLATE ================ */
window.theme = window.theme || {};
theme.Sections = function Sections() {
this.constructors = {};
this.instances = [];
$(document)
.on('shopify:section:load', this._onSectionLoad.bind(this))
.on('shopify:section:unload', this._onSectionUnload.bind(this))
.on('shopify:section:select', this._onSelect.bind(this))
.on('shopify:section:deselect', this._onDeselect.bind(this))
.on('shopify:block:select', this._onBlockSelect.bind(this))
.on('shopify:block:deselect', this._onBlockDeselect.bind(this));
};
theme.Sections.prototype = _.assignIn({}, theme.Sections.prototype, {
_createInstance: function(container, constructor) {
var $container = $(container);
var id = $container.attr('data-section-id');
var type = $container.attr('data-section-type');
constructor = constructor || this.constructors[type];
if (_.isUndefined(constructor)) {
return;
}
var instance = _.assignIn(new constructor(container), {
id: id,
type: type,
container: container
});
this.instances.push(instance);
},
_onSectionLoad: function(evt) {
var container = $('[data-section-id]', evt.target)[0];
if (container) {
this._createInstance(container);
}
},
_onSectionUnload: function(evt) {
this.instances = _.filter(this.instances, function(instance) {
var isEventInstance = (instance.id === evt.detail.sectionId);
if (isEventInstance) {
if (_.isFunction(instance.onUnload)) {
instance.onUnload(evt);
}
}
return !isEventInstance;
});
},
_onSelect: function(evt) {
// eslint-disable-next-line no-shadow
var instance = _.find(this.instances, function(instance) {
return instance.id === evt.detail.sectionId;
});
if (!_.isUndefined(instance) && _.isFunction(instance.onSelect)) {
instance.onSelect(evt);
}
},
_onDeselect: function(evt) {
// eslint-disable-next-line no-shadow
var instance = _.find(this.instances, function(instance) {
return instance.id === evt.detail.sectionId;
});
if (!_.isUndefined(instance) && _.isFunction(instance.onDeselect)) {
instance.onDeselect(evt);
}
},
_onBlockSelect: function(evt) {
// eslint-disable-next-line no-shadow
var instance = _.find(this.instances, function(instance) {
return instance.id === evt.detail.sectionId;
});
if (!_.isUndefined(instance) && _.isFunction(instance.onBlockSelect)) {
instance.onBlockSelect(evt);
}
},
_onBlockDeselect: function(evt) {
// eslint-disable-next-line no-shadow
var instance = _.find(this.instances, function(instance) {
return instance.id === evt.detail.sectionId;
});
if (!_.isUndefined(instance) && _.isFunction(instance.onBlockDeselect)) {
instance.onBlockDeselect(evt);
}
},
register: function(type, constructor) {
this.constructors[type] = constructor;
$('[data-section-type=' + type + ']').each(function(index, container) {
this._createInstance(container, constructor);
}.bind(this));
}
});
window.slate = window.slate || {};
/**
* iFrames
* -----------------------------------------------------------------------------
* Wrap videos in div to force responsive layout.
*
* @namespace iframes
*/
slate.rte = {
/**
* Wrap tables in a container div to make them scrollable when needed
*
* @param {object} options - Options to be used
* @param {jquery} options.$tables - jquery object(s) of the table(s) to wrap
* @param {string} options.tableWrapperClass - table wrapper class name
*/
wrapTable: function(options) {
options.$tables.wrap('<div class="' + options.tableWrapperClass + '"></div>');
},
/**
* Wrap iframes in a container div to make them responsive
*
* @param {object} options - Options to be used
* @param {jquery} options.$iframes - jquery object(s) of the iframe(s) to wrap
* @param {string} options.iframeWrapperClass - class name used on the wrapping div
*/
wrapIframe: function(options) {
options.$iframes.each(function() {
// Add wrapper to make video responsive
$(this).wrap('<div class="' + options.iframeWrapperClass + '"></div>');
// Re-set the src attribute on each iframe after page load
// for Chrome's "incorrect iFrame content on 'back'" bug.
// https://code.google.com/p/chromium/issues/detail?id=395791
// Need to specifically target video and admin bar
this.src = this.src;
});
}
};
window.slate = window.slate || {};
/**
* A11y Helpers
* -----------------------------------------------------------------------------
* A collection of useful functions that help make your theme more accessible
* to users with visual impairments.
*
*
* @namespace a11y
*/
slate.a11y = {
/**
* For use when focus shifts to a container rather than a link
* eg for In-page links, after scroll, focus shifts to content area so that
* next `tab` is where user expects if focusing a link, just $link.focus();
*
* @param {JQuery} $element - The element to be acted upon
*/
pageLinkFocus: function($element) {
var focusClass = 'js-focus-hidden';
$element.first()
.attr('tabIndex', '-1')
.focus()
.addClass(focusClass)
.one('blur', callback);
function callback() {
$element.first()
.removeClass(focusClass)
.removeAttr('tabindex');
}
},
/**
* If there's a hash in the url, focus the appropriate element
*/
focusHash: function() {
var hash = window.location.hash;
// is there a hash in the url? is it an element on the page?
if (hash && document.getElementById(hash.slice(1))) {
this.pageLinkFocus($(hash));
}
},
/**
* When an in-page (url w/hash) link is clicked, focus the appropriate element
*/
bindInPageLinks: function() {
$('a[href*=#]').on('click', function(evt) {
this.pageLinkFocus($(evt.currentTarget.hash));
}.bind(this));
},
/**
* Traps the focus in a particular container
*
* @param {object} options - Options to be used
* @param {jQuery} options.$container - Container to trap focus within
* @param {jQuery} options.$elementToFocus - Element to be focused when focus leaves container
* @param {string} options.namespace - Namespace used for new focus event handler
*/
trapFocus: function(options) {
var eventName = options.namespace
? 'focusin.' + options.namespace
: 'focusin';
if (!options.$elementToFocus) {
options.$elementToFocus = options.$container;
}
options.$container.attr('tabindex', '-1');
options.$elementToFocus.focus();
$(document).off('focusin');
$(document).on(eventName, function(evt) {
if (options.$container[0] !== evt.target && !options.$container.has(evt.target).length) {
options.$container.focus();
}
});
},
/**
* Removes the trap of focus in a particular container
*
* @param {object} options - Options to be used
* @param {jQuery} options.$container - Container to trap focus within
* @param {string} options.namespace - Namespace used for new focus event handler
*/
removeTrapFocus: function(options) {
var eventName = options.namespace
? 'focusin.' + options.namespace
: 'focusin';
if (options.$container && options.$container.length) {
options.$container.removeAttr('tabindex');
}
$(document).off(eventName);
}
};
/**
* Image Helper Functions
* -----------------------------------------------------------------------------
* A collection of functions that help with basic image operations.
*
*/
theme.Images = (function() {
/**
* Preloads an image in memory and uses the browsers cache to store it until needed.
*
* @param {Array} images - A list of image urls
* @param {String} size - A shopify image size attribute
*/
function preload(images, size) {
if (typeof images === 'string') {
images = [images];
}
for (var i = 0; i < images.length; i++) {
var image = images[i];
this.loadImage(this.getSizedImageUrl(image, size));
}
}
/**
* Loads and caches an image in the browsers cache.
* @param {string} path - An image url
*/
function loadImage(path) {
new Image().src = path;
}
/**
* Swaps the src of an image for another OR returns the imageURL to the callback function
* @param image
* @param element
* @param callback
*/
function switchImage(image, element, callback) {
var size = this.imageSize(element.src);
var imageUrl = this.getSizedImageUrl(image.src, size);
if (callback) {
callback(imageUrl, image, element); // eslint-disable-line callback-return
} else {
element.src = imageUrl;
}
}
/**
* +++ Useful
* Find the Shopify image attribute size
*
* @param {string} src
* @returns {null}
*/
function imageSize(src) {
var match = src.match(/.+_((?:pico|icon|thumb|small|compact|medium|large|grande)|\d{1,4}x\d{0,4}|x\d{1,4})(@{1}?\d{1}?x{1}?)*[_\.]/);
if (match !== null) {
if (match[2] !== undefined) {
return match[1] + match[2];
}
else {
return match[1];
}
} else {
return null;
}
}
/**
* +++ Useful
* Adds a Shopify size attribute to a URL
*
* @param src
* @param size
* @returns {*}
*/
function getSizedImageUrl(src, size) {
if (size == null) {
return src;
}
if (size === 'master') {
return this.removeProtocol(src);
}
var match = src.match(/\.(jpg|jpeg|gif|png|bmp|bitmap|tiff|tif)(\?v=\d+)?$/i);
if (match != null) {
var prefix = src.split(match[0]);
var suffix = match[0];
return this.removeProtocol(prefix[0] + '_' + size + suffix);
}
return null;
}
function removeProtocol(path) {
return path.replace(/http(s)?:/, '');
}
return {
preload: preload,
loadImage: loadImage,
switchImage: switchImage,
imageSize: imageSize,
getSizedImageUrl: getSizedImageUrl,
removeProtocol: removeProtocol
};
})();
/**
* Currency Helpers
* -----------------------------------------------------------------------------
* A collection of useful functions that help with currency formatting
*
* Current contents
* - formatMoney - Takes an amount in cents and returns it as a formatted dollar value.
*
* Alternatives
* - Accounting.js - http://openexchangerates.github.io/accounting.js/
*
*/
theme.Currency = (function() {
var moneyFormat = '${{amount}}'; // eslint-disable-line camelcase
function formatMoney(cents, format) {
if (typeof cents === 'string') {
cents = cents.replace('.', '');
}
var value = '';
var placeholderRegex = /\{\{\s*(\w+)\s*\}\}/;
var formatString = (format || moneyFormat);
function formatWithDelimiters(number, precision, thousands, decimal) {
thousands = thousands || ',';
decimal = decimal || '.';
if (isNaN(number) || number == null) {
return 0;
}
number = (number / 100.0).toFixed(precision);
var parts = number.split('.');
var dollarsAmount = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + thousands);
var centsAmount = parts[1] ? (decimal + parts[1]) : '';
return dollarsAmount + centsAmount;
}
switch (formatString.match(placeholderRegex)[1]) {
case 'amount':
value = formatWithDelimiters(cents, 2);
break;
case 'amount_no_decimals':
value = formatWithDelimiters(cents, 0);
break;
case 'amount_with_comma_separator':
value = formatWithDelimiters(cents, 2, '.', ',');
break;
case 'amount_no_decimals_with_comma_separator':
value = formatWithDelimiters(cents, 0, '.', ',');
break;
case 'amount_no_decimals_with_space_separator':
value = formatWithDelimiters(cents, 0, ' ');
break;
}
return formatString.replace(placeholderRegex, value);
}
return {
formatMoney: formatMoney
}
})();
/**
* Variant Selection scripts
* ------------------------------------------------------------------------------
*
* Handles change events from the variant inputs in any `cart/add` forms that may
* exist. Also updates the master select and triggers updates when the variants
* price or image changes.
*
* @namespace variants
*/
slate.Variants = (function() {
/**
* Variant constructor
*
* @param {object} options - Settings from `product.js`
*/
function Variants(options) {
this.$container = options.$container;
this.product = options.product;
this.singleOptionSelector = options.singleOptionSelector;
this.originalSelectorId = options.originalSelectorId;
this.enableHistoryState = options.enableHistoryState;
this.currentVariant = this._getVariantFromOptions();
$(this.singleOptionSelector, this.$container).on('change', this._onSelectChange.bind(this));
}
Variants.prototype = _.assignIn({}, Variants.prototype, {
/**
* Get the currently selected options from add-to-cart form. Works with all
* form input elements.
*
* @return {array} options - Values of currently selected variants
*/
_getCurrentOptions: function() {
var currentOptions = _.map($(this.singleOptionSelector, this.$container), function(element) {
var $element = $(element);
var type = $element.attr('type');
var currentOption = {};
if (type === 'radio' || type === 'checkbox') {
if ($element[0].checked) {
currentOption.value = $element.val();
currentOption.index = $element.data('index');
return currentOption;
} else {
return false;
}
} else {
currentOption.value = $element.val();
currentOption.index = $element.data('index');
return currentOption;
}
});
// remove any unchecked input values if using radio buttons or checkboxes
currentOptions = _.compact(currentOptions);
return currentOptions;
},
/**
* Find variant based on selected values.
*
* @param {array} selectedValues - Values of variant inputs
* @return {object || undefined} found - Variant object from product.variants
*/
_getVariantFromOptions: function() {
var selectedValues = this._getCurrentOptions();
var variants = this.product.variants;
var found = _.find(variants, function(variant) {
return selectedValues.every(function(values) {
return _.isEqual(variant[values.index], values.value);
});
});
return found;
},
/**
* Event handler for when a variant input changes.
*/
_onSelectChange: function() {
var variant = this._getVariantFromOptions();
this.$container.trigger({
type: 'variantChange',
variant: variant
});
if (!variant) {
return;
}
this._updateMasterSelect(variant);
this._updateImages(variant);
this._updatePrice(variant);
this._updateSKU(variant);
this.currentVariant = variant;
if (this.enableHistoryState) {
this._updateHistoryState(variant);
}
},
/**
* Trigger event when variant image changes
*
* @param {object} variant - Currently selected variant
* @return {event} variantImageChange
*/
_updateImages: function(variant) {
var variantImage = variant.featured_image || {};
var currentVariantImage = this.currentVariant.featured_image || {};
if (!variant.featured_image || variantImage.src === currentVariantImage.src) {
return;
}
this.$container.trigger({
type: 'variantImageChange',
variant: variant
});
},
/**
* Trigger event when variant price changes.
*
* @param {object} variant - Currently selected variant
* @return {event} variantPriceChange
*/
_updatePrice: function(variant) {
if (variant.price === this.currentVariant.price && variant.compare_at_price === this.currentVariant.compare_at_price) {
return;
}
this.$container.trigger({
type: 'variantPriceChange',
variant: variant
});
},
/**
* Trigger event when variant sku changes.
*
* @param {object} variant - Currently selected variant
* @return {event} variantSKUChange
*/
_updateSKU: function(variant) {
if (variant.sku === this.currentVariant.sku) {
return;
}
this.$container.trigger({
type: 'variantSKUChange',
variant: variant
});
},
/**
* Update history state for product deeplinking
*
* @param {variant} variant - Currently selected variant
* @return {k} [description]
*/
_updateHistoryState: function(variant) {
if (!history.replaceState || !variant) {
return;
}
var newurl = window.location.protocol + '//' + window.location.host + window.location.pathname + '?variant=' + variant.id;
window.history.replaceState({path: newurl}, '', newurl);
},
/**
* Update hidden master select of variant change
*
* @param {variant} variant - Currently selected variant
*/
_updateMasterSelect: function(variant) {
$(this.originalSelectorId, this.$container).val(variant.id);
}
});
return Variants;
})();
/* ================ GLOBAL ================ */
/*============================================================================
Drawer modules
==============================================================================*/
theme.Drawers = (function() {
function Drawer(id, position, options) {
var defaults = {
close: '.js-drawer-close',
open: '.js-drawer-open-' + position,
openClass: 'js-drawer-open',
dirOpenClass: 'js-drawer-open-' + position
};
this.nodes = {
$parent: $('html').add('body'),
$page: $('#PageContainer')
};
this.config = $.extend(defaults, options);
this.position = position;
this.$drawer = $('#' + id);
if (!this.$drawer.length) {
return false;
}
this.drawerIsOpen = false;
this.init();
}
Drawer.prototype.init = function() {
$(this.config.open).on('click', $.proxy(this.open, this));
this.$drawer.on('click', this.config.close, $.proxy(this.close, this));
};
Drawer.prototype.open = function(evt) {
// Keep track if drawer was opened from a click, or called by another function
var externalCall = false;
// Prevent following href if link is clicked
if (evt) {
evt.preventDefault();
} else {
externalCall = true;
}
// Without this, the drawer opens, the click event bubbles up to nodes.$page
// which closes the drawer.
if (evt && evt.stopPropagation) {
evt.stopPropagation();
// save the source of the click, we'll focus to this on close
this.$activeSource = $(evt.currentTarget);
}
if (this.drawerIsOpen && !externalCall) {
return this.close();
}
// Add is-transitioning class to moved elements on open so drawer can have
// transition for close animation
this.$drawer.prepareTransition();
this.nodes.$parent.addClass(this.config.openClass + ' ' + this.config.dirOpenClass);
this.drawerIsOpen = true;
// Set focus on drawer
slate.a11y.trapFocus({
$container: this.$drawer,
namespace: 'drawer_focus'
});
// Run function when draw opens if set
if (this.config.onDrawerOpen && typeof this.config.onDrawerOpen === 'function') {
if (!externalCall) {
this.config.onDrawerOpen();
}
}
if (this.$activeSource && this.$activeSource.attr('aria-expanded')) {
this.$activeSource.attr('aria-expanded', 'true');
}
this.bindEvents();
return this;
};
Drawer.prototype.close = function() {
if (!this.drawerIsOpen) { // don't close a closed drawer
return;
}
// deselect any focused form elements
$(document.activeElement).trigger('blur');
// Ensure closing transition is applied to moved elements, like the nav
this.$drawer.prepareTransition();
this.nodes.$parent.removeClass(this.config.dirOpenClass + ' ' + this.config.openClass);
this.drawerIsOpen = false;
// Remove focus on drawer
slate.a11y.removeTrapFocus({
$container: this.$drawer,
namespace: 'drawer_focus'
});
this.unbindEvents();
};
Drawer.prototype.bindEvents = function() {
this.nodes.$parent.on('keyup.drawer', $.proxy(function(evt) {
// close on 'esc' keypress
if (evt.keyCode === 27) {
this.close();
return false;
} else {
return true;
}
}, this));
// Lock scrolling on mobile
this.nodes.$page.on('touchmove.drawer', function() {
return false;
});
this.nodes.$page.on('click.drawer', $.proxy(function() {
this.close();
return false;
}, this));
};
Drawer.prototype.unbindEvents = function() {
this.nodes.$page.off('.drawer');
this.nodes.$parent.off('.drawer');
};
return Drawer;
})();
/* ================ MODULES ================ */
window.theme = window.theme || {};
theme.Header = (function() {
var selectors = {
body: 'body',
navigation: '#AccessibleNav',
siteNavHasDropdown: '.site-nav--has-dropdown',
siteNavChildLinks: '.site-nav__child-link',
siteNavActiveDropdown: '.site-nav--active-dropdown',
siteNavLinkMain: '.site-nav__link--main',
siteNavChildLink: '.site-nav__link--last'
};
var config = {
activeClass: 'site-nav--active-dropdown',
childLinkClass: 'site-nav__child-link'
};
var cache = {};
function init() {
cacheSelectors();
cache.$parents.on('click.siteNav', function(evt) {
var $el = $(this);
if (!$el.hasClass(config.activeClass)) {
// force stop the click from happening
evt.preventDefault();
evt.stopImmediatePropagation();
}
showDropdown($el);
});
// check when we're leaving a dropdown and close the active dropdown
$(selectors.siteNavChildLink).on('focusout.siteNav', function() {
setTimeout(function() {
if ($(document.activeElement).hasClass(config.childLinkClass) || !cache.$activeDropdown.length) {
return;
}
hideDropdown(cache.$activeDropdown);
});
});
// close dropdowns when on top level nav
cache.$topLevel.on('focus.siteNav', function() {
if (cache.$activeDropdown.length) {
hideDropdown(cache.$activeDropdown);
}
});
cache.$subMenuLinks.on('click.siteNav', function(evt) {
// Prevent click on body from firing instead of link
evt.stopImmediatePropagation();
});
}
function cacheSelectors() {
cache = {
$nav: $(selectors.navigation),
$topLevel: $(selectors.siteNavLinkMain),
$parents: $(selectors.navigation).find(selectors.siteNavHasDropdown),
$subMenuLinks: $(selectors.siteNavChildLinks),
$activeDropdown: $(selectors.siteNavActiveDropdown)
};
}
function showDropdown($el) {
$el.addClass(config.activeClass);
// close open dropdowns
if (cache.$activeDropdown.length) {
hideDropdown(cache.$activeDropdown);
}
cache.$activeDropdown = $el;
// set expanded on open dropdown
$el.find(selectors.siteNavLinkMain).attr('aria-expanded', 'true');
setTimeout(function() {
$(window).on('keyup.siteNav', function(evt) {
if (evt.keyCode === 27) {
hideDropdown($el);
}
});
$(selectors.body).on('click.siteNav', function() {
hideDropdown($el);
});
}, 250);
}
function hideDropdown($el) {
// remove aria on open dropdown
$el.find(selectors.siteNavLinkMain).attr('aria-expanded', 'false');
$el.removeClass(config.activeClass);
// reset active dropdown
cache.$activeDropdown = $(selectors.siteNavActiveDropdown);
$(selectors.body).off('click.siteNav');
$(window).off('keyup.siteNav');
}
function unload() {
$(window).off('.siteNav');
cache.$parents.off('.siteNav');
cache.$subMenuLinks.off('.siteNav');
cache.$topLevel.off('.siteNav');
$(selectors.siteNavChildLink).off('.siteNav');
$(selectors.body).off('.siteNav');
}
return {
init: init,
unload: unload
};
})();
window.theme = window.theme || {};
theme.MobileNav = (function() {
var classes = {
mobileNavOpenIcon: 'mobile-nav--open',
mobileNavCloseIcon: 'mobile-nav--close',
subNavLink: 'mobile-nav__sublist-link',
return: 'mobile-nav__return-btn',
subNavActive: 'is-active',
subNavClosing: 'is-closing',
navOpen: 'js-menu--is-open',
subNavShowing: 'sub-nav--is-open',
thirdNavShowing: 'third-nav--is-open',
subNavToggleBtn: 'js-toggle-submenu'
};
var cache = {};
var isTransitioning;
var $activeSubNav;
var $activeTrigger;
var menuLevel = 1;
// Breakpoints from src/stylesheets/global/variables.scss.liquid
var mediaQuerySmall = 'screen and (max-width: 749px)';
function init() {
cacheSelectors();
cache.$mobileNavToggle.on('click', toggleMobileNav);
cache.$subNavToggleBtn.on('click.subNav', toggleSubNav);
// Close mobile nav when unmatching mobile breakpoint
enquire.register(mediaQuerySmall, {
unmatch: function() {
closeMobileNav();
}
});
}
function toggleMobileNav() {
if (cache.$mobileNavToggle.hasClass(classes.mobileNavCloseIcon)) {
closeMobileNav();
} else {
openMobileNav();
}
}
function cacheSelectors() {
cache = {
$pageContainer: $('#PageContainer'),
$siteHeader: $('.site-header'),
$mobileNavToggle: $('.js-mobile-nav-toggle'),
$mobileNavContainer: $('.mobile-nav-wrapper'),
$mobileNav: $('#MobileNav'),
$subNavToggleBtn: $('.' + classes.subNavToggleBtn)
};
}
function openMobileNav() {
var translateHeaderHeight = cache.$siteHeader.outerHeight() + cache.$siteHeader.offset().top;
cache.$mobileNavContainer
.prepareTransition()
.addClass(classes.navOpen);
cache.$mobileNavContainer.css({
transform: 'translate3d(0, ' + translateHeaderHeight + 'px, 0)'
});
cache.$pageContainer.css({
transform: 'translate3d(0, ' + cache.$mobileNavContainer[0].scrollHeight + 'px, 0)'
});
slate.a11y.trapFocus({
$container: cache.$mobileNav,
namespace: 'navFocus'
});
cache.$mobileNavToggle
.addClass(classes.mobileNavCloseIcon)
.removeClass(classes.mobileNavOpenIcon);
// close on escape
$(window).on('keyup.mobileNav', function(evt) {
if (evt.which === 27) {
closeMobileNav();
}
});
}
function closeMobileNav() {
cache.$mobileNavContainer.prepareTransition().removeClass(classes.navOpen);
cache.$mobileNavContainer.css({
transform: 'translate3d(0, -100%, 0)'
});
cache.$pageContainer.removeAttr('style');
cache.$mobileNavContainer.one('TransitionEnd.navToggle webkitTransitionEnd.navToggle transitionend.navToggle oTransitionEnd.navToggle', function() {
slate.a11y.removeTrapFocus({
$container: cache.$mobileNav,
namespace: 'navFocus'
});
});
cache.$mobileNavToggle
.addClass(classes.mobileNavOpenIcon)
.removeClass(classes.mobileNavCloseIcon);
$(window).off('keyup.mobileNav');
}
function toggleSubNav(evt) {
if (isTransitioning) {
return;
}
var $toggleBtn = $(evt.currentTarget);
var isReturn = $toggleBtn.hasClass(classes.return);
isTransitioning = true;
if (isReturn) {
// Close all subnavs by removing active class on buttons
$('.' + classes.subNavToggleBtn + '[data-level="' + (menuLevel - 1) + '"]')
.removeClass(classes.subNavActive);
if ($activeTrigger && $activeTrigger.length) {
$activeTrigger.removeClass(classes.subNavActive);
}
} else {
$toggleBtn.addClass(classes.subNavActive);
}
$activeTrigger = $toggleBtn;
goToSubnav($toggleBtn.data('target'));
}
function goToSubnav(target) {
/*eslint-disable shopify/jquery-dollar-sign-reference */
var $targetMenu = target
? $('.mobile-nav__dropdown[data-parent="' + target + '"]')
: cache.$mobileNav;
menuLevel = $targetMenu.data('level') ? $targetMenu.data('level') : 1;
if ($activeSubNav && $activeSubNav.length) {
$activeSubNav
.prepareTransition()
.addClass(classes.subNavClosing);
}
$activeSubNav = $targetMenu;
var $elementToFocus = target
? $targetMenu.find('.' + classes.subNavLink + ':first')
: $activeTrigger;
/*eslint-enable shopify/jquery-dollar-sign-reference */
var translateMenuHeight = $targetMenu.outerHeight();
var openNavClass = menuLevel > 2
? classes.thirdNavShowing
: classes.subNavShowing;
cache.$mobileNavContainer
.css('height', translateMenuHeight)
.removeClass(classes.thirdNavShowing)
.addClass(openNavClass);
if (!target) {
// Show top level nav
cache.$mobileNavContainer
.removeClass(classes.thirdNavShowing)
.removeClass(classes.subNavShowing);
}
// Focusing an item in the subnav early forces element into view and breaks the animation.
cache.$mobileNavContainer.one('TransitionEnd.subnavToggle webkitTransitionEnd.subnavToggle transitionend.subnavToggle oTransitionEnd.subnavToggle', function() {
slate.a11y.trapFocus({
$container: $targetMenu,
$elementToFocus: $elementToFocus,
namespace: 'subNavFocus'
});
cache.$mobileNavContainer.off('.subnavToggle');
isTransitioning = false;
});
// Match height of subnav
cache.$pageContainer.css({
transform: 'translate3d(0, ' + translateMenuHeight + 'px, 0)'
});
$activeSubNav.removeClass(classes.subNavClosing);
}
return {
init: init,
closeMobileNav: closeMobileNav
};
})(jQuery);
window.theme = window.theme || {};
theme.Search = (function() {
var selectors = {
search: '.search',
searchSubmit: '.search__submit',
searchInput: '.search__input',
siteHeader: '.site-header',
siteHeaderSearchToggle: '.site-header__search-toggle',
siteHeaderSearch: '.site-header__search',
searchDrawer: '.search-bar',
searchDrawerInput: '.search-bar__input',
searchHeader: '.search-header',
searchHeaderInput: '.search-header__input',
searchHeaderSubmit: '.search-header__submit',
mobileNavWrapper: '.mobile-nav-wrapper'
};
var classes = {
focus: 'search--focus',
mobileNavIsOpen: 'js-menu--is-open'
};
function init() {
if (!$(selectors.siteHeader).length) {
return;
}
initDrawer();
searchSubmit();
$(selectors.searchHeaderInput).add(selectors.searchHeaderSubmit).on('focus blur', function() {
$(selectors.searchHeader).toggleClass(classes.focus);
});
$(selectors.siteHeaderSearchToggle).on('click', function() {
var searchHeight = $(selectors.siteHeader).outerHeight();
var searchOffset = $(selectors.siteHeader).offset().top - searchHeight;
$(selectors.searchDrawer).css({
height: searchHeight + 'px',
top: searchOffset + 'px'
});
});
}
function initDrawer() {
// Add required classes to HTML
$('#PageContainer').addClass('drawer-page-content');
$('.js-drawer-open-top').attr('aria-controls', 'SearchDrawer').attr('aria-expanded', 'false');
theme.SearchDrawer = new theme.Drawers('SearchDrawer', 'top', {
onDrawerOpen: searchDrawerFocus
});
}
function searchDrawerFocus() {
searchFocus($(selectors.searchDrawerInput));
if ($(selectors.mobileNavWrapper).hasClass(classes.mobileNavIsOpen)) {
theme.MobileNav.closeMobileNav();
}
}
function searchFocus($el) {
$el.focus();
// set selection range hack for iOS
$el[0].setSelectionRange(0, $el[0].value.length);
}
function searchSubmit() {
$(selectors.searchSubmit).on('click', function(evt) {
var $el = $(evt.target);
var $input = $el.parents(selectors.search).find(selectors.searchInput);
if ($input.val().length === 0) {
evt.preventDefault();
searchFocus($input);
}
});
}
return {
init: init
};
})();
(function() {
var selectors = {
backButton: '.return-link'
};
var $backButton = $(selectors.backButton);
if (!document.referrer || !$backButton.length || !window.history.length) {
return;
}
$backButton.one('click', function(evt) {
evt.preventDefault();
var referrerDomain = urlDomain(document.referrer);
var shopDomain = urlDomain(window.location.href);
if (shopDomain === referrerDomain) {
history.back();
}
return false;
});
function urlDomain(url) {
var anchor = document.createElement('a');
anchor.ref = url;
return anchor.hostname;
}
})();
theme.Slideshow = (function() {
this.$slideshow = null;
var classes = {
wrapper: 'slideshow-wrapper',
slideshow: 'slideshow',
currentSlide: 'slick-current',
video: 'slideshow__video',
videoBackground: 'slideshow__video--background',
closeVideoBtn: 'slideshow__video-control--close',
pauseButton: 'slideshow__pause',
isPaused: 'is-paused'
};
function slideshow(el) {
this.$slideshow = $(el);
this.$wrapper = this.$slideshow.closest('.' + classes.wrapper);
this.$pause = this.$wrapper.find('.' + classes.pauseButton);
this.settings = {
accessibility: true,
arrows: false,
dots: true,
fade: true,
draggable: true,
touchThreshold: 20,
autoplay: this.$slideshow.data('autoplay'),
autoplaySpeed: this.$slideshow.data('speed')
};
this.$slideshow.on('beforeChange', beforeChange.bind(this));
this.$slideshow.on('init', slideshowA11y.bind(this));
this.$slideshow.slick(this.settings);
this.$pause.on('click', this.togglePause.bind(this));
}
function slideshowA11y(event, obj) {
var $slider = obj.$slider;
var $list = obj.$list;
var $wrapper = this.$wrapper;
var autoplay = this.settings.autoplay;
// Remove default Slick aria-live attr until slider is focused
$list.removeAttr('aria-live');
// When an element in the slider is focused
// pause slideshow and set aria-live.
$wrapper.on('focusin', function(evt) {
if (!$wrapper.has(evt.target).length) {
return;
}
$list.attr('aria-live', 'polite');
if (autoplay) {
$slider.slick('slickPause');
}
});
// Resume autoplay
$wrapper.on('focusout', function(evt) {
if (!$wrapper.has(evt.target).length) {
return;
}
$list.removeAttr('aria-live');
if (autoplay) {
// Manual check if the focused element was the video close button
// to ensure autoplay does not resume when focus goes inside YouTube iframe
if ($(evt.target).hasClass(classes.closeVideoBtn)) {
return;
}
$slider.slick('slickPlay');
}
});
// Add arrow key support when focused
if (obj.$dots) {
obj.$dots.on('keydown', function(evt) {
if (evt.which === 37) {
$slider.slick('slickPrev');
}
if (evt.which === 39) {
$slider.slick('slickNext');
}
// Update focus on newly selected tab
if ((evt.which === 37) || (evt.which === 39)) {
obj.$dots.find('.slick-active button').focus();
}
});
}
}
function beforeChange(event, slick, currentSlide, nextSlide) {
var $slider = slick.$slider;
var $currentSlide = $slider.find('.' + classes.currentSlide);
var $nextSlide = $slider.find('.slideshow__slide[data-slick-index="' + nextSlide + '"]');
if (isVideoInSlide($currentSlide)) {
var $currentVideo = $currentSlide.find('.' + classes.video);
var currentVideoId = $currentVideo.attr('id');
theme.SlideshowVideo.pauseVideo(currentVideoId);
$currentVideo.attr('tabindex', '-1');
}
if (isVideoInSlide($nextSlide)) {
var $video = $nextSlide.find('.' + classes.video);
var videoId = $video.attr('id');
var isBackground = $video.hasClass(classes.videoBackground);
if (isBackground) {
theme.SlideshowVideo.playVideo(videoId);
} else {
$video.attr('tabindex', '0');
}
}
}
function isVideoInSlide($slide) {
return $slide.find('.' + classes.video).length;
}
slideshow.prototype.togglePause = function() {
var slideshowSelector = getSlideshowId(this.$pause);
if (this.$pause.hasClass(classes.isPaused)) {
this.$pause.removeClass(classes.isPaused);
$(slideshowSelector).slick('slickPlay');
} else {
this.$pause.addClass(classes.isPaused);
$(slideshowSelector).slick('slickPause');
}
};
function getSlideshowId($el) {
return '#Slideshow-' + $el.data('id');
}
return slideshow;
})();
// Youtube API callback
// eslint-disable-next-line no-unused-vars
function onYouTubeIframeAPIReady() {
theme.SlideshowVideo.loadVideos();
}
theme.SlideshowVideo = (function() {
var autoplayCheckComplete = false;
var autoplayAvailable = false;
var playOnClickChecked = false;
var playOnClick = false;
var youtubeLoaded = false;
var videos = {};
var videoPlayers = [];
var videoOptions = {
ratio: 16 / 9,
playerVars: {
// eslint-disable-next-line camelcase
iv_load_policy: 3,
modestbranding: 1,
autoplay: 0,
controls: 0,
showinfo: 0,
wmode: 'opaque',
branding: 0,
autohide: 0,
rel: 0
},
events: {
onReady: onPlayerReady,
onStateChange: onPlayerChange
}
};
var classes = {
playing: 'video-is-playing',
paused: 'video-is-paused',
loading: 'video-is-loading',
loaded: 'video-is-loaded',
slideshowWrapper: 'slideshow-wrapper',
slide: 'slideshow__slide',
slideBackgroundVideo: 'slideshow__slide--background-video',
slideDots: 'slick-dots',
videoChrome: 'slideshow__video--chrome',
videoBackground: 'slideshow__video--background',
playVideoBtn: 'slideshow__video-control--play',
closeVideoBtn: 'slideshow__video-control--close',
currentSlide: 'slick-current',
slickClone: 'slick-cloned',
supportsAutoplay: 'autoplay',
supportsNoAutoplay: 'no-autoplay'
};
/**
* Public functions
*/
function init($video) {
if (!$video.length) {
return;
}
videos[$video.attr('id')] = {
id: $video.attr('id'),
videoId: $video.data('id'),
type: $video.data('type'),
status: $video.data('type') === 'chrome' ? 'closed' : 'background', // closed, open, background
videoSelector: $video.attr('id'),
$parentSlide: $video.closest('.' + classes.slide),
$parentSlideshowWrapper: $video.closest('.' + classes.slideshowWrapper),
controls: $video.data('type') === 'background' ? 0 : 1,
slideshow: $video.data('slideshow')
};
if (!youtubeLoaded) {
// This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
}
function customPlayVideo(playerId) {
// Do not autoplay just because the slideshow asked you to.
// If the slideshow asks to play a video, make sure
// we have done the playOnClick check first
if (!playOnClickChecked && !playOnClick) {
return;
}
if (playerId && typeof videoPlayers[playerId].playVideo === 'function') {
privatePlayVideo(playerId);
}
}
function pauseVideo(playerId) {
if (videoPlayers[playerId] && typeof videoPlayers[playerId].pauseVideo === 'function') {
videoPlayers[playerId].pauseVideo();
}
}
function loadVideos() {
for (var key in videos) {
if (videos.hasOwnProperty(key)) {
var args = $.extend({}, videoOptions, videos[key]);
args.playerVars.controls = args.controls;
videoPlayers[key] = new YT.Player(key, args);
}
}
initEvents();
youtubeLoaded = true;
}
function loadVideo(key) {
if (!youtubeLoaded) {
return;
}
var args = $.extend({}, videoOptions, videos[key]);
args.playerVars.controls = args.controls;
videoPlayers[key] = new YT.Player(key, args);
initEvents();
}
/**
* Private functions
*/
function privatePlayVideo(id, clicked) {
var videoData = videos[id];
var player = videoPlayers[id];
var $slide = videos[id].$parentSlide;
if (playOnClick) {
// playOnClick means we are probably on mobile (no autoplay).
// setAsPlaying will show the iframe, requiring another click
// to play the video.
setAsPlaying(videoData);
} else if (clicked || (autoplayCheckComplete && autoplayAvailable)) {
// Play if autoplay is available or clicked to play
$slide.removeClass(classes.loading);
setAsPlaying(videoData);
player.playVideo();
return;
}
// Check for autoplay if not already done
if (!autoplayCheckComplete) {
autoplayCheckFunction(player, $slide);
}
}
function setAutoplaySupport(supported) {
var supportClass = supported ? classes.supportsAutoplay : classes.supportsNoAutoplay;
$(document.documentElement).addClass(supportClass);
if (!supported) {
playOnClick = true;
}
autoplayCheckComplete = true;
}
function autoplayCheckFunction(player, $slide) {
// attempt to play video
player.playVideo();
autoplayTest(player)
.then(function() {
setAutoplaySupport(true);
})
.fail(function() {
// No autoplay available (or took too long to start playing).
// Show fallback image. Stop video for safety.
setAutoplaySupport(false);
player.stopVideo();
})
.always(function() {
autoplayCheckComplete = true;
$slide.removeClass(classes.loading);
});
}
function autoplayTest(player) {
var deferred = $.Deferred();
var wait;
var timeout;
wait = setInterval(function() {
if (player.getCurrentTime() <= 0) {
return;
}
autoplayAvailable = true;
clearInterval(wait);
clearTimeout(timeout);
deferred.resolve();
}, 500);
timeout = setTimeout(function() {
clearInterval(wait);
deferred.reject();
}, 4000); // subjective. test up to 8 times over 4 seconds
return deferred;
}
function playOnClickCheck() {
// Bail early for a few instances:
// - small screen
// - device sniff mobile browser
if (playOnClickChecked) {
return;
}
if ($(window).width() < 750) {
playOnClick = true;
} else if (window.mobileCheck()) {
playOnClick = true;
}
if (playOnClick) {
// No need to also do the autoplay check
setAutoplaySupport(false);
}
playOnClickChecked = true;
}
// The API will call this function when each video player is ready
function onPlayerReady(evt) {
evt.target.setPlaybackQuality('hd1080');
var videoData = getVideoOptions(evt);
playOnClickCheck();
// Prevent tabbing through YouTube player controls until visible
$('#' + videoData.id).attr('tabindex', '-1');
sizeBackgroundVideos();
// Customize based on options from the video ID
switch (videoData.type) {
case 'background-chrome':
case 'background':
evt.target.mute();
// Only play the video if it is in the active slide
if (videoData.$parentSlide.hasClass(classes.currentSlide)) {
privatePlayVideo(videoData.id);
}
break;
}
videoData.$parentSlide.addClass(classes.loaded);
}
function onPlayerChange(evt) {
var videoData = getVideoOptions(evt);
switch (evt.data) {
case 0: // ended
setAsFinished(videoData);
break;
case 1: // playing
setAsPlaying(videoData);
break;
case 2: // paused
setAsPaused(videoData);
break;
}
}
function setAsFinished(videoData) {
switch (videoData.type) {
case 'background':
videoPlayers[videoData.id].seekTo(0);
break;
case 'background-chrome':
videoPlayers[videoData.id].seekTo(0);
closeVideo(videoData.id);
break;
case 'chrome':
closeVideo(videoData.id);
break;
}
}
function setAsPlaying(videoData) {
var $slideshow = videoData.$parentSlideshowWrapper;
var $slide = videoData.$parentSlide;
$slide.removeClass(classes.loading);
// Do not change element visibility if it is a background video
if (videoData.status === 'background') {
return;
}
$('#' + videoData.id).attr('tabindex', '0');
switch (videoData.type) {
case 'chrome':
case 'background-chrome':
$slideshow
.removeClass(classes.paused)
.addClass(classes.playing);
$slide
.removeClass(classes.paused)
.addClass(classes.playing);
break;
}
// Update focus to the close button so we stay within the slide
$slide.find('.' + classes.closeVideoBtn).focus();
}
function setAsPaused(videoData) {
var $slideshow = videoData.$parentSlideshowWrapper;
var $slide = videoData.$parentSlide;
if (videoData.type === 'background-chrome') {
closeVideo(videoData.id);
return;
}
// YT's events fire after our click event. This status flag ensures
// we don't interact with a closed or background video.
if (videoData.status !== 'closed' && videoData.type !== 'background') {
$slideshow.addClass(classes.paused);
$slide.addClass(classes.paused);
}
if (videoData.type === 'chrome' && videoData.status === 'closed') {
$slideshow.removeClass(classes.paused);
$slide.removeClass(classes.paused);
}
$slideshow.removeClass(classes.playing);
$slide.removeClass(classes.playing);
}
function closeVideo(playerId) {
var videoData = videos[playerId];
var $slideshow = videoData.$parentSlideshowWrapper;
var $slide = videoData.$parentSlide;
var classesToRemove = [classes.pause, classes.playing].join(' ');
$('#' + videoData.id).attr('tabindex', '-1');
videoData.status = 'closed';
switch (videoData.type) {
case 'background-chrome':
videoPlayers[playerId].mute();
setBackgroundVideo(playerId);
break;
case 'chrome':
videoPlayers[playerId].stopVideo();
setAsPaused(videoData); // in case the video is already paused
break;
}
$slideshow.removeClass(classesToRemove);
$slide.removeClass(classesToRemove);
}
function getVideoOptions(evt) {
return videos[evt.target.h.id];
}
function startVideoOnClick(playerId) {
var videoData = videos[playerId];
// add loading class to slide
videoData.$parentSlide.addClass(classes.loading);
videoData.status = 'open';
switch (videoData.type) {
case 'background-chrome':
unsetBackgroundVideo(playerId, videoData);
videoPlayers[playerId].unMute();
privatePlayVideo(playerId, true);
break;
case 'chrome':
privatePlayVideo(playerId, true);
break;
}
// esc to close video player
$(document).on('keydown.videoPlayer', function(evt) {
if (evt.keyCode === 27) {
closeVideo(playerId);
}
});
}
function sizeBackgroundVideos() {
$('.' + classes.videoBackground).each(function(index, el) {
sizeBackgroundVideo($(el));
});
}
function sizeBackgroundVideo($player) {
var $slide = $player.closest('.' + classes.slide);
// Ignore cloned slides
if ($slide.hasClass(classes.slickClone)) {
return;
}
var slideWidth = $slide.width();
var playerWidth = $player.width();
var playerHeight = $player.height();
// when screen aspect ratio differs from video, video must center and underlay one dimension
if (slideWidth / videoOptions.ratio < playerHeight) {
playerWidth = Math.ceil(playerHeight * videoOptions.ratio); // get new player width
$player.width(playerWidth).height(playerHeight).css({
left: (slideWidth - playerWidth) / 2,
top: 0
}); // player width is greater, offset left; reset top
} else { // new video width < window width (gap to right)
playerHeight = Math.ceil(slideWidth / videoOptions.ratio); // get new player height
$player.width(slideWidth).height(playerHeight).css({
left: 0,
top: (playerHeight - playerHeight) / 2
}); // player height is greater, offset top; reset left
}
$player
.prepareTransition()
.addClass(classes.loaded);
}
function unsetBackgroundVideo(playerId) {
// Switch the background-chrome to a chrome-only player once played
$('#' + playerId)
.removeAttr('style')
.removeClass(classes.videoBackground)
.addClass(classes.videoChrome);
videos[playerId].$parentSlideshowWrapper
.removeClass(classes.slideBackgroundVideo)
.addClass(classes.playing);
videos[playerId].$parentSlide
.removeClass(classes.slideBackgroundVideo)
.addClass(classes.playing);
videos[playerId].status = 'open';
}
function setBackgroundVideo(playerId) {
// Switch back to background-chrome when closed
var $player = $('#' + playerId)
.addClass(classes.videoBackground)
.removeClass(classes.videoChrome);
videos[playerId].$parentSlide
.addClass(classes.slideBackgroundVideo);
videos[playerId].status = 'background';
sizeBackgroundVideo($player);
}
function initEvents() {
$(document).on('click.videoPlayer', '.' + classes.playVideoBtn, function(evt) {
var playerId = $(evt.currentTarget).data('controls');
startVideoOnClick(playerId);
});
$(document).on('click.videoPlayer', '.' + classes.closeVideoBtn, function(evt) {
var playerId = $(evt.currentTarget).data('controls');
closeVideo(playerId);
});
// Listen to resize to keep a background-size:cover-like layout
$(window).on('resize.videoPlayer', $.debounce(250, function() {
if (youtubeLoaded) {
sizeBackgroundVideos();
}
}));
}
function removeEvents() {
$(document).off('.videoPlayer');
$(window).off('.videoPlayer');
}
return {
init: init,
loadVideos: loadVideos,
loadVideo: loadVideo,
playVideo: customPlayVideo,
pauseVideo: pauseVideo,
removeEvents: removeEvents
};
})();
/* ================ TEMPLATES ================ */
(function() {
var $filterBy = $('#BlogTagFilter');
if (!$filterBy.length) {
return;
}
$filterBy.on('change', function() {
location.href = $(this).val();
});
})();
window.theme = theme || {};
theme.customerTemplates = (function() {
function initEventListeners() {
// Show reset password form
$('#RecoverPassword').on('click', function(evt) {
evt.preventDefault();
toggleRecoverPasswordForm();
});
// Hide reset password form
$('#HideRecoverPasswordLink').on('click', function(evt) {
evt.preventDefault();
toggleRecoverPasswordForm();
});
}
/**
*
* Show/Hide recover password form
*
*/
function toggleRecoverPasswordForm() {
$('#RecoverPasswordForm').toggleClass('hide');
$('#CustomerLoginForm').toggleClass('hide');
}
/**
*
* Show reset password success message
*
*/
function resetPasswordSuccess() {
var $formState = $('.reset-password-success');
// check if reset password form was successfully submited.
if (!$formState.length) {
return;
}
// show success message
$('#ResetSuccess').removeClass('hide');
}
/**
*
* Show/hide customer address forms
*
*/
function customerAddressForm() {
var $newAddressForm = $('#AddressNewForm');
if (!$newAddressForm.length) {
return;
}
// Initialize observers on address selectors, defined in shopify_common.js
if (Shopify) {
// eslint-disable-next-line no-new
new Shopify.CountryProvinceSelector('AddressCountryNew', 'AddressProvinceNew', {
hideElement: 'AddressProvinceContainerNew'
});
}
// Initialize each edit form's country/province selector
$('.address-country-option').each(function() {
var formId = $(this).data('form-id');
var countrySelector = 'AddressCountry_' + formId;
var provinceSelector = 'AddressProvince_' + formId;
var containerSelector = 'AddressProvinceContainer_' + formId;
// eslint-disable-next-line no-new
new Shopify.CountryProvinceSelector(countrySelector, provinceSelector, {
hideElement: containerSelector
});
});
// Toggle new/edit address forms
$('.address-new-toggle').on('click', function() {
$newAddressForm.toggleClass('hide');
});
$('.address-edit-toggle').on('click', function() {
var formId = $(this).data('form-id');
$('#EditAddress_' + formId).toggleClass('hide');
});
$('.address-delete').on('click', function() {
var $el = $(this);
var formId = $el.data('form-id');
var confirmMessage = $el.data('confirm-message');
// eslint-disable-next-line no-alert
if (confirm(confirmMessage || 'Are you sure you wish to delete this address?')) {
Shopify.postLink('/account/addresses/' + formId, {parameters: {_method: 'delete'}});
}
});
}
/**
*
* Check URL for reset password hash
*
*/
function checkUrlHash() {
var hash = window.location.hash;
// Allow deep linking to recover password form
if (hash === '#recover') {
toggleRecoverPasswordForm();
}
}
return {
init: function() {
checkUrlHash();
initEventListeners();
resetPasswordSuccess();
customerAddressForm();
}
};
})();
/*================ SECTIONS ================*/
window.theme = window.theme || {};
theme.Cart = (function() {
var selectors = {
edit: '.js-edit-toggle'
};
var config = {
showClass: 'cart__update--show',
showEditClass: 'cart__edit--active',
cartNoCookies: 'cart--no-cookies'
};
function Cart(container) {
this.$container = $(container);
this.$edit = $(selectors.edit, this.$container);
if (!this.cookiesEnabled()) {
this.$container.addClass(config.cartNoCookies);
}
this.$edit.on('click', this._onEditClick.bind(this));
}
Cart.prototype = _.assignIn({}, Cart.prototype, {
onUnload: function() {
this.$edit.off('click', this._onEditClick);
},
_onEditClick: function(evt) {
var $evtTarget = $(evt.target);
var $updateLine = $('.' + $evtTarget.data('target'));
$evtTarget.toggleClass(config.showEditClass);
$updateLine.toggleClass(config.showClass);
},
cookiesEnabled: function() {
var cookieEnabled = navigator.cookieEnabled;
if (!cookieEnabled){
document.cookie = 'testcookie';
cookieEnabled = (document.cookie.indexOf('testcookie') !== -1);
}
return cookieEnabled;
}
});
return Cart;
})();
window.theme = window.theme || {};
theme.Filters = (function() {
var constants = {
SORT_BY: 'sort_by'
};
var selectors = {
filterSelection: '.filters-toolbar__input--filter',
sortSelection: '.filters-toolbar__input--sort',
defaultSort: '.collection-header__default-sort'
};
function Filters(container) {
var $container = this.$container = $(container);
this.$filterSelect = $(selectors.filterSelection, $container);
this.$sortSelect = $(selectors.sortSelection, $container);
this.$selects = $(selectors.filterSelection, $container).add($(selectors.sortSelection, $container));
this.defaultSort = this._getDefaultSortValue();
this._resizeSelect(this.$selects);
this.$selects.removeClass('hidden');
this.$filterSelect.on('change', this._onFilterChange.bind(this));
this.$sortSelect.on('change', this._onSortChange.bind(this));
}
Filters.prototype = _.assignIn({}, Filters.prototype, {
_onSortChange: function(evt) {
var sort = this._sortValue();
if (sort.length) {
window.location.search = sort;
} else {
// clean up our url if the sort value is blank for default
window.location.href = window.location.href.replace(window.location.search, '');
}
this._resizeSelect($(evt.target));
},
_onFilterChange: function(evt) {
window.location.href = this.$filterSelect.val() + window.location.search;
this._resizeSelect($(evt.target));
},
_getSortValue: function() {
return this.$sortSelect.val() || this.defaultSort;
},
_getDefaultSortValue: function() {
return $(selectors.defaultSort, this.$container).val();
},
_sortValue: function() {
var sort = this._getSortValue();
var query = '';
if (sort !== this.defaultSort) {
query = constants.SORT_BY + '=' + sort;
}
return query;
},
_resizeSelect: function($selection) {
$selection.each(function() {
var $this = $(this);
var arrowWidth = 10;
// create test element
var text = $this.find('option:selected').text();
var $test = $('<span>').html(text);
// add to body, get width, and get out
$test.appendTo('body');
var width = $test.width();
$test.remove();
// set select width
$this.width(width + arrowWidth);
});
},
onUnload: function() {
this.$filterSelect.off('change', this._onFilterChange);
this.$sortSelect.off('change', this._onSortChange);
}
});
return Filters;
})();
window.theme = window.theme || {};
theme.HeaderSection = (function() {
function Header() {
theme.Header.init();
theme.MobileNav.init();
theme.Search.init();
}
Header.prototype = _.assignIn({}, Header.prototype, {
onUnload: function() {
theme.Header.unload();
}
});
return Header;
})();
theme.Maps = (function() {
var config = {
zoom: 14
};
var apiStatus = null;
var mapsToLoad = [];
var errors = {
addressNoResults: theme.strings.addressNoResults,
addressQueryLimit: theme.strings.addressQueryLimit,
addressError: theme.strings.addressError,
authError: theme.strings.authError
};
var selectors = {
section: '[data-section-type="map"]',
map: '[data-map]',
mapOverlay: '[data-map-overlay]'
};
var classes = {
mapError: 'map-section--load-error',
errorMsg: 'map-section__error errors text-center'
};
// Global function called by Google on auth errors.
// Show an auto error message on all map instances.
// eslint-disable-next-line camelcase, no-unused-vars
window.gm_authFailure = function() {
if (Shopify.designMode) {
$(selectors.section).addClass(classes.mapError);
$(selectors.map).remove();
$(selectors.mapOverlay).after('<div class="' + classes.errorMsg + '">' + theme.strings.authError + '</div>');
}
}
function Map(container) {
this.$container = $(container);
this.$map = this.$container.find(selectors.map);
this.key = this.$map.data('api-key');
if (typeof this.key === 'undefined') {
return;
}
if (apiStatus === 'loaded') {
this.createMap();
} else {
mapsToLoad.push(this);
if (apiStatus !== 'loading') {
apiStatus = 'loading';
if (typeof window.google === 'undefined') {
$.getScript('https://maps.googleapis.com/maps/api/js?key=' + this.key)
.then(function() {
apiStatus = 'loaded';
initAllMaps();
});
}
}
}
}
function initAllMaps() {
// API has loaded, load all Map instances in queue
$.each(mapsToLoad, function(index, instance) {
instance.createMap();
});
}
function geolocate($map) {
var deferred = $.Deferred();
var geocoder = new google.maps.Geocoder();
var address = $map.data('address-setting');
geocoder.geocode({address: address}, function(results, status) {
if (status !== google.maps.GeocoderStatus.OK) {
deferred.reject(status);
}
deferred.resolve(results);
});
return deferred;
}
Map.prototype = _.assignIn({}, Map.prototype, {
createMap: function() {
var $map = this.$map;
return geolocate($map)
.then(function(results) {
var mapOptions = {
zoom: config.zoom,
center: results[0].geometry.location,
draggable: false,
clickableIcons: false,
scrollwheel: false,
disableDoubleClickZoom: true,
disableDefaultUI: true
};
var map = this.map = new google.maps.Map($map[0], mapOptions);
var center = this.center = map.getCenter();
//eslint-disable-next-line no-unused-vars
var marker = new google.maps.Marker({
map: map,
position: map.getCenter()
});
google.maps.event.addDomListener(window, 'resize', $.debounce(250, function() {
google.maps.event.trigger(map, 'resize');
map.setCenter(center);
$map.removeAttr('style');
}));
}.bind(this))
.fail(function() {
var errorMessage;
switch (status) {
case 'ZERO_RESULTS':
errorMessage = errors.addressNoResults;
break;
case 'OVER_QUERY_LIMIT':
errorMessage = errors.addressQueryLimit;
break;
case 'REQUEST_DENIED':
errorMessage = errors.authError;
break;
default:
errorMessage = errors.addressError;
break;
}
// Show errors only to merchant in the editor.
if (Shopify.designMode) {
$map
.parent()
.addClass(classes.mapError)
.html('<div class="' + classes.errorMsg + '">' + errorMessage + '</div>');
}
});
},
onUnload: function() {
if (this.$map.length === 0) {
return;
}
google.maps.event.clearListeners(this.map, 'resize');
}
});
return Map;
})();
/* eslint-disable no-new */
theme.Product = (function() {
function Product(container) {
var $container = this.$container = $(container);
var sectionId = $container.attr('data-section-id');
this.settings = {
// Breakpoints from src/stylesheets/global/variables.scss.liquid
mediaQueryMediumUp: 'screen and (min-width: 750px)',
mediaQuerySmall: 'screen and (max-width: 749px)',
bpSmall: false,
enableHistoryState: $container.data('enable-history-state') || false,
namespace: '.slideshow-' + sectionId,
sectionId: sectionId,
sliderActive: false,
zoomEnabled: false
};
this.selectors = {
addToCart: '#AddToCart-' + sectionId,
addToCartText: '#AddToCartText-' + sectionId,
comparePrice: '#ComparePrice-' + sectionId,
originalPrice: '#ProductPrice-' + sectionId,
SKU: '.variant-sku',
originalPriceWrapper: '.product-price__price-' + sectionId,
originalSelectorId: '#ProductSelect-' + sectionId,
productImageWraps: '.product-single__photo',
productPrices: '.product-single__price-' + sectionId,
productThumbImages: '.product-single__thumbnail--' + sectionId,
productThumbs: '.product-single__thumbnails-' + sectionId,
saleClasses: 'product-price__sale product-price__sale--single',
saleLabel: '.product-price__sale-label-' + sectionId,
singleOptionSelector: '.single-option-selector-' + sectionId
}
// Stop parsing if we don't have the product json script tag when loading
// section in the Theme Editor
if (!$('#ProductJson-' + sectionId).html()) {
return;
}
this.productSingleObject = JSON.parse(document.getElementById('ProductJson-' + sectionId).innerHTML);
this.settings.zoomEnabled = $(this.selectors.productImageWraps).hasClass('js-zoom-enabled');
this._initBreakpoints();
this._stringOverrides();
this._initVariants();
this._initImageSwitch();
this._setActiveThumbnail();
}
Product.prototype = _.assignIn({}, Product.prototype, {
_stringOverrides: function() {
theme.productStrings = theme.productStrings || {};
$.extend(theme.strings, theme.productStrings);
},
_initBreakpoints: function() {
var self = this;
enquire.register(this.settings.mediaQuerySmall, {
match: function() {
// initialize thumbnail slider on mobile if more than three thumbnails
if ($(self.selectors.productThumbImages).length > 3) {
self._initThumbnailSlider();
}
// destroy image zooming if enabled
if (self.settings.zoomEnabled) {
$(self.selectors.productImageWraps).each(function( index ) {
_destroyZoom(this);
});
}
self.settings.bpSmall = true;
},
unmatch: function() {
if (self.settings.sliderActive) {
self._destroyThumbnailSlider();
}
self.settings.bpSmall = false;
}
});
enquire.register(this.settings.mediaQueryMediumUp, {
match: function() {
if (self.settings.zoomEnabled) {
$(self.selectors.productImageWraps).each(function( index ) {
_enableZoom(this);
});
}
}
});
},
_initVariants: function() {
var options = {
$container: this.$container,
enableHistoryState: this.$container.data('enable-history-state') || false,
singleOptionSelector: this.selectors.singleOptionSelector,
originalSelectorId: this.selectors.originalSelectorId,
product: this.productSingleObject
};
this.variants = new slate.Variants(options);
this.$container.on('variantChange' + this.settings.namespace, this._updateAddToCart.bind(this));
this.$container.on('variantImageChange' + this.settings.namespace, this._updateImages.bind(this));
this.$container.on('variantPriceChange' + this.settings.namespace, this._updatePrice.bind(this));
this.$container.on('variantSKUChange' + this.settings.namespace, this._updateSKU.bind(this));
},
_initImageSwitch: function() {
if (!$(this.selectors.productThumbImages).length) {
return;
}
var self = this;
$(this.selectors.productThumbImages).on('click', function(evt) {
evt.preventDefault();
var $el = $(this);
var imageId = $el.data('thumbnail-id');
self._switchImage(imageId);
self._setActiveThumbnail(imageId);
});
},
_setActiveThumbnail: function(imageId) {
var activeClass = 'active-thumb';
// If there is no element passed, find it by the current product image
if (typeof imageId === 'undefined') {
imageId = $(this.selectors.productImageWraps + ":not('.hide')").data('image-id');
}
var $thumbnail = $(this.selectors.productThumbImages + "[data-thumbnail-id='" + imageId + "']");
$(this.selectors.productThumbImages).removeClass(activeClass);
$thumbnail.addClass(activeClass);
},
_switchImage: function(imageId) {
var $newImage = $( this.selectors.productImageWraps + "[data-image-id='" + imageId + "']", this.$container);
var $otherImages = $( this.selectors.productImageWraps + ":not([data-image-id='" + imageId + "'])", this.$container);
$newImage.removeClass('hide');
$otherImages.addClass('hide');
},
_initThumbnailSlider: function() {
var options = {
slidesToShow: 4,
slidesToScroll: 3,
infinite: false,
prevArrow: '.thumbnails-slider__prev--' + this.settings.sectionId,
nextArrow: '.thumbnails-slider__next--' + this.settings.sectionId,
responsive: [
{
breakpoint: 321,
settings: {
slidesToShow: 3
}
}
]
};
$(this.selectors.productThumbs).slick(options);
this.settings.sliderActive = true;
},
_destroyThumbnailSlider: function() {
$(this.selectors.productThumbs).slick('unslick');
this.settings.sliderActive = false;
},
_updateAddToCart: function(evt) {
var variant = evt.variant;
if (variant) {
$(this.selectors.productPrices)
.removeClass('visibility-hidden')
.attr('aria-hidden', 'true');
if (variant.available) {
$(this.selectors.addToCart).prop('disabled', false);
$(this.selectors.addToCartText).text(theme.strings.addToCart);
} else {
// The variant doesn't exist, disable submit button and change the text.
// This may be an error or notice that a specific variant is not available.
$(this.selectors.addToCart).prop('disabled', true);
$(this.selectors.addToCartText).text(theme.strings.soldOut);
}
} else {
$(this.selectors.addToCart).prop('disabled', true);
$(this.selectors.addToCartText).text(theme.strings.unavailable);
$(this.selectors.productPrices)
.addClass('visibility-hidden')
.attr('aria-hidden', 'false');
}
},
_updateImages: function(evt) {
var variant = evt.variant;
var imageId = variant.featured_image.id
this._switchImage(imageId);
this._setActiveThumbnail(imageId);
},
_updatePrice: function(evt) {
var variant = evt.variant;
// Update the product price
$(this.selectors.originalPrice).html(theme.Currency.formatMoney(variant.price, theme.moneyFormat));
// Update and show the product's compare price if necessary
if (variant.compare_at_price > variant.price) {
$(this.selectors.comparePrice)
.html(theme.Currency.formatMoney(variant.compare_at_price, theme.moneyFormat))
.removeClass('hide');
$(this.selectors.originalPriceWrapper).addClass(this.selectors.saleClasses);
$(this.selectors.saleLabel).removeClass('hide');
} else {
$(this.selectors.comparePrice).addClass('hide');
$(this.selectors.saleLabel).addClass('hide');
$(this.selectors.originalPriceWrapper).removeClass(this.selectors.saleClasses);
}
},
_updateSKU: function(evt) {
var variant = evt.variant;
// Update the sku
$(this.selectors.SKU).html(variant.sku);
},
onUnload: function() {
this.$container.off(this.settings.namespace);
}
});
function _enableZoom(el) {
var zoomUrl = $(el).data('zoom');
$(el).zoom({
url: zoomUrl
});
}
function _destroyZoom(el) {
$(el).trigger('zoom.destroy');
}
return Product;
})();
theme.Quotes = (function() {
var config = {
mediaQuerySmall: 'screen and (max-width: 749px)',
mediaQueryMediumUp: 'screen and (min-width: 750px)',
slideCount: 0
};
var defaults = {
accessibility: true,
arrows: false,
dots: true,
autoplay: false,
touchThreshold: 20,
slidesToShow: 3,
slidesToScroll: 3
};
function Quotes(container) {
var $container = this.$container = $(container);
var sectionId = $container.attr('data-section-id');
var wrapper = this.wrapper = '.quotes-wrapper';
var slider = this.slider = '#Quotes-' + sectionId;
var $slider = $(slider, wrapper);
var sliderActive = false;
var mobileOptions = $.extend({}, defaults, {
slidesToShow: 1,
slidesToScroll: 1,
adaptiveHeight: true
});
config.slideCount = $slider.data('count');
// Override slidesToShow/Scroll if there are not enough blocks
if (config.slideCount < defaults.slidesToShow) {
defaults.slidesToShow = config.slideCount;
defaults.slidesToScroll = config.slideCount;
}
$slider.on('init', this.a11y.bind(this));
enquire.register(config.mediaQuerySmall, {
match: function() {
initSlider($slider, mobileOptions);
}
});
enquire.register(config.mediaQueryMediumUp, {
match: function() {
initSlider($slider, defaults);
}
});
function initSlider(sliderObj, args) {
if (sliderActive) {
sliderObj.slick('unslick');
sliderActive = false;
}
sliderObj.slick(args);
sliderActive = true;
}
}
Quotes.prototype = _.assignIn({}, Quotes.prototype, {
onUnload: function() {
enquire.unregister(config.mediaQuerySmall);
enquire.unregister(config.mediaQueryMediumUp);
$(this.slider, this.wrapper).slick('unslick');
},
onBlockSelect: function(evt) {
// Ignore the cloned version
var $slide = $('.quotes-slide--' + evt.detail.blockId + ':not(.slick-cloned)');
var slideIndex = $slide.data('slick-index');
// Go to selected slide, pause autoplay
$(this.slider, this.wrapper).slick('slickGoTo', slideIndex);
},
a11y: function(event, obj) {
var $list = obj.$list;
var $wrapper = $(this.wrapper, this.$container);
// Remove default Slick aria-live attr until slider is focused
$list.removeAttr('aria-live');
// When an element in the slider is focused set aria-live
$wrapper.on('focusin', function(evt) {
if ($wrapper.has(evt.target).length) {
$list.attr('aria-live', 'polite');
}
});
// Remove aria-live
$wrapper.on('focusout', function(evt) {
if ($wrapper.has(evt.target).length) {
$list.removeAttr('aria-live');
}
});
}
});
return Quotes;
})();
theme.slideshows = {};
theme.SlideshowSection = (function() {
function SlideshowSection(container) {
var $container = this.$container = $(container);
var sectionId = $container.attr('data-section-id');
var slideshow = this.slideshow = '#Slideshow-' + sectionId;
$('.slideshow__video', slideshow).each(function() {
var $el = $(this);
theme.SlideshowVideo.init($el);
theme.SlideshowVideo.loadVideo($el.attr('id'));
});
theme.slideshows[slideshow] = new theme.Slideshow(slideshow);
}
return SlideshowSection;
})();
theme.SlideshowSection.prototype = _.assignIn({}, theme.SlideshowSection.prototype, {
onUnload: function() {
delete theme.slideshows[this.slideshow];
},
onBlockSelect: function(evt) {
var $slideshow = $(this.slideshow);
// Ignore the cloned version
var $slide = $('.slideshow__slide--' + evt.detail.blockId + ':not(.slick-cloned)');
var slideIndex = $slide.data('slick-index');
// Go to selected slide, pause autoplay
$slideshow.slick('slickGoTo', slideIndex).slick('slickPause');
},
onBlockDeselect: function() {
// Resume autoplay
$(this.slideshow).slick('slickPlay');
}
});
$(document).ready(function() {
var sections = new theme.Sections();
sections.register('cart-template', theme.Cart);
sections.register('product', theme.Product);
sections.register('collection-template', theme.Filters);
sections.register('product-template', theme.Product);
sections.register('header-section', theme.HeaderSection);
sections.register('map', theme.Maps);
sections.register('slideshow-section', theme.SlideshowSection);
sections.register('quotes', theme.Quotes);
});
theme.init = function() {
theme.customerTemplates.init();
// Theme-specific selectors to make tables scrollable
var tableSelectors =
'.rte table,' +
'.custom__item-inner--html table';
slate.rte.wrapTable({
$tables: $(tableSelectors),
tableWrapperClass: 'scrollable-wrapper',
});
// Theme-specific selectors to make iframes responsive
var iframeSelectors =
'.rte iframe[src*="youtube.com/embed"],' +
'.rte iframe[src*="player.vimeo"],' +
'.custom__item-inner--html iframe[src*="youtube.com/embed"],' +
'.custom__item-inner--html iframe[src*="player.vimeo"]';
slate.rte.wrapIframe({
$iframes: $(iframeSelectors),
iframeWrapperClass: 'video-wrapper'
});
// Common a11y fixes
slate.a11y.pageLinkFocus($(window.location.hash));
$('.in-page-link').on('click', function(evt) {
slate.a11y.pageLinkFocus($(evt.currentTarget.hash));
});
$('a[href="#"]').on('click', function(evt) {
evt.preventDefault();
});
};
$(theme.init);
|
jonschlinkert/liquid-to-handlebars
|
test/fixtures/shopify-debut/assets/theme.js
|
JavaScript
|
mit
| 77,185
|
{% extends "admin/base.html" %}
{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %}
{% block branding %}
<h1 id="site-name"><a href="{% url 'admin:index' %}">Git Involved Administration</a></h1>
{% endblock %}
{% block nav-global %}{% endblock %}
|
raoariel/git-involved
|
DjangoWebProject/gitinvolved/templates/admin/base_site.html
|
HTML
|
mit
| 291
|
/*
** A stack implemented with a dynamically allocated array.
** The array size is given when create is called, which must
** happen before any other stack operations are attempted.
*/
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <assert.h>
/*
** The array that holds the values on the stack, and a pointer
** to the topmost value on the stack.
*/
static STACK_TYPE *stack;
static size_t stack_size;
static int top_element = -1;
/*
** create_stack
*/
void
create_stack( size_t size )
{
assert( stack_size == 0 );
stack_size = size;
stack = malloc( stack_size * sizeof( STACK_TYPE ) );
assert( stack != NULL );
}
/*
** destroy_stack
*/
void
destroy_stack( void )
{
assert( stack_size > 0 );
stack_size = 0;
free( stack );
stack = NULL;
}
/*
** push
*/
void
push( STACK_TYPE value )
{
assert( !is_full() );
top_element += 1;
stack[ top_element ] = value;
}
/*
** pop
*/
void
pop( void )
{
assert( !is_empty() );
top_element -= 1;
}
/*
** top
*/
STACK_TYPE top( void )
{
assert( !is_empty() );
return stack[ top_element ];
}
/*
** is_empty
*/
int
is_empty( void )
{
assert( stack_size > 0 );
return top_element == -1;
}
/*
** is_full
*/
int
is_full( void )
{
assert( stack_size > 0 );
return top_element == stack_size - 1;
}
|
freudshow/learnc
|
Pointers.On.C/ch17/d_stack.c
|
C
|
mit
| 1,293
|
#ifndef AI_HPP
#define AI_HPP
class Mon;
class MonCtl
{
public:
MonCtl(Mon& mon) :
mon_(&mon) {}
MonCtl(const MonCtl&) = delete;
MonCtl& operator=(const MonCtl&) = delete;
virtual ~MonCtl() {}
virtual void act() = 0;
protected:
Mon* const mon_;
};
class Ai : public MonCtl
{
public:
Ai(Mon& mon) :
MonCtl(mon) {}
void act() override;
};
class PlayerMonCtl : public MonCtl
{
public:
PlayerMonCtl(Mon& mon) :
MonCtl(mon) {}
void act() override;
};
#endif // AI_HPP
|
martin-tornqvist/sfrl
|
include/ai.hpp
|
C++
|
mit
| 539
|
'use strict';
// Test specific configuration
// ===========================
module.exports = {
// MongoDB connection options
mongo: {
uri: 'mongodb://localhost/conversionrobot-test'
}
};
|
budacode/conversionrobot.com
|
server/config/environment/test.js
|
JavaScript
|
mit
| 197
|
package com.dimon.ganwumei.injector.modules;
import dagger.Module;
/**
*
* Created by Dimon on 2016/3/22.
*/
@Module
public class GanWuFragmentModule {
public GanWuFragmentModule(){}
}
|
Dimon94/GanWuMei
|
GanWuMei/app/src/main/java/com/dimon/ganwumei/injector/modules/GanWuFragmentModule.java
|
Java
|
mit
| 194
|
window.ProseMirror = require("prosemirror/dist/edit").ProseMirror
require("prosemirror/dist/menu/menubar") // Load menubar module
require( "prosemirror/dist/markdown/to_markdown" )
require( "prosemirror/dist/markdown/from_markdown" )
window.ProseMirrorUtils = {};
window.ProseMirrorUtils.defaultschema = require( "prosemirror/dist/model/defaultschema")
window.ProseMirrorUtils.schema = require( "prosemirror/dist/model/schema")
window.ProseMirrorUtils.commandSet = require( "prosemirror/dist/edit/command").CommandSet
window.ProseMirrorUtils.menu = require ( "prosemirror/dist/menu/menu" )
|
patternseek/pnsk-structured-editor-prosemirror
|
src/editor.js
|
JavaScript
|
mit
| 591
|
<!DOCTYPE html>
<html lang="en-us">
<head>
<title>{%= o.htmlWebpackPlugin.options.title %}</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<link rel="stylesheet" href="node_modules/react-datagrid/index.css" >
{% if (o.htmlWebpackPlugin.options.production) { %}
<link rel="stylesheet" href="app.{%=o.webpack.hash%}.css" media="all">
{% } %}
</head>
<body class="index">
<div id='app'></div>
{% for (var chunk in o.htmlWebpackPlugin.files.chunks) { %}
<script src="{%=o.htmlWebpackPlugin.files.chunks[chunk].entry %}"></script>
{% } %}
</body>
</html>
|
Switajski/react-processed-grid
|
conf/tmpl.html
|
HTML
|
mit
| 712
|
'''
These classes specify the attributes
that a view object can have when editing views
'''
__author__ = 'William Emfinger'
__copyright__ = 'Copyright 2016, ROSMOD'
__credits__ = ['William Emfinger', 'Pranav Srinivas Kumar']
__license__ = 'GPL'
__version__ = '0.4'
__maintainer__ = 'William Emfinger'
__email__ = 'emfinger@isis.vanderbilt.edu'
__status__ = 'Production'
from meta import Attribute
objects = ['Container', 'Association']
# model related
class Object(Attribute):
tooltip = 'What kind of object is being viewed.'
options = objects
def __init__(self, value):
super(Object, self).__init__('list', value)
# drawing related
class Layout_Style(Attribute):
tooltip = 'How are the children arranged in this object.'
options = ['horizontal', 'vertical', 'grid', 'anchor']
def __init__(self, value):
super(Layout_Style, self).__init__('list', value)
class Width(Attribute):
tooltip = 'Width of the object.'
def __init__(self, value):
super(Width, self).__init__('float', value)
class Height(Attribute):
tooltip = 'Height of the object.'
def __init__(self, value):
super(Height, self).__init__('float', value)
class Draw_Style(Attribute):
tooltip = 'How the object is drawn.'
options = ['icon', 'ellipse', 'rect', 'round rect', 'hidden']
def __init__(self, value):
super(Draw_Style, self).__init__('list', value)
class Icon(Attribute):
tooltip = 'Icon displayed as background of the object.'
def __init__(self, value):
super(Icon, self).__init__('file_png', value)
class Color(Attribute):
tooltip = 'What color will the object be drawn with.'
def __init__(self, value):
super(Color, self).__init__('string', value)
class Text_Location(Attribute):
tooltip = 'Where will text be located?'
options = ['top', 'bottom', 'left', 'right', 'center']
def __init__(self, value):
super(Text_Location, self).__init__('list', value)
class Text_Horizontal_Alignment(Attribute):
tooltip = 'Horizontal Alignment of text'
options = ['left', 'right', 'horizontal center', 'justify']
def __init__(self, value):
super(Text_Horizontal_Alignment, self).__init__('list', value)
class Text_Vertical_Alignment(Attribute):
tooltip = 'Vertical Alignment of text'
options = ['top', 'bottom', 'vertical center']
def __init__(self, value):
super(Text_Vertical_Alignment, self).__init__('list', value)
# Layout configuration related
class Layout_Config(Attribute):
options = ['horizontal', 'vertical', 'grid', 'anchor']
editable = False
def __init__(self, value):
super(Layout_Config, self).__init__('dictionary_list', value)
class Root(Attribute):
tooltip = 'What acts as the local anchor for this object?'
options = ['top left', 'top right',
'bottom left', 'bottom right',
'center left', 'center right',
'top center', 'bottom center']
def __init__(self, value):
super(Root, self).__init__('list', value)
class Anchor(Attribute):
tooltip = 'What other object:point acts as the anchor for this object?'
options = ['top left', 'top right',
'bottom left', 'bottom right',
'center left', 'center right',
'top center', 'bottom center']
editable = False
def __init__(self, value):
super(Anchor, self).__init__('dictionary_reference', value)
# Association
class Source(Attribute):
tooltip = 'What is the external oobject source reference for this object'
def __init__(self, value):
super(Source, self).__init__('string', value)
class Destination(Attribute):
tooltip = 'What is the object destination reference for this object'
def __init__(self, value):
super(Destination, self).__init__('string', value)
|
finger563/editor
|
src/view_attributes.py
|
Python
|
mit
| 3,890
|
package au.edu.federation.caliko.visualisation;
import au.edu.federation.caliko.FabrikBone3D;
import au.edu.federation.caliko.FabrikChain3D;
import au.edu.federation.caliko.FabrikStructure3D;
import au.edu.federation.utils.Colour4f;
import au.edu.federation.utils.Mat3f;
import au.edu.federation.utils.Mat4f;
import au.edu.federation.utils.Utils;
import au.edu.federation.utils.Vec3f;
/**
* A class to draw various constraints for ball and hinge joints on FabrikBone3D objects.
*
* @author Al Lansley
* @version 0.3.1 - 20/07/2016
*/
public class FabrikConstraint3D
{
// Constant to convert degrees to radians
private static final float DEGS_TO_RADS = (float)Math.PI / 180.0f;
// Constraint colours
private static final Colour4f ANTICLOCKWISE_CONSTRAINT_COLOUR = new Colour4f(1.0f, 0.0f, 0.0f, 1.0f);
private static final Colour4f CLOCKWISE_CONSTRAINT_COLOUR = new Colour4f(0.0f, 0.0f, 1.0f, 1.0f);
private static final Colour4f BALL_JOINT_COLOUR = new Colour4f(1.0f, 0.0f, 0.0f, 1.0f);
private static final Colour4f GLOBAL_HINGE_COLOUR = new Colour4f(1.0f, 1.0f, 0.0f, 1.0f);
private static final Colour4f LOCAL_HINGE_COLOUR = new Colour4f(0.0f, 1.0f, 1.0f, 1.0f);
private static final Colour4f REFERENCE_AXIS_COLOUR = new Colour4f(1.0f, 0.0f, 1.0f, 1.0f);
// The drawn length of the rotor cone and the radius of the cone and circle describing the hinge axes
private static final float CONE_LENGTH_FACTOR = 0.3f;
private static final float RADIUS_FACTOR = 0.25f;
private static final int NUM_CONE_LINES = 12;
private static float rotStep = 360.0f / (float)NUM_CONE_LINES;
private Circle3D mCircle; // Used to draw hinges
private Line3D mLine; // Used to draw hinge axes, reference axes and ball-joint cones
private boolean initialised = false;
/** Default constructor. */
public FabrikConstraint3D()
{
if (!initialised)
{
initialised = true;
mCircle = new Circle3D();
mLine = new Line3D();
}
}
/**
* Draw the constraint for this FabrikBone3D.
* <p>
* Ball joints are drawn as a series of lines forming a cone, while global and local hinge joints are drawn
* as circles aligned to the hinge rotation axis, with an optional reference axis within the plane of the
* circle if required.
* <p>
* Line widths may commonly be between 1.0f and 32.0f, values outside of this range may result in unspecified behaviour.
*
* @param bone The FabrikBone3D object to draw the constraint about.
* @param referenceDirection As bones are constrained about the direction relative to the previous bone in the chain, this is the direction of the previous bone.
* @param lineWidth The width of the line used to draw the rotor constraint in pixels.
* @param colour The colour of the line.
* @param mvpMatrix The ModelViewProjection matrix with which to draw the circle.
*/
private void draw(FabrikBone3D bone, Vec3f referenceDirection, float lineWidth, Mat4f mvpMatrix)
{
float boneLength = bone.length();
Vec3f lineStart = bone.getStartLocation();
switch ( bone.getJointType() )
{
case BALL: {
float constraintAngleDegs = bone.getBallJointConstraintDegs();
// If the ball joint constraint is 180 degrees then it's not really constrained, so we won't draw it
if ( Utils.approximatelyEquals(constraintAngleDegs, 180.0f, 0.01f) ) { return; }
// The constraint direction is the direction of the previous bone rotated about a perpendicular axis by the constraint angle of this bone
Vec3f constraintDirection = Vec3f.rotateAboutAxisDegs(referenceDirection, constraintAngleDegs, Vec3f.genPerpendicularVectorQuick(referenceDirection) ).normalised();
// Draw the lines about the the bone (relative to the reference direction)
Vec3f lineEnd;
for (int loop = 0; loop < NUM_CONE_LINES; ++loop)
{
lineEnd = lineStart.plus( constraintDirection.times(boneLength * CONE_LENGTH_FACTOR) );
constraintDirection = Vec3f.rotateAboutAxisDegs(constraintDirection, rotStep, referenceDirection).normalised();
mLine.draw(lineStart, lineEnd, BALL_JOINT_COLOUR, lineWidth, mvpMatrix);
}
// Draw the circle at the top of the cone
float pushDistance = (float)Math.cos(constraintAngleDegs * DEGS_TO_RADS) * boneLength;
float radius = (float)Math.sin(constraintAngleDegs * DEGS_TO_RADS) * boneLength;
Vec3f circleCentre = lineStart.plus( referenceDirection.times(pushDistance * CONE_LENGTH_FACTOR) );
mCircle.draw(circleCentre, referenceDirection, radius * CONE_LENGTH_FACTOR, BALL_JOINT_COLOUR, lineWidth, mvpMatrix);
break;
}
case GLOBAL_HINGE: {
// Get the hinge rotation axis and draw the circle describing the hinge rotation axis
Vec3f hingeRotationAxis = bone.getJoint().getHingeRotationAxis();
float radius = boneLength * RADIUS_FACTOR;
mCircle.draw(lineStart, hingeRotationAxis, radius, GLOBAL_HINGE_COLOUR, lineWidth, mvpMatrix);
// Note: While ACW rotation is negative and CW rotation about an axis is positive, we store both
// of these as positive values between the range 0 to 180 degrees, as such we'll negate the
// clockwise rotation value for it to turn in the correct direction.
float anticlockwiseConstraintDegs = bone.getHingeJointAnticlockwiseConstraintDegs();
float clockwiseConstraintDegs = -bone.getHingeJointClockwiseConstraintDegs();
// If both the anticlockwise (positive) and clockwise (negative) constraint angles are not 180 degrees (i.e. we
// are constraining the hinge about a reference direction which lies in the plane of the hinge rotation axis)...
if ( !Utils.approximatelyEquals(anticlockwiseConstraintDegs, 180.0f, 0.01f) &&
!Utils.approximatelyEquals( clockwiseConstraintDegs, 180.0f, 0.01f) )
{
Vec3f hingeReferenceAxis = bone.getJoint().getHingeReferenceAxis();
// ...then draw the hinge reference axis and ACW/CW constraints about it.
mLine.draw(lineStart, lineStart.plus( hingeReferenceAxis.times(boneLength * RADIUS_FACTOR) ), REFERENCE_AXIS_COLOUR, lineWidth, mvpMatrix);
Vec3f anticlockwiseDirection = Vec3f.rotateAboutAxisDegs(hingeReferenceAxis, anticlockwiseConstraintDegs, hingeRotationAxis);
Vec3f clockwiseDirection = Vec3f.rotateAboutAxisDegs(hingeReferenceAxis, clockwiseConstraintDegs, hingeRotationAxis);
Vec3f anticlockwisePoint = lineStart.plus( anticlockwiseDirection.times(radius) );
Vec3f clockwisePoint = lineStart.plus( clockwiseDirection.times(radius) );
mLine.draw(lineStart, anticlockwisePoint, ANTICLOCKWISE_CONSTRAINT_COLOUR, lineWidth, mvpMatrix);
mLine.draw(lineStart, clockwisePoint, CLOCKWISE_CONSTRAINT_COLOUR, lineWidth, mvpMatrix);
}
break;
}
case LOCAL_HINGE: {
// Construct a rotation matrix based on the reference direction (i.e. the previous bone's direction)...
Mat3f m = Mat3f.createRotationMatrix(referenceDirection);
// ...and transform the hinge rotation axis into the previous bone's frame of reference
Vec3f relativeHingeRotationAxis = m.times( bone.getJoint().getHingeRotationAxis() ).normalise();
// Draw the circle describing the hinge rotation axis
float radius = boneLength * RADIUS_FACTOR;
mCircle.draw(lineStart, relativeHingeRotationAxis, radius, LOCAL_HINGE_COLOUR, lineWidth, mvpMatrix);
// Draw the hinge reference and clockwise/anticlockwise constraints if necessary
float anticlockwiseConstraintDegs = bone.getHingeJointAnticlockwiseConstraintDegs();
float clockwiseConstraintDegs = -bone.getHingeJointClockwiseConstraintDegs();
if ( !Utils.approximatelyEquals(anticlockwiseConstraintDegs, 180.0f, 0.01f) &&
!Utils.approximatelyEquals( clockwiseConstraintDegs, 180.0f, 0.01f) )
{
// Get the relative hinge rotation axis and draw it...
bone.getJoint().getHingeReferenceAxis().projectOntoPlane(relativeHingeRotationAxis);
Vec3f relativeHingeReferenceAxis = m.times(bone.getJoint().getHingeReferenceAxis()).normalise();
mLine.draw(lineStart, lineStart.plus( relativeHingeReferenceAxis.times(radius) ), REFERENCE_AXIS_COLOUR, lineWidth, mvpMatrix);
// ...as well as the clockwise and anticlockwise constraints.
Vec3f anticlockwiseDirection = Vec3f.rotateAboutAxisDegs(relativeHingeReferenceAxis, anticlockwiseConstraintDegs, relativeHingeRotationAxis);
Vec3f clockwiseDirection = Vec3f.rotateAboutAxisDegs(relativeHingeReferenceAxis, clockwiseConstraintDegs, relativeHingeRotationAxis);
Vec3f anticlockwisePoint = lineStart.plus( anticlockwiseDirection.times(radius) );
Vec3f clockwisePoint = lineStart.plus( clockwiseDirection.times(radius) );
mLine.draw(lineStart, anticlockwisePoint, ANTICLOCKWISE_CONSTRAINT_COLOUR, lineWidth, mvpMatrix);
mLine.draw(lineStart, clockwisePoint, CLOCKWISE_CONSTRAINT_COLOUR, lineWidth, mvpMatrix);
}
break;
}
} // End of switch statement
}
/**
* Draw the constraints on all bones in a FabrikChain3D object.
*
* Line widths may commonly be between 1.0f and 32.0f, values outside of this range may result in unspecified behaviour.
*
* @param chain The chain to use.
* @param lineWidth The width of the lines to draw.
* @param mvpMatrix The ModelViewProjection matrix to use.
*/
public void draw(FabrikChain3D chain, float lineWidth, Mat4f mvpMatrix)
{
int numBones = chain.getNumBones();
if (numBones > 0)
{
// Draw the base bone, using the constraint UV as the relative direction
switch ( chain.getBaseboneConstraintType() )
{
case NONE:
break;
case GLOBAL_ROTOR:
case GLOBAL_HINGE:
draw( chain.getBone(0), chain.getBaseboneConstraintUV(), lineWidth, mvpMatrix );
break;
case LOCAL_ROTOR:
case LOCAL_HINGE:
// If the structure hasn't been solved yet then we won't have a relative basebone constraint which we require
// to draw the constraint itself - so our best option is to simply not draw the constraint until we can.
if (chain.getBaseboneRelativeConstraintUV().length() > 0.0f)
{
draw( chain.getBone(0), chain.getBaseboneRelativeConstraintUV(), lineWidth, mvpMatrix );
}
break;
// No need for a default - constraint types are enums and we've covered them all.
}
// Draw all the bones AFTER the base bone, using the previous bone direction as the relative direction
for (int loop = 1; loop < numBones; ++loop)
{
draw( chain.getBone(loop), chain.getBone(loop-1).getDirectionUV(), lineWidth, mvpMatrix );
}
}
}
/**
* Draw the constraints on all bones in a FabrikChain3D object using the default line width.
*
* If the chain does not contain any bones then an IllegalArgumentException is thrown.
*
* @param chain The chain to use.
* @param mvpMatrix The ModelViewProjection matrix to use.
*/
public void draw(FabrikChain3D chain, Mat4f mvpMatrix) { draw(chain, 1.0f, mvpMatrix); }
/**
* Draw the constraints on all chains and all bones in each chain of a FabrikStructure3D object.
*
* If any chain in the structure does not contain any bones then an IllegalArgumentException is thrown.
* Line widths may commonly be between 1.0f and 32.0f, values outside of this range may result in unspecified behaviour.
*
* @param structure The structure to use.
* @param lineWidth The width of the lines to draw.
* @param mvpMatrix The ModelViewProjection matrix to use.
*/
public void draw(FabrikStructure3D structure, float lineWidth, Mat4f mvpMatrix)
{
int numChains = structure.getNumChains();
for (int loop = 0; loop < numChains; ++loop)
{
draw( structure.getChain(loop), lineWidth, mvpMatrix );
}
}
/**
* Draw the constraints on all chains and all bones in each chain of a FabrikStructure3D object using the default line width.
*
* If any chain in the structure does not contain any bones then an IllegalArgumentException is thrown.
*
* @param structure The structure to use.
* @param mvpMatrix The ModelViewProjection matrix to use.
*/
public void draw(FabrikStructure3D structure, Mat4f mvpMatrix) { draw(structure, 1.0f, mvpMatrix); }
} // End of FabrikConstraint3D class
|
FedUni/caliko
|
caliko-visualisation/src/main/java/au/edu/federation/caliko/visualisation/FabrikConstraint3D.java
|
Java
|
mit
| 12,411
|
//
// ElementView.h
// MobileFramework
//
// Created by Think on 14-5-27.
// Copyright (c) 2014年 wt. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "NodeVO.h"
@protocol elementDelegate <NSObject>
-(void)selectButton:(NodeVO *)vo;
@end
@interface ElementView : UIView<UIGestureRecognizerDelegate>
@property (nonatomic, strong) NodeVO *data;
@property (nonatomic, strong) UIView *mainView;
@property (nonatomic, strong) UIButton *image;
@property (nonatomic, strong) UILabel *label;
@property (nonatomic,retain)id<elementDelegate>delegate;
- (id)initWithFrame:(CGRect)frame name:(NodeVO *)gridData;
- (void)setupFrame;
@end
|
winture/wt-mobile-ios
|
MFCode/View/iphone/Two/ElementView.h
|
C
|
mit
| 642
|
## 认识bash
linux默认的shell是bash,有一下几个优点
- 命令记忆功能(history)
- 命令与文件补全功能([Tab]按键的好处):
[Tab]接在一串命令的第一字后面,则为命令补全
[Tab]接在一串命令法人第二个字以后,则为文件补全
- 命令别名设置功能(alias)
alias lm='ls -al'
- 作业控制,前台,后台控制
- 程序脚本(shell script)
### shell的变量功能
brew为命令行安装软件的工具
curl 命令行发起ajax请求
你能不能执行某个命令跟PATH这个变量有很大的关系,例如执行 ls 这个命令时,系统是通过PATH这个变量里面的内容所记录的路径顺序来找到命令;如果在找完PATH变量内的路径还找不到ls这个命令时。会显示‘commond not found’的错误信息
为了区分与自定义变量的不同,环境变量通常用大写字母表示
变量的显示与设置: echo unset
变量被显示时,前面必须加上“$”字符
echo $PATH
子进程
在目前这个shell的情况下,去打开另一个新的shell,新的shell就是子进程。在一般状态下,父进程的自定义变量是无法再子进程内使用的,但是通过export将变量变为环境变量后,就能够在子进程下面应用了
设置全局环境变量
echo $myname
myname=wang
unset myname
设置当前命令行的全局变量,默认为bash 配置文件为.bashrc, zsh为.zshrc
|
funnycoderstar/summary
|
docs/linux/bash.md
|
Markdown
|
mit
| 1,427
|
package wait
import (
"fmt"
"time"
)
// Predicate is a helper test function that will wait for a timeout period of
// time until the passed predicate returns true. This function is helpful as
// timing doesn't always line up well when running integration tests with
// several running lnd nodes. This function gives callers a way to assert that
// some property is upheld within a particular time frame.
func Predicate(pred func() bool, timeout time.Duration) error {
const pollInterval = 20 * time.Millisecond
exitTimer := time.After(timeout)
for {
<-time.After(pollInterval)
select {
case <-exitTimer:
return fmt.Errorf("predicate not satisfied after time out")
default:
}
if pred() {
return nil
}
}
}
// NoError is a wrapper around Predicate that waits for the passed method f to
// execute without error, and returns the last error encountered if this doesn't
// happen within the timeout.
func NoError(f func() error, timeout time.Duration) error {
var predErr error
pred := func() bool {
if err := f(); err != nil {
predErr = err
return false
}
return true
}
// If f() doesn't succeed within the timeout, return the last
// encountered error.
if err := Predicate(pred, timeout); err != nil {
return predErr
}
return nil
}
// Invariant is a helper test function that will wait for a timeout period of
// time, verifying that a statement remains true for the entire duration. This
// function is helpful as timing doesn't always line up well when running
// integration tests with several running lnd nodes. This function gives callers
// a way to assert that some property is maintained over a particular time
// frame.
func Invariant(statement func() bool, timeout time.Duration) error {
const pollInterval = 20 * time.Millisecond
exitTimer := time.After(timeout)
for {
<-time.After(pollInterval)
// Fail if the invariant is broken while polling.
if !statement() {
return fmt.Errorf("invariant broken before time out")
}
select {
case <-exitTimer:
return nil
default:
}
}
}
// InvariantNoError is a wrapper around Invariant that waits out the duration
// specified by timeout. It fails if the predicate ever returns an error during
// that time.
func InvariantNoError(f func() error, timeout time.Duration) error {
var predErr error
pred := func() bool {
if err := f(); err != nil {
predErr = err
return false
}
return true
}
if err := Invariant(pred, timeout); err != nil {
return predErr
}
return nil
}
|
LightningNetwork/lnd
|
lntest/wait/wait.go
|
GO
|
mit
| 2,521
|
//go:generate go-bindata -pkg realtime -o realtime_embed.go realtime.js
package realtime
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"reflect"
"strconv"
"sync"
"time"
"golang.org/x/net/websocket"
)
var proto = "v1"
type Config struct {
Throttle time.Duration
}
type Handler struct {
config Config
ws http.Handler
mut sync.Mutex //protects object and user maps
objs map[key]*Object
users map[string]*User
watchingUsers bool
userEvents chan *User
}
func NewHandler() *Handler {
return NewHandlerConfig(Config{})
}
func NewHandlerConfig(c Config) *Handler {
if c.Throttle < 15*time.Millisecond {
//15ms is approximately highest resolution on the JS eventloop
c.Throttle = 200 * time.Millisecond
}
r := &Handler{config: c}
r.ws = websocket.Handler(r.serveWS)
r.objs = map[key]*Object{}
r.users = map[string]*User{}
r.userEvents = make(chan *User)
//continually batches and sends updates
go r.flusher()
return r
}
func (r *Handler) UserEvents() <-chan *User {
if r.watchingUsers {
panic("Already watching user changes")
}
r.watchingUsers = true
return r.userEvents
}
func (r *Handler) flusher() {
//loops at Throttle speed
for {
//compute updates for each object for each subscriber
//and append each update to the users pending updates
for _, o := range r.objs {
o.computeUpdate()
}
//send all pending updates
r.mut.Lock()
for _, u := range r.users {
u.sendPending()
}
r.mut.Unlock()
time.Sleep(r.config.Throttle)
}
}
type addable interface {
add(key string, val interface{}) (*Object, error)
}
func (r *Handler) MustAdd(k string, v interface{}) {
if err := r.Add(k, v); err != nil {
panic(err)
}
}
func (r *Handler) Add(k string, v interface{}) error {
r.mut.Lock()
defer r.mut.Unlock()
t := reflect.TypeOf(v)
if t.Kind() != reflect.Ptr {
return fmt.Errorf("Cannot add '%s' - it is not a pointer type", k)
}
if _, ok := r.objs[key(k)]; ok {
return fmt.Errorf("Cannot add '%s' - already exists", k)
}
//access v.object via interfaces:
a, ok := v.(addable)
if !ok {
return fmt.Errorf("Cannot add '%s' - does not embed realtime.Object", k)
}
//pass v into v.object and get v.object back out
o, err := a.add(k, v)
if err != nil {
return fmt.Errorf("Cannot add '%s' %s", k, err)
}
r.objs[key(k)] = o
return nil
}
func (r *Handler) UpdateAll() {
r.mut.Lock()
for _, obj := range r.objs {
obj.checked = false
}
r.mut.Unlock()
}
func (r *Handler) Update(k string) {
r.mut.Lock()
if obj, ok := r.objs[key(k)]; ok {
obj.checked = false
}
r.mut.Unlock()
}
func (r *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if req.Header.Get("Connection") == "Upgrade" &&
req.Header.Get("Upgrade") == "websocket" {
r.ws.ServeHTTP(w, req)
} else {
JS.ServeHTTP(w, req)
}
}
func (r *Handler) serveWS(conn *websocket.Conn) {
handshake := struct {
Protocol string
ObjectVersions objectVersions
}{}
//first message is the rt handshake
if err := json.NewDecoder(conn).Decode(&handshake); err != nil {
conn.Write([]byte("Invalid rt handshake"))
return
}
if handshake.Protocol != proto {
conn.Write([]byte("Invalid rt protocol version"))
return
}
//ready
u := &User{
ID: conn.Request().RemoteAddr,
Connected: true,
uptime: time.Now(),
conn: conn,
versions: handshake.ObjectVersions,
pending: []*update{},
}
//add user and subscribe to each obj
r.mut.Lock()
for k := range u.versions {
if _, ok := r.objs[k]; !ok {
conn.Write([]byte("missing object: " + k))
r.mut.Unlock()
return
}
}
r.users[u.ID] = u
if r.watchingUsers {
r.userEvents <- u
}
for k := range u.versions {
obj := r.objs[k]
obj.subscribers[u.ID] = u
//create initial update
u.pending = append(u.pending, &update{
Key: k, Version: obj.version, Data: obj.bytes,
})
obj.Update()
}
r.mut.Unlock()
//block here during connection - pipe to null
io.Copy(ioutil.Discard, conn)
u.Connected = false
//remove user and unsubscribe to each obj
r.mut.Lock()
delete(r.users, u.ID)
if r.watchingUsers {
r.userEvents <- u
}
for k := range u.versions {
obj := r.objs[k]
delete(obj.subscribers, u.ID)
}
r.mut.Unlock()
//disconnected
}
//embedded JS file
var JSBytes = _realtimeJs
type jsServe []byte
var JS = jsServe(JSBytes)
func (j jsServe) ServeHTTP(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Encoding", "gzip")
w.Header().Set("Content-Type", "text/javascript")
w.Header().Set("Content-Length", strconv.Itoa(len(JSBytes)))
w.Write(JSBytes)
}
|
cornerot/cloud-torrent
|
Godeps/_workspace/src/github.com/jpillora/go-realtime/realtime_handler.go
|
GO
|
mit
| 4,590
|
const SHADERS = require('../chunks/index.js')
module.exports = /* glsl */ `
precision highp float;
${SHADERS.math.PI}
${SHADERS.sky}
${SHADERS.rgbm}
${SHADERS.gamma}
${SHADERS.encodeDecode}
uniform vec3 uSunPosition;
varying vec2 vTexCoord0;
uniform bool uRGBM;
void main() {
//Texture coordinates to Normal is Based on
//http://gl.ict.usc.edu/Data/HighResProbes/
// u=[0,2], v=[0,1],
// theta=pi*(u-1), phi=pi*v
// (Dx,Dy,Dz) = (sin(phi)*sin(theta), cos(phi), -sin(phi)*cos(theta)).
float u = vTexCoord0.x;
float v = 1.0 - vTexCoord0.y; // uv's a Y flipped in WebGL
float theta = PI * (u * 2.0 - 1.0);
float phi = PI * v;
float x = sin(phi) * sin(theta);
float y = cos(phi);
float z = -sin(phi) * cos(theta);
vec3 N = vec3(x, y, z);
vec3 color = sky(uSunPosition, N);
if (uRGBM) {
gl_FragColor = encodeRGBM(color);
} else {
gl_FragColor.rgb = color;
gl_FragColor.a = 1.0;
}
}
`
|
pex-gl/pex-renderer
|
shaders/skybox/sky-env-map.frag.js
|
JavaScript
|
mit
| 938
|
var Q = require("q");
var quin = require("../quin");
var testGroup = {
setUp: function (callback) {
callback();
},
tearDown: function (callback) {
callback();
},
"wrap() returns a wrapper function when supplied a promise": function (test) {
var one = Q.denodeify(oneInput);
//quin promise wrappers
var validateMessage = quin.wrap(one);
test.equal(typeof validateMessage, "function");
test.done();
},
"inject() returns a wrapper function when supplied a promise": function (test) {
var one = Q.denodeify(oneInput);
//quin promise wrappers
var validateMessage = quin.inject(one);
test.equal(typeof validateMessage, "function");
test.done();
},
"inject() can deal with no injected values": function (test) {
var one = Q.denodeify(oneInput);
var hasOne = quin.inject(one);
one("in").then(hasOne).done(function () {
test.done();
});
},
"inject() can deal with one injected value": function (test) {
var one = Q.denodeify(oneInput);
var expected = "value";
var hasTwo = quin.inject(Q.denodeify(verifyExtra), expected);
one("in").then(hasTwo).done(function (injected) {
test.equal(expected, injected);
test.done();
});
},
"inject() can deal with more than one injected value": function (test) {
var one = Q.denodeify(oneInput);
var hasThree = quin.inject(Q.denodeify(returnsExtraAndMore), "extra", "more");
one("in").then(hasThree).done(function (obj) {
test.equal(obj.more, "more");
test.equal(obj.extra, "extra");
test.done();
});
},
"inject() can deal with a null injected value": function (test) {
var one = Q.denodeify(oneInput);
var expected = null;
var hasTwo = quin.inject(Q.denodeify(verifyExtra), expected);
one("in").then(hasTwo).done(function (injected) {
test.equal(expected, injected);
test.done();
});
},
"inject() returns a null if a null promise was provided": function (test) {
var one = Q.denodeify(oneInput);
var expected = null;
var hasTwo = quin.inject(null, expected);
one("in").then(hasTwo).done(function () {
test.done();
});
},
"inject() returns a function that can be called at the base of a promise chain": function (test) {
var expected = "value";
var one = Q.denodeify(oneInput);
var two = quin.denodeify(verifyExtra, expected);
var newBase = quin.inject(one, "in");
newBase().then(two).done(function () {
test.done();
});
},
"inject() returns a function that can be called at the base of a promise chain with a parameter": function (test) {
var expected = "value";
var one = Q.denodeify(oneInput);
var verify = quin.denodeify(verifyExtra, expected);
var newBase = quin.inject(one);
newBase("in").then(verify).done(function () {
test.done();
});
},
"denodify() returns a promise if a standard callback is provided": function (test) {
var expected = "validated";
var one = quin.denodeify(oneInput);
var two = quin.denodeify(oneInput);
var verify = quin.denodeify(verifyChain, test, expected);
one(expected).then(two).then(verify).done();
},
//"all() injects dependency into all items in array": function (test: nodeunit.Test): void {
// var expected = "validated";
// var one = quin.denodeify(oneInput);
// var promise = Q.denodeify(twoInputs);
// var two = quin.all([promise, promise], "injected");
// var verify = quin.denodeify(verifyChain, test, expected);
// one(expected)
// .then(two)
// .then(verify)
// .done();
//},
"Input from the top of the chain gets to the bottom with wrap": function (test) {
//plain promises
var getMessage = Q.denodeify(oneInput);
var validate = Q.denodeify(twoInputs);
//quin promise wrappers
var validateMessage = quin.wrap(validate);
var deleteMessage = quin.wrap(Q.denodeify(threeInputs));
var complete = quin.wrap(Q.denodeify(verifyChain));
getMessage("finished").then(validateMessage("a")).then(deleteMessage("a", "b")).then(complete(test, "finished")).done();
},
"Input from the top of the chain gets to the bottom with inject": function (test) {
var context = console;
//plain promises
var getMessage = Q.denodeify(oneInput);
var validate = Q.denodeify(twoInputs);
var del = Q.denodeify(threeInputs);
var final = Q.denodeify(verifyChain);
//quin promises
var validateMessage = quin.inject(validate, "a");
var deleteMessage = quin.inject(del, "a", "b");
var complete = quin.inject(final, test, "finished");
getMessage("finished").then(validateMessage).then(deleteMessage).then(complete).done();
},
"README example works": function (test) {
var messageService = new MockService();
//plain old promises
var getMessage = Q.denodeify(getIt);
var validateMessage = Q.denodeify(validateIt);
var del = Q.denodeify(deleteIt);
//quin returns a promise proxy injecting the extra dependency
var deleteMessage = quin.inject(del, messageService);
//The purpose and the flow of the chain is easier to read now.
getMessage(messageService).then(validateMessage).then(deleteMessage).done(function () {
test.done();
});
}
};
exports.activityTests = testGroup;
//Test Functions
function showResults(writer, result, cb) {
cb(null);
}
function oneInput(input, cb) {
cb(null, input);
}
function twoInputs(extra, input, cb) {
cb(null, input);
}
function threeInputs(extra, more, input, cb) {
cb(null, input);
}
function verifyChain(test, expected, actual, cb) {
test.equal(expected, actual);
test.done();
cb(null, "");
}
function verifyExtra(extra, input, cb) {
cb(null, extra);
}
function returnsExtraAndMore(extra, more, input, cb) {
cb(null, { extra: extra, more: more });
}
//README functions
//needs the messageService so we pass it in at the start of the chain
function getIt(messageService, cb) {
messageService.getMsg(function (err, msg) {
cb(null, msg);
});
}
//this function does not know or care about the messageService
function validateIt(msg, cb) {
if (msg.isGood == false) {
cb(new Error("INVALID"), null);
}
cb(null, msg);
}
//this function needs the messageService to do it's work
function deleteIt(messageService, msg, cb) {
messageService.deleteMsg(msg, function () {
cb(null, msg);
});
}
var MockService = (function () {
function MockService() {
}
MockService.prototype.getMsg = function (cb) {
cb(null, { id: "abc", isGood: true });
};
MockService.prototype.deleteMsg = function (msg, cb) {
cb(null);
};
return MockService;
})();
//# sourceMappingURL=quin-test.js.map
|
midknight41/quin
|
lib/tests/quin-test.js
|
JavaScript
|
mit
| 7,232
|
---
layout: post
title: 理解 vertical-align
description: '掌握 vertical-align 的原理'
share: false
tags: [CSS]
image:
feature: abstract-8.jpg
---
vertical-align 用于行内元素和表格单元的垂直对齐,开发中经常会遇到,有必要了解其背后的原理。
## 一、应用范围
对于 `vertical-align`,新手通常的困惑是对块元素进行设置,想垂直居中其子元素,然而并不会起作用(关于居中的方法可查看[CSS 居中](https://huxinsen.github.io/centering-in-css/))。因为,`vertical-align` 只对以下元素有效:
- `inline-level` 元素,包括 `inline`、`inline-table` 和 `inline-block`
- `table-cell` 元素
## 二、IFC
想了解 `vertical-align` 如何起作用,需要结合行内格式化上下文(Inline formatting context,`IFC`)理解。
`IFC` 如同 `BFC`,也是一种布局规则。其中的 `box` 水平放置。这些 `box` 水平方向的 `margin`,`border`,`padding` 有效。垂直方向有不同对齐方式,例如顶部、底部和基线对齐。容纳一行 `box` 的容器叫 `line box`。
- `line box` 的宽度由包含它的块(`containing box`)和块中是否有浮动来决定。一般 `line box` 的左右边界分别紧挨包含块的左右边界,宽度与包含块的一样。有浮动时,浮动的 `box` 会介于 `line box` 和包含块的边界之间,`line box` 的宽度因此会减小。
- `line box` 的高度由以下计算规则决定:
1. 计算 `inline-level box` 的高度。
对于 `inline box`,为其 `line-height`;对于替换元素, `inline-block` 和 `inline-table`,为 `margin box` 的高度。空行内元素的 `margin`、`border`、`padding` 和 `line-height` 也会影响 `line box` 高度的计算。
2. `inline-level box` 依据 `vertical-align` 对齐。
CSS 2 未定义 `line box` 的 `baseline`(基线)。每个 `line box` 以一个想象的零宽度的 `inline box` (W3C 称 `strut`)开始,`strut` 拥有包含块的 `font` 和 `line-height` 属性。`baseline` 在 `line box` 的位置由行内所有的 `inline-level box` 共同决定。
3. `line box` 的高度为行内最高 `box` 的顶部和最低 `box` 的底部之间的距离。
- 当多个 `inline-level box` 一行容不下时,会被分成两个或多个 `line box`。同一个 `IFC` 下,不同 `line box` 的高度可能不一样,例如:某一行包含一个大图片,另一行只有文字。
- 如果一行所有 `inline-level box` 的宽度之和小于 `line box` 的宽度时,`line box` 内的水平布局由 `text-align` 属性决定。
- 当一个 `inline box` 的宽度超过 `line box` 时,会被分割成多个 `box` 分布于两个或多个 `line box`内。如果不能分割,则溢出 `line box`,例如只有一个字、`word-break` 不允许换行或 `white-space` 不允许换行。另外,分割处 `margin`、`border` 和 `padding` 无视觉效果。
还有一点要补充,当 `IFC` 中有块级元素插入时,会产生两个 `IFC`。
## 三、vertical-align 的取值
可以分成三类:
### 1. 相对于 line box 的 baseline

- baseline
初始值,元素的基线与 `line box` 的基线对齐。
- sub
元素的基线与 `line box` 的下标基线对齐。
- super
元素的基线与 `line box` 的上标基线对齐。
- percentage
元素的基线由 `line box` 的基线移动相对 `line-height` 给定百分比的距离。
- length
元素的基线由 `line box` 的基线移动给定的距离。
- middle

元素的中线与 `line box` 的基线加上小写字母 x 高度(x-height)的一半的位置对齐。
### 2. 相对于 line box 的 strut box

- text-top
元素的顶部与 `strut box` 的顶部对齐。
- text-bottom
元素的底部与 `strut box` 的底部对齐。
### 3. 相对于 line box 的边界

- top
元素的顶部与 `line box` 的顶部对齐。
- bottom
元素的底部与 `line box` 的底部对齐。
## 四、表格单元
对于表格单元(`table-cell`)对来说,`vertical-align` 的默认值为 `middle`。
使用时,建议取值:`top`、`middle` 和 `bottom`,其他取值跨浏览器可能有不一致表现。
## 参考链接
> - [Inline formatting context](https://drafts.csswg.org/css2/visuren.html#inline-formatting)
> - [Vertical-Align: All You Need To Know](https://christopheraue.net/design/vertical-align)
> - [Deep dive CSS: font metrics, line-height and vertical-align](https://iamvdo.me/en/blog/css-font-metrics-line-height-and-vertical-align)
> - [What is Vertical Align? - CSS-Tricks](https://css-tricks.com/what-is-vertical-align/)
|
daniel-hoo/daniel-hoo.github.io
|
_posts/2020-05-08-vertical-align.markdown
|
Markdown
|
mit
| 4,935
|
<?php
ini_set('display_errors',1);
ini_set('display_startup_erros',1);
error_reporting(E_ALL);
require_once("libs/conta.php");
|
SharingDreams/sharingdreams
|
conta.php
|
PHP
|
mit
| 128
|
import estap from '../../lib';
const test = estap();
estap.disableAutorun();
test('should pass', t => {
t.pass();
});
|
iefserge/estap
|
test/integration/no-autorun.js
|
JavaScript
|
mit
| 122
|
#! /usr/bin/env python3
import vk
import sys
import json
# get access token
#app_id = 4360605
#url = "http://api.vkontakte.ru/oauth/authorize?client_id=" + str(app_id) + "&scope=4&redirect_uri=http://api.vk.com/blank.html&display=page&response_type=token"
#webbrowser.open_new_tab(url)
#exit()
word = sys.argv[1]
txt_file = open(word + '.txt', "w")
html_file = open(word + '.html', "w")
vkapi = vk.API(access_token='copy_token_here')
result = vkapi.groups.search(q = word, offset = 0, count = 100)
#print(result['count'])
#exit()
json_tree = result['items']
for item in json_tree:
link = 'http://vk.com/club' + str(item['id'])
name = item['name']
tag_link = '<a href="' + link + '">' + link + '</a>' + '\t' + name + '<br>'
txt_file.write(link + '\n')
html_file.write(tag_link + '\n')
txt_file.close()
html_file.close()
|
dm-urievich/learn_vk_api
|
test_api.py
|
Python
|
mit
| 849
|
GovukAdminTemplate.configure do |c|
c.app_title = "GOV.UK Policy Publisher"
c.show_flash = true
c.show_signout = true
end
|
alphagov/policy-publisher
|
config/initializers/govuk_admin_template.rb
|
Ruby
|
mit
| 128
|
package net.coding.program.network.model.file;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class Share implements Serializable {
private static final long serialVersionUID = 1350215870059841873L;
@SerializedName("resource_type")
@Expose
public int resourceType;
@SerializedName("resource_id")
@Expose
public int resourceId;
@SerializedName("user_id")
@Expose
public int userId;
@SerializedName("access_type")
@Expose
public int accessType;
@SerializedName("project_id")
@Expose
public int projectId;
@SerializedName("overdue")
@Expose
public long overdue;
@SerializedName("created_at")
@Expose
public long createdAt;
@SerializedName("hash")
@Expose
public String hash = "";
@SerializedName("url")
@Expose
public String url = "";
}
|
Coding/Coding-Android
|
common-coding/src/main/java/net/coding/program/network/model/file/Share.java
|
Java
|
mit
| 935
|
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using PetsWonderland.Business.Common.Constants;
using PetsWonderland.Business.Models.Animals.Contracts;
namespace PetsWonderland.Business.Models.Animals
{
public class AnimalType : IAnimalType
{
[Key]
public int Id { get; set; }
[Required]
[Index(IsUnique = true)]
[MinLength(ValidationConstants.MinTypeLength)]
[MaxLength(ValidationConstants.MaxTypeLength)]
public string Name { get; set; }
public bool IsDeleted { get; set; }
}
}
|
TeamHappyFace/Pets-Wonderland
|
PetsWonderland/Business/PetsWonderland.Business.Models/Animals/AnimalType.cs
|
C#
|
mit
| 611
|
import { connect } from 'react-redux'
import SignUpForm from '../components/SignUpForm'
import { signUpUser } from '../actions/SignUpFormActions'
const mapStateToProps = (state, ownProps) => {
return {}
}
const mapDispatchToProps = (dispatch) => {
return {
onSignUpFormSubmit: (name) => {
event.preventDefault();
dispatch(signUpUser(name))
}
}
}
const SignUpFormContainer = connect(
mapStateToProps,
mapDispatchToProps
)(SignUpForm)
export default SignUpFormContainer
|
ranneyd/eth-faucet
|
src/containers/SignUpFormContainer.js
|
JavaScript
|
mit
| 503
|
/**
* @author xialeistudio<home.xialei@gmail.com>
*/
window.onload = function() {
cc.game.onStart = function() {
cc.view.adjustViewPort(true);
cc.view.setDesignResolutionSize(320, 504, cc.ResolutionPolicy.SHOW_ALL);
cc.view.resizeWithBrowserSize(true);
//load resources
cc.LoaderScene.preload(
[
'res/background.png',
'res/hero1.png',
'res/bullet1.png',
'res/enemy1.png',
'res/bullet2.png',
'res/game_music.mp3',
'res/bullet.mp3',
'res/enemy1_down.mp3'
]
, function() {
/**
* 游戏场景
* @type {void|*}
*/
var GameScene = cc.Scene.extend({
_enemies: [],//敌机列表
_enemyBullets: [],//敌机子弹
_plane: null,//我方飞机
_planeBullets: [],//我房子弹
_gameLayer: null,
_hitCount: 0,
life: 10,
updateGame: function() {
//我方子弹打中敌方飞机,敌方飞机和子弹消失
var planeRect = this._plane.getBoundingBox();
var _this = this;
this._planeBullets.forEach(function(bullect) {
var bulletRect = bullect.getBoundingBox();
_this._enemies.forEach(function(enemy) {
var enemyRect = enemy.getBoundingBox();
if (cc.rectIntersectsRect(bulletRect, enemyRect)) {
//移除敌方飞机和子弹
_this._hitCount++;
cc.audioEngine.playEffect('res/enemy1_down.mp3');
var enemyName = enemy.getTag();
_this._enemies.splice(_this._enemies.indexOf(enemy), 1);
_this._gameLayer.removeChild(enemy);
//_this._enemyBullets.forEach(function(enemyBullet) {
// if (enemyBullet.getTag().indexOf(enemyName) !== -1) {
// _this._enemyBullets.splice(_this._enemyBullets.indexOf(enemyBullet), 1);
// _this._gameLayer.removeChild(enemyBullet);
// }
//});
}
});
});
//敌方子弹打中我方飞机,10次
this._enemyBullets.forEach(function(enemyBullet, enemyBulletIndex) {
var bulletRect = enemyBullet.getBoundingBox();
if (cc.rectIntersectsRect(bulletRect, planeRect)) {
_this.life--;
if (_this.life <= 0) {
cc.log('game over');
}
// 移除子弹
_this._enemyBullets.splice(enemyBulletIndex, 1);
_this._gameLayer.removeChild(enemyBullet);
}
});
//敌方飞机撞上我方飞机,游戏结束
this._enemies.forEach(function(enemy, enemyIndex) {
var enemyRect = enemy.getBoundingBox();
if (cc.rectIntersectsRect(planeRect, enemyRect)) {
_this.lift = 0;
cc.log('game over');
// 移除飞机
_this._enemyBullets.splice(enemyIndex, 1);
_this._gameLayer.removeChild(enemy);
}
});
_this._gameLayer.setHit(_this._hitCount);
_this._gameLayer.setLife(_this.life);
},
onEnter: function() {
this._super();
var gameOver = false;
var _this = this;
//游戏层
_this._gameLayer = new GameLayer();
_this._gameLayer.init();
this.addChild(_this._gameLayer);
// 音乐
cc.audioEngine.playMusic('res/game_music.mp3');
//添加飞机
this._plane = new PlaneSprite();
_this._gameLayer.addChild(this._plane);
//子弹
var fireBullet = function() {
//cc.log('fireBullet');
if (gameOver) {
return;
}
var bullet = new PlaneBulletSprite();
var planeBulletSpeed = 2;
bullet.setPosition(_this._plane.getPosition().x, 126 + 15);
bullet.schedule(function() {
this.setPosition(this.getPosition().x, this.getPosition().y + planeBulletSpeed);
if (this.getPosition().x < 0 || this.getPosition().x > 320 - 5 / 2 || this.getPosition().y > 504) {
_this._planeBullets.splice(_this._planeBullets.indexOf(this), 1);
_this._gameLayer.removeChild(this);
}
}, 0, null, 0);
_this._gameLayer.addChild(bullet);
_this._planeBullets.push(bullet);
cc.audioEngine.playEffect('res/bullet.mp3');
};
this.schedule(fireBullet, 0.3, null, 0);
//敌机
var enemyPlaneAction = function() {
//cc.log('enemyPlane');
if (gameOver) {
return;
}
var enemyPlane = new EnemyPlaneSprite();
var enemyPlaneSpeed = 1;
var originX = Math.random();
enemyPlane.setTag('enemy-' + Math.random());
enemyPlane.setPosition(originX * 320, 480);
enemyPlane.schedule(function() {
this.setPosition(this.getPosition().x, this.getPosition().y - enemyPlaneSpeed);
if (this.getPosition().x < 0 || this.getPosition().x > 320 - 5 / 2 || this.getPosition().y < 0) {
_this._enemies.splice(_this._enemies.indexOf(this), 1);
_this._gameLayer.removeChild(this);
}
}, 0, null, 0);
//敌机生成子弹
enemyPlane.schedule(function() {
var bullet = new EnemyPlaneBulletSprite();
var bulletSpeed = 2;
bullet.setPosition(this.getPosition().x + 57 / 2, this.getPosition().y);
//敌机子弹动作
bullet.schedule(function() {
bullet.setPosition(bullet.getPosition().x, bullet.getPosition().y - bulletSpeed);
if (bullet.getPosition().x < 0 || bullet.getPosition().x > 320 - 5 / 2 || bullet.getPosition().y > 504 || bullet.getPosition().y < 0) {
_this._enemyBullets.splice(_this._enemyBullets.indexOf(bullet), 1);
_this._gameLayer.removeChild(bullet);
}
}, 0, null, 0);
_this._gameLayer.addChild(bullet);
bullet.setTag('enemybullet-' + enemyPlane.getTag());
_this._enemyBullets.push(bullet);
}, 1, null, 0);
_this._gameLayer.addChild(enemyPlane);
_this._enemies.push(enemyPlane);
};
this.schedule(enemyPlaneAction, 2, null, 0);
// 更新游戏
this.schedule(this.updateGame);
}
});
/**
* 游戏层
* @type {void|*}
*/
var GameLayer = cc.Layer.extend({
_lifeLabel: null,
_hitLabel: null,
init: function() {
this._super();
var size = cc.director.getWinSize();
var layer = cc.Layer.create();
//添加背景
var bg = cc.Sprite.create('res/background.png');
bg.setAnchorPoint(0, 0);
bg.setPosition(0, 0);
layer.addChild(bg);
//敌机浮层
this._lifeLabel = cc.LabelTTF.create('life: 10', 'Arial', 16, null, cc.TEXT_ALIGNMENT_RIGHT, cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM);
this._lifeLabel.setPosition(size.width - 10, size.height - 30);
this._lifeLabel.setAnchorPoint(1, 0);
layer.addChild(this._lifeLabel);
//生命浮层
this._hitLabel = cc.LabelTTF.create('hit: 0', 'Arial', 16, null, cc.TEXT_ALIGNMENT_RIGHT, cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM);
this._hitLabel.setPosition(size.width - 10, size.height - 50);
this._hitLabel.setAnchorPoint(1, 0);
layer.addChild(this._hitLabel);
this.addChild(layer);
return true;
},
setHit: function(number) {
this._hitLabel.setString('hit: ' + number);
},
setLife: function(number) {
this._lifeLabel.setString('life: ' + number);
}
});
/**
* 飞机
* @type {void|*}
*/
var PlaneSprite = cc.Sprite.extend({
ctor: function() {
this._super();
var size = cc.director.getWinSize();
this.initWithFile('res/hero1.png');
//this.setAnchorPoint(0, 0);
this.setPosition(size.width / 2, 63);
var _this = this;
//注册事件
var listener = cc.EventListener.create({
event: cc.EventListener.TOUCH_ONE_BY_ONE,
swallowTouches: true,
onTouchBegan: function(touch, event) {
//cc.log('on touch began');
return true;
},
onTouchMoved: function(touch, event) {
//cc.log('on touch move');
var point = touch.getLocation();
//边界监测
if (point.x > size.width - 102 / 2) {
point.x = size.width - 102 / 2;
}
if (point.x <= 61) {
point.x = 61;
}
_this.setPositionX(point.x);
},
onTouchEnded: function(touch, event) {
}
});
cc.eventManager.addListener(listener, this);
}
});
/**
* 飞机子弹
* @type {void|*}
*/
var PlaneBulletSprite = cc.Sprite.extend({
ctor: function() {
this._super();
//var size = cc.director.getWinSize();
this.initWithFile('res/bullet1.png');
}
});
/**
* 敌机
* @type {void|*}
*/
var EnemyPlaneSprite = cc.Sprite.extend({
ctor: function() {
this._super();
this.initWithFile('res/enemy1.png');
this.setAnchorPoint(0, 0);
}
});
/**
* 敌机子弹
* @type {void|*}
*/
var EnemyPlaneBulletSprite = cc.Sprite.extend({
ctor: function() {
this._super();
this.initWithFile('res/bullet2.png');
}
});
cc.director.runScene(new GameScene);
}, this);
};
cc.game.run("gameCanvas");
};
|
xialeistudio/cocos2d-hitplane
|
main.js
|
JavaScript
|
mit
| 9,061
|
---
layout: docs
title: Image replacement
description: Swap text for background images with the image replacement class.
group: utilities
toc: true
---
Utilize the `.text-hide` class or mixin to help replace an element's text content with a background image.
{% highlight html %}
<h1 class="text-hide">Custom heading</h1>
{% endhighlight %}
{% highlight scss %}
// Usage as a mixin
.heading {
@include text-hide;
}
{% endhighlight %}
Use the `.text-hide` class to maintain the accessibility and SEO benefits of heading tags, but want to utilize a `background-image` instead of text.
{% capture example %}
<h1 class="text-hide" style="background-image: url('/assets/brand/bootstrap-solid.svg'); width: 50px; height: 50px;">Bootstrap</h1>
{% endcapture %}
{% include example.html content=example %}
|
creativewebjp/bootstrap
|
docs/4.0/utilities/image-replacement.md
|
Markdown
|
mit
| 804
|
/*
* Copyright (c) HakoComposer & Mehrez Kristou (kristou.com), distributed
* as-is and without warranty under the MIT License. See
* [root]/license.txt for more. This information must remain intact.
*/
#ifndef WORKSPACEVIEW_H
#define WORKSPACEVIEW_H
#include <QGraphicsView>
#include <QWheelEvent>
class WorkspaceView : public QGraphicsView
{
Q_OBJECT
public:
explicit WorkspaceView(QWidget *parent = 0);
protected:
virtual void wheelEvent(QWheelEvent* event);
signals:
public slots:
};
#endif // WORKSPACEVIEW_H
|
HakoComposer/HakoComposer
|
include/WorkspaceView.hpp
|
C++
|
mit
| 549
|
# Generate PDF
## A PDF generation plugin for Ruby on Rails
Generate PDF uses the shell utility [wkhtmltopdf](http://code.google.com/p/wkhtmltopdf/) to serve a PDF file to a user from HTML. In other words, rather than dealing with a PDF generation DSL of some sort, you simply write an HTML view as you would normally, and let GeneratePdf take care of the hard stuff.
_Generate PDF has been verified to work on Ruby 1.8.7 and 1.9.2; Rails 2 and Rails 3_
### Installation
First, be sure to install [wkhtmltopdf](http://code.google.com/p/wkhtmltopdf/).
Note that versions before 0.9.0 [have problems](http://code.google.com/p/wkhtmltopdf/issues/detail?id=82&q=vodnik) on some machines with reading/writing to streams.
This plugin relies on streams to communicate with wkhtmltopdf.
More information about [wkhtmltopdf](http://code.google.com/p/wkhtmltopdf/) could be found [here](http://madalgo.au.dk/~jakobt/wkhtmltopdf-0.9.0_beta2-doc.html).
win32-opne3 gem [http://rubygems.org/gems/win32-open3]
Next:
Download plugin and paste it in vendor/plugins folder.
script/generate generate_pdf
### Basic Usage - 1
class ThingsController < ApplicationController
def show
respond_to do |format|
format.html
format.pdf
end
end
end
### Basic Usage - 2
In Url just specify in the end .pdf example http://www.example.com/show/2 in pdf http://www.example.com/show/2.pdf
class ThingsController < ApplicationController
def show
end
end
### Advanced Usage with all available options
class ThingsController < ApplicationController
def show
respond_to do |format|
format.html
format.pdf do
render :pdf => 'file_name',
:template => 'things/show.pdf.erb',
:layout => 'pdf.html', # use 'pdf.html' for a pfd.html.erb file
:wkhtmltopdf => '/usr/local/bin/wkhtmltopdf', # path to binary
:show_as_html => params[:debug].present?, # allow debuging based on url param
:orientation => 'Landscape', # default Portrait
:page_size => 'A4, Letter, ...', # default A4
:save_to_file => Rails.root.join('pdfs', "#{filename}.pdf"),
:save_only => false, # depends on :save_to_file being set first
:proxy => 'TEXT',
:username => 'TEXT',
:password => 'TEXT',
:cover => 'URL',
:dpi => 'dpi',
:encoding => 'TEXT',
:user_style_sheet => 'URL',
:redirect_delay => NUMBER,
:zoom => FLOAT,
:page_offset => NUMBER,
:book => true,
:default_header => true,
:disable_javascript => false,
:greyscale => true,
:lowquality => true,
:enable_plugins => true,
:disable_internal_links => true,
:disable_external_links => true,
:print_media_type => true,
:disable_smart_shrinking => true,
:use_xserver => true,
:no_background => true,
:margin => {:top => SIZE, # default 10 (mm)
:bottom => SIZE,
:left => SIZE,
:right => SIZE},
:header => {:html => { :template => 'users/header.pdf.erb', # use :template OR :url
:url => 'www.example.com',
:locals => { :foo => @bar }},
:center => 'TEXT',
:font_name => 'NAME',
:font_size => SIZE,
:left => 'TEXT',
:right => 'TEXT',
:spacing => REAL,
:line => true},
:footer => {:html => { :template => 'shared/footer.pdf.erb', # use :template OR :url
:url => 'www.example.com',
:locals => { :foo => @bar }},
:center => 'TEXT',
:font_name => 'NAME',
:font_size => SIZE,
:left => 'TEXT',
:right => 'TEXT',
:spacing => REAL,
:line => true},
:toc => {:font_name => "NAME",
:depth => LEVEL,
:header_text => "TEXT",
:header_fs => SIZE,
:l1_font_size => SIZE,
:l2_font_size => SIZE,
:l3_font_size => SIZE,
:l4_font_size => SIZE,
:l5_font_size => SIZE,
:l6_font_size => SIZE,
:l7_font_size => SIZE,
:l1_indentation => NUM,
:l2_indentation => NUM,
:l3_indentation => NUM,
:l4_indentation => NUM,
:l5_indentation => NUM,
:l6_indentation => NUM,
:l7_indentation => NUM,
:no_dots => true,
:disable_links => true,
:disable_back_links => true},
:outline => {:outline => true,
:outline_depth => LEVEL}
end
end
end
end
By default, it will render without a layout (:layout => false) and the template for the current controller and action.
### Super Advanced Usage ###
If you need to just create a pdf and not display it:
# create a pdf from a string
pdf = GeneratePdf.new.pdf_from_string('<h1>Hello There!</h1>')
# or from your controller, using views & templates and all Generate_pdf options as normal
pdf = render_to_string :pdf => "some_file_name"
# then save to a file
save_path = Rails.root.join('pdfs','filename.pdf')
File.open(save_path, 'wb') do |file|
file << pdf
end
### Styles
You must define *:media => :all* to CSS files.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<%= stylesheet_link_tag "pdf",:media => "all" -%>
<%= javascript_include_tag "number_pages" %>
</head>
<body onload='number_pages'>
<div id="header">
<%= image_tag 'mysite.jpg' %>
</div>
<div id="content">
<%= yield %>
</div>
</body>
</html>
### Page Numbering
A bit of javascript can help you number your pages, create a template or header/footer file with this:
<html>
<head>
<script>
function number_pages() {
var vars={};
var x=document.location.search.substring(1).split('&');
for(var i in x) {var z=x[i].split('=',2);vars[z[0]] = unescape(z[1]);}
var x=['frompage','topage','page','webpage','section','subsection','subsubsection'];
for(var i in x) {
var y = document.getElementsByClassName(x[i]);
for(var j=0; j<y.length; ++j) y[j].textContent = vars[x[i]];
}
}
</script>
</head>
<body onload="number_pages()">
Page <span class="page"></span> of <span class="topage"></span>
</body>
</html>
Anything with a class listed in "var x" above will be auto-filled at render time.
### Configuration
You can put your default configuration, applied to all pdf's at "generate_pdf.rb" initializer.
### Further Reading
Andreas Happe's post [Generating PDFs from Ruby on Rails](http://snikt.net/index.php/2010/03/03/generating-pdfs-from-ruby-on-rails)
|
shreyas123/generate_pdf
|
README.md
|
Markdown
|
mit
| 9,512
|
{% extends "LanguageStatistic/main.html" %}
{% load staticfiles %}
{% block body %}
<h1>Status for Khan Academy's I18N Initiatives </h1>
<div id="tabs"><ul>
<li><a href="#Test">Test</a></li>
<li><a href="#Live">Live</a></li>
<li><a href="#Rockstar">Rockstar</a>
</li></ul>
{% if targets %}
{% for t in targets %}
<div id="{{t}}">
<table id="keywords" class="sort" cellspacing="0" cellpadding="0"><thead><th class="lalign"></th><th></th><th>Dub</th><th>Amara</th><th colspan="3" class="center">Crowdin</th></thead>
<thead><th class="lalign">Language</th><th></th><th>Hours</th><th>Subtitles</th><th>Left*</th><th>Speed*</th><th>ETA*</th></thead>
{% if languageList %}
{% for lang in languageList %}
{% if lang.target == t %}
<tr><td><a href="{{ base }}{{ lang.code }}/{{ lang.target }}SiteStatistic.html">{{ lang.name }}</a></td><td>{{ lang.data.progress | safe }}</td>
<td>{{ lang.data.D.left }}</td><td>{{ lang.data.S.left }}</td><td>{{ lang.data.C.left }}</td><td>{{ lang.data.C.speed }}</td><td>{{ lang.data.C.eta }}</td></tr>
{% endif %}
{% endfor %}
{% endif %}
</table><center>*Speed and ETA calculated for Crowdin Words only (if your language has less than 30 days data or recently changed Target Speed and ETA might be wrong)</center>
</div>
{% endfor %}
{% endif %}
{% endblock %}
|
alani1/KALanguageReport
|
LanguageStatistic/templates/LanguageStatistic/index.html
|
HTML
|
mit
| 1,395
|
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="generator" content="Hugo 0.54.0 with theme Tranquilpeak 0.4.3-BETA">
<title>Hidden social section showcase</title>
<meta name="author" content="Sanghun Kang">
<meta name="keywords" content="">
<link rel="icon" href="https://sanghunka.github.io/favicon-btc.png">
<meta name="description" content="This post is used to show how a site looks if the social section is hidden.">
<meta property="og:description" content="This post is used to show how a site looks if the social section is hidden.">
<meta property="og:type" content="blog">
<meta property="og:title" content="Hidden social section showcase">
<meta property="og:url" content="/2014/08/hidden-social-section-showcase/">
<meta property="og:site_name" content="Keep Moving">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Keep Moving">
<meta name="twitter:description" content="This post is used to show how a site looks if the social section is hidden.">
<meta property="og:image" content="//www.gravatar.com/avatar/286acbc504a86d12987dfa5cd3782a41?s=640">
<meta property="og:image" content="//d1u9biwaxjngwg.cloudfront.net/cover-image-showcase/city-750.jpg">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha256-eZrrJcwDc/3uDhsdt61sL2oOBY362qM3lon1gyExkL0=" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.4/jquery.fancybox.min.css" integrity="sha256-vuXZ9LGmmwtjqFX1F+EKin1ThZMub58gKULUyf0qECk=" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.4/helpers/jquery.fancybox-thumbs.min.css" integrity="sha256-SEa4XYAHihTcEP1f5gARTB2K26Uk8PsndQYHQC1f4jU=" crossorigin="anonymous" />
<link rel="stylesheet" href="https://sanghunka.github.io/css/style-jsjn0006wyhpyzivf6yceb31gvpjatbcs3qzjvlumobfnugccvobqwxnnaj8.min.css" />
</head>
<body>
<div id="blog">
<header id="header" data-behavior="4">
<i id="btn-open-sidebar" class="fa fa-lg fa-bars"></i>
<div class="header-title">
<a class="header-title-link" href="https://sanghunka.github.io/">Keep Moving</a>
</div>
<a class="header-right-picture "
href="https://sanghunka.github.io/#about">
<img class="header-picture" src="//www.gravatar.com/avatar/286acbc504a86d12987dfa5cd3782a41?s=90" alt="Author's picture" />
</a>
</header>
<nav id="sidebar" data-behavior="4">
<div class="sidebar-container">
<div class="sidebar-profile">
<a href="https://sanghunka.github.io/#about">
<img class="sidebar-profile-picture" src="//www.gravatar.com/avatar/286acbc504a86d12987dfa5cd3782a41?s=110" alt="Author's picture" />
</a>
<h4 class="sidebar-profile-name">Sanghun Kang</h4>
<h5 class="sidebar-profile-bio"><strong>COOL</strong></h5>
</div>
<ul class="sidebar-buttons">
<li class="sidebar-button">
<a class="sidebar-button-link " href="https://sanghunka.github.io/">
<i class="sidebar-button-icon fa fa-lg fa-home"></i>
<span class="sidebar-button-desc">Home</span>
</a>
</li>
<li class="sidebar-button">
<a class="sidebar-button-link " href="https://sanghunka.github.io/categories">
<i class="sidebar-button-icon fa fa-lg fa-bookmark"></i>
<span class="sidebar-button-desc">Categories</span>
</a>
</li>
<li class="sidebar-button">
<a class="sidebar-button-link " href="https://sanghunka.github.io/tags">
<i class="sidebar-button-icon fa fa-lg fa-tags"></i>
<span class="sidebar-button-desc">Tags</span>
</a>
</li>
<li class="sidebar-button">
<a class="sidebar-button-link " href="https://sanghunka.github.io/archives">
<i class="sidebar-button-icon fa fa-lg fa-archive"></i>
<span class="sidebar-button-desc">Archives</span>
</a>
</li>
<li class="sidebar-button">
<a class="sidebar-button-link " href="https://sanghunka.github.io/#about">
<i class="sidebar-button-icon fa fa-lg fa-question"></i>
<span class="sidebar-button-desc">About</span>
</a>
</li>
</ul>
<ul class="sidebar-buttons">
<li class="sidebar-button">
<a class="sidebar-button-link " href="https://github.com/sanghunka" target="_blank" rel="noopener">
<i class="sidebar-button-icon fa fa-lg fa-github"></i>
<span class="sidebar-button-desc">GitHub</span>
</a>
</li>
</ul>
<ul class="sidebar-buttons">
<li class="sidebar-button">
<a class="sidebar-button-link " href="https://sanghunka.github.io/index.xml">
<i class="sidebar-button-icon fa fa-lg fa-rss"></i>
<span class="sidebar-button-desc">RSS</span>
</a>
</li>
</ul>
</div>
</nav>
<div id="main" data-behavior="4"
class="
hasCoverMetaIn
">
<article class="post" itemscope itemType="http://schema.org/BlogPosting">
<div class="post-header main-content-wrap text-left">
<h1 class="post-title" itemprop="headline">
Hidden social section showcase
</h1>
<div class="postShorten-meta post-meta">
<time itemprop="datePublished" datetime="2014-08-17T00:00:00Z">
August 17, 2014
</time>
<span>in</span>
<a class="category-link" href="https://sanghunka.github.io/categories/tranquilpeak-sample">tranquilpeak-sample</a>
</div>
</div>
<div class="post-content markdown" itemprop="articleBody">
<div class="main-content-wrap">
<p>This post is used to show how a site looks if the social section is hidden.</p>
<p>In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus.</p>
</div>
</div>
<div id="post-footer" class="post-footer main-content-wrap">
<div class="post-actions-wrap">
<nav >
<ul class="post-actions post-action-nav">
<li class="post-action">
<a class="post-action-btn btn btn--default tooltip--top" href="https://sanghunka.github.io/2014/10/tags-plugins-showcase/" data-tooltip="Tags plugins showcase">
<i class="fa fa-angle-left"></i>
<span class="hide-xs hide-sm text-small icon-ml">NEXT</span>
</a>
</li>
<li class="post-action">
<a class="post-action-btn btn btn--default tooltip--top" href="https://sanghunka.github.io/2014/08/hidden-tag-section-showcase/" data-tooltip="Hidden tag section showcase">
<span class="hide-xs hide-sm text-small icon-mr">PREVIOUS</span>
<i class="fa fa-angle-right"></i>
</a>
</li>
</ul>
</nav>
<ul class="post-actions post-action-share" >
<li class="post-action">
<a class="post-action-btn btn btn--default" href="#disqus_thread">
<i class="fa fa-comment-o"></i>
</a>
</li>
<li class="post-action">
<a class="post-action-btn btn btn--default" href="#">
<i class="fa fa-list"></i>
</a>
</li>
</ul>
</div>
<div id="disqus_thread">
<noscript>Please enable JavaScript to view the <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>
</div>
</article>
<footer id="footer" class="main-content-wrap">
<span class="copyrights">
© 2019 <a href="https://github.com/sanghunka">sanghunka</a>. All Rights Reserved
</span>
</footer>
</div>
<div id="bottom-bar" class="post-bottom-bar" data-behavior="4">
<div class="post-actions-wrap">
<nav >
<ul class="post-actions post-action-nav">
<li class="post-action">
<a class="post-action-btn btn btn--default tooltip--top" href="https://sanghunka.github.io/2014/10/tags-plugins-showcase/" data-tooltip="Tags plugins showcase">
<i class="fa fa-angle-left"></i>
<span class="hide-xs hide-sm text-small icon-ml">NEXT</span>
</a>
</li>
<li class="post-action">
<a class="post-action-btn btn btn--default tooltip--top" href="https://sanghunka.github.io/2014/08/hidden-tag-section-showcase/" data-tooltip="Hidden tag section showcase">
<span class="hide-xs hide-sm text-small icon-mr">PREVIOUS</span>
<i class="fa fa-angle-right"></i>
</a>
</li>
</ul>
</nav>
<ul class="post-actions post-action-share" >
<li class="post-action">
<a class="post-action-btn btn btn--default" href="#disqus_thread">
<i class="fa fa-comment-o"></i>
</a>
</li>
<li class="post-action">
<a class="post-action-btn btn btn--default" href="#">
<i class="fa fa-list"></i>
</a>
</li>
</ul>
</div>
</div>
<div id="share-options-bar" class="share-options-bar" data-behavior="4">
<i id="btn-close-shareoptions" class="fa fa-close"></i>
<ul class="share-options">
<li class="share-option">
<a class="share-option-btn" target="new" href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fsanghunka.github.io%2F2014%2F08%2Fhidden-social-section-showcase%2F">
<i class="fa fa-facebook-official"></i><span>Share on Facebook</span>
</a>
</li>
<li class="share-option">
<a class="share-option-btn" target="new" href="https://twitter.com/intent/tweet?text=https%3A%2F%2Fsanghunka.github.io%2F2014%2F08%2Fhidden-social-section-showcase%2F">
<i class="fa fa-twitter"></i><span>Share on Twitter</span>
</a>
</li>
<li class="share-option">
<a class="share-option-btn" target="new" href="https://plus.google.com/share?url=https%3A%2F%2Fsanghunka.github.io%2F2014%2F08%2Fhidden-social-section-showcase%2F">
<i class="fa fa-google-plus"></i><span>Share on Google+</span>
</a>
</li>
</ul>
</div>
<div id="share-options-mask" class="share-options-mask"></div>
</div>
<div id="about">
<div id="about-card">
<div id="about-btn-close">
<i class="fa fa-remove"></i>
</div>
<img id="about-card-picture" src="//www.gravatar.com/avatar/286acbc504a86d12987dfa5cd3782a41?s=110" alt="Author's picture" />
<h4 id="about-card-name">Sanghun Kang</h4>
<div id="about-card-bio"><strong>COOL</strong></div>
<div id="about-card-job">
<i class="fa fa-briefcase"></i>
<br/>
Data Engineer&Analyst
</div>
<div id="about-card-location">
<i class="fa fa-map-marker"></i>
<br/>
South Korea
</div>
</div>
</div>
<div id="algolia-search-modal" class="modal-container">
<div class="modal">
<div class="modal-header">
<span class="close-button"><i class="fa fa-close"></i></span>
<a href="https://algolia.com" target="_blank" rel="noopener" class="searchby-algolia text-color-light link-unstyled">
<span class="searchby-algolia-text text-color-light text-small">by</span>
<img class="searchby-algolia-logo" src="https://www.algolia.com/static_assets/images/press/downloads/algolia-light.svg">
</a>
<i class="search-icon fa fa-search"></i>
<form id="algolia-search-form">
<input type="text" id="algolia-search-input" name="search"
class="form-control input--large search-input" placeholder="Search" />
</form>
</div>
<div class="modal-body">
<div class="no-result text-color-light text-center">no post found</div>
<div class="results">
<div class="media">
<div class="media-body">
<a class="link-unstyled" href="https://sanghunka.github.io/2018/01/zsh%EC%97%90-%EC%84%A4%EC%A0%95%ED%95%B4%EB%91%94-alias%EB%A5%BC-crontab%EC%97%90-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B3%A0-%EC%8B%B6%EC%9D%84%EB%95%8C/">
<h3 class="media-heading">zsh에 설정해둔 alias를 crontab에 사용하고 싶을때</h3>
</a>
<span class="media-meta">
<span class="media-date text-small">
Jan 1, 2018
</span>
</span>
<div class="media-content hide-xs font-merryweather">Put your functions in .zshenv.
.zshenv is sourced on all invocations of the shell, unless the -f option is set. It should contain commands to set the command search path, plus other important environment variables. .zshenv should not contain commands that produce output or assume the shell is attached to a tty.
.zshrc is sourced in interactive shells. It should contain commands to set up aliases, functions, options, key bindings, etc.</div>
</div>
<div style="clear:both;"></div>
<hr>
</div>
<div class="media">
<div class="media-body">
<a class="link-unstyled" href="https://sanghunka.github.io/2018/01/%EC%95%A0%EB%93%9C%EC%9B%8C%EC%A6%88-%ED%95%99%EC%8A%B5/">
<h3 class="media-heading">애드워즈 학습</h3>
</a>
<span class="media-meta">
<span class="media-date text-small">
Jan 1, 2018
</span>
</span>
<div class="media-content hide-xs font-merryweather">강의 1: 온라인 광고의 가치에 대한 이해 이 모듈에서 학습할 내용
온라인 광고 및 애드워즈의 장점 Google의 광고 네트워크 애드워즈의 작동 원리 1.1 온라인 광고 및 애드워즈의 장점 광고 타겟팅 키워드 광고 위치 연령,위치,언어 요일,시간대,게재빈도 기기 비용관리 월, 일, 또는 광고 단위로 지출 비용 설정 가능 광고 효과 측정 캠페인 관리 MCC, 애드워즈 에디터등 애드워즈 광고
1.2 Google의 광고 네트워크 검색 네트워크</div>
</div>
<div style="clear:both;"></div>
<hr>
</div>
<div class="media">
<div class="media-body">
<a class="link-unstyled" href="https://sanghunka.github.io/2017/12/raspberrypi-stretch-with-desktop%EC%97%90%EC%84%9C-%EC%8A%A4%ED%8A%B8%EB%9D%BC%ED%8B%B0%EC%8A%A4-qt%EC%9B%94%EB%A0%9B-%EB%B9%8C%EB%93%9C%ED%95%98%EA%B8%B0/">
<h3 class="media-heading">Raspberrypi stretch with desktop에서 스트라티스 qt월렛 빌드하기</h3>
</a>
<span class="media-meta">
<span class="media-date text-small">
Dec 12, 2017
</span>
</span>
<div class="media-content hide-xs font-merryweather"><p>Guide대로 Jessie에서 하면 편합니다만 Stretch에서 하시길 원하신다면</p></div>
</div>
<div style="clear:both;"></div>
<hr>
</div>
<div class="media">
<div class="media-body">
<a class="link-unstyled" href="https://sanghunka.github.io/2017/12/airflow-6.-multi-cluster%EC%97%90%EC%84%9C-airflow-%EC%8B%A4%ED%96%89%ED%95%98%EA%B8%B0/">
<h3 class="media-heading">[airflow] 6. Multi cluster에서 airflow 실행하기</h3>
</a>
<span class="media-meta">
<span class="media-date text-small">
Dec 12, 2017
</span>
</span>
<div class="media-content hide-xs font-merryweather">요약 다루는 내용 분산 인스턴스에서 각각 airflow worker를 실행하고 task를 분산해서 실행하는법 task가 실행될 worker를 명시적으로 지정하는법 테스트 환경 두 개의 Amazon EC2 Instance 사용 1번 Instance에 아래와 같이 셋팅 metadata database(postsgres) rabbitmq airflow webserver airflow worker 2번 Instance에 아래와 같이 셋팅 airflow worker airflow configuration 1번과 2번 instance에 airflow를 설치한다. dag폴더에 동일한 파일을 넣어준다. dag폴더를 Git repository로 세팅하고 Chef, Puppet, Ansible등으로 동기화 해주는 방법도 있다.</div>
</div>
<div style="clear:both;"></div>
<hr>
</div>
<div class="media">
<div class="media-body">
<a class="link-unstyled" href="https://sanghunka.github.io/2017/12/airflow-5.-pyspark-sample-code-on-airflow/">
<h3 class="media-heading">[airflow] 5. Pyspark sample code on airflow</h3>
</a>
<span class="media-meta">
<span class="media-date text-small">
Dec 12, 2017
</span>
</span>
<div class="media-content hide-xs font-merryweather"><p>Airflow에서 Pyspark task 실행하기</p></div>
</div>
<div style="clear:both;"></div>
<hr>
</div>
<div class="media">
<div class="media-body">
<a class="link-unstyled" href="https://sanghunka.github.io/2017/12/airflow-5.-pyspark-sample-code-on-airflow/">
<h3 class="media-heading">[airflow] 5. Pyspark sample code on airflow</h3>
</a>
<span class="media-meta">
<span class="media-date text-small">
Dec 12, 2017
</span>
</span>
<div class="media-content hide-xs font-merryweather"><p>Airflow에서 Pyspark task 실행하기</p></div>
</div>
<div style="clear:both;"></div>
<hr>
</div>
<div class="media">
<div class="media-body">
<a class="link-unstyled" href="https://sanghunka.github.io/2017/12/mac-ijavascript-%EC%84%A4%EC%B9%98/">
<h3 class="media-heading">[Mac] ijavascript 설치</h3>
</a>
<span class="media-meta">
<span class="media-date text-small">
Dec 12, 2017
</span>
</span>
<div class="media-content hide-xs font-merryweather"> ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" brew install pkg-config node zeromq sudo easy_install pip sudo pip install --upgrade pyzmq jupyter sudo npm install -g ijavascript 설치하고자 하는 가상환경에서 ijsinstall ijsnotebook으로 실행 </div>
</div>
<div style="clear:both;"></div>
<hr>
</div>
<div class="media">
<div class="media-body">
<a class="link-unstyled" href="https://sanghunka.github.io/2017/12/airflow-4.-celeryexecutor-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0/">
<h3 class="media-heading">[airflow] 4. CeleryExecutor 사용하기</h3>
</a>
<span class="media-meta">
<span class="media-date text-small">
Dec 12, 2017
</span>
</span>
<div class="media-content hide-xs font-merryweather"><p>Airflow CeleryExecutor 사용하기</p></div>
</div>
<div style="clear:both;"></div>
<hr>
</div>
<div class="media">
<div class="media-body">
<a class="link-unstyled" href="https://sanghunka.github.io/2017/12/airflow-3.-localexecutor-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0/">
<h3 class="media-heading">[airflow] 3. LocalExecutor 사용하기</h3>
</a>
<span class="media-meta">
<span class="media-date text-small">
Dec 12, 2017
</span>
</span>
<div class="media-content hide-xs font-merryweather"><p>Airflow LocalExecutor 사용하기</p></div>
</div>
<div style="clear:both;"></div>
<hr>
</div>
<div class="media">
<div class="media-body">
<a class="link-unstyled" href="https://sanghunka.github.io/2017/12/mac-apche-spark-%EC%84%A4%EC%B9%98/">
<h3 class="media-heading">[Mac] Apche Spark 설치</h3>
</a>
<span class="media-meta">
<span class="media-date text-small">
Dec 12, 2017
</span>
</span>
<div class="media-content hide-xs font-merryweather">Java 설치 이미 설치된 java의 경로를 찾고 싶다면 /usr/libexec/java_home 명령어를 이용하면 된다.
brew tap caskroom/versions brew cask search java # brew cask install java 이렇게하면 자바9가 설치됩니다. brew cask install java8 2017-12-05 현재 Spark는 Java9를 지원하지 않는다. 그러므로 java8을 설치해야한다. 아래처럼 본인의 version에 맞는 path를 .bashrc(또는 .zshrc)에 지정해준다. export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home" Scala 설치 brew install scala java와 마찬가지로 본인의 version에 맞는 path를 .bashrc(또는 .</div>
</div>
<div style="clear:both;"></div>
<hr>
</div>
</div>
</div>
<div class="modal-footer">
<p class="results-count text-medium"
data-message-zero="no post found"
data-message-one="1 post found"
data-message-other="{n} posts found">
51 posts found
</p>
</div>
</div>
</div>
<div id="cover" style="background-image:url('https://themes.gohugo.io/theme/hugo-tranquilpeak-theme/images/cover.jpg');"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.7/js/jquery.fancybox.min.js" integrity="sha256-GEAnjcTqVP+vBp3SSc8bEDQqvWAZMiHyUSIorrWwH50=" crossorigin="anonymous"></script>
<script src="https://sanghunka.github.io/js/script-qi9wbxp2ya2j6p7wx1i6tgavftewndznf4v0hy2gvivk1rxgc3lm7njqb6bz.min.js"></script>
<script>
var disqus_config = function () {
this.page.url = 'https:\/\/sanghunka.github.io\/2014\/08\/hidden-social-section-showcase\/';
this.page.identifier = '\/2014\/08\/hidden-social-section-showcase\/'
};
(function() {
if (window.location.hostname == "localhost") {
return;
}
var d = document, s = d.createElement('script');
var disqus_shortname = 'sanghunka';
s.src = '//' + disqus_shortname + '.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
</body>
</html>
|
sanghkaang/sanghkaang.github.io
|
2014/08/hidden-social-section-showcase/index.html
|
HTML
|
mit
| 24,696
|
#HV Control &
#Read and Plot from the PMT
#This code is to record the data that is received into the Teensy's ADC.
#Includes the HV control and replotting the results at the end.
#See CSV Dataplot notebook to plot old experiment data.
from __future__ import division
from __future__ import print_function
from pyqtgraph import QtGui, QtCore #Provides usage of PyQt4's libraries which aids in UI design
import pyqtgraph as pg #Initiation of plotting code
import serial #Communication with the serial port is done using the pySerial 2.7 package
from datetime import datetime #Allows us to look at current date and time
#import dataprocessing #code for plotting the data from the CSV
## Always start by initializing Qt (only once per application)
app = QtGui.QApplication([])
## Define a top-level widget to hold everything (a window)
w = QtGui.QWidget()
w.resize(1000,600)
w.setWindowTitle('Voltage Plots')
startBtnClicked = False
quitBtnClicked = False
firstupdate = 0
## This function contains the behavior we want to see when the start button is clicked
def startButtonClicked():
global startBtnClicked
global startBtn
if (startBtnClicked == False):
teensySerialData.flushInput() #empty serial buffer for input from the teensy
startBtnClicked = True
startBtn.setText('Stop')
elif (startBtnClicked == True):
startBtnClicked = False
startBtn.setText('Start')
## Below at the end of the update function we check the value of quitBtnClicked
def quitButtonClicked():
global quitBtnClicked
quitBtnClicked = True
## Buttons to control the High Voltage
def HVoffButtonClicked():
teensySerialData.write('0')
print("HV Off")
def HVonButtonClicked():
teensySerialData.write('1')
print("HV On")
def insertionButtonClicked():
teensySerialData.write('3')
print("Insertion")
def separationButtonClicked():
teensySerialData.write('2')
print("Separation")
#Start Recording in Widget
## Create widgets to be placed inside
startBtn = QtGui.QPushButton('Start')
startBtn.setToolTip('Click to begin graphing') #This message appears while hovering mouse over button
quitBtn = QtGui.QPushButton('Quit')
quitBtn.setToolTip('Click to quit program')
HVonBtn = QtGui.QPushButton("HV on")
HVonBtn.setToolTip('Click to turn the high voltage on')
HVoffBtn = QtGui.QPushButton("HV off")
HVoffBtn.setToolTip('Click to turn the high voltage off')
insBtn = QtGui.QPushButton("Insertion")
insBtn.setToolTip('Click to start insertion (#3)')
sepBtn = QtGui.QPushButton("Separation")
sepBtn.setToolTip('Click to start separation (#2)')
## Functions in parantheses are to be called when buttons are clicked
startBtn.clicked.connect(startButtonClicked)
quitBtn.clicked.connect(quitButtonClicked)
HVonBtn.clicked.connect(HVonButtonClicked)
HVoffBtn.clicked.connect(HVoffButtonClicked)
insBtn.clicked.connect(insertionButtonClicked)
sepBtn.clicked.connect(separationButtonClicked)
## xSamples is the maximum amount of samples we want graphed at a time
xSamples = 300
## Create plot widget for peak detector plot
pmtPlotWidget = pg.PlotWidget()
pmtPlotWidget.setYRange(0, 4096)
pmtPlotWidget.setXRange(0, xSamples)
pmtPlotWidget.setLabel('top', text = "PMT") #Title to appear at top of widget
## Create a grid layout to manage the widgets size and position
## The grid layout allows us to place a widget in a given column and row
layout = QtGui.QGridLayout()
w.setLayout(layout)
## Add widgets to the layout in their proper positions
## The first number in parantheses is the row, the second is the column
layout.addWidget(quitBtn, 0, 0)
layout.addWidget(startBtn, 2, 0)
layout.addWidget(HVonBtn, 0, 2)
layout.addWidget(insBtn, 2, 2)
layout.addWidget(sepBtn, 3, 2)
layout.addWidget(HVoffBtn, 4, 2)
layout.addWidget(pmtPlotWidget, 1, 1)
## Display the widget as a new window
w.show()
## Initialize all global variables
## Whenever we plot a range of samples, xLeftIndex is the x value on the
## PlotWidget where we start plotting the samples, xRightIndex is where we stop
## These values will reset when they reach the value of xSamples
xRightIndex = 0
xLeftIndex = 0
## These arrays will hold the unplotted voltage values from the pmt
## and the peak detector until we are able to update the plot
pmtData = []
## Used to determine how often we plot a range of values
graphCount = 0
## Time values in microseconds read from the teensy are stored in these variables
## Before timeElapsed is updated, we store its old value in timeElapsedPrev
timeElapsed = 0
timeElapsedPrev = 0
## Determines if we are running through the update loop for the first time
firstRun = True
## Create new file, with the name being today's date and current time and write headings to file in CSV format
i = datetime.now()
fileName = str(i.year) + str(i.month) + str(i.day) + "_" + str(i.hour) + str(i.minute) + str(i.second) + ".csv"
## File is saved to Documents/IPython Notebooks/RecordedData
#f = open('RecordedData\\' + fileName, 'a')
#f.write("#Data from " + str(i.year) + "-" + str(i.month) + "-" + str(i.day) + " at " + str(i.hour) + ":" + str(i.minute) + ":" + str(i.second) + '\n')
#f.write("Timestamp,PMT\n")
## Initialize the container for our voltage values read in from the teensy
## IMPORTANT NOTE: The com port value needs to be updated if the com value
## changes. It's the same number that appears on the bottom right corner of the
## window containing the TeensyDataWrite.ino code
teensySerialData = serial.Serial("/dev/tty.usbmodem1452", 115200)
def update():
## Set global precedence to previously defined values
global xSamples
global xRightIndex
global xLeftIndex
global pmtData
global graphCount
global timeElapsed
global timeElapsedPrev
global firstRun
global firstupdate
if firstupdate == 0:
teensySerialData.flushInput()
firstupdate += 1
## The number of bytes currently waiting to be read in.
## We want to read these values as soon as possible, because
## we will lose them if the buffer fills up
bufferSize = teensySerialData.inWaiting()
runCount = bufferSize//8 # since we write 8 bytes at a time, we similarly want to read them 8 at a time
#print(bufferSize, runCount)
while (runCount > 0):
if (startBtnClicked == True):
#Read in time (int) and PMT output (float with up to 5 decimal places)
temp = []
temp.append(teensySerialData.readline().strip().split(',') )
print(bufferSize, runCount, temp[-1][0], temp[-1][1])
timeElapsedPrev = timeElapsed
timeElapsed = int (temp[0][0])
if (firstRun == True):
## Only run once to ensure buffer is completely flushed
firstRun = False
teensySerialData.flushInput()
break
# We'll add all our values to this string until we're ready to exit the loop, at which point it will be written to a file
stringToWrite = str(timeElapsed) + ","
## This difference calucalted in the if statement is the amount of time in microseconds since the last value
## we read in and wrote to a file. If this value is significantly greater than 100, we know we have missed some
## values, probably as a result of the buffer filling up and scrapping old values to make room for new values.
## The number we print out will be the approximate number of values we failed to read in.
## This is useful to determine if your code is running too slow
#if (timeElapsed - timeElapsedPrev > 8000):
#print(str((timeElapsed-timeElapsedPrev)/7400))
numData = float (temp[0][1])
pmtData.append(numData)
stringToWrite = stringToWrite + str(numData) + '\n'
#f.write(stringToWrite)
graphCount = graphCount + 1
xRightIndex = xRightIndex + 1
runCount = runCount - 1
## We will start plotting when the start button is clicked
if startBtnClicked == True:
if (graphCount >= 1): #We will plot new values once we have this many values to plot
if (xLeftIndex == 0):
# Remove all PlotDataItems from the PlotWidgets.
# This will effectively reset the graphs (approximately every 30000 samples)
#pmtPlotWidget.clear()
pmtPlotWidget.clear()
## pmtCurve are of the PlotDataItem type and are added to the PlotWidget.
## Documentation for these types can be found on pyqtgraph's website
pmtCurve = pmtPlotWidget.plot()
xRange = range(xLeftIndex,xRightIndex)
pmtCurve.setData(xRange, pmtData)
## Now that we've plotting the values, we no longer need these arrays to store them
pmtData = []
xLeftIndex = xRightIndex
graphCount = 0
if(xRightIndex >= xSamples):
xRightIndex = 0
xLeftIndex = 0
pmtData = []
if(quitBtnClicked == True):
## Close the file and close the window. Performing this action here ensures values we want to write to the file won't be cut off
#f.close()
w.close()
teensySerialData.close()
#dataprocessing.CSVDataPlot(fileName)
## Run update function in response to a timer
timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.start(0)
## Start the Qt event loop
app.exec_()
|
gregnordin/micropython_pyboard
|
150729_pyboard_to_pyqtgraph/serial_pyboard_to_python.py
|
Python
|
mit
| 9,779
|
{% extends "layout.html" %} {% block content %}
<h3>用户管理</h3>
<div>
<ul class="breadcrumb">
<li>
<a href="{{url_for('Common.index')}}">Home</a> <span class="divider">/</span>
</li>
<li>
<a href="{{url_for('Common.user_setting')}}">用户管理</a><span class="divider">/</span>
</li>
<li>
<a href="#">添加用户</a>
</li>
</ul>
</div>
<div class="box-content">
<form class="form-horizontal" role="form" action="{{url_for('Common.user_setting', action="add")}}" method="post">
{{ form.csrf_token }}
<fieldset>
<div class="control-group">
<label class="control-label">姓名</label>
<div class="controls">
{{ form.name(class="form-control", placeholder="请输入用户名", autocomplete=true)}}
</div>
</div>
<div class="control-group">
<label class="control-label" for="focusedInput">邮箱</label>
<div class="controls">
{{ form.email(class="form-control", placeholder="Email") }}
</div>
</div>
<div class="control-group">
<label class="control-label" for="focusedInput">密码</label>
<div class="controls">
{{ form.password(class="form-control", placeholder="password") }}
</div>
</div>
<button type="submit" class="btn btn-primary">添加</button>
</fieldset>
</form>
</div>
{% endblock %}
|
san-na/crm
|
crm_web/crm/templates/user_add.html
|
HTML
|
mit
| 1,413
|
'use strict';
/** Load Node.js modules. */
var fs = require('fs');
/** Load other modules. */
var _ = require('lodash-compat');
/** Used to minify variables and string values to a single character. */
var minNames = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
minNames.push.apply(minNames, minNames.map(function(value) {
return value + value;
}));
/** Used to protect the specified properties from getting minified. */
var propWhitelist = _.union(
_.keys(_),
_.keys(_.prototype),
_.keys(_.support),
_.keys(_.templateSettings), [
'BYTES_PER_ELEMENT',
'NEGATIVE_INFINITY',
'POSITIVE_INFINITY',
'Array',
'ArrayBuffer',
'Boolean',
'Cache',
'Date',
'Error',
'Float32Array',
'Float64Array',
'Function',
'Int8Array',
'Int16Array',
'Int32Array',
'Math',
'Number',
'Object',
'RegExp',
'Set',
'String',
'TypeError',
'Uint8Array',
'Uint8ClampedArray',
'Uint16Array',
'Uint32Array',
'WeakMap',
'WinRTError',
'__actions__',
'__chain__',
'__data__',
'__dir__',
'__filtered__',
'__iteratees__',
'__takeCount__',
'__views__',
'__wrapped__',
'add',
'args',
'amd',
'buffer',
'byteLength',
'cache',
'cancel',
'clearTimeout',
'count',
'createDocumentFragment',
'criteria',
'data',
'delete',
'document',
'done',
'end',
'exports',
'func',
'get',
'global',
'has',
'hash',
'index',
'iteratee',
'leading',
'length',
'limit',
'maxWait',
'name',
'nodeType',
'omission',
'placeholder',
'self',
'separator',
'set',
'setTimeout',
'size',
'source',
'sourceURL',
'start',
'thisArg',
'trailing',
'type',
'value',
'window'
]);
/*----------------------------------------------------------------------------*/
/**
* Pre-process a given lodash `source`, preparing it for minification.
*
* @param {string} [source=''] The source to process.
* @param {Object} [options={}] The options object.
* @returns {string} Returns the processed source.
*/
function preprocess(source, options) {
source || (source = '');
options || (options = {});
// Remove unrecognized JSDoc tags so the Closure Compiler won't complain.
source = source.replace(/@(?:alias|category)\b.*/g, '');
if (options.isTemplate) {
return source;
}
// Remove whitespace from `_.template` related regexes.
source = source.replace(/(reEmptyString\w+\s*=)([\s\S]+?)(?=[,;]\n)/g, function(match, left, value) {
return left + value.replace(/\s|\\n/g, '');
});
// Remove whitespace from `_.template`.
source = source.replace(/^( *)function template\b[\s\S]+?\n\1}/m, function(snippet) {
// Remove whitespace from string literals.
snippet = snippet.replace(/^((?:[ "'$\w]+:)?\s*)"[^"\n\\]*?(?:\\.[^"\n\\]*?)*"|'[^'\n\\]*?(?:\\.[^'\n\\]*?)*'/gm, function(string, left) {
// Clip `string` after an object literal property name or leading spaces.
if (left) {
string = string.slice(left.length);
}
// Avoids removing the '\n' of the `stringEscapes` object.
string = string.replace(/\[object |delete |else (?!{)|function | in | instanceof |return\s+["'$\w]|throw |typeof |use strict|var |# |(["'])(?:\\n| )\1|\\\\n|\\n|\s+/g, function(match) {
return match == false || match == '\\n' ? '' : match;
});
// Unclip `string`.
return (left || '') + string;
});
// Remove newline from double-quoted strings.
snippet = snippet
.replace('"__p += \'"', '"__p+=\'"')
.replace('"\';\\n"', '"\';"');
// Add a newline back so "evaluate" delimiters can support single line comments.
snippet = snippet.replace('";__p+=\'"', '";\\n__p+=\'"');
// Remove default `sourceURL` value.
return snippet.replace(/^( *var\s+sourceURL\s*=\s*)[\s\S]+?(?=;\n$)/m, function(match, left) {
return left + "'sourceURL' in options ? '//# sourceURL=' + options.sourceURL + '\\n' : ''";
});
});
// Minify internal properties.
(function() {
var funcNames = [
'baseSortBy',
'baseSortByOrder',
'compareAscending',
'compareMultiple',
'sortBy'
];
var props = [
'criteria',
'index',
'value'
];
// Minify properties used in `funcNames` functions.
var snippets = source.match(RegExp('^( *)(?:var|function) +(?:' + funcNames.join('|') + ')\\b[\\s\\S]+?\\n\\1}', 'gm'));
_.each(snippets, function(snippet) {
var modified = snippet;
_.each(props, function(prop, index) {
var minName = minNames[index],
reBracketProp = RegExp("\\['(" + prop + ")'\\]", 'g'),
reDotProp = RegExp('\\.' + prop + '\\b', 'g'),
rePropColon = RegExp("([^?\\s])\\s*([\"'])?\\b" + prop + "\\2\\s*:", 'g');
modified = modified
.replace(reBracketProp, "['" + minName + "']")
.replace(reDotProp, "['" + minName + "']")
.replace(rePropColon, "$1'" + minName + "':");
});
// Replace with modified snippet.
source = source.replace(snippet, function() {
return modified;
});
});
}());
// Add brackets to whitelisted properties so the Closure Compiler won't mung them.
// See http://code.google.com/closure/compiler/docs/api-tutorial3.html#export.
return source.replace(RegExp('(["\'])(?:(?!\\1)[^\\n\\\\]|\\\\.)*\\1|\\.(' + propWhitelist.join('|') + ')\\b', 'g'), function(match, quote, prop) {
return quote ? match : "['" + prop + "']";
});
}
/*----------------------------------------------------------------------------*/
// Export `preprocess`.
if (module != require.main) {
module.exports = preprocess;
}
// Read the lodash source file from the first argument if the script was invoked
// by the command-line (e.g. `node pre-compile.js source.js`) and write to the same file.
else if (_.size(process.argv) > 2) {
(function() {
var filePath = path.normalize(_.last(process.argv)),
isTemplate = _.includes(process.argv, '-t') || _.includes(process.argv, '--template'),
source = fs.readFileSync(filePath, 'utf8');
fs.writeFileSync(filePath, preprocess(source, {
'isTemplate': isTemplate
}), 'utf8');
}());
}
|
megawac/lodash-cli
|
lib/pre-compile.js
|
JavaScript
|
mit
| 6,181
|
Ember.TEMPLATES["unit-controllers"] = Ember.Handlebars.compile(
'<div class="unit-controllers">{{render "rendered" someModel className="asd"}}</div>'
);
//--------------------------------------------------------------------------
module("templates - controllers - full environment", {
setup: function() {
var container = new Ember.Container();
container.register("template:rendered", Ember.Handlebars.compile("controller stub"), {instantiate: false});
container.register("view:rendered", Ember.View);
container.register("controller:rendered", Ember.Controller);
var view = Ember.View.create({
controller: Ember.Controller.create({
container: container
}),
template: Ember.TEMPLATES["unit-controllers"]
});
Ember.run(function() {
view.appendTo("#qunit-fixture");
});
}
});
test("template renders correctly", function() {
equal(Ember.$("#qunit-fixture .unit-controllers").text(), "controller stub");
});
module("templates - controllers - stubbing helper", {
setup: function() {
sinon.stub(Ember.Handlebars.helpers, 'render').returns(new Handlebars.SafeString("controller stub"));
var view = Ember.View.create({
template: Ember.TEMPLATES["unit-controllers"]
});
Ember.run(function() {
view.appendTo("#qunit-fixture");
});
}
});
test("template renders correctly", function() {
equal(Ember.$("#qunit-fixture .unit-controllers").text(), "controller stub");
});
|
velesin/ember-testing-cookbook
|
unit/templates/controller_rendering.js
|
JavaScript
|
mit
| 1,475
|
---
title: "Racial profiling no better than random screening"
slug: "racial-profiling-no-better-than-random-screening"
date: "2009-03-04T09:05:45-06:00"
author: "fak3r"
categories:
- commentary
- geek
- headline
- politics
- travel
tags:
- bioinformatics
- screening
- security
- terrorist
- travel
- tsa
- watchlist
---
While the TSA alway seem to be trying to cover every eventuality, even warning me about my 6 oz. tube of hair gel last week in Rhode Island, statistical studies are showing that [racial profiling is no better than radom screening](http://www.schneier.com/blog/archives/2009/02/racial_profilin.html) in finding terrorist suspects. Just as people with the same names as potential suspects are showing up on watchlists, this is not a good way to determine their threat level. While there certainly are many challenges to generating profiles of potential terrorists, this study released by the _Proceedings of the National Academies of Science_ does a mathematical analysis how we're deploying the profiles we do have, and suggests we may not be using them wisely.
> The study was performed by William Press, who does bioinformatics research at the University of Texas, Austin, with a joint appointment at Los Alamos National Labs. His background in statistics is apparent in his ability to handle various mathematical formulae with aplomb, but he's apparently used to explaining his work to biologists, since the descriptions that surround those formulae make the general outlines of the paper fairly accessible.
Press starts by examining what could be viewed as an idealized situation, at least from the screening perspective: a single perpetrator living under an authoritarian government that has perfect records on its citizens. Applying a profile to those records should allow the government to rank those citizens in order of risk, and it can screen them one-by-one until it identifies the actual perpetrator. Those circumstances lead to a pretty rapid screening process, and they can be generalized out to a situation where there are multiple likely perpetrators.
Things go rapidly sour for this system, however, as soon as you have an imperfect profile. In that case, which is more likely to reflect reality, there's a finite chance that the screening process misses a likely security risk. Since it works its way through the list of individuals iteratively, it never goes back to rescreen someone that's made it through the first pass. The impact of this flaw grows rapidly as the ability to accurately match the profile to the data available on an individual gets worse. Since we've already said that making a profile is challenging, and we know that even authoritarian governments don't have perfect information on their citizens, this system is probably worse than random screening in the real world.
Many say racial profiling is just another form of racism, but is it an effect of the TSA in picking out possible suspects, or a reflection on what our society sees as a threat? Either way, just as our not being able to take a big bottle of shampoo on a plane, it's not making us any safer.
|
philcryer/docker-fak3r.com
|
content/post/racial-profiling-no-better-than-random-screening.markdown
|
Markdown
|
mit
| 3,301
|
'use babel'
import util from 'util'
import { exec } from 'child_process'
import applescript from 'applescript'
import { Errors } from './constants'
const runscript = (file) => new Promise((resolve, reject) => {
applescript.execFile(file, (error, result) => {
if (error) { reject(error) }
try {
if (result) {
resolve(JSON.parse(result))
} else {
reject(new Error(Errors.NO_DATA))
}
} catch (e) {
reject(new Error(Errors.JSON_PARSE_ERROR))
}
});
})
const getState = () => runscript(`${__dirname}/scripts/getState.applescript`)
const getTrack = () => runscript(`${__dirname}/scripts/getTrack.applescript`)
export default {
getState,
getTrack
}
|
yianL/atom-spotified
|
src/utils/spotify-applescript.js
|
JavaScript
|
mit
| 711
|
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "SBIcon.h"
@interface SBIcon (SBFolderIcon)
- (_Bool)hasFolderIconView;
- (id)folder;
- (_Bool)isFolderIcon;
@end
|
iMokhles/iPhone5S-iOS8.1-SBHeaders
|
SBIcon-SBFolderIcon.h
|
C
|
mit
| 263
|
# frozen_string_literal: true
require_relative "../../../../test_helper"
class Comfy::Admin::Cms::PagesControllerTest < ActionDispatch::IntegrationTest
def setup
@site = comfy_cms_sites(:default)
@layout = comfy_cms_layouts(:default)
@page = comfy_cms_pages(:default)
end
def test_get_index
r :get, comfy_admin_cms_site_pages_path(site_id: @site)
assert_response :success
assert assigns(:pages)
assert_template :index
end
def test_get_index_with_no_pages
Comfy::Cms::Page.delete_all
r :get, comfy_admin_cms_site_pages_path(site_id: @site)
assert_response :redirect
assert_redirected_to action: :new
end
def test_get_index_with_category
category = @site.categories.create!(
label: "Test Category",
categorized_type: "Comfy::Cms::Page"
)
category.categorizations.create!(categorized: comfy_cms_pages(:child))
r :get, comfy_admin_cms_site_pages_path(site_id: @site), params: { categories: category.label }
assert_response :success
assert assigns(:pages)
assert_equal 1, assigns(:pages).count
assert assigns(:pages).first.categories.member? category
end
def test_get_index_with_category_invalid
r :get, comfy_admin_cms_site_pages_path(site_id: @site), params: { categories: "invalid" }
assert_response :success
assert assigns(:pages)
assert_equal 0, assigns(:pages).count
end
def test_get_index_with_toggle
@site.pages.create!(
label: "test",
slug: "test",
parent: comfy_cms_pages(:child),
layout: comfy_cms_layouts(:default)
)
r :get, comfy_admin_cms_site_pages_path(site_id: @site)
assert_response :success
end
def test_get_links_with_redactor
r :get, comfy_admin_cms_site_pages_path(site_id: @site), params: { source: "redactor" }
assert_response :success
assert_equal [
{ "name" => "Select page...", "url" => false },
{ "name" => "Default Page", "url" => "/" },
{ "name" => ". . Child Page", "url" => "/child-page" }
], JSON.parse(response.body)
end
def test_get_new
r :get, new_comfy_admin_cms_site_page_path(site_id: @site)
assert_response :success
assert assigns(:page)
assert_equal @layout, assigns(:page).layout
assert_template :new
assert_select "form[action='/admin/sites/#{@site.id}/pages']"
assert_select "select[data-url='/admin/sites/#{@site.id}/pages/0/form_fragments']"
assert_select "textarea[name='page[fragments_attributes][0][content]']"
assert_select "input[type='hidden'][name='page[fragments_attributes][0][identifier]'][value='content']"
assert_select "input[type='hidden'][name='page[fragments_attributes][0][tag]'][value='text_area']"
end
def test_get_new_with_several_fields
@layout.update_column(:content, "{{cms:wysiwyg a}}{{cms:markdown b}}")
r :get, new_comfy_admin_cms_site_page_path(site_id: @site)
assert_response :success
assert_select "textarea[name='page[fragments_attributes][0][content]']"
assert_select "input[type='hidden'][name='page[fragments_attributes][0][identifier]'][value='a']"
assert_select "input[type='hidden'][name='page[fragments_attributes][0][tag]'][value='wysiwyg']"
assert_select "textarea[name='page[fragments_attributes][1][content]']"
assert_select "input[type='hidden'][name='page[fragments_attributes][1][identifier]'][value='b']"
assert_select "input[type='hidden'][name='page[fragments_attributes][1][tag]'][value='markdown']"
end
def test_get_new_with_non_renderable_fragment
@layout.update_column(:content, "{{cms:text a}}{{cms:text b, render: false}}")
r :get, new_comfy_admin_cms_site_page_path(site_id: @site)
assert_response :success
assert_select "label.renderable-true", "A"
assert_select "label.renderable-false", "B"
end
def test_get_new_with_invalid_tag
@layout.update_column(:content, "{{cms:invalid}}")
r :get, new_comfy_admin_cms_site_page_path(site_id: @site)
assert_response :success
assert_select "div.alert-danger", "Unrecognized tag: {{cms:invalid}}"
end
def test_get_new_with_invalid_fragment_tag
@layout.update_column(:content, "a {{cms:markdown}} b")
r :get, new_comfy_admin_cms_site_page_path(site_id: @site)
assert_response :success
assert_select "div.alert-danger", "Missing identifier for fragment tag: {{cms:markdown}}"
end
def test_get_new_with_repeated_tag
@layout.update_column(:content, "{{cms:text test}}{{cms:text test}}")
r :get, new_comfy_admin_cms_site_page_path(site_id: @site)
assert_response :success
assert_select "input[name='page[fragments_attributes][0][content]']"
assert_select "input[type='hidden'][name='page[fragments_attributes][0][identifier]'][value='test']"
assert_select "input[name='page[fragments_attributes][1][content]']", 0
assert_select "input[type='hidden'][name='page[fragments_attributes][1][identifier]'][value='test']", 0
end
def test_get_new_with_namespaced_tags
@layout.update_column(:content, "{{cms:text a, namespace: a}}{{cms:text b, namespace: b}}")
r :get, new_comfy_admin_cms_site_page_path(site_id: @site)
assert_response :success
assert_select "a[data-toggle='tab'][href='#ns-a']", "A"
assert_select "a[data-toggle='tab'][href='#ns-b']", "B"
assert_select "input[name='page[fragments_attributes][0][content]']"
assert_select "input[type='hidden'][name='page[fragments_attributes][0][identifier]'][value='a']"
assert_select "input[name='page[fragments_attributes][1][content]']"
assert_select "input[type='hidden'][name='page[fragments_attributes][1][identifier]'][value='b']"
end
def test_get_new_with_localized_names
I18n.backend.store_translations(:en, comfy: { cms: { content:
{ tag: { localized_a: "Localized Fragment" },
namespace: { localized_a: "Localized Namespace" } }
} })
@layout.update_column(
:content,
"{{cms:text localized_a, namespace: localized_a}}{{cms:text b, namespace: b}}"
)
r :get, new_comfy_admin_cms_site_page_path(site_id: @site)
assert_response :success
assert_select "a[data-toggle='tab'][href='#ns-localized_a']", "Localized Namespace"
assert_select "label", "Localized Fragment"
ensure
I18n.backend.store_translations(:en, comfy: { cms: { content:
{ tag: nil, namespace: nil }
} })
end
def test_get_new_as_child_page
r :get, new_comfy_admin_cms_site_page_path(site_id: @site), params: { parent_id: @page }
assert_response :success
assert assigns(:page)
assert_equal comfy_cms_pages(:default), assigns(:page).parent
assert_template :new
end
def test_get_edit
r :get, edit_comfy_admin_cms_site_page_path(site_id: @site, id: @page)
assert_response :success
assert assigns(:page)
assert_template :edit
assert_select "form[action='/admin/sites/#{@site.id}/pages/#{@page.id}']"
assert_select "select[data-url='/admin/sites/#{@site.id}/pages/#{@page.id}/form_fragments']"
end
def test_get_edit_failure
r :get, edit_comfy_admin_cms_site_page_path(site_id: @site, id: "not_found")
assert_response :redirect
assert_redirected_to action: :index
assert_equal "Page not found", flash[:danger]
end
def test_get_edit_with_blank_layout
@page.update_column(:layout_id, nil)
r :get, edit_comfy_admin_cms_site_page_path(site_id: @site, id: @page)
assert_response :success
assert assigns(:page)
end
def test_get_edit_with_non_english_locale
@site.update_column(:locale, "es")
r :get, edit_comfy_admin_cms_site_page_path(site_id: @site, id: @page)
assert_response :success
end
def test_get_edit_with_layout_and_no_tags
@page.layout.update_column(:content, "")
r :get, edit_comfy_admin_cms_site_page_path(site_id: @site, id: @page)
assert_response :success
end
def test_creation
assert_difference "Comfy::Cms::Page.count" do
assert_difference "Comfy::Cms::Fragment.count", 2 do
r :post, comfy_admin_cms_site_pages_path(site_id: @site), params: {
page: {
label: "Test Page",
slug: "test-page",
parent_id: @page.id,
layout_id: @layout.id,
fragments_attributes: [
{ identifier: "default_page_text",
content: "content content" },
{ identifier: "default_field_text",
content: "title content" }
]
},
commit: "Create Page"
}
assert_response :redirect
page = Comfy::Cms::Page.last
assert_equal @site, page.site
assert_redirected_to action: :edit, id: page
assert_equal "Page created", flash[:success]
end
end
end
def test_creation_with_files
assert_difference "Comfy::Cms::Page.count" do
assert_difference "Comfy::Cms::Fragment.count", 3 do
assert_difference "ActiveStorage::Attachment.count", 3 do
r :post, comfy_admin_cms_site_pages_path(site_id: @site), params: {
page: {
label: "Test Page",
slug: "test-page",
parent_id: @page.id,
layout_id: @layout.id,
fragments_attributes: [
{ identifier: "image",
tag: "file",
files: fixture_file_upload("files/image.jpg", "image/jpeg")
},
{ identifier: "files_multiple",
tag: "files",
files: [
fixture_file_upload("files/image.jpg", "image/jpeg"),
fixture_file_upload("files/document.pdf", "application/pdf")
]
},
{ identifier: "unpopulated",
tag: "file",
content: nil
}
]
},
commit: "Create Page"
}
assert_response :redirect
page = Comfy::Cms::Page.last
assert_equal @site, page.site
assert_redirected_to action: :edit, id: page
assert_equal "Page created", flash[:success]
end
end
end
end
def test_creation_failure
assert_no_difference ["Comfy::Cms::Page.count", "Comfy::Cms::Fragment.count"] do
r :post, comfy_admin_cms_site_pages_path(site_id: @site), params: { page: {
layout_id: @layout.id,
fragments_attributes: [
{ identifier: "content",
content: "content content" },
{ identifier: "title",
content: "title content" }
]
} }
assert_response :success
page = assigns(:page)
assert_equal 2, page.fragments.size
assert_equal ["content content", "title content"], page.fragments.collect(&:content)
assert_template :new
assert_equal "Failed to create page", flash[:danger]
end
end
def test_update
assert_no_difference "Comfy::Cms::Fragment.count" do
r :put, comfy_admin_cms_site_page_path(site_id: @site, id: @page), params: { page: {
label: "Updated Label"
} }
@page.reload
assert_response :redirect
assert_redirected_to action: :edit, id: @page
assert_equal "Page updated", flash[:success]
assert_equal "Updated Label", @page.label
end
end
def test_update_with_layout_change
assert_difference "Comfy::Cms::Fragment.count" do
r :put, comfy_admin_cms_site_page_path(site_id: @site, id: @page), params: { page: {
label: "Updated Label",
layout_id: comfy_cms_layouts(:nested).id,
fragments_attributes: [
{ identifier: "content",
content: "new_page_text_content" },
{ identifier: "header",
content: "new_page_string_content" }
]
} }
@page.reload
assert_response :redirect
assert_redirected_to action: :edit, id: @page
assert_equal "Page updated", flash[:success]
assert_equal "Updated Label", @page.label
identifiers = @page.fragments.collect(&:identifier)
assert_equal %w[boolean content datetime file header], identifiers.sort
end
end
def test_update_failure
r :put, comfy_admin_cms_site_page_path(site_id: @site, id: @page), params: { page: {
label: ""
} }
assert_response :success
assert_template :edit
assert assigns(:page)
assert_equal "Failed to update page", flash[:danger]
end
def test_destroy
assert_difference "Comfy::Cms::Page.count", -2 do
assert_difference "Comfy::Cms::Fragment.count", -4 do
r :delete, comfy_admin_cms_site_page_path(site_id: @site, id: @page)
assert_response :redirect
assert_redirected_to action: :index
assert_equal "Page deleted", flash[:success]
end
end
end
def test_get_form_fragments
r :get, form_fragments_comfy_admin_cms_site_page_path(site_id: @site, id: @page), xhr: true, params: {
layout_id: comfy_cms_layouts(:nested).id
}
assert_response :success
assert assigns(:page)
assert_equal 2, assigns(:page).fragment_nodes.size
assert_template "comfy/admin/cms/fragments/_form_fragments"
r :get, form_fragments_comfy_admin_cms_site_page_path(site_id: @site, id: @page), xhr: true, params: {
layout_id: @layout.id
}
assert_response :success
assert assigns(:page)
assert_equal 1, assigns(:page).fragment_nodes.size
assert_template "comfy/admin/cms/fragments/_form_fragments"
end
def test_get_form_fragments_for_new_page
r :get, form_fragments_comfy_admin_cms_site_page_path(site_id: @site, id: 0), xhr: true, params: {
layout_id: @layout.id
}
assert_response :success
assert assigns(:page)
assert_equal 1, assigns(:page).fragment_nodes.size
assert_template "comfy/admin/cms/fragments/_form_fragments"
end
def test_creation_preview
assert_no_difference "Comfy::Cms::Page.count" do
r :post, comfy_admin_cms_site_pages_path(site_id: @site), params: {
preview: "Preview",
page: {
label: "Test Page",
slug: "test-page",
parent_id: @page.id,
layout_id: @layout.id,
fragments_attributes: [
{ identifier: "content",
content: "preview content" }
]
}
}
assert_response :success
assert_match %r{preview content}, response.body
assert_equal "text/html", response.content_type
assert_equal @site, assigns(:cms_site)
assert_equal @layout, assigns(:cms_layout)
assert assigns(:cms_page)
assert assigns(:cms_page).new_record?
end
end
def test_update_preview
assert_no_difference "Comfy::Cms::Page.count" do
r :put, comfy_admin_cms_site_page_path(site_id: @site, id: @page), params: {
preview: "Preview",
page: {
label: "Updated Label",
fragments_attributes: [
{ identifier: "content",
content: "preview content" }
]
}
}
assert_response :success
assert_match %r{preview content}, response.body
@page.reload
assert_not_equal "Updated Label", @page.label
assert_equal @page.site, assigns(:cms_site)
assert_equal @page.layout, assigns(:cms_layout)
assert_equal @page, assigns(:cms_page)
end
end
def test_preview_language
@site.update_column(:locale, "de")
assert_equal :en, I18n.locale
r :post, comfy_admin_cms_site_pages_path(site_id: @site), params: {
preview: "Preview",
page: {
label: "Test Page",
slug: "test-page",
parent_id: @page.id,
layout_id: @layout.id,
fragments_attributes: [
{ identifier: "content",
content: "preview content" }
]
}
}
assert_response :success
assert_equal :de, I18n.locale
end
def test_get_new_with_no_layout
Comfy::Cms::Layout.destroy_all
r :get, new_comfy_admin_cms_site_page_path(site_id: @site)
assert_response :redirect
assert_redirected_to new_comfy_admin_cms_site_layout_path(@site)
assert_equal "No Layouts found. Please create one.", flash[:danger]
end
def test_get_edit_with_no_layout
Comfy::Cms::Layout.destroy_all
r :get, edit_comfy_admin_cms_site_page_path(site_id: @site, id: @page)
assert_response :redirect
assert_redirected_to new_comfy_admin_cms_site_layout_path(@site)
assert_equal "No Layouts found. Please create one.", flash[:danger]
end
def test_get_toggle_branch
r :get, toggle_branch_comfy_admin_cms_site_page_path(site_id: @site, id: @page), xhr: true, params: { format: :js }
assert_response :success
assert_equal [@page.id.to_s], session[:cms_page_tree]
r :get, toggle_branch_comfy_admin_cms_site_page_path(site_id: @site, id: @page), xhr: true, params: { format: :js }
assert_response :success
assert_equal [], session[:cms_page_tree]
end
def test_reorder
page_one = comfy_cms_pages(:child)
page_two = @site.pages.create!(
parent: @page,
layout: @layout,
label: "test",
slug: "test"
)
assert_equal 0, page_one.position
assert_equal 1, page_two.position
r :put, reorder_comfy_admin_cms_site_pages_path(site_id: @site), params: {
order: [page_two.id, page_one.id]
}
assert_response :success
page_one.reload
page_two.reload
assert_equal 1, page_one.position
assert_equal 0, page_two.position
end
end
|
melvinsembrano/comfortable-mexican-sofa
|
test/controllers/comfy/admin/cms/pages_controller_test.rb
|
Ruby
|
mit
| 17,659
|
class Statistic
def initialize(shas = nil)
shas = shas.to_s.split(',')
@query_chain = if shas.present?
Commit.where(repository_id: Repository.where(access_token: shas).pluck(:id))
else
Commit
end
end
def to_hash
result = {}
[:pending, :discuss].each do |state|
query = @query_chain.send(state)
result[state] = {
count: query.count,
per_project: per_repo_count(query),
per_author: per_author_count(query),
overall_per_project: overall_per_repo(query),
overall_per_author: overall_per_author(query)
}
end
result
end
def overall_per_repo(query)
counts = Hash[query.group(:repository_id).count]
result = counts.map do |r_id, count|
[
Repository.find(r_id).full_name,
per_author_count(query.where(repository_id: r_id))
]
end.compact.sort {|a, b| b[1].values.sum <=> a[1].values.sum }
Hash[result]
end
def overall_per_author(query)
counts = Hash[query.group(:author_id).count]
result = counts.map do |author_id, count|
[
User.find(author_id).name,
per_repo_count(query.where(author_id: author_id))
]
end.compact.sort {|a, b| b[1].values.sum <=> a[1].values.sum }
Hash[result]
end
def per_repo_count(query)
counts = Hash[query.group(:repository_id).count]
result = counts.map do |r_id, count|
[
Repository.find(r_id).full_name,
count.to_i
]
end.compact.sort {|a, b| b[1] <=> a[1] }
Hash[result]
end
def per_author_count(query)
counts = Hash[query.group(:author_id).count]
result = counts.map do |author_id, count|
[
User.find(author_id).name,
count.to_i
]
end.compact.sort {|a, b| b[1] <=> a[1] }
Hash[result]
end
end
|
monterail/ghcr-api
|
app/services/statistic.rb
|
Ruby
|
mit
| 1,856
|
module Volt
# Included into ViewScope to provide processing for attributes
module AttributeScope
# Take the attributes and create any bindings
def process_attributes(tag_name, attributes)
new_attributes = attributes.dup
attributes.each_pair do |name, value|
if name[0..1] == 'e-'
process_event_binding(tag_name, new_attributes, name, value)
else
process_attribute(tag_name, new_attributes, name, value)
end
end
new_attributes
end
def process_event_binding(tag_name, attributes, name, value)
id = add_id_to_attributes(attributes)
event = name[2..-1]
if tag_name == 'a'
# For links, we need to add blank href to make it clickable.
attributes['href'] ||= ''
end
# Remove the e- attribute
attributes.delete(name)
save_binding(id, "lambda { |__p, __t, __c, __id| Volt::EventBinding.new(__p, __t, __c, __id, #{event.inspect}, Proc.new {|event| #{value} })}")
end
# Takes a string and splits on bindings, returns the string split on bindings
# and the number of bindings.
def binding_parts_and_count(value)
if value.is_a?(String)
parts = value.split(/(\{\{[^\}]+\}\})/).reject(&:blank?)
else
parts = ['']
end
binding_count = parts.count { |p| p[0] == '{' && p[1] == '{' && p[-2] == '}' && p[-1] == '}' }
[parts, binding_count]
end
def process_attribute(tag_name, attributes, attribute_name, value)
parts, binding_count = binding_parts_and_count(value)
# if this attribute has bindings
if binding_count > 0
# Setup an id
id = add_id_to_attributes(attributes)
if parts.size > 1
# Multiple bindings
add_multiple_attribute(tag_name, id, attribute_name, parts, value)
elsif parts.size == 1 && binding_count == 1
# A single binding
add_single_attribute(id, attribute_name, parts)
end
# Remove the attribute
attributes.delete(attribute_name)
end
end
# TODO: We should use a real parser for this
def getter_to_setter(getter)
getter = getter.strip.gsub(/\(\s*\)/, '')
# Check to see if this can be converted to a setter
if getter[0] =~ /^[a-z_]/ && getter[-1] != ')'
# Convert a getter into a setter
if getter.index('.') || getter.index('@')
prefix = ''
else
prefix = 'self.'
end
"#{prefix}#{getter}=(val)"
else
"raise \"could not auto generate setter for `#{getter}`\""
end
end
# Add an attribute binding on the tag, bind directly to the getter in the binding
def add_single_attribute(id, attribute_name, parts)
getter = parts[0][2...-2].strip
# if getter.index('@')
# raise "Bindings currently do not support instance variables"
# end
setter = getter_to_setter(getter)
save_binding(id, "lambda { |__p, __t, __c, __id| Volt::AttributeBinding.new(__p, __t, __c, __id, #{attribute_name.inspect}, Proc.new { #{getter} }, Proc.new { |val| #{setter} }) }")
end
def add_multiple_attribute(tag_name, id, attribute_name, parts, content)
case attribute_name
when 'checked', 'value'
if parts.size > 1
if tag_name == 'textarea'
fail "The content of text area's can not be bound to multiple bindings."
else
# Multiple values can not be passed to value or checked attributes.
fail "Multiple bindings can not be passed to a #{attribute_name} binding: #{parts.inspect}"
end
end
end
string_template_renderer_path = add_string_template_renderer(content)
save_binding(id, "lambda { |__p, __t, __c, __id| Volt::AttributeBinding.new(__p, __t, __c, __id, #{attribute_name.inspect}, Proc.new { Volt::StringTemplateRender.new(__p, __c, #{string_template_renderer_path.inspect}) }) }")
end
def add_string_template_renderer(content)
path = @path + "/_rv#{@binding_number}"
new_handler = ViewHandler.new(path, false)
@binding_number += 1
SandlebarsParser.new(content, new_handler)
# Close out the last scope
new_handler.scope.last.close_scope
# Copy in the templates from the new handler
new_handler.templates.each_pair do |key, value|
@handler.templates[key] = value
end
path
end
def add_id_to_attributes(attributes)
id = attributes['id'] ||= "id#{@binding_number}"
@binding_number += 1
id.to_s
end
def attribute_string(attributes)
attr_str = attributes.map { |v| "#{v[0]}=\"#{v[1]}\"" }.join(' ')
if attr_str.size > 0
# extra space
attr_str = ' ' + attr_str
end
attr_str
end
end
end
|
bglusman/volt
|
lib/volt/server/html_parser/attribute_scope.rb
|
Ruby
|
mit
| 4,894
|
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Module: Erubis::InterpolationEnhancer</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<link rel="stylesheet" href="../.././rdoc-style.css" type="text/css" media="screen" />
<script type="text/javascript">
// <![CDATA[
function popupCode( url ) {
window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400")
}
function toggleCode( id ) {
if ( document.getElementById )
elem = document.getElementById( id );
else if ( document.all )
elem = eval( "document.all." + id );
else
return false;
elemStyle = elem.style;
if ( elemStyle.display != "block" ) {
elemStyle.display = "block"
} else {
elemStyle.display = "none"
}
return true;
}
// Make codeblocks hidden by default
document.writeln( "<style type=\"text/css\">div.method-source-code { display: none }</style>" )
// ]]>
</script>
</head>
<body>
<div id="classHeader">
<table class="header-table">
<tr class="top-aligned-row">
<td><strong>Module</strong></td>
<td class="class-name-in-header">Erubis::InterpolationEnhancer</td>
</tr>
<tr class="top-aligned-row">
<td><strong>In:</strong></td>
<td>
<a href="../../files/erubis/enhancer_rb.html">
erubis/enhancer.rb
</a>
<br />
</td>
</tr>
</table>
</div>
<!-- banner header -->
<div id="bodyContent">
<div id="contextContent">
<div id="description">
<p>
convert "<h1><%=title%></h1>" into "_buf
<< %Q`<h1>#{title}</h1>`"
</p>
<p>
this is only for <a href="Eruby.html">Eruby</a>.
</p>
</div>
</div>
<div id="method-list">
<h3 class="section-bar">Methods</h3>
<div class="name-list">
<a href="#M000200">_add_text_to_str</a>
<a href="#M000201">add_expr_escaped</a>
<a href="#M000202">add_expr_literal</a>
<a href="#M000199">add_text</a>
<a href="#M000198">convert_input</a>
</div>
</div>
</div>
<!-- if includes -->
<div id="section">
<!-- if method_list -->
<div id="methods">
<h3 class="section-bar">Public Instance methods</h3>
<div id="method-M000200" class="method-detail">
<a name="M000200"></a>
<div class="method-heading">
<a href="#M000200" class="method-signature">
<span class="method-name">_add_text_to_str</span><span class="method-args">(str, text)</span>
</a>
</div>
<div class="method-description">
<p><a class="source-toggle" href="#"
onclick="toggleCode('M000200-source');return false;">[Source]</a></p>
<div class="method-source-code" id="M000200-source">
<pre>
<span class="ruby-comment cmt"># File erubis/enhancer.rb, line 664</span>
<span class="ruby-keyword kw">def</span> <span class="ruby-identifier">_add_text_to_str</span>(<span class="ruby-identifier">str</span>, <span class="ruby-identifier">text</span>)
<span class="ruby-keyword kw">return</span> <span class="ruby-keyword kw">if</span> <span class="ruby-operator">!</span><span class="ruby-identifier">text</span> <span class="ruby-operator">||</span> <span class="ruby-identifier">text</span>.<span class="ruby-identifier">empty?</span>
<span class="ruby-identifier">text</span>.<span class="ruby-identifier">gsub!</span>(<span class="ruby-regexp re">/['\#\\]/</span>, <span class="ruby-value str">'\\\\\&'</span>)
<span class="ruby-identifier">str</span> <span class="ruby-operator"><<</span> <span class="ruby-identifier">text</span>
<span class="ruby-keyword kw">end</span>
</pre>
</div>
</div>
</div>
<div id="method-M000201" class="method-detail">
<a name="M000201"></a>
<div class="method-heading">
<a href="#M000201" class="method-signature">
<span class="method-name">add_expr_escaped</span><span class="method-args">(str, code)</span>
</a>
</div>
<div class="method-description">
<p><a class="source-toggle" href="#"
onclick="toggleCode('M000201-source');return false;">[Source]</a></p>
<div class="method-source-code" id="M000201-source">
<pre>
<span class="ruby-comment cmt"># File erubis/enhancer.rb, line 670</span>
<span class="ruby-keyword kw">def</span> <span class="ruby-identifier">add_expr_escaped</span>(<span class="ruby-identifier">str</span>, <span class="ruby-identifier">code</span>)
<span class="ruby-identifier">str</span> <span class="ruby-operator"><<</span> <span class="ruby-node">"\#{#{escaped_expr(code)}}"</span>
<span class="ruby-keyword kw">end</span>
</pre>
</div>
</div>
</div>
<div id="method-M000202" class="method-detail">
<a name="M000202"></a>
<div class="method-heading">
<a href="#M000202" class="method-signature">
<span class="method-name">add_expr_literal</span><span class="method-args">(str, code)</span>
</a>
</div>
<div class="method-description">
<p><a class="source-toggle" href="#"
onclick="toggleCode('M000202-source');return false;">[Source]</a></p>
<div class="method-source-code" id="M000202-source">
<pre>
<span class="ruby-comment cmt"># File erubis/enhancer.rb, line 674</span>
<span class="ruby-keyword kw">def</span> <span class="ruby-identifier">add_expr_literal</span>(<span class="ruby-identifier">str</span>, <span class="ruby-identifier">code</span>)
<span class="ruby-identifier">str</span> <span class="ruby-operator"><<</span> <span class="ruby-node">"\#{#{code}}"</span>
<span class="ruby-keyword kw">end</span>
</pre>
</div>
</div>
</div>
<div id="method-M000199" class="method-detail">
<a name="M000199"></a>
<div class="method-heading">
<a href="#M000199" class="method-signature">
<span class="method-name">add_text</span><span class="method-args">(src, text)</span>
</a>
</div>
<div class="method-description">
<p><a class="source-toggle" href="#"
onclick="toggleCode('M000199-source');return false;">[Source]</a></p>
<div class="method-source-code" id="M000199-source">
<pre>
<span class="ruby-comment cmt"># File erubis/enhancer.rb, line 653</span>
<span class="ruby-keyword kw">def</span> <span class="ruby-identifier">add_text</span>(<span class="ruby-identifier">src</span>, <span class="ruby-identifier">text</span>)
<span class="ruby-keyword kw">return</span> <span class="ruby-keyword kw">if</span> <span class="ruby-operator">!</span><span class="ruby-identifier">text</span> <span class="ruby-operator">||</span> <span class="ruby-identifier">text</span>.<span class="ruby-identifier">empty?</span>
<span class="ruby-comment cmt">#src << " _buf << %Q`" << text << "`;"</span>
<span class="ruby-keyword kw">if</span> <span class="ruby-identifier">text</span>[<span class="ruby-value">-1</span>] <span class="ruby-operator">==</span> <span class="ruby-value">?\n</span>
<span class="ruby-identifier">text</span>[<span class="ruby-value">-1</span>] = <span class="ruby-value str">"\\n"</span>
<span class="ruby-identifier">src</span> <span class="ruby-operator"><<</span> <span class="ruby-value str">" _buf << %Q`"</span> <span class="ruby-operator"><<</span> <span class="ruby-identifier">text</span> <span class="ruby-operator"><<</span> <span class="ruby-value str">"`\n"</span>
<span class="ruby-keyword kw">else</span>
<span class="ruby-identifier">src</span> <span class="ruby-operator"><<</span> <span class="ruby-value str">" _buf << %Q`"</span> <span class="ruby-operator"><<</span> <span class="ruby-identifier">text</span> <span class="ruby-operator"><<</span> <span class="ruby-value str">"`;"</span>
<span class="ruby-keyword kw">end</span>
<span class="ruby-keyword kw">end</span>
</pre>
</div>
</div>
</div>
<div id="method-M000198" class="method-detail">
<a name="M000198"></a>
<div class="method-heading">
<a href="#M000198" class="method-signature">
<span class="method-name">convert_input</span><span class="method-args">(src, input)</span>
</a>
</div>
<div class="method-description">
<p><a class="source-toggle" href="#"
onclick="toggleCode('M000198-source');return false;">[Source]</a></p>
<div class="method-source-code" id="M000198-source">
<pre>
<span class="ruby-comment cmt"># File erubis/enhancer.rb, line 598</span>
<span class="ruby-keyword kw">def</span> <span class="ruby-identifier">convert_input</span>(<span class="ruby-identifier">src</span>, <span class="ruby-identifier">input</span>)
<span class="ruby-identifier">pat</span> = <span class="ruby-ivar">@pattern</span>
<span class="ruby-identifier">regexp</span> = <span class="ruby-identifier">pat</span>.<span class="ruby-identifier">nil?</span> <span class="ruby-operator">||</span> <span class="ruby-identifier">pat</span> <span class="ruby-operator">==</span> <span class="ruby-value str">'<% %>'</span> <span class="ruby-operator">?</span> <span class="ruby-constant">Basic</span><span class="ruby-operator">::</span><span class="ruby-constant">Converter</span><span class="ruby-operator">::</span><span class="ruby-constant">DEFAULT_REGEXP</span> <span class="ruby-operator">:</span> <span class="ruby-identifier">pattern_regexp</span>(<span class="ruby-identifier">pat</span>)
<span class="ruby-identifier">pos</span> = <span class="ruby-value">0</span>
<span class="ruby-identifier">is_bol</span> = <span class="ruby-keyword kw">true</span> <span class="ruby-comment cmt"># is beginning of line</span>
<span class="ruby-identifier">str</span> = <span class="ruby-value str">''</span>
<span class="ruby-identifier">input</span>.<span class="ruby-identifier">scan</span>(<span class="ruby-identifier">regexp</span>) <span class="ruby-keyword kw">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">indicator</span>, <span class="ruby-identifier">code</span>, <span class="ruby-identifier">tailch</span>, <span class="ruby-identifier">rspace</span><span class="ruby-operator">|</span>
<span class="ruby-identifier">match</span> = <span class="ruby-constant">Regexp</span>.<span class="ruby-identifier">last_match</span>()
<span class="ruby-identifier">len</span> = <span class="ruby-identifier">match</span>.<span class="ruby-identifier">begin</span>(<span class="ruby-value">0</span>) <span class="ruby-operator">-</span> <span class="ruby-identifier">pos</span>
<span class="ruby-identifier">text</span> = <span class="ruby-identifier">input</span>[<span class="ruby-identifier">pos</span>, <span class="ruby-identifier">len</span>]
<span class="ruby-identifier">pos</span> = <span class="ruby-identifier">match</span>.<span class="ruby-identifier">end</span>(<span class="ruby-value">0</span>)
<span class="ruby-identifier">ch</span> = <span class="ruby-identifier">indicator</span> <span class="ruby-value">? </span><span class="ruby-identifier">indicator</span>[<span class="ruby-value">0</span>] <span class="ruby-operator">:</span> <span class="ruby-keyword kw">nil</span>
<span class="ruby-identifier">lspace</span> = <span class="ruby-identifier">ch</span> <span class="ruby-operator">==</span> <span class="ruby-value">?=</span> <span class="ruby-operator">?</span> <span class="ruby-keyword kw">nil</span> <span class="ruby-operator">:</span> <span class="ruby-identifier">detect_spaces_at_bol</span>(<span class="ruby-identifier">text</span>, <span class="ruby-identifier">is_bol</span>)
<span class="ruby-identifier">is_bol</span> = <span class="ruby-identifier">rspace</span> <span class="ruby-value">? </span><span class="ruby-keyword kw">true</span> <span class="ruby-operator">:</span> <span class="ruby-keyword kw">false</span>
<span class="ruby-identifier">_add_text_to_str</span>(<span class="ruby-identifier">str</span>, <span class="ruby-identifier">text</span>)
<span class="ruby-comment cmt">## * when '<%= %>', do nothing</span>
<span class="ruby-comment cmt">## * when '<% %>' or '<%# %>', delete spaces iff only spaces are around '<% %>'</span>
<span class="ruby-keyword kw">if</span> <span class="ruby-identifier">ch</span> <span class="ruby-operator">==</span> <span class="ruby-value">?=</span> <span class="ruby-comment cmt"># <%= %></span>
<span class="ruby-identifier">rspace</span> = <span class="ruby-keyword kw">nil</span> <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">tailch</span> <span class="ruby-operator">&&</span> <span class="ruby-operator">!</span><span class="ruby-identifier">tailch</span>.<span class="ruby-identifier">empty?</span>
<span class="ruby-identifier">str</span> <span class="ruby-operator"><<</span> <span class="ruby-identifier">lspace</span> <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">lspace</span>
<span class="ruby-identifier">add_expr</span>(<span class="ruby-identifier">str</span>, <span class="ruby-identifier">code</span>, <span class="ruby-identifier">indicator</span>)
<span class="ruby-identifier">str</span> <span class="ruby-operator"><<</span> <span class="ruby-identifier">rspace</span> <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">rspace</span>
<span class="ruby-keyword kw">elsif</span> <span class="ruby-identifier">ch</span> <span class="ruby-operator">==</span> <span class="ruby-value">?\#</span> <span class="ruby-comment cmt"># <%# %></span>
<span class="ruby-identifier">n</span> = <span class="ruby-identifier">code</span>.<span class="ruby-identifier">count</span>(<span class="ruby-value str">"\n"</span>) <span class="ruby-operator">+</span> (<span class="ruby-identifier">rspace</span> <span class="ruby-value">? </span><span class="ruby-value">1</span> <span class="ruby-operator">:</span> <span class="ruby-value">0</span>)
<span class="ruby-keyword kw">if</span> <span class="ruby-ivar">@trim</span> <span class="ruby-operator">&&</span> <span class="ruby-identifier">lspace</span> <span class="ruby-operator">&&</span> <span class="ruby-identifier">rspace</span>
<span class="ruby-identifier">add_text</span>(<span class="ruby-identifier">src</span>, <span class="ruby-identifier">str</span>)
<span class="ruby-identifier">str</span> = <span class="ruby-value str">''</span>
<span class="ruby-identifier">add_stmt</span>(<span class="ruby-identifier">src</span>, <span class="ruby-value str">"\n"</span> <span class="ruby-operator">*</span> <span class="ruby-identifier">n</span>)
<span class="ruby-keyword kw">else</span>
<span class="ruby-identifier">str</span> <span class="ruby-operator"><<</span> <span class="ruby-identifier">lspace</span> <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">lspace</span>
<span class="ruby-identifier">add_text</span>(<span class="ruby-identifier">src</span>, <span class="ruby-identifier">str</span>)
<span class="ruby-identifier">str</span> = <span class="ruby-value str">''</span>
<span class="ruby-identifier">add_stmt</span>(<span class="ruby-identifier">src</span>, <span class="ruby-value str">"\n"</span> <span class="ruby-operator">*</span> <span class="ruby-identifier">n</span>)
<span class="ruby-identifier">str</span> <span class="ruby-operator"><<</span> <span class="ruby-identifier">rspace</span> <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">rspace</span>
<span class="ruby-keyword kw">end</span>
<span class="ruby-keyword kw">else</span> <span class="ruby-comment cmt"># <% %></span>
<span class="ruby-keyword kw">if</span> <span class="ruby-ivar">@trim</span> <span class="ruby-operator">&&</span> <span class="ruby-identifier">lspace</span> <span class="ruby-operator">&&</span> <span class="ruby-identifier">rspace</span>
<span class="ruby-identifier">add_text</span>(<span class="ruby-identifier">src</span>, <span class="ruby-identifier">str</span>)
<span class="ruby-identifier">str</span> = <span class="ruby-value str">''</span>
<span class="ruby-identifier">add_stmt</span>(<span class="ruby-identifier">src</span>, <span class="ruby-node">"#{lspace}#{code}#{rspace}"</span>)
<span class="ruby-keyword kw">else</span>
<span class="ruby-identifier">str</span> <span class="ruby-operator"><<</span> <span class="ruby-identifier">lspace</span> <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">lspace</span>
<span class="ruby-identifier">add_text</span>(<span class="ruby-identifier">src</span>, <span class="ruby-identifier">str</span>)
<span class="ruby-identifier">str</span> = <span class="ruby-value str">''</span>
<span class="ruby-identifier">add_stmt</span>(<span class="ruby-identifier">src</span>, <span class="ruby-identifier">code</span>)
<span class="ruby-identifier">str</span> <span class="ruby-operator"><<</span> <span class="ruby-identifier">rspace</span> <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">rspace</span>
<span class="ruby-keyword kw">end</span>
<span class="ruby-keyword kw">end</span>
<span class="ruby-keyword kw">end</span>
<span class="ruby-comment cmt">#rest = $' || input # ruby1.8</span>
<span class="ruby-identifier">rest</span> = <span class="ruby-identifier">pos</span> <span class="ruby-operator">==</span> <span class="ruby-value">0</span> <span class="ruby-operator">?</span> <span class="ruby-identifier">input</span> <span class="ruby-operator">:</span> <span class="ruby-identifier">input</span>[<span class="ruby-identifier">pos</span><span class="ruby-operator">..</span><span class="ruby-value">-1</span>] <span class="ruby-comment cmt"># ruby1.9</span>
<span class="ruby-identifier">_add_text_to_str</span>(<span class="ruby-identifier">str</span>, <span class="ruby-identifier">rest</span>)
<span class="ruby-identifier">add_text</span>(<span class="ruby-identifier">src</span>, <span class="ruby-identifier">str</span>)
<span class="ruby-keyword kw">end</span>
</pre>
</div>
</div>
</div>
</div>
</div>
<div id="validator-badges">
<p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
</div>
</body>
</html>
|
netshade/erubis
|
doc-api/classes/Erubis/InterpolationEnhancer.html
|
HTML
|
mit
| 19,827
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
#if !NETSTANDARD2_0
using System.Windows.Data;
#endif
namespace ChoETL
{
public class ChoTypeConverter
{
public static readonly ChoTypeConverter Global = new ChoTypeConverter();
private readonly object _padLock = new object();
private readonly Dictionary<Type, object> _defaultTypeConverters = new Dictionary<Type, object>();
static ChoTypeConverter()
{
ChoTypeConverter.Global.Add(typeof(Boolean), new ChoBooleanConverter());
}
public void Clear()
{
lock (_padLock)
{
_defaultTypeConverters.Clear();
}
}
public void Remove(Type type)
{
ChoGuard.ArgumentNotNull(type, "Type");
lock (_padLock)
{
if (!_defaultTypeConverters.ContainsKey(type))
return;
_defaultTypeConverters.Remove(type);
}
}
public void Add(Type type, TypeConverter converter)
{
ChoGuard.ArgumentNotNull(type, "Type");
ChoGuard.ArgumentNotNull(converter, "Converter");
lock (_padLock)
{
Remove(type);
_defaultTypeConverters.Add(type, converter);
}
}
#if !NETSTANDARD2_0
public void Add(Type type, IValueConverter converter)
{
ChoGuard.ArgumentNotNull(type, "Type");
ChoGuard.ArgumentNotNull(converter, "Converter");
lock (_padLock)
{
Remove(type);
_defaultTypeConverters.Add(type, converter);
}
}
#endif
public void Add(Type type, IChoValueConverter converter)
{
ChoGuard.ArgumentNotNull(type, "Type");
ChoGuard.ArgumentNotNull(converter, "Converter");
lock (_padLock)
{
Remove(type);
_defaultTypeConverters.Add(type, converter);
}
}
public KeyValuePair<Type, object>[] GetAll()
{
lock (_padLock)
{
return _defaultTypeConverters.ToArray();
}
}
public bool Contains(Type type)
{
ChoGuard.ArgumentNotNull(type, "Type");
lock (_padLock)
{
return _defaultTypeConverters.ContainsKey(type);
}
}
public object GetConverter(Type type)
{
if (Contains(type))
return _defaultTypeConverters[type];
else
return null;
}
}
}
|
Cinchoo/ChoETL
|
src/ChoETL/ChoTypeConverter.cs
|
C#
|
mit
| 2,804
|
package com.jlubecki.qtest;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}
|
lubecjac/Q-Example
|
app/src/androidTest/java/com/jlubecki/qtest/ApplicationTest.java
|
Java
|
mit
| 341
|
/**
* @file tcp.c
* @brief TCP (Transmission Control Protocol)
*
* @section License
*
* Copyright (C) 2010-2015 Oryx Embedded SARL. All rights reserved.
*
* This file is part of CycloneTCP Open.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @author Oryx Embedded SARL (www.oryx-embedded.com)
* @version 1.6.0
**/
//Switch to the appropriate trace level
#define TRACE_LEVEL TCP_TRACE_LEVEL
//Dependencies
#include <string.h>
#include "core/net.h"
#include "core/socket.h"
#include "core/tcp.h"
#include "core/tcp_misc.h"
#include "core/tcp_timer.h"
#include "debug.h"
//Check TCP/IP stack configuration
#if (TCP_SUPPORT == ENABLED)
//Ephemeral ports are used for dynamic port assignment
static uint16_t tcpDynamicPort;
/**
* @brief TCP related initialization
* @return Error code
**/
error_t tcpInit(void)
{
//Reset ephemeral port number
tcpDynamicPort = 0;
//Successful initialization
return NO_ERROR;
}
/**
* @brief Get an ephemeral port number
* @return Ephemeral port
**/
uint16_t tcpGetDynamicPort(void)
{
uint16_t port;
//Retrieve current port number
port = tcpDynamicPort;
//Invalid port number?
if(port < SOCKET_EPHEMERAL_PORT_MIN || port > SOCKET_EPHEMERAL_PORT_MAX)
{
//Generate a random port number
port = SOCKET_EPHEMERAL_PORT_MIN + netGetRand() %
(SOCKET_EPHEMERAL_PORT_MAX - SOCKET_EPHEMERAL_PORT_MIN + 1);
}
//Next dynamic port to use
if(port < SOCKET_EPHEMERAL_PORT_MAX)
{
//Increment port number
tcpDynamicPort = port + 1;
}
else
{
//Wrap around if necessary
tcpDynamicPort = SOCKET_EPHEMERAL_PORT_MIN;
}
//Return an ephemeral port number
return port;
}
/**
* @brief Establish a TCP connection
* @param[in] socket Handle to an unconnected socket
* @return Error code
**/
error_t tcpConnect(Socket *socket)
{
error_t error;
uint_t event;
//Socket already connected?
if(socket->state != TCP_STATE_CLOSED)
return ERROR_ALREADY_CONNECTED;
//The user owns the socket
socket->ownedFlag = TRUE;
//Number of chunks that comprise the TX and the RX buffers
socket->txBuffer.maxChunkCount = arraysize(socket->txBuffer.chunk);
socket->rxBuffer.maxChunkCount = arraysize(socket->rxBuffer.chunk);
//Allocate transmit buffer
error = netBufferSetLength((NetBuffer *) &socket->txBuffer, socket->txBufferSize);
//Allocate receive buffer
if(!error)
error = netBufferSetLength((NetBuffer *) &socket->rxBuffer, socket->rxBufferSize);
//Failed to allocate memory?
if(error)
{
//Free any previously allocated memory
tcpDeleteControlBlock(socket);
//Report an error to the caller
return error;
}
//Default MSS value
socket->mss = MIN(TCP_DEFAULT_MSS, TCP_MAX_MSS);
//An initial send sequence number is selected
socket->iss = netGetRand();
//Initialize TCP control block
socket->sndUna = socket->iss;
socket->sndNxt = socket->iss + 1;
socket->rcvUser = 0;
socket->rcvWnd = socket->rxBufferSize;
//Default retransmission timeout
socket->rto = TCP_INITIAL_RTO;
//Send a SYN segment
error = tcpSendSegment(socket, TCP_FLAG_SYN, socket->iss, 0, 0, TRUE);
//Failed to send TCP segment?
if(error) return error;
//Switch to the SYN-SENT state
tcpChangeState(socket, TCP_STATE_SYN_SENT);
//Wait for the connection to be established
event = tcpWaitForEvents(socket, SOCKET_EVENT_CONNECTED |
SOCKET_EVENT_CLOSED, socket->timeout);
//Connection successfully established?
if(event == SOCKET_EVENT_CONNECTED)
return NO_ERROR;
//Failed to establish connection?
else if(event == SOCKET_EVENT_CLOSED)
return ERROR_CONNECTION_FAILED;
//Timeout exception?
else
return ERROR_TIMEOUT;
}
/**
* @brief Place a socket in the listening state
*
* Place a socket in a state in which it is listening for an incoming connection
*
* @param[in] socket Socket to place in the listening state
* @param[in] backlog backlog The maximum length of the pending connection queue.
* If this parameter is zero, then the default backlog value is used instead
* @return Error code
**/
error_t tcpListen(Socket *socket, uint_t backlog)
{
//Socket already connected?
if(socket->state != TCP_STATE_CLOSED)
return ERROR_ALREADY_CONNECTED;
//Set the size of the SYN queue
socket->synQueueSize = (backlog > 0) ? backlog : TCP_DEFAULT_SYN_QUEUE_SIZE;
//Limit the number of pending connections
socket->synQueueSize = MIN(socket->synQueueSize, TCP_MAX_SYN_QUEUE_SIZE);
//Place the socket in the listening state
tcpChangeState(socket, TCP_STATE_LISTEN);
//Successful processing
return NO_ERROR;
}
/**
* @brief Permit an incoming connection attempt on a TCP socket
* @param[in] socket Handle to a socket previously placed in a listening state
* @param[out] clientIpAddr IP address of the client
* @param[out] clientPort Port number used by the client
* @return Handle to the socket in which the actual connection is made
**/
Socket *tcpAccept(Socket *socket, IpAddr *clientIpAddr, uint16_t *clientPort)
{
error_t error;
Socket *newSocket;
TcpSynQueueItem *queueItem;
//Ensure the socket was previously placed in the listening state
if(tcpGetState(socket) != TCP_STATE_LISTEN)
return NULL;
//Enter critical section
osAcquireMutex(&socketMutex);
//Wait for an connection attempt
while(1)
{
//The SYN queue is empty?
if(!socket->synQueue)
{
//Set the events the application is interested in
socket->eventMask = SOCKET_EVENT_RX_READY;
//Reset the event object
osResetEvent(&socket->event);
//Leave critical section
osReleaseMutex(&socketMutex);
//Wait until a SYN message is received from a client
osWaitForEvent(&socket->event, socket->timeout);
//Enter critical section
osAcquireMutex(&socketMutex);
}
//Check whether the queue is still empty
if(!socket->synQueue)
{
//Timeout error
newSocket = NULL;
//Exit immediately
break;
}
//Point to the first item in the receive queue
queueItem = socket->synQueue;
//Return the client IP address and port number
if(clientIpAddr)
*clientIpAddr = queueItem->srcAddr;
if(clientPort)
*clientPort = queueItem->srcPort;
//Leave critical section
osReleaseMutex(&socketMutex);
//Create a new socket to handle the incoming connection request
newSocket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_IP_PROTO_TCP);
//Enter critical section
osAcquireMutex(&socketMutex);
//Socket successfully created?
if(newSocket != NULL)
{
//The user owns the socket
newSocket->ownedFlag = TRUE;
//Inherit settings from the listening socket
newSocket->txBufferSize = socket->txBufferSize;
newSocket->rxBufferSize = socket->rxBufferSize;
//Number of chunks that comprise the TX and the RX buffers
newSocket->txBuffer.maxChunkCount = arraysize(newSocket->txBuffer.chunk);
newSocket->rxBuffer.maxChunkCount = arraysize(newSocket->rxBuffer.chunk);
//Allocate transmit buffer
error = netBufferSetLength((NetBuffer *) &newSocket->txBuffer, newSocket->txBufferSize);
//Check status code
if(!error)
{
//Allocate receive buffer
error = netBufferSetLength((NetBuffer *) &newSocket->rxBuffer, newSocket->rxBufferSize);
}
//Transmit and receive buffers successfully allocated?
if(!error)
{
//Bind the newly created socket to the appropriate interface
newSocket->interface = queueItem->interface;
//Bind the socket to the specified address
newSocket->localIpAddr = queueItem->destAddr;
newSocket->localPort = socket->localPort;
//Save the port number and the IP address of the remote host
newSocket->remoteIpAddr = queueItem->srcAddr;
newSocket->remotePort = queueItem->srcPort;
//Save the maximum segment size
newSocket->mss = queueItem->mss;
//Initialize TCP control block
newSocket->iss = netGetRand();
newSocket->irs = queueItem->isn;
newSocket->sndUna = newSocket->iss;
newSocket->sndNxt = newSocket->iss + 1;
newSocket->rcvNxt = newSocket->irs + 1;
newSocket->rcvUser = 0;
newSocket->rcvWnd = newSocket->rxBufferSize;
//Default retransmission timeout
newSocket->rto = TCP_INITIAL_RTO;
//Initial congestion window
newSocket->cwnd = MIN(TCP_INITIAL_WINDOW * newSocket->mss, newSocket->txBufferSize);
//Slow start threshold should be set arbitrarily high
newSocket->ssthresh = UINT16_MAX;
//Send a SYN ACK control segment
error = tcpSendSegment(newSocket, TCP_FLAG_SYN | TCP_FLAG_ACK,
newSocket->iss, newSocket->rcvNxt, 0, TRUE);
//TCP segment successfully sent?
if(!error)
{
//Remove the item from the SYN queue
socket->synQueue = queueItem->next;
//Deallocate memory buffer
memPoolFree(queueItem);
//Update the state of events
tcpUpdateEvents(socket);
//The connection state should be changed to SYN-RECEIVED
tcpChangeState(newSocket, TCP_STATE_SYN_RECEIVED);
//We are done...
break;
}
}
//Dispose the socket
tcpAbort(newSocket);
}
//Debug message
TRACE_WARNING("Cannot accept TCP connection!\r\n");
//Remove the item from the SYN queue
socket->synQueue = queueItem->next;
//Deallocate memory buffer
memPoolFree(queueItem);
//Wait for the next connection attempt
}
//Leave critical section
osReleaseMutex(&socketMutex);
//Return a handle to the newly created socket
return newSocket;
}
/**
* @brief Send data to a connected socket
* @param[in] socket Handle that identifies a connected socket
* @param[in] data Pointer to a buffer containing the data to be transmitted
* @param[in] length Number of bytes to be transmitted
* @param[out] written Actual number of bytes written (optional parameter)
* @param[in] flags Set of flags that influences the behavior of this function
* @return Error code
**/
error_t tcpSend(Socket *socket, const uint8_t *data,
size_t length, size_t *written, uint_t flags)
{
uint_t n;
uint_t totalLength;
uint_t event;
//Check whether the socket is in the listening state
if(socket->state == TCP_STATE_LISTEN)
return ERROR_NOT_CONNECTED;
//Actual number of bytes written
totalLength = 0;
//Send as much data as possible
do
{
//Wait until there is more room in the send buffer
event = tcpWaitForEvents(socket, SOCKET_EVENT_TX_READY, socket->timeout);
//A timeout exception occurred?
if(event != SOCKET_EVENT_TX_READY)
return ERROR_TIMEOUT;
//Check current TCP state
switch(socket->state)
{
//ESTABLISHED or CLOSE-WAIT state?
case TCP_STATE_ESTABLISHED:
case TCP_STATE_CLOSE_WAIT:
//The send buffer is now available for writing
break;
//LAST-ACK, FIN-WAIT-1, FIN-WAIT-2, CLOSING or TIME-WAIT state?
case TCP_STATE_LAST_ACK:
case TCP_STATE_FIN_WAIT_1:
case TCP_STATE_FIN_WAIT_2:
case TCP_STATE_CLOSING:
case TCP_STATE_TIME_WAIT:
//The connection is being closed
return ERROR_CONNECTION_CLOSING;
//CLOSED state?
default:
//The connection was reset by remote side?
return (socket->resetFlag) ? ERROR_CONNECTION_RESET : ERROR_NOT_CONNECTED;
}
//Determine the actual number of bytes in the send buffer
n = socket->sndUser + socket->sndNxt - socket->sndUna;
//Exit immediately if the transmission buffer is full (sanity check)
if(n >= socket->txBufferSize)
return ERROR_FAILURE;
//Number of bytes available for writing
n = socket->txBufferSize - n;
//Calculate the number of bytes to copy at a time
n = MIN(n, length - totalLength);
//Any data to copy?
if(n > 0)
{
//Copy user data to send buffer
tcpWriteTxBuffer(socket, socket->sndNxt + socket->sndUser, data, n);
//Update the number of data buffered but not yet sent
socket->sndUser += n;
//Advance data pointer
data += n;
//Update byte counter
totalLength += n;
//Total number of data that have been written
if(written != NULL)
*written = totalLength;
//Update TX events
tcpUpdateEvents(socket);
//To avoid a deadlock, it is necessary to have a timeout to force
//transmission of data, overriding the SWS avoidance algorithm. In
//practice, this timeout should seldom occur (see RFC 1122 4.2.3.4)
if(socket->sndUser == n)
tcpTimerStart(&socket->overrideTimer, TCP_OVERRIDE_TIMEOUT);
}
//The Nagle algorithm should be implemented to coalesce
//short segments (refer to RFC 1122 4.2.3.4)
tcpNagleAlgo(socket, flags);
//Send as much data as possible
} while(totalLength < length);
//The SOCKET_FLAG_WAIT_ACK flag causes the function to
//wait for acknowledgement from the remote side
if(flags & SOCKET_FLAG_WAIT_ACK)
{
//Wait for the data to be acknowledged
event = tcpWaitForEvents(socket, SOCKET_EVENT_TX_ACKED, socket->timeout);
//A timeout exception occurred?
if(event != SOCKET_EVENT_TX_ACKED)
return ERROR_TIMEOUT;
//The connection was closed before an acknowledgement was received?
if(socket->state != TCP_STATE_ESTABLISHED && socket->state != TCP_STATE_CLOSE_WAIT)
return ERROR_NOT_CONNECTED;
}
//Successful write operation
return NO_ERROR;
}
/**
* @brief Receive data from a connected socket
* @param[in] socket Handle that identifies a connected socket
* @param[out] data Buffer where to store the incoming data
* @param[in] size Maximum number of bytes that can be received
* @param[out] received Number of bytes that have been received
* @param[in] flags Set of flags that influences the behavior of this function
* @return Error code
**/
error_t tcpReceive(Socket *socket, uint8_t *data,
size_t size, size_t *received, uint_t flags)
{
uint_t i;
uint_t n;
uint_t event;
uint32_t seqNum;
systime_t timeout;
//Retrieve the break character code
char_t c = LSB(flags);
//No data has been read yet
*received = 0;
//Check whether the socket is in the listening state
if(socket->state == TCP_STATE_LISTEN)
return ERROR_NOT_CONNECTED;
//Read as much data as possible
while(*received < size)
{
//The SOCKET_FLAG_DONT_WAIT enables non-blocking operation
timeout = (flags & SOCKET_FLAG_DONT_WAIT) ? 0 : socket->timeout;
//Wait for data to be available for reading
event = tcpWaitForEvents(socket, SOCKET_EVENT_RX_READY, timeout);
//A timeout exception occurred?
if(event != SOCKET_EVENT_RX_READY)
return ERROR_TIMEOUT;
//Check current TCP state
switch(socket->state)
{
//ESTABLISHED, FIN-WAIT-1 or FIN-WAIT-2 state?
case TCP_STATE_ESTABLISHED:
case TCP_STATE_FIN_WAIT_1:
case TCP_STATE_FIN_WAIT_2:
//Sequence number of the first byte to read
seqNum = socket->rcvNxt - socket->rcvUser;
//Data is available in the receive buffer
break;
//CLOSE-WAIT, LAST-ACK, CLOSING or TIME-WAIT state?
case TCP_STATE_CLOSE_WAIT:
case TCP_STATE_LAST_ACK:
case TCP_STATE_CLOSING:
case TCP_STATE_TIME_WAIT:
//The user must be satisfied with data already on hand
if(!socket->rcvUser)
{
if(*received > 0)
return NO_ERROR;
else
return ERROR_END_OF_STREAM;
}
//Sequence number of the first byte to read
seqNum = (socket->rcvNxt - 1) - socket->rcvUser;
//Data is available in the receive buffer
break;
//CLOSED state?
default:
//The connection was reset by remote side?
if(socket->resetFlag)
return ERROR_CONNECTION_RESET;
//The connection has not yet been established?
if(!socket->closedFlag)
return ERROR_NOT_CONNECTED;
//The user must be satisfied with data already on hand
if(!socket->rcvUser)
{
if(*received > 0)
return NO_ERROR;
else
return ERROR_END_OF_STREAM;
}
//Sequence number of the first byte to read
seqNum = (socket->rcvNxt - 1) - socket->rcvUser;
//Data is available in the receive buffer
break;
}
//Sanity check
if(!socket->rcvUser)
return ERROR_FAILURE;
//Calculate the number of bytes to read at a time
n = MIN(socket->rcvUser, size - *received);
//Copy data from circular buffer
tcpReadRxBuffer(socket, seqNum, data, n);
//Read data until a break character is encountered?
if(flags & SOCKET_FLAG_BREAK_CHAR)
{
//Search for the specified break character
for(i = 0; i < n && data[i] != c; i++);
//Adjust the number of data to read
n = MIN(n, i + 1);
}
//Total number of data that have been read
*received += n;
//Remaining data still available in the receive buffer
socket->rcvUser -= n;
//Update the receive window
tcpUpdateReceiveWindow(socket);
//Update RX event state
tcpUpdateEvents(socket);
//The SOCKET_FLAG_BREAK_CHAR flag causes the function to stop reading
//data as soon as the specified break character is encountered
if(flags & SOCKET_FLAG_BREAK_CHAR)
{
//Check whether a break character has been found
if(data[n - 1] == c) break;
}
//The SOCKET_FLAG_WAIT_ALL flag causes the function to return
//only when the requested number of bytes have been read
else if(!(flags & SOCKET_FLAG_WAIT_ALL))
{
break;
}
//Advance data pointer
data += n;
}
//Successful read operation
return NO_ERROR;
}
/**
* @brief Shutdown gracefully reception, transmission, or both
*
* Note that socketShutdown() does not close the socket, and resources attached
* to the socket will not be freed until socketClose() is invoked
*
* @param[in] socket Handle to a socket
* @param[in] how Flag that describes what types of operation will no longer be allowed
* @return Error code
**/
error_t tcpShutdown(Socket *socket, uint_t how)
{
error_t error;
uint_t event;
//Disable transmission?
if(how == SOCKET_SD_SEND || how == SOCKET_SD_BOTH)
{
//Check current state
switch(socket->state)
{
//CLOSED or LISTEN state?
case TCP_STATE_CLOSED:
case TCP_STATE_LISTEN:
//Connection does not exist
return ERROR_NOT_CONNECTED;
//SYN-RECEIVED or ESTABLISHED state?
case TCP_STATE_SYN_RECEIVED:
case TCP_STATE_ESTABLISHED:
//Flush the send buffer
error = tcpSend(socket, NULL, 0, NULL, SOCKET_FLAG_NO_DELAY);
//Any error to report?
if(error) return error;
//Make sure all the data has been sent out
event = tcpWaitForEvents(socket, SOCKET_EVENT_TX_DONE, socket->timeout);
//Timeout error?
if(event != SOCKET_EVENT_TX_DONE)
return ERROR_TIMEOUT;
//Send a FIN segment
error = tcpSendSegment(socket, TCP_FLAG_FIN | TCP_FLAG_ACK,
socket->sndNxt, socket->rcvNxt, 0, TRUE);
//Failed to send FIN segment?
if(error) return error;
//Sequence number expected to be received
socket->sndNxt++;
//Switch to the FIN-WAIT1 state
tcpChangeState(socket, TCP_STATE_FIN_WAIT_1);
//Wait for the FIN to be acknowledged
event = tcpWaitForEvents(socket, SOCKET_EVENT_TX_SHUTDOWN, socket->timeout);
//Timeout interval elapsed?
if(event != SOCKET_EVENT_TX_SHUTDOWN)
return ERROR_TIMEOUT;
//Continue processing...
break;
//CLOSE-WAIT state?
case TCP_STATE_CLOSE_WAIT:
//Flush the send buffer
error = tcpSend(socket, NULL, 0, NULL, SOCKET_FLAG_NO_DELAY);
//Any error to report?
if(error) return error;
//Make sure all the data has been sent out
event = tcpWaitForEvents(socket, SOCKET_EVENT_TX_DONE, socket->timeout);
//Timeout error?
if(event != SOCKET_EVENT_TX_DONE)
return ERROR_TIMEOUT;
//Send a FIN segment
error = tcpSendSegment(socket, TCP_FLAG_FIN | TCP_FLAG_ACK,
socket->sndNxt, socket->rcvNxt, 0, TRUE);
//Failed to send FIN segment?
if(error) return error;
//Sequence number expected to be received
socket->sndNxt++;
//Switch to the LAST-ACK state
tcpChangeState(socket, TCP_STATE_LAST_ACK);
//Wait for the FIN to be acknowledged
event = tcpWaitForEvents(socket, SOCKET_EVENT_TX_SHUTDOWN, socket->timeout);
//Timeout interval elapsed?
if(event != SOCKET_EVENT_TX_SHUTDOWN)
return ERROR_TIMEOUT;
//Continue processing...
break;
//SYN-SENT, FIN-WAIT-1, FIN-WAIT-2, CLOSING,
//TIME-WAIT or LAST-ACK state?
default:
//Continue processing...
break;
}
}
//Disable reception?
if(how == SOCKET_SD_RECEIVE || how == SOCKET_SD_BOTH)
{
//Check current state
switch(socket->state)
{
//CLOSED or LISTEN state?
case TCP_STATE_CLOSED:
case TCP_STATE_LISTEN:
//Connection does not exist
return ERROR_NOT_CONNECTED;
//SYN-SENT, SYN-RECEIVED, ESTABLISHED, FIN-WAIT-1 or FIN-WAIT-2 state?
case TCP_STATE_SYN_SENT:
case TCP_STATE_SYN_RECEIVED:
case TCP_STATE_ESTABLISHED:
case TCP_STATE_FIN_WAIT_1:
case TCP_STATE_FIN_WAIT_2:
//Wait for a FIN to be received
event = tcpWaitForEvents(socket, SOCKET_EVENT_RX_SHUTDOWN, socket->timeout);
//Timeout interval elapsed?
if(event != SOCKET_EVENT_RX_SHUTDOWN)
return ERROR_TIMEOUT;
//A FIN segment has been received
break;
//CLOSING, TIME-WAIT, CLOSE-WAIT or LAST-ACK state?
default:
//A FIN segment has already been received
break;
}
}
//Successful operation
return NO_ERROR;
}
/**
* @brief Abort an existing TCP connection
* @param[in] socket Handle identifying the socket to close
* @return Error code
**/
error_t tcpAbort(Socket *socket)
{
error_t error;
//Check current state
switch(socket->state)
{
//SYN-RECEIVED, ESTABLISHED, FIN-WAIT-1
//FIN-WAIT-2 or CLOSE-WAIT state?
case TCP_STATE_SYN_RECEIVED:
case TCP_STATE_ESTABLISHED:
case TCP_STATE_FIN_WAIT_1:
case TCP_STATE_FIN_WAIT_2:
case TCP_STATE_CLOSE_WAIT:
//Send a reset segment
error = tcpSendSegment(socket, TCP_FLAG_RST, socket->sndNxt, 0, 0, FALSE);
//Enter CLOSED state
tcpChangeState(socket, TCP_STATE_CLOSED);
//Delete TCB
tcpDeleteControlBlock(socket);
//Mark the socket as closed
socket->type = SOCKET_TYPE_UNUSED;
//Return status code
return error;
//TIME-WAIT state?
case TCP_STATE_TIME_WAIT:
#if (TCP_2MSL_TIMER > 0)
//The user doe not own the socket anymore...
socket->ownedFlag = FALSE;
//TCB will be deleted and socket will be closed
//when the 2MSL timer will elapse
return NO_ERROR;
#else
//Enter CLOSED state
tcpChangeState(socket, TCP_STATE_CLOSED);
//Delete TCB
tcpDeleteControlBlock(socket);
//Mark the socket as closed
socket->type = SOCKET_TYPE_UNUSED;
//No error to report
return NO_ERROR;
#endif
//Any other state?
default:
//Enter CLOSED state
tcpChangeState(socket, TCP_STATE_CLOSED);
//Delete TCB
tcpDeleteControlBlock(socket);
//Mark the socket as closed
socket->type = SOCKET_TYPE_UNUSED;
//No error to report
return NO_ERROR;
}
}
/**
* @brief Get the current state of the TCP FSM
* @param[in] socket Handle identifying the socket
* @return TCP FSM state
**/
TcpState tcpGetState(Socket *socket)
{
TcpState state;
//Enter critical section
osAcquireMutex(&socketMutex);
//Get TCP FSM current state
state = socket->state;
//Leave critical section
osReleaseMutex(&socketMutex);
//Return current state
return state;
}
/**
* @brief Kill the oldest socket in the TIME-WAIT state
* @return Handle identyfying the oldest TCP connection in the TIME-WAIT state.
* NULL is returned if no socket is currently in the TIME-WAIT state
**/
Socket *tcpKillOldestConnection(void)
{
uint_t i;
Socket *socket;
Socket *oldestSocket;
//Keep track of the oldest socket in the TIME-WAIT state
oldestSocket = NULL;
//Loop through socket descriptors
for(i = 0; i < SOCKET_MAX_COUNT; i++)
{
//Point to the current socket descriptor
socket = &socketTable[i];
//TCP connection found?
if(socket->type == SOCKET_TYPE_STREAM)
{
//Check current state
if(socket->state == TCP_STATE_TIME_WAIT)
{
//Keep track of the oldest socket in the TIME-WAIT state
if(oldestSocket == NULL)
{
//Save socket handle
oldestSocket = socket;
}
else if(timeCompare(socket->timeWaitTimer.startTime,
oldestSocket->timeWaitTimer.startTime) < 0)
{
//Save socket handle
oldestSocket = socket;
}
}
}
}
//Any connection in the TIME-WAIT state?
if(oldestSocket != NULL)
{
//Enter CLOSED state
tcpChangeState(oldestSocket, TCP_STATE_CLOSED);
//Delete TCB
tcpDeleteControlBlock(oldestSocket);
//Mark the socket as closed
oldestSocket->type = SOCKET_TYPE_UNUSED;
}
//The oldest connection in the TIME-WAIT state can be reused
//when the socket table runs out of space
return oldestSocket;
}
#endif
|
Velleman/VM204-Firmware
|
cyclone_tcp/core/tcp.c
|
C
|
mit
| 27,591
|
/*!
* CanJS - 2.2.5
* http://canjs.com/
* Copyright (c) 2015 Bitovi
* Wed, 22 Apr 2015 15:03:29 GMT
* Licensed MIT
*/
/*can@2.2.5#view/elements*/
var can = require('../util/util.js');
require('./view.js');
var doc = typeof document !== 'undefined' ? document : null;
var selectsCommentNodes = doc && function () {
return can.$(document.createComment('~')).length === 1;
}();
var elements = {
tagToContentPropMap: {
option: doc && 'textContent' in document.createElement('option') ? 'textContent' : 'innerText',
textarea: 'value'
},
attrMap: can.attr.map,
attrReg: /([^\s=]+)[\s]*=[\s]*/,
defaultValue: can.attr.defaultValue,
tagMap: {
'': 'span',
colgroup: 'col',
table: 'tbody',
tr: 'td',
ol: 'li',
ul: 'li',
tbody: 'tr',
thead: 'tr',
tfoot: 'tr',
select: 'option',
optgroup: 'option'
},
reverseTagMap: {
col: 'colgroup',
tr: 'tbody',
option: 'select',
td: 'tr',
th: 'tr',
li: 'ul'
},
getParentNode: function (el, defaultParentNode) {
return defaultParentNode && el.parentNode.nodeType === 11 ? defaultParentNode : el.parentNode;
},
setAttr: can.attr.set,
getAttr: can.attr.get,
removeAttr: can.attr.remove,
contentText: function (text) {
if (typeof text === 'string') {
return text;
}
if (!text && text !== 0) {
return '';
}
return '' + text;
},
after: function (oldElements, newFrag) {
var last = oldElements[oldElements.length - 1];
if (last.nextSibling) {
can.insertBefore(last.parentNode, newFrag, last.nextSibling);
} else {
can.appendChild(last.parentNode, newFrag);
}
},
replace: function (oldElements, newFrag) {
elements.after(oldElements, newFrag);
if (can.remove(can.$(oldElements)).length < oldElements.length && !selectsCommentNodes) {
can.each(oldElements, function (el) {
if (el.nodeType === 8) {
el.parentNode.removeChild(el);
}
});
}
}
};
can.view.elements = elements;
module.exports = elements;
|
tka/goyangi
|
frontend/canjs/static/bower_components/canjs/cjs/view/elements.js
|
JavaScript
|
mit
| 2,542
|
import Resolver from 'ember/resolver';
var CustomResolver = Resolver.extend({
moduleNameLookupPatterns: Ember.computed(function() {
var defaults = this._super();
return defaults.concat([
this.podBasedComponentsInResource
]);
}),
podBasedComponentsInResource: function(parsedName) {
var podPrefix = this.namespace.podModulePrefix || this.namespace.modulePrefix;
if (parsedName.type === 'component' || parsedName.fullNameWithoutType.match(/^components/)) {
var nameWithoutComponent = parsedName.fullNameWithoutType.replace(/components\//, '');
var slash = nameWithoutComponent.lastIndexOf('/');
if (slash > 0) {
podPrefix = podPrefix + "/" + nameWithoutComponent.substr(0, slash);
parsedName.fullNameWithoutType = nameWithoutComponent.substr(slash + 1);
return this.podBasedLookupWithPrefix(podPrefix, parsedName);
}
}
},
podBasedComponentsInSubdir: function(parsedName) {
var podPrefix = this.namespace.modulePrefix; // this.namespace.podModulePrefix || this.namespace.modulePrefix
podPrefix = podPrefix + '/components';
if (parsedName.type === 'component' || parsedName.fullNameWithoutType.match(/^components/)) {
return this.podBasedLookupWithPrefix(podPrefix, parsedName);
}
}
});
export default CustomResolver
|
unchartedcode/alternate-pod-structure
|
addon/resolver.js
|
JavaScript
|
mit
| 1,330
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="/favicon.ico">
<script src="../dist/js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/holder.min.js"></script>
<script src="js/ie10-viewport-bug-workaround.js"></script>
<title>CouchInn</title>
<!-- jQuery -->
<script src="../dist/js/jquery.js"></script>
<!-- Placed at the end of the document so the pages load faster
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')</script> -->
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<!-- Just to make our placeholder images work. Don't actually copy the next line! -->
<script src="js/holder.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="js/ie10-viewport-bug-workaround.js"></script>
<!-- Bootstrap core CSS -->
<link href="../dist/css/bootstrap.min.css" rel="stylesheet">
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<link href="../dist/css/ie10-viewport-bug-workaround.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="js/ie-emulation-modes-warning.js"></script>
<!-- Custom CSS -->
<link href="../dist/css/scrolling-nav.css" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type='text/javascript' src="../validacion.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<style type="text/css">
/* GLOBAL STYLES
-------------------------------------------------- */
/* Padding below the footer and lighter body text */
body {
padding-bottom: 40px;
color: #5a5a5a;
}
/* CUSTOMIZE THE NAVBAR
-------------------------------------------------- */
/* Special class on .container surrounding .navbar, used for positioning it into place. */
.navbar-wrapper {
position: absolute;
top: 0;
right: 0;
left: 0;
z-index: 20;
}
/* Flip around the padding for proper display in narrow viewports */
.navbar-wrapper > .container {
padding-right: 0;
padding-left: 0;
}
.navbar-wrapper .navbar {
padding-right: 15px;
padding-left: 15px;
}
.navbar-wrapper .navbar .container {
width: auto;
}
/* CUSTOMIZE THE CAROUSEL
-------------------------------------------------- */
/* Carousel base class */
.carousel {
height: 500px;
margin-bottom: 60px;
}
/* Since positioning the image, we need to help out the caption */
.carousel-caption {
z-index: 10;
}
/* Declare heights because of positioning of img element */
.carousel .item {
height: 500px;
background-color: #777;
}
.carousel-inner > .item > img {
position: absolute;
top: 0;
left: 0;
min-width: 100%;
height: 500px;
}
/* MARKETING CONTENT
-------------------------------------------------- */
/* Center align the text within the three columns below the carousel */
.marketing .col-lg-4 {
margin-bottom: 20px;
text-align: center;
}
.marketing h2 {
font-weight: normal;
}
.marketing .col-lg-4 p {
margin-right: 10px;
margin-left: 10px;
}
/* Featurettes
------------------------- */
.featurette-divider {
margin: 30px 0; /* Space out the Bootstrap <hr> more */
}
.row-featurette{
background: #EAFAF1;
}
/* Thin out the marketing headings */
.featurette-heading {
font-weight: 300;
line-height: 1;
letter-spacing: -1px;
}
/* RESPONSIVE CSS
-------------------------------------------------- */
@media (min-width: 768px) {
/* Navbar positioning foo */
.navbar-wrapper {
margin-top: 20px;
}
.navbar-wrapper .container {
padding-right: 15px;
padding-left: 15px;
}
.navbar-wrapper .navbar {
padding-right: 130px;
padding-left: 130px;
padding-top: 0px;
padding-bottom: 5px;
}
/* The navbar becomes detached from the top, so we round the corners */
.navbar-wrapper .navbar {
border-radius: 4px;
}
/* Bump up size of carousel content */
.carousel-caption p {
margin-bottom: 20px;
font-size: 21px;
line-height: 1.4;
}
.featurette-heading {
font-size: 25px;
margin-left: 15px;
}
.lead {
font-size: 16px;
margin-left: 15px;
}
.text-muted{
margin-left: 15px;
}
}
@media (min-width: 992px) {
.featurette-heading {
margin-top: 100px;
}
}
.experience{
background: #EAFAF1;
}
.btn-lg{
background-color: #2ECC71;
color: white;
}
.title{
font-family: "Gabriola";
}
</style>
</head>
<!-- NAVBAR
==================================================
VER EL USO DEL BODY
-->
<body>
<div class="navbar-wrapper">
<div class="container">
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<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 page-scroll" href="#"> <img src="../images/couchinn.png" class="img-responsive" alt="CouchInn" width="169" height="136"> </a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="#about">Sobre nosotros</a></li>
<li><a href="#preguntas">Preguntas frecuentes</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><?php
$nombre = $user->nombre;
echo $nombre?><span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="../index.php/couchs/publicar">Publicar couch</a></li>
<li><a href="#">Mis couchs</a></li>
<li><a href="#">Mis hospedajes</a></li>
<li><a href="../index.php/inicio/ver_perfil/">Ver perfil</a></li>
<li><a href="#">Reservas</a></li>
<li role="separator" class="divider"></li>
<!-- <li class="dropdown-header">Nav header</li> -->
<li><a href="../index.php/usuarios/cerrar_sesion">Salir</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
</div>
</div>
|
marcos09/CouchInn
|
application/views/header_premium.php
|
PHP
|
mit
| 7,763
|
<?php
namespace Cerad\Bundle\TournBundle\FormType\Schedule\Official;
/* ========================================================
* Copied from cerad1
* Not currently used
*/
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvents;
class AssignPersonSubscriber implements EventSubscriberInterface
{
private $factory;
public function __construct(FormFactoryInterface $factory, $officials)
{
$this->factory = $factory;
$this->officials = $officials;
}
public static function getSubscribedEvents()
{
// Tells the dispatcher that we want to listen on the form.pre_set_data
// event and that the preSetData method should be called.
return array(FormEvents::PRE_SET_DATA => 'preSetData');
}
public function preSetData(FormEvent $event)
{
$gamePerson = $event->getData();
$form = $event->getForm();
if (!$gamePerson) return;
// guid
$personId = $gamePerson->getPerson();
$statusPickList = array
(
'RequestAssignment' => 'Request Assignment',
'RequestRemoval' => 'Request Removal',
'AssignmentRequested' => 'Assignment Requested',
'AssignmentApproved' => 'Assignment Approved',
);
$officialsPickList = array();
if ($personId) $emptyValue = null;
else
{
$emptyValue = 'Select Your Name';
$statusPickList = array('RequestAssignment' => 'Request Assignment');
}
$matched = false;
foreach($this->officials as $official)
{
$officialsPickList[$official->getId()] = $official->getName();
if ($official->getId() == $personId) $matched = true;
}
if ($personId && !$matched)
{
// Someone not in officials is currently assigned
$officialsPickList = array($personId => $gamePerson->getName());
$emptyValue = false;
$status = $gamePerson->getStatus();
// Because of error in batch update
if (!$status) $status = 'AssignmentRequested';
if (isset($statusPickList[$status])) $statusDesc = $statusPickList[$status];
else $statusDesc = $status;
$statusPickList = array($status => $statusDesc);
}
if ($personId && $matched)
{
//$officialsPickList = array($personId => $gamePerson->getName());
$emptyValue = false;
$statusPickList = array
(
'RequestRemoval' => 'Request Removal',
'AssignmentRequested' => 'Assignment Requested',
'AssignmentApproved' => 'Assignment Approved',
);
}
$form->add($this->factory->createNamed('personx','choice', null, array(
'label' => 'Person',
'required' => false,
'empty_value' => $emptyValue,
'empty_data' => false,
'auto_initialize' => false,
'choices' => $officialsPickList,
)));
// Mess with state
$status = $gamePerson->getStatus();
if (!$status) $status = 'RequestAssignment';
$form->add($this->factory->createNamed('statusx','choice', null, array(
'label' => 'Status',
'required' => false,
'empty_value' => false,
'empty_data' => false,
'choices' => $statusPickList,
'auto_initialize' => false,
)));
// Done
return;
}
}
class AssignPersonFormType extends AbstractType
{
public function getName() { return 'schedule_referee_assign_person'; }
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Cerad\Bundle\GameBundle\Entity\GamePerson',
));
}
public function __construct($officials)
{
$this->officials = $officials;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('role', 'text', array(
'attr' => array('size' => 10),
'read_only' => true,
));
$subscriber = new AssignPersonSubscriber($builder->getFormFactory(),$this->officials);
$builder->addEventSubscriber($subscriber);
}
}
class AssignFormType extends AbstractType
{
public function getName() { return 'schedule_referee_assign'; }
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Cerad\Bundle\GameBundle\Entity\Game',
));
}
public function __construct($manager = null)
{
$this->manager = $manager;
}
protected $manager;
protected $officials;
public function setOfficials($officials)
{
$this->officials = $officials;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('persons', 'collection', array('type' => new AssignPersonFormType($this->officials)));
}
}
?>
|
cerad/cerad2
|
src/Cerad/Bundle/TournBundle/FormType/Schedule/Official/AssignFormType.php
|
PHP
|
mit
| 5,776
|
import { Routes, RouterModule } from '@angular/router';
import { StudentsHomeComponent } from './index';
import { StudentsComponent } from './index';
import { StudentsProfileComponent } from './index';
import { StudentsSponsorLettersComponent } from './index';
import { SponsorLettersAddComponent } from './index';
import { CanActivateViaStudentAuthGuard } from '../app.routing-guards';
const routes: Routes = [
{
path: 'students',
component: StudentsComponent,
canActivate: [CanActivateViaStudentAuthGuard],
children: [
{
path: '',
pathMatch: 'full',
component: StudentsHomeComponent
},
{
path: 'home',
component: StudentsHomeComponent
},
{
path: 'profile/:id',
component: StudentsProfileComponent
},
{
path: 'sponsor-letters/:id',
component: StudentsSponsorLettersComponent
},
{
path: 'sponsor-letters-add/:studentId/:sponsorId',
component: SponsorLettersAddComponent
}
]
}
];
export const StudentsRouting = RouterModule.forChild(routes);
|
ckapilla/JovenesA-client
|
src/client/app/+students/students.routing.ts
|
TypeScript
|
mit
| 1,157
|
package info.arimateia.overwatchpocket.ui.heros;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import info.arimateia.overwatchpocket.R;
import info.arimateia.overwatchpocket.di.Injectable;
import info.arimateia.overwatchpocket.vo.Hero;
/**
* Created by felipets on 7/18/17.
*/
public class HerosFragment extends Fragment implements HerosView, Injectable{
@Inject
IHerosPresenter presenter;
private RecyclerView listHeros;
private HerosAdapter adapter;
private ProgressDialog progressDialog;
public static HerosFragment newInstance() {
HerosFragment fragment = new HerosFragment();
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_heros, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
listHeros = (RecyclerView)view.findViewById(R.id.list_heros);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
listHeros.setLayoutManager(layoutManager);
adapter = new HerosAdapter(new ArrayList<Hero>());
listHeros.setAdapter(adapter);
presenter.loadHeros();
}
@Override
public void showHeros(List<Hero> heros) {
adapter.addAll(heros);
}
@Override
public void showLoading() {
progressDialog = ProgressDialog.show(getContext(), getString(R.string.app_name), "Carregando...");
progressDialog.show();
}
@Override
public void hideLoading() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
|
felipearimateia/overwatch-pocket
|
app/src/main/java/info/arimateia/overwatchpocket/ui/heros/HerosFragment.java
|
Java
|
mit
| 2,251
|
{%extends 'base.html'%}
{%block page_content%}
<div class="post">
<h3 class="entry-title">
<a href="{{ url_for('post', posttitle=post.title) }}">{{ post.title }}</a>
</h3>
<div class="entry-meta">
<ul class="list-inline post-meta">
<li><a href="{{ url_for('about') }}">老官</a></li>
<li>{{ post.timestamp }}</li>
<li>on <a href="{{ url_for('category', name=Category.query.filter_by(id=post.category_id).first().name) }}">
{{ Category.query.filter_by(id = post.category_id).first().name }}</a></li>
{% for tag in post.tags %}
<li class="meta-tag">
<a href="{{ url_for('tag', name=tag.name) }}">{{ tag.name }}<span class="gap">,</span></a>
</li>
{% endfor %}
<a href="{{ url_for('reedit_post', posttitle=post.title)}}" class="edit-link">编辑</a>
{# <li>{{ post.views }}</li>#}
</ul>
</div>
<div class="entry-summary">
{% if post.content_html %}
<p>{{ post.content_html | safe }}</p>
{% else %}
<p>{{ post.content }}</p>
{% endif %}
</div>
</div>
{%endblock%}
|
guan080/personal_website
|
app/templates/post.html
|
HTML
|
mit
| 1,217
|
<?php
/**
* This file is part of the teamneusta/php-cli-magedev package.
*
* Copyright (c) 2017 neusta GmbH | Ein team neusta Unternehmen
*
* For the full copyright and license information, please view the LICENSE file that was distributed with this source code.
*
* @license https://opensource.org/licenses/mit-license MIT License
*/
namespace TeamNeusta\Magedev\Commands\Init;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use TeamNeusta\Magedev\Commands\AbstractCommand;
use TeamNeusta\Magedev\Runtime\Config;
use TeamNeusta\Magedev\Services\DockerService;
/**
* Class: PermissionsCommand.
*
* @see AbstractCommand
*/
class PermissionsCommand extends AbstractCommand
{
/**
* @var \TeamNeusta\Magedev\Runtime\Config
*/
protected $config;
/**
* @var \TeamNeusta\Magedev\Services\DockerService
*/
protected $dockerService;
/**
* __construct.
*
* @param \TeamNeusta\Magedev\Runtime\Config $config
* @param \TeamNeusta\Magedev\Services\DockerService $dockerService
*/
public function __construct(
\TeamNeusta\Magedev\Runtime\Config $config,
\TeamNeusta\Magedev\Services\DockerService $dockerService
) {
$this->config = $config;
$this->dockerService = $dockerService;
parent::__construct();
}
/**
* configure.
*/
protected function configure()
{
$this->setName('init:permissions');
$this->setDescription('set file and folder permissions for magento');
}
/**
* execute.
*
* @param InputInterface $input
* @param OutputInterface $output
*/
public function execute(InputInterface $input, OutputInterface $output)
{
$sourceFolder = $this->config->get('source_folder');
// use current folder, if it is the current one
if (empty($sourceFolder)) {
$sourceFolder = '.';
}
$commands = [
'mkdir -p /var/www/html',
'mkdir -p /var/www/.composer',
'mkdir -p /var/www/.ssh',
'mkdir -p /var/www/modules',
'mkdir -p /var/www/composer-cache',
'chown -R www-data:users /var/www/html',
'chown -R www-data:users /var/www/.composer',
'chown -R www-data:users /var/www/.ssh',
'chown -R www-data:users /var/www/modules',
'chown -R www-data:users /var/www/composer-cache',
// TODO: more fine grained permissions
'cd /var/www/html && chmod -R 775 '.$sourceFolder,
];
foreach ($commands as $cmd) {
$this->dockerService->execute(
$cmd,
[
'user' => 'root',
]
);
}
$this->dockerService->execute(
'usermod -u '.getmyuid().' mysql',
[
'user' => 'root',
'container' => 'mysql',
]
);
}
}
|
teamneusta/php-cli-magedev
|
src/Commands/Init/PermissionsCommand.php
|
PHP
|
mit
| 3,037
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class MagicIndex {
public int getMagicIndex(int [] nums) {
return getMagicIndex(nums, 0, nums.length - 1);
}
public int getMagicIndex(int [] nums, int s, int e) {
if (s > e) {
return -1;
} else {
int mid = (e + s) / 2;
if (nums[mid] > mid) {
return getMagicIndex(nums, s, mid - 1);
} else if (nums[mid] < mid) {
return getMagicIndex(nums, mid + 1, e);
} else {
return mid;
}
}
}
public static void main(String[] args) {
MagicIndex magic = new MagicIndex();
int [] nums = {-2, -1, 1, 3, 5};
System.out.println(magic.getMagicIndex(nums));
}
}
|
jonathasdantas/algorithms-data-structures
|
Interview-Preparation/Recursion-and-Dynamic-Programming/MagicIndex.java
|
Java
|
mit
| 857
|
import Element from '../../../shared/Element';
import Elements from '../../../shared/Elements';
import link from '../../../shared/link';
import { isNormalElement } from '../../../shared/helper';
export function createElements(elements, parent) {
elements.forEach(
element => appendElement(element, parent)
);
return parent;
}
export function appendElement(element, parent) {
parent.appendChild(createElement(element, parent));
}
export function createElement(element) {
const {props, tag, children} = element;
let node;
if (Element.isInstance(element)) {
node = document.createElement(tag);
createElements(children, node); // children
if (isNormalElement(element)) { // only link normal nodes
link(node, element);
}
setProps(node, {
tag, type: props.type , props
}); // props
} else if (Elements.isInstance(element)) {
const node = document.createDocumentFragment(); // package
createElements(element, node);
} else {
node = document.createTextNode(element);
}
return node;
}
const acceptValue = (tag) => ['input', 'textarea', 'option', 'select', 'progress'].includes(tag);
const mustUseProp = (tag, type, attr) => (
(attr === 'value' && acceptValue(tag)) && type !== 'button' ||
(attr === 'selected' && tag === 'option') ||
(attr === 'checked' && tag === 'input') ||
(attr === 'muted' && tag === 'video')
);
export function setProps(node, {tag, type, props}) {
Object.keys(props).forEach((name) => {
if (mustUseProp(tag, type, name)) {
node[name] = props[name];
} else {
node.setAttribute(name, props[name]);
}
});
}
export function setStyle(node, styles) {
Object.assign(node.style, styles);
}
|
daisyjs/daisy.js
|
src/platforms/browser/renderers/dom.js
|
JavaScript
|
mit
| 1,839
|
<html><body>
<h4>Windows 10 x64 (18362.418)</h4><br>
<h2>_EVENT_FILTER_HEADER</h2>
<font face="arial"> +0x000 Id : Uint2B<br>
+0x002 Version : UChar<br>
+0x003 Reserved : [5] UChar<br>
+0x008 InstanceId : Uint8B<br>
+0x010 Size : Uint4B<br>
+0x014 NextOffset : Uint4B<br>
</font></body></html>
|
epikcraw/ggool
|
public/Windows 10 x64 (18362.418)/_EVENT_FILTER_HEADER.html
|
HTML
|
mit
| 374
|
require 'stackbuilder/stacks/namespace'
require 'stackbuilder/stacks/machine_def'
class Stacks::Services::KafkaServer < Stacks::MachineDef
def to_enc
enc = super()
siblings = @virtual_service.children
enc.merge!('role::kafka_server' => {
'hostname' => @hostname,
'clusternodes' => siblings.map(&:prod_fqdn).sort,
'dependant_instances' => @virtual_service.dependant_instance_fqdns(location, [:prod], false)
})
enc
end
end
|
tim-group/stackbuilder
|
lib/stackbuilder/stacks/services/kafka_server.rb
|
Ruby
|
mit
| 526
|
body {
margin: 0;
padding: 0;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
a {
color: grey;
text-decoration: none;
}
.hero {
height: 200px;
margin-top: 50px;
text-align: center;
background-image: linear-gradient(to right, #880E4F 0, #C2185B 100%);
}
.hero p {
color: white;
opacity: .7;
text-shadow: 0 2px 0 rgba(0, 0, 0, 0.3);
}
h1 {
color: white;
padding: 1.5em 0 .5em 0;
}
section {
padding: 3em 0;
box-sizing: border-box;
}
code {
display: block;
width: 30%;
margin: 0 auto;
margin-top: 2em;
padding: 1em;
color: #E0E0E0;
border-radius: 3px;
box-sizing: border-box;
background-color: #263238;
}
code:first-child {
margin: 0 auto;
}
code span {
display: block;
}
code span.space {
height: 15px;
}
code span.tab {
text-indent: 20px;
}
code span.comment {
color: #757575;
}
code span.token {
display: inline;
color: #64B5F6;
}
code span.id {
display: inline;
color: #e57373;
}
code span.val {
display: inline;
color: #FFCC80;
}
.progressBar {
width: 30%;
margin: 0 auto;
}
.footer {
text-align: center;
}
/*# sourceMappingURL=style.css.map */
|
ErezNagar/Skinny-Progress-Bar
|
src/style.css
|
CSS
|
mit
| 1,140
|
#ifndef __EEPROM_H
#define __EEPROM_H
#include "ConfigApp.h"
#include "GenericTypeDefs.h"
#include "Compiler.h"
#define SPI_WRT_STATUS 0x01
#define SPI_WRITE 0x02
#define SPI_READ 0x03
#define SPI_DIS_WRT 0x04
#define SPI_RD_STATUS 0x05
#define SPI_EN_WRT 0x06
#define EEPROM_MAC_ADDR 0xFA
void EEPROMRead(BYTE *dest, BYTE addr, BYTE count);
#endif
|
kareen2707/TFG
|
CWSN LSI Node/Include/WirelessProtocols/EEPROM.h
|
C
|
mit
| 458
|
/*
Fontname: -FreeType-PC Senior-Medium-R-Normal--8-80-72-72-P-48-ISO10646-1
Copyright: TrueType conversion © 2001 codeman38.
Glyphs: 18/260
BBX Build Mode: 3
*/
const uint8_t u8g2_font_pcsenior_8n[237] U8X8_FONT_SECTION("u8g2_font_pcsenior_8n") =
"\22\3\3\3\4\4\1\2\5\10\7\0\376\6\376\6\377\0\0\0\0\0\324 \7\210\301\307\277\0*\15"
"\210\301\7\251\221\16!\232H\216\6+\14\210\301\207\211\205F\261\34\31\0,\11\210\301\307\7\261T\12"
"-\11\210\301\307f\307\31\0.\11\210\301\307\7\261\34\12/\11\210\301\325\347\70\12\0\60\20\210\301)"
"\311$\242\211\204E\62\22\325a\0\61\12\210\301\222\216u\264\303\0\62\16\210\301\241\211\304\302\241T$"
"\262\303\0\63\16\210\301\241\211\304\302\71@\244F\7\2\64\15\210\301\33\322$\42\245\253\224\16\2\65\15"
"\210\301\60\211\353\0\261H\215\16\4\66\15\210\301\32J\305\65\221\66:\20\0\67\13\210\301\60)K\225"
"\325\241\0\70\15\210\301\241\211\264\321D\332\350@\0\71\15\210\301\241\211\264\225\245\302\71\24\0:\14\210"
"\301\207\211\345X\304r(\0\0\0\0";
|
WiseLabCMU/gridballast
|
Source/framework/main/u8g2/tools/font/build/single_font_files/u8g2_font_pcsenior_8n.c
|
C
|
mit
| 1,021
|
# gwt-spielwiese
|
EriKra/gwt-spielwiese
|
README.md
|
Markdown
|
mit
| 16
|
@font-face {
font-family: 'DIN Web Light';
src: url('fonts/DINWeb-Light.eot');
src: url('fonts/DINWeb-Light.eot?#iefix') format('embedded-opentype'), url('fonts/DINWeb-Light.woff') format('woff');
font-weight: normal;
font-style: normal;
font-stretch: normal;
}
@font-face {
font-family: 'DIN Web LightItalic';
src: url('fonts/DINWeb-LightIta.eot');
src: url('fonts/DINWeb-LightIta.eot?#iefix') format('embedded-opentype'), url('fonts/DINWeb-LightIta.woff') format('woff');
font-weight: normal;
font-style: normal;
font-stretch: normal;
}
@font-face {
font-family: 'DIN Web Book';
src: url('fonts/DINWeb.eot');
src: url('fonts/DINWeb.eot?#iefix') format('embedded-opentype'), url('fonts/DINWeb.woff') format('woff');
font-weight: normal;
font-style: normal;
font-stretch: normal;
}
@font-face {
font-family: 'DIN Web BookItalic';
src: url('fonts/DINWeb-Ita.eot');
src: url('fonts/DINWeb-Ita.eot?#iefix') format('embedded-opentype'), url('fonts/DINWeb-Ita.woff') format('woff');
font-weight: normal;
font-style: normal;
font-stretch: normal;
}
@font-face {
font-family: 'DIN Web Medium';
src: url('fonts/DINWeb-Medium.eot');
src: url('fonts/DINWeb-Medium.eot?#iefix') format('embedded-opentype'), url('fonts/DINWeb-Medium.woff') format('woff');
font-weight: normal;
font-style: normal;
font-stretch: normal;
}
@font-face {
font-family: 'DIN Web MediumItalic';
src: url('fonts/DINWeb-MediumIta.eot');
src: url('fonts/DINWeb-MediumIta.eot?#iefix') format('embedded-opentype'), url('fonts/DINWeb-MediumIta.woff') format('woff');
font-weight: normal;
font-style: normal;
font-stretch: normal;
}
@font-face {
font-family: 'DIN Web Bold';
src: url('fonts/DINWeb-Bold.eot');
src: url('fonts/DINWeb-Bold.eot?#iefix') format('embedded-opentype'), url('fonts/DINWeb-Bold.woff') format('woff');
font-weight: normal;
font-style: normal;
font-stretch: normal;
}
@font-face {
font-family: 'DIN Web BoldItalic';
src: url('fonts/DINWeb-BoldIta.eot');
src: url('fonts/DINWeb-BoldIta.eot?#iefix') format('embedded-opentype'), url('fonts/DINWeb-BoldIta.woff') format('woff');
font-weight: normal;
font-style: normal;
font-stretch: normal;
}
@font-face {
font-family: 'DIN Web Black';
src: url('fonts/DINWeb-Black.eot');
src: url('fonts/DINWeb-Black.eot?#iefix') format('embedded-opentype'), url('fonts/DINWeb-Black.woff') format('woff');
font-weight: normal;
font-style: normal;
font-stretch: normal;
}
@font-face {
font-family: 'DIN Web BlackItalic';
src: url('fonts/DINWeb-BlackIta.eot');
src: url('fonts/DINWeb-BlackIta.eot?#iefix') format('embedded-opentype'), url('fonts/DINWeb-BlackIta.woff') format('woff');
font-weight: normal;
font-style: normal;
font-stretch: normal;
}
/*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */
/**
* 1. Set default font family to sans-serif.
* 2. Prevent iOS and IE text size adjust after device orientation change,
* without disabling user zoom.
*/
html {
font-family: sans-serif;
/* 1 */
-ms-text-size-adjust: 100%;
/* 2 */
-webkit-text-size-adjust: 100%;
/* 2 */
}
/**
* Remove default margin.
*/
body {
margin: 0;
}
/* HTML5 display definitions
========================================================================== */
/**
* Correct `block` display not defined for any HTML5 element in IE 8/9.
* Correct `block` display not defined for `details` or `summary` in IE 10/11
* and Firefox.
* Correct `block` display not defined for `main` in IE 11.
*/
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
menu,
nav,
section,
summary {
display: block;
}
/**
* 1. Correct `inline-block` display not defined in IE 8/9.
* 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera.
*/
audio,
canvas,
progress,
video {
display: inline-block;
/* 1 */
vertical-align: baseline;
/* 2 */
}
/**
* Prevent modern browsers from displaying `audio` without controls.
* Remove excess height in iOS 5 devices.
*/
audio:not([controls]) {
display: none;
height: 0;
}
/**
* Address `[hidden]` styling not present in IE 8/9/10.
* Hide the `template` element in IE 8/9/10/11, Safari, and Firefox < 22.
*/
[hidden],
template {
display: none;
}
/* Links
========================================================================== */
/**
* Remove the gray background color from active links in IE 10.
*/
a {
background-color: transparent;
}
/**
* Improve readability of focused elements when they are also in an
* active/hover state.
*/
a:active,
a:hover {
outline: 0;
}
/* Text-level semantics
========================================================================== */
/**
* Address styling not present in IE 8/9/10/11, Safari, and Chrome.
*/
abbr[title] {
border-bottom: 1px dotted;
}
/**
* Address style set to `bolder` in Firefox 4+, Safari, and Chrome.
*/
b,
strong {
font-weight: bold;
}
/**
* Address styling not present in Safari and Chrome.
*/
dfn {
font-style: italic;
}
/**
* Address variable `h1` font-size and margin within `section` and `article`
* contexts in Firefox 4+, Safari, and Chrome.
*/
h1 {
font-size: 2em;
margin: 0.67em 0;
}
/**
* Address styling not present in IE 8/9.
*/
mark {
background: #ff0;
color: #000;
}
/**
* Address inconsistent and variable font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` affecting `line-height` in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
/* Embedded content
========================================================================== */
/**
* Remove border when inside `a` element in IE 8/9/10.
*/
img {
border: 0;
}
/**
* Correct overflow not hidden in IE 9/10/11.
*/
svg:not(:root) {
overflow: hidden;
}
/* Grouping content
========================================================================== */
/**
* Address margin not present in IE 8/9 and Safari.
*/
figure {
margin: 1em 40px;
}
/**
* Address differences between Firefox and other browsers.
*/
hr {
box-sizing: content-box;
height: 0;
}
/**
* Contain overflow in all browsers.
*/
pre {
overflow: auto;
}
/**
* Address odd `em`-unit font size rendering in all browsers.
*/
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em;
}
/* Forms
========================================================================== */
/**
* Known limitation: by default, Chrome and Safari on OS X allow very limited
* styling of `select`, unless a `border` property is set.
*/
/**
* 1. Correct color not being inherited.
* Known issue: affects color of disabled elements.
* 2. Correct font properties not being inherited.
* 3. Address margins set differently in Firefox 4+, Safari, and Chrome.
*/
button,
input,
optgroup,
select,
textarea {
color: inherit;
/* 1 */
font: inherit;
/* 2 */
margin: 0;
/* 3 */
}
/**
* Address `overflow` set to `hidden` in IE 8/9/10/11.
*/
button {
overflow: visible;
}
/**
* Address inconsistent `text-transform` inheritance for `button` and `select`.
* All other form control elements do not inherit `text-transform` values.
* Correct `button` style inheritance in Firefox, IE 8/9/10/11, and Opera.
* Correct `select` style inheritance in Firefox.
*/
button,
select {
text-transform: none;
}
/**
* 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
* and `video` controls.
* 2. Correct inability to style clickable `input` types in iOS.
* 3. Improve usability and consistency of cursor style between image-type
* `input` and others.
*/
button,
html input[type="button"],
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button;
/* 2 */
cursor: pointer;
/* 3 */
}
/**
* Re-set default cursor for disabled elements.
*/
button[disabled],
html input[disabled] {
cursor: default;
}
/**
* Remove inner padding and border in Firefox 4+.
*/
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0;
}
/**
* Address Firefox 4+ setting `line-height` on `input` using `!important` in
* the UA stylesheet.
*/
input {
line-height: normal;
}
/**
* It's recommended that you don't attempt to style these elements.
* Firefox's implementation doesn't respect box-sizing, padding, or width.
*
* 1. Address box sizing set to `content-box` in IE 8/9/10.
* 2. Remove excess padding in IE 8/9/10.
*/
input[type="checkbox"],
input[type="radio"] {
box-sizing: border-box;
/* 1 */
padding: 0;
/* 2 */
}
/**
* Fix the cursor style for Chrome's increment/decrement buttons. For certain
* `font-size` values of the `input`, it causes the cursor style of the
* decrement button to change from `default` to `text`.
*/
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
height: auto;
}
/**
* 1. Address `appearance` set to `searchfield` in Safari and Chrome.
* 2. Address `box-sizing` set to `border-box` in Safari and Chrome.
*/
input[type="search"] {
-webkit-appearance: textfield;
/* 1 */
box-sizing: content-box;
/* 2 */
}
/**
* Remove inner padding and search cancel button in Safari and Chrome on OS X.
* Safari (but not Chrome) clips the cancel button when the search input has
* padding (and `textfield` appearance).
*/
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* Define consistent border, margin, and padding.
*/
fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.35em 0.625em 0.75em;
}
/**
* 1. Correct `color` not being inherited in IE 8/9/10/11.
* 2. Remove padding so people aren't caught out if they zero out fieldsets.
*/
legend {
border: 0;
/* 1 */
padding: 0;
/* 2 */
}
/**
* Remove default vertical scrollbar in IE 8/9/10/11.
*/
textarea {
overflow: auto;
}
/**
* Don't inherit the `font-weight` (applied by a rule above).
* NOTE: the default cannot safely be changed in Chrome and Safari on OS X.
*/
optgroup {
font-weight: bold;
}
/* Tables
========================================================================== */
/**
* Remove most spacing between table cells.
*/
table {
border-collapse: collapse;
border-spacing: 0;
}
td,
th {
padding: 0;
}
/* Grids! */
.container {
margin-right: auto;
margin-left: auto;
padding: 0 20px;
overflow: hidden;
}
.row:before,
.row:after {
content: " ";
display: table;
}
.row:after {
clear: both;
}
.col {
float: left;
box-sizing: border-box;
}
.col-right {
float: right;
box-sizing: border-box;
}
.col-1 {
width: 8.33333%;
}
.col-2 {
width: 16.66667%;
}
.col-3 {
width: 25%;
}
.col-4 {
width: 33.33333%;
}
.col-5 {
width: 41.66667%;
}
.col-6 {
width: 50%;
}
.col-7 {
width: 58.33333%;
}
.col-8 {
width: 66.66667%;
}
.col-9 {
width: 75%;
}
.col-10 {
width: 83.33333%;
}
.col-11 {
width: 91.66667%;
}
.col-12 {
width: 100%;
}
@media (min-width: 768px) {
.sm-center {
text-align: center;
}
.sm-right {
text-align: right;
}
.sm-col {
float: left;
box-sizing: border-box;
}
.sm-col-right {
float: right;
box-sizing: border-box;
}
.sm-col-1 {
width: 8.33333%;
}
.sm-col-2 {
width: 16.66667%;
}
.sm-col-3 {
width: 25%;
}
.sm-col-4 {
width: 33.33333%;
}
.sm-col-5 {
width: 41.66667%;
}
.sm-col-6 {
width: 50%;
}
.sm-col-7 {
width: 58.33333%;
}
.sm-col-8 {
width: 66.66667%;
}
.sm-col-9 {
width: 75%;
}
.sm-col-10 {
width: 83.33333%;
}
.sm-col-11 {
width: 91.66667%;
}
.sm-col-12 {
width: 100%;
}
.sm-col-offset-2 {
margin-left: 16.66667%;
}
}
@media (min-width: 980px) {
.md-col {
float: left;
box-sizing: border-box;
}
.md-col-right {
float: right;
box-sizing: border-box;
}
.md-col-1 {
width: 8.33333%;
}
.md-col-2 {
width: 16.66667%;
}
.md-col-3 {
width: 25%;
}
.md-col-4 {
width: 33.33333%;
}
.md-col-5 {
width: 41.66667%;
}
.md-col-6 {
width: 50%;
}
.md-col-7 {
width: 58.33333%;
}
.md-col-8 {
width: 66.66667%;
}
.md-col-9 {
width: 75%;
}
.md-col-10 {
width: 83.33333%;
}
.md-col-11 {
width: 91.66667%;
}
.md-col-12 {
width: 100%;
}
}
@media (min-width: 1140px) {
.container {
width: 1100px;
}
.lg-col {
float: left;
box-sizing: border-box;
}
.lg-col-right {
float: right;
box-sizing: border-box;
}
.lg-col-1 {
width: 8.33333%;
}
.lg-col-2 {
width: 16.66667%;
}
.lg-col-3 {
width: 25%;
}
.lg-col-4 {
width: 33.33333%;
}
.lg-col-5 {
width: 41.66667%;
}
.lg-col-6 {
width: 50%;
}
.lg-col-7 {
width: 58.33333%;
}
.lg-col-8 {
width: 66.66667%;
}
.lg-col-9 {
width: 75%;
}
.lg-col-10 {
width: 83.33333%;
}
.lg-col-11 {
width: 91.66667%;
}
.lg-col-12 {
width: 100%;
}
}
@font-face {
font-family: 'aa-icons';
src: url('fonts/aa-icons.eot?dxd3n2');
src: url('fonts/aa-icons.eot?#iefixdxd3n2') format('embedded-opentype'), url('fonts/aa-icons.ttf?dxd3n2') format('truetype'), url('fonts/aa-icons.woff?dxd3n2') format('woff'), url('fonts/aa-icons.svg?dxd3n2#aa-icons') format('svg');
font-weight: normal;
font-style: normal;
}
[class^="icon-"],
[class*=" icon-"] {
font-family: 'aa-icons';
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
/* Better Font Rendering =========== */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.icon-star:before {
content: "\e260";
}
.icon-email:before {
content: "\e603";
}
.icon-phone:before {
content: "\e604";
}
.icon-linkedin:before {
content: "\e600";
}
.icon-twitter:before {
content: "\e601";
}
.icon-houzz:before {
content: "\e602";
}
.icon-facebook:before {
content: "\e607";
}
.hide-text {
font: 0/0 a;
color: transparent;
text-shadow: none;
}
.no-border {
-webkit-border-radius: 0;
-moz-border-radius: 0;
border-radius: 0;
}
.clearfix:before,
.clearfix:after {
content: " ";
display: table;
}
.clearfix:after {
clear: both;
}
/*-----Base-----*/
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
box-sizing: border-box;
*behavior: url(/css/vendor/boxsizing.htc);
}
html,
body {
margin: 0;
padding: 0;
height: 100%;
}
body {
background: #ffffff;
color: #333333;
font-family: 'DIN Web Light', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: normal;
font-size: 16px;
line-height: 22px;
}
body.nav-open {
overflow: hidden;
}
p {
margin: 0 0 20px;
}
p.hero {
font-size: 16px;
line-height: 22px;
}
ul {
list-style: none;
margin: 0;
}
figure {
margin: 0;
}
figure .caption {
text-align: center;
}
img {
max-width: none;
}
::-moz-selection {
color: #ffffff;
background: #ea088c;
}
::selection {
color: #ffffff;
background: #ea088c;
}
/*-----Typography-----*/
h1 {
margin: 0 0 20px;
font-family: 'DIN Web Bold', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: normal;
font-size: 40px;
line-height: 40px;
}
h2 {
margin: 10px 0 30px;
font-family: 'DIN Web Light', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: normal;
font-size: 30px;
line-height: 32px;
}
h2 img {
vertical-align: bottom;
margin-right: 15px;
}
h3 {
margin: 0 0 10px;
font-family: 'DIN Web Medium', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: normal;
font-size: 28px;
line-height: 30px;
}
h3 small {
display: block;
font-family: 'DIN Web Light', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: normal;
text-transform: none;
font-size: 14px;
line-height: 22px;
}
strong,
b {
font-family: 'DIN Web Medium', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: normal;
}
em,
i {
font-family: 'DIN Web BookItalic', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: normal;
}
strong em,
strong i,
b em,
b i {
font-family: 'DIN Web BoldItalic', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: normal;
}
a {
color: #ea088c;
text-decoration: none;
-webkit-transition: all 0.2s linear;
-moz-transition: all 0.2s linear;
-o-transition: all 0.2s linear;
-ms-transition: all 0.2s linear;
transition: all 0.2s linear;
}
.visible-xs {
display: block !important;
}
.hidden-xs {
display: none !important;
}
.pad-20 {
padding: 0 5%;
}
.btn {
white-space: nowrap;
font-family: 'DIN Web Medium', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: normal;
border: none;
}
.btn.btn-text {
color: #ea088c;
font-size: 65%;
text-transform: uppercase;
letter-spacing: 2px;
}
.btn.submit {
display: block;
width: 100%;
padding: 10px 20px 8px;
text-transform: uppercase;
background: #ea088c;
color: #ffffff;
}
.btn.submit:focus {
outline: none;
}
.btn.btn-block {
display: block;
color: #ffffff;
background: #ea088c;
white-space: normal;
padding: 10px 20px 8px;
text-align: center;
}
/*----- Scaffolding -----*/
#wrapper {
z-index: 1;
}
#wrapper,
.inner-wrapper {
position: relative;
margin: 0 auto;
}
.inner-wrapper {
background: #ffffff;
}
ul.social {
display: block;
list-style: none;
margin: 10px 0 20px 0;
padding: 0;
}
ul.social:before,
ul.social:after {
content: " ";
display: table;
}
ul.social:after {
clear: both;
}
ul.social li {
display: inline-block;
margin: 0;
}
ul.social li a {
display: block;
width: 30px;
height: 30px;
text-decoration: none;
font-size: 30px;
line-height: 1;
color: #ababab;
-webkit-transition: all 0.2s linear;
-moz-transition: all 0.2s linear;
-o-transition: all 0.2s linear;
-ms-transition: all 0.2s linear;
transition: all 0.2s linear;
}
ul.social li a:hover {
color: #ea088c;
}
ul.social li a.houzz:hover {
color: #7ac142 !important;
}
ul.social li a.facebook:hover {
color: #3664A2 !important;
}
ul.social li a.twitter:hover {
color: #55ACEE !important;
}
ul.social li a.linkedin:hover {
color: #0077B5 !important;
}
ul.social.home {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
text-align: center;
z-index: 4;
}
ul.social.home li a {
color: #333333;
}
ul.social.home li a:hover {
color: #ea088c;
}
ul.social.stacked {
position: fixed;
margin: 45px 0;
z-index: 4;
}
ul.social.stacked li {
display: block;
margin: 2px 0;
}
ul.social.stacked li a {
color: #333333;
}
ul.social.stacked li a:hover {
color: #ea088c;
}
.houzz-callout {
display: none;
position: absolute;
top: 85px;
right: 10px;
z-index: 4;
width: 75px;
height: 75px;
text-decoration: none;
}
.houzz-callout img {
display: block;
width: 100%;
height: auto;
}
#main {
position: relative;
padding-top: 60px;
overflow: hidden;
}
/*----- Header -----*/
.nav-open-overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 2;
}
.nav-open .nav-open-overlay {
display: block;
}
#header {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 3;
}
#header a.logo {
display: block;
position: relative;
width: 200px;
margin: 10px 0 10px -10px;
}
#header a.logo img {
display: block;
width: 100%;
height: auto;
}
#header .container {
overflow: visible;
}
#main-nav {
display: none;
margin: 0 -20px;
background: #ea088c;
text-align: center;
}
#main-nav ul {
list-style: none;
margin: 0;
padding: 20px 0;
}
#main-nav ul li a {
display: block;
padding: 10px;
font-family: 'DIN Web Medium', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: normal;
font-size: 24px;
line-height: 30px;
text-decoration: none;
color: #ffffff;
}
#main-nav ul li.dropdown ul {
display: none;
margin-bottom: 20px;
padding: 0;
}
#main-nav ul li.dropdown ul li a {
padding: 5px 0;
font-family: 'DIN Web Book', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: normal;
font-size: 16px;
line-height: 20px;
}
.menu-toggle {
position: absolute;
top: 0;
right: 0;
width: 70px;
}
.menu-toggle .toggle-btn {
display: block;
width: 30px;
height: 30px;
position: relative;
margin: 17px auto;
-webkit-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
transform: rotate(0deg);
-webkit-transition: 0.5s ease-in-out;
-moz-transition: 0.5s ease-in-out;
-o-transition: 0.5s ease-in-out;
transition: 0.5s ease-in-out;
cursor: pointer;
}
.menu-toggle .toggle-btn span {
display: block;
position: absolute;
height: 3px;
width: 30px;
background: #333333;
opacity: 1;
left: 0;
-webkit-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
transform: rotate(0deg);
-webkit-transition: 0.25s ease-in-out;
-moz-transition: 0.25s ease-in-out;
-o-transition: 0.25s ease-in-out;
transition: 0.25s ease-in-out;
}
.menu-toggle .toggle-btn span:nth-child(1) {
top: 6px;
}
.menu-toggle .toggle-btn span:nth-child(2),
.menu-toggle .toggle-btn span:nth-child(3) {
top: 13px;
}
.menu-toggle .toggle-btn span:nth-child(4) {
top: 20px;
}
.menu-toggle .toggle-btn.open span:nth-child(1) {
top: 15px;
width: 0%;
left: 50%;
}
.menu-toggle .toggle-btn.open span:nth-child(2) {
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
}
.menu-toggle .toggle-btn.open span:nth-child(3) {
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
-o-transform: rotate(-45deg);
transform: rotate(-45deg);
}
.menu-toggle .toggle-btn.open span:nth-child(4) {
top: 15px;
width: 0%;
left: 50%;
}
/*----- Footer ----- */
#footer {
position: relative;
text-align: center;
font-size: 14px;
line-height: 17px;
z-index: 2;
}
#footer .inner-wrapper {
padding: 60px 0 60px;
height: 100%;
background: #f3f3f3;
}
a.contact-link {
display: inline-block;
font-size: 16px;
line-height: 30px;
text-decoration: none;
padding-left: 8px;
color: #333333;
-webkit-transition: all 0.2s linear;
-moz-transition: all 0.2s linear;
-o-transition: all 0.2s linear;
-ms-transition: all 0.2s linear;
transition: all 0.2s linear;
}
a.contact-link:hover {
color: #ea088c;
}
a.contact-link span {
font-size: 30px;
float: left;
}
ul.houzz-awards {
display: inline-block;
list-style: none;
margin: 30px 0;
padding: 0;
}
ul.houzz-awards a {
display: block;
color: #333333;
}
ul.houzz-awards p {
margin: 0 0 10px;
}
ul.houzz-awards li {
display: inline-block;
margin: 2px;
}
ul.houzz-awards li img {
display: block;
width: 52px;
height: auto;
border: 1px solid #ababab;
-webkit-transition: all 0.1s ease;
-moz-transition: all 0.1s ease;
-o-transition: all 0.1s ease;
-ms-transition: all 0.1s ease;
transition: all 0.1s ease;
transform: scale(1);
}
ul.houzz-awards li img:hover {
transform: scale(1.1);
}
ul.houzz-awards li.green img {
border-color: #7ac142;
}
.houzz-rating {
margin-top: 5px;
}
.houzz-rating:before,
.houzz-rating:after {
content: " ";
display: table;
}
.houzz-rating:after {
clear: both;
}
.houzz-rating .stars {
float: left;
color: #008d00;
font-size: 14px;
}
.houzz-rating span.text {
float: right;
}
/*----- Sections ----- */
#page-header {
position: relative;
padding: 30px 0;
background-color: #ababab;
background-attachment: scroll;
background-size: cover;
background-position: center center;
}
#page-header:before {
content: '';
display: block;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
background: #ffffff;
zoom: 1;
opacity: 0.75;
filter: alpha(opacity=75);
}
#page-header > .container {
position: relative;
}
#page-header h1 {
margin: 10px 0;
}
.crumbs {
display: none;
margin-left: 5px;
}
.crumbs a {
color: #333333;
}
.crumbs span {
margin: 0 15px;
}
#content {
position: relative;
background: #ffffff;
z-index: 2;
}
.bg {
display: block;
position: fixed;
width: 100%;
left: 0;
z-index: -9999;
}
.bg.home-bg {
top: 0;
height: 100%;
}
.bg.project-bg,
.bg.page-bg {
top: 60px;
height: 350px;
}
#intro {
display: table;
position: relative;
width: 100%;
}
#intro .bg-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: transparent url('../img/bg-home-overlay.png') center center no-repeat;
background-size: cover;
background-attachment: scroll;
}
#intro .go-down {
display: block;
position: absolute;
bottom: 20px;
left: 50%;
margin-left: -25px;
width: 50px;
height: 50px;
}
#intro .overlay {
display: table-cell;
position: relative;
vertical-align: middle;
text-align: center;
z-index: 2;
}
#intro .overlay h1 {
font-size: 36px;
line-height: 40px;
margin-bottom: 50px;
}
#intro .overlay .logo-large {
display: block;
width: 150px;
height: 150px;
margin: 0 auto 20px;
}
#intro .overlay .logo-large img {
display: block;
width: 100%;
height: auto;
}
#home-text {
text-align: center;
}
#home-text .well {
padding: 30px 0;
background: rgba(255, 255, 255, 0.75);
}
#home-text .well .hero {
font-size: 14px;
line-height: 20px;
margin: 0;
}
#home-callout {
background-color: #553e37;
background-attachment: scroll;
background-size: cover;
background-position: center center;
color: #ffffff;
padding: 40px 0;
}
#home-callout .callout {
margin: 40px 0;
}
#home-callout .callout h2 {
text-align: center;
}
#home-callout .callout h2 img {
display: block;
margin: 0 auto 10px;
}
#latest-work,
#all-work,
#all-news,
#project-content {
background: #ffffff;
padding: 50px 0;
}
#latest-work .row,
#all-work .row,
#all-news .row,
#project-content .row {
margin: 0 -15px;
}
.project.project-sizer,
.post.project-sizer {
position: absolute;
zoom: 1;
opacity: 0;
filter: alpha(opacity=0);
visibility: hidden;
}
.project a,
.post a {
display: block;
position: relative;
margin: 5px;
overflow: hidden;
}
.project a .overlay,
.post a .overlay {
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.project a .overlay:after,
.post a .overlay:after {
content: '';
display: block;
width: 100%;
height: 100%;
background: #ea088c;
zoom: 1;
opacity: 0;
filter: alpha(opacity=0);
-webkit-transition: all 0.15s linear;
-moz-transition: all 0.15s linear;
-o-transition: all 0.15s linear;
-ms-transition: all 0.15s linear;
transition: all 0.15s linear;
}
.project a .overlay .title,
.post a .overlay .title {
display: block;
position: absolute;
top: 50%;
left: 0;
margin-top: 10px;
width: 100%;
text-align: center;
color: #ffffff;
transform: translateY(-35%);
zoom: 1;
opacity: 0;
filter: alpha(opacity=0);
-webkit-transition: all 0.15s cubic-bezier(0.42, 0, 1, 1);
-moz-transition: all 0.15s cubic-bezier(0.42, 0, 1, 1);
-o-transition: all 0.15s cubic-bezier(0.42, 0, 1, 1);
-ms-transition: all 0.15s cubic-bezier(0.42, 0, 1, 1);
transition: all 0.15s cubic-bezier(0.42, 0, 1, 1);
z-index: 1;
}
.project a .overlay .title h3,
.post a .overlay .title h3 {
margin: 0 20px;
}
.project a img,
.post a img {
display: block;
width: auto;
height: auto;
max-width: 100%;
max-height: 100%;
-webkit-transition: all 0.15s cubic-bezier(0.455, 0.03, 0.515, 0.955);
-moz-transition: all 0.15s cubic-bezier(0.455, 0.03, 0.515, 0.955);
-o-transition: all 0.15s cubic-bezier(0.455, 0.03, 0.515, 0.955);
-ms-transition: all 0.15s cubic-bezier(0.455, 0.03, 0.515, 0.955);
transition: all 0.15s cubic-bezier(0.455, 0.03, 0.515, 0.955);
transform: scale(1);
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
#projects-filter {
background-color: #553e37;
background-attachment: scroll;
background-size: cover;
background-position: center center;
color: #ffffff;
padding: 50px 0;
}
.filter {
position: relative;
margin: 0;
padding: 5px;
list-style: none;
width: 100%;
background: rgba(0, 0, 0, 0.33);
}
.filter:before,
.filter:after {
content: " ";
display: table;
}
.filter:after {
clear: both;
}
.filter li {
z-index: 2;
}
.filter li a {
display: block;
position: relative;
height: 40px;
line-height: 44px;
padding: 0 10px;
text-align: center;
font-family: 'DIN Web Medium', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: normal;
font-size: 18px;
color: #ffffff;
z-index: 2;
}
.filter li a:before {
content: '';
display: block;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
background: #ea088c;
z-index: -1;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
zoom: 1;
opacity: 0;
filter: alpha(opacity=0);
transform: scale(0.95);
-webkit-transition: all 0.1s ease;
-moz-transition: all 0.1s ease;
-o-transition: all 0.1s ease;
-ms-transition: all 0.1s ease;
transition: all 0.1s ease;
}
.filter li.active a:before {
zoom: 1;
opacity: 1;
filter: alpha(opacity=100);
transform: scale(1);
}
#project-hero,
#page-hero {
position: relative;
height: 350px;
}
#project-hero .well,
#page-hero .well {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
padding: 25px 0 20px;
background: rgba(255, 255, 255, 0.75);
}
#project-hero .well h1,
#page-hero .well h1 {
margin: 0;
font-size: 30px;
line-height: 30px;
}
#projects-nav {
position: relative;
background: #f3f3f3;
}
#projects-nav > .container {
position: relative;
overflow: visible;
}
#projects-nav .nav-wrapper {
display: none;
text-align: center;
}
#projects-nav .prev-project,
#projects-nav .next-project {
display: inline-block;
position: relative;
width: 40%;
padding: 10px;
text-align: center;
font-size: 16px;
line-height: 22px;
}
#projects-nav .prev-project a,
#projects-nav .next-project a {
position: relative;
display: inline-block;
width: 100%;
height: 0;
padding: 50% 0;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
border-radius: 50%;
overflow: hidden;
z-index: 9;
}
#projects-nav .prev-project a > img,
#projects-nav .next-project a > img {
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: auto;
transform: scale(1);
-webkit-transition: all 0.2s cubic-bezier(0.42, 0, 1, 1);
-moz-transition: all 0.2s cubic-bezier(0.42, 0, 1, 1);
-o-transition: all 0.2s cubic-bezier(0.42, 0, 1, 1);
-ms-transition: all 0.2s cubic-bezier(0.42, 0, 1, 1);
transition: all 0.2s cubic-bezier(0.42, 0, 1, 1);
}
#projects-nav .prev-project a .overlay,
#projects-nav .next-project a .overlay {
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
zoom: 1;
opacity: 0;
filter: alpha(opacity=0);
-webkit-transform: translateZ(0);
-webkit-transition: all 0.15s linear;
-moz-transition: all 0.15s linear;
-o-transition: all 0.15s linear;
-ms-transition: all 0.15s linear;
transition: all 0.15s linear;
}
#projects-nav .prev-project a .overlay:after,
#projects-nav .next-project a .overlay:after {
content: '';
display: block;
width: 100%;
height: 100%;
background: #ea088c;
zoom: 1;
opacity: 0.75;
filter: alpha(opacity=75);
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
border-radius: 50%;
}
#projects-nav .prev-project a .overlay img,
#projects-nav .next-project a .overlay img {
display: block;
position: absolute;
top: 50%;
left: 50%;
width: 50px;
height: 50px;
margin: -25px 0 0 -25px;
transform: scale(0.8);
-webkit-transition: all 0.15s linear;
-moz-transition: all 0.15s linear;
-o-transition: all 0.15s linear;
-ms-transition: all 0.15s linear;
transition: all 0.15s linear;
z-index: 9;
}
#projects-nav .project-desc {
margin: 25px 0;
font-size: 16px;
line-height: 22px;
}
#project-content img,
.entry img {
display: block;
margin: 20px auto;
width: auto;
height: auto;
max-width: 100%;
max-height: 100%;
}
#project-content figure,
.entry figure {
margin: 20px auto;
}
#project-content figure img,
.entry figure img {
margin: 0 auto 10px;
}
#project-content blockquote,
.entry blockquote {
position: relative;
margin: 20px 10px;
padding: 0 40px;
font-size: 16px;
line-height: 22px;
font-family: 'DIN Web LightItalic', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: normal;
}
#project-content blockquote:before,
.entry blockquote:before,
#project-content blockquote:after,
.entry blockquote:after {
display: block;
position: absolute;
font-family: 'DIN Web Bold', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: normal;
font-size: 60px;
color: #ea088c;
}
#project-content blockquote:before,
.entry blockquote:before {
content: '“';
left: 0;
top: 25px;
}
#project-content blockquote:after,
.entry blockquote:after {
content: '”';
right: 0;
bottom: -25px;
}
#project-content .share-project,
.entry .share-project {
background: #f3f3f3;
margin: 0 20px;
padding: 10px 0;
text-align: center;
}
#project-content .share-project ul,
.entry .share-project ul {
margin: 0 10px;
padding: 0;
}
#project-content .share-project ul:before,
.entry .share-project ul:before,
#project-content .share-project ul:after,
.entry .share-project ul:after {
content: " ";
display: table;
}
#project-content .share-project ul:after,
.entry .share-project ul:after {
clear: both;
}
#project-content .share-project li,
.entry .share-project li {
display: block;
float: left;
width: 50%;
padding: 10px;
}
#project-content .share-project li a,
.entry .share-project li a {
display: block;
position: relative;
padding-left: 35px;
height: 35px;
overflow: hidden;
}
#project-content .share-project li a span,
.entry .share-project li a span {
display: block;
position: absolute;
top: 0;
left: 0;
width: 35px;
height: 35px;
font-size: 36px;
line-height: 36px;
background: #ffffff;
}
#project-content .share-project li a small,
.entry .share-project li a small {
display: block;
padding: 8px 10px;
height: 35px;
background: #ababab;
color: #ffffff;
font-family: 'DIN Web Medium', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: normal;
font-size: 16px;
}
#project-content .share-project li a.houzz span,
.entry .share-project li a.houzz span {
color: #7ac142;
}
#project-content .share-project li a.houzz small,
.entry .share-project li a.houzz small {
background: #629d33;
}
#project-content .share-project li a.facebook span,
.entry .share-project li a.facebook span {
color: #3664A2;
}
#project-content .share-project li a.facebook small,
.entry .share-project li a.facebook small {
background: #294c7c;
}
#project-content .share-project li a.twitter span,
.entry .share-project li a.twitter span {
color: #55ACEE;
}
#project-content .share-project li a.twitter small,
.entry .share-project li a.twitter small {
background: #2795e9;
}
#project-content .share-project li a.linkedin span,
.entry .share-project li a.linkedin span {
color: #0077B5;
}
#project-content .share-project li a.linkedin small,
.entry .share-project li a.linkedin small {
background: #005582;
}
.entry {
padding: 50px 0;
}
.entry.news-entry {
padding-bottom: 0;
margin-bottom: -30px;
}
.entry img {
display: inline;
}
.entry ul {
list-style: none;
margin: 0;
padding-left: 35px;
}
.entry ul li {
position: relative;
margin-bottom: 20px;
}
.entry ul li:before {
content: '';
display: block;
position: absolute;
left: -30px;
background: transparent url('../img/icon.bullet.png') center center no-repeat;
background-size: 4px 8px;
width: 30px;
height: 18px;
}
.bucket {
background-color: #553e37;
background-size: cover;
background-position: center center;
background-attachment: scroll;
margin: 30px 10px 50px;
padding: 30px;
color: #ffffff;
}
.bucket h2 {
text-align: center;
}
.bucket h2 img {
display: block;
margin: 0 auto 10px;
}
#team {
margin: 20px 0;
}
#team .row {
margin: 0 -5px;
}
.member a {
display: block;
position: relative;
margin: 5px;
overflow: hidden;
}
.member a .overlay {
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.member a .overlay:after {
content: '';
display: block;
width: 100%;
height: 100%;
background: #ea088c;
zoom: 1;
opacity: 0;
filter: alpha(opacity=0);
-webkit-transition: all 0.15s linear;
-moz-transition: all 0.15s linear;
-o-transition: all 0.15s linear;
-ms-transition: all 0.15s linear;
transition: all 0.15s linear;
}
.member a .title {
display: block;
position: absolute;
bottom: 0;
left: 0;
width: 100%;
padding: 10px;
text-align: center;
background: #ea088c;
background: rgba(234, 8, 140, 0.75);
color: #ffffff;
}
.member a .title h3 {
margin: 0 20px;
font-size: 18px;
line-height: 22px;
}
.member a img {
display: block;
width: auto;
height: auto;
max-width: 100%;
max-height: 100%;
margin: 0;
-webkit-transition: all 0.15s cubic-bezier(0.455, 0.03, 0.515, 0.955);
-moz-transition: all 0.15s cubic-bezier(0.455, 0.03, 0.515, 0.955);
-o-transition: all 0.15s cubic-bezier(0.455, 0.03, 0.515, 0.955);
-ms-transition: all 0.15s cubic-bezier(0.455, 0.03, 0.515, 0.955);
transition: all 0.15s cubic-bezier(0.455, 0.03, 0.515, 0.955);
transform: scale(1);
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
#contact-form {
position: relative;
}
#contact-form .row {
margin: 0 -10px;
zoom: 1;
opacity: 1;
filter: alpha(opacity=100);
-webkit-transition: all 0.2s linear;
-moz-transition: all 0.2s linear;
-o-transition: all 0.2s linear;
-ms-transition: all 0.2s linear;
transition: all 0.2s linear;
}
#contact-form .form-group {
padding: 0 10px;
margin-bottom: 30px;
}
#contact-form .form-group label {
display: block;
font-family: 'DIN Web Bold', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: normal;
text-transform: uppercase;
margin: 0 0 5px;
}
#contact-form .form-group label.error {
display: none !important;
}
#contact-form .form-group label span {
text-transform: none;
font-size: 13px;
font-family: 'DIN Web LightItalic', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: normal;
color: #ababab;
}
#contact-form .form-group input,
#contact-form .form-group textarea {
display: block;
width: 100%;
outline: none;
border: none;
background: #f3f3f3;
padding: 10px;
line-height: 20px;
-webkit-transition: all 0.1s linear;
-moz-transition: all 0.1s linear;
-o-transition: all 0.1s linear;
-ms-transition: all 0.1s linear;
transition: all 0.1s linear;
}
#contact-form .form-group input:focus,
#contact-form .form-group textarea:focus {
outline: none;
background: #333333;
color: #ffffff;
}
#contact-form .form-group.error input,
#contact-form .form-group.error textarea {
background: #ea088c;
color: #ffffff;
}
#contact-form .notice {
margin-bottom: 20px;
text-align: center;
font-family: 'DIN Web Bold', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: normal;
text-transform: uppercase;
font-size: 14px;
}
#contact-form .notice span {
text-transform: none;
font-size: 13px;
font-family: 'DIN Web LightItalic', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: normal;
color: #ababab;
}
#contact-form #contact-success {
display: block;
position: absolute;
top: 40%;
width: 100%;
text-align: center;
transform: translateY(-30%);
zoom: 1;
opacity: 0;
filter: alpha(opacity=0);
visibility: hidden;
z-index: 2;
-webkit-transition: all 0.2s linear;
-moz-transition: all 0.2s linear;
-o-transition: all 0.2s linear;
-ms-transition: all 0.2s linear;
transition: all 0.2s linear;
}
#contact-form #contact-success h2 {
margin-bottom: 0;
}
#contact-form.success:after {
content: '';
display: block;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
}
#contact-form.success .row {
zoom: 1;
opacity: 0.1;
filter: alpha(opacity=10);
}
#contact-form.success #contact-success {
transform: translateY(-50%);
zoom: 1;
opacity: 1;
filter: alpha(opacity=100);
visibility: visible;
}
#phone-link {
margin: 20px 0;
text-align: center;
}
#map {
width: 100%;
height: 240px;
background: #f3f3f3;
}
#map img {
max-width: none;
max-height: none;
}
/*----- Mobile-Specific -----*/
/*----- Tablet -----*/
@media (min-width: 768px) {
h1 {
font-size: 50px;
line-height: 50px;
}
.btn.submit {
display: inline-block;
width: auto;
}
.visible-xs {
display: none !important;
}
.hidden-xs {
display: block !important;
}
#wrapper {
min-height: 100%;
margin-bottom: -240px;
}
#wrapper:after {
content: '';
display: block;
height: 240px;
}
.houzz-callout {
display: block;
}
#main {
padding-top: 75px;
}
#header a.logo {
float: left;
margin: 7.5px 0;
width: 300px;
height: 60px;
}
#main-nav {
display: block !important;
float: right;
margin: 15px 0 10px;
background: none;
text-align: left;
}
#main-nav > ul {
padding: 0;
}
#main-nav > ul:before,
#main-nav > ul:after {
content: " ";
display: table;
}
#main-nav > ul:after {
clear: both;
}
#main-nav > ul > li {
float: left;
}
#main-nav > ul > li a {
padding: 10px 14px;
font-family: 'DIN Web Book', 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: normal;
font-size: 14px;
color: #333333;
}
#main-nav > ul > li a:hover {
color: #ea088c;
}
#main-nav > ul > li.active a {
color: #ea088c;
}
#main-nav > ul > li.dropdown {
position: relative;
}
#main-nav > ul > li.dropdown ul {
display: block;
position: absolute;
width: 200px;
top: 100%;
left: 50%;
padding-top: 10px;
margin-left: -100px;
margin-bottom: 0;
padding: 10px 0;
text-align: center;
visibility: hidden;
transform: scale(0.95);
zoom: 1;
opacity: 0;
filter: alpha(opacity=0);
-webkit-transition: all 0.2s linear;
-moz-transition: all 0.2s linear;
-o-transition: all 0.2s linear;
-ms-transition: all 0.2s linear;
transition: all 0.2s linear;
}
#main-nav > ul > li.dropdown ul:before {
content: '';
display: block;
position: absolute;
top: 0;
left: 50%;
margin-left: -10px;
width: 0;
height: 0;
border-bottom: 10px solid #ea088c;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
}
#main-nav > ul > li.dropdown ul li {
background: #ea088c;
}
#main-nav > ul > li.dropdown ul li:first-child {
padding-top: 10px;
}
#main-nav > ul > li.dropdown ul li:last-child {
padding-bottom: 10px;
}
#main-nav > ul > li.dropdown ul li a {
padding: 8px 10px;
color: #ffffff;
}
#main-nav > ul > li.dropdown ul li a:hover {
color: #ffffff;
background: #b9066e;
}
#main-nav > ul > li.dropdown:hover > a {
color: #ea088c;
}
#main-nav > ul > li.dropdown:hover ul {
visibility: visible;
transform: scale(1);
zoom: 1;
opacity: 1;
filter: alpha(opacity=100);
}
.menu-toggle {
display: none;
}
#footer {
text-align: left;
height: 240px;
}
#footer .inner-wrapper {
padding: 55px 0 0;
}
ul.houzz-awards {
margin: 10px 0 0 0;
}
#page-header {
width: 100%;
height: 220px;
padding: 72px 0;
z-index: 1;
}
#page-header h1 {
margin-top: 0;
}
.bg.project-bg,
.bg.page-bg {
top: 75px;
height: 550px;
}
#intro {
padding: 0;
}
#intro .overlay .logo-large {
margin: 0 auto 40px;
width: 200px;
height: 200px;
}
#intro .overlay h1 {
font-size: 40px;
line-height: 40px;
margin-bottom: 10px;
}
#home-text .well {
padding: 60px 0;
}
#home-text .well .hero {
font-size: 16px;
line-height: 22px;
}
#home-callout .row {
margin: 0 -40px;
}
#home-callout .row .callout {
padding: 0 40px;
}
#home-callout .row .callout h2 {
text-align: left;
}
#home-callout .row .callout h2 img {
display: inline;
margin: 0 10px 0 0;
}
#latest-work,
#all-work,
#all-news,
#project-content {
padding: 100px 0;
}
#latest-work .row,
#all-work .row,
#all-news .row,
#project-content .row {
margin: 0 -10px;
}
.project a,
.post a {
margin: 10px;
}
.project a:hover img,
.post a:hover img {
transform: scale(1.05);
-webkit-transition: all 0.2s cubic-bezier(0.42, 0, 1, 1);
-moz-transition: all 0.2s cubic-bezier(0.42, 0, 1, 1);
-o-transition: all 0.2s cubic-bezier(0.42, 0, 1, 1);
-ms-transition: all 0.2s cubic-bezier(0.42, 0, 1, 1);
transition: all 0.2s cubic-bezier(0.42, 0, 1, 1);
}
.project a:hover .overlay:after,
.post a:hover .overlay:after {
zoom: 1;
opacity: 0.75;
filter: alpha(opacity=75);
}
.project a:hover .overlay .title,
.post a:hover .overlay .title {
transform: translateY(-50%);
zoom: 1;
opacity: 1;
filter: alpha(opacity=100);
}
.filter li {
display: table-cell;
width: 1%;
}
.filter li a {
font-size: 14px;
border-left: 1px solid rgba(131, 96, 85, 0.4);
border-right: 1px solid rgba(131, 96, 85, 0.4);
}
.filter li:first-child a {
border-left: none;
}
.filter li:last-child a {
border-right: none;
}
#project-hero,
#page-hero {
height: 550px;
}
#project-hero .well,
#page-hero .well {
padding: 40px 0 30px;
}
#project-hero .well h1,
#page-hero .well h1 {
margin: 0 0 10px 5px;
font-size: 50px;
line-height: 50px;
}
#projects-nav {
padding: 60px 0;
}
#projects-nav > .container {
min-height: 200px;
}
#projects-nav .nav-wrapper {
display: block;
}
#projects-nav .prev-project {
left: 10px;
}
#projects-nav .next-project {
right: 10px;
}
#projects-nav .prev-project,
#projects-nav .next-project {
position: absolute;
width: 16%;
top: 50%;
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
}
#projects-nav .prev-project a:hover > img,
#projects-nav .next-project a:hover > img {
transform: scale(1.05);
}
#projects-nav .prev-project a:hover .overlay,
#projects-nav .next-project a:hover .overlay {
zoom: 1;
opacity: 1;
filter: alpha(opacity=100);
}
#projects-nav .prev-project a:hover .overlay img,
#projects-nav .next-project a:hover .overlay img {
transform: scale(1);
}
#project-content img,
.entry img {
margin: 40px auto;
}
#project-content figure,
.entry figure {
margin: 40px auto;
}
#project-content figure img,
.entry figure img {
margin: 0 auto 20px;
}
#project-content blockquote,
.entry blockquote {
margin: 50px 0;
}
#project-content .share-project,
.entry .share-project {
margin: 0;
padding: 30px 0;
}
#project-content .share-project ul,
.entry .share-project ul {
margin: 0;
height: 25px;
}
#project-content .share-project li,
.entry .share-project li {
display: inline-block;
float: none;
margin: 0 10px;
padding: 0;
width: auto;
}
#project-content .share-project li a,
.entry .share-project li a {
padding-left: 25px;
height: 25px;
}
#project-content .share-project li a span,
.entry .share-project li a span {
width: 25px;
height: 25px;
font-size: 26px;
line-height: 26px;
}
#project-content .share-project li a small,
.entry .share-project li a small {
display: block;
padding: 3px 15px;
height: 25px;
font-size: 14px;
}
.entry {
padding: 80px 0;
}
.entry.news-entry {
margin-bottom: -50px;
}
.bucket h2 {
text-align: left;
}
.bucket h2 img {
display: inline;
margin: 0 10px 0 0;
}
#team {
margin: 30px 0;
}
#team .row {
margin: 0 -10px;
}
.member a {
margin: 10px;
}
.member a:hover img {
transform: scale(1.05);
-webkit-transition: all 0.2s cubic-bezier(0.42, 0, 1, 1);
-moz-transition: all 0.2s cubic-bezier(0.42, 0, 1, 1);
-o-transition: all 0.2s cubic-bezier(0.42, 0, 1, 1);
-ms-transition: all 0.2s cubic-bezier(0.42, 0, 1, 1);
transition: all 0.2s cubic-bezier(0.42, 0, 1, 1);
}
.member a:hover .overlay:after {
zoom: 1;
opacity: 0.75;
filter: alpha(opacity=75);
}
#contact-form .notice {
margin: 0;
text-align: right;
float: right;
}
#contact-form .submit {
float: left;
}
#phone-link {
margin: 30px 0;
text-align: right;
}
#map {
height: 300px;
}
}
/*----- Desktop -----*/
@media (min-width: 992px) {
#main-nav ul li a {
padding: 10px 20px;
font-size: 16px;
}
.bg.project-bg,
.bg.page-bg {
height: 650px;
}
.crumbs {
display: block;
}
.filter li a {
font-size: 18px;
}
#project-hero,
#page-hero {
height: 650px;
}
}
/*----- Large Desktop -----*/
@media (min-width: 1200px) {
#projects-nav .prev-project,
#projects-nav .next-project {
width: 200px;
height: 200px;
}
#projects-nav .prev-project {
left: -30px;
}
#projects-nav .next-project {
right: -30px;
}
}
|
ndimatteo/aa-theme
|
assets/css/app.css
|
CSS
|
mit
| 49,630
|
#!/usr/bin/env bash
echo "Test basic matching"
BASEURL="http://localhost:5455/api/user/matches"
echo
SKILLS="javascript,ruby", GOALS="", INTERESTS=""
URL="$BASEURL?skills=$SKILLS&goals=$GOALS&interests=$INTERESTS"
echo "Calling WITH skills=$SKILLS goals=$GOALS interests=$INTERESTS"
wget -qO- $URL | python -m json.tool
echo "INPUT was: skills=$SKILLS goals=$GOALS interests=$INTERESTS"
echo
SKILLS="javascript", GOALS="learn", INTERESTS=""
URL="$BASEURL?skills=$SKILLS&goals=$GOALS&interests=$INTERESTS"
echo "Calling WITH skills=$SKILLS goals=$GOALS interests=$INTERESTS"
wget -qO- $URL | python -m json.tool
echo "INPUT was: skills=$SKILLS goals=$GOALS interests=$INTERESTS"
echo
SKILLS="", GOALS="", INTERESTS="homelessness,housing"
URL="$BASEURL?skills=$SKILLS&goals=$GOALS&interests=$INTERESTS"
echo "Calling WITH skills=$SKILLS goals=$GOALS interests=$INTERESTS"
wget -qO- $URL | python -m json.tool
echo "INPUT was: skills=$SKILLS goals=$GOALS interests=$INTERESTS"
echo
echo "Done!"
|
designforsf/brigade-matchmaker
|
test/matching/test_matching.sh
|
Shell
|
mit
| 998
|
IdleState = State:new()
function IdleState:needToRun(game_context, bot_context, keys)
return true
end
function IdleState:writeText(game_context, bot_context)
gui.text(0, 0, "idle")
end
function IdleState:run(game_context, bot_context, keys)
if bot_context.has_bot_done_stuff then
--client.pause()
bot_context.has_bot_done_stuff = false
end
end
|
jasongdove/FCEUXLuaScripts
|
FF VIII/ffviii-state-idle.lua
|
Lua
|
mit
| 363
|
(function () {
'use strict';
angular
.module('mainApp', []);
})();
|
santibout/Z.E.R.O-1
|
web/Scripts/AngularJs/mainApp.js
|
JavaScript
|
mit
| 85
|
WebhookService webhookService = paymillContext.WebhookService;
Webhook webhook = webhookService.DeleteAsync("hook_40237e20a7d5a231d99b").Result;
|
paymill/paymill-net
|
samples/webhooks/remove_webhook.cs
|
C#
|
mit
| 145
|
const Rebase = require('../../../src/rebase');
const React = require('react');
const ReactDOM = require('react-dom');
const firebase = require('firebase');
require('firebase/firestore');
var dummyCollection = require('../../fixtures/dummyCollection');
var firebaseConfig = require('../../fixtures/config');
describe('get()', function() {
var base;
var testApp;
var collectionPath = 'testCollection';
var collectionRef;
var app;
function seedCollection() {
const docs = dummyCollection.map((doc, index) => {
const docRef = collectionRef.doc(`doc-${index + 1}`);
return docRef.set(doc);
});
return Promise.all(docs);
}
beforeAll(() => {
testApp = firebase.initializeApp(firebaseConfig, 'DB_CHECK');
collectionRef = testApp.firestore().collection(collectionPath);
var mountNode = document.createElement('div');
mountNode.setAttribute('id', 'mount');
document.body.appendChild(mountNode);
});
afterAll(done => {
var mountNode = document.getElementById('mount');
mountNode.parentNode.removeChild(mountNode);
testApp.delete().then(done);
});
beforeEach(done => {
app = firebase.initializeApp(firebaseConfig);
var db = firebase.firestore(app);
base = Rebase.createClass(db);
seedCollection().then(done);
});
afterEach(done => {
ReactDOM.unmountComponentAtNode(document.body);
Promise.all([
collectionRef.get().then(docs => {
const deleteOps = [];
docs.forEach(doc => {
deleteOps.push(doc.ref.delete());
});
return Promise.all(deleteOps);
}),
app.delete()
])
.then(done)
.catch(err => done.fail(err));
});
it('get() validates endpoint', done => {
try {
base.get('').then(() => {
done.fail('error should thrown');
});
} catch (err) {
expect(err).not.toBeNull(err);
done();
}
});
describe('Async tests', function() {
it('get() resolves with data from a collection', done => {
base
.get(collectionPath)
.then(data => {
expect(data.length).toEqual(5);
done();
})
.catch(err => done.fail(err));
});
it('get() resolves with data from a collection query', done => {
base
.get(`${collectionPath}`, {
query: ref =>
ref
.where('id', '<', 5)
.where('id', '>', 2)
.orderBy('id')
})
.then(data => {
expect(data.length).toEqual(2);
expect(data[0].name).toEqual('Document 3');
expect(data[1].name).toEqual('Document 4');
done();
})
.catch(err => done.fail(err));
});
it('get() rejects if collection query returns no results', done => {
base
.get(`${collectionPath}`, {
query: ref => ref.where('id', '>', 5).orderBy('id')
})
.then(data => {
done.fail('query should reject');
})
.catch(err => {
expect(err.message).toEqual('No Result');
done();
});
});
it('get() rejects if document does not exist', done => {
base
.get(`${collectionPath}/nodoc`)
.then(data => {
done.fail('query should reject');
})
.catch(err => {
expect(err.message).toEqual('No Result');
done();
});
});
it('get() resolves with a document', done => {
base
.get(`${collectionPath}/doc-1`)
.then(data => {
expect(data.name).toEqual(dummyCollection[0].name);
done();
})
.catch(err => done.fail(err));
});
it('get() accepts a document reference', done => {
const docRef = app
.firestore()
.collection('testCollection')
.doc('doc-1');
base
.get(docRef)
.then(data => {
expect(data.name).toEqual(dummyCollection[0].name);
done();
})
.catch(err => done.fail(err));
});
it('get() accepts a collection reference', done => {
const testRef = app.firestore().collection('testCollection');
base
.get(testRef)
.then(data => {
expect(data[0].name).toEqual(dummyCollection[0].name);
done();
})
.catch(err => done.fail(err));
});
it('get() rejects Promise when read fails or is denied', done => {
base
.get('/readFail')
.then(() => {
done.fail('Promise should reject');
})
.catch(err => {
expect(err.code).toContain('permission-denied');
done();
});
});
});
});
|
aggiedefenders/aggiedefenders.github.io
|
node_modules/re-base/tests/specs/firestore/get.spec.js
|
JavaScript
|
mit
| 4,672
|
import { Type } from '@angular/core';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MatDialogModule } from '@angular/material/dialog';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import {
TdDialogComponent,
TdDialogTitleDirective,
TdDialogActionsDirective,
TdDialogContentDirective,
} from './dialog.component';
import { TdAlertDialogComponent } from './alert-dialog/alert-dialog.component';
import { TdConfirmDialogComponent } from './confirm-dialog/confirm-dialog.component';
import { TdPromptDialogComponent } from './prompt-dialog/prompt-dialog.component';
import { TdDialogService } from './services/dialog.service';
import { TdWindowDialogComponent } from './window-dialog/window-dialog.component';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatIconModule } from '@angular/material/icon';
const TD_DIALOGS: Type<any>[] = [
TdAlertDialogComponent,
TdConfirmDialogComponent,
TdPromptDialogComponent,
TdDialogComponent,
TdDialogTitleDirective,
TdDialogActionsDirective,
TdDialogContentDirective,
TdWindowDialogComponent,
];
const TD_DIALOGS_ENTRY_COMPONENTS: Type<any>[] = [
TdAlertDialogComponent,
TdConfirmDialogComponent,
TdPromptDialogComponent,
];
@NgModule({
imports: [
FormsModule,
CommonModule,
MatDialogModule,
MatInputModule,
MatButtonModule,
MatToolbarModule,
MatTooltipModule,
MatIconModule,
],
declarations: [TD_DIALOGS],
exports: [TD_DIALOGS],
providers: [TdDialogService],
})
export class CovalentDialogsModule {}
|
Teradata/covalent
|
src/platform/core/dialogs/dialogs.module.ts
|
TypeScript
|
mit
| 1,773
|
Imports Microsoft.Devices.Sensors
Imports Microsoft.Phone.Reactive
Imports Microsoft.Xna.Framework
Imports System.Threading
Partial Public Class MainPage
Inherits PhoneApplicationPage
' Constructor
Private _Accelerometer As Accelerometer
Private _UseEmulation As Boolean = True
Public Sub New()
InitializeComponent()
End Sub
Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
If Not _UseEmulation Then
_Accelerometer = New Accelerometer
Dim accelerometerReadingAsObservable = Observable.FromEvent(Of AccelerometerReadingEventArgs)(_Accelerometer, "ReadingChanged")
Dim vector3FromAccelerometerEventArgs = From args In accelerometerReadingAsObservable
Select New Vector3(
CSng(args.EventArgs.X),
CSng(args.EventArgs.Y),
CSng(args.EventArgs.Z))
vector3FromAccelerometerEventArgs.Subscribe(
Sub(args)
InvokeAccelerometerReadingChanged(args)
End Sub)
Try
_Accelerometer.Start()
Catch ex As Exception
ReadingTextBlock.Text = "Error starting accelerometer"
End Try
Else
StartAccelerometerEmulation()
End If
End Sub
Private _Subscribed As IDisposable
Private Sub InvokeAccelerometerReadingChanged(ByVal data As Vector3)
Deployment.Current.Dispatcher.BeginInvoke(
Sub() AccelerometerReadingChanged(data))
End Sub
Private Sub StartAccelerometerEmulation()
If _Subscribed Is Nothing Then
Dim emulationObservable = GetEmulator()
_Subscribed = emulationObservable.SubscribeOn(Scheduler.ThreadPool).
Subscribe(Sub(accelerometerReadingEventArgs) InvokeAccelerometerReadingChanged(accelerometerReadingEventArgs))
Else
_Subscribed.Dispose()
_Subscribed = Nothing
End If
End Sub
Private Sub AccelerometerReadingChanged(ByVal data As Vector3)
ReadingTextBlock.Text = String.Format("X: {0} y: {1} z: {2}",
data.X.ToString("0.00"),
data.Y.ToString("0.00"),
data.Z.ToString("0.00"))
Dim multiplier As Short
If Short.TryParse(Me.MoveMultiplier.Text, multiplier) Then
ButtonTransform.X = data.X * multiplier
ButtonTransform.Y = data.Y * multiplier
End If
End Sub
Public Shared Function GetEmulator() As IObservable(Of Vector3)
Dim obs = Observable.Create(Of Vector3)(
Function(subscriber)
Dim rnd = New Random
Dim theta As Double
Do
theta = rnd.NextDouble
Dim reading = New Vector3(CSng(Math.Sin(theta)), CSng(Math.Cos(theta * 1.1)), CSng(Math.Sin(theta * 0.7)))
reading.Normalize()
Thread.Sleep(100)
subscriber.OnNext(reading)
Loop
End Function)
Return obs
End Function
End Class
|
jwooley/RxSamples
|
WP7RxSamplesVB/WP7AccelerometerVB/WP7AccelerometerVB/MainPage.xaml.vb
|
Visual Basic
|
mit
| 3,429
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var informationCircled = exports.informationCircled = { "viewBox": "0 0 512 512", "children": [{ "name": "g", "attribs": {}, "children": [{ "name": "path", "attribs": { "d": "M480,253C478.3,129.3,376.7,30.4,253,32S30.4,135.3,32,259c1.7,123.7,103.3,222.6,227,221C382.7,478.3,481.7,376.7,480,253\r\n\t\tz M256,111.9c17.7,0,32,14.3,32,32s-14.3,32-32,32c-17.7,0-32-14.3-32-32S238.3,111.9,256,111.9z M300,395h-88v-11h22V224h-22v-12\r\n\t\th66v172h22V395z" }, "children": [{ "name": "path", "attribs": { "d": "M480,253C478.3,129.3,376.7,30.4,253,32S30.4,135.3,32,259c1.7,123.7,103.3,222.6,227,221C382.7,478.3,481.7,376.7,480,253\r\n\t\tz M256,111.9c17.7,0,32,14.3,32,32s-14.3,32-32,32c-17.7,0-32-14.3-32-32S238.3,111.9,256,111.9z M300,395h-88v-11h22V224h-22v-12\r\n\t\th66v172h22V395z" }, "children": [] }] }] }] };
|
xuan6/admin_dashboard_local_dev
|
node_modules/react-icons-kit/ionicons/informationCircled.js
|
JavaScript
|
mit
| 889
|
#ifndef __CF_TIMER_H_
#define __CF_TIMER_H_
#include <stdint.h>
#include <stdlib.h>
#include "cf_object_pool.h"
#include "cf_list.h"
typedef void(*time_cb_f)(void* param, uint32_t timer_id);
typedef void(*free_param_f)(void* param);
typedef struct
{
uint32_t id;
uint64_t ts; /*³¬Ê±Ê±¼ä*/
void* param;
time_cb_f cb;
free_param_f free_cb;
uint32_t magic;
}timer_node_t;
typedef struct
{
size_t size; /*IDÊý×éµÄ³¤¶È*/
uint32_t pos;
uint32_t number; /*ÓÐЧµÄtime node¸öÊý*/
ob_pool_t* pool; /*timer node pool*/
timer_node_t** array; /*time IDÓëtimer_nodeµÄ¶ÔÓ¦¹ØÏµ*/
}timer_node_pool_t;
#define RING_SIZE 1024
typedef struct
{
timer_node_pool_t* node_pool;
uint64_t prev_ts; /*ÉÏÒ»´ÎÂÖתµÄʱ¼ä´Á*/
int first_pos;
int second_pos;
uint32_t* first_ring[RING_SIZE];
uint32_t* second_ring[RING_SIZE];
}cf_timer_t;
cf_timer_t* create_timer();
void destroy_timer(cf_timer_t* timer);
uint32_t add_timer(cf_timer_t* timer, void* param, time_cb_f cb, uint32_t delay);
void cancel_timer(cf_timer_t* timer, uint32_t id);
uint32_t reset_timer(cf_timer_t* timer, uint32_t id, uint32_t delay);
void expire_timer(cf_timer_t* timer);
#endif
|
yuanrongxi/sharing
|
common/cf_timer.h
|
C
|
mit
| 1,195
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_72) on Mon May 22 22:54:16 EDT 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>All Classes (JAQL SDK)</title>
<meta name="date" content="2017-05-22">
<link rel="stylesheet" type="text/css" href="javadoc.css" title="Style">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<h1 class="bar">All Classes</h1>
<div class="indexContainer">
<ul>
<li><a href="bhgomes/jaql/util/ColumnIterable.html" title="interface in bhgomes.jaql.util" target="classFrame"><span class="interfaceName">ColumnIterable</span></a></li>
<li><a href="bhgomes/jaql/util/ColumnIterator.html" title="class in bhgomes.jaql.util" target="classFrame">ColumnIterator</a></li>
<li><a href="bhgomes/jaql/conn/ConnectionManager.html" title="class in bhgomes.jaql.conn" target="classFrame">ConnectionManager</a></li>
<li><a href="bhgomes/jaql/conn/ConnectionNotFoundException.html" title="class in bhgomes.jaql.conn" target="classFrame">ConnectionNotFoundException</a></li>
<li><a href="bhgomes/jaql/Database.html" title="class in bhgomes.jaql" target="classFrame">Database</a></li>
<li><a href="bhgomes/jaql/io/FileManager.html" title="class in bhgomes.jaql.io" target="classFrame">FileManager</a></li>
<li><a href="bhgomes/jaql/JAQL.html" title="class in bhgomes.jaql" target="classFrame">JAQL</a></li>
<li><a href="bhgomes/jaql/io/JAQLFile.html" title="class in bhgomes.jaql.io" target="classFrame">JAQLFile</a></li>
<li><a href="bhgomes/jaql/io/JAQLFileException.html" title="class in bhgomes.jaql.io" target="classFrame">JAQLFileException</a></li>
<li><a href="bhgomes/jaql/lang/LangObject.html" title="class in bhgomes.jaql.lang" target="classFrame">LangObject</a></li>
<li><a href="bhgomes/jaql/lang/LangObject.Type.html" title="enum in bhgomes.jaql.lang" target="classFrame">LangObject.Type</a></li>
<li><a href="bhgomes/jaql/logging/Level.html" title="class in bhgomes.jaql.logging" target="classFrame">Level</a></li>
<li><a href="bhgomes/jaql/logging/LogFormatter.html" title="class in bhgomes.jaql.logging" target="classFrame">LogFormatter</a></li>
<li><a href="bhgomes/jaql/LoggableException.html" title="class in bhgomes.jaql" target="classFrame">LoggableException</a></li>
<li><a href="bhgomes/jaql/logging/LoggableManager.html" title="class in bhgomes.jaql.logging" target="classFrame">LoggableManager</a></li>
<li><a href="bhgomes/jaql/logging/Logger.html" title="class in bhgomes.jaql.logging" target="classFrame">Logger</a></li>
<li><a href="bhgomes/jaql/LogicException.html" title="class in bhgomes.jaql" target="classFrame">LogicException</a></li>
<li><a href="bhgomes/jaql/util/MultiIterable.html" title="interface in bhgomes.jaql.util" target="classFrame"><span class="interfaceName">MultiIterable</span></a></li>
<li><a href="bhgomes/jaql/util/MultiIterator.html" title="class in bhgomes.jaql.util" target="classFrame">MultiIterator</a></li>
<li><a href="bhgomes/jaql/lang/ResultModel.html" title="class in bhgomes.jaql.lang" target="classFrame">ResultModel</a></li>
<li><a href="bhgomes/jaql/util/RowIterable.html" title="interface in bhgomes.jaql.util" target="classFrame"><span class="interfaceName">RowIterable</span></a></li>
<li><a href="bhgomes/jaql/util/RowIterator.html" title="class in bhgomes.jaql.util" target="classFrame">RowIterator</a></li>
<li><a href="bhgomes/jaql/lang/Statement.html" title="class in bhgomes.jaql.lang" target="classFrame">Statement</a></li>
<li><a href="bhgomes/jaql/logging/STDOUT.html" title="class in bhgomes.jaql.logging" target="classFrame">STDOUT</a></li>
<li><a href="bhgomes/jaql/lang/Table.html" title="class in bhgomes.jaql.lang" target="classFrame">Table</a></li>
<li><a href="bhgomes/jaql/lang/Table.Coord.html" title="class in bhgomes.jaql.lang" target="classFrame">Table.Coord</a></li>
<li><a href="bhgomes/jaql/lang/Table.Direction.html" title="enum in bhgomes.jaql.lang" target="classFrame">Table.Direction</a></li>
</ul>
</div>
</body>
</html>
|
bhgomes/jaql
|
docs/javadoc/allclasses-frame.html
|
HTML
|
mit
| 4,121
|
---
layout: post
title: Markdown 语法速查
category: 语言
tags: Markdown
description: Markdown 语法速查
---
# Markdown 速查
## 标题
[Setext][] 式, 使用`=`与`-`作下划底线行表示高低阶标题.
This is an H1
=============
This is an H2
-------------
[atx][] 式, 通过行首不同个数`#`符表示标题层次.
# 这是 H1
## 这是 H2
###### 这是 H6
## 语句换行
以下方法:
* 行末添加两个空格;
* 使用HTML换行标签`<br>`;
## 段落
段落由若干个连续的文本行组成, 以空行作为起始与结束,
行内可换行.
## 链接
### 行内式
格式: \[链接文字](链接地址 "可选链接标题")
* 链接资源位于同一主机的, 可使用相对路径;
### 参考式
使用格式: \[链接文字][链接标识符]
* 可省略标识符, 此时表示链接文字为标识符;
* 链接文字标识符间可添加空格;
* 标识符合法字符有: 字母, 数字, 空白和标点符号, 其中字母不区分大小写;
定义格式: \[链接表示符]: 链接地址 "可选链接标题"
* 冒号后需要至少一空白符;
* 链接地址可用尖括号`<>`包围;
* 可选链接标题可用双引号, 圆括弧或单引号(某些版本不支持单引号)包围;
### 自动链接
格式: <链接地址>
* 支持网址与邮箱地址;
* 链接文字为地址本身;
## 格式显示
### 行内式代码标签
使用反引号`` ` ``将标签包围即可,
若要表示反引号本身, 则可使用多个反引号包围即可.
### 段落式代码
使用三个反引号包围段落, 且前后需要至少一个空行.
### 原始格式显示
将原始格式统一缩进即可.
## 列表
无序列表使用字符`*`, `+`, `-`字符并加一空白字符作为行首 ,
有序字符使用数字加点号加上至少一空白字符作为行首, 数字不要求有序.
## 分隔线
在一行中使用重复的三个以上`*`, `-`, `_`字符, 且无除空白符外的字符, 则显示分隔线.
## 强调
将文字用 `*`或`_`包围表示强调, 使用重复的两个以上字符表示更加强调.
## 图片
不提倡使用图片
图片格式与链接格式相同, 只需在使用链接前添加感叹号`!`.
## 反转义
在特使字符前添加反斜杠以显示该字符.
[Setext]: <http://en.wikipedia.org/wiki/Setext>
[atx]: <http://www.aaronsw.com/2002/atx/>
|
ticty/ticty.github.io
|
_posts/Program Language/2015-04-19-Markdown.md
|
Markdown
|
mit
| 2,448
|
import {Injectable} from '@angular/core';
import {db, model} from 'baqend';
/**
* Dieser Service stellt den Bewerber zum eingeloggten User bereit (z.B. für Bewerber-Profil)
*/
@Injectable()
export class BewerberService {
public getBewerber(): Promise<model.Bewerber> {
return db.Bewerber.find().equal('user', db.User.me).singleResult();
}
public getNewBewerber(): model.Bewerber {
const bewerber = new db.Bewerber();
bewerber.user = db.User.me;
bewerber.sprachen = [];
bewerber.vertragsarten = [];
bewerber.email = db.User.me.username;
return bewerber;
}
}
|
v1ctr/name
|
src/app/_services/bewerber.service.ts
|
TypeScript
|
mit
| 636
|
/**
* Set the Job state data
* @param {string} id - the job id
* @param {IState} state - the state document
*/
function setJobState(id: string, state: IState) {
let context: IContext = getContext();
let collection: ICollection = context.getCollection();
let response: IResponse = getContext().getResponse();
let collectionLink: string = collection.getAltLink();
let documentLink: string = `${collectionLink}/docs/${id}`;
// default response
response.setBody(false);
let isAccepted: boolean = collection.readDocument(documentLink, (error: IRequestCallbackError, job: IJob) => {
if (error) {
throw error;
}
job.state_id = state.id;
job.state_name = state.name;
let options: IReplaceOptions = { etag: job._etag };
let success: boolean = collection.replaceDocument(job._self, job, options, (err: IRequestCallbackError) => {
if (err) {
throw err;
}
response.setBody(true);
});
if (!success) {
throw new Error("The call was not accepted");
}
});
if (!isAccepted) {
throw new Error("The call was not accepted");
}
}
|
imranmomin/Hangfire.AzureDocumentDB
|
src/StoredProcedure/setJobState.ts
|
TypeScript
|
mit
| 1,221
|
# Chapter 2. Type less, Do more
## Semicolons
* **continued after** = { , . operator
## Variable Declarations
* val (value object)
* var (change value, don't change object type)
* initialized immediately
- except: using at constructor
* no primitive type
* use **val**
## Ranges
* literal
* Int, Long, Float, Double, Char, BigInt, BigDecimal
```scala
1 to 10
1 until 10
1 to 10 by 3
10 to 1 by -3
1.1f to 10.3f by 3.1f // Float
1.1 to 10.3 by 3.1 // Double
'a' to 'g' by 3 // Char
BigInt(1) to BigInt(10) by 3
```
## Partial Function
* Functions are partial in the sense that they aren't defined for all possible inputs, only those inputs that match at least one of the specified case clause
* case clauses, enclosed in curly braces {}
* isDefinedAt for check
* chain PartialFunctions
```scala
val pf1: PartialFunction[Any,String] = { case s: String => "Yes" }
val pf2: PartialFunction[Any,Double] = { case d: Double => "Yes" }
val pf = pf1 orElse pf2
```
## Method Declarations
### Method Default and Named Arguments
* case class copy method
* used with parameter name
```scala
val p1 = new Point(x=3.3, y=4.4)
val p2 = p1.copy(y=6.6)
```
### Methods with Multiple Argument Lists
* function( , ) == function ( )( )
```scala
def draw(offset: Point = Point(0.0,0.0))(f: String => Unit): Unit = { ... }
```
```scala
s.draw(Point(1.0,2.0))(str => println(s"Shapes..."))
```
* **change argument list ( ) => { }**
```scala
s.draw(Point(1.0,2.0)){
str => println(s"Shapes...")
}
```
* **3 case with last argument**
- ( ) -> { }
- type inference
- implicit argument
### Future
* implicit argument
```scala
apply[T](body: => T)(implicit executor: ExecutionContext): = { ... }
```
* implicit val
```scala
object Implicits {
implicit val global: ExecutionContext ...
}
```
### Nesting Method Definitions and Recursion
* Method definition can also be nested
- using recursively, divided to small functions
* Parameter shadow
- The use of i as parameter of nested function shadow outer use of i
* tail-call optimization
- convert a tail-call optimization into a loop
- use @tailrec
- except: trampoline calls i.e. "a calls b calls a calls b"
### Inferring Type Information
```scala
val intToStringMap2 = new HashMap[Integer,String]
```
* Subtype polymorphism (inheritance): Limited Inferring Type
* Explicit Type Annotations
- val, var declaration don't assign value i.e. abstract class
- All method parameter
- method return type
+ explicit use ```return```
+ recursive
+ overloading method & one call another
+ infered by Any
* variadic method
```scala
def joiner(strings: String*): String = Strings.mkString("-")
def joiner(strings: List[String]): String = joiner(strings: _*)
```
- ```_*``` : inferred type + variadic
## Reserved Words
* def : start method declaration
* forSome : used in existential type declaration
* implicit
* lazy
* match
* object
* override
* sealed : applied to a parent type
* super
* trait : mixin module
* val
* var
* with
* yield
* none
- *break, continue*
* escape reserved word : use `match`
## Literal Values
### Integer Literals
* Decimal
* Hexadecimal
* Type
- Long, Int, Short, Char, Byte, Range
### Floating-Point Literals
* Float : postfix ```'f' or 'F'```
* Double
### Boolean Literals
### Character Literals
```
'A', '\u0041', '\n', '\012'
```
* escape character: \b, \t, \n, \f, \r, \", \', \\
### String Literals
* """ : multiline string literal
- white space indentation : |
### Symbol Literals
* interned strings
* refer to the same object in memory
```
Symbol("Programming Scala")
```
### Function Literals
```
val f1: (Int,String) => String = (i, s) => s+i
val f2: Function2[Int,String,String] = (i, s) => s+i
```
### Tuple Literals
* First class value
* immutable
* ( , , )
* Pair
- ( 1, "one")
- 1 -> "one"
- Tuple2(1, "one")
### Option, Some, None : Avoiding nulls
* Option : abstract
- Some
- None
* ```None.get```: NoSuchElementException
- use getOrElse
* **don't use null**
## Sealed Class Hierachies
* prevent users from creating their own
* ```sealed class ... ```
- must be declared in the same source file
## Organizing Code in Files and Namespaces
* Doesn't have to match
- filename and typename
- package structure and directory structure
```
package a.b.c {
...
}
```
or
```
package a {
package b {
package c {
...
}
}
}
```
* successive package statement idiom
* bring into scope all packages level
* package can not be defined within classes and method
## Importing Types and Their Members
* use import
* _ : as a wildcard
* import static => import
* { } : selective importing
* You can put import state almost any where
- scope
* undefined => _
* alias
```scala
def stuffWithBigInteger() = {
import java.math.BigInteger.{
ONE => _, // undefined
TEN,
ZERO => JAVAZERO // alias
}
}
```
### Import Are Relative
```
import scala.collection.mutable._
import collection.immutable._
import _root_.scala.collection.parallel._
```
### Package Objects
* Appropriate members to expose to client
### Abstract type Versus Parameterized Type
* Parameterized Type
- Similar to generic
- use [ ]
- Each Types are independent
- Parametric Polymorphism
- +A : covariant typing
- -A : contravaiant typing
```scala
sealed abstract class List[+A]
```
```scala
abstract class BulkReader[In] {
val source: In
def read: String
}
class StringBulkReader(val source: String) extends BulkReader[String] {
def read: String = source
}
class FileBulkReader(val source: File) extends BulkReader[File] {
def read: String = {
val in = new BufferedInputStream(new FileInputStream(source))
val numBytes = in.available()
val bytes = new Array[Byte](numBytes)
in.read(bytes, 0, numBytes)
new String(bytes)
}
}
```
* Abstract Type
- type abstract mechanism
- can be a member of type
- match the *behaviours*
- evolve in parallel
- family polymorphism
- covariant specialization
```scala
import java.io._
abstract class BulkReader {
type In
val source: In
def read: String // Read source and return a String
}
class StringBulkReader(val source: String) extends BulkReader {
type In = String
def read: String = source
}
class FileBulkReader(val source: File) extends BulkReader {
type In = File
def read: String = {
val in = new BufferedInputStream(new FileInputStream(source))
val numBytes = in.available()
var bytes = new Array[Byte](numBytes)
in.read(bytes, 0, numBytes)
new String(bytes)
}
}
println(new StringBulkReader("Hello Scala!").read)
println(new FileBulkReader(new File("TypeLessDoMore/abstract-types.sc")).read)
```
|
younggi/books
|
programming_scala/Chapter2.md
|
Markdown
|
mit
| 7,353
|
package me.realmoriss.prog3.nagyhf.entities;
import me.realmoriss.prog3.nagyhf.entities.primitives.Vec2D;
/**
* Created on 11/30/16.
*/
public class CyanBrick extends Brick {
private static final String DEF_CLASSNAME = "prop_brick_cyan";
public CyanBrick(Vec2D pos, String name) {
super(pos, name, "cyan");
classname = DEF_CLASSNAME;
}
}
|
realmoriss/prog3
|
nagyhf/src/me/realmoriss/prog3/nagyhf/entities/CyanBrick.java
|
Java
|
mit
| 349
|
var webpack = require('webpack');
var path = require('path');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://127.0.0.1:3000', // WebpackDevServer host and port
'webpack/hot/only-dev-server',
'./src/js/index.js' // Your appʼs entry point
],
output: {
path: path.join(__dirname, 'build'),
filename: 'bundle.js',
publicPath: '/static/'
},
module: {
loaders: [
{ test: /\.less$/, loader: 'style-loader!css-loader!less-loader' },
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{ test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192'},
{ test: /\.js?$/, loaders: ['react-hot', 'babel'], include: [path.join(__dirname, 'src/js')]}
]
},
resolve: {
root: [path.resolve(__dirname)],
extensions: ['', '.js', '.jsx']
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]
};
|
firKing/the-jigsaw-puzzle
|
webpack.config.js
|
JavaScript
|
mit
| 896
|
import re
list_re = re.compile(r'\((.*)\) \"(.*)\" \"(.*)\"')
class Response(object):
# There are three possible server completion responses
OK = "OK" # indicates success
NO = "NO" # indicates failure
BAD = "BAD" # indicates a protocol error
class ListResponse(object):
def __init__(self, list_response):
match = list_re.match(list_response)
self.attributes = match.group(1).split()
self.hierarchy_delimiter = match.group(2)
self.name = match.group(3)
|
clara-labs/imaplib3
|
imaplib3/response.py
|
Python
|
mit
| 513
|
<?php
declare(strict_types = 1);
namespace Innmind\Immutable;
/**
* @template T
* @psalm-immutable
*/
final class Set implements \Countable
{
/** @var Set\Implementation<T> */
private Set\Implementation $implementation;
private function __construct(Set\Implementation $implementation)
{
$this->implementation = $implementation;
}
/**
* Add an element to the set
*
* Example:
* <code>
* Set::of()(1)(3)
* </code>
*
* @param T $element
*
* @return self<T>
*/
public function __invoke($element): self
{
return new self(($this->implementation)($element));
}
/**
* @template V
* @no-named-arguments
* @psalm-pure
*
* @param V $values
*
* @return self<V>
*/
public static function of(...$values): self
{
return new self(Set\Primitive::of(...$values));
}
/**
* It will load the values inside the generator only upon the first use
* of the set
*
* Use this mode when the amount of data may not fit in memory
*
* @template V
* @psalm-pure
*
* @param \Generator<V> $generator
*
* @return self<V>
*/
public static function defer(\Generator $generator): self
{
return new self(Set\Defer::of($generator));
}
/**
* It will call the given function every time a new operation is done on the
* set. This means the returned structure may not be truly immutable as
* between the calls the underlying source may change.
*
* Use this mode when calling to an external source (meaning IO bound) such
* as parsing a file or calling an API
*
* @template V
* @psalm-pure
* @psalm-type RegisterCleanup = callable(callable(): void): void
*
* @param callable(RegisterCleanup): \Generator<V> $generator
*
* @return self<V>
*/
public static function lazy(callable $generator): self
{
return new self(Set\Lazy::of($generator));
}
/**
* @no-named-arguments
* @psalm-pure
*
* @return self<mixed>
*/
public static function mixed(mixed ...$values): self
{
return new self(Set\Primitive::of(...$values));
}
/**
* @no-named-arguments
* @psalm-pure
*
* @return self<int>
*/
public static function ints(int ...$values): self
{
/** @var self<int> */
$self = new self(Set\Primitive::of(...$values));
return $self;
}
/**
* @no-named-arguments
* @psalm-pure
*
* @return self<float>
*/
public static function floats(float ...$values): self
{
/** @var self<float> */
$self = new self(Set\Primitive::of(...$values));
return $self;
}
/**
* @no-named-arguments
* @psalm-pure
*
* @return self<string>
*/
public static function strings(string ...$values): self
{
/** @var self<string> */
$self = new self(Set\Primitive::of(...$values));
return $self;
}
/**
* @no-named-arguments
* @psalm-pure
*
* @return self<object>
*/
public static function objects(object ...$values): self
{
/** @var self<object> */
$self = new self(Set\Primitive::of(...$values));
return $self;
}
public function size(): int
{
return $this->implementation->size();
}
public function count(): int
{
return $this->implementation->size();
}
/**
* Intersect this set with the given one
*
* @param self<T> $set
*
* @return self<T>
*/
public function intersect(self $set): self
{
return new self($this->implementation->intersect(
$set->implementation,
));
}
/**
* Add an element to the set
*
* @param T $element
*
* @return self<T>
*/
public function add($element): self
{
return ($this)($element);
}
/**
* Check if the set contains the given element
*
* @param T $element
*/
public function contains($element): bool
{
return $this->implementation->contains($element);
}
/**
* Remove the element from the set
*
* @param T $element
*
* @return self<T>
*/
public function remove($element): self
{
return new self($this->implementation->remove($element));
}
/**
* Return the diff between this set and the given one
*
* @param self<T> $set
*
* @return self<T>
*/
public function diff(self $set): self
{
return new self($this->implementation->diff(
$set->implementation,
));
}
/**
* Check if the given set is identical to this one
*
* @param self<T> $set
*/
public function equals(self $set): bool
{
return $this->implementation->equals($set->implementation);
}
/**
* Return all elements that satisfy the given predicate
*
* @param callable(T): bool $predicate
*
* @return self<T>
*/
public function filter(callable $predicate): self
{
return new self($this->implementation->filter($predicate));
}
/**
* Apply the given function to all elements of the set
*
* @param callable(T): void $function
*/
public function foreach(callable $function): SideEffect
{
return $this->implementation->foreach($function);
}
/**
* Return a new map of pairs grouped by keys determined with the given
* discriminator function
*
* @template D
*
* @param callable(T): D $discriminator
*
* @return Map<D, self<T>>
*/
public function groupBy(callable $discriminator): Map
{
return $this->implementation->groupBy($discriminator);
}
/**
* Return a new set by applying the given function to all elements
*
* @template S
*
* @param callable(T): S $function
*
* @return self<S>
*/
public function map(callable $function): self
{
return new self($this->implementation->map($function));
}
/**
* Merge all sets created by each value from the original set
*
* @template S
*
* @param callable(T): self<S> $map
*
* @return self<S>
*/
public function flatMap(callable $map): self
{
/**
* @psalm-suppress InvalidArgument
* @psalm-suppress MixedArgument
*/
return $this->reduce(
self::of(),
static fn(self $carry, $value) => $carry->merge($map($value)),
);
}
/**
* Return a sequence of 2 sets partitioned according to the given predicate
*
* @param callable(T): bool $predicate
*
* @return Map<bool, self<T>>
*/
public function partition(callable $predicate): Map
{
return $this->implementation->partition($predicate);
}
/**
* Return a sequence sorted with the given function
*
* @param callable(T, T): int $function
*
* @return Sequence<T>
*/
public function sort(callable $function): Sequence
{
return $this->implementation->sort($function);
}
/**
* Create a new set with elements of both sets
*
* @param self<T> $set
*
* @return self<T>
*/
public function merge(self $set): self
{
return new self($this->implementation->merge(
$set->implementation,
));
}
/**
* Reduce the set to a single value
*
* @template R
*
* @param R $carry
* @param callable(R, T): R $reducer
*
* @return R
*/
public function reduce($carry, callable $reducer)
{
return $this->implementation->reduce($carry, $reducer);
}
/**
* Return a set of the same type but without any value
*
* @return self<T>
*/
public function clear(): self
{
return new self($this->implementation->clear());
}
public function empty(): bool
{
return $this->implementation->empty();
}
/**
* @param callable(T): bool $predicate
*
* @return Maybe<T>
*/
public function find(callable $predicate): Maybe
{
return $this->implementation->find($predicate);
}
/**
* @param callable(T): bool $predicate
*/
public function matches(callable $predicate): bool
{
/** @psalm-suppress MixedArgument */
return $this->reduce(
true,
static fn(bool $matches, $value): bool => $matches && $predicate($value),
);
}
/**
* @param callable(T): bool $predicate
*/
public function any(callable $predicate): bool
{
return $this->find($predicate)->match(
static fn() => true,
static fn() => false,
);
}
/**
* @return list<T>
*/
public function toList(): array
{
/**
* @psalm-suppress MixedAssignment
* @var list<T>
*/
return $this->reduce(
[],
static function(array $carry, $value): array {
$carry[] = $value;
return $carry;
},
);
}
}
|
Innmind/Immutable
|
src/Set.php
|
PHP
|
mit
| 9,424
|
#!/usr/bin/env python
import argparse
import bz2
import gzip
import os.path
import sys
from csvkit import CSVKitReader
from csvkit.exceptions import ColumnIdentifierError, RequiredHeaderError
def lazy_opener(fn):
def wrapped(self, *args, **kwargs):
self._lazy_open()
fn(*args, **kwargs)
return wrapped
class LazyFile(object):
"""
A proxy for a File object that delays opening it until
a read method is called.
Currently this implements only the minimum methods to be useful,
but it could easily be expanded.
"""
def __init__(self, init, *args, **kwargs):
self.init = init
self.f = None
self._is_lazy_opened = False
self._lazy_args = args
self._lazy_kwargs = kwargs
def __getattr__(self, name):
if not self._is_lazy_opened:
self.f = self.init(*self._lazy_args, **self._lazy_kwargs)
self._is_lazy_opened = True
return getattr(self.f, name)
def __iter__(self):
return self
def close(self):
self.f.close()
self.f = None
self._is_lazy_opened = False
def next(self):
if not self._is_lazy_opened:
self.f = self.init(*self._lazy_args, **self._lazy_kwargs)
self._is_lazy_opened = True
return self.f.next()
class CSVFileType(object):
"""
An argument factory like argparse.FileType with compression support.
"""
def __init__(self, mode='rb'):
"""
Initialize the factory.
"""
self._mode = mode
def __call__(self, path):
"""
Build a file-like object from the specified path.
"""
if path == '-':
if 'r' in self._mode:
return sys.stdin
elif 'w' in self._mode:
return sys.stdout
else:
raise ValueError('Invalid path "-" with mode {0}'.format(self._mode))
else:
(_, extension) = os.path.splitext(path)
if extension == '.gz':
return LazyFile(gzip.open, path, self._mode)
if extension == '.bz2':
return LazyFile(bz2.BZ2File, path, self._mode)
else:
return LazyFile(open, path, self._mode)
class CSVKitUtility(object):
description = ''
epilog = ''
override_flags = ''
def __init__(self, args=None, output_file=None):
"""
Perform argument processing and other setup for a CSVKitUtility.
"""
self._init_common_parser()
self.add_arguments()
self.args = self.argparser.parse_args(args)
self.reader_kwargs = self._extract_csv_reader_kwargs()
self.writer_kwargs = self._extract_csv_writer_kwargs()
self._install_exception_handler()
if output_file is None:
self.output_file = sys.stdout
else:
self.output_file = output_file
# Ensure SIGPIPE doesn't throw an exception
# Prevents [Errno 32] Broken pipe errors, e.g. when piping to 'head'
# To test from the shell:
# python -c "for i in range(5000): print 'a,b,c'" | csvlook | head
# Without this fix you will see at the end:
# [Errno 32] Broken pipe
# With this fix, there should be no error
# For details on Python and SIGPIPE, see http://bugs.python.org/issue1652
try:
import signal
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
except (ImportError, AttributeError):
#Do nothing on platforms that don't have signals or don't have SIGPIPE
pass
def add_arguments(self):
"""
Called upon initialization once the parser for common arguments has been constructed.
Should be overriden by individual utilities.
"""
raise NotImplementedError('add_arguments must be provided by each subclass of CSVKitUtility.')
def main(self):
"""
Main loop of the utility.
Should be overriden by individual utilities and explicitly called by the executing script.
"""
raise NotImplementedError(' must be provided by each subclass of CSVKitUtility.')
def _init_common_parser(self):
"""
Prepare a base argparse argument parser so that flags are consistent across different shell command tools.
If you want to constrain which common args are present, you can pass a string for 'omitflags'. Any argument
whose single-letter form is contained in 'omitflags' will be left out of the configured parser. Use 'f' for
file.
"""
self.argparser = argparse.ArgumentParser(description=self.description, epilog=self.epilog)
# Input
if 'f' not in self.override_flags:
self.argparser.add_argument('file', metavar="FILE", nargs='?', type=CSVFileType(), default=sys.stdin,
help='The CSV file to operate on. If omitted, will accept input on STDIN.')
if 'd' not in self.override_flags:
self.argparser.add_argument('-d', '--delimiter', dest='delimiter',
help='Delimiting character of the input CSV file.')
if 't' not in self.override_flags:
self.argparser.add_argument('-t', '--tabs', dest='tabs', action='store_true',
help='Specifies that the input CSV file is delimited with tabs. Overrides "-d".')
if 'q' not in self.override_flags:
self.argparser.add_argument('-q', '--quotechar', dest='quotechar',
help='Character used to quote strings in the input CSV file.')
if 'u' not in self.override_flags:
self.argparser.add_argument('-u', '--quoting', dest='quoting', type=int, choices=[0,1,2,3],
help='Quoting style used in the input CSV file. 0 = Quote Minimal, 1 = Quote All, 2 = Quote Non-numeric, 3 = Quote None.')
if 'b' not in self.override_flags:
self.argparser.add_argument('-b', '--doublequote', dest='doublequote', action='store_true',
help='Whether or not double quotes are doubled in the input CSV file.')
if 'p' not in self.override_flags:
self.argparser.add_argument('-p', '--escapechar', dest='escapechar',
help='Character used to escape the delimiter if --quoting 3 ("Quote None") is specified and to escape the QUOTECHAR if --doublequote is not specified.')
if 'z' not in self.override_flags:
self.argparser.add_argument('-z', '--maxfieldsize', dest='maxfieldsize', type=int,
help='Maximum length of a single field in the input CSV file.')
if 'e' not in self.override_flags:
self.argparser.add_argument('-e', '--encoding', dest='encoding', default='utf-8',
help='Specify the encoding the input CSV file.')
if 'S' not in self.override_flags:
self.argparser.add_argument('-S', '--skipinitialspace', dest='skipinitialspace', default=False, action='store_true',
help='Ignore whitespace immediately following the delimiter.')
if 'H' not in self.override_flags:
self.argparser.add_argument('-H', '--no-header-row', dest='no_header_row', action='store_true',
help='Specifies that the input CSV file has no header row. Will create default headers.')
if 'v' not in self.override_flags:
self.argparser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
help='Print detailed tracebacks when errors occur.')
# Output
if 'l' not in self.override_flags:
self.argparser.add_argument('-l', '--linenumbers', dest='line_numbers', action='store_true',
help='Insert a column of line numbers at the front of the output. Useful when piping to grep or as a simple primary key.')
# Input/Output
if 'zero' not in self.override_flags:
self.argparser.add_argument('--zero', dest='zero_based', action='store_true',
help='When interpreting or displaying column numbers, use zero-based numbering instead of the default 1-based numbering.')
def _extract_csv_reader_kwargs(self):
"""
Extracts those from the command-line arguments those would should be passed through to the input CSV reader(s).
"""
kwargs = {}
if self.args.encoding:
kwargs['encoding'] = self.args.encoding
if self.args.tabs:
kwargs['delimiter'] = '\t'
elif self.args.delimiter:
kwargs['delimiter'] = self.args.delimiter
if self.args.quotechar:
kwargs['quotechar'] = self.args.quotechar
if self.args.quoting:
kwargs['quoting'] = self.args.quoting
if self.args.doublequote:
kwargs['doublequote'] = self.args.doublequote
if self.args.escapechar:
kwargs['escapechar'] = self.args.escapechar
if self.args.maxfieldsize:
kwargs['maxfieldsize'] = self.args.maxfieldsize
if self.args.skipinitialspace:
kwargs['skipinitialspace'] = self.args.skipinitialspace
return kwargs
def _extract_csv_writer_kwargs(self):
"""
Extracts those from the command-line arguments those would should be passed through to the output CSV writer.
"""
kwargs = {}
if 'l' not in self.override_flags and self.args.line_numbers:
kwargs['line_numbers'] = True
return kwargs
def _install_exception_handler(self):
"""
Installs a replacement for sys.excepthook, which handles pretty-printing uncaught exceptions.
"""
def handler(t, value, traceback):
if self.args.verbose:
sys.__excepthook__(t, value, traceback)
else:
# Special case handling for Unicode errors, which behave very strangely
# when cast with unicode()
if t == UnicodeDecodeError:
sys.stderr.write('Your file is not "%s" encoded. Please specify the correct encoding with the -e flag. Use the -v flag to see the complete error.\n' % self.args.encoding)
else:
sys.stderr.write('%s\n' % unicode(value).encode('utf-8'))
sys.excepthook = handler
def print_column_names(self):
"""
Pretty-prints the names and indices of all columns to a file-like object (usually sys.stdout).
"""
if self.args.no_header_row:
raise RequiredHeaderError, 'You cannot use --no-header-row with the -n or --names options.'
f = self.args.file
output = self.output_file
try:
zero_based=self.args.zero_based
except:
zero_based=False
rows = CSVKitReader(f, **self.reader_kwargs)
column_names = rows.next()
for i, c in enumerate(column_names):
if not zero_based:
i += 1
output.write('%3i: %s\n' % (i, c))
def match_column_identifier(column_names, c, zero_based=False):
"""
Determine what column a single column id (name or index) matches in a series of column names.
Note that integer values are *always* treated as positional identifiers. If you happen to have
column names which are also integers, you must specify them using a positional index.
"""
if isinstance(c, basestring) and not c.isdigit() and c in column_names:
return column_names.index(c)
else:
try:
c = int(c)
if not zero_based:
c -= 1
# Fail out if neither a column name nor an integer
except:
raise ColumnIdentifierError('Column identifier "%s" is neither an integer, nor a existing column\'s name.' % c)
# Fail out if index is 0-based
if c < 0:
raise ColumnIdentifierError('Column 0 is not valid; columns are 1-based.')
# Fail out if index is out of range
if c >= len(column_names):
raise ColumnIdentifierError('Index %i is beyond the last named column, "%s" at index %i.' % (c, column_names[-1], len(column_names) - 1))
return c
def parse_column_identifiers(ids, column_names, zero_based=False, excluded_columns=None):
"""
Parse a comma-separated list of column indices AND/OR names into a list of integer indices.
Ranges of integers can be specified with two integers separated by a '-' or ':' character. Ranges of
non-integers (e.g. column names) are not supported.
Note: Column indices are 1-based.
"""
columns = []
# If not specified, start with all columns
if not ids:
columns = range(len(column_names))
if columns and not excluded_columns:
return columns
if not columns:
for c in ids.split(','):
c = c.strip()
try:
columns.append(match_column_identifier(column_names, c, zero_based))
except ColumnIdentifierError:
if ':' in c:
a,b = c.split(':',1)
elif '-' in c:
a,b = c.split('-',1)
else:
raise
try:
if a:
a = int(a)
else:
a = 1
if b:
b = int(b) + 1
else:
b = len(column_names)
except ValueError:
raise ColumnIdentifierError("Invalid range %s. Ranges must be two integers separated by a - or : character.")
for x in range(a,b):
columns.append(match_column_identifier(column_names, x, zero_based))
excludes = []
if excluded_columns:
for c in excluded_columns.split(','):
c = c.strip()
try:
excludes.append(match_column_identifier(column_names, c, zero_based))
except ColumnIdentifierError:
if ':' in c:
a,b = c.split(':',1)
elif '-' in c:
a,b = c.split('-',1)
else:
raise
try:
if a:
a = int(a)
else:
a = 1
if b:
b = int(b) + 1
else:
b = len(column_names)
except ValueError:
raise ColumnIdentifierError("Invalid range %s. Ranges must be two integers separated by a - or : character.")
for x in range(a,b):
excludes.append(match_column_identifier(column_names, x, zero_based))
return [c for c in columns if c not in excludes]
|
cypreess/csvkit
|
csvkit/cli.py
|
Python
|
mit
| 15,243
|
import { expect } from 'chai';
import request from '../src/reqwest-fetch';
/* eslint func-names: 0 */
/* eslint prefer-arrow-callback: 0 */
describe('reqwest-fetch', function () {
it('should accept json response', function () {
this.timeout(10000);
const test = request({ url: 'https://o.hahoo.cn/test.json' })
.then(function (res) {
expect(res.body).to.eql({ foo: 'bar' });
});
return test;
});
});
|
hahoocn/hahoorequest
|
test/reqwest-fetch.spec.js
|
JavaScript
|
mit
| 437
|
export {FormlyJigsawHeaderModule} from './header.module';
export {FormlyFieldHeader} from './header.type';
|
rdkmaster/jigsaw
|
src/ngx-formly/jigsaw/header/src/public_api.ts
|
TypeScript
|
mit
| 107
|
/* Shield UI 1.6.10 Trial Version | Copyright 2013-2014 Shield UI Ltd. | www.shieldui.com/eula */
.sui-window{border-color:#e7e7e7;color:#333;background-color:#fff;box-shadow:0 0 7px #e7e7e7}.sui-window-titlebar{color:#fff;border-color:#4fa7ef;background-color:#428bca}.sui-window-content{background-color:#fff}.sui-window-modal{background-color:#919191}
|
Etxea/adeges_extranet
|
web/shieldui/css/light-bootstrap/window.min.css
|
CSS
|
mit
| 354
|
<!doctype html>
<!--
Minimal Mistakes Jekyll Theme 4.5.1 by Michael Rose
Copyright 2017 Michael Rose - mademistakes.com | @mmistakes
Free for personal and commercial use under the MIT license
https://github.com/mmistakes/minimal-mistakes/blob/master/LICENSE.txt
-->
<html lang="en" class="no-js">
<head>
<meta charset="utf-8">
<!-- begin SEO -->
<title>IPOP</title>
<meta name="description" content="IP-Over-P2P, Open-source User-centric Software Virtual Network">
<meta name="author" content="">
<meta property="og:locale" content="en">
<meta property="og:site_name" content="IPOP">
<meta property="og:title" content="IPOP">
<script type="application/ld+json">
{
"@context" : "http://schema.org",
"@type" : "Person",
"name" : "IPOP",
"url" : null,
"sameAs" : null
}
</script>
<!-- end SEO -->
<link href="/feed.xml" type="application/atom+xml" rel="alternate" title="IPOP Feed">
<!-- http://t.co/dKP3o1e -->
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
document.documentElement.className = document.documentElement.className.replace(/\bno-js\b/g, '') + ' js ';
</script>
<!-- For all browsers -->
<link rel="stylesheet" href="/assets/css/main.css">
<!--[if lte IE 9]>
<style>
/* old IE unsupported flexbox fixes */
.greedy-nav .site-title {
padding-right: 3em;
}
.greedy-nav button {
position: absolute;
top: 0;
right: 0;
height: 100%;
}
</style>
<![endif]-->
<meta http-equiv="cleartype" content="on">
<!-- start custom head snippets -->
<!-- insert favicons. use http://realfavicongenerator.net/ -->
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">
<meta name="theme-color" content="#ffffff">
<!-- end custom head snippets -->
</head>
<body class="layout--wiki">
<!--[if lt IE 9]>
<div class="notice--danger align-center" style="margin: 0;">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</div>
<![endif]-->
<div class="masthead">
<div class="masthead__inner-wrap">
<div class="masthead__menu">
<nav id="site-nav" class="greedy-nav">
<a class="site-title" href="/">IPOP</a>
<ul class="visible-links">
<li class="masthead__menu-item"><a href="/about/">About</a></li>
<li class="masthead__menu-item"><a href="/wiki/Quick-Start">Quick Start</a></li>
<li class="masthead__menu-item"><a href="/download">Download</a></li>
<li class="masthead__menu-item"><a href="/learn/">Learn</a></li>
<li class="masthead__menu-item"><a href="/wiki/">Wiki</a></li>
<li class="masthead__menu-item"><a href="/whitepaper/">White Paper</a></li>
<li class="masthead__menu-item"><a href="/contribute/">Contribute</a></li>
<li class="masthead__menu-item"><a href="/contact/">Contact</a></li>
</ul>
<button><div class="navicon"></div></button>
<ul class="hidden-links hidden"></ul>
</nav>
</div>
</div>
</div>
<div id="main" role="main">
<article class="page" itemscope itemtype="http://schema.org/CreativeWork">
<div class="page__inner-wrap">
<section class="page__content" itemprop="text">
<aside class="sidebar__right">
<nav class="toc">
<header><h4 class="nav__title"><i class="fa fa-file-text"></i> On This Page</h4></header>
<ul class="section-nav">
<li class="toc-entry toc-h1"><a href="#use-ipop-on-ubuntu-and-raspberry-pi-manually">Use IPOP on Ubuntu and Raspberry Pi, Manually</a>
<ul>
<li class="toc-entry toc-h2"><a href="#download-and-install-dependencies">Download and Install Dependencies</a></li>
<li class="toc-entry toc-h2"><a href="#get-ipop-binary">Get IPOP Binary</a></li>
<li class="toc-entry toc-h2"><a href="#copy-configuration-file">Copy Configuration File</a></li>
<li class="toc-entry toc-h2"><a href="#run-ipop">Run IPOP</a>
<ul>
<li class="toc-entry toc-h3"><a href="#run-ipop-tincan">Run IPOP TinCan</a></li>
<li class="toc-entry toc-h3"><a href="#run-ipop-controller">Run IPOP Controller</a></li>
</ul>
</li>
<li class="toc-entry toc-h2"><a href="#stop-ipop">Stop IPOP</a>
<ul>
<li class="toc-entry toc-h3"><a href="#stop-ipop-tincan">Stop IPOP Tincan</a></li>
<li class="toc-entry toc-h3"><a href="#stop-ipop-controller">Stop IPOP Controller</a></li>
</ul>
</li>
<li class="toc-entry toc-h2"><a href="#remove-ipop">Remove IPOP</a></li>
</ul>
</li>
<li class="toc-entry toc-h1"><a href="#key-points-summary">Key Points Summary</a></li>
</ul>
</nav>
</aside>
<h1 id="use-ipop-on-ubuntu-and-raspberry-pi-manually">Use IPOP on Ubuntu and Raspberry Pi, Manually</h1>
<table>
<thead>
<tr>
<th> </th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Tested on</strong></td>
<td>Ubuntu 16.04 and 18.04 x64<br />Raspbian Jessie and Stretch on Raspberry Pi 3<br />Raspbian Stretch on Raspberry Pi Zero</td>
</tr>
<tr>
<td><strong>Time</strong></td>
<td>~ 10 Minutes</td>
</tr>
<tr>
<td><strong>Question(s)</strong></td>
<td>- How to install IPOP?<br /> - How to run IPOP?<br /> - How to remove IPOP?</td>
</tr>
<tr>
<td><strong>Objective(s)</strong></td>
<td>- Install IPOP<br /> - Run IPOP<br /> - Stop IPOP<br /> - Remove IPOP</td>
</tr>
</tbody>
</table>
<h2 id="download-and-install-dependencies">Download and Install Dependencies</h2>
<div class="language-shell highlighter-rouge"><pre class="highlight"><code>sudo apt-get update -y
sudo apt-get install -y python3 python3-pip iproute2 openvswitch-switch
sudo -H pip3 install psutil sleekxmpp requests
</code></pre>
</div>
<h2 id="get-ipop-binary">Get IPOP Binary</h2>
<p>Download the proper version of IPOP from <a href="https://github.com/ipop-project/Downloads/releases">our latest release</a>.</p>
<p>Then go to the download directory and extract the file (Put in the actual file name):</p>
<div class="language-shell highlighter-rouge"><pre class="highlight"><code>tar -xzvf ipop-vxxx.tar.gz
<span class="nb">cd </span>ipop-vxxx
</code></pre>
</div>
<h2 id="copy-configuration-file">Copy Configuration File</h2>
<p>You will need a valid configuration file (ipop-config.json) to run IPOP. Go to the directory you have your config file and copy the file to the <code class="highlighter-rouge">config</code> directory:</p>
<div class="language-shell highlighter-rouge"><pre class="highlight"><code>cp PATH/TO/CONFIGFILE/ipop-config.json config/
</code></pre>
</div>
<h2 id="run-ipop">Run IPOP</h2>
<h3 id="run-ipop-tincan">Run IPOP TinCan</h3>
<div class="language-shell highlighter-rouge"><pre class="highlight"><code>sudo ./ipop-tincan &
</code></pre>
</div>
<h3 id="run-ipop-controller">Run IPOP Controller</h3>
<div class="language-shell highlighter-rouge"><pre class="highlight"><code>python3 -m controller.Controller -c ./config/ipop-config.json &
</code></pre>
</div>
<p>Now, if everything is going well, IPOP should be run.</p>
<h2 id="stop-ipop">Stop IPOP</h2>
<h3 id="stop-ipop-tincan">Stop IPOP Tincan</h3>
<div class="language-shell highlighter-rouge"><pre class="highlight"><code>sudo killall ipop-tincan
</code></pre>
</div>
<h3 id="stop-ipop-controller">Stop IPOP Controller</h3>
<div class="language-shell highlighter-rouge"><pre class="highlight"><code>ps aux | grep -v grep | grep controller.Controller | awk <span class="s1">'{print $2}'</span> | xargs sudo <span class="nb">kill</span> -9
</code></pre>
</div>
<h2 id="remove-ipop">Remove IPOP</h2>
<p>To uninstall IPOP, its is safe to stop it first and then remove the IPOP execution directory.</p>
<hr />
<h1 id="key-points-summary">Key Points Summary</h1>
<ul>
<li>Run IPOP:</li>
</ul>
<div class="language-shell highlighter-rouge"><pre class="highlight"><code>sudo ./ipop-tincan &
python3 -m controller.Controller -c ./config/ipop-config.json &
</code></pre>
</div>
<ul>
<li>Stop IPOP:</li>
</ul>
<div class="language-shell highlighter-rouge"><pre class="highlight"><code>sudo killall ipop-tincan
ps aux | grep -v grep | grep controller.Controller | awk <span class="s1">'{print $2}'</span> | xargs sudo <span class="nb">kill</span> -9
</code></pre>
</div>
</section>
</div>
</article>
<div class="sidebar">
<nav class="nav__list">
<div class="wiki-top-links">
<a href="../wiki" class="display-unset">Wiki Home</a> / <a href="../wikipages" class="display-unset">Wiki Pages</a>
</div>
<ul>
<li><strong>Deploying IPOP-VPN</strong>
<ul>
<li><a href="Quick-Start">Quick Start</a></li>
<li><a href="Use-IPOP,-Intro">Installation</a></li>
<li>
<table>
<tbody>
<tr>
<td>[[Configuration</td>
<td>Understanding the IPOP Configuration]]</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
<li><strong>Development Guide</strong>
<ul>
<li><a href="Development-Workflow">Development Workflow</a></li>
<li><a href="Coding-Guidelines">Coding Guidelines</a></li>
<li><a href="Build-IPOP,-Intro">Building the Code</a></li>
<li><a href="IPOP-Scale-test-Walkthrough">Testing Your Build</a></li>
<li><a href="Controller-Framework">Controller Framework</a></li>
<li><a href="Controller-API">Controller API</a></li>
<li><a href="Build-WebRTC-Libraries,-Intro">Building WebRTC Libraries</a></li>
</ul>
</li>
<li><strong>General Documentation</strong>
<ul>
<li><a href="FAQs">FAQs</a></li>
<li><a href="Troubleshooting">Troubleshooting</a></li>
<li><a href="Planning-Your-Network">Planning Your Network</a></li>
<li><a href="Coding-Challenges">Coding Challenges</a></li>
<li><a href="Known-Issues">Known Issues</a></li>
<li><a href="Getting-Help">Getting Help</a></li>
<li><a href="How-to-Contribute">How to Contribute</a></li>
</ul>
</li>
</ul>
</section>
</div>
</article>
</div>
</nav>
</div>
</div>
<div class="page__footer">
<footer>
<!-- start custom footer snippets -->
<!-- end custom footer snippets -->
<!-- <div class="page__footer-follow">
<ul class="social-icons">
<li><strong>Follow:</strong></li>
-->
<!-- <li><a href="/feed.xml"><i class="fa fa-fw fa-rss-square" aria-hidden="true"></i> Feed</a></li> -->
<!-- </ul>
</div> -->
<div class="page__footer-copyright footer-address">
<div class="float-left">
<img src="/assets/images/uf_small.png" class="padding-bottom-right" /><img src="/assets/images/nsf_small.png" class="padding-bottom-right" />
</div>
<i class="fa fa-address-card-o" aria-hidden="true"></i>
<a href="http://www.acis.ufl.edu" rel="nofollow" target="_blank">ACIS Lab</a>, P.O. Box 116200, 339 Larsen Hall, Gainesville, FL 32611-6200; 352.392.4964<br />
<a href="http://www.ece.ufl.edu/" rel="nofollow" target="_blank">Department of Electrical & Computer Engineering</a><br />
<a href="http://www.eng.ufl.edu/" rel="nofollow" target="_blank">College of Engineering</a>, <a href="http://www.ufl.edu/" rel="nofollow" target="_blank">University of Florida</a>
</div>
<div class="page__footer-copyright footer-links">
<div>
<a href="/contact">Contact</a> | <a href="/contact/#mailing-list-subscription">Mailing List</a> | <a href="https://ipopvpn.slack.com/">Slack Channel</a> | <a href="/sitemap">Sitemap</a><br />
<div>Powered by <a href="http://jekyllrb.com" rel="nofollow" target="_blank">Jekyll</a> & <a href="https://mademistakes.com/work/minimal-mistakes-jekyll-theme/" rel="nofollow" target="_blank">Minimal Mistakes</a><br />
© 2019 IPOP - <a href="http://www.acis.ufl.edu" rel="nofollow" target="_blank">ACIS Lab</a>
</div>
</div>
</div>
<div class="page__footer-copyright footer-sponsor clear-both">This material is based upon work supported in part by the National Science Foundation under Grants No. 1234983, 1339737 and 1527415.</div>
</footer>
</div>
<script src="/assets/js/main.min.js"></script>
</body>
</html>
|
vahid-dan/ipop-project.github.io
|
_site/wiki/Use-IPOP-on-Ubuntu-and-Raspberry-Pi,-Manually.html
|
HTML
|
mit
| 12,982
|
Subscreen
=========
|
fxaeberhard/UnderTheScreen
|
README.md
|
Markdown
|
mit
| 20
|
$.extend( $.fn, {
// http://jqueryvalidation.org/validate/
validate: function( options ) {
// If nothing is selected, return nothing; can't chain anyway
if ( !this.length ) {
if ( options && options.debug && window.console ) {
console.warn( "Nothing selected, can't validate, returning nothing." );
}
return;
}
// Check if a validator for this form was already created
var validator = $.data( this[ 0 ], "validator" );
if ( validator ) {
return validator;
}
// Add novalidate tag if HTML5.
this.attr( "novalidate", "novalidate" );
validator = new $.validator( options, this[ 0 ] );
$.data( this[ 0 ], "validator", validator );
if ( validator.settings.onsubmit ) {
this.on( "click.validate", ":submit", function( event ) {
if ( validator.settings.submitHandler ) {
validator.submitButton = event.target;
}
// Allow suppressing validation by adding a cancel class to the submit button
if ( $( this ).hasClass( "cancel" ) ) {
validator.cancelSubmit = true;
}
// Allow suppressing validation by adding the html5 formnovalidate attribute to the submit button
if ( $( this ).attr( "formnovalidate" ) !== undefined ) {
validator.cancelSubmit = true;
}
} );
// Validate the form on submit
this.on( "submit.validate", function( event ) {
if ( validator.settings.debug ) {
// Prevent form submit to be able to see console output
event.preventDefault();
}
function handle() {
var hidden, result;
if ( validator.settings.submitHandler ) {
if ( validator.submitButton ) {
// Insert a hidden input as a replacement for the missing submit button
hidden = $( "<input type='hidden'/>" )
.attr( "name", validator.submitButton.name )
.val( $( validator.submitButton ).val() )
.appendTo( validator.currentForm );
}
result = validator.settings.submitHandler.call( validator, validator.currentForm, event );
if ( validator.submitButton ) {
// And clean up afterwards; thanks to no-block-scope, hidden can be referenced
hidden.remove();
}
if ( result !== undefined ) {
return result;
}
return false;
}
return true;
}
// Prevent submit for invalid forms or custom submit handlers
if ( validator.cancelSubmit ) {
validator.cancelSubmit = false;
return handle();
}
if ( validator.form() ) {
if ( validator.pendingRequest ) {
validator.formSubmitted = true;
return false;
}
return handle();
} else {
validator.focusInvalid();
return false;
}
} );
}
return validator;
},
// http://jqueryvalidation.org/valid/
valid: function() {
var valid, validator, errorList;
if ( $( this[ 0 ] ).is( "form" ) ) {
valid = this.validate().form();
} else {
errorList = [];
valid = true;
validator = $( this[ 0 ].form ).validate();
this.each( function() {
valid = validator.element( this ) && valid;
errorList = errorList.concat( validator.errorList );
} );
validator.errorList = errorList;
}
return valid;
},
// http://jqueryvalidation.org/rules/
rules: function( command, argument ) {
var element = this[ 0 ],
settings, staticRules, existingRules, data, param, filtered;
if ( command ) {
settings = $.data( element.form, "validator" ).settings;
staticRules = settings.rules;
existingRules = $.validator.staticRules( element );
switch ( command ) {
case "add":
$.extend( existingRules, $.validator.normalizeRule( argument ) );
// Remove messages from rules, but allow them to be set separately
delete existingRules.messages;
staticRules[ element.name ] = existingRules;
if ( argument.messages ) {
settings.messages[ element.name ] = $.extend( settings.messages[ element.name ], argument.messages );
}
break;
case "remove":
if ( !argument ) {
delete staticRules[ element.name ];
return existingRules;
}
filtered = {};
$.each( argument.split( /\s/ ), function( index, method ) {
filtered[ method ] = existingRules[ method ];
delete existingRules[ method ];
if ( method === "required" ) {
$( element ).removeAttr( "aria-required" );
}
} );
return filtered;
}
}
data = $.validator.normalizeRules(
$.extend(
{},
$.validator.classRules( element ),
$.validator.attributeRules( element ),
$.validator.dataRules( element ),
$.validator.staticRules( element )
), element );
// Make sure required is at front
if ( data.required ) {
param = data.required;
delete data.required;
data = $.extend( { required: param }, data );
$( element ).attr( "aria-required", "true" );
}
// Make sure remote is at back
if ( data.remote ) {
param = data.remote;
delete data.remote;
data = $.extend( data, { remote: param } );
}
return data;
}
} );
// Custom selectors
$.extend( $.expr[ ":" ], {
// http://jqueryvalidation.org/blank-selector/
blank: function( a ) {
return !$.trim( "" + $( a ).val() );
},
// http://jqueryvalidation.org/filled-selector/
filled: function( a ) {
return !!$.trim( "" + $( a ).val() );
},
// http://jqueryvalidation.org/unchecked-selector/
unchecked: function( a ) {
return !$( a ).prop( "checked" );
}
} );
// Constructor for validator
$.validator = function( options, form ) {
this.settings = $.extend( true, {}, $.validator.defaults, options );
this.currentForm = form;
this.init();
};
// http://jqueryvalidation.org/jQuery.validator.format/
$.validator.format = function( source, params ) {
if ( arguments.length === 1 ) {
return function() {
var args = $.makeArray( arguments );
args.unshift( source );
return $.validator.format.apply( this, args );
};
}
if ( arguments.length > 2 && params.constructor !== Array ) {
params = $.makeArray( arguments ).slice( 1 );
}
if ( params.constructor !== Array ) {
params = [ params ];
}
$.each( params, function( i, n ) {
source = source.replace( new RegExp( "\\{" + i + "\\}", "g" ), function() {
return n;
} );
} );
return source;
};
$.extend( $.validator, {
defaults: {
messages: {},
groups: {},
rules: {},
errorClass: "error",
pendingClass: "pending",
validClass: "valid",
errorElement: "label",
focusCleanup: false,
focusInvalid: true,
errorContainer: $( [] ),
errorLabelContainer: $( [] ),
onsubmit: true,
ignore: ":hidden",
ignoreTitle: false,
onfocusin: function( element ) {
this.lastActive = element;
// Hide error label and remove error class on focus if enabled
if ( this.settings.focusCleanup ) {
if ( this.settings.unhighlight ) {
this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass );
}
this.hideThese( this.errorsFor( element ) );
}
},
onfocusout: function( element ) {
if ( !this.checkable( element ) && ( element.name in this.submitted || !this.optional( element ) ) ) {
this.element( element );
}
},
onkeyup: function( element, event ) {
// Avoid revalidate the field when pressing one of the following keys
// Shift => 16
// Ctrl => 17
// Alt => 18
// Caps lock => 20
// End => 35
// Home => 36
// Left arrow => 37
// Up arrow => 38
// Right arrow => 39
// Down arrow => 40
// Insert => 45
// Num lock => 144
// AltGr key => 225
var excludedKeys = [
16, 17, 18, 20, 35, 36, 37,
38, 39, 40, 45, 144, 225
];
if ( event.which === 9 && this.elementValue( element ) === "" || $.inArray( event.keyCode, excludedKeys ) !== -1 ) {
return;
} else if ( element.name in this.submitted || this.isValidElement( element ) ) {
this.element( element );
}
},
onclick: function( element ) {
// Click on selects, radiobuttons and checkboxes
if ( element.name in this.submitted ) {
this.element( element );
// Or option elements, check parent select in that case
} else if ( element.parentNode.name in this.submitted ) {
this.element( element.parentNode );
}
},
highlight: function( element, errorClass, validClass ) {
if ( element.type === "radio" ) {
this.findByName( element.name ).addClass( errorClass ).removeClass( validClass );
} else {
$( element ).addClass( errorClass ).removeClass( validClass );
}
},
unhighlight: function( element, errorClass, validClass ) {
if ( element.type === "radio" ) {
this.findByName( element.name ).removeClass( errorClass ).addClass( validClass );
} else {
$( element ).removeClass( errorClass ).addClass( validClass );
}
}
},
// http://jqueryvalidation.org/jQuery.validator.setDefaults/
setDefaults: function( settings ) {
$.extend( $.validator.defaults, settings );
},
messages: {
required: "This field is required.",
remote: "Please fix this field.",
email: "Please enter a valid email address.",
url: "Please enter a valid URL.",
date: "Please enter a valid date.",
dateISO: "Please enter a valid date ( ISO ).",
number: "Please enter a valid number.",
digits: "Please enter only digits.",
equalTo: "Please enter the same value again.",
maxlength: $.validator.format( "Please enter no more than {0} characters." ),
minlength: $.validator.format( "Please enter at least {0} characters." ),
rangelength: $.validator.format( "Please enter a value between {0} and {1} characters long." ),
range: $.validator.format( "Please enter a value between {0} and {1}." ),
max: $.validator.format( "Please enter a value less than or equal to {0}." ),
min: $.validator.format( "Please enter a value greater than or equal to {0}." )
},
autoCreateRanges: false,
prototype: {
init: function() {
this.labelContainer = $( this.settings.errorLabelContainer );
this.errorContext = this.labelContainer.length && this.labelContainer || $( this.currentForm );
this.containers = $( this.settings.errorContainer ).add( this.settings.errorLabelContainer );
this.submitted = {};
this.valueCache = {};
this.pendingRequest = 0;
this.pending = {};
this.invalid = {};
this.reset();
var groups = ( this.groups = {} ),
rules;
$.each( this.settings.groups, function( key, value ) {
if ( typeof value === "string" ) {
value = value.split( /\s/ );
}
$.each( value, function( index, name ) {
groups[ name ] = key;
} );
} );
rules = this.settings.rules;
$.each( rules, function( key, value ) {
rules[ key ] = $.validator.normalizeRule( value );
} );
function delegate( event ) {
var validator = $.data( this.form, "validator" ),
eventType = "on" + event.type.replace( /^validate/, "" ),
settings = validator.settings;
if ( settings[ eventType ] && !$( this ).is( settings.ignore ) ) {
settings[ eventType ].call( validator, this, event );
}
}
$( this.currentForm )
.on( "focusin.validate focusout.validate keyup.validate",
":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], " +
"[type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], " +
"[type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], " +
"[type='radio'], [type='checkbox'], [contenteditable]", delegate )
// Support: Chrome, oldIE
// "select" is provided as event.target when clicking a option
.on( "click.validate", "select, option, [type='radio'], [type='checkbox']", delegate );
if ( this.settings.invalidHandler ) {
$( this.currentForm ).on( "invalid-form.validate", this.settings.invalidHandler );
}
// Add aria-required to any Static/Data/Class required fields before first validation
// Screen readers require this attribute to be present before the initial submission http://www.w3.org/TR/WCAG-TECHS/ARIA2.html
$( this.currentForm ).find( "[required], [data-rule-required], .required" ).attr( "aria-required", "true" );
},
// http://jqueryvalidation.org/Validator.form/
form: function() {
this.checkForm();
$.extend( this.submitted, this.errorMap );
this.invalid = $.extend( {}, this.errorMap );
if ( !this.valid() ) {
$( this.currentForm ).triggerHandler( "invalid-form", [ this ] );
}
this.showErrors();
return this.valid();
},
checkForm: function() {
this.prepareForm();
for ( var i = 0, elements = ( this.currentElements = this.elements() ); elements[ i ]; i++ ) {
this.check( elements[ i ] );
}
return this.valid();
},
// http://jqueryvalidation.org/Validator.element/
element: function( element ) {
var cleanElement = this.clean( element ),
checkElement = this.validationTargetFor( cleanElement ),
result = true;
if ( checkElement === undefined ) {
delete this.invalid[ cleanElement.name ];
} else {
this.prepareElement( checkElement );
this.currentElements = $( checkElement );
result = this.check( checkElement ) !== false;
if ( result ) {
this.invalid[ checkElement.name ] = false;
} else {
this.invalid[ checkElement.name ] = true;
}
}
// Add aria-invalid status for screen readers
$( element ).attr( "aria-invalid", !result );
if ( !this.numberOfInvalids() ) {
// Hide error containers on last error
this.toHide = this.toHide.add( this.containers );
}
this.showErrors();
return result;
},
// http://jqueryvalidation.org/Validator.showErrors/
showErrors: function( errors ) {
if ( errors ) {
// Add items to error list and map
$.extend( this.errorMap, errors );
this.errorList = [];
for ( var name in errors ) {
this.errorList.push( {
message: errors[ name ],
element: this.findByName( name )[ 0 ]
} );
}
// Remove items from success list
this.successList = $.grep( this.successList, function( element ) {
return !( element.name in errors );
} );
}
if ( this.settings.showErrors ) {
this.settings.showErrors.call( this, this.errorMap, this.errorList );
} else {
this.defaultShowErrors();
}
},
// http://jqueryvalidation.org/Validator.resetForm/
resetForm: function() {
if ( $.fn.resetForm ) {
$( this.currentForm ).resetForm();
}
this.submitted = {};
this.prepareForm();
this.hideErrors();
var i, elements = this.elements()
.removeData( "previousValue" )
.removeAttr( "aria-invalid" );
if ( this.settings.unhighlight ) {
for ( i = 0; elements[ i ]; i++ ) {
this.settings.unhighlight.call( this, elements[ i ],
this.settings.errorClass, "" );
}
} else {
elements.removeClass( this.settings.errorClass );
}
},
numberOfInvalids: function() {
return this.objectLength( this.invalid );
},
objectLength: function( obj ) {
/* jshint unused: false */
var count = 0,
i;
for ( i in obj ) {
if ( obj[ i ] ) {
count++;
}
}
return count;
},
hideErrors: function() {
this.hideThese( this.toHide );
},
hideThese: function( errors ) {
errors.not( this.containers ).text( "" );
this.addWrapper( errors ).hide();
},
valid: function() {
return this.size() === 0;
},
// Check if the given element is valid
// return
// true If the field is valid
// false If the field is invalid
// undefined If the field is not validated yet.
//
// Note that this method assumes that you have
// already called `validate()` on your form
isValidElement: function( element ) {
return this.invalid[ element.name ] === undefined ? undefined : !this.invalid[ element.name ];
},
size: function() {
return this.errorList.length;
},
focusInvalid: function() {
if ( this.settings.focusInvalid ) {
try {
$( this.findLastActive() || this.errorList.length && this.errorList[ 0 ].element || [] )
.filter( ":visible" )
.focus()
// Manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find
.trigger( "focusin" );
} catch ( e ) {
// Ignore IE throwing errors when focusing hidden elements
}
}
},
findLastActive: function() {
var lastActive = this.lastActive;
return lastActive && $.grep( this.errorList, function( n ) {
return n.element.name === lastActive.name;
} ).length === 1 && lastActive;
},
elements: function() {
var validator = this,
rulesCache = {};
// Select all valid inputs inside the form (no submit or reset buttons)
return $( this.currentForm )
.find( "input, select, textarea, [contenteditable]" )
.not( ":submit, :reset, :image, :disabled" )
.not( this.settings.ignore )
.filter( function() {
var name = this.name || $( this ).attr( "name" ); // For contenteditable
if ( !name && validator.settings.debug && window.console ) {
console.error( "%o has no name assigned", this );
}
// Set form expando on contenteditable
if ( this.hasAttribute( "contenteditable" ) ) {
this.form = $( this ).closest( "form" )[ 0 ];
}
// Select only the first element for each name, and only those with rules specified
if ( name in rulesCache || !validator.objectLength( $( this ).rules() ) ) {
return false;
}
rulesCache[ name ] = true;
return true;
} );
},
clean: function( selector ) {
return $( selector )[ 0 ];
},
errors: function() {
var errorClass = this.settings.errorClass.split( " " ).join( "." );
return $( this.settings.errorElement + "." + errorClass, this.errorContext );
},
reset: function() {
this.successList = [];
this.errorList = [];
this.errorMap = {};
this.toShow = $( [] );
this.toHide = $( [] );
this.currentElements = $( [] );
},
prepareForm: function() {
this.reset();
this.toHide = this.errors().add( this.containers );
},
prepareElement: function( element ) {
this.reset();
this.toHide = this.errorsFor( element );
},
elementValue: function( element ) {
var val,
$element = $( element ),
type = element.type;
if ( type === "radio" || type === "checkbox" ) {
return this.findByName( element.name ).filter( ":checked" ).val();
} else if ( type === "number" && typeof element.validity !== "undefined" ) {
return element.validity.badInput ? false : $element.val();
}
if ( element.hasAttribute( "contenteditable" ) ) {
val = $element.text();
} else {
val = $element.val();
}
if ( typeof val === "string" ) {
return val.replace( /\r/g, "" );
}
return val;
},
check: function( element ) {
element = this.validationTargetFor( this.clean( element ) );
var rules = $( element ).rules(),
rulesCount = $.map( rules, function( n, i ) {
return i;
} ).length,
dependencyMismatch = false,
val = this.elementValue( element ),
result, method, rule;
// If a normalizer is defined for this element, then
// call it to retreive the changed value instead
// of using the real one.
// Note that `this` in the normalizer is `element`.
if ( typeof rules.normalizer === "function" ) {
val = rules.normalizer.call( element, val );
if ( typeof val !== "string" ) {
throw new TypeError( "The normalizer should return a string value." );
}
// Delete the normalizer from rules to avoid treating
// it as a pre-defined method.
delete rules.normalizer;
}
for ( method in rules ) {
rule = { method: method, parameters: rules[ method ] };
try {
result = $.validator.methods[ method ].call( this, val, element, rule.parameters );
// If a method indicates that the field is optional and therefore valid,
// don't mark it as valid when there are no other rules
if ( result === "dependency-mismatch" && rulesCount === 1 ) {
dependencyMismatch = true;
continue;
}
dependencyMismatch = false;
if ( result === "pending" ) {
this.toHide = this.toHide.not( this.errorsFor( element ) );
return;
}
if ( !result ) {
this.formatAndAdd( element, rule );
return false;
}
} catch ( e ) {
if ( this.settings.debug && window.console ) {
console.log( "Exception occurred when checking element " + element.id + ", check the '" + rule.method + "' method.", e );
}
if ( e instanceof TypeError ) {
e.message += ". Exception occurred when checking element " + element.id + ", check the '" + rule.method + "' method.";
}
throw e;
}
}
if ( dependencyMismatch ) {
return;
}
if ( this.objectLength( rules ) ) {
this.successList.push( element );
}
return true;
},
// Return the custom message for the given element and validation method
// specified in the element's HTML5 data attribute
// return the generic message if present and no method specific message is present
customDataMessage: function( element, method ) {
return $( element ).data( "msg" + method.charAt( 0 ).toUpperCase() +
method.substring( 1 ).toLowerCase() ) || $( element ).data( "msg" );
},
// Return the custom message for the given element name and validation method
customMessage: function( name, method ) {
var m = this.settings.messages[ name ];
return m && ( m.constructor === String ? m : m[ method ] );
},
// Return the first defined argument, allowing empty strings
findDefined: function() {
for ( var i = 0; i < arguments.length; i++ ) {
if ( arguments[ i ] !== undefined ) {
return arguments[ i ];
}
}
return undefined;
},
defaultMessage: function( element, method ) {
return this.findDefined(
this.customMessage( element.name, method ),
this.customDataMessage( element, method ),
// 'title' is never undefined, so handle empty string as undefined
!this.settings.ignoreTitle && element.title || undefined,
$.validator.messages[ method ],
"<strong>Warning: No message defined for " + element.name + "</strong>"
);
},
formatAndAdd: function( element, rule ) {
var message = this.defaultMessage( element, rule.method ),
theregex = /\$?\{(\d+)\}/g;
if ( typeof message === "function" ) {
message = message.call( this, rule.parameters, element );
} else if ( theregex.test( message ) ) {
message = $.validator.format( message.replace( theregex, "{$1}" ), rule.parameters );
}
this.errorList.push( {
message: message,
element: element,
method: rule.method
} );
this.errorMap[ element.name ] = message;
this.submitted[ element.name ] = message;
},
addWrapper: function( toToggle ) {
if ( this.settings.wrapper ) {
toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) );
}
return toToggle;
},
defaultShowErrors: function() {
var i, elements, error;
for ( i = 0; this.errorList[ i ]; i++ ) {
error = this.errorList[ i ];
if ( this.settings.highlight ) {
this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass );
}
this.showLabel( error.element, error.message );
}
if ( this.errorList.length ) {
this.toShow = this.toShow.add( this.containers );
}
if ( this.settings.success ) {
for ( i = 0; this.successList[ i ]; i++ ) {
this.showLabel( this.successList[ i ] );
}
}
if ( this.settings.unhighlight ) {
for ( i = 0, elements = this.validElements(); elements[ i ]; i++ ) {
this.settings.unhighlight.call( this, elements[ i ], this.settings.errorClass, this.settings.validClass );
}
}
this.toHide = this.toHide.not( this.toShow );
this.hideErrors();
this.addWrapper( this.toShow ).show();
},
validElements: function() {
return this.currentElements.not( this.invalidElements() );
},
invalidElements: function() {
return $( this.errorList ).map( function() {
return this.element;
} );
},
showLabel: function( element, message ) {
var place, group, errorID,
error = this.errorsFor( element ),
elementID = this.idOrName( element ),
describedBy = $( element ).attr( "aria-describedby" );
if ( error.length ) {
// Refresh error/success class
error.removeClass( this.settings.validClass ).addClass( this.settings.errorClass );
// Replace message on existing label
error.html( message );
} else {
// Create error element
error = $( "<" + this.settings.errorElement + ">" )
.attr( "id", elementID + "-error" )
.addClass( this.settings.errorClass )
.html( message || "" );
// Maintain reference to the element to be placed into the DOM
place = error;
if ( this.settings.wrapper ) {
// Make sure the element is visible, even in IE
// actually showing the wrapped element is handled elsewhere
place = error.hide().show().wrap( "<" + this.settings.wrapper + "/>" ).parent();
}
if ( this.labelContainer.length ) {
this.labelContainer.append( place );
} else if ( this.settings.errorPlacement ) {
this.settings.errorPlacement( place, $( element ) );
} else {
place.insertAfter( element );
}
// Link error back to the element
if ( error.is( "label" ) ) {
// If the error is a label, then associate using 'for'
error.attr( "for", elementID );
}
// If the element is not a child of an associated label, then it's necessary
// to explicitly apply aria-describedby
else if ( error.parents( "label[for='" + this.escapeCssMeta( elementID ) + "']" ).length === 0 ) {
errorID = error.attr( "id" );
// Respect existing non-error aria-describedby
if ( !describedBy ) {
describedBy = errorID;
} else if ( !describedBy.match( new RegExp( "\\b" + this.escapeCssMeta( errorID ) + "\\b" ) ) ) {
// Add to end of list if not already present
describedBy += " " + errorID;
}
$( element ).attr( "aria-describedby", describedBy );
// If this element is grouped, then assign to all elements in the same group
group = this.groups[ element.name ];
if ( group ) {
$.each( this.groups, function( name, testgroup ) {
if ( testgroup === group ) {
$( "[name='" + this.escapeCssMeta( name ) + "']", this.currentForm )
.attr( "aria-describedby", error.attr( "id" ) );
}
} );
}
}
}
if ( !message && this.settings.success ) {
error.text( "" );
if ( typeof this.settings.success === "string" ) {
error.addClass( this.settings.success );
} else {
this.settings.success( error, element );
}
}
this.toShow = this.toShow.add( error );
},
errorsFor: function( element ) {
var name = this.escapeCssMeta( this.idOrName( element ) ),
describer = $( element ).attr( "aria-describedby" ),
selector = "label[for='" + name + "'], label[for='" + name + "'] *";
// 'aria-describedby' should directly reference the error element
if ( describer ) {
selector = selector + ", #" + this.escapeCssMeta( describer )
.replace( /\s+/g, ", #" );
}
return this
.errors()
.filter( selector );
},
// See https://api.jquery.com/category/selectors/, for CSS
// meta-characters that should be escaped in order to be used with JQuery
// as a literal part of a name/id or any selector.
escapeCssMeta: function( string ) {
return string.replace( /([\\!"#$%&'()*+,./:;<=>?@\[\]^`{|}~])/g, "\\$1" );
},
idOrName: function( element ) {
return this.groups[ element.name ] || ( this.checkable( element ) ? element.name : element.id || element.name );
},
validationTargetFor: function( element ) {
// If radio/checkbox, validate first element in group instead
if ( this.checkable( element ) ) {
element = this.findByName( element.name );
}
// Always apply ignore filter
return $( element ).not( this.settings.ignore )[ 0 ];
},
checkable: function( element ) {
return ( /radio|checkbox/i ).test( element.type );
},
findByName: function( name ) {
return $( this.currentForm ).find( "[name='" + this.escapeCssMeta( name ) + "']" );
},
getLength: function( value, element ) {
switch ( element.nodeName.toLowerCase() ) {
case "select":
return $( "option:selected", element ).length;
case "input":
if ( this.checkable( element ) ) {
return this.findByName( element.name ).filter( ":checked" ).length;
}
}
return value.length;
},
depend: function( param, element ) {
return this.dependTypes[ typeof param ] ? this.dependTypes[ typeof param ]( param, element ) : true;
},
dependTypes: {
"boolean": function( param ) {
return param;
},
"string": function( param, element ) {
return !!$( param, element.form ).length;
},
"function": function( param, element ) {
return param( element );
}
},
optional: function( element ) {
var val = this.elementValue( element );
return !$.validator.methods.required.call( this, val, element ) && "dependency-mismatch";
},
startRequest: function( element ) {
if ( !this.pending[ element.name ] ) {
this.pendingRequest++;
$( element ).addClass( this.settings.pendingClass );
this.pending[ element.name ] = true;
}
},
stopRequest: function( element, valid ) {
this.pendingRequest--;
// Sometimes synchronization fails, make sure pendingRequest is never < 0
if ( this.pendingRequest < 0 ) {
this.pendingRequest = 0;
}
delete this.pending[ element.name ];
$( element ).removeClass( this.settings.pendingClass );
if ( valid && this.pendingRequest === 0 && this.formSubmitted && this.form() ) {
$( this.currentForm ).submit();
this.formSubmitted = false;
} else if ( !valid && this.pendingRequest === 0 && this.formSubmitted ) {
$( this.currentForm ).triggerHandler( "invalid-form", [ this ] );
this.formSubmitted = false;
}
},
previousValue: function( element ) {
return $.data( element, "previousValue" ) || $.data( element, "previousValue", {
old: null,
valid: true,
message: this.defaultMessage( element, "remote" )
} );
},
// Cleans up all forms and elements, removes validator-specific events
destroy: function() {
this.resetForm();
$( this.currentForm )
.off( ".validate" )
.removeData( "validator" );
}
},
classRuleSettings: {
required: { required: true },
email: { email: true },
url: { url: true },
date: { date: true },
dateISO: { dateISO: true },
number: { number: true },
digits: { digits: true },
creditcard: { creditcard: true }
},
addClassRules: function( className, rules ) {
if ( className.constructor === String ) {
this.classRuleSettings[ className ] = rules;
} else {
$.extend( this.classRuleSettings, className );
}
},
classRules: function( element ) {
var rules = {},
classes = $( element ).attr( "class" );
if ( classes ) {
$.each( classes.split( " " ), function() {
if ( this in $.validator.classRuleSettings ) {
$.extend( rules, $.validator.classRuleSettings[ this ] );
}
} );
}
return rules;
},
normalizeAttributeRule: function( rules, type, method, value ) {
// Convert the value to a number for number inputs, and for text for backwards compability
// allows type="date" and others to be compared as strings
if ( /min|max/.test( method ) && ( type === null || /number|range|text/.test( type ) ) ) {
value = Number( value );
// Support Opera Mini, which returns NaN for undefined minlength
if ( isNaN( value ) ) {
value = undefined;
}
}
if ( value || value === 0 ) {
rules[ method ] = value;
} else if ( type === method && type !== "range" ) {
// Exception: the jquery validate 'range' method
// does not test for the html5 'range' type
rules[ method ] = true;
}
},
attributeRules: function( element ) {
var rules = {},
$element = $( element ),
type = element.getAttribute( "type" ),
method, value;
for ( method in $.validator.methods ) {
// Support for <input required> in both html5 and older browsers
if ( method === "required" ) {
value = element.getAttribute( method );
// Some browsers return an empty string for the required attribute
// and non-HTML5 browsers might have required="" markup
if ( value === "" ) {
value = true;
}
// Force non-HTML5 browsers to return bool
value = !!value;
} else {
value = $element.attr( method );
}
this.normalizeAttributeRule( rules, type, method, value );
}
// 'maxlength' may be returned as -1, 2147483647 ( IE ) and 524288 ( safari ) for text inputs
if ( rules.maxlength && /-1|2147483647|524288/.test( rules.maxlength ) ) {
delete rules.maxlength;
}
return rules;
},
dataRules: function( element ) {
var rules = {},
$element = $( element ),
type = element.getAttribute( "type" ),
method, value;
for ( method in $.validator.methods ) {
value = $element.data( "rule" + method.charAt( 0 ).toUpperCase() + method.substring( 1 ).toLowerCase() );
this.normalizeAttributeRule( rules, type, method, value );
}
return rules;
},
staticRules: function( element ) {
var rules = {},
validator = $.data( element.form, "validator" );
if ( validator.settings.rules ) {
rules = $.validator.normalizeRule( validator.settings.rules[ element.name ] ) || {};
}
return rules;
},
normalizeRules: function( rules, element ) {
// Handle dependency check
$.each( rules, function( prop, val ) {
// Ignore rule when param is explicitly false, eg. required:false
if ( val === false ) {
delete rules[ prop ];
return;
}
if ( val.param || val.depends ) {
var keepRule = true;
switch ( typeof val.depends ) {
case "string":
keepRule = !!$( val.depends, element.form ).length;
break;
case "function":
keepRule = val.depends.call( element, element );
break;
}
if ( keepRule ) {
rules[ prop ] = val.param !== undefined ? val.param : true;
} else {
delete rules[ prop ];
}
}
} );
// Evaluate parameters
$.each( rules, function( rule, parameter ) {
rules[ rule ] = $.isFunction( parameter ) && rule !== "normalizer" ? parameter( element ) : parameter;
} );
// Clean number parameters
$.each( [ "minlength", "maxlength" ], function() {
if ( rules[ this ] ) {
rules[ this ] = Number( rules[ this ] );
}
} );
$.each( [ "rangelength", "range" ], function() {
var parts;
if ( rules[ this ] ) {
if ( $.isArray( rules[ this ] ) ) {
rules[ this ] = [ Number( rules[ this ][ 0 ] ), Number( rules[ this ][ 1 ] ) ];
} else if ( typeof rules[ this ] === "string" ) {
parts = rules[ this ].replace( /[\[\]]/g, "" ).split( /[\s,]+/ );
rules[ this ] = [ Number( parts[ 0 ] ), Number( parts[ 1 ] ) ];
}
}
} );
if ( $.validator.autoCreateRanges ) {
// Auto-create ranges
if ( rules.min != null && rules.max != null ) {
rules.range = [ rules.min, rules.max ];
delete rules.min;
delete rules.max;
}
if ( rules.minlength != null && rules.maxlength != null ) {
rules.rangelength = [ rules.minlength, rules.maxlength ];
delete rules.minlength;
delete rules.maxlength;
}
}
return rules;
},
// Converts a simple string to a {string: true} rule, e.g., "required" to {required:true}
normalizeRule: function( data ) {
if ( typeof data === "string" ) {
var transformed = {};
$.each( data.split( /\s/ ), function() {
transformed[ this ] = true;
} );
data = transformed;
}
return data;
},
// http://jqueryvalidation.org/jQuery.validator.addMethod/
addMethod: function( name, method, message ) {
$.validator.methods[ name ] = method;
$.validator.messages[ name ] = message !== undefined ? message : $.validator.messages[ name ];
if ( method.length < 3 ) {
$.validator.addClassRules( name, $.validator.normalizeRule( name ) );
}
},
methods: {
// http://jqueryvalidation.org/required-method/
required: function( value, element, param ) {
// Check if dependency is met
if ( !this.depend( param, element ) ) {
return "dependency-mismatch";
}
if ( element.nodeName.toLowerCase() === "select" ) {
// Could be an array for select-multiple or a string, both are fine this way
var val = $( element ).val();
return val && val.length > 0;
}
if ( this.checkable( element ) ) {
return this.getLength( value, element ) > 0;
}
return value.length > 0;
},
// http://jqueryvalidation.org/email-method/
email: function( value, element ) {
// From https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address
// Retrieved 2014-01-14
// If you have a problem with this implementation, report a bug against the above spec
// Or use custom methods to implement your own email validation
return this.optional( element ) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test( value );
},
// http://jqueryvalidation.org/url-method/
url: function( value, element ) {
// Copyright (c) 2010-2013 Diego Perini, MIT licensed
// https://gist.github.com/dperini/729294
// see also https://mathiasbynens.be/demo/url-regex
// modified to allow protocol-relative URLs
return this.optional( element ) || /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test( value );
},
// http://jqueryvalidation.org/date-method/
date: function( value, element ) {
return this.optional( element ) || !/Invalid|NaN/.test( new Date( value ).toString() );
},
// http://jqueryvalidation.org/dateISO-method/
dateISO: function( value, element ) {
return this.optional( element ) || /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test( value );
},
// http://jqueryvalidation.org/number-method/
number: function( value, element ) {
return this.optional( element ) || /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test( value );
},
// http://jqueryvalidation.org/digits-method/
digits: function( value, element ) {
return this.optional( element ) || /^\d+$/.test( value );
},
// http://jqueryvalidation.org/minlength-method/
minlength: function( value, element, param ) {
var length = $.isArray( value ) ? value.length : this.getLength( value, element );
return this.optional( element ) || length >= param;
},
// http://jqueryvalidation.org/maxlength-method/
maxlength: function( value, element, param ) {
var length = $.isArray( value ) ? value.length : this.getLength( value, element );
return this.optional( element ) || length <= param;
},
// http://jqueryvalidation.org/rangelength-method/
rangelength: function( value, element, param ) {
var length = $.isArray( value ) ? value.length : this.getLength( value, element );
return this.optional( element ) || ( length >= param[ 0 ] && length <= param[ 1 ] );
},
// http://jqueryvalidation.org/min-method/
min: function( value, element, param ) {
return this.optional( element ) || value >= param;
},
// http://jqueryvalidation.org/max-method/
max: function( value, element, param ) {
return this.optional( element ) || value <= param;
},
// http://jqueryvalidation.org/range-method/
range: function( value, element, param ) {
return this.optional( element ) || ( value >= param[ 0 ] && value <= param[ 1 ] );
},
// http://jqueryvalidation.org/equalTo-method/
equalTo: function( value, element, param ) {
// Bind to the blur event of the target in order to revalidate whenever the target field is updated
// TODO find a way to bind the event just once, avoiding the unbind-rebind overhead
var target = $( param );
if ( this.settings.onfocusout ) {
target.off( ".validate-equalTo" ).on( "blur.validate-equalTo", function() {
$( element ).valid();
} );
}
return value === target.val();
},
// http://jqueryvalidation.org/remote-method/
remote: function( value, element, param ) {
if ( this.optional( element ) ) {
return "dependency-mismatch";
}
var previous = this.previousValue( element ),
validator, data, optionDataString;
if ( !this.settings.messages[ element.name ] ) {
this.settings.messages[ element.name ] = {};
}
previous.originalMessage = this.settings.messages[ element.name ].remote;
this.settings.messages[ element.name ].remote = previous.message;
param = typeof param === "string" && { url: param } || param;
optionDataString = $.param( $.extend( { data: value }, param.data ) );
if ( previous.old === optionDataString ) {
return previous.valid;
}
previous.old = optionDataString;
validator = this;
this.startRequest( element );
data = {};
data[ element.name ] = value;
$.ajax( $.extend( true, {
mode: "abort",
port: "validate" + element.name,
dataType: "json",
data: data,
context: validator.currentForm,
success: function( response ) {
var valid = response === true || response === "true",
errors, message, submitted;
validator.settings.messages[ element.name ].remote = previous.originalMessage;
if ( valid ) {
submitted = validator.formSubmitted;
validator.prepareElement( element );
validator.formSubmitted = submitted;
validator.successList.push( element );
delete validator.invalid[ element.name ];
validator.showErrors();
} else {
errors = {};
message = response || validator.defaultMessage( element, "remote" );
errors[ element.name ] = previous.message = $.isFunction( message ) ? message( value ) : message;
validator.invalid[ element.name ] = true;
validator.showErrors( errors );
}
previous.valid = valid;
validator.stopRequest( element, valid );
}
}, param ) );
return "pending";
}
}
} );
|
etylsarin/jquery-validation
|
src/core.js
|
JavaScript
|
mit
| 42,456
|
// EnemyJunkbotWalking.cpp: implementation of the EnemyJunkbotWalking class.
//
//////////////////////////////////////////////////////////////////////
#include "EnemyJunkbotWalking.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
EnemyJunkbotWalking::EnemyJunkbotWalking(Level *curLevel)
{
InitEnemy(base_enemy_type_3,
base_x_velocity,
base_y_velocity,
0,
.5,
0,
true);
SetRenderOffset(enemy_junkbot_walking_render_offset);
SetMaxWalkVelocity(35);
level_class = curLevel;
rectDX = 15;
rectDY = 45;
rectXOffset = -nOffSet;
rectYOffset = -15;
}
EnemyJunkbotWalking::~EnemyJunkbotWalking()
{
}
/*HPTRect &EnemyJunkbotWalking::GetWorldLoc()
{
return rectWorldLoc;
}*/
void EnemyJunkbotWalking::processLeft()
{
//If Not Previously Moving Left - Reset Animation
if(ipFlags.PrevMState != move_left)
SetAnimation(ENEMY_JUNKBOT_WALKING_MOVE, 0, true, false, 15, true);
else
SetAnimation(ENEMY_JUNKBOT_WALKING_MOVE, 0, true, false, 15, false);
//Accelerate Left Velocity
velMovement = -maxWalkSpeed;
//Set Sprite Direction
ipFlags.S_DIRECTION = false;
}
void EnemyJunkbotWalking::processRight()
{
//If Not Previously Moving Right - Reset Animation
if(ipFlags.PrevMState != move_right)
SetAnimation(ENEMY_JUNKBOT_WALKING_MOVE, 0, true, false, 15, true);
else
SetAnimation(ENEMY_JUNKBOT_WALKING_MOVE, 0, true, false, 15, false);
//Accelerate Right Velocity
velMovement = maxWalkSpeed;
//Set Sprite Direction
ipFlags.S_DIRECTION = true;
}
void EnemyJunkbotWalking::processAttack()
{
Projectile *temp;
if(!ipFlags.S_ATTACK)
{
ipFlags.S_ATTACK = true;
// ipFlags.nCurrAttack = 1;
switch(ipFlags.nCurrAttack)
{
case 0:
// if (ipFlags.S_ACTIVE) soundPlayer->PlaySound(laser01);
SetAnimation(ENEMY_JUNKBOT_WALKING_ATTACK, 0, true, true, 20, true);
if(ipFlags.S_DIRECTION)
{
temp = new ProjectileJunkbotWalkingBullet(ipFlags.S_DIRECTION, static_cast<int>(xLoc + nOffSet+20), static_cast<int>(yLoc - 10),projectile_list, 90, 0, .4f, 3);
(*projectile_list).push_back(temp);
}
else
{
temp = new ProjectileJunkbotWalkingBullet(ipFlags.S_DIRECTION, static_cast<int>(xLoc - nOffSet-20), static_cast<int>(yLoc - 10),projectile_list, -90, 0, .4f, 3);
(*projectile_list).push_back(temp);
}
//Stop All Directional Movement
StopMovement();
break;
case 1:
//if (ipFlags.S_ACTIVE) soundPlayer->PlaySound(laser03);
SetAnimation(ENEMY_JUNKBOT_WALKING_ATTACK, 0, true, true, 20, true);
if(ipFlags.S_DIRECTION)
{
temp = new ProjectileJunkbotWalkingBullet(ipFlags.S_DIRECTION, static_cast<int>(xLoc + nOffSet+20), static_cast<int>(yLoc - 10),projectile_list, 140, 0, .4f, .20);
(*projectile_list).push_back(temp);
temp = new ProjectileJunkbotWalkingBullet(ipFlags.S_DIRECTION, static_cast<int>(xLoc + nOffSet+20), static_cast<int>(yLoc - 10),projectile_list, 130, 80, .45f, .20);
(*projectile_list).push_back(temp);
temp = new ProjectileJunkbotWalkingBullet(ipFlags.S_DIRECTION, static_cast<int>(xLoc + nOffSet+20), static_cast<int>(yLoc - 10),projectile_list, 130, -80, .45f, .20);
(*projectile_list).push_back(temp);
}
else
{
temp = new ProjectileJunkbotWalkingBullet(ipFlags.S_DIRECTION, static_cast<int>(xLoc - nOffSet-20), static_cast<int>(yLoc - 10),projectile_list, -140, 0, .4f, .20);
(*projectile_list).push_back(temp);
temp = new ProjectileJunkbotWalkingBullet(ipFlags.S_DIRECTION, static_cast<int>(xLoc - nOffSet-20), static_cast<int>(yLoc - 10),projectile_list, -130, 80, .45f, .20);
(*projectile_list).push_back(temp);
temp = new ProjectileJunkbotWalkingBullet(ipFlags.S_DIRECTION, static_cast<int>(xLoc - nOffSet-20), static_cast<int>(yLoc - 10),projectile_list, -130, -80, .45f, .20);
(*projectile_list).push_back(temp);
}
//Stop All Directional Movement
StopMovement();
break;
default:
ipFlags.S_ATTACK = false;
break;
}
}
}
void EnemyJunkbotWalking::processDamage()
{
//if (ipFlags.S_ACTIVE) soundPlayer->PlaySound(laser02);
ipFlags.S_ATTACK = false;
if( ipFlags.S_DAMAGED_DIRECTION)
velMovement = 30;
else
velMovement = -30;
}
void EnemyJunkbotWalking::processDeath()
{
//Stop All Directional Movement
velMovement = 0;
velModifier = 0;
SetAnimation(ENEMY_JUNKBOT_WALKING_DEATH, 0, true, true, 10, true);
}
void EnemyJunkbotWalking::stop()
{
//Stop All Movement
StopMovement();
//Reset Animation
if(ipFlags.PrevMState != move_stop)
SetAnimation(ENEMY_JUNKBOT_WALKING_MOVE, 0, false, false, 22, true);
else
SetAnimation(ENEMY_JUNKBOT_WALKING_MOVE, 0, false, false, 22, false);
}
void EnemyJunkbotWalking::processUpdate()
{
if((player_spr->GetFrameSet() == ENEMY_JUNKBOT_WALKING_DEATH) && !player_spr->IsAnimating())
Die();
if(ipFlags.S_ATTACK)
{
if(!player_spr->IsAnimating())
{
ipFlags.S_ATTACK = false;
}
}
// Apply Velocity Modifier
if(!ipFlags.S_DAMAGED && !ipFlags.S_ATTACK)
switch(ipFlags.CurMState)
{
case move_stop:
stop();
break;
case move_left:
processLeft();
break;
case move_right:
processRight();
break;
default:
break;
}
/* Center (0,0), offset by Render Offset */
// SetRectangle(rectWorldLoc, 15, 45, -nOffSet, -15);
}
|
duhone/BladeofBetrayal
|
Bob/EnemyJunkbotWalking.cpp
|
C++
|
mit
| 5,461
|
#pragma once
#include "PoolAllocatorTest.h"
#include "StackAllocatorTest.h"
#include "GeneralPurposeAllocatorTest.h"
#include "DefragmentationAllocatorTest.h"
#include "StringTest.h"
#include "DataStructures/ListTest.h"
#include "DataStructures/HashMapTest.h"
#include "DataStructures/StackTest.h"
#include "DataStructures/ArrayTest.h"
#include "DataStructures/DynamicArrayTest.h"
#include "BBE/UtilTest.h"
#include "UniquePointerTest.h"
#include "Matrix4Test.h"
#include "MathTest.h"
#include "Vector2Test.h"
#include "Vector3Test.h"
#include "LinearCongruentialGeneratorTest.h"
#include "ImageTest.h"
namespace bbe {
namespace test {
void runAllTests() {
std::cout << "Starting Tests!" << std::endl;
Person::checkIfAllPersonsWereDestroyed();
std::cout << "Testing PoolAllocator" << std::endl;
bbe::test::testPoolAllocator();
Person::checkIfAllPersonsWereDestroyed();
std::cout << "Testing StackAllocator" << std::endl;
bbe::test::testStackAllocator();
Person::checkIfAllPersonsWereDestroyed();
std::cout << "Testing GeneralPurposeAllocator" << std::endl;
bbe::test::testGeneralPurposeAllocator();
Person::checkIfAllPersonsWereDestroyed();
std::cout << "Testing DefragmentationAllocaotr" << std::endl;
bbe::test::testDefragmentationAllocator();
Person::checkIfAllPersonsWereDestroyed();
std::cout << "Testing String" << std::endl;
bbe::test::testString();
Person::checkIfAllPersonsWereDestroyed();
std::cout << "Testing List" << std::endl;
bbe::test::testList();
Person::checkIfAllPersonsWereDestroyed();
std::cout << "Testing HashMap" << std::endl;
bbe::test::testHashMap();
Person::checkIfAllPersonsWereDestroyed();
std::cout << "Testing Stack" << std::endl;
bbe::test::testStack();
Person::checkIfAllPersonsWereDestroyed();
std::cout << "Testing UniquePointer" << std::endl;
bbe::test::testUniquePointer();
Person::checkIfAllPersonsWereDestroyed();
std::cout << "Testing Array" << std::endl;
bbe::test::testArray();
Person::checkIfAllPersonsWereDestroyed();
std::cout << "Testing DynamicArray" << std::endl;
bbe::test::testDynamicArray();
Person::checkIfAllPersonsWereDestroyed();
std::cout << "Testing testMatrix4" << std::endl;
bbe::test::testMatrix4();
Person::checkIfAllPersonsWereDestroyed();
std::cout << "Testing testMath" << std::endl;
bbe::test::testMath();
Person::checkIfAllPersonsWereDestroyed();
std::cout << "Testing Vector2" << std::endl;
bbe::test::testVector2();
Person::checkIfAllPersonsWereDestroyed();
std::cout << "Testing Vector3" << std::endl;
bbe::test::testVector3();
Person::checkIfAllPersonsWereDestroyed();
std::cout << "Testing LinearCongruentialGenerator" << std::endl;
bbe::test::testLinearCongruentailGenerators();
Person::checkIfAllPersonsWereDestroyed();
std::cout << "Testing Image" << std::endl;
bbe::test::testImage();
Person::checkIfAllPersonsWereDestroyed();
std::cout << "All Tests complete!" << std::endl;
}
}
}
|
Brotcrunsher/BrotboxEngine
|
BrotBoxEngineTest/Tests/AllTests.h
|
C
|
mit
| 3,047
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta charset="utf-8" />
<title>Démos : Panneaux dépliants accessibles (show/hide) avec ARIA et en Vanilla Javascript - Van11y </title>
<link href="./styles.css" rel="stylesheet" media="all" />
<meta name="description" content="Ce script va transformer une simple liste de Hx/contenus en de beaux panneaux dépliants (hide/show), en utilisant ARIA" />
<meta name="keywords" content="collection, accessibilité, panneaux dépliants, accordéon, scripts, projets, onglets, info-bulle, customisable" />
<meta property="og:type" content="website" />
<!-- Open Graph Meta Data -->
<meta property="og:title" content="Démo : Panneaux dépliants accessibles (show/hide) avec ARIA et en Vanilla Javascript - Van11y " />
<meta property="og:description" content="Ce script va transformer une simple liste de Hx/contenus en de beaux panneaux dépliants (hide/show), en utilisant ARIA" />
<meta property="og:image" content="https://van11y.net/apple-touch-icon_1471815930.png" />
<meta property="og:url" content="https://van11y.net/fr/panneaux-depliants-accessibles/" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:url" content="https://van11y.net/fr/panneaux-depliants-accessibles/" />
<meta name="twitter:title" content="Démos : Panneaux dépliants accessibles (show/hide) avec ARIA et en Vanilla Javascript - Van11y" />
<meta name="twitter:description" content="Ce script va transformer une simple liste de Hx/contenus en de beaux panneaux dépliants (hide/show), en utilisant ARIA" />
<meta name="twitter:image" content="https://van11y.net/apple-touch-icon_1471815930.png" />
<meta name="twitter:site" content="Van11y" />
<meta name="twitter:creator" content="Van11y" />
<meta name="robots" content="index, follow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body role="document">
<div id="page" class="mw960e" role="main">
<br>
<div class="aligncenter">
<a href="https://van11y.net/fr/" class="logo-link"><img src="https://van11y.net/layout/images/logo-van11y_1491639888.svg" alt="Retour à la page d’accueil" width="267" height="90" class="logo" /></a>
</div>
<br>
<h1 class="aligncenter">Démos : Panneaux dépliants accessibles avec <abbr title="Accessible Rich Internet Applications" lang="en" xml:lang="en">ARIA</abbr>, en Vanilla <abbr title="JavaScript" lang="en" xml:lang="en">JS</abbr></h1>
<h2 class="js-expandmore" data-hideshow-prefix-class="animated">Exemple animé (ouvert par défaut)</h2>
<div class="js-to_expand is-opened">
<p>Oui, ça poutre des marmottes.</p>
</div>
<br><br>
<h2 class="js-expandmore" data-hideshow-prefix-class="simple">Exemple non animé (fermé par défaut)</h2>
<div class="js-to_expand">
<p>Oui, ça poutre des coincoins aussi.</p>
</div>
<br><br>
<h2 class="js-expandmore" data-hideshow-prefix-class="simpleplus">Exemple avec un plus</h2>
<div class="js-to_expand">
<p>Oui, ça marche aussi, et ça met un « moins » quand c’est ouvert.</p>
</div>
<br><br>
<div class="relative dropdown-container">
<h2 class="js-expandmore2 mb0" data-hideshow-prefix-class2="dropdown" tabindex="0">Exemple de bouton <span lang="en">drop down</span></h2>
<div class="js-to_expand"> <!-- js-first_load -->
<div>Oui, ça poutre des coincoins aussi, et on peut faire apparaître du contenu avec une petite animation.
<br />Et c’est chargé via une configuration différente.
</div>
</div>
</div>
<br><br><br><br>
<div class="footer" role="contentinfo"><br>Ces démos sont des exemples de <a href="https://van11y.net/fr/panneaux-depliants-accessibles/" class="link">panneaux dépliants accessibles (<em lang="en" xml:lang="en">show/hide</em>) utilisant <abbr title="Accessible Rich Internet Applications" lang="en" xml:lang="en">ARIA</abbr></a>.<br></div>
<br><br>
</div>
<script src="../dist/van11y-accessible-hide-show-aria.min.js"></script>
<script>
var other_expand = van11yAccessibleHideShowAria({
HIDESHOW_EXPAND: 'js-expandmore2',
DATA_PREFIX_CLASS: 'data-hideshow-prefix-class2'
});
other_expand.attach();
</script>
</body>
</html>
|
nico3333fr/van11y-accessible-hide-show-aria
|
demo/index-fr.html
|
HTML
|
mit
| 4,231
|
<?php
include_once "includes/globalfunctions.php";
session_start();
if (!isset($_SESSION['authorization_id'])) {
navto("index.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php include "includes/head.html"; ?>
<link rel="stylesheet" type="text/css"
href="vendor/datatables/DataTables-1.10.15/css/dataTables.bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="vendor/datatables/Buttons-1.3.1/css/buttons.bootstrap.min.css"/>
<link rel="stylesheet" type="text/css"
href="vendor/datatables/FixedColumns-3.2.2/css/fixedColumns.bootstrap.min.css"/>
<link rel="stylesheet" type="text/css"
href="vendor/datatables/FixedHeader-3.1.2/css/fixedHeader.bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="vendor/datatables/KeyTable-2.2.1/css/keyTable.bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="vendor/datatables/Responsive-2.1.1/css/responsive.bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="vendor/datatables/RowReorder-1.2.0/css/rowReorder.bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="vendor/datatables/RowGroup-1.0.0/css/rowGroup.dataTables.min.css"/>
<link rel="stylesheet" type="text/css" href="vendor/jquery/jquery.datetimepicker.min.css"/>
</head>
<body>
<div id="wrapper">
<!-- include wrapper -->
<?php include "navigation.php"; ?>
<!-- Page Content -->
<div id="page-wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="page-header">
<div class="pull-right form-inline">
</div>
<h3><span class="totranslate">pagetitle.balance </span></h3>
<div class="row">
<div class="col-lg-8 no-padding">
<div class="col-lg-2 form-group">
<label for="dateFrom" class="control-label"> <span class="totranslate">label.from </span> </label>
<input class="form-control dateTimePicker" type="text" id="dateFrom" name="from">
</div>
<div class="col-lg-2 form-group">
<label for="dateTo" class="control-label"> <span class="totranslate">label.to </span> </label>
<input class="form-control dateTimePicker" type="text" id="dateTo" name="to">
</div>
<div class="form-group">
<div class="col-lg-2">
<label for="dateTo" class="control-label whiteText"> <span class="totranslate">label.search </span> </label>
<a href="javascript:getBalancesheet()" class="btn btn-primary form-control"
role="button"><span class="totranslate">label.search </span></a>
</div>
</div>
</div>
<div class="col-lg-4">
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div id="sumEventAmountText"></div>
</div>
</div>
</div>
<div id="balanceTableContainer">
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</div>
<!-- /#page-wrapper -->
</div>
</div>
<?php include "includes/script.html" ?>
<script type="text/javascript" src="vendor/datatables/DataTables-1.10.15/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="vendor/datatables/DataTables-1.10.15/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" src="vendor/datatables/Buttons-1.3.1/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="vendor/datatables/Buttons-1.3.1/js/buttons.bootstrap.min.js"></script>
<script type="text/javascript" src="vendor/datatables/Buttons-1.3.1/js/buttons.colVis.min.js"></script>
<script type="text/javascript" src="vendor/datatables/Buttons-1.3.1/js/buttons.print.min.js"></script>
<script type="text/javascript"
src="vendor/datatables/FixedColumns-3.2.2/js/dataTables.fixedColumns.min.js"></script>
<script type="text/javascript" src="vendor/datatables/FixedHeader-3.1.2/js/dataTables.fixedHeader.min.js"></script>
<script type="text/javascript" src="vendor/datatables/KeyTable-2.2.1/js/dataTables.keyTable.min.js"></script>
<script type="text/javascript" src="vendor/datatables/Responsive-2.1.1/js/dataTables.responsive.min.js"></script>
<script type="text/javascript" src="vendor/datatables/Responsive-2.1.1/js/responsive.bootstrap.min.js"></script>
<script type="text/javascript" src="vendor/datatables/RowReorder-1.2.0/js/dataTables.rowReorder.min.js"></script>
<script type="text/javascript" src="vendor/datatables/RowGroup-1.0.0/js/dataTables.rowGroup.min.js"></script>
<script type="text/javascript" src="vendor/jquery/jquery.datetimepicker.full.min.js"></script>
<script type="text/javascript" src="js/dataTableCast.js"></script>
<script type="text/javascript" src="js/moment.min.js"></script>
<script type="text/javascript" src="js/balance.js"></script>
<script type="text/javascript">
var settingLocale = '<?php echo(isset($_SESSION['language']) ? $_SESSION['language'] : "en") ?>';
initSite(settingLocale);
var dateTimeStart = moment().format("01-MM-YYYY");
var dateTimeEnd = moment().daysInMonth() + moment().format("-MM-YYYY");
jQuery.datetimepicker.setLocale('de');
$('#dateFrom').datetimepicker({
format: 'd.m.Y',
value: dateTimeStart,
timepicker: false,
step: 5
});
$('#dateTo').datetimepicker({
format: 'd.m.Y',
value: dateTimeEnd,
timepicker: false,
step: 5
});
getBalancesheet();
$(document).ready(function () {
finishLoadingSite();
});
</script>
</body>
</html>
|
Bonus83/cast
|
site/balancesheet.php
|
PHP
|
mit
| 6,413
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.