code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
<?php
/*
* This file is part of Laravel HTTP Adapter.
*
* (c) Hidde Beydals <hello@hidde.co>, Mark Redeman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace HiddeCo\HttpAdapter\Adapters;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcherInterface as SymfonyDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* This adapter provides a Laravel integration for applications
* using the Symfony EventDispatcherInterface.
*
* It passes any request on to a Symfony Dispatcher and only
* uses the Laravel Dispatcher when dispatching events.
*/
abstract class AbstractEventDispatcher implements SymfonyDispatcher
{
/**
* The Laravel Events Dispatcher.
*
* @var \Illuminate\Contracts\Events\Dispatcher|\Illuminate\Events\Dispatcher
*/
protected $laravelDispatcher;
/**
* The Symfony Event Dispatcher.
*
* @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
*/
protected $symfonyDispatcher;
/**
* Dispatches an event to all registered listeners.
*
* @param string $eventName The name of the event to dispatch. The name of
* the event is the name of the method that is
* invoked on listeners.
* @param Event $event The event to pass to the event handlers/listeners.
* If not supplied, an empty Event instance is created.
*
* @return Event
*/
public function dispatch($eventName, Event $event = null)
{
if ($event === null) {
$event = new Event();
}
$event->setName($eventName);
$event->setDispatcher($this);
$this->laravelDispatcher->fire($eventName, $event);
$this->symfonyDispatcher->dispatch($eventName, $event);
$event->setDispatcher($this);
return $event;
}
/**
* Adds an event listener that listens on the specified events.
*
* @param string $eventName The event to listen on
* @param callable $listener The listener
* @param int $priority The higher this value, the earlier an event
* listener will be triggered in the chain.
*/
public function addListener($eventName, $listener, $priority = 0)
{
$this->symfonyDispatcher->addListener($eventName, $listener, $priority);
}
/**
* Adds an event subscriber.
*
* The subscriber is asked for all the events he is
* interested in and added as a listener for these events.
*
* @param EventSubscriberInterface $subscriber The subscriber.
*/
public function addSubscriber(EventSubscriberInterface $subscriber)
{
$this->symfonyDispatcher->addSubscriber($subscriber);
}
/**
* Removes an event listener from the specified events.
*
* @param string $eventName The event to remove a listener from
* @param callable $listenerToBeRemoved The listener to remove
*/
public function removeListener($eventName, $listenerToBeRemoved)
{
$this->symfonyDispatcher->removeListener($eventName, $listenerToBeRemoved);
}
/**
* Removes an event subscriber.
*
* @param EventSubscriberInterface $subscriber The subscriber
*/
public function removeSubscriber(EventSubscriberInterface $subscriber)
{
$this->symfonyDispatcher->removeSubscriber($subscriber);
}
/**
* Gets the listeners of a specific event or all listeners.
*
* @param string $eventName The name of the event
*
* @return array The event listeners for the specified event, or all event listeners by event name
*/
public function getListeners($eventName = null)
{
return $this->symfonyDispatcher->getListeners($eventName);
}
/**
* Checks whether an event has any registered listeners.
*
* @param string $eventName The name of the event
*
* @return bool true if the specified event has any listeners, false otherwise
*/
public function hasListeners($eventName = null)
{
return ($this->symfonyDispatcher->hasListeners($eventName) ||
$this->laravelDispatcher->hasListeners($eventName));
}
}
| Java |
class UsersController < ApplicationController
load_and_authorize_resource
def index
end
def update
if params[:admins].present?
@new_admins = User.not_admins.where(:id => params[:admins])
@new_admins.map {|user| user.admin = true}
@no_longer_admins = User.admins.where('id NOT IN (?)', params[:admins])
@no_longer_admins.map {|user| user.admin = false}
if (@new_admins + @no_longer_admins).all? {|user| user.save}
flash[:success] = 'Admins updated'
else
flash[:error] = 'Error updating the admins, please try again'
end
else
flash[:error] = "You can't remove ALL the admins!"
end
redirect_to users_url
end
def new
end
def create
if @user.save
@user.update_attribute :admin, true
flash[:success] = 'Welcome to Bennett!'
sign_in(@user, :bypass => true)
redirect_to root_url
else
render :new
end
end
end
| Java |
"use strict";
var gulp = require('gulp');
var clean = require('gulp-clean');
var cleanTask = function() {
return gulp.src('dist', { read: false })
.pipe(clean());
};
gulp.task('clean', cleanTask);
module.exports = cleanTask;
| Java |
scripts
=======
Some scripts
| Java |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="apple-touch-icon" sizes="76x76" href="assets/img/apple-icon.png">
<link rel="icon" type="image/png" href="assets/img/favicon.png">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>Material Kit by Creative Tim</title>
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<!-- Fonts and icons -->
<link rel="stylesheet" href="//fonts.googleapis.com/icon?family=Material+Icons" />
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Roboto:300,400,500,700" />
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" />
<!-- CSS Files -->
<link href="assets/css/bootstrap.min.css" rel="stylesheet" />
<link href="assets/css/material-kit.css" rel="stylesheet"/>
<!-- CSS Just for demo purpose, don't include it in your project -->
<link href="assets/css/demo.css" rel="stylesheet" />
</head>
<body class="index-page">
<!-- Navbar -->
<nav class="navbar navbar-transparent navbar-fixed-top navbar-color-on-scroll">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navigation-index">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="http://www.creative-tim.com">
<div class="logo-container">
<div class="logo">
<img src="assets/img/logo.png" alt="Creative Tim Logo" rel="tooltip" title="<b>Material Kit</b> was Designed & Coded with care by the staff from <b>Creative Tim</b>" data-placement="bottom" data-html="true">
</div>
<div class="brand">
Creative Tim
</div>
</div>
</a>
</div>
<div class="collapse navbar-collapse" id="navigation-index">
<ul class="nav navbar-nav navbar-right">
<li>
<a href="components-documentation.html" target="_blank">
<i class="material-icons">dashboard</i> Components
</a>
</li>
<li>
<a href="http://demos.creative-tim.com/material-kit-pro/presentation.html?ref=utp-freebie" target="_blank">
<i class="material-icons">unarchive</i> Upgrade to PRO
</a>
</li>
<li>
<a rel="tooltip" title="Follow us on Twitter" data-placement="bottom" href="//twitter.com/CreativeTim" target="_blank" class="btn btn-white btn-simple btn-just-icon">
<i class="fa fa-twitter"></i>
</a>
</li>
<li>
<a rel="tooltip" title="Like us on Facebook" data-placement="bottom" href="//www.facebook.com/CreativeTim" target="_blank" class="btn btn-white btn-simple btn-just-icon">
<i class="fa fa-facebook-square"></i>
</a>
</li>
<li>
<a rel="tooltip" title="Follow us on Instagram" data-placement="bottom" href="//www.instagram.com/CreativeTimOfficial" target="_blank" class="btn btn-white btn-simple btn-just-icon">
<i class="fa fa-instagram"></i>
</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- End Navbar -->
<div class="wrapper">
<div class="header header-filter" style="background-image: url('assets/img/bg2.jpeg');">
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="brand">
<h1>Material Kit.</h1>
<h3>A Badass Bootstrap UI Kit based on Material Design.</h3>
</div>
</div>
</div>
</div>
</div>
<div class="main main-raised">
<div class="section section-basic">
<div class="container">
<div class="title">
<h2>Basic Elements</h2>
</div>
<div id="buttons">
<div class="title">
<h3>Buttons <br />
<small>Pick your style</small>
</h3>
</div>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<button class="btn btn-primary">Default</button>
<button class="btn btn-primary btn-round">Round</button>
<button class="btn btn-primary btn-round">
<i class="material-icons">favorite</i> With Icon
</button>
<button class="btn btn-primary btn-fab btn-fab-mini btn-round">
<i class="material-icons">favorite</i>
</button>
<button class="btn btn-primary btn-simple">Simple</button>
</div>
</div>
<div class="title">
<h3><small>Pick your size</small></h3>
</div>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<button class="btn btn-primary btn-xs">x-Small</button>
<button class="btn btn-primary btn-sm">Small</button>
<button class="btn btn-primary">Regular</button>
<button class="btn btn-primary btn-lg">Large</button>
</div>
</div>
<div class="title">
<h3><small> Pick your color </small></h3>
</div>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<button class="btn">Default</button>
<button class="btn btn-primary">Primary</button>
<button class="btn btn-info">Info</button>
<button class="btn btn-success">Success</button>
<button class="btn btn-warning">Warning</button>
<button class="btn btn-danger">Danger</button>
</div>
</div>
<div class="title">
<h3>Links</h3>
</div>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<button class="btn btn-simple">Default</button>
<button class="btn btn-simple btn-primary ">Primary</button>
<button class="btn btn-simple btn-info">Info</button>
<button class="btn btn-simple btn-success">Success</button>
<button class="btn btn-simple btn-warning">Warning</button>
<button class="btn btn-simple btn-danger">Danger</button>
</div>
</div>
</div>
<div id="inputs">
<div class="title">
<h3>Inputs</h3>
</div>
<div class="row">
<div class="col-sm-3">
<div class="form-group">
<input type="text" value="" placeholder="Regular" class="form-control" />
</div>
</div>
<div class="col-sm-3">
<div class="form-group label-floating">
<label class="control-label">With Floating Label</label>
<input type="email" class="form-control">
</div>
</div>
<div class="col-sm-3">
<div class="form-group label-floating has-success">
<label class="control-label">Success input</label>
<input type="text" value="Success" class="form-control" />
<span class="form-control-feedback">
<i class="material-icons">done</i>
</span>
</div>
</div>
<div class="col-sm-3">
<div class="form-group label-floating has-error">
<label class="control-label">Error input</label>
<input type="email" value="Error Input" class="form-control" />
<span class="material-icons form-control-feedback">clear</span>
</div>
</div>
<div class="col-sm-3">
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">group</i>
</span>
<input type="text" class="form-control" placeholder="With Material Icons">
</div>
</div>
<div class="col-sm-3">
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-group"></i>
</span>
<input type="text" class="form-control" placeholder="With Font Awesome Icons">
</div>
</div>
</div>
</div>
<div class="space-70"></div>
<div id="checkRadios">
<div class="row">
<div class="col-sm-3">
<div class="title">
<h3>Checkboxes</h3>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="optionsCheckboxes">
Unchecked
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="optionsCheckboxes" checked>
Checked
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="optionsCheckboxes" disabled>
Disabled Unchecked
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="optionsCheckboxes" disabled checked>
Disabled Checked
</label>
</div>
</div>
<div class="col-sm-3">
<div class="title">
<h3>Radio Buttons</h3>
</div>
<div class="radio">
<label>
<input type="radio" name="optionsRadios">
Radio is off
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optionsRadios" checked="true">
Radio is on
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optionsRadiosDisabled" disabled>
Disabled Radio is off
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optionsRadiosDisabled" checked="true" disabled>
Disabled Radio is on
</label>
</div>
</div>
<div class="col-sm-3">
<div class="title">
<h3>Toggle Buttons</h3>
</div>
<div class="togglebutton">
<label>
<input type="checkbox" checked="">
Toggle is on
</label>
</div>
<div class="togglebutton">
<label>
<input type="checkbox">
Toggle is off
</label>
</div>
</div>
<div class="col-sm-3">
<div class="title">
<h3>Sliders</h3>
</div>
<div id="sliderRegular" class="slider"></div>
<div id="sliderDouble" class="slider slider-info"></div>
</div>
</div>
</div>
</div>
</div>
<div class="section section-navbars">
<div class="container" id="menu-dropdown">
<div class="row">
<div class="col-md-6">
<div class="title">
<h3>Menu</h3>
</div>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#example-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" href="#">Menu</a>
</div>
<div class="collapse navbar-collapse" id="example-navbar">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown
<b class="caret"></b>
</a>
<ul class="dropdown-menu dropdown-menu-right">
<li class="dropdown-header">Dropdown header</li>
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
<li class="divider"></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
</div>
<div class="col-md-6">
<div class="title">
<h3>Menu with Icons</h3>
</div>
<nav class="navbar navbar-info">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#example-navbar-icons">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Icons</a>
</div>
<div class="collapse navbar-collapse" id="example-navbar-icons">
<ul class="nav navbar-nav navbar-right">
<li>
<a href="#pablo"><i class="material-icons">email</i></a>
</li>
<li>
<a href="#pablo"><i class="material-icons">face</i></a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="material-icons">settings</i>
<b class="caret"></b>
</a>
<ul class="dropdown-menu dropdown-menu-right">
<li class="dropdown-header">Dropdown header</li>
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
<li class="divider"></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
</div>
</div>
<div class="title">
<h3>Navigation</h3>
</div>
</div>
<div id="navbar">
<div class="navigation-example">
<!-- Navbar Primary -->
<nav class="navbar navbar-primary">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#example-navbar-primary">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#pablo">Primary Color</a>
</div>
<div class="collapse navbar-collapse" id="example-navbar-primary">
<ul class="nav navbar-nav navbar-right">
<li class="active">
<a href="#pablo">
<i class="material-icons">explore</i>
Discover
</a>
</li>
<li>
<a href="#pablo">
<i class="material-icons">account_circle</i>
Profile
</a>
</li>
<li>
<a href="#pablo">
<i class="material-icons">settings</i>
Settings
</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- End Navbar Primary -->
<!-- Navbar Info -->
<nav class="navbar navbar-info">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#example-navbar-info">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#pablo">Info Color</a>
</div>
<div class="collapse navbar-collapse" id="example-navbar-info">
<ul class="nav navbar-nav navbar-right">
<li class="active">
<a href="#pablo" >
Discover
</a>
</li>
<li>
<a href="#pablo">
Profile
</a>
</li>
<li>
<a href="#pablo">
Settings
</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- End Navbar Info -->
<!-- Navbar Success -->
<nav class="navbar navbar-success">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#example-navbar-success">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Success Color</a>
</div>
<div class="collapse navbar-collapse" id="example-navbar-success">
<ul class="nav navbar-nav navbar-right">
<li class="active">
<a href="#pablo">
<i class="material-icons">explore</i>
</a>
</li>
<li>
<a href="#pablo">
<i class="material-icons">account_circle</i>
</a>
</li>
<li>
<a href="#pablo">
<i class="material-icons">settings</i>
</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- End Navbar Success -->
<!-- Navbar Warning -->
<nav class="navbar navbar-warning">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#example-navbar-warning">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#pablo">Warning Color</a>
</div>
<div class="collapse navbar-collapse" id="example-navbar-warning">
<ul class="nav navbar-nav navbar-right">
<li>
<a href="#pablo">
<i class="fa fa-facebook-square"></i>
</a>
</li>
<li>
<a href="#pablo">
<i class="fa fa-twitter"></i>
</a>
</li>
<li>
<a href="#pablo">
<i class="fa fa-google-plus"></i>
</a>
</li>
<li>
<a href="#pablo">
<i class="fa fa-instagram"></i>
</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- End Navbar Warning -->
<!-- Navbar Danger -->
<nav class="navbar navbar-danger">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#example-navbar-danger">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#pablo">Danger Color</a>
</div>
<div class="collapse navbar-collapse" id="example-navbar-danger">
<ul class="nav navbar-nav navbar-right">
<li>
<a href="#pablo">
<i class="fa fa-facebook-square"></i> Share
</a>
</li>
<li>
<a href="#pablo">
<i class="fa fa-twitter"></i> Tweet
</a>
</li>
<li>
<a href="#pablo">
<i class="fa fa-pinterest"></i> Pin
</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- End Navbar Danger -->
<!-- Navbar Transparent -->
<nav class="navbar navbar-transparent">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#example-navbar-transparent">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#pablo">Transparent</a>
</div>
<div class="collapse navbar-collapse" id="example-navbar-transparent">
<ul class="nav navbar-nav navbar-right">
<li>
<a href="#pablo">
<i class="fa fa-facebook-square"></i>
Facebook
</a>
</li>
<li>
<a href="#pablo">
<i class="fa fa-twitter"></i>
Twitter
</a>
</li>
<li>
<a href="#pablo">
<i class="fa fa-instagram"></i> Instagram
</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- End Navbar Transparent-->
</div>
</div>
</div>
<!-- End .section-navbars -->
<div class="section section-tabs">
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="title">
<h3>Tabs with Icons on Card</h3>
</div>
<!-- Tabs with icons on Card -->
<div class="card card-nav-tabs">
<div class="header header-success">
<!-- colors: "header-primary", "header-info", "header-success", "header-warning", "header-danger" -->
<div class="nav-tabs-navigation">
<div class="nav-tabs-wrapper">
<ul class="nav nav-tabs" data-tabs="tabs">
<li class="active">
<a href="#profile" data-toggle="tab">
<i class="material-icons">face</i>
Profile
</a>
</li>
<li>
<a href="#messages" data-toggle="tab">
<i class="material-icons">chat</i>
Messages
</a>
</li>
<li>
<a href="#settings" data-toggle="tab">
<i class="material-icons">build</i>
Settings
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="content">
<div class="tab-content text-center">
<div class="tab-pane active" id="profile">
<p> I will be the leader of a company that ends up being worth billions of dollars, because I got the answers. I understand culture. I am the nucleus. I think that’s a responsibility that I have, to push possibilities, to show people, this is the level that things could be at. I think that’s a responsibility that I have, to push possibilities, to show people, this is the level that things could be at. </p>
</div>
<div class="tab-pane" id="messages">
<p> I think that’s a responsibility that I have, to push possibilities, to show people, this is the level that things could be at. I will be the leader of a company that ends up being worth billions of dollars, because I got the answers. I understand culture. I am the nucleus. I think that’s a responsibility that I have, to push possibilities, to show people, this is the level that things could be at.</p>
</div>
<div class="tab-pane" id="settings">
<p>I think that’s a responsibility that I have, to push possibilities, to show people, this is the level that things could be at. So when you get something that has the name Kanye West on it, it’s supposed to be pushing the furthest possibilities. I will be the leader of a company that ends up being worth billions of dollars, because I got the answers. I understand culture. I am the nucleus.</p>
</div>
</div>
</div>
</div>
<!-- End Tabs with icons on Card -->
</div>
<div class="col-md-6">
<div class="title">
<h3>Tabs on Plain Card</h3>
</div>
<!-- Tabs on Plain Card -->
<div class="card card-nav-tabs card-plain">
<div class="header header-danger">
<!-- colors: "header-primary", "header-info", "header-success", "header-warning", "header-danger" -->
<div class="nav-tabs-navigation">
<div class="nav-tabs-wrapper">
<ul class="nav nav-tabs" data-tabs="tabs">
<li class="active"><a href="#home" data-toggle="tab">Home</a></li>
<li><a href="#updates" data-toggle="tab">Updates</a></li>
<li><a href="#history" data-toggle="tab">History</a></li>
</ul>
</div>
</div>
</div>
<div class="content">
<div class="tab-content text-center">
<div class="tab-pane active" id="home">
<p>I think that’s a responsibility that I have, to push possibilities, to show people, this is the level that things could be at. So when you get something that has the name Kanye West on it, it’s supposed to be pushing the furthest possibilities. I will be the leader of a company that ends up being worth billions of dollars, because I got the answers. I understand culture. I am the nucleus.</p>
</div>
<div class="tab-pane" id="updates">
<p> I will be the leader of a company that ends up being worth billions of dollars, because I got the answers. I understand culture. I am the nucleus. I think that’s a responsibility that I have, to push possibilities, to show people, this is the level that things could be at. I think that’s a responsibility that I have, to push possibilities, to show people, this is the level that things could be at. </p>
</div>
<div class="tab-pane" id="history">
<p> I think that’s a responsibility that I have, to push possibilities, to show people, this is the level that things could be at. I will be the leader of a company that ends up being worth billions of dollars, because I got the answers. I understand culture. I am the nucleus. I think that’s a responsibility that I have, to push possibilities, to show people, this is the level that things could be at.</p>
</div>
</div>
</div>
</div>
<!-- End Tabs on plain Card -->
</div>
</div>
</div>
</div>
<!-- End Section Tabs -->
<div class="section section-pagination">
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="title">
<h3>Progress Bars</h3>
</div>
<div class="progress progress-line-primary">
<div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 30%;">
<span class="sr-only">60% Complete</span>
</div>
</div>
<div class="progress progress-line-info">
<div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;">
<span class="sr-only">60% Complete</span>
</div>
</div>
<div class="progress progress-line-danger">
<div class="progress-bar progress-bar-success" style="width: 35%">
<span class="sr-only">35% Complete (success)</span>
</div>
<div class="progress-bar progress-bar-warning" style="width: 20%">
<span class="sr-only">20% Complete (warning)</span>
</div>
<div class="progress-bar progress-bar-danger" style="width: 10%">
<span class="sr-only">10% Complete (danger)</span>
</div>
</div>
<br />
<div class="title">
<h3>Navigation Pills</h3>
</div>
<ul class="nav nav-pills" role="tablist">
<!--
color-classes: "nav-pills-primary", "nav-pills-info", "nav-pills-success", "nav-pills-warning","nav-pills-danger"
-->
<li>
<a href="#dashboard" role="tab" data-toggle="tab">
<i class="material-icons">dashboard</i>
Dashboard
</a>
</li>
<li class="active">
<a href="#schedule" role="tab" data-toggle="tab">
<i class="material-icons">schedule</i>
Schedule
</a>
</li>
<li>
<a href="#tasks" role="tab" data-toggle="tab">
<i class="material-icons">list</i>
Tasks
</a>
</li>
<li>
<a href="#payments" role="tab" data-toggle="tab">
<i class="material-icons">attach_money</i>
Payments
</a>
</li>
</ul>
</div>
<div class="col-md-6">
<div class="title">
<h3>Pagination</h3>
</div>
<ul class="pagination pagination-primary">
<!--
color-classes: "pagination-primary", "pagination-info", "pagination-success", "pagination-warning", "pagination-danger"
-->
<li><a href="javascript:void(0);">1</a></li>
<li><a href="javascript:void(0);">...</a></li>
<li><a href="javascript:void(0);">5</a></li>
<li><a href="javascript:void(0);">6</a></li>
<li class="active"><a href="javascript:void(0);">7</a></li>
<li><a href="javascript:void(0);">8</a></li>
<li><a href="javascript:void(0);">9</a></li>
<li><a href="javascript:void(0);">...</a></li>
<li><a href="javascript:void(0);">12</a></li>
</ul>
<ul class="pagination pagination-info">
<li><a href="javascript:void(0);">< prev</a></li>
<li><a href="javascript:void(0);">1</a></li>
<li><a href="javascript:void(0);">2</a></li>
<li class="active"><a href="javascript:void(0);">3</a></li>
<li><a href="javascript:void(0);">4</a></li>
<li><a href="javascript:void(0);">5</a></li>
<li><a href="javascript:void(0);">next ></a></li>
</ul>
<div class="title">
<h3>Labels </h3>
</div>
<span class="label label-default">Default</span>
<span class="label label-primary">Primary</span>
<span class="label label-info">Info</span>
<span class="label label-success">Success</span>
<span class="label label-warning">Warning</span>
<span class="label label-danger">Danger</span>
</div>
</div>
<div class="space"></div>
<div class="title">
<h3>Notifications</h3>
</div>
</div>
</div>
<div class="section section-notifications" id="notifications">
<div class="alert alert-info">
<div class="container-fluid">
<div class="alert-icon">
<i class="material-icons">info_outline</i>
</div>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true"><i class="material-icons">clear</i></span>
</button>
<b>Info alert:</b> You've got some friends nearby, stop looking at your phone and find them...
</div>
</div>
<div class="alert alert-success">
<div class="container-fluid">
<div class="alert-icon">
<i class="material-icons">check</i>
</div>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true"><i class="material-icons">clear</i></span>
</button>
<b>Success Alert:</b> Yuhuuu! You've got your $11.99 album from The Weeknd
</div>
</div>
<div class="alert alert-warning">
<div class="container-fluid">
<div class="alert-icon">
<i class="material-icons">warning</i>
</div>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true"><i class="material-icons">clear</i></span>
</button>
<b>Warning Alert:</b> Hey, it looks like you still have the "copyright © 2015" in your footer. Please update it!
</div>
</div>
<div class="alert alert-danger">
<div class="container-fluid">
<div class="alert-icon">
<i class="material-icons">error_outline</i>
</div>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true"><i class="material-icons">clear</i></span>
</button>
<b>Error Alert:</b> Damn man! You screwed up the server this time. You should find a good excuse for your Boss...
</div>
</div>
<div class="clearfix"></div>
</div><!-- end notifications -->
<div class="section">
<div class="container tim-container">
<div class="title">
<h2>Typography</h2>
</div>
<div id="typography">
<div class="row">
<div class="tim-typo">
<h1><span class="tim-note">Header 1</span>The Life of Material Kit </h1>
</div>
<div class="tim-typo">
<h2><span class="tim-note">Header 2</span>The Life of Material Kit</h2>
</div>
<div class="tim-typo">
<h3><span class="tim-note">Header 3</span>The Life of Material Kit</h3>
</div>
<div class="tim-typo">
<h4><span class="tim-note">Header 4</span>The Life of Material Kit</h4>
</div>
<div class="tim-typo">
<h5><span class="tim-note">Header 5</span>The Life of Material Kit</h5>
</div>
<div class="tim-typo">
<h6><span class="tim-note">Header 6</span>The Life of Material Kit</h6>
</div>
<div class="tim-typo">
<p><span class="tim-note">Paragraph</span>
I will be the leader of a company that ends up being worth billions of dollars, because I got the answers. I understand culture. I am the nucleus. I think that’s a responsibility that I have, to push possibilities, to show people, this is the level that things could be at.</p>
</div>
<div class="tim-typo">
<span class="tim-note">Quote</span>
<blockquote>
<p>
I will be the leader of a company that ends up being worth billions of dollars, because I got the answers. I understand culture. I am the nucleus. I think that’s a responsibility that I have, to push possibilities, to show people, this is the level that things could be at.
</p>
<small>
Kanye West, Musician
</small>
</blockquote>
</div>
<div class="tim-typo">
<span class="tim-note">Muted Text</span>
<p class="text-muted">
I will be the leader of a company that ends up being worth billions of dollars, because I got the answers...
</p>
</div>
<div class="tim-typo">
<span class="tim-note">Primary Text</span>
<p class="text-primary">
I will be the leader of a company that ends up being worth billions of dollars, because I got the answers... </p>
</div>
<div class="tim-typo">
<span class="tim-note">Info Text</span>
<p class="text-info">
I will be the leader of a company that ends up being worth billions of dollars, because I got the answers... </p>
</div>
<div class="tim-typo">
<span class="tim-note">Success Text</span>
<p class="text-success">
I will be the leader of a company that ends up being worth billions of dollars, because I got the answers... </p>
</div>
<div class="tim-typo">
<span class="tim-note">Warning Text</span>
<p class="text-warning">
I will be the leader of a company that ends up being worth billions of dollars, because I got the answers...
</p>
</div>
<div class="tim-typo">
<span class="tim-note">Danger Text</span>
<p class="text-danger">
I will be the leader of a company that ends up being worth billions of dollars, because I got the answers... </p>
</div>
<div class="tim-typo">
<h2><span class="tim-note">Small Tag</span>
Header with small subtitle <br>
<small>Use "small" tag for the headers</small>
</h2>
</div>
</div>
</div>
<div class="space-50"></div>
<div id="images">
<div class="title">
<h2>Images</h2>
</div>
<br>
<div class="row">
<div class="col-sm-2">
<h4>Rounded Image</h4>
<img src="assets/img/avatar.jpg" alt="Rounded Image" class="img-rounded img-responsive">
</div>
<div class="col-sm-2 col-sm-offset-1">
<h4>Circle Image</h4>
<img src="assets/img/avatar.jpg" alt="Circle Image" class="img-circle img-responsive">
</div>
<div class="col-sm-2 col-sm-offset-1">
<h4>Rounded Raised</h4>
<img src="assets/img/avatar.jpg" alt="Raised Image" class="img-rounded img-responsive img-raised">
</div>
<div class="col-sm-2 col-sm-offset-1">
<h4>Circle Raised</h4>
<img src="assets/img/avatar.jpg" alt="Thumbnail Image" class="img-circle img-raised img-responsive">
</div>
</div>
<div class="row">
</div>
</div>
</div>
</div>
<div class="section" id="javascriptComponents">
<div class="container">
<div class="title">
<h2>Javascript components</h2>
</div>
<div class="row" id="modals">
<div class="col-md-6">
<div class="title">
<h3>Modal</h3>
</div>
<button class="btn btn-primary" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
</div>
<div class="col-md-6">
<div class="title">
<h3>Popovers</h3>
</div>
<button type="button" class="btn btn-default" data-toggle="popover" data-placement="left" title="Popover on left" data-content="Here will be some very useful information about his popover.<br> Here will be some very useful information about his popover." data-container="body">On left</button>
<button type="button" class="btn btn-default" data-toggle="popover" data-placement="top" title="Popover on top" data-content="Here will be some very useful information about his popover." data-container="body">On top</button>
<button type="button" class="btn btn-default" data-toggle="popover" data-placement="bottom" title="Popover on bottom" data-content="Here will be some very useful information about his popover." data-container="body">On bottom</button>
<button type="button" class="btn btn-default" data-toggle="popover" data-placement="right" title="Popover on right" data-content="Here will be some very useful information about his popover." data-container="body">On right</button>
</div>
<br /><br />
<div class="col-md-6">
<div class="title">
<h3>Datepicker</h3>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group label-static">
<label class="control-label">Datepicker</label>
<input type="text" class="datepicker form-control" value="03/12/2016" />
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="title">
<h3>Tooltips</h3>
</div>
<button type="button" class="btn btn-default btn-tooltip" data-toggle="tooltip" data-placement="left" title="Tooltip on left" data-container="body">On left</button>
<button type="button" class="btn btn-default btn-tooltip" data-toggle="tooltip" data-placement="top" title="Tooltip on top" data-container="body">On top</button>
<button type="button" class="btn btn-default btn-tooltip" data-toggle="tooltip" data-placement="bottom" title="Tooltip on bottom" data-container="body">On bottom</button>
<button type="button" class="btn btn-default btn-tooltip" data-toggle="tooltip" data-placement="right" title="Tooltip on right" data-container="body">On right</button>
<div class="clearfix"></div><br><br>
</div>
<div class="title">
<h3>Carousel</h3>
</div>
</div>
</div>
</div>
<div class="section" id="carousel">
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<!-- Carousel Card -->
<div class="card card-raised card-carousel">
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
<div class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
<li data-target="#carousel-example-generic" data-slide-to="1"></li>
<li data-target="#carousel-example-generic" data-slide-to="2"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner">
<div class="item active">
<img src="assets/img/bg2.jpeg" alt="Awesome Image">
<div class="carousel-caption">
<h4><i class="material-icons">location_on</i> Yellowstone National Park, United States</h4>
</div>
</div>
<div class="item">
<img src="assets/img/bg3.jpeg" alt="Awesome Image">
<div class="carousel-caption">
<h4><i class="material-icons">location_on</i> Somewhere Beyond, United States</h4>
</div>
</div>
<div class="item">
<img src="assets/img/bg4.jpeg" alt="Awesome Image">
<div class="carousel-caption">
<h4><i class="material-icons">location_on</i> Yellowstone National Park, United States</h4>
</div>
</div>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">
<i class="material-icons">keyboard_arrow_left</i>
</a>
<a class="right carousel-control" href="#carousel-example-generic" data-slide="next">
<i class="material-icons">keyboard_arrow_right</i>
</a>
</div>
</div>
</div>
<!-- End Carousel Card -->
</div>
</div>
</div>
</div>
<div class="section">
<div class="container text-center">
<div class="row">
<div class="col-md-8 col-md-offset-2 text-center">
<h2>Completed with examples</h2>
<h4>The kit comes with three pre-built pages to help you get started faster. You can change the text and images and you're good to go. More importantly, looking at them will give you a picture of what you can built with this powerful kit.</h4>
</div>
</div>
</div>
</div>
<div class="section section-full-screen section-signup" style="background-image: url('assets/img/city.jpg'); background-size: cover; background-position: top center; min-height: 700px;">
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="card card-signup">
<form class="form" method="" action="">
<div class="header header-primary text-center">
<h4>Sign Up</h4>
<div class="social-line">
<a href="#pablo" class="btn btn-simple btn-just-icon">
<i class="fa fa-facebook-square"></i>
</a>
<a href="#pablo" class="btn btn-simple btn-just-icon">
<i class="fa fa-twitter"></i>
</a>
<a href="#pablo" class="btn btn-simple btn-just-icon">
<i class="fa fa-google-plus"></i>
</a>
</div>
</div>
<p class="text-divider">Or Be Classical</p>
<div class="content">
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">face</i>
</span>
<input type="text" class="form-control" placeholder="First Name...">
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">email</i>
</span>
<input type="text" class="form-control" placeholder="Email...">
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">lock_outline</i>
</span>
<input type="password" placeholder="Password..." class="form-control" />
</div>
<!-- If you want to add a checkbox to this form, uncomment this code
<div class="checkbox">
<label>
<input type="checkbox" name="optionsCheckboxes" checked>
Subscribe to newsletter
</label>
</div> -->
</div>
<div class="footer text-center">
<a href="#pablo" class="btn btn-simple btn-primary btn-lg">Get Started</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12 text-center">
<a href="examples/signup-page.html" class="btn btn-simple btn-primary btn-lg" target="_blank">View Signup Page</a>
</div>
<div class="space-50"></div>
<div class="section section-examples">
<div class="container-fluid text-center">
<div class="row">
<div class="col-md-6">
<a href="examples/landing-page.html" target="_blank">
<img src="assets/img/landing.jpg" alt="Rounded Image" class="img-rounded img-raised img-responsive">
<button class="btn btn-simple btn-primary btn-lg">View Landing Page</button>
</a>
</div>
<div class="col-md-6">
<a href="examples/profile-page.html" target="_blank">
<img src="assets/img/profile.jpg" alt="Rounded Image" class="img-rounded img-raised img-responsive">
<button class="btn btn-simple btn-primary btn-lg">View Profile Page</button>
</a>
</div>
</div>
</div>
</div>
<div class="section section-download">
<div class="container">
<div class="row text-center">
<div class="col-md-8 col-md-offset-2">
<h2>Do you love this UI Kit?</h2>
<h4>Cause if you do, it can be yours for FREE. Hit the button below to navigate to Creative Tim where you can find the kit. Start a new project or give an old Bootstrap project a new look!</h4>
</div>
<div class="col-xs-8 col-xs-offset-2 col-sm-4 col-sm-offset-4">
<a href="http://www.creative-tim.com/product/material-kit" class="btn btn-primary btn-lg">
<i class="material-icons">cloud_download</i> Free Download
</a>
</div>
</div>
<br><br>
<div class="row text-center">
<div class="col-md-8 col-md-offset-2">
<h2>Want more?</h2>
<h4>We've just launched <a href="http://demos.creative-tim.com/material-kit-pro/presentation.html?ref=utp-freebie" target="_blank">Material Kit PRO</a>. It has a huge number of components, sections and example pages. Start Your Development With A Badass Bootstrap UI Kit inspired by Material Design.</h4>
</div>
<div class="col-xs-8 col-xs-offset-2 col-sm-4 col-sm-offset-4">
<a href="http://demos.creative-tim.com/material-kit-pro/presentation.html?ref=utp-freebie" class="btn btn-upgrade btn-lg" target="_blank">
<i class="material-icons">unarchive</i> Upgrade to PRO
</a>
</div>
</div>
<div class="row sharing-area text-center">
<h3>Thank you for supporting us!</h3>
<a href="#" class="btn btn-twitter">
<i class="fa fa-twitter"></i>
Tweet
</a>
<a href="#" class="btn btn-facebook">
<i class="fa fa-facebook-square"></i>
Share
</a>
<a href="#" class="btn btn-google-plus">
<i class="fa fa-google-plus"></i>
Share
</a>
<a href="#" class="btn btn-github">
<i class="fa fa-github"></i>
Star
</a>
</div>
</div>
</div>
</div>
<footer class="footer">
<div class="container">
<nav class="pull-left">
<ul>
<li>
<a href="http://www.creative-tim.com">
Creative Tim
</a>
</li>
<li>
<a href="http://presentation.creative-tim.com">
About Us
</a>
</li>
<li>
<a href="http://blog.creative-tim.com">
Blog
</a>
</li>
<li>
<a href="http://www.creative-tim.com/license">
Licenses
</a>
</li>
</ul>
</nav>
<div class="copyright pull-right">
© 2016, made with <i class="material-icons">favorite</i> by Creative Tim for a better web.
</div>
</div>
</footer>
</div>
<!-- Sart Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
<i class="material-icons">clear</i>
</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean. A small river named Duden flows by their place and supplies it with the necessary regelialia. It is a paradisematic country, in which roasted parts of sentences fly into your mouth. Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic life One day however a small line of blind text by the name of Lorem Ipsum decided to leave for the far World of Grammar.
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default btn-simple">Nice Button</button>
<button type="button" class="btn btn-danger btn-simple" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- End Modal -->
</body>
<!-- Core JS Files -->
<script src="assets/js/jquery.min.js" type="text/javascript"></script>
<script src="assets/js/bootstrap.min.js" type="text/javascript"></script>
<script src="assets/js/material.min.js"></script>
<!-- Plugin for the Sliders, full documentation here: http://refreshless.com/nouislider/ -->
<script src="assets/js/nouislider.min.js" type="text/javascript"></script>
<!-- Plugin for the Datepicker, full documentation here: http://www.eyecon.ro/bootstrap-datepicker/ -->
<script src="assets/js/bootstrap-datepicker.js" type="text/javascript"></script>
<!-- Control Center for Material Kit: activating the ripples, parallax effects, scripts from the example pages etc -->
<script src="assets/js/material-kit.js" type="text/javascript"></script>
<script type="text/javascript">
$().ready(function(){
// the body of this function is in assets/material-kit.js
materialKit.initSliders();
window_width = $(window).width();
if (window_width >= 992){
big_image = $('.wrapper > .header');
$(window).on('scroll', materialKitDemo.checkScrollForParallax);
}
});
</script>
</html>
| Java |
import os
class Config(object):
DEBUG = False
TESTING = False
CSRF_ENABLED = True
SECRET_KEY = "super_secret_key"
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
class ProductionConfig(Config):
DEBUG = False
SECRET_KEY = os.environ['SECRET_KEY']
class DevelopmentConfig(Config):
DEVELOPMENT = True
DEBUG = True
class TestingConfig(Config):
TESTING = True
| Java |
<div id="about">
<header class="twelve columns">
<h1>My background</h1>
<p class="opening">I'm a programmer, entrepreneur, speaker, designer, and trail runner among other things. As an engineer I've worked across the stack in backend, web, and mobile. I live and work in Los Angeles and studied at UCLA.</p>
</header>
<div id="page-content" class="twelve columns">
<section class="twelve columns">
<p>I'm currently an Engineering Manager working on feature development and engineering best practices alongside a great team at <a href="https://www.gotinder.com/" target="_blank">Tinder</a>. I'm also an organizer of monthly meetups at the <a href="http://lactoforum.org/" target="_blank">LA CTO Forum</a>.</p>
<p> In 2015 I was featured in Inc.'s <a href="https://enplug.com/blog/enplug-makes-inc-magazines-2015-30-under-30-list">30 under 30</a> for co-founding <a href="https://enplug.com">Enplug</a>, a display software for teams and businesses.</p>
<p>You can find my work history on <a href="https://www.linkedin.com/in/alexross8">LinkedIn</a>, or you can download my <a href="/src/pdf/AlexRoss-Resume.pdf">resume</a>. I have a few projects on <a href="https://github.com/aleross">Github</a>.</p>
</section>
<article id="photos" class="twelve columns">
<img src="/src/img/about/1.jpg">
<img src="/src/img/about/4.jpg">
<img src="/src/img/about/13.jpg">
<img src="/src/img/about/11.jpg">
<img src="/src/img/about/5.jpg">
<img src="/src/img/about/7.jpg">
</article>
<article class="twelve columns">
<h2>Programming</h2>
<p>I frequently work across the full stack, including mobile. Below are some technologies I've used in production projects:</p>
<ul>
<li><strong>Front-end:</strong> HTML5, CSS3, SASS, JavaScript</li>
<li><strong>Back-end & scripting:</strong> NodeJS, PHP, Ruby, Python</li>
<li><strong>Frameworks:</strong> AngularJS, Bootstrap, jQuery, Wordpress, ZendFramework</li>
<li><strong>Servers:</strong> Linux, Apache, RabbitMQ, Rackspace, AWS</li>
<li><strong>Databases:</strong> MySQL, MongoDB, Redis, DynamoDB, Firebase (DBaaS)</li>
<li><strong>Mobile:</strong> Objective-C & Interface Builder, Java (Android), PhoneGap/Cordova</li>
<li><strong>Dev tools:</strong> Git, Grunt, Bower, NPM, Composer, Jasmine+Karma</li>
<li><strong>The Internet:</strong> DNS, HTTP, sockets, CDNs, load-balancing, etc.</li>
<li><strong>Design:</strong> Adobe Photoshop & Illustrator, InvisionApp</li>
</ul>
<p></p>
</article>
</div>
</div>
| Java |
var scroller = angular.module("scroller", ["ngTouch", "angular-websql"]); | Java |
/******************************************************************************
QtAV: Multimedia framework based on Qt and FFmpeg
Copyright (C) 2012-2016 Wang Bin <wbsecg1@gmail.com>
* This file is part of QtAV (from 2014)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
******************************************************************************/
#include "QtAV/LibAVFilter.h"
#include <QtCore/QSharedPointer>
#include "QtAV/private/Filter_p.h"
#include "QtAV/Statistics.h"
#include "QtAV/AudioFrame.h"
#include "QtAV/VideoFrame.h"
#include "QtAV/private/AVCompat.h"
#include "utils/internal.h"
#include "utils/Logger.h"
/*
* libav10.x, ffmpeg2.x: av_buffersink_read deprecated
* libav9.x: only av_buffersink_read can be used
* ffmpeg<2.0: av_buffersink_get_buffer_ref and av_buffersink_read
*/
// TODO: enabled = false if no libavfilter
// TODO: filter_complex
// NO COPY in push/pull
#define QTAV_HAVE_av_buffersink_get_frame (LIBAV_MODULE_CHECK(LIBAVFILTER, 4, 2, 0) || FFMPEG_MODULE_CHECK(LIBAVFILTER, 3, 79, 100)) //3.79.101: ff2.0.4
namespace QtAV {
#if QTAV_HAVE(AVFILTER)
// local types can not be used as template parameters
class AVFrameHolder {
public:
AVFrameHolder() {
m_frame = av_frame_alloc();
#if !QTAV_HAVE_av_buffersink_get_frame
picref = 0;
#endif
}
~AVFrameHolder() {
av_frame_free(&m_frame);
#if !QTAV_HAVE_av_buffersink_get_frame
avfilter_unref_bufferp(&picref);
#endif
}
AVFrame* frame() { return m_frame;}
#if !QTAV_HAVE_av_buffersink_get_frame
AVFilterBufferRef** bufferRef() { return &picref;}
// copy properties and data ptrs(no deep copy).
void copyBufferToFrame() { avfilter_copy_buf_props(m_frame, picref);}
#endif
private:
AVFrame *m_frame;
#if !QTAV_HAVE_av_buffersink_get_frame
AVFilterBufferRef *picref;
#endif
};
typedef QSharedPointer<AVFrameHolder> AVFrameHolderRef;
#endif //QTAV_HAVE(AVFILTER)
class LibAVFilter::Private
{
public:
Private()
: avframe(0)
, status(LibAVFilter::NotConfigured)
{
#if QTAV_HAVE(AVFILTER)
filter_graph = 0;
in_filter_ctx = 0;
out_filter_ctx = 0;
avfilter_register_all();
#endif //QTAV_HAVE(AVFILTER)
}
~Private() {
#if QTAV_HAVE(AVFILTER)
avfilter_graph_free(&filter_graph);
#endif //QTAV_HAVE(AVFILTER)
if (avframe) {
av_frame_free(&avframe);
avframe = 0;
}
}
bool setOptions(const QString& opt) {
if (options == opt)
return false;
options = opt;
status = LibAVFilter::NotConfigured;
return true;
}
bool pushAudioFrame(Frame *frame, bool changed, const QString& args);
bool pushVideoFrame(Frame *frame, bool changed, const QString& args);
bool setup(const QString& args, bool video) {
if (avframe) {
av_frame_free(&avframe);
avframe = 0;
}
status = LibAVFilter::ConfigureFailed;
#if QTAV_HAVE(AVFILTER)
avfilter_graph_free(&filter_graph);
filter_graph = avfilter_graph_alloc();
//QString sws_flags_str;
// pixel_aspect==sar, pixel_aspect is more compatible
QString buffersrc_args = args;
qDebug("buffersrc_args=%s", buffersrc_args.toUtf8().constData());
AVFilter *buffersrc = avfilter_get_by_name(video ? "buffer" : "abuffer");
Q_ASSERT(buffersrc);
AV_ENSURE_OK(avfilter_graph_create_filter(&in_filter_ctx,
buffersrc,
"in", buffersrc_args.toUtf8().constData(), NULL,
filter_graph)
, false);
/* buffer video sink: to terminate the filter chain. */
AVFilter *buffersink = avfilter_get_by_name(video ? "buffersink" : "abuffersink");
Q_ASSERT(buffersink);
AV_ENSURE_OK(avfilter_graph_create_filter(&out_filter_ctx, buffersink, "out",
NULL, NULL, filter_graph)
, false);
/* Endpoints for the filter graph. */
AVFilterInOut *outputs = avfilter_inout_alloc();
AVFilterInOut *inputs = avfilter_inout_alloc();
outputs->name = av_strdup("in");
outputs->filter_ctx = in_filter_ctx;
outputs->pad_idx = 0;
outputs->next = NULL;
inputs->name = av_strdup("out");
inputs->filter_ctx = out_filter_ctx;
inputs->pad_idx = 0;
inputs->next = NULL;
struct delete_helper {
AVFilterInOut **x;
delete_helper(AVFilterInOut **io) : x(io) {}
~delete_helper() {
// libav always free it in avfilter_graph_parse. so we does nothing
#if QTAV_USE_FFMPEG(LIBAVFILTER)
avfilter_inout_free(x);
#endif
}
} scoped_in(&inputs), scoped_out(&outputs);
//avfilter_graph_parse, avfilter_graph_parse2?
AV_ENSURE_OK(avfilter_graph_parse_ptr(filter_graph, options.toUtf8().constData(), &inputs, &outputs, NULL), false);
AV_ENSURE_OK(avfilter_graph_config(filter_graph, NULL), false);
avframe = av_frame_alloc();
status = LibAVFilter::ConfigureOk;
#if DBG_GRAPH
//not available in libav9
const char* g = avfilter_graph_dump(filter_graph, NULL);
if (g)
qDebug().nospace() << "filter graph:\n" << g; // use << to not print special chars in qt5.5
av_freep(&g);
#endif //DBG_GRAPH
return true;
#endif //QTAV_HAVE(AVFILTER)
return false;
}
#if QTAV_HAVE(AVFILTER)
AVFilterGraph *filter_graph;
AVFilterContext *in_filter_ctx;
AVFilterContext *out_filter_ctx;
#endif //QTAV_HAVE(AVFILTER)
AVFrame *avframe;
QString options;
LibAVFilter::Status status;
};
QStringList LibAVFilter::videoFilters()
{
static const QStringList list(LibAVFilter::registeredFilters(AVMEDIA_TYPE_VIDEO));
return list;
}
QStringList LibAVFilter::audioFilters()
{
static const QStringList list(LibAVFilter::registeredFilters(AVMEDIA_TYPE_AUDIO));
return list;
}
QString LibAVFilter::filterDescription(const QString &filterName)
{
QString s;
#if QTAV_HAVE(AVFILTER)
avfilter_register_all();
const AVFilter *f = avfilter_get_by_name(filterName.toUtf8().constData());
if (!f)
return s;
if (f->description)
s.append(QString::fromUtf8(f->description));
#if AV_MODULE_CHECK(LIBAVFILTER, 3, 7, 0, 8, 100)
return s.append(QLatin1String("\n")).append(QObject::tr("Options:"))
.append(Internal::optionsToString((void*)&f->priv_class));
#endif
#endif //QTAV_HAVE(AVFILTER)
Q_UNUSED(filterName);
return s;
}
LibAVFilter::LibAVFilter()
: priv(new Private())
{
}
LibAVFilter::~LibAVFilter()
{
delete priv;
}
void LibAVFilter::setOptions(const QString &options)
{
if (!priv->setOptions(options))
return;
Q_EMIT optionsChanged();
}
QString LibAVFilter::options() const
{
return priv->options;
}
LibAVFilter::Status LibAVFilter::status() const
{
return priv->status;
}
bool LibAVFilter::pushVideoFrame(Frame *frame, bool changed)
{
return priv->pushVideoFrame(frame, changed, sourceArguments());
}
bool LibAVFilter::pushAudioFrame(Frame *frame, bool changed)
{
return priv->pushAudioFrame(frame, changed, sourceArguments());
}
void* LibAVFilter::pullFrameHolder()
{
#if QTAV_HAVE(AVFILTER)
AVFrameHolder *holder = NULL;
holder = new AVFrameHolder();
#if QTAV_HAVE_av_buffersink_get_frame
int ret = av_buffersink_get_frame(priv->out_filter_ctx, holder->frame());
#else
int ret = av_buffersink_read(priv->out_filter_ctx, holder->bufferRef());
#endif //QTAV_HAVE_av_buffersink_get_frame
if (ret < 0) {
qWarning("av_buffersink_get_frame error: %s", av_err2str(ret));
delete holder;
return 0;
}
#if !QTAV_HAVE_av_buffersink_get_frame
holder->copyBufferToFrame();
#endif
return holder;
#endif //QTAV_HAVE(AVFILTER)
return 0;
}
QStringList LibAVFilter::registeredFilters(int type)
{
QStringList filters;
#if QTAV_HAVE(AVFILTER)
avfilter_register_all();
const AVFilter* f = NULL;
AVFilterPad* fp = NULL; // no const in avfilter_pad_get_name() for ffmpeg<=1.2 libav<=9
#if AV_MODULE_CHECK(LIBAVFILTER, 3, 8, 0, 53, 100)
while ((f = avfilter_next(f))) {
#else
AVFilter** ff = NULL;
while ((ff = av_filter_next(ff)) && *ff) {
f = (*ff);
#endif
fp = (AVFilterPad*)f->inputs;
// only check the 1st pad
if (!fp || !avfilter_pad_get_name(fp, 0) || avfilter_pad_get_type(fp, 0) != (AVMediaType)type)
continue;
fp = (AVFilterPad*)f->outputs;
// only check the 1st pad
if (!fp || !avfilter_pad_get_name(fp, 0) || avfilter_pad_get_type(fp, 0) != (AVMediaType)type)
continue;
filters.append(QLatin1String(f->name));
}
#endif //QTAV_HAVE(AVFILTER)
return filters;
}
class LibAVFilterVideoPrivate : public VideoFilterPrivate
{
public:
LibAVFilterVideoPrivate()
: VideoFilterPrivate()
, pixfmt(QTAV_PIX_FMT_C(NONE))
, width(0)
, height(0)
{}
AVPixelFormat pixfmt;
int width, height;
};
LibAVFilterVideo::LibAVFilterVideo(QObject *parent)
: VideoFilter(*new LibAVFilterVideoPrivate(), parent)
, LibAVFilter()
{
}
QStringList LibAVFilterVideo::filters() const
{
return LibAVFilter::videoFilters();
}
void LibAVFilterVideo::process(Statistics *statistics, VideoFrame *frame)
{
Q_UNUSED(statistics);
#if QTAV_HAVE(AVFILTER)
if (status() == ConfigureFailed)
return;
DPTR_D(LibAVFilterVideo);
//Status old = status();
bool changed = false;
if (d.width != frame->width() || d.height != frame->height() || d.pixfmt != frame->pixelFormatFFmpeg()) {
changed = true;
d.width = frame->width();
d.height = frame->height();
d.pixfmt = (AVPixelFormat)frame->pixelFormatFFmpeg();
}
bool ok = pushVideoFrame(frame, changed);
//if (old != status())
// emit statusChanged();
if (!ok)
return;
AVFrameHolderRef ref((AVFrameHolder*)pullFrameHolder());
if (!ref)
return;
const AVFrame *f = ref->frame();
VideoFrame vf(f->width, f->height, VideoFormat(f->format));
vf.setBits((quint8**)f->data);
vf.setBytesPerLine((int*)f->linesize);
vf.setMetaData(QStringLiteral("avframe_hoder_ref"), QVariant::fromValue(ref));
vf.setTimestamp(ref->frame()->pts/1000000.0); //pkt_pts?
//vf.setMetaData(frame->availableMetaData());
*frame = vf;
#else
Q_UNUSED(frame);
#endif //QTAV_HAVE(AVFILTER)
}
QString LibAVFilterVideo::sourceArguments() const
{
DPTR_D(const LibAVFilterVideo);
#if QTAV_USE_LIBAV(LIBAVFILTER)
return QStringLiteral("%1:%2:%3:%4:%5:%6:%7")
#else
return QStringLiteral("video_size=%1x%2:pix_fmt=%3:time_base=%4/%5:pixel_aspect=%6/%7")
#endif
.arg(d.width).arg(d.height).arg(d.pixfmt)
.arg(1).arg(AV_TIME_BASE) //time base 1/1?
.arg(1).arg(1) //sar
;
}
class LibAVFilterAudioPrivate : public AudioFilterPrivate
{
public:
LibAVFilterAudioPrivate()
: AudioFilterPrivate()
, sample_rate(0)
, sample_fmt(AV_SAMPLE_FMT_NONE)
, channel_layout(0)
{}
int sample_rate;
AVSampleFormat sample_fmt;
qint64 channel_layout;
};
LibAVFilterAudio::LibAVFilterAudio(QObject *parent)
: AudioFilter(*new LibAVFilterAudioPrivate(), parent)
, LibAVFilter()
{}
QStringList LibAVFilterAudio::filters() const
{
return LibAVFilter::audioFilters();
}
QString LibAVFilterAudio::sourceArguments() const
{
DPTR_D(const LibAVFilterAudio);
return QStringLiteral("time_base=%1/%2:sample_rate=%3:sample_fmt=%4:channel_layout=0x%5")
.arg(1)
.arg(AV_TIME_BASE)
.arg(d.sample_rate)
//ffmpeg new: AV_OPT_TYPE_SAMPLE_FMT
//libav, ffmpeg old: AV_OPT_TYPE_STRING
.arg(QLatin1String(av_get_sample_fmt_name(d.sample_fmt)))
.arg(d.channel_layout, 0, 16) //AV_OPT_TYPE_STRING
;
}
void LibAVFilterAudio::process(Statistics *statistics, AudioFrame *frame)
{
Q_UNUSED(statistics);
#if QTAV_HAVE(AVFILTER)
if (status() == ConfigureFailed)
return;
DPTR_D(LibAVFilterAudio);
//Status old = status();
bool changed = false;
const AudioFormat afmt(frame->format());
if (d.sample_rate != afmt.sampleRate() || d.sample_fmt != afmt.sampleFormatFFmpeg() || d.channel_layout != afmt.channelLayoutFFmpeg()) {
changed = true;
d.sample_rate = afmt.sampleRate();
d.sample_fmt = (AVSampleFormat)afmt.sampleFormatFFmpeg();
d.channel_layout = afmt.channelLayoutFFmpeg();
}
bool ok = pushAudioFrame(frame, changed);
//if (old != status())
// emit statusChanged();
if (!ok)
return;
AVFrameHolderRef ref((AVFrameHolder*)pullFrameHolder());
if (!ref)
return;
const AVFrame *f = ref->frame();
AudioFormat fmt;
fmt.setSampleFormatFFmpeg(f->format);
fmt.setChannelLayoutFFmpeg(f->channel_layout);
fmt.setSampleRate(f->sample_rate);
if (!fmt.isValid()) {// need more data to decode to get a frame
return;
}
AudioFrame af(fmt);
//af.setBits((quint8**)f->extended_data);
//af.setBytesPerLine((int*)f->linesize);
af.setBits(f->extended_data); // TODO: ref
af.setBytesPerLine(f->linesize[0], 0); // for correct alignment
af.setSamplesPerChannel(f->nb_samples);
af.setMetaData(QStringLiteral("avframe_hoder_ref"), QVariant::fromValue(ref));
af.setTimestamp(ref->frame()->pts/1000000.0); //pkt_pts?
//af.setMetaData(frame->availableMetaData());
*frame = af;
#else
Q_UNUSED(frame);
#endif //QTAV_HAVE(AVFILTER)
}
bool LibAVFilter::Private::pushVideoFrame(Frame *frame, bool changed, const QString &args)
{
#if QTAV_HAVE(AVFILTER)
VideoFrame *vf = static_cast<VideoFrame*>(frame);
if (status == LibAVFilter::NotConfigured || !avframe || changed) {
if (!setup(args, true)) {
qWarning("setup video filter graph error");
//enabled = false; // skip this filter and avoid crash
return false;
}
}
if (!vf->constBits(0)) {
*vf = vf->to(vf->format());
}
avframe->pts = frame->timestamp() * 1000000.0; // time_base is 1/1000000
avframe->width = vf->width();
avframe->height = vf->height();
avframe->format = (AVPixelFormat)vf->pixelFormatFFmpeg();
for (int i = 0; i < vf->planeCount(); ++i) {
avframe->data[i] = (uint8_t*)vf->constBits(i);
avframe->linesize[i] = vf->bytesPerLine(i);
}
//TODO: side data for vf_codecview etc
//int ret = av_buffersrc_add_frame_flags(in_filter_ctx, avframe, AV_BUFFERSRC_FLAG_KEEP_REF);
/*
* av_buffersrc_write_frame equals to av_buffersrc_add_frame_flags with AV_BUFFERSRC_FLAG_KEEP_REF.
* av_buffersrc_write_frame is more compatible, while av_buffersrc_add_frame_flags only exists in ffmpeg >=2.0
* add a ref if frame is ref counted
* TODO: libav < 10.0 will copy the frame, prefer to use av_buffersrc_buffer
*/
AV_ENSURE_OK(av_buffersrc_write_frame(in_filter_ctx, avframe), false);
return true;
#endif //QTAV_HAVE(AVFILTER)
Q_UNUSED(frame);
return false;
}
bool LibAVFilter::Private::pushAudioFrame(Frame *frame, bool changed, const QString &args)
{
#if QTAV_HAVE(AVFILTER)
if (status == LibAVFilter::NotConfigured || !avframe || changed) {
if (!setup(args, false)) {
qWarning("setup audio filter graph error");
//enabled = false; // skip this filter and avoid crash
return false;
}
}
AudioFrame *af = static_cast<AudioFrame*>(frame);
const AudioFormat afmt(af->format());
avframe->pts = frame->timestamp() * 1000000.0; // time_base is 1/1000000
avframe->sample_rate = afmt.sampleRate();
avframe->channel_layout = afmt.channelLayoutFFmpeg();
#if QTAV_USE_FFMPEG(LIBAVCODEC) || QTAV_USE_FFMPEG(LIBAVUTIL) //AVFrame was in avcodec
avframe->channels = afmt.channels(); //MUST set because av_buffersrc_write_frame will compare channels and layout
#endif
avframe->format = (AVSampleFormat)afmt.sampleFormatFFmpeg();
avframe->nb_samples = af->samplesPerChannel();
for (int i = 0; i < af->planeCount(); ++i) {
//avframe->data[i] = (uint8_t*)af->constBits(i);
avframe->extended_data[i] = (uint8_t*)af->constBits(i);
avframe->linesize[i] = af->bytesPerLine(i);
}
AV_ENSURE_OK(av_buffersrc_write_frame(in_filter_ctx, avframe), false);
return true;
#endif //QTAV_HAVE(AVFILTER)
Q_UNUSED(frame);
return false;
}
} //namespace QtAV
#if QTAV_HAVE(AVFILTER)
Q_DECLARE_METATYPE(QtAV::AVFrameHolderRef)
#endif
| Java |
r"""
Create MapServer class diagrams
Requires https://graphviz.gitlab.io/_pages/Download/Download_windows.html
https://stackoverflow.com/questions/1494492/graphviz-how-to-go-from-dot-to-a-graph
For DOT languge see http://www.graphviz.org/doc/info/attrs.html
cd C:\Program Files (x86)\Graphviz2.38\bin
dot -Tpng D:\GitHub\mappyfile\mapfile_classes.dot -o outfile.png
outfile.png
For Entity Relationship diagrams:
https://graphviz.readthedocs.io/en/stable/examples.html#er-py
"""
import os
import pydot
# import pprint
FONT = "Lucida Sans"
def graphviz_setup(gviz_path):
os.environ['PATH'] = gviz_path + ";" + os.environ['PATH']
def add_child(graph, child_id, child_label, parent_id, colour):
"""
http://www.graphviz.org/doc/info/shapes.html#polygon
"""
node = pydot.Node(child_id, style="filled", fillcolor=colour, label=child_label, shape="polygon", fontname=FONT)
graph.add_node(node)
graph.add_edge(pydot.Edge(parent_id, node))
def add_children(graph, parent_id, d, level=0):
blue = "#6b6bd1"
white = "#fdfefd"
green = "#33a333"
colours = [blue, white, green] * 3
for class_, children in d.items():
colour = colours[level]
child_label = class_
child_id = parent_id + "_" + class_
add_child(graph, child_id, child_label, parent_id, colour)
add_children(graph, child_id, children, level+1)
def save_file(graph, fn):
filename = "%s.png" % fn
graph.write_png(filename)
graph.write("%s.dot" % fn)
os.startfile(filename)
def main(gviz_path, layer_only=False):
graphviz_setup(gviz_path)
graph = pydot.Dot(graph_type='digraph', rankdir="TB")
layer_children = {
'CLASS': {
'LABEL': {'STYLE': {}},
'CONNECTIONOPTIONS': {},
'LEADER': {'STYLE': {}},
'STYLE': {},
'VALIDATION': {}
},
'CLUSTER': {},
'COMPOSITE': {},
'FEATURE': {'POINTS': {}},
'GRID': {},
'JOIN': {},
'METADATA': {},
'PROJECTION': {},
'SCALETOKEN': {'VALUES': {}},
'VALIDATION': {}
}
# pprint.pprint(layer_children)
classes = {
"MAP": {
"LAYER": layer_children,
'LEGEND': {'LABEL': {}},
'PROJECTION': {},
'QUERYMAP': {},
'REFERENCE': {},
'SCALEBAR': {'LABEL': {}},
'SYMBOL': {},
'WEB': {'METADATA': {}, 'VALIDATION': {}}
}
}
if layer_only:
root = "LAYER"
classes = classes["MAP"]
fn = "layer_classes"
else:
fn = "map_classes"
root, = classes.keys()
node = pydot.Node(root, style="filled", fillcolor="#33a333", label=root, fontname=FONT, shape="polygon")
graph.add_node(node)
add_children(graph, root, classes[root])
save_file(graph, fn)
if __name__ == "__main__":
gviz_path = r"C:\Program Files (x86)\Graphviz2.38\bin"
main(gviz_path, True)
main(gviz_path, False)
print("Done!")
| Java |
import { get_definition } from './../base';
export const push_link = (
oid, linkurl, linkname, onmenu='true', instance_name,
when, additional_args, description
) => get_definition({
oid,
linkurl,
linkname,
onmenu,
instance_name
},
{
label: 'VersionOne - Push Link',
method: 'push_link',
module: 'main',
name: 'v1plugin'
},
when, additional_args, description
); | Java |
#region License
/* The MIT License
*
* Copyright (c) 2011 Red Badger Consulting
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
namespace RedBadger.Xpf.Graphics
{
/// <summary>
/// Represents a Texture.
/// </summary>
public interface ITexture
{
/// <summary>
/// Gets the height of this texture in pixels.
/// </summary>
int Height { get; }
/// <summary>
/// Gets the width of this texture in pixels.
/// </summary>
int Width { get; }
}
}
| Java |
<?php
namespace fufudao\base;
use yii\behaviors\TimestampBehavior;
//use yii\behaviors\AttributeBehavior;
use yii\db\ActiveRecord as ar;
use yii\db\Expression;
class ActiveRecord extends ar
{
public function behaviors()
{
return [
'timestamp' => [
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created','modified'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['modified']
],
'value' => new Expression(date('\'Y-m-d H:i:s\'')),
],
];
}
public function newID(){
$schema = $this->getTableSchema();
$primaryKey = $schema->primaryKey[0];
$col = $schema->columns[$primaryKey];
$ret = $this->getAttribute($primaryKey);
if( empty($ret) ){
if( $col->phpType === \yii\db\Schema::TYPE_STRING ){
switch ($col->size){
case 13:
$ret = uniqid();
break;
case 32:
$ret = md5(uniqid(mt_rand(), true));
break;
}
}
}
return $ret;
}
} | Java |
SET DEFINE OFF;
CREATE SEQUENCE AFW_07_AUDIT_STRUC_APLIC_SEQ
START WITH 1
MAXVALUE 9999999999999999999999999999
MINVALUE 1
NOCYCLE
CACHE 20
NOORDER
/
| Java |
#
# Cookbook Name:: dokku
# Spec:: plugins
#
# Copyright (c) 2015 Nick Charlton, MIT licensed.
require "spec_helper"
describe "dokku::plugins" do
context "when all attributes are default" do
let(:chef_run) do
runner = ChefSpec::ServerRunner.new
runner.converge(described_recipe)
end
before do
stub_command("which nginx").and_return("/usr/bin/nginx")
end
it "does nothing" do
expect { chef_run }.to_not raise_error
end
end
context "when plugins exist in attributes and no actions are listed" do
let(:chef_run) do
runner = ChefSpec::ServerRunner.new do |node|
node.override["dokku"]["plugins"] = [{
name: "redis",
url: "https://github.com/dokku/dokku-redis.git"
}]
end
runner.converge(described_recipe)
end
before do
stub_command("which nginx").and_return("/usr/bin/nginx")
end
it "installs plugins" do
expect(chef_run).to install_dokku_plugin(
"redis").with(url: "https://github.com/dokku/dokku-redis.git")
end
end
context "when plugins exist in attributes" do
let(:chef_run) do
runner = ChefSpec::ServerRunner.new do |node|
node.override["dokku"]["plugins"] = [
{ name: "redis", url: "https://github.com/dokku/dokku-redis.git",
action: "install" },
{ name: "mongo", url: "https://github.com/dokku/dokku-mongo.git",
action: "uninstall" },
]
end
runner.converge(described_recipe)
end
before do
stub_command("which nginx").and_return("/usr/bin/nginx")
end
it "manages plugins" do
expect(chef_run).to install_dokku_plugin(
"redis").with(url: "https://github.com/dokku/dokku-redis.git")
expect(chef_run).to uninstall_dokku_plugin(
"mongo").with(url: "https://github.com/dokku/dokku-mongo.git")
end
end
context "when plugins to be installed provide a commit to fetch" do
let(:chef_run) do
runner = ChefSpec::ServerRunner.new do |node|
node.override["dokku"]["plugins"] = [
{ name: "redis", url: "https://github.com/dokku/dokku-redis.git",
action: "install", committish: "0.4.4" },
]
end
runner.converge(described_recipe)
end
before do
stub_command("which nginx").and_return("/usr/bin/nginx")
end
it "installs the plugins specifying that committish" do
expect(chef_run).to install_dokku_plugin("redis").with(
url: "https://github.com/dokku/dokku-redis.git", committish: "0.4.4",
)
end
end
end
| Java |
'use strict';
// Load the application's configuration
const config = require('../server/config');
const url = config.express_host + '/api';
// Required modules
const async = require('async');
const colors = require('colors');
const request = require('request');
// Counter for the Measurements
let counter = 1;
// Read the arguments from the command line or set them to the default values
const interval = process.argv[2] || 2000;
const thingName = process.argv[3] || 'Demo';
const thingLocLat = process.argv[4] || 51.964113;
const thingLocLng = process.argv[5] || 7.624862;
// REST API authentication token
let token;
console.log('\n////////////////////////////////////////////////////////////\n');
console.log(' STARTING DEMONSTRATION...'.cyan);
console.log('\n////////////////////////////////////////////////////////////\n');
async.waterfall([
// Create a new User
function(callback) {
console.log(' Creating a new', 'User...\n'.cyan);
const userJson = {
email: 'demo#' + Math.random().toFixed() + '@example.com',
password: 'demoPass'
};
// Post the new User
request.post({
headers: {'content-type': 'application/json'},
url: url + '/users',
json: userJson
}, function(error, response, body) {
if (!error) {
console.log(' New User', 'created.'.green);
token = body.token;
} else {
console.log(' New User creation', 'failed'.red);
}
console.log('\n------------------------------------------------------------\n');
callback(error, body._id);
});
},
// Create a new Thing
function(userId, callback) {
console.log(' Creating a new', 'Thing...\n'.cyan);
const thingJson = {
name: thingName,
loc: {
coordinates: [ thingLocLat, thingLocLng ]
},
userId: userId,
waterbodyId: '5752d2d7e5d703480187e0d9',
token: token
};
// Post the new Thing
request.post({
headers: {'content-type': 'application/json'},
url: url + '/things',
json: thingJson
}, function(error, response, body) {
if (!error) {
console.log(' New Thing', 'created.'.green);
} else {
console.log(' New Thing creation', 'failed'.red);
}
console.log('\n------------------------------------------------------------\n');
callback(error, body._id);
});
},
// Create a new Feature
function(thingId, callback) {
console.log(' Creating a new', 'Feature...\n'.cyan);
const featureJson = {
name: 'demoFeature',
unit: 'foo',
token: token
};
// Post the new Feature
request.post({
headers: {'content-type': 'application/json'},
url: url + '/features',
json: featureJson
}, function(error, response, body) {
if (!error) {
console.log(' New Feature', 'created'.green);
} else {
console.log(' New Feature creation', 'failed'.red);
}
console.log('\n------------------------------------------------------------\n');
callback(error, thingId, body._id);
});
},
// Create a new Sensor
function(thingId, featureId, callback) {
console.log(' Creating a new', 'Sensor...\n'.cyan);
const sensorJson = {
name: 'demoSensor',
interval: interval,
refLevel: 2,
warnLevel: 6,
riskLevel: 8,
thingId: thingId,
featureId: featureId,
token: token
};
// Post the new Sensor
request.post({
headers: {'content-type': 'application/json'},
url: url + '/sensors',
json: sensorJson
}, function(error, response, body) {
if (!error) {
console.log(' New Sensor', 'created.'.green);
} else {
console.log(' New Sensor creation', 'failed'.red);
}
console.log('\n------------------------------------------------------------\n');
callback(error, body._id);
});
},
// Create new Measurements in an interval
function(sensorId, callback) {
console.log(' Finished demo setup. Measuring now...'.cyan);
console.log('\n------------------------------------------------------------\n');
let value = 4;
setInterval(function() {
console.log(' Creating a new', 'Measurement...\n'.cyan);
// Calculate the Measurement's value as a random number with respect to its previous value
if (value < 1 || Math.random() > 0.5) {
value += Math.random();
} else {
value -= Math.random();
}
value = parseFloat(value.toFixed(2));
let measurementJson = {
date: Date.now(),
value: value,
sensorId: sensorId,
token: token
};
// Post the new Measurement
request.post({
headers: {'content-type': 'application/json'},
url: url + '/measurements',
json: measurementJson
}, function(error, response, body) {
if (!error) {
console.log(' New Measurement', ('#' + counter).cyan, 'created.'.green, '\nValue:', body.value.cyan);
counter++;
} else {
console.log(' New Measurement creation', 'failed'.red);
callback(error);
}
console.log('\n------------------------------------------------------------\n');
});
}, interval);
}
], function(err, result) {
if (err) {
console.log(err);
}
}); | Java |
import React from 'react'
import {HOC, Link} from 'cerebral-view-react'
import PageProgress from '../PageProgress'
// View
class AutoReload extends React.Component {
constructor (props) {
super(props)
this.state = {
secondsElapsed: 0
}
this.onInterval = this.onInterval.bind(this)
}
componentWillMount () {
this.intervals = []
}
componentWillUnmount () {
this.intervals.forEach(clearInterval)
}
componentDidMount () {
this.setInterval(this.onInterval, 1000)
}
setInterval () {
this.intervals.push(setInterval.apply(null, arguments))
}
onInterval () {
let secondsElapsed = 0
if (this.props.isEnabled) {
secondsElapsed = this.state.secondsElapsed + 1
if (secondsElapsed >= this.props.triggerAfterSeconds) {
this.trigger()
secondsElapsed = 0
}
}
if (secondsElapsed !== this.state.secondsElapsed) {
this.setState({
secondsElapsed: secondsElapsed
})
}
}
trigger () {
this.props.triggers.map((trigger) => trigger())
}
triggerNow (e) {
if (e) {
e.preventDefault()
}
if (this.props.isEnabled) {
if (this.state.secondsElapsed > 0) {
this.trigger()
this.setState({
secondsElapsed: 0
})
}
}
}
render () {
const signals = this.props.signals
const progress = {
isEnabled: this.props.isEnabled,
elapsed: this.state.secondsElapsed,
total: this.props.triggerAfterSeconds
}
return (
<div>
<PageProgress {...progress} />
<hr />
<pre>
BastardAutoloaderFromHell<br />
=========================<br />
[{'='.repeat(this.state.secondsElapsed)}{'.'.repeat(this.props.triggerAfterSeconds - this.state.secondsElapsed - 1)}]<br />
isEnabled: {this.props.isEnabled ? 'yepp' : 'nope'}<br />
triggerAfterSeconds: {this.props.triggerAfterSeconds}<br />
numberOfTriggers: {this.props.triggers.length}<br />
secondsElapsed: {this.state.secondsElapsed}<br />
secondsBeforeReload: {this.props.triggerAfterSeconds - this.state.secondsElapsed}<br />
-------------------------<br />
<Link signal={signals.app.reload.reloadingDisabled}>clickmeto_<b>disable</b>_reloading</Link><br />
--<br />
<Link signal={signals.app.reload.reloadingEnabled}>clickmeto_<b>enable</b>_reloading</Link><br />
--<br />
<Link signal={signals.app.reload.reloadingToggled}>clickmeto_<b>toggle</b>_reloading</Link><br />
-------------------------<br />
<a onClick={(e) => this.triggerNow(e)}>clickmeto_<b>trigger_NOW</b></a><br />
-------------------------<br />
<Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 10}}>clickmeto_reload_@<b>10_seconds</b></Link><br />
--<br />
<Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 20}}>clickmeto_reload_@<b>20_seconds</b></Link><br />
--<br />
<Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 30}}>clickmeto_reload_@<b>30_seconds</b></Link><br />
--<br />
<Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 60}}>clickmeto_reload_@<b>60_seconds</b></Link><br />
====<br />
<i>designed by pbit</i>
</pre>
</div>
)
}
}
// Model
AutoReload.propTypes = {
isEnabled: React.PropTypes.bool,
triggerAfterSeconds: React.PropTypes.number,
signals: React.PropTypes.object,
triggers: React.PropTypes.array
}
AutoReload.defaultProps = {
triggers: []
}
// Binding
const StatefullAutoReload = HOC(AutoReload, {
isEnabled: ['app', 'reload', 'isEnabled'],
triggerAfterSeconds: ['app', 'reload', 'triggerAfterSeconds']
})
// API
export default StatefullAutoReload
| Java |
#!/bin/bash
#SBATCH --partition=mono
#SBATCH --ntasks=1
#SBATCH --time=4-0:00
#SBATCH --mem-per-cpu=8000
#SBATCH -J Deep-RBM_DBM_4_inc_bin_PARAL_base
#SBATCH -e Deep-RBM_DBM_4_inc_bin_PARAL_base.err.txt
#SBATCH -o Deep-RBM_DBM_4_inc_bin_PARAL_base.out.txt
source /etc/profile.modules
module load gcc
module load matlab
cd ~/deepLearn && srun ./deepFunction 4 'RBM' 'DBM' '128 1000 1500 10' '0 1 1 1' '4_inc_bin' 'PARAL_base' "'iteration.n_epochs', 'learning.lrate', 'learning.cd_k', 'learning.persistent_cd', 'parallel_tempering.use'" '200 1e-3 1 0 1' "'iteration.n_epochs', 'learning.persistent_cd'" '200 1' | Java |
<!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">
<meta name="description" content="">
<meta name="author" content="">
<title>Task Management System</title>
<!-- Bootstrap Core CSS -->
<link href="<?=base_url()?>assets/css/bootstrap.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="<?=base_url()?>assets/css/metisMenu.min.css" rel="stylesheet">
<!-- DataTables CSS -->
<link href="<?=base_url()?>assets/css/dataTables.bootstrap.css" rel="stylesheet">
<link href="<?=base_url()?>assets/css/bootstrap-editable.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="<?=base_url()?>assets/css/main.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="<?=base_url()?>assets/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- Custom tab icons -->
<link rel="shortcut icon" href="<?=base_url()?>assets/images/favicon.ico" type="image/x-icon">
<link href="<?=base_url()?>assets/js/jquery-ui-1.11.4.custom/jquery-ui.css" rel="stylesheet" type="text/css" />
<link href="<?=base_url()?>assets/js/jquery-ui-1.11.4.custom/jquery-ui-custom-datepicker.css" rel="stylesheet" type="text/css" />
<input type="hidden" id="base-url" value="<?=base_url()?>"/>
<input type="hidden" id="current-page" value=""/>
<input type="hidden" id="current-status-filter" value=""/>
<input type="hidden" id="current-page-child" value=""/>
<input type="hidden" id="current-parentID" value=""/>
<input type="hidden" id="current-status-filter-child" value=""/>
<input type="hidden" id="current-child-parentID" value=""/>
<style>
.inline-block{display:inline-block;}
</style>
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-static-top text-center" role="navigation" style="margin-bottom: 0">
<div class="navbar-header">
<a class="navbar-brand" href="<?=base_url();?>">
<div class="inline"> Welcome to Streamfream Task Management System </div>
</a>
</div>
</nav>
<!-- /.navbar-header -->
<!-- /.navbar-top-links --> | Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<title>Test Users Roles Demote</title>
</head>
<body>
<?php
require_once('test-util.php');
require_once(dirname(__FILE__) . '/../lib/ca-main.php');
echo '<div class="apitest">';
echo '<h1>users_roles_demote</h1>';
$ca = new CityApi();
$ca->debug = true;
$ca->json = true;
$userid = 238801;
$roleid = 986632;
$args = array('title' => 'Participant');
$results = $ca->users_roles_demote($userid, $roleid, $args);
echo '<h2>Formatted JSON results: </h2>';
echo '<pre>';
echo format_json($results);
echo '</pre>';
echo '</div>';
?>
</body>
</html>
| Java |
# coffeehaus
A coffeescript shop for JVM locals.
## /!\ Extraction in progress
This library is the extraction of the coffeescript compiler used
in [coffeescripted-sbt](https://github.com/softprops/coffeescripted-sbt) for use as a standalone library
## install
(todo)
## usage
This library provides scala interfaces for compiling [vanilla][vanilla] and [iced][iced] CoffeeScript.
It uses the versions `1.6.3` and `1.6.3-b` respectively.
To compile vanilla coffeescript
```scala
coffeehaus.Compile.vanilla()("alert 'vanilla'")
```
or simply
```scala
coffeehaus.Compile("alert 'vanilla'")
```
To compile iced coffeescript
```scala
coffeehaus.Compile.iced()("alert 'iced'")
```
These will return a `Either[coffeehaus.CompilerError, String]` with the compiled source.
Don't have time to wait while your coffee's being brewed? Try moving to the side of the counter.
```scala
import coffeehaus.Compile
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
Future(Compile("alert 'vanilla'")).map { coffee =>
Thread.sleep(1000)
coffee.fold(println, println)
}
println("checkin' my tweets")
```
### Be Your Own Barista
This library will always make a best attempt at providing interfaces to the latest coffeescript compilers.
That doesn't mean you can't experiment with your own brews ( other versions of coffeescript ) by extending `coffeehaus.Compile` providing
a resource path to the source of the script. As an example the built-in vanilla coffeescript compiler is defined as follows
```scala
Vanilla extends Compile("vanilla/coffee-script.js")
```
enjoy.
Doug Tangren (softprops) 2013
[vanilla]: http://coffeescript.org/
[iced]: http://maxtaco.github.io/coffee-script/
| Java |
# Author: John Elkins <john.elkins@yahoo.com>
# License: MIT <LICENSE>
from common import *
if len(sys.argv) < 2:
log('ERROR output directory is required')
time.sleep(3)
exit()
# setup the output directory, create it if needed
output_dir = sys.argv[1]
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# log in and load personal library
api = open_api()
library = load_personal_library()
def playlist_handler(playlist_name, playlist_description, playlist_tracks):
# skip empty and no-name playlists
if not playlist_name: return
if len(playlist_tracks) == 0: return
# setup output files
playlist_name = playlist_name.replace('/', '')
open_log(os.path.join(output_dir,playlist_name+u'.log'))
outfile = codecs.open(os.path.join(output_dir,playlist_name+u'.csv'),
encoding='utf-8',mode='w')
# keep track of stats
stats = create_stats()
export_skipped = 0
# keep track of songids incase we need to skip duplicates
song_ids = []
log('')
log('============================================================')
log(u'Exporting '+ unicode(len(playlist_tracks)) +u' tracks from '
+playlist_name)
log('============================================================')
# add the playlist description as a "comment"
if playlist_description:
outfile.write(tsep)
outfile.write(playlist_description)
outfile.write(os.linesep)
for tnum, pl_track in enumerate(playlist_tracks):
track = pl_track.get('track')
# we need to look up these track in the library
if not track:
library_track = [
item for item in library if item.get('id')
in pl_track.get('trackId')]
if len(library_track) == 0:
log(u'!! '+str(tnum+1)+repr(pl_track))
export_skipped += 1
continue
track = library_track[0]
result_details = create_result_details(track)
if not allow_duplicates and result_details['songid'] in song_ids:
log('{D} '+str(tnum+1)+'. '+create_details_string(result_details,True))
export_skipped += 1
continue
# update the stats
update_stats(track,stats)
# export the track
song_ids.append(result_details['songid'])
outfile.write(create_details_string(result_details))
outfile.write(os.linesep)
# calculate the stats
stats_results = calculate_stats_results(stats,len(playlist_tracks))
# output the stats to the log
log('')
log_stats(stats_results)
log(u'export skipped: '+unicode(export_skipped))
# close the files
close_log()
outfile.close()
# the personal library is used so we can lookup tracks that fail to return
# info from the ...playlist_contents() call
playlist_contents = api.get_all_user_playlist_contents()
for playlist in playlist_contents:
playlist_name = playlist.get('name')
playlist_description = playlist.get('description')
playlist_tracks = playlist.get('tracks')
playlist_handler(playlist_name, playlist_description, playlist_tracks)
if export_thumbs_up:
# get thumbs up playlist
thumbs_up_tracks = []
for track in library:
if track.get('rating') is not None and int(track.get('rating')) > 1:
thumbs_up_tracks.append(track)
# modify format of each dictionary to match the data type
# of the other playlists
thumbs_up_tracks_formatted = []
for t in thumbs_up_tracks:
thumbs_up_tracks_formatted.append({'track': t})
playlist_handler('Thumbs up', 'Thumbs up tracks', thumbs_up_tracks_formatted)
if export_all:
all_tracks_formatted = []
for t in library:
all_tracks_formatted.append({'track': t})
playlist_handler('All', 'All tracks', all_tracks_formatted)
close_api()
| Java |
require "./test/test_helper"
require "pinker/rule"
include Pinker
regarding "remember helps gather up things that get returned if the rule is valid." do
class Request
def initialize(path_info, query_string=nil)
@path_info = path_info
@query_string = query_string
end
end
test "stick things in memory, return them with a successful result" do
rule =
RuleBuilder.new(Request) {
declare("Path must have at least three sections"){@path_info.split("/").length>=3}
remember { |memory|
memory[:resource_type] = @path_info.split("/")[2]
}
}.build
assert{ rule.apply_to(Request.new("/v1/widgets/foo")).memory ==
{:resource_type => "widgets"}
}
end
test "disregard the results of remembers" do
rule =
RuleBuilder.new(Request) {
remember { |memory, context|
memory[:x] = "y"
nil #caused explosions at one time
}
}.build
assert{ rule.apply_to(Request.new("/v1/widgets/foo")).memory ==
{:x => "y"}
}
end
test "cache useful things across calls using context" do
the_rule =
RuleBuilder.new(Request) {
declare("Path must have at least three sections") { |call, context|
(context[:path_parts]=@path_info.split("/")).length>=3
}
with_rule(:text_is_widgets){|rule, context|rule.apply_to(context[:path_parts][2])}
rule(:text_is_widgets) {
declare("Must be widgets"){self=="widgets"}
}
remember { |memory, context|
memory[:resource_type] = context[:path_parts][2]
}
}.build
assert{ the_rule.apply_to(Request.new("/v1/widgets/foo")).satisfied? }
assert{ the_rule.apply_to(Request.new("/v1/widgets/foo")).memory ==
{:resource_type => "widgets"}
}
end
test "if a remember fails and nothing else has, bubble up the error" do
rule =
RuleBuilder.new(Request) {
declare { |call, context|
(context[:path_parts]=@path_info.split("/")).length>=3 || call.fail("Path must have at least three sections")
}
remember { |memory, context|
raise StandardError.new("blam!")
}
}.build
assert{ rescuing{ rule.apply_to(Request.new("/v1/widgets/foo")) }.message ==
"blam!"
}
end
test "if something else has already failed, swallow the exception. this is a 'best effort'/completeness failure strategy." do
rule =
RuleBuilder.new(Request) {
declare { |call, context|
@path_info.split("/").length>=99 || call.fail("Path must have at least 99 sections")
}
remember { |memory, context|
raise StandardError.new("blam!")
}
}.build
assert{ rescuing{ rule.apply_to(Request.new("/v1/widgets/foo")) }.nil? }
assert{ rule.apply_to(Request.new("/v1/widgets/foo")).problems.first.message == "Path must have at least 99 sections" }
end
test "merge together memory hashes from rules" do
grammar =
RuleBuilder.new(:foo) {
rule(:a) {
remember{|memory|memory[:a] = 1}
with_rule(:b){|rule|rule.apply_to("y")}
}
rule(:b) {
remember{|memory|memory[:b] = 2}
}
}.build
assert{ grammar.apply_to("x").memory == {:a => 1, :b => 2} }
end
end
| Java |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// Why base-58 instead of standard base-64 encoding?
// - Don't want 0OIl characters that look the same in some fonts and
// could be used to create visually identical looking account numbers.
// - A string with non-alphanumeric characters is not as easily accepted as an account number.
// - E-mail usually won't line-break if there's no punctuation to break at.
// - Double-clicking selects the whole number as one word if it's all alphanumeric.
//
#ifndef BITCOIN_BASE58_H
#define BITCOIN_BASE58_H
#include <string>
#include <vector>
#include "bignum.h"
#include "key.h"
#include "script.h"
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
// Encode a byte sequence as a base58-encoded string
inline std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{
CAutoBN_CTX pctx;
CBigNum bn58 = 58;
CBigNum bn0 = 0;
// Convert big endian data to little endian
// Extra zero at the end make sure bignum will interpret as a positive number
std::vector<unsigned char> vchTmp(pend-pbegin+1, 0);
reverse_copy(pbegin, pend, vchTmp.begin());
// Convert little endian data to bignum
CBigNum bn;
bn.setvch(vchTmp);
// Convert bignum to std::string
std::string str;
// Expected size increase from base58 conversion is approximately 137%
// use 138% to be safe
str.reserve((pend - pbegin) * 138 / 100 + 1);
CBigNum dv;
CBigNum rem;
while (bn > bn0)
{
if (!BN_div(&dv, &rem, &bn, &bn58, pctx))
throw bignum_error("EncodeBase58 : BN_div failed");
bn = dv;
unsigned int c = rem.getulong();
str += pszBase58[c];
}
// Leading zeroes encoded as base58 zeros
for (const unsigned char* p = pbegin; p < pend && *p == 0; p++)
str += pszBase58[0];
// Convert little endian std::string to big endian
reverse(str.begin(), str.end());
return str;
}
// Encode a byte vector as a base58-encoded string
inline std::string EncodeBase58(const std::vector<unsigned char>& vch)
{
return EncodeBase58(&vch[0], &vch[0] + vch.size());
}
// Decode a base58-encoded string psz into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet)
{
CAutoBN_CTX pctx;
vchRet.clear();
CBigNum bn58 = 58;
CBigNum bn = 0;
CBigNum bnChar;
while (isspace(*psz))
psz++;
// Convert big endian string to bignum
for (const char* p = psz; *p; p++)
{
const char* p1 = strchr(pszBase58, *p);
if (p1 == NULL)
{
while (isspace(*p))
p++;
if (*p != '\0')
return false;
break;
}
bnChar.setulong(p1 - pszBase58);
if (!BN_mul(&bn, &bn, &bn58, pctx))
throw bignum_error("DecodeBase58 : BN_mul failed");
bn += bnChar;
}
// Get bignum as little endian data
std::vector<unsigned char> vchTmp = bn.getvch();
// Trim off sign byte if present
if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80)
vchTmp.erase(vchTmp.end()-1);
// Restore leading zeros
int nLeadingZeros = 0;
for (const char* p = psz; *p == pszBase58[0]; p++)
nLeadingZeros++;
vchRet.assign(nLeadingZeros + vchTmp.size(), 0);
// Convert little endian data to big endian
reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size());
return true;
}
// Decode a base58-encoded string str into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58(str.c_str(), vchRet);
}
// Encode a byte vector to a base58-encoded string, including checksum
inline std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
{
// add 4-byte hash check to the end
std::vector<unsigned char> vch(vchIn);
uint256 hash = Hash(vch.begin(), vch.end());
vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
return EncodeBase58(vch);
}
// Decode a base58-encoded string psz that includes a checksum, into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
{
if (!DecodeBase58(psz, vchRet))
return false;
if (vchRet.size() < 4)
{
vchRet.clear();
return false;
}
uint256 hash = Hash(vchRet.begin(), vchRet.end()-4);
if (memcmp(&hash, &vchRet.end()[-4], 4) != 0)
{
vchRet.clear();
return false;
}
vchRet.resize(vchRet.size()-4);
return true;
}
// Decode a base58-encoded string str that includes a checksum, into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58Check(str.c_str(), vchRet);
}
/** Base class for all base58-encoded data */
class CBase58Data
{
protected:
// the version byte
unsigned char nVersion;
// the actually encoded data
std::vector<unsigned char> vchData;
CBase58Data()
{
nVersion = 0;
vchData.clear();
}
~CBase58Data()
{
// zero the memory, as it may contain sensitive data
if (!vchData.empty())
memset(&vchData[0], 0, vchData.size());
}
void SetData(int nVersionIn, const void* pdata, size_t nSize)
{
nVersion = nVersionIn;
vchData.resize(nSize);
if (!vchData.empty())
memcpy(&vchData[0], pdata, nSize);
}
void SetData(int nVersionIn, const unsigned char *pbegin, const unsigned char *pend)
{
SetData(nVersionIn, (void*)pbegin, pend - pbegin);
}
public:
bool SetString(const char* psz)
{
std::vector<unsigned char> vchTemp;
DecodeBase58Check(psz, vchTemp);
if (vchTemp.empty())
{
vchData.clear();
nVersion = 0;
return false;
}
nVersion = vchTemp[0];
vchData.resize(vchTemp.size() - 1);
if (!vchData.empty())
memcpy(&vchData[0], &vchTemp[1], vchData.size());
memset(&vchTemp[0], 0, vchTemp.size());
return true;
}
bool SetString(const std::string& str)
{
return SetString(str.c_str());
}
std::string ToString() const
{
std::vector<unsigned char> vch(1, nVersion);
vch.insert(vch.end(), vchData.begin(), vchData.end());
return EncodeBase58Check(vch);
}
int CompareTo(const CBase58Data& b58) const
{
if (nVersion < b58.nVersion) return -1;
if (nVersion > b58.nVersion) return 1;
if (vchData < b58.vchData) return -1;
if (vchData > b58.vchData) return 1;
return 0;
}
bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; }
bool operator<=(const CBase58Data& b58) const { return CompareTo(b58) <= 0; }
bool operator>=(const CBase58Data& b58) const { return CompareTo(b58) >= 0; }
bool operator< (const CBase58Data& b58) const { return CompareTo(b58) < 0; }
bool operator> (const CBase58Data& b58) const { return CompareTo(b58) > 0; }
};
/** base58-encoded Bitcoin addresses.
* Public-key-hash-addresses have version 0 (or 111 testnet).
* The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
* Script-hash-addresses have version 5 (or 196 testnet).
* The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
*/
class CBitcoinAddress;
class CBitcoinAddressVisitor : public boost::static_visitor<bool>
{
private:
CBitcoinAddress *addr;
public:
CBitcoinAddressVisitor(CBitcoinAddress *addrIn) : addr(addrIn) { }
bool operator()(const CKeyID &id) const;
bool operator()(const CScriptID &id) const;
bool operator()(const CNoDestination &no) const;
};
class CBitcoinAddress : public CBase58Data
{
public:
enum
{
PUBKEY_ADDRESS = 25, // Basecoin: address begin with 'B'
SCRIPT_ADDRESS = 8,
PUBKEY_ADDRESS_TEST = 111,
SCRIPT_ADDRESS_TEST = 196,
};
bool Set(const CKeyID &id) {
SetData(fTestNet ? PUBKEY_ADDRESS_TEST : PUBKEY_ADDRESS, &id, 20);
return true;
}
bool Set(const CScriptID &id) {
SetData(fTestNet ? SCRIPT_ADDRESS_TEST : SCRIPT_ADDRESS, &id, 20);
return true;
}
bool Set(const CTxDestination &dest)
{
return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);
}
bool IsValid() const
{
unsigned int nExpectedSize = 20;
bool fExpectTestNet = false;
switch(nVersion)
{
case PUBKEY_ADDRESS:
nExpectedSize = 20; // Hash of public key
fExpectTestNet = false;
break;
case SCRIPT_ADDRESS:
nExpectedSize = 20; // Hash of CScript
fExpectTestNet = false;
break;
case PUBKEY_ADDRESS_TEST:
nExpectedSize = 20;
fExpectTestNet = true;
break;
case SCRIPT_ADDRESS_TEST:
nExpectedSize = 20;
fExpectTestNet = true;
break;
default:
return false;
}
return fExpectTestNet == fTestNet && vchData.size() == nExpectedSize;
}
CBitcoinAddress()
{
}
CBitcoinAddress(const CTxDestination &dest)
{
Set(dest);
}
CBitcoinAddress(const std::string& strAddress)
{
SetString(strAddress);
}
CBitcoinAddress(const char* pszAddress)
{
SetString(pszAddress);
}
CTxDestination Get() const {
if (!IsValid())
return CNoDestination();
switch (nVersion) {
case PUBKEY_ADDRESS:
case PUBKEY_ADDRESS_TEST: {
uint160 id;
memcpy(&id, &vchData[0], 20);
return CKeyID(id);
}
case SCRIPT_ADDRESS:
case SCRIPT_ADDRESS_TEST: {
uint160 id;
memcpy(&id, &vchData[0], 20);
return CScriptID(id);
}
}
return CNoDestination();
}
bool GetKeyID(CKeyID &keyID) const {
if (!IsValid())
return false;
switch (nVersion) {
case PUBKEY_ADDRESS:
case PUBKEY_ADDRESS_TEST: {
uint160 id;
memcpy(&id, &vchData[0], 20);
keyID = CKeyID(id);
return true;
}
default: return false;
}
}
bool IsScript() const {
if (!IsValid())
return false;
switch (nVersion) {
case SCRIPT_ADDRESS:
case SCRIPT_ADDRESS_TEST: {
return true;
}
default: return false;
}
}
};
bool inline CBitcoinAddressVisitor::operator()(const CKeyID &id) const { return addr->Set(id); }
bool inline CBitcoinAddressVisitor::operator()(const CScriptID &id) const { return addr->Set(id); }
bool inline CBitcoinAddressVisitor::operator()(const CNoDestination &id) const { return false; }
/** A base58-encoded secret key */
class CBitcoinSecret : public CBase58Data
{
public:
void SetSecret(const CSecret& vchSecret, bool fCompressed)
{
assert(vchSecret.size() == 32);
SetData(128 + (fTestNet ? CBitcoinAddress::PUBKEY_ADDRESS_TEST : CBitcoinAddress::PUBKEY_ADDRESS), &vchSecret[0], vchSecret.size());
if (fCompressed)
vchData.push_back(1);
}
CSecret GetSecret(bool &fCompressedOut)
{
CSecret vchSecret;
vchSecret.resize(32);
memcpy(&vchSecret[0], &vchData[0], 32);
fCompressedOut = vchData.size() == 33;
return vchSecret;
}
bool IsValid() const
{
bool fExpectTestNet = false;
switch(nVersion)
{
case (128 + CBitcoinAddress::PUBKEY_ADDRESS):
break;
case (128 + CBitcoinAddress::PUBKEY_ADDRESS_TEST):
fExpectTestNet = true;
break;
default:
return false;
}
return fExpectTestNet == fTestNet && (vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1));
}
bool SetString(const char* pszSecret)
{
return CBase58Data::SetString(pszSecret) && IsValid();
}
bool SetString(const std::string& strSecret)
{
return SetString(strSecret.c_str());
}
CBitcoinSecret(const CSecret& vchSecret, bool fCompressed)
{
SetSecret(vchSecret, fCompressed);
}
CBitcoinSecret()
{
}
};
#endif
| Java |
/* Client-side router settings */
Router.configure({
layoutTemplate:"layout",
notFoundTemplate:"page_not_found",
loadingTemplate:"loading"
});
Router.route("/", {
name:"home",
template:"home"
});
Router.route("/profile", {
name:"profile",
template:"profile"
});
Router.route("/admin", {
name:"admin",
template:"admin"
});
Router.route("/user/:_id", {
name:"user",
template:"user",
data: function(){
return Meteor.users.findOne({_id: this.params._id});
}
});
| Java |
/*---------------------------------------------------------------------------------
Name : amixer.c
Author : Marvin Raaijmakers
Description : Plugin for keyTouch that can change the volume (using amixer).
Date of last change: 24-Sep-2006
History : 24-Sep-2006 Added two new plugin functions:
"Volume increase 10%" and "Volume decrease 10%"
05-Mar-2006 - clean_exit() will be used to exit the client
process, that manages the volume bar, cleanly
- update_window() now returns a boolean indicating
if the function should be called again
29-Jan-2006 Added the GUI volume bar to the plugin
Copyright (C) 2005-2006 Marvin Raaijmakers
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 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.
-----------------------------------------------------------------------------------*/
#define _GNU_SOURCE
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <gtk/gtk.h>
#include <time.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <plugin.h>
#include <amixer-plugin.h>
void vol_increase (KTPreferences *preferences);
void vol_decrease (KTPreferences *preferences);
void vol_increase_10 (KTPreferences *preferences);
void vol_decrease_10 (KTPreferences *preferences);
void mute (KTPreferences *preferences);
static void create_window (VOLUMEBAR_INFO *volumebar_info);
static int get_current_volume (void);
static void update_volume_bar (GtkWidget *volume_bar);
static gboolean update_window (VOLUMEBAR_INFO *volumebar_info);
static void clean_exit (int sig);
static void start_window (void);
static char *get_keytouch_user_dir (void);
static void change_volume (char *command);
static Boolean is_muted = FALSE;
KeytouchPlugin plugin_struct = {
{"Amixer", "Marvin Raaijmakers", "GPL 2", "2.3",
"This plugin allows you to change the volume. It also shows\n"
"the current volume when it changes. To use this plugin amixer\n"
"needs to be installed."},
"amixer.so",
5,
{{"Volume increase", KTPluginFunctionType_Function, {.function = vol_increase}},
{"Volume decrease", KTPluginFunctionType_Function, {.function = vol_decrease}},
{"Volume increase 10%", KTPluginFunctionType_Function, {.function = vol_increase_10}},
{"Volume decrease 10%", KTPluginFunctionType_Function, {.function = vol_decrease_10}},
{"Mute", KTPluginFunctionType_Function, {.function = mute}},
}
};
void
create_window (VOLUMEBAR_INFO *volumebar_info)
/*
Input:
-
Output:
volumebar_info - The window element points to the created window and the
volume_bar element points to the volume progressbar in the
window
Returns:
-
Description:
This function creates a window with a progressbar with the following
properties:
- It is positioned in the center ot the screen.
- It has no window decorations and can not be resized by the user.
- It will allways be above other windows.
- It is visible on all desktops.
- It will not be visible in the taskbar an pager.
- It does not accept focus.
*/
{
volumebar_info->window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_position (GTK_WINDOW (volumebar_info->window), GTK_WIN_POS_CENTER);
gtk_window_set_resizable (GTK_WINDOW (volumebar_info->window), FALSE);
gtk_window_set_decorated (GTK_WINDOW (volumebar_info->window), FALSE);
/* The window will allways be above others */
gtk_window_set_keep_above (GTK_WINDOW (volumebar_info->window), TRUE);
/* Let the window be visible on all desktops: */
gtk_window_stick (GTK_WINDOW (volumebar_info->window));
/* This window will not be visible in the taskbar: */
gtk_window_set_skip_taskbar_hint (GTK_WINDOW (volumebar_info->window), TRUE);
/* This window will not be visible in the pager: */
gtk_window_set_skip_pager_hint (GTK_WINDOW (volumebar_info->window), TRUE);
gtk_window_set_accept_focus (GTK_WINDOW (volumebar_info->window), FALSE);
volumebar_info->volume_bar = gtk_progress_bar_new();
gtk_widget_show (volumebar_info->volume_bar);
gtk_container_add (GTK_CONTAINER (volumebar_info->window), volumebar_info->volume_bar);
gtk_widget_set_size_request (volumebar_info->volume_bar, 231, 24);
gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (volumebar_info->volume_bar), 0.52);
gtk_progress_bar_set_pulse_step (GTK_PROGRESS_BAR (volumebar_info->volume_bar), 0.02);
gtk_progress_bar_set_text (GTK_PROGRESS_BAR (volumebar_info->volume_bar), "Volume");
}
int
get_current_volume (void)
/*
Returns:
The current volume retrieved from amixer. -1 will be returned when
retrieving the volume failed.
*/
{
FILE *amixer;
char c;
int volume = -1;
amixer = popen ("amixer sget Master | grep \"Front Left:\"", "r");
if (amixer)
{
do {
c = getc(amixer);
/* We have found the volume when the following appears:
* '[' followed by an integer followed by '%'
*/
if (c == '[' && fscanf(amixer, "%d", &volume) && (c = getc(amixer)) == '%')
{
break;
}
volume = -1;
} while (c != '\n' && c != EOF);
pclose (amixer);
}
return (volume);
}
void
update_volume_bar (GtkWidget *volume_bar)
/*
Output:
volume_bar - Will show the percentage of the current volume
*/
{
int volume;
gchar *text;
volume = get_current_volume();
if (volume && volume != -1)
{
text = g_strdup_printf("Volume %d%%", volume);
if (text)
{
gtk_progress_bar_set_text (GTK_PROGRESS_BAR(volume_bar), text);
g_free (text);
}
}
else
{
volume = 0;
gtk_progress_bar_set_text (GTK_PROGRESS_BAR(volume_bar), "Muted");
}
gtk_progress_set_percentage (GTK_PROGRESS(volume_bar), (gdouble)volume/100.0);
/* Directly draw the progressbar: */
while (g_main_context_iteration(NULL, FALSE))
; /* NULL Statement */
}
gboolean
update_window (VOLUMEBAR_INFO *volumebar_info)
/*
Input:
volumebar_info->close_time - The time to close the window
Output:
volumebar_info - Will be updated
Returns:
TRUE if this function should be called again after UPDATE_INTERVAL
miliseconds, otherwise FALSE.
Description:
This function destroys volumebar_info->window and escapes from the GTK main
routine if the current time is later than volumebar_info->close_time. If not
then the volume bar will be updated with the current volume.
*/
{
MSGBUF msg;
Boolean close_window;
/* Check if there is a new message on the queue */
if (msgrcv(volumebar_info->msgqid, &msg, sizeof(msg.time), 1, IPC_NOWAIT) != -1)
{
volumebar_info->close_time = msg.time + SHOW_WINDOW_TIME;
}
close_window = (time(NULL) > volumebar_info->close_time);
if (!close_window)
{
update_volume_bar (volumebar_info->volume_bar);
}
else
{
gtk_widget_destroy (volumebar_info->window);
gtk_main_quit();
}
return !close_window;
}
void
start_window (void)
/*
Description:
This function creates a window with a volume bar and shows it
SHOW_WINDOW_TIME seconds when it receives a message on the message queue.
The key of the message queue is generated by running
ftok(get_keytouch_user_dir(), MSGQ_AMIXER_PROJ_ID). The messages that are
sent to this queue should contain the time they are sent. The volume window
will be showed from the time this function receives the message, until the
time the message was sent plus SHOW_WINDOW_TIME seconds.
*/
{
MSGBUF msg;
VOLUMEBAR_INFO volumebar_info;
key_t msgq_key;
char *keytouch_user_dir;
gtk_init (0, NULL);
keytouch_user_dir = get_keytouch_user_dir();
/* Get the key for the message queue */
msgq_key = ftok(keytouch_user_dir, MSGQ_AMIXER_PROJ_ID);
free (keytouch_user_dir);
if (msgq_key == -1)
{
perror ("keytouch amixer plugin");
return;
}
/* Get the message queue identifier and create the queue if necessary */
volumebar_info.msgqid = msgget(msgq_key, 0);
if (volumebar_info.msgqid == -1)
{
perror ("keytouch amixer plugin");
return;
}
while (1)
{
if (msgrcv(volumebar_info.msgqid, &msg, sizeof(msg.time), 1, 0) != -1)
{
volumebar_info.close_time = msg.time + SHOW_WINDOW_TIME;
if (time(NULL) <= volumebar_info.close_time)
{
create_window (&volumebar_info);
update_volume_bar (volumebar_info.volume_bar);
gtk_widget_show (volumebar_info.window);
g_timeout_add (UPDATE_INTERVAL, (GSourceFunc) update_window, &volumebar_info);
gtk_main();
}
}
}
}
char
*get_keytouch_user_dir (void)
/*
Returns:
The address of some new allocated space which is a string containing the
value of the environment variable HOME followed by "/.keytouch2".
*/
{
char *keytouch_dir, *home;
home = getenv("HOME");
if (home == NULL)
{
fputs ("keytouch amixer plugin: could not get environment variable $HOME", stderr);
exit (EXIT_FAILURE);
}
if (asprintf(&keytouch_dir, "%s/.keytouch2", home) == -1)
{
fputs ("keytouch amixer plugin: asprintf() failed. "
"This is probably caused because it failed to allocate memory.", stderr);
exit (EXIT_FAILURE);
}
return (keytouch_dir);
}
void
clean_exit (int sig)
{
exit (EXIT_SUCCESS);
}
void
send_volume_changed_signal (void)
/*
Description:
This function sends a signal to the child program that manages the
volumebar. The child will receive the signal and will show the volumebar.
The child process will be created if it does not exist yet.
*/
{
static int qid = -1;
MSGBUF msg;
/* If this is the first time this function was called */
if (qid == -1)
{
key_t msgq_key;
char *keytouch_user_dir;
keytouch_user_dir = get_keytouch_user_dir();
/* Get the key for the message queue */
msgq_key = ftok(keytouch_user_dir, MSGQ_AMIXER_PROJ_ID);
free (keytouch_user_dir);
if (msgq_key == -1)
{
perror ("keytouch amixer plugin");
return;
}
/* Get the message queue identifier and create the queue if necessary */
qid = msgget(msgq_key, MSGQ_PERMISSIONS | IPC_CREAT);
if (qid == -1)
{
perror ("keytouch amixer plugin");
return;
}
if (fork() == 0)
{
/* Trap key signals */
signal (SIGINT, clean_exit);
signal (SIGQUIT, clean_exit);
signal (SIGTERM, clean_exit);
/* We will now start the run_window() function in our
* child process for showing a volume bar to the user
*/
start_window();
exit (EXIT_SUCCESS); /* We will never get here because of
* the infinite loop in run_window()
*/
}
}
msg.mtype = 1;
msg.time = time(NULL);
if (msgsnd(qid, &msg, sizeof(msg.time), 0) == -1)
{
perror ("keytouch amixer plugin");
}
}
void
change_volume (char *command)
/*
Input:
command - The command that changes the volume.
Description:
This function executes 'command' in a child process and then calls
send_volume_changed_signal().
*/
{
if (fork() == 0)
{
execlp ("sh", "sh", "-c", command, NULL);
exit (EXIT_SUCCESS);
}
else
{
send_volume_changed_signal();
}
}
void
vol_increase (KTPreferences *preferences)
{
is_muted = FALSE;
change_volume ( CHANGE_VOL_CMD(VOL_DEFAULT_INCR) );
}
void
vol_decrease (KTPreferences *preferences)
{
is_muted &= !get_current_volume();
change_volume ( CHANGE_VOL_CMD(VOL_DEFAULT_DECR) );
}
void
vol_increase_10 (KTPreferences *preferences)
{
is_muted = FALSE;
change_volume ( CHANGE_VOL_CMD(VOL_10PERCENT_INCR) );
}
void
vol_decrease_10 (KTPreferences *preferences)
{
is_muted &= !get_current_volume();
change_volume ( CHANGE_VOL_CMD(VOL_10PERCENT_DECR) );
}
void
mute (KTPreferences *preferences)
{
static int prev_volume = -1;
int current_volume;
char *command = NULL;
current_volume = get_current_volume();
is_muted &= !current_volume;
if (is_muted)
{
/* Tell amixer to set the volume to prev_volume */
if (asprintf(&command, "amixer sset Master %d%% > /dev/null", prev_volume) == -1)
{
fputs ("keytouch amixer plugin: asprintf() failed. "
"This is probably caused because it failed to allocate memory.", stderr);
}
}
else if (current_volume)
{
/* Tell amixer to set the volume to 0 */
command = strdup("amixer sset Master 0% > /dev/null");
if (command == NULL)
{
perror ("keytouch amixer plugin");
}
prev_volume = current_volume;
}
/* Do we have to mute/unmute? */
if (command)
{
if (fork() == 0)
{
execlp ("sh", "sh", "-c", command, NULL);
exit (EXIT_SUCCESS);
}
else
{
send_volume_changed_signal();
}
free (command);
is_muted = !is_muted;
}
}
| Java |
<?php
namespace S327at\L51blog\Models;
use Illuminate\Database\Eloquent\Model;
class Group extends Model {
} | Java |
# Dokumenttien laatiminen
Tämän ohjesivun sisältö:
- Dokumentoinnin periaatteet
- Uuden sivudokumentin laatiminen, muokkaaminen ja päivittäminen
- Taulukoiden tekeminen piazzalla
- Uuden tiedostodokumentin laatiminen, tiedoston nostaminen piazzalle, muokkaaminen ja päivittäminen
- Dokumenttien linkitys
- Kuvan liittäminen dokumenttiin
- Dokumenttien poistaminen
- Dokumenttien ja kansioiden muut tiedot
Lue myös [dokumenttien ylläpito](dokumentin_yllapito) ja [Toimintaohjeet](toimintaohjeet).
----
## Uuden dokumentin laatimisen periaatteita
Jotta prosessidokumentit (prosessikaaviot, prosessikuvaukset, apteekkiohjeet, toimintaohjeet, kokousmuistiot, sisäisten arviointien muistiot) ovat ulkoasultaan yhdenmukaiset, niille kannattaa laatia jo prosessikehittämisen alussa **mallipohjat**.
Tässä esimerkki prosessikuvauksen mallipohjasta, kun dokumentti laaditaan sivuna.

----
Näin tunnistetiedot, fontit ja otsikot tulevat kohdalleen, eikä niitä tarvitse miettiä joka kerta erikseen.
Dokumenttien yhtenäinen ulkoasu näyttää mukavalta, kertoo yhdenmukaisista toimintatavoista myös dokumentoinnissa.
----
Jos mallipohjat on jokaiselle dokumenttityypille, niille kannattaa laatia oman kansionsa Mallipohjat, josta pohjat löytyvät helposti.

Kansioiden lisäämisestä ja ylläpidosta on [tarkempaa ohjetta](kansiot).
----
Dokumentteja voi laatia piazzalle kahdella tapaa: **joko suoraan sivuna** tai **nostaa liitetiedostona** (tiedostona vanha tapa).
Nykyisin suositellaan, että kaikki perustekstit (Wordit, esim. kuvaukset, ohjeet ja muistiot) laaditaan sivuna, jolloin niiden hallinta on helpompaa ja yksinkertaisempaa.<br>
Niitä pystyy muokkaamaan suoraan piazzalla, myös hakutoiminto etsii tekstin (esim. ohjeen) sisällöstä.
Jos tekstissä on taulukko tai muita erikoismerkkejä, tekstit laaditaan teksinkäsittelyohjelmalla ja käsitellään piazzalla tiedostona, näin myös powerpoint-, pdf- ja excel-muotoiset.
Käytännössä vain prosessikaaviot, mittarit ja koulutusmateriaali vaativat tiedostokäsittelyn, muut voidaan laatia helposti sivuna.
----
## Uuden sivudokumentin laatiminen ja päivittäminen
Käytettäessä mallipohjaa (suositus) avataan Mallipohja -kansio tai kansio, jossa mallipohja on.
Valitaan kansion vihreästä valikosta **Sisältö** -> ruksataan pohja -> valitaan **Kopio**.

Tämän jälkeen avataan kansio, johon pohja halutaan siirtää (laatia uusi dokumentti).<br>
Valitaan vihreästä valikosta Sisältö -> valitaan **Leikkaa**, jolloin pohja kopioituu sopivaan kansioon.
----
Tämän jälkeen avataan siirretty pohja -> valitaan **Muokkaa -> muutetaan otsikko, tunnistetiedot** ym.
Nyt pääset kirjoittamaan tekstiä. **Tallenna** aina välillä (alaosassa Tallenna).
Sitten kun jatkat kirjoittamista, avaa dokumentti, valitse Muokkaa, muuta tarvittaessa pvm ja jatka kirjoittamista.
Sitten kun dokumentti on valmis, se lähetetään [hyväksyttäväksi](dokumentin_yllapito/#dokumentin-hyvaksyminen).
Päivitettäessä dokumenttia (dokumentti on jo hyväksytty) muuttuneet kohdat kirjoitetaan esim. kursiivilla tai miten muutokset on sovittu merkittäväksi. Kun dokumenttia muutetaan seuraavan kerran, kursiivit oikaistaan ja uudet muuttuneet kohdat kursiivilla. Kursiivia käytetään vasta kun dokumentit on hyväksytty.
Muistetaan muuttaa aina myös päivämäärä ja laatija tarvittaessa.<br>
Myös päivitetyt dokumentit lähetetään [hyväksyttäväksi](dokumentin_yllapito/#dokumentin-hyvaksyminen).
Jos et käytä mallipohjaa, avaa kansio, johon haluat laatia dokumentin. Valitse valikosta **Lisää uusi** -> **Sivu**. Avaa sitten ko. sivu -> **Muokkaa** -> aloita kirjoittaminen.
Uusi dokumentti menee alimmaiseksi. Voit siirtää sen haluamaasi paikkaan samalla tavalla kuin
[kansioiden sisältöä järjestetään](kansiot/#kansion-sisallon-jarjestaminen-uudelleen).
----
## Kuvaukset ja ohjeet aikaisemmin olleet tiedostoina
Aikaisemmin käytäntönä oli, että dokumentit laadittiin tietokoneella tiedostoina, jotka nostettiin piazzalle.<br>
Tämä käytäntö on kerrottu seuraavassa otsikossa.
__Suositeltavaa on__, että dokumentin seuraavan päivityksen yhteydessä tekstit tehdään sivuina, jotta niiden käsittely jatkossa on helpompaa.
Se tehdään näin:
- Kopioi mallipohja ko. kansioon tai laadi uusi sivu edellä kuvatun mukaisesti.
- Avaa päivitettävä tiedosto.
- Maalaa teksti alusta loppuun (yläotsikkoa ei pysty maalaamaan ainakaan helposti), vie se leikepöydälle (contrl c).
- Avaa äsken tehty sivu, valitse muokkaa, vie kursori tekstikenttään ja liitä tiedoston teksti (control w), jolloin teksti siirtyy sivulle. Lopuksi tallenna.
- Tarvittaessa poista ylimääräiset rivit, lihavoi/kursivoi sekä kirjoita päivitettävä teksti ja lopuksi tallenna.
- Poista vanha tiedosto.
Siirtymisen tiedostoista voi tehdä myös "urakkana", esim. joku keskitetysti tekee siirrot.
Muistetaan muuttaa tekijät oikeiksi.
----
## Uuden tiedostodokumentin laatiminen
- Avataan mallipohja -> tallennetaan se tietokoneelle (esim. työpöydälle) mahdollisimman kuvaavalla lyhyellä nimellä.
- Muutetaan tunnistetiedot ja jatketaan kirjoittamista tekstinkäsittelyohjelmalla.
- Tallennuksen jälkeen tiedosto siirretään piazzalle.
- Myös keskeneräiset kannattaa nostaa piazzalle.
### Tiedoston nostaminen piazzalle
Avataan kansio, johon tiedosto halutaan liittää.<br>
Valitaan vihreästä valikosta **Lisää uusi** -> **Tiedosto**.

Kirjoitetaan nimikkeeksi tiedoston nimi.
Kuvaus ei ole pakollinen, mutta suositeltava. Siinä voi hieman tarkentaa mitä tämä liitetiedosto pitää sisällään tai jotain muuta siihen liittyvää tietoa.
Varsinainen tiedosto poimitaan omalta koneelta **Browse** tai **Selaa** -toiminnolla.
Lopuksi **Tallenna**, jolla tiedosto siirtyy fyysisesti piazzalle.<br>
Työpöydältä käydään poistamassa tiedosto, jotta sinne ei kerry tiedostoja.
### Tiedoston muokkaaminen ja täydentäminen
Tiedostoja ei voi muokata suoraan piazzalla, vaan ne on aina tehtävä tekstinkäsittelyohjelmalla.
Suositeltavaa on, että päivitettävä tiedosto avataan piazzalla, jotta päivitetään viimeisintä versiota.
Tiedosto tallennetaan tietokoneelle ja tehdään muutokset koneelle.
Jos tiedostodokumentti on jo hyväksytty, muuttuneet kohdat esim. kursiivilla tai miten muutokset on sovittu merkittäväksi.
Muistetaan muuttaa aina myös päivämäärä ja laatija tarvittaessa.
Päivitetty tiedosto mostetaan piazzalle seuraavasti:
- Avataan päivitettävä tiedosto
- Valitaan **Muokkaa**
- Valitaan **Korvaa uudella tiedostolla**, haetaan tiedosto koneelta, lopuksi **Tallenna**.



----
## Taulukoiden laatiminen
Piazzalla voi laatia myös taulukoita joko omiksi dokumenteikseen (esim. koulukortit, projektisuunnitelmat) tai taulukoita sivudokumenttien tekstiin.
Taulukon laatiminen tekstidokumenttiin tehdään Muokkaa-tilassa:
- Mene dokumentissa kohtaan, johon haluat taulukon
- Valitse ylläolevasta valikosta taulukko
- Lisää sarakkeiden ja rivien määrä
- Tallenna tai täytä taulokkoa samantien
Jos laaditaan taulukkodokumentteja (esim. koulutuskortteja), tehdään näin:
- Lisää uusi sivu
- Kirjoita Nimike ja lisää tekstiin (kommentti) taulukko em. opastuksen mukaisesti
Taulukossa ei ole kaikkia excelin hienouksia, mutta perustaulukon tekemiseen varsin kätevä, esim.rivejä ja sarakkeita on helppo lisätä tai poistaa.
## Dokumenttien linkitys
Piazzalla on mahdollista myös dokumenttien linkitys, esim. asiakastyytyväisyystutkimus markkinoinnin ja asiakaspalveluprosessien mittarina tai halutaan linkittää dokumenttia sivulta toiselle.
Ylläpidon hallinnan kannalta on tärkeää, että dokumentti on vain yhdessä paikassa.
Linkitys voidaan tehdä kahdella tavalla.
### Linkitys sivulta dokumenttiin
!!! note "Huom"
Linkitys ei toimi Internet Explorerilla.<br>
Käytä Mozilla Firefoxia tai Google Chromea linkkien lisäämiseen.
Sivueditorin (tekstieditorin) tulee olla muotoa [TinyMCE](sivueditorit/#tinymce-editori).<br>
Näkyy ja muutetaan tarvittaessa piazzan pääsivulla Asetukset.
* Avataan/lisätään sivudokumentti, johon linkitys halutaan.
* Valitaan **Muokkaa**, "maalataan" linkitettävä sana/-t, valitaan editoripalkista **Lisää/muuta linkki** (ketju).
* Näyttöön avautuu Lisää/muokkaa -näkymä.
* Jos halutaan linkittää piazzalla oleva dokumentti, valitaan sisäisestä linkitettävä dokumentti, eli avataan kansioita niin pitkälle, että dokumentti löytyy.
* Ruksataan linkitettävä dokumentti ja lopuksi OK. Linkitys näkyy dokumentissa alleviivauksena.
* Vastaavasti linkitetään ulkoinen linkki (nettisvu).
Tällä tavalla on erityisen helppoa linkittää sivuna laadittuun dokumenttiin muita dokumentteja, esim. kaikki toimintaohjeet toimintaohjeluetteloon.

### Myös näin on mahdollista linkittää
Etenkin aikaisemmin suosittiin tätä kategorisoinnin kautta tapahtuvaa linkitystä, joka tehdään näin.
* Luodaan tai avataan sivu, johon linkitys halutaan.
* Valitaan **Muokkaa**, valitaan "Kategorisointi", avautuvalta sivulta valitaan **Samasta aiheesta** ja **Lisää** -toiminnolla haetaan sopiva dokumentti linkitettäväksi avaamalla kansioita niin pitkälle, että dokumentti löytyy, ja lopuksi "Tallenna".
* Makuasia kumpaako tapaa haluaa käyttää.
----
## Kuvan liittäminen dokumenttiin
Sivudokumenttiin on helppo liittää kuva esim. havainnollistaakseen tekstiä.
Kuvia voi lisätä tekstiin näin (ensin kuva haetaan piazzalle omaan kansioon):
- Avaa oma kansio (löytyy ylhäältä oikealta)
- Lisää uusi kuva, hae se tietokoneeltasi ja lopuksi tallenna (siis jos kuvaa ei ole piazzalla)
- Avaa dokumentti, johon haluat liittää kuvan. Valitse Muokkaa ja mene siihen kohtaan, johon haluat kuvan.
- Valitse ylläolevasta valikosta vasemmasta laidasta ”kuvaruutu” (lisää/muuta kuva).
- Valitse näkymän oikeasta kulmasta keskimmäinen List view.
- Valitse Pääsivu, jolloin näkyviin tulee kansiorakenteenne piazzalla.
- Valitse sieltä Käyttäjät -> oma kansiosi ja sieltä valitse kuva ja lopuksi ok
- Ja ihan viimeiseksi tallenna ko. dokumentti.
Jos kuva on jo piazzalla, liitä kuva näin:
- Avaa dokumentti, johon haluat liittää kuvan. Valitse Muokkaa ja mene siihen kohtaan, johon haluat kuvan.
- Valitse ylläolevasta valikosta vasemmasta laidasta ”kuvaruutu” (lisää/muuta kuva).
- Valitse näkymän oikeasta kulmasta keskimmäinen List view.
- Valitse Pääsivu, jolloin näkyviin tulee kansiorakenteenne piazzalla.
- Avaa kansio, jossa kuva on. Valitse kuva ja ok.
- Lopuksi tallenna dokumentti.
----
## Dokumenttien poistaminen
Piazzan dokumentit ja liitetiedostot voidaan poistaa helposti, jos niitä ei enää tarvita tai ovat vanhentuneita, ja joku uusi dokumentti korvaa ne.
Poisto voidaan tehdä monellakin tavalla, mutta yleisin on ottaa dokumentti ensin esiin, ja sen jälkeen avataan toiminnot -valikko, josta löytyy kohta **Poista**.

Ennen varsinaista poistoa piazza vielä kysyy käyttäjältä varmistuksen poistolle.
----
## Dokumenttien ja kansioiden muut tiedot
**Muuokkaa** -tilassa on mahdollista antaa myös muita sisältöön liittyviä tietoja.
Ruudulla on viisi __"välilehden"__ näköistä osioita, joista avautuu kyseiseen kansioon tai sisältöön liittyvää lisätietoa.

* __Kategorisointi__
- Voidaan antaa sisällölle joitain avainsanoja, jotka ovat hyödyllisiä esim. haettaessa tietyntyyppisiä dokumentteja **Haku**-toiminnolla.
- Sitä voidaan myös käyttää ns. älykansioissa hyödyksi, jolloin saadaan kaikki samantyyppiset dokumentit koottua __"loogiseen kansioon"__ vaikka ne fyysisesti olisivatkin hajallaan ympäri sisältörakennetta.
* __Päivät__
- Voidaan antaa dokumentin julkaisemisen alkamis- ja päättymispäivät.
- Tulee kyseeseen aika harvoin, mutta on mahdollista jos on joku tietyn ajan voimassa oleva dokumentti tai jos haluaa jukaista dokumentin tiettynä ajankohtana.
* __Omistaja__ - _tärkeä_
- Täällä voidaan käydä vaihtamassa dokumentin omistaja- tai tekijä toiseksi.
- Esim. tilanteessa jossa vastuu dokumentin tai kansion sisällöstä siirretään toiselle henkilölle, kts. [tekijän muuttaminen](kansiot/#kansion-tekijan-muuttaminen).
* __Asetukset__
- Oletusarvona, että kommentointi sallittua.

----
| Java |
package com.calebmeyer.bettercrafting.creativetab;
import com.calebmeyer.bettercrafting.constants.Project;
import com.calebmeyer.bettercrafting.initialization.ModItems;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
public class CreativeTabBCT {
public static final CreativeTabs BETTER_CRAFTING_TABLES_TAB = new CreativeTabs(Project.MOD_ID) {
/**
* This method returns an item, whose icon is used for this creative tab
*
* @return an item to use for the creative tab's icon
*/
@Override
public Item getTabIconItem() {
return ModItems.craftingPanel;
}
/**
* Gets the label for this creative tab.
*
* @return the label
*/
@Override
public String getTranslatedTabLabel() {
return Project.MOD_NAME;
}
};
}
| Java |
//Change class of "Home" and "About"
function setActive() {
document.getElementById("about").className += "active"
document.getElementById("home").setAttribute('class','no')
}
| Java |
<?php
class PostModel extends CI_Model
{
public $id;
public $title;
public $content;
public $date;
public $author;
public $upvotes = 0;
public $downvotes = 0;
public $voters;
public function __construct()
{
parent::__construct();
}
public function GetAll()
{
$this->db->order_by('date', 'desc');
$query = $this->db->get('posts');
return $query->result();
}
public function GetByID($id)
{
$query = $this->db->get_where('posts', array('id' => $id));
return $query->row();
}
private function Insert($post)
{
session_start();
$this->author = $_SESSION["username"];
return $this->db->insert('posts', $this);
}
private function Update($post)
{
$this->db->set('title', $this->title);
$this->db->set('content', $this->content);
$this->db->where('id', $this->id);
return $this->db->update('posts');
}
public function Delete()
{
$this->db->where('id', $this->id);
return $this->db->delete('posts');
}
public function Save()
{
if (isset($this->id))
{
return $this->Update();
}
else
{
return $this->Insert();
}
}
public function Vote()
{
$this->db->set('upvotes', $this->upvotes);
$this->db->set('downvotes', $this->downvotes);
$this->db->set('voters', $this->voters);
$this->db->where('id', $this->id);
return $this->db->update('posts');
}
}
?> | Java |
---
title: 'PB & Homemade J'
author: lbjay
layout: post
permalink: /2007/10/05/pb-homemade-j/
categories:
- "What's for Lunch"
---
<abbr class="unapi-id" title=""><!-- --></abbr>
<div style="float: right; margin-left: 10px; margin-bottom: 10px;">
<a href="http://www.flickr.com/photos/37849137@N00/1490397893/" title="photo sharing"><img src="http://farm2.static.flickr.com/1243/1490397893_cac4375203_m.jpg" alt="" style="border: solid 2px #000000;" /></a><br /> <br /> <span style="font-size: 0.9em; margin-top: 0px;"><br /> <a href="http://www.flickr.com/photos/37849137@N00/1490397893/">PB & Homemade J</a><br /> <br /> Originally uploaded by <a href="http://www.flickr.com/people/37849137@N00/">jayluker</a><br /> </span>
</div>
This one’s been stuck in the Flickr queue for a couple of weeks. Also it wasn’t truly Peanut Butter, but Sunflower Butter. It just seems so awkward to call it a SFB & J.
The jelly is grape and was made by my neighbor Leah from <a href='http://en.wikipedia.org/wiki/Concord_grape' target='_blank'>Concord grapes</a> growing on a trellis right out her back door.
The pile ‘o’ orange in the foreground is some delicious carrot slaw made with honey, walnuts and dried cranberries.
<br clear="all" /> | Java |
---
layout: default
---
<h2>{{ page.title }}</h2>
<div class="post">
{{ content }}
</div>
| Java |
body {
color: #ffffff;
font-family: Monospace, sans-serif;
font-size: 13px;
text-align: center;
font-weight: bold;
background-color: #000000;
margin: 0;
overflow: hidden;
cursor: none;
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Chrome/Safari/Opera */
-khtml-user-select: none; /* Konqueror */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none;
}
ul {
list-style: none;
}
.found {
text-decoration: line-through;
color: #00ff00;
}
.player-information {
font-size: 1.2em;
font-weight: bold;
position: absolute;
left: 0;
top: 0;
padding: 1em;
z-index: 2147483647;
}
.items {
font-size: 1.2em;
font-weight: bold;
position: absolute;
right: 0;
top: 0;
padding-right: 1em;
z-index: 2147483647;
height: 90%;
overflow: hidden;
}
.refreshButton {
position: absolute;
left: 0;
top: 5.5em;
margin-left: 10px;
padding: 1.25em;
color: white;
font-size: larger;
text-decoration: none;
border-radius: 1em;
background-repeat: no-repeat;
background-image: url('./../ui/refresh.svg');
background-size: contain;
background-color: teal;
z-index: 2147483647;
}
/*********************
Player Settings
**********************/
#settings {
display: none;
width: 25%;
min-width: 300px;
margin: 1% auto;
}
#settings label {
display: block;
}
#settings label.inline {
display: inline-block;
}
#settings input {
padding: 5px 10px;
margin-bottom: 10px;
}
#settings input.small {
width: 25px;
}
#settings button {
display: block;
margin: 15px auto;
padding: 5px 10px;
}
| Java |
<html><body>
<h4>Windows 10 x64 (18362.329)</h4><br>
<h2>_CM_UOW_SET_VALUE_KEY_DATA</h2>
<font face="arial"> +0x000 PreparedCell : Uint4B<br>
+0x004 OldValueCell : Uint4B<br>
+0x008 NameLength : Uint2B<br>
+0x00c DataSize : Uint4B<br>
</font></body></html> | Java |
/// <reference types="xrm" />
export declare function findIndex(handlers: Xrm.Events.ContextSensitiveHandler[], handler: Xrm.Events.ContextSensitiveHandler): number;
| Java |
<?php
namespace Vilks\DataObject;
use Vilks\DataObject\Exception\DirectPropertySetException;
use Vilks\DataObject\Exception\PropertyNotFoundException;
use Vilks\DataObject\Exception\PropertyValidationFailedException;
use Vilks\DataObject\Exception\WrongEvolutionInheritanceException;
use Vilks\DataObject\Validator\DataObjectValidatorFactory;
/**
* Base DataObject
*
* @package Vilks\DataObject
*/
abstract class DataObject
{
private static $validators = [];
/**
* Create instance of DataObject
*
* @return static
*/
public static function create()
{
return new static;
}
/**
* Create instance of DataObject with values based on related DataObject
*
* @param DataObject $source Data source object
*
* @return static
* @throws Exception\WrongEvolutionInheritanceException If DataObjects has different chain of inheritance
*/
public static function mutate(DataObject $source)
{
$replica = static::create();
if ($replica instanceof $source) {
$properties = get_object_vars($source);
} elseif ($source instanceof $replica) {
$properties = get_object_vars($replica);
} else {
throw new WrongEvolutionInheritanceException(
$replica,
$source,
sprintf('Class "%s" must be parent or child for "%s"', get_class($source), get_class($replica))
);
}
foreach ($properties as $name => $value) {
$replica->$name = $value;
}
return $replica;
}
/**
* Magic set property of DataObject
*
* IMPORTANT: For better performance in production you need
* to overwrite method for each property in final DataObjects
*
* @param string $name
* @param array $arguments
*
* @return static
*/
public function __call($name, array $arguments)
{
$this->_isPropertyExists($name);
if (!count($arguments)) {
return $this->$name;
} else {
$value = $arguments[0];
$this->_validateDataType($name, $value);
$replica = static::_isMutable() ? $this : clone $this;
$replica->$name = $value;
return $replica;
}
}
/**
* Magic get property of DataObject
*
* IMPORTANT: For better performance in production you need
* to make properties public in final DataObjects
*
* @param string $name
*
* @return mixed
*/
public function __get($name)
{
$this->_isPropertyExists($name);
return $this->$name;
}
/**
* Disallow direct setting of properties
*
* @param string $name
* @param string $value
*
* @throws Exception\DirectPropertySetException
* @deprecated
*/
public function __set($name, $value)
{
throw new DirectPropertySetException($name, $value, $this);
}
/**
* Turning off constructor outside object
* Use Class::create()
*/
protected function __construct()
{}
/**
* List of datatypes for properties
*
* @return string[]
*/
protected static function _getDataTypes()
{
return [];
}
/**
* Setting for DataObject which set behavior on property changing.
* If it's false changing of property will generate new DataObject with same values,
* if it's true changing of property will just change property in object
*
* @return bool
*/
protected static function _isMutable()
{
return false;
}
/**
* Exclude validators from serialization
*
* @return string[]
*/
public function __sleep()
{
$properties = array_keys(get_object_vars($this));
unset($properties['validators']);
return $properties;
}
private static function _getPropertyValidator($class, $property)
{
$key = sprintf('%s.%s', $class, $property);
if (!array_key_exists($key, self::$validators)) {
$types = static::_getDataTypes();
self::$validators[$key] = array_key_exists($property, $types) ?
DataObjectValidatorFactory::getValidator($class)->getValidationCallback($types[$property]) :
null;
}
return self::$validators[$key];
}
private function _validateDataType($property, $value)
{
if (!is_null($value)) {
$validator = self::_getPropertyValidator(get_class($this), $property);
if ($validator && !$validator($value)) {
throw new PropertyValidationFailedException(
$property,
$value,
static::_getDataTypes()[$property],
$this
);
}
}
}
private function _isPropertyExists($name, $strict = true)
{
$result = property_exists($this, $name);
if ($strict && !$result) {
throw new PropertyNotFoundException($this, $name);
}
return $result;
}
}
| Java |
import _plotly_utils.basevalidators
class ShowexponentValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self,
plotly_name="showexponent",
parent_name="scatterpolar.marker.colorbar",
**kwargs
):
super(ShowexponentValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "colorbars"),
values=kwargs.pop("values", ["all", "first", "last", "none"]),
**kwargs
)
| Java |
<?php
namespace Midnight\Crawler\Plugin\TestData;
class MuryoTestData extends AbstractTestData
{
/**
* @var string
**/
protected $rss_name = 'muryo.xml';
/**
* @var array
**/
protected $html_paths = array(
'muryo/71340.html',
'muryo/71370.html',
'muryo/71376.html',
'muryo/error.html',
'muryo/error2.html'
);
}
| Java |
using System;
using Argus.Extensions;
namespace Argus.Data
{
/// <summary>
/// Contains a string name/value pair seperated by an equals sign. The values can be set via the properties or by passing in a
/// delimited string. E.g. FirstName=Blake.
/// </summary>
/// <remarks></remarks>
public class Parameter
{
//*********************************************************************************************************************
//
// Class: Parameter
// Organization: http://www.blakepell.com
// Initial Date: 12/19/2012
// Last Updated: 04/07/2016
// Programmer(s): Blake Pell, blakepell@hotmail.com
//
//*********************************************************************************************************************
/// <summary>
/// Constructor
/// </summary>
/// <remarks></remarks>
public Parameter()
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">The name of the parameter.</param>
/// <param name="value">The value of the parameter.</param>
/// <remarks></remarks>
public Parameter(string name, string value)
{
this.Name = name;
this.Value = value;
}
/// <summary>
/// Returns the name/value pair in string format. E.g. FirstName=Blake
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
public override string ToString()
{
return $"{this.Name}={this.Value}";
}
/// <summary>
/// Sets the parameter based off of a passed in string via an operator.
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
/// <remarks></remarks>
public static implicit operator Parameter(string str)
{
if (string.IsNullOrWhiteSpace(str) == true)
{
throw new Exception("The a valid parameter string. A value parameter string includes a name/value pair seperated by an equals sign.");
}
if (str.Contains("=") == false)
{
throw new Exception("The a valid parameter string. A value parameter string includes a name/value pair seperated by an equals sign.");
}
// Since there was an equals sign, we will have a name/value pair.
string[] items = str.SplitPcl("=");
return new Parameter(items[0], items[1]);
}
/// <summary>
/// Sets the string based off of the current value of the parameter.
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
/// <remarks></remarks>
public static implicit operator string(Parameter p)
{
return $"{p.Name}={p.Value}";
}
public string Name { get; set; }
public string Value { get; set; }
}
} | Java |
__author__ = 'miko'
from Tkinter import Frame
class GameState(Frame):
def __init__(self, *args, **kwargs):
self.stateName = kwargs["stateName"]
self.root = args[0]
self.id = kwargs["id"]
Frame.__init__(self, self.root.mainWindow)
self.config(
background="gold"
)
self.place(relwidth=1, relheight=1)
| Java |
<!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_24) on Fri Feb 22 14:06:12 EET 2013 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
javalabra.chess.core.impl.state (Chess 0.0.1-SNAPSHOT API)
</TITLE>
<META NAME="date" CONTENT="2013-02-22">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="javalabra.chess.core.impl.state (Chess 0.0.1-SNAPSHOT API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../javalabra/chess/core/impl/move/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../../javalabra/chess/domain/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?javalabra/chess/core/impl/state/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<H2>
Package javalabra.chess.core.impl.state
</H2>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Class Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../javalabra/chess/core/impl/state/AbstractGameState.html" title="class in javalabra.chess.core.impl.state">AbstractGameState</A></B></TD>
<TD>Abstract game state.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../javalabra/chess/core/impl/state/SelectMoveState.html" title="class in javalabra.chess.core.impl.state">SelectMoveState</A></B></TD>
<TD>State object representing state when piece on the board is selected and
game is waiting for a move to be choosen.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../javalabra/chess/core/impl/state/SelectPieceState.html" title="class in javalabra.chess.core.impl.state">SelectPieceState</A></B></TD>
<TD>State object representing state when game is waiting for piece of concrete
color to be selected.</TD>
</TR>
</TABLE>
<P>
<DL>
</DL>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../javalabra/chess/core/impl/move/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../../javalabra/chess/domain/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?javalabra/chess/core/impl/state/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2013. All Rights Reserved.
</BODY>
</HTML>
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>18 --> 19</title>
<link href="./../../assets/style.css" rel="stylesheet">
</head>
<body>
<h2>You have to be fast</h2>
<a href="./4ac3f45b236dfce453c7b08f66748497144da944c805dd71a7d9c6d6ff5efcff.html">Teleport</a>
<hr>
<a href="./../../about.md">About</a> (Spoilers! )
<script src="./../../assets/md5.js"></script>
<script>
window.currentLevel = 7;
</script>
<script src="./../../assets/script.js"></script>
</body>
</html> | Java |
from csacompendium.csa_practice.models import PracticeLevel
from csacompendium.utils.pagination import APILimitOffsetPagination
from csacompendium.utils.permissions import IsOwnerOrReadOnly
from csacompendium.utils.viewsutils import DetailViewUpdateDelete, CreateAPIViewHook
from rest_framework.filters import DjangoFilterBackend
from rest_framework.generics import CreateAPIView, ListAPIView
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from .filters import PracticeLevelListFilter
from csacompendium.csa_practice.api.practicelevel.practicelevelserializers import practice_level_serializers
def practice_level_views():
"""
Practice level views
:return: All practice level views
:rtype: Object
"""
practice_level_serializer = practice_level_serializers()
class PracticeLevelCreateAPIView(CreateAPIViewHook):
"""
Creates a single record.
"""
queryset = PracticeLevel.objects.all()
serializer_class = practice_level_serializer['PracticeLevelDetailSerializer']
permission_classes = [IsAuthenticated]
class PracticeLevelListAPIView(ListAPIView):
"""
API list view. Gets all records API.
"""
queryset = PracticeLevel.objects.all()
serializer_class = practice_level_serializer['PracticeLevelListSerializer']
filter_backends = (DjangoFilterBackend,)
filter_class = PracticeLevelListFilter
pagination_class = APILimitOffsetPagination
class PracticeLevelDetailAPIView(DetailViewUpdateDelete):
"""
Updates a record.
"""
queryset = PracticeLevel.objects.all()
serializer_class = practice_level_serializer['PracticeLevelDetailSerializer']
permission_classes = [IsAuthenticated, IsAdminUser]
lookup_field = 'slug'
return {
'PracticeLevelListAPIView': PracticeLevelListAPIView,
'PracticeLevelDetailAPIView': PracticeLevelDetailAPIView,
'PracticeLevelCreateAPIView': PracticeLevelCreateAPIView
}
| Java |
export const ADD_COCKTAIL = 'ADD_COCKTAIL';
export const LOAD_COCKTAILS = 'LOAD_COCKTAILS';
export const ADD_SPIRIT = 'ADD_SPIRIT';
export const REMOVE_SPIRIT = 'REMOVE_SPIRIT';
export const UPDATE_HUE = 'UPDATE_HUE';
| Java |
#include <algorithm>
#include <iostream>
#include "RustyFist/DrawMe.h"
#include "RustyFist/TouchSink.h"
#include "OpenGLLayer.h"
using namespace cocos2d;
using namespace std;
OpenGLLayer::OpenGLLayer()
{
}
OpenGLLayer::~OpenGLLayer()
{
}
bool OpenGLLayer::init()
{
return Layer::init();
}
cocos2d::Scene* OpenGLLayer::scene(DrawMe* drawMe, TouchSink* ts)
{
auto scene = Scene::create();
OpenGLLayer *layer = OpenGLLayer::create();
layer->setDrawMe(drawMe);
layer->setTouchSink(ts);
scene->addChild(layer);
return scene;
}
void OpenGLLayer::draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, uint32_t flags)
{
if (_drawMe)
_drawMe->draw();
}
void OpenGLLayer::setTouchSink(TouchSink* ts)
{
_ts = ts;
auto mouseEvents = EventListenerMouse::create();
mouseEvents->onMouseDown = [this](Event* e)
{
if(auto me = dynamic_cast<EventMouse*>(e))
{
if(_ts)
_ts->mouse({me->getCursorX(), me->getCursorY()});
}
};
mouseEvents->onMouseUp = [this](Event* e)
{
if(auto me = dynamic_cast<EventMouse*>(e))
{
if(_ts)
_ts->mouse({me->getCursorX(), me->getCursorY()});
}
};
mouseEvents->onMouseMove = [this](Event* e)
{
if(auto me = dynamic_cast<EventMouse*>(e))
{
if(_ts)
_ts->mouse({me->getCursorX(), me->getCursorY()});
}
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(mouseEvents, this);
}
void OpenGLLayer::onTouchesBegan(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event* unused_event)
{
sendTouch(touches);
}
void OpenGLLayer::onTouchesMoved(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event* unused_event)
{
sendTouch(touches);
}
void OpenGLLayer::onTouchesEnded(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event* unused_event)
{
sendTouch(touches);
}
void OpenGLLayer::onTouchesCancelled(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event* unused_event)
{
sendTouch(touches);
}
void OpenGLLayer::sendTouch(const std::vector<cocos2d::Touch*>& touches)
{
std::vector<::Touch> tochs;
std::transform(touches.begin(), touches.end(), back_inserter(tochs), [](cocos2d::Touch* t)
{
return ::Touch{t->getID(), t->getLocation().x, t->getLocation().y};
});
if(_ts)
_ts->touch(tochs);
}
| Java |
//
// PASConnectionTransformation.h
// ximber
//
// Created by Paul Samuels on 15/09/2014.
// Copyright (c) 2014 Paul Samuels. All rights reserved.
//
@import Foundation;
/**
* The connection transformation is a basic data structure that holds a block that is
* executed on each node found at the xpath
*/
@interface PASConnectionTransformation : NSObject
@property (nonatomic, copy, readonly) NSString *xPath;
@property (nonatomic, copy, readonly) NSString *(^keyTransformer)(NSString *key);
+ (instancetype)connectionTransformationWithXPath:(NSString *)xPath keyTransformer:(NSString *(^)(NSString *key))keyTransformer;
@end
| Java |
/* icon */
.ico-file{width: 32px;height: 32px;display: inline-block;vertical-align: middle;background: url(../img/spr-icon.png) -384px 0 no-repeat;}
.ico-bt-file{background-position: 0 0}
.ico-bt-link{background-position: -32px 0}
.ico-chm{background-position: -64px 0}
.ico-xls{background-position: -96px 0}
.ico-link{background-position: -128px 0}
.ico-pdf{background-position: -160px 0}
.ico-doc{background-position: -192px 0}
.ico-ppt{background-position: -224px 0}
.ico-txt{background-position: -256px 0}
.ico-word{background-position: -288px 0}
.ico-install{background-position: -320px 0}
.ico-music{background-position: -352px 0}
.ico-unknow{background-position: -384px 0}
.ico-pic{background-position: -416px 0}
.ico-apk{background-position: -448px 0}
.ico-exe{background-position: -480px 0}
.ico-ipa{background-position: -512px 0}
.ico-ipsw{background-position: -544px 0}
.ico-iso{background-position: -576px 0}
.ico-group{background-position: -608px 0}
.ico-video{background-position: -832px 0}
.ico-avi{background-position: -640px 0}
.ico-flv{background-position: -672px 0}
.ico-mkv{background-position: -704px 0}
.ico-mov{background-position: -736px 0}
.ico-mp4{background-position: -768px 0}
.ico-mpg{background-position: -800px 0}
.ico-rm{background-position: -864px 0}
.ico-rmvb{background-position: -896px 0}
.ico-wmv{background-position: -928px 0}
.ico-rar{background-position: -960px 0}
/* 会员图标 vip */
.icvip{display:inline-block;width:42px;height:12px;background:url(../img/ic_vip.png) no-repeat 0 999em;overflow:hidden;vertical-align:-1px;margin: 0 0 0 2px;}
.icvip00{width: 36px;background-position: 0 0} .icvip01{background-position: -37px 0} .icvip02{background-position: -80px 0} .icvip03{background-position: -123px 0} .icvip04{background-position: -166px 0} .icvip05{background-position: -209px 0} .icvip06{background-position: -252px 0} .icvip00hui{background-position: 0 -18px}
.icvip00hui{width: 35px;background-position: 0px -18px}.icvip01hui{background-position: -37px -18px} .icvip02hui{background-position: -80px -18px} .icvip03hui{background-position: -123px -18px} .icvip04hui{background-position: -166px -18px} .icvip05hui{background-position: -209px -18px} .icvip06hui{background-position: -252px -18px}
/* gold vip */
.icgold00{width: 35px;background-position: 0 -36px} .icgold01{background-position: -37px -36px} .icgold02{background-position: -80px -36px} .icgold03{background-position: -123px -36px} .icgold04{background-position: -166px -36px} .icgold05{background-position: -209px -36px} .icgold06{background-position: -252px -36px} .icgold07{background-position: -295px -36px} .icgold00hui{background-position: 0 -54px}
.icgold00hui{width: 35px;background-position: 0px -54px} .icgold01hui{background-position: -37px -54px} .icgold02hui{background-position: -80px -54px} .icgold03hui{background-position: -123px -54px} .icgold04hui{background-position: -166px -54px} .icgold05hui{background-position: -209px -54px} .icgold06hui{background-position: -252px -54px} .icgold07hui{background-position: -295px -54px}
/* super vip */
.icsuper00{width: 35px;background-position: 0 -72px} .icsuper01{background-position: -37px -72px} .icsuper02{background-position: -80px -72px} .icsuper03{background-position: -123px -72px} .icsuper04{background-position: -166px -72px} .icsuper05{background-position: -209px -72px} .icsuper06{background-position: -252px -72px} .icsuper07{background-position: -295px -72px} .icsuper00hui{background-position: 0 -90px}
.icsuper00hui{width: 35px;background-position: 0px -90px} .icsuper01hui{background-position: -37px -90px} .icsuper02hui{background-position: -80px -90px} .icsuper03hui{background-position: -123px -90px} .icsuper04hui{background-position: -166px -90px} .icsuper05hui{background-position: -209px -90px}
/* another */
.icnian{width:12px;height:12px; background-position: 0px -108px;} .icnianhui{width:12px;height:12px; background-position: 0px -128px} .icdongjie{width:16px;height:16px; background-position: -19px -109px}
.icdongjiehui{width:16px;height:16px; background-position: -19px -128px} .icshuai{width:16px;height:16px; background-position: -38px -108px} .icshuaihui{width:16px;height:16px; background-position: -38px -128px}
.icqiye{width:16px;height:16px; background-position: -57px -109px} .icqiyehui{width:16px;height:16px; background-position: -57px -128px}
.ichongren{width:16px;height:16px; background-position: -76px -109px} .ichongrenhui{width:16px;height:16px; background-position: -76px -128px}
.icbao{width:16px;height:16px; background-position: -95px -109px} .icbaohui{width:16px;height:16px; background-position: -95px -128px}
.icxun{width:15px;height:16px; background-position: -116px -109px} .icxunhui{width:15px;height:16px; background-position: -116px -128px}
.icgold{width:15px;height:16px; background-position: -136px -109px} .icgoldhui{width:15px;height:14px; background-position: -136px -128px}
.icgrow{width:12px;height:14px; background-position: -155px -109px;} .icdown{width:12px;height:14px; background-position: -155px -128px;}
.ickuainiao{background-position: -338px 0;width: 36px;}
.ickuainiaohui{background-position: -338px -18px}
.icshangxing{background-position: -380px 0;width: 36px}
.icshangxinghui{background-position: -380px -18px;}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
#include "tcp_socket.h"
using namespace easynet;
//TCPSocket 已连接的服务器
TCPSocket::TCPSocket(EPOLLSvrPtr s) {
socket_handler_ = nullptr;
svr_ = s;
msg_ = nullptr;
step_ = READ_HEAD;
}
void TCPSocket::SetHandler(On_Socket_Handler h){
socket_handler_ = h;
}
void TCPSocket::OnNetMessage(){
if( nullptr == socket_handler_){
LOG(FATAL) << "tcpsocket handler is nullptr!";
return;
}
//char *buff = svr_.get()->buff_; //对数组操作一定要注意, 会有越界的可能
for(;;){
char *buff = svr_.get()->buff_;
//一直读, 直到出错
int32_t ret = NetPackage::Read(peer_.fd_, buff, MAX_SOCK_BUFF);
//LOG(INFO) << "read ok ret[" << ret << "]";
if(0 == ret ){
LOG(INFO) << "connection closed by peer fd[" << peer_.fd_ << "]";
this->KickOut();
return;
}
if( ret < 0 ){
if( EAGAIN == errno || EWOULDBLOCK == errno ){
//再次read, buff将从头开始填充
//buff = svr_.get()->buff_;
//continue;
return;
}else{
LOG(INFO) << "read fail! fd[" << peer_.fd_ << "] errno[" << errno << "] msg[" << strerror(errno) << "]";
this->KickOut();
return;
}
}
int32_t more_data = ret;
while( more_data > 0){
if( nullptr == peer_.buff_ ){
peer_.buff_ = std::make_shared<DataBuffer>(peer_.fd_, HEADER_SZ);
}
auto data_buffer = peer_.buff_.get();
int32_t need_data = data_buffer->NeedData();
//读取包头
if( READ_HEAD == step_ ){
if( more_data < need_data ) {
//包头没有读完整
data_buffer->AddData(more_data, buff);
return;
}
data_buffer->AddData(need_data, buff);
//指向body的头指针, 向前添加已经读过的内存
buff += need_data;
more_data = (more_data - need_data) < 0 ? 0:(more_data - need_data);
msg_ = (MSG* )data_buffer->GetBuffPtr();
if(VERSION != msg_->header.version_ || IDENTIFY != msg_->header.identify_){
LOG(ERROR) << "version or identify is not fit! kick out client fd[" << peer_.fd_ << "] version["
<< (int)msg_->header.version_ << "] current version[" << (int)VERSION<<"]" << "identify["
<< (int)msg_->header.identify_ << "] current identify[" << (int)IDENTIFY << "]";
this->KickOut();
LOG(INFO) << "receive msg count[" << m.GetRecvPack() << "]";
return;
}
msg_->header.length_ = ntohs(msg_->header.length_);
msg_->header.type_ = ntohs(msg_->header.type_);
//为body 申请内存
data_buffer->Resize(msg_->header.length_ + HEADER_SZ);
//重新申请内存后, 以前的msg_指向的内容不能再使用了
msg_ = (MSG* )data_buffer->GetBuffPtr();
need_data = data_buffer->NeedData();
step_ = READ_BODY;
}
//现在的step 肯定是 READ_BODY
if( more_data > 0 ) {
//读取body
if(more_data < need_data) {
data_buffer->AddData(more_data, buff);
return;
}
data_buffer->AddData(need_data, buff);
more_data = (more_data - need_data) < 0 ? 0:(more_data - need_data);
//buff读取后指针后移
buff += need_data;
m.AddRecvPack();
//客户程序只需要截获到数据信息就行, 不用关心包头
char *pMsg = (char* )(data_buffer->GetBuffPtr());
pMsg += sizeof(HEADER);
auto f = socket_handler_;
try{
f(this->getID(), pMsg,msg_->header.length_, msg_->header.type_);
}catch(...){
LOG(ERROR) << "tcpsocket handler run fail!";
}
//自动删除已经用过的packet
auto tmp = std::move(peer_.buff_);
tmp = nullptr;
peer_.buff_ = nullptr;//是不是多此一举, 就是多此一举, move 后peer_buff_ 会为nullptr
//读取新的包头
step_ = READ_HEAD;
}
}
}
}
void TCPSocket::KickOut() {
IPlayer::KickOut();
//TODO 需要再 EPOLLSvr 的map 中删除事件events_map_ 和连接信息 player_map_
}
| Java |
{% extends 'base.html' %}
{% block content %}
<div class="row">
<div class="col-md-12">
<form action="/login" method="post">
{{ form.csrf_token }}
{{ form.next(value=next) }}
<div class="form-group">
{{ form.username.label }}
{{ form.username(class='form-control') }}
</div>
<div class="form-group">
{{ form.password.label }}
{{ form.password(class='form-control') }}
</div>
<div class="form-group">
<input type="submit" class="form-control" value="Login">
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-md-12">
{% with messages = get_flashed_messages() %}
{% for message in messages %}
<div class="alert alert-info">{{ message }}</div>
{% endfor %}
{% endwith %}
</div>
</div>
{% endblock %} | Java |
using Android.OS;
using Android.Text;
using Android.Util;
using REKT.Graphics;
using REKT.Graphics.Unsafe;
using REKT.DI;
using SkiaSharp;
using System;
using System.Text;
using D = System.Diagnostics.Debug;
using NativeActivity = Android.App.Activity;
using NativeBitmap = Android.Graphics.Bitmap;
using NativeBitmapFactory = Android.Graphics.BitmapFactory;
using NativeContext = Android.Content.Context;
using NativeRect = Android.Graphics.Rect;
using NativeDialog = Android.Support.V7.App.AlertDialog;
using NativeProgressDialog = Android.App.ProgressDialog;
using NativeColour = Android.Graphics.Color;
using NativeArrayAdapter = Android.Widget.ArrayAdapter;
using NativeView = Android.Views.View;
using System.Collections;
using NativeThread = System.Threading.Thread;
namespace REKT
{
public static class AndroidExtensions
{
/////////////////////////////////////////////////////////////////////
// STRINGS
/////////////////////////////////////////////////////////////////////
public static ISpanned ToSpannedHTML(this string rawHtml)
{
ISpanned html;
if (AndroidPlatform.Version >= BuildVersionCodes.N)
html = Html.FromHtml(rawHtml, FromHtmlOptions.ModeLegacy);
else
{
#pragma warning disable CS0618 //deprecation
html = Html.FromHtml(rawHtml);
#pragma warning restore CS0618
}
return html;
}
/////////////////////////////////////////////////////////////////////
// CONTEXTS
/////////////////////////////////////////////////////////////////////
public static SKColor ThemeColour(this NativeContext context, int themeColourID)
{
if (context == null)
throw new ArgumentNullException("context");
using (var typedValue = new TypedValue())
{
var theme = context.Theme;
theme.ResolveAttribute(themeColourID, typedValue, true);
var data = typedValue.Data;
return new SKColor(
(byte)NativeColour.GetRedComponent(data),
(byte)NativeColour.GetGreenComponent(data),
(byte)NativeColour.GetBlueComponent(data),
(byte)NativeColour.GetAlphaComponent(data));
}
}
public static NativeBitmap BitmapResource(this NativeContext context, int bitmapResourceID)
{
using (var opts = new NativeBitmapFactory.Options())
{
opts.InPreferQualityOverSpeed = true;
return NativeBitmapFactory.DecodeResource(context.Resources, bitmapResourceID, opts);
}
}
public static SKBitmap BitmapResourceSkia(this NativeContext context, int bitmapResourceID)
{
using (var nativeBmp = context.BitmapResource(bitmapResourceID))
return nativeBmp.ToSkia();
}
private static void RunOnUIThreadIfPossible(this NativeContext context, Action action)
{
if (context is NativeActivity activity)
activity.RunOnUiThread(action);
else
action();
}
public static void ShowYesNoDialog(this NativeContext context, string title, string text,
Action yesAction = null, Action noAction = null)
{
if (context == null)
throw new ArgumentNullException("context");
context.RunOnUIThreadIfPossible(() =>
{
using (var builder = new NativeDialog.Builder(context))
{
builder.SetTitle((title ?? "").Trim());
builder.SetMessage((text ?? "").Trim());
builder.SetCancelable(false);
builder.SetPositiveButton("Yes", (s, e) => { yesAction?.Invoke(); });
builder.SetNegativeButton("No", (s, e) => { noAction?.Invoke(); });
using (var dialog = builder.Create())
dialog.Show();
}
});
}
public static void ShowOKDialog(this NativeContext context, string title, string text, Action okAction = null)
{
if (context == null)
throw new ArgumentNullException("context");
context.RunOnUIThreadIfPossible(() =>
{
using (var builder = new NativeDialog.Builder(context))
{
builder.SetTitle((title ?? "").Trim());
builder.SetMessage((text ?? "").Trim());
builder.SetCancelable(false);
builder.SetPositiveButton(Android.Resource.String.Ok, (s, e) => { okAction?.Invoke(); });
using (var dialog = builder.Create())
dialog.Show();
}
});
}
public static void ShowWaitDialog(this NativeContext context, string title, string text, Action asyncTask)
{
if (context == null)
throw new ArgumentNullException("context");
if (asyncTask == null)
throw new ArgumentNullException("asyncTask");
context.RunOnUIThreadIfPossible(() =>
{
var dialog = NativeProgressDialog.Show(context, (title ?? "").Trim(), (text ?? "").Trim(), true, false);
new NativeThread(() =>
{
asyncTask?.Invoke();
dialog.Dismiss();
dialog.Dispose();
}).Start();
});
}
public static void ShowListDialog(this NativeContext context, string title, IList data, Action<int> selectionAction,
Action cancelAction = null)
{
if (context == null)
throw new ArgumentNullException("context");
if (selectionAction == null)
throw new ArgumentNullException("selectionAction");
if (data == null)
throw new ArgumentNullException("data");
context.RunOnUIThreadIfPossible(() =>
{
using (var builder = new NativeDialog.Builder(context))
{
var adapter = new NativeArrayAdapter(context, Android.Resource.Layout.SimpleListItem1, data);
builder.SetTitle((title ?? "").Trim())
.SetAdapter(adapter, (s, e) => { selectionAction.Invoke(e.Which); });
if (cancelAction != null)
builder.SetCancelable(true).SetNegativeButton(Android.Resource.String.Cancel, (s, e) => { cancelAction.Invoke(); });
else
builder.SetCancelable(false);
using (var dialog = builder.Create())
dialog.Show();
}
});
}
public static void ShowCustomDialog(this Activity activity, string title, int viewResID,
Action<NativeView> initAction = null,
Action<NativeView> okAction = null,
Action<NativeView> cancelAction = null)
{
if (activity == null)
throw new ArgumentNullException("context");
activity.RunOnUIThreadIfPossible(() =>
{
using (var builder = new NativeDialog.Builder(activity))
{
builder.SetTitle((title ?? "").Trim());
var view = activity.LayoutInflater.Inflate(viewResID, null);
initAction?.Invoke(view);
builder.SetView(view);
builder.SetPositiveButton(Android.Resource.String.Ok,
(s, e) => { okAction?.Invoke(view); });
if (cancelAction != null)
builder.SetCancelable(true).SetNegativeButton(Android.Resource.String.Cancel,
(s, e) => { cancelAction.Invoke(view); });
else
builder.SetCancelable(false);
using (var dialog = builder.Create())
dialog.Show();
}
});
}
public static void Toast(this NativeContext context, string text)
{
Android.Widget.Toast.MakeText(context, text, Android.Widget.ToastLength.Long).Show();
}
public static void LaunchWebsite(this NativeContext context, string uri)
{
using (var _uri = Android.Net.Uri.Parse(uri))
using (var intent = new Android.Content.Intent(Android.Content.Intent.ActionView, _uri))
{
intent.AddFlags(Android.Content.ActivityFlags.NewTask);
intent.AddFlags(Android.Content.ActivityFlags.NoHistory);
intent.AddFlags(Android.Content.ActivityFlags.ExcludeFromRecents);
context.StartActivity(intent);
}
}
public static ISpanned GetSpannedHTML(this NativeContext context, int resid)
{
return context.GetString(resid).ToSpannedHTML();
}
public static void LaunchAppSettings(this NativeContext context)
{
using (var _uri = Android.Net.Uri.Parse("package:" + context.PackageName))
using (var intent = new Android.Content.Intent("android.settings.APPLICATION_DETAILS_SETTINGS", _uri))
{
intent.AddFlags(Android.Content.ActivityFlags.NewTask);
intent.AddFlags(Android.Content.ActivityFlags.NoHistory);
intent.AddFlags(Android.Content.ActivityFlags.ExcludeFromRecents);
context.StartActivity(intent);
}
}
/////////////////////////////////////////////////////////////////////
// ACTIVITIES
/////////////////////////////////////////////////////////////////////
public static float CanvasScaleHint(this NativeActivity activity)
{
using (var displayMetrics = new DisplayMetrics())
{
activity.WindowManager.DefaultDisplay.GetMetrics(displayMetrics);
if (displayMetrics.ScaledDensity.IsZero()) //can this even happen??
return 1.0f;
return (displayMetrics.ScaledDensity / 3.0f).Clamp(0.4f, 1.5f);
}
}
public static void With<T>(this NativeActivity activity, int id, Action<T> viewAction) where T : Android.Views.View
{
using (var view = activity.FindViewById<T>(id))
viewAction(view);
}
/////////////////////////////////////////////////////////////////////
// SKIA
/////////////////////////////////////////////////////////////////////
public static NativeRect ToREKT(this SKRect rect)
{
return new NativeRect((int)rect.Left, (int)rect.Top,
(int)rect.Right, (int)rect.Bottom);
}
public static NativeColour ToNative(this SKColor col)
{
return new NativeColour(col.Red, col.Green, col.Blue, col.Alpha);
}
public static SKColor ToREKT(this NativeColour col)
{
return new SKColor(col.R, col.G, col.B, col.A);
}
/////////////////////////////////////////////////////////////////////
// BITMAPS
/////////////////////////////////////////////////////////////////////
public static SKBitmap ToSkia(this NativeBitmap source)
{
if (source == null)
throw new ArgumentNullException("source");
//init destination bitmap
var output = new SKBitmap(
source.Width,
source.Height,
SKColorType.Rgba8888,
SKAlphaType.Unpremul
);
//get source pixels
//"The returned colors are non-premultiplied ARGB values in the sRGB color space.",
//per https://developer.android.com/reference/android/graphics/Bitmap.html
int[] sourcePixels = new int[source.Width * source.Height];
source.GetPixels(sourcePixels, 0, source.Width, 0, 0, source.Width, source.Height);
//copy into destination
try
{
output.LockPixels();
var buffer = output.GetPixels();
unsafe
{
int* firstPixelAddr = (int*)buffer.ToPointer();
System.Threading.Tasks.Parallel.For(0, output.Height, (y) =>
{
int p = y * output.Width;
int* pixel = firstPixelAddr + p;
for (int x = 0; x < output.Width; x++, p++, pixel++)
*pixel = sourcePixels[p].SwapBytes02();
});
}
output.UnlockPixels();
}
catch (Exception e)
{
e.WriteToLog();
output.Dispose();
throw;
}
return output;
}
public static Bitmap ToREKT(this NativeBitmap source)
{
if (source == null)
throw new ArgumentNullException("source");
#if DEBUG
StringBuilder sb = new StringBuilder("Bitmap: constructing from Android.Graphics.Bitmap:");
sb.AppendLine();
sb.AppendFormattedLine("Dimensions: {0} x {1}", source.Width, source.Height);
sb.AppendFormattedLine("AllocationByteCount: {0}", source.AllocationByteCount);
sb.AppendFormattedLine("ByteCount: {0}", source.ByteCount);
sb.AppendFormattedLine("RowBytes: {0}", source.RowBytes);
sb.AppendFormattedLine("Density: {0}", source.Density);
sb.AppendFormattedLine("HasAlpha: {0}", source.HasAlpha);
sb.AppendFormattedLine("IsPremultiplied: {0}", source.IsPremultiplied);
D.WriteLine(sb);
#endif
//init destination bitmap
var output = new Bitmap(source.Width, source.Height, SKColorType.Rgba8888);
//get source pixels
//"The returned colors are non-premultiplied ARGB values in the sRGB color space.",
//per https://developer.android.com/reference/android/graphics/Bitmap.html
int[] sourcePixels = new int[source.Width * source.Height];
source.GetPixels(sourcePixels, 0, source.Width, 0, 0, source.Width, source.Height);
//copy into destination
try
{
output.Lock((buffer) =>
{
unsafe
{
byte* firstPixelAddr = (byte*)buffer.ToPointer();
Thread.Distribute((threadIndex, threadCount) =>
{
for (long y = threadIndex; y < output.Height; y += threadCount)
{
long p = y * output.Width;
for (long x = 0; x < output.Width; x++, p++)
output.SetPixel(firstPixelAddr, x, y, ((uint)sourcePixels[p]));
}
});
}
});
}
catch (Exception e)
{
e.WriteToLog();
output.Dispose();
throw;
}
return output;
}
/////////////////////////////////////////////////////////////////////
// UUIDs
/////////////////////////////////////////////////////////////////////
public static bool Equals(this Java.Util.UUID uuid, string uuidString)
{
if (uuid == null)
throw new ArgumentNullException("uuid");
if (uuidString == null)
throw new ArgumentNullException("uuidString");
return uuid.ToString().ToUpper() == uuidString.ToUpper();
}
}
} | Java |
// animating the scroll effect
$('.screenshots').on('click', function(e){
e.preventDefault();
$("html, body").animate({ scrollTop: "950px", duration: 500 });
});
| Java |
#include "strm.h"
#include <math.h>
static int
num_plus(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
strm_value x, y;
strm_get_args(strm, argc, args, "NN", &x, &y);
if (strm_int_p(x) && strm_int_p(y)) {
*ret = strm_int_value(strm_value_int(x)+strm_value_int(y));
return STRM_OK;
}
if (strm_number_p(x) && strm_number_p(y)) {
*ret = strm_float_value(strm_value_float(x)+strm_value_float(y));
return STRM_OK;
}
return STRM_NG;
}
static int
num_minus(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
if (argc == 1) {
if (strm_int_p(args[0])) {
*ret = strm_int_value(-strm_value_int(args[0]));
return STRM_OK;
}
if (strm_float_p(args[0])) {
*ret = strm_float_value(-strm_value_float(args[0]));
return STRM_OK;
}
}
else {
strm_value x, y;
strm_get_args(strm, argc, args, "NN", &x, &y);
if (strm_int_p(x) && strm_int_p(y)) {
*ret = strm_int_value(strm_value_int(x)-strm_value_int(y));
return STRM_OK;
}
if (strm_number_p(x) && strm_number_p(y)) {
*ret = strm_float_value(strm_value_float(x)-strm_value_float(y));
return STRM_OK;
}
}
return STRM_NG;
}
static int
num_mult(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
strm_value x, y;
strm_get_args(strm, argc, args, "NN", &x, &y);
if (strm_int_p(x) && strm_int_p(y)) {
*ret = strm_int_value(strm_value_int(x)*strm_value_int(y));
return STRM_OK;
}
*ret = strm_float_value(strm_value_float(x)*strm_value_float(y));
return STRM_OK;
}
static int
num_div(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
double x, y;
strm_get_args(strm, argc, args, "ff", &x, &y);
*ret = strm_float_value(x/y);
return STRM_OK;
}
static int
num_bar(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
strm_value x, y;
strm_get_args(strm, argc, args, "ii", &x, &y);
*ret = strm_int_value(strm_value_int(x)|strm_value_int(y));
return STRM_OK;
}
static int
num_mod(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
strm_value x;
strm_int y;
strm_get_args(strm, argc, args, "Ni", &x, &y);
if (strm_int_p(x)) {
*ret = strm_int_value(strm_value_int(x)%y);
return STRM_OK;
}
if (strm_float_p(x)) {
*ret = strm_float_value(fmod(strm_value_float(x), y));
return STRM_OK;
}
return STRM_NG;
}
static int
num_gt(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
double x, y;
strm_get_args(strm, argc, args, "ff", &x, &y);
*ret = strm_bool_value(x>y);
return STRM_OK;
}
static int
num_ge(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
double x, y;
strm_get_args(strm, argc, args, "ff", &x, &y);
*ret = strm_bool_value(x>=y);
return STRM_OK;
}
static int
num_lt(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
double x, y;
strm_get_args(strm, argc, args, "ff", &x, &y);
*ret = strm_bool_value(x<y);
return STRM_OK;
}
static int
num_le(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
double x, y;
strm_get_args(strm, argc, args, "ff", &x, &y);
*ret = strm_bool_value(x<=y);
return STRM_OK;
}
static int
num_number(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
strm_get_args(strm, argc, args, "N", ret);
return STRM_OK;
}
strm_state* strm_ns_number;
void
strm_number_init(strm_state* state)
{
strm_ns_number = strm_ns_new(NULL, "number");
strm_var_def(strm_ns_number, "+", strm_cfunc_value(num_plus));
strm_var_def(strm_ns_number, "-", strm_cfunc_value(num_minus));
strm_var_def(strm_ns_number, "*", strm_cfunc_value(num_mult));
strm_var_def(strm_ns_number, "/", strm_cfunc_value(num_div));
strm_var_def(strm_ns_number, "%", strm_cfunc_value(num_mod));
strm_var_def(strm_ns_number, "|", strm_cfunc_value(num_bar));
strm_var_def(strm_ns_number, "<", strm_cfunc_value(num_lt));
strm_var_def(strm_ns_number, "<=", strm_cfunc_value(num_le));
strm_var_def(strm_ns_number, ">", strm_cfunc_value(num_gt));
strm_var_def(strm_ns_number, ">=", strm_cfunc_value(num_ge));
strm_var_def(state, "number", strm_cfunc_value(num_number));
}
| Java |
<html>
<head>
</head>
<body>
<h2>
Their Antiquity
</h2>
<span class="oldenglish">
Who
</span>
<span class="oldenglish">
were
</span>
<span class="oldenglish">
the
</span>
originall
<span class="oldenglish">
writers
</span>
<span class="oldenglish">
of
</span>
<span class="oldenglish">
the
</span>
severall
<span class="oldenglish">
Books
</span>
<span class="oldenglish">
of
</span>
<span class="oldenglish">
Holy
</span>
Scripture, has
<span class="english">
not
</span>
been
<span class="oldenglish">
made
</span>
<span class="oldfrench">
evident
</span>
<span class="oldenglish">
by
</span>
<span class="oldenglish">
any
</span>
<span class="oldfrench">
sufficient
</span>
<span class="oldfrench">
testimony
</span>
<span class="oldenglish">
of
</span>
<span class="oldenglish">
other
</span>
History, (which
<span class="oldenglish">
is
</span>
<span class="oldenglish">
the
</span>
<span class="oldenglish">
only
</span>
<span class="oldfrench">
proof
</span>
<span class="oldenglish">
of
</span>
<span class="oldfrench">
matter
</span>
<span class="oldenglish">
of
</span>
fact);
<span class="english">
nor
</span>
<span class="oldenglish">
can
</span>
<span class="oldenglish">
be
</span>
<span class="oldenglish">
by
</span>
<span class="oldenglish">
any
</span>
<span class="oldfrench">
arguments
</span>
<span class="oldenglish">
of
</span>
naturall Reason;
<span class="oldenglish">
for
</span>
<span class="oldfrench">
Reason
</span>
serves
<span class="oldenglish">
only
</span>
<span class="oldenglish">
to
</span>
<span class="latin">
convince
</span>
<span class="oldenglish">
the
</span>
<span class="oldenglish">
truth
</span>
(not
<span class="oldenglish">
of
</span>
fact, but)
<span class="oldenglish">
of
</span>
consequence.
<span class="oldenglish">
The
</span>
<span class="oldenglish">
light
</span>
<span class="oldenglish">
therefore
</span>
<span class="oldenglish">
that
</span>
<span class="oldenglish">
must
</span>
<span class="oldfrench">
guide
</span>
<span class="oldenglish">
us
</span>
<span class="oldenglish">
in
</span>
<span class="oldenglish">
this
</span>
question,
<span class="oldenglish">
must
</span>
<span class="oldenglish">
be
</span>
<span class="oldenglish">
that
</span>
<span class="oldenglish">
which
</span>
<span class="oldenglish">
is
</span>
<span class="oldenglish">
held
</span>
<span class="oldenglish">
out
</span>
<span class="oldenglish">
unto
</span>
<span class="oldenglish">
us
</span>
<span class="oldenglish">
from
</span>
<span class="oldenglish">
the
</span>
<span class="oldenglish">
Bookes
</span>
themselves:
<span class="oldenglish">
And
</span>
<span class="oldenglish">
this
</span>
light,
<span class="oldenglish">
though
</span>
<span class="oldenglish">
it
</span>
<span class="americanenglish">
show
</span>
<span class="oldenglish">
us
</span>
<span class="english">
not
</span>
<span class="oldenglish">
the
</span>
<span class="oldenglish">
writer
</span>
<span class="oldenglish">
of
</span>
<span class="oldenglish">
every
</span>
book,
<span class="oldenglish">
yet
</span>
<span class="oldenglish">
it
</span>
<span class="oldenglish">
is
</span>
<span class="english">
not
</span>
unusefull
<span class="oldenglish">
to
</span>
<span class="oldenglish">
give
</span>
<span class="oldenglish">
us
</span>
<span class="english">
knowledge
</span>
<span class="oldenglish">
of
</span>
<span class="oldenglish">
the
</span>
time,
<span class="dutch">
wherein
</span>
<span class="oldnorse">
they
</span>
<span class="oldenglish">
were
</span>
written.
</body>
</html> | Java |
'use strict';
var path = require('path');
module.exports = path.join.bind(path, __dirname, '..');
| Java |
---
title: Svett
tag: svett
active: false
url: https://www.facebook.com/svettifi/
template: association.pug
---
Navnet Svett spiller på den populært utbredte stereotypen av informatikere. Mange ser på informatikere som svette «nerder». Vi velger å spille videre på dette med et glimt i øyet.
**Formål:** Foreningens formål å fremme studenters interesse for spesielle informatiske fagområder. Fokuset vil ligge på å dele dybdekunnskap om fagrelaterte emner i sosiale omgivelser.
**Aktiviteter:** Vi arrangerer foredrag, workshops og konkurranser. Ved å fokusere på dybdekunnskap håper vi å kunne åpne flere studenters øyne for mer spesialiserte deler av pensum. Vi vil forsøke å introdusere medstudenter til dypere og mer tekniske aspekter ved den informatiske verden mens vi har det gøy. | Java |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Master thesis presentation – OpenLaws</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Presentation of Master thesis @CEID">
<meta name="author" content="Kostas Plessas">
<meta name="keywords" content="publications">
<link rel="canonical" href="http://www.openlaws.gr/publications/2016/10/19/master-thesis-presentation/">
<!-- Custom CSS -->
<link rel="stylesheet" href="/css/pixyll.css" type="text/css">
<!-- Fonts -->
<link href='//fonts.googleapis.com/css?family=Merriweather:900,900italic,300,300italic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Lato:900,300' rel='stylesheet' type='text/css'>
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<!-- Open Graph -->
<!-- From: https://github.com/mmistakes/hpstr-jekyll-theme/blob/master/_includes/head.html -->
<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="Master thesis presentation">
<meta property="og:description" content="A Project Opening Greek Legislation to Citizens">
<meta property="og:url" content="http://www.openlaws.gr/publications/2016/10/19/master-thesis-presentation/">
<meta property="og:site_name" content="OpenLaws">
<!-- Icons -->
<link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-touch-icon-60x60.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-touch-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180x180.png">
<link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="/android-chrome-192x192.png" sizes="192x192">
</head>
<body class="">
<div class="site-wrap">
<header class="site-header px2 px-responsive">
<div class="mt2 wrap">
<div class="measure">
<div><a href="http://www.openlaws.gr"><img src="/images/logo.png" alt="logo"/></a></div>
<nav class="site-nav right">
<a href="/about/">About</a>
<a href="/roadmap/">Roadmap</a>
<!--<a href="/contact/">Contact</a>-->
</nav>
<div class="clearfix"></div>
<div class="social-icons">
<div class="right">
<a class="fa fa-github" href="https://github.com/OpenLawsGR"></a>
<a class="fa fa-rss" href="/feed.xml"></a>
<a class="fa fa-twitter" href="https://twitter.com/OpenLawsGR"></a>
<a class="fa fa-envelope" href="mailto:kplessas@ceid.upatras.gr"></a>
</div>
<div class="right">
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
</header>
<div class="post p2 p-responsive wrap" role="main">
<div class="measure">
<div class="post-header mb2">
<h1>Master thesis presentation</h1>
<span class="post-meta">Oct 19, 2016</span><br>
<span class="post-meta small">1 minute read</span>
</div>
<article class="post-content">
<p>This project is implemented in the framework of a Master thesis for the postgraduate program Computer Science and Technology at the <a href="https://www.ceid.upatras.gr/en">Department of Computer Engineering and Informatics</a> of the <a href="http://www.upatras.gr/en">University of Patras</a>, which is supervised by <a href="http://athos.cti.gr/garofalakis/index_en.htm">Prof. John Garofalakis</a> and postdoctoral researcher <a href="http://www.plessas.info/index.php/home-en/">Athanasios Plessas</a>.</p>
<p>Last week, the defense presentation of the thesis took place successfully.</p>
<p><img src="/images/master_thesis_presentation.jpg" alt="Master thesis presentation"></p>
<p>The text of the thesis (in Greek) can be found <a href="https://dl.dropboxusercontent.com/u/104921582/K.Plessas_Master_Thesis.pdf">here</a>.</p>
<p>The presentation (also in Greek) can be found <a href="https://dl.dropboxusercontent.com/u/104921582/K.Plessas_Master_Thesis_Presentation.pdf">here</a>. </p>
</article>
<div class="share-page">
Share this post!
<div class="share-links">
<a class = "fa fa-facebook" href="https://facebook.com/sharer.php?u=http://www.openlaws.gr/publications/2016/10/19/master-thesis-presentation/" rel="nofollow" target="_blank" title="Share on Facebook"></a>
<a class="fa fa-twitter" href="https://twitter.com/intent/tweet?text=Master thesis presentation&url=http://www.openlaws.gr/publications/2016/10/19/master-thesis-presentation/" rel="nofollow" target="_blank" title="Share on Twitter"></a>
<a class="fa fa-google-plus" href="https://plus.google.com/share?url=http://www.openlaws.gr/publications/2016/10/19/master-thesis-presentation/" rel="nofollow" target="_blank" title="Share on Google+"></a>
<a class="fa fa-linkedin" href="http://www.linkedin.com/shareArticle?url=http://www.openlaws.gr/publications/2016/10/19/master-thesis-presentation/&title=Master thesis presentation" rel="nofollow" target="_blank" title="Share on LinkedIn"></a>
<a class = "fa fa-hacker-news" onclick="parent.postMessage('submit','*')" href="https://news.ycombinator.com/submitlink?u=http://www.openlaws.gr/publications/2016/10/19/master-thesis-presentation/&t=Master thesis presentation" rel="nofollow" target="_blank" title="Share on Hacker News"></a>
</div>
</div>
<div id="disqus_thread"></div>
<script type="text/javascript">
var disqus_shortname = 'OpenLawsGR';
var disqus_identifier = '/publications/2016/10/19/master-thesis-presentation';
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>
</div>
</div>
<footer class="footer">
<div class="p2 wrap">
<div class="measure mt1 center">
<small>
Based on <a href="https://github.com/johnotander/pixyll">Pixyll</a> theme for <a href="http://jekyllrb.com/">Jekyll</a>. This site is not affiliated in any way to <a href="http://www.openlaws.eu">openlaws.eu</a>.
</small>
</div>
</div>
</footer>
</body>
</html>
| Java |
<?php
/*
* This file is part of the Asset Injection package, an RunOpenCode project.
*
* (c) 2015 RunOpenCode
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace RunOpenCode\AssetsInjection\Tests\Mockup;
use RunOpenCode\AssetsInjection\Contract\Compiler\CompilerPassInterface;
use RunOpenCode\AssetsInjection\Contract\ContainerInterface;
use RunOpenCode\AssetsInjection\Library\LibraryDefinition;
use RunOpenCode\AssetsInjection\Value\CompilerPassResult;
/**
* Class DummyCompilerPass
*
* Dummy compiler pass which will add definition with given name to container in order to check validity of executed test.
*
* @package RunOpenCode\AssetsInjection\Tests\Mockup
*/
final class DummyCompilerPass implements CompilerPassInterface
{
/**
* @var string
*/
private $definitionTestNameMarker;
/**
* @var bool
*/
private $stopProcessing;
/**
* A constructor.
*
* @param string $definitionTestNameMarker LibraryDefinition marker name to add to container.
* @param bool|false $stopProcessing Should compilation be stopped.
*/
public function __construct($definitionTestNameMarker, $stopProcessing = false)
{
$this->definitionTestNameMarker = $definitionTestNameMarker;
$this->stopProcessing = $stopProcessing;
}
/**
* {@inheritdoc}
*/
public function process(ContainerInterface $container)
{
$container->getLibraries()->addDefinition(new LibraryDefinition($this->definitionTestNameMarker));
return new CompilerPassResult($container, $this->stopProcessing);
}
} | Java |
---
layout: default
title: Pegmatite
github: CompilerTeaching/Pegmatite
---
Pegmatite design overview
-------------------------
This is a fork and extensive rewrite of Achilleas Margaritis's ParserLib. It
has the following goals:
- Idiomatic C++11
- Simple use
- Reuseable, reentrant grammars with multiple action delegates
- No dependency on RTTI / exceptions (usable in embedded contexts)
It has the following explicit non-goals:
- High performance (ease of use or modification should not be sacrificed in the
name of performance)
- Compatibility with the old ParserLib
Design outline
--------------
All rules should be immutable after creation. Ideally they'd be constexpr, but
this is likely not to be possible. They should have no state associated with
them, however, and so parsing should be entirely reentrant. State, for a
grammar, is in two categories:
- The current parsing state
- The actions to be performed when parsing
The actions can also be immutable (they don't change over a parse, at least),
but should not be tied to the grammar. It should be possible to write one
singleton class encapsulating the grammar, with members for the rules, and
singleton subclasses (or, ideally, delegates) providing parser actions. The
parsing state should be entirely contained within a context object and so the
same grammar can be used from multiple threads and can be used for compilation,
syntax highlighting, and so on.
RTTI Usage
----------
ParserLib requires RTTI for one specific purpose: down-casting from `ast_node`
to a subclass (and checking that the result really is of that class). If you
are using RTTI in the rest of your application, then you can instruct ParserLib
to use RTTI for these casts by defining the `USE_RTTI` macro before including
the ParserLib headers and when building ParserLib.
If you do not wish to depend on RTTI, then ParserLib provides a macro that you
can use in your own AST classes that will provide the required virtual
functions to implement ad-hoc RTTI for this specific use. You use them like
this:
{% highlight c++ %}
class MyASTClass : parserlib::ast_node
{
/* Your methods go here. */
PARSELIB_RTTI(MyASTClass, parserlib::ast_node)
};
{% endhighlight %}
This macro will be compiled away if you do define `USE_RTTI`, so you can
provide grammars built with ParserLib that don't force consumers to use or
not-use RTTI. It is also completely safe to build without `USE_RTTI`, but
still compile with RTTI.
What is Pegmatite
-----------------
Pegmatite is a very crystalline, intrusive igneous rock composed of
interlocking crystals usually larger than 2.5 cm in size.
It is also, in the Computer Lab's tradition of using bad puns for naming, a Parsing Expression Grammar library that rocks!
| Java |
var markdown = window.markdownit();
$(document).ready(function() {
var $wish = $('#wish');
var todoNotificationArea = $('#todos .notification-area');
var todoNotificationIcon = $('#todos .notification-area > i');
var todoNotificationText = $('#todos .notification-area > span');
$('#news-stream .menu .item').tab({history:false});
$('.todo.menu .item').tab({history:false});
$('.top.menu .item').tab({history:false});
$('body').on('click', '.button', function() {
$(this).transition('pulse');
})
$('#todos').ready(function() {
$.each($('#todos .segment'), function(index, $element){
var $html, $md;
$element = $($element);
$md = $element.find('.md-content-name');
$html = $element.find('.html-content-name');
$html.html(markdown.render($md.val()));
$md = $element.find('.md-content');
$html = $element.find('.html-content');
$html.html(markdown.render($md.val()));
});
});
$('#todos').on('click', '.edit.button', function() {
var $button = $(this);
var $html = $button.parent().siblings('.html-content');
var $md = $button.parent().siblings('.md-content');
var $htmlname = $button.parent().siblings('.html-content-name');
var $mdname = $button.parent().siblings('.md-content-name');
if($html.css('display') == 'none') {
var result = markdown.render($md.val());
$html.html(result);
result = markdown.render($mdname.val());
$htmlname.html(result);
$button.text('Edit');
}
else {
$button.text('Preview');
}
$md.toggle();
$html.toggle();
$mdname.toggle();
$htmlname.toggle();
});
$('#todos').on('click', '.save.button', function() {
var $button = $(this);
var $mdname = $button.parent().parent().find('input');
var $md = $button.parent().parent().find('textarea');
var id = $button.parent().parent().attr('data-tab');
$.post('/todos/save', {id:id, name: $mdname.val(), content: $md.val()}, function(resp){
console.log('Saved');
});
});
$('#todos').on('click', '.delete.button', function() {
var $button = $(this);
var id = $button.parent().parent().attr('data-tab');
$.post('/todos/delete', {id:id}, function(resp){
$('*[data-tab="'+id+'"]').remove();
});
});
$('#new-todo').click(function(e) {
$button = $(this);
$.post('/todos/create', function(resp) {
var $menuItem = $('<a>').addClass('item').attr('data-tab', resp.id)
.html(resp.name);
var $todoContent = $('<div>').addClass('ui tab basic segment basic')
.attr('data-tab', resp.id)
.append(
$('<div>').addClass('ui text menu right floated')
.append($('<div>').addClass('ui edit basic button item').text('Edit'))
.append($('<div>').addClass('ui save basic button item').text('Save'))
.append($('<div>').addClass('ui download basic button item').text('Download'))
.append($('<div>').addClass('ui delete basic button item').text('Delete'))
)
.append(
$('<div>').addClass('ui section divider')
)
.append(
$('<input>').addClass('ui fluid md-content-name')
.attr('style', 'display:none;').val(resp.name)
)
.append(
$('<div>').addClass('html-content-name').html(markdown.render(resp.name))
)
.append(
$('<div>').addClass('ui horizontal divider')
)
.append(
$('<textarea>').addClass('md-content')
.attr('style', 'display:none;').html(resp.content)
)
.append(
$('<div>').addClass('html-content')
);
$button.parent().append($menuItem);
$button.parent().parent().next().prepend($todoContent);
$button.parent().children().last().tab({history:false});
})
.fail(function() {
uiModules.showError('Something went wrong while creating a Todo');
});
})
$('#reminders').on('click', 'i.delete', function(e){
var $parentTr = $(this).parents("tr");
$.post('/reminders/' + $parentTr.attr('id') + '/delete', function(resp) {
$parentTr.remove();
})
});
$('#wish-form').submit(function(e){
e.preventDefault();
var wish = $wish.val();
$.get('/wish', {wish: wish}, function(resp) {
var targetType = resp.type;
if(targetType === 'remind') {
var value = resp.response;
var error = resp.error
if (error) {
uiModules.showError(error);
return;
}
$('#reminders table tbody').append(
$('<tr>').attr('id', value.id)
.append($('<td>').html(value.m))
.append($('<td>').html(value.t))
.append($('<td>').html(value.d))
.append($('<td>').append($('<i>').addClass('ui delete red icon')))
);
}
else if(targetType === 'comic') {
var link = resp.response;
var error = resp.error
if (error) {
uiModules.showError(error);
return;
}
var $webcomicmodal = $('#webcomic-modal');
$webcomicmodal.find('.header').html(link.title);
$webcomicmodal.find('a').attr('href', link.url);
var showModal = true;
if (link.content_type == 'image') {
$webcomicmodal.find('img').attr('src', link.content_url);
}
else if (link.content_type == 'page') {
alert('Page found');
}
else {
showModal = false;
uiModules.showError('Unsuported content_type ' + link.content_type);
}
if( showModal ) {
$webcomicmodal.modal({
context: 'html',
observeChanges: true,
onVisible: function () {
$webcomicmodal.modal("refresh");
}
}).modal('show');
}
}
else if(targetType === 'astro') {
var url = resp.response;
var error = resp.error
if (error) {
uiModules.showError(error);
return;
}
$('#astro-modal iframe').attr('src', url);
$('#astro-modal').modal({
onVisible: function () {
$("#astro-modal").modal("refresh");
}
}).modal('show');
}
else {
uiModules.showError('Invalid type ' + resp.type);
}
// $('#reply').addClass('animated slideInDown').html(resp.response.message);
// setTimeout(function() {
// $('#reply').removeClass('animated slideInDown');
// }, 1000);
});
$wish.val(null);
});
$.get('/commands', function(resp) {
$('#commands').html(resp);
});
$('#webcomics .button').click(function(e) {
var $comic = $(this).parent()
var comic_id = $comic.attr('id');
var $button = $comic.find('.button');
$button.addClass('disabled');
$.post('/webcomics/' + comic_id + '/sync', function(response) {
$comic.find('p').text(response.resp.links_count);
$comic.find('label').text(response.resp.last_sync);
}).
always(function() {
$button.removeClass('disabled');
});
});
$('#astros .button').click(function(e) {
var $astro = $(this).parent()
var astro_id = $astro.attr('id');
var $button = $astro.find('.button');
$button.addClass('disabled');
$.post('/astros/' + astro_id + '/sync', function(response) {
$astro.find('p').text(response.resp.links_count);
$astro.find('label').text(response.resp.last_sync);
}).
always(function() {
$button.removeClass('disabled');
});
});
$('#create-playlist-button').click(function(e) {
var $playlist_name = $('#playlist-name');
var name = $playlist_name.val();
if(!name) {
uiModules.showError('Playlist name cannot be empty');
return;
}
name = name.trim();
$.post('/music/playlist/create', {name:name}, function(resp) {
if(resp.error) {
uiModules.showError(resp.error);
return;
}
$('#music .playlists').append(resp.html);
$playlist_name.val(null);
});
});
$('#music').on('click', 'i.delete-playlist', function(e) {
var $playlist_element = $(this).parents('div');
var playlist_id = $playlist_element.attr('id');
$.post('/music/playlist/delete', {id:playlist_id}, function(resp) {
if(resp.error) {
uiModules.showError(resp.error);
return;
}
if(resp.resp) {
$('#' + playlist_id).remove();
uiModules.notify('Playlist deleted successfully');
}
else {
uiModules.showError('Playlist not deleted');
}
})
});
$('#music').on('click', '.youtube-link button', function(e) {
var $button = $(this);
var $link_input = $(this).siblings('input');
var link = $link_input.val();
if(!link) {
$link_input.parent().addClass('error');
uiModules.showError('No link found');
return;
}
var playlist_id = $button.parents('div.playlist').attr('id');
var $playlist_element = $('#' + playlist_id);
$button.addClass('loading');
$.post('/music/playlist/'+ playlist_id +'/add', {link: link, site: 'youtube'}, function(resp) {
if(resp.error) {
uiModules.showError(resp.error);
return;
}
$playlist_element.find('.update-field').text(resp.resp.updated_at);
$playlist_element.find('.links-count').text(resp.resp.links_count)
}).always(function(){
$link_input.val(null);
$button.removeClass('loading');
});
});
$('#music').on('click', '.random-music', function(e) {
var $button = $(this);
var playlist_id = $button.parents('div.playlist').attr('id');
var $playlist_element = $('#' + playlist_id);
$.get('/music/playlist/'+ playlist_id +'/random', function(resp) {
var video_id = resp.resp.video_id;
var $musicmodal = $('#music-modal');
$musicmodal.find('.header').html(resp.resp.title);
$musicmodal.modal({
context: 'html',
observeChanges: true,
onVisible: function () {
$musicmodal.modal("refresh");
music_player.loadVideoById(video_id, 0, "large")
},
onHidden: function() {
music_player.stopVideo();
}
}).modal('show');
}).fail(function(response) {
uiModules.showError(response.responseText);
})
});
$('#music').on('click', '.full-playlist', function(e) {
var $button = $(this);
var playlist_id = $button.parents('div.playlist').attr('id');
var $playlist_element = $('#' + playlist_id);
var playlist_name = $playlist_element.find('a.header').text();
$.get('/music/playlist/'+ playlist_id +'/all', function(resp) {
var $musicmodal = $('#music-modal');
$musicmodal.find('.header').html(resp.resp.title);
$musicmodal.modal({
context: 'html',
observeChanges: true,
onVisible: function () {
$musicmodal.modal("refresh");
var ids = [];
for( var i = 0; i < 100 && i < resp.resp.length ; i++ ) {
var video = resp.resp[i];
ids.push(video.video_id);
}
music_player.loadPlaylist(ids);
},
onHidden: function() {
music_player.stopVideo();
}
}).modal('show');
}).fail(function(response) {
uiModules.showError(response.responseText);
})
});
});
| Java |
//
// AWSAppDelegate.h
// TAWS
//
// Created by CocoaPods on 05/27/2015.
// Copyright (c) 2014 suwa.yuki. All rights reserved.
//
@import UIKit;
@interface AWSAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>metacoq-erasure: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[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]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / extra-dev</a></li>
<li class="active"><a href="">8.10.dev / metacoq-erasure - 1.0~alpha+8.8</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
metacoq-erasure
<small>
1.0~alpha+8.8
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2020-07-17 06:06:32 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-17 06:06:32 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.10.dev Formal proof management system
num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.08.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.08.1 Official release 4.08.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "matthieu.sozeau@inria.fr"
homepage: "https://metacoq.github.io/metacoq"
dev-repo: "git+https://github.com/MetaCoq/metacoq.git#coq-8.8"
bug-reports: "https://github.com/MetaCoq/metacoq/issues"
authors: ["Abhishek Anand <aa755@cs.cornell.edu>"
"Simon Boulier <simon.boulier@inria.fr>"
"Cyril Cohen <cyril.cohen@inria.fr>"
"Yannick Forster <forster@ps.uni-saarland.de>"
"Fabian Kunze <fkunze@fakusb.de>"
"Gregory Malecha <gmalecha@gmail.com>"
"Matthieu Sozeau <matthieu.sozeau@inria.fr>"
"Nicolas Tabareau <nicolas.tabareau@inria.fr>"
"Théo Winterhalter <theo.winterhalter@inria.fr>"
]
license: "MIT"
build: [
["sh" "./configure.sh"]
[make "-j%{jobs}%" "-C" "erasure"]
[make "test-suite"] {with-test}
]
install: [
[make "-C" "erasure" "install"]
]
depends: [
"ocaml" {> "4.02.3"}
"coq" {>= "8.8" & < "8.9~"}
"coq-metacoq-template" {= version}
"coq-metacoq-checker" {= version}
"coq-metacoq-pcuic" {= version}
"coq-metacoq-safechecker" {= version}
]
synopsis: "Implementation and verification of an erasure procedure for Coq"
description: """
MetaCoq is a meta-programming framework for Coq.
The Erasure module provides a complete specification of Coq's so-called
\"extraction\" procedure, starting from the PCUIC calculus and targeting
untyped call-by-value lambda-calculus.
The `erasure` function translates types and proofs in well-typed terms
into a dummy `tBox` constructor, following closely P. Letouzey's PhD
thesis.
"""
url {
src: "https://github.com/MetaCoq/metacoq/archive/1.0-alpha+8.8.tar.gz"
checksum: "sha256=c2fe122ad30849e99c1e5c100af5490cef0e94246f8eb83f6df3f2ccf9edfc04"
}</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-metacoq-erasure.1.0~alpha+8.8 coq.8.10.dev</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.10.dev).
The following dependencies couldn't be met:
- coq-metacoq-erasure -> coq < 8.9~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-metacoq-erasure.1.0~alpha+8.8</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| Java |
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
"""The Query type hierarchy for DBCore.
"""
import re
from operator import mul
from beets import util
from datetime import datetime, timedelta
import unicodedata
from functools import reduce
class ParsingError(ValueError):
"""Abstract class for any unparseable user-requested album/query
specification.
"""
class InvalidQueryError(ParsingError):
"""Represent any kind of invalid query.
The query should be a unicode string or a list, which will be space-joined.
"""
def __init__(self, query, explanation):
if isinstance(query, list):
query = " ".join(query)
message = f"'{query}': {explanation}"
super().__init__(message)
class InvalidQueryArgumentValueError(ParsingError):
"""Represent a query argument that could not be converted as expected.
It exists to be caught in upper stack levels so a meaningful (i.e. with the
query) InvalidQueryError can be raised.
"""
def __init__(self, what, expected, detail=None):
message = f"'{what}' is not {expected}"
if detail:
message = f"{message}: {detail}"
super().__init__(message)
class Query:
"""An abstract class representing a query into the item database.
"""
def clause(self):
"""Generate an SQLite expression implementing the query.
Return (clause, subvals) where clause is a valid sqlite
WHERE clause implementing the query and subvals is a list of
items to be substituted for ?s in the clause.
"""
return None, ()
def match(self, item):
"""Check whether this query matches a given Item. Can be used to
perform queries on arbitrary sets of Items.
"""
raise NotImplementedError
def __repr__(self):
return f"{self.__class__.__name__}()"
def __eq__(self, other):
return type(self) == type(other)
def __hash__(self):
return 0
class FieldQuery(Query):
"""An abstract query that searches in a specific field for a
pattern. Subclasses must provide a `value_match` class method, which
determines whether a certain pattern string matches a certain value
string. Subclasses may also provide `col_clause` to implement the
same matching functionality in SQLite.
"""
def __init__(self, field, pattern, fast=True):
self.field = field
self.pattern = pattern
self.fast = fast
def col_clause(self):
return None, ()
def clause(self):
if self.fast:
return self.col_clause()
else:
# Matching a flexattr. This is a slow query.
return None, ()
@classmethod
def value_match(cls, pattern, value):
"""Determine whether the value matches the pattern. Both
arguments are strings.
"""
raise NotImplementedError()
def match(self, item):
return self.value_match(self.pattern, item.get(self.field))
def __repr__(self):
return ("{0.__class__.__name__}({0.field!r}, {0.pattern!r}, "
"{0.fast})".format(self))
def __eq__(self, other):
return super().__eq__(other) and \
self.field == other.field and self.pattern == other.pattern
def __hash__(self):
return hash((self.field, hash(self.pattern)))
class MatchQuery(FieldQuery):
"""A query that looks for exact matches in an item field."""
def col_clause(self):
return self.field + " = ?", [self.pattern]
@classmethod
def value_match(cls, pattern, value):
return pattern == value
class NoneQuery(FieldQuery):
"""A query that checks whether a field is null."""
def __init__(self, field, fast=True):
super().__init__(field, None, fast)
def col_clause(self):
return self.field + " IS NULL", ()
def match(self, item):
return item.get(self.field) is None
def __repr__(self):
return "{0.__class__.__name__}({0.field!r}, {0.fast})".format(self)
class StringFieldQuery(FieldQuery):
"""A FieldQuery that converts values to strings before matching
them.
"""
@classmethod
def value_match(cls, pattern, value):
"""Determine whether the value matches the pattern. The value
may have any type.
"""
return cls.string_match(pattern, util.as_string(value))
@classmethod
def string_match(cls, pattern, value):
"""Determine whether the value matches the pattern. Both
arguments are strings. Subclasses implement this method.
"""
raise NotImplementedError()
class StringQuery(StringFieldQuery):
"""A query that matches a whole string in a specific item field."""
def col_clause(self):
search = (self.pattern
.replace('\\', '\\\\')
.replace('%', '\\%')
.replace('_', '\\_'))
clause = self.field + " like ? escape '\\'"
subvals = [search]
return clause, subvals
@classmethod
def string_match(cls, pattern, value):
return pattern.lower() == value.lower()
class SubstringQuery(StringFieldQuery):
"""A query that matches a substring in a specific item field."""
def col_clause(self):
pattern = (self.pattern
.replace('\\', '\\\\')
.replace('%', '\\%')
.replace('_', '\\_'))
search = '%' + pattern + '%'
clause = self.field + " like ? escape '\\'"
subvals = [search]
return clause, subvals
@classmethod
def string_match(cls, pattern, value):
return pattern.lower() in value.lower()
class RegexpQuery(StringFieldQuery):
"""A query that matches a regular expression in a specific item
field.
Raises InvalidQueryError when the pattern is not a valid regular
expression.
"""
def __init__(self, field, pattern, fast=True):
super().__init__(field, pattern, fast)
pattern = self._normalize(pattern)
try:
self.pattern = re.compile(self.pattern)
except re.error as exc:
# Invalid regular expression.
raise InvalidQueryArgumentValueError(pattern,
"a regular expression",
format(exc))
@staticmethod
def _normalize(s):
"""Normalize a Unicode string's representation (used on both
patterns and matched values).
"""
return unicodedata.normalize('NFC', s)
@classmethod
def string_match(cls, pattern, value):
return pattern.search(cls._normalize(value)) is not None
class BooleanQuery(MatchQuery):
"""Matches a boolean field. Pattern should either be a boolean or a
string reflecting a boolean.
"""
def __init__(self, field, pattern, fast=True):
super().__init__(field, pattern, fast)
if isinstance(pattern, str):
self.pattern = util.str2bool(pattern)
self.pattern = int(self.pattern)
class BytesQuery(MatchQuery):
"""Match a raw bytes field (i.e., a path). This is a necessary hack
to work around the `sqlite3` module's desire to treat `bytes` and
`unicode` equivalently in Python 2. Always use this query instead of
`MatchQuery` when matching on BLOB values.
"""
def __init__(self, field, pattern):
super().__init__(field, pattern)
# Use a buffer/memoryview representation of the pattern for SQLite
# matching. This instructs SQLite to treat the blob as binary
# rather than encoded Unicode.
if isinstance(self.pattern, (str, bytes)):
if isinstance(self.pattern, str):
self.pattern = self.pattern.encode('utf-8')
self.buf_pattern = memoryview(self.pattern)
elif isinstance(self.pattern, memoryview):
self.buf_pattern = self.pattern
self.pattern = bytes(self.pattern)
def col_clause(self):
return self.field + " = ?", [self.buf_pattern]
class NumericQuery(FieldQuery):
"""Matches numeric fields. A syntax using Ruby-style range ellipses
(``..``) lets users specify one- or two-sided ranges. For example,
``year:2001..`` finds music released since the turn of the century.
Raises InvalidQueryError when the pattern does not represent an int or
a float.
"""
def _convert(self, s):
"""Convert a string to a numeric type (float or int).
Return None if `s` is empty.
Raise an InvalidQueryError if the string cannot be converted.
"""
# This is really just a bit of fun premature optimization.
if not s:
return None
try:
return int(s)
except ValueError:
try:
return float(s)
except ValueError:
raise InvalidQueryArgumentValueError(s, "an int or a float")
def __init__(self, field, pattern, fast=True):
super().__init__(field, pattern, fast)
parts = pattern.split('..', 1)
if len(parts) == 1:
# No range.
self.point = self._convert(parts[0])
self.rangemin = None
self.rangemax = None
else:
# One- or two-sided range.
self.point = None
self.rangemin = self._convert(parts[0])
self.rangemax = self._convert(parts[1])
def match(self, item):
if self.field not in item:
return False
value = item[self.field]
if isinstance(value, str):
value = self._convert(value)
if self.point is not None:
return value == self.point
else:
if self.rangemin is not None and value < self.rangemin:
return False
if self.rangemax is not None and value > self.rangemax:
return False
return True
def col_clause(self):
if self.point is not None:
return self.field + '=?', (self.point,)
else:
if self.rangemin is not None and self.rangemax is not None:
return ('{0} >= ? AND {0} <= ?'.format(self.field),
(self.rangemin, self.rangemax))
elif self.rangemin is not None:
return f'{self.field} >= ?', (self.rangemin,)
elif self.rangemax is not None:
return f'{self.field} <= ?', (self.rangemax,)
else:
return '1', ()
class CollectionQuery(Query):
"""An abstract query class that aggregates other queries. Can be
indexed like a list to access the sub-queries.
"""
def __init__(self, subqueries=()):
self.subqueries = subqueries
# Act like a sequence.
def __len__(self):
return len(self.subqueries)
def __getitem__(self, key):
return self.subqueries[key]
def __iter__(self):
return iter(self.subqueries)
def __contains__(self, item):
return item in self.subqueries
def clause_with_joiner(self, joiner):
"""Return a clause created by joining together the clauses of
all subqueries with the string joiner (padded by spaces).
"""
clause_parts = []
subvals = []
for subq in self.subqueries:
subq_clause, subq_subvals = subq.clause()
if not subq_clause:
# Fall back to slow query.
return None, ()
clause_parts.append('(' + subq_clause + ')')
subvals += subq_subvals
clause = (' ' + joiner + ' ').join(clause_parts)
return clause, subvals
def __repr__(self):
return "{0.__class__.__name__}({0.subqueries!r})".format(self)
def __eq__(self, other):
return super().__eq__(other) and \
self.subqueries == other.subqueries
def __hash__(self):
"""Since subqueries are mutable, this object should not be hashable.
However and for conveniences purposes, it can be hashed.
"""
return reduce(mul, map(hash, self.subqueries), 1)
class AnyFieldQuery(CollectionQuery):
"""A query that matches if a given FieldQuery subclass matches in
any field. The individual field query class is provided to the
constructor.
"""
def __init__(self, pattern, fields, cls):
self.pattern = pattern
self.fields = fields
self.query_class = cls
subqueries = []
for field in self.fields:
subqueries.append(cls(field, pattern, True))
super().__init__(subqueries)
def clause(self):
return self.clause_with_joiner('or')
def match(self, item):
for subq in self.subqueries:
if subq.match(item):
return True
return False
def __repr__(self):
return ("{0.__class__.__name__}({0.pattern!r}, {0.fields!r}, "
"{0.query_class.__name__})".format(self))
def __eq__(self, other):
return super().__eq__(other) and \
self.query_class == other.query_class
def __hash__(self):
return hash((self.pattern, tuple(self.fields), self.query_class))
class MutableCollectionQuery(CollectionQuery):
"""A collection query whose subqueries may be modified after the
query is initialized.
"""
def __setitem__(self, key, value):
self.subqueries[key] = value
def __delitem__(self, key):
del self.subqueries[key]
class AndQuery(MutableCollectionQuery):
"""A conjunction of a list of other queries."""
def clause(self):
return self.clause_with_joiner('and')
def match(self, item):
return all(q.match(item) for q in self.subqueries)
class OrQuery(MutableCollectionQuery):
"""A conjunction of a list of other queries."""
def clause(self):
return self.clause_with_joiner('or')
def match(self, item):
return any(q.match(item) for q in self.subqueries)
class NotQuery(Query):
"""A query that matches the negation of its `subquery`, as a shorcut for
performing `not(subquery)` without using regular expressions.
"""
def __init__(self, subquery):
self.subquery = subquery
def clause(self):
clause, subvals = self.subquery.clause()
if clause:
return f'not ({clause})', subvals
else:
# If there is no clause, there is nothing to negate. All the logic
# is handled by match() for slow queries.
return clause, subvals
def match(self, item):
return not self.subquery.match(item)
def __repr__(self):
return "{0.__class__.__name__}({0.subquery!r})".format(self)
def __eq__(self, other):
return super().__eq__(other) and \
self.subquery == other.subquery
def __hash__(self):
return hash(('not', hash(self.subquery)))
class TrueQuery(Query):
"""A query that always matches."""
def clause(self):
return '1', ()
def match(self, item):
return True
class FalseQuery(Query):
"""A query that never matches."""
def clause(self):
return '0', ()
def match(self, item):
return False
# Time/date queries.
def _to_epoch_time(date):
"""Convert a `datetime` object to an integer number of seconds since
the (local) Unix epoch.
"""
if hasattr(date, 'timestamp'):
# The `timestamp` method exists on Python 3.3+.
return int(date.timestamp())
else:
epoch = datetime.fromtimestamp(0)
delta = date - epoch
return int(delta.total_seconds())
def _parse_periods(pattern):
"""Parse a string containing two dates separated by two dots (..).
Return a pair of `Period` objects.
"""
parts = pattern.split('..', 1)
if len(parts) == 1:
instant = Period.parse(parts[0])
return (instant, instant)
else:
start = Period.parse(parts[0])
end = Period.parse(parts[1])
return (start, end)
class Period:
"""A period of time given by a date, time and precision.
Example: 2014-01-01 10:50:30 with precision 'month' represents all
instants of time during January 2014.
"""
precisions = ('year', 'month', 'day', 'hour', 'minute', 'second')
date_formats = (
('%Y',), # year
('%Y-%m',), # month
('%Y-%m-%d',), # day
('%Y-%m-%dT%H', '%Y-%m-%d %H'), # hour
('%Y-%m-%dT%H:%M', '%Y-%m-%d %H:%M'), # minute
('%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S') # second
)
relative_units = {'y': 365, 'm': 30, 'w': 7, 'd': 1}
relative_re = '(?P<sign>[+|-]?)(?P<quantity>[0-9]+)' + \
'(?P<timespan>[y|m|w|d])'
def __init__(self, date, precision):
"""Create a period with the given date (a `datetime` object) and
precision (a string, one of "year", "month", "day", "hour", "minute",
or "second").
"""
if precision not in Period.precisions:
raise ValueError(f'Invalid precision {precision}')
self.date = date
self.precision = precision
@classmethod
def parse(cls, string):
"""Parse a date and return a `Period` object or `None` if the
string is empty, or raise an InvalidQueryArgumentValueError if
the string cannot be parsed to a date.
The date may be absolute or relative. Absolute dates look like
`YYYY`, or `YYYY-MM-DD`, or `YYYY-MM-DD HH:MM:SS`, etc. Relative
dates have three parts:
- Optionally, a ``+`` or ``-`` sign indicating the future or the
past. The default is the future.
- A number: how much to add or subtract.
- A letter indicating the unit: days, weeks, months or years
(``d``, ``w``, ``m`` or ``y``). A "month" is exactly 30 days
and a "year" is exactly 365 days.
"""
def find_date_and_format(string):
for ord, format in enumerate(cls.date_formats):
for format_option in format:
try:
date = datetime.strptime(string, format_option)
return date, ord
except ValueError:
# Parsing failed.
pass
return (None, None)
if not string:
return None
# Check for a relative date.
match_dq = re.match(cls.relative_re, string)
if match_dq:
sign = match_dq.group('sign')
quantity = match_dq.group('quantity')
timespan = match_dq.group('timespan')
# Add or subtract the given amount of time from the current
# date.
multiplier = -1 if sign == '-' else 1
days = cls.relative_units[timespan]
date = datetime.now() + \
timedelta(days=int(quantity) * days) * multiplier
return cls(date, cls.precisions[5])
# Check for an absolute date.
date, ordinal = find_date_and_format(string)
if date is None:
raise InvalidQueryArgumentValueError(string,
'a valid date/time string')
precision = cls.precisions[ordinal]
return cls(date, precision)
def open_right_endpoint(self):
"""Based on the precision, convert the period to a precise
`datetime` for use as a right endpoint in a right-open interval.
"""
precision = self.precision
date = self.date
if 'year' == self.precision:
return date.replace(year=date.year + 1, month=1)
elif 'month' == precision:
if (date.month < 12):
return date.replace(month=date.month + 1)
else:
return date.replace(year=date.year + 1, month=1)
elif 'day' == precision:
return date + timedelta(days=1)
elif 'hour' == precision:
return date + timedelta(hours=1)
elif 'minute' == precision:
return date + timedelta(minutes=1)
elif 'second' == precision:
return date + timedelta(seconds=1)
else:
raise ValueError(f'unhandled precision {precision}')
class DateInterval:
"""A closed-open interval of dates.
A left endpoint of None means since the beginning of time.
A right endpoint of None means towards infinity.
"""
def __init__(self, start, end):
if start is not None and end is not None and not start < end:
raise ValueError("start date {} is not before end date {}"
.format(start, end))
self.start = start
self.end = end
@classmethod
def from_periods(cls, start, end):
"""Create an interval with two Periods as the endpoints.
"""
end_date = end.open_right_endpoint() if end is not None else None
start_date = start.date if start is not None else None
return cls(start_date, end_date)
def contains(self, date):
if self.start is not None and date < self.start:
return False
if self.end is not None and date >= self.end:
return False
return True
def __str__(self):
return f'[{self.start}, {self.end})'
class DateQuery(FieldQuery):
"""Matches date fields stored as seconds since Unix epoch time.
Dates can be specified as ``year-month-day`` strings where only year
is mandatory.
The value of a date field can be matched against a date interval by
using an ellipsis interval syntax similar to that of NumericQuery.
"""
def __init__(self, field, pattern, fast=True):
super().__init__(field, pattern, fast)
start, end = _parse_periods(pattern)
self.interval = DateInterval.from_periods(start, end)
def match(self, item):
if self.field not in item:
return False
timestamp = float(item[self.field])
date = datetime.fromtimestamp(timestamp)
return self.interval.contains(date)
_clause_tmpl = "{0} {1} ?"
def col_clause(self):
clause_parts = []
subvals = []
if self.interval.start:
clause_parts.append(self._clause_tmpl.format(self.field, ">="))
subvals.append(_to_epoch_time(self.interval.start))
if self.interval.end:
clause_parts.append(self._clause_tmpl.format(self.field, "<"))
subvals.append(_to_epoch_time(self.interval.end))
if clause_parts:
# One- or two-sided interval.
clause = ' AND '.join(clause_parts)
else:
# Match any date.
clause = '1'
return clause, subvals
class DurationQuery(NumericQuery):
"""NumericQuery that allow human-friendly (M:SS) time interval formats.
Converts the range(s) to a float value, and delegates on NumericQuery.
Raises InvalidQueryError when the pattern does not represent an int, float
or M:SS time interval.
"""
def _convert(self, s):
"""Convert a M:SS or numeric string to a float.
Return None if `s` is empty.
Raise an InvalidQueryError if the string cannot be converted.
"""
if not s:
return None
try:
return util.raw_seconds_short(s)
except ValueError:
try:
return float(s)
except ValueError:
raise InvalidQueryArgumentValueError(
s,
"a M:SS string or a float")
# Sorting.
class Sort:
"""An abstract class representing a sort operation for a query into
the item database.
"""
def order_clause(self):
"""Generates a SQL fragment to be used in a ORDER BY clause, or
None if no fragment is used (i.e., this is a slow sort).
"""
return None
def sort(self, items):
"""Sort the list of objects and return a list.
"""
return sorted(items)
def is_slow(self):
"""Indicate whether this query is *slow*, meaning that it cannot
be executed in SQL and must be executed in Python.
"""
return False
def __hash__(self):
return 0
def __eq__(self, other):
return type(self) == type(other)
class MultipleSort(Sort):
"""Sort that encapsulates multiple sub-sorts.
"""
def __init__(self, sorts=None):
self.sorts = sorts or []
def add_sort(self, sort):
self.sorts.append(sort)
def _sql_sorts(self):
"""Return the list of sub-sorts for which we can be (at least
partially) fast.
A contiguous suffix of fast (SQL-capable) sub-sorts are
executable in SQL. The remaining, even if they are fast
independently, must be executed slowly.
"""
sql_sorts = []
for sort in reversed(self.sorts):
if not sort.order_clause() is None:
sql_sorts.append(sort)
else:
break
sql_sorts.reverse()
return sql_sorts
def order_clause(self):
order_strings = []
for sort in self._sql_sorts():
order = sort.order_clause()
order_strings.append(order)
return ", ".join(order_strings)
def is_slow(self):
for sort in self.sorts:
if sort.is_slow():
return True
return False
def sort(self, items):
slow_sorts = []
switch_slow = False
for sort in reversed(self.sorts):
if switch_slow:
slow_sorts.append(sort)
elif sort.order_clause() is None:
switch_slow = True
slow_sorts.append(sort)
else:
pass
for sort in slow_sorts:
items = sort.sort(items)
return items
def __repr__(self):
return f'MultipleSort({self.sorts!r})'
def __hash__(self):
return hash(tuple(self.sorts))
def __eq__(self, other):
return super().__eq__(other) and \
self.sorts == other.sorts
class FieldSort(Sort):
"""An abstract sort criterion that orders by a specific field (of
any kind).
"""
def __init__(self, field, ascending=True, case_insensitive=True):
self.field = field
self.ascending = ascending
self.case_insensitive = case_insensitive
def sort(self, objs):
# TODO: Conversion and null-detection here. In Python 3,
# comparisons with None fail. We should also support flexible
# attributes with different types without falling over.
def key(item):
field_val = item.get(self.field, '')
if self.case_insensitive and isinstance(field_val, str):
field_val = field_val.lower()
return field_val
return sorted(objs, key=key, reverse=not self.ascending)
def __repr__(self):
return '<{}: {}{}>'.format(
type(self).__name__,
self.field,
'+' if self.ascending else '-',
)
def __hash__(self):
return hash((self.field, self.ascending))
def __eq__(self, other):
return super().__eq__(other) and \
self.field == other.field and \
self.ascending == other.ascending
class FixedFieldSort(FieldSort):
"""Sort object to sort on a fixed field.
"""
def order_clause(self):
order = "ASC" if self.ascending else "DESC"
if self.case_insensitive:
field = '(CASE ' \
'WHEN TYPEOF({0})="text" THEN LOWER({0}) ' \
'WHEN TYPEOF({0})="blob" THEN LOWER({0}) ' \
'ELSE {0} END)'.format(self.field)
else:
field = self.field
return f"{field} {order}"
class SlowFieldSort(FieldSort):
"""A sort criterion by some model field other than a fixed field:
i.e., a computed or flexible field.
"""
def is_slow(self):
return True
class NullSort(Sort):
"""No sorting. Leave results unsorted."""
def sort(self, items):
return items
def __nonzero__(self):
return self.__bool__()
def __bool__(self):
return False
def __eq__(self, other):
return type(self) == type(other) or other is None
def __hash__(self):
return 0
| Java |
require_relative '../animation'
module NixonPi
module Animations
class CountFromToAnimation < Animation
register :count_from_to, self
accepted_commands :start_value, :single_digit?
# TODO: unfinished and untested
def initialize(options = {})
super(options)
@options[:single_digit?] ||= true
from = @options[:start_value]
to = from
if @options[:single_digit?]
from.each_char { |f| to[i] = (f.to_i += 1).to_s }
from.reverse.each_char.with_index do |number|
@output << number
end
end
end
def write
handle_output_on_tick(@output.shift)
end
end
end
end
| Java |
FROM python:3
ADD ./simplesocial /simplesocial
WORKDIR /simplesocial
RUN pip install -r requirements.txt
EXPOSE 8000
CMD [ "python", "manage.py", "runserver", "0.0.0.0:8000"] | Java |
---
layout: post
title: "Class Based Views"
date: 2013-05-13 07:04
tags: [python, django, yakindanegitim]
icons: [python]
---
Web development is a bit repetitive and web frameworks try to reduce this burden. One of the best features of Django for making object manipulation easier is class based views(CBV). We are usually good to go by only setting model in class based views and in the background, it handles all form processing.
There is also function based views(FBV) which have the same power and some more. I think, difference between them can be best explained by the analogy of C vs Python. Python is compact and writing Python is more fun. That's why it enables to do lots of work in a few lines. On the other hand, C is verbose and fast since there is no boilerplate and you directly do what you want but whenever you go off the standard lines and need some more control, you have to use C.
Even if CBVs get attention recently, FBVs aren't deprecated. Python gets traction but C is always [there](http://www.tiobe.com/content/paperinfo/tpci/index.html) so which one should we use?
CBVs enables to write more compact code as a result of more enjoyable reading, that is quite important for maintenance. Moreover, CBVs are better to write tests for. Therefore, we should stick to them when possible.
Mainly, CBVs have two disadvantages; namely, a very steep learning curve and the difficulty of handling multiple forms.
1- How is context data created? How is object retrieved? How is form validated? In FBVs, most of the time, we write these logic ourselves explicitly but in CBVs, we should aware of how and when our methods are called. Getting used to it takes some time but later, I think, CBV makes us more productive.
2- Even if inline formsets makes possible multi model form handling in CBVs, it is hard. It seems this is the only reason to use FBVs.
Now, I would like to show inline formset usage via CBVs with an example(adding album with songs):
Our models:
``` python
# models.py
from django.db import models
class Album(models.Model):
name = models.CharField(max_length=255)
class Song(models.Model):
name = models.CharField(max_length=255)
lyrics = models.TextField(blank=True, null=True)
album = models.ForeignKey(Album)
```
Our forms:
``` python
# forms.py
from django.forms import ModelForm
from django.forms.models import inlineformset_factory
from .models import Album, Song
class AlbumForm(ModelForm):
class Meta:
model = Album
AlbumSongFormSet = inlineformset_factory(Album, Song, form=AlbumForm, extra=3)
```
Our create view:
``` python
# views.py
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.views.generic import CreateView
from django.utils.text import slugify
from django.utils.translation import ugettext as _
from braces.views import LoginRequiredMixin
from core.mixins import ActionMixin
from .models import Album, Song
from .forms import AlbumForm
class AlbumCreateView(LoginRequiredMixin, ActionMixin, CreateView):
model = Album
form_class = AlbumForm
template_name = 'music/album_add.html'
action = _("Album is successfully added") # ActionMixin is written in an earlier post
def form_valid(self, form):
context = self.get_context_data()
albumsong_form = context['albumsong_formset']
if albumsong_form.is_valid():
self.object = form.save(commit=False) # to set extra attributes that doesn't come from form
self.object.artist = Artist.objects.get(profile__username__exact=self.kwargs.get("username"))
self.object.slug = slugify(self.object.name)
self.object.save()
for song_form in albumsong_form:
song = song_form.save(commit=False)
song.slug = slugify(song.name)
song.album = self.object
song.save()
return HttpResponseRedirect(self.get_success_url())
else:
return self.render_to_response(self.get_context_data(form=form))
def form_invalid(self, form):
return self.render_to_response(self.get_context_data(form=form))
def get_context_data(self, **kwargs):
context = super(AlbumCreateView, self).get_context_data(**kwargs)
if self.request.POST:
context['albumsong_formset'] = AlbumSongFormSet(self.request.POST)
else:
context['albumsong_formset'] = AlbumSongFormSet()
return context
def get_success_url(self):
return reverse('artist_detail', kwargs=self.kwargs)
```
And finally, our urlconf:
``` python
# urls.py
from django.conf.urls import patterns, url
from .views import *
urlpatterns = patterns('',
url(r'^(?P<username>[-_\.\w]+)/add/$',
AlbumCreateView.as_view(), name="album_add"),
)
```
That's it!
| Java |
local Swapout = require('sconce.Swapout')
return function(tester)
local suite = torch.TestSuite()
function suite.test_swapout_always_add()
local swapout = Swapout.new(1.0)
local actual = swapout:forward({torch.Tensor{1, 2}, torch.Tensor{3, 2}})
local expected = torch.Tensor{4, 4}
tester:eq(actual, expected)
end
function suite.test_swapout_never_add()
local swapout = Swapout.new(0.0)
local actual = swapout:forward({torch.Tensor{1, 2}, torch.Tensor{3, 2}})
local expected = torch.Tensor{0, 0}
tester:eq(actual, expected)
end
function suite.test_swapout_sometimes_add()
torch.manualSeed(1234)
local swapout = Swapout.new(0.5)
local actual = swapout:forward({
torch.Tensor(4):fill(1), torch.Tensor(4):fill(2)
})
local expected = torch.Tensor{3, 1, 0, 0}
tester:eq(actual, expected)
end
tester:add(suite)
return suite
end
| Java |
"use strict";
var http_1 = require("@angular/http");
var AppSettings = (function () {
function AppSettings() {
}
Object.defineProperty(AppSettings, "API_OPTIONS", {
get: function () {
var headers = new http_1.Headers({ 'Content-Type': 'application/json' }), options = new http_1.RequestOptions({ headers: headers });
return options;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AppSettings, "API_URL", {
get: function () {
var devMode = true, prodPath = "http://cristi.red:8080/api", apiSecured = false, apiHost = "localhost", apiPort = "8080/api";
return (devMode) ? ("http" + ((apiSecured) ? "s" : "") + "://" + apiHost + ":" + apiPort) : prodPath;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AppSettings, "SOCKETG_URL", {
get: function () {
var devMode = true, prodPath = "http://cristi.red:8080/gs-guide-websocket", local = "http://localhost:8080/gs-guide-websocket";
return (devMode) ? local : prodPath;
},
enumerable: true,
configurable: true
});
return AppSettings;
}());
exports.AppSettings = AppSettings;
//# sourceMappingURL=app.settings.js.map | Java |
const fs = require('fs')
const path = require('path')
const {generateBabelEnvLoader, getConfig} = require('./common')
const buildCache = {}
module.exports = (params) => {
const baseConfig = getConfig(params)
const config = Object.assign({}, baseConfig)
config.outputPath = path.join(__dirname, '../dist-' + config.app)
return {
entry: config.sourcePath + '/tools/initdb.js',
context: config.sourcePath,
target: 'node',
output: {
path: config.outputPath,
filename: 'initdb.js'
},
stats: {
colors: true,
reasons: true,
chunks: false
},
cache: buildCache,
module: {
rules: [generateBabelEnvLoader({node: 'current'}, config)]
},
resolve: {
extensions: ['.js', '.jsx'],
alias: baseConfig.aliases
},
devServer: {
contentBase: config.sourcePath
}
}
}
| Java |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using tomware.Microwf.Domain;
using tomware.Microwf.Infrastructure;
namespace tomware.Microwf.Engine
{
public interface IJobQueueControllerService
{
Task<IEnumerable<WorkItemViewModel>> GetSnapshotAsync();
Task<PaginatedList<WorkItemViewModel>> GetUpCommingsAsync(PagingParameters parameters);
Task<PaginatedList<WorkItemViewModel>> GetFailedAsync(PagingParameters parameters);
Task Reschedule(WorkItemViewModel model);
}
public class JobQueueControllerService : IJobQueueControllerService
{
private readonly IJobQueueService service;
private readonly IWorkItemService workItemService;
public JobQueueControllerService(
IJobQueueService service,
IWorkItemService workItemService
)
{
this.service = service;
this.workItemService = workItemService;
}
public async Task<IEnumerable<WorkItemViewModel>> GetSnapshotAsync()
{
var result = this.service.GetSnapshot();
return await Task.FromResult(result.Select(x => ToViewModel(x)));
}
public async Task<PaginatedList<WorkItemViewModel>> GetUpCommingsAsync(
PagingParameters parameters
)
{
var result = await this.workItemService.GetUpCommingsAsync(parameters);
return new PaginatedList<WorkItemViewModel>(
result.Select(x => ToViewModel(x)),
result.AllItemsCount,
parameters.PageIndex,
parameters.PageSize
);
}
public async Task<PaginatedList<WorkItemViewModel>> GetFailedAsync(
PagingParameters parameters
)
{
var result = await this.workItemService.GetFailedAsync(parameters);
return new PaginatedList<WorkItemViewModel>(
result.Select(x => ToViewModel(x)),
result.AllItemsCount,
parameters.PageIndex,
parameters.PageSize
);
}
public async Task Reschedule(WorkItemViewModel model)
{
await this.workItemService.Reschedule(new Infrastructure.WorkItemDto
{
Id = model.Id,
DueDate = model.DueDate
});
}
private WorkItemViewModel ToViewModel(Domain.WorkItemDto dto)
{
return PropertyMapper<Domain.WorkItemDto, WorkItemViewModel>.From(dto);
// return new WorkItemViewModel
// {
// Id = dto.Id,
// TriggerName = dto.TriggerName,
// EntityId = dto.EntityId,
// WorkflowType = dto.WorkflowType,
// Retries = dto.Retries,
// Error = dto.Error,
// DueDate = dto.DueDate
// };
}
}
} | Java |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__wchar_t_connect_socket_w32spawnl_18.c
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-18.tmpl.c
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Fixed string
* Sink: w32spawnl
* BadSink : execute command with wspawnl
* Flow Variant: 18 Control flow: goto statements
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT L"cmd.exe"
#define COMMAND_ARG1 L"/c"
#define COMMAND_ARG2 L"dir"
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH L"/bin/sh"
#define COMMAND_INT L"sh"
#define COMMAND_ARG1 L"ls"
#define COMMAND_ARG2 L"-la"
#define COMMAND_ARG3 data
#endif
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
#include <process.h>
#ifndef OMITBAD
void CWE78_OS_Command_Injection__wchar_t_connect_socket_w32spawnl_18_bad()
{
wchar_t * data;
wchar_t dataBuffer[100] = L"";
data = dataBuffer;
goto source;
source:
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
wchar_t *replace;
SOCKET connectSocket = INVALID_SOCKET;
size_t dataLen = wcslen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
/* Abort on error or the connection was closed */
recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(wchar_t)] = L'\0';
/* Eliminate CRLF */
replace = wcschr(data, L'\r');
if (replace)
{
*replace = L'\0';
}
replace = wcschr(data, L'\n');
if (replace)
{
*replace = L'\0';
}
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
/* wspawnl - specify the path where the command is located */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
_wspawnl(_P_WAIT, COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() - use goodsource and badsink by reversing the blocks on the goto statement */
static void goodG2B()
{
wchar_t * data;
wchar_t dataBuffer[100] = L"";
data = dataBuffer;
goto source;
source:
/* FIX: Append a fixed string to data (not user / external input) */
wcscat(data, L"*.*");
/* wspawnl - specify the path where the command is located */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
_wspawnl(_P_WAIT, COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL);
}
void CWE78_OS_Command_Injection__wchar_t_connect_socket_w32spawnl_18_good()
{
goodG2B();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE78_OS_Command_Injection__wchar_t_connect_socket_w32spawnl_18_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE78_OS_Command_Injection__wchar_t_connect_socket_w32spawnl_18_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| Java |
require "pivotal/sass/version"
module Pivotal
module Sass
class Engine < ::Rails::Engine
end
end
end
| Java |
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 200);
$table->string('provider');
$table->string('provider_id');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
| Java |
<html><body>
<h4>Windows 10 x64 (19041.208) 2004</h4><br>
<h2>_HEAP_DESCRIPTOR_KEY</h2>
<font face="arial"> +0x000 Key : Uint4B<br>
+0x000 EncodedCommittedPageCount : Pos 0, 16 Bits<br>
+0x000 LargePageCost : Pos 16, 8 Bits<br>
+0x000 UnitCount : Pos 24, 8 Bits<br>
</font></body></html> | Java |
<?php
/*
*
*/
namespace RDF\JobDefinitionFormatBundle\Type;
/**
*
*
* @author Richard Fullmer <richardfullmer@gmail.com>
*/
class CMYKColor
{
/**
* @var float
*/
protected $cyan;
/**
* @var float
*/
protected $magenta;
/**
* @var float
*/
protected $yellow;
/**
* @var float
*/
protected $black;
/**
* @param float $cyan
* @param float $magenta
* @param float $yellow
* @param float $black
*/
public function __construct($cyan, $magenta, $yellow, $black)
{
$this->cyan = (float) $cyan;
$this->magenta = (float) $magenta;
$this->yellow = (float) $yellow;
$this->black = (float) $black;
}
/**
* @param float $black
*/
public function setBlack($black)
{
$this->black = (float) $black;
}
/**
* @return float
*/
public function getBlack()
{
return $this->black;
}
/**
* @param float $cyan
*/
public function setCyan($cyan)
{
$this->cyan = (float) $cyan;
}
/**
* @return float
*/
public function getCyan()
{
return $this->cyan;
}
/**
* @param float $magenta
*/
public function setMagenta($magenta)
{
$this->magenta = (float) $magenta;
}
/**
* @return float
*/
public function getMagenta()
{
return $this->magenta;
}
/**
* @param float $yellow
*/
public function setYellow($yellow)
{
$this->yellow = (float) $yellow;
}
/**
* @return float
*/
public function getYellow()
{
return $this->yellow;
}
}
| Java |
<html>
<head>
<title> Install SEO Commerce</title>
<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
<style>
#container {
margin:auto;
}
label, input {
display: block;
}
</style>
</head>
<body>
<div class="container">
<form action="pasang_p.php" method="POST">
<label> Nama Situs </label>
<input type="text" name="s_name">
<label> Author (Nama Pemilik) </label>
<input type="text" name="s_author">
<label> Username </label>
<input type="text" name="a_username">
<label> Password </label>
<input type="password" name="a_password">
<input type="submit" value="kirim">
</form>
</div>
</body>
<html> | Java |
Turbocoin Core version 0.9.0 is now available from:
https://turbocoin.us/bin/0.9.0/
This is a new major version release, bringing both new features and
bug fixes.
Please report bugs using the issue tracker at github:
https://github.com/turbocoin/turbocoin/issues
How to Upgrade
--------------
If you are running an older version, shut it down. Wait until it has completely
shut down (which might take a few minutes for older versions), uninstall all
earlier versions of Turbocoin, then run the installer (on Windows) or just copy
over /Applications/Turbocoin-Qt (on Mac) or turbocoind/turbocoin-qt (on Linux).
If you are upgrading from version 0.7.2 or earlier, the first time you run
0.9.0 your blockchain files will be re-indexed, which will take anywhere from
30 minutes to several hours, depending on the speed of your machine.
On Windows, do not forget to uninstall all earlier versions of the Turbocoin
client first, especially if you are switching to the 64-bit version.
Windows 64-bit installer
-------------------------
New in 0.9.0 is the Windows 64-bit version of the client. There have been
frequent reports of users running out of virtual memory on 32-bit systems
during the initial sync. Because of this it is recommended to install the
64-bit version if your system supports it.
NOTE: Release candidate 2 Windows binaries are not code-signed; use PGP
and the SHA256SUMS.asc file to make sure your binaries are correct.
In the final 0.9.0 release, Windows setup.exe binaries will be code-signed.
OSX 10.5 / 32-bit no longer supported
-------------------------------------
0.9.0 drops support for older Macs. The minimum requirements are now:
* A 64-bit-capable CPU (see http://support.apple.com/kb/ht3696);
* Mac OS 10.6 or later (see https://support.apple.com/kb/ht1633).
Downgrading warnings
--------------------
The 'chainstate' for this release is not always compatible with previous
releases, so if you run 0.9 and then decide to switch back to a
0.8.x release you might get a blockchain validation error when starting the
old release (due to 'pruned outputs' being omitted from the index of
unspent transaction outputs).
Running the old release with the -reindex option will rebuild the chainstate
data structures and correct the problem.
Also, the first time you run a 0.8.x release on a 0.9 wallet it will rescan
the blockchain for missing spent coins, which will take a long time (tens
of minutes on a typical machine).
Rebranding to Turbocoin Core
---------------------------
To reduce confusion between Turbocoin-the-network and Turbocoin-the-software we
have renamed the reference client to Turbocoin Core.
OP_RETURN and data in the block chain
-------------------------------------
On OP_RETURN: There was been some confusion and misunderstanding in
the community, regarding the OP_RETURN feature in 0.9 and data in the
blockchain. This change is not an endorsement of storing data in the
blockchain. The OP_RETURN change creates a provably-prunable output,
to avoid data storage schemes -- some of which were already deployed --
that were storing arbitrary data such as images as forever-unspendable
TX outputs, bloating turbocoin's UTXO database.
Storing arbitrary data in the blockchain is still a bad idea; it is less
costly and far more efficient to store non-currency data elsewhere.
Autotools build system
-----------------------
For 0.9.0 we switched to an autotools-based build system instead of individual
(q)makefiles.
Using the standard "./autogen.sh; ./configure; make" to build Turbocoin-Qt and
turbocoind makes it easier for experienced open source developers to contribute
to the project.
Be sure to check doc/build-*.md for your platform before building from source.
Turbocoin-cli
-------------
Another change in the 0.9 release is moving away from the turbocoind executable
functioning both as a server and as a RPC client. The RPC client functionality
("tell the running turbocoin daemon to do THIS") was split into a separate
executable, 'turbocoin-cli'. The RPC client code will eventually be removed from
turbocoind, but will be kept for backwards compatibility for a release or two.
`walletpassphrase` RPC
-----------------------
The behavior of the `walletpassphrase` RPC when the wallet is already unlocked
has changed between 0.8 and 0.9.
The 0.8 behavior of `walletpassphrase` is to fail when the wallet is already unlocked:
> walletpassphrase 1000
walletunlocktime = now + 1000
> walletpassphrase 10
Error: Wallet is already unlocked (old unlock time stays)
The new behavior of `walletpassphrase` is to set a new unlock time overriding
the old one:
> walletpassphrase 1000
walletunlocktime = now + 1000
> walletpassphrase 10
walletunlocktime = now + 10 (overriding the old unlock time)
Transaction malleability-related fixes
--------------------------------------
This release contains a few fixes for transaction ID (TXID) malleability
issues:
- -nospendzeroconfchange command-line option, to avoid spending
zero-confirmation change
- IsStandard() transaction rules tightened to prevent relaying and mining of
mutated transactions
- Additional information in listtransactions/gettransaction output to
report wallet transactions that conflict with each other because
they spend the same outputs.
- Bug fixes to the getbalance/listaccounts RPC commands, which would report
incorrect balances for double-spent (or mutated) transactions.
- New option: -zapwallettxes to rebuild the wallet's transaction information
Transaction Fees
----------------
This release drops the default fee required to relay transactions across the
network and for miners to consider the transaction in their blocks to
0.01mTURBO per kilobyte.
Note that getting a transaction relayed across the network does NOT guarantee
that the transaction will be accepted by a miner; by default, miners fill
their blocks with 50 kilobytes of high-priority transactions, and then with
700 kilobytes of the highest-fee-per-kilobyte transactions.
The minimum relay/mining fee-per-kilobyte may be changed with the
minrelaytxfee option. Note that previous releases incorrectly used
the mintxfee setting to determine which low-priority transactions should
be considered for inclusion in blocks.
The wallet code still uses a default fee for low-priority transactions of
0.1mTURBO per kilobyte. During periods of heavy transaction volume, even this
fee may not be enough to get transactions confirmed quickly; the mintxfee
option may be used to override the default.
0.9.0 Release notes
=======================
RPC:
- New notion of 'conflicted' transactions, reported as confirmations: -1
- 'listreceivedbyaddress' now provides tx ids
- Add raw transaction hex to 'gettransaction' output
- Updated help and tests for 'getreceivedby(account|address)'
- In 'getblock', accept 2nd 'verbose' parameter, similar to getrawtransaction,
but defaulting to 1 for backward compatibility
- Add 'verifychain', to verify chain database at runtime
- Add 'dumpwallet' and 'importwallet' RPCs
- 'keypoolrefill' gains optional size parameter
- Add 'getbestblockhash', to return tip of best chain
- Add 'chainwork' (the total work done by all blocks since the genesis block)
to 'getblock' output
- Make RPC password resistant to timing attacks
- Clarify help messages and add examples
- Add 'getrawchangeaddress' call for raw transaction change destinations
- Reject insanely high fees by default in 'sendrawtransaction'
- Add RPC call 'decodescript' to decode a hex-encoded transaction script
- Make 'validateaddress' provide redeemScript
- Add 'getnetworkhashps' to get the calculated network hashrate
- New RPC 'ping' command to request ping, new 'pingtime' and 'pingwait' fields
in 'getpeerinfo' output
- Adding new 'addrlocal' field to 'getpeerinfo' output
- Add verbose boolean to 'getrawmempool'
- Add rpc command 'getunconfirmedbalance' to obtain total unconfirmed balance
- Explicitly ensure that wallet is unlocked in `importprivkey`
- Add check for valid keys in `importprivkey`
Command-line options:
- New option: -nospendzeroconfchange to never spend unconfirmed change outputs
- New option: -zapwallettxes to rebuild the wallet's transaction information
- Rename option '-tor' to '-onion' to better reflect what it does
- Add '-disablewallet' mode to let turbocoind run entirely without wallet (when
built with wallet)
- Update default '-rpcsslciphers' to include TLSv1.2
- make '-logtimestamps' default on and rework help-message
- RPC client option: '-rpcwait', to wait for server start
- Remove '-logtodebugger'
- Allow `-noserver` with turbocoind
Block-chain handling and storage:
- Update leveldb to 1.15
- Check for correct genesis (prevent cases where a datadir from the wrong
network is accidentally loaded)
- Allow txindex to be removed and add a reindex dialog
- Log aborted block database rebuilds
- Store orphan blocks in serialized form, to save memory
- Limit the number of orphan blocks in memory to 750
- Fix non-standard disconnected transactions causing mempool orphans
- Add a new checkpoint at block 279,000
Wallet:
- Bug fixes and new regression tests to correctly compute
the balance of wallets containing double-spent (or mutated) transactions
- Store key creation time. Calculate whole-wallet birthday.
- Optimize rescan to skip blocks prior to birthday
- Let user select wallet file with -wallet=foo.dat
- Consider generated coins mature at 101 instead of 120 blocks
- Improve wallet load time
- Don't count txins for priority to encourage sweeping
- Don't create empty transactions when reading a corrupted wallet
- Fix rescan to start from beginning after importprivkey
- Only create signatures with low S values
Mining:
- Increase default -blockmaxsize/prioritysize to 750K/50K
- 'getblocktemplate' does not require a key to create a block template
- Mining code fee policy now matches relay fee policy
Protocol and network:
- Drop the fee required to relay a transaction to 0.01mTURBO per kilobyte
- Send tx relay flag with version
- New 'reject' P2P message (BIP 0061, see
https://gist.github.com/gavinandresen/7079034 for draft)
- Dump addresses every 15 minutes instead of 10 seconds
- Relay OP_RETURN data TxOut as standard transaction type
- Remove CENT-output free transaction rule when relaying
- Lower maximum size for free transaction creation
- Send multiple inv messages if mempool.size > MAX_INV_SZ
- Split MIN_PROTO_VERSION into INIT_PROTO_VERSION and MIN_PEER_PROTO_VERSION
- Do not treat fFromMe transaction differently when broadcasting
- Process received messages one at a time without sleeping between messages
- Improve logging of failed connections
- Bump protocol version to 70002
- Add some additional logging to give extra network insight
- Added new DNS seed from turbocoinstats.com
Validation:
- Log reason for non-standard transaction rejection
- Prune provably-unspendable outputs, and adapt consistency check for it.
- Detect any sufficiently long fork and add a warning
- Call the -alertnotify script when we see a long or invalid fork
- Fix multi-block reorg transaction resurrection
- Reject non-canonically-encoded serialization sizes
- Reject dust amounts during validation
- Accept nLockTime transactions that finalize in the next block
Build system:
- Switch to autotools-based build system
- Build without wallet by passing `--disable-wallet` to configure, this
removes the BerkeleyDB dependency
- Upgrade gitian dependencies (libpng, libz, libupnpc, boost, openssl) to more
recent versions
- Windows 64-bit build support
- Solaris compatibility fixes
- Check integrity of gitian input source tarballs
- Enable full GCC Stack-smashing protection for all OSes
GUI:
- Switch to Qt 5.2.0 for Windows build
- Add payment request (BIP 0070) support
- Improve options dialog
- Show transaction fee in new send confirmation dialog
- Add total balance in overview page
- Allow user to choose data directory on first start, when data directory is
missing, or when the -choosedatadir option is passed
- Save and restore window positions
- Add vout index to transaction id in transactions details dialog
- Add network traffic graph in debug window
- Add open URI dialog
- Add Coin Control Features
- Improve receive coins workflow: make the 'Receive' tab into a form to request
payments, and move historical address list functionality to File menu.
- Rebrand to `Turbocoin Core`
- Move initialization/shutdown to a thread. This prevents "Not responding"
messages during startup. Also show a window during shutdown.
- Don't regenerate autostart link on every client startup
- Show and store message of normal turbocoin:URI
- Fix richtext detection hang issue on very old Qt versions
- OS X: Make use of the 10.8+ user notification center to display Growl-like
notifications
- OS X: Added NSHighResolutionCapable flag to Info.plist for better font
rendering on Retina displays.
- OS X: Fix turbocoin-qt startup crash when clicking dock icon
- Linux: Fix Gnome turbocoin: URI handler
Miscellaneous:
- Add Linux script (contrib/qos/tc.sh) to limit outgoing bandwidth
- Add '-regtest' mode, similar to testnet but private with instant block
generation with 'setgenerate' RPC.
- Add 'linearize.py' script to contrib, for creating bootstrap.dat
- Add separate turbocoin-cli client
Credits
--------
Thanks to everyone who contributed to this release:
- Andrey
- Ashley Holman
- b6393ce9-d324-4fe1-996b-acf82dbc3d53
- bitsofproof
- Brandon Dahler
- Calvin Tam
- Christian Decker
- Christian von Roques
- Christopher Latham
- Chuck
- coblee
- constantined
- Cory Fields
- Cozz Lovan
- daniel
- Daniel Larimer
- David Hill
- Dmitry Smirnov
- Drak
- Eric Lombrozo
- fanquake
- fcicq
- Florin
- frewil
- Gavin Andresen
- Gregory Maxwell
- gubatron
- Guillermo Céspedes Tabárez
- Haakon Nilsen
- HaltingState
- Han Lin Yap
- harry
- Ian Kelling
- Jeff Garzik
- Johnathan Corgan
- Jonas Schnelli
- Josh Lehan
- Josh Triplett
- Julian Langschaedel
- Kangmo
- Lake Denman
- Luke Dashjr
- Mark Friedenbach
- Matt Corallo
- Michael Bauer
- Michael Ford
- Michagogo
- Midnight Magic
- Mike Hearn
- Nils Schneider
- Noel Tiernan
- Olivier Langlois
- patrick s
- Patrick Strateman
- paveljanik
- Peter Todd
- phantomcircuit
- phelixbtc
- Philip Kaufmann
- Pieter Wuille
- Rav3nPL
- R E Broadley
- regergregregerrge
- Robert Backhaus
- Roman Mindalev
- Rune K. Svendsen
- Ryan Niebur
- Scott Ellis
- Scott Willeke
- Sergey Kazenyuk
- Shawn Wilkinson
- Sined
- sje
- Subo1978
- super3
- Tamas Blummer
- theuni
- Thomas Holenstein
- Timon Rapp
- Timothy Stranex
- Tom Geller
- Torstein Husebø
- Vaclav Vobornik
- vhf / victor felder
- Vinnie Falco
- Warren Togami
- Wil Bown
- Wladimir J. van der Laan
| Java |
{{ define "main" }}
<!-- Header -->
{{ partial "header" . }}
<div class="container">
<section id="projects">
<h4 class="my-5">{{ .Site.Data.projects.name }}</h4>
<div class="panel">
<div class="panel-body">
{{ range $el := .Site.Data.projects.source }}
<h5>
<i class="{{ .icon }}"></i>
<b><a href="{{ .url }}">{{ $el.name }}</a></b> - {{ $el.description }}
</h5>
{{ end }}
</div>
</div>
</section>
</div>
{{ end }}
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DebtSnowBall2017
{
class LoanList
{
private List<Loan> loanList;
public LoanList()
{
this.loanList = new List<Loan>();
}
public void addLoan(Loan newLoan)
{
this.loanList.Add(newLoan);
this.loanList.Sort(delegate(Loan L1, Loan L2){ return L1.getTotalOwed().CompareTo(L2.getTotalOwed()); });
}
public void printToScreen(TableLayoutPanel panel)
{
panel.Controls.Clear();
foreach(Loan loan in loanList)
{
Label principle = new Label();
principle.Text = Convert.ToString(loan.getPrinciple());
panel.Controls.Add(principle);
Label interest = new Label();
interest.Text = Convert.ToString(loan.getInterest() * 100) + "%";
panel.Controls.Add(interest);
Label monthsToPay = new Label();
if (loan.getMonthsToPay() <= 0)
{
monthsToPay.Text = "Not Yet Calculated";
}
else
{
monthsToPay.Text = Convert.ToString(loan.getMonthsToPay());
}
panel.Controls.Add(monthsToPay);
Label totalPaid = new Label();
if (loan.getTotalPaid() < 0)
{
totalPaid.Text = "Not Yet Calculated";
}
else
{
totalPaid.Text = Convert.ToString(loan.getTotalPaid());
}
panel.Controls.Add(totalPaid);
}
}
public bool allPaid()
{
foreach(Loan loan in loanList)
{
if (!loan.isFullyPaid())
{
return false;
}
}
return true;
}
public void calculate(double salary)
{
while (!allPaid())
{
double thisMonthsSalary = salary;
foreach (Loan nextLoan in this.loanList)
{
thisMonthsSalary = nextLoan.payMonthlyBill(thisMonthsSalary);
}
foreach (Loan nextLoan in this.loanList)
{
if (!nextLoan.isFullyPaid())
{
nextLoan.payExtra(thisMonthsSalary);
break;
}
}
}
}
}
}
| Java |
---
layout: default
title: Отправить совет!
---
<div class="grid_8 alpha omega white">
<h2>Отправить совет!</h2>
<iframe src="http://spreadsheets.google.com/embeddedform?key=pNxLaOX4yIJnLpmHYEDxXXQ" width="590" height="616" frameborder="0" marginheight="0" marginwidth="0">Загрузка...</iframe>
</div>
| Java |
package render
import (
"github.com/gin-gonic/gin"
)
/* ================================================================================
* Render 工具模块
* qq group: 582452342
* email : 2091938785@qq.com
* author : 美丽的地球啊 - mliu
* ================================================================================ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* 输出错误消息
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
func Error(c *gin.Context, msg string) {
String(c, msg, 400)
}
| Java |
/*
* _____ _ _ _ _____ _ _ _ _____ _ __ _____ _____
* / ___| | | | | | | |_ _| | | / / | | | ____| | | / / | ____| | _ \
* | | | | | | | | | | | | / / | | | |__ | | __ / / | |__ | |_| |
* | | _ | | | | | | | | | | / / | | | __| | | / | / / | __| | _ /
* | |_| | | |___ | |_| | | | | |/ / | | | |___ | |/ |/ / | |___ | | \ \
* \_____/ |_____| \_____/ |_| |___/ |_| |_____| |___/|___/ |_____| |_| \_\
*
* Version 0.9
* Bruno Levy, August 2006
* INRIA, Project ALICE
*
*/
#include "glut_viewer_gui.h"
#include <GLsdk/gl_stuff.h>
#include <GL/glut.h>
#include <iostream>
#include <stdarg.h>
#include <math.h>
#include <stdio.h>
namespace GlutViewerGUI {
// ------------------- Primitives for internal use --------------------------------------
static void printf_xy(GLfloat x, GLfloat y, const char *format, ...) {
va_list args;
char buffer[1024], *p;
va_start(args, format);
vsprintf(buffer, format, args);
va_end(args);
glPushMatrix();
glTranslatef(x, y, 0);
for (p = buffer; *p; p++) {
glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, *p);
}
glPopMatrix();
}
static void circle_arc_vertices(
GLfloat x, GLfloat y, GLfloat r1, GLfloat r2, GLfloat theta1, GLfloat theta2
) {
const GLfloat delta_theta = 1.0f ;
if(theta2 > theta1) {
for(GLfloat theta = theta1; theta <= theta2; theta += delta_theta) {
GLfloat theta_rad = theta * 3.14159f / 200.0f ;
glVertex2f(x + r1 * cos(theta_rad), y + r2 * sin(theta_rad)) ;
}
} else {
for(GLfloat theta = theta1; theta >= theta2; theta -= delta_theta) {
GLfloat theta_rad = theta * 3.14159f / 200.0f ;
glVertex2f(x + r1 * cos(theta_rad), y + r2 * sin(theta_rad)) ;
}
}
}
static void circle_arc_vertices(
GLfloat x, GLfloat y, GLfloat r, GLfloat theta1, GLfloat theta2
) {
circle_arc_vertices(x,y,r,r,theta1,theta2) ;
}
static void circle(GLfloat x, GLfloat y, GLfloat r) {
glBegin(GL_LINE_LOOP) ;
circle_arc_vertices(x,y,r,0.0f,400.0f) ;
glEnd() ;
}
static void fill_circle(GLfloat x, GLfloat y, GLfloat r) {
glBegin(GL_POLYGON) ;
circle_arc_vertices(x,y,r,0.0f,400.0f) ;
glEnd() ;
}
static void round_rectangle_vertices(
GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2, GLfloat r
) {
glVertex2f(x1+r,y2) ;
glVertex2f(x2-r,y2) ;
circle_arc_vertices(x2-r, y2-r, r, 100.0f, 0.0f) ;
glVertex2f(x2,y2-r) ;
glVertex2f(x2,y1+r) ;
circle_arc_vertices(x2-r, y1+r, r, 0.0f, -100.0f) ;
glVertex2f(x2-r,y1) ;
glVertex2f(x1+r,y1) ;
circle_arc_vertices(x1+r, y1+r, r, -100.0f, -200.0f) ;
glVertex2f(x1,y1+r) ;
glVertex2f(x1,y2-r) ;
circle_arc_vertices(x1+r, y2-r, r, -200.0f, -300.0f) ;
}
static void round_rectangle(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2, GLfloat r) {
glBegin(GL_LINE_LOOP) ;
round_rectangle_vertices(x1, y1, x2, y2, r) ;
glEnd() ;
}
static void fill_round_rectangle(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2, GLfloat r) {
glBegin(GL_POLYGON) ;
round_rectangle_vertices(x1, y1, x2, y2, r) ;
glEnd() ;
}
static void arrow_vertices(Direction dir, GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2) {
GLfloat x12 = 0.5 * (x1 + x2) ;
GLfloat y12 = 0.5 * (y1 + y2) ;
switch(dir) {
case DOWN:
glVertex2f(x1,y2) ;
glVertex2f(x2,y2) ;
glVertex2f(x12,y1) ;
break ;
case UP:
glVertex2f(x1,y1) ;
glVertex2f(x2,y1) ;
glVertex2f(x12,y2) ;
break ;
case LEFT:
glVertex2f(x2,y2) ;
glVertex2f(x2,y1) ;
glVertex2f(x1,y12) ;
break ;
case RIGHT:
glVertex2f(x1,y2) ;
glVertex2f(x1,y1) ;
glVertex2f(x2,y12) ;
break ;
}
}
static void arrow(Direction dir, GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2) {
glBegin(GL_LINE_LOOP) ;
arrow_vertices(dir, x1, y1, x2, y2) ;
glEnd() ;
}
static void fill_arrow(Direction dir, GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2) {
glBegin(GL_POLYGON) ;
arrow_vertices(dir, x1, y1, x2, y2) ;
glEnd() ;
}
// ------------------- Widget class --------------------------------------
Widget::Widget(
GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2
) : style_(BlueStyle), visible_(true), highlight_(false) {
set_geometry(x1, y1, x2, y2) ;
r_ = 100.0f ;
}
Widget::~Widget() {
}
void Widget::glColor(ColorRole role_in) {
ColorRole role = role_in ;
if(highlight_) {
switch(role_in) {
case Background:
role = Foreground ; break ;
case Middleground:
role = Middleground ; break ;
case Foreground:
role = Foreground ; break ;
}
}
switch(style_) {
case RedStyle: {
switch(role) {
case Background:
glColor4f(0.5f, 0.0f, 0.0f, 0.5f) ;
break ;
case Middleground:
glColor4f(1.0f, 0.5f, 0.5f, 1.0f) ;
break ;
case Foreground:
glColor4f(5.0f, 5.0f, 5.0f, 1.0f) ;
break ;
}
} break ;
case GreenStyle: {
switch(role) {
case Background:
glColor4f(0.0f, 0.5f, 0.0f, 0.5f) ;
break ;
case Middleground:
glColor4f(0.5f, 1.0f, 0.5f, 1.0f) ;
break ;
case Foreground:
glColor4f(5.0f, 5.0f, 5.0f, 1.0f) ;
break ;
}
} break ;
case BlueStyle: {
switch(role) {
case Background:
glColor4f(0.0f, 0.0f, 0.5f, 0.5f) ;
break ;
case Middleground:
glColor4f(0.5f, 0.5f, 1.0f, 1.0f) ;
break ;
case Foreground:
glColor4f(5.0f, 5.0f, 5.0f, 1.0f) ;
break ;
}
} break ;
case BWStyle: {
switch(role) {
case Background:
glColor4f(5.0f, 5.0f, 5.0f, 0.5f) ;
break ;
case Middleground:
glColor4f(0.2f, 0.2f, 0.2f, 1.0f) ;
break ;
case Foreground:
glColor4f(0.0f, 0.0f, 0.0f, 1.0f) ;
break ;
}
} break ;
}
}
GLboolean Widget::process_mouse_event(float x, float y, int button, GlutViewerEvent event) {
return contains(int(x),int(y)) ;
}
void Widget::draw() {
if(!visible()) { return ; }
draw_background() ;
draw_border() ;
}
void Widget::draw_background() {
glEnable(GL_BLEND) ;
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
glColor(Background) ;
fill_round_rectangle(x1_, y1_, x2_, y2_, r_) ;
glDisable(GL_BLEND) ;
}
void Widget::draw_border() {
glColor(Foreground) ;
glLineWidth(2.0) ;
round_rectangle(x1_, y1_, x2_, y2_, r_) ;
}
//______________________________________________________________________________________________________
Container* Container::main_widget_ = NULL ;
Container::~Container() {
if(main_widget_ == this) {
main_widget_ = NULL ;
}
for(size_t i=0; i<children_.size(); i++) {
delete children_[i] ;
}
}
void Container::draw() {
if(!visible()) {
return ;
}
for(size_t i=0; i<children_.size(); i++) {
children_[i]->draw() ;
}
}
GLboolean Container::process_mouse_event(float x, float y, int button, GlutViewerEvent event) {
if(!visible()) { return GL_FALSE ; }
switch(event) {
case GLUT_VIEWER_DOWN: {
for(size_t i=0; i<children_.size(); i++) {
if(children_[i]->contains(x,y) && children_[i]->process_mouse_event(x, y, button, event)) {
active_child_ = children_[i] ;
return GL_TRUE ;
}
}
} break ;
case GLUT_VIEWER_MOVE: {
if(active_child_ != NULL) {
return active_child_->process_mouse_event(x, y, button, event) ;
}
} break ;
case GLUT_VIEWER_UP: {
if(active_child_ != NULL) {
Widget* w = active_child_ ;
active_child_ = NULL ;
return w->process_mouse_event(x, y, button, event) ;
}
} break ;
}
return GL_FALSE ;
}
void Container::draw_handler() {
if(main_widget_ != NULL) {
main_widget_->draw() ;
}
}
GLboolean Container::mouse_handler(float x, float y, int button, enum GlutViewerEvent event) {
if(main_widget_ != NULL) {
return main_widget_->process_mouse_event(x, y, button, event) ;
}
return GL_FALSE ;
}
void Container::set_as_main_widget() {
main_widget_ = this ;
glut_viewer_set_overlay_func(draw_handler) ;
glut_viewer_set_mouse_func(mouse_handler) ;
}
//______________________________________________________________________________________________________
void Panel::draw() {
Widget::draw() ;
Container::draw() ;
}
GLboolean Panel::process_mouse_event(float x, float y, int button, GlutViewerEvent event) {
if(!visible() || !contains(x,y)) {
return GL_FALSE ;
}
return Container::process_mouse_event(x,y,button,event) ;
}
//______________________________________________________________________________________________________
void Button::draw() {
Widget::draw() ;
}
GLboolean Button::process_mouse_event(float x, float y, int button, GlutViewerEvent event) {
if(visible() && contains(x,y) && event == GLUT_VIEWER_DOWN) {
pressed() ;
highlight_ = GL_TRUE ;
return GL_TRUE ;
}
if(visible() && contains(x,y) && event == GLUT_VIEWER_UP) {
highlight_ = GL_FALSE ;
return GL_TRUE ;
}
return GL_FALSE ;
}
void Button::pressed() {
if(callback_ != NULL) {
callback_(client_data_) ;
}
}
//______________________________________________________________________________________________________
void Checkbox::draw() {
if(!visible()) { return ; }
Button::draw() ;
glColor(Foreground) ;
GLfloat x = 0.5f * (x1_ + x2_) ;
GLfloat y = 0.5f * (y1_ + y2_) ;
if(toggle_) {
glColor(Middleground) ;
fill_circle(x,y,d_) ;
glColor(Foreground) ;
glLineWidth(1.0f) ;
circle(x,y,d_) ;
}
}
void Checkbox::pressed() {
toggle_ = !toggle_ ;
}
//______________________________________________________________________________________________________
ArrowButton::ArrowButton(
Direction dir, GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2
) : Button(x1, y1, x2, y2), direction_(dir) {
d_ /= 1.5 ;
r_ /= 2.0 ;
}
void ArrowButton::draw() {
Button::draw() ;
glColor(Middleground) ;
fill_arrow(direction_, x1_ + d_, y1_ + d_, x2_ - d_, y2_ - d_) ;
glColor(Foreground);
arrow(direction_, x1_ + d_, y1_ + d_, x2_ - d_, y2_ - d_) ;
}
//______________________________________________________________________________________________________
void Slider::set_value(GLfloat x, bool update) {
if(integer_) { x = GLfloat(GLint(x)) ; }
if(x < min_) { x = min_ ; }
if(x > max_) { x = max_ ; }
value_ = x ;
if(update && callback_ != NULL) { callback_(value_) ; }
}
void Slider::set_range(GLfloat x1, GLfloat x2) {
min_ = x1 ;
max_ = x2 ;
if(value_ < min_) { set_value(min_) ; }
if(value_ > max_) { set_value(max_) ; }
}
void Slider::draw() {
if(!visible()) { return ; }
Widget::draw() ;
glColor(Middleground) ;
glLineWidth(2.0f) ;
glBegin(GL_LINES) ;
glVertex2f(x1_+d_, 0.5f*(y1_+y2_)) ;
glVertex2f(x2_-d_, 0.5f*(y1_+y2_)) ;
glEnd() ;
GLfloat w = (value_ - min_) / (max_ - min_) ;
GLfloat x = w*(x2_ - d_) + (1.0f - w)*(x1_ + d_) ;
GLfloat y = 0.5f*(y1_+y2_) ;
glColor(Middleground) ;
fill_circle(x,y,d_) ;
glColor(Foreground) ;
glLineWidth(1.0f) ;
circle(x,y,d_) ;
}
GLboolean Slider::process_mouse_event(float x, float y, int button, GlutViewerEvent event) {
if(!visible()) { return GL_FALSE ; }
if(event == GLUT_VIEWER_DOWN || event == GLUT_VIEWER_MOVE) {
GLfloat w = GLfloat(x - x1_ - d_) / GLfloat(x2_ - x1_ - 2.0f * d_) ;
set_value((1.0f - w) * min_ + w * max_, continuous_update_ == GL_TRUE) ;
return GL_TRUE ;
} else if(event == GLUT_VIEWER_UP) {
set_value(value_) ;
}
return GL_FALSE ;
}
//______________________________________________________________________________________________________
void CurveEditor::draw() {
if(!visible()) { return ; }
draw_background() ;
// Draw grid
glColor(Middleground) ;
glLineWidth(1.0) ;
glBegin(GL_LINES) ;
for(unsigned int i=1; i<10; i++) {
float x = x1_ + (x2_ - x1_) * float(i) / 10.0f ;
glVertex2f(x, y1_) ;
glVertex2f(x, y2_) ;
}
for(unsigned int i=1; i<4; i++) {
float y = y1_ + (y2_ - y1_) * float(i) / 4.0f ;
glVertex2f(x1_, y) ;
glVertex2f(x2_, y) ;
}
glEnd() ;
// Draw curve
glColor(Foreground) ;
glLineWidth(2.0) ;
glBegin(GL_LINE_STRIP) ;
for(unsigned int i=0; i<CurveSize; i++) {
glVertex2f(
x1_ + (float)i * (x2_ - x1_) / (float)(CurveSize - 1),
y1_ + curve_[i] * (y2_ - y1_)
) ;
}
glEnd() ;
draw_border() ;
}
GLboolean CurveEditor::process_mouse_event(float x, float y, int button, GlutViewerEvent event) {
if(!visible()) {
return GL_FALSE ;
}
if(event == GLUT_VIEWER_DOWN && !contains(x,y)) {
return GL_FALSE ;
}
int i = int((x - x1_) * (CurveSize - 1) / (x2_ - x1_)) ;
GLfloat v = GLfloat(y - y1_) / GLfloat(y2_ - y1_) ;
if(v < 0.0) { v = 0.0 ; }
if(v > 1.0) { v = 1.0 ; }
if(i < 0) { i = 0 ; }
if(i >= CurveSize) { i = CurveSize - 1 ; }
if(event == GLUT_VIEWER_DOWN) {
last_i_ = i ;
last_v_ = v ;
return GL_TRUE ;
}
if(event == GLUT_VIEWER_UP) {
if(callback_ != NULL) {
callback_(curve_, CurveSize) ;
}
return GL_TRUE ;
}
if(event == GLUT_VIEWER_MOVE) {
if(i > last_i_) {
set_curve(last_i_, last_v_, i, v) ;
} else {
set_curve(i, v, last_i_, last_v_) ;
}
}
last_i_ = i ;
last_v_ = v ;
return GL_TRUE ;
}
void CurveEditor::set_curve(int i1, float val1, int i2, float val2) {
if(i1 == i2) {
curve_[i1] = val1 ;
} else {
for(int i=i1; i<=i2; i++) {
curve_[i] = val1 + (float)(i - i1) * (val2 - val1) / (float)(i2 - i1) ;
}
}
}
void CurveEditor::set_curve(GLfloat* curve, bool update) {
for(unsigned int i=0; i<CurveSize; i++) {
curve_[i] = curve[i] ;
}
if(update && callback_ != NULL) {
callback_(curve_, CurveSize) ;
}
}
void CurveEditor::reset(bool update) {
for(unsigned int i=0; i<CurveSize; i++) {
curve_[i] = 0.5f ;
}
if(update && callback_ != NULL) {
callback_(curve_, CurveSize) ;
}
}
void CurveEditor::reset_ramp(bool update) {
for(unsigned int i=0; i<CurveSize; i++) {
curve_[i] = float(i) / float(CurveSize - 1) ;
}
if(update && callback_ != NULL) {
callback_(curve_, CurveSize) ;
}
}
GLfloat CurveEditor::value(GLfloat x) const {
if(x < 0.0f) { x = 0.0f ; }
if(x > 1.0f) { x = 1.0f ; }
return curve_[int(x * (CurveSize - 1))] ;
}
//______________________________________________________________________________________________________
void ColormapEditor::draw() {
if(!visible()) { return ; }
draw_background() ;
// Draw curve
glColor(Foreground) ;
glLineWidth(2.0) ;
glBegin(GL_LINE_STRIP) ;
for(unsigned int i=0; i<ColormapSize; i++) {
glVertex2f(
x1_ + (float)i * (x2_ - x1_) / (float)(ColormapSize - 1),
y1_ + curve()[i] * (y2_ - y1_)
) ;
}
glEnd() ;
draw_border() ;
}
void ColormapEditor::draw_background() {
glEnable(GL_BLEND) ;
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
drawBackgroundCB_(curve(), ColormapSize) ;
glDisable(GL_BLEND) ;
}
void ColormapEditor::draw_border() {
glColor(Foreground) ;
glLineWidth(2.0) ;
glBegin(GL_LINE_LOOP) ;
glVertex2f(x1_, y1_) ;
glVertex2f(x1_, y2_) ;
glVertex2f(x2_, y2_) ;
glVertex2f(x2_, y1_) ;
glEnd() ;
}
void ColormapEditor::update(unsigned char* cmap_data, int size, int component) {
for(unsigned int i = 0; i < ColormapSize; ++i) {
int idx = (double(i) / double(ColormapSize)) * (size-1) ;
curve()[i] = double(cmap_data[4*idx + component]) / 255.0 ;
}
}
//______________________________________________________________________________________________________
void TextLabel::draw() {
if(!visible()) { return ; }
glLineWidth(textwidth_) ;
printf_xy(x1_+10, y1_+50, (char*)text_.c_str()) ;
}
//______________________________________________________________________________________________________
Spinbox::Spinbox(
GLfloat x, GLfloat y, GLenum& value, const std::vector<std::string>& labels
) : Container(x, y, x+3000, y+170), value_(value), labels_(labels) {
down_ = new ArrowButton(DOWN, x, y, x+170, y+170) ;
up_ = new ArrowButton(UP, x+200, y, x+370, y+170) ;
up_->set_callback(increment_CB, this) ;
down_->set_callback(decrement_CB, this) ;
if(value_ < 0) { value_ = 0 ; }
if(value_ >= int(labels_.size())) { value_ = (GLenum)(labels_.size() - 1) ; }
text_ = new TextLabel(x+450,y,labels_[value_]) ;
add_child(up_) ;
add_child(down_) ;
add_child(text_) ;
show() ;
}
void Spinbox::draw() {
Container::draw() ;
}
void Spinbox::increment() {
value_++ ;
if(value_ >= labels_.size()) { value_ = 0 ; }
text_->set_text(labels_[value_]) ;
}
void Spinbox::decrement() {
if(int(value_) - 1 < 0) {
value_ = (GLenum)(labels_.size() - 1) ;
} else {
value_-- ;
}
text_->set_text(labels_[value_]) ;
}
void Spinbox::increment_CB(void* spinbox) {
static_cast<Spinbox*>(spinbox)->increment() ;
}
void Spinbox::decrement_CB(void* spinbox) {
static_cast<Spinbox*>(spinbox)->decrement() ;
}
//______________________________________________________________________________________________________
void MessageBox::draw() {
if(!visible()) { return ; }
Panel::draw() ;
glLineWidth(2) ;
for(unsigned int i=0; i<message_.size(); i++) {
printf_xy(x1_+100, y2_-200-i*150, (char*)message_[i].c_str()) ;
}
}
//______________________________________________________________________________________________________
PropertyPage::PropertyPage(
GLfloat x_in, GLfloat y_in, const std::string& caption
) : Panel(x_in,y_in-10,x_in+Width,y_in) {
y_ = y2_ - 200 ;
x_caption_ = x1_ + 100 ;
x_widget_ = x1_ + 1300 ;
caption_ = add_separator(caption) ;
y1_ = y_ ;
}
TextLabel* PropertyPage::add_separator(const std::string& text) {
TextLabel* w = new TextLabel(x1_ + 400, y_, text, 2.0f) ;
add_child(w) ;
y_ -= 250 ;
y1_ = y_ ;
return w ;
}
TextLabel* PropertyPage::add_string(const std::string& text) {
TextLabel* w = new TextLabel(x1_ + 200, y_, text, 1.0f) ;
add_child(w) ;
y_ -= 150 ;
y1_ = y_ ;
return w ;
}
Slider* PropertyPage::add_slider(
const std::string& caption, GLfloat& value, GLfloat vmin, GLfloat vmax
) {
add_child(new TextLabel(x_caption_, y_, caption)) ;
Slider* w = new Slider(x_widget_, y_, x_widget_+800, y_+200, value) ;
w->set_range(vmin, vmax) ;
add_child(w) ;
y_ -= 250 ;
y1_ = y_ ;
return w ;
}
Checkbox* PropertyPage::add_toggle(
const std::string& caption, GLboolean& value
) {
add_child(new TextLabel(x_caption_, y_, caption)) ;
Checkbox* w = new Checkbox(x_widget_, y_, x_widget_+200, y_+200, value) ;
add_child(w) ;
y_ -= 250 ;
y1_ = y_ ;
return w ;
}
Spinbox* PropertyPage::add_enum(
const std::string& caption, GLenum& value, const std::vector<std::string>& labels) {
add_child(new TextLabel(x_caption_, y_, caption)) ;
Spinbox* w = new Spinbox(x_widget_, y_, value, labels) ;
add_child(w) ;
y_ -= 250 ;
y1_ = y_ ;
return w ;
}
//______________________________________________________________________________________________________
ViewerProperties::ViewerProperties(GLfloat x_left, GLfloat y_top) : PropertyPage(
x_left, y_top, "Viewer"
) {
add_toggle("Rot. light", *glut_viewer_is_enabled_ptr(GLUT_VIEWER_ROTATE_LIGHT)) ;
if(glut_viewer_is_enabled(GLUT_VIEWER_HDR)) {
add_slider("Exposure", *glut_viewer_float_ptr(GLUT_VIEWER_HDR_EXPOSURE), 0.001, 3.0) ;
add_slider("Gamma", *glut_viewer_float_ptr(GLUT_VIEWER_HDR_GAMMA), 0.2, 1.5) ;
add_toggle("Vignette", *glut_viewer_is_enabled_ptr(GLUT_VIEWER_HDR_VIGNETTE)) ;
add_slider("Blur amount", *glut_viewer_float_ptr(GLUT_VIEWER_HDR_BLUR_AMOUNT)) ;
add_slider("Blur width", *glut_viewer_float_ptr(GLUT_VIEWER_HDR_BLUR_WIDTH), 1.0, 20.0) ;
add_toggle("UnMsk.", *glut_viewer_is_enabled_ptr(GLUT_VIEWER_HDR_UNSHARP_MASKING)) ;
add_toggle("UnMsk.+", *glut_viewer_is_enabled_ptr(GLUT_VIEWER_HDR_POSITIVE_UNSHARP_MASKING)) ;
add_slider("UnMsk. Gamm", *glut_viewer_float_ptr(GLUT_VIEWER_HDR_UNSHARP_MASKING_GAMMA), 0.2, 1.5) ;
}
}
void ViewerProperties::draw() {
if(glut_viewer_is_enabled(GLUT_VIEWER_IDLE_REDRAW)) {
static char buff[256] ;
sprintf(buff, " [%4d FPS]", glut_viewer_fps()) ;
caption_->set_text("Viewer" + std::string(buff)) ;
} else {
caption_->set_text("Viewer") ;
}
PropertyPage::draw() ;
}
void ViewerProperties::apply() {
}
//______________________________________________________________________________________________________
Image::Image(
GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2, GLint texture, GLint target
) : Widget(x1, y1, x2, y2), texture_(texture), texture_target_(target) {
}
void Image::draw() {
if(texture_ == 0) { return ; }
glEnable(texture_target_) ;
glBindTexture(texture_target_, texture_) ;
glBegin(GL_QUADS) ;
glTexCoord2f(0.0, 0.0) ;
glVertex2f(x1_, y1_) ;
glTexCoord2f(1.0, 0.0) ;
glVertex2f(x2_, y1_) ;
glTexCoord2f(1.0, 1.0) ;
glVertex2f(x2_, y2_) ;
glTexCoord2f(0.0, 1.0) ;
glVertex2f(x1_, y2_) ;
glEnd() ;
glDisable(texture_target_) ;
}
//______________________________________________________________________________________________________
}
| Java |
<?php
/**
* Description of aSites
*
* @author almaz
*/
class aSitesUsers extends Action {
protected $defaultAct = 'List';
protected function configure() {
require_once $this->module->pathModels . 'as_Sites.php';
require_once $this->module->pathModels . 'as_SitesUsers.php';
$authModule = General::$loadedModules['Auth'];
require_once $authModule->pathModels . 'au_Users.php';
}
/**setTpl
* выводит список всех сайтов
*/
public function act_List() {
if ($this->request->isAjax()) {
$this->context->setTopTpl('html_list');
} else {
$this->_parent();
$this->context->setTpl('content', 'html_list');
}
$sql = Stmt::prepare2(as_Stmt::GET_SITES_USERS_USER, array('user_id' => $this->userInfo['user']['id']));
$tbl = new oTable(DBExt::selectToTable($sql));
$tbl->setIsDel();
$tbl->setIsEdit();
$tbl->setNamesColumns(array('host'=>'Сайт'));
$tbl->addRulesView('password', '******');
$tbl->sort(Navigation::get('field'), Navigation::get('order'));
$this->context->set('tbl', $tbl);
$this->context->set('h1', 'Мои сайты');
}
/**
* выводит список всех сайтов
*/
public function act_Add() {
if ($this->request->isAjax()) {
$this->context->setTopTpl('site_add_html');
} else {
$this->_parent();
$this->context->setTpl('content', 'site_add_html');
}
$sqlSites = Stmt::prepare2(as_Stmt::ALL_SITES, array(), array (Stmt::ORDER => 'sort'));
$listSites = new oList(DBExt::selectToList($sqlSites));
$fields['site_id'] = array('title' => 'Сайт', 'value' => '', 'data' => $listSites, 'type'=>'select', 'required' => true, 'validator' => null, 'info'=>'Список поддерживаемых на данный момент сайтов', 'error' => false, 'attr' => '', $checked = array());
$fields['login'] = array('title' => 'Логин', 'value'=>'', 'type'=>'text', 'required' => true, 'validator' => null, 'info'=>'', 'error' => false, 'attr' => '', $checked = array());
$fields['password'] = array('title' => 'Пароль', 'value'=>'', 'type'=>'text', 'required' => true, 'validator' => null, 'info'=>'', 'error' => false, 'attr' => '', $checked = array());
$form = new oForm($fields);
$this->context->set('form', $form);
$this->context->set('info_text', 'Добавление настроек для нового сайта...');
if ($this->request->is('POST')) {
$form->fill($this->request->get('POST'));
if ($form->isComplited()) {
$siteUser = new as_SitesUsers();
$siteUser->site_id = $form->getFieldValue('site_id');
$siteUser->login = $form->getFieldValue('login');
$siteUser->password = $form->getFieldValue('password');
$siteUser->user_id = $this->userInfo['user']['id'];
$siteUser->save();
$this->context->del('form');
$this->context->set('info_text', 'Настройки добавлены');
}
}
}
function act_Del () {
$id = (int)$this->request->get('id', 0);
$sqlSites = Stmt::prepare2(as_Stmt::DEL_SITE_USER, array('user_id' => $this->userInfo['user']['id'], 'site_id' => $id));
DB::execute($prepare_stmt);
$sql = Stmt::prepare(se_Stmt::IS_KEYWORDS_SET, array('set_id' => $id, Stmt::LIMIT => 1));
$sitesUsers = new as_SitesUsers((int)$this->request->get('id'));
$sets->delete();
$iRoute = new InternalRoute();
$iRoute->module = 'SEParsing';
$iRoute->action = 'Sets';
$actR = new ActionResolver();
$act = $actR->getInternalAction($iRoute);
$act->runAct();
}
/**
* Функция-обвертка, модули уровнем выще. для отображения
* @param InternalRoute $iRoute
*/
function _parent(InternalRoute $iRoute = null) {
$this->context->set('title', 'Сайты');
if (!$iRoute) {
$iRoute = new InternalRoute();
$iRoute->module = 'Pages';
$iRoute->action = 'Pages';
}
$actR = new ActionResolver();
$act = $actR->getInternalAction($iRoute);
$act->runParentAct();
}
} | Java |
package cz.muni.fi.pa165.mushrooms.service.exceptions;
/**
* @author bkompis
*/
public class EntityOperationServiceException extends MushroomHunterServiceDataAccessException {
public <T> EntityOperationServiceException(String what, String operation, T entity, Throwable e) {
super("Could not " + operation + " " + what + " (" + entity + ").", e);
}
public EntityOperationServiceException(String msg) {
super(msg);
}
public EntityOperationServiceException(String msg, Throwable cause) {
super(msg, cause);
}
}
| Java |
#!/usr/bin/env python
import subprocess
import praw
from hashlib import sha1
from flask import Flask
from flask import Response
from flask import request
from cStringIO import StringIO
from base64 import b64encode
from base64 import b64decode
from ConfigParser import ConfigParser
import OAuth2Util
import os
import markdown
import bleach
# encoding=utf8
import sys
from participantCollection import ParticipantCollection
reload(sys)
sys.setdefaultencoding('utf8')
# Edit Me!
# Each day after you post a signup post, copy its 6-character ID to this array.
signupPageSubmissionIds = [ '7zrrj1', '7zxkpq', '8055hn', '80ddrf', '80nbm1', '80waq3' ]
flaskport = 8993
app = Flask(__name__)
app.debug = True
commentHashesAndComments = {}
def loginAndReturnRedditSession():
config = ConfigParser()
config.read("../reddit-password-credentials.cfg")
user = config.get("Reddit", "user")
password = config.get("Reddit", "password")
# TODO: password auth is going away, and we will soon need to do oauth.
redditSession = praw.Reddit(user_agent='Test Script by /u/foobarbazblarg')
redditSession.login(user, password, disable_warning=True)
# submissions = redditSession.get_subreddit('pornfree').get_hot(limit=5)
# print [str(x) for x in submissions]
return redditSession
def loginOAuthAndReturnRedditSession():
redditSession = praw.Reddit(user_agent='Test Script by /u/foobarbazblarg')
# New version of praw does not require explicit use of the OAuth2Util object. Presumably because reddit now REQUIRES oauth.
# o = OAuth2Util.OAuth2Util(redditSession, print_log=True, configfile="../reddit-oauth-credentials.cfg")
# TODO: Testing comment of refresh. We authenticate fresh every time, so presumably no need to do o.refresh().
# o.refresh(force=True)
return redditSession
def getSubmissionsForRedditSession(redditSession):
# submissions = [redditSession.get_submission(submission_id=submissionId) for submissionId in signupPageSubmissionIds]
submissions = [redditSession.submission(id=submissionId) for submissionId in signupPageSubmissionIds]
for submission in submissions:
submission.comments.replace_more(limit=None)
# submission.replace_more_comments(limit=None, threshold=0)
return submissions
def getCommentsForSubmissions(submissions):
comments = []
for submission in submissions:
commentForest = submission.comments
comments += [comment for comment in commentForest.list() if comment.__class__ == praw.models.Comment]
return comments
def retireCommentHash(commentHash):
with open("retiredcommenthashes.txt", "a") as commentHashFile:
commentHashFile.write(commentHash + '\n')
def retiredCommentHashes():
with open("retiredcommenthashes.txt", "r") as commentHashFile:
# return commentHashFile.readlines()
return commentHashFile.read().splitlines()
@app.route('/moderatesignups.html')
def moderatesignups():
global commentHashesAndComments
commentHashesAndComments = {}
stringio = StringIO()
stringio.write('<html>\n<head>\n</head>\n\n')
# redditSession = loginAndReturnRedditSession()
redditSession = loginOAuthAndReturnRedditSession()
submissions = getSubmissionsForRedditSession(redditSession)
flat_comments = getCommentsForSubmissions(submissions)
retiredHashes = retiredCommentHashes()
i = 1
stringio.write('<iframe name="invisibleiframe" style="display:none;"></iframe>\n')
stringio.write("<h3>")
stringio.write(os.getcwd())
stringio.write("<br>\n")
for submission in submissions:
stringio.write(submission.title)
stringio.write("<br>\n")
stringio.write("</h3>\n\n")
stringio.write('<form action="copydisplayduringsignuptoclipboard.html" method="post" target="invisibleiframe">')
stringio.write('<input type="submit" value="Copy display-during-signup.py stdout to clipboard">')
stringio.write('</form>')
for comment in flat_comments:
# print comment.is_root
# print comment.score
i += 1
commentHash = sha1()
commentHash.update(comment.fullname)
commentHash.update(comment.body.encode('utf-8'))
commentHash = commentHash.hexdigest()
if commentHash not in retiredHashes:
commentHashesAndComments[commentHash] = comment
authorName = str(comment.author) # can be None if author was deleted. So check for that and skip if it's None.
stringio.write("<hr>\n")
stringio.write('<font color="blue"><b>')
stringio.write(authorName) # can be None if author was deleted. So check for that and skip if it's None.
stringio.write('</b></font><br>')
if ParticipantCollection().hasParticipantNamed(authorName):
stringio.write(' <small><font color="green">(member)</font></small>')
# if ParticipantCollection().participantNamed(authorName).isStillIn:
# stringio.write(' <small><font color="green">(in)</font></small>')
# else:
# stringio.write(' <small><font color="red">(out)</font></small>')
else:
stringio.write(' <small><font color="red">(not a member)</font></small>')
stringio.write('<form action="takeaction.html" method="post" target="invisibleiframe">')
stringio.write('<input type="submit" name="actiontotake" value="Signup" style="color:white;background-color:green">')
# stringio.write('<input type="submit" name="actiontotake" value="Signup and checkin">')
# stringio.write('<input type="submit" name="actiontotake" value="Relapse">')
# stringio.write('<input type="submit" name="actiontotake" value="Reinstate">')
stringio.write('<input type="submit" name="actiontotake" value="Skip comment">')
stringio.write('<input type="submit" name="actiontotake" value="Skip comment and don\'t upvote">')
stringio.write('<input type="hidden" name="username" value="' + b64encode(authorName) + '">')
stringio.write('<input type="hidden" name="commenthash" value="' + commentHash + '">')
# stringio.write('<input type="hidden" name="commentpermalink" value="' + comment.permalink + '">')
stringio.write('</form>')
stringio.write(bleach.clean(markdown.markdown(comment.body.encode('utf-8')), tags=['p']))
stringio.write("\n<br><br>\n\n")
stringio.write('</html>')
pageString = stringio.getvalue()
stringio.close()
return Response(pageString, mimetype='text/html')
@app.route('/takeaction.html', methods=["POST"])
def takeaction():
username = b64decode(request.form["username"])
commentHash = str(request.form["commenthash"])
# commentPermalink = request.form["commentpermalink"]
actionToTake = request.form["actiontotake"]
# print commentHashesAndComments
comment = commentHashesAndComments[commentHash]
# print "comment: " + str(comment)
if actionToTake == 'Signup':
print "signup - " + username
subprocess.call(['./signup.py', username])
comment.upvote()
retireCommentHash(commentHash)
# if actionToTake == 'Signup and checkin':
# print "signup and checkin - " + username
# subprocess.call(['./signup-and-checkin.sh', username])
# comment.upvote()
# retireCommentHash(commentHash)
# elif actionToTake == 'Relapse':
# print "relapse - " + username
# subprocess.call(['./relapse.py', username])
# comment.upvote()
# retireCommentHash(commentHash)
# elif actionToTake == 'Reinstate':
# print "reinstate - " + username
# subprocess.call(['./reinstate.py', username])
# comment.upvote()
# retireCommentHash(commentHash)
elif actionToTake == 'Skip comment':
print "Skip comment - " + username
comment.upvote()
retireCommentHash(commentHash)
elif actionToTake == "Skip comment and don't upvote":
print "Skip comment and don't upvote - " + username
retireCommentHash(commentHash)
return Response("hello", mimetype='text/html')
@app.route('/copydisplayduringsignuptoclipboard.html', methods=["POST"])
def copydisplayduringsignuptoclipboard():
print "TODO: Copy display to clipboard"
subprocess.call(['./display-during-signup.py'])
return Response("hello", mimetype='text/html')
if __name__ == '__main__':
app.run(host='127.0.0.1', port=flaskport)
| Java |
#![cfg_attr(all(feature = "nightly", test), feature(test))]
#![cfg(all(feature = "nightly", test))]
extern crate test;
extern crate cxema;
#[cfg(test)]
use cxema::sha2::{Sha256};
use cxema::digest::Digest;
use test::Bencher;
#[bench]
pub fn sha256_10(bh: &mut Bencher) {
let mut sh = Sha256::new();
let bytes = [1u8; 10];
bh.iter(|| {
sh.input(&bytes);
});
bh.bytes = bytes.len() as u64;
}
#[bench]
pub fn sha256_1k(bh: &mut Bencher) {
let mut sh = Sha256::new();
let bytes = [1u8; 1024];
bh.iter(|| {
sh.input(&bytes);
});
bh.bytes = bytes.len() as u64;
}
#[bench]
pub fn sha256_64k(bh: &mut Bencher) {
let mut sh = Sha256::new();
let bytes = [1u8; 65536];
bh.iter(|| {
sh.input(&bytes);
});
bh.bytes = bytes.len() as u64;
} | Java |
using System.Collections.Generic;
using JsonApiDotNetCore.Resources;
using JsonApiDotNetCore.Resources.Annotations;
using JsonApiDotNetCore.Serialization.Objects;
namespace JsonApiDotNetCore.Serialization.Building
{
/// <summary>
/// Responsible for converting resources into <see cref="ResourceObject" />s given a collection of attributes and relationships.
/// </summary>
public interface IResourceObjectBuilder
{
/// <summary>
/// Converts <paramref name="resource" /> into a <see cref="ResourceObject" />. Adds the attributes and relationships that are enlisted in
/// <paramref name="attributes" /> and <paramref name="relationships" />.
/// </summary>
/// <param name="resource">
/// Resource to build a <see cref="ResourceObject" /> for.
/// </param>
/// <param name="attributes">
/// Attributes to include in the building process.
/// </param>
/// <param name="relationships">
/// Relationships to include in the building process.
/// </param>
/// <returns>
/// The resource object that was built.
/// </returns>
ResourceObject Build(IIdentifiable resource, IReadOnlyCollection<AttrAttribute> attributes, IReadOnlyCollection<RelationshipAttribute> relationships);
}
}
| Java |
# Wir backen uns ein Mandelbrötchen

Die [Mandelbrot-Menge](https://de.wikipedia.org/wiki/Mandelbrot-Menge) ist die zentrale Ikone der Chaos-Theorie und das Urbild aller Fraktale. Sie ist die Menge aller komplexen Zahlen *c*, für welche die durch
$$
\begin{align}
z_{0} & = 0\\\\
z_{n+1} & = z_{n}^{2}+c\\\\
\end{align}
$$
rekursiv definierte Folge beschränkt ist. Bilder der Mandelbrot-Menge können erzeugt werden, indem für jeden Wert des Parameters *c*, der gemäß obiger Rekursion endlich bleibt, ein Farbwert in der komplexen Ebene zugeordnet wird.
Die komplexe Ebene wird in der Regel so dargestellt, daß in der Horizontalen (in der kartesisschen Ebene die *x-Achse*) der Realteil der komplexen Zahl und in der Vertikalen (in der kartesischen Ebene die *y-Achse*) der imaginäre Teil aufgetragen wird. Jede komplexe Zahl entspricht also einen Punkt in der komplexen Ebene. Die zur Mandelbrotmenge gehörenden Zahlen werden im Allgemeinen schwarz dargestellt, die übrigen Farbwerte werden der Anzahl von Iterationen (`maxiter`) zugeordnet, nach der der gewählte Punkt der Ebene einen Grenzwert (`maxlimit`) verläßt. Der theoretische Grenzwert ist *2.0*, doch können besonders bei Ausschnitten aus der Menge, um andere Farbkombinationen zu erreichen, auch höhere Grenzwerte verwendet werden. Bei Ausschnitten muß auch die Anzahl der Iterationen massiv erhöht werden, um eine hinreichende Genauigkeit der Darstellung zu erreichen.
## Das Programm
Python kennt den Datentyp `complex` und kann mit komplexen Zahlen rechnen. Daher drängt sich die Sprache für Experimente mit komplexen Zahlen geradezu auf. Zuert werden mit `cr` und `ci` Real- und Imaginärteil definiert und dann mit
~~~python
c = complex(cr, ci)
~~~
die komplexe Zahl erzeugt. Für die eigentliche Iteration wird dann -- nachdem der Startwert `z = 0.0` festgelegt wurde -- nur eine Zeile benötigt:
~~~python
z = (z**2) + c
~~~
Wie schon in anderen Beispielen habe ich für die Farbdarstellung den HSB-Raum verwendet und über den *Hue*-Wert iteriert. Das macht alles schön bunt, aber es gibt natürlich viele Möglichkeiten, ansprechendere Farben zu bekommen, beliebt sind zum Beispiel selbsterstellte Paletten mit 256 ausgesuchten Farbwerten, die entweder harmonisch ineinander übergehen oder bestimmte Kontraste betonen.
## Der komplette Quellcode
~~~python
left = -2.25
right = 0.75
bottom = -1.5
top = 1.5
maxlimit = 2.0
maxiter = 20
def setup():
size(400, 400)
background("#ffffff")
colorMode(HSB, 255, 100, 100)
# frame.setTitle(u"Mandelbrötchen")
noLoop()
def draw():
for x in range(width):
cr = left + x*(right - left)/width
for y in range(height):
ci = bottom + y*(top - bottom)/height
c = complex(cr, ci)
z = 0.0
i = 0
for i in range(maxiter):
if abs(z) > maxlimit:
break
z = (z**2) + c
if i == (maxiter - 1):
set(x, y, color(0, 0, 0))
else:
set(x, y, color((i*48)%255, 100, 100))
~~~
Um zu sehen, wie sich die Farben ändern, kann man durchaus mal mit den Werten von `maxlimit` spielen und diesen zum Beispiel auf `3.0` oder `4.0` setzen. Auch die Erhöhung der Anzahl der Iterationen `maxiter` verändert die Farbzuordnung, verlängert aber auch die Rechhenzeit drastisch, so daß man speziell bei Ausschnitten aus der Mandelbrotmenge schon einige Zeit auf das Ergebnis warten muß. | Java |
<html>
<head>
<title>User agent detail - Mozilla/5.0 (Linux; U; Android 4.0.3; zh-tw; ME171 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="section">
<h1 class="header center orange-text">User agent detail</h1>
<div class="row center">
<h5 class="header light">
Mozilla/5.0 (Linux; U; Android 4.0.3; zh-tw; ME171 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30
</h5>
</div>
</div>
<div class="section">
<table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Source result (test suite)</th></tr><tr><td>piwik/device-detector<br /><small>/Tests/fixtures/tablet.yml</small></td><td>Android Browser </td><td>Android 4.0.3</td><td>WebKit </td><td style="border-left: 1px solid #555">Asus</td><td>Eee Pad MeMO 171</td><td>tablet</td><td></td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td></td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-test">Detail</a>
<!-- Modal Structure -->
<div id="modal-test" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Testsuite result detail</h4>
<p><pre><code class="php">Array
(
[user_agent] => Mozilla/5.0 (Linux; U; Android 4.0.3; zh-tw; ME171 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30
[os] => Array
(
[name] => Android
[short_name] => AND
[version] => 4.0.3
[platform] =>
)
[client] => Array
(
[type] => browser
[name] => Android Browser
[short_name] => AN
[version] =>
[engine] => WebKit
)
[device] => Array
(
[type] => tablet
[brand] => AU
[model] => Eee Pad MeMO 171
)
[os_family] => Android
[browser_family] => Android Browser
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapPhp<br /><small>6012</small></td><td>Android 4.0</td><td>WebKit </td><td>Android 4.0</td><td style="border-left: 1px solid #555"></td><td></td><td>Mobile Phone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.02101</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-215ac98d-ccf8-4615-916e-5a819d6a59c9">Detail</a>
<!-- Modal Structure -->
<div id="modal-215ac98d-ccf8-4615-916e-5a819d6a59c9" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>BrowscapPhp result detail</h4>
<p><pre><code class="php">stdClass Object
(
[browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.4\.0.* build\/.*\).*applewebkit\/.*\(.*khtml,.*like gecko.*\).*version\/4\.0.*safari.*$/
[browser_name_pattern] => mozilla/5.0 (*linux*android?4.0* build/*)*applewebkit/*(*khtml,*like gecko*)*version/4.0*safari*
[parent] => Android Browser 4.0
[comment] => Android Browser 4.0
[browser] => Android
[browser_type] => Browser
[browser_bits] => 32
[browser_maker] => Google Inc
[browser_modus] => unknown
[version] => 4.0
[majorver] => 4
[minorver] => 0
[platform] => Android
[platform_version] => 4.0
[platform_description] => Android OS
[platform_bits] => 32
[platform_maker] => Google Inc
[alpha] =>
[beta] =>
[win16] =>
[win32] =>
[win64] =>
[frames] => 1
[iframes] => 1
[tables] => 1
[cookies] => 1
[backgroundsounds] =>
[javascript] => 1
[vbscript] =>
[javaapplets] => 1
[activexcontrols] =>
[ismobiledevice] => 1
[istablet] =>
[issyndicationreader] =>
[crawler] =>
[cssversion] => 3
[aolversion] => 0
[device_name] => general Mobile Phone
[device_maker] => unknown
[device_type] => Mobile Phone
[device_pointing_method] => touchscreen
[device_code_name] => general Mobile Phone
[device_brand_name] => unknown
[renderingengine_name] => WebKit
[renderingengine_version] => unknown
[renderingengine_description] => For Google Chrome, iOS (including both mobile Safari, WebViews within third-party apps, and web clips), Safari, Arora, Midori, OmniWeb, Shiira, iCab since version 4, Web, SRWare Iron, Rekonq, and in Maxthon 3.
[renderingengine_maker] => Apple Inc
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>DonatjUAParser<br /><small>v0.5.0</small></td><td>Android Browser 4.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.001</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-f1436016-fdf1-4aea-b4be-1d7c99ab0661">Detail</a>
<!-- Modal Structure -->
<div id="modal-f1436016-fdf1-4aea-b4be-1d7c99ab0661" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>DonatjUAParser result detail</h4>
<p><pre><code class="php">Array
(
[platform] => Android
[browser] => Android Browser
[version] => 4.0
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>NeutrinoApiCom<br /><small></small></td><td>Android Webkit 4.0</td><td><i class="material-icons">close</i></td><td>Android 4.0.3</td><td style="border-left: 1px solid #555">Generic</td><td>Android 4.0</td><td>mobile-browser</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.247</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-9b0fa449-ec1b-40c8-8b1c-9486eb3b9cbc">Detail</a>
<!-- Modal Structure -->
<div id="modal-9b0fa449-ec1b-40c8-8b1c-9486eb3b9cbc" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>NeutrinoApiCom result detail</h4>
<p><pre><code class="php">stdClass Object
(
[mobile_screen_height] => 480
[is_mobile] => 1
[type] => mobile-browser
[mobile_brand] => Generic
[mobile_model] => Android 4.0
[version] => 4.0
[is_android] => 1
[browser_name] => Android Webkit
[operating_system_family] => Android
[operating_system_version] => 4.0.3
[is_ios] =>
[producer] => Google Inc.
[operating_system] => Android 4.0.x Ice Cream Sandwich
[mobile_screen_width] => 320
[mobile_browser] => Android Webkit
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>PiwikDeviceDetector<br /><small>3.5.2</small></td><td>Android Browser </td><td>WebKit </td><td>Android 4.0</td><td style="border-left: 1px solid #555">Asus</td><td>Eee Pad MeMO 171</td><td>tablet</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.004</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-21638055-738d-46ba-a1b1-f5114bc26475">Detail</a>
<!-- Modal Structure -->
<div id="modal-21638055-738d-46ba-a1b1-f5114bc26475" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>PiwikDeviceDetector result detail</h4>
<p><pre><code class="php">Array
(
[client] => Array
(
[type] => browser
[name] => Android Browser
[short_name] => AN
[version] =>
[engine] => WebKit
)
[operatingSystem] => Array
(
[name] => Android
[short_name] => AND
[version] => 4.0
[platform] =>
)
[device] => Array
(
[brand] => AU
[brandName] => Asus
[model] => Eee Pad MeMO 171
[device] => 2
[deviceName] => tablet
)
[bot] =>
[extra] => Array
(
[isBot] =>
[isBrowser] => 1
[isFeedReader] =>
[isMobileApp] =>
[isPIM] =>
[isLibrary] =>
[isMediaPlayer] =>
[isCamera] =>
[isCarBrowser] =>
[isConsole] =>
[isFeaturePhone] =>
[isPhablet] =>
[isPortableMediaPlayer] =>
[isSmartDisplay] =>
[isSmartphone] =>
[isTablet] => 1
[isTV] =>
[isDesktop] =>
[isMobile] => 1
[isTouchEnabled] =>
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>SinergiBrowserDetector<br /><small>6.0.0</small></td><td>Navigator 4.0</td><td><i class="material-icons">close</i></td><td>Android 4.0.3</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.001</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-5415e7f2-ef7b-434c-abe0-b71ba9f6707c">Detail</a>
<!-- Modal Structure -->
<div id="modal-5415e7f2-ef7b-434c-abe0-b71ba9f6707c" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>SinergiBrowserDetector result detail</h4>
<p><pre><code class="php">Array
(
[browser] => Sinergi\BrowserDetector\Browser Object
(
[userAgent:Sinergi\BrowserDetector\Browser:private] => Sinergi\BrowserDetector\UserAgent Object
(
[userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 4.0.3; zh-tw; ME171 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30
)
[name:Sinergi\BrowserDetector\Browser:private] => Navigator
[version:Sinergi\BrowserDetector\Browser:private] => 4.0
[isRobot:Sinergi\BrowserDetector\Browser:private] =>
[isChromeFrame:Sinergi\BrowserDetector\Browser:private] =>
)
[operatingSystem] => Sinergi\BrowserDetector\Os Object
(
[name:Sinergi\BrowserDetector\Os:private] => Android
[version:Sinergi\BrowserDetector\Os:private] => 4.0.3
[isMobile:Sinergi\BrowserDetector\Os:private] => 1
[userAgent:Sinergi\BrowserDetector\Os:private] => Sinergi\BrowserDetector\UserAgent Object
(
[userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 4.0.3; zh-tw; ME171 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30
)
)
[device] => Sinergi\BrowserDetector\Device Object
(
[name:Sinergi\BrowserDetector\Device:private] => unknown
[userAgent:Sinergi\BrowserDetector\Device:private] => Sinergi\BrowserDetector\UserAgent Object
(
[userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 4.0.3; zh-tw; ME171 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30
)
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>UAParser<br /><small>v3.4.5</small></td><td>Android 4.0.3</td><td><i class="material-icons">close</i></td><td>Android 4.0.3</td><td style="border-left: 1px solid #555">Asus</td><td>ME171</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.001</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-346c1a98-5fd3-454f-b6c8-350f2f505d8b">Detail</a>
<!-- Modal Structure -->
<div id="modal-346c1a98-5fd3-454f-b6c8-350f2f505d8b" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>UAParser result detail</h4>
<p><pre><code class="php">UAParser\Result\Client Object
(
[ua] => UAParser\Result\UserAgent Object
(
[major] => 4
[minor] => 0
[patch] => 3
[family] => Android
)
[os] => UAParser\Result\OperatingSystem Object
(
[major] => 4
[minor] => 0
[patch] => 3
[patchMinor] =>
[family] => Android
)
[device] => UAParser\Result\Device Object
(
[brand] => Asus
[model] => ME171
[family] => Asus ME171
)
[originalUserAgent] => Mozilla/5.0 (Linux; U; Android 4.0.3; zh-tw; ME171 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>UserAgentStringCom<br /><small></small></td><td>Android Webkit Browser </td><td><i class="material-icons">close</i></td><td>Android 4.0.3</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.047</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-9cdd8b45-a2eb-406b-bd27-7e48af38ffd4">Detail</a>
<!-- Modal Structure -->
<div id="modal-9cdd8b45-a2eb-406b-bd27-7e48af38ffd4" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>UserAgentStringCom result detail</h4>
<p><pre><code class="php">stdClass Object
(
[agent_type] => Browser
[agent_name] => Android Webkit Browser
[agent_version] => --
[os_type] => Android
[os_name] => Android
[os_versionName] =>
[os_versionNumber] => 4.0.3
[os_producer] =>
[os_producerURL] =>
[linux_distibution] => Null
[agent_language] => Chinese - Taiwan
[agent_languageTag] => zh-tw
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>WhatIsMyBrowserCom<br /><small></small></td><td>Android Browser 4.0</td><td>WebKit 534.30</td><td>Android 4.0.3</td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.421</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-9795f66f-7271-430e-973a-a5c0e14dc35a">Detail</a>
<!-- Modal Structure -->
<div id="modal-9795f66f-7271-430e-973a-a5c0e14dc35a" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>WhatIsMyBrowserCom result detail</h4>
<p><pre><code class="php">stdClass Object
(
[operating_system_name] => Android
[simple_sub_description_string] =>
[simple_browser_string] => Android Browser 4 on Android (Ice Cream Sandwich)
[browser_version] => 4
[extra_info] => Array
(
)
[operating_platform] =>
[extra_info_table] => stdClass Object
(
[System Build] => IML74K
)
[layout_engine_name] => WebKit
[detected_addons] => Array
(
)
[operating_system_flavour_code] =>
[hardware_architecture] =>
[operating_system_flavour] =>
[operating_system_frameworks] => Array
(
)
[browser_name_code] => android-browser
[operating_system_version] => Ice Cream Sandwich
[simple_operating_platform_string] =>
[is_abusive] =>
[layout_engine_version] => 534.30
[browser_capabilities] => Array
(
)
[operating_platform_vendor_name] =>
[operating_system] => Android (Ice Cream Sandwich)
[operating_system_version_full] => 4.0.3
[operating_platform_code] =>
[browser_name] => Android Browser
[operating_system_name_code] => android
[user_agent] => Mozilla/5.0 (Linux; U; Android 4.0.3; zh-tw; ME171 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30
[browser_version_full] => 4.0
[browser] => Android Browser 4
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>WhichBrowser<br /><small>2.0.10</small></td><td>Android Browser </td><td>Webkit 534.30</td><td>Android 4.0.3</td><td style="border-left: 1px solid #555">Asus</td><td>Eee Pad MeMO</td><td>tablet</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.008</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-342c8d32-4765-40a8-8a5c-af3a38d19ae4">Detail</a>
<!-- Modal Structure -->
<div id="modal-342c8d32-4765-40a8-8a5c-af3a38d19ae4" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>WhichBrowser result detail</h4>
<p><pre><code class="php">Array
(
[browser] => Array
(
[name] => Android Browser
)
[engine] => Array
(
[name] => Webkit
[version] => 534.30
)
[os] => Array
(
[name] => Android
[version] => 4.0.3
)
[device] => Array
(
[type] => tablet
[manufacturer] => Asus
[model] => Eee Pad MeMO
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>Woothee<br /><small>v1.2.0</small></td><td>Safari 4.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>smartphone</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-3f285ff5-314b-4db4-9948-54572e92e7b6">Detail</a>
<!-- Modal Structure -->
<div id="modal-3f285ff5-314b-4db4-9948-54572e92e7b6" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Woothee result detail</h4>
<p><pre><code class="php">Array
(
[name] => Safari
[vendor] => Apple
[version] => 4.0
[category] => smartphone
[os] => Android
[os_version] => 4.0.3
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>Wurfl<br /><small>1.6.4</small></td><td>Android Webkit 4.0</td><td><i class="material-icons">close</i></td><td>Android 4.0</td><td style="border-left: 1px solid #555"></td><td></td><td>Tablet</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.13004</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-1a1aee36-7ce7-4111-a391-8e2c501f1532">Detail</a>
<!-- Modal Structure -->
<div id="modal-1a1aee36-7ce7-4111-a391-8e2c501f1532" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Wurfl result detail</h4>
<p><pre><code class="php">Array
(
[virtual] => Array
(
[is_android] => true
[is_ios] => false
[is_windows_phone] => false
[is_app] => false
[is_full_desktop] => false
[is_largescreen] => true
[is_mobile] => true
[is_robot] => false
[is_smartphone] => false
[is_touchscreen] => true
[is_wml_preferred] => false
[is_xhtmlmp_preferred] => false
[is_html_preferred] => true
[advertised_device_os] => Android
[advertised_device_os_version] => 4.0
[advertised_browser] => Android Webkit
[advertised_browser_version] => 4.0
[complete_device_name] => Generic Android 4 Tablet
[form_factor] => Tablet
[is_phone] => false
[is_app_webview] => false
)
[all] => Array
(
[brand_name] => Generic
[model_name] => Android 4 Tablet
[unique] => true
[ununiqueness_handler] =>
[is_wireless_device] => true
[device_claims_web_support] => true
[has_qwerty_keyboard] => true
[can_skip_aligned_link_row] => true
[uaprof] =>
[uaprof2] =>
[uaprof3] =>
[nokia_series] => 0
[nokia_edition] => 0
[device_os] => Android
[mobile_browser] => Android Webkit
[mobile_browser_version] =>
[device_os_version] => 4.0
[pointing_method] => touchscreen
[release_date] => 2012_january
[marketing_name] =>
[model_extra_info] =>
[nokia_feature_pack] => 0
[can_assign_phone_number] => false
[is_tablet] => true
[manufacturer_name] =>
[is_bot] => false
[is_google_glass] => false
[proportional_font] => false
[built_in_back_button_support] => false
[card_title_support] => true
[softkey_support] => false
[table_support] => true
[numbered_menus] => false
[menu_with_select_element_recommended] => false
[menu_with_list_of_links_recommended] => true
[icons_on_menu_items_support] => false
[break_list_of_links_with_br_element_recommended] => true
[access_key_support] => false
[wrap_mode_support] => false
[times_square_mode_support] => false
[deck_prefetch_support] => false
[elective_forms_recommended] => true
[wizards_recommended] => false
[image_as_link_support] => false
[insert_br_element_after_widget_recommended] => false
[wml_can_display_images_and_text_on_same_line] => false
[wml_displays_image_in_center] => false
[opwv_wml_extensions_support] => false
[wml_make_phone_call_string] => wtai://wp/mc;
[chtml_display_accesskey] => false
[emoji] => false
[chtml_can_display_images_and_text_on_same_line] => false
[chtml_displays_image_in_center] => false
[imode_region] => none
[chtml_make_phone_call_string] => tel:
[chtml_table_support] => false
[xhtml_honors_bgcolor] => true
[xhtml_supports_forms_in_table] => true
[xhtml_support_wml2_namespace] => false
[xhtml_autoexpand_select] => false
[xhtml_select_as_dropdown] => false
[xhtml_select_as_radiobutton] => false
[xhtml_select_as_popup] => false
[xhtml_display_accesskey] => false
[xhtml_supports_invisible_text] => false
[xhtml_supports_inline_input] => false
[xhtml_supports_monospace_font] => false
[xhtml_supports_table_for_layout] => true
[xhtml_supports_css_cell_table_coloring] => true
[xhtml_format_as_css_property] => false
[xhtml_format_as_attribute] => false
[xhtml_nowrap_mode] => false
[xhtml_marquee_as_css_property] => false
[xhtml_readable_background_color1] => #FFFFFF
[xhtml_readable_background_color2] => #FFFFFF
[xhtml_allows_disabled_form_elements] => true
[xhtml_document_title_support] => true
[xhtml_preferred_charset] => iso-8859-1
[opwv_xhtml_extensions_support] => false
[xhtml_make_phone_call_string] => tel:
[xhtmlmp_preferred_mime_type] => text/html
[xhtml_table_support] => true
[xhtml_send_sms_string] => sms:
[xhtml_send_mms_string] => mms:
[xhtml_file_upload] => supported
[cookie_support] => true
[accept_third_party_cookie] => true
[xhtml_supports_iframe] => full
[xhtml_avoid_accesskeys] => true
[xhtml_can_embed_video] => none
[ajax_support_javascript] => true
[ajax_manipulate_css] => true
[ajax_support_getelementbyid] => true
[ajax_support_inner_html] => true
[ajax_xhr_type] => standard
[ajax_manipulate_dom] => true
[ajax_support_events] => true
[ajax_support_event_listener] => true
[ajax_preferred_geoloc_api] => w3c_api
[xhtml_support_level] => 4
[preferred_markup] => html_web_4_0
[wml_1_1] => false
[wml_1_2] => false
[wml_1_3] => false
[html_wi_w3_xhtmlbasic] => true
[html_wi_oma_xhtmlmp_1_0] => true
[html_wi_imode_html_1] => false
[html_wi_imode_html_2] => false
[html_wi_imode_html_3] => false
[html_wi_imode_html_4] => false
[html_wi_imode_html_5] => false
[html_wi_imode_htmlx_1] => false
[html_wi_imode_htmlx_1_1] => false
[html_wi_imode_compact_generic] => false
[html_web_3_2] => true
[html_web_4_0] => true
[voicexml] => false
[multipart_support] => false
[total_cache_disable_support] => false
[time_to_live_support] => false
[resolution_width] => 480
[resolution_height] => 800
[columns] => 60
[max_image_width] => 480
[max_image_height] => 800
[rows] => 40
[physical_screen_width] => 92
[physical_screen_height] => 153
[dual_orientation] => true
[density_class] => 1.0
[wbmp] => true
[bmp] => false
[epoc_bmp] => false
[gif_animated] => false
[jpg] => true
[png] => true
[tiff] => false
[transparent_png_alpha] => true
[transparent_png_index] => true
[svgt_1_1] => true
[svgt_1_1_plus] => false
[greyscale] => false
[gif] => true
[colors] => 65536
[webp_lossy_support] => true
[webp_lossless_support] => false
[post_method_support] => true
[basic_authentication_support] => true
[empty_option_value_support] => true
[emptyok] => false
[nokia_voice_call] => false
[wta_voice_call] => false
[wta_phonebook] => false
[wta_misc] => false
[wta_pdc] => false
[https_support] => true
[phone_id_provided] => false
[max_data_rate] => 3600
[wifi] => true
[sdio] => false
[vpn] => false
[has_cellular_radio] => true
[max_deck_size] => 2000000
[max_url_length_in_requests] => 256
[max_url_length_homepage] => 0
[max_url_length_bookmark] => 0
[max_url_length_cached_page] => 0
[max_no_of_connection_settings] => 0
[max_no_of_bookmarks] => 0
[max_length_of_username] => 0
[max_length_of_password] => 0
[max_object_size] => 0
[downloadfun_support] => false
[directdownload_support] => true
[inline_support] => false
[oma_support] => true
[ringtone] => false
[ringtone_3gpp] => false
[ringtone_midi_monophonic] => false
[ringtone_midi_polyphonic] => false
[ringtone_imelody] => false
[ringtone_digiplug] => false
[ringtone_compactmidi] => false
[ringtone_mmf] => false
[ringtone_rmf] => false
[ringtone_xmf] => false
[ringtone_amr] => false
[ringtone_awb] => false
[ringtone_aac] => false
[ringtone_wav] => false
[ringtone_mp3] => false
[ringtone_spmidi] => false
[ringtone_qcelp] => false
[ringtone_voices] => 1
[ringtone_df_size_limit] => 0
[ringtone_directdownload_size_limit] => 0
[ringtone_inline_size_limit] => 0
[ringtone_oma_size_limit] => 0
[wallpaper] => false
[wallpaper_max_width] => 0
[wallpaper_max_height] => 0
[wallpaper_preferred_width] => 0
[wallpaper_preferred_height] => 0
[wallpaper_resize] => none
[wallpaper_wbmp] => false
[wallpaper_bmp] => false
[wallpaper_gif] => false
[wallpaper_jpg] => false
[wallpaper_png] => false
[wallpaper_tiff] => false
[wallpaper_greyscale] => false
[wallpaper_colors] => 2
[wallpaper_df_size_limit] => 0
[wallpaper_directdownload_size_limit] => 0
[wallpaper_inline_size_limit] => 0
[wallpaper_oma_size_limit] => 0
[screensaver] => false
[screensaver_max_width] => 0
[screensaver_max_height] => 0
[screensaver_preferred_width] => 0
[screensaver_preferred_height] => 0
[screensaver_resize] => none
[screensaver_wbmp] => false
[screensaver_bmp] => false
[screensaver_gif] => false
[screensaver_jpg] => false
[screensaver_png] => false
[screensaver_greyscale] => false
[screensaver_colors] => 2
[screensaver_df_size_limit] => 0
[screensaver_directdownload_size_limit] => 0
[screensaver_inline_size_limit] => 0
[screensaver_oma_size_limit] => 0
[picture] => false
[picture_max_width] => 0
[picture_max_height] => 0
[picture_preferred_width] => 0
[picture_preferred_height] => 0
[picture_resize] => none
[picture_wbmp] => false
[picture_bmp] => false
[picture_gif] => false
[picture_jpg] => false
[picture_png] => false
[picture_greyscale] => false
[picture_colors] => 2
[picture_df_size_limit] => 0
[picture_directdownload_size_limit] => 0
[picture_inline_size_limit] => 0
[picture_oma_size_limit] => 0
[video] => false
[oma_v_1_0_forwardlock] => false
[oma_v_1_0_combined_delivery] => false
[oma_v_1_0_separate_delivery] => false
[streaming_video] => true
[streaming_3gpp] => true
[streaming_mp4] => true
[streaming_mov] => false
[streaming_video_size_limit] => 0
[streaming_real_media] => none
[streaming_flv] => false
[streaming_3g2] => false
[streaming_vcodec_h263_0] => 10
[streaming_vcodec_h263_3] => -1
[streaming_vcodec_mpeg4_sp] => 2
[streaming_vcodec_mpeg4_asp] => -1
[streaming_vcodec_h264_bp] => 3.0
[streaming_acodec_amr] => nb
[streaming_acodec_aac] => lc
[streaming_wmv] => none
[streaming_preferred_protocol] => rtsp
[streaming_preferred_http_protocol] => apple_live_streaming
[wap_push_support] => false
[connectionless_service_indication] => false
[connectionless_service_load] => false
[connectionless_cache_operation] => false
[connectionoriented_unconfirmed_service_indication] => false
[connectionoriented_unconfirmed_service_load] => false
[connectionoriented_unconfirmed_cache_operation] => false
[connectionoriented_confirmed_service_indication] => false
[connectionoriented_confirmed_service_load] => false
[connectionoriented_confirmed_cache_operation] => false
[utf8_support] => true
[ascii_support] => false
[iso8859_support] => false
[expiration_date] => false
[j2me_cldc_1_0] => false
[j2me_cldc_1_1] => false
[j2me_midp_1_0] => false
[j2me_midp_2_0] => false
[doja_1_0] => false
[doja_1_5] => false
[doja_2_0] => false
[doja_2_1] => false
[doja_2_2] => false
[doja_3_0] => false
[doja_3_5] => false
[doja_4_0] => false
[j2me_jtwi] => false
[j2me_mmapi_1_0] => false
[j2me_mmapi_1_1] => false
[j2me_wmapi_1_0] => false
[j2me_wmapi_1_1] => false
[j2me_wmapi_2_0] => false
[j2me_btapi] => false
[j2me_3dapi] => false
[j2me_locapi] => false
[j2me_nokia_ui] => false
[j2me_motorola_lwt] => false
[j2me_siemens_color_game] => false
[j2me_siemens_extension] => false
[j2me_heap_size] => 0
[j2me_max_jar_size] => 0
[j2me_storage_size] => 0
[j2me_max_record_store_size] => 0
[j2me_screen_width] => 0
[j2me_screen_height] => 0
[j2me_canvas_width] => 0
[j2me_canvas_height] => 0
[j2me_bits_per_pixel] => 0
[j2me_audio_capture_enabled] => false
[j2me_video_capture_enabled] => false
[j2me_photo_capture_enabled] => false
[j2me_capture_image_formats] => none
[j2me_http] => false
[j2me_https] => false
[j2me_socket] => false
[j2me_udp] => false
[j2me_serial] => false
[j2me_gif] => false
[j2me_gif89a] => false
[j2me_jpg] => false
[j2me_png] => false
[j2me_bmp] => false
[j2me_bmp3] => false
[j2me_wbmp] => false
[j2me_midi] => false
[j2me_wav] => false
[j2me_amr] => false
[j2me_mp3] => false
[j2me_mp4] => false
[j2me_imelody] => false
[j2me_rmf] => false
[j2me_au] => false
[j2me_aac] => false
[j2me_realaudio] => false
[j2me_xmf] => false
[j2me_wma] => false
[j2me_3gpp] => false
[j2me_h263] => false
[j2me_svgt] => false
[j2me_mpeg4] => false
[j2me_realvideo] => false
[j2me_real8] => false
[j2me_realmedia] => false
[j2me_left_softkey_code] => 0
[j2me_right_softkey_code] => 0
[j2me_middle_softkey_code] => 0
[j2me_select_key_code] => 0
[j2me_return_key_code] => 0
[j2me_clear_key_code] => 0
[j2me_datefield_no_accepts_null_date] => false
[j2me_datefield_broken] => false
[receiver] => false
[sender] => false
[mms_max_size] => 0
[mms_max_height] => 0
[mms_max_width] => 0
[built_in_recorder] => false
[built_in_camera] => true
[mms_jpeg_baseline] => false
[mms_jpeg_progressive] => false
[mms_gif_static] => false
[mms_gif_animated] => false
[mms_png] => false
[mms_bmp] => false
[mms_wbmp] => false
[mms_amr] => false
[mms_wav] => false
[mms_midi_monophonic] => false
[mms_midi_polyphonic] => false
[mms_midi_polyphonic_voices] => 0
[mms_spmidi] => false
[mms_mmf] => false
[mms_mp3] => false
[mms_evrc] => false
[mms_qcelp] => false
[mms_ota_bitmap] => false
[mms_nokia_wallpaper] => false
[mms_nokia_operatorlogo] => false
[mms_nokia_3dscreensaver] => false
[mms_nokia_ringingtone] => false
[mms_rmf] => false
[mms_xmf] => false
[mms_symbian_install] => false
[mms_jar] => false
[mms_jad] => false
[mms_vcard] => false
[mms_vcalendar] => false
[mms_wml] => false
[mms_wbxml] => false
[mms_wmlc] => false
[mms_video] => false
[mms_mp4] => false
[mms_3gpp] => false
[mms_3gpp2] => false
[mms_max_frame_rate] => 0
[nokiaring] => false
[picturemessage] => false
[operatorlogo] => false
[largeoperatorlogo] => false
[callericon] => false
[nokiavcard] => false
[nokiavcal] => false
[sckl_ringtone] => false
[sckl_operatorlogo] => false
[sckl_groupgraphic] => false
[sckl_vcard] => false
[sckl_vcalendar] => false
[text_imelody] => false
[ems] => false
[ems_variablesizedpictures] => false
[ems_imelody] => false
[ems_odi] => false
[ems_upi] => false
[ems_version] => 0
[siemens_ota] => false
[siemens_logo_width] => 101
[siemens_logo_height] => 29
[siemens_screensaver_width] => 101
[siemens_screensaver_height] => 50
[gprtf] => false
[sagem_v1] => false
[sagem_v2] => false
[panasonic] => false
[sms_enabled] => true
[wav] => false
[mmf] => false
[smf] => false
[mld] => false
[midi_monophonic] => false
[midi_polyphonic] => false
[sp_midi] => false
[rmf] => false
[xmf] => false
[compactmidi] => false
[digiplug] => false
[nokia_ringtone] => false
[imelody] => false
[au] => false
[amr] => false
[awb] => false
[aac] => true
[mp3] => true
[voices] => 1
[qcelp] => false
[evrc] => false
[flash_lite_version] =>
[fl_wallpaper] => false
[fl_screensaver] => false
[fl_standalone] => false
[fl_browser] => false
[fl_sub_lcd] => false
[full_flash_support] => true
[css_supports_width_as_percentage] => true
[css_border_image] => webkit
[css_rounded_corners] => webkit
[css_gradient] => none
[css_spriting] => true
[css_gradient_linear] => none
[is_transcoder] => false
[transcoder_ua_header] => user-agent
[rss_support] => false
[pdf_support] => true
[progressive_download] => true
[playback_vcodec_h263_0] => 10
[playback_vcodec_h263_3] => -1
[playback_vcodec_mpeg4_sp] => 0
[playback_vcodec_mpeg4_asp] => -1
[playback_vcodec_h264_bp] => 3.0
[playback_real_media] => none
[playback_3gpp] => true
[playback_3g2] => false
[playback_mp4] => true
[playback_mov] => false
[playback_acodec_amr] => nb
[playback_acodec_aac] => none
[playback_df_size_limit] => 0
[playback_directdownload_size_limit] => 0
[playback_inline_size_limit] => 0
[playback_oma_size_limit] => 0
[playback_acodec_qcelp] => false
[playback_wmv] => none
[hinted_progressive_download] => true
[html_preferred_dtd] => html4
[viewport_supported] => true
[viewport_width] => device_width_token
[viewport_userscalable] => no
[viewport_initial_scale] =>
[viewport_maximum_scale] =>
[viewport_minimum_scale] =>
[mobileoptimized] => false
[handheldfriendly] => false
[canvas_support] => full
[image_inlining] => true
[is_smarttv] => false
[is_console] => false
[nfc_support] => false
[ux_full_desktop] => false
[jqm_grade] => A
[is_sencha_touch_ok] => false
[controlcap_is_smartphone] => default
[controlcap_is_ios] => default
[controlcap_is_android] => default
[controlcap_is_robot] => default
[controlcap_is_app] => default
[controlcap_advertised_device_os] => default
[controlcap_advertised_device_os_version] => default
[controlcap_advertised_browser] => default
[controlcap_advertised_browser_version] => default
[controlcap_is_windows_phone] => default
[controlcap_is_full_desktop] => default
[controlcap_is_largescreen] => default
[controlcap_is_mobile] => default
[controlcap_is_touchscreen] => default
[controlcap_is_wml_preferred] => default
[controlcap_is_xhtmlmp_preferred] => default
[controlcap_is_html_preferred] => default
[controlcap_form_factor] => default
[controlcap_complete_device_name] => default
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr></table>
</div>
<div class="section">
<h1 class="header center orange-text">About this comparison</h1>
<div class="row center">
<h5 class="header light">
The primary goal of this project is simple<br />
I wanted to know which user agent parser is the most accurate in each part - device detection, bot detection and so on...<br />
<br />
The secondary goal is to provide a source for all user agent parsers to improve their detection based on this results.<br />
<br />
You can also improve this further, by suggesting ideas at <a href="https://github.com/ThaDafinser/UserAgentParserComparison">ThaDafinser/UserAgentParserComparison</a><br />
<br />
The comparison is based on the abstraction by <a href="https://github.com/ThaDafinser/UserAgentParser">ThaDafinser/UserAgentParser</a>
</h5>
</div>
</div>
<div class="card">
<div class="card-content">
Comparison created <i>2016-02-13 13:41:35</i> | by
<a href="https://github.com/ThaDafinser">ThaDafinser</a>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/list.js/1.1.1/list.min.js"></script>
<script>
$(document).ready(function(){
// the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
$('.modal-trigger').leanModal();
});
</script>
</body>
</html> | Java |
<html>
<head>
<script src='https://surikov.github.io/webaudiofont/npm/dist/WebAudioFontPlayer.js'></script>
<script src='0410_Aspirin_sf2_file.js'></script>
<script>
var selectedPreset=_tone_0410_Aspirin_sf2_file;
var AudioContextFunc = window.AudioContext || window.webkitAudioContext;
var audioContext = new AudioContextFunc();
var player=new WebAudioFontPlayer();
player.adjustPreset(audioContext,selectedPreset);
function startWaveTableNow(pitch) {
var audioBufferSourceNode = player.queueWaveTable(audioContext, audioContext.destination, selectedPreset, audioContext.currentTime + 0, pitch, 0.4);
var audioBufferSourceNode = player.queueWaveTable(audioContext, audioContext.destination, selectedPreset, audioContext.currentTime + 0.4, pitch, 0.2);
var audioBufferSourceNode = player.queueWaveTable(audioContext, audioContext.destination, selectedPreset, audioContext.currentTime + 0.6, pitch, 0.2);
var audioBufferSourceNode = player.queueWaveTable(audioContext, audioContext.destination, selectedPreset, audioContext.currentTime + 0.8, pitch, 4);
}
</script>
</head>
<body>
<p>file: 0410_Aspirin_sf2_file.js<br/>
variable: _tone_0410_Aspirin_sf2_file<br/>
MIDI: 41. Viola: Strings</p>
<p><a href='javascript:player.cancelQueue(audioContext);'>stop</a></p>
<p>chords:
<a href='javascript:startWaveTableNow(4+12*4+0); startWaveTableNow(9+12*4+0); startWaveTableNow(2+12*5+2); startWaveTableNow(7+12*5+2); startWaveTableNow(11+12*5+1); startWaveTableNow(4+12*6+0);'>Am</a>
| <a href='javascript:startWaveTableNow(4+12*4+0); startWaveTableNow(9+12*4+3); startWaveTableNow(2+12*5+2); startWaveTableNow(7+12*5+0); startWaveTableNow(11+12*5+1); startWaveTableNow(4+12*6+0);'>C</a>
| <a href='javascript:startWaveTableNow(4+12*4+0); startWaveTableNow(9+12*4+2); startWaveTableNow(2+12*5+2); startWaveTableNow(7+12*5+1); startWaveTableNow(11+12*5+0); startWaveTableNow(4+12*6+0);'>E</a>
| <a href='javascript:startWaveTableNow(4+12*4+3); startWaveTableNow(9+12*4+2); startWaveTableNow(2+12*5+0); startWaveTableNow(7+12*5+0); startWaveTableNow(11+12*5+0); startWaveTableNow(4+12*6+3);'>G</a>
</p>
<p>1.
<a href='javascript:startWaveTableNow(0+12*1);'>C</a>
<a href='javascript:startWaveTableNow(1+12*1);'>C#</a>
<a href='javascript:startWaveTableNow(2+12*1);'>D</a>
<a href='javascript:startWaveTableNow(3+12*1);'>D#</a>
<a href='javascript:startWaveTableNow(4+12*1);'>E</a>
<a href='javascript:startWaveTableNow(5+12*1);'>F</a>
<a href='javascript:startWaveTableNow(6+12*1);'>F#</a>
<a href='javascript:startWaveTableNow(7+12*1);'>G</a>
<a href='javascript:startWaveTableNow(8+12*1);'>G#</a>
<a href='javascript:startWaveTableNow(9+12*1);'>A</a>
<a href='javascript:startWaveTableNow(10+12*1);'>A#</a>
<a href='javascript:startWaveTableNow(11+12*1);'>B</a>
</p>
<p>2.
<a href='javascript:startWaveTableNow(0+12*2);'>C</a>
<a href='javascript:startWaveTableNow(1+12*2);'>C#</a>
<a href='javascript:startWaveTableNow(2+12*2);'>D</a>
<a href='javascript:startWaveTableNow(3+12*2);'>D#</a>
<a href='javascript:startWaveTableNow(4+12*2);'>E</a>
<a href='javascript:startWaveTableNow(5+12*2);'>F</a>
<a href='javascript:startWaveTableNow(6+12*2);'>F#</a>
<a href='javascript:startWaveTableNow(7+12*2);'>G</a>
<a href='javascript:startWaveTableNow(8+12*2);'>G#</a>
<a href='javascript:startWaveTableNow(9+12*2);'>A</a>
<a href='javascript:startWaveTableNow(10+12*2);'>A#</a>
<a href='javascript:startWaveTableNow(11+12*2);'>B</a>
</p>
<p>3.
<a href='javascript:startWaveTableNow(0+12*3);'>C</a>
<a href='javascript:startWaveTableNow(1+12*3);'>C#</a>
<a href='javascript:startWaveTableNow(2+12*3);'>D</a>
<a href='javascript:startWaveTableNow(3+12*3);'>D#</a>
<a href='javascript:startWaveTableNow(4+12*3);'>E</a>
<a href='javascript:startWaveTableNow(5+12*3);'>F</a>
<a href='javascript:startWaveTableNow(6+12*3);'>F#</a>
<a href='javascript:startWaveTableNow(7+12*3);'>G</a>
<a href='javascript:startWaveTableNow(8+12*3);'>G#</a>
<a href='javascript:startWaveTableNow(9+12*3);'>A</a>
<a href='javascript:startWaveTableNow(10+12*3);'>A#</a>
<a href='javascript:startWaveTableNow(11+12*3);'>B</a>
</p>
<p>4.
<a href='javascript:startWaveTableNow(0+12*4);'>C</a>
<a href='javascript:startWaveTableNow(1+12*4);'>C#</a>
<a href='javascript:startWaveTableNow(2+12*4);'>D</a>
<a href='javascript:startWaveTableNow(3+12*4);'>D#</a>
<a href='javascript:startWaveTableNow(4+12*4);'>E</a>
<a href='javascript:startWaveTableNow(5+12*4);'>F</a>
<a href='javascript:startWaveTableNow(6+12*4);'>F#</a>
<a href='javascript:startWaveTableNow(7+12*4);'>G</a>
<a href='javascript:startWaveTableNow(8+12*4);'>G#</a>
<a href='javascript:startWaveTableNow(9+12*4);'>A</a>
<a href='javascript:startWaveTableNow(10+12*4);'>A#</a>
<a href='javascript:startWaveTableNow(11+12*4);'>B</a>
</p>
<p>5.
<a href='javascript:startWaveTableNow(0+12*5);'>C</a>
<a href='javascript:startWaveTableNow(1+12*5);'>C#</a>
<a href='javascript:startWaveTableNow(2+12*5);'>D</a>
<a href='javascript:startWaveTableNow(3+12*5);'>D#</a>
<a href='javascript:startWaveTableNow(4+12*5);'>E</a>
<a href='javascript:startWaveTableNow(5+12*5);'>F</a>
<a href='javascript:startWaveTableNow(6+12*5);'>F#</a>
<a href='javascript:startWaveTableNow(7+12*5);'>G</a>
<a href='javascript:startWaveTableNow(8+12*5);'>G#</a>
<a href='javascript:startWaveTableNow(9+12*5);'>A</a>
<a href='javascript:startWaveTableNow(10+12*5);'>A#</a>
<a href='javascript:startWaveTableNow(11+12*5);'>B</a>
</p>
<p>6.
<a href='javascript:startWaveTableNow(0+12*6);'>C</a>
<a href='javascript:startWaveTableNow(1+12*6);'>C#</a>
<a href='javascript:startWaveTableNow(2+12*6);'>D</a>
<a href='javascript:startWaveTableNow(3+12*6);'>D#</a>
<a href='javascript:startWaveTableNow(4+12*6);'>E</a>
<a href='javascript:startWaveTableNow(5+12*6);'>F</a>
<a href='javascript:startWaveTableNow(6+12*6);'>F#</a>
<a href='javascript:startWaveTableNow(7+12*6);'>G</a>
<a href='javascript:startWaveTableNow(8+12*6);'>G#</a>
<a href='javascript:startWaveTableNow(9+12*6);'>A</a>
<a href='javascript:startWaveTableNow(10+12*6);'>A#</a>
<a href='javascript:startWaveTableNow(11+12*6);'>B</a>
</p>
<p>7.
<a href='javascript:startWaveTableNow(0+12*7);'>C</a>
<a href='javascript:startWaveTableNow(1+12*7);'>C#</a>
<a href='javascript:startWaveTableNow(2+12*7);'>D</a>
<a href='javascript:startWaveTableNow(3+12*7);'>D#</a>
<a href='javascript:startWaveTableNow(4+12*7);'>E</a>
<a href='javascript:startWaveTableNow(5+12*7);'>F</a>
<a href='javascript:startWaveTableNow(6+12*7);'>F#</a>
<a href='javascript:startWaveTableNow(7+12*7);'>G</a>
<a href='javascript:startWaveTableNow(8+12*7);'>G#</a>
<a href='javascript:startWaveTableNow(9+12*7);'>A</a>
<a href='javascript:startWaveTableNow(10+12*7);'>A#</a>
<a href='javascript:startWaveTableNow(11+12*7);'>B</a>
</p>
<p>8.
<a href='javascript:startWaveTableNow(0+12*8);'>C</a>
<a href='javascript:startWaveTableNow(1+12*8);'>C#</a>
<a href='javascript:startWaveTableNow(2+12*8);'>D</a>
<a href='javascript:startWaveTableNow(3+12*8);'>D#</a>
<a href='javascript:startWaveTableNow(4+12*8);'>E</a>
<a href='javascript:startWaveTableNow(5+12*8);'>F</a>
<a href='javascript:startWaveTableNow(6+12*8);'>F#</a>
<a href='javascript:startWaveTableNow(7+12*8);'>G</a>
<a href='javascript:startWaveTableNow(8+12*8);'>G#</a>
<a href='javascript:startWaveTableNow(9+12*8);'>A</a>
<a href='javascript:startWaveTableNow(10+12*8);'>A#</a>
<a href='javascript:startWaveTableNow(11+12*8);'>B</a>
</p>
</body>
</html>
| Java |
'use strict';
var page = 'projects';
module.exports = {
renderPage: function(req, res) {
if (!req.user) {
res.redirect('/login');
} else {
res.render(page, {
helpers: {
activeClass: function(section) {
if (section === 'projects') {
return 'active';
} else {
return '';
}
}
},
user: req.user ? req.user.toJSON() : null
});
}
}
}
| Java |
[](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-jsx)
# JSX Next.js example
This is a really simple project that show the usage of Next.js with JSX.
## How to use it?
```
npm install # to install dependencies
npm run dev # to run next.js
``` | Java |
Search = function(data, input, result) {
this.data = data;
this.$input = $(input);
this.$result = $(result);
this.$current = null;
this.$view = this.$result.parent();
this.searcher = new Searcher(data.index);
this.init();
};
Search.prototype = $.extend({}, Navigation, new function() {
var suid = 1;
this.init = function() {
var _this = this;
var observer = function(e) {
switch(e.originalEvent.keyCode) {
case 38: // Event.KEY_UP
case 40: // Event.KEY_DOWN
return;
}
_this.search(_this.$input[0].value);
};
this.$input.keyup(observer);
this.$input.click(observer); // mac's clear field
this.searcher.ready(function(results, isLast) {
_this.addResults(results, isLast);
});
this.initNavigation();
this.setNavigationActive(false);
};
this.search = function(value, selectFirstMatch) {
value = jQuery.trim(value).toLowerCase();
if (value) {
this.setNavigationActive(true);
} else {
this.setNavigationActive(false);
}
if (value == '') {
this.lastQuery = value;
this.$result.empty();
this.$result.attr('aria-expanded', 'false');
this.setNavigationActive(false);
} else if (value != this.lastQuery) {
this.lastQuery = value;
this.$result.attr('aria-busy', 'true');
this.$result.attr('aria-expanded', 'true');
this.firstRun = true;
this.searcher.find(value);
}
};
this.addResults = function(results, isLast) {
var target = this.$result.get(0);
if (this.firstRun && (results.length > 0 || isLast)) {
this.$current = null;
this.$result.empty();
}
for (var i=0, l = results.length; i < l; i++) {
var item = this.renderItem.call(this, results[i]);
item.setAttribute('id', 'search-result-' + target.childElementCount);
target.appendChild(item);
}
if (this.firstRun && results.length > 0) {
this.firstRun = false;
this.$current = $(target.firstChild);
this.$current.addClass('search-selected');
}
if (jQuery.browser.msie) this.$element[0].className += '';
if (isLast) this.$result.attr('aria-busy', 'false');
};
this.move = function(isDown) {
if (!this.$current) return;
var $next = this.$current[isDown ? 'next' : 'prev']();
if ($next.length) {
this.$current.removeClass('search-selected');
$next.addClass('search-selected');
this.$input.attr('aria-activedescendant', $next.attr('id'));
this.scrollIntoView($next[0], this.$view[0]);
this.$current = $next;
this.$input.val($next[0].firstChild.firstChild.text);
this.$input.select();
}
return true;
};
this.hlt = function(html) {
return this.escapeHTML(html).
replace(/\u0001/g, '<em>').
replace(/\u0002/g, '</em>');
};
this.escapeHTML = function(html) {
return html.replace(/[&<>]/g, function(c) {
return '&#' + c.charCodeAt(0) + ';';
});
}
});
| Java |
version https://git-lfs.github.com/spec/v1
oid sha256:505b4ccd47ed9526d0238c6f2d03a343ce476abc1c4aa79a9f22cabcbd0a3c16
size 12575
| Java |
#include "ConfirmationMenu.h"
ConfirmationMenu::ConfirmationMenu(CarrotQt5* mainClass, std::function<void(bool)> callback, const QString& text, const QString& yesLabel, const QString& noLabel)
: MenuScreen(mainClass), text(text) {
menuOptions.append(buildMenuItem([this, callback]() {
root->popState();
callback(true);
}, yesLabel));
menuOptions.append(buildMenuItem([this, callback]() {
root->popState();
callback(false);
}, noLabel));
cancelItem = buildMenuItem([this, callback]() {
root->popState();
callback(false);
}, noLabel);
setMenuItemSelected(0);
}
ConfirmationMenu::~ConfirmationMenu() {
}
void ConfirmationMenu::renderTick(bool, bool) {
auto canvas = root->getCanvas();
uint viewWidth = canvas->getView().getSize().x;
uint viewHeight = canvas->getView().getSize().y;
BitmapString::drawString(canvas, root->getFont(), text, viewWidth / 2, viewHeight / 2 - 50, FONT_ALIGN_CENTER);
menuOptions[0]->text->drawString(canvas, viewWidth / 2 - 100, viewHeight / 2 + 50);
menuOptions[1]->text->drawString(canvas, viewWidth / 2 + 100, viewHeight / 2 + 50);
}
void ConfirmationMenu::processControlDownEvent(const ControlEvent& e) {
MenuScreen::processControlDownEvent(e);
switch (e.first.keyboardKey) {
case Qt::Key_Left:
setMenuItemSelected(-1, true);
break;
case Qt::Key_Right:
setMenuItemSelected(1, true);
break;
}
}
| Java |
'use strict';
//Ghost service used for communicating with the ghost api
angular.module('ghost').factory('Ghost', ['$http', 'localStorageService',
function($http, localStorageService) {
return {
login: function() {
return $http.get('api/ghost/login').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
data.authenticator = 'simple-auth-authenticator:oauth2-password-grant';
data.expires_at = data.expires_in + Date.now();
localStorageService.set('ghost-cms:session',data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('ghost login failure');
});
}
};
}
]).factory('GhostPosts', ['$http',
function($http) {
return {
read: function(options) {
return $http.get('api/ghost/posts/slug/' + options.slug).
success(function(data, status, headers, config) {
//console.log(data);
return data;
});
},
query: function(options) {
return $http.get('api/ghost/posts/tag/' + options.tag).
success(function(data, status, headers, config) {
//console.log(data);
return data;
});
}
};
}
]);
| Java |
from flask_webapi import status
from unittest import TestCase
class TestStatus(TestCase):
def test_is_informational(self):
self.assertFalse(status.is_informational(99))
self.assertFalse(status.is_informational(200))
for i in range(100, 199):
self.assertTrue(status.is_informational(i))
def test_is_success(self):
self.assertFalse(status.is_success(199))
self.assertFalse(status.is_success(300))
for i in range(200, 299):
self.assertTrue(status.is_success(i))
def test_is_redirect(self):
self.assertFalse(status.is_redirect(299))
self.assertFalse(status.is_redirect(400))
for i in range(300, 399):
self.assertTrue(status.is_redirect(i))
def test_is_client_error(self):
self.assertFalse(status.is_client_error(399))
self.assertFalse(status.is_client_error(500))
for i in range(400, 499):
self.assertTrue(status.is_client_error(i))
def test_is_server_error(self):
self.assertFalse(status.is_server_error(499))
self.assertFalse(status.is_server_error(600))
for i in range(500, 599):
self.assertTrue(status.is_server_error(i))
| Java |
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.ac.nott.mrl.gles.program;
import android.opengl.GLES20;
import android.util.Log;
import com.android.grafika.gles.GlUtil;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
public class GraphProgram
{
private static final int SIZEOF_FLOAT = 4;
private static final int VERTEX_STRIDE = SIZEOF_FLOAT * 2;
private static final String TAG = GlUtil.TAG;
private static final String VERTEX_SHADER =
"uniform mat4 uMVPMatrix;" +
"attribute vec4 aPosition;" +
"void main() {" +
" gl_Position = uMVPMatrix * aPosition;" +
"}";
private static final String FRAGMENT_SHADER =
"precision mediump float;" +
"uniform vec4 uColor;" +
"void main() {" +
" gl_FragColor = uColor;" +
"}";
private final int MAX_SIZE = 200;
// Handles to the GL program and various components of it.
private int programHandle = -1;
private int colorLocation = -1;
private int matrixLocation = -1;
private int positionLocation = -1;
private final float[] colour = {1f, 1f, 1f, 1f};
private final FloatBuffer points;
private final float[] values = new float[MAX_SIZE];
private int size = 0;
private int offset = 0;
private boolean bufferValid = false;
private float min = Float.MAX_VALUE;
private float max = Float.MIN_VALUE;
private static final float left = 1.8f;
private static final float right = 0.2f;
private static final float top = 0.8f;
private static final float bottom = -0.8f;
/**
* Prepares the program in the current EGL context.
*/
public GraphProgram()
{
programHandle = GlUtil.createProgram(VERTEX_SHADER, FRAGMENT_SHADER);
if (programHandle == 0)
{
throw new RuntimeException("Unable to create program");
}
Log.d(TAG, "Created program " + programHandle);
// get locations of attributes and uniforms
ByteBuffer bb = ByteBuffer.allocateDirect(MAX_SIZE * VERTEX_STRIDE);
bb.order(ByteOrder.nativeOrder());
points = bb.asFloatBuffer();
positionLocation = GLES20.glGetAttribLocation(programHandle, "aPosition");
GlUtil.checkLocation(positionLocation, "aPosition");
matrixLocation = GLES20.glGetUniformLocation(programHandle, "uMVPMatrix");
GlUtil.checkLocation(matrixLocation, "uMVPMatrix");
colorLocation = GLES20.glGetUniformLocation(programHandle, "uColor");
GlUtil.checkLocation(colorLocation, "uColor");
}
/**
* Releases the program.
*/
public void release()
{
GLES20.glDeleteProgram(programHandle);
programHandle = -1;
}
public synchronized void add(float value)
{
values[offset] = value;
min = Math.min(value, min);
max = Math.max(value, max);
size = Math.min(size + 1, MAX_SIZE);
offset = (offset + 1) % MAX_SIZE;
bufferValid = false;
}
public void setColour(final float r, final float g, final float b)
{
colour[0] = r;
colour[1] = g;
colour[2] = b;
}
private synchronized FloatBuffer getValidBuffer()
{
if (!bufferValid)
{
points.position(0);
for(int index = 0; index < size; index++)
{
float value = values[(offset + index) % size];
float scaledValue = ((value - min) / (max - min) * (top - bottom)) + bottom;
//Log.i(TAG, "x=" + ((index * (right - left) / size) + left) + ", y=" + scaledValue);
points.put((index * (right - left) / (size - 1)) + left);
points.put(scaledValue);
}
points.position(0);
bufferValid = true;
}
return points;
}
public void draw(float[] matrix)
{
GlUtil.checkGlError("draw start");
// Select the program.
GLES20.glUseProgram(programHandle);
GlUtil.checkGlError("glUseProgram");
// Copy the model / view / projection matrix over.
GLES20.glUniformMatrix4fv(matrixLocation, 1, false, matrix, 0);
GlUtil.checkGlError("glUniformMatrix4fv");
// Copy the color vector in.
GLES20.glUniform4fv(colorLocation, 1, colour, 0);
GlUtil.checkGlError("glUniform4fv ");
// Enable the "aPosition" vertex attribute.
GLES20.glEnableVertexAttribArray(positionLocation);
GlUtil.checkGlError("glEnableVertexAttribArray");
// Connect vertexBuffer to "aPosition".
GLES20.glVertexAttribPointer(positionLocation, 2,
GLES20.GL_FLOAT, false, VERTEX_STRIDE, getValidBuffer());
GlUtil.checkGlError("glVertexAttribPointer");
// Draw the rect.
GLES20.glDrawArrays(GLES20.GL_LINE_STRIP, 0, size);
GlUtil.checkGlError("glDrawArrays");
// Done -- disable vertex array and program.
GLES20.glDisableVertexAttribArray(positionLocation);
GLES20.glUseProgram(0);
}
}
| Java |
# nazdrave
Като Untappd ама за ракия
| Java |
Omnom App
=========
This is the example app for Omnom. See [Omnom](https://github.com/tombenner/omnom) for details.
License
-------
Omnom App is released under the MIT License. Please see the MIT-LICENSE file for details.
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.