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
|
---|---|---|---|---|---|
module Indian
module States
VERSION = "0.0.4"
end
end
| vajapravin/indian-states | lib/indian/states/version.rb | Ruby | mit | 62 |
<!DOCTYPE html>
<!--[if lt IE 7]>
<html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>
<html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>
<html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Student</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/sidebar.css" rel="stylesheet">
<link rel="stylesheet" href="css/bootstrap.min.css">
<style>
body {
padding-top: 50px;
padding-bottom: 20px;
}
</style>
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
</head>
<body>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a
href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#menu-toggle" id="menu-toggle">CS Assess</a>
</div>
<form class="navbar-text navbar-right" style="float: right">
<a href="user_profile.html"
style=";font-size: 20px; color:#ffffff; padding-right: 20px; text-decoration: none"> Testy
Jones </a>
<a href="login.html" style="font-size: 14px"> Logout </a>
</form>
</div>
<!--/.navbar-collapse -->
</nav>
<div id="wrapper">
<!-- The navbar on the right side -->
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li class="sidebar-brand"><a href="#">Navigation</a></li>
<li><a href="student_section.html">Class 1</a></li>
<li>
<ul>
<li><a href="#">Grades</a></li>
<li><a href="#">Assignments</a></li>
</ul>
</li>
<li><a href="student_section.html">Class 2</a></li>
<li>
<ul>
<li><a href="#">Grades</a></li>
<li><a href="#">Assignments</a></li>
</ul>
</li>
<li><a href="student_section.html">Class 3</a></li>
<li>
<ul>
<li><a href="#">Grades</a></li>
<li><a href="#">Assignments</a></li>
</ul>
</li>
<li><a href="practice.html">Practice</a></li>
</ul>
</div>
<!-- Home Page -->
<div id="page-content-wrapper">
<h2>CS402: AP Computer Science I</h2>
<h4>Instructor: John Boyarsky</h4>
<h3>Current Assignments</h3>
<div class="table">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th> Assignment</th>
<th> Course</th>
<th> Instructor</th>
<th> Status</th>
<th> Due</th>
<th> # Questions</th>
<th> Point Value</th>
</tr>
</thead>
<tbody>
<tr>
<th><a href="#"> Learning to use files </a></th>
<th> CS402</th>
<th> John Boyarsky</th>
<th> Not Started</th>
<th> 03/04/2015</th>
<th> 10</th>
<th> 100</th>
</tr>
</tbody>
</table>
</div>
<h3>Returned Assignments</h3>
<div class="table">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th> Assignment Title</th>
<th> Course</th>
<th> Instructor</th>
<th> Date Submitted</th>
<th> Points Earned</th>
<th> Point Value</th>
<th> Grade</th>
</tr>
</thead>
<tbody>
<tr>
<th><a href="#"> Using files </a></th>
<th> CS402</th>
<th> John Boyarsky</th>
<th> 02/24/2015</th>
<th> 10</th>
<th> 12</th>
<th> 83</th>
</tr>
<tr>
<th><a href="#"> Creating a linked list </a></th>
<th> CS402</th>
<th> Sam Morrison</th>
<th> 02/28/2015</th>
<th> 47</th>
<th> 50</th>
<th> 94</th>
</tr>
</tbody>
</table>
</div>
<h3><a href="practice.html">Practice</a></h3>
</div>
</div>
<hr>
<footer>
<p>© Company 2014</p>
</footer>
<!-- /container -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.1.js"><\/script>')</script>
<script src="js/vendor/bootstrap.min.js"></script>
<script src="js/main.js"></script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
(function (b, o, i, l, e, r) {
b.GoogleAnalyticsObject = l;
b[l] || (b[l] =
function () {
(b[l].q = b[l].q || []).push(arguments)
});
b[l].l = +new Date;
e = o.createElement(i);
r = o.getElementsByTagName(i)[0];
e.src = '//www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e, r)
}(window, document, 'script', 'ga'));
ga('create', 'UA-XXXXX-X');
ga('send', 'pageview');
</script>
</body>
</html>
| NCSSM-CS/CSAssess | view/student_section.html | HTML | mit | 7,369 |
# A secret token used to encrypt user_id's in the Bookmarks#export callback URL
# functionality, for example in Refworks export of Bookmarks. In Rails 4, Blacklight
# will use the application's secret key base instead.
#
# Blacklight.secret_key = 'e7ac6b51ad342a5757ea602e7e86309345bbc653a423195e1b82e1dd9102bd62643b82bb558df4b59ef674bbd8c8cb844acce6d792b86224fca0798b51692693'
| dtulibrary/ddf | config/initializers/blacklight_initializer.rb | Ruby | mit | 380 |
<?php return unserialize('a:2:{i:0;O:31:"Doctrine\\ORM\\Mapping\\ManyToMany":7:{s:12:"targetEntity";s:7:"Partida";s:8:"mappedBy";N;s:10:"inversedBy";N;s:7:"cascade";N;s:5:"fetch";s:4:"LAZY";s:13:"orphanRemoval";b:0;s:7:"indexBy";N;}i:1;O:30:"Doctrine\\ORM\\Mapping\\JoinTable":4:{s:4:"name";s:11:"usu_par_jug";s:6:"schema";N;s:11:"joinColumns";a:1:{i:0;O:31:"Doctrine\\ORM\\Mapping\\JoinColumn":7:{s:4:"name";s:10:"id_usuario";s:20:"referencedColumnName";s:2:"id";s:6:"unique";b:0;s:8:"nullable";b:1;s:8:"onDelete";N;s:16:"columnDefinition";N;s:9:"fieldName";N;}}s:18:"inverseJoinColumns";a:1:{i:0;O:31:"Doctrine\\ORM\\Mapping\\JoinColumn":7:{s:4:"name";s:10:"id_partida";s:20:"referencedColumnName";s:2:"id";s:6:"unique";b:0;s:8:"nullable";b:1;s:8:"onDelete";N;s:16:"columnDefinition";N;s:9:"fieldName";N;}}}}'); | CaosSLL/pruebas_caos | app/cache/dev/annotations/c202f13319a8139e2157969a59d0181ae4a326b8$partidas.cache.php | PHP | mit | 813 |
require 'timeout'
module CircuitBreakage
class CircuitOpen < RuntimeError; end
class CircuitTimeout < RuntimeError; end
# A simple circuit breaker implementation. See the main README for usage
# details.
#
class Breaker
attr_accessor :failure_count, :last_failed, :state, :block
attr_accessor :failure_threshold, :duration, :timeout, :last_exception
attr_accessor :only_trip_on, :never_trip_on
DEFAULT_FAILURE_THRESHOLD = 5 # Number of failures required to trip circuit
DEFAULT_DURATION = 300 # Number of seconds the circuit stays tripped
DEFAULT_TIMEOUT = 10 # Number of seconds before the call times out
DEFAULT_ONLY_TRIP_ON = [Exception] # Exceptions that trigger the breaker
DEFAULT_NEVER_TRIP_ON = [] # Exceptions that won't trigger the breaker
def initialize(block=nil)
self.block = block
self.failure_threshold = DEFAULT_FAILURE_THRESHOLD
self.duration = DEFAULT_DURATION
self.timeout = DEFAULT_TIMEOUT
self.only_trip_on = DEFAULT_ONLY_TRIP_ON
self.never_trip_on = DEFAULT_NEVER_TRIP_ON
self.failure_count ||= 0
self.last_failed ||= 0
self.state ||= 'closed'
end
# Yield the block within the circuit. If no block
# is passed use the block passed in at initialization
def call(*args, &block_arg)
case(state)
when 'open'
if time_to_retry?
do_retry(*args, &block_arg)
else
raise CircuitOpen
end
when 'closed'
do_call(*args, &block_arg)
end
end
private
# Defined independently so that it can be overridden.
def do_retry(*args, &block_arg)
do_call(*args, &block_arg)
end
def do_call(*args, &block_arg)
ret_value = nil
Timeout.timeout(self.timeout) do
ret_value = (block_arg || @block).call(*args)
end
handle_success
return ret_value
rescue *self.only_trip_on => e
raise if never_trip_on.any? { |t| e.instance_of?(t) }
handle_failure(e)
end
def time_to_retry?
Time.now.to_i >= self.last_failed + self.duration
end
def handle_success
self.failure_count = 0
self.state = 'closed'
end
def handle_failure(error)
self.last_failed = Time.now.to_i
self.failure_count += 1
if self.failure_count >= self.failure_threshold
self.state = 'open'
end
self.last_exception = error
if error.instance_of?(Timeout::Error)
# Raising an instance of Interrupt seems pretty rude, and there's no
# useful information in Timeout::Error anyway, so re-raise timeout
# errors as our own error class.
raise CircuitTimeout, "Circuit breaker timed out."
else
raise(error)
end
end
end
end
| djspinmonkey/circuit_breakage | lib/circuit_breakage/breaker.rb | Ruby | mit | 2,931 |
from django.http import JsonResponse
from django.shortcuts import render
from django.views.generic import View
# model
from gpsmap.models import UltimosGps, BusesDiarios
# Create your views here.
class MapHandler(View):
'''This class manages the map where the markers from the devices using the
application are shown'''
def __init__(self):
"""the contructor, context are the parameter given to the html template"""
self.context={}
def get(self, request):
template = "map.html"
return render(request, template, self.context)
class GetMapPositions(View):
'''This class requests to the database the values of the actives users'''
def __init__(self):
"""the contructor, context are the parameter given to the html template"""
self.context={}
def get(self, request):
# the position of interest are the ones ocurred in the last 10 minutes
positions = UltimosGps.objects.all()
#positions = UltimaCargaGps.objects.all()[:10]
response = []
for aPosition in positions:
response.append({'patente': aPosition.patente,
'servicioCodigo': aPosition.servicio,
'servicio': aPosition.servicio_usuario,
'distEnRuta': aPosition.dist_en_ruta,
'distARuta': aPosition.dist_a_ruta,
'velocidadInstantanea': aPosition.velocidad_instantanea,
'velocidad2GPS': aPosition.velocidad_2gps,
'velocidad4GPS': aPosition.velocidad_4gps,
'operador': aPosition.operador,
'latitud': aPosition.latitud,
'longitud': aPosition.longitud,
'tiempo': aPosition.tiempo,
'orientacion': aPosition.orientacion,
'tipo': aPosition.tipo,
'capacidad': aPosition.capacidad})
#response.append({'patente': aPosition.patente, 'servicio': aPosition.servicio, 'latitud': aPosition.latitud, 'longitud': aPosition.longitud, 'tiempo': aPosition.tiempo})
return JsonResponse(response, safe=False)
class GetMapPositionsByService(View):
'''This class requests to the database the values of the actives users'''
def __init__(self):
"""the contructor, context are the parameter given to the html template"""
self.context={}
def get(self, request, service, direction):
# the position of interest are the ones ocurred in the last 10 minutes
positions = UltimosGps.objects.filter(servicio_usuario__iregex=r'{0}{1}$'.format(service, direction))
response = []
for aPosition in positions:
noStop = BusesDiarios.objects.filter(patente=aPosition.patente).order_by('-t_inicial').first()
noStopNum = "No Info."
if noStop is not None:
noStopNum = noStop.no_detenciones
response.append({'patente': aPosition.patente,
'servicioCodigo': aPosition.servicio,
'servicio': aPosition.servicio_usuario,
'distEnRuta': aPosition.dist_en_ruta,
'distARuta': aPosition.dist_a_ruta,
'velocidadInstantanea': aPosition.velocidad_instantanea,
'velocidad2GPS': aPosition.velocidad_2gps,
'velocidad4GPS': aPosition.velocidad_4gps,
'operador': aPosition.operador,
'latitud': aPosition.latitud,
'longitud': aPosition.longitud,
'tiempo': aPosition.tiempo,
'orientacion': aPosition.orientacion,
'tipo': aPosition.tipo,
'capacidad': aPosition.capacidad,
'noParo': noStopNum})
return JsonResponse(response, safe=False)
class ServiceHandler(View):
'''This class manages the map where the markers from the devices using the
application are shown'''
def __init__(self):
"""the contructor, context are the parameter given to the html template"""
self.context={}
def get(self, request):
template = "service.html"
return render(request, template, self.context)
| SmartcitySantiagoChile/onlineGPS | gpsmap/views.py | Python | mit | 4,112 |
<?php
class LocationModel extends CI_Model
{
public function __construct()
{
parent::__construct();
}
/////////////////////////
// CRUD-actions
/////////////////////////
/** Returns all locations as an array */
public function get_all_locations()
{
return $this->db->get('location')->result();
}
/** Adds a location to the DB */
public function add_location($location)
{
$this->db->insert('location', $location);
return $this->db->insert_id();
}
/** Updates the location specified by the id with the details of the location */
public function update_location($location_id, $location)
{
$this->db->where('id', $location_id);
$this->db->update('location', $location);
}
/** Deletes a location from the DB */
public function delete_location($location_id)
{
$this->db->delete('location', array('id' => $location_id));
}
/** Returns the location for an id */
public function get_location_by_id($location_id)
{
return $this->db->get_where('location', array('id' => $location_id))->row();
}
/////////////////////////
// Experiments
/////////////////////////
/** Retrieves all experiments for a location */
public function get_experiments_by_location($location_id)
{
$this->db->where('location_id', $location_id);
return $this->db->get('experiment')->result();
}
/** Retrieves a location by the experiment id */
public function get_location_by_experiment($experiment)
{
return $this->db->get_where('location', array('id' => $experiment->location_id))->row();
}
} | UiL-OTS-labs/babylab-admin | application/models/LocationModel.php | PHP | mit | 1,522 |
package by.triumgroup.recourse.controller;
import by.triumgroup.recourse.configuration.security.Auth;
import by.triumgroup.recourse.configuration.security.UserAuthDetails;
import by.triumgroup.recourse.controller.exception.ControllerException;
import by.triumgroup.recourse.entity.dto.PasswordChanging;
import by.triumgroup.recourse.entity.dto.RegistrationDetails;
import by.triumgroup.recourse.entity.model.User;
import org.springframework.data.domain.Pageable;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("api/users")
public interface UserController extends CrudController<User, Integer> {
@GetMapping(value = "", params = "role")
List<User> getUsersByRole(@RequestParam("role") User.Role role, Pageable pageable, @Auth UserAuthDetails authDetails);
@GetMapping("/me")
User getMyInfo(@Auth UserAuthDetails authDetails);
@PostMapping("/register")
void register(@RequestBody RegistrationDetails registrationDetails) throws ControllerException;
@PostMapping("/logout")
void logout(OAuth2Authentication principal) throws ControllerException;
@PostMapping("/password/change")
void changePassword(@RequestBody PasswordChanging passwordChanging, @Auth UserAuthDetails userAuthDetails) throws ControllerException;
}
| TriumGroup/ReCourse | src/main/java/by/triumgroup/recourse/controller/UserController.java | Java | mit | 1,394 |
---
title: "Sitting on the beach at sunset"
excerpt: "PaperFaces portrait of @sbrolins drawn with Paper for iOS on an iPad."
image:
path: &image /assets/images/paperfaces-sbrolins-twitter.jpg
feature: *image
thumbnail: /assets/images/paperfaces-sbrolins-twitter-150.jpg
categories: [paperfaces]
tags: [portrait, illustration, Paper for iOS]
---
PaperFaces portrait of [@sbrolins](https://twitter.com/sbrolins). Painting a sky or water is very rewarding with Paper for iOS, because with little effort you can create a masterpiece.
There really wasn't much to this landscape --- just a few layers of light red orange that fade into the horizon, and pink pencil strokes for the clouds. The beach is made up of dull blue violet watercolor layers, topped with light pencil strokes to create a sand texture.
{% include_cached boilerplate/paperfaces.md %}
{% figure caption:"Work in progress screenshots." class:"gallery-2-col" %}
[](/assets/images/paperfaces-sbrolins-process-1-lg.jpg)
[](/assets/images/paperfaces-sbrolins-process-2-lg.jpg)
{% endfigure %}
{% figure caption:"Work in progress screenshot." %}
[](/assets/images/paperfaces-sbrolins-process-3-lg.jpg)
{% endfigure %}
{% figure caption:"Work in progress screenshots." class:"gallery-2-col" %}
[](/assets/images/paperfaces-sbrolins-process-4-lg.jpg)
[](/assets/images/paperfaces-sbrolins-process-5-lg.jpg)
{% endfigure %}
| mmistakes/made-mistakes-jekyll | src/_posts/paperfaces/2013-07-29-sbrolins-portrait.md | Markdown | mit | 1,678 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Turbo Admin LTE </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.6 -->
<link rel="stylesheet" href="assets/plugins/bootstrap/css/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="assets/css/turbolte.min.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="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="sidebar-mini skin-blue " >
<div class="wrapper">
<header class="main-header">
<!-- Header Navbar: style can be found in header.less -->
<nav class="navbar navbar-static-top">
<!-- Logo -->
<a href="index2.html" class="logo">
<span class="logo-lg"><b>Turbo Admin</b> LTE</span>
</a>
<!-- Sidebar toggle button-->
<a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button">
<span class="sr-only">Toggle navigation</span>
</a>
<!-- search form -->
<form action="#" method="get" class="sidebar-form">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="Search...">
</div>
</form>
<!-- /.search form -->
<div class="navbar-custom-menu">
<ul class="nav navbar-nav">
<!-- Messages: style can be found in dropdown.less-->
<li class="dropdown messages-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-envelope-o"></i>
<span class="label label-success">4</span>
</a>
<ul class="dropdown-menu">
<li class="header">You have 4 messages</li>
<li>
<!-- inner menu: contains the actual data -->
<ul class="menu">
<li><!-- start message -->
<a href="#">
<div class="pull-left">
<img src="assets/img/user2-160x160.jpg" class="img-circle" alt="User Image">
</div>
<h4>
Support Team
<small><i class="fa fa-clock-o"></i> 5 mins</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
<!-- end message -->
<li>
<a href="#">
<div class="pull-left">
<img src="assets/img/user3-128x128.jpg" class="img-circle" alt="User Image">
</div>
<h4>
AdminLTE Design Team
<small><i class="fa fa-clock-o"></i> 2 hours</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
<li>
<a href="#">
<div class="pull-left">
<img src="assets/img/user4-128x128.jpg" class="img-circle" alt="User Image">
</div>
<h4>
Developers
<small><i class="fa fa-clock-o"></i> Today</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
<li>
<a href="#">
<div class="pull-left">
<img src="assets/img/user3-128x128.jpg" class="img-circle" alt="User Image">
</div>
<h4>
Sales Department
<small><i class="fa fa-clock-o"></i> Yesterday</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
<li>
<a href="#">
<div class="pull-left">
<img src="assets/img/user4-128x128.jpg" class="img-circle" alt="User Image">
</div>
<h4>
Reviewers
<small><i class="fa fa-clock-o"></i> 2 days</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
</ul>
</li>
<li class="footer"><a href="#">See All Messages</a></li>
</ul>
</li>
<!-- Notifications: style can be found in dropdown.less -->
<li class="dropdown notifications-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-bell-o"></i>
<span class="label label-warning">10</span>
</a>
<ul class="dropdown-menu">
<li class="header">You have 10 notifications</li>
<li>
<!-- inner menu: contains the actual data -->
<ul class="menu">
<li>
<a href="#">
<i class="fa fa-users text-aqua"></i> 5 new members joined today
</a>
</li>
<li>
<a href="#">
<i class="fa fa-warning text-yellow"></i> Very long description here that may not fit into the
page and may cause design problems
</a>
</li>
<li>
<a href="#">
<i class="fa fa-users text-red"></i> 5 new members joined
</a>
</li>
<li>
<a href="#">
<i class="fa fa-shopping-cart text-green"></i> 25 sales made
</a>
</li>
<li>
<a href="#">
<i class="fa fa-user text-red"></i> You changed your username
</a>
</li>
</ul>
</li>
<li class="footer"><a href="#">View all</a></li>
</ul>
</li>
<!-- Tasks: style can be found in dropdown.less -->
<li class="dropdown tasks-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-flag-o"></i>
<span class="label label-danger">9</span>
</a>
<ul class="dropdown-menu">
<li class="header">You have 9 tasks</li>
<li>
<!-- inner menu: contains the actual data -->
<ul class="menu">
<li><!-- Task item -->
<a href="#">
<h3>
Design some buttons
<small class="pull-right">20%</small>
</h3>
<div class="progress xs">
<div class="progress-bar progress-bar-aqua" style="width: 20%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">20% Complete</span>
</div>
</div>
</a>
</li>
<!-- end task item -->
<li><!-- Task item -->
<a href="#">
<h3>
Create a nice theme
<small class="pull-right">40%</small>
</h3>
<div class="progress xs">
<div class="progress-bar progress-bar-green" style="width: 40%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">40% Complete</span>
</div>
</div>
</a>
</li>
<!-- end task item -->
<li><!-- Task item -->
<a href="#">
<h3>
Some task I need to do
<small class="pull-right">60%</small>
</h3>
<div class="progress xs">
<div class="progress-bar progress-bar-red" style="width: 60%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">60% Complete</span>
</div>
</div>
</a>
</li>
<!-- end task item -->
<li><!-- Task item -->
<a href="#">
<h3>
Make beautiful transitions
<small class="pull-right">80%</small>
</h3>
<div class="progress xs">
<div class="progress-bar progress-bar-yellow" style="width: 80%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">80% Complete</span>
</div>
</div>
</a>
</li>
<!-- end task item -->
</ul>
</li>
<li class="footer">
<a href="#">View all tasks</a>
</li>
</ul>
</li>
<!-- User Account: style can be found in dropdown.less -->
<li class="dropdown user user-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<img src="assets/img/user2-160x160.jpg" class="user-image" alt="User Image">
<span class="hidden-xs">Alexander Pierce</span>
</a>
<ul class="dropdown-menu">
<!-- User image -->
<li class="user-header">
<img src="assets/img/user2-160x160.jpg" class="img-circle" alt="User Image">
<p>
Alexander Pierce - Web Developer
<small>Member since Nov. 2012</small>
</p>
</li>
<!-- Menu Body -->
<li class="user-body">
<div class="row">
<div class="col-xs-4 text-center">
<a href="#">Followers</a>
</div>
<div class="col-xs-4 text-center">
<a href="#">Sales</a>
</div>
<div class="col-xs-4 text-center">
<a href="#">Friends</a>
</div>
</div>
<!-- /.row -->
</li>
<!-- Menu Footer-->
<li class="user-footer">
<div class="pull-left">
<a href="#" class="btn btn-default btn-flat">Profile</a>
</div>
<div class="pull-right">
<a href="#" class="btn btn-default btn-flat">Sign out</a>
</div>
</li>
</ul>
</li>
<!-- Control Sidebar Toggle Button -->
<li>
<a href="#" data-toggle="control-sidebar"><i class="fa fa-gears"></i></a>
</li>
</ul>
</div>
</nav>
</header>
<aside class="main-sidebar">
<section class="sidebar">
<ul class="sidebar-menu">
<li class="header">MAIN NAVIGATION</li>
<li class="treeview">
<a href="#">
<i class="fa fa-dashboard"></i> <span>Dashboard</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<li id="index"><a href="index.html"> Dashboard v1</a></li>
<li id="index2"><a href="index2.html"> Dashboard v2</a></li>
</ul>
</li>
<li id="widgets">
<a href="widgets.html">
<i class="fa fa-th"></i> <span>Widgets</span>
<span class="pull-right-container">
<small class="label pull-right bg-green">new</small>
</span>
</a>
</li>
<li class="treeview">
<a href="#">
<i class="fa fa-pie-chart"></i>
<span>Charts</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<li id="charts_chartjs"><a href="charts_chartjs.html"> ChartJS</a></li>
<li id="charts_morrisjs"><a href="charts_morrisjs.html"> Morris</a></li>
<li id="charts_flotjs"><a href="charts_flotjs.html"> Flot</a></li>
<li id="charts_inlinejs"><a href="charts_inlinejs.html"> Inline charts</a></li>
</ul>
</li>
<li class="treeview">
<a href="#">
<i class="fa fa-laptop"></i>
<span>UI Elements</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<li id="ui_general"><a href="ui_general.html"> General</a></li>
<li id="ui_icons"><a href="ui_icons.html"> Icons</a></li>
<li id="ui_buttons"><a href="ui_buttons.html"> Buttons</a></li>
<li id="ui_sliders"><a href="ui_sliders.html"> Sliders</a></li>
<li id="ui_timeline"><a href="ui_timeline.html"> Timeline</a></li>
<li id="ui_modals"><a href="ui_modals.html"> Modals</a></li>
</ul>
</li>
<li class="treeview">
<a href="#">
<i class="fa fa-edit"></i> <span>Forms</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<li id="forms_general"><a href="forms_general.html"> General Elements</a></li>
<li id="forms_advanced"><a href="forms_advanced.html"> Advanced Elements</a></li>
<li id="forms_editors"><a href="forms_editors.html"> Editors</a></li>
</ul>
</li>
<li class="treeview">
<a href="#">
<i class="fa fa-table"></i> <span>Tables</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<li id="tables_simple"><a href="tables_simple.html"> Simple tables</a></li>
<li id="tables_data"><a href="tables_data.html"> Data tables</a></li>
</ul>
</li>
<li id="_calendar">
<a href="_calendar.html">
<i class="fa fa-calendar"></i> <span>Calendar</span>
<span class="pull-right-container">
<small class="label pull-right bg-red">3</small>
<small class="label pull-right bg-blue">17</small>
</span>
</a>
</li>
<li id="mailbox_mailbox">
<a href="mailbox_mailbox.html">
<i class="fa fa-envelope"></i> <span>Mailbox</span>
<span class="pull-right-container">
<small class="label pull-right bg-yellow">12</small>
<small class="label pull-right bg-green">16</small>
<small class="label pull-right bg-red">5</small>
</span>
</a>
</li>
<li class="treeview">
<a href="#">
<i class="fa fa-folder"></i> <span>Examples</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<li id="pages_example_invoice"><a href="pages_example_invoice.html"> Invoice</a></li>
<li id="pages_example_profile"><a href="pages_example_profile.html"> Profile</a></li>
<li id="pages_example_login"><a href="pages_example_login.html"> Login</a></li>
<li id="pages_example_register"><a href="pages_example_register.html"> Register</a></li>
<li id="pages_example_lockscreen"><a href="pages_example_lockscreen.html"> Lockscreen</a></li>
<li id="pages_example_404"><a href="pages_example_404.html"> 404 Error</a></li>
<li id="pages_example_500"><a href="pages_example_500.html"> 500 Error</a></li>
<li id="pages_example_blank"><a href="pages_example_blank.html"> Blank Page</a></li>
<li id="pages_examples_pace"><a href="pages_examples_pace.html"> Pace Page</a></li>
</ul>
</li>
<li class="treeview">
<a href="#">
<i class="fa fa-share"></i> <span>Multilevel</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<li><a href="#"> Level One</a></li>
<li>
<a href="#"> Level One
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<li><a href="#"> Level Two</a></li>
<li>
<a href="#"> Level Two
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<li><a href="#"> Level Three</a></li>
<li><a href="#"> Level Three</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#"> Level One</a></li>
</ul>
</li>
<li class="header">LABELS</li>
<li><a href="#"><i class="fa fa-circle-o text-red"></i> <span>Important</span></a></li>
<li><a href="#"><i class="fa fa-circle-o text-yellow"></i> <span>Warning</span></a></li>
<li><a href="#"><i class="fa fa-circle-o text-aqua"></i> <span>Information</span></a></li>
<li><a href="https://github.com/Rafaelgfirmino/Turbo-Admin-LTE" target="_blank"><i class="fa fa-github"></i> <span>To contribute </span></a>
</li>
</ul>
</section>
<!-- /.sidebar -->
</aside>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
<small></small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i>Home</a></li>
<li class="active">Dashboard</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<!-- row -->
<div class="row">
<div class="col-md-12">
<!-- The time line -->
<ul class="timeline">
<!-- timeline time label -->
<li class="time-label">
<span class="bg-red">
10 Feb. 2014
</span>
</li>
<!-- /.timeline-label -->
<!-- timeline item -->
<li>
<i class="fa fa-envelope bg-blue"></i>
<div class="timeline-item">
<span class="time"><i class="fa fa-clock-o"></i> 12:05</span>
<h3 class="timeline-header"><a href="#">Support Team</a> sent you an email</h3>
<div class="timeline-body">
Etsy doostang zoodles disqus groupon greplin oooj voxy zoodles,
weebly ning heekya handango imeem plugg dopplr jibjab, movity
jajah plickers sifteo edmodo ifttt zimbra. Babblely odeo kaboodle
quora plaxo ideeli hulu weebly balihoo...
</div>
<div class="timeline-footer">
<a class="btn btn-primary btn-xs">Read more</a>
<a class="btn btn-danger btn-xs">Delete</a>
</div>
</div>
</li>
<!-- END timeline item -->
<!-- timeline item -->
<li>
<i class="fa fa-user bg-aqua"></i>
<div class="timeline-item">
<span class="time"><i class="fa fa-clock-o"></i> 5 mins ago</span>
<h3 class="timeline-header no-border"><a href="#">Sarah Young</a> accepted your friend request</h3>
</div>
</li>
<!-- END timeline item -->
<!-- timeline item -->
<li>
<i class="fa fa-comments bg-yellow"></i>
<div class="timeline-item">
<span class="time"><i class="fa fa-clock-o"></i> 27 mins ago</span>
<h3 class="timeline-header"><a href="#">Jay White</a> commented on your post</h3>
<div class="timeline-body">
Take me to your leader!
Switzerland is small and neutral!
We are more like Germany, ambitious and misunderstood!
</div>
<div class="timeline-footer">
<a class="btn btn-warning btn-flat btn-xs">View comment</a>
</div>
</div>
</li>
<!-- END timeline item -->
<!-- timeline time label -->
<li class="time-label">
<span class="bg-green">
3 Jan. 2014
</span>
</li>
<!-- /.timeline-label -->
<!-- timeline item -->
<li>
<i class="fa fa-camera bg-purple"></i>
<div class="timeline-item">
<span class="time"><i class="fa fa-clock-o"></i> 2 days ago</span>
<h3 class="timeline-header"><a href="#">Mina Lee</a> uploaded new photos</h3>
<div class="timeline-body">
<img src="http://placehold.it/150x100" alt="..." class="margin">
<img src="http://placehold.it/150x100" alt="..." class="margin">
<img src="http://placehold.it/150x100" alt="..." class="margin">
<img src="http://placehold.it/150x100" alt="..." class="margin">
</div>
</div>
</li>
<!-- END timeline item -->
<!-- timeline item -->
<li>
<i class="fa fa-video-camera bg-maroon"></i>
<div class="timeline-item">
<span class="time"><i class="fa fa-clock-o"></i> 5 days ago</span>
<h3 class="timeline-header"><a href="#">Mr. Doe</a> shared a video</h3>
<div class="timeline-body">
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/tMWkeBIohBs"
frameborder="0" allowfullscreen></iframe>
</div>
</div>
<div class="timeline-footer">
<a href="#" class="btn btn-xs bg-maroon">See comments</a>
</div>
</div>
</li>
<!-- END timeline item -->
<li>
<i class="fa fa-clock-o bg-gray"></i>
</li>
</ul>
</div>
<!-- /.col -->
</div>
<!-- /.row -->
<div class="row" style="margin-top: 10px;">
<div class="col-md-12">
<div class="box box-primary">
<div class="box-header">
<h3 class="box-title"><i class="fa fa-code"></i> Timeline Markup</h3>
</div>
<div class="box-body">
<pre style="font-weight: 600;">
<ul class="timeline">
<!-- timeline time label -->
<li class="time-label">
<span class="bg-red">
10 Feb. 2014
</span>
</li>
<!-- /.timeline-label -->
<!-- timeline item -->
<li>
<!-- timeline icon -->
<i class="fa fa-envelope bg-blue"></i>
<div class="timeline-item">
<span class="time"><i class="fa fa-clock-o"></i> 12:05</span>
<h3 class="timeline-header"><a href="#">Support Team</a> ...</h3>
<div class="timeline-body">
...
Content goes here
</div>
<div class="timeline-footer">
<a class="btn btn-primary btn-xs">...</a>
</div>
</div>
</li>
<!-- END timeline item -->
...
</ul>
</pre>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<footer class="main-footer">
<div class="pull-right hidden-xs">
<b>Version</b> 0.0.0-dev
</div>
<strong>Copyright © 2014-2016 <a href="javascript;"> Turbo Admin LTE</a>.</strong> All rights
reserved.
</footer>
<!-- Control Sidebar -->
<aside class="control-sidebar control-sidebar-dark">
<!-- Create the tabs -->
<ul class="nav nav-tabs nav-justified control-sidebar-tabs">
<li><a href="#control-sidebar-home-tab" data-toggle="tab"><i class="fa fa-home"></i></a></li>
<li><a href="#control-sidebar-settings-tab" data-toggle="tab"><i class="fa fa-gears"></i></a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<!-- Home tab content -->
<div class="tab-pane" id="control-sidebar-home-tab">
<h3 class="control-sidebar-heading">Recent Activity</h3>
<ul class="control-sidebar-menu">
<li>
<a href="javascript:void(0)">
<i class="menu-icon fa fa-birthday-cake bg-red"></i>
<div class="menu-info">
<h4 class="control-sidebar-subheading">Langdon's Birthday</h4>
<p>Will be 23 on April 24th</p>
</div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<i class="menu-icon fa fa-user bg-yellow"></i>
<div class="menu-info">
<h4 class="control-sidebar-subheading">Frodo Updated His Profile</h4>
<p>New phone +1(800)555-1234</p>
</div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<i class="menu-icon fa fa-envelope-o bg-light-blue"></i>
<div class="menu-info">
<h4 class="control-sidebar-subheading">Nora Joined Mailing List</h4>
<p>[email protected]</p>
</div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<i class="menu-icon fa fa-file-code-o bg-green"></i>
<div class="menu-info">
<h4 class="control-sidebar-subheading">Cron Job 254 Executed</h4>
<p>Execution time 5 seconds</p>
</div>
</a>
</li>
</ul>
<!-- /.control-sidebar-menu -->
<h3 class="control-sidebar-heading">Tasks Progress</h3>
<ul class="control-sidebar-menu">
<li>
<a href="javascript:void(0)">
<h4 class="control-sidebar-subheading">
Custom Template Design
<span class="label label-danger pull-right">70%</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar progress-bar-danger" style="width: 70%"></div>
</div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<h4 class="control-sidebar-subheading">
Update Resume
<span class="label label-success pull-right">95%</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar progress-bar-success" style="width: 95%"></div>
</div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<h4 class="control-sidebar-subheading">
Laravel Integration
<span class="label label-warning pull-right">50%</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar progress-bar-warning" style="width: 50%"></div>
</div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<h4 class="control-sidebar-subheading">
Back End Framework
<span class="label label-primary pull-right">68%</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar progress-bar-primary" style="width: 68%"></div>
</div>
</a>
</li>
</ul>
<!-- /.control-sidebar-menu -->
</div>
<!-- /.tab-pane -->
<!-- Stats tab content -->
<div class="tab-pane" id="control-sidebar-stats-tab">Stats Tab Content</div>
<!-- /.tab-pane -->
<!-- Settings tab content -->
<div class="tab-pane" id="control-sidebar-settings-tab">
<form method="post">
<h3 class="control-sidebar-heading">General Settings</h3>
<div class="form-group">
<label class="control-sidebar-subheading">
Report panel usage
<input type="checkbox" class="pull-right" checked>
</label>
<p>
Some information about this general settings option
</p>
</div>
<!-- /.form-group -->
<div class="form-group">
<label class="control-sidebar-subheading">
Allow mail redirect
<input type="checkbox" class="pull-right" checked>
</label>
<p>
Other sets of options are available
</p>
</div>
<!-- /.form-group -->
<div class="form-group">
<label class="control-sidebar-subheading">
Expose author name in posts
<input type="checkbox" class="pull-right" checked>
</label>
<p>
Allow the user to show his name in blog posts
</p>
</div>
<!-- /.form-group -->
<h3 class="control-sidebar-heading">Chat Settings</h3>
<div class="form-group">
<label class="control-sidebar-subheading">
Show me as online
<input type="checkbox" class="pull-right" checked>
</label>
</div>
<!-- /.form-group -->
<div class="form-group">
<label class="control-sidebar-subheading">
Turn off notifications
<input type="checkbox" class="pull-right">
</label>
</div>
<!-- /.form-group -->
<div class="form-group">
<label class="control-sidebar-subheading">
Delete chat history
<a href="javascript:void(0)" class="text-red pull-right"><i class="fa fa-trash-o"></i></a>
</label>
</div>
<!-- /.form-group -->
</form>
</div>
<!-- /.tab-pane -->
</div>
</aside>
<!-- /.control-sidebar -->
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar -->
<div class="control-sidebar-bg"></div>
</div>
<!-- ./wrapper -->
<!-- jQuery 2.2.3 -->
<script src="assets/plugins/jQuery/jquery-2.2.3.min.js"></script>
<!-- Bootstrap 3.3.6 -->
<script src="assets/plugins/bootstrap/js/bootstrap.min.js"></script>
<!-- slimscroll -->
<script src="assets/plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="assets/plugins/fastclick/fastclick.js"></script>
<!-- AdminLTE App -->
<script src="assets/js/app.min.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="assets/js/demo.js"></script>
</body>
</html>
| Rafaelgfirmino/Turbo-Admin-LTE | dist/ui_timeline.html | HTML | mit | 39,366 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="it">
<head>
<!-- Generated by javadoc (1.8.0_172) on Mon Aug 20 16:03:10 CEST 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Overview List (PlugFace :: Core 0.7.1 API)</title>
<meta name="date" content="2018-08-20">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div class="indexHeader"><span><a href="allclasses-frame.html" target="packageFrame">All Classes</a></span></div>
<div class="indexContainer">
<h2 title="Packages">Packages</h2>
<ul title="Packages">
<li><a href="org/plugface/core/package-frame.html" target="packageFrame">org.plugface.core</a></li>
<li><a href="org/plugface/core/annotations/package-frame.html" target="packageFrame">org.plugface.core.annotations</a></li>
<li><a href="org/plugface/core/factory/package-frame.html" target="packageFrame">org.plugface.core.factory</a></li>
<li><a href="org/plugface/core/impl/package-frame.html" target="packageFrame">org.plugface.core.impl</a></li>
<li><a href="org/plugface/core/internal/package-frame.html" target="packageFrame">org.plugface.core.internal</a></li>
<li><a href="org/plugface/core/internal/di/package-frame.html" target="packageFrame">org.plugface.core.internal.di</a></li>
</ul>
</div>
<p> </p>
</body>
</html>
| MatteoJoliveau/PlugFace | docs/apidocs/plugface-core/overview-frame.html | HTML | mit | 1,473 |
<div style="padding: 10px">
<h1 ng-show="item.title">
{{item.title}}
</h1>
<div ng-bind-html="item.content | markdown" ng-style="{'height':windowHeight-196, 'overflow-y': 'auto'}"/>
<div class="text-muted">
{{item.tags.join(' ')}}
</div>
<rating class="pull-left" value="item.rate" max="5" readonly="true"></rating>
<span class="text-muted pull-right">
<small>
created: {{item.createdAt | date:'yyyy/MM/dd HH:mm:ss'}},
modified: {{item.modifiedAt | date:'yyyy/MM/dd HH:mm:ss'}},
due: {{item.dueDate | date:'yyyy/MM/dd'}}
</small>
</span>
</div> | zoetrope/sidekick-note | ui/scripts/item/item.view.tpl.html | HTML | mit | 647 |
# dolar-realtime
Información del Dólar Interbancario en tiempo real desde https://dolar.set-icap.com/
To run the app you need [node.js,](https://nodejs.org/en/) then:
install dependencies:
$ cd dolar-realtime
$ npm install
On MacOS or Linux, run the app with this command:
$ DEBUG=myapp:* npm start
On Windows, use this command:
set DEBUG=myapp:* & npm start
Then load http://localhost:3000/ in your browser to access the app.
You can see the app running [here](https://dolar.victorv.co/)
| victorv977/dolar-realtime | README.md | Markdown | mit | 517 |
<?php
return [
'@class' => 'Grav\\Common\\File\\CompiledYamlFile',
'filename' => '/Applications/MAMP/htdocs/grav-ewb/system/blueprints/config/media.yaml',
'modified' => 1472221240,
'data' => [
'title' => 'PLUGIN_ADMIN.MEDIA',
'form' => [
'validation' => 'loose',
'fields' => NULL
]
]
];
| EWB/grav-ewb | cache/compiled/files/e0b85c7699fae6d1edbdd875a91d8bde.yaml.php | PHP | mit | 355 |
# 2017 - A New Blog Direction & Life Update
As you may've noticed, I don't really post here terribly often. A big reason for this is I envisioned starting a _tech_ blog as opposed to just a personal blog. The problem is, technical blog posts take a lot of time and thought to write, and I'm not a huge writer. That said, I would like to start getting in the habit of documenting my life a little more, so from this point on I'm going to just blog about _whatever_ is going on and assume nobody reads it as I assume now 👍
### A stressful summer
Around the end of July, I got a call from my mom stating that my dad had a heart attack. I drove up to Chicago to see him a few days later, when he was in the ICU. It was a rollercoaster of good news and bad news, and generally just a really stressful few days in the hospital. As things were looking optimistic, I headed home. A few weeks later I got another call that my dad had passed away. He was 71. I don't want to go into too much detail on this, but July and August were just difficult months. And I missed the solar eclipse due to the timing.
### New habits
The silver lining this summer is that I picked up a few good habits. For the drive home from Chicago on my first trip, I picked up an audiobook to listen to. I've never tried listening to audiobooks, and it turns out I rather like it. I've finished 9 books in about 6 weeks now. I decided that I would start doing some cardio to lose weight, and listening to audiobooks while exercising turns out to be a great combination.
In addition to that, I finally decided to seek some counseling for my anxiety issues. I've been pretty sure I've had generalized anxiety disorder for the last 2 years or so, but the summer putting my anxiety over the top made me realize that this issue won't get better unless I make a conscious effort to treat it. The daily exercise helps with this too, so all the new self-improvement efforts have a nice synergy.
### Goals for the rest of 2017/2018
My big goal for the remainder of 2017 is a weight loss goal. In total, the hope is to lose 36 pounds in a span of roughly 22 weeks. So far I've lost about 6 pounds, which is slower progress than I hoped for. I'm adding intermittent fasting (starting with a 16:8 every day) in addition to calorie counting + cardio. I've never tried intermittent fasting as part of a weight loss regimen, so it'll be interesting to see what the effect is.
While in Chicago, my sister mentioned that she ran a marathon and she was planning on running another one next year. Being the little brother, I have a very strong "if she can do it, so can I" attitude. Setting realistic goals, the plan is to run a half marathon in the first half of 2018. If that goes well, I can shoot for a full marathon for fall 2018/spring 2019. I'm not rushing to get to the full marathon, mainly because I'd rather avoid injury and gradually ramp up to that type of distance.
### What else?
Work is work, I just finished writing a few services in scala. Most of my focus is still R & Python, working with data scientists. Getting some time to play with a compiled language writing REST services is a nice change of pace.
Life is starting to feel a little more normal.
| nmcginn/blog | posts/2017-09-18-new-blog-direction.md | Markdown | mit | 3,233 |
/*
* Copyright (C) 2005 The Android Open Source Project
*
* 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.
*/
#define LOG_TAG "sharedbuffer"
#include <stdlib.h>
#include <string.h>
#include <log/log.h>
#include "SharedBuffer.h"
// ---------------------------------------------------------------------------
namespace android {
SharedBuffer* SharedBuffer::alloc(size_t size)
{
// Don't overflow if the combined size of the buffer / header is larger than
// size_max.
LOG_ALWAYS_FATAL_IF((size >= (SIZE_MAX - sizeof(SharedBuffer))),
"Invalid buffer size %zu", size);
SharedBuffer* sb = static_cast<SharedBuffer *>(malloc(sizeof(SharedBuffer) + size));
if (sb) {
// Should be std::atomic_init(&sb->mRefs, 1);
// But that generates a warning with some compilers.
// The following is OK on Android-supported platforms.
sb->mRefs.store(1, std::memory_order_relaxed);
sb->mSize = size;
}
return sb;
}
void SharedBuffer::dealloc(const SharedBuffer* released)
{
free(const_cast<SharedBuffer*>(released));
}
SharedBuffer* SharedBuffer::edit() const
{
if (onlyOwner()) {
return const_cast<SharedBuffer*>(this);
}
SharedBuffer* sb = alloc(mSize);
if (sb) {
memcpy(sb->data(), data(), size());
release();
}
return sb;
}
SharedBuffer* SharedBuffer::editResize(size_t newSize) const
{
if (onlyOwner()) {
SharedBuffer* buf = const_cast<SharedBuffer*>(this);
if (buf->mSize == newSize) return buf;
// Don't overflow if the combined size of the new buffer / header is larger than
// size_max.
LOG_ALWAYS_FATAL_IF((newSize >= (SIZE_MAX - sizeof(SharedBuffer))),
"Invalid buffer size %zu", newSize);
buf = (SharedBuffer*)realloc(buf, sizeof(SharedBuffer) + newSize);
if (buf != NULL) {
buf->mSize = newSize;
return buf;
}
}
SharedBuffer* sb = alloc(newSize);
if (sb) {
const size_t mySize = mSize;
memcpy(sb->data(), data(), newSize < mySize ? newSize : mySize);
release();
}
return sb;
}
SharedBuffer* SharedBuffer::attemptEdit() const
{
if (onlyOwner()) {
return const_cast<SharedBuffer*>(this);
}
return 0;
}
SharedBuffer* SharedBuffer::reset(size_t new_size) const
{
// cheap-o-reset.
SharedBuffer* sb = alloc(new_size);
if (sb) {
release();
}
return sb;
}
void SharedBuffer::acquire() const {
mRefs.fetch_add(1, std::memory_order_relaxed);
}
int32_t SharedBuffer::release(uint32_t flags) const
{
int32_t prev = 1;
if (onlyOwner()
|| (((prev = mRefs.fetch_sub(1, std::memory_order_release)) == 1)
&& (atomic_thread_fence(std::memory_order_acquire), true))) {
mRefs.store(0, std::memory_order_relaxed);
if ((flags & eKeepStorage) == 0) {
free(const_cast<SharedBuffer*>(this));
}
}
return prev;
}
}; // namespace android
| dylanh333/android-unmkbootimg | vendor/android-tools/libutils/SharedBuffer.cpp | C++ | mit | 3,576 |
"use strict";
import {IEngine} from './Engine';
import {DieselEngine} from './DieselEngine';
import {GasolineEngine} from './GasolineEngine';
export class Vehicle {
engine: IEngine;
constructor(type: string) {
switch(type) {
case "diesel":
this.engine = new DieselEngine(200);
break;
case "gasoline":
default:
this.engine = new GasolineEngine(200);
}
}
}
| mechanoid/ts-import-error-test | src/Vehicle.ts | TypeScript | mit | 414 |
namespace Caliburn.PresentationFramework
{
using Configuration;
using Core.Configuration;
/// <summary>
/// Extension methods related to the PresentationFramework classes.
/// </summary>
public static class PresentationFrameworkExtensions
{
/// <summary>
/// Adds the presentation framework module's configuration to the system.
/// </summary>
/// <param name="hook">The hook.</param>
public static PresentationFrameworkConfiguration PresentationFramework(this IModuleHook hook)
{
return hook.Module(CaliburnModule<PresentationFrameworkConfiguration>.Instance);
}
/// <summary>
/// Safely converts an object to a string.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>The converted string or null, if the value was null.</returns>
internal static string SafeToString(this object value)
{
return value == null ? null : value.ToString();
}
}
} | CaliburnFx/Caliburn | src/Caliburn/PresentationFramework/PresentationFrameworkExtensions.cs | C# | mit | 1,086 |
package sc.ala.neo4j.commands
import sc.ala.neo4j._
import org.neo4j.kernel.EmbeddedGraphDatabase
import org.neo4j.graphdb._
import org.neo4j.graphalgo.GraphAlgoFactory
import org.neo4j.kernel.Traversal
import scala.collection.mutable.Map
import scala.collection.JavaConversions._
import scala.Console.err
trait DijkstraPath { this:Neo =>
private val nodes = findNodeByName
def dijkstraPath(n1:String, n2:String, relName:String) = R{
val rel = DynamicRelationshipType.withName(relName)
val trav = Traversal.expanderForTypes( rel, Direction.BOTH )
val algo = GraphAlgoFactory.shortestPath(trav, 15)
val paths = algo.findAllPaths(nodes(n1), nodes(n2))
println("size="+paths.size)
// TODO: this raises null pointer exception
paths foreach(println)
}
}
| maiha/neo4j | src/main/scala/sc/ala/neo4j/commands/DijkstraPath.scala | Scala | mit | 790 |
local table_utils = require("riritools.lua.table_utils")
local vector3 = vmath.vector3
local vector4 = vmath.vector4
local max = math.max
local min = math.min
local vector = table_utils.make_read_only_table {
NULL_VECTOR3 = vector3(),
NULL_VECTOR4 = vector4(),
UNIT_VECTOR3 = vector3(1),
UNIT_VECTOR4 = vector4(1),
move_to = function(vector, x, y, speed)
local result = 0
if (vector.x < x) then
vector.x = min(vector.x + speed, x)
elseif (vector.x > x) then
vector.x = max(vector.x - speed, x)
else
result = result + 1
end
if (vector.y < y) then
vector.y = min(vector.y + speed, y)
elseif (vector.y > y) then
vector.y = max(vector.y - speed, y)
else
result = result + 1
end
return (result == 2)
end,
vector3_to_table = function(vector)
return {x=vector.x, y=vector.y, z=vector.z}
end,
vector4_to_table = function(vector)
return {x=vector.x, y=vector.y, z=vector.z, w=vector.w}
end,
table_to_vector3 = function(table)
return vector3(table.x, table.y, table.z)
end,
table_to_vector4 = function(table)
return vector4(table.x, table.y, table.z, table.w)
end,
vector3_to_vector4 = function(vector3_instance)
return vector4(vector3_instance.x, vector3_instance.y, vector3_instance.z, 0)
end,
vector3_to_vector4_normalized = function(vector3_instance)
return vector4(vector3_instance.x, vector3_instance.y, vector3_instance.z, 1)
end,
vector4_to_vector3 = function(vector4_instance)
return vector3(vector4_instance.x, vector4_instance.y, vector4_instance.z)
end,
}
return vector
| CodingKitsune/Riritools | riritools/lua/vector_utils.lua | Lua | mit | 1,617 |
from .models import Client
from .models import Profile
from .models import Service
from .models import Testimonial
from django.contrib.auth.models import User
from rest_framework import serializers
class ClientSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Client
fields = ('name', 'description', 'icon')
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('first_name', 'last_name')
class ProfileSerializer(serializers.ModelSerializer):
# https://github.com/tomchristie/django-rest-framework/issues/1984#issuecomment-60267220
user = UserSerializer()
class Meta:
model = Profile
depth = 1
fields = ('get_avatar_url', 'get_username', 'bio', 'user')
class ServiceSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Service
fields = ('name', 'description', 'icon')
class TestimonialSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Testimonial
fields = ('name', 'slug', 'title', 'description', 'issue_date')
| ACLARKNET/aclarknet-database | aclarknet/database/serializers.py | Python | mit | 1,133 |
package eu.appbucket.queue.core.service.util;
import java.util.Calendar;
import java.util.Date;
public class TimeGenerator {
public static Date getTodayMidnightDate() {
Date now = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
}
| codeforireland/myq-backend-app | src/main/java/eu/appbucket/queue/core/service/util/TimeGenerator.java | Java | mit | 476 |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "alert.h"
#include "checkpoints.h"
#include "db.h"
#include "net.h"
#include "init.h"
#include "ui_interface.h"
#include "kernel.h"
#include "scrypt_mine.h"
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
using namespace std;
using namespace boost;
//
// Global state
//
CCriticalSection cs_setpwalletRegistered;
set<CWallet*> setpwalletRegistered;
CCriticalSection cs_main;
CTxMemPool mempool;
unsigned int nTransactionsUpdated = 0;
map<uint256, CBlockIndex*> mapBlockIndex;
set<pair<COutPoint, unsigned int> > setStakeSeen;
uint256 hashGenesisBlock = hashGenesisBlockOfficial;
static CBigNum bnProofOfWorkLimit(~uint256(0) >> 20);
static CBigNum bnProofOfStakeLimit(~uint256(0) >> 20);
static CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 20);
static CBigNum bnProofOfStakeLimitTestNet(~uint256(0) >> 20);
unsigned int nStakeMinAge = 60 * 60 * 24 * 20; // minimum age for coin age: 20d
unsigned int nStakeMaxAge = 60 * 60 * 24 * 40; // stake age of full weight: 40d
unsigned int nStakeTargetSpacing = 30; // 30 sec block spacing
int64 nChainStartTime = 1391393673;
int nCoinbaseMaturity = 30;
CBlockIndex* pindexGenesisBlock = NULL;
int nBestHeight = -1;
CBigNum bnBestChainTrust = 0;
CBigNum bnBestInvalidTrust = 0;
uint256 hashBestChain = 0;
CBlockIndex* pindexBest = NULL;
int64 nTimeBestReceived = 0;
CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
map<uint256, CBlock*> mapOrphanBlocks;
multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
map<uint256, uint256> mapProofOfStake;
map<uint256, CDataStream*> mapOrphanTransactions;
map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
// Constant stuff for coinbase transactions we create:
CScript COINBASE_FLAGS;
const string strMessageMagic = "MintCoin Signed Message:\n";
double dHashesPerSec;
int64 nHPSTimerStart;
// Settings
int64 nTransactionFee = MIN_TX_FEE;
//////////////////////////////////////////////////////////////////////////////
//
// dispatching functions
//
// These functions dispatch to one or all registered wallets
void RegisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.insert(pwalletIn);
}
}
void UnregisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.erase(pwalletIn);
}
}
// check whether the passed transaction is from us
bool static IsFromMe(CTransaction& tx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->IsFromMe(tx))
return true;
return false;
}
// get the wallet transaction with the given hash (if it exists)
bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->GetTransaction(hashTx,wtx))
return true;
return false;
}
// erases transaction with the given hash from all wallets
void static EraseFromWallets(uint256 hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->EraseFromWallet(hash);
}
// make sure all wallets know about the given transaction, in the given block
void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
{
if (!fConnect)
{
// ppcoin: wallets need to refund inputs when disconnecting coinstake
if (tx.IsCoinStake())
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->IsFromMe(tx))
pwallet->DisableTransaction(tx);
}
return;
}
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
}
// notify wallets about a new best chain
void static SetBestChain(const CBlockLocator& loc)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->SetBestChain(loc);
}
// notify wallets about an updated transaction
void static UpdatedTransaction(const uint256& hashTx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->UpdatedTransaction(hashTx);
}
// dump all wallets
void static PrintWallets(const CBlock& block)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->PrintWallet(block);
}
// notify wallets about an incoming inventory (for request counts)
void static Inventory(const uint256& hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->Inventory(hash);
}
// ask wallets to resend their transactions
void ResendWalletTransactions()
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->ResendWalletTransactions();
}
//////////////////////////////////////////////////////////////////////////////
//
// mapOrphanTransactions
//
bool AddOrphanTx(const CDataStream& vMsg)
{
CTransaction tx;
CDataStream(vMsg) >> tx;
uint256 hash = tx.GetHash();
if (mapOrphanTransactions.count(hash))
return false;
CDataStream* pvMsg = new CDataStream(vMsg);
// Ignore big transactions, to avoid a
// send-big-orphans memory exhaustion attack. If a peer has a legitimate
// large transaction with a missing parent then we assume
// it will rebroadcast it later, after the parent transaction(s)
// have been mined or received.
// 10,000 orphans, each of which is at most 5,000 bytes big is
// at most 500 megabytes of orphans:
if (pvMsg->size() > 5000)
{
printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
delete pvMsg;
return false;
}
mapOrphanTransactions[hash] = pvMsg;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
mapOrphanTransactions.size());
return true;
}
void static EraseOrphanTx(uint256 hash)
{
if (!mapOrphanTransactions.count(hash))
return;
const CDataStream* pvMsg = mapOrphanTransactions[hash];
CTransaction tx;
CDataStream(*pvMsg) >> tx;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
}
delete pvMsg;
mapOrphanTransactions.erase(hash);
}
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
{
unsigned int nEvicted = 0;
while (mapOrphanTransactions.size() > nMaxOrphans)
{
// Evict a random orphan:
uint256 randomhash = GetRandHash();
map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
EraseOrphanTx(it->first);
++nEvicted;
}
return nEvicted;
}
//////////////////////////////////////////////////////////////////////////////
//
// CTransaction and CTxIndex
//
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
{
SetNull();
if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
return false;
if (!ReadFromDisk(txindexRet.pos))
return false;
if (prevout.n >= vout.size())
{
SetNull();
return false;
}
return true;
}
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
{
CTxIndex txindex;
return ReadFromDisk(txdb, prevout, txindex);
}
bool CTransaction::ReadFromDisk(COutPoint prevout)
{
CTxDB txdb("r");
CTxIndex txindex;
return ReadFromDisk(txdb, prevout, txindex);
}
bool CTransaction::IsStandard() const
{
if (nVersion > CTransaction::CURRENT_VERSION)
return false;
BOOST_FOREACH(const CTxIn& txin, vin)
{
// Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
// pay-to-script-hash, which is 3 ~80-byte signatures, 3
// ~65-byte public keys, plus a few script ops.
if (txin.scriptSig.size() > 500)
return false;
if (!txin.scriptSig.IsPushOnly())
return false;
}
BOOST_FOREACH(const CTxOut& txout, vout) {
if (!::IsStandard(txout.scriptPubKey))
return false;
if (txout.nValue == 0)
return false;
}
return true;
}
//
// Check transaction inputs, and make sure any
// pay-to-script-hash transactions are evaluating IsStandard scripts
//
// Why bother? To avoid denial-of-service attacks; an attacker
// can submit a standard HASH... OP_EQUAL transaction,
// which will get accepted into blocks. The redemption
// script can be anything; an attacker could use a very
// expensive-to-check-upon-redemption script like:
// DUP CHECKSIG DROP ... repeated 100 times... OP_1
//
bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
{
if (IsCoinBase())
return true; // Coinbases don't use vin normally
for (unsigned int i = 0; i < vin.size(); i++)
{
const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
vector<vector<unsigned char> > vSolutions;
txnouttype whichType;
// get the scriptPubKey corresponding to this input:
const CScript& prevScript = prev.scriptPubKey;
if (!Solver(prevScript, whichType, vSolutions))
return false;
int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
if (nArgsExpected < 0)
return false;
// Transactions with extra stuff in their scriptSigs are
// non-standard. Note that this EvalScript() call will
// be quick, because if there are any operations
// beside "push data" in the scriptSig the
// IsStandard() call returns false
vector<vector<unsigned char> > stack;
if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
return false;
if (whichType == TX_SCRIPTHASH)
{
if (stack.empty())
return false;
CScript subscript(stack.back().begin(), stack.back().end());
vector<vector<unsigned char> > vSolutions2;
txnouttype whichType2;
if (!Solver(subscript, whichType2, vSolutions2))
return false;
if (whichType2 == TX_SCRIPTHASH)
return false;
int tmpExpected;
tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
if (tmpExpected < 0)
return false;
nArgsExpected += tmpExpected;
}
if (stack.size() != (unsigned int)nArgsExpected)
return false;
}
return true;
}
unsigned int
CTransaction::GetLegacySigOpCount() const
{
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTxIn& txin, vin)
{
nSigOps += txin.scriptSig.GetSigOpCount(false);
}
BOOST_FOREACH(const CTxOut& txout, vout)
{
nSigOps += txout.scriptPubKey.GetSigOpCount(false);
}
return nSigOps;
}
int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
{
if (fClient)
{
if (hashBlock == 0)
return 0;
}
else
{
CBlock blockTmp;
if (pblock == NULL)
{
// Load the block this tx is in
CTxIndex txindex;
if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
return 0;
if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
return 0;
pblock = &blockTmp;
}
// Update the tx's hashBlock
hashBlock = pblock->GetHash();
// Locate the transaction
for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
if (pblock->vtx[nIndex] == *(CTransaction*)this)
break;
if (nIndex == (int)pblock->vtx.size())
{
vMerkleBranch.clear();
nIndex = -1;
printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
return 0;
}
// Fill in merkle branch
vMerkleBranch = pblock->GetMerkleBranch(nIndex);
}
// Is the tx in a block that's in the main chain
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return pindexBest->nHeight - pindex->nHeight + 1;
}
bool CTransaction::CheckTransaction() const
{
// Basic checks that don't depend on any context
if (vin.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
if (vout.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
// Size limits
if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
// Check for negative or overflow output values
int64 nValueOut = 0;
for (unsigned int i = 0; i < vout.size(); i++)
{
const CTxOut& txout = vout[i];
if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
// ppcoin: enforce minimum output amount
if ((!txout.IsEmpty()) && txout.nValue < MIN_TXOUT_AMOUNT)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue below minimum"));
if (txout.nValue > MAX_MONEY)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
nValueOut += txout.nValue;
if (!MoneyRange(nValueOut))
return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
}
// Check for duplicate inputs
set<COutPoint> vInOutPoints;
BOOST_FOREACH(const CTxIn& txin, vin)
{
if (vInOutPoints.count(txin.prevout))
return false;
vInOutPoints.insert(txin.prevout);
}
if (IsCoinBase())
{
if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
}
else
{
BOOST_FOREACH(const CTxIn& txin, vin)
if (txin.prevout.IsNull())
return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
}
return true;
}
int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
enum GetMinFee_mode mode, unsigned int nBytes) const
{
// Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
unsigned int nNewBlockSize = nBlockSize + nBytes;
int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
// To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
if (nMinFee < nBaseFee)
{
BOOST_FOREACH(const CTxOut& txout, vout)
if (txout.nValue < CENT)
nMinFee = nBaseFee;
}
// Raise the price as the block approaches full
if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
{
if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
return MAX_MONEY;
nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
}
if (!MoneyRange(nMinFee))
nMinFee = MAX_MONEY;
return nMinFee;
}
bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
bool* pfMissingInputs)
{
if (pfMissingInputs)
*pfMissingInputs = false;
if (!tx.CheckTransaction())
return error("CTxMemPool::accept() : CheckTransaction failed");
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
// ppcoin: coinstake is also only valid in a block, not as a loose transaction
if (tx.IsCoinStake())
return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
// To help v0.1.5 clients who would see it as a negative number
if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
// Rather not work on nonstandard transactions (unless -testnet)
if (!fTestNet && !tx.IsStandard())
return error("CTxMemPool::accept() : nonstandard transaction type");
// Do we already have it?
uint256 hash = tx.GetHash();
{
LOCK(cs);
if (mapTx.count(hash))
return false;
}
if (fCheckInputs)
if (txdb.ContainsTx(hash))
return false;
// Check for conflicts with in-memory transactions
CTransaction* ptxOld = NULL;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (mapNextTx.count(outpoint))
{
// Disable replacement feature for now
return false;
// Allow replacing with a newer version of the same transaction
if (i != 0)
return false;
ptxOld = mapNextTx[outpoint].ptx;
if (ptxOld->IsFinal())
return false;
if (!tx.IsNewerThan(*ptxOld))
return false;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
return false;
}
break;
}
}
if (fCheckInputs)
{
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
if (fInvalid)
return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
if (pfMissingInputs)
*pfMissingInputs = true;
return false;
}
// Check for non-standard pay-to-script-hash in inputs
if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
return error("CTxMemPool::accept() : nonstandard transaction input");
// Note: if you modify this code to accept non-standard transactions, then
// you should add code here to check that the transaction does a
// reasonable number of ECDSA signature verifications.
int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
// Don't accept it if it can't get into a block
int64 txMinFee = tx.GetMinFee(1000, false, GMF_RELAY, nSize);
if (nFees < txMinFee)
return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
hash.ToString().c_str(),
nFees, txMinFee);
// Continuously rate-limit free transactions
// This mitigates 'penny-flooding' -- sending thousands of free transactions just to
// be annoying or make others' transactions take longer to confirm.
if (nFees < MIN_RELAY_TX_FEE)
{
static CCriticalSection cs;
static double dFreeCount;
static int64 nLastTime;
int64 nNow = GetTime();
{
LOCK(cs);
// Use an exponentially decaying ~10-minute window:
dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
nLastTime = nNow;
// -limitfreerelay unit is thousand-bytes-per-minute
// At default rate it would take over a month to fill 1GB
if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
if (fDebug)
printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
dFreeCount += nSize;
}
}
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
{
return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
}
}
// Store transaction in memory
{
LOCK(cs);
if (ptxOld)
{
printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
remove(*ptxOld);
}
addUnchecked(hash, tx);
}
///// are we sure this is ok when loading transactions or restoring block txes
// If updated, erase old tx from wallet
if (ptxOld)
EraseFromWallets(ptxOld->GetHash());
printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
hash.ToString().substr(0,10).c_str(),
mapTx.size());
return true;
}
bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
{
return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
}
bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
{
// Add to memory pool without checking anything. Don't call this directly,
// call CTxMemPool::accept to properly check the transaction first.
{
mapTx[hash] = tx;
for (unsigned int i = 0; i < tx.vin.size(); i++)
mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
nTransactionsUpdated++;
}
return true;
}
bool CTxMemPool::remove(CTransaction &tx)
{
// Remove transaction from memory pool
{
LOCK(cs);
uint256 hash = tx.GetHash();
if (mapTx.count(hash))
{
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapNextTx.erase(txin.prevout);
mapTx.erase(hash);
nTransactionsUpdated++;
}
}
return true;
}
void CTxMemPool::clear()
{
LOCK(cs);
mapTx.clear();
mapNextTx.clear();
++nTransactionsUpdated;
}
void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
{
vtxid.clear();
LOCK(cs);
vtxid.reserve(mapTx.size());
for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
vtxid.push_back((*mi).first);
}
int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
{
if (hashBlock == 0 || nIndex == -1)
return 0;
// Find the block it claims to be in
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
// Make sure the merkle branch connects to this block
if (!fMerkleVerified)
{
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
return 0;
fMerkleVerified = true;
}
pindexRet = pindex;
return pindexBest->nHeight - pindex->nHeight + 1;
}
int CMerkleTx::GetBlocksToMaturity() const
{
if (!(IsCoinBase() || IsCoinStake()))
return 0;
return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
}
bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
{
if (fClient)
{
if (!IsInMainChain() && !ClientConnectInputs())
return false;
return CTransaction::AcceptToMemoryPool(txdb, false);
}
else
{
return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
}
}
bool CMerkleTx::AcceptToMemoryPool()
{
CTxDB txdb("r");
return AcceptToMemoryPool(txdb);
}
bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
{
{
LOCK(mempool.cs);
// Add previous supporting transactions first
BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
{
if (!(tx.IsCoinBase() || tx.IsCoinStake()))
{
uint256 hash = tx.GetHash();
if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
tx.AcceptToMemoryPool(txdb, fCheckInputs);
}
}
return AcceptToMemoryPool(txdb, fCheckInputs);
}
return false;
}
bool CWalletTx::AcceptWalletTransaction()
{
CTxDB txdb("r");
return AcceptWalletTransaction(txdb);
}
int CTxIndex::GetDepthInMainChain() const
{
// Read block header
CBlock block;
if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
return 0;
// Find the block in the index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return 1 + nBestHeight - pindex->nHeight;
}
// Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
{
{
LOCK(cs_main);
{
LOCK(mempool.cs);
if (mempool.exists(hash))
{
tx = mempool.lookup(hash);
return true;
}
}
CTxDB txdb("r");
CTxIndex txindex;
if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
{
CBlock block;
if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
hashBlock = block.GetHash();
return true;
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
//
// CBlock and CBlockIndex
//
static CBlockIndex* pblockindexFBBHLast;
CBlockIndex* FindBlockByHeight(int nHeight)
{
CBlockIndex *pblockindex;
if (nHeight < nBestHeight / 2)
pblockindex = pindexGenesisBlock;
else
pblockindex = pindexBest;
if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
pblockindex = pblockindexFBBHLast;
while (pblockindex->nHeight > nHeight)
pblockindex = pblockindex->pprev;
while (pblockindex->nHeight < nHeight)
pblockindex = pblockindex->pnext;
pblockindexFBBHLast = pblockindex;
return pblockindex;
}
bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
{
if (!fReadTransactions)
{
*this = pindex->GetBlockHeader();
return true;
}
if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
return false;
if (GetHash() != pindex->GetBlockHash())
return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
return true;
}
uint256 static GetOrphanRoot(const CBlock* pblock)
{
// Work back to the first block in the orphan chain
while (mapOrphanBlocks.count(pblock->hashPrevBlock))
pblock = mapOrphanBlocks[pblock->hashPrevBlock];
return pblock->GetHash();
}
// ppcoin: find block wanted by given orphan block
uint256 WantedByOrphan(const CBlock* pblockOrphan)
{
// Work back to the first block in the orphan chain
while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
return pblockOrphan->hashPrevBlock;
}
int generateMTRandom(unsigned int s, int range)
{
random::mt19937 gen(s);
random::uniform_int_distribution<> dist(0, range);
return dist(gen);
}
static const int64 nMinSubsidy = 1 * COIN;
static const int CUTOFF_HEIGHT = 100800; // Height at the end of 5 weeks
// miner's coin base reward based on nBits
int64 GetProofOfWorkReward(int nHeight, int64 nFees, uint256 prevHash)
{
int64 nSubsidy = 100000 * COIN;
if(nHeight == 1)
{
nSubsidy = TAX_PERCENTAGE * CIRCULATION_MONEY;
return nSubsidy + nFees;
}
else if(nHeight > CUTOFF_HEIGHT)
{
return nMinSubsidy + nFees;
}
std::string cseed_str = prevHash.ToString().substr(14,7);
const char* cseed = cseed_str.c_str();
long seed = hex2long(cseed);
nSubsidy += generateMTRandom(seed, 800000) * COIN;
// Subsidy is cut in half every week or 20160 blocks, which will occur approximately every month
nSubsidy >>= (nHeight / 20160);
return nSubsidy + nFees;
}
// miner's coin stake reward based on nBits and coin age spent (coin-days)
// simple algorithm, not depend on the diff
const int YEARLY_BLOCKCOUNT = 1051200; // 365 * 2880
int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, int nHeight)
{
int64 nRewardCoinYear;
nRewardCoinYear = MAX_MINT_PROOF_OF_STAKE;
if(nHeight < YEARLY_BLOCKCOUNT)
nRewardCoinYear = 4 * MAX_MINT_PROOF_OF_STAKE;
else if(nHeight < (2 * YEARLY_BLOCKCOUNT))
nRewardCoinYear = 3 * MAX_MINT_PROOF_OF_STAKE;
else if(nHeight < (3 * YEARLY_BLOCKCOUNT))
nRewardCoinYear = 2 * MAX_MINT_PROOF_OF_STAKE;
int64 nSubsidy = nCoinAge * nRewardCoinYear / 365;
if (fDebug && GetBoolArg("-printcreation"))
printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d" nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
return nSubsidy;
}
static const int64 nTargetTimespan = 30 * 30;
static const int64 nTargetSpacingWorkMax = 3 * nStakeTargetSpacing;
//
// maximum nBits value could possible be required nTime after
// minimum proof-of-work required was nBase
//
unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64 nTime)
{
CBigNum bnResult;
bnResult.SetCompact(nBase);
bnResult *= 2;
while (nTime > 0 && bnResult < bnTargetLimit)
{
// Maximum 200% adjustment per day...
bnResult *= 2;
nTime -= 24 * 60 * 60;
}
if (bnResult > bnTargetLimit)
bnResult = bnTargetLimit;
return bnResult.GetCompact();
}
//
// minimum amount of work that could possibly be required nTime after
// minimum proof-of-work required was nBase
//
unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
{
return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
}
//
// minimum amount of stake that could possibly be required nTime after
// minimum proof-of-stake required was nBase
//
unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime)
{
return ComputeMaxBits(bnProofOfStakeLimit, nBase, nTime);
}
// ppcoin: find last block index up to pindex
const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
{
while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
pindex = pindex->pprev;
return pindex;
}
unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
{
CBigNum bnTargetLimit = bnProofOfWorkLimit;
if(fProofOfStake)
{
// Proof-of-Stake blocks has own target limit since nVersion=3 supermajority on mainNet and always on testNet
bnTargetLimit = bnProofOfStakeLimit;
}
if (pindexLast == NULL)
return bnTargetLimit.GetCompact(); // genesis block
const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
if (pindexPrev->pprev == NULL)
return bnTargetLimit.GetCompact(); // first block
const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
if (pindexPrevPrev->pprev == NULL)
return bnTargetLimit.GetCompact(); // second block
int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
if(nActualSpacing < 0)
{
// printf(">> nActualSpacing = %"PRI64d" corrected to 1.\n", nActualSpacing);
nActualSpacing = 1;
}
else if(nActualSpacing > nTargetTimespan)
{
// printf(">> nActualSpacing = %"PRI64d" corrected to nTargetTimespan (900).\n", nActualSpacing);
nActualSpacing = nTargetTimespan;
}
// ppcoin: target change every block
// ppcoin: retarget with exponential moving toward target spacing
CBigNum bnNew;
bnNew.SetCompact(pindexPrev->nBits);
int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(nTargetSpacingWorkMax, (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
int64 nInterval = nTargetTimespan / nTargetSpacing;
bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
bnNew /= ((nInterval + 1) * nTargetSpacing);
/*
printf(">> Height = %d, fProofOfStake = %d, nInterval = %"PRI64d", nTargetSpacing = %"PRI64d", nActualSpacing = %"PRI64d"\n",
pindexPrev->nHeight, fProofOfStake, nInterval, nTargetSpacing, nActualSpacing);
printf(">> pindexPrev->GetBlockTime() = %"PRI64d", pindexPrev->nHeight = %d, pindexPrevPrev->GetBlockTime() = %"PRI64d", pindexPrevPrev->nHeight = %d\n",
pindexPrev->GetBlockTime(), pindexPrev->nHeight, pindexPrevPrev->GetBlockTime(), pindexPrevPrev->nHeight);
*/
if (bnNew > bnTargetLimit)
bnNew = bnTargetLimit;
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
// Check range
if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
return error("CheckProofOfWork() : nBits below minimum work");
// Check proof of work matches claimed amount
if (hash > bnTarget.getuint256())
return error("CheckProofOfWork() : hash doesn't match nBits");
return true;
}
// Return maximum amount of blocks that other nodes claim to have
int GetNumBlocksOfPeers()
{
return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
}
bool IsInitialBlockDownload()
{
if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
return true;
static int64 nLastUpdate;
static CBlockIndex* pindexLastBest;
if (pindexBest != pindexLastBest)
{
pindexLastBest = pindexBest;
nLastUpdate = GetTime();
}
return (GetTime() - nLastUpdate < 10 &&
pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
}
void static InvalidChainFound(CBlockIndex* pindexNew)
{
if (pindexNew->bnChainTrust > bnBestInvalidTrust)
{
bnBestInvalidTrust = pindexNew->bnChainTrust;
CTxDB().WriteBestInvalidTrust(bnBestInvalidTrust);
uiInterface.NotifyBlocksChanged();
}
printf("InvalidChainFound: invalid block=%s height=%d trust=%s date=%s\n",
pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
pindexNew->bnChainTrust.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S",
pindexNew->GetBlockTime()).c_str());
printf("InvalidChainFound: current best=%s height=%d trust=%s date=%s\n",
hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainTrust.ToString().c_str(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
}
void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
{
nTime = max(GetBlockTime(), GetAdjustedTime());
}
bool CTransaction::DisconnectInputs(CTxDB& txdb)
{
// Relinquish previous transactions' spent pointers
if (!IsCoinBase())
{
BOOST_FOREACH(const CTxIn& txin, vin)
{
COutPoint prevout = txin.prevout;
// Get prev txindex from disk
CTxIndex txindex;
if (!txdb.ReadTxIndex(prevout.hash, txindex))
return error("DisconnectInputs() : ReadTxIndex failed");
if (prevout.n >= txindex.vSpent.size())
return error("DisconnectInputs() : prevout.n out of range");
// Mark outpoint as not spent
txindex.vSpent[prevout.n].SetNull();
// Write back
if (!txdb.UpdateTxIndex(prevout.hash, txindex))
return error("DisconnectInputs() : UpdateTxIndex failed");
}
}
// Remove transaction from index
// This can fail if a duplicate of this transaction was in a chain that got
// reorganized away. This is only possible if this transaction was completely
// spent, so erasing it would be a no-op anyway.
txdb.EraseTxIndex(*this);
return true;
}
bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
{
// FetchInputs can return false either because we just haven't seen some inputs
// (in which case the transaction should be stored as an orphan)
// or because the transaction is malformed (in which case the transaction should
// be dropped). If tx is definitely invalid, fInvalid will be set to true.
fInvalid = false;
if (IsCoinBase())
return true; // Coinbase transactions have no inputs to fetch.
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
if (inputsRet.count(prevout.hash))
continue; // Got it already
// Read txindex
CTxIndex& txindex = inputsRet[prevout.hash].first;
bool fFound = true;
if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
{
// Get txindex from current proposed changes
txindex = mapTestPool.find(prevout.hash)->second;
}
else
{
// Read txindex from txdb
fFound = txdb.ReadTxIndex(prevout.hash, txindex);
}
if (!fFound && (fBlock || fMiner))
return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
// Read txPrev
CTransaction& txPrev = inputsRet[prevout.hash].second;
if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
{
// Get prev tx from single transactions in memory
{
LOCK(mempool.cs);
if (!mempool.exists(prevout.hash))
return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
txPrev = mempool.lookup(prevout.hash);
}
if (!fFound)
txindex.vSpent.resize(txPrev.vout.size());
}
else
{
// Get prev tx from disk
if (!txPrev.ReadFromDisk(txindex.pos))
return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
}
}
// Make sure all prevout.n indexes are valid:
for (unsigned int i = 0; i < vin.size(); i++)
{
const COutPoint prevout = vin[i].prevout;
assert(inputsRet.count(prevout.hash) != 0);
const CTxIndex& txindex = inputsRet[prevout.hash].first;
const CTransaction& txPrev = inputsRet[prevout.hash].second;
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
{
// Revisit this if/when transaction replacement is implemented and allows
// adding inputs:
fInvalid = true;
return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
}
}
return true;
}
const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
{
MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
if (mi == inputs.end())
throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
const CTransaction& txPrev = (mi->second).second;
if (input.prevout.n >= txPrev.vout.size())
throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
return txPrev.vout[input.prevout.n];
}
int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
{
if (IsCoinBase())
return 0;
int64 nResult = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
nResult += GetOutputFor(vin[i], inputs).nValue;
}
return nResult;
}
unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
{
if (IsCoinBase())
return 0;
unsigned int nSigOps = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
const CTxOut& prevout = GetOutputFor(vin[i], inputs);
if (prevout.scriptPubKey.IsPayToScriptHash())
nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
}
return nSigOps;
}
bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
{
// Take over previous transactions' spent pointers
// fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
// fMiner is true when called from the internal bitcoin miner
// ... both are false when called from CTransaction::AcceptToMemoryPool
if (!IsCoinBase())
{
int64 nValueIn = 0;
int64 nFees = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
assert(inputs.count(prevout.hash) > 0);
CTxIndex& txindex = inputs[prevout.hash].first;
CTransaction& txPrev = inputs[prevout.hash].second;
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
// If prev is coinbase or coinstake, check that it's matured
if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
// ppcoin: check transaction timestamp
if (txPrev.nTime > nTime)
return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
// Check for negative or overflow input values
nValueIn += txPrev.vout[prevout.n].nValue;
if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return DoS(100, error("ConnectInputs() : txin values out of range"));
}
// The first loop above does all the inexpensive checks.
// Only if ALL inputs pass do we perform expensive ECDSA signature checks.
// Helps prevent CPU exhaustion attacks.
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
assert(inputs.count(prevout.hash) > 0);
CTxIndex& txindex = inputs[prevout.hash].first;
CTransaction& txPrev = inputs[prevout.hash].second;
// Check for conflicts (double-spend)
// This doesn't trigger the DoS code on purpose; if it did, it would make it easier
// for an attacker to attempt to split the network.
if (!txindex.vSpent[prevout.n].IsNull())
return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
// Skip ECDSA signature verification when connecting blocks (fBlock=true)
// before the last blockchain checkpoint. This is safe because block merkle hashes are
// still computed and checked, and any change will be caught at the next checkpoint.
if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
{
// Verify signature
if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
{
// only during transition phase for P2SH: do not invoke anti-DoS code for
// potentially old clients relaying bad P2SH transactions
if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
}
}
// Mark outpoints as spent
txindex.vSpent[prevout.n] = posThisTx;
// Write back
if (fBlock || fMiner)
{
mapTestPool[prevout.hash] = txindex;
}
}
if (IsCoinStake())
{
// ppcoin: coin stake tx earns reward instead of paying fee
uint64 nCoinAge;
if (!GetCoinAge(txdb, nCoinAge))
return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
int64 nStakeReward = GetValueOut() - nValueIn;
if (nStakeReward > GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime, pindexBlock->nHeight) - GetMinFee() + MIN_TX_FEE)
return DoS(100, error("ConnectInputs() : %s stake reward exceeded", GetHash().ToString().substr(0,10).c_str()));
}
else
{
if (nValueIn < GetValueOut())
return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
// Tally transaction fees
int64 nTxFee = nValueIn - GetValueOut();
if (nTxFee < 0)
return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
// ppcoin: enforce transaction fees for every block
if (nTxFee < GetMinFee())
return fBlock? DoS(100, error("ConnectInputs() : %s not paying required fee=%s, paid=%s", GetHash().ToString().substr(0,10).c_str(), FormatMoney(GetMinFee()).c_str(), FormatMoney(nTxFee).c_str())) : false;
nFees += nTxFee;
if (!MoneyRange(nFees))
return DoS(100, error("ConnectInputs() : nFees out of range"));
}
}
return true;
}
bool CTransaction::ClientConnectInputs()
{
if (IsCoinBase())
return false;
// Take over previous transactions' spent pointers
{
LOCK(mempool.cs);
int64 nValueIn = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
// Get prev tx from single transactions in memory
COutPoint prevout = vin[i].prevout;
if (!mempool.exists(prevout.hash))
return false;
CTransaction& txPrev = mempool.lookup(prevout.hash);
if (prevout.n >= txPrev.vout.size())
return false;
// Verify signature
if (!VerifySignature(txPrev, *this, i, true, 0))
return error("ConnectInputs() : VerifySignature failed");
///// this is redundant with the mempool.mapNextTx stuff,
///// not sure which I want to get rid of
///// this has to go away now that posNext is gone
// // Check for conflicts
// if (!txPrev.vout[prevout.n].posNext.IsNull())
// return error("ConnectInputs() : prev tx already used");
//
// // Flag outpoints as used
// txPrev.vout[prevout.n].posNext = posThisTx;
nValueIn += txPrev.vout[prevout.n].nValue;
if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return error("ClientConnectInputs() : txin values out of range");
}
if (GetValueOut() > nValueIn)
return false;
}
return true;
}
bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
{
// Disconnect in reverse order
for (int i = vtx.size()-1; i >= 0; i--)
if (!vtx[i].DisconnectInputs(txdb))
return false;
// Update block index on disk without changing it in memory.
// The memory index structure will be changed after the db commits.
if (pindex->pprev)
{
CDiskBlockIndex blockindexPrev(pindex->pprev);
blockindexPrev.hashNext = 0;
if (!txdb.WriteBlockIndex(blockindexPrev))
return error("DisconnectBlock() : WriteBlockIndex failed");
}
// ppcoin: clean up wallet after disconnecting coinstake
BOOST_FOREACH(CTransaction& tx, vtx)
SyncWithWallets(tx, this, false, false);
return true;
}
bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
{
// Check it again in case a previous version let a bad block in
if (!CheckBlock(!fJustCheck, !fJustCheck))
return false;
// Do not allow blocks that contain transactions which 'overwrite' older transactions,
// unless those are already completely spent.
// If such overwrites are allowed, coinbases and transactions depending upon those
// can be duplicated to remove the ability to spend the first instance -- even after
// being sent to another address.
// See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
// This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
// already refuses previously-known transaction ids entirely.
// This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
// Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
// two in the chain that violate it. This prevents exploiting the issue against nodes in their
// initial block download.
bool fEnforceBIP30 = true; // Always active in MintCoin
bool fStrictPayToScriptHash = true; // Always active in MintCoin
//// issue here: it doesn't know the version
unsigned int nTxPos;
if (fJustCheck)
// FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
// Since we're just checking the block and not actually connecting it, it might not (and probably shouldn't) be on the disk to get the transaction from
nTxPos = 1;
else
nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
map<uint256, CTxIndex> mapQueuedChanges;
int64 nFees = 0;
int64 nValueIn = 0;
int64 nValueOut = 0;
unsigned int nSigOps = 0;
BOOST_FOREACH(CTransaction& tx, vtx)
{
uint256 hashTx = tx.GetHash();
if (fEnforceBIP30) {
CTxIndex txindexOld;
if (txdb.ReadTxIndex(hashTx, txindexOld)) {
BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
if (pos.IsNull())
return false;
}
}
nSigOps += tx.GetLegacySigOpCount();
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
if (!fJustCheck)
nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
MapPrevTx mapInputs;
if (tx.IsCoinBase())
nValueOut += tx.GetValueOut();
else
{
bool fInvalid;
if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
return false;
if (fStrictPayToScriptHash)
{
// Add in sigops done by pay-to-script-hash inputs;
// this is to prevent a "rogue miner" from creating
// an incredibly-expensive-to-validate block.
nSigOps += tx.GetP2SHSigOpCount(mapInputs);
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
}
int64 nTxValueIn = tx.GetValueIn(mapInputs);
int64 nTxValueOut = tx.GetValueOut();
nValueIn += nTxValueIn;
nValueOut += nTxValueOut;
if (!tx.IsCoinStake())
nFees += nTxValueIn - nTxValueOut;
if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
return false;
}
mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
}
// ppcoin: track money supply and mint amount info
pindex->nMint = nValueOut - nValueIn + nFees;
pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
return error("Connect() : WriteBlockIndex for pindex failed");
// ppcoin: fees are not collected by miners as in bitcoin
// ppcoin: fees are destroyed to compensate the entire network
if (fDebug && GetBoolArg("-printcreation"))
printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
if (fJustCheck)
return true;
// Write queued txindex changes
for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
{
if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
return error("ConnectBlock() : UpdateTxIndex failed");
}
uint256 prevHash = 0;
if(pindex->pprev)
{
prevHash = pindex->pprev->GetBlockHash();
// printf("==> Got prevHash = %s\n", prevHash.ToString().c_str());
}
if (vtx[0].GetValueOut() > GetProofOfWorkReward(pindex->nHeight, nFees, prevHash))
return false;
// Update block index on disk without changing it in memory.
// The memory index structure will be changed after the db commits.
if (pindex->pprev)
{
CDiskBlockIndex blockindexPrev(pindex->pprev);
blockindexPrev.hashNext = pindex->GetBlockHash();
if (!txdb.WriteBlockIndex(blockindexPrev))
return error("ConnectBlock() : WriteBlockIndex failed");
}
// Watch for transactions paying to me
BOOST_FOREACH(CTransaction& tx, vtx)
SyncWithWallets(tx, this, true);
return true;
}
bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
{
printf("REORGANIZE\n");
// Find the fork
CBlockIndex* pfork = pindexBest;
CBlockIndex* plonger = pindexNew;
while (pfork != plonger)
{
while (plonger->nHeight > pfork->nHeight)
if (!(plonger = plonger->pprev))
return error("Reorganize() : plonger->pprev is null");
if (pfork == plonger)
break;
if (!(pfork = pfork->pprev))
return error("Reorganize() : pfork->pprev is null");
}
// List of what to disconnect
vector<CBlockIndex*> vDisconnect;
for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
vDisconnect.push_back(pindex);
// List of what to connect
vector<CBlockIndex*> vConnect;
for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
vConnect.push_back(pindex);
reverse(vConnect.begin(), vConnect.end());
printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
printf("REORGANIZE: Connect %"PRIszu" blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
// Disconnect shorter branch
vector<CTransaction> vResurrect;
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
{
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("Reorganize() : ReadFromDisk for disconnect failed");
if (!block.DisconnectBlock(txdb, pindex))
return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
// Queue memory transactions to resurrect
BOOST_FOREACH(const CTransaction& tx, block.vtx)
if (!(tx.IsCoinBase() || tx.IsCoinStake()))
vResurrect.push_back(tx);
}
// Connect longer branch
vector<CTransaction> vDelete;
for (unsigned int i = 0; i < vConnect.size(); i++)
{
CBlockIndex* pindex = vConnect[i];
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("Reorganize() : ReadFromDisk for connect failed");
if (!block.ConnectBlock(txdb, pindex))
{
// Invalid block
return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
}
// Queue memory transactions to delete
BOOST_FOREACH(const CTransaction& tx, block.vtx)
vDelete.push_back(tx);
}
if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
return error("Reorganize() : WriteHashBestChain failed");
// Make sure it's successfully written to disk before changing memory structure
if (!txdb.TxnCommit())
return error("Reorganize() : TxnCommit failed");
// Disconnect shorter branch
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
if (pindex->pprev)
pindex->pprev->pnext = NULL;
// Connect longer branch
BOOST_FOREACH(CBlockIndex* pindex, vConnect)
if (pindex->pprev)
pindex->pprev->pnext = pindex;
// Resurrect memory transactions that were in the disconnected branch
BOOST_FOREACH(CTransaction& tx, vResurrect)
tx.AcceptToMemoryPool(txdb, false);
// Delete redundant memory transactions that are in the connected branch
BOOST_FOREACH(CTransaction& tx, vDelete)
mempool.remove(tx);
printf("REORGANIZE: done\n");
return true;
}
// Called from inside SetBestChain: attaches a block to the new best chain being built
bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
{
uint256 hash = GetHash();
// Adding to current best branch
if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
{
txdb.TxnAbort();
InvalidChainFound(pindexNew);
return false;
}
if (!txdb.TxnCommit())
return error("SetBestChain() : TxnCommit failed");
// Add to current best branch
pindexNew->pprev->pnext = pindexNew;
// Delete redundant memory transactions
BOOST_FOREACH(CTransaction& tx, vtx)
mempool.remove(tx);
return true;
}
bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
{
uint256 hash = GetHash();
if (!txdb.TxnBegin())
return error("SetBestChain() : TxnBegin failed");
if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
{
txdb.WriteHashBestChain(hash);
if (!txdb.TxnCommit())
return error("SetBestChain() : TxnCommit failed");
pindexGenesisBlock = pindexNew;
}
else if (hashPrevBlock == hashBestChain)
{
if (!SetBestChainInner(txdb, pindexNew))
return error("SetBestChain() : SetBestChainInner failed");
}
else
{
// the first block in the new chain that will cause it to become the new best chain
CBlockIndex *pindexIntermediate = pindexNew;
// list of blocks that need to be connected afterwards
std::vector<CBlockIndex*> vpindexSecondary;
// Reorganize is costly in terms of db load, as it works in a single db transaction.
// Try to limit how much needs to be done inside
while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainTrust > pindexBest->bnChainTrust)
{
vpindexSecondary.push_back(pindexIntermediate);
pindexIntermediate = pindexIntermediate->pprev;
}
if (!vpindexSecondary.empty())
printf("Postponing %"PRIszu" reconnects\n", vpindexSecondary.size());
// Switch to new best branch
if (!Reorganize(txdb, pindexIntermediate))
{
txdb.TxnAbort();
InvalidChainFound(pindexNew);
return error("SetBestChain() : Reorganize failed");
}
// Connect further blocks
BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
{
CBlock block;
if (!block.ReadFromDisk(pindex))
{
printf("SetBestChain() : ReadFromDisk failed\n");
break;
}
if (!txdb.TxnBegin()) {
printf("SetBestChain() : TxnBegin 2 failed\n");
break;
}
// errors now are not fatal, we still did a reorganisation to a new chain in a valid way
if (!block.SetBestChainInner(txdb, pindex))
break;
}
}
// Update best block in wallet (so we can detect restored wallets)
bool fIsInitialDownload = IsInitialBlockDownload();
if (!fIsInitialDownload)
{
const CBlockLocator locator(pindexNew);
::SetBestChain(locator);
}
// New best block
hashBestChain = hash;
pindexBest = pindexNew;
pblockindexFBBHLast = NULL;
nBestHeight = pindexBest->nHeight;
bnBestChainTrust = pindexNew->bnChainTrust;
nTimeBestReceived = GetTime();
nTransactionsUpdated++;
printf("SetBestChain: new best=%s height=%d trust=%s date=%s\n",
hashBestChain.ToString().c_str(), nBestHeight, bnBestChainTrust.ToString().c_str(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
printf("Stake checkpoint: %x\n", pindexBest->nStakeModifierChecksum);
// Check the version of the last 100 blocks to see if we need to upgrade:
if (!fIsInitialDownload)
{
int nUpgraded = 0;
const CBlockIndex* pindex = pindexBest;
for (int i = 0; i < 100 && pindex != NULL; i++)
{
if (pindex->nVersion > CBlock::CURRENT_VERSION)
++nUpgraded;
pindex = pindex->pprev;
}
if (nUpgraded > 0)
printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
if (nUpgraded > 100/2)
// strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
}
std::string strCmd = GetArg("-blocknotify", "");
if (!fIsInitialDownload && !strCmd.empty())
{
boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
return true;
}
// ppcoin: total coin age spent in transaction, in the unit of coin-days.
// Only those coins meeting minimum age requirement counts. As those
// transactions not in main chain are not currently indexed so we
// might not find out about their coin age. Older transactions are
// guaranteed to be in main chain by sync-checkpoint. This rule is
// introduced to help nodes establish a consistent view of the coin
// age (trust score) of competing branches.
bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
{
CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
nCoinAge = 0;
if (IsCoinBase())
return true;
BOOST_FOREACH(const CTxIn& txin, vin)
{
// First try finding the previous transaction in database
CTransaction txPrev;
CTxIndex txindex;
if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
continue; // previous transaction not in main chain
if (nTime < txPrev.nTime)
return false; // Transaction timestamp violation
// Read block header
CBlock block;
if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
return false; // unable to read block of previous transaction
if (block.GetBlockTime() + nStakeMinAge > nTime)
continue; // only count coins meeting min age requirement
int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
if (fDebug && GetBoolArg("-printcoinage"))
printf("coin age nValueIn=%"PRI64d" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
}
CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
if (fDebug && GetBoolArg("-printcoinage"))
printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
nCoinAge = bnCoinDay.getuint64();
return true;
}
// ppcoin: total coin age spent in block, in the unit of coin-days.
bool CBlock::GetCoinAge(uint64& nCoinAge) const
{
nCoinAge = 0;
CTxDB txdb("r");
BOOST_FOREACH(const CTransaction& tx, vtx)
{
uint64 nTxCoinAge;
if (tx.GetCoinAge(txdb, nTxCoinAge))
nCoinAge += nTxCoinAge;
else
return false;
}
if (nCoinAge == 0) // block coin age minimum 1 coin-day
nCoinAge = 1;
if (fDebug && GetBoolArg("-printcoinage"))
printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
return true;
}
bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
{
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
// Construct new block index object
CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
if (!pindexNew)
return error("AddToBlockIndex() : new CBlockIndex failed");
pindexNew->phashBlock = &hash;
map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
if (miPrev != mapBlockIndex.end())
{
pindexNew->pprev = (*miPrev).second;
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
}
// ppcoin: compute chain trust score
pindexNew->bnChainTrust = (pindexNew->pprev ? pindexNew->pprev->bnChainTrust : 0) + pindexNew->GetBlockTrust();
// ppcoin: compute stake entropy bit for stake modifier
if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nHeight)))
return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
// ppcoin: record proof-of-stake hash value
if (pindexNew->IsProofOfStake())
{
if (!mapProofOfStake.count(hash))
return error("AddToBlockIndex() : hashProofOfStake not found in map");
pindexNew->hashProofOfStake = mapProofOfStake[hash];
}
// ppcoin: compute stake modifier
uint64 nStakeModifier = 0;
bool fGeneratedStakeModifier = false;
if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
// Add to mapBlockIndex
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
if (pindexNew->IsProofOfStake())
setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
pindexNew->phashBlock = &((*mi).first);
// Write to disk block index
CTxDB txdb;
if (!txdb.TxnBegin())
return false;
txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
if (!txdb.TxnCommit())
return false;
// New best
if (pindexNew->bnChainTrust > bnBestChainTrust)
if (!SetBestChain(txdb, pindexNew))
return false;
txdb.Close();
if (pindexNew == pindexBest)
{
// Notify UI to display prev block's coinbase if it was ours
static uint256 hashPrevBestCoinBase;
UpdatedTransaction(hashPrevBestCoinBase);
hashPrevBestCoinBase = vtx[0].GetHash();
}
uiInterface.NotifyBlocksChanged();
return true;
}
bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot) const
{
// These are checks that are independent of context
// that can be verified before saving an orphan block.
// Size limits
if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CheckBlock() : size limits failed"));
// Check proof of work matches claimed amount
if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
return DoS(50, error("CheckBlock() : proof of work failed"));
// Check timestamp
if (GetBlockTime() > GetAdjustedTime() + nMaxClockDrift)
return error("CheckBlock() : block timestamp too far in the future");
// First transaction must be coinbase, the rest must not be
if (vtx.empty() || !vtx[0].IsCoinBase())
return DoS(100, error("CheckBlock() : first tx is not coinbase"));
for (unsigned int i = 1; i < vtx.size(); i++)
if (vtx[i].IsCoinBase())
return DoS(100, error("CheckBlock() : more than one coinbase"));
// ppcoin: only the second transaction can be the optional coinstake
for (unsigned int i = 2; i < vtx.size(); i++)
if (vtx[i].IsCoinStake())
return DoS(100, error("CheckBlock() : coinstake in wrong position"));
// ppcoin: coinbase output should be empty if proof-of-stake block
if (IsProofOfStake() && (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty()))
return error("CheckBlock() : coinbase output not empty for proof-of-stake block");
// Check coinbase timestamp
if (GetBlockTime() > (int64)vtx[0].nTime + nMaxClockDrift)
return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
// Check coinstake timestamp
if (IsProofOfStake() && !CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
// Check transactions
BOOST_FOREACH(const CTransaction& tx, vtx)
{
if (!tx.CheckTransaction())
return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
// ppcoin: check transaction timestamp
if (GetBlockTime() < (int64)tx.nTime)
return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
}
// Check for duplicate txids. This is caught by ConnectInputs(),
// but catching it earlier avoids a potential DoS attack:
set<uint256> uniqueTx;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
uniqueTx.insert(tx.GetHash());
}
if (uniqueTx.size() != vtx.size())
return DoS(100, error("CheckBlock() : duplicate transaction"));
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
nSigOps += tx.GetLegacySigOpCount();
}
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
// Check merkle root
if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
// ppcoin: check block signature
if (!CheckBlockSignature())
return DoS(100, error("CheckBlock() : bad block signature"));
return true;
}
bool CBlock::AcceptBlock()
{
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AcceptBlock() : block already in mapBlockIndex");
// Get prev block index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
if (mi == mapBlockIndex.end())
return DoS(10, error("AcceptBlock() : prev block not found"));
CBlockIndex* pindexPrev = (*mi).second;
int nHeight = pindexPrev->nHeight+1;
if (IsProofOfWork() && nHeight > CUTOFF_POW_BLOCK)
return DoS(100, error("AcceptBlock() : No proof-of-work allowed anymore (height = %d)", nHeight));
// Check proof-of-work or proof-of-stake
if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
// Check timestamp against prev
if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + nMaxClockDrift < pindexPrev->GetBlockTime())
return error("AcceptBlock() : block's timestamp is too early");
// Check that all transactions are finalized
BOOST_FOREACH(const CTransaction& tx, vtx)
if (!tx.IsFinal(nHeight, GetBlockTime()))
return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
// Check that the block chain matches the known block chain up to a checkpoint
if (!Checkpoints::CheckHardened(nHeight, hash))
return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
// ppcoin: check that the block satisfies synchronized checkpoint
if (!Checkpoints::CheckSync(hash, pindexPrev))
{
if(!GetBoolArg("-nosynccheckpoints", false))
{
return error("AcceptBlock() : rejected by synchronized checkpoint");
}
else
{
strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
}
}
// Reject block.nVersion < 3 blocks since 95% threshold on mainNet and always on testNet:
if (nVersion < 3 && ((!fTestNet && nHeight > 14060) || (fTestNet && nHeight > 0)))
return error("CheckBlock() : rejected nVersion < 3 block");
// Enforce rule that the coinbase starts with serialized block height
CScript expect = CScript() << nHeight;
if (!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
// Write block to history file
if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
return error("AcceptBlock() : out of disk space");
unsigned int nFile = -1;
unsigned int nBlockPos = 0;
if (!WriteToDisk(nFile, nBlockPos))
return error("AcceptBlock() : WriteToDisk failed");
if (!AddToBlockIndex(nFile, nBlockPos))
return error("AcceptBlock() : AddToBlockIndex failed");
// Relay inventory, but don't relay old inventory during initial block download
int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
if (hashBestChain == hash)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
pnode->PushInventory(CInv(MSG_BLOCK, hash));
}
// ppcoin: check pending sync-checkpoint
Checkpoints::AcceptPendingSyncCheckpoint();
return true;
}
CBigNum CBlockIndex::GetBlockTrust() const
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
if (bnTarget <= 0)
return 0;
if (IsProofOfStake())
{
// Return trust score as usual
return (CBigNum(1)<<256) / (bnTarget+1);
}
else
{
// Calculate work amount for block
CBigNum bnPoWTrust = (bnProofOfWorkLimit / (bnTarget+1));
return bnPoWTrust > 1 ? bnPoWTrust : 1;
}
}
bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
{
unsigned int nFound = 0;
for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
{
if (pstart->nVersion >= minVersion)
++nFound;
pstart = pstart->pprev;
}
return (nFound >= nRequired);
}
bool ProcessBlock(CNode* pfrom, CBlock* pblock)
{
// Check for duplicate
uint256 hash = pblock->GetHash();
if (mapBlockIndex.count(hash))
return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
if (mapOrphanBlocks.count(hash))
return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
// ppcoin: check proof-of-stake
// Limited duplicity on stake: prevents block flood attack
// Duplicate stake allowed only when there is orphan child block
if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str());
// Preliminary checks
if (!pblock->CheckBlock())
return error("ProcessBlock() : CheckBlock FAILED");
// ppcoin: verify hash target and signature of coinstake tx
if (pblock->IsProofOfStake())
{
uint256 hashProofOfStake = 0;
if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake))
{
printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
return false; // do not error here as we expect this during initial block download
}
if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
}
CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
{
// Extra checks to prevent "fill up memory by spamming with bogus blocks"
int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
CBigNum bnNewBlock;
bnNewBlock.SetCompact(pblock->nBits);
CBigNum bnRequired;
if (pblock->IsProofOfStake())
bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
else
bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
if (bnNewBlock > bnRequired)
{
if (pfrom)
pfrom->Misbehaving(100);
return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
}
}
// ppcoin: ask for pending sync-checkpoint if any
if (!IsInitialBlockDownload())
Checkpoints::AskForPendingSyncCheckpoint(pfrom);
// If don't already have its previous block, shunt it off to holding area until we get it
if (!mapBlockIndex.count(pblock->hashPrevBlock))
{
printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
CBlock* pblock2 = new CBlock(*pblock);
// ppcoin: check proof-of-stake
if (pblock2->IsProofOfStake())
{
// Limited duplicity on stake: prevents block flood attack
// Duplicate stake allowed only when there is orphan child block
if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for orphan block %s", pblock2->GetProofOfStake().first.ToString().c_str(), pblock2->GetProofOfStake().second, hash.ToString().c_str());
else
setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
}
mapOrphanBlocks.insert(make_pair(hash, pblock2));
mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
// Ask this guy to fill in what we're missing
if (pfrom)
{
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
// ppcoin: getblocks may not obtain the ancestor block rejected
// earlier by duplicate-stake check so we ask for it again directly
if (!IsInitialBlockDownload())
pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
}
return true;
}
// Store to disk
if (!pblock->AcceptBlock())
return error("ProcessBlock() : AcceptBlock FAILED");
// Recursively process any orphan blocks that depended on this one
vector<uint256> vWorkQueue;
vWorkQueue.push_back(hash);
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
++mi)
{
CBlock* pblockOrphan = (*mi).second;
if (pblockOrphan->AcceptBlock())
vWorkQueue.push_back(pblockOrphan->GetHash());
mapOrphanBlocks.erase(pblockOrphan->GetHash());
setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
delete pblockOrphan;
}
mapOrphanBlocksByPrev.erase(hashPrev);
}
printf("ProcessBlock: ACCEPTED\n");
// ppcoin: if responsible for sync-checkpoint send it
if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
return true;
}
// ppcoin: sign block
bool CBlock::SignBlock(const CKeyStore& keystore)
{
vector<valtype> vSolutions;
txnouttype whichType;
if(!IsProofOfStake())
{
for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
{
const CTxOut& txout = vtx[0].vout[i];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
continue;
if (whichType == TX_PUBKEY)
{
// Sign
valtype& vchPubKey = vSolutions[0];
CKey key;
if (!keystore.GetKey(Hash160(vchPubKey), key))
continue;
if (key.GetPubKey() != vchPubKey)
continue;
if(!key.Sign(GetHash(), vchBlockSig))
continue;
return true;
}
}
}
else
{
const CTxOut& txout = vtx[1].vout[1];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY)
{
// Sign
valtype& vchPubKey = vSolutions[0];
CKey key;
if (!keystore.GetKey(Hash160(vchPubKey), key))
return false;
if (key.GetPubKey() != vchPubKey)
return false;
return key.Sign(GetHash(), vchBlockSig);
}
}
printf("Sign failed\n");
return false;
}
// ppcoin: check block signature
bool CBlock::CheckBlockSignature() const
{
if (GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
return vchBlockSig.empty();
vector<valtype> vSolutions;
txnouttype whichType;
if(IsProofOfStake())
{
const CTxOut& txout = vtx[1].vout[1];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY)
{
valtype& vchPubKey = vSolutions[0];
CKey key;
if (!key.SetPubKey(vchPubKey))
return false;
if (vchBlockSig.empty())
return false;
return key.Verify(GetHash(), vchBlockSig);
}
}
else
{
for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
{
const CTxOut& txout = vtx[0].vout[i];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY)
{
// Verify
valtype& vchPubKey = vSolutions[0];
CKey key;
if (!key.SetPubKey(vchPubKey))
continue;
if (vchBlockSig.empty())
continue;
if(!key.Verify(GetHash(), vchBlockSig))
continue;
return true;
}
}
}
return false;
}
bool CheckDiskSpace(uint64 nAdditionalBytes)
{
uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
// Check for nMinDiskSpace bytes (currently 50MB)
if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
{
fShutdown = true;
string strMessage = _("Warning: Disk space is low!");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage, "MintCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
StartShutdown();
return false;
}
return true;
}
static filesystem::path BlockFilePath(unsigned int nFile)
{
string strBlockFn = strprintf("blk%04u.dat", nFile);
return GetDataDir() / strBlockFn;
}
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
{
if ((nFile < 1) || (nFile == (unsigned int) -1))
return NULL;
FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
if (!file)
return NULL;
if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
{
if (fseek(file, nBlockPos, SEEK_SET) != 0)
{
fclose(file);
return NULL;
}
}
return file;
}
static unsigned int nCurrentBlockFile = 1;
FILE* AppendBlockFile(unsigned int& nFileRet)
{
nFileRet = 0;
loop
{
FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
if (!file)
return NULL;
if (fseek(file, 0, SEEK_END) != 0)
return NULL;
// FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
{
nFileRet = nCurrentBlockFile;
return file;
}
fclose(file);
nCurrentBlockFile++;
}
}
bool LoadBlockIndex(bool fAllowNew)
{
if (fTestNet)
{
pchMessageStart[0] = 0xcd;
pchMessageStart[1] = 0xf2;
pchMessageStart[2] = 0xc0;
pchMessageStart[3] = 0xef;
bnProofOfStakeLimit = bnProofOfStakeLimitTestNet; // 0x00000fff PoS base target is fixed in testnet
bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 0x0000ffff PoW base target is fixed in testnet
nStakeMinAge = 20 * 60; // test net min age is 20 min
nStakeMaxAge = 60 * 60; // test net min age is 60 min
nModifierInterval = 60; // test modifier interval is 2 minutes
nCoinbaseMaturity = 10; // test maturity is 10 blocks
nStakeTargetSpacing = 3 * 60; // test block spacing is 3 minutes
}
//
// Load block index
//
CTxDB txdb("cr");
if (!txdb.LoadBlockIndex())
return false;
txdb.Close();
//
// Init with genesis block
//
if (mapBlockIndex.empty())
{
if (!fAllowNew)
return false;
// Genesis block
const char* pszTimestamp = "Feb 2, 2014: The Denver Broncos finally got on the board with a touchdown in the final seconds of the third quarter. But the Seattle Seahawks are dominating the Broncos 36-8";
CTransaction txNew;
txNew.nTime = nChainStartTime;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].SetEmpty();
CBlock block;
block.vtx.push_back(txNew);
block.hashPrevBlock = 0;
block.hashMerkleRoot = block.BuildMerkleTree();
block.nVersion = 1;
block.nTime = 1391393693;
block.nBits = bnProofOfWorkLimit.GetCompact();
block.nNonce = 12488421;
//// debug print
block.print();
printf("block.GetHash() == %s\n", block.GetHash().ToString().c_str());
printf("block.hashMerkleRoot == %s\n", block.hashMerkleRoot.ToString().c_str());
printf("block.nTime = %u \n", block.nTime);
printf("block.nNonce = %u \n", block.nNonce);
assert(block.hashMerkleRoot == uint256("cf174ca43b1b30e9a27f7fdc20ff9caf626499d023f1f033198fdbadf73ca747"));
assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
// Start new block file
unsigned int nFile;
unsigned int nBlockPos;
if (!block.WriteToDisk(nFile, nBlockPos))
return error("LoadBlockIndex() : writing genesis block to disk failed");
if (!block.AddToBlockIndex(nFile, nBlockPos))
return error("LoadBlockIndex() : genesis block not accepted");
// ppcoin: initialize synchronized checkpoint
if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
return error("LoadBlockIndex() : failed to init sync checkpoint");
}
// ppcoin: if checkpoint master key changed must reset sync-checkpoint
{
CTxDB txdb;
string strPubKey = "";
if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
{
// write checkpoint master key to db
txdb.TxnBegin();
if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
if (!txdb.TxnCommit())
return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
return error("LoadBlockIndex() : failed to reset sync-checkpoint");
}
txdb.Close();
}
return true;
}
void PrintBlockTree()
{
// pre-compute tree structure
map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
CBlockIndex* pindex = (*mi).second;
mapNext[pindex->pprev].push_back(pindex);
// test
//while (rand() % 3 == 0)
// mapNext[pindex->pprev].push_back(pindex);
}
vector<pair<int, CBlockIndex*> > vStack;
vStack.push_back(make_pair(0, pindexGenesisBlock));
int nPrevCol = 0;
while (!vStack.empty())
{
int nCol = vStack.back().first;
CBlockIndex* pindex = vStack.back().second;
vStack.pop_back();
// print split or gap
if (nCol > nPrevCol)
{
for (int i = 0; i < nCol-1; i++)
printf("| ");
printf("|\\\n");
}
else if (nCol < nPrevCol)
{
for (int i = 0; i < nCol; i++)
printf("| ");
printf("|\n");
}
nPrevCol = nCol;
// print columns
for (int i = 0; i < nCol; i++)
printf("| ");
// print item
CBlock block;
block.ReadFromDisk(pindex);
printf("%d (%u,%u) %s %08x %s mint %7s tx %"PRIszu"",
pindex->nHeight,
pindex->nFile,
pindex->nBlockPos,
block.GetHash().ToString().c_str(),
block.nBits,
DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
FormatMoney(pindex->nMint).c_str(),
block.vtx.size());
PrintWallets(block);
// put the main time-chain first
vector<CBlockIndex*>& vNext = mapNext[pindex];
for (unsigned int i = 0; i < vNext.size(); i++)
{
if (vNext[i]->pnext)
{
swap(vNext[0], vNext[i]);
break;
}
}
// iterate children
for (unsigned int i = 0; i < vNext.size(); i++)
vStack.push_back(make_pair(nCol+i, vNext[i]));
}
}
bool LoadExternalBlockFile(FILE* fileIn)
{
int64 nStart = GetTimeMillis();
int nLoaded = 0;
{
LOCK(cs_main);
try {
CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
unsigned int nPos = 0;
while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
{
unsigned char pchData[65536];
do {
fseek(blkdat, nPos, SEEK_SET);
int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
if (nRead <= 8)
{
nPos = (unsigned int)-1;
break;
}
void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
if (nFind)
{
if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
{
nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
break;
}
nPos += ((unsigned char*)nFind - pchData) + 1;
}
else
nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
} while(!fRequestShutdown);
if (nPos == (unsigned int)-1)
break;
fseek(blkdat, nPos, SEEK_SET);
unsigned int nSize;
blkdat >> nSize;
if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
{
CBlock block;
blkdat >> block;
if (ProcessBlock(NULL,&block))
{
nLoaded++;
nPos += 4 + nSize;
}
}
}
}
catch (std::exception &e) {
printf("%s() : Deserialize or I/O error caught during load\n",
__PRETTY_FUNCTION__);
}
}
printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
return nLoaded > 0;
}
//////////////////////////////////////////////////////////////////////////////
//
// CAlert
//
extern map<uint256, CAlert> mapAlerts;
extern CCriticalSection cs_mapAlerts;
string GetWarnings(string strFor)
{
int nPriority = 0;
string strStatusBar;
string strRPC;
if (GetBoolArg("-testsafemode"))
strRPC = "test";
// Misc warnings like out of disk space and clock is wrong
if (strMiscWarning != "")
{
nPriority = 1000;
strStatusBar = strMiscWarning;
}
// ppcoin: should not enter safe mode for longer invalid chain
// ppcoin: if sync-checkpoint is too old do not enter safe mode
if (Checkpoints::IsSyncCheckpointTooOld(60 * 60 * 24 * 365) && !fTestNet && !IsInitialBlockDownload())
{
nPriority = 100;
strStatusBar = "WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers.";
}
// ppcoin: if detected invalid checkpoint enter safe mode
if (Checkpoints::hashInvalidCheckpoint != 0)
{
nPriority = 3000;
strStatusBar = strRPC = "WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.";
}
// Alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
{
const CAlert& alert = item.second;
if (alert.AppliesToMe() && alert.nPriority > nPriority)
{
nPriority = alert.nPriority;
strStatusBar = alert.strStatusBar;
if (nPriority > 1000)
strRPC = strStatusBar; // ppcoin: safe mode for high alert
}
}
}
if (strFor == "statusbar")
return strStatusBar;
else if (strFor == "rpc")
return strRPC;
assert(!"GetWarnings() : invalid parameter");
return "error";
}
//////////////////////////////////////////////////////////////////////////////
//
// Messages
//
bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
{
switch (inv.type)
{
case MSG_TX:
{
bool txInMap = false;
{
LOCK(mempool.cs);
txInMap = (mempool.exists(inv.hash));
}
return txInMap ||
mapOrphanTransactions.count(inv.hash) ||
txdb.ContainsTx(inv.hash);
}
case MSG_BLOCK:
return mapBlockIndex.count(inv.hash) ||
mapOrphanBlocks.count(inv.hash);
}
// Don't know what it is, just say we already got one
return true;
}
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
unsigned char pchMessageStart[4] = { 0xce, 0xd5, 0xdb, 0xfa };
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
{
static map<CService, CPubKey> mapReuseKey;
RandAddSeedPerfmon();
if (fDebug)
printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
{
printf("dropmessagestest DROPPING RECV MESSAGE\n");
return true;
}
if (strCommand == "version")
{
// Each connection can only send one version message
if (pfrom->nVersion != 0)
{
pfrom->Misbehaving(1);
return false;
}
int64 nTime;
CAddress addrMe;
CAddress addrFrom;
uint64 nNonce = 1;
vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
if (pfrom->nVersion < MIN_PROTO_VERSION)
{
// Since February 20, 2012, the protocol is initiated at version 209,
// and earlier versions are no longer supported
printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
pfrom->fDisconnect = true;
return false;
}
if (pfrom->nVersion == 10300)
pfrom->nVersion = 300;
if (!vRecv.empty())
vRecv >> addrFrom >> nNonce;
if (!vRecv.empty())
vRecv >> pfrom->strSubVer;
if (!vRecv.empty())
vRecv >> pfrom->nStartingHeight;
if (pfrom->fInbound && addrMe.IsRoutable())
{
pfrom->addrLocal = addrMe;
SeenLocal(addrMe);
}
// Disconnect if we connected to ourself
if (nNonce == nLocalHostNonce && nNonce > 1)
{
printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
pfrom->fDisconnect = true;
return true;
}
// ppcoin: record my external IP reported by peer
if (addrFrom.IsRoutable() && addrMe.IsRoutable())
addrSeenByPeer = addrMe;
// Be shy and don't send version until we hear
if (pfrom->fInbound)
pfrom->PushVersion();
pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
AddTimeData(pfrom->addr, nTime);
// Change version
pfrom->PushMessage("verack");
pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
if (!pfrom->fInbound)
{
// Advertise our address
if (!fNoListen && !IsInitialBlockDownload())
{
CAddress addr = GetLocalAddress(&pfrom->addr);
if (addr.IsRoutable())
pfrom->PushAddress(addr);
}
// Get recent addresses
if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
{
pfrom->PushMessage("getaddr");
pfrom->fGetAddr = true;
}
addrman.Good(pfrom->addr);
} else {
if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
{
addrman.Add(addrFrom, addrFrom);
addrman.Good(addrFrom);
}
}
// Ask the first connected node for block updates
static int nAskedForBlocks = 0;
if (!pfrom->fClient && !pfrom->fOneShot &&
(pfrom->nStartingHeight > (nBestHeight - 144)) &&
(pfrom->nVersion < NOBLKS_VERSION_START ||
pfrom->nVersion >= NOBLKS_VERSION_END) &&
(nAskedForBlocks < 1 || vNodes.size() <= 1))
{
nAskedForBlocks++;
pfrom->PushGetBlocks(pindexBest, uint256(0));
}
// Relay alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
item.second.RelayTo(pfrom);
}
// ppcoin: relay sync-checkpoint
{
LOCK(Checkpoints::cs_hashSyncCheckpoint);
if (!Checkpoints::checkpointMessage.IsNull())
Checkpoints::checkpointMessage.RelayTo(pfrom);
}
pfrom->fSuccessfullyConnected = true;
printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str());
cPeerBlockCounts.input(pfrom->nStartingHeight);
// ppcoin: ask for pending sync-checkpoint if any
if (!IsInitialBlockDownload())
Checkpoints::AskForPendingSyncCheckpoint(pfrom);
}
else if (pfrom->nVersion == 0)
{
// Must have a version message before anything else
pfrom->Misbehaving(1);
return false;
}
else if (strCommand == "verack")
{
pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
}
else if (strCommand == "addr")
{
vector<CAddress> vAddr;
vRecv >> vAddr;
// Don't want addr from older versions unless seeding
if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
return true;
if (vAddr.size() > 1000)
{
pfrom->Misbehaving(20);
return error("message addr size() = %"PRIszu"", vAddr.size());
}
// Store the new addresses
vector<CAddress> vAddrOk;
int64 nNow = GetAdjustedTime();
int64 nSince = nNow - 10 * 60;
BOOST_FOREACH(CAddress& addr, vAddr)
{
if (fShutdown)
return true;
if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
addr.nTime = nNow - 5 * 24 * 60 * 60;
pfrom->AddAddressKnown(addr);
bool fReachable = IsReachable(addr);
if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
{
// Relay to a limited number of other nodes
{
LOCK(cs_vNodes);
// Use deterministic randomness to send to the same nodes for 24 hours
// at a time so the setAddrKnowns of the chosen nodes prevent repeats
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint64 hashAddr = addr.GetHash();
uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
hashRand = Hash(BEGIN(hashRand), END(hashRand));
multimap<uint256, CNode*> mapMix;
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->nVersion < CADDR_TIME_VERSION)
continue;
unsigned int nPointer;
memcpy(&nPointer, &pnode, sizeof(nPointer));
uint256 hashKey = hashRand ^ nPointer;
hashKey = Hash(BEGIN(hashKey), END(hashKey));
mapMix.insert(make_pair(hashKey, pnode));
}
int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
((*mi).second)->PushAddress(addr);
}
}
// Do not store addresses outside our network
if (fReachable)
vAddrOk.push_back(addr);
}
addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
if (vAddr.size() < 1000)
pfrom->fGetAddr = false;
if (pfrom->fOneShot)
pfrom->fDisconnect = true;
}
else if (strCommand == "inv")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
pfrom->Misbehaving(20);
return error("message inv size() = %"PRIszu"", vInv.size());
}
// find last block in inv vector
unsigned int nLastBlock = (unsigned int)(-1);
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
nLastBlock = vInv.size() - 1 - nInv;
break;
}
}
CTxDB txdb("r");
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
{
const CInv &inv = vInv[nInv];
if (fShutdown)
return true;
pfrom->AddInventoryKnown(inv);
bool fAlreadyHave = AlreadyHave(txdb, inv);
if (fDebug)
printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
if (!fAlreadyHave)
pfrom->AskFor(inv);
else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
} else if (nInv == nLastBlock) {
// In case we are on a very long side-chain, it is possible that we already have
// the last block in an inv bundle sent in response to getblocks. Try to detect
// this situation and push another getblocks to continue.
pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
if (fDebug)
printf("force request: %s\n", inv.ToString().c_str());
}
// Track requests for our stuff
Inventory(inv.hash);
}
}
else if (strCommand == "getdata")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
pfrom->Misbehaving(20);
return error("message getdata size() = %"PRIszu"", vInv.size());
}
if (fDebugNet || (vInv.size() != 1))
printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
BOOST_FOREACH(const CInv& inv, vInv)
{
if (fShutdown)
return true;
if (fDebugNet || (vInv.size() == 1))
printf("received getdata for: %s\n", inv.ToString().c_str());
if (inv.type == MSG_BLOCK)
{
// Send block from disk
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
if (mi != mapBlockIndex.end())
{
CBlock block;
block.ReadFromDisk((*mi).second);
pfrom->PushMessage("block", block);
// Trigger them to send a getblocks request for the next batch of inventory
if (inv.hash == pfrom->hashContinue)
{
// ppcoin: send latest proof-of-work block to allow the
// download node to accept as orphan (proof-of-stake
// block might be rejected by stake connection check)
vector<CInv> vInv;
vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
pfrom->PushMessage("inv", vInv);
pfrom->hashContinue = 0;
}
}
}
else if (inv.IsKnownType())
{
// Send stream from relay memory
bool pushed = false;
{
LOCK(cs_mapRelay);
map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
if (mi != mapRelay.end()) {
pfrom->PushMessage(inv.GetCommand(), (*mi).second);
pushed = true;
}
}
if (!pushed && inv.type == MSG_TX) {
LOCK(mempool.cs);
if (mempool.exists(inv.hash)) {
CTransaction tx = mempool.lookup(inv.hash);
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << tx;
pfrom->PushMessage("tx", ss);
}
}
}
// Track requests for our stuff
Inventory(inv.hash);
}
}
else if (strCommand == "getblocks")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
// Find the last block the caller has in the main chain
CBlockIndex* pindex = locator.GetBlockIndex();
// Send the rest of the chain
if (pindex)
pindex = pindex->pnext;
int nLimit = 500;
printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
for (; pindex; pindex = pindex->pnext)
{
if (pindex->GetBlockHash() == hashStop)
{
printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
// ppcoin: tell downloading node about the latest block if it's
// without risk being rejected due to stake connection check
if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
break;
}
pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
if (--nLimit <= 0)
{
// When this block is requested, we'll send an inv that'll make them
// getblocks the next batch of inventory.
printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
pfrom->hashContinue = pindex->GetBlockHash();
break;
}
}
}
else if (strCommand == "checkpoint")
{
CSyncCheckpoint checkpoint;
vRecv >> checkpoint;
if (checkpoint.ProcessSyncCheckpoint(pfrom))
{
// Relay
pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
checkpoint.RelayTo(pnode);
}
}
else if (strCommand == "getheaders")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
CBlockIndex* pindex = NULL;
if (locator.IsNull())
{
// If locator is null, return the hashStop block
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
if (mi == mapBlockIndex.end())
return true;
pindex = (*mi).second;
}
else
{
// Find the last block the caller has in the main chain
pindex = locator.GetBlockIndex();
if (pindex)
pindex = pindex->pnext;
}
vector<CBlock> vHeaders;
int nLimit = 2000;
printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
for (; pindex; pindex = pindex->pnext)
{
vHeaders.push_back(pindex->GetBlockHeader());
if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
break;
}
pfrom->PushMessage("headers", vHeaders);
}
else if (strCommand == "tx")
{
vector<uint256> vWorkQueue;
vector<uint256> vEraseQueue;
CDataStream vMsg(vRecv);
CTxDB txdb("r");
CTransaction tx;
vRecv >> tx;
CInv inv(MSG_TX, tx.GetHash());
pfrom->AddInventoryKnown(inv);
bool fMissingInputs = false;
if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
{
SyncWithWallets(tx, NULL, true);
RelayMessage(inv, vMsg);
mapAlreadyAskedFor.erase(inv);
vWorkQueue.push_back(inv.hash);
vEraseQueue.push_back(inv.hash);
// Recursively process any orphan transactions that depended on this one
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
mi != mapOrphanTransactionsByPrev[hashPrev].end();
++mi)
{
const CDataStream& vMsg = *((*mi).second);
CTransaction tx;
CDataStream(vMsg) >> tx;
CInv inv(MSG_TX, tx.GetHash());
bool fMissingInputs2 = false;
if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
{
printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
SyncWithWallets(tx, NULL, true);
RelayMessage(inv, vMsg);
mapAlreadyAskedFor.erase(inv);
vWorkQueue.push_back(inv.hash);
vEraseQueue.push_back(inv.hash);
}
else if (!fMissingInputs2)
{
// invalid orphan
vEraseQueue.push_back(inv.hash);
printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
}
}
}
BOOST_FOREACH(uint256 hash, vEraseQueue)
EraseOrphanTx(hash);
}
else if (fMissingInputs)
{
AddOrphanTx(vMsg);
// DoS prevention: do not allow mapOrphanTransactions to grow unbounded
unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
if (nEvicted > 0)
printf("mapOrphan overflow, removed %u tx\n", nEvicted);
}
if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
}
else if (strCommand == "block")
{
CBlock block;
vRecv >> block;
printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
// block.print();
CInv inv(MSG_BLOCK, block.GetHash());
pfrom->AddInventoryKnown(inv);
if (ProcessBlock(pfrom, &block))
mapAlreadyAskedFor.erase(inv);
if (block.nDoS) pfrom->Misbehaving(block.nDoS);
}
else if (strCommand == "getaddr")
{
pfrom->vAddrToSend.clear();
vector<CAddress> vAddr = addrman.GetAddr();
BOOST_FOREACH(const CAddress &addr, vAddr)
pfrom->PushAddress(addr);
}
else if (strCommand == "mempool")
{
std::vector<uint256> vtxid;
mempool.queryHashes(vtxid);
vector<CInv> vInv;
for (unsigned int i = 0; i < vtxid.size(); i++) {
CInv inv(MSG_TX, vtxid[i]);
vInv.push_back(inv);
if (i == (MAX_INV_SZ - 1))
break;
}
if (vInv.size() > 0)
pfrom->PushMessage("inv", vInv);
}
else if (strCommand == "checkorder")
{
uint256 hashReply;
vRecv >> hashReply;
if (!GetBoolArg("-allowreceivebyip"))
{
pfrom->PushMessage("reply", hashReply, (int)2, string(""));
return true;
}
CWalletTx order;
vRecv >> order;
/// we have a chance to check the order here
// Keep giving the same key to the same ip until they use it
if (!mapReuseKey.count(pfrom->addr))
pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
// Send back approval of order and pubkey to use
CScript scriptPubKey;
scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
}
else if (strCommand == "reply")
{
uint256 hashReply;
vRecv >> hashReply;
CRequestTracker tracker;
{
LOCK(pfrom->cs_mapRequests);
map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
if (mi != pfrom->mapRequests.end())
{
tracker = (*mi).second;
pfrom->mapRequests.erase(mi);
}
}
if (!tracker.IsNull())
tracker.fn(tracker.param1, vRecv);
}
else if (strCommand == "ping")
{
if (pfrom->nVersion > BIP0031_VERSION)
{
uint64 nonce = 0;
vRecv >> nonce;
// Echo the message back with the nonce. This allows for two useful features:
//
// 1) A remote node can quickly check if the connection is operational
// 2) Remote nodes can measure the latency of the network thread. If this node
// is overloaded it won't respond to pings quickly and the remote node can
// avoid sending us more work, like chain download requests.
//
// The nonce stops the remote getting confused between different pings: without
// it, if the remote node sends a ping once per second and this node takes 5
// seconds to respond to each, the 5th ping the remote sends would appear to
// return very quickly.
pfrom->PushMessage("pong", nonce);
}
}
else if (strCommand == "alert")
{
CAlert alert;
vRecv >> alert;
uint256 alertHash = alert.GetHash();
if (pfrom->setKnown.count(alertHash) == 0)
{
if (alert.ProcessAlert())
{
// Relay
pfrom->setKnown.insert(alertHash);
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
alert.RelayTo(pnode);
}
}
else {
// Small DoS penalty so peers that send us lots of
// duplicate/expired/invalid-signature/whatever alerts
// eventually get banned.
// This isn't a Misbehaving(100) (immediate ban) because the
// peer might be an older or different implementation with
// a different signature key, etc.
pfrom->Misbehaving(10);
}
}
}
else
{
// Ignore unknown commands for extensibility
}
// Update the last seen time for this node's address
if (pfrom->fNetworkNode)
if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
AddressCurrentlyConnected(pfrom->addr);
return true;
}
bool ProcessMessages(CNode* pfrom)
{
CDataStream& vRecv = pfrom->vRecv;
if (vRecv.empty())
return true;
//if (fDebug)
// printf("ProcessMessages(%u bytes)\n", vRecv.size());
//
// Message format
// (4) message start
// (12) command
// (4) size
// (4) checksum
// (x) data
//
loop
{
// Don't bother if send buffer is too full to respond anyway
if (pfrom->vSend.size() >= SendBufferSize())
break;
// Scan for message start
CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
if (vRecv.end() - pstart < nHeaderSize)
{
if ((int)vRecv.size() > nHeaderSize)
{
printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
}
break;
}
if (pstart - vRecv.begin() > 0)
printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
vRecv.erase(vRecv.begin(), pstart);
// Read header
vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
CMessageHeader hdr;
vRecv >> hdr;
if (!hdr.IsValid())
{
printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
continue;
}
string strCommand = hdr.GetCommand();
// Message size
unsigned int nMessageSize = hdr.nMessageSize;
if (nMessageSize > MAX_SIZE)
{
printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
continue;
}
if (nMessageSize > vRecv.size())
{
// Rewind and wait for rest of message
vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
break;
}
// Checksum
uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
if (nChecksum != hdr.nChecksum)
{
printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
continue;
}
// Copy message to its own buffer
CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
vRecv.ignore(nMessageSize);
// Process message
bool fRet = false;
try
{
{
LOCK(cs_main);
fRet = ProcessMessage(pfrom, strCommand, vMsg);
}
if (fShutdown)
return true;
}
catch (std::ios_base::failure& e)
{
if (strstr(e.what(), "end of data"))
{
// Allow exceptions from under-length message on vRecv
printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
}
else if (strstr(e.what(), "size too large"))
{
// Allow exceptions from over-long size
printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
}
else
{
PrintExceptionContinue(&e, "ProcessMessages()");
}
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ProcessMessages()");
} catch (...) {
PrintExceptionContinue(NULL, "ProcessMessages()");
}
if (!fRet)
printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
}
vRecv.Compact();
return true;
}
bool SendMessages(CNode* pto, bool fSendTrickle)
{
TRY_LOCK(cs_main, lockMain);
if (lockMain) {
// Don't send anything until we get their version message
if (pto->nVersion == 0)
return true;
// Keep-alive ping. We send a nonce of zero because we don't use it anywhere
// right now.
if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
uint64 nonce = 0;
if (pto->nVersion > BIP0031_VERSION)
pto->PushMessage("ping", nonce);
else
pto->PushMessage("ping");
}
// Resend wallet transactions that haven't gotten in a block yet
ResendWalletTransactions();
// Address refresh broadcast
static int64 nLastRebroadcast;
if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
// Periodically clear setAddrKnown to allow refresh broadcasts
if (nLastRebroadcast)
pnode->setAddrKnown.clear();
// Rebroadcast our address
if (!fNoListen)
{
CAddress addr = GetLocalAddress(&pnode->addr);
if (addr.IsRoutable())
pnode->PushAddress(addr);
}
}
}
nLastRebroadcast = GetTime();
}
//
// Message: addr
//
if (fSendTrickle)
{
vector<CAddress> vAddr;
vAddr.reserve(pto->vAddrToSend.size());
BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
{
// returns true if wasn't already contained in the set
if (pto->setAddrKnown.insert(addr).second)
{
vAddr.push_back(addr);
// receiver rejects addr messages larger than 1000
if (vAddr.size() >= 1000)
{
pto->PushMessage("addr", vAddr);
vAddr.clear();
}
}
}
pto->vAddrToSend.clear();
if (!vAddr.empty())
pto->PushMessage("addr", vAddr);
}
//
// Message: inventory
//
vector<CInv> vInv;
vector<CInv> vInvWait;
{
LOCK(pto->cs_inventory);
vInv.reserve(pto->vInventoryToSend.size());
vInvWait.reserve(pto->vInventoryToSend.size());
BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
{
if (pto->setInventoryKnown.count(inv))
continue;
// trickle out tx inv to protect privacy
if (inv.type == MSG_TX && !fSendTrickle)
{
// 1/4 of tx invs blast to all immediately
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint256 hashRand = inv.hash ^ hashSalt;
hashRand = Hash(BEGIN(hashRand), END(hashRand));
bool fTrickleWait = ((hashRand & 3) != 0);
// always trickle our own transactions
if (!fTrickleWait)
{
CWalletTx wtx;
if (GetTransaction(inv.hash, wtx))
if (wtx.fFromMe)
fTrickleWait = true;
}
if (fTrickleWait)
{
vInvWait.push_back(inv);
continue;
}
}
// returns true if wasn't already contained in the set
if (pto->setInventoryKnown.insert(inv).second)
{
vInv.push_back(inv);
if (vInv.size() >= 1000)
{
pto->PushMessage("inv", vInv);
vInv.clear();
}
}
}
pto->vInventoryToSend = vInvWait;
}
if (!vInv.empty())
pto->PushMessage("inv", vInv);
//
// Message: getdata
//
vector<CInv> vGetData;
int64 nNow = GetTime() * 1000000;
CTxDB txdb("r");
while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
{
const CInv& inv = (*pto->mapAskFor.begin()).second;
if (!AlreadyHave(txdb, inv))
{
if (fDebugNet)
printf("sending getdata: %s\n", inv.ToString().c_str());
vGetData.push_back(inv);
if (vGetData.size() >= 1000)
{
pto->PushMessage("getdata", vGetData);
vGetData.clear();
}
mapAlreadyAskedFor[inv] = nNow;
}
pto->mapAskFor.erase(pto->mapAskFor.begin());
}
if (!vGetData.empty())
pto->PushMessage("getdata", vGetData);
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
//
// BitcoinMiner
//
int static FormatHashBlocks(void* pbuffer, unsigned int len)
{
unsigned char* pdata = (unsigned char*)pbuffer;
unsigned int blocks = 1 + ((len + 8) / 64);
unsigned char* pend = pdata + 64 * blocks;
memset(pdata + len, 0, 64 * blocks - len);
pdata[len] = 0x80;
unsigned int bits = len * 8;
pend[-1] = (bits >> 0) & 0xff;
pend[-2] = (bits >> 8) & 0xff;
pend[-3] = (bits >> 16) & 0xff;
pend[-4] = (bits >> 24) & 0xff;
return blocks;
}
static const unsigned int pSHA256InitState[8] =
{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
void SHA256Transform(void* pstate, void* pinput, const void* pinit)
{
SHA256_CTX ctx;
unsigned char data[64];
SHA256_Init(&ctx);
for (int i = 0; i < 16; i++)
((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
for (int i = 0; i < 8; i++)
ctx.h[i] = ((uint32_t*)pinit)[i];
SHA256_Update(&ctx, data, sizeof(data));
for (int i = 0; i < 8; i++)
((uint32_t*)pstate)[i] = ctx.h[i];
}
// Some explaining would be appreciated
class COrphan
{
public:
CTransaction* ptx;
set<uint256> setDependsOn;
double dPriority;
double dFeePerKb;
COrphan(CTransaction* ptxIn)
{
ptx = ptxIn;
dPriority = dFeePerKb = 0;
}
void print() const
{
printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb);
BOOST_FOREACH(uint256 hash, setDependsOn)
printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
}
};
uint64 nLastBlockTx = 0;
uint64 nLastBlockSize = 0;
int64 nLastCoinStakeSearchInterval = 0;
// We want to sort transactions by priority and fee, so:
typedef boost::tuple<double, double, CTransaction*> TxPriority;
class TxPriorityCompare
{
bool byFee;
public:
TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
bool operator()(const TxPriority& a, const TxPriority& b)
{
if (byFee)
{
if (a.get<1>() == b.get<1>())
return a.get<0>() < b.get<0>();
return a.get<1>() < b.get<1>();
}
else
{
if (a.get<0>() == b.get<0>())
return a.get<1>() < b.get<1>();
return a.get<0>() < b.get<0>();
}
}
};
// CreateNewBlock:
// fProofOfStake: try (best effort) to make a proof-of-stake block
CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
{
CReserveKey reservekey(pwallet);
// Create new block
auto_ptr<CBlock> pblock(new CBlock());
if (!pblock.get())
return NULL;
// Create coinbase tx
CTransaction txNew;
txNew.vin.resize(1);
txNew.vin[0].prevout.SetNull();
txNew.vout.resize(1);
txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
// Add our coinbase tx as first transaction
pblock->vtx.push_back(txNew);
// Largest block you're willing to create:
unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
// Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
// How much of the block should be dedicated to high-priority transactions,
// included regardless of the fees they pay
unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
// Minimum block size you want to create; block will be filled with free transactions
// until there are no more or the block reaches this size:
unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
// Fee-per-kilobyte amount considered the same as "free"
// Be careful setting this: if you set it to zero then
// a transaction spammer can cheaply fill blocks using
// 1-satoshi-fee transactions. It should be set above the real
// cost to you of processing a transaction.
int64 nMinTxFee = MIN_TX_FEE;
if (mapArgs.count("-mintxfee"))
ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
// ppcoin: if coinstake available add coinstake tx
static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // only initialized at startup
CBlockIndex* pindexPrev = pindexBest;
if (fProofOfStake) // attempt to find a coinstake
{
pblock->nBits = GetNextTargetRequired(pindexPrev, true);
CTransaction txCoinStake;
int64 nSearchTime = txCoinStake.nTime; // search to current time
if (nSearchTime > nLastCoinStakeSearchTime)
{
// printf(">>> OK1\n");
if (pwallet->CreateCoinStake(*pwallet, pblock->nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake))
{
if (txCoinStake.nTime >= max(pindexPrev->GetMedianTimePast()+1, pindexPrev->GetBlockTime() - nMaxClockDrift))
{ // make sure coinstake would meet timestamp protocol
// as it would be the same as the block timestamp
pblock->vtx[0].vout[0].SetEmpty();
pblock->vtx[0].nTime = txCoinStake.nTime;
pblock->vtx.push_back(txCoinStake);
}
}
nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
nLastCoinStakeSearchTime = nSearchTime;
}
}
pblock->nBits = GetNextTargetRequired(pindexPrev, pblock->IsProofOfStake());
// Collect memory pool transactions into the block
int64 nFees = 0;
{
LOCK2(cs_main, mempool.cs);
CBlockIndex* pindexPrev = pindexBest;
CTxDB txdb("r");
// Priority order to process transactions
list<COrphan> vOrphan; // list memory doesn't move
map<uint256, vector<COrphan*> > mapDependers;
// This vector will be sorted into a priority queue:
vector<TxPriority> vecPriority;
vecPriority.reserve(mempool.mapTx.size());
for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
{
CTransaction& tx = (*mi).second;
if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
continue;
COrphan* porphan = NULL;
double dPriority = 0;
int64 nTotalIn = 0;
bool fMissingInputs = false;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
// Read prev transaction
CTransaction txPrev;
CTxIndex txindex;
if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
{
// This should never happen; all transactions in the memory
// pool should connect to either transactions in the chain
// or other transactions in the memory pool.
if (!mempool.mapTx.count(txin.prevout.hash))
{
printf("ERROR: mempool transaction missing input\n");
if (fDebug) assert("mempool transaction missing input" == 0);
fMissingInputs = true;
if (porphan)
vOrphan.pop_back();
break;
}
// Has to wait for dependencies
if (!porphan)
{
// Use list for automatic deletion
vOrphan.push_back(COrphan(&tx));
porphan = &vOrphan.back();
}
mapDependers[txin.prevout.hash].push_back(porphan);
porphan->setDependsOn.insert(txin.prevout.hash);
nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
continue;
}
int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
nTotalIn += nValueIn;
int nConf = txindex.GetDepthInMainChain();
dPriority += (double)nValueIn * nConf;
}
if (fMissingInputs) continue;
// Priority is sum(valuein * age) / txsize
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
dPriority /= nTxSize;
// This is a more accurate fee-per-kilobyte than is used by the client code, because the
// client code rounds up the size to the nearest 1K. That's good, because it gives an
// incentive to create smaller transactions.
double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
if (porphan)
{
porphan->dPriority = dPriority;
porphan->dFeePerKb = dFeePerKb;
}
else
vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
}
// Collect transactions into block
map<uint256, CTxIndex> mapTestPool;
uint64 nBlockSize = 1000;
uint64 nBlockTx = 0;
int nBlockSigOps = 100;
bool fSortedByFee = (nBlockPrioritySize <= 0);
TxPriorityCompare comparer(fSortedByFee);
std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
while (!vecPriority.empty())
{
// Take highest priority transaction off the priority queue:
double dPriority = vecPriority.front().get<0>();
double dFeePerKb = vecPriority.front().get<1>();
CTransaction& tx = *(vecPriority.front().get<2>());
std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
vecPriority.pop_back();
// Size limits
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
if (nBlockSize + nTxSize >= nBlockMaxSize)
continue;
// Legacy limits on sigOps:
unsigned int nTxSigOps = tx.GetLegacySigOpCount();
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
// Timestamp limit
if (tx.nTime > GetAdjustedTime() || (pblock->IsProofOfStake() && tx.nTime > pblock->vtx[1].nTime))
continue;
// ppcoin: simplify transaction fee - allow free = false
int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK);
// Skip free transactions if we're past the minimum block size:
if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
continue;
// Prioritize by fee once past the priority size or we run out of high-priority
// transactions:
if (!fSortedByFee &&
((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
{
fSortedByFee = true;
comparer = TxPriorityCompare(fSortedByFee);
std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
}
// Connecting shouldn't fail due to dependency on other memory pool transactions
// because we're already processing them in order of dependency
map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
MapPrevTx mapInputs;
bool fInvalid;
if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
continue;
int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
if (nTxFees < nMinFee)
continue;
nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
continue;
mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
swap(mapTestPool, mapTestPoolTmp);
// Added
pblock->vtx.push_back(tx);
nBlockSize += nTxSize;
++nBlockTx;
nBlockSigOps += nTxSigOps;
nFees += nTxFees;
if (fDebug && GetBoolArg("-printpriority"))
{
printf("priority %.1f feeperkb %.1f txid %s\n",
dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
}
// Add transactions that depend on this one to the priority queue
uint256 hash = tx.GetHash();
if (mapDependers.count(hash))
{
BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
{
if (!porphan->setDependsOn.empty())
{
porphan->setDependsOn.erase(hash);
if (porphan->setDependsOn.empty())
{
vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
}
}
}
}
}
nLastBlockTx = nBlockTx;
nLastBlockSize = nBlockSize;
if (fDebug && GetBoolArg("-printpriority"))
printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
if (pblock->IsProofOfWork())
pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pindexPrev->nHeight+1, nFees, pindexPrev->GetBlockHash());
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
if (pblock->IsProofOfStake())
pblock->nTime = pblock->vtx[1].nTime; //same as coinstake timestamp
pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
if (pblock->IsProofOfWork())
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
}
return pblock.release();
}
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
}
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
{
//
// Pre-build hash buffers
//
struct
{
struct unnamed2
{
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
}
block;
unsigned char pchPadding0[64];
uint256 hash1;
unsigned char pchPadding1[64];
}
tmp;
memset(&tmp, 0, sizeof(tmp));
tmp.block.nVersion = pblock->nVersion;
tmp.block.hashPrevBlock = pblock->hashPrevBlock;
tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
tmp.block.nTime = pblock->nTime;
tmp.block.nBits = pblock->nBits;
tmp.block.nNonce = pblock->nNonce;
FormatHashBlocks(&tmp.block, sizeof(tmp.block));
FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
// Byte swap all the input buffer
for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
// Precalc the first half of the first hash, which stays constant
SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
memcpy(pdata, &tmp.block, 128);
memcpy(phash1, &tmp.hash1, 64);
}
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
{
uint256 hash = pblock->GetHash();
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
if (hash > hashTarget && pblock->IsProofOfWork())
return error("BitcoinMiner : proof-of-work not meeting target");
//// debug print
printf("BitcoinMiner:\n");
printf("new block found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
pblock->print();
printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
// Found a solution
{
LOCK(cs_main);
if (pblock->hashPrevBlock != hashBestChain)
return error("BitcoinMiner : generated block is stale");
// Remove key from key pool
reservekey.KeepKey();
// Track how many getdata requests this block gets
{
LOCK(wallet.cs_wallet);
wallet.mapRequestCount[pblock->GetHash()] = 0;
}
// Process this block the same as if we had received it from another node
if (!ProcessBlock(NULL, pblock))
return error("BitcoinMiner : ProcessBlock, block not accepted");
}
return true;
}
void static ThreadBitcoinMiner(void* parg);
static bool fGenerateBitcoins = false;
static bool fLimitProcessors = false;
static int nLimitProcessors = -1;
void BitcoinMiner(CWallet *pwallet, bool fProofOfStake)
{
void *scratchbuf = scrypt_buffer_alloc();
printf("CPUMiner started for proof-of-%s\n", fProofOfStake? "stake" : "work");
SetThreadPriority(THREAD_PRIORITY_LOWEST);
// Make this thread recognisable as the mining thread
RenameThread("bitcoin-miner");
// Each thread has its own key and counter
CReserveKey reservekey(pwallet);
unsigned int nExtraNonce = 0;
while (fGenerateBitcoins || fProofOfStake)
{
if (fShutdown)
return;
while (vNodes.empty() || IsInitialBlockDownload() || pwallet->IsLocked())
{
nLastCoinStakeSearchInterval = 0;
Sleep(1000);
if (fShutdown)
return;
if (!fGenerateBitcoins && !fProofOfStake)
return;
}
//
// Create new block
//
unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrev = pindexBest;
auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, fProofOfStake));
if (!pblock.get())
return;
IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
if (fProofOfStake)
{
// ppcoin: if proof-of-stake block found then process block
if (pblock->IsProofOfStake())
{
if (!pblock->SignBlock(*pwalletMain))
continue;
printf("CPUMiner : proof-of-stake block found %s\n", pblock->GetHash().ToString().c_str());
SetThreadPriority(THREAD_PRIORITY_NORMAL);
CheckWork(pblock.get(), *pwalletMain, reservekey);
SetThreadPriority(THREAD_PRIORITY_LOWEST);
}
Sleep(500);
continue;
}
printf("Running BitcoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
//
// Pre-build hash buffers
//
char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
//
// Search
//
int64 nStart = GetTime();
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
unsigned int max_nonce = 0xffff0000;
block_header res_header;
uint256 result;
loop
{
unsigned int nHashesDone = 0;
unsigned int nNonceFound;
nNonceFound = scanhash_scrypt(
(block_header *)&pblock->nVersion,
scratchbuf,
max_nonce,
nHashesDone,
UBEGIN(result),
&res_header
);
// Check if something found
if (nNonceFound != (unsigned int) -1)
{
if (result <= hashTarget)
{
// Found a solution
pblock->nNonce = nNonceFound;
assert(result == pblock->GetHash());
if (!pblock->SignBlock(*pwalletMain))
break;
SetThreadPriority(THREAD_PRIORITY_NORMAL);
CheckWork(pblock.get(), *pwalletMain, reservekey);
SetThreadPriority(THREAD_PRIORITY_LOWEST);
break;
}
}
// Meter hashes/sec
static int64 nHashCounter;
if (nHPSTimerStart == 0)
{
nHPSTimerStart = GetTimeMillis();
nHashCounter = 0;
}
else
nHashCounter += nHashesDone;
if (GetTimeMillis() - nHPSTimerStart > 4000)
{
static CCriticalSection cs;
{
LOCK(cs);
if (GetTimeMillis() - nHPSTimerStart > 4000)
{
dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
nHPSTimerStart = GetTimeMillis();
nHashCounter = 0;
static int64 nLogTime;
if (GetTime() - nLogTime > 30 * 60)
{
nLogTime = GetTime();
printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
}
}
}
}
// Check for stop or if block needs to be rebuilt
if (fShutdown)
return;
if (!fGenerateBitcoins)
return;
if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
return;
if (vNodes.empty())
break;
if (nBlockNonce >= 0xffff0000)
break;
if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
break;
if (pindexPrev != pindexBest)
break;
// Update nTime every few seconds
pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
pblock->UpdateTime(pindexPrev);
nBlockTime = ByteReverse(pblock->nTime);
if (pblock->GetBlockTime() >= (int64)pblock->vtx[0].nTime + nMaxClockDrift)
break; // need to update coinbase timestamp
}
}
scrypt_buffer_free(scratchbuf);
}
void static ThreadBitcoinMiner(void* parg)
{
CWallet* pwallet = (CWallet*)parg;
try
{
vnThreadsRunning[THREAD_MINER]++;
BitcoinMiner(pwallet, false);
vnThreadsRunning[THREAD_MINER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_MINER]--;
PrintException(&e, "ThreadBitcoinMiner()");
} catch (...) {
vnThreadsRunning[THREAD_MINER]--;
PrintException(NULL, "ThreadBitcoinMiner()");
}
nHPSTimerStart = 0;
if (vnThreadsRunning[THREAD_MINER] == 0)
dHashesPerSec = 0;
printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
}
void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
{
fGenerateBitcoins = fGenerate;
nLimitProcessors = GetArg("-genproclimit", -1);
if (nLimitProcessors == 0)
fGenerateBitcoins = false;
fLimitProcessors = (nLimitProcessors != -1);
if (fGenerate)
{
int nProcessors = boost::thread::hardware_concurrency();
printf("%d processors\n", nProcessors);
if (nProcessors < 1)
nProcessors = 1;
if (fLimitProcessors && nProcessors > nLimitProcessors)
nProcessors = nLimitProcessors;
int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
printf("Starting %d BitcoinMiner threads\n", nAddThreads);
for (int i = 0; i < nAddThreads; i++)
{
if (!NewThread(ThreadBitcoinMiner, pwallet))
printf("Error: NewThread(ThreadBitcoinMiner) failed\n");
Sleep(10);
}
}
}
| Crestington/mintcoin | src/main.cpp | C++ | mit | 157,528 |
import csv
import _csv
import json
import click # type: ignore
from collections import OrderedDict
from typing import OrderedDict as tOrderedDict, TextIO, List, Dict, Optional
from voluptuous import ( # type: ignore
Schema, Required, MultipleInvalid, ALLOW_EXTRA
)
from ..common_types import SequenceResult, AlignedGeneSeq
GENES: tOrderedDict = OrderedDict([
('PR', 99),
('RT', 560),
('IN', 288)
])
schema: Schema = Schema([{
Required('inputSequence'): {
Required('header'): str
},
Required('alignedGeneSequences'): [{
Required('gene'): {
Required('name'): str
},
Required('firstAA'): int,
Required('lastAA'): int,
Required('alignedNAs'): str
}]
}], extra=ALLOW_EXTRA)
@click.pass_context
def sequencetsv(ctx: click.Context) -> None:
"""Export mutation set of each sequences from Sierra result."""
seq: SequenceResult
seqheader: str
geneseqs: Dict[str, AlignedGeneSeq]
geneseq: Optional[AlignedGeneSeq]
first_aa: int
last_aa: int
aligned_nas: str
output: TextIO = ctx.obj['OUTPUT']
sequences: List[SequenceResult] = json.load(ctx.obj['INPUT'])
try:
schema(sequences)
except MultipleInvalid as e:
raise click.ClickException(str(e))
writer: _csv._writer = csv.writer(output, delimiter='\t')
writer.writerow(['Header', 'Gene', 'FirstAA', 'LastAA', 'AlignedNAs'])
for seq in sequences:
seqheader = seq['inputSequence']['header']
geneseqs = {gs['gene']['name']: gs
for gs in seq['alignedGeneSequences']}
for gene, _ in GENES.items():
geneseq = geneseqs.get(gene)
if not geneseq:
continue
first_aa = geneseq['firstAA']
last_aa = geneseq['lastAA']
aligned_nas = geneseq['alignedNAs']
writer.writerow([seqheader, gene, first_aa, last_aa, aligned_nas])
| hivdb/sierra-client | python/sierrapy/recipes/sequencetsv.py | Python | mit | 1,952 |
# http://peter-hoffmann.com/2011/adding-dict-interface-python-leveldb-api.html
from UserDict import DictMixin
import leveldb
import json
class LevelDict(object, DictMixin):
"""Dict Wrapper around the Google LevelDB Database"""
def __init__(self, path):
"""Constructor for LevelDict"""
self.path = path
self.db = leveldb.LevelDB(self.path)
def __getitem__(self, key):
return self.db.Get(key)
def __setitem__(self, key, value):
self.db.Put(key, value)
def __delitem__(self, key):
self.db.Delete(key)
def __iter__(self):
for k, v in self.db.RangeIter(include_value=False):
yield k
def keys(self):
return [k for k, v in self.db.RangeIter()]
def iteritems(self):
return self.db.RangeIter()
def rangescan(self, start=None, end=None):
if start is None and end is None:
return self.db.RangeIter()
elif end is None:
return self.db.RangeIter(start)
else:
return self.db.RangeIter(start, end)
class LevelJsonDict(LevelDict):
"""Dict Wrapper around the Google LevelDB Database with JSON serialization"""
def __getitem__(self, key):
return json.loads(LevelDict.__getitem__(self, key))
def __setitem__(self, key, value):
LevelDict.__setitem__(self, key, json.dumps(value))
def iteritems(self):
for k, v in LevelDict.iteritems(self):
yield k, json.loads(v)
def rangescan(self, start=None, end=None):
for k, v in LevelDict.rangescan(self, start, end):
yield k, json.loads(v)
| davidthewatson/flickr2leveldb | level_dict.py | Python | mit | 1,629 |
# MASimplestSemiModalViewController
The simplest Semi Modal implementation possible.
Very, very simplified version based on [KNSemiModalViewController](https://github.com/kentnguyen/KNSemiModalViewController).
## Features (or lack of)
* iOS 6+
* No options configuration
* No callback completion blocks
* No UIViewController containment logic implemented
* No tests
## Usage
* Add `MASimplestSemiModalViewController` on your Podfile and install it
* `#import "UIViewController+MASimplestSemiModal.h"'`
* `[viewController presentSemiView:semiView];`
## Disclaimer
If you want a better, configurable and complex Semi Modal implementation you should go for
[KNSemiModalViewController](https://github.com/kentnguyen/KNSemiModalViewController),
[@kentnguyen](https://github.com/kentnguyen) and the other contributors made a great job on that project.
Even thought I said that it is the simplest Semi Modal implementation possible
I know that it's not, so fell free to make it simpler.
| marlonandrade/MASimplestSemiModalViewController | README.md | Markdown | mit | 993 |
namespace Caliburn.Micro {
using System;
using System.Collections.Generic;
using Windows.Foundation;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
#if WP81
using Windows.Phone.UI.Input;
#endif
/// <summary>
/// Implemented by services that provide (<see cref="Uri" /> based) navigation.
/// </summary>
public interface INavigationService {
/// <summary>
/// Raised after navigation.
/// </summary>
event NavigatedEventHandler Navigated;
/// <summary>
/// Raised prior to navigation.
/// </summary>
event NavigatingCancelEventHandler Navigating;
/// <summary>
/// Raised when navigation fails.
/// </summary>
event NavigationFailedEventHandler NavigationFailed;
/// <summary>
/// Raised when navigation is stopped.
/// </summary>
event NavigationStoppedEventHandler NavigationStopped;
/// <summary>
/// Gets or sets the data type of the current content, or the content that should be navigated to.
/// </summary>
Type SourcePageType { get; set; }
/// <summary>
/// Gets the data type of the content that is currently displayed.
/// </summary>
Type CurrentSourcePageType { get; }
/// <summary>
/// Indicates whether the navigator can navigate forward.
/// </summary>
bool CanGoForward { get; }
/// <summary>
/// Indicates whether the navigator can navigate back.
/// </summary>
bool CanGoBack { get; }
/// <summary>
/// Navigates to the specified content.
/// </summary>
/// <param name="sourcePageType"> The <see cref="System.Type" /> to navigate to. </param>
/// <returns> Whether or not navigation succeeded. </returns>
bool Navigate(Type sourcePageType);
/// <summary>
/// Navigates to the specified content.
/// </summary>
/// <param name="sourcePageType"> The <see cref="System.Type" /> to navigate to. </param>
/// <param name="parameter">The object parameter to pass to the target.</param>
/// <returns> Whether or not navigation succeeded. </returns>
bool Navigate(Type sourcePageType, object parameter);
/// <summary>
/// Navigates forward.
/// </summary>
void GoForward();
/// <summary>
/// Navigates back.
/// </summary>
void GoBack();
#if WinRT81
/// <summary>
/// Gets a collection of PageStackEntry instances representing the backward navigation history of the Frame.
/// </summary>
IList<PageStackEntry> BackStack { get; }
/// <summary>
/// Gets a collection of PageStackEntry instances representing the forward navigation history of the Frame.
/// </summary>
IList<PageStackEntry> ForwardStack { get; }
#endif
#if WP81
/// <summary>
/// Occurs when the user presses the hardware Back button.
/// </summary>
event EventHandler<BackPressedEventArgs> BackPressed;
#endif
/// <summary>
/// Stores the frame navigation state in local settings if it can.
/// </summary>
/// <returns>Whether the suspension was sucessful</returns>
bool SuspendState();
/// <summary>
/// Tries to restore the frame navigation state from local settings.
/// </summary>
/// <returns>Whether the restoration of successful.</returns>
bool ResumeState();
}
/// <summary>
/// A basic implementation of <see cref="INavigationService" /> designed to adapt the <see cref="Frame" /> control.
/// </summary>
public class FrameAdapter : INavigationService {
private static readonly ILog Log = LogManager.GetLog(typeof(FrameAdapter));
private const string FrameStateKey = "FrameState";
private const string ParameterKey = "ParameterKey";
private readonly Frame frame;
private readonly bool treatViewAsLoaded;
private event NavigatingCancelEventHandler ExternalNavigatingHandler = delegate { };
private object currentParameter;
/// <summary>
/// Creates an instance of <see cref="FrameAdapter" />.
/// </summary>
/// <param name="frame">The frame to represent as a <see cref="INavigationService" />.</param>
/// <param name="treatViewAsLoaded">
/// Tells the frame adapter to assume that the view has already been loaded by the time OnNavigated is called.
/// This is necessary when using the TransitionFrame.
/// </param>
public FrameAdapter(Frame frame, bool treatViewAsLoaded = false) {
this.frame = frame;
this.treatViewAsLoaded = treatViewAsLoaded;
this.frame.Navigating += OnNavigating;
this.frame.Navigated += OnNavigated;
#if WP81
this.frame.Loaded += (sender, args) => { HardwareButtons.BackPressed += OnHardwareBackPressed; };
this.frame.Unloaded += (sender, args) => { HardwareButtons.BackPressed -= OnHardwareBackPressed; };
#endif
}
/// <summary>
/// Occurs before navigation
/// </summary>
/// <param name="sender"> The event sender. </param>
/// <param name="e"> The event args. </param>
protected virtual void OnNavigating(object sender, NavigatingCancelEventArgs e) {
ExternalNavigatingHandler(sender, e);
if (e.Cancel)
return;
var view = frame.Content as FrameworkElement;
if (view == null)
return;
var guard = view.DataContext as IGuardClose;
if (guard != null) {
var shouldCancel = false;
var runningAsync = true;
guard.CanClose(result => { runningAsync = false; shouldCancel = !result; });
if (runningAsync)
throw new NotSupportedException("Async CanClose is not supported.");
if (shouldCancel) {
e.Cancel = true;
return;
}
}
var deactivator = view.DataContext as IDeactivate;
if (deactivator != null) {
deactivator.Deactivate(CanCloseOnNavigating(sender, e));
}
}
/// <summary>
/// Occurs after navigation
/// </summary>
/// <param name="sender"> The event sender. </param>
/// <param name="e"> The event args. </param>
protected virtual void OnNavigated(object sender, NavigationEventArgs e) {
if (e.Content == null)
return;
currentParameter = e.Parameter;
var view = e.Content as Page;
if (view == null) {
throw new ArgumentException("View '" + e.Content.GetType().FullName +
"' should inherit from Page or one of its descendents.");
}
BindViewModel(view);
}
/// <summary>
/// Binds the view model.
/// </summary>
/// <param name="view">The view.</param>
protected virtual void BindViewModel(DependencyObject view) {
ViewLocator.InitializeComponent(view);
var viewModel = ViewModelLocator.LocateForView(view);
if (viewModel == null)
return;
if (treatViewAsLoaded) {
view.SetValue(View.IsLoadedProperty, true);
}
TryInjectParameters(viewModel, currentParameter);
ViewModelBinder.Bind(viewModel, view, null);
var activator = viewModel as IActivate;
if (activator != null) {
activator.Activate();
}
GC.Collect(); // Why?
}
/// <summary>
/// Attempts to inject query string parameters from the view into the view model.
/// </summary>
/// <param name="viewModel"> The view model.</param>
/// <param name="parameter"> The parameter.</param>
protected virtual void TryInjectParameters(object viewModel, object parameter) {
var viewModelType = viewModel.GetType();
if (parameter is string && ((string) parameter).StartsWith("caliburn://")) {
var uri = new Uri((string) parameter);
if (!String.IsNullOrEmpty(uri.Query)) {
var decorder = new WwwFormUrlDecoder(uri.Query);
foreach (var pair in decorder) {
var property = viewModelType.GetPropertyCaseInsensitive(pair.Name);
if (property == null) {
continue;
}
property.SetValue(viewModel, MessageBinder.CoerceValue(property.PropertyType, pair.Value, null));
}
}
}
else {
var property = viewModelType.GetPropertyCaseInsensitive("Parameter");
if (property == null)
return;
property.SetValue(viewModel, MessageBinder.CoerceValue(property.PropertyType, parameter, null));
}
}
/// <summary>
/// Called to check whether or not to close current instance on navigating.
/// </summary>
/// <param name="sender"> The event sender from OnNavigating event. </param>
/// <param name="e"> The event args from OnNavigating event. </param>
protected virtual bool CanCloseOnNavigating(object sender, NavigatingCancelEventArgs e) {
return false;
}
/// <summary>
/// Raised after navigation.
/// </summary>
public event NavigatedEventHandler Navigated {
add { frame.Navigated += value; }
remove { frame.Navigated -= value; }
}
/// <summary>
/// Raised prior to navigation.
/// </summary>
public event NavigatingCancelEventHandler Navigating {
add { ExternalNavigatingHandler += value; }
remove { ExternalNavigatingHandler -= value; }
}
/// <summary>
/// Raised when navigation fails.
/// </summary>
public event NavigationFailedEventHandler NavigationFailed {
add { frame.NavigationFailed += value; }
remove { frame.NavigationFailed -= value; }
}
/// <summary>
/// Raised when navigation is stopped.
/// </summary>
public event NavigationStoppedEventHandler NavigationStopped {
add { frame.NavigationStopped += value; }
remove { frame.NavigationStopped -= value; }
}
/// <summary>
/// Gets or sets the data type of the current content, or the content that should be navigated to.
/// </summary>
public Type SourcePageType {
get { return frame.SourcePageType; }
set { frame.SourcePageType = value; }
}
/// <summary>
/// Gets the data type of the content that is currently displayed.
/// </summary>
public Type CurrentSourcePageType {
get { return frame.CurrentSourcePageType; }
}
/// <summary>
/// Navigates to the specified content.
/// </summary>
/// <param name="sourcePageType"> The <see cref="System.Type" /> to navigate to. </param>
/// <returns> Whether or not navigation succeeded. </returns>
public bool Navigate(Type sourcePageType) {
return frame.Navigate(sourcePageType);
}
/// <summary>
/// Navigates to the specified content.
/// </summary>
/// <param name="sourcePageType"> The <see cref="System.Type" /> to navigate to. </param>
/// <param name="parameter">The object parameter to pass to the target.</param>
/// <returns> Whether or not navigation succeeded. </returns>
public bool Navigate(Type sourcePageType, object parameter) {
return frame.Navigate(sourcePageType, parameter);
}
/// <summary>
/// Navigates forward.
/// </summary>
public void GoForward() {
frame.GoForward();
}
/// <summary>
/// Navigates back.
/// </summary>
public void GoBack() {
frame.GoBack();
}
/// <summary>
/// Indicates whether the navigator can navigate forward.
/// </summary>
public bool CanGoForward {
get { return frame.CanGoForward; }
}
/// <summary>
/// Indicates whether the navigator can navigate back.
/// </summary>
public bool CanGoBack {
get { return frame.CanGoBack; }
}
#if WinRT81
/// <summary>
/// Gets a collection of PageStackEntry instances representing the backward navigation history of the Frame.
/// </summary>
public IList<PageStackEntry> BackStack {
get { return frame.BackStack; }
}
/// <summary>
/// Gets a collection of PageStackEntry instances representing the forward navigation history of the Frame.
/// </summary>
public IList<PageStackEntry> ForwardStack {
get { return frame.ForwardStack; }
}
#endif
/// <summary>
/// Stores the frame navigation state in local settings if it can.
/// </summary>
/// <returns>Whether the suspension was sucessful</returns>
public bool SuspendState() {
try {
var container = GetSettingsContainer();
container.Values[FrameStateKey] = frame.GetNavigationState();
container.Values[ParameterKey] = currentParameter;
return true;
}
catch (Exception ex) {
Log.Error(ex);
}
return false;
}
/// <summary>
/// Tries to restore the frame navigation state from local settings.
/// </summary>
/// <returns>Whether the restoration of successful.</returns>
public bool ResumeState() {
var container = GetSettingsContainer();
if (!container.Values.ContainsKey(FrameStateKey))
return false;
var frameState = (string) container.Values[FrameStateKey];
currentParameter = container.Values.ContainsKey(ParameterKey) ?
container.Values[ParameterKey] :
null;
if (String.IsNullOrEmpty(frameState))
return false;
frame.SetNavigationState(frameState);
var view = frame.Content as Page;
if (view == null) {
return false;
}
BindViewModel(view);
if (Window.Current.Content != frame)
Window.Current.Content = frame;
Window.Current.Activate();
return true;
}
#if WP81
/// <summary>
/// Occurs when the user presses the hardware Back button.
/// </summary>
public event EventHandler<BackPressedEventArgs> BackPressed = delegate { };
/// <summary>
/// Occurs when the user presses the hardware Back button. Allows the handlers to cancel the default behavior.
/// </summary>
/// <param name="e">The event arguments</param>
protected virtual void OnBackPressed(BackPressedEventArgs e) {
BackPressed(this, e);
}
private void OnHardwareBackPressed(object sender, BackPressedEventArgs e) {
OnBackPressed(e);
if (e.Handled)
return;
if (CanGoBack) {
e.Handled = true;
GoBack();
}
}
#endif
private static ApplicationDataContainer GetSettingsContainer() {
return ApplicationData.Current.LocalSettings.CreateContainer("Caliburn.Micro",
ApplicationDataCreateDisposition.Always);
}
}
}
| chrisrpatterson/Caliburn.Micro | src/Caliburn.Micro.Platform/win8/INavigationService.cs | C# | mit | 16,390 |
TSLint JUnit Formatter
======================
A custom TSLint formatter for JUnit XML.
Installation
------------
```
npm install tslint-junit-formatter --save-dev
```
Usage
-----
```
tslint --formatters-dir node_modules/tslint-junit-formatter/formatters --format junit src/**/*.ts
```
| GenoLogics-OpenSource/tslint-junit-formatter | README.md | Markdown | mit | 290 |
module Minitest
module Reporters
# A reporter identical to the standard Minitest reporter except with more
# colors.
#
# Based upon Ryan Davis of Seattle.rb's Minitest (MIT License).
#
# @see https://github.com/seattlerb/minitest Minitest
class DefaultReporter < BaseReporter
include ANSI::Code
include RelativePosition
def initialize(options = {})
super
@detailed_skip = options.fetch(:detailed_skip, true)
@slow_count = options.fetch(:slow_count, 0)
@slow_suite_count = options.fetch(:slow_suite_count, 0)
@suite_times = []
@suite_start_times = {}
@fast_fail = options.fetch(:fast_fail, false)
@show_test_location = options.fetch(:location, false)
@options = options
end
def start
super
on_start
end
def on_start
puts
puts("# Running tests with run options %s:" % options[:args])
puts
end
def before_test(test)
super
print "\n#{test.class}##{test.name} " if options[:verbose]
end
def before_suite(suite)
@suite_start_times[suite] = Minitest::Reporters.clock_time
super
end
def after_suite(suite)
super
duration = suite_duration(suite)
@suite_times << [suite.name, duration]
end
def record(test)
super
on_record(test)
end
def on_record(test)
print "#{"%.2f" % test.time} = " if options[:verbose]
# Print the pass/skip/fail mark
print(if test.passed?
record_pass(test)
elsif test.skipped?
record_skip(test)
elsif test.failure
record_failure(test)
end)
# Print fast_fail information
if @fast_fail && (test.skipped? || test.failure)
print_failure(test)
end
end
def record_pass(record)
green(record.result_code)
end
def record_skip(record)
yellow(record.result_code)
end
def record_failure(record)
red(record.result_code)
end
def report
super
on_report
end
def on_report
status_line = "Finished tests in %.6fs, %.4f tests/s, %.4f assertions/s." %
[total_time, count / total_time, assertions / total_time]
puts
puts
puts colored_for(suite_result, status_line)
puts
unless @fast_fail
tests.reject(&:passed?).each do |test|
print_failure(test)
end
end
if @slow_count > 0
slow_tests = tests.sort_by(&:time).reverse.take(@slow_count)
puts
puts "Slowest tests:"
puts
slow_tests.each do |test|
puts "%.6fs %s#%s" % [test.time, test.name, test_class(test)]
end
end
if @slow_suite_count > 0
slow_suites = @suite_times.sort_by { |x| x[1] }.reverse.take(@slow_suite_count)
puts
puts "Slowest test classes:"
puts
slow_suites.each do |slow_suite|
puts "%.6fs %s" % [slow_suite[1], slow_suite[0]]
end
end
puts
print colored_for(suite_result, result_line)
puts
end
alias to_s report
def print_failure(test)
message = message_for(test)
unless message.nil? || message.strip == ''
puts
puts colored_for(result(test), message)
if @show_test_location
location = get_source_location(test)
puts "\n\n#{relative_path(location[0])}:#{location[1]}"
end
end
end
private
def relative_path(path)
Pathname.new(path).relative_path_from(Pathname.new(Dir.getwd))
end
def get_source_location(result)
if result.respond_to? :klass
result.source_location
else
result.method(result.name).source_location
end
end
def color?
return @color if defined?(@color)
@color = @options.fetch(:color) do
io.tty? && (
ENV["TERM"] =~ /^screen|color/ ||
ENV["EMACS"] == "t"
)
end
end
def green(string)
color? ? ANSI::Code.green(string) : string
end
def yellow(string)
color? ? ANSI::Code.yellow(string) : string
end
def red(string)
color? ? ANSI::Code.red(string) : string
end
def colored_for(result, string)
case result
when :fail, :error; red(string)
when :skip; yellow(string)
else green(string)
end
end
def suite_result
case
when failures > 0; :fail
when errors > 0; :error
when skips > 0; :skip
else :pass
end
end
def location(exception)
last_before_assertion = ''
exception.backtrace.reverse_each do |s|
break if s =~ /in .(assert|refute|flunk|pass|fail|raise|must|wont)/
last_before_assertion = s
end
last_before_assertion.sub(/:in .*$/, '')
end
def message_for(test)
e = test.failure
if test.skipped?
if @detailed_skip
"Skipped:\n#{test_class(test)}##{test.name} [#{location(e)}]:\n#{e.message}"
end
elsif test.error?
"Error:\n#{test_class(test)}##{test.name}:\n#{e.message}"
else
"Failure:\n#{test_class(test)}##{test.name} [#{test.failure.location}]\n#{e.class}: #{e.message}"
end
end
def result_line
'%d tests, %d assertions, %d failures, %d errors, %d skips' %
[count, assertions, failures, errors, skips]
end
def suite_duration(suite)
start_time = @suite_start_times.delete(suite)
if start_time.nil?
0
else
Minitest::Reporters.clock_time - start_time
end
end
end
end
end
| kern/minitest-reporters | lib/minitest/reporters/default_reporter.rb | Ruby | mit | 6,019 |
describe('L.esri.Layers.FeatureLayer', function () {
function createMap(){
// create container
var container = document.createElement('div');
// give container a width/height
container.setAttribute('style', 'width:500px; height: 500px;');
// add contianer to body
document.body.appendChild(container);
return L.map(container, {
minZoom: 1,
maxZoom: 19
}).setView([45.51, -122.66], 5);
}
var layer;
var map = createMap();
var features = [({
type: 'Feature',
id: 1,
geometry: {
type: 'LineString',
coordinates: [[-122, 45], [-121, 40]]
},
properties: {
time: new Date('January 1 2014').valueOf()
}
}),{
type: 'Feature',
id: 2,
geometry: {
type: 'LineString',
coordinates: [[-123, 46], [-120, 45]]
},
properties: {
time: new Date('Febuary 1 2014').valueOf()
}
}];
var multiPolygon = [({
type : 'Feature',
id: 1,
geometry: {
type: 'MultiPolygon',
coordinates: [[[[-95, 43], [-95, 50], [-90, 50], [-91, 42], [-95, 43]]], [[[-89, 42], [-89, 50], [-80, 50], [-80, 42]]]]
},
properties: {
time: new Date('Febuary 1 2014').valueOf()
}
})];
beforeEach(function(){
layer = L.esri.featureLayer('http://services.arcgis.com/mock/arcgis/rest/services/MockService/MockFeatureServer/0', {
timeField: 'time',
pointToLayer: function(feature, latlng){
return L.circleMarker(latlng);
}
}).addTo(map);
layer.createLayers(features);
});
it('should fire a createfeature event', function(done){
layer = L.esri.featureLayer('http://services.arcgis.com/mock/arcgis/rest/services/MockService/MockFeatureServer/0', {
timeField: 'time',
pointToLayer: function(feature, latlng){
return L.circleMarker(latlng);
}
}).addTo(map);
layer.on('createfeature', function(e){
expect(e.feature.id).to.equal(2);
done();
});
layer.createLayers(features);
});
it('should have an alias at L.esri.Layers.featureLayer', function(){
var layer = L.esri.Layers.featureLayer('http://services.arcgis.com/mock/arcgis/rest/services/MockService/MockFeatureServer/0');
expect(layer).to.be.an.instanceof(L.esri.Layers.FeatureLayer);
});
it('should create features on a map', function(){
expect(map.hasLayer(layer.getFeature(1))).to.equal(true);
expect(map.hasLayer(layer.getFeature(2))).to.equal(true);
});
it('should remove features on a map', function(){
layer.removeLayers([1]);
expect(map.hasLayer(layer.getFeature(1))).to.equal(false);
expect(map.hasLayer(layer.getFeature(2))).to.equal(true);
});
it('should fire a removefeature event', function(){
layer.on('removefeature', function(e){
expect(e.feature.id).to.equal(1);
});
layer.removeLayers([1]);
});
it('should add features back to a map', function(){
layer.removeLayers([1]);
layer.addLayers([1]);
expect(map.hasLayer(layer.getFeature(1))).to.equal(true);
expect(map.hasLayer(layer.getFeature(2))).to.equal(true);
});
it('should fire a addfeature event', function(){
layer.on('addfeature', function(e){
expect(e.feature.id).to.equal(1);
});
layer.removeLayers([1]);
layer.addLayers([1]);
});
it('should readd features back to a map', function(){
map.removeLayer(layer.getFeature(1));
layer.createLayers([{
type: 'Feature',
id: 1,
geometry: {
type: 'LineString',
coordinates: [[-122, 45], [-121, 40], [-121.5, 42.5]]
},
properties: {
time: new Date('January 1 2014').valueOf()
}
}]);
expect(map.hasLayer(layer.getFeature(1))).to.equal(true);
expect(layer.getFeature(1).getLatLngs().length).to.equal(3);
});
it('should not add features outside the time range', function(){
layer.setTimeRange(new Date('January 1 2014'), new Date('Febuary 1 2014'));
layer.createLayers([{
type: 'Feature',
id: 3,
geometry: {
type: 'Point',
coordinates: [-123, 47]
},
properties: {
time: new Date('March 1 2014').valueOf()
}
}]);
expect(map.hasLayer(layer.getFeature(1))).to.equal(true);
expect(map.hasLayer(layer.getFeature(2))).to.equal(true);
expect(map.hasLayer(layer.getFeature(3))).to.equal(false);
});
it('should be able to add itself to a map', function(){
layer.addTo(map);
expect(map.hasLayer(layer)).to.equal(true);
});
it('should be remove itself from a map', function(){
layer.addTo(map);
map.removeLayer(layer);
expect(map.hasLayer(layer)).to.equal(false);
});
it('should bind popups to existing features', function(){
layer.bindPopup(function(feature){
return 'ID: ' + feature.id;
});
expect(layer.getFeature(1)._popup.getContent()).to.equal('ID: 1');
expect(layer.getFeature(2)._popup.getContent()).to.equal('ID: 2');
});
it('should bind popups to new features', function(){
layer.bindPopup(function(feature){
return 'ID: ' + feature.id;
});
layer.createLayers([{
type: 'Feature',
id: 3,
geometry: {
type: 'Point',
coordinates: [-123, 46]
},
properties: {
time: new Date('Febuary 24 2014').valueOf()
}
}]);
expect(layer.getFeature(3)._popup.getContent()).to.equal('ID: 3');
});
it('should preserve popup options when binding popup to new or existing features', function(){
layer.bindPopup(function(feature){
return 'ID: ' + feature.id;
}, {minWidth: 500});
layer.createLayers([{
type: 'Feature',
id: 3,
geometry: {
type: 'Point',
coordinates: [-123, 46]
},
properties: {
time: new Date('Febuary 24 2014').valueOf()
}
}]);
expect(layer.getFeature(1)._popup.options.minWidth).to.equal(500);
expect(layer.getFeature(2)._popup.options.minWidth).to.equal(500);
expect(layer.getFeature(3)._popup.options.minWidth).to.equal(500);
});
it('should unbind popups on features', function(){
layer.bindPopup(function(feature){
return 'ID: ' + feature.id;
});
layer.unbindPopup();
expect(layer.getFeature(1)._popup).to.equal(null);
expect(layer.getFeature(2)._popup).to.equal(null);
});
it('should unbind popups on multi polygon features', function(){
layer = L.esri.featureLayer('http://services.arcgis.com/mock/arcgis/rest/services/MockService/MockFeatureServer/0', { timeField: 'time' }).addTo(map);
layer.createLayers(multiPolygon);
layer.bindPopup(function(feature){
return 'ID: ' + feature.id;
});
layer.unbindPopup();
expect(layer.getFeature(1).getLayers()[0]._popup).to.equal(null);
expect(layer.getFeature(1).getLayers()[1]._popup).to.equal(null);
});
it('should reset style on multi polygon features', function(){
layer = L.esri.featureLayer('http://services.arcgis.com/mock/arcgis/rest/services/MockService/MockFeatureServer/0', {
style: {
color: 'black'
}
}).addTo(map);
layer.createLayers(multiPolygon);
layer.setFeatureStyle(1, {
color: 'red'
});
expect(layer.getFeature(1).getLayers()[0].options.color).to.equal('red');
layer.resetStyle(1);
expect(layer.getFeature(1).getLayers()[0].options.color).to.equal('black');
});
it('should reset to default style on multi polygon features', function(){
layer = L.esri.featureLayer('http://services.arcgis.com/mock/arcgis/rest/services/MockService/MockFeatureServer/0').addTo(map);
layer.createLayers(multiPolygon);
layer.setFeatureStyle(1, {
color: 'red'
});
expect(layer.getFeature(1).getLayers()[0].options.color).to.equal('red');
layer.resetStyle(1);
expect(layer.getFeature(1).getLayers()[0].options.color).to.equal('#0033ff');
});
it('should iterate over each feature', function(){
var spy = sinon.spy();
layer.eachFeature(spy);
expect(spy.callCount).to.equal(2);
});
it('should run a function against every feature', function(){
var spy = sinon.spy();
layer = L.esri.featureLayer('http://services.arcgis.com/mock/arcgis/rest/services/MockService/MockFeatureServer/0', {
onEachFeature: spy
}).addTo(map);
layer.createLayers(features);
expect(spy.callCount).to.equal(2);
});
it('should change styles on features with an object', function(){
layer.setStyle({
color: 'red'
});
expect(layer.getFeature(1).options.color).to.equal('red');
expect(layer.getFeature(2).options.color).to.equal('red');
layer.createLayers([{
type: 'Feature',
id: 3,
geometry: {
type: 'LineString',
coordinates: [[-122, 45], [-121, 40]]
},
properties: {
time: new Date('Febuary 24 2014').valueOf()
}
}]);
expect(layer.getFeature(3).options.color).to.equal('red');
});
it('should change styles on features with a function', function(){
layer.setStyle(function(){
return {
color: 'red'
};
});
expect(layer.getFeature(1).options.color).to.equal('red');
expect(layer.getFeature(2).options.color).to.equal('red');
layer.createLayers([{
type: 'Feature',
id: 3,
geometry: {
type: 'LineString',
coordinates: [[-122, 45], [-121, 40]]
},
properties: {
time: new Date('Febuary 24 2014').valueOf()
}
}]);
expect(layer.getFeature(3).options.color).to.equal('red');
});
it('should propagate events from individual features', function(){
var spy = sinon.spy();
layer.on('click', spy);
layer.getFeature(1).fire('click', {
foo: 'bar'
});
expect(spy.getCall(0).args[0].foo).to.equal('bar');
expect(spy.getCall(0).args[0].type).to.equal('click');
});
});
| rossanag/bicimapuy | node_modules/esri-leaflet/spec/Layers/FeatureLayer/FeatureLayerSpec.js | JavaScript | mit | 9,943 |
# blues.js
MVC Framework for Node.js (ES6)
| tokovenko/blues.js | README.md | Markdown | mit | 44 |
<!doctype html>
<html lang="en" data-ng-app="Igo">
<head>
<meta charset="UTF-8">
<title>Exercício 06 - Delete</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/css/materialize.min.css">
<style>
.wrapper {
max-width: 600px;
margin: 0 auto;
}
</style>
</head>
<body data-ng-controller="UserController as User">
<section class="row wrapper">
<h1>{{ User.titulo }}</h1>
<p class="col s12">
<label>
<input type="text" data-ng-model="form.User.name" placeholder="Name">
</label>
<br>
<label>
<input type="email" data-ng-model="form.User.email" placeholder="Email">
</label>
</p>
<button data-ng-click="User.add(form.User)" class="btn btn-large green waves-effect waves-light col s12" type="submit" name="action">Add
</button>
<span data-ng-init="predicate = 'name'; reverse = true; "></span>
<table>
<thead>
<tr>
<th colspan="{{ User.keysLength + 1 }}">
<label>
<input ng-model="searchUser" placeholder="Search">
</label>
</th>
</tr>
<tr>
<th></th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="user in User.users | orderBy:predicate:reverse | filter:searchUser ">
<td>
<input type="checkbox" id="user-{{$index}}" ng-model="user.selecionado" />
<label for="user-{{$index}}"></label>
</td>
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
</tr>
</tbody>
</table>
<button data-ng-click="User.remove(User.users)" class="btn btn-large red waves-effect waves-light col s12" type="submit" name="action">Remove
</button>
</section>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script>
angular.module('Igo', [])
.controller('UserController', UserController);
function UserController() {
var vm = this;
vm.titulo = "Be MEAN - Usuários";
vm.users = [
{name: 'Igo', email: '[email protected]'}
, {name: 'Leandro', email: '[email protected]'}
, {name: 'Luis', email: '[email protected]'}
];
function getKeyLength() {
return Object.keys(angular.copy(vm.users[0])).length;
}
vm.keysLength = getKeyLength();
vm.add = add;
function add(user) {
vm.users.push(angular.copy(user));
}
vm.remove = remove;
function remove(users) {
for(user in users){
if (users[user].selecionado) {
users.splice(user, 1);
}
}
}
}
</script>
</body>
</html> | Webschool-io/be-mean-instagram-angular1-exercises | class-06/igopdm/ex06.html | HTML | mit | 2,759 |
/*
* Created by Phil on 26/11/2010.
* Copyright 2010 Two Blue Cubes Ltd. All rights reserved.
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#include "catch_reporter_bases.hpp"
#include "catch_reporter_junit.h"
#include "../internal/catch_tostring.h"
#include "../internal/catch_reporter_registrars.hpp"
#include "../internal/catch_text.h"
#include <cassert>
#include <sstream>
#include <ctime>
#include <algorithm>
namespace Catch {
namespace {
std::string getCurrentTimestamp() {
// Beware, this is not reentrant because of backward compatibility issues
// Also, UTC only, again because of backward compatibility (%z is C++11)
time_t rawtime;
std::time(&rawtime);
auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
#ifdef _MSC_VER
std::tm timeInfo = {};
gmtime_s(&timeInfo, &rawtime);
#else
std::tm* timeInfo;
timeInfo = std::gmtime(&rawtime);
#endif
char timeStamp[timeStampSize];
const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
#ifdef _MSC_VER
std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
#else
std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
#endif
return std::string(timeStamp);
}
std::string fileNameTag(const std::vector<std::string> &tags) {
auto it = std::find_if(begin(tags),
end(tags),
[] (std::string const& tag) {return tag.front() == '#'; });
if (it != tags.end())
return it->substr(1);
return std::string();
}
} // anonymous namespace
JunitReporter::JunitReporter( ReporterConfig const& _config )
: CumulativeReporterBase( _config ),
xml( _config.stream() )
{
m_reporterPrefs.shouldRedirectStdOut = true;
m_reporterPrefs.shouldReportAllAssertions = true;
}
JunitReporter::~JunitReporter() {}
std::string JunitReporter::getDescription() {
return "Reports test results in an XML format that looks like Ant's junitreport target";
}
void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
CumulativeReporterBase::testRunStarting( runInfo );
xml.startElement( "testsuites" );
}
void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
suiteTimer.start();
stdOutForSuite.clear();
stdErrForSuite.clear();
unexpectedExceptions = 0;
CumulativeReporterBase::testGroupStarting( groupInfo );
}
void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
m_okToFail = testCaseInfo.okToFail();
}
bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
unexpectedExceptions++;
return CumulativeReporterBase::assertionEnded( assertionStats );
}
void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
stdOutForSuite += testCaseStats.stdOut;
stdErrForSuite += testCaseStats.stdErr;
CumulativeReporterBase::testCaseEnded( testCaseStats );
}
void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
double suiteTime = suiteTimer.getElapsedSeconds();
CumulativeReporterBase::testGroupEnded( testGroupStats );
writeGroup( *m_testGroups.back(), suiteTime );
}
void JunitReporter::testRunEndedCumulative() {
xml.endElement();
}
void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
TestGroupStats const& stats = groupNode.value;
xml.writeAttribute( "name", stats.groupInfo.name );
xml.writeAttribute( "errors", unexpectedExceptions );
xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
xml.writeAttribute( "tests", stats.totals.assertions.total() );
xml.writeAttribute( "hostname", "tbd" ); // !TBD
if( m_config->showDurations() == ShowDurations::Never )
xml.writeAttribute( "time", "" );
else
xml.writeAttribute( "time", suiteTime );
xml.writeAttribute( "timestamp", getCurrentTimestamp() );
// Write properties if there are any
if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
auto properties = xml.scopedElement("properties");
if (m_config->hasTestFilters()) {
xml.scopedElement("property")
.writeAttribute("name", "filters")
.writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
}
if (m_config->rngSeed() != 0) {
xml.scopedElement("property")
.writeAttribute("name", "random-seed")
.writeAttribute("value", m_config->rngSeed());
}
}
// Write test cases
for( auto const& child : groupNode.children )
writeTestCase( *child );
xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), XmlFormatting::Newline );
xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), XmlFormatting::Newline );
}
void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
TestCaseStats const& stats = testCaseNode.value;
// All test cases have exactly one section - which represents the
// test case itself. That section may have 0-n nested sections
assert( testCaseNode.children.size() == 1 );
SectionNode const& rootSection = *testCaseNode.children.front();
std::string className = stats.testInfo.className;
if( className.empty() ) {
className = fileNameTag(stats.testInfo.tags);
if ( className.empty() )
className = "global";
}
if ( !m_config->name().empty() )
className = m_config->name() + "." + className;
writeSection( className, "", rootSection );
}
void JunitReporter::writeSection( std::string const& className,
std::string const& rootName,
SectionNode const& sectionNode ) {
std::string name = trim( sectionNode.stats.sectionInfo.name );
if( !rootName.empty() )
name = rootName + '/' + name;
if( !sectionNode.assertions.empty() ||
!sectionNode.stdOut.empty() ||
!sectionNode.stdErr.empty() ) {
XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
if( className.empty() ) {
xml.writeAttribute( "classname", name );
xml.writeAttribute( "name", "root" );
}
else {
xml.writeAttribute( "classname", className );
xml.writeAttribute( "name", name );
}
xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
writeAssertions( sectionNode );
if( !sectionNode.stdOut.empty() )
xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), XmlFormatting::Newline );
if( !sectionNode.stdErr.empty() )
xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), XmlFormatting::Newline );
}
for( auto const& childNode : sectionNode.childSections )
if( className.empty() )
writeSection( name, "", *childNode );
else
writeSection( className, name, *childNode );
}
void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
for( auto const& assertion : sectionNode.assertions )
writeAssertion( assertion );
}
void JunitReporter::writeAssertion( AssertionStats const& stats ) {
AssertionResult const& result = stats.assertionResult;
if( !result.isOk() ) {
std::string elementName;
switch( result.getResultType() ) {
case ResultWas::ThrewException:
case ResultWas::FatalErrorCondition:
elementName = "error";
break;
case ResultWas::ExplicitFailure:
elementName = "failure";
break;
case ResultWas::ExpressionFailed:
elementName = "failure";
break;
case ResultWas::DidntThrowException:
elementName = "failure";
break;
// We should never see these here:
case ResultWas::Info:
case ResultWas::Warning:
case ResultWas::Ok:
case ResultWas::Unknown:
case ResultWas::FailureBit:
case ResultWas::Exception:
elementName = "internalError";
break;
}
XmlWriter::ScopedElement e = xml.scopedElement( elementName );
xml.writeAttribute( "message", result.getExpression() );
xml.writeAttribute( "type", result.getTestMacroName() );
ReusableStringStream rss;
if (stats.totals.assertions.total() > 0) {
rss << "FAILED" << ":\n";
if (result.hasExpression()) {
rss << " ";
rss << result.getExpressionInMacro();
rss << '\n';
}
if (result.hasExpandedExpression()) {
rss << "with expansion:\n";
rss << Column(result.getExpandedExpression()).indent(2) << '\n';
}
} else {
rss << '\n';
}
if( !result.getMessage().empty() )
rss << result.getMessage() << '\n';
for( auto const& msg : stats.infoMessages )
if( msg.type == ResultWas::Info )
rss << msg.message << '\n';
rss << "at " << result.getSourceInfo();
xml.writeText( rss.str(), XmlFormatting::Newline );
}
}
CATCH_REGISTER_REPORTER( "junit", JunitReporter )
} // end namespace Catch
| SoundMetrics/aris-integration-sdk | submodules/Catch2/include/reporters/catch_reporter_junit.cpp | C++ | mit | 10,708 |
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M5 17h14v2H5v-2zm7-12L5.33 15h13.34L12 5z" />
, 'EjectSharp');
| kybarg/material-ui | packages/material-ui-icons/src/EjectSharp.js | JavaScript | mit | 183 |
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>InPlaceEditor</title><link rel="stylesheet" type="text/css" href="demo.css">
<script type="text/javascript" src="../mootools.js"></script>
<script type="text/javascript" src="../mootools/Element.Data.js"></script>
<script type="text/javascript" src="../Source/InPlaceEditor.js"></script>
<script type="text/javascript" src="../Source/InPlaceEditor.Delegation.js"></script><script type="text/javascript">
//<![CDATA[ window.addEvent('domready', function () { new InPlaceEditor.Delegation('form',{
relay: '.text',
property: 'text',
onChange: function () { console.log(arguments)
}
});
new InPlaceEditor.Delegation('form', {
relay: '.html',
property: 'html',
onChange: function () {
console.log(arguments)
}
});
})
//]]></script>
</head><body>
<form action="" method="get">
<div class="text">edit text</div>
<div class="text">edit text too</div>
<div class="html"><span>edit HTML</span></div>
<div class="html"><span>edit HTML too</span></div>
</form>
</body></html> | tbela99/InPlaceEditor | Demos/index-delegation.html | HTML | mit | 1,225 |
// action.type 常量
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
export const CLEAR_NUM = 'CLEAR_NUM';
export const TOGGLE_ALERT = 'TOGGLE_ALERT';
export const REQUEST_DATA = 'REQUEST_DATA';
export const RECEIVE_DATA = 'RECEIVE_DATA';
export const FETCH_DATA = 'FETCH_DATA';
export const FETCH_DATA_FAILED = 'FETCH_DATA_FAILED';
export const TOGGLE_ALERT_ASYNC = 'TOGGLE_ALERT_ASYNC';
| JackZhangXL/react-redux | src/reactReduxSaga/configs/action.js | JavaScript | mit | 418 |
#include "chain_kv_tests.hpp"
#include <boost/filesystem.hpp>
using chain_kv::bytes;
using chain_kv::to_slice;
BOOST_AUTO_TEST_SUITE(view_tests)
void view_test(bool reload_session) {
boost::filesystem::remove_all("view-test-session-db");
chain_kv::database db{ "view-test-session-db", true };
chain_kv::undo_stack undo_stack{ db, { 0x10 } };
std::unique_ptr<chain_kv::write_session> session;
std::unique_ptr<chain_kv::view> view;
auto reload = [&] {
if (session && reload_session) {
session->write_changes(undo_stack);
view = nullptr;
session = nullptr;
}
if (!session)
session = std::make_unique<chain_kv::write_session>(db);
if (!view)
view = std::make_unique<chain_kv::view>(*session, bytes{ 0x70 });
};
reload();
BOOST_REQUIRE_EQUAL(get_matching(*view, 0x1234), (kv_values{}));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0x1234), get_matching2(*view, 0x1234));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0x5678), (kv_values{}));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0x5678), get_matching2(*view, 0x5678));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0x9abc), (kv_values{}));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0x9abc), get_matching2(*view, 0x9abc));
view->set(0x1234, to_slice({ 0x30, 0x40 }), to_slice({ 0x50, 0x60 }));
view->set(0x5678, to_slice({ 0x30, 0x71 }), to_slice({ 0x59, 0x69 }));
view->set(0x5678, to_slice({ 0x30, 0x00 }), to_slice({ 0x59, 0x69 }));
view->set(0x5678, to_slice({ 0x30, 0x42 }), to_slice({ 0x55, 0x66 }));
view->set(0x5678, to_slice({ 0x30, 0x41 }), to_slice({ 0x51, 0x61 }));
view->set(0x9abc, to_slice({ 0x30, 0x42 }), to_slice({ 0x52, 0x62 }));
reload();
BOOST_REQUIRE_EQUAL(get_matching(*view, 0x1234), (kv_values{ {
{ { 0x30, 0x40 }, { 0x50, 0x60 } },
} }));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0x1234), get_matching2(*view, 0x1234));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0x5678), (kv_values{ {
{ { 0x30, 0x00 }, { 0x59, 0x69 } },
{ { 0x30, 0x41 }, { 0x51, 0x61 } },
{ { 0x30, 0x42 }, { 0x55, 0x66 } },
{ { 0x30, 0x71 }, { 0x59, 0x69 } },
} }));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0x5678), get_matching2(*view, 0x5678));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0x9abc), (kv_values{ {
{ { 0x30, 0x42 }, { 0x52, 0x62 } },
} }));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0x9abc), get_matching2(*view, 0x9abc));
view->erase(0x5678, to_slice({ 0x30, 0x00 }));
view->erase(0x5678, to_slice({ 0x30, 0x71 }));
view->erase(0x5678, to_slice({ 0x30, 0x42 }));
reload();
BOOST_REQUIRE_EQUAL(get_matching(*view, 0x1234), (kv_values{ {
{ { 0x30, 0x40 }, { 0x50, 0x60 } },
} }));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0x1234), get_matching2(*view, 0x1234));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0x5678), (kv_values{ {
{ { 0x30, 0x41 }, { 0x51, 0x61 } },
} }));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0x5678), get_matching2(*view, 0x5678));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0x9abc), (kv_values{ {
{ { 0x30, 0x42 }, { 0x52, 0x62 } },
} }));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0x9abc), get_matching2(*view, 0x9abc));
{
chain_kv::view::iterator it{ *view, 0x5678, {} };
it.lower_bound({ 0x30, 0x22 });
BOOST_REQUIRE_EQUAL(get_it(it), (kv_values{ {
{ { 0x30, 0x41 }, { 0x51, 0x61 } },
} }));
view->set(0x5678, to_slice({ 0x30, 0x22 }), to_slice({ 0x55, 0x66 }));
BOOST_REQUIRE_EQUAL(get_it(it), (kv_values{ {
{ { 0x30, 0x41 }, { 0x51, 0x61 } },
} }));
it.lower_bound({ 0x30, 0x22 });
BOOST_REQUIRE_EQUAL(get_it(it), (kv_values{ {
{ { 0x30, 0x22 }, { 0x55, 0x66 } },
} }));
view->set(0x5678, to_slice({ 0x30, 0x22 }), to_slice({ 0x00, 0x11 }));
BOOST_REQUIRE_EQUAL(get_it(it), (kv_values{ {
{ { 0x30, 0x22 }, { 0x00, 0x11 } },
} }));
view->erase(0x5678, to_slice({ 0x30, 0x22 }));
KV_REQUIRE_EXCEPTION(it.get_kv(), "kv iterator is at an erased value");
KV_REQUIRE_EXCEPTION(--it, "kv iterator is at an erased value");
KV_REQUIRE_EXCEPTION(++it, "kv iterator is at an erased value");
view->set(0x5678, to_slice({ 0x30, 0x22 }), to_slice({}));
KV_REQUIRE_EXCEPTION(it.get_kv(), "kv iterator is at an erased value");
it.lower_bound({ 0x30, 0x22 });
BOOST_REQUIRE_EQUAL(get_it(it), (kv_values{ {
{ { 0x30, 0x22 }, {} },
} }));
view->set(0x5678, to_slice({ 0x30, 0x22 }), to_slice({ 0x00 }));
BOOST_REQUIRE_EQUAL(get_it(it), (kv_values{ {
{ { 0x30, 0x22 }, { 0x00 } },
} }));
view->erase(0x5678, to_slice({ 0x30, 0x22 }));
KV_REQUIRE_EXCEPTION(it.get_kv(), "kv iterator is at an erased value");
}
reload();
{
chain_kv::view::iterator it{ *view, 0xbeefbeef, {} };
view->set(0xbeefbeef, to_slice({ (char)0x80 }), to_slice({ (char)0xff }));
view->set(0xbeefbeef, to_slice({ (char)0x90 }), to_slice({ (char)0xfe }));
view->set(0xbeefbeef, to_slice({ (char)0xa0 }), to_slice({ (char)0xfd }));
view->set(0xbeefbeef, to_slice({ (char)0xb0 }), to_slice({ (char)0xfc }));
it.lower_bound({});
BOOST_REQUIRE_EQUAL(get_it(it), (kv_values{ {
{ { (char)0x80 }, { (char)0xff } },
} }));
it.lower_bound({ (char)0x80 });
BOOST_REQUIRE_EQUAL(get_it(it), (kv_values{ {
{ { (char)0x80 }, { (char)0xff } },
} }));
it.lower_bound({ (char)0x81 });
BOOST_REQUIRE_EQUAL(get_it(it), (kv_values{ {
{ { (char)0x90 }, { (char)0xfe } },
} }));
it.lower_bound({ (char)0x90 });
BOOST_REQUIRE_EQUAL(get_it(it), (kv_values{ {
{ { (char)0x90 }, { (char)0xfe } },
} }));
--it;
BOOST_REQUIRE_EQUAL(get_it(it), (kv_values{ {
{ { (char)0x80 }, { (char)0xff } },
} }));
++it;
++it;
BOOST_REQUIRE_EQUAL(get_it(it), (kv_values{ {
{ { (char)0xa0 }, { (char)0xfd } },
} }));
view->erase(0xbeefbeef, to_slice({ (char)0x90 }));
--it;
BOOST_REQUIRE_EQUAL(get_it(it), (kv_values{ {
{ { (char)0x80 }, { (char)0xff } },
} }));
view->erase(0xbeefbeef, to_slice({ (char)0xa0 }));
++it;
BOOST_REQUIRE_EQUAL(get_it(it), (kv_values{ {
{ { (char)0xb0 }, { (char)0xfc } },
} }));
}
reload();
BOOST_REQUIRE_EQUAL(get_matching(*view, 0xbeefbeef), (kv_values{ {
{ { (char)0x80 }, { (char)0xff } },
{ { (char)0xb0 }, { (char)0xfc } },
} }));
view->set(0xf00df00d, to_slice({ 0x10, 0x20, 0x00 }), to_slice({ (char)0x70 }));
view->set(0xf00df00d, to_slice({ 0x10, 0x20, 0x01 }), to_slice({ (char)0x71 }));
view->set(0xf00df00d, to_slice({ 0x10, 0x20, 0x02 }), to_slice({ (char)0x72 }));
view->set(0xf00df00d, to_slice({ 0x10, 0x30, 0x00 }), to_slice({ (char)0x70 }));
view->set(0xf00df00d, to_slice({ 0x10, 0x30, 0x01 }), to_slice({ (char)0x71 }));
view->set(0xf00df00d, to_slice({ 0x10, 0x30, 0x02 }), to_slice({ (char)0x72 }));
view->set(0xf00df00d, to_slice({ 0x20, 0x00 }), to_slice({ (char)0x70 }));
view->set(0xf00df00d, to_slice({ 0x20, 0x01 }), to_slice({ (char)0x71 }));
view->set(0xf00df00d, to_slice({ 0x20, 0x02 }), to_slice({ (char)0x72 }));
reload();
BOOST_REQUIRE_EQUAL(get_matching(*view, 0xf00df00d, { 0x10, 0x20 }), (kv_values{ {
{ { 0x10, 0x20, 0x00 }, { 0x70 } },
{ { 0x10, 0x20, 0x01 }, { 0x71 } },
{ { 0x10, 0x20, 0x02 }, { 0x72 } },
} }));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0xf00df00d, { 0x10, 0x20 }),
get_matching2(*view, 0xf00df00d, { 0x10, 0x20 }));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0xf00df00d, { 0x10, 0x30 }), (kv_values{ {
{ { 0x10, 0x30, 0x00 }, { 0x70 } },
{ { 0x10, 0x30, 0x01 }, { 0x71 } },
{ { 0x10, 0x30, 0x02 }, { 0x72 } },
} }));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0xf00df00d, { 0x10, 0x30 }),
get_matching2(*view, 0xf00df00d, { 0x10, 0x30 }));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0xf00df00d, { 0x10 }), (kv_values{ {
{ { 0x10, 0x20, 0x00 }, { 0x70 } },
{ { 0x10, 0x20, 0x01 }, { 0x71 } },
{ { 0x10, 0x20, 0x02 }, { 0x72 } },
{ { 0x10, 0x30, 0x00 }, { 0x70 } },
{ { 0x10, 0x30, 0x01 }, { 0x71 } },
{ { 0x10, 0x30, 0x02 }, { 0x72 } },
} }));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0xf00df00d, { 0x10 }), get_matching2(*view, 0xf00df00d, { 0x10 }));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0xf00df00d, { 0x20 }), (kv_values{ {
{ { 0x20, 0x00 }, { 0x70 } },
{ { 0x20, 0x01 }, { 0x71 } },
{ { 0x20, 0x02 }, { 0x72 } },
} }));
BOOST_REQUIRE_EQUAL(get_matching(*view, 0xf00df00d, { 0x20 }), get_matching2(*view, 0xf00df00d, { 0x20 }));
} // view_test()
BOOST_AUTO_TEST_CASE(test_view) {
view_test(false);
view_test(true);
}
BOOST_AUTO_TEST_SUITE_END();
| EOSIO/eos | libraries/chain_kv/unit_tests/view_tests.cpp | C++ | mit | 12,189 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConvFMML.Data.MML.Command.MXDRV
{
public class MXDRVTempo : Tempo
{
public MXDRVTempo(int value, MMLCommandRelation relation) : base(value, relation) { }
protected override string GenerateString(Settings settings, SoundModule module)
{
return "t" + Value;
}
}
}
| rerrahkr/ConvFMML | ConvFMML/ConvFMML/Data/MML/Command/MXDRV/MXDRVTempo.cs | C# | mit | 449 |
---
layout: post
title: Play! meetup recap
date: '2013-07-12T09:18:00-04:00'
tags:
- scala
- async
- playnyc
tumblr_url: http://tech.gilt.com/post/55256473782/play-meetup-recap
---
<div><img src="http://media.tumblr.com/274d531c0ffe54d82a034450d710df33/tumblr_inline_mpsl29xF4y1qz4rgp.jpg"/>
</div>
<p>On Wednesday, around 70 Play framework enthusiasts visited Gilt’s 2 Park Ave. office in NYC for the <a href="http://www.meetup.com/Play-NYC/" target="_blank">Play NYC</a> meetup group’s “Async Coding in Play and Scala” talk, featuring LinkedIn engineer Jim Brikman. To add to our <a href="http://tech.gilt.com/2013/07/10/async-coding-in-play-with-both-java-and-scala" target="_blank">earlier post</a> about the meetup: Jim’s discussion of Play’s non-blocking IO nature.</p>
<ul><li>Seeing identical Play-powered functionality implemented in both Java and Scala highlighted how much more efficient and concise Scala is.</li>
<li>Play and Scala are a great match, especially when it comes to async coding, mostly due to functions being first-class citizens, and having access to great syntax “candy” such as sequence comprehensions.</li>
<li>If you are stuck in Javaland but want to write more async code and not drown in boilerplate, check out <a href="https://github.com/linkedin/parseq" target="_blank">ParSeq</a>.</li>
</ul><p>Check out the slides from Jim’s talk <a href="http://www.slideshare.net/brikis98/play-framework-async-io-with-java-and-scala" target="_blank">here</a>.</p>
| nataliab/tech-blog | _posts/tumblr/2013-07-12-play-meetup-recap.html | HTML | mit | 1,543 |
'use strict';
describe('Preference Service', function () {
// load the service's module
beforeEach(module('ngDataflow'));
// instantiate service
var Preferences;
beforeEach(inject(function (_Preferences_) {
Preferences = _Preferences_;
}));
it('should do something', function () {
expect(!!Preferences).toBe(true);
});
});
| elmarquez/ngDataflow | test/spec/services/preferences.js | JavaScript | mit | 376 |
<http://www.bitauto.com/topics/adtopic/2017_r_class/> | wangyichen1064431086/workNote | 工作业务事项/2017/26.制作新的广告页面(by 写文字)/参考页面.md | Markdown | mit | 53 |
package rescuerover.gui;
import rescuerover.gui.states.MenuScreenState;
import rescuerover.gui.states.WonGameScreenState;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class WonGameKeyListener implements KeyListener {
WonGamePanel panel;
public WonGameKeyListener(WonGamePanel wonGamePanel) {
this.panel = wonGamePanel;
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
switch (code) {
case KeyEvent.VK_LEFT:
if (panel.image == 2) {
panel.image = 1;
}
break;
case KeyEvent.VK_RIGHT:
if (panel.image == 1) {
panel.image = 2;
}
break;
case KeyEvent.VK_ENTER:
if (panel.image == 1) {
panel.wonGameScreenState.setNextState(MenuScreenState.getInstance(panel.wonGameScreenState.getFrame()));
panel.wonGameScreenState.notifyObservers();
} else if (panel.image == 2) {
panel.wonGameScreenState.setNextState(MenuScreenState.getInstance(panel.wonGameScreenState.getFrame()));
panel.wonGameScreenState.notifyObservers();
}
break;
default:
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
}
}
| ruigomeseu/rescue-rover | src/rescuerover/gui/WonGameKeyListener.java | Java | mit | 1,528 |
//
// EDComboBox.h
// Grafik Konsol
//
// Created by Todd Ditchendorf on 4/27/19.
// Copyright © 2019 Celestial Teapot. All rights reserved.
//
#import <Cocoa/Cocoa.h>
extern NSString * const EDComboBoxDidBecomeFirstResponderNotification;
extern NSString * const EDComboBoxDidResignFirstResponderNotification;
@interface EDComboBox : NSComboBox
@end
| itod/devapp | DevApp/EDComboBox.h | C | mit | 359 |
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using LamarCodeGeneration;
using LamarCodeGeneration.Frames;
using Marten.Internal.CodeGeneration;
using Marten.Linq.Parsing;
using Marten.Storage;
using Marten.Util;
using Npgsql;
using NpgsqlTypes;
using Weasel.Postgresql;
using Weasel.Postgresql.Tables;
namespace Marten.Events.Schema
{
internal class EventTableColumn: TableColumn, IEventTableColumn
{
private readonly Expression<Func<IEvent, object>> _eventMemberExpression;
private readonly MemberInfo _member;
public EventTableColumn(string name, Expression<Func<IEvent, object>> eventMemberExpression) : base(name, "varchar")
{
_eventMemberExpression = eventMemberExpression;
_member = FindMembers.Determine(eventMemberExpression).Single();
var memberType = _member.GetMemberType();
Type = TypeMappings.GetPgType(memberType, EnumStorage.AsInteger);
NpgsqlDbType = TypeMappings.ToDbType(memberType);
}
public NpgsqlDbType NpgsqlDbType { get; set; }
public void GenerateSelectorCodeSync(GeneratedMethod method, EventGraph graph, int index)
{
method.IfDbReaderValueIsNotNull(index, () =>
{
method.AssignMemberFromReader(null, index, _eventMemberExpression);
});
}
public void GenerateSelectorCodeAsync(GeneratedMethod method, EventGraph graph, int index)
{
method.IfDbReaderValueIsNotNull(index, () =>
{
method.AssignMemberFromReader(null, index, _eventMemberExpression);
});
}
public void GenerateAppendCode(GeneratedMethod method, EventGraph graph, int index)
{
method.Frames.Code($"parameters[{index}].{nameof(NpgsqlParameter.NpgsqlDbType)} = {{0}};",
NpgsqlDbType);
method.Frames.Code(
$"parameters[{index}].{nameof(NpgsqlParameter.Value)} = {{0}}.{_member.Name};", Use.Type<IEvent>());
}
}
}
| JasperFx/Marten | src/Marten/Events/Schema/EventTableColumn.cs | C# | mit | 2,099 |
package com.sl.algorithms.core.list;
import static com.sl.algorithms.core.list.ListNode.createLinkedList;
import static com.sl.algorithms.core.list.ListNode.dummyNode;
import com.sl.algorithms.core.utils.Pair;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class LLCycleDetectionTest extends CycleDetection {
private ListNode<Integer> integerListNode;
private ListNode<String> stringListNode;
@Before
public void setup() {
integerListNode = createLinkedList(new Integer[]{1, 2, 3, 4, 5});
stringListNode = createLinkedList(new String[]{"Array", "List", "Tree", "Map"});
}
@Test
public void testCycleEndPoints() {
{
Assert.assertNull(getCycleEndPoints(dummyNode()));
Assert.assertNull(getCycleEndPoints(new ListNode<>(1)));
Assert.assertNull(getCycleEndPoints(integerListNode));
Assert.assertNull(getCycleEndPoints(stringListNode));
}
{
ListNode<Integer> curr = integerListNode;
while (curr.next != null) {
curr = curr.next;
}
ListNode<Integer> cyclePoint = integerListNode.next.next;
curr.next = cyclePoint;
Pair<ListNode<Integer>, ListNode<Integer>> endPoints = getCycleEndPoints(integerListNode);
Assert.assertEquals("3", endPoints.left.data.toString());
Assert.assertEquals("5", endPoints.right.data.toString());
}
{
ListNode<String> curr = stringListNode;
while (curr.next != null) {
curr = curr.next;
}
curr.next = stringListNode;
Pair<ListNode<String>, ListNode<String>> endPoints = getCycleEndPoints(stringListNode);
Assert.assertEquals("Array", endPoints.left.data.toString());
Assert.assertEquals("Map", endPoints.right.data.toString());
}
}
}
| sachinlala/SimplifyLearning | algorithms/src/test/java/com/sl/algorithms/core/list/LLCycleDetectionTest.java | Java | mit | 1,770 |
require 'active_admin/async_panel' | holyketzer/activeadmin-async_panel | lib/activeadmin-async_panel.rb | Ruby | mit | 34 |
JS History Logger
=================
Store Logs in Local Storage or Cookies. Requires jQuery.local-storage.js
Basic Usage
-----------
~~~ coffee
# clear log history
HistoryLogger.clear()
HistoryLogger.log('A')
> Fri Aug 23 2013 15:23:45 - A
HistoryLogger.log('B')
> Fri Aug 23 2013 15:24:13 - B
HistoryLogger.log('C')
> Fri Aug 23 2013 15:25:46 - C
HistoryLogger.listAll()
> Fri Aug 23 2013 15:23:45 - A
> Fri Aug 23 2013 15:24:13 - B
> Fri Aug 23 2013 15:25:46 - C
# display last 2 logs
HistoryLogger.list(2)
> Fri Aug 23 2013 15:24:13 - B
> Fri Aug 23 2013 15:25:46 - C
# turn off logging
HistoryLogger.off()
# turn on logging
HistoryLogger.on()
~~~
Installation
------------
~~~ html
<script type='text/javascript' src='js/cross-browser-js-fixes.js'></script>
<script type='text/javascript' src='js/jquery.min.js'></script>
<script type='text/javascript' src='js/jquery.local-storage.js'></script>
<script type='text/javascript' src='js/js-history-logger.js'></script>
~~~
Acknowledgements
----------------
© 2013, Joshua Arvin Lat. Released under the [MIT License](LICENSE).
| joshua-arvin-lat/js-history-logger | README.md | Markdown | mit | 1,093 |
import logging
logger = logging.getLogger('tensorflow')
logger.setLevel(logging.WARN)
import colorlog
from colorlog import ColoredFormatter
formatter = ColoredFormatter(
"%(log_color)s%(levelname)s%(reset)s %(message)s",
datefmt=None,
reset=True,
log_colors={
'DEBUG': 'blue',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'red,bg_white',
},
secondary_log_colors={},
style='%'
)
logger = colorlog.getLogger('tensorprob')
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
from . import config
from . import utilities
from . import distributions
from .distribution import Distribution, DistributionError, Region
from .model import Model, ModelError
from .parameter import Parameter
from .distributions import *
from .optimizers import *
from .samplers import *
| ibab/tensorprob | tensorprob/__init__.py | Python | mit | 935 |
<html>
<head>
<script type="text/javascript" src="../js/webgldiagdata.js"></script>
<script type="text/javascript" src="../js/webgldiagnostic.js"></script>
<script type="text/javascript">
function main() {
var i = WebGLDiagnostic.report('test-canvas');
var r = document.getElementById('webgl-report');
var dl= document.getElementById('driverlink');
var d = WebGLDiagnostic.detectDriver('test-canvas');
if (d==null) { dl.innerHTML=""; }
else { dl.href=d.v; dl.innerHTML=dl.innerHTML+" ("+d.label+")"}
r.innerHTML = i;
}
</script>
</head>
<body onload="main()">
<canvas id="test-canvas" style="display: none" width="1"
height="1"></canvas>
<a href="" id="driverlink">Update Your Video Card Drivers</a>
<pre id="webgl-report"></pre>
</body>
</html>
| ashima/webgl-diagnostic | example/report.html | HTML | mit | 763 |
# frozen_string_literal: true
# Rake 11+ has a misfeature where @warning = true by default
# See https://github.com/ruby/rake/pull/97/files
# This causes all tests to be run with `ruby -w`, causing a huge number of warnings
# from gems we don't control and overwhelming our test output.
# This patch reverts that.
_ = Rake::TestTask
class Rake::TestTask
module SetWarningFalseMixin
def initialize(*args)
super
self.warning = false
end
end
prepend SetWarningFalseMixin
end
| Invoca/exception_handling | spec/rake_test_warning_false.rb | Ruby | mit | 502 |
//
// NSString+HLSExtensions.h
// CoconutKit
//
// Created by Samuel Défago on 11/3/10.
// Copyright 2010 Hortis. All rights reserved.
//
// Formatting functions
NSString *HLSStringFromCATransform3D(CATransform3D transform);
@interface NSString (HLSExtensions)
/**
* Trims spaces left and right
*/
- (NSString *)stringByTrimmingWhitespaces;
/**
* Returns NO if the string is empty or only made of whitespaces
*/
- (BOOL)isFilled;
/**
* URL encoded (aka percent encoded) string with RFC 3986 compliance
* See http://www.openradar.me/6546984
*/
- (NSString *)urlEncodedStringUsingEncoding:(NSStringEncoding)encoding;
/**
* Calculates the MD2 hash of a string (hexadecimal)
*/
- (NSString *)md2hash;
/**
* Calculates the MD4 hash of a string (hexadecimal)
*/
- (NSString *)md4hash;
/**
* Calculates the MD5 hash of a string (hexadecimal)
*/
- (NSString *)md5hash;
/**
* Calculates the SHA-1 hash of a string (hexadecimal)
*/
- (NSString *)sha1hash;
/**
* Calculates the SHA-224 hash of a string (hexadecimal)
*/
- (NSString *)sha224hash;
/**
* Calculates the SHA-256 hash of a string (hexadecimal)
*/
- (NSString *)sha256hash;
/**
* Calculates the SHA-384 hash of a string (hexadecimal)
*/
- (NSString *)sha384hash;
/**
* Calculates the SHA-512 hash of a string (hexadecimal)
*/
- (NSString *)sha512hash;
/**
* At Hortis, we use a convenient way to identify versions during development, for tags and for official releases:
* - For all versions except AppStore releases: [lastVersionNumber+]versionNumber[+qualifier]
* - For AppStore releases: versionNumber
* where:
* - lastVersionNumber is the most recent tagged version (if any)
* - versionNumber is a version number. We use several formats:
* x.x[.x[.x]] represents "standard" versions
* x.x[.x[.x]]+bN represents the N-th beta for version x.x[.x[.x]]
* x.x[.x[.x]]+rcN represents the N-th release candidate for version x.x[.x[.x]]
* This ordering works because it matches the alphabetical ordering.
* - qualifier is either:
* dev for development versions (trunk). This qualifier is never to be used for tags
* test for tagged versions used with test environments (e.g. test servers)
* Examples are:
* 0.8 version 0.8
* 0.8+dev trunk, last tagged version was 0.8
* 0.9+1.0b1 first beta for version 1.0, last tagged version was 0.9
* 0.9+1.0b1+dev trunk, last tagged version was 0.9+1.0b1
* 0.9+1.0rc2 second release candidate for version 1.0, last taggged version was 0.9
* 1.0 version 1.0; this might for example be an AppStore release
* 1.0+test test version 1.0
*
* This convention is well suited for version number ordering with the AppStore and iTunes, but can be difficult
* to understand for users. The following method is used to convert a string into the corresponding user-friendly
* version number:
* - for versions with dev or test qualifier, return the full version number
* - for versions without qualifier, only returns the version number (only the rightmost version number).
* In the examples above, we get respectively:
* 0.8
* 0.8+dev
* 1.0b1
* 0.9+1.0b1+dev
* 1.0rc2
* 1.0
* 1.0+test
*/
- (NSString *)friendlyVersionNumber;
@end
| defagos/CoconutKit-binaries | CoconutKit.framework/Headers/NSString+HLSExtensions.h | C | mit | 3,482 |
module.exports = require('./plugin').default;
| maltsev/gulp-htmlnano | index.js | JavaScript | mit | 46 |
///////////////////////////////////////////////////////////////////////
// Doubly Linked List Testbench
//
// This file implements an onboard testbench for the the
// doubly_linked_list module. It includes support for input via
// tracefiles from the SD card or local storage, a primitive heap
// validator to check for memory leaks, and tee-like functionality to
// allow simultaneous output to both the screen and a file.
//
// All code is provided as-is, for the students to use at their own
// risk. This system will not be used for grading, but is intended to
// give the students some framework for testing their code.
//
// Author: Connor Lawson, GEORGIA INSTITUTE OF TECHNOLOGY, FALL 2016
///////////////////////////////////////////////////////////////////////
/*
#include "testbench.h"
#include "globals.h"
#include "doubly_linked_list.h"
#include <mbed.h>
#include <stdarg.h>
#include <ctype.h>
//////////////////////
// Memory monitoring
//////////////////////
struct heap_info_t
{
const char* HighestAllocBlock;
const char* HighestFreeBlock;
unsigned long TotalAlloc;
unsigned long TotalFree;
};
static int heap_parse_line(void* pvHeapInfo, char const* pFormatString, ...);
#define GET_HEAP_INFO(info) memset((void*)&info, 0, sizeof(heap_info_t)); \
__heapvalid(heap_parse_line, &info, 1);
#define START_HEAP_TRACE() heap_info_t start_heap, current_heap; \
GET_HEAP_INFO(start_heap);
#define UPDATE_HEAP_TRACE() GET_HEAP_INFO(current_heap);
#define START_HEAP_ALLOC() (start_heap.TotalAlloc)
#define CURRENT_HEAP_ALLOC() (current_heap.TotalAlloc)
#define NET_HEAP_ALLOC() (CURRENT_HEAP_ALLOC() - START_HEAP_ALLOC())
/** Parses the output of __heapvalid line by line to extract structured data.
* This function is the workshorse of the GET_HEAP_INFO macro.
* Modified from an example found here:
* https://developer.mbed.org/forum/mbed/topic/2702/?page=1#comment-13895
static int heap_parse_line(void* pvHeapInfo, char const* pFormatString, ...)
{
static const char* pAllocFormatString = "alloc block %p size %3lx";
static const char* pFreeFormatString = "free block %p size %3lx next=%p";
static const char* pCompleteFormatString = "------- heap validation complete";
heap_info_t* pHeapInfo = (heap_info_t*)pvHeapInfo;
va_list valist;
va_start(valist, pFormatString);
if (pFormatString == strstr(pFormatString, pAllocFormatString))
{
const char* pBlock = va_arg(valist, const char*);
unsigned long BlockSize = va_arg(valist, unsigned long);
const char* pBlockLastByte = pBlock + BlockSize - 1;
if (pBlockLastByte > pHeapInfo->HighestAllocBlock)
{
pHeapInfo->HighestAllocBlock = pBlockLastByte;
}
pHeapInfo->TotalAlloc += BlockSize;
}
else if (pFormatString == strstr(pFormatString, pFreeFormatString))
{
const char* pBlock = va_arg(valist, const char*);
unsigned long BlockSize = va_arg(valist, unsigned long);
const char* pBlockLastByte = pBlock + BlockSize - 1;
if (pBlockLastByte > pHeapInfo->HighestFreeBlock)
{
pHeapInfo->HighestFreeBlock = pBlockLastByte;
}
pHeapInfo->TotalFree += BlockSize;
}
else if (pFormatString == strstr(pFormatString, pCompleteFormatString))
{
// Ignoring end of dump string.
}
else
{
// Unrecognized format string.
printf("Unrecognized format of %s", pFormatString);
}
return 1;
}
static void demo_heap_monitoring() {
// Make sure stdout is already allocated or the stream buffer will show up
// in the heap allocations
printf("Start heap monitoring demo\n");
START_HEAP_TRACE();
printf("Heap trace at start:\n");
__heapvalid((__heapprt)fprintf, stdout, 1);
printf("Total allocation: %d\n", START_HEAP_ALLOC());
printf("Allocating 10 32-byte buffers...\n");
void* a[10];
for(int i = 0; i < 10; i++)
a[i] = malloc(32*i);
printf("Heap trace after allocation:\n");
UPDATE_HEAP_TRACE();
__heapvalid((__heapprt)fprintf, stdout, 1);
printf("Measured allocation: %x\r\n", NET_HEAP_ALLOC());
printf("Free all 32-byte buffers...\n");
for(int i = 0; i < 10; i++)
free(a[i]);
printf("Heap trace after free:\n");
UPDATE_HEAP_TRACE();
__heapvalid((__heapprt)fprintf, stdout, 1);
printf("Measured allocation after free: %x\r\n", NET_HEAP_ALLOC());
}
//////////////////////////////
// Test bench implementation
//////////////////////////////
static void tee(FILE* fp, const char* format, ...)
{
va_list args1, args2;
va_start( args1, format );
va_copy ( args2, args1 );
vprintf( format, args1 );
if (fp)
vfprintf(fp, format, args2 );
va_end( args2 );
va_end( args1 );
}
static void test_createdestroy(FILE* outfile)
{
START_HEAP_TRACE();
int result = 1;
DLinkedList* list = create_dlinkedlist();
if (list != NULL)
destroyList(list, 1);
else
result = 0;
// Check for memory leak
UPDATE_HEAP_TRACE();
result &= (NET_HEAP_ALLOC() == 0);
tee(outfile, "Create/destroy test (check for memory leak): %s\n", (result)?"SUCCESS":"FAIL");
}
static void test_shouldFree(FILE* outfile)
{
START_HEAP_TRACE();
int result = 1;
// Allocate data
void* data = malloc(2048);
if (data == NULL)
{
tee(outfile, "shouldFree test (check for memory leak): %s\n", "malloc failed!");
return;
}
// Create list, add data to list
DLinkedList* dll = create_dlinkedlist();
if (dll != NULL)
{
// Add data to list
insertHead(dll, data);
// Destroy list (shouldFree = 1)
destroyList(dll, 1);
// Check that the data and list were both deleted
UPDATE_HEAP_TRACE();
result &= (NET_HEAP_ALLOC() == 0);
tee(outfile, "shouldFree test (check for memory leak): %s\n", (result)?"SUCCESS":"FAIL");
}
else
{
result = 0;
}
// Clean up if something went wrong
if (!result) free(data);
}
static void ignore_whitespace(FILE* fp)
{
int c = fgetc(fp);
while (c != '\n' && isspace(c)) c = fgetc(fp);
ungetc(c, fp);
}
static void ignore_comment(FILE* fp)
{
// Check if there's a comment here
int c = fgetc(fp);
if (c != '%') {
ungetc(c, fp);
return;
}
// There is a comment!
// Read until the newline, but don't consume it
while(c != '\n') c = fgetc(fp);
ungetc(c, fp);
}
static void skip_inconsequential(FILE* fp)
{
ignore_whitespace(fp);
ignore_comment(fp);
}
enum Token {
NEWLINE = -1,
INSERT_HEAD = -2,
INSERT_TAIL = -3,
INSERT_AFTER = -4,
INSERT_AFTER_SHOULD_FAIL = -5,
INSERT_BEFORE = -6,
INSERT_BEFORE_SHOULD_FAIL = -7,
DELETE_FORWARD = -8,
DELETE_BACKWARD = -9,
GET_HEAD = -10,
GET_TAIL = -11,
GET_CURRENT = -12,
GET_NEXT = -13,
GET_PREVIOUS = -14,
GET_SIZE = -15,
CHECK_LIST = -16,
CLEAR_LIST = -17,
END_OF_TRACE = -18,
PARSE_ERROR = 0xFFFF // Make sure we get a whole 16 bits to use here
};
static Token get_next_token(FILE* fp)
{
int c, sc, tc;
skip_inconsequential(fp);
c = fgetc(fp);
switch (c)
{
case '\n': return NEWLINE;
case 'i':
sc = fgetc(fp);
switch (sc)
{
case 'h': return INSERT_HEAD;
case 't': return INSERT_TAIL;
case 'a':
tc = fgetc(fp);
if (tc == 'f')
{
return INSERT_AFTER_SHOULD_FAIL;
}
else
{
ungetc(tc, fp);
return INSERT_AFTER;
}
case 'b':
tc = fgetc(fp);
if (tc == 'f')
{
return INSERT_BEFORE_SHOULD_FAIL;
}
else
{
ungetc(tc, fp);
return INSERT_BEFORE;
}
default: return PARSE_ERROR;
}
case 'd':
sc = fgetc(fp);
switch (sc)
{
case 'f': return DELETE_FORWARD;
case 'b': return DELETE_BACKWARD;
default: return PARSE_ERROR;
}
case 'h': return GET_HEAD;
case 't': return GET_TAIL;
case 'c': return GET_CURRENT;
case 'n': return GET_NEXT;
case 'p': return GET_PREVIOUS;
case 's': return GET_SIZE;
case 'e': return CHECK_LIST;
case 'r': return CLEAR_LIST;
case EOF: return END_OF_TRACE;
default:
// Check to make sure this is actually a value, not an error...
if (!isdigit(c)) return PARSE_ERROR;
// Read the value
int value = 0;
while (isdigit(c)) {
// Accumulate an integer
value *= 10;
value += (c - '0');
// Read next char
c = fgetc(fp);
}
// Don't consume the last character -- it wasn't a digit
ungetc(c, fp);
return (Token)value;
}
}
static void parse_trace(FILE* out, FILE* trace)
{
// Parser state
Token current_command = NEWLINE;
int line = 1;
// Initialize list for testing
DLinkedList *dll = create_dlinkedlist();
// Execute tests
Token next = get_next_token(trace);
while (next != END_OF_TRACE)
{
if (next == PARSE_ERROR)
{
// Error condition, warn and quit
tee(out, "Parse error on line %d! Aborting.\r\n", line);
break;
}
else if (next == NEWLINE)
{
//tee("Newline\n");
line++;
}
else if (next < 0)
{
current_command = next;
// Some commands don't take arguments. Execute immediately
if (current_command == CLEAR_LIST)
{
tee(out, "--- Clear List ---\n");
destroyList(dll, 0);
dll = create_dlinkedlist();
}
}
else // Every time we have a value (argument)
{
int result = 0;
switch(current_command)
{
case INSERT_HEAD:
tee(out, "insertHead(%d)", (int)next);
if (next != 0) {
insertHead(dll, (void*)next);
tee(out, "\n");
}
else
{
tee(out, ": Cowardly refusing to insert 0\n");
}
break;
case INSERT_TAIL:
tee(out, "insertTail(%d)", (int)next);
if (next != 0) {
insertTail(dll, (void*)next);
tee(out, "\n");
}
else
{
tee(out, ": Cowardly refusing to insert 0\n");
}
break;
case INSERT_AFTER_SHOULD_FAIL:
tee(out, "[SHOULD FAIL] ");
// Fallthrough
case INSERT_AFTER:
tee(out, "insertAfter(%d)", (int)next);
if (next != 0) {
result = insertAfter(dll, (void*)next);
tee(out, ": %s\n", (result)?"SUCCESS":"FAIL");
}
else
{
tee(out, ": Cowardly refusing to insert 0\n");
}
break;
case INSERT_BEFORE_SHOULD_FAIL:
tee(out, "[SHOULD FAIL] ");
// Fallthrough
case INSERT_BEFORE:
tee(out, "insertBefore(%d)", (int)next);
if (next != 0) {
result = insertBefore(dll, (void*)next);
tee(out, ": %s\n", (result)?"SUCCESS":"FAIL");
}
else
{
tee(out, ": Cowardly refusing to insert 0\n");
}
break;
case DELETE_FORWARD:
result = deleteForward(dll, 0) == (void*)next;
tee(out, "deleteForward() == %d: %s\n", (int)next, (result)?"SUCCESS":"FAIL");
break;
case DELETE_BACKWARD:
result = deleteBackward(dll, 0) == (void*)next;
tee(out, "deleteBackward() == %d: %s\n", (int)next, (result)?"SUCCESS":"FAIL");
break;
case GET_HEAD:
result = (getHead(dll) == (void*)next);
tee(out, "getHead() == %d: %s\n", (int)next, (result)?"SUCCESS":"FAIL");
break;
case GET_TAIL:
result = (getTail(dll) == (void*)next);
tee(out, "getTail() == %d: %s\n", (int)next, (result)?"SUCCESS":"FAIL");
break;
case GET_CURRENT:
result = (getCurrent(dll) == (void*)next);
tee(out, "getCurrent() == %d: %s\n", (int)next, (result)?"SUCCESS":"FAIL");
break;
case GET_NEXT:
result = (getNext(dll) == (void*)next);
tee(out, "getNext() == %d: %s\n", (int)next, (result)?"SUCCESS":"FAIL");
break;
case GET_PREVIOUS:
result = (getPrevious(dll) == (void*)next);
tee(out, "getPrevious() == %d: %s\n", (int)next, (result)?"SUCCESS":"FAIL");
break;
case GET_SIZE:
result = (getSize(dll) == (int)next);
tee(out, "getSize() == %d: %s\n", (int)next, (result)?"SUCCESS":"FAIL");
break;
case CHECK_LIST:
{
tee(out, "Check list: ");
int correct = 1;
int length = 0;
void* val = getHead(dll);
while ((int)next > 0) // Only read values
{
correct &= (val == (void*)next);
tee(out, "%d ", (int)val);
length++;
val = getNext(dll);
next = get_next_token(trace);
}
correct &= (getSize(dll) == length);
tee(out, ": %s\n", (correct)?"SUCCESS":"FAIL");
// Continue here allows proper parsing of next token at the
// top of the loop
continue;
}
}
}
// Don't forget to grab the next token!
next = get_next_token(trace);
}
tee(out, "End of trace\n");
// Clean up list
destroyList(dll, 0);
}
void test_tracefile(FILE* out, const char* tracefile)
{
tee(out, "Beginning trace of file %s\n", tracefile);
FILE* trace = fopen(tracefile, "r");
if (trace == NULL)
{
tee(out, "Could not open file! Abort.\n");
return;
}
parse_trace(out, trace);
// Close file
fclose(trace);
}
void test_dlinkedlist(const char* tracefile, const char* outfile)
{
//demo_heap_monitoring();
// Open output file
FILE* out = NULL;
if (outfile != NULL)
out = fopen(outfile, "w");
// Check if it worked
if (out == NULL)
printf("WARNING: Output to screen only!\n");
else
printf("Output will be saved to file: %s\n", outfile);
// Run the tests
test_createdestroy(out);
test_shouldFree(out);
test_tracefile(out, tracefile);
// Clean up
if (outfile != NULL)
fclose(out);
}
*/
| harrisonstatham/HSMissileCommand | HSMissileCommand/testbench.cpp | C++ | mit | 16,820 |
// Warehouse
// A typical abandoned warehouse that anarchists hang out in and can be bribed to burn down Buildings.
// DO NOT MODIFY THIS FILE
// Never try to directly create an instance of this class, or modify its member variables.
// Instead, you should only be reading its variables and calling its functions.
#include "warehouse.hpp"
#include "../../joueur/src/base_ai.hpp"
#include "../../joueur/src/any.hpp"
#include "../../joueur/src/exceptions.hpp"
#include "../../joueur/src/delta.hpp"
#include "building.hpp"
#include "fire_department.hpp"
#include "forecast.hpp"
#include "game_object.hpp"
#include "player.hpp"
#include "police_department.hpp"
#include "warehouse.hpp"
#include "weather_station.hpp"
#include "impl/anarchy.hpp"
#include <type_traits>
namespace cpp_client
{
namespace anarchy
{
} // anarchy
} // cpp_client
| siggame/Joueur.cpp | games/anarchy/warehouse.cpp | C++ | mit | 844 |
---
layout: post
title: 'But You Forgot About: Five Easy Pieces'
category: posts
---
<a href="http://www.avclub.com/content/home">The A.V. Club</a> loves lists. Previously a subsection of The Onion, The A.V. Club has since come into its own producing a pretty overwhelming number of critiques and feature articles, most of which come down to lists of songs or movies centered around a specific topic.
To coincide with the release of Wes Anderson's _The Darjeeling Limited_, The A.V. Club put two lists up: "<a href="http://www.avclub.com/content/feature/16_films_without_which_wes">16 Films Without Which Wes Anderson Couldn't Have Happened</a>" and "<a href="http://www.avclub.com/content/feature/10_films_that_couldnt_have">10 Films That Couldn't Have Happened Without Wes Anderson</a>."
The first list, films predating Wes Anderson, sprung to mind as I finished Jack Nicholson's _Five Easy Pieces_. Including it in a list of films necessary for the existence of Wes Anderson might be drawing too strong a thread of causality from one to the next, but I couldn't help seeing shades of Wes Anderson, especially _The Royal Tenenbaums_, through the entire movie.
Maybe there's universal appeal to the story of a son who flees his socially dysfunctional family of post-upper class savants, especially driven away by the impossibly distant father figure at its head, and goes in search of something different, something other. (<a href="http://en.wikipedia.org/wiki/Monomyth">Monomyth</a>, possibly?)
Even so, the minor characters have quirks and unsettling misbehaviors that add more to the movie than just advancing Nicholson's reassociation with his family. Does the brother need to be wearing a neck brace throughout? Probably not, and it's in those quick details that the similarities to Wes Anderson stick out. At the same time those quick little pieces of life infuse the movie with a greater life, and elevate well beyond the other more standard late-60s paeans to the counterculture.
I'm not sure this should be as highly regarded as it is, but it can't hurt to use this clip here to highlight the movie's most famous scene:
<div align="center">
<object><param name="movie" value="http://www.youtube.com/v/6wtfNE4z6a8&rel=1"></param><param name="wmode" value="transparent"></param><embed class="center" src="http://www.youtube.com/v/6wtfNE4z6a8&rel=1" type="application/x-shockwave-flash" wmode="transparent" width="600" height="400"></embed></object>
</div> | IanWhalen/ianwhalen.github.io | _posts/2007-11-01-but-you-forgot-about-five-easy-pieces.markdown | Markdown | mit | 2,477 |
@charset "UTF-8";
.clear {
clear: both;
display: block;
overflow: hidden;
visibility: hidden;
width: 0;
height: 0;
}
.grid-container:before, .clearfix:before,
.grid-container:after,
.clearfix:after {
content: ".";
display: block;
overflow: hidden;
visibility: hidden;
font-size: 0;
line-height: 0;
width: 0;
height: 0;
}
.grid-container:after, .clearfix:after {
clear: both;
}
.grid-container {
max-width: 1080px;
position: relative;
}
.grid-5, .mobile-grid-5, .grid-10, .mobile-grid-10, .grid-15, .mobile-grid-15, .grid-20, .mobile-grid-20, .grid-25, .mobile-grid-25, .grid-30, .mobile-grid-30, .grid-35, .mobile-grid-35, .grid-40, .mobile-grid-40, .grid-45, .mobile-grid-45, .grid-50, .mobile-grid-50, .grid-55, .mobile-grid-55, .grid-60, .mobile-grid-60, .grid-65, .mobile-grid-65, .grid-70, .mobile-grid-70, .grid-75, .mobile-grid-75, .grid-80, .mobile-grid-80, .grid-85, .mobile-grid-85, .grid-90, .mobile-grid-90, .grid-95, .mobile-grid-95, .grid-100, .mobile-grid-100, .grid-33, .mobile-grid-33, .grid-66, .mobile-grid-66 {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding-left: 15px;
padding-right: 15px;
}
.grid-parent {
padding-left: 0;
padding-right: 0;
}
body {
min-width: 320px;
}
@media screen {
.clear {
clear: both;
display: block;
overflow: hidden;
visibility: hidden;
width: 0;
height: 0;
}
.grid-container:before, .clearfix:before,
.grid-container:after,
.clearfix:after {
content: ".";
display: block;
overflow: hidden;
visibility: hidden;
font-size: 0;
line-height: 0;
width: 0;
height: 0;
}
.grid-container:after, .clearfix:after {
clear: both;
}
.grid-container {
max-width: 1080px;
position: relative;
}
.grid-5, .mobile-grid-5, .grid-10, .mobile-grid-10, .grid-15, .mobile-grid-15, .grid-20, .mobile-grid-20, .grid-25, .mobile-grid-25, .grid-30, .mobile-grid-30, .grid-35, .mobile-grid-35, .grid-40, .mobile-grid-40, .grid-45, .mobile-grid-45, .grid-50, .mobile-grid-50, .grid-55, .mobile-grid-55, .grid-60, .mobile-grid-60, .grid-65, .mobile-grid-65, .grid-70, .mobile-grid-70, .grid-75, .mobile-grid-75, .grid-80, .mobile-grid-80, .grid-85, .mobile-grid-85, .grid-90, .mobile-grid-90, .grid-95, .mobile-grid-95, .grid-100, .mobile-grid-100, .grid-33, .mobile-grid-33, .grid-66, .mobile-grid-66, .tablet-grid-5, .tablet-grid-10, .tablet-grid-15, .tablet-grid-20, .tablet-grid-25, .tablet-grid-30, .tablet-grid-35, .tablet-grid-40, .tablet-grid-45, .tablet-grid-50, .tablet-grid-55, .tablet-grid-60, .tablet-grid-65, .tablet-grid-70, .tablet-grid-75, .tablet-grid-80, .tablet-grid-85, .tablet-grid-90, .tablet-grid-95, .tablet-grid-100, .tablet-grid-33, .tablet-grid-66 {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding-left: 15px;
padding-right: 15px;
}
.grid-parent {
padding-left: 0;
padding-right: 0;
}
body {
min-width: 320px;
}
}
@media screen and (min-width: 1080px) {
.clear {
clear: both;
display: block;
overflow: hidden;
visibility: hidden;
width: 0;
height: 0;
}
.grid-container:before, .grid-100:before, .clearfix:before,
.grid-container:after,
.grid-100:after,
.clearfix:after {
content: ".";
display: block;
overflow: hidden;
visibility: hidden;
font-size: 0;
line-height: 0;
width: 0;
height: 0;
}
.grid-container:after, .grid-100:after, .clearfix:after {
clear: both;
}
.grid-container {
max-width: 1080px;
position: relative;
}
.grid-5, .mobile-grid-5, .grid-10, .mobile-grid-10, .grid-15, .mobile-grid-15, .grid-20, .mobile-grid-20, .grid-25, .mobile-grid-25, .grid-30, .mobile-grid-30, .grid-35, .mobile-grid-35, .grid-40, .mobile-grid-40, .grid-45, .mobile-grid-45, .grid-50, .mobile-grid-50, .grid-55, .mobile-grid-55, .grid-60, .mobile-grid-60, .grid-65, .mobile-grid-65, .grid-70, .mobile-grid-70, .grid-75, .mobile-grid-75, .grid-80, .mobile-grid-80, .grid-85, .mobile-grid-85, .grid-90, .mobile-grid-90, .grid-95, .mobile-grid-95, .grid-100, .mobile-grid-100, .grid-33, .mobile-grid-33, .grid-66, .mobile-grid-66 {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding-left: 15px;
padding-right: 15px;
}
.grid-parent {
padding-left: 0;
padding-right: 0;
}
.push-5,
.pull-5, .push-10,
.pull-10, .push-15,
.pull-15, .push-20,
.pull-20, .push-25,
.pull-25, .push-30,
.pull-30, .push-35,
.pull-35, .push-40,
.pull-40, .push-45,
.pull-45, .push-50,
.pull-50, .push-55,
.pull-55, .push-60,
.pull-60, .push-65,
.pull-65, .push-70,
.pull-70, .push-75,
.pull-75, .push-80,
.pull-80, .push-85,
.pull-85, .push-90,
.pull-90, .push-95,
.pull-95, .push-33,
.pull-33, .push-66,
.pull-66 {
position: relative;
}
.hide-on-desktop {
display: none !important;
}
.grid-5 {
float: left;
width: 5%;
}
.prefix-5 {
margin-left: 5%;
}
.suffix-5 {
margin-right: 5%;
}
.push-5 {
left: 5%;
}
.pull-5 {
left: -5%;
}
.grid-10 {
float: left;
width: 10%;
}
.prefix-10 {
margin-left: 10%;
}
.suffix-10 {
margin-right: 10%;
}
.push-10 {
left: 10%;
}
.pull-10 {
left: -10%;
}
.grid-15 {
float: left;
width: 15%;
}
.prefix-15 {
margin-left: 15%;
}
.suffix-15 {
margin-right: 15%;
}
.push-15 {
left: 15%;
}
.pull-15 {
left: -15%;
}
.grid-20 {
float: left;
width: 20%;
}
.prefix-20 {
margin-left: 20%;
}
.suffix-20 {
margin-right: 20%;
}
.push-20 {
left: 20%;
}
.pull-20 {
left: -20%;
}
.grid-25 {
float: left;
width: 25%;
}
.prefix-25 {
margin-left: 25%;
}
.suffix-25 {
margin-right: 25%;
}
.push-25 {
left: 25%;
}
.pull-25 {
left: -25%;
}
.grid-30 {
float: left;
width: 30%;
}
.prefix-30 {
margin-left: 30%;
}
.suffix-30 {
margin-right: 30%;
}
.push-30 {
left: 30%;
}
.pull-30 {
left: -30%;
}
.grid-35 {
float: left;
width: 35%;
}
.prefix-35 {
margin-left: 35%;
}
.suffix-35 {
margin-right: 35%;
}
.push-35 {
left: 35%;
}
.pull-35 {
left: -35%;
}
.grid-40 {
float: left;
width: 40%;
}
.prefix-40 {
margin-left: 40%;
}
.suffix-40 {
margin-right: 40%;
}
.push-40 {
left: 40%;
}
.pull-40 {
left: -40%;
}
.grid-45 {
float: left;
width: 45%;
}
.prefix-45 {
margin-left: 45%;
}
.suffix-45 {
margin-right: 45%;
}
.push-45 {
left: 45%;
}
.pull-45 {
left: -45%;
}
.grid-50 {
float: left;
width: 50%;
}
.prefix-50 {
margin-left: 50%;
}
.suffix-50 {
margin-right: 50%;
}
.push-50 {
left: 50%;
}
.pull-50 {
left: -50%;
}
.grid-55 {
float: left;
width: 55%;
}
.prefix-55 {
margin-left: 55%;
}
.suffix-55 {
margin-right: 55%;
}
.push-55 {
left: 55%;
}
.pull-55 {
left: -55%;
}
.grid-60 {
float: left;
width: 60%;
}
.prefix-60 {
margin-left: 60%;
}
.suffix-60 {
margin-right: 60%;
}
.push-60 {
left: 60%;
}
.pull-60 {
left: -60%;
}
.grid-65 {
float: left;
width: 65%;
}
.prefix-65 {
margin-left: 65%;
}
.suffix-65 {
margin-right: 65%;
}
.push-65 {
left: 65%;
}
.pull-65 {
left: -65%;
}
.grid-70 {
float: left;
width: 70%;
}
.prefix-70 {
margin-left: 70%;
}
.suffix-70 {
margin-right: 70%;
}
.push-70 {
left: 70%;
}
.pull-70 {
left: -70%;
}
.grid-75 {
float: left;
width: 75%;
}
.prefix-75 {
margin-left: 75%;
}
.suffix-75 {
margin-right: 75%;
}
.push-75 {
left: 75%;
}
.pull-75 {
left: -75%;
}
.grid-80 {
float: left;
width: 80%;
}
.prefix-80 {
margin-left: 80%;
}
.suffix-80 {
margin-right: 80%;
}
.push-80 {
left: 80%;
}
.pull-80 {
left: -80%;
}
.grid-85 {
float: left;
width: 85%;
}
.prefix-85 {
margin-left: 85%;
}
.suffix-85 {
margin-right: 85%;
}
.push-85 {
left: 85%;
}
.pull-85 {
left: -85%;
}
.grid-90 {
float: left;
width: 90%;
}
.prefix-90 {
margin-left: 90%;
}
.suffix-90 {
margin-right: 90%;
}
.push-90 {
left: 90%;
}
.pull-90 {
left: -90%;
}
.grid-95 {
float: left;
width: 95%;
}
.prefix-95 {
margin-left: 95%;
}
.suffix-95 {
margin-right: 95%;
}
.push-95 {
left: 95%;
}
.pull-95 {
left: -95%;
}
.grid-33 {
float: left;
width: 33.33333%;
}
.prefix-33 {
margin-left: 33.33333%;
}
.suffix-33 {
margin-right: 33.33333%;
}
.push-33 {
left: 33.33333%;
}
.pull-33 {
left: -33.33333%;
}
.grid-66 {
float: left;
width: 66.66667%;
}
.prefix-66 {
margin-left: 66.66667%;
}
.suffix-66 {
margin-right: 66.66667%;
}
.push-66 {
left: 66.66667%;
}
.pull-66 {
left: -66.66667%;
}
.grid-100 {
clear: both;
width: 100%;
}
}
@media screen and (max-width: 400px) {
@-ms-viewport {
width: 320px;
}
}
@media screen and (max-width: 680px) {
.clear {
clear: both;
display: block;
overflow: hidden;
visibility: hidden;
width: 0;
height: 0;
}
.grid-container:before, .mobile-grid-100:before, .clearfix:before,
.grid-container:after,
.mobile-grid-100:after,
.clearfix:after {
content: ".";
display: block;
overflow: hidden;
visibility: hidden;
font-size: 0;
line-height: 0;
width: 0;
height: 0;
}
.grid-container:after, .mobile-grid-100:after, .clearfix:after {
clear: both;
}
.grid-container {
max-width: 1080px;
position: relative;
}
.grid-5, .mobile-grid-5, .grid-10, .mobile-grid-10, .grid-15, .mobile-grid-15, .grid-20, .mobile-grid-20, .grid-25, .mobile-grid-25, .grid-30, .mobile-grid-30, .grid-35, .mobile-grid-35, .grid-40, .mobile-grid-40, .grid-45, .mobile-grid-45, .grid-50, .mobile-grid-50, .grid-55, .mobile-grid-55, .grid-60, .mobile-grid-60, .grid-65, .mobile-grid-65, .grid-70, .mobile-grid-70, .grid-75, .mobile-grid-75, .grid-80, .mobile-grid-80, .grid-85, .mobile-grid-85, .grid-90, .mobile-grid-90, .grid-95, .mobile-grid-95, .grid-100, .mobile-grid-100, .grid-33, .mobile-grid-33, .grid-66, .mobile-grid-66 {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding-left: 15px;
padding-right: 15px;
}
.grid-parent {
padding-left: 0;
padding-right: 0;
}
.mobile-push-5,
.mobile-pull-5, .mobile-push-10,
.mobile-pull-10, .mobile-push-15,
.mobile-pull-15, .mobile-push-20,
.mobile-pull-20, .mobile-push-25,
.mobile-pull-25, .mobile-push-30,
.mobile-pull-30, .mobile-push-35,
.mobile-pull-35, .mobile-push-40,
.mobile-pull-40, .mobile-push-45,
.mobile-pull-45, .mobile-push-50,
.mobile-pull-50, .mobile-push-55,
.mobile-pull-55, .mobile-push-60,
.mobile-pull-60, .mobile-push-65,
.mobile-pull-65, .mobile-push-70,
.mobile-pull-70, .mobile-push-75,
.mobile-pull-75, .mobile-push-80,
.mobile-pull-80, .mobile-push-85,
.mobile-pull-85, .mobile-push-90,
.mobile-pull-90, .mobile-push-95,
.mobile-pull-95, .mobile-push-33,
.mobile-pull-33, .mobile-push-66,
.mobile-pull-66 {
position: relative;
}
.hide-on-mobile {
display: none !important;
}
.mobile-grid-5 {
float: left;
width: 5%;
}
.mobile-prefix-5 {
margin-left: 5%;
}
.mobile-suffix-5 {
margin-right: 5%;
}
.mobile-push-5 {
left: 5%;
}
.mobile-pull-5 {
left: -5%;
}
.mobile-grid-10 {
float: left;
width: 10%;
}
.mobile-prefix-10 {
margin-left: 10%;
}
.mobile-suffix-10 {
margin-right: 10%;
}
.mobile-push-10 {
left: 10%;
}
.mobile-pull-10 {
left: -10%;
}
.mobile-grid-15 {
float: left;
width: 15%;
}
.mobile-prefix-15 {
margin-left: 15%;
}
.mobile-suffix-15 {
margin-right: 15%;
}
.mobile-push-15 {
left: 15%;
}
.mobile-pull-15 {
left: -15%;
}
.mobile-grid-20 {
float: left;
width: 20%;
}
.mobile-prefix-20 {
margin-left: 20%;
}
.mobile-suffix-20 {
margin-right: 20%;
}
.mobile-push-20 {
left: 20%;
}
.mobile-pull-20 {
left: -20%;
}
.mobile-grid-25 {
float: left;
width: 25%;
}
.mobile-prefix-25 {
margin-left: 25%;
}
.mobile-suffix-25 {
margin-right: 25%;
}
.mobile-push-25 {
left: 25%;
}
.mobile-pull-25 {
left: -25%;
}
.mobile-grid-30 {
float: left;
width: 30%;
}
.mobile-prefix-30 {
margin-left: 30%;
}
.mobile-suffix-30 {
margin-right: 30%;
}
.mobile-push-30 {
left: 30%;
}
.mobile-pull-30 {
left: -30%;
}
.mobile-grid-35 {
float: left;
width: 35%;
}
.mobile-prefix-35 {
margin-left: 35%;
}
.mobile-suffix-35 {
margin-right: 35%;
}
.mobile-push-35 {
left: 35%;
}
.mobile-pull-35 {
left: -35%;
}
.mobile-grid-40 {
float: left;
width: 40%;
}
.mobile-prefix-40 {
margin-left: 40%;
}
.mobile-suffix-40 {
margin-right: 40%;
}
.mobile-push-40 {
left: 40%;
}
.mobile-pull-40 {
left: -40%;
}
.mobile-grid-45 {
float: left;
width: 45%;
}
.mobile-prefix-45 {
margin-left: 45%;
}
.mobile-suffix-45 {
margin-right: 45%;
}
.mobile-push-45 {
left: 45%;
}
.mobile-pull-45 {
left: -45%;
}
.mobile-grid-50 {
float: left;
width: 50%;
}
.mobile-prefix-50 {
margin-left: 50%;
}
.mobile-suffix-50 {
margin-right: 50%;
}
.mobile-push-50 {
left: 50%;
}
.mobile-pull-50 {
left: -50%;
}
.mobile-grid-55 {
float: left;
width: 55%;
}
.mobile-prefix-55 {
margin-left: 55%;
}
.mobile-suffix-55 {
margin-right: 55%;
}
.mobile-push-55 {
left: 55%;
}
.mobile-pull-55 {
left: -55%;
}
.mobile-grid-60 {
float: left;
width: 60%;
}
.mobile-prefix-60 {
margin-left: 60%;
}
.mobile-suffix-60 {
margin-right: 60%;
}
.mobile-push-60 {
left: 60%;
}
.mobile-pull-60 {
left: -60%;
}
.mobile-grid-65 {
float: left;
width: 65%;
}
.mobile-prefix-65 {
margin-left: 65%;
}
.mobile-suffix-65 {
margin-right: 65%;
}
.mobile-push-65 {
left: 65%;
}
.mobile-pull-65 {
left: -65%;
}
.mobile-grid-70 {
float: left;
width: 70%;
}
.mobile-prefix-70 {
margin-left: 70%;
}
.mobile-suffix-70 {
margin-right: 70%;
}
.mobile-push-70 {
left: 70%;
}
.mobile-pull-70 {
left: -70%;
}
.mobile-grid-75 {
float: left;
width: 75%;
}
.mobile-prefix-75 {
margin-left: 75%;
}
.mobile-suffix-75 {
margin-right: 75%;
}
.mobile-push-75 {
left: 75%;
}
.mobile-pull-75 {
left: -75%;
}
.mobile-grid-80 {
float: left;
width: 80%;
}
.mobile-prefix-80 {
margin-left: 80%;
}
.mobile-suffix-80 {
margin-right: 80%;
}
.mobile-push-80 {
left: 80%;
}
.mobile-pull-80 {
left: -80%;
}
.mobile-grid-85 {
float: left;
width: 85%;
}
.mobile-prefix-85 {
margin-left: 85%;
}
.mobile-suffix-85 {
margin-right: 85%;
}
.mobile-push-85 {
left: 85%;
}
.mobile-pull-85 {
left: -85%;
}
.mobile-grid-90 {
float: left;
width: 90%;
}
.mobile-prefix-90 {
margin-left: 90%;
}
.mobile-suffix-90 {
margin-right: 90%;
}
.mobile-push-90 {
left: 90%;
}
.mobile-pull-90 {
left: -90%;
}
.mobile-grid-95 {
float: left;
width: 95%;
}
.mobile-prefix-95 {
margin-left: 95%;
}
.mobile-suffix-95 {
margin-right: 95%;
}
.mobile-push-95 {
left: 95%;
}
.mobile-pull-95 {
left: -95%;
}
.mobile-grid-33 {
float: left;
width: 33.33333%;
}
.mobile-prefix-33 {
margin-left: 33.33333%;
}
.mobile-suffix-33 {
margin-right: 33.33333%;
}
.mobile-push-33 {
left: 33.33333%;
}
.mobile-pull-33 {
left: -33.33333%;
}
.mobile-grid-66 {
float: left;
width: 66.66667%;
}
.mobile-prefix-66 {
margin-left: 66.66667%;
}
.mobile-suffix-66 {
margin-right: 66.66667%;
}
.mobile-push-66 {
left: 66.66667%;
}
.mobile-pull-66 {
left: -66.66667%;
}
.mobile-grid-100 {
clear: both;
width: 100%;
}
}
@media screen and (min-width: 680px) and (max-width: 1080px) {
.clear {
clear: both;
display: block;
overflow: hidden;
visibility: hidden;
width: 0;
height: 0;
}
.grid-container:before, .tablet-grid-100:before, .clearfix:before,
.grid-container:after,
.tablet-grid-100:after,
.clearfix:after {
content: ".";
display: block;
overflow: hidden;
visibility: hidden;
font-size: 0;
line-height: 0;
width: 0;
height: 0;
}
.grid-container:after, .tablet-grid-100:after, .clearfix:after {
clear: both;
}
.grid-container {
max-width: 1080px;
position: relative;
}
.grid-5, .mobile-grid-5, .grid-10, .mobile-grid-10, .grid-15, .mobile-grid-15, .grid-20, .mobile-grid-20, .grid-25, .mobile-grid-25, .grid-30, .mobile-grid-30, .grid-35, .mobile-grid-35, .grid-40, .mobile-grid-40, .grid-45, .mobile-grid-45, .grid-50, .mobile-grid-50, .grid-55, .mobile-grid-55, .grid-60, .mobile-grid-60, .grid-65, .mobile-grid-65, .grid-70, .mobile-grid-70, .grid-75, .mobile-grid-75, .grid-80, .mobile-grid-80, .grid-85, .mobile-grid-85, .grid-90, .mobile-grid-90, .grid-95, .mobile-grid-95, .grid-100, .mobile-grid-100, .grid-33, .mobile-grid-33, .grid-66, .mobile-grid-66 {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding-left: 15px;
padding-right: 15px;
}
.grid-parent {
padding-left: 0;
padding-right: 0;
}
.tablet-push-5,
.tablet-pull-5, .tablet-push-10,
.tablet-pull-10, .tablet-push-15,
.tablet-pull-15, .tablet-push-20,
.tablet-pull-20, .tablet-push-25,
.tablet-pull-25, .tablet-push-30,
.tablet-pull-30, .tablet-push-35,
.tablet-pull-35, .tablet-push-40,
.tablet-pull-40, .tablet-push-45,
.tablet-pull-45, .tablet-push-50,
.tablet-pull-50, .tablet-push-55,
.tablet-pull-55, .tablet-push-60,
.tablet-pull-60, .tablet-push-65,
.tablet-pull-65, .tablet-push-70,
.tablet-pull-70, .tablet-push-75,
.tablet-pull-75, .tablet-push-80,
.tablet-pull-80, .tablet-push-85,
.tablet-pull-85, .tablet-push-90,
.tablet-pull-90, .tablet-push-95,
.tablet-pull-95, .tablet-push-33,
.tablet-pull-33, .tablet-push-66,
.tablet-pull-66 {
position: relative;
}
.hide-on-tablet {
display: none !important;
}
.tablet-grid-5 {
float: left;
width: 5%;
}
.tablet-prefix-5 {
margin-left: 5%;
}
.tablet-suffix-5 {
margin-right: 5%;
}
.tablet-push-5 {
left: 5%;
}
.tablet-pull-5 {
left: -5%;
}
.tablet-grid-10 {
float: left;
width: 10%;
}
.tablet-prefix-10 {
margin-left: 10%;
}
.tablet-suffix-10 {
margin-right: 10%;
}
.tablet-push-10 {
left: 10%;
}
.tablet-pull-10 {
left: -10%;
}
.tablet-grid-15 {
float: left;
width: 15%;
}
.tablet-prefix-15 {
margin-left: 15%;
}
.tablet-suffix-15 {
margin-right: 15%;
}
.tablet-push-15 {
left: 15%;
}
.tablet-pull-15 {
left: -15%;
}
.tablet-grid-20 {
float: left;
width: 20%;
}
.tablet-prefix-20 {
margin-left: 20%;
}
.tablet-suffix-20 {
margin-right: 20%;
}
.tablet-push-20 {
left: 20%;
}
.tablet-pull-20 {
left: -20%;
}
.tablet-grid-25 {
float: left;
width: 25%;
}
.tablet-prefix-25 {
margin-left: 25%;
}
.tablet-suffix-25 {
margin-right: 25%;
}
.tablet-push-25 {
left: 25%;
}
.tablet-pull-25 {
left: -25%;
}
.tablet-grid-30 {
float: left;
width: 30%;
}
.tablet-prefix-30 {
margin-left: 30%;
}
.tablet-suffix-30 {
margin-right: 30%;
}
.tablet-push-30 {
left: 30%;
}
.tablet-pull-30 {
left: -30%;
}
.tablet-grid-35 {
float: left;
width: 35%;
}
.tablet-prefix-35 {
margin-left: 35%;
}
.tablet-suffix-35 {
margin-right: 35%;
}
.tablet-push-35 {
left: 35%;
}
.tablet-pull-35 {
left: -35%;
}
.tablet-grid-40 {
float: left;
width: 40%;
}
.tablet-prefix-40 {
margin-left: 40%;
}
.tablet-suffix-40 {
margin-right: 40%;
}
.tablet-push-40 {
left: 40%;
}
.tablet-pull-40 {
left: -40%;
}
.tablet-grid-45 {
float: left;
width: 45%;
}
.tablet-prefix-45 {
margin-left: 45%;
}
.tablet-suffix-45 {
margin-right: 45%;
}
.tablet-push-45 {
left: 45%;
}
.tablet-pull-45 {
left: -45%;
}
.tablet-grid-50 {
float: left;
width: 50%;
}
.tablet-prefix-50 {
margin-left: 50%;
}
.tablet-suffix-50 {
margin-right: 50%;
}
.tablet-push-50 {
left: 50%;
}
.tablet-pull-50 {
left: -50%;
}
.tablet-grid-55 {
float: left;
width: 55%;
}
.tablet-prefix-55 {
margin-left: 55%;
}
.tablet-suffix-55 {
margin-right: 55%;
}
.tablet-push-55 {
left: 55%;
}
.tablet-pull-55 {
left: -55%;
}
.tablet-grid-60 {
float: left;
width: 60%;
}
.tablet-prefix-60 {
margin-left: 60%;
}
.tablet-suffix-60 {
margin-right: 60%;
}
.tablet-push-60 {
left: 60%;
}
.tablet-pull-60 {
left: -60%;
}
.tablet-grid-65 {
float: left;
width: 65%;
}
.tablet-prefix-65 {
margin-left: 65%;
}
.tablet-suffix-65 {
margin-right: 65%;
}
.tablet-push-65 {
left: 65%;
}
.tablet-pull-65 {
left: -65%;
}
.tablet-grid-70 {
float: left;
width: 70%;
}
.tablet-prefix-70 {
margin-left: 70%;
}
.tablet-suffix-70 {
margin-right: 70%;
}
.tablet-push-70 {
left: 70%;
}
.tablet-pull-70 {
left: -70%;
}
.tablet-grid-75 {
float: left;
width: 75%;
}
.tablet-prefix-75 {
margin-left: 75%;
}
.tablet-suffix-75 {
margin-right: 75%;
}
.tablet-push-75 {
left: 75%;
}
.tablet-pull-75 {
left: -75%;
}
.tablet-grid-80 {
float: left;
width: 80%;
}
.tablet-prefix-80 {
margin-left: 80%;
}
.tablet-suffix-80 {
margin-right: 80%;
}
.tablet-push-80 {
left: 80%;
}
.tablet-pull-80 {
left: -80%;
}
.tablet-grid-85 {
float: left;
width: 85%;
}
.tablet-prefix-85 {
margin-left: 85%;
}
.tablet-suffix-85 {
margin-right: 85%;
}
.tablet-push-85 {
left: 85%;
}
.tablet-pull-85 {
left: -85%;
}
.tablet-grid-90 {
float: left;
width: 90%;
}
.tablet-prefix-90 {
margin-left: 90%;
}
.tablet-suffix-90 {
margin-right: 90%;
}
.tablet-push-90 {
left: 90%;
}
.tablet-pull-90 {
left: -90%;
}
.tablet-grid-95 {
float: left;
width: 95%;
}
.tablet-prefix-95 {
margin-left: 95%;
}
.tablet-suffix-95 {
margin-right: 95%;
}
.tablet-push-95 {
left: 95%;
}
.tablet-pull-95 {
left: -95%;
}
.tablet-grid-33 {
float: left;
width: 33.33333%;
}
.tablet-prefix-33 {
margin-left: 33.33333%;
}
.tablet-suffix-33 {
margin-right: 33.33333%;
}
.tablet-push-33 {
left: 33.33333%;
}
.tablet-pull-33 {
left: -33.33333%;
}
.tablet-grid-66 {
float: left;
width: 66.66667%;
}
.tablet-prefix-66 {
margin-left: 66.66667%;
}
.tablet-suffix-66 {
margin-right: 66.66667%;
}
.tablet-push-66 {
left: 66.66667%;
}
.tablet-pull-66 {
left: -66.66667%;
}
.tablet-grid-100 {
clear: both;
width: 100%;
}
}
.clear {
clear: both;
display: block;
overflow: hidden;
visibility: hidden;
width: 0;
height: 0;
}
.grid-container:before, .clearfix:before,
.grid-container:after,
.clearfix:after {
content: ".";
display: block;
overflow: hidden;
visibility: hidden;
font-size: 0;
line-height: 0;
width: 0;
height: 0;
}
.grid-container:after, .clearfix:after {
clear: both;
}
.grid-container {
max-width: 1080px;
position: relative;
}
.grid-5, .mobile-grid-5, .grid-10, .mobile-grid-10, .grid-15, .mobile-grid-15, .grid-20, .mobile-grid-20, .grid-25, .mobile-grid-25, .grid-30, .mobile-grid-30, .grid-35, .mobile-grid-35, .grid-40, .mobile-grid-40, .grid-45, .mobile-grid-45, .grid-50, .mobile-grid-50, .grid-55, .mobile-grid-55, .grid-60, .mobile-grid-60, .grid-65, .mobile-grid-65, .grid-70, .mobile-grid-70, .grid-75, .mobile-grid-75, .grid-80, .mobile-grid-80, .grid-85, .mobile-grid-85, .grid-90, .mobile-grid-90, .grid-95, .mobile-grid-95, .grid-100, .mobile-grid-100, .grid-33, .mobile-grid-33, .grid-66, .mobile-grid-66 {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding-left: 15px;
padding-right: 15px;
}
.grid-parent {
padding-left: 0;
padding-right: 0;
}
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font: inherit;
font-size: 100%;
vertical-align: baseline;
}
html {
line-height: 1;
}
ol, ul {
list-style: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
caption, th, td {
text-align: left;
font-weight: normal;
vertical-align: middle;
}
q, blockquote {
quotes: none;
}
q:before, q:after, blockquote:before, blockquote:after {
content: "";
content: none;
}
a img {
border: none;
}
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section, summary {
display: block;
}
body {
background: #edeff0;
padding: 50px 0 0;
font-family: "Varela Round", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 62.5%;
}
.centered {
margin: 0 auto;
}
.contained {
background: white;
padding: 30px 15px;
margin-bottom: 30px;
position: relative;
overflow: hidden;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
-ms-border-radius: 5px;
-o-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 1px 0 0 rgba(0, 0, 0, 0.1);
-moz-box-shadow: 0 1px 0 0 rgba(0, 0, 0, 0.1);
box-shadow: 0 1px 0 0 rgba(0, 0, 0, 0.1);
}
.heading {
margin-bottom: 20px;
}
h1,
h2 {
font-size: 2.4em;
font-weight: 500;
margin-bottom: 8px;
color: #384047;
line-height: 1.2;
}
h2 {
font-size: 1.8em;
}
aside h2 {
margin-bottom: 15px;
}
p, label {
color: #8d9aa5;
font-size: 1.4em;
margin-bottom: 15px;
line-height: 1.4;
}
a {
color: #3f8abf;
line-height: 1.4;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
ul li {
margin: 15px 0 0;
font-size: 1.6em;
color: #8d9aa5;
position: relative;
}
ul.rooms {
margin-bottom: 30px;
}
ul.rooms li {
font-size: 1em;
display: inline-block;
width: 10%;
padding: 3px 2px 2px;
border-radius: 2px;
margin: 0 3px 3px 3px;
color: white;
text-align: center;
}
ul.rooms li.empty {
background-color: #5fcf80;
}
ul.rooms li.full {
background-color: #ed5a5a;
}
ul.bulleted {
margin-bottom: 20px;
}
ul.bulleted li {
padding-left: 40px;
}
ul.bulleted li:before {
position: absolute;
top: 0;
left: 0;
color: white;
font-size: .5em;
padding: 3px 2px 2px;
border-radius: 2px;
text-align:center;
width: 25px;
}
ul.bulleted .in {
color: #5A6772;
}
ul.bulleted .in:before {
content: "IN";
background-color: #5fcf80;
}
ul.bulleted .out {
color: #A7B4BF;
}
ul.bulleted .out:before {
content: "OUT";
background-color: #ed5a5a;
}
ul.filter-select {
display: table;
table-layout: fixed;
width: 100%;
background: #edeff0;
overflow: hidden;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
-ms-border-radius: 5px;
-o-border-radius: 5px;
border-radius: 5px;
}
ul.filter-select li {
margin: 0;
padding: 0;
text-align: center;
display: table-cell;
}
ul.filter-select li:before {
display: none;
}
ul.filter-select button {
width: 100%;
text-align: center;
background: none;
border: none;
outline: none;
padding: 15px;
margin: 0;
font-family: "Varela Round", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
font-weight: 500;
cursor: pointer;
position: relative;
-webkit-transition: 0.3s;
-moz-transition: 0.3s;
-o-transition: 0.3s;
transition: 0.3s;
}
ul.filter-select button:hover:after, ul.filter-select button.selected:after, li:last-child ul.filter-select button:after {
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0);
opacity: 0;
}
ul.filter-select button:hover {
background: #dfe3e4;
}
ul.filter-select button.selected {
background: #d1d6d9;
}
ul.filter-select button:after {
content: "";
display: block;
position: absolute;
right: -1px;
top: 15px;
bottom: 15px;
width: 1px;
background: #d1d6d9;
}
#photos li {
margin: 30px 0 0;
vertical-align: middle;
}
#photos li:before {
display: none;
}
#photos .image {
display: block;
min-height: 240px;
background: #edeff0;
text-align: center;
height: 260px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
-ms-border-radius: 5px;
-o-border-radius: 5px;
border-radius: 5px;
-webkit-transition: 0.3s;
-moz-transition: 0.3s;
-o-transition: 0.3s;
transition: 0.3s;
}
#photos .image:hover {
background: #dfe3e4;
}
#photos .image:before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
}
#photos img {
max-width: 80%;
max-height: 200px;
vertical-align: middle;
-webkit-box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.2);
-moz-box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.2);
box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.2);
}
.button {
background: #3f8abf;
padding: 8px 18px;
font-family: "Varela Round", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 1.4em;
color: white;
font-weight: 500;
border: 3px solid #3f8abf;
outline: none;
cursor: pointer;
display: -moz-inline-stack;
display: inline-block;
vertical-align: middle;
*vertical-align: auto;
zoom: 1;
*display: inline;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
-ms-border-radius: 5px;
-o-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 2px 0 0 #3574a0;
-moz-box-shadow: 0 2px 0 0 #3574a0;
box-shadow: 0 2px 0 0 #3574a0;
-webkit-transition: 0.3s;
-moz-transition: 0.3s;
-o-transition: 0.3s;
transition: 0.3s;
}
.button:hover {
background: #397cac;
border-color: #397cac;
-webkit-box-shadow: 0 2px 0 0 #2c6085;
-moz-box-shadow: 0 2px 0 0 #2c6085;
box-shadow: 0 2px 0 0 #2c6085;
}
.selected {
background: #397cac;
border-color: #397cac;
-webkit-box-shadow: 0 2px 0 0 #2c6085;
-moz-box-shadow: 0 2px 0 0 #2c6085;
box-shadow: 0 2px 0 0 #2c6085;
}
.response {
padding: 30px;
background: #fbfbfc;
border: 1px solid #e2e5e8;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
-ms-border-radius: 5px;
-o-border-radius: 5px;
border-radius: 5px;
}
.response p {
margin: 0;
}
footer p {
color: #b2bac2;
font-size: 1.15em;
margin: 0;
}
input[type=search] {
font-size: 2em;
}
| estermer/ericstermer.com | css/flikr.css | CSS | mit | 32,072 |
//add new data
function add_user_form(){
console.log('add_user');
$.ajax({
type:"POST",
url:"../php/process_student.php",
data:$("#add_user_form").serialize(),
success:function(data){
//close modal
$(".close").trigger("click");
//show result
alert(data);
//reload page
location.reload();
}
});
return false;
}
//show data for edit
function show_edit_user(sid){
$.ajax({
type:"POST",
url:"../php/process_student.php",
data:{show_user_id:sid},
success:function(data){
$("#edit_form").html(data);
}
});
return false;
}
//edit data
function edit_user_form(){
$.ajax({
type:"POST",
url:"../php/process_student.php",
data:$("#edit_user_form").serialize(),
success:function(data){
//close modal
$(".close").trigger("click");
//show result
alert(data);
//reload page
location.reload();
}
});
return false;
}
//delete user
function delete_user(id){
if(confirm("คุณต้องการลบข้อมูลหรือไม่")){
$.ajax({
type:"POST",
url:"../php/process_student.php",
data:{delete_user_id:id},
success:function(data){
alert(data);
location.reload();
}
});
}
return false;
} | joesoftheart/Sahakit | script/script_student.js | JavaScript | mit | 1,538 |
foo {
a: 4e2px;
b: 5e-2px;
c: 603px;
d: 3.07px;
}
| xzyfer/sass-spec | spec/libsass-closed-issues/issue_2465/expected_output.css | CSS | mit | 58 |
<?php if (validation_errors()): ?>
<div class="alert alert-danger text-capitalize">
<?php echo validation_errors(); ?>
</div>
<?php endif ?>
<?php echo form_open('users/register'); ?>
<div class="row">
<div class="col-sm-12">
<div class="card">
<div class="card-header">
<strong>Register New Investor</strong>
<small>Form</small>
</div>
<div class="card-body">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" placeholder="Name">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" name="email" placeholder="Email">
</div>
<div class="form-group">
<label>Phone</label>
<input type="number" class="form-control" name="number" placeholder="Number">
</div>
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" name="username" placeholder="Username">
</div>
<div class="form-group">
<label>VISA Card Number</label>
<input type="text" class="form-control" name="visacard" placeholder="Visa Card Number">
</div>
<?php if ($this->session->userdata('logged_in') && ($this->session->userdata('user_type') == 'admin' || $this->session->userdata('user_type') == 'superadmin' )): ?>
<div class="form-group">
<div class="radio">
<label>
<input type="radio" name="user_type" id="user" value="client" checked>
Register Client account
</label>
</div>
</div>
<?php endif ?>
</div>
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-sm btn-primary"><i class="fa fa-dot-circle-o"></i> Submit</button>
</div>
</div>
</div>
</div>
<?php echo form_close(); ?>
| Kantnathan/pursaPortal | application/views/users/register.php | PHP | mit | 2,409 |
policies = -> {
%w(UserPolicy RolePolicy RecipePolicy GroceryPolicy)
}
FactoryGirl.define do
factory :role do
sequence(:name, 0) { |n| "Role_#{n}" }
sequence(:display_name, 0) { |n| "Role_#{n}" }
end
factory :guest_role, class: Role do
name "brewmaster_padawan"
display_name "Brewmaster Padawan"
trait :with_permissions do
after(:create) do |role, evaluator|
policies.call.each do |policy|
unless %w(RolePolicy GroceryPolicy).include?(policy)
actions = if policy == "UserPolicy"
%w(show? update?)
else
%w(index? show?)
end
actions.each do |action|
policy_scope = "owner?" if %w(show? update?).include?(action) && policy == "UserPolicy"
create(:role_permission,
role: role,
name: action,
policy_name: policy,
policy_scope: policy_scope)
end
end
end
end
end
end
factory :user_role, class: Role do
name "brewmaster_jedi"
display_name "Brewmaster Jedi"
trait :with_permissions do
after(:create) do |role, evaluator|
policies.call.each do |policy|
unless %w(RolePolicy GroceryPolicy).include?(policy)
actions = if policy == "UserPolicy"
%w(show? update?)
else
%w(index? show? create? update? destroy?)
end
actions.each do |action|
policy_scope_required = (policy == "UserPolicy" && %w(show? update?).include?(action)) ||
%w(update? destroy?).include?(action)
policy_scope = "owner?" if policy_scope_required
create(:role_permission,
role: role,
name: action,
policy_name: policy,
policy_scope: policy_scope)
end
end
end
end
end
end
factory :admin_role, class: Role do
name "brewmaster_yoda"
display_name "Brewmaster Yoda"
trait :with_permissions do
after(:create) do |role, evaluator|
policies.call.each do |policy|
%w(index? show? create? update? destroy?).each do |action|
create(:role_permission,
role: role,
name: action,
policy_name: policy)
end
end
end
end
end
end
| bhuskic/star_brewars | spec/factories/roles.rb | Ruby | mit | 2,595 |
---
permalink: /teach/
title: "Teaching"
excerpt: "Courses I teach."
last_modified_at: 2017-06-02T14:28:13-05:00
feature_row:
- image_path: assets/images/HD1.png
- image_path: /assets/images/HD2.png
- image_path: /assets/images/HD3.png
feature_row2:
- image_path: /assets/images/Rlogo.svg
---
Courses that I teach at the [University of Nebraska - Lincoln](www.unl.edu).
# [NRES 315: Human Dimensions of Wildlife and Fisheries](https://bulletin.unl.edu/courses/NRES/315)
{% include feature_row %}
Managers and researchers increasingly must contend with the problem of understanding and managing complex, social-ecological systems.
To be effective in the job requires understanding how people value, experience, use, care for, interact with, and are sustained by the natural environment.
This course provides an introduction to the theory and methods necessary to understand human dimensions as well as applications and case studies of human dimensions in fisheries and wildlife management.
# [Special topics using R](https://bulletin.unl.edu/courses/NRES/898)
{% include feature_row id="feature_row2" %}
I teach a Special Topics course every semester that covers aspects of using the R statistical language. We have covered a wide variety of topics including Ecological Detective, applied mutlivariate statitics, regression, ecological simulations, building Shiny apps, data wrangling, and graphics. While graduate students take this for credit, the group is open to faculty, postdocs, graduate students, and agency personnel. I keep all the lessons in a github repository with its own [project page](https://chrischizinski.github.io/SNR_R_Group/).
| chrischizinski/chrischizinski.github.io | _pages/teach.md | Markdown | mit | 1,672 |
<!doctype html>
<html lang="zh-ch">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/main.css">
<style>
body{
padding: 0;
margin: 0;
text-align: center;
}
</style>
<title>Part6-3</title>
</head>
<body>
<div id="slider">
<ul>
<li style="z-index: 1"><img src="img/bizhi1.jpeg" alt=""/></li>
<li><img src="img/bizhi2.jpeg" alt=""/></li>
<li><img src="img/bizhi3.jpeg" alt=""/></li>
<li><img src="img/bizhi4.jpeg" alt=""/></li>
<li><img src="img/bizhi5.jpeg" alt=""/></li>
</ul>
<div id="num">
<span class="active"></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
</div>
<script type="text/javascript" src="js/util.js"></script>
<script type="text/javascript" src="js/task0002_3.js"></script>
</body>
</html> | hellozts4120/FullStack-HKUST | ife-exercise/task0002/work/task0002_3.html | HTML | mit | 1,015 |
require 'spec_helper'
describe Nexaas::Auditor::AuditLogger do
it 'instanciates using the logger from the Configuration' do
logger = double('SomeLogger')
expect(Nexaas::Auditor).
to receive_message_chain(:configuration, :logger).
and_return(logger)
auditter = described_class.new
expect(auditter.logger).to eql(logger)
end
describe '#log' do
it 'requires a :level option' do
expect { subject.log(measure: 'foobar') }.
to raise_error(ArgumentError, "required key `:level` not found")
end
it 'requires a valid :level option' do
expect { subject.log(level: 'invalid', measure: 'foobar') }.
to raise_error(ArgumentError, "key `:level` is invalid: 'invalid'")
end
it 'requires a :measure option' do
expect { subject.log(level: 'info') }.
to raise_error(ArgumentError, "required key 'measure' not found or empty")
end
it 'sends the formatted log message to the logger with the correct level' do
logger = double('SomeLogger')
expect(subject).to receive(:logger).and_return(logger)
expect(logger).to receive(:warn).with('audit_log=true measure=foo.bar other=info')
subject.log(level: :warn, measure: 'foo.bar', other: 'info')
end
it 'logs any error and never raises and exception' do
logger = double('SomeLogger')
expect(subject).to receive(:logger).at_least(2).times.and_return(logger)
expect(logger).to receive(:warn).and_raise(RuntimeError, 'some error')
expect(logger).
to receive(:fatal).
with("role=audit_logger class=Nexaas::Auditor::AuditLogger measure=errors.unable_to_log exception=RuntimeError")
expect {
subject.log(level: :warn, measure: 'foo.bar', other: 'info')
}.to_not raise_error
end
end
end
| myfreecomm/nexaas-auditor | spec/nexaas/auditor/audit_logger_spec.rb | Ruby | mit | 1,810 |
#!/usr/bin/env python
""" pybcompgen
Pybcompgen calculates context sensitive tab-completion data which is
derived from environment bash system settings. It doesn't need to know
anything about whether you use /etc/completion or /etc/bash_completion.d,
all that matters is whether *bash* knows about the completion. The benefit
of doing it this way is obvious: you get access to all the completion features
that the system has installed without caring how the completion features
work. Note that this approach doesn't just work for things in the users
$PATH, it works for arbitrary complex completion. In the default linux
installations, completion normally includes everything from
git-subcommands to debian packages, depending on context.
Example I/O:
$ pybcompgen "/et"
["/etc "]
$ pybcompgen "git lo"
["log", "lol", "lola"]
$ pybcompgen "apt-ge"
["apt-get "]
$ pybcompgen "apt-get inst"
["install "]
$pybcompgen "apt-get install ubuntu-art"
["ubuntu-artwork "]
"""
import re
import sys
import json
import unicodedata
from subprocess import Popen, PIPE
from smashlib._logging import smash_log
# possibly this should be all vt100 codes, idk
# http://ascii-table.com/ansi-escape-sequences-vt-100.php
# http://stackoverflow.com/questions/7857352/python-regex-to-match-vt100-escape-sequences
ansi_escape = re.compile(r'\x1b\[C')
def remove_control_characters(s):
s = unicode(s)
s = ansi_escape.sub('', s)
s = s.replace('[1@#', '')
return "".join(ch for ch in s if unicodedata.category(ch)[0] != "C")
def complete(to_complete):
""" wow! so this is stupid, but what can you do? to understand
the command required to get completion information out of bash,
start by executing "printf '/et\x09\x09' | bash -i". What this
command does is put bash into interactive mode, then simulate
typing "/et<tab><tab>" inside bash. The tab-completion information
can be scraped out of the text, but several things complicate the final
solution:
1) the tab-completion info, apart from being post-processed, must be
scraped from stderr, not from stdout.
2) for post-processing, without knowledge of how the prompt will be
rendered or if there is some kind of banner that will be printed,
it's hard to know where exactly to start capturing tab-completion
options.
3) the method used to get the tab completion involves the bash builtins
"printf", meaning we have to launch subprocess with "bash -c"
4) completion output could be paginated by bash if there are lots of
options. have to account for that and still try to get all the
options instead of just the first page
5) sending EOF does not work unless it comes after a newline. this
means we have to take extra steps to avoid actually executing the
command we want to complete (executing the command is not what the
user expects and is possibly unsafe). to avoid executing the line,
after getting tab completion you have to simulate control-a (go to
start of line) followed by '#'. this comments the line and prevents
it from executing. note: you cannot send control-c to cancel the
execution of the line because we are dealing with pipes, whereas
control-c is processed only by proper tty's.
"""
# smash_log.info("[{0}]".format(to_complete))
if not to_complete:
return []
cmd = '''bash -c "printf 'PS1=\"\";echo MARKER\n{complete}\t\t\x01#\necho MARKER'|bash -i"'''.format(
complete=to_complete)
p1 = Popen(cmd, shell=True, stdout=PIPE, stdin=PIPE, stderr=PIPE)
out, err = p1.communicate()
lines = err.split('\n')
# smash_log.info(err)
first_marker = None
last_marker = None
for i in range(len(lines)):
line = lines[i]
if line.strip().endswith('echo MARKER'):
if first_marker is None:
first_marker = i
else:
last_marker = i
# SPECIAL CASE: pagination
if last_marker is None:
# when this happens there are too many options,
# ie bash is asking something like this:
# Display all 103 possibilities? (y or n)
# Pagination indicators like '--More--'must be removed
lines = [x for x in lines if not line.startswith('--More')]
last_marker = len(lines) - 3
first_marker += 1
complete_lines = lines[first_marker + 2:last_marker - 1]
# SPECIAL-CASE: no completion options or only one option
if not complete_lines:
# NOTE:
# if there is only one option, readline simply applies it,
# which affects the current line in place. apparently this
# results in tons of control-characters being dumped onto
# the line, and we have to clean those up for the output
try:
the_line = lines[first_marker + 1:last_marker][0]
except IndexError:
smash_log.info(
'error completing '+str([
lines, first_marker, last_marker]))
return []
the_line = remove_control_characters(the_line)
tmp = the_line[the_line.rfind(to_complete) + len(to_complete):]
result = to_complete.split()[-1] + tmp
if '#' in result:
# this seems to only happen for directories. not sure why
result = result[:result.find('#')]
if result == to_complete.split()[-1]:
# SPECIAL-CASE: no completion options at all.
return []
return [result]
else:
# there are multiple completion options
completion_choices_by_row = [x.split() for x in complete_lines]
completion_choices = reduce(
lambda x, y: x + y, completion_choices_by_row)
return completion_choices
def main():
# if being called from the command line, output json
# so it is easier for another application to consume
txt = sys.argv[-1]
result = complete(txt)
print json.dumps(result)
if __name__ == '__main__':
main()
| mattvonrocketstein/smash | smashlib/bin/pybcompgen.py | Python | mit | 6,278 |
.loginBtn {
height: 30px;
width: 150px;
background-image: url('/images/LogInWithStrava.png');
}
| SergiuB/stravaboard | public/css/style.css | CSS | mit | 102 |
module("attributes", { teardown: moduleTeardown });
var bareObj = function(value) { return value; };
var functionReturningObj = function(value) { return (function() { return value; }); };
test("jQuery.attrFix/jQuery.propFix integrity test", function() {
expect(2);
// This must be maintained and equal jQuery.attrFix when appropriate
// Ensure that accidental or erroneous property
// overwrites don't occur
// This is simply for better code coverage and future proofing.
var props = {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
};
var propsShouldBe = {
tabindex: "tabIndex"
};
deepEqual(propsShouldBe, jQuery.attrFix, "jQuery.attrFix passes integrity check");
deepEqual(props, jQuery.propFix, "jQuery.propFix passes integrity check");
});
test("attr(String)", function() {
expect(45);
equals( jQuery("#text1").attr("type"), "text", "Check for type attribute" );
equals( jQuery("#radio1").attr("type"), "radio", "Check for type attribute" );
equals( jQuery("#check1").attr("type"), "checkbox", "Check for type attribute" );
equals( jQuery("#simon1").attr("rel"), "bookmark", "Check for rel attribute" );
equals( jQuery("#google").attr("title"), "Google!", "Check for title attribute" );
equals( jQuery("#mark").attr("hreflang"), "en", "Check for hreflang attribute" );
equals( jQuery("#en").attr("lang"), "en", "Check for lang attribute" );
equals( jQuery("#simon").attr("class"), "blog link", "Check for class attribute" );
equals( jQuery("#name").attr("name"), "name", "Check for name attribute" );
equals( jQuery("#text1").attr("name"), "action", "Check for name attribute" );
ok( jQuery("#form").attr("action").indexOf("formaction") >= 0, "Check for action attribute" );
equals( jQuery("#text1").attr("value", "t").attr("value"), "t", "Check setting the value attribute" );
equals( jQuery("<div value='t'></div>").attr("value"), "t", "Check setting custom attr named 'value' on a div" );
equals( jQuery("#form").attr("blah", "blah").attr("blah"), "blah", "Set non-existant attribute on a form" );
equals( jQuery("#foo").attr("height"), undefined, "Non existent height attribute should return undefined" );
// [7472] & [3113] (form contains an input with name="action" or name="id")
var extras = jQuery("<input name='id' name='name' /><input id='target' name='target' />").appendTo("#testForm");
equals( jQuery("#form").attr("action","newformaction").attr("action"), "newformaction", "Check that action attribute was changed" );
equals( jQuery("#testForm").attr("target"), undefined, "Retrieving target does not equal the input with name=target" );
equals( jQuery("#testForm").attr("target", "newTarget").attr("target"), "newTarget", "Set target successfully on a form" );
equals( jQuery("#testForm").removeAttr("id").attr("id"), undefined, "Retrieving id does not equal the input with name=id after id is removed [#7472]" );
// Bug #3685 (form contains input with name="name")
equals( jQuery("#testForm").attr("name"), undefined, "Retrieving name does not retrieve input with name=name" );
extras.remove();
equals( jQuery("#text1").attr("maxlength"), "30", "Check for maxlength attribute" );
equals( jQuery("#text1").attr("maxLength"), "30", "Check for maxLength attribute" );
equals( jQuery("#area1").attr("maxLength"), "30", "Check for maxLength attribute" );
// using innerHTML in IE causes href attribute to be serialized to the full path
jQuery("<a/>").attr({ "id": "tAnchor5", "href": "#5" }).appendTo("#qunit-fixture");
equals( jQuery("#tAnchor5").attr("href"), "#5", "Check for non-absolute href (an anchor)" );
// list attribute is readonly by default in browsers that support it
jQuery("#list-test").attr("list", "datalist");
equals( jQuery("#list-test").attr("list"), "datalist", "Check setting list attribute" );
// Related to [5574] and [5683]
var body = document.body, $body = jQuery(body);
strictEqual( $body.attr("foo"), undefined, "Make sure that a non existent attribute returns undefined" );
body.setAttribute("foo", "baz");
equals( $body.attr("foo"), "baz", "Make sure the dom attribute is retrieved when no expando is found" );
$body.attr("foo","cool");
equals( $body.attr("foo"), "cool", "Make sure that setting works well when both expando and dom attribute are available" );
body.removeAttribute("foo"); // Cleanup
var select = document.createElement("select"), optgroup = document.createElement("optgroup"), option = document.createElement("option");
optgroup.appendChild( option );
select.appendChild( optgroup );
equal( jQuery( option ).attr("selected"), "selected", "Make sure that a single option is selected, even when in an optgroup." );
var $img = jQuery("<img style='display:none' width='215' height='53' src='http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif'/>").appendTo("body");
equals( $img.attr("width"), "215", "Retrieve width attribute an an element with display:none." );
equals( $img.attr("height"), "53", "Retrieve height attribute an an element with display:none." );
// Check for style support
ok( !!~jQuery("#dl").attr("style").indexOf("position"), "Check style attribute getter, also normalize css props to lowercase" );
ok( !!~jQuery("#foo").attr("style", "position:absolute;").attr("style").indexOf("position"), "Check style setter" );
// Check value on button element (#1954)
var $button = jQuery("<button value='foobar'>text</button>").insertAfter("#button");
equals( $button.attr("value"), "foobar", "Value retrieval on a button does not return innerHTML" );
equals( $button.attr("value", "baz").html(), "text", "Setting the value does not change innerHTML" );
// Attributes with a colon on a table element (#1591)
equals( jQuery("#table").attr("test:attrib"), undefined, "Retrieving a non-existent attribute on a table with a colon does not throw an error." );
equals( jQuery("#table").attr("test:attrib", "foobar").attr("test:attrib"), "foobar", "Setting an attribute on a table with a colon does not throw an error." );
var $form = jQuery("<form class='something'></form>").appendTo("#qunit-fixture");
equal( $form.attr("class"), "something", "Retrieve the class attribute on a form." );
var $a = jQuery("<a href='#' onclick='something()'>Click</a>").appendTo("#qunit-fixture");
equal( $a.attr("onclick"), "something()", "Retrieve ^on attribute without anonymous function wrapper." );
ok( jQuery("<div/>").attr("doesntexist") === undefined, "Make sure undefined is returned when no attribute is found." );
ok( jQuery("<div/>").attr("title") === undefined, "Make sure undefined is returned when no attribute is found." );
equal( jQuery("<div/>").attr("title", "something").attr("title"), "something", "Set the title attribute." );
ok( jQuery().attr("doesntexist") === undefined, "Make sure undefined is returned when no element is there." );
equal( jQuery("<div/>").attr("value"), undefined, "An unset value on a div returns undefined." );
equal( jQuery("<input/>").attr("value"), "", "An unset value on an input returns current value." );
});
if ( !isLocal ) {
test("attr(String) in XML Files", function() {
expect(3);
stop();
jQuery.get("data/dashboard.xml", function( xml ) {
equal( jQuery( "locations", xml ).attr("class"), "foo", "Check class attribute in XML document" );
equal( jQuery( "location", xml ).attr("for"), "bar", "Check for attribute in XML document" );
equal( jQuery( "location", xml ).attr("checked"), "different", "Check that hooks are not attached in XML document" );
start();
});
});
}
test("attr(String, Function)", function() {
expect(2);
equals( jQuery("#text1").attr("value", function() { return this.id; })[0].value, "text1", "Set value from id" );
equals( jQuery("#text1").attr("title", function(i) { return i; }).attr("title"), "0", "Set value with an index");
});
test("attr(Hash)", function() {
expect(3);
var pass = true;
jQuery("div").attr({foo: "baz", zoo: "ping"}).each(function(){
if ( this.getAttribute("foo") != "baz" && this.getAttribute("zoo") != "ping" ) pass = false;
});
ok( pass, "Set Multiple Attributes" );
equals( jQuery("#text1").attr({value: function() { return this.id; }})[0].value, "text1", "Set attribute to computed value #1" );
equals( jQuery("#text1").attr({title: function(i) { return i; }}).attr("title"), "0", "Set attribute to computed value #2");
});
test("attr(String, Object)", function() {
expect(75);
var div = jQuery("div").attr("foo", "bar"),
fail = false;
for ( var i = 0; i < div.size(); i++ ) {
if ( div.get(i).getAttribute("foo") != "bar" ){
fail = i;
break;
}
}
equals( fail, false, "Set Attribute, the #" + fail + " element didn't get the attribute 'foo'" );
ok( jQuery("#foo").attr({ "width": null }), "Try to set an attribute to nothing" );
jQuery("#name").attr("name", "something");
equals( jQuery("#name").attr("name"), "something", "Set name attribute" );
jQuery("#name").attr("name", null);
equals( jQuery("#name").attr("name"), undefined, "Remove name attribute" );
var $input = jQuery("<input>", { name: "something" });
equals( $input.attr("name"), "something", "Check element creation gets/sets the name attribute." );
jQuery("#check2").prop("checked", true).prop("checked", false).attr("checked", true);
equals( document.getElementById("check2").checked, true, "Set checked attribute" );
equals( jQuery("#check2").prop("checked"), true, "Set checked attribute" );
equals( jQuery("#check2").attr("checked"), "checked", "Set checked attribute" );
jQuery("#check2").attr("checked", false);
equals( document.getElementById("check2").checked, false, "Set checked attribute" );
equals( jQuery("#check2").prop("checked"), false, "Set checked attribute" );
equals( jQuery("#check2").attr("checked"), undefined, "Set checked attribute" );
jQuery("#text1").attr("readonly", true);
equals( document.getElementById("text1").readOnly, true, "Set readonly attribute" );
equals( jQuery("#text1").prop("readOnly"), true, "Set readonly attribute" );
equals( jQuery("#text1").attr("readonly"), "readonly", "Set readonly attribute" );
jQuery("#text1").attr("readonly", false);
equals( document.getElementById("text1").readOnly, false, "Set readonly attribute" );
equals( jQuery("#text1").prop("readOnly"), false, "Set readonly attribute" );
equals( jQuery("#text1").attr("readonly"), undefined, "Set readonly attribute" );
jQuery("#check2").prop("checked", true);
equals( document.getElementById("check2").checked, true, "Set checked attribute" );
equals( jQuery("#check2").prop("checked"), true, "Set checked attribute" );
equals( jQuery("#check2").attr("checked"), "checked", "Set checked attribute" );
jQuery("#check2").prop("checked", false);
equals( document.getElementById("check2").checked, false, "Set checked attribute" );
equals( jQuery("#check2").prop("checked"), false, "Set checked attribute" );
equals( jQuery("#check2").attr("checked"), undefined, "Set checked attribute" );
jQuery("#check2").attr("checked", "checked");
equal( document.getElementById("check2").checked, true, "Set checked attribute with 'checked'" );
equal( jQuery("#check2").prop("checked"), true, "Set checked attribute" );
equal( jQuery("#check2").attr("checked"), "checked", "Set checked attribute" );
jQuery("#text1").prop("readOnly", true);
equals( document.getElementById("text1").readOnly, true, "Set readonly attribute" );
equals( jQuery("#text1").prop("readOnly"), true, "Set readonly attribute" );
equals( jQuery("#text1").attr("readonly"), "readonly", "Set readonly attribute" );
jQuery("#text1").prop("readOnly", false);
equals( document.getElementById("text1").readOnly, false, "Set readonly attribute" );
equals( jQuery("#text1").prop("readOnly"), false, "Set readonly attribute" );
equals( jQuery("#text1").attr("readonly"), undefined, "Set readonly attribute" );
jQuery("#name").attr("maxlength", "5");
equals( document.getElementById("name").maxLength, 5, "Set maxlength attribute" );
jQuery("#name").attr("maxLength", "10");
equals( document.getElementById("name").maxLength, 10, "Set maxlength attribute" );
// HTML5 boolean attributes
var $text = jQuery("#text1").attr({
"autofocus": true,
"required": true
});
equal( $text.attr("autofocus"), "autofocus", "Set boolean attributes to the same name" );
equal( $text.attr("autofocus", false).attr("autofocus"), undefined, "Setting autofocus attribute to false removes it" );
equal( $text.attr("required"), "required", "Set boolean attributes to the same name" );
equal( $text.attr("required", false).attr("required"), undefined, "Setting required attribute to false removes it" );
var $details = jQuery("<details open></details>").appendTo("#qunit-fixture");
equal( $details.attr("open"), "open", "open attribute presense indicates true" );
equal( $details.attr("open", false).attr("open"), undefined, "Setting open attribute to false removes it" );
$text.attr("data-something", true);
equal( $text.attr("data-something"), "true", "Set data attributes");
equal( $text.data("something"), true, "Setting data attributes are not affected by boolean settings");
$text.attr("data-another", false);
equal( $text.attr("data-another"), "false", "Set data attributes");
equal( $text.data("another"), false, "Setting data attributes are not affected by boolean settings" );
equal( $text.attr("aria-disabled", false).attr("aria-disabled"), "false", "Setting aria attributes are not affected by boolean settings");
$text.removeData("something").removeData("another").removeAttr("aria-disabled");
jQuery("#foo").attr("contenteditable", true);
equals( jQuery("#foo").attr("contenteditable"), "true", "Enumerated attributes are set properly" );
var attributeNode = document.createAttribute("irrelevant"),
commentNode = document.createComment("some comment"),
textNode = document.createTextNode("some text"),
obj = {};
jQuery.each( [commentNode, textNode, attributeNode], function( i, elem ) {
var $elem = jQuery( elem );
$elem.attr( "nonexisting", "foo" );
strictEqual( $elem.attr("nonexisting"), undefined, "attr(name, value) works correctly on comment and text nodes (bug #7500)." );
});
jQuery.each( [window, document, obj, "#firstp"], function( i, elem ) {
var $elem = jQuery( elem );
strictEqual( $elem.attr("nonexisting"), undefined, "attr works correctly for non existing attributes (bug #7500)." );
equal( $elem.attr("something", "foo" ).attr("something"), "foo", "attr falls back to prop on unsupported arguments" );
});
var table = jQuery("#table").append("<tr><td>cell</td></tr><tr><td>cell</td><td>cell</td></tr><tr><td>cell</td><td>cell</td></tr>"),
td = table.find("td:first");
td.attr("rowspan", "2");
equals( td[0].rowSpan, 2, "Check rowspan is correctly set" );
td.attr("colspan", "2");
equals( td[0].colSpan, 2, "Check colspan is correctly set" );
table.attr("cellspacing", "2");
equals( table[0].cellSpacing, "2", "Check cellspacing is correctly set" );
equals( jQuery("#area1").attr("value"), "foobar", "Value attribute retrieves the property for backwards compatibility." );
// for #1070
jQuery("#name").attr("someAttr", "0");
equals( jQuery("#name").attr("someAttr"), "0", "Set attribute to a string of \"0\"" );
jQuery("#name").attr("someAttr", 0);
equals( jQuery("#name").attr("someAttr"), "0", "Set attribute to the number 0" );
jQuery("#name").attr("someAttr", 1);
equals( jQuery("#name").attr("someAttr"), "1", "Set attribute to the number 1" );
// using contents will get comments regular, text, and comment nodes
var j = jQuery("#nonnodes").contents();
j.attr("name", "attrvalue");
equals( j.attr("name"), "attrvalue", "Check node,textnode,comment for attr" );
j.removeAttr("name");
QUnit.reset();
// Type
var type = jQuery("#check2").attr("type");
var thrown = false;
try {
jQuery("#check2").attr("type","hidden");
} catch(e) {
thrown = true;
}
ok( thrown, "Exception thrown when trying to change type property" );
equals( type, jQuery("#check2").attr("type"), "Verify that you can't change the type of an input element" );
var check = document.createElement("input");
var thrown = true;
try {
jQuery(check).attr("type", "checkbox");
} catch(e) {
thrown = false;
}
ok( thrown, "Exception thrown when trying to change type property" );
equals( "checkbox", jQuery(check).attr("type"), "Verify that you can change the type of an input element that isn't in the DOM" );
var check = jQuery("<input />");
var thrown = true;
try {
check.attr("type","checkbox");
} catch(e) {
thrown = false;
}
ok( thrown, "Exception thrown when trying to change type property" );
equals( "checkbox", check.attr("type"), "Verify that you can change the type of an input element that isn't in the DOM" );
var button = jQuery("#button");
var thrown = false;
try {
button.attr("type","submit");
} catch(e) {
thrown = true;
}
ok( thrown, "Exception thrown when trying to change type property" );
equals( "button", button.attr("type"), "Verify that you can't change the type of a button element" );
var $radio = jQuery("<input>", { "value": "sup", "type": "radio" }).appendTo("#testForm");
equals( $radio.val(), "sup", "Value is not reset when type is set after value on a radio" );
// Setting attributes on svg elements (bug #3116)
var $svg = jQuery("<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' version='1.1' baseProfile='full' width='200' height='200'>"
+ "<circle cx='200' cy='200' r='150' />"
+ "</svg>").appendTo("body");
equals( $svg.attr("cx", 100).attr("cx"), "100", "Set attribute on svg element" );
$svg.remove();
});
test("attr(jquery_method)", function(){
expect(7);
var $elem = jQuery("<div />"),
elem = $elem[0];
// one at a time
$elem.attr({html: "foo"}, true);
equals( elem.innerHTML, "foo", "attr(html)");
$elem.attr({text: "bar"}, true);
equals( elem.innerHTML, "bar", "attr(text)");
$elem.attr({css: {color: "red"}}, true);
ok( /^(#ff0000|red)$/i.test(elem.style.color), "attr(css)");
$elem.attr({height: 10}, true);
equals( elem.style.height, "10px", "attr(height)");
// Multiple attributes
$elem.attr({
width:10,
css:{ paddingLeft:1, paddingRight:1 }
}, true);
equals( elem.style.width, "10px", "attr({...})");
equals( elem.style.paddingLeft, "1px", "attr({...})");
equals( elem.style.paddingRight, "1px", "attr({...})");
});
if ( !isLocal ) {
test("attr(String, Object) - Loaded via XML document", function() {
expect(2);
stop();
jQuery.get("data/dashboard.xml", function( xml ) {
var titles = [];
jQuery( "tab", xml ).each(function() {
titles.push( jQuery(this).attr("title") );
});
equals( titles[0], "Location", "attr() in XML context: Check first title" );
equals( titles[1], "Users", "attr() in XML context: Check second title" );
start();
});
});
}
test("attr('tabindex')", function() {
expect(8);
// elements not natively tabbable
equals(jQuery("#listWithTabIndex").attr("tabindex"), 5, "not natively tabbable, with tabindex set to 0");
equals(jQuery("#divWithNoTabIndex").attr("tabindex"), undefined, "not natively tabbable, no tabindex set");
// anchor with href
equals(jQuery("#linkWithNoTabIndex").attr("tabindex"), 0, "anchor with href, no tabindex set");
equals(jQuery("#linkWithTabIndex").attr("tabindex"), 2, "anchor with href, tabindex set to 2");
equals(jQuery("#linkWithNegativeTabIndex").attr("tabindex"), -1, "anchor with href, tabindex set to -1");
// anchor without href
equals(jQuery("#linkWithNoHrefWithNoTabIndex").attr("tabindex"), undefined, "anchor without href, no tabindex set");
equals(jQuery("#linkWithNoHrefWithTabIndex").attr("tabindex"), 1, "anchor without href, tabindex set to 2");
equals(jQuery("#linkWithNoHrefWithNegativeTabIndex").attr("tabindex"), -1, "anchor without href, no tabindex set");
});
test("attr('tabindex', value)", function() {
expect(9);
var element = jQuery("#divWithNoTabIndex");
equals(element.attr("tabindex"), undefined, "start with no tabindex");
// set a positive string
element.attr("tabindex", "1");
equals(element.attr("tabindex"), 1, "set tabindex to 1 (string)");
// set a zero string
element.attr("tabindex", "0");
equals(element.attr("tabindex"), 0, "set tabindex to 0 (string)");
// set a negative string
element.attr("tabindex", "-1");
equals(element.attr("tabindex"), -1, "set tabindex to -1 (string)");
// set a positive number
element.attr("tabindex", 1);
equals(element.attr("tabindex"), 1, "set tabindex to 1 (number)");
// set a zero number
element.attr("tabindex", 0);
equals(element.attr("tabindex"), 0, "set tabindex to 0 (number)");
// set a negative number
element.attr("tabindex", -1);
equals(element.attr("tabindex"), -1, "set tabindex to -1 (number)");
element = jQuery("#linkWithTabIndex");
equals(element.attr("tabindex"), 2, "start with tabindex 2");
element.attr("tabindex", -1);
equals(element.attr("tabindex"), -1, "set negative tabindex");
});
test("removeAttr(String)", function() {
expect(8);
equal( jQuery("#mark").removeAttr( "class" )[0].className, "", "remove class" );
equal( jQuery("#form").removeAttr("id").attr("id"), undefined, "Remove id" );
equal( jQuery("#foo").attr("style", "position:absolute;").removeAttr("style").attr("style"), undefined, "Check removing style attribute" );
equal( jQuery("#form").attr("style", "position:absolute;").removeAttr("style").attr("style"), undefined, "Check removing style attribute on a form" );
equal( jQuery("<div style='position: absolute'></div>").appendTo("#foo").removeAttr("style").prop("style").cssText, "", "Check removing style attribute (#9699 Webkit)" );
equal( jQuery("#fx-test-group").attr("height", "3px").removeAttr("height").css("height"), "1px", "Removing height attribute has no effect on height set with style attribute" );
jQuery("#check1").removeAttr("checked").prop("checked", true).removeAttr("checked");
equal( document.getElementById("check1").checked, false, "removeAttr sets boolean properties to false" );
jQuery("#text1").prop("readOnly", true).removeAttr("readonly");
equal( document.getElementById("text1").readOnly, false, "removeAttr sets boolean properties to false" );
});
test("prop(String, Object)", function() {
expect(30);
equals( jQuery("#text1").prop("value"), "Test", "Check for value attribute" );
equals( jQuery("#text1").prop("value", "Test2").prop("defaultValue"), "Test", "Check for defaultValue attribute" );
equals( jQuery("#select2").prop("selectedIndex"), 3, "Check for selectedIndex attribute" );
equals( jQuery("#foo").prop("nodeName").toUpperCase(), "DIV", "Check for nodeName attribute" );
equals( jQuery("#foo").prop("tagName").toUpperCase(), "DIV", "Check for tagName attribute" );
equals( jQuery("<option/>").prop("selected"), false, "Check selected attribute on disconnected element." );
equals( jQuery("#listWithTabIndex").prop("tabindex"), 5, "Check retrieving tabindex" );
jQuery("#text1").prop("readonly", true);
equals( document.getElementById("text1").readOnly, true, "Check setting readOnly property with 'readonly'" );
equals( jQuery("#label-for").prop("for"), "action", "Check retrieving htmlFor" );
jQuery("#text1").prop("class", "test");
equals( document.getElementById("text1").className, "test", "Check setting className with 'class'" );
equals( jQuery("#text1").prop("maxlength"), 30, "Check retrieving maxLength" );
jQuery("#table").prop("cellspacing", 1);
equals( jQuery("#table").prop("cellSpacing"), "1", "Check setting and retrieving cellSpacing" );
jQuery("#table").prop("cellpadding", 1);
equals( jQuery("#table").prop("cellPadding"), "1", "Check setting and retrieving cellPadding" );
jQuery("#table").prop("rowspan", 1);
equals( jQuery("#table").prop("rowSpan"), 1, "Check setting and retrieving rowSpan" );
jQuery("#table").prop("colspan", 1);
equals( jQuery("#table").prop("colSpan"), 1, "Check setting and retrieving colSpan" );
jQuery("#table").prop("usemap", 1);
equals( jQuery("#table").prop("useMap"), 1, "Check setting and retrieving useMap" );
jQuery("#table").prop("frameborder", 1);
equals( jQuery("#table").prop("frameBorder"), 1, "Check setting and retrieving frameBorder" );
QUnit.reset();
var body = document.body, $body = jQuery( body );
ok( $body.prop("nextSibling") === null, "Make sure a null expando returns null" );
body.foo = "bar";
equals( $body.prop("foo"), "bar", "Make sure the expando is preferred over the dom attribute" );
body.foo = undefined;
ok( $body.prop("foo") === undefined, "Make sure the expando is preferred over the dom attribute, even if undefined" );
var select = document.createElement("select"), optgroup = document.createElement("optgroup"), option = document.createElement("option");
optgroup.appendChild( option );
select.appendChild( optgroup );
equals( jQuery(option).prop("selected"), true, "Make sure that a single option is selected, even when in an optgroup." );
equals( jQuery(document).prop("nodeName"), "#document", "prop works correctly on document nodes (bug #7451)." );
var attributeNode = document.createAttribute("irrelevant"),
commentNode = document.createComment("some comment"),
textNode = document.createTextNode("some text"),
obj = {};
jQuery.each( [document, attributeNode, commentNode, textNode, obj, "#firstp"], function( i, ele ) {
strictEqual( jQuery(ele).prop("nonexisting"), undefined, "prop works correctly for non existing attributes (bug #7500)." );
});
var obj = {};
jQuery.each( [document, obj], function( i, ele ) {
var $ele = jQuery( ele );
$ele.prop( "nonexisting", "foo" );
equal( $ele.prop("nonexisting"), "foo", "prop(name, value) works correctly for non existing attributes (bug #7500)." );
});
jQuery( document ).removeProp("nonexisting");
});
test("prop('tabindex')", function() {
expect(8);
// elements not natively tabbable
equals(jQuery("#listWithTabIndex").prop("tabindex"), 5, "not natively tabbable, with tabindex set to 0");
equals(jQuery("#divWithNoTabIndex").prop("tabindex"), undefined, "not natively tabbable, no tabindex set");
// anchor with href
equals(jQuery("#linkWithNoTabIndex").prop("tabindex"), 0, "anchor with href, no tabindex set");
equals(jQuery("#linkWithTabIndex").prop("tabindex"), 2, "anchor with href, tabindex set to 2");
equals(jQuery("#linkWithNegativeTabIndex").prop("tabindex"), -1, "anchor with href, tabindex set to -1");
// anchor without href
equals(jQuery("#linkWithNoHrefWithNoTabIndex").prop("tabindex"), undefined, "anchor without href, no tabindex set");
equals(jQuery("#linkWithNoHrefWithTabIndex").prop("tabindex"), 1, "anchor without href, tabindex set to 2");
equals(jQuery("#linkWithNoHrefWithNegativeTabIndex").prop("tabindex"), -1, "anchor without href, no tabindex set");
});
test("prop('tabindex', value)", function() {
expect(9);
var element = jQuery("#divWithNoTabIndex");
equals(element.prop("tabindex"), undefined, "start with no tabindex");
// set a positive string
element.prop("tabindex", "1");
equals(element.prop("tabindex"), 1, "set tabindex to 1 (string)");
// set a zero string
element.prop("tabindex", "0");
equals(element.prop("tabindex"), 0, "set tabindex to 0 (string)");
// set a negative string
element.prop("tabindex", "-1");
equals(element.prop("tabindex"), -1, "set tabindex to -1 (string)");
// set a positive number
element.prop("tabindex", 1);
equals(element.prop("tabindex"), 1, "set tabindex to 1 (number)");
// set a zero number
element.prop("tabindex", 0);
equals(element.prop("tabindex"), 0, "set tabindex to 0 (number)");
// set a negative number
element.prop("tabindex", -1);
equals(element.prop("tabindex"), -1, "set tabindex to -1 (number)");
element = jQuery("#linkWithTabIndex");
equals(element.prop("tabindex"), 2, "start with tabindex 2");
element.prop("tabindex", -1);
equals(element.prop("tabindex"), -1, "set negative tabindex");
});
test("removeProp(String)", function() {
expect(6);
var attributeNode = document.createAttribute("irrelevant"),
commentNode = document.createComment("some comment"),
textNode = document.createTextNode("some text"),
obj = {};
strictEqual( jQuery( "#firstp" ).prop( "nonexisting", "foo" ).removeProp( "nonexisting" )[0].nonexisting, undefined, "removeprop works correctly on DOM element nodes" );
jQuery.each( [document, obj], function( i, ele ) {
var $ele = jQuery( ele );
$ele.prop( "nonexisting", "foo" ).removeProp( "nonexisting" );
strictEqual( ele.nonexisting, undefined, "removeProp works correctly on non DOM element nodes (bug #7500)." );
});
jQuery.each( [commentNode, textNode, attributeNode], function( i, ele ) {
var $ele = jQuery( ele );
$ele.prop( "nonexisting", "foo" ).removeProp( "nonexisting" );
strictEqual( ele.nonexisting, undefined, "removeProp works correctly on non DOM element nodes (bug #7500)." );
});
});
test("val()", function() {
expect(26);
document.getElementById("text1").value = "bla";
equals( jQuery("#text1").val(), "bla", "Check for modified value of input element" );
QUnit.reset();
equals( jQuery("#text1").val(), "Test", "Check for value of input element" );
// ticket #1714 this caused a JS error in IE
equals( jQuery("#first").val(), "", "Check a paragraph element to see if it has a value" );
ok( jQuery([]).val() === undefined, "Check an empty jQuery object will return undefined from val" );
equals( jQuery("#select2").val(), "3", "Call val() on a single=\"single\" select" );
same( jQuery("#select3").val(), ["1", "2"], "Call val() on a multiple=\"multiple\" select" );
equals( jQuery("#option3c").val(), "2", "Call val() on a option element with value" );
equals( jQuery("#option3a").val(), "", "Call val() on a option element with empty value" );
equals( jQuery("#option3e").val(), "no value", "Call val() on a option element with no value attribute" );
equals( jQuery("#option3a").val(), "", "Call val() on a option element with no value attribute" );
jQuery("#select3").val("");
same( jQuery("#select3").val(), [""], "Call val() on a multiple=\"multiple\" select" );
same( jQuery("#select4").val(), [], "Call val() on multiple=\"multiple\" select with all disabled options" );
jQuery("#select4 optgroup").add("#select4 > [disabled]").attr("disabled", false);
same( jQuery("#select4").val(), ["2", "3"], "Call val() on multiple=\"multiple\" select with some disabled options" );
jQuery("#select4").attr("disabled", true);
same( jQuery("#select4").val(), ["2", "3"], "Call val() on disabled multiple=\"multiple\" select" );
equals( jQuery("#select5").val(), "3", "Check value on ambiguous select." );
jQuery("#select5").val(1);
equals( jQuery("#select5").val(), "1", "Check value on ambiguous select." );
jQuery("#select5").val(3);
equals( jQuery("#select5").val(), "3", "Check value on ambiguous select." );
var checks = jQuery("<input type='checkbox' name='test' value='1'/><input type='checkbox' name='test' value='2'/><input type='checkbox' name='test' value=''/><input type='checkbox' name='test'/>").appendTo("#form");
same( checks.serialize(), "", "Get unchecked values." );
equals( checks.eq(3).val(), "on", "Make sure a value of 'on' is provided if none is specified." );
checks.val([ "2" ]);
same( checks.serialize(), "test=2", "Get a single checked value." );
checks.val([ "1", "" ]);
same( checks.serialize(), "test=1&test=", "Get multiple checked values." );
checks.val([ "", "2" ]);
same( checks.serialize(), "test=2&test=", "Get multiple checked values." );
checks.val([ "1", "on" ]);
same( checks.serialize(), "test=1&test=on", "Get multiple checked values." );
checks.remove();
var $button = jQuery("<button value='foobar'>text</button>").insertAfter("#button");
equals( $button.val(), "foobar", "Value retrieval on a button does not return innerHTML" );
equals( $button.val("baz").html(), "text", "Setting the value does not change innerHTML" );
equals( jQuery("<option/>").val("test").attr("value"), "test", "Setting value sets the value attribute" );
});
if ( "value" in document.createElement("meter") &&
"value" in document.createElement("progress") ) {
test("val() respects numbers without exception (Bug #9319)", function() {
expect(4);
var $meter = jQuery("<meter min='0' max='10' value='5.6'></meter>"),
$progress = jQuery("<progress max='10' value='1.5'></progress>");
try {
equal( typeof $meter.val(), "number", "meter, returns a number and does not throw exception" );
equal( $meter.val(), $meter[0].value, "meter, api matches host and does not throw exception" );
equal( typeof $progress.val(), "number", "progress, returns a number and does not throw exception" );
equal( $progress.val(), $progress[0].value, "progress, api matches host and does not throw exception" );
} catch(e) {}
$meter.remove();
$progress.remove();
});
}
var testVal = function(valueObj) {
expect(8);
QUnit.reset();
jQuery("#text1").val(valueObj( "test" ));
equals( document.getElementById("text1").value, "test", "Check for modified (via val(String)) value of input element" );
jQuery("#text1").val(valueObj( undefined ));
equals( document.getElementById("text1").value, "", "Check for modified (via val(undefined)) value of input element" );
jQuery("#text1").val(valueObj( 67 ));
equals( document.getElementById("text1").value, "67", "Check for modified (via val(Number)) value of input element" );
jQuery("#text1").val(valueObj( null ));
equals( document.getElementById("text1").value, "", "Check for modified (via val(null)) value of input element" );
var $select1 = jQuery("#select1");
$select1.val(valueObj( "3" ));
equals( $select1.val(), "3", "Check for modified (via val(String)) value of select element" );
$select1.val(valueObj( 2 ));
equals( $select1.val(), "2", "Check for modified (via val(Number)) value of select element" );
$select1.append("<option value='4'>four</option>");
$select1.val(valueObj( 4 ));
equals( $select1.val(), "4", "Should be possible to set the val() to a newly created option" );
// using contents will get comments regular, text, and comment nodes
var j = jQuery("#nonnodes").contents();
j.val(valueObj( "asdf" ));
equals( j.val(), "asdf", "Check node,textnode,comment with val()" );
j.removeAttr("value");
}
test("val(String/Number)", function() {
testVal(bareObj);
});
test("val(Function)", function() {
testVal(functionReturningObj);
});
test( "val(Array of Numbers) (Bug #7123)", function() {
expect(4);
jQuery("#form").append("<input type='checkbox' name='arrayTest' value='1' /><input type='checkbox' name='arrayTest' value='2' /><input type='checkbox' name='arrayTest' value='3' checked='checked' /><input type='checkbox' name='arrayTest' value='4' />");
var elements = jQuery("input[name=arrayTest]").val([ 1, 2 ]);
ok( elements[0].checked, "First element was checked" );
ok( elements[1].checked, "Second element was checked" );
ok( !elements[2].checked, "Third element was unchecked" );
ok( !elements[3].checked, "Fourth element remained unchecked" );
elements.remove();
});
test("val(Function) with incoming value", function() {
expect(10);
QUnit.reset();
var oldVal = jQuery("#text1").val();
jQuery("#text1").val(function(i, val) {
equals( val, oldVal, "Make sure the incoming value is correct." );
return "test";
});
equals( document.getElementById("text1").value, "test", "Check for modified (via val(String)) value of input element" );
oldVal = jQuery("#text1").val();
jQuery("#text1").val(function(i, val) {
equals( val, oldVal, "Make sure the incoming value is correct." );
return 67;
});
equals( document.getElementById("text1").value, "67", "Check for modified (via val(Number)) value of input element" );
oldVal = jQuery("#select1").val();
jQuery("#select1").val(function(i, val) {
equals( val, oldVal, "Make sure the incoming value is correct." );
return "3";
});
equals( jQuery("#select1").val(), "3", "Check for modified (via val(String)) value of select element" );
oldVal = jQuery("#select1").val();
jQuery("#select1").val(function(i, val) {
equals( val, oldVal, "Make sure the incoming value is correct." );
return 2;
});
equals( jQuery("#select1").val(), "2", "Check for modified (via val(Number)) value of select element" );
jQuery("#select1").append("<option value='4'>four</option>");
oldVal = jQuery("#select1").val();
jQuery("#select1").val(function(i, val) {
equals( val, oldVal, "Make sure the incoming value is correct." );
return 4;
});
equals( jQuery("#select1").val(), "4", "Should be possible to set the val() to a newly created option" );
});
// testing if a form.reset() breaks a subsequent call to a select element's .val() (in IE only)
test("val(select) after form.reset() (Bug #2551)", function() {
expect(3);
jQuery("<form id='kk' name='kk'><select id='kkk'><option value='cf'>cf</option><option value='gf'>gf</option></select></form>").appendTo("#qunit-fixture");
jQuery("#kkk").val( "gf" );
document.kk.reset();
equal( jQuery("#kkk")[0].value, "cf", "Check value of select after form reset." );
equal( jQuery("#kkk").val(), "cf", "Check value of select after form reset." );
// re-verify the multi-select is not broken (after form.reset) by our fix for single-select
same( jQuery("#select3").val(), ["1", "2"], "Call val() on a multiple=\"multiple\" select" );
jQuery("#kk").remove();
});
var testAddClass = function(valueObj) {
expect(9);
var div = jQuery("div");
div.addClass( valueObj("test") );
var pass = true;
for ( var i = 0; i < div.size(); i++ ) {
if ( !~div.get(i).className.indexOf("test") ) {
pass = false;
}
}
ok( pass, "Add Class" );
// using contents will get regular, text, and comment nodes
var j = jQuery("#nonnodes").contents();
j.addClass( valueObj("asdf") );
ok( j.hasClass("asdf"), "Check node,textnode,comment for addClass" );
div = jQuery("<div/>");
div.addClass( valueObj("test") );
equals( div.attr("class"), "test", "Make sure there's no extra whitespace." );
div.attr("class", " foo");
div.addClass( valueObj("test") );
equals( div.attr("class"), "foo test", "Make sure there's no extra whitespace." );
div.attr("class", "foo");
div.addClass( valueObj("bar baz") );
equals( div.attr("class"), "foo bar baz", "Make sure there isn't too much trimming." );
div.removeClass();
div.addClass( valueObj("foo") ).addClass( valueObj("foo") )
equal( div.attr("class"), "foo", "Do not add the same class twice in separate calls." );
div.addClass( valueObj("fo") );
equal( div.attr("class"), "foo fo", "Adding a similar class does not get interrupted." );
div.removeClass().addClass("wrap2");
ok( div.addClass("wrap").hasClass("wrap"), "Can add similarly named classes");
div.removeClass();
div.addClass( valueObj("bar bar") );
equal( div.attr("class"), "bar", "Do not add the same class twice in the same call." );
};
test("addClass(String)", function() {
testAddClass(bareObj);
});
test("addClass(Function)", function() {
testAddClass(functionReturningObj);
});
test("addClass(Function) with incoming value", function() {
expect(48);
var div = jQuery("div"), old = div.map(function(){
return jQuery(this).attr("class") || "";
});
div.addClass(function(i, val) {
if ( this.id !== "_firebugConsole") {
equals( val, old[i], "Make sure the incoming value is correct." );
return "test";
}
});
var pass = true;
for ( var i = 0; i < div.length; i++ ) {
if ( div.get(i).className.indexOf("test") == -1 ) pass = false;
}
ok( pass, "Add Class" );
});
var testRemoveClass = function(valueObj) {
expect(7);
var $divs = jQuery("div");
$divs.addClass("test").removeClass( valueObj("test") );
ok( !$divs.is(".test"), "Remove Class" );
QUnit.reset();
$divs = jQuery("div");
$divs.addClass("test").addClass("foo").addClass("bar");
$divs.removeClass( valueObj("test") ).removeClass( valueObj("bar") ).removeClass( valueObj("foo") );
ok( !$divs.is(".test,.bar,.foo"), "Remove multiple classes" );
QUnit.reset();
$divs = jQuery("div");
// Make sure that a null value doesn't cause problems
$divs.eq(0).addClass("test").removeClass( valueObj(null) );
ok( $divs.eq(0).is(".test"), "Null value passed to removeClass" );
$divs.eq(0).addClass("test").removeClass( valueObj("") );
ok( $divs.eq(0).is(".test"), "Empty string passed to removeClass" );
// using contents will get regular, text, and comment nodes
var j = jQuery("#nonnodes").contents();
j.removeClass( valueObj("asdf") );
ok( !j.hasClass("asdf"), "Check node,textnode,comment for removeClass" );
var div = document.createElement("div");
div.className = " test foo ";
jQuery(div).removeClass( valueObj("foo") );
equals( div.className, "test", "Make sure remaining className is trimmed." );
div.className = " test ";
jQuery(div).removeClass( valueObj("test") );
equals( div.className, "", "Make sure there is nothing left after everything is removed." );
};
test("removeClass(String) - simple", function() {
testRemoveClass(bareObj);
});
test("removeClass(Function) - simple", function() {
testRemoveClass(functionReturningObj);
});
test("removeClass(Function) with incoming value", function() {
expect(48);
var $divs = jQuery("div").addClass("test"), old = $divs.map(function(){
return jQuery(this).attr("class");
});
$divs.removeClass(function(i, val) {
if ( this.id !== "_firebugConsole" ) {
equals( val, old[i], "Make sure the incoming value is correct." );
return "test";
}
});
ok( !$divs.is(".test"), "Remove Class" );
QUnit.reset();
});
var testToggleClass = function(valueObj) {
expect(17);
var e = jQuery("#firstp");
ok( !e.is(".test"), "Assert class not present" );
e.toggleClass( valueObj("test") );
ok( e.is(".test"), "Assert class present" );
e.toggleClass( valueObj("test") );
ok( !e.is(".test"), "Assert class not present" );
// class name with a boolean
e.toggleClass( valueObj("test"), false );
ok( !e.is(".test"), "Assert class not present" );
e.toggleClass( valueObj("test"), true );
ok( e.is(".test"), "Assert class present" );
e.toggleClass( valueObj("test"), false );
ok( !e.is(".test"), "Assert class not present" );
// multiple class names
e.addClass("testA testB");
ok( (e.is(".testA.testB")), "Assert 2 different classes present" );
e.toggleClass( valueObj("testB testC") );
ok( (e.is(".testA.testC") && !e.is(".testB")), "Assert 1 class added, 1 class removed, and 1 class kept" );
e.toggleClass( valueObj("testA testC") );
ok( (!e.is(".testA") && !e.is(".testB") && !e.is(".testC")), "Assert no class present" );
// toggleClass storage
e.toggleClass(true);
ok( e[0].className === "", "Assert class is empty (data was empty)" );
e.addClass("testD testE");
ok( e.is(".testD.testE"), "Assert class present" );
e.toggleClass();
ok( !e.is(".testD.testE"), "Assert class not present" );
ok( jQuery._data(e[0], "__className__") === "testD testE", "Assert data was stored" );
e.toggleClass();
ok( e.is(".testD.testE"), "Assert class present (restored from data)" );
e.toggleClass(false);
ok( !e.is(".testD.testE"), "Assert class not present" );
e.toggleClass(true);
ok( e.is(".testD.testE"), "Assert class present (restored from data)" );
e.toggleClass();
e.toggleClass(false);
e.toggleClass();
ok( e.is(".testD.testE"), "Assert class present (restored from data)" );
// Cleanup
e.removeClass("testD");
jQuery.removeData(e[0], "__className__", true);
};
test("toggleClass(String|boolean|undefined[, boolean])", function() {
testToggleClass(bareObj);
});
test("toggleClass(Function[, boolean])", function() {
testToggleClass(functionReturningObj);
});
test("toggleClass(Fucntion[, boolean]) with incoming value", function() {
expect(14);
var e = jQuery("#firstp"), old = e.attr("class") || "";
ok( !e.is(".test"), "Assert class not present" );
e.toggleClass(function(i, val) {
equal( old, val, "Make sure the incoming value is correct." );
return "test";
});
ok( e.is(".test"), "Assert class present" );
old = e.attr("class");
e.toggleClass(function(i, val) {
equal( old, val, "Make sure the incoming value is correct." );
return "test";
});
ok( !e.is(".test"), "Assert class not present" );
old = e.attr("class") || "";
// class name with a boolean
e.toggleClass(function(i, val, state) {
equal( old, val, "Make sure the incoming value is correct." );
equal( state, false, "Make sure that the state is passed in." );
return "test";
}, false );
ok( !e.is(".test"), "Assert class not present" );
old = e.attr("class") || "";
e.toggleClass(function(i, val, state) {
equal( old, val, "Make sure the incoming value is correct." );
equal( state, true, "Make sure that the state is passed in." );
return "test";
}, true );
ok( e.is(".test"), "Assert class present" );
old = e.attr("class");
e.toggleClass(function(i, val, state) {
equal( old, val, "Make sure the incoming value is correct." );
equal( state, false, "Make sure that the state is passed in." );
return "test";
}, false );
ok( !e.is(".test"), "Assert class not present" );
// Cleanup
e.removeClass("test");
jQuery.removeData(e[0], "__className__", true);
});
test("addClass, removeClass, hasClass", function() {
expect(17);
var jq = jQuery("<p>Hi</p>"), x = jq[0];
jq.addClass("hi");
equals( x.className, "hi", "Check single added class" );
jq.addClass("foo bar");
equals( x.className, "hi foo bar", "Check more added classes" );
jq.removeClass();
equals( x.className, "", "Remove all classes" );
jq.addClass("hi foo bar");
jq.removeClass("foo");
equals( x.className, "hi bar", "Check removal of one class" );
ok( jq.hasClass("hi"), "Check has1" );
ok( jq.hasClass("bar"), "Check has2" );
var jq = jQuery("<p class='class1\nclass2\tcla.ss3\n\rclass4'></p>");
ok( jq.hasClass("class1"), "Check hasClass with line feed" );
ok( jq.is(".class1"), "Check is with line feed" );
ok( jq.hasClass("class2"), "Check hasClass with tab" );
ok( jq.is(".class2"), "Check is with tab" );
ok( jq.hasClass("cla.ss3"), "Check hasClass with dot" );
ok( jq.hasClass("class4"), "Check hasClass with carriage return" );
ok( jq.is(".class4"), "Check is with carriage return" );
jq.removeClass("class2");
ok( jq.hasClass("class2")==false, "Check the class has been properly removed" );
jq.removeClass("cla");
ok( jq.hasClass("cla.ss3"), "Check the dotted class has not been removed" );
jq.removeClass("cla.ss3");
ok( jq.hasClass("cla.ss3")==false, "Check the dotted class has been removed" );
jq.removeClass("class4");
ok( jq.hasClass("class4")==false, "Check the class has been properly removed" );
});
test("contents().hasClass() returns correct values", function() {
expect(2);
var $div = jQuery("<div><span class='foo'></span><!-- comment -->text</div>"),
$contents = $div.contents();
ok( $contents.hasClass("foo"), "Found 'foo' in $contents" );
ok( !$contents.hasClass("undefined"), "Did not find 'undefined' in $contents (correctly)" );
});
| hbkarun/jquery | test/unit/attributes.js | JavaScript | mit | 47,227 |
#include "aboutdialog.h"
#include "ui_aboutdialog.h"
#include "clientmodel.h"
#include "clientversion.h"
// Copyright year (2009-this)
// Todo: update this when changing our copyright comments in the source
const int ABOUTDIALOG_COPYRIGHT_YEAR = 2014;
AboutDialog::AboutDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::AboutDialog)
{
ui->setupUi(this);
// Set current copyright year
ui->copyrightLabel->setText(tr("Copyright") + QString(" © 2009-2013 ") + tr("The Bitcoin developers") + QString("<br>") + tr("Copyright") + QString(" © ") + tr("2011-2013 The Litecoin developers") + QString("<br>") + tr("Copyright") + QString(" © ") + tr("2013-%1 The Indocoin developers").arg(ABOUTDIALOG_COPYRIGHT_YEAR));
}
void AboutDialog::setModel(ClientModel *model)
{
if(model)
{
ui->versionLabel->setText(model->formatFullVersion());
}
}
AboutDialog::~AboutDialog()
{
delete ui;
}
void AboutDialog::on_buttonBox_accepted()
{
close();
}
| indocoinproject/indocoin | src/qt/aboutdialog.cpp | C++ | mit | 1,002 |
jQuery(document).ready(function($){
var timelines = $('.cd-horizontal-timeline'),
eventsMinDistance = 60;
(timelines.length > 0) && initTimeline(timelines);
var timelineWidth = $('.events-wrapper').width() - 40;
var translaWidth = 0;
minHeightTimeLine();
function initTimeline(timelines) {
timelines.each(function(){
var timeline = $(this),
timelineComponents = {};
//cache timeline components
timelineComponents['timelineWrapper'] = timeline.find('.events-wrapper');
timelineComponents['eventsWrapper'] = timelineComponents['timelineWrapper'].children('.events');
timelineComponents['fillingLine'] = timelineComponents['eventsWrapper'].children('.filling-line');
timelineComponents['timelineEvents'] = timelineComponents['eventsWrapper'].find('a');
timelineComponents['timelineDates'] = parseDate(timelineComponents['timelineEvents']);
timelineComponents['eventsMinLapse'] = minLapse(timelineComponents['timelineDates']);
timelineComponents['timelineNavigation'] = timeline.find('.cd-timeline-navigation');
timelineComponents['eventsContent'] = timeline.children('.events-content');
//assign a left postion to the single events along the timeline
setDatePosition(timelineComponents, eventsMinDistance);
//assign a width to the timeline
var timelineTotWidth = setTimelineWidth(timelineComponents, eventsMinDistance);
//the timeline has been initialize - show it
timeline.addClass('loaded');
//detect click on the a single event - show new event content
timelineComponents['eventsWrapper'].on('click', 'a', function(event){
event.preventDefault();
timelineComponents['timelineEvents'].removeClass('selected');
$(this).addClass('selected');
updateOlderEvents($(this));
updateFilling($(this), timelineComponents['fillingLine'], timelineTotWidth);
updateVisibleContent($(this), timelineComponents['eventsContent']);
});
//detect click on the next arrow
timelineComponents['timelineNavigation'].on('click', '.next', function(event){
if (!$('a.next').hasClass('inactive')){
var index = Number($('a.selected').attr('value'));
$('a[value='+(index+1)+']').click();
event.preventDefault();
if($('a[value='+(index+1)+']').position().left+translaWidth > timelineWidth)
updateSlide(timelineComponents, timelineTotWidth, 'next');
updateArrow();
}
});
//detect click on the prev arrow
timelineComponents['timelineNavigation'].on('click', '.prev', function(event){
if (!$('a.prev').hasClass('inactive')){
var index = Number($('a.selected').attr('value'));
$('a[value='+(index-1)+']').click();
event.preventDefault();
if($('a[value='+(index-1)+']').position().left+translaWidth < 0)
updateSlide(timelineComponents, timelineTotWidth, 'prev');
updateArrow();
}
});
//on swipe, show next/prev event content
timelineComponents['eventsContent'].on('swipeleft', function(){
var mq = checkMQ();
( mq == 'mobile' ) && showNewContent(timelineComponents, timelineTotWidth, 'next');
});
timelineComponents['eventsContent'].on('swiperight', function(){
var mq = checkMQ();
( mq == 'mobile' ) && showNewContent(timelineComponents, timelineTotWidth, 'prev');
});
//keyboard navigation
$(document).keyup(function(event){
if(event.which=='37' && elementInViewport(timeline.get(0)) ) {
showNewContent(timelineComponents, timelineTotWidth, 'prev');
} else if( event.which=='39' && elementInViewport(timeline.get(0))) {
showNewContent(timelineComponents, timelineTotWidth, 'next');
}
});
});
}
function minHeightTimeLine(){
var li = $('.events-content').find('li');
var s = 0;
for (i=0; i<li.length; i++){
if (s < $(li[i]).height())
s = $(li[i]).height();
}
$('.events-content').css('min-height', s+'px');
}
function updateArrow(){
if ($('a.selected').attr('value') == "0")
$('a.prev').addClass('inactive')
else
$('a.prev').removeClass('inactive');
if (Number($('a.selected').attr('value')) == $('ol#timeline').children('li').length-1)
$('a.next').addClass('inactive')
else
$('a.next').removeClass('inactive');
}
function updateSlide(timelineComponents, timelineTotWidth, string) {
//retrieve translateX value of timelineComponents['eventsWrapper']
var aux;
if ($(window).width() >= 770)
aux = Number(timelineComponents['timelineWrapper'].css('width').replace('px', ''));
else
if ($(window).width() > 400)
aux = Number(timelineComponents['timelineWrapper'].css('width').replace('px', ''))*0.8;
else
if ($(window).width() > 360)
aux = Number(timelineComponents['timelineWrapper'].css('width').replace('px', ''))*0.9;
else
if ($(window).width() > 320)
aux = Number(timelineComponents['timelineWrapper'].css('width').replace('px', ''));
else
aux = Number(timelineComponents['timelineWrapper'].css('width').replace('px', ''))*1.1;
var translateValue = getTranslateValue(timelineComponents['eventsWrapper']),
wrapperWidth = aux;
//translate the timeline to the left('next')/right('prev')
(string == 'next')
? translateTimeline(timelineComponents, translateValue - wrapperWidth + eventsMinDistance, wrapperWidth - timelineTotWidth)
: translateTimeline(timelineComponents, translateValue + wrapperWidth - eventsMinDistance);
//timelineWidth = (translateValue - wrapperWidth + eventsMinDistance)*-1;
}
function showNewContent(timelineComponents, timelineTotWidth, string) {
//go from one event to the next/previous one
var visibleContent = timelineComponents['eventsContent'].find('.selected'),
newContent = ( string == 'next' ) ? visibleContent.next() : visibleContent.prev();
if ( newContent.length > 0 ) { //if there's a next/prev event - show it
var selectedDate = timelineComponents['eventsWrapper'].find('.selected'),
newEvent = ( string == 'next' ) ? selectedDate.parent('li').next('li').children('a') : selectedDate.parent('li').prev('li').children('a');
updateFilling(newEvent, timelineComponents['fillingLine'], timelineTotWidth);
updateVisibleContent(newEvent, timelineComponents['eventsContent']);
newEvent.addClass('selected');
selectedDate.removeClass('selected');
updateOlderEvents(newEvent);
updateTimelinePosition(string, newEvent, timelineComponents);
}
}
function updateTimelinePosition(string, event, timelineComponents) {
//translate timeline to the left/right according to the position of the selected event
var eventStyle = window.getComputedStyle(event.get(0), null),
eventLeft = Number(eventStyle.getPropertyValue("left").replace('px', '')),
timelineWidth = Number(timelineComponents['timelineWrapper'].css('width').replace('px', '')),
timelineTotWidth = Number(timelineComponents['eventsWrapper'].css('width').replace('px', ''));
var timelineTranslate = getTranslateValue(timelineComponents['eventsWrapper']);
if( (string == 'next' && eventLeft > timelineWidth - timelineTranslate) || (string == 'prev' && eventLeft < - timelineTranslate) ) {
translateTimeline(timelineComponents, - eventLeft + timelineWidth/2, timelineWidth - timelineTotWidth);
}
}
function translateTimeline(timelineComponents, value, totWidth) {
var eventsWrapper = timelineComponents['eventsWrapper'].get(0);
value = (value > 0) ? 0 : value; //only negative translate value
value = ( !(typeof totWidth === 'undefined') && value < totWidth ) ? totWidth : value; //do not translate more than timeline width
setTransformValue(eventsWrapper, 'translateX', value+'px');
translaWidth = value;
//update navigation arrows visibility
}
function updateFilling(selectedEvent, filling, totWidth) {
//change .filling-line length according to the selected event
var eventStyle = window.getComputedStyle(selectedEvent.get(0), null),
eventLeft = eventStyle.getPropertyValue("left"),
eventWidth = eventStyle.getPropertyValue("width");
eventLeft = Number(eventLeft.replace('px', '')) + Number(eventWidth.replace('px', ''))/2;
var scaleValue = eventLeft/totWidth;
setTransformValue(filling.get(0), 'scaleX', scaleValue);
}
function setDatePosition(timelineComponents, min) {
for (i = 0; i < timelineComponents['timelineDates'].length; i++) {
var distance = daydiff(timelineComponents['timelineDates'][0], timelineComponents['timelineDates'][i]),
distanceNorm = Math.round(distance/timelineComponents['eventsMinLapse']) + 2;
timelineComponents['timelineEvents'].eq(i).css('left', distanceNorm*min+'px');
}
}
function setTimelineWidth(timelineComponents, width) {
var timeSpan = daydiff(timelineComponents['timelineDates'][0], timelineComponents['timelineDates'][timelineComponents['timelineDates'].length-1]),
timeSpanNorm = timeSpan/timelineComponents['eventsMinLapse'],
timeSpanNorm = Math.round(timeSpanNorm) + 4,
totalWidth = timeSpanNorm*width;
timelineComponents['eventsWrapper'].css('width', totalWidth+'px');
updateFilling(timelineComponents['eventsWrapper'].find('a.selected'), timelineComponents['fillingLine'], totalWidth);
updateTimelinePosition('next', timelineComponents['eventsWrapper'].find('a.selected'), timelineComponents);
return totalWidth;
}
function updateVisibleContent(event, eventsContent) {
var eventDate = event.data('date'),
visibleContent = eventsContent.find('.selected'),
selectedContent = eventsContent.find('[data-date="'+ eventDate +'"]'),
selectedContentHeight = selectedContent.height();
if (selectedContent.index() > visibleContent.index()) {
var classEnetering = 'selected enter-right',
classLeaving = 'leave-left';
} else {
var classEnetering = 'selected enter-left',
classLeaving = 'leave-right';
}
selectedContent.attr('class', classEnetering);
visibleContent.attr('class', classLeaving).one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(){
visibleContent.removeClass('leave-right leave-left');
selectedContent.removeClass('enter-left enter-right');
});
eventsContent.css('height', selectedContentHeight+'px');
}
function updateOlderEvents(event) {
event.parent('li').prevAll('li').children('a').addClass('older-event').end().end().nextAll('li').children('a').removeClass('older-event');
}
function getTranslateValue(timeline) {
var timelineStyle = window.getComputedStyle(timeline.get(0), null),
timelineTranslate = timelineStyle.getPropertyValue("-webkit-transform") ||
timelineStyle.getPropertyValue("-moz-transform") ||
timelineStyle.getPropertyValue("-ms-transform") ||
timelineStyle.getPropertyValue("-o-transform") ||
timelineStyle.getPropertyValue("transform");
if( timelineTranslate.indexOf('(') >=0 ) {
var timelineTranslate = timelineTranslate.split('(')[1];
timelineTranslate = timelineTranslate.split(')')[0];
timelineTranslate = timelineTranslate.split(',');
var translateValue = timelineTranslate[4];
} else {
var translateValue = 0;
}
return Number(translateValue);
}
function setTransformValue(element, property, value) {
element.style["-webkit-transform"] = property+"("+value+")";
element.style["-moz-transform"] = property+"("+value+")";
element.style["-ms-transform"] = property+"("+value+")";
element.style["-o-transform"] = property+"("+value+")";
element.style["transform"] = property+"("+value+")";
}
//based on http://stackoverflow.com/questions/542938/how-do-i-get-the-number-of-days-between-two-dates-in-javascript
function parseDate(events) {
var dateArrays = [];
events.each(function(){
var singleDate = $(this),
dateComp = singleDate.data('date').split('T');
if( dateComp.length > 1 ) { //both DD/MM/YEAR and time are provided
var dayComp = dateComp[0].split('/'),
timeComp = dateComp[1].split(':');
} else if( dateComp[0].indexOf(':') >=0 ) { //only time is provide
var dayComp = ["2000", "0", "0"],
timeComp = dateComp[0].split(':');
} else { //only DD/MM/YEAR
var dayComp = dateComp[0].split('/'),
timeComp = ["0", "0"];
}
var newDate = new Date(dayComp[2], dayComp[1]-1, dayComp[0], timeComp[0], timeComp[1]);
dateArrays.push(newDate);
});
return dateArrays;
}
function daydiff(first, second) {
return Math.round((second-first));
}
function minLapse(dates) {
//determine the minimum distance among events
var dateDistances = [];
for (i = 1; i < dates.length; i++) {
var distance = daydiff(dates[i-1], dates[i]);
dateDistances.push(distance);
}
return Math.min.apply(null, dateDistances);
}
/*
How to tell if a DOM element is visible in the current viewport?
http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport
*/
function elementInViewport(el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top < (window.pageYOffset + window.innerHeight) &&
left < (window.pageXOffset + window.innerWidth) &&
(top + height) > window.pageYOffset &&
(left + width) > window.pageXOffset
);
}
function checkMQ() {
//check if mobile or desktop device
return window.getComputedStyle(document.querySelector('.cd-horizontal-timeline'), '::before').getPropertyValue('content').replace(/'/g, "").replace(/"/g, "");
}
}); | ftprestes/ciroandrequintino.com.br | js/timeline.js | JavaScript | mit | 13,599 |
# -*- coding: utf-8 -*-
require 'helper'
require 'write_xlsx/package/xml_writer_simple'
class TestXMLWriterSimple < Minitest::Test
def setup
@obj = Writexlsx::Package::XMLWriterSimple.new
end
def test_xml_decl
assert_equal(
%Q!<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n!,
@obj.xml_decl
)
end
def test_empty_tag
assert_equal('<foo/>', @obj.empty_tag('foo'))
end
def test_empty_tag_with_xml_decl
expected = <<EOS
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo/>
EOS
assert_equal(expected, @obj.xml_decl + @obj.empty_tag('foo') + "\n")
end
def test_start_end_tag
assert_equal("<foo></foo>", @obj.start_tag('foo') + @obj.end_tag('foo'))
end
def test_attribute
assert_equal(
"<foo x=\"1>2\"/>", @obj.empty_tag("foo", [ ['x', '1>2'] ])
)
end
def test_character_data
assert_equal(
"<foo><tag>&amp;</tag></foo>",
@obj.start_tag('foo') + @obj.characters("<tag>&</tag>") + @obj.end_tag('foo')
)
end
def test_data_element_with_empty_attr
expected = "<foo>data</foo>"
@obj.data_element('foo', 'data')
result = @obj.string
assert_equal(expected, result)
end
def test_data_element
attributes = [
['name', '_xlnm.Print_Titles'],
['localSheetId', 0]
]
expected =
"<definedName name=\"_xlnm.Print_Titles\" localSheetId=\"0\">Sheet1!$1:$1</definedName>"
@obj.data_element('definedName', 'Sheet1!$1:$1', attributes)
result = @obj.string
assert_equal(expected, result)
end
end
| cxn03651/write_xlsx | test/test_xml_writer_simple.rb | Ruby | mit | 1,586 |
class API::V1::FbPostsController < ApplicationController
respond_to :json
def index
render json: '{"hello":"world"}'
end
end
| amcaplan/watchmyreviews | app/controllers/api/v1/fb_posts_controller.rb | Ruby | mit | 138 |
package simpleci.worker.cache;
public interface DownloadedCacheHandler {
void handleDownloadedCache(String tmpCacheFilePath) throws Exception;
}
| simpleci/simpleci | src/backend/worker/src/main/java/simpleci/worker/cache/DownloadedCacheHandler.java | Java | mit | 150 |
html {
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
}
body {
margin: 0;
}
[lang^="zh"] body{
font-family:"Hiragino Sans GB","华文细黑","STHeiti","微软雅黑",
"Microsoft YaHei",SimHei,"Helvetica Neue",Helvetica,Arial,
sans-serif !important
}
/* HTML5 display definitions
========================================================================== */
article, aside, details, figcaption, figure, footer, header, hgroup, main, nav, section, summary, cite, code, small {
display: block;
}
body, article, section, footer, header, div, input, nav, article ol, article ul, blockquote, figure {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
audio, canvas, progress, video {
display: inline-block; /* 1 */
vertical-align: baseline; /* 2 */
}
audio:not([controls]) {
display: none;
height: 0;
}
[hidden], template {
display: none;
}
/* Links
========================================================================== */
a {
background: transparent;
}
a:active, a:hover {
outline: 0;
}
/* Text-level semantics
========================================================================== */
abbr {
letter-spacing: 0.1em;
}
abbr[title] {
border-bottom: 1px dotted;
}
b, strong {
font-weight: bold;
}
dfn {
font-style: italic;
}
mark {
background: #ff0;
color: #000;
}
small {
font-size: 70%;
}
sub, sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
em, i {
line-height: 0;
position: relative;
vertical-align: baseline;
}
/* Embedded content
========================================================================== */
img {
border: 0;
}
svg:not(:root) {
overflow: hidden;
}
/* Grouping content
========================================================================== */
hr {
-moz-box-sizing: content-box;
box-sizing: content-box;
height: 0;
}
pre {
overflow: auto;
}
code, kbd, pre, samp {
font-family: monospace, monospace;
}
/* Tables
========================================================================== */
table {
border-collapse: collapse;
border-spacing: 0;
}
td, th {
padding: 0;
}
/* Images
========================================================================== */
img {
max-width: 100%;
display: block;
margin: inherit auto;
}
| lilac/lilac.github.io | static/css/reset.css | CSS | mit | 2,352 |
require "spec_helper"
describe Databox::LineChart do
let(:chart){ Databox::LineChart.new "my_line" }
context "simple" do
before {
stub_request(:post, /push/)
.to_return { request_from "line_chart_simple" }
}
before do
chart.add 2000, "2014-01-29"
chart.add 1600, "2014-02-01"
chart.add 999, "2014-02-03"
end
it { expect(chart.save).to be_true }
end
end
| sraka1/databox | spec/databox/line_chart_spec.rb | Ruby | mit | 417 |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="shortcut icon" type="image/x-icon" href="../../../../../../favicon.ico" />
<title>ActivityRecognitionResult | Android Developers</title>
<!-- STYLESHEETS -->
<link rel="stylesheet"
href="http://fonts.googleapis.com/css?family=Roboto:regular,medium,thin,italic,mediumitalic,bold" title="roboto">
<link href="../../../../../../assets/css/default.css" rel="stylesheet" type="text/css">
<!-- FULLSCREEN STYLESHEET -->
<link href="../../../../../../assets/css/fullscreen.css" rel="stylesheet" class="fullscreen"
type="text/css">
<!-- JAVASCRIPT -->
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script src="../../../../../../assets/js/global-libraries-combined.js" type="text/javascript"></script>
<script type="text/javascript">
var toRoot = "../../../../../../";
</script>
<script src="../../../../../../assets/js/docs.js" type="text/javascript"></script>
<script src="../../../../../../navtree_data.js" type="text/javascript"></script>
</head>
<body class="gc-documentation
develop" itemscope itemtype="http://schema.org/Article">
<div id="doc-api-level" class="" style="display:none"></div>
<a name="top"></a>
<!-- Header -->
<div id="header">
<div class="wrap" id="header-wrap">
<div class="col-3 logo">
<a href="../../../../../../index.html">
<img src="../../../../../../assets/images/dac_logo.png" width="123" height="25" alt="Android Developers" />
</a>
<div class="btn-quicknav" id="btn-quicknav">
<a href="#" class="arrow-inactive">Quicknav</a>
<a href="#" class="arrow-active">Quicknav</a>
</div>
</div>
<ul class="nav-x col-9">
<li class="design">
<a href="../../../../../../design/index.html"
zh-TW-lang="設計"
zh-CN-lang="设计"
ru-lang="Проектирование"
ko-lang="디자인"
ja-lang="設計"
es-lang="Diseñar"
>Design</a></li>
<li class="develop"><a href="../../../../../../develop/index.html" class="selected"
zh-TW-lang="開發"
zh-CN-lang="开发"
ru-lang="Разработка"
ko-lang="개발"
ja-lang="開発"
es-lang="Desarrollar"
>Develop</a></li>
<li class="distribute last"><a href="../../../../../../distribute/index.html"
zh-TW-lang="發佈"
zh-CN-lang="分发"
ru-lang="Распространение"
ko-lang="배포"
ja-lang="配布"
es-lang="Distribuir"
>Distribute</a></li>
</ul>
<!-- New Search -->
<div class="menu-container">
<div class="moremenu">
<div id="more-btn"></div>
</div>
<div class="morehover" id="moremenu">
<div class="top"></div>
<div class="mid">
<div class="header">Links</div>
<ul>
<li><a href="https://play.google.com/apps/publish/">Google Play Developer Console</a></li>
<li><a href="http://android-developers.blogspot.com/">Android Developers Blog</a></li>
<li><a href="../../../../../../about/index.html">About Android</a></li>
</ul>
<div class="header">Android Sites</div>
<ul>
<li><a href="http://www.android.com">Android.com</a></li>
<li class="active"><a>Android Developers</a></li>
<li><a href="http://source.android.com">Android Open Source Project</a></li>
</ul>
<!-- <div class="header">Support</div>
<ul>
<li><a href="../../../../../../support.html">Developer Support</a></li>
</ul> -->
<div class="header">Languages</div>
<div id="language" class="locales">
<select name="language" onChange="changeLangPref(this.value, true)">
<option value="en">English</option>
<option value="es">Español</option>
<option value="ja">日本語</option>
<option value="ko">한국어</option>
<option value="ru">Русский</option>
<option value="zh-CN">中文 (中国)</option>
<option value="zh-TW">中文 (台灣)</option>
</select>
</div>
<script type="text/javascript">
<!--
loadLangPref();
//-->
</script>
<br class="clearfix" />
</div>
<div class="bottom"></div>
</div>
<div class="search" id="search-container">
<div class="search-inner">
<div id="search-btn"></div>
<div class="left"></div>
<form onsubmit="return submit_search()">
<input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../../../../')"
onkeyup="return search_changed(event, false, '../../../../../../')" />
</form>
<div class="right"></div>
<a class="close hide">close</a>
<div class="left"></div>
<div class="right"></div>
</div>
</div>
<div id="search_filtered_wrapper">
<div id="search_filtered_div" class="no-display">
<ul id="search_filtered">
</ul>
</div>
</div>
</div>
<!-- /New Search>
<!-- Expanded quicknav -->
<div id="quicknav" class="col-9">
<ul>
<li class="design">
<ul>
<li><a href="../../../../../../design/index.html">Get Started</a></li>
<li><a href="../../../../../../design/style/index.html">Style</a></li>
<li><a href="../../../../../../design/patterns/index.html">Patterns</a></li>
<li><a href="../../../../../../design/building-blocks/index.html">Building Blocks</a></li>
<li><a href="../../../../../../design/downloads/index.html">Downloads</a></li>
<li><a href="../../../../../../design/videos/index.html">Videos</a></li>
</ul>
</li>
<li class="develop">
<ul>
<li><a href="../../../../../../training/index.html"
zh-TW-lang="訓練課程"
zh-CN-lang="培训"
ru-lang="Курсы"
ko-lang="교육"
ja-lang="トレーニング"
es-lang="Capacitación"
>Training</a></li>
<li><a href="../../../../../../guide/components/index.html"
zh-TW-lang="API 指南"
zh-CN-lang="API 指南"
ru-lang="Руководства по API"
ko-lang="API 가이드"
ja-lang="API ガイド"
es-lang="Guías de la API"
>API Guides</a></li>
<li><a href="../../../../../../reference/packages.html"
zh-TW-lang="參考資源"
zh-CN-lang="参考"
ru-lang="Справочник"
ko-lang="참조문서"
ja-lang="リファレンス"
es-lang="Referencia"
>Reference</a></li>
<li><a href="../../../../../../tools/index.html"
zh-TW-lang="相關工具"
zh-CN-lang="工具"
ru-lang="Инструменты"
ko-lang="도구"
ja-lang="ツール"
es-lang="Herramientas"
>Tools</a>
<ul><li><a href="../../../../../../sdk/index.html">Get the SDK</a></li></ul>
</li>
<li><a href="../../../../../../google/index.html">Google Services</a>
</li>
</ul>
</li>
<li class="distribute last">
<ul>
<li><a href="../../../../../../distribute/index.html">Google Play</a></li>
<li><a href="../../../../../../distribute/googleplay/publish/index.html">Publishing</a></li>
<li><a href="../../../../../../distribute/googleplay/promote/index.html">Promoting</a></li>
<li><a href="../../../../../../distribute/googleplay/quality/index.html">App Quality</a></li>
<li><a href="../../../../../../distribute/googleplay/spotlight/index.html">Spotlight</a></li>
<li><a href="../../../../../../distribute/open.html">Open Distribution</a></li>
</ul>
</li>
</ul>
</div>
<!-- /Expanded quicknav -->
</div>
</div>
<!-- /Header -->
<div id="searchResults" class="wrap" style="display:none;">
<h2 id="searchTitle">Results</h2>
<div id="leftSearchControl" class="search-control">Loading...</div>
</div>
<!-- Secondary x-nav -->
<div id="nav-x">
<div class="wrap">
<ul class="nav-x col-9 develop" style="width:100%">
<li><a href="../../../../../../training/index.html"
zh-TW-lang="訓練課程"
zh-CN-lang="培训"
ru-lang="Курсы"
ko-lang="교육"
ja-lang="トレーニング"
es-lang="Capacitación"
>Training</a></li>
<li><a href="../../../../../../guide/components/index.html"
zh-TW-lang="API 指南"
zh-CN-lang="API 指南"
ru-lang="Руководства по API"
ko-lang="API 가이드"
ja-lang="API ガイド"
es-lang="Guías de la API"
>API Guides</a></li>
<li><a href="../../../../../../reference/packages.html" class="selected"
zh-TW-lang="參考資源"
zh-CN-lang="参考"
ru-lang="Справочник"
ko-lang="참조문서"
ja-lang="リファレンス"
es-lang="Referencia"
>Reference</a></li>
<li><a href="../../../../../../tools/index.html"
zh-TW-lang="相關工具"
zh-CN-lang="工具"
ru-lang="Инструменты"
ko-lang="도구"
ja-lang="ツール"
es-lang="Herramientas"
>Tools</a></li>
<li><a href="../../../../../../google/index.html"
>Google Services</a>
</li>
</ul>
</div>
</div>
<!-- /Sendondary x-nav -->
<div class="wrap clearfix" id="body-content">
<div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav">
<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
<div id="api-nav-header">
<div id="api-level-toggle">
<label for="apiLevelCheckbox" class="disabled">API level: </label>
<div class="select-wrapper">
<select id="apiLevelSelector">
<!-- option elements added by buildApiLevelSelector() -->
</select>
</div>
</div><!-- end toggle -->
<div id="api-nav-title">Android APIs</div>
</div><!-- end nav header -->
<script>
var SINCE_DATA = [ ];
buildApiLevelSelector();
</script>
<div id="swapper">
<div id="nav-panels">
<div id="resize-packages-nav">
<div id="packages-nav" class="scroll-pane">
<ul>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/package-summary.html">com.google.android.gms</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/ads/package-summary.html">com.google.android.gms.ads</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/ads/identifier/package-summary.html">com.google.android.gms.ads.identifier</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/ads/mediation/package-summary.html">com.google.android.gms.ads.mediation</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/ads/mediation/admob/package-summary.html">com.google.android.gms.ads.mediation.admob</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/ads/mediation/customevent/package-summary.html">com.google.android.gms.ads.mediation.customevent</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/appstate/package-summary.html">com.google.android.gms.appstate</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/auth/package-summary.html">com.google.android.gms.auth</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/common/package-summary.html">com.google.android.gms.common</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/common/data/package-summary.html">com.google.android.gms.common.data</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/common/images/package-summary.html">com.google.android.gms.common.images</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/games/package-summary.html">com.google.android.gms.games</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/games/achievement/package-summary.html">com.google.android.gms.games.achievement</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/games/leaderboard/package-summary.html">com.google.android.gms.games.leaderboard</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/games/multiplayer/package-summary.html">com.google.android.gms.games.multiplayer</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/games/multiplayer/realtime/package-summary.html">com.google.android.gms.games.multiplayer.realtime</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/gcm/package-summary.html">com.google.android.gms.gcm</a></li>
<li class="selected api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/location/package-summary.html">com.google.android.gms.location</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/maps/package-summary.html">com.google.android.gms.maps</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/maps/model/package-summary.html">com.google.android.gms.maps.model</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/panorama/package-summary.html">com.google.android.gms.panorama</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/plus/package-summary.html">com.google.android.gms.plus</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/plus/model/moments/package-summary.html">com.google.android.gms.plus.model.moments</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/plus/model/people/package-summary.html">com.google.android.gms.plus.model.people</a></li>
<li class="api apilevel-">
<a href="../../../../../../reference/com/google/android/gms/wallet/package-summary.html">com.google.android.gms.wallet</a></li>
</ul><br/>
</div> <!-- end packages-nav -->
</div> <!-- end resize-packages -->
<div id="classes-nav" class="scroll-pane">
<ul>
<li><h2>Interfaces</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../../reference/com/google/android/gms/location/Geofence.html">Geofence</a></li>
<li class="api apilevel-"><a href="../../../../../../reference/com/google/android/gms/location/LocationClient.OnAddGeofencesResultListener.html">LocationClient.OnAddGeofencesResultListener</a></li>
<li class="api apilevel-"><a href="../../../../../../reference/com/google/android/gms/location/LocationClient.OnRemoveGeofencesResultListener.html">LocationClient.OnRemoveGeofencesResultListener</a></li>
<li class="api apilevel-"><a href="../../../../../../reference/com/google/android/gms/location/LocationListener.html">LocationListener</a></li>
</ul>
</li>
<li><h2>Classes</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../../reference/com/google/android/gms/location/ActivityRecognitionClient.html">ActivityRecognitionClient</a></li>
<li class="selected api apilevel-"><a href="../../../../../../reference/com/google/android/gms/location/ActivityRecognitionResult.html">ActivityRecognitionResult</a></li>
<li class="api apilevel-"><a href="../../../../../../reference/com/google/android/gms/location/DetectedActivity.html">DetectedActivity</a></li>
<li class="api apilevel-"><a href="../../../../../../reference/com/google/android/gms/location/Geofence.Builder.html">Geofence.Builder</a></li>
<li class="api apilevel-"><a href="../../../../../../reference/com/google/android/gms/location/LocationClient.html">LocationClient</a></li>
<li class="api apilevel-"><a href="../../../../../../reference/com/google/android/gms/location/LocationRequest.html">LocationRequest</a></li>
<li class="api apilevel-"><a href="../../../../../../reference/com/google/android/gms/location/LocationStatusCodes.html">LocationStatusCodes</a></li>
</ul>
</li>
</ul><br/>
</div><!-- end classes -->
</div><!-- end nav-panels -->
<div id="nav-tree" style="display:none" class="scroll-pane">
<div id="tree-list"></div>
</div><!-- end nav-tree -->
</div><!-- end swapper -->
<div id="nav-swap">
<a class="fullscreen">fullscreen</a>
<a href='#' onclick='swapNav();return false;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>
</div>
</div> <!-- end devdoc-nav -->
</div> <!-- end side-nav -->
<script type="text/javascript">
// init fullscreen based on user pref
var fullscreen = readCookie("fullscreen");
if (fullscreen != 0) {
if (fullscreen == "false") {
toggleFullscreen(false);
} else {
toggleFullscreen(true);
}
}
// init nav version for mobile
if (isMobile) {
swapNav(); // tree view should be used on mobile
$('#nav-swap').hide();
} else {
chooseDefaultNav();
if ($("#nav-tree").is(':visible')) {
init_default_navtree("../../../../../../");
}
}
// scroll the selected page into view
$(document).ready(function() {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
});
</script>
<script>
$(document).ready(function() {
changeDocLang(getLangPref());
});
</script>
<div class="col-12" id="doc-col">
<div id="api-info-block">
<div class="sum-details-links">
Summary:
<a href="#constants">Constants</a>
| <a href="#inhconstants">Inherited Constants</a>
| <a href="#lfields">Fields</a>
| <a href="#pubctors">Ctors</a>
| <a href="#pubmethods">Methods</a>
| <a href="#inhmethods">Inherited Methods</a>
| <a href="#" onclick="return toggleAllClassInherited()" id="toggleAllClassInherited">[Expand All]</a>
</div><!-- end sum-details-links -->
<div class="api-level">
</div>
</div><!-- end api-info-block -->
<!-- ======== START OF CLASS DATA ======== -->
<div id="jd-header">
public
class
<h1 itemprop="name">ActivityRecognitionResult</h1>
extends Object<br/>
implements
Parcelable
</div><!-- end header -->
<div id="naMessage"></div>
<div id="jd-content" class="api apilevel-">
<table class="jd-inheritance-table">
<tr>
<td colspan="2" class="jd-inheritance-class-cell">java.lang.Object</td>
</tr>
<tr>
<td class="jd-inheritance-space"> ↳</td>
<td colspan="1" class="jd-inheritance-class-cell">com.google.android.gms.location.ActivityRecognitionResult</td>
</tr>
</table>
<div class="jd-descr">
<h2>Class Overview</h2>
<p itemprop="articleBody">Result of an activity recognition.
<p>
It contains a list of activities that a user may have been doing at a
particular time. The activities are sorted by the most probable activity
first. A confidence is associated with each activity which indicates how
likely that activity is.
<p>
<code><a href="../../../../../../reference/com/google/android/gms/location/ActivityRecognitionResult.html#getMostProbableActivity()">getMostProbableActivity()</a></code> will return the most probable activity of
the user at the time that activity recognition was run.
</p>
</div><!-- jd-descr -->
<div class="jd-descr">
<h2>Summary</h2>
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<table id="constants" class="jd-sumtable"><tr><th colspan="12">Constants</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">String</td>
<td class="jd-linkcol"><a href="../../../../../../reference/com/google/android/gms/location/ActivityRecognitionResult.html#EXTRA_ACTIVITY_RESULT">EXTRA_ACTIVITY_RESULT</a></td>
<td class="jd-descrcol" width="100%"></td>
</tr>
</table>
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<table id="inhconstants" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited Constants</div></th></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-constants-android.os.Parcelable" class="jd-expando-trigger closed"
><img id="inherited-constants-android.os.Parcelable-trigger"
src="../../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>From interface
android.os.Parcelable
<div id="inherited-constants-android.os.Parcelable">
<div id="inherited-constants-android.os.Parcelable-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-constants-android.os.Parcelable-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">int</td>
<td class="jd-linkcol">CONTENTS_FILE_DESCRIPTOR</td>
<td class="jd-descrcol" width="100%"></td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">int</td>
<td class="jd-linkcol">PARCELABLE_WRITE_RETURN_VALUE</td>
<td class="jd-descrcol" width="100%"></td>
</tr>
</table>
</div>
</div>
</td></tr>
</table>
<!-- =========== FIELD SUMMARY =========== -->
<table id="lfields" class="jd-sumtable"><tr><th colspan="12">Fields</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
public
static
final
<a href="../../../../../../reference/com/google/android/gms/location/ActivityRecognitionResultCreator.html">ActivityRecognitionResultCreator</a></nobr></td>
<td class="jd-linkcol"><a href="../../../../../../reference/com/google/android/gms/location/ActivityRecognitionResult.html#CREATOR">CREATOR</a></td>
<td class="jd-descrcol" width="100%"></td>
</tr>
</table>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<table id="pubctors" class="jd-sumtable"><tr><th colspan="12">Public Constructors</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../reference/com/google/android/gms/location/ActivityRecognitionResult.html#ActivityRecognitionResult(java.util.List<com.google.android.gms.location.DetectedActivity>, long, long)">ActivityRecognitionResult</a></span>(List<<a href="../../../../../../reference/com/google/android/gms/location/DetectedActivity.html">DetectedActivity</a>> probableActivities, long time, long elapsedRealtimeMillis)</nobr>
<div class="jd-descrdiv">Constructs an ActivityRecognitionResult.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../reference/com/google/android/gms/location/ActivityRecognitionResult.html#ActivityRecognitionResult(com.google.android.gms.location.DetectedActivity, long, long)">ActivityRecognitionResult</a></span>(<a href="../../../../../../reference/com/google/android/gms/location/DetectedActivity.html">DetectedActivity</a> mostProbableActivity, long time, long elapsedRealtimeMillis)</nobr>
<div class="jd-descrdiv">Constructs an ActivityRecognitionResult from a single activity.</div>
</td></tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="pubmethods" class="jd-sumtable"><tr><th colspan="12">Public Methods</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../reference/com/google/android/gms/location/ActivityRecognitionResult.html#describeContents()">describeContents</a></span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
static
<a href="../../../../../../reference/com/google/android/gms/location/ActivityRecognitionResult.html">ActivityRecognitionResult</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../reference/com/google/android/gms/location/ActivityRecognitionResult.html#extractResult(android.content.Intent)">extractResult</a></span>(Intent intent)</nobr>
<div class="jd-descrdiv">Extracts the ActivityRecognitionResult from an Intent.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../reference/com/google/android/gms/location/ActivityRecognitionResult.html#getActivityConfidence(int)">getActivityConfidence</a></span>(int activityType)</nobr>
<div class="jd-descrdiv">Returns the confidence of the given activity type.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
long</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../reference/com/google/android/gms/location/ActivityRecognitionResult.html#getElapsedRealtimeMillis()">getElapsedRealtimeMillis</a></span>()</nobr>
<div class="jd-descrdiv">Returns the elapsed real time of this detection in milliseconds since
boot, including time spent in sleep as obtained by
SystemClock.elapsedRealtime().</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="../../../../../../reference/com/google/android/gms/location/DetectedActivity.html">DetectedActivity</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../reference/com/google/android/gms/location/ActivityRecognitionResult.html#getMostProbableActivity()">getMostProbableActivity</a></span>()</nobr>
<div class="jd-descrdiv">Returns the most probable activity of the user.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
List<<a href="../../../../../../reference/com/google/android/gms/location/DetectedActivity.html">DetectedActivity</a>></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../reference/com/google/android/gms/location/ActivityRecognitionResult.html#getProbableActivities()">getProbableActivities</a></span>()</nobr>
<div class="jd-descrdiv">Returns the list of activities that where detected with the confidence
value associated with each activity.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
long</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../reference/com/google/android/gms/location/ActivityRecognitionResult.html#getTime()">getTime</a></span>()</nobr>
<div class="jd-descrdiv">Returns the UTC time of this detection, in milliseconds since January 1,
1970.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
static
boolean</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../reference/com/google/android/gms/location/ActivityRecognitionResult.html#hasResult(android.content.Intent)">hasResult</a></span>(Intent intent)</nobr>
<div class="jd-descrdiv">Returns true if an Intent contains an ActivityRecognitionResult.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
String</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../reference/com/google/android/gms/location/ActivityRecognitionResult.html#toString()">toString</a></span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../reference/com/google/android/gms/location/ActivityRecognitionResult.html#writeToParcel(android.os.Parcel, int)">writeToParcel</a></span>(Parcel out, int flags)</nobr>
</td></tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="inhmethods" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited Methods</div></th></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-java.lang.Object" class="jd-expando-trigger closed"
><img id="inherited-methods-java.lang.Object-trigger"
src="../../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From class
java.lang.Object
<div id="inherited-methods-java.lang.Object">
<div id="inherited-methods-java.lang.Object-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-java.lang.Object-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
Object</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">clone</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
boolean</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">equals</span>(Object arg0)</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">finalize</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
final
Class<?></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">getClass</span>()</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">hashCode</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">notify</span>()</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">notifyAll</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
String</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">toString</span>()</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">wait</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">wait</span>(long arg0, int arg1)</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">wait</span>(long arg0)</nobr>
</td></tr>
</table>
</div>
</div>
</td></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-android.os.Parcelable" class="jd-expando-trigger closed"
><img id="inherited-methods-android.os.Parcelable-trigger"
src="../../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From interface
android.os.Parcelable
<div id="inherited-methods-android.os.Parcelable">
<div id="inherited-methods-android.os.Parcelable-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-android.os.Parcelable-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
abstract
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">describeContents</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
abstract
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">writeToParcel</span>(Parcel arg0, int arg1)</nobr>
</td></tr>
</table>
</div>
</div>
</td></tr>
</table>
</div><!-- jd-descr (summary) -->
<!-- Details -->
<!-- XML Attributes -->
<!-- Enum Values -->
<!-- Constants -->
<!-- ========= ENUM CONSTANTS DETAIL ======== -->
<h2>Constants</h2>
<A NAME="EXTRA_ACTIVITY_RESULT"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
static
final
String
</span>
EXTRA_ACTIVITY_RESULT
</h4>
<div class="api-level">
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
<div class="jd-tagdata">
<span class="jd-tagtitle">Constant Value: </span>
<span>
"com.google.android.location.internal.EXTRA_ACTIVITY_RESULT"
</span>
</div>
</div>
</div>
<!-- Fields -->
<!-- ========= FIELD DETAIL ======== -->
<h2>Fields</h2>
<A NAME="CREATOR"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
static
final
<a href="../../../../../../reference/com/google/android/gms/location/ActivityRecognitionResultCreator.html">ActivityRecognitionResultCreator</a>
</span>
CREATOR
</h4>
<div class="api-level">
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<!-- Public ctors -->
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<h2>Public Constructors</h2>
<A NAME="ActivityRecognitionResult(java.util.List<com.google.android.gms.location.DetectedActivity>, long, long)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
</span>
<span class="sympad">ActivityRecognitionResult</span>
<span class="normal">(List<<a href="../../../../../../reference/com/google/android/gms/location/DetectedActivity.html">DetectedActivity</a>> probableActivities, long time, long elapsedRealtimeMillis)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Constructs an ActivityRecognitionResult.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>probableActivities</td>
<td>the activities that where detected, sorted by
confidence (most probable first).</td>
</tr>
<tr>
<th>time</td>
<td>the UTC time of this detection, in milliseconds since January
1, 1970.</td>
</tr>
<tr>
<th>elapsedRealtimeMillis</td>
<td>milliseconds since boot
</td>
</tr>
</table>
</div>
</div>
</div>
<A NAME="ActivityRecognitionResult(com.google.android.gms.location.DetectedActivity, long, long)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
</span>
<span class="sympad">ActivityRecognitionResult</span>
<span class="normal">(<a href="../../../../../../reference/com/google/android/gms/location/DetectedActivity.html">DetectedActivity</a> mostProbableActivity, long time, long elapsedRealtimeMillis)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Constructs an ActivityRecognitionResult from a single activity.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>mostProbableActivity</td>
<td>the most probable activity of the device.</td>
</tr>
<tr>
<th>time</td>
<td>the UTC time of this detection, in milliseconds since January
1, 1970.</td>
</tr>
<tr>
<th>elapsedRealtimeMillis</td>
<td>milliseconds since boot.
</td>
</tr>
</table>
</div>
</div>
</div>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<!-- Protected ctors -->
<!-- ========= METHOD DETAIL ======== -->
<!-- Public methdos -->
<h2>Public Methods</h2>
<A NAME="describeContents()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
int
</span>
<span class="sympad">describeContents</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<A NAME="extractResult(android.content.Intent)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
static
<a href="../../../../../../reference/com/google/android/gms/location/ActivityRecognitionResult.html">ActivityRecognitionResult</a>
</span>
<span class="sympad">extractResult</span>
<span class="normal">(Intent intent)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Extracts the ActivityRecognitionResult from an Intent.
<p>
This is a utility function which extracts the ActivityRecognitionResult
from the extras of an Intent that was sent from the activity detection
service.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>an ActivityRecognitionResult, or <code>null</code> if the intent doesn't
contain an ActivityRecognitionResult.
</li></ul>
</div>
</div>
</div>
<A NAME="getActivityConfidence(int)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
int
</span>
<span class="sympad">getActivityConfidence</span>
<span class="normal">(int activityType)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns the confidence of the given activity type.
</p></div>
</div>
</div>
<A NAME="getElapsedRealtimeMillis()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
long
</span>
<span class="sympad">getElapsedRealtimeMillis</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns the elapsed real time of this detection in milliseconds since
boot, including time spent in sleep as obtained by
SystemClock.elapsedRealtime().
</p></div>
</div>
</div>
<A NAME="getMostProbableActivity()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../../../../reference/com/google/android/gms/location/DetectedActivity.html">DetectedActivity</a>
</span>
<span class="sympad">getMostProbableActivity</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns the most probable activity of the user.
</p></div>
</div>
</div>
<A NAME="getProbableActivities()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
List<<a href="../../../../../../reference/com/google/android/gms/location/DetectedActivity.html">DetectedActivity</a>>
</span>
<span class="sympad">getProbableActivities</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns the list of activities that where detected with the confidence
value associated with each activity. The activities are sorted by most
probable activity first.
<p>
The sum of confidence values for the activities is guaranteed to be <=
100.
</p></div>
</div>
</div>
<A NAME="getTime()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
long
</span>
<span class="sympad">getTime</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns the UTC time of this detection, in milliseconds since January 1,
1970.
</p></div>
</div>
</div>
<A NAME="hasResult(android.content.Intent)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
static
boolean
</span>
<span class="sympad">hasResult</span>
<span class="normal">(Intent intent)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns true if an Intent contains an ActivityRecognitionResult.
<p>
This is a utility function that can be called from inside an intent
receiver to make sure the received intent is from activity recognition.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>true if the intent contains an ActivityRecognitionResult, false
otherwise.
</li></ul>
</div>
</div>
</div>
<A NAME="toString()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
String
</span>
<span class="sympad">toString</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<A NAME="writeToParcel(android.os.Parcel, int)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
void
</span>
<span class="sympad">writeToParcel</span>
<span class="normal">(Parcel out, int flags)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<!-- ========= METHOD DETAIL ======== -->
<!-- ========= END OF CLASS DATA ========= -->
<A NAME="navbar_top"></A>
<div id="footer" class="wrap" >
<div id="copyright">
Except as noted, this content is licensed under <a
href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>.
For details and restrictions, see the <a href="../../../../../../license.html">
Content License</a>.
</div>
<div id="build_info">
Android r — 25 Oct 2013 17:03
</div>
<div id="footerlinks">
<p>
<a href="../../../../../../about/index.html">About Android</a> |
<a href="../../../../../../legal.html">Legal</a> |
<a href="../../../../../../support.html">Support</a>
</p>
</div>
</div> <!-- end footer -->
</div> <!-- jd-content -->
</div><!-- end doc-content -->
</div> <!-- end body-content -->
<!-- Grid - for dev
<script type="text/javascript">
window.gOverride = {
gColor: '#FF0000',
pColor: '#EEEEEE',
gOpacity: 0.10,
pOpacity: 0.40,
pHeight: 16,
pOffset: 2,
gColumns:16,
gEnabled:false,
pEnabled:false
}
</script>
<link href="../../../../../../assets/js/grid/960.gridder.css" rel="stylesheet" type="text/css">
<script src="../../../../../../assets/js/grid/960.gridder.js" type="text/javascript"></script>
-->
<script type="text/javascript">
init(); /* initialize android-developer-docs.js */
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-5831155-1");
pageTracker._trackPageview();
</script>
</body>
</html>
| NebulaX/Maestro | google_play_services/docs/reference/com/google/android/gms/location/ActivityRecognitionResult.html | HTML | mit | 52,531 |
Docker for go-ethereum
============================
* OS: `Ubuntu 16.04 LTS`
* Docker image: build by yourself
* geth version: v1.8.20 with RPC parity_submitWorkDetail
## Install Docker CE
```
# Use official mirrors
curl -fsSL https://get.docker.com | bash -s docker
# Or use Aliyun mirrors
curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun
```
## Change Image Mirrors and Data Root (optional)
```
mkdir -p /work/docker
vim /eth/docker/daemon.json
```
```
{
"registry-mirrors": ["https://<REPLACED-TO-YOUR-MIRROR-ID>.mirror.aliyuncs.com"],
"data-root": "/work/docker"
}
```
```
service docker restart
```
## Build Docker Image
```
git clone --depth=1 -b v1.8.23-btcpool https://github.com/btccom/go-ethereum.git
cd go-ethereum
docker build -t eth-geth:1.8.23-btcpool .
```
## Create Config Files
### Command Line Options
```
mkdir -p /work/ethereum/eth-geth
vim /work/ethereum/eth-geth/config.sh
```
```
geth \
--rpc \
--rpcaddr='0.0.0.0' \
--rpcvhosts='*' \
--mine \
--etherbase='<your ethereum address>' \
--extradata='Project BTCPool' \
--cache=2048 \
--maxpeers=200 \
>> /root/.ethereum/debug.log 2>&1
```
Tips:
* It's a shell script for running `geth`.
* Suggested format:
- The first line is the program name `geth`.
- One configuration per line, ending with `\`.
- The last line is a output redirection or a single semicolon (`;`) if you don't want a log file.
#### Why is it a shell script instead of a configuration file?
@YihaoPeng wrote on September 4, 2018:
<blockquote>
At the beginning, I want to use the configuration file (`--config=xxx.toml`) of `geth`.
However, [a decision](https://blog.ethereum.org/2017/04/14/geth-1-6-puppeth-master/) by `geth`'s developer made my plan unsuccessful:
> Certain fields have been omitted to prevent sensitive data circulating in configuration files.
So `--extradata` is omitted... But it is not sensitive at all, it will be public in each block you mined!
Although very unhappy, I have no choice. I can only switch to using the shell script.
In addition, writing configuration files directly is difficult due to the lack of official documentation.
You can only write the command line options first, then use the `dumpconfig` command to generate a configuration file.
So why not just use the shell script directly? Although it's not so readable, it has good documentation,
can be written directly, and can controls all the features you want to control.
However, I still hope to have a regular and convenient configuration file.

</blockquote>
### Static Nodes
```
mkdir -p /work/ethereum/eth-geth/geth/
vim /work/ethereum/eth-geth/geth/static-nodes.json
```
```
[
"enode://f4642fa65af50cfdea8fa7414a5def7bb7991478b768e296f5e4a54e8b995de102e0ceae2e826f293c481b5325f89be6d207b003382e18a8ecba66fbaf6416c0@33.4.2.1:30303",
"enode://pubkey@ip:port"
]
```
## Start Docker Container
```
# start docker
docker run -it -v /work/ethereum/eth-geth/:/root/.ethereum/ -p 8545:8545 -p 30303:30303 --name eth-geth --restart always -d eth-geth:1.8.23-btcpool
# see the log
tail -f /work/ethereum/eth-geth/geth.log
# login
docker exec -it eth-geth sh
# If it not running properly, you can debug it
docker stop eth-geth
docker rm eth-geth
docker run -it -v /work/ethereum/eth-geth/:/root/.ethereum/ -p 8545:8545 -p 30303:30303 --name eth-geth --entrypoint=/bin/sh eth-geth:1.8.23-btcpool
```
| btccom/btcpool | docker/eth-geth/v1.8.23-btcpool-patched/README.md | Markdown | mit | 3,498 |
<?php
/**
* This file is part of prestaconcept/symfony-prestacms
*
* (c) PrestaConcept <http://www.prestaconcept.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Application\Presta\CMSCoreBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
/**
* @author Nicolas Bastien <[email protected]>
*/
class ApplicationPrestaCMSCoreBundle extends Bundle
{
/**
* {@inheritdoc}
*/
public function getParent()
{
return 'PrestaCMSCoreBundle';
}
}
| prestaconcept/symfony-prestacms | src/Application/Presta/CMSCoreBundle/ApplicationPrestaCMSCoreBundle.php | PHP | mit | 588 |
import { TestBed, inject } from '@angular/core/testing';
import { SsrsReportService } from './ssrs-report.service';
import { HttpService } from './http.service';
import { FTHelperService } from '../helper/ftHelper.service';
describe('SsrsReportService', () => {
let ftHelperService: any;
let httpService: any;
beforeEach(() => {
ftHelperService = jasmine.createSpyObj('FTHelperService', ['version']);
httpService = jasmine.createSpyObj('HttpService', ['']);
TestBed.configureTestingModule({
providers: [SsrsReportService,
{ provide: FTHelperService, useValue: ftHelperService },
{ provide: HttpService, useValue: httpService }]
});
});
it('should be created', inject([SsrsReportService], (service: SsrsReportService) => {
expect(service).toBeTruthy();
}));
});
| PublicHealthEngland/fingertips-open | IndicatorsUI/MainUI/angular-app/src/app/shared/service/api/ssrs-report.service.spec.ts | TypeScript | mit | 824 |
'use strict';
// MODULES //
var randUniform = require( 'distributions-uniform-random/lib/number.js' );
// FUNCTIONS //
var pow = Math.pow;
// PARTIAL //
/**
* FUNCTION: partial( alpha, beta[, rand] )
* Partially applies `alpha` and `beta` and returns a function
* to generate random variables from the Pareto (Type I) distribution.
*
* @param {Number} alpha - shape parameter
* @param {Number} beta - scale parameter
* @param {Function} [rand=Math.random] - random number generator
* @returns {Function} function which generates random draws from the specified distribution
*/
function partial( alpha, beta, rand ) {
/**
* FUNCTION: draw( x )
* Generates a random draw for a inverse-gamma distribution with parameters `alpha` and `beta`.
*
* @private
* @returns {Number} random draw from the specified distribution
*/
return function draw() {
var u = randUniform( 0, 1, rand );
return beta / pow( u, 1/alpha );
}; // end FUNCTION draw()
} // end FUNCTION partial()
// EXPORTS //
module.exports = partial;
| distributions-io/pareto-type1-random | lib/partial.js | JavaScript | mit | 1,029 |
<html>
<head>
<title>
Standing up for our rights
</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>
</head>
<body bgcolor="#FFFFCC" text="000000" link="990000" vlink="660000" alink="003366" leftmargin="0" topmargin="0">
<table width="744" cellspacing="0" cellpadding="0" border="0">
<tr><td width="474"><a name="Top"></a><?php include "../../legacy-includes/TopLogo.htmlf" ?></td>
<td width="270"><?php include "../../legacy-includes/TopAd.htmlf" ?>
</td></tr></table>
<table width="744" cellspacing="0" cellpadding="0" border="0">
<tr><td width="18" bgcolor="FFCC66"></td>
<td width="108" bgcolor="FFCC66" valign=top><?php include "../../legacy-includes/LeftButtons.htmlf" ?></td>
<td width="18"></td>
<td width="480" valign="top">
<?php include "../../legacy-includes/BodyInsert.htmlf" ?>
<P><font face="Times New Roman, Times, serif" size="4">Harassed by police for selling <I>Socialist Worker</font><br></I>
<font face="Times New Roman, Times, serif" size="5"><b>Standing up for our rights</b></font></P>
<p><font face="Arial, Helvetica, sans-serif" size="2">July 18, 2003 | Page 4</font></p>
<B><P><font face="Times New Roman, Times, serif" size="3">Dear <I>Socialist Worker,</P>
</B></I><P>Living in New York City after September 11 means dealing with cops who feel they have a special new right to harass people. I'm white, but I spend most of my time in a Black neighborhood in the city. </P>
<P>In addition to seeing the police abuse people frequently, I have been pulled over in my car seven times this year--simply because I've been in the "wrong place." The supposed "budget crisis" in New York means that cops are also looking for any excuse to give working class people expensive tickets.</P>
<P>When my branch of the International Socialist Organization (ISO) sells <I>Socialist Worker</I> in Harlem, which we've been doing without hassle for years, we are now getting cops in our face at every turn. Recently, a cop came up to our sale and gave me a criminal summons--forcing me to appear in court and miss a day of work to answer charges of selling a newspaper without a tax stamp.</P>
<P>Of course, the cop didn't care that it is our right as a political group to sell our newspaper and to distribute literature. Apparently, the Constitution doesn't apply if the NYPD is in the mood to make up their own laws.</P>
<P>My day in court started with a three-hour line, since billionaire Mayor Michael Bloomberg just can't find the money to pay city workers like court clerks. No surprise, most of the angry people waiting with me were Black and Latino. When I finally went in front of the judge for my arraignment, I found that I had a city-appointed attorney who wouldn't even let me talk. </P>
<P>Since my lawyer didn't know the case or the laws involved, he just told the judge that I had the right to free speech. The judge disagreed and wanted the case to go to trial. Luckily, I had gone online and researched the law that I was charged under. I asked the judge if I could speak on my own behalf. </P>
<P>I cited the law and told him that paper sales were explicitly exempted under the "definitions" clause of the statute, and I cited a Supreme Court case that ISO members know about. The judge actually said that I'd represented myself very well (he looked at "my" lawyer like he was an arrogant jerk) and told me that he would dismiss the case. </P>
<P>This time, standing up for myself and knowing the law worked to get me off. But as socialists in a climate of right-wing hysteria and city budget cuts, we will have to be prepared to keep fighting tooth and nail for our right to free speech.</P>
<B><P>David Rapkin, </B>New York City</P>
<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>
<td width="12"></td>
<td width="108" valign="top">
<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>
</td>
</tr>
</table>
</body>
</html>
| ISO-tech/sw-d8 | web/2003-2/461/461_04_SellingSW.php | PHP | mit | 3,975 |
import React from "react";
import format from "date-fns/format";
import axios from 'axios';
export default class GalleriesPreview extends React.Component {
constructor(props) {
super(props);
this.state = {
photos: []
}
}
render() {
const {entry, widgetFor} = this.props,
user_id = "19709765",
gallery_id = entry.getIn(['data', 'gallery_id']),
_this = this;
let photoArray = [];
// Fetch the data from the provided gallery ID
axios.get('https://api.500px.com/v1/users/' + user_id + '/galleries/' + gallery_id + '/items', {
params: {
image_size: 4,
consumer_key: "RgAZO3RwsFWdy1eNCnwiC5JaSBxTFypd3cvVbVMl"
}
})
.then(function (response) {
console.log(response);
//photoData = response.data.photos;
_this.setState({
photos: response.data.photos
});
})
.catch(function (error) {
console.log(error);
});
if (this.state.photos.length > 0) {
for (var i in this.state.photos) {
let self = this.state.photos[i];
photoArray.push(
<div>
<img src={self.image_url} alt={self.name} />
<p>{self.description}</p>
</div>
);
}
}
return (
<article className="content">
<header className="container">
<div className="content-narrow u-center">
<h1>{ entry.getIn(["data", "title"])}</h1>
</div>
</header>
<section className="cms container">
<div className="content__body">
{photoArray}
</div>
</section>
</article>
);
}
}
| ianmilliken/trifi | src/js/cms-preview-templates/galleries.js | JavaScript | mit | 1,670 |
<?php
require_once __DIR__ . '/../autoload.php';
use const nspl\f\apply;
use const nspl\op\gt;
use const nspl\op\object;
use function nspl\a\all;
use function nspl\a\map;
use function nspl\a\sorted;
use function nspl\a\zip;
use function nspl\f\partial;
use function nspl\f\rpartial;
use function nspl\op\instanceCreator;
use function nspl\op\itemGetter;
class User {
private $name;
private $age;
public function __construct($name, $age=0) {
$this->name = $name;
$this->age = $age;
}
}
$users = [
array('name' => 'John', 'age' => 15),
array('name' => 'Jack', 'age' => 35),
array('name' => 'Sarah', 'age' => 25),
array('name' => 'Norah', 'age' => 20),
array('name' => 'Michael', 'age' => 30),
];
// 1. Get user names from list of users presented with array data
$names = map(itemGetter('name'), $users);
$ages = map(itemGetter('age'), $users);
echo sprintf("User names are: %s (users were presented with array data)\n", implode(', ', $names));
// 2. Convert list of user presented with array data to list of objects
$objects = map(object, $users);
echo sprintf("List of users converted to objects consists of types: %s\n", implode(', ', map(\nspl\getType, $objects)));
$userClassObjectsWithName = map(instanceCreator(User::class), $names);
echo sprintf("List of user class instances with name consists of types: %s\n", implode(', ', map(\nspl\getType, $userClassObjectsWithName)));
$userClassObjectsWithNameAndAge = map(partial(apply, instanceCreator(User::class)), zip($names, $ages));
echo sprintf("List of user class instances name and age consists of types: %s\n", implode(', ', map(\nspl\getType, $userClassObjectsWithNameAndAge)));
// 3. Sort users by age
$sorted = sorted($users, false, itemGetter('age'));
echo "Users sorted by age:\n";
foreach ($sorted as $user) {
echo sprintf(" %s - %s y.o.\n", $user['name'], $user['age']);
}
// 4. Check if all numbers are positive
$allPositive = all([1, 2, 3, 4, 5], rpartial(gt, 0));
echo $allPositive ? "All numbers are positive\n" : "At least one number was not positive\n";
| ihor/Nspl | examples/op.php | PHP | mit | 2,080 |
//
// AppDelegate.h
// RefreshDemo
//
// Created by neal on 15/6/25.
// Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| applexiaohao/LORefreshControl | RefreshDemo/RefreshDemo/AppDelegate.h | C | mit | 280 |
'use strict';
require('mocha');
var assert = require('assert');
var name = require('./');
describe('project-name', function() {
it('should return the name from package.json', function() {
assert.equal(name(), 'project-name');
});
it('should return the name from a directory', function() {
assert.equal(name('fixtures/foo'), 'foo');
});
it('should return the name from an empty directory', function() {
assert.equal(name('fixtures/foo/bar'), 'bar');
});
it('should return the name from a git config', function() {
assert.equal(name('fixtures/foo'), 'foo');
});
});
| jonschlinkert/project-name | test.js | JavaScript | mit | 601 |
#!/usr/bin/perl
use strict;
use warnings;
# This class is generated from DBIx.pm. Do not modify.
package WWW::Shopify::Model::DBIx::Schema::Result::Model::APIClient;
use base qw/DBIx::Class::Core/;
__PACKAGE__->load_components(qw/InflateColumn::DateTime/);
__PACKAGE__->table('shopify_api_clients');
__PACKAGE__->add_columns(
"title", { is_nullable => '1', data_type => 'TEXT' },
"visible", { is_nullable => '1', data_type => 'BOOL' },
"embedded", { is_nullable => '1', data_type => 'BOOL' },
"api_url", { data_type => 'VARCHAR(255)', is_nullable => '1' },
"api_permissions_count", { is_nullable => '1', data_type => 'INT' },
"shared_secret", { is_nullable => '1', data_type => 'VARCHAR(255)' },
"support_url", { data_type => 'VARCHAR(255)', is_nullable => '1' },
"created_at", { is_nullable => '1', data_type => 'DATETIME' },
"id", { data_type => 'BIGINT', is_nullable => '0' },
"api_key", { is_nullable => '1', data_type => 'VARCHAR(255)' },
"kind", { data_type => 'VARCHAR(255)', is_nullable => '1' },
"number", { is_nullable => '1', data_type => 'INT' },
"application_developer_id", { data_type => 'BIGINT', is_nullable => '1' },
"shop_id", { data_type => "BIGINT" }
);
__PACKAGE__->set_primary_key('id');
__PACKAGE__->belongs_to(shop => 'WWW::Shopify::Model::DBIx::Schema::Result::Model::Shop', 'shop_id');
__PACKAGE__->belongs_to(application_developer => 'WWW::Shopify::Model::DBIx::Schema::Result::Model::Shop', 'application_developer_id', { join_type => 'left' });
sub represents { return 'WWW::Shopify::Model::APIClient'; }
sub parent_variable { return undef; }
1; | gitpan/WWW-Shopify | lib/WWW/Shopify/Model/DBIx/Schema/Result/Model/APIClient.pm | Perl | mit | 1,595 |
using Microsoft.WindowsAzure.MobileServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TimelineForms.Services
{
/// <summary>
/// https://azure.microsoft.com/en-us/documentation/articles/app-service-mobile-xamarin-forms-get-started-users
/// </summary>
public interface IAuthenticator
{
Task<MobileServiceUser> LoginAsync();
Task LogoutAsync();
}
}
| DotNetToscana/TimelineForms | Src/Client/TimelineForms/TimelineForms/Services/IAuthenticator.cs | C# | mit | 478 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>equations: 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 / released</a></li>
<li class="active"><a href="">8.7.1 / equations - 1.2.1+8.10</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
equations
<small>
1.2.1+8.10
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-02-24 17:13:48 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-24 17:13:48 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.7.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.06.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.06.1 Official 4.06.1 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
authors: [ "Matthieu Sozeau <[email protected]>" "Cyprien Mangin <[email protected]>" ]
dev-repo: "git+https://github.com/mattam82/Coq-Equations.git"
maintainer: "[email protected]"
homepage: "https://mattam82.github.io/Coq-Equations"
bug-reports: "https://github.com/mattam82/Coq-Equations/issues"
license: "LGPL-2.1-or-later"
synopsis: "A function definition package for Coq"
description: """
Equations is a function definition plugin for Coq, that allows the
definition of functions by dependent pattern-matching and well-founded,
mutual or nested structural recursion and compiles them into core
terms. It automatically derives the clauses equations, the graph of the
function and its associated elimination principle.
"""
tags: [
"keyword:dependent pattern-matching"
"keyword:functional elimination"
"category:Miscellaneous/Coq Extensions"
"logpath:Equations"
]
build: [
["./configure.sh" "HoTT" {coq-hott:installed}]
[make "-j%{jobs}%"]
]
install: [
[make "install"]
]
run-test: [
[make "test-suite"]
]
depends: [
"coq" {>= "8.10~" & < "8.11~"}
]
depopts: [ "coq-hott" {= "8.10.dev" } ]
url {
src:
"https://github.com/mattam82/Coq-Equations/archive/v1.2.1-8.10-2.tar.gz"
checksum: "sha512=f95dc46d905a28e62846991fa9612476019f933ac7bee2117f1d1c17a2ea78c66f925d14dd11534c29526fe9cabc77efd7fea78b0a32c82af0c50360b4a123fb"
}
</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-equations.1.2.1+8.10 coq.8.7.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1).
The following dependencies couldn't be met:
- coq-equations -> coq >= 8.10~
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-equations.1.2.1+8.10</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.06.1-2.0.5/released/8.7.1/equations/1.2.1+8.10.html | HTML | mit | 7,417 |
module.exports = function ( karma ) {
karma.set({
/**
* From where to look for files, starting with the location of this file.
*/
basePath: '../',
/**
* This is the list of file patterns to load into the browser during testing.
*/
files: [
'vendor/angular/angular.js',
'vendor/angular-bootstrap/ui-bootstrap-tpls.min.js',
'vendor/placeholders/angular-placeholders-0.0.1-SNAPSHOT.min.js',
'vendor/angular-ui-router/release/angular-ui-router.js',
'vendor/angularjs-slider/dist/rzslider.min.js',
'vendor/moment/moment.js',
'vendor/angular-moment/angular-moment.js',
'build/templates-app.js',
'build/templates-common.js',
'vendor/angular-mocks/angular-mocks.js',
'src/**/*.js',
'src/**/*.coffee',
],
exclude: [
'src/assets/**/*.js'
],
frameworks: [ 'jasmine' ],
plugins: [ 'karma-jasmine', 'karma-firefox-launcher', 'karma-coffee-preprocessor' ],
preprocessors: {
'**/*.coffee': 'coffee',
},
/**
* How to report, by default.
*/
reporters: 'dots',
/**
* On which port should the browser connect, on which port is the test runner
* operating, and what is the URL path for the browser to use.
*/
port: 9018,
runnerPort: 9100,
urlRoot: '/',
/**
* Disable file watching by default.
*/
autoWatch: false,
/**
* The list of browsers to launch to test on. This includes only "Firefox" by
* default, but other browser names include:
* Chrome, ChromeCanary, Firefox, Opera, Safari, PhantomJS
*
* Note that you can also use the executable name of the browser, like "chromium"
* or "firefox", but that these vary based on your operating system.
*
* You may also leave this blank and manually navigate your browser to
* http://localhost:9018/ when you're running tests. The window/tab can be left
* open and the tests will automatically occur there during the build. This has
* the aesthetic advantage of not launching a browser every time you save.
*/
browsers: [
'Firefox'
]
});
};
| fibasile/ng-printer | build/karma-unit.js | JavaScript | mit | 2,178 |
class Solution(object):
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
nums.sort()
n=len(nums)
mid=nums[n/2]
A=lambda i:(2*i+1)%(n|1)
# tree way partion
i,j,k=0,0,n-1
while j<=k:
if nums[A(j)]>mid:
nums[A(i)],nums[A(j)]=nums[A(j)],nums[A(i)]
i+=1
j+=1
elif nums[A(j)]<mid:
nums[A(j)],nums[A(k)]=nums[A(k)],nums[A(j)]
k-=1
else:
j+=1
| Tanych/CodeTracking | 324-Wiggle-Sort-II/solution.py | Python | mit | 660 |
body {
padding: 50px;
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
}
a {
color: #00B7FF;
}
.result-table {
margin: 20px 0;
width: 100%;
border-collapse: collapse;
}
.result-table td { padding: 8px; }
.result-table > tbody > tr > td:first-child {
width: 25%;
max-width: 300px;
text-align: right;
}
.result-table td table {
background-color: lightblue;
text-align: right;
} | gus-ar-martinez/MEAN-gm-ose | public/stylesheets/style.css | CSS | mit | 408 |
/*
Copyright (c) 2016-2019 Xavier Leclercq
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
/// @file
#ifndef _WX_CHARTS_WXDOUGHNUTCHARTCTRL_H_
#define _WX_CHARTS_WXDOUGHNUTCHARTCTRL_H_
#include "wxchartctrl.h"
#include "wxdoughnutchart.h"
/// A control that displays a doughnut chart.
/// \ingroup chartclasses
class wxDoughnutChartCtrl : public wxChartCtrl, public wxChartValueObserver<std::map<wxString, wxChartSliceData>>
{
public:
wxDoughnutChartCtrl(wxWindow *parent, wxWindowID id, wxPieChartData::ptr data,
const wxPoint &pos = wxDefaultPosition, const wxSize &size = wxDefaultSize,
long style = 0);
wxDoughnutChartCtrl(wxWindow *parent, wxWindowID id, wxPieChartData::ptr data,
const wxDougnutChartOptions &options, const wxPoint &pos = wxDefaultPosition,
const wxSize &size = wxDefaultSize, long style = 0);
private:
virtual wxDoughnutChart& GetChart();
void OnUpdate(const std::map<wxString,wxChartSliceData> &data) override;
private:
wxDoughnutChart m_doughnutChart;
};
#endif
| Kvaz1r/wxCharts | include/wx/charts/wxdoughnutchartctrl.h | C | mit | 2,092 |
#Introduction
*Hotspotc* is a small daemon based on `prahladyeri/hotspotd` to create a wifi
hotspot on linux. It depends on *hostapd* for AP provisioning and *dnsmasq* to
assign IP addresses to devices.
Hotspotc works by creating a virtual NAT (Network address transation) table
between your connected device and the internet using Linux' *iptables*.
#Dependencies
* *dnsmasq* (typically pre-installed on most linux distributions)
* *hostapd* for AP provisioning
#How to use
Root is needed to start and stop hotspots.
To start a hotspot:
```
./hotspotc
```
To stop the hotspot: Ctrl-c.
When you run `hotspotc`, it will ask you for configuration values for SSID,
password, etc.
#Testing status
Ahahahaha.
| cemeyer/hotspotc | README.md | Markdown | mit | 716 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__char_listen_socket_system_21.c
Label Definition File: CWE78_OS_Command_Injection.one_string.label.xml
Template File: sources-sink-21.tmpl.c
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: listen_socket Read data using a listen socket (server side)
* GoodSource: Fixed string
* Sink: system
* BadSink : Execute command in data using system()
* Flow Variant: 21 Control flow: Flow controlled by value of a static global variable. All functions contained in one file.
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define FULL_COMMAND "%WINDIR%\\system32\\cmd.exe /c dir "
#else
#include <unistd.h>
#define FULL_COMMAND "/bin/sh ls -la "
#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
#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 LISTEN_BACKLOG 5
#ifdef _WIN32
#define SYSTEM system
#else /* NOT _WIN32 */
#define SYSTEM system
#endif
#ifndef OMITBAD
/* The static variable below is used to drive control flow in the source function */
static int badStatic = 0;
static char * badSource(char * data)
{
if(badStatic)
{
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
char *replace;
SOCKET listenSocket = INVALID_SOCKET;
SOCKET acceptSocket = INVALID_SOCKET;
size_t dataLen = strlen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a listen socket */
listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listenSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY;
service.sin_port = htons(TCP_PORT);
if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
{
break;
}
acceptSocket = accept(listenSocket, NULL, NULL);
if (acceptSocket == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed */
recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(char)] = '\0';
/* Eliminate CRLF */
replace = strchr(data, '\r');
if (replace)
{
*replace = '\0';
}
replace = strchr(data, '\n');
if (replace)
{
*replace = '\0';
}
}
while (0);
if (listenSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(listenSocket);
}
if (acceptSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(acceptSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
}
return data;
}
void CWE78_OS_Command_Injection__char_listen_socket_system_21_bad()
{
char * data;
char data_buf[100] = FULL_COMMAND;
data = data_buf;
badStatic = 1; /* true */
data = badSource(data);
/* POTENTIAL FLAW: Execute command in data possibly leading to command injection */
if (SYSTEM(data) <= 0)
{
printLine("command execution failed!");
exit(1);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* The static variables below are used to drive control flow in the source functions. */
static int goodG2B1Static = 0;
static int goodG2B2Static = 0;
/* goodG2B1() - use goodsource and badsink by setting the static variable to false instead of true */
static char * goodG2B1Source(char * data)
{
if(goodG2B1Static)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Append a fixed string to data (not user / external input) */
strcat(data, "*.*");
}
return data;
}
static void goodG2B1()
{
char * data;
char data_buf[100] = FULL_COMMAND;
data = data_buf;
goodG2B1Static = 0; /* false */
data = goodG2B1Source(data);
/* POTENTIAL FLAW: Execute command in data possibly leading to command injection */
if (SYSTEM(data) <= 0)
{
printLine("command execution failed!");
exit(1);
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if in the source function */
static char * goodG2B2Source(char * data)
{
if(goodG2B2Static)
{
/* FIX: Append a fixed string to data (not user / external input) */
strcat(data, "*.*");
}
return data;
}
static void goodG2B2()
{
char * data;
char data_buf[100] = FULL_COMMAND;
data = data_buf;
goodG2B2Static = 1; /* true */
data = goodG2B2Source(data);
/* POTENTIAL FLAW: Execute command in data possibly leading to command injection */
if (SYSTEM(data) <= 0)
{
printLine("command execution failed!");
exit(1);
}
}
void CWE78_OS_Command_Injection__char_listen_socket_system_21_good()
{
goodG2B1();
goodG2B2();
}
#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__char_listen_socket_system_21_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE78_OS_Command_Injection__char_listen_socket_system_21_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| maurer/tiamat | samples/Juliet/testcases/CWE78_OS_Command_Injection/s04/CWE78_OS_Command_Injection__char_listen_socket_system_21.c | C | mit | 7,395 |
import Marionette from 'backbone.marionette';
import Collection from './collection';
import ListItemView from './listItem';
export default Marionette.CollectionView.extend({
childView: ListItemView,
childViewOptions() {
return {
comboType: this.options.comboType,
keyPrefix: this.options.keyPrefix
};
},
initialize(options) {
this.collection = new Collection();
if (options.options && options.options.length > 0) {
for (const value of options.options) {
this.collection.add({ value });
}
} else {
this.collection.add({});
}
},
addOption(option) {
if (option === false) {
return false;
}
if (typeof option === 'undefined') {
return this.collection.add({});
}
if (option.value) {
const currentTag = this.collection.findWhere({ value: option.value });
if (currentTag) {
return currentTag.set(option);
}
}
return this.collection.add(option);
},
getOptions() {
return this.collection.map(model => model.get('value'));
}
});
| MapContrib/MapContrib | public/js/ui/form/comboFieldOptions/index.js | JavaScript | mit | 1,079 |
ifeq ($(STATIC_LINK), 1)
SLINK=-static-libstdc++
else
SLINK=
endif
WORKDIR=.
OBJDIR=./build
include misc/mf-template.mk
all:main_exec
@echo "Done"
main_exec:core_objs utilities libs_3rdparty main.d
$(LINK) utils/*.o $(OBJDIR)/*.o $(WORK_LIBS) $(SLINK) -o cerberus
runtest:main_exec utilities libs_3rdparty
@make -f test/Makefile MODE=$(MODE) COMPILER=$(COMPILER) \
CHECK_MEM=$(CHECK_MEM)
utilities:
@make -f utils/Makefile MODE=$(MODE) COMPILER=$(COMPILER)
kill-test-server:
@python test/cluster_launcher.py kill
core_objs:
@mkdir -p $(OBJDIR)
@make -f core/Makefile OBJDIR=$(OBJDIR) MODE=$(MODE) COMPILER=$(COMPILER)
libs_3rdparty:
@mkdir -p $(LIBS_DIR)
@make -f backtracpp/Makefile LIB_DIR=$(LIBS_DIR) REL_PATH=backtracpp
clean:
find -type f -name "*.o" -exec rm {} \;
rm -f cerberus
rm -f test/*.out
rm -rf $(LIBS_DIR)
| sdgdsffdsfff/redis-cerberus | Makefile | Makefile | mit | 871 |
package endpoints
package documented
package algebra
import scala.language.higherKinds
/**
* Algebra interface for describing endpoints including documentation
* (such as human readable descriptions of things).
*
* This interface is modeled after [[endpoints.algebra.Endpoints]] but some methods
* take additional parameters carrying the documentation part.
*/
trait Endpoints
extends Requests
with Responses {
/**
* Information carried by an HTTP endpoint
* @tparam A Information carried by the request
* @tparam B Information carried by the response
*/
type Endpoint[A, B]
/**
* HTTP endpoint.
*
* @param request Request
* @param response Response
*/
def endpoint[A, B](request: Request[A], response: Response[B]): Endpoint[A, B]
}
| Krever/endpoints | openapi/openapi/src/main/scala/endpoints/documented/algebra/Endpoints.scala | Scala | mit | 801 |
class Api::PagesController < Api::ApplicationController
attr_accessor :page, :feed
helper_method :page, :feed, :pages
def index
end
def create
self.page = Page.create!(uid: fb_page['id'], username: fb_page['username'])
end
def show
self.page = Page.find(params[:id])
self.feed = fb_page_feed
end
private
def pages
@pages ||= Page.all
end
def fb_page_feed
@fb_page_feed ||= fb_api.get_connection(page.uid, 'feed')
end
def fb_page
@fb_page ||= fb_api.get_object(params[:id])
end
def fb_api
@fb_api ||= Koala::Facebook::API.new(Rails.application.secrets.fb_access_token)
end
end
| daniel-g/page_fetcher | app/controllers/api/pages_controller.rb | Ruby | mit | 646 |
<?php
namespace SaleBoss\Services\Menu;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Str;
class Manager implements ManagerInterface {
/**
* @param Builder $builder
*/
public function __construct(
Builder $builder
){
$this->builder = $builder;
}
/**
* Send the method to the needed class
*
* @param $method
* @param $arguments
*
* @return mixed
*/
public function __call($method, $arguments)
{
if (!empty($arguments)){
$probClass = "\\SaleBoss\\Services\\Menu\\CustomBuilders\\" . ucfirst(Str::camel($arguments[0]));
if(class_exists($probClass)){
$custom = App::make($probClass);
return call_user_func_array([$custom,$method],$arguments);
}
}
return call_user_func_array(array($this->builder,$method),$arguments);
}
} | lucknerjb/SaleBoss | app/SaleBoss/Services/Menu/Manager.php | PHP | mit | 878 |
// ***************************************************************************
// BamStandardIndex.cpp (c) 2010 Derek Barnett
// Marth Lab, Department of Biology, Boston College
// ---------------------------------------------------------------------------
// Last modified: 25 May 2012 (DB)
// ---------------------------------------------------------------------------
// Provides index operations for the standardized BAM index format (".bai")
// ***************************************************************************
#include "api/internal/index/BamStandardIndex_p.h"
#include "api/BamAlignment.h"
#include "api/internal/bam/BamReader_p.h"
#include "api/internal/io/BamDeviceFactory_p.h"
#include "api/internal/utils/BamException_p.h"
using namespace BamTools;
using namespace BamTools::Internal;
#include <algorithm>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sstream>
// -----------------------------------
// static BamStandardIndex constants
// -----------------------------------
const int BamStandardIndex::MAX_BIN = 37450; // =(8^6-1)/7+1
const int BamStandardIndex::BAM_LIDX_SHIFT = 14;
const std::string BamStandardIndex::BAI_EXTENSION = ".bai";
const char* const BamStandardIndex::BAI_MAGIC = "BAI\1";
const int BamStandardIndex::SIZEOF_ALIGNMENTCHUNK = sizeof(uint64_t) * 2;
const int BamStandardIndex::SIZEOF_BINCORE = sizeof(uint32_t) + sizeof(int32_t);
const int BamStandardIndex::SIZEOF_LINEAROFFSET = sizeof(uint64_t);
// ----------------------------
// RaiiWrapper implementation
// ----------------------------
BamStandardIndex::RaiiWrapper::RaiiWrapper()
: Device(0)
, Buffer(0)
{}
BamStandardIndex::RaiiWrapper::~RaiiWrapper()
{
if (Device) {
Device->Close();
delete Device;
Device = 0;
}
if (Buffer) {
delete[] Buffer;
Buffer = 0;
}
}
// ---------------------------------
// BamStandardIndex implementation
// ---------------------------------
// ctor
BamStandardIndex::BamStandardIndex(Internal::BamReaderPrivate* reader)
: BamIndex(reader)
, m_bufferLength(0)
{
m_isBigEndian = BamTools::SystemIsBigEndian();
}
// dtor
BamStandardIndex::~BamStandardIndex()
{
CloseFile();
}
void BamStandardIndex::AdjustRegion(const BamRegion& region, uint32_t& begin, uint32_t& end)
{
// retrieve references from reader
const RefVector& references = m_reader->GetReferenceData();
// LeftPosition cannot be greater than or equal to reference length
if (region.LeftPosition >= references.at(region.LeftRefID).RefLength)
throw BamException("BamStandardIndex::AdjustRegion", "invalid region requested");
// set region 'begin'
begin = (unsigned int)region.LeftPosition;
// if right bound specified AND left&right bounds are on same reference
// OK to use right bound position as region 'end'
if (region.isRightBoundSpecified() && (region.LeftRefID == region.RightRefID))
end = (unsigned int)region.RightPosition;
// otherwise, set region 'end' to last reference base
else
end = (unsigned int)references.at(region.LeftRefID).RefLength;
}
// [begin, end)
void BamStandardIndex::CalculateCandidateBins(const uint32_t& begin, const uint32_t& end,
std::set<uint16_t>& candidateBins)
{
// initialize list, bin '0' is always a valid bin
candidateBins.insert(0);
// get rest of bins that contain this region
unsigned int k;
for (k = 1 + (begin >> 26); k <= 1 + (end >> 26); ++k) {
candidateBins.insert(k);
}
for (k = 9 + (begin >> 23); k <= 9 + (end >> 23); ++k) {
candidateBins.insert(k);
}
for (k = 73 + (begin >> 20); k <= 73 + (end >> 20); ++k) {
candidateBins.insert(k);
}
for (k = 585 + (begin >> 17); k <= 585 + (end >> 17); ++k) {
candidateBins.insert(k);
}
for (k = 4681 + (begin >> 14); k <= 4681 + (end >> 14); ++k) {
candidateBins.insert(k);
}
}
void BamStandardIndex::CalculateCandidateOffsets(const BaiReferenceSummary& refSummary,
const uint64_t& minOffset,
std::set<uint16_t>& candidateBins,
std::vector<int64_t>& offsets)
{
// seek to first bin
Seek(refSummary.FirstBinFilePosition, SEEK_SET);
// iterate over reference bins
uint32_t binId;
int32_t numAlignmentChunks;
std::set<uint16_t>::iterator candidateBinIter;
for (int i = 0; i < refSummary.NumBins; ++i) {
// read bin contents (if successful, alignment chunks are now in m_buffer)
ReadBinIntoBuffer(binId, numAlignmentChunks);
// see if bin is a 'candidate bin'
candidateBinIter = candidateBins.find(binId);
// if not, move on to next bin
if (candidateBinIter == candidateBins.end()) continue;
// otherwise, check bin's contents against for overlap
else {
std::size_t offset = 0;
uint64_t chunkStart;
uint64_t chunkStop;
// iterate over alignment chunks
for (int j = 0; j < numAlignmentChunks; ++j) {
// read chunk start & stop from buffer
memcpy((char*)&chunkStart, m_resources.Buffer + offset, sizeof(uint64_t));
offset += sizeof(uint64_t);
memcpy((char*)&chunkStop, m_resources.Buffer + offset, sizeof(uint64_t));
offset += sizeof(uint64_t);
// swap endian-ness if necessary
if (m_isBigEndian) {
SwapEndian_64(chunkStart);
SwapEndian_64(chunkStop);
}
// store alignment chunk's start offset
// if its stop offset is larger than our 'minOffset'
if (chunkStop >= minOffset) offsets.push_back(chunkStart);
}
// 'pop' bin ID from candidate bins set
candidateBins.erase(candidateBinIter);
// quit if no more candidates
if (candidateBins.empty()) break;
}
}
}
uint64_t BamStandardIndex::CalculateMinOffset(const BaiReferenceSummary& refSummary,
const uint32_t& begin)
{
// if no linear offsets exist, return 0
if (refSummary.NumLinearOffsets == 0) return 0;
// if 'begin' starts beyond last linear offset, use the last linear offset as minimum
// else use the offset corresponding to the requested start position
const int shiftedBegin = begin >> BamStandardIndex::BAM_LIDX_SHIFT;
if (shiftedBegin >= refSummary.NumLinearOffsets)
return LookupLinearOffset(refSummary, refSummary.NumLinearOffsets - 1);
else
return LookupLinearOffset(refSummary, shiftedBegin);
}
void BamStandardIndex::CheckBufferSize(char*& buffer, unsigned int& bufferLength,
const unsigned int& requestedBytes)
{
try {
if (requestedBytes > bufferLength) {
bufferLength = requestedBytes + 10;
delete[] buffer;
buffer = new char[bufferLength];
}
} catch (std::bad_alloc&) {
std::stringstream s;
s << "out of memory when allocating " << requestedBytes << " bytes";
throw BamException("BamStandardIndex::CheckBufferSize", s.str());
}
}
void BamStandardIndex::CheckBufferSize(unsigned char*& buffer, unsigned int& bufferLength,
const unsigned int& requestedBytes)
{
try {
if (requestedBytes > bufferLength) {
bufferLength = requestedBytes + 10;
delete[] buffer;
buffer = new unsigned char[bufferLength];
}
} catch (std::bad_alloc&) {
std::stringstream s;
s << "out of memory when allocating " << requestedBytes << " bytes";
throw BamException("BamStandardIndex::CheckBufferSize", s.str());
}
}
void BamStandardIndex::CheckMagicNumber()
{
// check 'magic number' to see if file is BAI index
char magic[4];
const int64_t numBytesRead = m_resources.Device->Read(magic, sizeof(magic));
if (numBytesRead != 4)
throw BamException("BamStandardIndex::CheckMagicNumber", "could not read BAI magic number");
// compare to expected value
if (strncmp(magic, BamStandardIndex::BAI_MAGIC, 4) != 0)
throw BamException("BamStandardIndex::CheckMagicNumber", "invalid BAI magic number");
}
void BamStandardIndex::ClearReferenceEntry(BaiReferenceEntry& refEntry)
{
refEntry.ID = -1;
refEntry.Bins.clear();
refEntry.LinearOffsets.clear();
}
void BamStandardIndex::CloseFile()
{
// close file stream
if (IsDeviceOpen()) {
m_resources.Device->Close();
delete m_resources.Device;
m_resources.Device = 0;
}
// clear index file summary data
m_indexFileSummary.clear();
// clean up I/O buffer
delete[] m_resources.Buffer;
m_resources.Buffer = 0;
m_bufferLength = 0;
}
// builds index from associated BAM file & writes out to index file
bool BamStandardIndex::Create()
{
// skip if BamReader is invalid or not open
if (m_reader == 0 || !m_reader->IsOpen()) {
SetErrorString("BamStandardIndex::Create", "could not create index: reader is not open");
return false;
}
// rewind BamReader
if (!m_reader->Rewind()) {
const std::string readerError = m_reader->GetErrorString();
const std::string message = "could not create index: \n\t" + readerError;
SetErrorString("BamStandardIndex::Create", message);
return false;
}
try {
// open new index file (read & write)
std::string indexFilename = m_reader->Filename() + Extension();
OpenFile(indexFilename, IBamIODevice::ReadWrite);
// initialize BaiFileSummary with number of references
const int& numReferences = m_reader->GetReferenceCount();
ReserveForSummary(numReferences);
// initialize output file
WriteHeader();
// set up bin, ID, offset, & coordinate markers
const uint32_t defaultValue = 0xffffffffu;
uint32_t currentBin = defaultValue;
uint32_t lastBin = defaultValue;
int32_t currentRefID = defaultValue;
int32_t lastRefID = defaultValue;
uint64_t currentOffset = (uint64_t)m_reader->Tell();
uint64_t lastOffset = currentOffset;
int32_t lastPosition = defaultValue;
// iterate through alignments in BAM file
BamAlignment al;
BaiReferenceEntry refEntry;
while (m_reader->LoadNextAlignment(al)) {
// changed to new reference
if (lastRefID != al.RefID) {
// if not first reference, save previous reference data
if (lastRefID != (int32_t)defaultValue) {
SaveAlignmentChunkToBin(refEntry.Bins, currentBin, currentOffset, lastOffset);
WriteReferenceEntry(refEntry);
ClearReferenceEntry(refEntry);
// write any empty references between (but *NOT* including) lastRefID & al.RefID
for (int i = lastRefID + 1; i < al.RefID; ++i) {
BaiReferenceEntry emptyEntry(i);
WriteReferenceEntry(emptyEntry);
}
// update bin markers
currentOffset = lastOffset;
currentBin = al.Bin;
lastBin = al.Bin;
currentRefID = al.RefID;
}
// otherwise, this is first pass
// be sure to write any empty references up to (but *NOT* including) current RefID
else {
for (int i = 0; i < al.RefID; ++i) {
BaiReferenceEntry emptyEntry(i);
WriteReferenceEntry(emptyEntry);
}
}
// update reference markers
refEntry.ID = al.RefID;
lastRefID = al.RefID;
lastBin = defaultValue;
}
// if lastPosition greater than current alignment position - file not sorted properly
else if (lastPosition > al.Position) {
std::stringstream s;
s << "BAM file is not properly sorted by coordinate" << std::endl
<< "Current alignment position: " << al.Position
<< " < previous alignment position: " << lastPosition
<< " on reference ID: " << al.RefID << std::endl;
SetErrorString("BamStandardIndex::Create", s.str());
return false;
}
// if alignment's ref ID is valid & its bin is not a 'leaf'
if ((al.RefID >= 0) && (al.Bin < 4681))
SaveLinearOffsetEntry(refEntry.LinearOffsets, al.Position, al.GetEndPosition(),
lastOffset);
// changed to new BAI bin
if (al.Bin != lastBin) {
// if not first bin on reference, save previous bin data
if (currentBin != defaultValue)
SaveAlignmentChunkToBin(refEntry.Bins, currentBin, currentOffset, lastOffset);
// update markers
currentOffset = lastOffset;
currentBin = al.Bin;
lastBin = al.Bin;
currentRefID = al.RefID;
// if invalid RefID, break out
if (currentRefID < 0) break;
}
// make sure that current file pointer is beyond lastOffset
if (m_reader->Tell() <= (int64_t)lastOffset) {
SetErrorString("BamStandardIndex::Create", "calculating offsets failed");
return false;
}
// update lastOffset & lastPosition
lastOffset = m_reader->Tell();
lastPosition = al.Position;
}
// after finishing alignments, if any data was read, check:
if (lastOffset != currentOffset) {
// store last alignment chunk to its bin, then write last reference entry with data
SaveAlignmentChunkToBin(refEntry.Bins, currentBin, currentOffset, lastOffset);
WriteReferenceEntry(refEntry);
}
// then write any empty references remaining at end of file
for (int i = currentRefID + 1; i < numReferences; ++i) {
BaiReferenceEntry emptyEntry(i);
WriteReferenceEntry(emptyEntry);
}
} catch (BamException& e) {
m_errorString = e.what();
return false;
}
// rewind BamReader
if (!m_reader->Rewind()) {
const std::string readerError = m_reader->GetErrorString();
const std::string message = "could not create index: \n\t" + readerError;
SetErrorString("BamStandardIndex::Create", message);
return false;
}
// return success
return true;
}
// returns format's file extension
const std::string BamStandardIndex::Extension()
{
return BamStandardIndex::BAI_EXTENSION;
}
void BamStandardIndex::GetOffset(const BamRegion& region, int64_t& offset,
bool* hasAlignmentsInRegion)
{
// cannot calculate offsets if unknown/invalid reference ID requested
if (region.LeftRefID < 0 || region.LeftRefID >= (int)m_indexFileSummary.size())
throw BamException("BamStandardIndex::GetOffset", "invalid reference ID requested");
// retrieve index summary for left bound reference
const BaiReferenceSummary& refSummary = m_indexFileSummary.at(region.LeftRefID);
// set up region boundaries based on actual BamReader data
uint32_t begin;
uint32_t end;
AdjustRegion(region, begin, end);
// retrieve all candidate bin IDs for region
std::set<uint16_t> candidateBins;
CalculateCandidateBins(begin, end, candidateBins);
// use reference's linear offsets to calculate the minimum offset
// that must be considered to find overlap
const uint64_t& minOffset = CalculateMinOffset(refSummary, begin);
// attempt to use reference summary, minOffset, & candidateBins to calculate offsets
// no data should not be error, just bail
std::vector<int64_t> offsets;
CalculateCandidateOffsets(refSummary, minOffset, candidateBins, offsets);
if (offsets.empty()) return;
// ensure that offsets are sorted before processing
sort(offsets.begin(), offsets.end());
// binary search for an overlapping block (may not be first one though)
BamAlignment al;
typedef std::vector<int64_t>::const_iterator OffsetConstIterator;
OffsetConstIterator offsetFirst = offsets.begin();
OffsetConstIterator offsetIter = offsetFirst;
OffsetConstIterator offsetLast = offsets.end();
std::iterator_traits<OffsetConstIterator>::difference_type count =
distance(offsetFirst, offsetLast);
std::iterator_traits<OffsetConstIterator>::difference_type step;
while (count > 0) {
offsetIter = offsetFirst;
step = count / 2;
advance(offsetIter, step);
// attempt seek to candidate offset
const int64_t& candidateOffset = (*offsetIter);
if (!m_reader->Seek(candidateOffset)) {
const std::string readerError = m_reader->GetErrorString();
const std::string message = "could not seek in BAM file: \n\t" + readerError;
throw BamException("BamToolsIndex::GetOffset", message);
}
// load first available alignment, setting flag to true if data exists
*hasAlignmentsInRegion = m_reader->LoadNextAlignment(al);
// check alignment against region
if (al.GetEndPosition() <= region.LeftPosition) {
offsetFirst = ++offsetIter;
count -= step + 1;
} else
count = step;
}
// step back to the offset before the 'current offset' (to make sure we cover overlaps)
if (offsetIter != offsets.begin()) --offsetIter;
offset = (*offsetIter);
}
// returns whether reference has alignments or no
bool BamStandardIndex::HasAlignments(const int& referenceID) const
{
if (referenceID < 0 || referenceID >= (int)m_indexFileSummary.size()) return false;
const BaiReferenceSummary& refSummary = m_indexFileSummary.at(referenceID);
return (refSummary.NumBins > 0);
}
bool BamStandardIndex::IsDeviceOpen() const
{
if (m_resources.Device == 0) return false;
return m_resources.Device->IsOpen();
}
// attempts to use index data to jump to @region, returns success/fail
// a "successful" jump indicates no error, but not whether this region has data
// * thus, the method sets a flag to indicate whether there are alignments
// available after the jump position
bool BamStandardIndex::Jump(const BamRegion& region, bool* hasAlignmentsInRegion)
{
// clear out flag
*hasAlignmentsInRegion = false;
// skip if invalid reader or not open
if (m_reader == 0 || !m_reader->IsOpen()) {
SetErrorString("BamStandardIndex::Jump", "could not jump: reader is not open");
return false;
}
// calculate nearest offset to jump to
int64_t offset;
try {
GetOffset(region, offset, hasAlignmentsInRegion);
} catch (BamException& e) {
m_errorString = e.what();
return false;
}
// if region has alignments, return success/fail of seeking there
if (*hasAlignmentsInRegion) return m_reader->Seek(offset);
// otherwise, simply return true (but hasAlignmentsInRegion flag has been set to false)
// (this is OK, BamReader will check this flag before trying to load data)
return true;
}
// loads existing data from file into memory
bool BamStandardIndex::Load(const std::string& filename)
{
try {
// attempt to open file (read-only)
OpenFile(filename, IBamIODevice::ReadOnly);
// validate format
CheckMagicNumber();
// load in-memory summary of index data
SummarizeIndexFile();
// return success
return true;
} catch (BamException& e) {
m_errorString = e.what();
return false;
}
}
uint64_t BamStandardIndex::LookupLinearOffset(const BaiReferenceSummary& refSummary,
const int& index)
{
// attempt seek to proper index file position
const int64_t linearOffsetFilePosition = (int64_t)refSummary.FirstLinearOffsetFilePosition +
index * BamStandardIndex::SIZEOF_LINEAROFFSET;
Seek(linearOffsetFilePosition, SEEK_SET);
// read linear offset from BAI file
uint64_t linearOffset;
ReadLinearOffset(linearOffset);
return linearOffset;
}
void BamStandardIndex::MergeAlignmentChunks(BaiAlignmentChunkVector& chunks)
{
// skip if chunks are empty, nothing to merge
if (chunks.empty()) return;
// set up merged alignment chunk container
BaiAlignmentChunkVector mergedChunks;
mergedChunks.push_back(chunks[0]);
// iterate over chunks
int i = 0;
BaiAlignmentChunkVector::iterator chunkIter = chunks.begin();
BaiAlignmentChunkVector::iterator chunkEnd = chunks.end();
for (++chunkIter; chunkIter != chunkEnd; ++chunkIter) {
// get 'currentMergeChunk' based on numeric index
BaiAlignmentChunk& currentMergeChunk = mergedChunks[i];
// get sourceChunk based on source vector iterator
BaiAlignmentChunk& sourceChunk = (*chunkIter);
// if currentMergeChunk ends where sourceChunk starts, then merge the two
if (currentMergeChunk.Stop >> 16 == sourceChunk.Start >> 16)
currentMergeChunk.Stop = sourceChunk.Stop;
// otherwise
else {
// append sourceChunk after currentMergeChunk
mergedChunks.push_back(sourceChunk);
// update i, so the next iteration will consider the
// recently-appended sourceChunk as new mergeChunk candidate
++i;
}
}
// saved newly-merged chunks into (parameter) chunks
chunks = mergedChunks;
}
void BamStandardIndex::OpenFile(const std::string& filename, IBamIODevice::OpenMode mode)
{
// make sure any previous index file is closed
CloseFile();
m_resources.Device = BamDeviceFactory::CreateDevice(filename);
if (m_resources.Device == 0) {
const std::string message = std::string("could not open file: ") + filename;
throw BamException("BamStandardIndex::OpenFile", message);
}
// attempt to open file
m_resources.Device->Open(mode);
if (!IsDeviceOpen()) {
const std::string message = std::string("could not open file: ") + filename;
throw BamException("BamStandardIndex::OpenFile", message);
}
}
void BamStandardIndex::ReadBinID(uint32_t& binId)
{
const int64_t numBytesRead = m_resources.Device->Read((char*)&binId, sizeof(binId));
if (m_isBigEndian) SwapEndian_32(binId);
if (numBytesRead != sizeof(binId))
throw BamException("BamStandardIndex::ReadBinID", "could not read BAI bin ID");
}
void BamStandardIndex::ReadBinIntoBuffer(uint32_t& binId, int32_t& numAlignmentChunks)
{
// read bin header
ReadBinID(binId);
ReadNumAlignmentChunks(numAlignmentChunks);
// read bin contents
const unsigned int bytesRequested =
numAlignmentChunks * BamStandardIndex::SIZEOF_ALIGNMENTCHUNK;
ReadIntoBuffer(bytesRequested);
}
void BamStandardIndex::ReadIntoBuffer(const unsigned int& bytesRequested)
{
// ensure that our buffer is big enough for request
BamStandardIndex::CheckBufferSize(m_resources.Buffer, m_bufferLength, bytesRequested);
// read from BAI file stream
const int64_t bytesRead = m_resources.Device->Read(m_resources.Buffer, bytesRequested);
if (bytesRead != static_cast<int64_t>(bytesRequested)) {
std::stringstream s;
s << "expected to read: " << bytesRequested << " bytes, "
<< "but instead read: " << bytesRead;
throw BamException("BamStandardIndex::ReadIntoBuffer", s.str());
}
}
void BamStandardIndex::ReadLinearOffset(uint64_t& linearOffset)
{
const int64_t numBytesRead =
m_resources.Device->Read((char*)&linearOffset, sizeof(linearOffset));
if (m_isBigEndian) SwapEndian_64(linearOffset);
if (numBytesRead != sizeof(linearOffset))
throw BamException("BamStandardIndex::ReadLinearOffset",
"could not read BAI linear offset");
}
void BamStandardIndex::ReadNumAlignmentChunks(int& numAlignmentChunks)
{
const int64_t numBytesRead =
m_resources.Device->Read((char*)&numAlignmentChunks, sizeof(numAlignmentChunks));
if (m_isBigEndian) SwapEndian_32(numAlignmentChunks);
if (numBytesRead != sizeof(numAlignmentChunks))
throw BamException("BamStandardIndex::ReadNumAlignmentChunks",
"could not read BAI chunk count");
}
void BamStandardIndex::ReadNumBins(int& numBins)
{
const int64_t numBytesRead = m_resources.Device->Read((char*)&numBins, sizeof(numBins));
if (m_isBigEndian) SwapEndian_32(numBins);
if (numBytesRead != sizeof(numBins))
throw BamException("BamStandardIndex::ReadNumBins", "could not read BAI bin count");
}
void BamStandardIndex::ReadNumLinearOffsets(int& numLinearOffsets)
{
const int64_t numBytesRead =
m_resources.Device->Read((char*)&numLinearOffsets, sizeof(numLinearOffsets));
if (m_isBigEndian) SwapEndian_32(numLinearOffsets);
if (numBytesRead != sizeof(numLinearOffsets))
throw BamException("BamStandardIndex::ReadNumAlignmentChunks",
"could not read BAI linear offset count");
}
void BamStandardIndex::ReadNumReferences(int& numReferences)
{
const int64_t numBytesRead =
m_resources.Device->Read((char*)&numReferences, sizeof(numReferences));
if (m_isBigEndian) SwapEndian_32(numReferences);
if (numBytesRead != sizeof(numReferences))
throw BamException("BamStandardIndex::ReadNumReferences", "could not read reference count");
}
void BamStandardIndex::ReserveForSummary(const int& numReferences)
{
m_indexFileSummary.clear();
m_indexFileSummary.assign(numReferences, BaiReferenceSummary());
}
void BamStandardIndex::SaveAlignmentChunkToBin(BaiBinMap& binMap, const uint32_t& currentBin,
const uint64_t& currentOffset,
const uint64_t& lastOffset)
{
// create new alignment chunk
BaiAlignmentChunk newChunk(currentOffset, lastOffset);
// if no entry exists yet for this bin, create one and store alignment chunk
BaiBinMap::iterator binIter = binMap.find(currentBin);
if (binIter == binMap.end()) {
BaiAlignmentChunkVector newChunks;
newChunks.push_back(newChunk);
binMap.insert(std::pair<uint32_t, BaiAlignmentChunkVector>(currentBin, newChunks));
}
// otherwise, just append alignment chunk
else {
BaiAlignmentChunkVector& binChunks = (*binIter).second;
binChunks.push_back(newChunk);
}
}
void BamStandardIndex::SaveBinsSummary(const int& refId, const int& numBins)
{
BaiReferenceSummary& refSummary = m_indexFileSummary.at(refId);
refSummary.NumBins = numBins;
refSummary.FirstBinFilePosition = Tell();
}
void BamStandardIndex::SaveLinearOffsetEntry(BaiLinearOffsetVector& offsets,
const int& alignmentStartPosition,
const int& alignmentStopPosition,
const uint64_t& lastOffset)
{
// get converted offsets
const int beginOffset = alignmentStartPosition >> BamStandardIndex::BAM_LIDX_SHIFT;
const int endOffset = (alignmentStopPosition - 1) >> BamStandardIndex::BAM_LIDX_SHIFT;
// resize vector if necessary
int oldSize = offsets.size();
int newSize = endOffset + 1;
if (oldSize < newSize) offsets.resize(newSize, 0);
// store offset
for (int i = beginOffset + 1; i <= endOffset; ++i) {
if (offsets[i] == 0) offsets[i] = lastOffset;
}
}
void BamStandardIndex::SaveLinearOffsetsSummary(const int& refId, const int& numLinearOffsets)
{
BaiReferenceSummary& refSummary = m_indexFileSummary.at(refId);
refSummary.NumLinearOffsets = numLinearOffsets;
refSummary.FirstLinearOffsetFilePosition = Tell();
}
// seek to position in index file stream
void BamStandardIndex::Seek(const int64_t& position, const int origin)
{
if (!m_resources.Device->Seek(position, origin))
throw BamException("BamStandardIndex::Seek", "could not seek in BAI file");
}
void BamStandardIndex::SkipBins(const int& numBins)
{
uint32_t binId;
int32_t numAlignmentChunks;
for (int i = 0; i < numBins; ++i)
ReadBinIntoBuffer(binId, numAlignmentChunks); // results & buffer ignored
}
void BamStandardIndex::SkipLinearOffsets(const int& numLinearOffsets)
{
const unsigned int bytesRequested = numLinearOffsets * BamStandardIndex::SIZEOF_LINEAROFFSET;
ReadIntoBuffer(bytesRequested);
}
void BamStandardIndex::SortLinearOffsets(BaiLinearOffsetVector& linearOffsets)
{
sort(linearOffsets.begin(), linearOffsets.end());
}
void BamStandardIndex::SummarizeBins(BaiReferenceSummary& refSummary)
{
// load number of bins
int numBins;
ReadNumBins(numBins);
// store bins summary for this reference
refSummary.NumBins = numBins;
refSummary.FirstBinFilePosition = Tell();
// skip this reference's bins
SkipBins(numBins);
}
void BamStandardIndex::SummarizeIndexFile()
{
// load number of reference sequences
int numReferences;
ReadNumReferences(numReferences);
// initialize file summary data
ReserveForSummary(numReferences);
// iterate over reference entries
BaiFileSummary::iterator summaryIter = m_indexFileSummary.begin();
BaiFileSummary::iterator summaryEnd = m_indexFileSummary.end();
for (int i = 0; summaryIter != summaryEnd; ++summaryIter, ++i)
SummarizeReference(*summaryIter);
}
void BamStandardIndex::SummarizeLinearOffsets(BaiReferenceSummary& refSummary)
{
// load number of linear offsets
int numLinearOffsets;
ReadNumLinearOffsets(numLinearOffsets);
// store bin summary data for this reference
refSummary.NumLinearOffsets = numLinearOffsets;
refSummary.FirstLinearOffsetFilePosition = Tell();
// skip linear offsets in index file
SkipLinearOffsets(numLinearOffsets);
}
void BamStandardIndex::SummarizeReference(BaiReferenceSummary& refSummary)
{
SummarizeBins(refSummary);
SummarizeLinearOffsets(refSummary);
}
// return position of file pointer in index file stream
int64_t BamStandardIndex::Tell() const
{
return m_resources.Device->Tell();
}
void BamStandardIndex::WriteAlignmentChunk(const BaiAlignmentChunk& chunk)
{
// localize alignment chunk offsets
uint64_t start = chunk.Start;
uint64_t stop = chunk.Stop;
// swap endian-ness if necessary
if (m_isBigEndian) {
SwapEndian_64(start);
SwapEndian_64(stop);
}
// write to index file
int64_t numBytesWritten = 0;
numBytesWritten += m_resources.Device->Write((const char*)&start, sizeof(start));
numBytesWritten += m_resources.Device->Write((const char*)&stop, sizeof(stop));
if (numBytesWritten != (sizeof(start) + sizeof(stop)))
throw BamException("BamStandardIndex::WriteAlignmentChunk",
"could not write BAI alignment chunk");
}
void BamStandardIndex::WriteAlignmentChunks(BaiAlignmentChunkVector& chunks)
{
// make sure chunks are merged (simplified) before writing & saving summary
MergeAlignmentChunks(chunks);
// write chunks
int32_t chunkCount = chunks.size();
if (m_isBigEndian) SwapEndian_32(chunkCount);
const int64_t numBytesWritten =
m_resources.Device->Write((const char*)&chunkCount, sizeof(chunkCount));
if (numBytesWritten != sizeof(chunkCount))
throw BamException("BamStandardIndex::WriteAlignmentChunks",
"could not write BAI chunk count");
// iterate over chunks
BaiAlignmentChunkVector::const_iterator chunkIter = chunks.begin();
BaiAlignmentChunkVector::const_iterator chunkEnd = chunks.end();
for (; chunkIter != chunkEnd; ++chunkIter)
WriteAlignmentChunk((*chunkIter));
}
void BamStandardIndex::WriteBin(const uint32_t& binId, BaiAlignmentChunkVector& chunks)
{
// write BAM bin ID
uint32_t binKey = binId;
if (m_isBigEndian) SwapEndian_32(binKey);
const int64_t numBytesWritten = m_resources.Device->Write((const char*)&binKey, sizeof(binKey));
if (numBytesWritten != sizeof(binKey))
throw BamException("BamStandardIndex::WriteBin", "could not write bin ID");
// write bin's alignment chunks
WriteAlignmentChunks(chunks);
}
void BamStandardIndex::WriteBins(const int& refId, BaiBinMap& bins)
{
// write number of bins
int32_t binCount = bins.size();
if (m_isBigEndian) SwapEndian_32(binCount);
const int64_t numBytesWritten =
m_resources.Device->Write((const char*)&binCount, sizeof(binCount));
if (numBytesWritten != sizeof(binCount))
throw BamException("BamStandardIndex::WriteBins", "could not write bin count");
// save summary for reference's bins
SaveBinsSummary(refId, bins.size());
// iterate over bins
BaiBinMap::iterator binIter = bins.begin();
BaiBinMap::iterator binEnd = bins.end();
for (; binIter != binEnd; ++binIter)
WriteBin((*binIter).first, (*binIter).second);
}
void BamStandardIndex::WriteHeader()
{
int64_t numBytesWritten = 0;
// write magic number
numBytesWritten += m_resources.Device->Write(BamStandardIndex::BAI_MAGIC, 4);
// write number of reference sequences
int32_t numReferences = m_indexFileSummary.size();
if (m_isBigEndian) SwapEndian_32(numReferences);
numBytesWritten +=
m_resources.Device->Write((const char*)&numReferences, sizeof(numReferences));
if (numBytesWritten != sizeof(numReferences) + 4)
throw BamException("BamStandardIndex::WriteHeader", "could not write BAI header");
}
void BamStandardIndex::WriteLinearOffsets(const int& refId, BaiLinearOffsetVector& linearOffsets)
{
// make sure linear offsets are sorted before writing & saving summary
SortLinearOffsets(linearOffsets);
int64_t numBytesWritten = 0;
// write number of linear offsets
int32_t offsetCount = linearOffsets.size();
if (m_isBigEndian) SwapEndian_32(offsetCount);
numBytesWritten += m_resources.Device->Write((const char*)&offsetCount, sizeof(offsetCount));
// save summary for reference's linear offsets
SaveLinearOffsetsSummary(refId, linearOffsets.size());
// iterate over linear offsets
BaiLinearOffsetVector::const_iterator offsetIter = linearOffsets.begin();
BaiLinearOffsetVector::const_iterator offsetEnd = linearOffsets.end();
for (; offsetIter != offsetEnd; ++offsetIter) {
// write linear offset
uint64_t linearOffset = (*offsetIter);
if (m_isBigEndian) SwapEndian_64(linearOffset);
numBytesWritten +=
m_resources.Device->Write((const char*)&linearOffset, sizeof(linearOffset));
}
if (numBytesWritten !=
static_cast<int64_t>(sizeof(offsetCount) + linearOffsets.size() * sizeof(uint64_t)))
throw BamException("BamStandardIndex::WriteLinearOffsets",
"could not write BAI linear offsets");
}
void BamStandardIndex::WriteReferenceEntry(BaiReferenceEntry& refEntry)
{
WriteBins(refEntry.ID, refEntry.Bins);
WriteLinearOffsets(refEntry.ID, refEntry.LinearOffsets);
}
| davidliwei/rnaseqmut | src/bamtools/src/api/internal/index/BamStandardIndex_p.cpp | C++ | mit | 35,965 |
/*
@styleguide
# Animation
The animation mixin supports comma separated lists of values, which allows different transitions for individual properties to be described in a single style rule. Each value in the list corresponds to the value at that same position in the other properties.
<div id="run-demo" class="box">box</div>
<div id="run-demo" class="box"></div>
*/
.box:hover {
-webkit-animation: scale 1s ease-in, slide 2s ease;
-moz-animation: scale 1s ease-in, slide 2s ease;
animation: scale 1s ease-in, slide 2s ease;
-webkit-animation-name: scale, slide;
-moz-animation-name: scale, slide;
animation-name: scale, slide;
-webkit-animation-duration: 2s;
-moz-animation-duration: 2s;
animation-duration: 2s;
-webkit-animation-timing-function: ease;
-moz-animation-timing-function: ease;
animation-timing-function: ease;
-webkit-animation-iteration-count: infinite;
-moz-animation-iteration-count: infinite;
animation-iteration-count: infinite; }
/*
@styleguide
# Button
Deprecation Warning: The button mixin has been deprecated and will be removed in the next major version release. Take a look at Bitters, which includes basic styles for buttons.
The button add-on provides well-designed buttons with a single line in your CSS.
The mixin supports a style parameter and an optional color argument. The available button styles are:
- simple (default)
- shiny
- pill
<button class="button">Simple button</button>
<button class="button">Simple button</button>
<button class="button-pill">Pill Button</button>
<button class="button-pill">Pill Button</button>
<button class="button-shiny">Shiny Button</button>
<button class="button-shiny">Shiny Button</button>
*/
.button {
border: 1px solid #076fe4;
border-radius: 3px;
box-shadow: inset 0 1px 0 0 #8ebcf1;
color: white;
display: inline-block;
font-size: inherit;
font-weight: bold;
background-color: #4294f0;
background-image: -webkit-linear-gradient(#4294f0, #0776f3);
background-image: linear-gradient(#4294f0, #0776f3);
padding: 7px 18px;
text-decoration: none;
text-shadow: 0 1px 0 #0065d6;
background-clip: padding-box; }
.button:hover:not(:disabled) {
background-color: #2f87ea;
background-image: -webkit-linear-gradient(#2f87ea, #086fe3);
background-image: linear-gradient(#2f87ea, #086fe3);
box-shadow: inset 0 1px 0 0 #60a2ec;
cursor: pointer; }
.button:active:not(:disabled), .button:focus:not(:disabled) {
border: 1px solid #076fe4;
box-shadow: inset 0 0 8px 4px #0868d3, inset 0 0 8px 4px #0868d3; }
.button:disabled {
cursor: not-allowed;
opacity: 0.5; }
.button-pill {
border: 1px solid #3371b2;
border-color: #3371b2 #2457a3 #164297;
border-radius: 16px;
box-shadow: inset 0 1px 0 0 #64a9f2;
color: white;
display: inline-block;
font-size: inherit;
font-weight: normal;
line-height: 1;
background-color: #4294f0;
background-image: -webkit-linear-gradient(#4294f0, #0156fe);
background-image: linear-gradient(#4294f0, #0156fe);
padding: 7px 18px;
text-align: center;
text-decoration: none;
text-shadow: 0 -1px 1px #2762bf;
background-clip: padding-box; }
.button-pill:hover:not(:disabled) {
background-color: #2d88ee;
background-image: -webkit-linear-gradient(#2d88ee, #1554ce);
background-image: linear-gradient(#2d88ee, #1554ce);
background-clip: padding-box;
border: 1px solid #2062a7;
border-color: #2062a7 #0e479a #01318e;
box-shadow: inset 0 1px 0 0 #519cf0;
cursor: pointer;
text-shadow: 0 -1px 1px #134faf; }
.button-pill:active:not(:disabled), .button-pill:focus:not(:disabled) {
background: #226edd;
border: 1px solid #0d3c8c;
border-bottom: 1px solid #062d8d;
box-shadow: inset 0 0 6px 3px #0c44b8;
text-shadow: 0 -1px 1px #1a52aa; }
.button-pill:disabled {
cursor: not-allowed;
opacity: 0.5; }
.button-shiny {
background-color: #ff0000;
background-image: -webkit-linear-gradient(top, #ff0000 0%, #c70000 50%, #a90000 50%, #b00000 100%);
background-image: linear-gradient(to bottom,#ff0000 0%, #c70000 50%, #a90000 50%, #b00000 100%);
border: 1px solid #8a0000;
border-bottom: 1px solid #810000;
border-radius: 5px;
box-shadow: inset 0 1px 0 0 #ff1d0c;
color: white;
display: inline-block;
font-size: inherit;
font-weight: bold;
padding: 7px 18px;
text-align: center;
text-decoration: none;
text-shadow: 0 -1px 1px #730000; }
.button-shiny:hover:not(:disabled) {
background-color: #f20000;
background-image: -webkit-linear-gradient(top, #f20000 0%, #bd0000 50%, #a20000 50%, #a90000 100%);
background-image: linear-gradient(to bottom,#f20000 0%, #bd0000 50%, #a20000 50%, #a90000 100%);
cursor: pointer; }
.button-shiny:active:not(:disabled), .button-shiny:focus:not(:disabled) {
box-shadow: inset 0 0 20px 0 #900000; }
.button-shiny:disabled {
cursor: not-allowed;
opacity: 0.5; }
| waterbolik/prestudy | demo/css-demo/_css/bourbon-demo.css | CSS | mit | 4,966 |
// Quintus Game Engine
// (c) 2012 Pascal Rettig, Cykod LLC
// Quintus may be freely distributed under the MIT license or GPLv2 License.
// For all details and documentation:
// http://html5quintus.com
//
/**
Quintus HTML5 Game Engine
The code in `quintus.js` defines the base `Quintus()` method
which create an instance of the engine. The basic engine doesn't
do a whole lot - it provides an architecture for extension, a
game loop, and a method for creating or binding to an exsiting
canvas context. The engine has dependencies on Underscore.js and jQuery,
although the jQuery dependency will be removed in the future.
Most of the game-specific functionality is in the
various other modules:
* `quintus_input.js` - `Input` module, which allows for user input via keyboard and touchscreen
* `quintus_sprites.js` - `Sprites` module, which defines a basic `Q.Sprite` class along with spritesheet support in `Q.SpriteSheet`.
* `quintus_scenes.js` - `Scenes` module. It defines the `Q.Scene` class, which allows creation of reusable scenes, and the `Q.Stage` class, which handles managing a number of sprites at once.
* `quintus_anim.js` - `Anim` module, which adds in support for animations on sprites along with a `viewport` component to follow the player around and a `Q.Repeater` class that can create a repeating, scrolling background.
@module Quintus
*/
/**
Top-level Quintus engine factory wrapper,
creates new instances of the engine by calling:
var Q = Quintus({ ... });
Any initial setup methods also all return the `Q` object, allowing any initial
setup calls to be chained together.
var Q = Quintus()
.include("Input, Sprites, Scenes")
.setup('quintus', { maximize: true })
.controls();
`Q` is used internally as the object name, and is used in most of the examples,
but multiple instances of the engine on the same page can have different names.
var Game1 = Quintus(), Game2 = Quintus();
@class Quintus
**/
var Quintus = function Quintus(opts) {
/**
A la jQuery - the returned `Q` object is actually
a method that calls `Q.select`. `Q.select` doesn't do anything
initially, but can be overridden by a module to allow
selection of game objects. The `Scenes` module adds in
the select method which selects from the default stage.
var Q = Quintus().include("Sprites, Scenes");
... Game Code ...
// Set the angry property on all Enemy1 class objects to true
Q("Enemy1").p({ angry: true });
@method Q
@for Quintus
*/
var Q = function (selector, scope, options) {
return Q.select(selector, scope, options);
};
/**
Default no-op select method. Replaced with the Quintus.Scene class
@method Q.select
@for Quintus
*/
Q.select = function () { /* No-op */
};
// Syntax for including other modules into quintus, can accept a comma-separated
// list of strings, an array of strings, or an array of actual objects. Example:
//
// Q.include("Input, Sprites, Scenes")
//
Q.include = function (mod) {
Q._each(Q._normalizeArg(mod), function (name) {
var m = Quintus[name] || name;
if (!Q._isFunction(m)) {
throw "Invalid Module:" + name;
}
m(Q);
});
return Q;
};
// Utility Methods
// ===============
//
// Most of these utility methods are a subset of Underscore.js,
// Most are pulled directly from underscore and some are
// occasionally optimized for speed and memory usage in lieu of flexibility.
// Underscore.js is (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
// Underscore is freely distributable under the MIT license.
// http://underscorejs.org
// An internal utility method (utility methods are prefixed with underscores)
// It's used to take a string of comma separated names and turn it into an `Array`
// of names. If an array of names is passed in, it's left as is. Example usage:
//
// Q._normalizeArg("Sprites, Scenes, Physics ");
// // returns [ "Sprites", "Scenes", "Physics" ]
//
// Used by `Q.include` and `Q.Sprite.add` to add modules and components, respectively.
Q._normalizeArg = function (arg) {
if (Q._isString(arg)) {
arg = arg.replace(/\s+/g, '').split(",");
}
if (!Q._isArray(arg)) {
arg = [ arg ];
}
return arg;
};
// Extends a destination object
// with a source object
Q._extend = function (dest, source) {
if (!source) {
return dest;
}
for (var prop in source) {
dest[prop] = source[prop];
}
return dest;
};
// Return a shallow copy of an object. Sub-objects (and sub-arrays) are not cloned.
Q._clone = function (obj) {
return Q._extend({}, obj);
};
// Method that adds default properties onto
// an object only if the key is undefined
Q._defaults = function (dest, source) {
if (!source) {
return dest;
}
for (var prop in source) {
if (dest[prop] === void 0) {
dest[prop] = source[prop];
}
}
return dest;
};
// Shortcut for hasOwnProperty
Q._has = function (obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
};
// Check if something is a string
// NOTE: this fails for non-primitives
Q._isString = function (obj) {
return typeof obj === "string";
};
Q._isNumber = function (obj) {
return Object.prototype.toString.call(obj) === '[object Number]';
};
// Check if something is a function
Q._isFunction = function (obj) {
return Object.prototype.toString.call(obj) === '[object Function]';
};
// Check if something is a function
Q._isObject = function (obj) {
return Object.prototype.toString.call(obj) === '[object Object]';
};
// Check if something is a function
Q._isArray = function (obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
// Check if something is undefined
Q._isUndefined = function (obj) {
return obj === void 0;
};
// Removes a property from an object and returns it
Q._popProperty = function (obj, property) {
var val = obj[property];
delete obj[property];
return val;
};
// Basic iteration method. This can often be a performance
// handicap when the callback iterator is created inline,
// as this leads to lots of functions that need to be GC'd.
// Better is to define the iterator as a private method so
// it is only created once.
Q._each = function (obj, iterator, context) {
if (obj == null) {
return;
}
if (obj.forEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
iterator.call(context, obj[i], i, obj);
}
} else {
for (var key in obj) {
iterator.call(context, obj[key], key, obj);
}
}
};
// Invoke the named property on each element of the array
Q._invoke = function (arr, property, arg1, arg2) {
if (arr == null) {
return;
}
for (var i = 0, l = arr.length; i < l; i++) {
arr[i][property](arg1, arg2);
}
};
// Basic detection method, returns the first instance where the
// iterator returns truthy.
Q._detect = function (obj, iterator, context, arg1, arg2) {
var result;
if (obj == null) {
return;
}
if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
result = iterator.call(context, obj[i], i, arg1, arg2);
if (result) {
return result;
}
}
return false;
} else {
for (var key in obj) {
result = iterator.call(context, obj[key], key, arg1, arg2);
if (result) {
return result;
}
}
return false;
}
};
// Returns a new Array with entries set to the return value of the iterator.
Q._map = function (obj, iterator, context) {
var results = [];
if (obj == null) {
return results;
}
if (obj.map) {
return obj.map(iterator, context);
}
Q._each(obj, function (value, index, list) {
results[results.length] = iterator.call(context, value, index, list);
});
if (obj.length === +obj.length) {
results.length = obj.length;
}
return results;
};
// Returns a sorted copy of unique array elements with null remove
Q._uniq = function (arr) {
arr = arr.slice().sort();
var output = [];
var last = null;
for (var i = 0; i < arr.length; i++) {
if (arr[i] !== void 0 && last !== arr[i]) {
output.push(arr[i]);
}
last = arr[i];
}
return output;
};
// returns a new array with the same entries as the source but in a random order.
Q._shuffle = function (obj) {
var shuffled = [], rand;
Q._each(obj, function (value, index, list) {
rand = Math.floor(Math.random() * (index + 1));
shuffled[index] = shuffled[rand];
shuffled[rand] = value;
});
return shuffled;
};
// Return an object's keys
Q._keys = Object.keys || function (obj) {
if (Q._isObject(obj)) {
throw new TypeError('Invalid object');
}
var keys = [];
for (var key in obj) {
if (Q._has(obj, key)) {
keys[keys.length] = key;
}
}
return keys;
};
Q._range = function (start, stop, step) {
step = step || 1;
var len = Math.max(Math.ceil((stop - start) / step), 0);
var idx = 0;
var range = new Array(len);
while (idx < len) {
range[idx++] = start;
start += step;
}
return range;
};
var idIndex = 0;
// Return a unique identifier
Q._uniqueId = function () {
return idIndex++;
};
// Options
// ========
// Default engine options defining the paths
// where images, sound and other mock files should be found
// relative to the base HTML file. As well as a couple of other
// options.
//
// These can be overriden by passing in options to the `Quintus()`
// factory method, for example:
//
// // Override the imagePath to default to /assets/images/
// var Q = Quintus({ imagePath: "/assets/images/" });
//
// If you follow the default convention from the examples, however,
// you should be able to call `Quintus()` without any options.
var assetsPath = '';
if(!!window.wish && wish.assetsPath){
assetsPath = wish.assetsPath + '/game/';
}
Q.options = {
imagePath: assetsPath + "images/",
audioPath: assetsPath + "sound/",
dataPath: assetsPath + "mock/",
audioSupported: [ 'mp3', 'ogg' ],
sound: true,
frameTimeLimit: 100
};
if (opts) {
Q._extend(Q.options, opts);
}
Q._needForceRepaint = true;
(function(){
var userAgent = navigator.userAgent;
//不需要强刷的机器.
var isIOS = (/iPhone|iPod|iPad|iTouch/i).test(userAgent);
//米3强刷canvas会被挂起.
var mi3 = (/MI 3 Build/i).test(userAgent);
if(isIOS || mi3){
Q._needForceRepaint = false;
}
})();
// Game Loop support
// =================
// By default the engine doesn't start a game loop until you actually tell it to.
// Usually the loop is started the first time you call `Q.stageScene`, but if you
// aren't using the `Scenes` module you can explicitly start the game loop yourself
// and control **exactly** what the engine does each cycle. For example:
//
// var Q = Quintus().setup();
//
// var ball = new Q.Sprite({ .. });
//
// Q.gameLoop(function(dt) {
// Q.clear();
// ball.step(dt);
// ball.draw(Q.ctx);
// });
//
// The callback will be called with fraction of a second that has elapsed since
// the last call to the loop method.
Q.gameLoop = function (callback) {
Q.lastGameLoopFrame = new Date().getTime();
// Short circuit the loop check in case multiple scenes
// are staged immediately
Q.loop = true;
// Keep track of the frame we are on (so that animations can be synced
// to the next frame)
Q._loopFrame = 0;
// Wrap the callback to save it and standardize the passed
// in time.
Q.gameLoopCallbackWrapper = function () {
var now = new Date().getTime();
Q._loopFrame++;
Q.loop = window.requestAnimationFrame(Q.gameLoopCallbackWrapper);
var dt = now - Q.lastGameLoopFrame;
/* Prevent fast-forwarding by limiting the length of a single frame. */
if (dt > Q.options.frameTimeLimit) {
dt = Q.options.frameTimeLimit;
}
callback.apply(Q, [dt / 1000]);
Q.lastGameLoopFrame = now;
//force repaint
if(Q._needForceRepaint){
Q.el.style.display='none';
Q.el.offsetHeight; // no need to store this anywhere, the reference is enough
Q.el.style.display='block';
}
};
window.requestAnimationFrame(Q.gameLoopCallbackWrapper);
return Q;
};
// Pause the entire game by canceling the requestAnimationFrame call. If you use setTimeout or
// setInterval in your game, those will, of course, keep on rolling...
Q.pauseGame = function () {
if (Q.loop) {
window.cancelAnimationFrame(Q.loop);
}
Q.loop = null;
};
// Unpause the game by restarting the requestAnimationFrame-based loop.
Q.unpauseGame = function () {
if (!Q.loop) {
Q.lastGameLoopFrame = new Date().getTime();
Q.loop = window.requestAnimationFrame(Q.gameLoopCallbackWrapper);
}
};
/**
The base Class object
Quintus uses the Simple JavaScript inheritance Class object, created by
John Resig and described on his blog:
[http://ejohn.org/blog/simple-javascript-inheritance/](http://ejohn.org/blog/simple-javascript-inheritance/)
The class is used wholesale, with the only differences being that instead
of appearing in a top-level namespace, the `Class` object is available as
`Q.Class` and a second argument on the `extend` method allows for adding
class level methods and the class name is passed in a parameter for introspection
purposes.
Classes can be created by calling `Q.Class.extend(name,{ .. })`, although most of the time
you'll want to use one of the derivitive classes, `Q.Evented` or `Q.GameObject` which
have a little bit of functionality built-in. `Q.Evented` adds event binding and
triggering support and `Q.GameObject` adds support for components and a destroy method.
The main things Q.Class get you are easy inheritance, a constructor method called `init()`,
dynamic addition of a this._super method when a method is overloaded (be careful with
this as it adds some overhead to method calls.) Calls to `instanceof` also all
work as you'd hope.
By convention, classes should be added onto to the `Q` object and capitalized, so if
you wanted to create a new class for your game, you'd write:
Q.Class.extend("MyClass",{ ... });
Examples:
Q.Class.extend("Bird",{
init: function(name) { this.name = name; },
speak: function() { console.log(this.name); },
fly: function() { console.log("Flying"); }
});
Q.Bird.extend("Penguin",{
speak: function() { console.log(this.name + " the penguin"); },
fly: function() { console.log("Can't fly, sorry..."); }
});
var randomBird = new Q.Bird("Frank"),
pengy = new Q.Penguin("Pengy");
randomBird.fly(); // Logs "Flying"
pengy.fly(); // Logs "Can't fly,sorry..."
randomBird.speak(); // Logs "Frank"
pengy.speak(); // Logs "Pengy the penguin"
console.log(randomBird instanceof Q.Bird); // true
console.log(randomBird instanceof Q.Penguin); // false
console.log(pengy instanceof Q.Bird); // true
console.log(pengy instanceof Q.Penguin); // true
Simple JavaScript Inheritance
By John Resig http://ejohn.org/
MIT Licensed.
Inspired by base2 and Prototype
@class Q.Class
@for Quintus
*/
(function () {
var initializing = false,
fnTest = /xyz/.test(function () {
var xyz;
}) ? /\b_super\b/ : /.*/;
/** The base Class implementation (does nothing)
*
* @constructor
* @for Q.Class
*/
Q.Class = function () {
};
/**
* See if a object is a specific class
*
* @method isA
*/
Q.Class.prototype.isA = function (className) {
return this.className === className;
};
/**
* Create a new Class that inherits from this class
*
* @method extend
*/
Q.Class.extend = function (className, prop, classMethods) {
/* No name, don't add onto Q */
if (!Q._isString(className)) {
classMethods = prop;
prop = className;
className = null;
}
var _super = this.prototype,
ThisClass = this;
/* Instantiate a base class (but only create the instance, */
/* don't run the init constructor) */
initializing = true;
var prototype = new ThisClass();
initializing = false;
function _superFactory(name, fn) {
return function () {
var tmp = this._super;
/* Add a new ._super() method that is the same method */
/* but on the super-class */
this._super = _super[name];
/* The method only need to be bound temporarily, so we */
/* remove it when we're done executing */
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
}
/* Copy the properties over onto the new prototype */
for (var name in prop) {
/* Check if we're overwriting an existing function */
prototype[name] = typeof prop[name] === "function" &&
typeof _super[name] === "function" &&
fnTest.test(prop[name]) ?
_superFactory(name, prop[name]) :
prop[name];
}
/* The dummy class constructor */
function Class() {
/* All construction is actually done in the init method */
if (!initializing && this.init) {
this.init.apply(this, arguments);
}
}
/* Populate our constructed prototype object */
Class.prototype = prototype;
/* Enforce the constructor to be what we expect */
Class.prototype.constructor = Class;
/* And make this class extendable */
Class.extend = Q.Class.extend;
/* If there are class-level Methods, add them to the class */
if (classMethods) {
Q._extend(Class, classMethods);
}
if (className) {
/* Save the class onto Q */
Q[className] = Class;
/* Let the class know its name */
Class.prototype.className = className;
Class.className = className;
}
return Class;
};
}());
// Event Handling
// ==============
/**
The `Q.Evented` class adds event handling onto the base `Q.Class`
class. Q.Evented objects can trigger events and other objects can
bind to those events.
@class Q.Evented
@for Quintus
*/
Q.Class.extend("Evented", {
/**
Binds a callback to an event on this object. If you provide a
`target` object, that object will add this event to it's list of
binds, allowing it to automatically remove it when it is destroyed.
@method on
@for Q.Evented
*/
on: function (event, target, callback) {
if (Q._isArray(event) || event.indexOf(",") !== -1) {
event = Q._normalizeArg(event);
for (var i = 0; i < event.length; i++) {
this.on(event[i], target, callback);
}
return;
}
// Handle the case where there is no target provided,
// swapping the target and callback parameters.
if (!callback) {
callback = target;
target = null;
}
// If there's still no callback, default to the event name
if (!callback) {
callback = event;
}
// Handle case for callback that is a string, this will
// pull the callback from the target object or from this
// object.
if (Q._isString(callback)) {
callback = (target || this)[callback];
}
// To keep `Q.Evented` objects from needing a constructor,
// the `listeners` object is created on the fly as needed.
// `listeners` keeps a list of callbacks indexed by event name
// for quick lookup.
this.listeners = this.listeners || {};
this.listeners[event] = this.listeners[event] || [];
this.listeners[event].push([ target || this, callback]);
// With a provided target, the target object keeps track of
// the events it is bound to, which allows for automatic
// unbinding on destroy.
if (target) {
if (!target.binds) {
target.binds = [];
}
target.binds.push([this, event, callback]);
}
},
// Triggers an event, passing in some optional additional mock about
// the event.
trigger: function (event, data) {
// First make sure there are any listeners, then check for any listeners
// on this specific event, if not, early out.
if (this.listeners && this.listeners[event]) {
// Call each listener in the context of either the target passed into
// `on` or the object itself.
for (var i = 0, len = this.listeners[event].length; i < len; i++) {
var listener = this.listeners[event][i];
if(listener[1] !== undefined) {
listener[1].call(listener[0], data);
}
}
}
},
// Unbinds an event. Can be called with 1, 2, or 3 parameters, each
// of which unbinds a more specific listener.
off: function (event, target, callback) {
// Without a target, remove all teh listeners.
if (!target) {
if (this.listeners[event]) {
delete this.listeners[event];
}
} else {
// If the callback is a string, find a method of the
// same name on the target.
if (Q._isString(callback) && target[callback]) {
callback = target[callback];
}
var l = this.listeners && this.listeners[event];
if (l) {
// Loop from the end to the beginning, which allows us
// to remove elements without having to affect the loop.
for (var i = l.length - 1; i >= 0; i--) {
if (l[i][0] === target) {
if (!callback || callback === l[i][1]) {
this.listeners[event].splice(i, 1);
}
}
}
}
}
},
// `debind` is called to remove any listeners an object had
// on other objects. The most common case is when an object is
// destroyed you'll want all the event listeners to be removed
// for you.
debind: function () {
if (this.binds) {
for (var i = 0, len = this.binds.length; i < len; i++) {
var boundEvent = this.binds[i],
source = boundEvent[0],
event = boundEvent[1];
source.off(event, this);
}
}
}
});
// Components
// ==============
//
// Components are self-contained pieces of functionality that can be added onto and removed
// from objects. The allow for a more dynamic functionality tree than using inheritance (i.e.
// by favoring composition over inheritance) and are added and removed on the fly at runtime.
// (yes, I know everything in JS is at runtime, but you know what I mean, geez)
//
// Combining components with events makes it easy to create reusable pieces of
// functionality that can be decoupled from each other.
/**
The master list of registered components, indexed in an object by name.
@property Q.components
@for Quintus
*/
Q.components = {};
// The base class for components. These are usually not derived directly but are instead
// created by calling `Q.register` to register a new component given a set of methods the
// component supports. Components are created automatically when they are added to a
// `Q.GameObject` with the `add` method.
//
// Many components also define an `added` method, which is called automatically by the
// `init` constructor after a component has been added to an object. This is a good time
// to add event listeners on the object.
Q.Evented.extend("Component", {
// Components are created when they are added onto a `Q.GameObject` entity. The entity
// is directly extended with any methods inside of an `extend` property and then the
// component itself is added onto the entity as well.
init: function (entity) {
this.entity = entity;
if (this.extend) {
Q._extend(entity, this.extend);
}
entity[this.name] = this;
entity.activeComponents.push(this.componentName);
if (entity.stage && entity.stage.addToList) {
entity.stage.addToList(this.componentName, entity);
}
if (this.added) {
this.added();
}
},
// `destroy` is called automatically when a component is removed from an entity. It is
// not called, however, when an entity is destroyed (for performance reasons).
//
// It's job is to remove any methods that were added with `extend` and then remove and
// debind itself from the entity. It will also call `destroyed` if the component has
// a method by that name.
destroy: function () {
if (this.extend) {
var extensions = Q._keys(this.extend);
for (var i = 0, len = extensions.length; i < len; i++) {
delete this.entity[extensions[i]];
}
}
delete this.entity[this.name];
var idx = this.entity.activeComponents.indexOf(this.componentName);
if (idx !== -1) {
this.entity.activeComponents.splice(idx, 1);
if (this.entity.stage && this.entity.stage.addToList) {
this.entity.stage.addToLists(this.componentName, this.entity);
}
}
this.debind();
if (this.destroyed) {
this.destroyed();
}
}
});
// This is the base class most Quintus objects are derived from, it extends
// `Q.Evented` and adds component support to an object, allowing components to
// be added and removed from an object. It also defines a destroyed method
// which will debind the object, remove it from it's parent (usually a scene)
// if it has one, and trigger a destroyed event.
Q.Evented.extend("GameObject", {
// Simple check to see if a component already exists
// on an object by searching for a property of the same name.
has: function (component) {
return this[component] ? true : false;
},
// Adds one or more components to an object. Accepts either
// a comma separated string or an array of strings that map
// to component names.
//
// Instantiates a new component object of the correct type
// (if the component exists) and then triggers an addComponent
// event.
//
// Returns the object to allow chaining.
add: function (components) {
components = Q._normalizeArg(components);
if (!this.activeComponents) {
this.activeComponents = [];
}
for (var i = 0, len = components.length; i < len; i++) {
var name = components[i],
Comp = Q.components[name];
if (!this.has(name) && Comp) {
var c = new Comp(this);
this.trigger('addComponent', c);
}
}
return this;
},
// Removes one or more components from an object. Accepts the
// same style of parameters as `add`. Triggers a delComponent event
// and and calls destroy on the component.
//
// Returns the element to allow chaining.
del: function (components) {
components = Q._normalizeArg(components);
for (var i = 0, len = components.length; i < len; i++) {
var name = components[i];
if (name && this.has(name)) {
this.trigger('delComponent', this[name]);
this[name].destroy();
}
}
return this;
},
// Destroys the object by calling debind and removing the
// object from it's parent. Will trigger a destroyed event
// callback.
destroy: function () {
if (this.isDestroyed) {
return;
}
this.trigger('destroyed');
this.debind();
if (this.stage && this.stage.remove) {
this.stage.remove(this);
}
this.isDestroyed = true;
if (this.destroyed) {
this.destroyed();
}
}
});
// This registers a component with the engine, making it available to `Q.GameObject`'s
// This creates a new descendent class of `Q.Component` with new methods added in.
Q.component = function (name, methods) {
if (!methods) {
return Q.components[name];
}
methods.name = name;
methods.componentName = "." + name;
return (Q.components[name] = Q.Component.extend(name + "Component", methods));
};
// Generic Game State object that can be used to
// track of the current state of the Game, for example when the player starts
// a new game you might want to keep track of their score and remaining lives:
//
// Q.reset({ score: 0, lives: 2 });
//
// Then in your game might want to add to the score:
//
// Q.state.inc("score",50);
//
// In your hud, you can listen for change events on the state to update your
// display:
//
// Q.state.on("change.score",function() { .. update the score display .. });
//
Q.GameObject.extend("GameState", {
init: function (p) {
this.p = Q._extend({}, p);
this.listeners = {};
},
// Resets the state to value p
reset: function (p) {
this.init(p);
this.trigger("reset");
},
// Internal helper method to set an individual property
_triggerProperty: function (value, key) {
if (this.p[key] !== value) {
this.p[key] = value;
this.trigger("change." + key, value);
}
},
// Set one or more properties, trigger events on those
// properties changing
set: function (properties, value) {
if (Q._isObject(properties)) {
Q._each(properties, this._triggerProperty, this);
} else {
this._triggerProperty(value, properties);
}
this.trigger("change");
},
// Increment an individual property by amount
inc: function (property, amount) {
this.set(property, this.get(property) + amount);
},
// Increment an individual property by amount
dec: function (property, amount) {
this.set(property, this.get(property) - amount);
},
// Return an individual property
get: function (property) {
return this.p[property];
}
});
// The instance of the Q.stage property
Q.state = new Q.GameState();
// Reset the game state and unbind all state events
Q.reset = function () {
Q.state.reset();
};
// Canvas Methods
// ==============
//
// The `setup` and `clear` method are the only two canvas-specific methods in
// the core of Quintus. `imageData` also uses canvas but it can be used in
// any type of game.
// Setup will either create a new canvas element and append it
// to the body of the document or use an existing one. It will then
// pull out the width and height of the canvas for engine use.
//
// It also adds a wrapper container around the element.
//
// If the `maximize` is set to true, the canvas element is maximized
// on the page and the scroll trick is used to try to get the address bar away.
//
// The engine will also resample the game to CSS dimensions at twice pixel
// dimensions if the `resampleWidth` or `resampleHeight` options are set.
//
// TODO: add support for auto-resize w/ engine event notifications, remove
// jQuery.
Q.touchDevice = ('ontouchstart' in document);
Q.setup = function (id, options) {
if (Q._isObject(id)) {
options = id;
id = null;
}
options = options || {};
id = id || "quintus";
if (Q._isString(id)) {
Q.el = document.getElementById(id);
} else {
Q.el = id;
}
if (!Q.el) {
Q.el = document.createElement("canvas");
Q.el.width = options.width || 320;
Q.el.height = options.height || 420;
Q.el.id = id;
document.body.appendChild(Q.el);
}
var w = parseInt(Q.el.width, 10),
h = parseInt(Q.el.height, 10);
var maxWidth = options.maxWidth || 5000,
maxHeight = options.maxHeight || 5000,
resampleWidth = options.resampleWidth,
resampleHeight = options.resampleHeight,
cssHeight = options.cssHeight,
cssWidth = options.cssWidth,
upsampleWidth = options.upsampleWidth,
upsampleHeight = options.upsampleHeight;
if (options.maximize === true || (Q.touchDevice && options.maximize === 'touch')) {
document.body.style.padding = 0;
document.body.style.margin = 0;
w = Math.min(window.innerWidth, maxWidth);
h = Math.min(window.innerHeight - 5, maxHeight);
if (Q.touchDevice) {
Q.el.style.height = (h * 2) + "px";
window.scrollTo(0, 1);
w = Math.min(window.innerWidth, maxWidth);
h = Math.min(window.innerHeight, maxHeight);
}
} else if (Q.touchDevice) {
window.scrollTo(0, 1);
}
if ((upsampleWidth && w <= upsampleWidth) ||
(upsampleHeight && h <= upsampleHeight)) {
Q.el.style.height = h + "px";
Q.el.style.width = w + "px";
Q.el.width = w * 2;
Q.el.height = h * 2;
}
else if (((resampleWidth && w > resampleWidth) ||
(resampleHeight && h > resampleHeight)) &&
Q.touchDevice) {
Q.el.style.height = h + "px";
Q.el.style.width = w + "px";
Q.el.width = w / 2;
Q.el.height = h / 2;
}
else if (cssWidth || cssHeight) {
Q.el.style.height = cssHeight + "px";
Q.el.style.width = cssWidth + "px";
Q.el.width = w;
Q.el.height = h;
}
else {
Q.el.style.height = h + "px";
Q.el.style.width = w + "px";
Q.el.width = w;
Q.el.height = h;
}
var elParent = Q.el.parentNode;
if (elParent) {
Q.wrapper = document.createElement("div");
Q.wrapper.id = id + '_container';
// Q.wrapper.style.width = cssWidth + "px";
// Q.wrapper.style.margin = "0 auto";
// Q.wrapper.style.position = "relative";
elParent.insertBefore(Q.wrapper, Q.el);
Q.wrapper.appendChild(Q.el);
}
Q.el.style.position = 'relative';
Q.ctx = Q.el.getContext &&
Q.el.getContext("2d");
// Q.width = parseInt(Q.el.width, 10);
// Q.height = parseInt(Q.el.height, 10);
// Q.cssWidth = w;
// Q.cssHeight = h;
Q.width = parseInt(Q.el.width, 10);
Q.height = parseInt(Q.el.height, 10);
Q.cssWidth = cssWidth || w;
Q.cssHeight = cssHeight || w;
window.addEventListener('orientationchange', function () {
setTimeout(function () {
window.scrollTo(0, 1);
}, 0);
});
return Q;
};
// Clear the canvas completely.
Q.clear = function () {
if (Q.clearColor) {
Q.ctx.globalAlpha = 1;
Q.ctx.fillStyle = Q.clearColor;
Q.ctx.fillRect(0, 0, Q.width, Q.height);
} else {
Q.ctx.clearRect(0, 0, Q.width, Q.height);
}
};
// Return canvas image mock given an Image object.
Q.imageData = function (img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
return ctx.getImageData(0, 0, img.width, img.height);
};
// Asset Loading Support
// =====================
//
// The engine supports loading assets of different types using
// `load` or `preload`. Assets are stored by their name so the
// same asset won't be loaded twice if it already exists.
// Augmentable list of asset types, loads a specific asset
// type if the file type matches, otherwise defaults to a Ajax
// load of the mock.
//
// You can new types of assets based on file extension by
// adding to `assetTypes` and adding a method called
// loadAssetTYPENAME where TYPENAME is the name of the
// type you added in.
Q.assetTypes = {
png: 'Image', jpg: 'Image', gif: 'Image', jpeg: 'Image',
ogg: 'Audio', wav: 'Audio', m4a: 'Audio', mp3: 'Audio'
};
// Determine the type of asset based on the lookup table above
Q.assetType = function (asset) {
/* Determine the lowercase extension of the file */
var fileParts = asset.split("."),
fileExt = fileParts[fileParts.length - 1].toLowerCase();
// Use the web sound loader instead of the regular loader
// if it's supported.
var fileType = Q.assetTypes[fileExt];
if (fileType === 'Audio' && Q.audio && Q.audio.type === "WebAudio") {
fileType = 'WebAudio';
}
/* Lookup the asset in the assetTypes hash, or return other */
return fileType || 'Other';
};
// Either return an absolute URL,
// or add a base to a relative URL
Q.assetUrl = function (base, url) {
var timestamp = "";
if (Q.options.development) {
timestamp = (/\?/.test(url) ? "&" : "?") + "_t=" + new Date().getTime();
}
if (/^https?:\/\//.test(url) || url[0] === "/") {
return url + timestamp;
} else {
return base + url + timestamp;
}
};
// Loader for Images, creates a new `Image` object and uses the
// load callback to determine the image has been loaded
Q.loadAssetImage = function (key, src, callback, errorCallback) {
var img = new Image();
img.onload = function () {
callback(key, img);
};
img.onerror = errorCallback;
img.src = Q.assetUrl(Q.options.imagePath, src);
};
// List of mime types given an sound file extension, used to
// determine what sound types the browser can play using the
// built-in `Sound.canPlayType`
Q.audioMimeTypes = { mp3: 'sound/mpeg',
ogg: 'sound/ogg; codecs="vorbis"',
m4a: 'sound/m4a',
wav: 'sound/wav' };
Q._audioAssetExtension = function () {
if (Q._audioAssetPreferredExtension) {
return Q._audioAssetPreferredExtension;
}
var snd = new Audio();
/* Find a supported type */
return Q._audioAssetPreferredExtension =
Q._detect(Q.options.audioSupported,
function (extension) {
return snd.canPlayType(Q.audioMimeTypes[extension]) ?
extension : null;
});
};
// Loader for Audio assets. By default chops off the extension and
// will automatically determine which of the supported types is
// playable by the browser and load that type.
//
// Which types are available are determined by the file extensions
// listed in the Quintus `options.audioSupported`
Q.loadAssetAudio = function (key, src, callback, errorCallback) {
if (!document.createElement("audio").play || !Q.options.sound) {
callback(key, null);
return;
}
var baseName = Q._removeExtension(src),
extension = Q._audioAssetExtension(),
filename = null,
snd = new Audio();
/* No supported sound = trigger ok callback anyway */
if (!extension) {
callback(key, null);
return;
}
snd.addEventListener("error", errorCallback);
// Don't wait for canplaythrough on mobile
if (!Q.touchDevice) {
snd.addEventListener('canplaythrough', function () {
callback(key, snd);
});
}
snd.src = Q.assetUrl(Q.options.audioPath, baseName + "." + extension);
snd.load();
if (Q.touchDevice) {
callback(key, snd);
}
};
Q.loadAssetWebAudio = function (key, src, callback, errorCallback) {
var request = new XMLHttpRequest(),
baseName = Q._removeExtension(src),
extension = Q._audioAssetExtension();
request.open("GET", Q.assetUrl(Q.options.audioPath, baseName + "." + extension), true);
request.responseType = "arraybuffer";
// Our asynchronous callback
request.onload = function () {
var audioData = request.response;
Q.audioContext.decodeAudioData(request.response, function (buffer) {
callback(key, buffer);
}, errorCallback);
};
request.send();
};
// Loader for other file types, just store the mock
// returned from an Ajax call.
Q.loadAssetOther = function (key, src, callback, errorCallback) {
var request = new XMLHttpRequest();
var fileParts = src.split("."),
fileExt = fileParts[fileParts.length - 1].toLowerCase();
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request.status === 200) {
if (fileExt === 'json') {
callback(key, JSON.parse(request.responseText));
} else {
callback(key, request.responseText);
}
} else {
errorCallback();
}
}
};
request.open("GET", Q.assetUrl(Q.options.dataPath, src), true);
request.send(null);
};
// Helper method to return a name without an extension
Q._removeExtension = function (filename) {
return filename.replace(/\.(\w{3,4})$/, "");
};
// Asset hash storing any loaded assets
Q.assets = {};
// Getter method to return an asset by its name.
//
// Asset names default to their filenames, but can be overridden
// by passing a hash to `load` to set different names.
Q.asset = function (name) {
return Q.assets[name];
};
// Load assets, and call our callback when done.
//
// Also optionally takes a `progressCallback` which will be called
// with the number of assets loaded and the total number of assets
// to allow showing of a progress.
//
// Assets can be passed in as an array of file names, and Quintus
// will use the file names as the name for reference, or as a hash of
// `{ name: filename }`.
//
// Example usage:
// Q.load(['sprites.png','sprites.,json'],function() {
// Q.stageScene("level1"); // or something to start the game.
// });
Q.load = function (assets, callback, options) {
var assetObj = {};
/* Make sure we have an options hash to work with */
if (!options) {
options = {};
}
/* Get our progressCallback if we have one */
var progressCallback = options.progressCallback;
var errors = false,
errorCallback = function (itm) {
errors = true;
(options.errorCallback ||
function (itm) {
throw("Error Loading: " + itm );
})(itm);
};
/* Convert to an array if it's a string */
if (Q._isString(assets)) {
assets = Q._normalizeArg(assets);
}
/* If the user passed in an array, convert it */
/* to a hash with lookups by filename */
if (Q._isArray(assets)) {
Q._each(assets, function (itm) {
if (Q._isObject(itm)) {
Q._extend(assetObj, itm);
} else {
assetObj[itm] = itm;
}
});
} else {
/* Otherwise just use the assets as is */
assetObj = assets;
}
/* Find the # of assets we're loading */
var assetsTotal = Q._keys(assetObj).length,
assetsRemaining = assetsTotal;
/* Closure'd per-asset callback gets called */
/* each time an asset is successfully loadded */
var loadedCallback = function (key, obj, force) {
if (errors) {
return;
}
// Prevent double callbacks (I'm looking at you Firefox, canplaythrough
if (!Q.assets[key] || force) {
/* Add the object to our asset list */
Q.assets[key] = obj;
/* We've got one less asset to load */
assetsRemaining--;
/* Update our progress if we have it */
if (progressCallback) {
progressCallback(assetsTotal - assetsRemaining, assetsTotal);
}
}
/* If we're out of assets, call our full callback */
/* if there is one */
if (assetsRemaining === 0 && callback) {
/* if we haven't set up our canvas element yet, */
/* assume we're using a canvas with id 'quintus' */
callback.apply(Q);
}
};
/* Now actually load each asset */
Q._each(assetObj, function (itm, key) {
/* Determine the type of the asset */
var assetType = Q.assetType(itm);
/* If we already have the asset loaded, */
/* don't load it again */
if (Q.assets[key]) {
loadedCallback(key, Q.assets[key], true);
} else {
/* Call the appropriate loader function */
/* passing in our per-asset callback */
/* Dropping our asset by name into Q.assets */
Q["loadAsset" + assetType](key, itm,
loadedCallback,
function () {
errorCallback(itm);
});
}
});
};
// Array to store any assets that need to be
// preloaded
Q.preloads = [];
// Let us gather assets to load at a later time,
// and then preload them all at the same time with
// a single callback. Options are passed through to the
// Q.load method if used.
//
// Example usage:
// Q.preload("sprites.png");
// ...
// Q.preload("sprites.json");
// ...
//
// Q.preload(function() {
// Q.stageScene("level1"); // or something to start the game
// });
Q.preload = function (arg, options) {
if (Q._isFunction(arg)) {
Q.load(Q._uniq(Q.preloads), arg, options);
Q.preloads = [];
} else {
Q.preloads = Q.preloads.concat(arg);
}
};
// Math Methods
// ==============
//
// Math methods, for rotating and scaling points
// A list of matrices available
Q.matrices2d = [];
Q.matrix2d = function () {
return Q.matrices2d.length > 0 ? Q.matrices2d.pop().identity() : new Q.Matrix2D();
};
// A 2D matrix class, optimized for 2D points,
// where the last row of the matrix will always be 0,0,1
// Good Docs where:
// https://github.com/heygrady/transform/wiki/calculating-2d-matrices
Q.Matrix2D = Q.Class.extend({
init: function (source) {
if (source) {
this.m = [];
this.clone(source);
} else {
this.m = [1, 0, 0, 0, 1, 0];
}
},
// Turn this matrix into the identity
identity: function () {
var m = this.m;
m[0] = 1;
m[1] = 0;
m[2] = 0;
m[3] = 0;
m[4] = 1;
m[5] = 0;
return this;
},
// Clone another matrix into this one
clone: function (matrix) {
var d = this.m, s = matrix.m;
d[0] = s[0];
d[1] = s[1];
d[2] = s[2];
d[3] = s[3];
d[4] = s[4];
d[5] = s[5];
return this;
},
// a * b =
// [ [ a11*b11 + a12*b21 ], [ a11*b12 + a12*b22 ], [ a11*b31 + a12*b32 + a13 ] ,
// [ a21*b11 + a22*b21 ], [ a21*b12 + a22*b22 ], [ a21*b31 + a22*b32 + a23 ] ]
multiply: function (matrix) {
var a = this.m, b = matrix.m;
var m11 = a[0] * b[0] + a[1] * b[3];
var m12 = a[0] * b[1] + a[1] * b[4];
var m13 = a[0] * b[2] + a[1] * b[5] + a[2];
var m21 = a[3] * b[0] + a[4] * b[3];
var m22 = a[3] * b[1] + a[4] * b[4];
var m23 = a[3] * b[2] + a[4] * b[5] + a[5];
a[0] = m11;
a[1] = m12;
a[2] = m13;
a[3] = m21;
a[4] = m22;
a[5] = m23;
return this;
},
// Multiply this matrix by a rotation matrix rotated radians radians
rotate: function (radians) {
if (radians === 0) {
return this;
}
var cos = Math.cos(radians),
sin = Math.sin(radians),
m = this.m;
var m11 = m[0] * cos + m[1] * sin;
var m12 = m[0] * -sin + m[1] * cos;
var m21 = m[3] * cos + m[4] * sin;
var m22 = m[3] * -sin + m[4] * cos;
m[0] = m11;
m[1] = m12; // m[2] == m[2]
m[3] = m21;
m[4] = m22; // m[5] == m[5]
return this;
},
// Helper method to rotate by a set number of degrees
rotateDeg: function (degrees) {
if (degrees === 0) {
return this;
}
return this.rotate(Math.PI * degrees / 180);
},
// Multiply this matrix by a scaling matrix scaling sx and sy
scale: function (sx, sy) {
var m = this.m;
if (sy === void 0) {
sy = sx;
}
m[0] *= sx;
m[1] *= sy;
m[3] *= sx;
m[4] *= sy;
return this;
},
// Multiply this matrix by a translation matrix translate by tx and ty
translate: function (tx, ty) {
var m = this.m;
m[2] += m[0] * tx + m[1] * ty;
m[5] += m[3] * tx + m[4] * ty;
return this;
},
// Memory Hoggy version
transform: function (x, y) {
return [ x * this.m[0] + y * this.m[1] + this.m[2],
x * this.m[3] + y * this.m[4] + this.m[5] ];
},
// Transform an object with an x and y property by this Matrix
transformPt: function (obj) {
var x = obj.x, y = obj.y;
obj.x = x * this.m[0] + y * this.m[1] + this.m[2];
obj.y = x * this.m[3] + y * this.m[4] + this.m[5];
return obj;
},
// Transform an array with an x and y property by this Matrix
transformArr: function (inArr, outArr) {
var x = inArr[0], y = inArr[1];
outArr[0] = x * this.m[0] + y * this.m[1] + this.m[2];
outArr[1] = x * this.m[3] + y * this.m[4] + this.m[5];
return outArr;
},
// Return just the x component by this Matrix
transformX: function (x, y) {
return x * this.m[0] + y * this.m[1] + this.m[2];
},
// Return just the y component by this Matrix
transformY: function (x, y) {
return x * this.m[3] + y * this.m[4] + this.m[5];
},
// Release this Matrix to be reused
release: function () {
Q.matrices2d.push(this);
return null;
},
setContextTransform: function (ctx) {
var m = this.m;
// source:
// m[0] m[1] m[2]
// m[3] m[4] m[5]
// 0 0 1
//
// destination:
// m11 m21 dx
// m12 m22 dy
// 0 0 1
// setTransform(m11, m12, m21, m22, dx, dy)
ctx.transform(m[0], m[3], m[1], m[4], m[2], m[5]);
//ctx.setTransform(m[0],m[1],m[2],m[3],m[4],m[5]);
}
});
// And that's it..
// ===============
//
// Return the `Q` object from the `Quintus()` factory method. Create awesome games. Repeat.
return Q;
};
// Lastly, add in the `requestAnimationFrame` shim, if necessary. Does nothing
// if `requestAnimationFrame` is already on the `window` object.
(function () {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
}
var blacklisted = /iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent);
if (!window.requestAnimationFrame || blacklisted) {
window.requestAnimationFrame = function (callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function () {
callback(currTime + timeToCall);
},
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame || blacklisted) {
window.cancelAnimationFrame = function (id) {
clearTimeout(id);
};
}
}());
;/*global Quintus:false */
/**
Quintus HTML5 Game Engine - Sprites Module
The code in `quintus_sprites.js` defines the `Quintus.Sprites` module, which
add support for sprite sheets and the base sprite class.
Most games will include at a minimum `Quintus.Sprites` and `Quintus.Scenes`
@module Quintus.Sprites
*/
/**
* Quintus Sprites Module Class
*
* @class Quintus.Sprites
*/
Quintus.Sprites = function (Q) {
/**
*
Create a new sprite sheet
Options:
tileW - tile width
tileH - tile height
w - width of the sprite block
h - height of the sprite block
sx - start x
sy - start y
cols - number of columns per row
@class SpriteSheet
@for Quintus.Sprites
*/
Q.Class.extend("SpriteSheet", {
/**
@constructor
*/
init: function (name, asset, options) {
if (!Q.asset(asset)) {
throw "Invalid Asset:" + asset;
}
Q._extend(this, {
name: name,
asset: asset,
w: Q.asset(asset).width,
h: Q.asset(asset).height,
tileW: 64,
tileH: 64,
sx: 0,
sy: 0
});
if (options) {
Q._extend(this, options);
}
// fix for old tilew instead of tileW
if (this.tilew) {
this.tileW = this.tilew;
delete this['tilew'];
}
if (this.tileh) {
this.tileH = this.tileh;
delete this['tileh'];
}
this.cols = this.cols ||
Math.floor(this.w / this.tileW);
this.frames = this.cols * (Math.ceil(this.h / this.tileH));
},
fx: function (frame) {
return Math.floor((frame % this.cols) * this.tileW + this.sx);
},
fy: function (frame) {
return Math.floor(Math.floor(frame / this.cols) * this.tileH + this.sy);
},
odi: function(frame){
return (frame / this.cols) * this.tileH + this.sy;
},
draw: function (ctx, x, y, frame) {
if (!ctx) {
ctx = Q.ctx;
}
// if(this.asset == 'scaffold/Shank.png'){
// //debugger;
// ctx.drawImage(Q.asset(this.asset),
// this.fx(frame), this.fy(frame),
// 130, 130,
// Math.floor(x), Math.floor(y),
// this.tileW, this.tileH);
//
// }
// else{
// ctx.drawImage(Q.asset(this.asset),
// this.fx(frame), this.fy(frame),
// this.tileW, this.tileH,
// Math.floor(x), Math.floor(y),
// this.tileW, this.tileH);
// }
ctx.drawImage(Q.asset(this.asset),
this.fx(frame), this.fy(frame),
this.swidth || this.tileW, this.sheight || this.tileH, //add support swidth and sheight http://www.w3school.com.cn/html5/canvas_drawimage.asp
Math.floor(x), Math.floor(y),
this.tileW, this.tileH);
}
});
Q.sheets = {};
Q.sheet = function (name, asset, options) {
if (asset) {
Q.sheets[name] = new Q.SpriteSheet(name, asset, options);
} else {
return Q.sheets[name];
}
};
Q.compileSheets = function (imageAsset, spriteDataAsset) {
var data = Q.asset(spriteDataAsset);
Q._each(data, function (spriteData, name) {
Q.sheet(name, imageAsset, spriteData);
});
};
Q.SPRITE_NONE = 0;
Q.SPRITE_DEFAULT = 1;
Q.SPRITE_PARTICLE = 2;
Q.SPRITE_ACTIVE = 4;
Q.SPRITE_FRIENDLY = 8;
Q.SPRITE_ENEMY = 16;
Q.SPRITE_POWERUP = 32;
Q.SPRITE_UI = 64;
Q.SPRITE_ALL = 0xFFFF;
Q._generatePoints = function (obj, force) {
if (obj.p.points && !force) {
return;
}
var p = obj.p,
halfW = p.w / 2,
halfH = p.h / 2;
p.points = [
[ -halfW, -halfH ],
[ halfW, -halfH ],
[ halfW, halfH ],
[ -halfW, halfH ]
];
};
Q._generateCollisionPoints = function (obj) {
if (!obj.matrix && !obj.refreshMatrix) {
return;
}
if (!obj.c) {
obj.c = { points: [] };
}
var p = obj.p, c = obj.c;
if (!p.moved &&
c.origX === p.x &&
c.origY === p.y &&
c.origScale === p.scale &&
c.origScale === p.angle) {
return;
}
c.origX = p.x;
c.origY = p.y;
c.origScale = p.scale;
c.origAngle = p.angle;
obj.refreshMatrix();
var container = obj.container || Q._nullContainer;
// TODO: see if we care or if it's more
// efficient just to do the calc each time
c.x = container.matrix.transformX(p.x, p.y);
c.y = container.matrix.transformY(p.x, p.y);
c.angle = p.angle + container.c.angle;
c.scale = (container.c.scale || 1) * (p.scale || 1);
var minX = Infinity,
minY = Infinity,
maxX = -Infinity,
maxY = -Infinity;
for (var i = 0; i < obj.p.points.length; i++) {
if (!obj.c.points[i]) {
obj.c.points[i] = [];
}
obj.matrix.transformArr(obj.p.points[i], obj.c.points[i]);
var x = obj.c.points[i][0],
y = obj.c.points[i][1];
if (x < minX) {
minX = x;
}
if (x > maxX) {
maxX = x;
}
if (y < minY) {
minY = y;
}
if (y > maxY) {
maxY = y;
}
}
if (minX === maxX) {
maxX += 1;
}
if (minY === maxY) {
maxY += 1;
}
c.cx = c.x - minX;
c.cy = c.y - minY;
c.w = maxX - minX;
c.h = maxY - minY;
// TODO: Invoke moved on children
};
// Properties:
// x
// y
// z - sort order
// sheet or asset
// frame
Q.GameObject.extend("Sprite", {
init: function (props, defaultProps) {
this.p = Q._extend({
x: 0,
y: 0,
z: 0,
opacity: 1,
angle: 0,
frame: 0,
type: Q.SPRITE_DEFAULT | Q.SPRITE_ACTIVE
}, defaultProps);
this.matrix = new Q.Matrix2D();
this.children = [];
Q._extend(this.p, props);
this.size();
this.p.id = this.p.id || Q._uniqueId();
this.c = { points: [] };
this.refreshMatrix();
},
// Resets the width, height and center based on the
// asset or sprite sheet
size: function (force) {
if (force || (!this.p.w || !this.p.h)) {
if (this.asset()) {
this.p.w = this.asset().width;
this.p.h = this.asset().height;
} else if (this.sheet()) {
this.p.w = this.sheet().tileW;
this.p.h = this.sheet().tileH;
}
}
this.p.cx = (force || this.p.cx === void 0) ? (this.p.w / 2) : this.p.cx;
this.p.cy = (force || this.p.cy === void 0) ? (this.p.h / 2) : this.p.cy;
},
// Get or set the asset associate with this sprite
asset: function (name, resize) {
if (!name) {
return Q.asset(this.p.asset);
}
this.p.asset = name;
if (resize) {
this.size(true);
Q._generatePoints(this, true);
}
},
// Get or set the sheet associate with this sprite
sheet: function (name, resize) {
if (!name) {
return Q.sheet(this.p.sheet);
}
this.p.sheet = name;
if (resize) {
this.size(true);
Q._generatePoints(this, true);
}
},
hide: function () {
this.p.hidden = true;
},
show: function () {
this.p.hidden = false;
},
set: function (properties) {
Q._extend(this.p, properties);
return this;
},
_sortChild: function (a, b) {
return ((a.p && a.p.z) || -1) - ((b.p && b.p.z) || -1);
},
_flipArgs: {
"x": [ -1, 1],
"y": [ 1, -1],
"xy": [ -1, -1]
},
render: function (ctx) {
var p = this.p;
if (p.hidden) {
return;
}
if (!ctx) {
ctx = Q.ctx;
}
this.trigger('predraw', ctx);
ctx.save();
if (this.p.opacity !== void 0 && this.p.opacity !== 1) {
ctx.globalAlpha = this.p.opacity;
}
this.matrix.setContextTransform(ctx);
if (this.p.flip) {
ctx.scale.apply(ctx, this._flipArgs[this.p.flip]);
}
this.trigger('beforedraw', ctx);
this.draw(ctx);
this.trigger('draw', ctx);
ctx.restore();
// Children set up their own complete matrix
// from the base stage matrix
if (this.p.sort) {
this.children.sort(this._sortChild);
}
Q._invoke(this.children, "render", ctx);
this.trigger('postdraw', ctx);
if (Q.debug) {
this.debugRender(ctx);
}
},
center: function () {
if (this.container) {
this.p.x = this.container.p.w / 2;
this.p.y = this.container.p.h / 2;
} else {
this.p.x = Q.width / 2;
this.p.y = Q.height / 2;
}
},
draw: function (ctx) {
var p = this.p;
if (p.sheet) {
this.sheet().draw(ctx, -p.cx, -p.cy, p.frame);
} else if (p.asset) {
ctx.drawImage(Q.asset(p.asset), -p.cx, -p.cy);
}
},
debugRender: function (ctx) {
if (!this.p.points) {
Q._generatePoints(this);
}
ctx.save();
this.matrix.setContextTransform(ctx);
ctx.beginPath();
ctx.fillStyle = this.p.hit ? "blue" : "red";
ctx.strokeStyle = "#FF0000";
ctx.fillStyle = "rgba(0,0,0,0.5)";
ctx.moveTo(this.p.points[0][0], this.p.points[0][1]);
for (var i = 0; i < this.p.points.length; i++) {
ctx.lineTo(this.p.points[i][0], this.p.points[i][1]);
}
ctx.lineTo(this.p.points[0][0], this.p.points[0][1]);
ctx.stroke();
if (Q.debugFill) {
ctx.fill();
}
ctx.restore();
if (this.c) {
var c = this.c;
ctx.save();
ctx.globalAlpha = 1;
ctx.lineWidth = 2;
ctx.strokeStyle = "#FF00FF";
ctx.beginPath();
ctx.moveTo(c.x - c.cx, c.y - c.cy);
ctx.lineTo(c.x - c.cx + c.w, c.y - c.cy);
ctx.lineTo(c.x - c.cx + c.w, c.y - c.cy + c.h);
ctx.lineTo(c.x - c.cx, c.y - c.cy + c.h);
ctx.lineTo(c.x - c.cx, c.y - c.cy);
ctx.stroke();
ctx.restore();
}
},
update: function (dt) {
this.trigger('prestep', dt);
if (this.step) {
this.step(dt);
}
this.trigger('step', dt);
this.refreshMatrix();
// Ugly coupling to stage - workaround?
if (this.stage && this.children.length > 0) {
this.stage.updateSprites(this.children, dt, true);
}
},
refreshMatrix: function () {
var p = this.p;
this.matrix.identity();
if (this.container) {
this.matrix.multiply(this.container.matrix);
}
this.matrix.translate(p.x, p.y);
if (p.scale) {
this.matrix.scale(p.scale, p.scale);
}
this.matrix.rotateDeg(p.angle);
}
});
Q.Sprite.extend("MovingSprite", {
init: function (props, defaultProps) {
this._super(Q._extend({
vx: 0,
vy: 0,
ax: 0,
ay: 0
}, props), defaultProps);
},
step: function (dt) {
var p = this.p;
p.vx += p.ax * dt;
p.vy += p.ay * dt;
p.x += p.vx * dt;
p.y += p.vy * dt;
}
});
return Q;
};
;/*global Quintus:false */
Quintus["2D"] = function (Q) {
Q.component('2d', {
added: function () {
var entity = this.entity;
Q._defaults(entity.p, {
collisionMask: Q.SPRITE_DEFAULT
});
entity.on('step', this, "step");
},
step: function (dt) {
var p = this.entity.p,
dtStep = dt;
// TODO: check the entity's magnitude of vx and vy,
// reduce the max dtStep if necessary to prevent
// skipping through objects.
while (dtStep > 0) {
dt = Math.min(1 / 30, dtStep);
this.entity.stage.collide(this.entity);
dtStep -= dt;
}
}
});
};
;/*global Quintus:false */
Quintus.Scenes = function (Q) {
Q.scenes = {};
Q.stages = [];
Q.Scene = Q.Class.extend({
init: function (sceneFunc, opts) {
this.opts = opts || {};
this.sceneFunc = sceneFunc;
}
});
// Set up or return a new scene
Q.scene = function (name, sceneObj, opts) {
if (sceneObj === void 0) {
return Q.scenes[name];
} else {
if (Q._isFunction(sceneObj)) {
sceneObj = new Q.Scene(sceneObj, opts);
}
Q.scenes[name] = sceneObj;
return sceneObj;
}
};
Q._nullContainer = {
c: {
x: 0,
y: 0,
/* cx: 0,
cy: 0, */
angle: 0,
scale: 1
},
matrix: Q.matrix2d()
};
// Default to SAT collision between two objects
// Thanks to doc's at: http://www.sevenson.com.au/actionscript/sat/
Q.collision = (function () {
var normalX, normalY,
offset = [ 0, 0 ],
result1 = { separate: [] },
result2 = { separate: [] };
function calculateNormal(points, idx) {
var pt1 = points[idx],
pt2 = points[idx + 1] || points[0];
normalX = -(pt2[1] - pt1[1]);
normalY = pt2[0] - pt1[0];
var dist = Math.sqrt(normalX * normalX + normalY * normalY);
if (dist > 0) {
normalX /= dist;
normalY /= dist;
}
}
function dotProductAgainstNormal(point) {
return (normalX * point[0]) + (normalY * point[1]);
}
function collide(o1, o2, flip) {
var min1, max1,
min2, max2,
d1, d2,
offsetLength,
tmp, i, j,
minDist, minDistAbs,
shortestDist = Number.POSITIVE_INFINITY,
collided = false,
p1, p2;
var result = flip ? result2 : result1;
offset[0] = 0; //o1.x + o1.cx - o2.x - o2.cx;
offset[1] = 0; //o1.y + o1.cy - o2.y - o2.cy;
// If we have a position matrix, just use those points,
if (o1.c) {
p1 = o1.c.points;
} else {
p1 = o1.p.points;
offset[0] += o1.p.x;
offset[1] += o1.p.y;
}
if (o2.c) {
p2 = o2.c.points;
} else {
p2 = o2.p.points;
offset[0] += -o2.p.x;
offset[1] += -o2.p.y;
}
o1 = o1.p;
o2 = o2.p;
for (i = 0; i < p1.length; i++) {
calculateNormal(p1, i);
min1 = dotProductAgainstNormal(p1[0]);
max1 = min1;
for (j = 1; j < p1.length; j++) {
tmp = dotProductAgainstNormal(p1[j]);
if (tmp < min1) {
min1 = tmp;
}
if (tmp > max1) {
max1 = tmp;
}
}
min2 = dotProductAgainstNormal(p2[0]);
max2 = min2;
for (j = 1; j < p2.length; j++) {
tmp = dotProductAgainstNormal(p2[j]);
if (tmp < min2) {
min2 = tmp;
}
if (tmp > max2) {
max2 = tmp;
}
}
offsetLength = dotProductAgainstNormal(offset);
min1 += offsetLength;
max1 += offsetLength;
d1 = min1 - max2;
d2 = min2 - max1;
if (d1 > 0 || d2 > 0) {
return null;
}
minDist = (max2 - min1) * -1;
if (flip) {
minDist *= -1;
}
minDistAbs = Math.abs(minDist);
if (minDistAbs < shortestDist) {
result.distance = minDist;
result.magnitude = minDistAbs;
result.normalX = normalX;
result.normalY = normalY;
if (result.distance > 0) {
result.distance *= -1;
result.normalX *= -1;
result.normalY *= -1;
}
collided = true;
shortestDist = minDistAbs;
}
}
// Do return the actual collision
return collided ? result : null;
}
function satCollision(o1, o2) {
var result1, result2, result;
// Don't compare a square to a square for no reason
// if(!o1.p.points && !o2.p.points) return true;
if (!o1.p.points) {
Q._generatePoints(o1);
}
if (!o2.p.points) {
Q._generatePoints(o2);
}
Q._generateCollisionPoints(o1);
Q._generateCollisionPoints(o2);
result1 = collide(o1, o2);
if (!result1) {
return false;
}
result2 = collide(o2, o1, true);
if (!result2) {
return false;
}
result = (result2.magnitude < result1.magnitude) ? result2 : result1;
if (result.magnitude === 0) {
return false;
}
result.separate[0] = result.distance * result.normalX;
result.separate[1] = result.distance * result.normalY;
return result;
}
return satCollision;
}());
Q.overlap = function (o1, o2) {
var c1 = o1.c || o1.p;
var c2 = o2.c || o2.p;
var o1x = c1.x - c1.cx,
o1y = c1.y - c1.cy;
var o2x = c2.x - c2.cx,
o2y = c2.y - c2.cy;
return !((o1y + c1.h < o2y) || (o1y > o2y + c2.h) ||
(o1x + c1.w < o2x) || (o1x > o2x + c2.w));
};
Q.Stage = Q.GameObject.extend({
// Should know whether or not the stage is paused
defaults: {
sort: false,
gridW: 400,
gridH: 400
},
init: function (scene, opts) {
this.scene = scene;
this.items = [];
this.lists = {};
this.index = {};
this.removeList = [];
this.grid = {};
this.time = 0;
this.options = Q._extend({}, this.defaults);
if (this.scene) {
Q._extend(this.options, scene.opts);
}
if (opts) {
Q._extend(this.options, opts);
}
if (this.options.sort && !Q._isFunction(this.options.sort)) {
this.options.sort = function (a, b) {
return ((a.p && a.p.z) || -1) - ((b.p && b.p.z) || -1);
};
}
},
destroyed: function () {
this.invoke("debind");
this.trigger("destroyed");
},
// Needs to be separated out so the current stage can be set
loadScene: function () {
if (this.scene) {
this.scene.sceneFunc(this);
}
},
// Load an array of assets of the form:
// [ [ "Player", { x: 15, y: 54 } ],
// [ "Enemy", { x: 54, y: 42 } ] ]
// Either pass in the array or a string of asset name
loadAssets: function (asset) {
var assetArray = Q._isArray(asset) ? asset : Q.asset(asset);
for (var i = 0; i < assetArray.length; i++) {
var spriteClass = assetArray[i][0];
var spriteProps = assetArray[i][1];
this.insert(new Q[spriteClass](spriteProps));
}
},
each: function (callback) {
for (var i = 0, len = this.items.length; i < len; i++) {
callback.call(this.items[i], arguments[1], arguments[2]);
}
},
invoke: function (funcName) {
for (var i = 0, len = this.items.length; i < len; i++) {
this.items[i][funcName].call(
this.items[i], arguments[1], arguments[2]
);
}
},
detect: function (func) {
for (var i = this.items.length - 1; i >= 0; i--) {
if (func.call(this.items[i], arguments[1], arguments[2], arguments[3])) {
return this.items[i];
}
}
return false;
},
identify: function (func) {
var result;
for (var i = this.items.length - 1; i >= 0; i--) {
if (result = func.call(this.items[i], arguments[1], arguments[2], arguments[3])) {
return result;
}
}
return false;
},
addToLists: function (lists, object) {
for (var i = 0; i < lists.length; i++) {
this.addToList(lists[i], object);
}
},
addToList: function (list, itm) {
if (!this.lists[list]) {
this.lists[list] = [];
}
this.lists[list].push(itm);
},
removeFromLists: function (lists, itm) {
for (var i = 0; i < lists.length; i++) {
this.removeFromList(lists[i], itm);
}
},
removeFromList: function (list, itm) {
var listIndex = this.lists[list].indexOf(itm);
if (listIndex !== -1) {
this.lists[list].splice(listIndex, 1);
}
},
insert: function (itm, container) {
this.items.push(itm);
itm.stage = this;
itm.container = container;
if (container) {
container.children.push(itm);
}
itm.grid = {};
// Make sure we have a square of collision points
Q._generatePoints(itm);
Q._generateCollisionPoints(itm);
if (itm.className) {
this.addToList(itm.className, itm);
}
if (itm.activeComponents) {
this.addToLists(itm.activeComponents, itm);
}
if (itm.p) {
this.index[itm.p.id] = itm;
}
this.trigger('inserted', itm);
itm.trigger('inserted', this);
this.regrid(itm);
return itm;
},
remove: function (itm) {
this.delGrid(itm);
this.removeList.push(itm);
},
forceRemove: function (itm) {
var idx = this.items.indexOf(itm);
if (idx !== -1) {
this.items.splice(idx, 1);
if (itm.className) {
this.removeFromList(itm.className, itm);
}
if (itm.activeComponents) {
this.removeFromLists(itm.activeComponents, itm);
}
if (itm.container) {
var containerIdx = itm.container.children.indexOf(itm);
if (containerIdx !== -1) {
itm.container.children.splice(containerIdx, 1);
}
}
if (itm.destroy) {
itm.destroy();
}
if (itm.p.id) {
delete this.index[itm.p.id];
}
this.trigger('removed', itm);
}
},
pause: function () {
this.paused = true;
},
unpause: function () {
this.paused = false;
},
_gridCellCheck: function (type, id, obj, collisionMask) {
if (!collisionMask || collisionMask & type) {
var obj2 = this.index[id];
if (obj2 && obj2 !== obj && Q.overlap(obj, obj2)) {
var col = Q.collision(obj, obj2);
if (col) {
col.obj = obj2;
return col;
} else {
return false;
}
}
}
},
gridTest: function (obj, collisionMask, collisionLayer) {
var grid = obj.grid, gridCell, col;
for (var y = grid.Y1; y <= grid.Y2; y++) {
if (this.grid[y]) {
for (var x = grid.X1; x <= grid.X2; x++) {
gridCell = this.grid[y][x];
if (gridCell) {
col = Q._detect(gridCell, this._gridCellCheck, this, obj, collisionMask);
if (col) {
return col;
}
}
}
}
}
return false;
},
collisionLayer: function (layer) {
this._collisionLayer = layer;
return this.insert(layer);
},
search: function (obj, collisionMask) {
var col;
collisionMask = collisionMask || (obj.p && obj.p.collisionMask);
if (this._collisionLayer && (this._collisionLayer.p.type & collisionMask)) {
col = this._collisionLayer.collide(obj);
if (col) {
return col;
}
}
col = this.gridTest(obj, collisionMask, this._collisionLayer);
return col;
},
_locateObj: {
p: {
x: 0,
y: 0,
cx: 0,
cy: 0,
w: 1,
h: 1
}, grid: {}
},
locate: function (x, y, collisionMask) {
var col = null;
this._locateObj.p.x = x;
this._locateObj.p.y = y;
this.regrid(this._locateObj, true);
if (this._collisionLayer && (this._collisionLayer.p.type & collisionMask)) {
col = this._collisionLayer.collide(this._locateObj);
}
if (!col) {
col = this.gridTest(this._locateObj, collisionMask, this._collisionLayer);
}
if (col && col.obj) {
return col.obj;
} else {
return false;
}
},
collide: function (obj, options) {
var col, col2, collisionMask,
maxCol, curCol, skipEvents;
if (Q._isObject(options)) {
collisionMask = options.collisionMask;
maxCol = options.maxCol;
skipEvents = options.skipEvents;
} else {
collisionMask = options;
}
collisionMask = collisionMask || (obj.p && obj.p.collisionMask);
maxCol = maxCol || 3;
curCol = maxCol;
this.regrid(obj);
if (this._collisionLayer && (this._collisionLayer.p.type & collisionMask)) {
while (curCol > 0 && (col = this._collisionLayer.collide(obj))) {
col.obj = this._collisionLayer;
if (!skipEvents) {
obj.trigger('hit', col);
obj.trigger('hit.collision', col);
}
this.regrid(obj);
curCol--;
}
}
curCol = maxCol;
while (curCol > 0 && (col2 = this.gridTest(obj, collisionMask, this._collisionLayer))) {
obj.trigger('hit', col2);
obj.trigger('hit.sprite', col2);
// Do the recipricol collision
// TODO: extract
if (!skipEvents) {
var obj2 = col2.obj;
col2.obj = obj;
col2.normalX *= -1;
col2.normalY *= -1;
col2.distance = 0;
col2.magnitude = 0;
col2.separate[0] = 0;
col2.separate[1] = 0;
obj2.trigger('hit', col2);
obj2.trigger('hit.sprite', col2);
}
this.regrid(obj);
curCol--;
}
return col2 || col;
},
delGrid: function (item) {
var grid = item.grid;
for (var y = grid.Y1; y <= grid.Y2; y++) {
if (this.grid[y]) {
for (var x = grid.X1; x <= grid.X2; x++) {
if (this.grid[y][x]) {
delete this.grid[y][x][item.p.id];
}
}
}
}
},
addGrid: function (item) {
var grid = item.grid;
for (var y = grid.Y1; y <= grid.Y2; y++) {
if (!this.grid[y]) {
this.grid[y] = {};
}
for (var x = grid.X1; x <= grid.X2; x++) {
if (!this.grid[y][x]) {
this.grid[y][x] = {};
}
this.grid[y][x][item.p.id] = item.p.type;
}
}
},
// Add an item into the collision detection grid,
// Ignore the collision layer or objects without a type
regrid: function (item, skipAdd) {
if (this._collisionLayer && item === this._collisionLayer) {
return;
}
var c = item.c || item.p;
var gridX1 = Math.floor((c.x - c.cx) / this.options.gridW),
gridY1 = Math.floor((c.y - c.cy) / this.options.gridH),
gridX2 = Math.floor((c.x - c.cx + c.w) / this.options.gridW),
gridY2 = Math.floor((c.y - c.cy + c.h) / this.options.gridH),
grid = item.grid;
if (grid.X1 !== gridX1 || grid.X2 !== gridX2 ||
grid.Y1 !== gridY1 || grid.Y2 !== gridY2) {
if (grid.X1 !== void 0) {
this.delGrid(item);
}
grid.X1 = gridX1;
grid.X2 = gridX2;
grid.Y1 = gridY1;
grid.Y2 = gridY2;
if (!skipAdd) {
this.addGrid(item);
}
}
},
markSprites: function (items, time) {
var viewport = this.viewport,
scale = viewport ? viewport.scale : 1,
x = viewport ? viewport.x : 0,
y = viewport ? viewport.y : 0,
viewW = Q.width / scale,
viewH = Q.height / scale,
gridX1 = Math.floor(x / this.options.gridW),
gridY1 = Math.floor(y / this.options.gridH),
gridX2 = Math.floor((x + viewW) / this.options.gridW),
gridY2 = Math.floor((y + viewH) / this.options.gridH),
gridRow, gridBlock;
for (var iy = gridY1; iy <= gridY2; iy++) {
if ((gridRow = this.grid[iy])) {
for (var ix = gridX1; ix <= gridX2; ix++) {
if ((gridBlock = gridRow[ix])) {
for (var id in gridBlock) {
if(this.index[id] == void 0) continue; //add by jiangC. sprites maybe destroyed.
this.index[id].mark = time;
if (this.index[id].container) {
this.index[id].container.mark = time;
}
}
}
}
}
}
if (this._collisionLayer) {
this._collisionLayer.mark = time;
}
},
updateSprites: function (items, dt, isContainer) {
var item;
for (var i = 0, len = items.length; i < len; i++) {
item = items[i];
// If set to visible only, don't step if set to visibleOnly
if (!isContainer && (item.p.visibleOnly && item.mark < this.time)) {
continue;
}
if (isContainer || !item.container) {
item.update(dt);
Q._generateCollisionPoints(item);
this.regrid(item);
}
}
},
step: function (dt) {
if (this.paused) {
return false;
}
this.time += dt;
this.markSprites(this.items, this.time);
this.trigger("prestep", dt);
this.updateSprites(this.items, dt);
this.trigger("step", dt);
if (this.removeList.length > 0) {
for (var i = 0, len = this.removeList.length; i < len; i++) {
this.forceRemove(this.removeList[i]);
}
this.removeList.length = 0;
}
this.trigger('poststep', dt);
},
hide: function () {
this.hidden = true;
},
show: function () {
this.hidden = false;
},
stop: function () {
this.hide();
this.pause();
},
start: function () {
this.show();
this.unpause();
},
render: function (ctx) {
if (this.hidden) {
return false;
}
if (this.options.sort) {
this.items.sort(this.options.sort);
}
this.trigger("prerender", ctx);
this.trigger("beforerender", ctx);
for (var i = 0, len = this.items.length; i < len; i++) {
var item = this.items[i];
// Don't render sprites with containers (sprites do that themselves)
// Also don't render if not onscreen
if (!item.container && item.mark >= this.time) {
item.render(ctx);
}
}
this.trigger("render", ctx);
this.trigger("postrender", ctx);
}
});
Q.activeStage = 0;
Q.StageSelector = Q.Class.extend({
emptyList: [],
init: function (stage, selector) {
this.stage = stage;
this.selector = selector;
// Generate an object list from the selector
// TODO: handle array selectors
this.items = this.stage.lists[this.selector] || this.emptyList;
this.length = this.items.length;
},
each: function (callback) {
for (var i = 0, len = this.items.length; i < len; i++) {
callback.call(this.items[i], arguments[1], arguments[2]);
}
return this;
},
invoke: function (funcName) {
for (var i = 0, len = this.items.length; i < len; i++) {
this.items[i][funcName].call(
this.items[i], arguments[1], arguments[2]
);
}
return this;
},
trigger: function (name, params) {
this.invoke("trigger", name, params);
},
destroy: function () {
this.invoke("destroy");
},
detect: function (func) {
for (var i = 0, val = null, len = this.items.length; i < len; i++) {
if (func.call(this.items[i], arguments[1], arguments[2])) {
return this.items[i];
}
}
return false;
},
identify: function (func) {
var result = null;
for (var i = 0, val = null, len = this.items.length; i < len; i++) {
if (result = func.call(this.items[i], arguments[1], arguments[2])) {
return result;
}
}
return false;
},
// This hidden utility method extends
// and object's properties with a source object.
// Used by the p method to set properties.
_pObject: function (source) {
Q._extend(this.p, source);
},
_pSingle: function (property, value) {
this.p[property] = value;
},
set: function (property, value) {
// Is value undefined
if (value === void 0) {
this.each(this._pObject, property);
} else {
this.each(this._pSingle, property, value);
}
return this;
},
at: function (idx) {
return this.items[idx];
},
first: function () {
return this.items[0];
},
last: function () {
return this.items[this.items.length - 1];
}
});
// Maybe add support for different types
// entity - active collision detection
// particle - no collision detection, no adding components to lists / etc
//
// Q("Player").invoke("shimmer); - needs to return a selector
// Q(".happy").invoke("sasdfa",'fdsafas',"fasdfas");
// Q("Enemy").p({ a: "asdfasf" });
Q.select = function (selector, scope) {
scope = (scope === void 0) ? Q.activeStage : scope;
scope = Q.stage(scope);
if (Q._isNumber(selector)) {
return scope.index[selector];
} else {
return new Q.StageSelector(scope, selector);
// check if is array
// check is has any commas
// split into arrays
// find each of the classes
// find all the instances of a specific class
}
};
Q.stage = function (num) {
// Use activeStage is num is undefined
num = (num === void 0) ? Q.activeStage : num;
return Q.stages[num];
};
Q.stageScene = function (scene, num, options) {
// If it's a string, find a registered scene by that name
if (Q._isString(scene)) {
scene = Q.scene(scene);
}
// If the user skipped the num arg and went straight to options,
// swap the two and grab a default for num
if (Q._isObject(num)) {
options = num;
num = Q._popProperty(options, "stage") || (scene && scene.opts.stage) || 0;
}
// Clone the options arg to prevent modification
options = Q._clone(options);
// Grab the stage class, pulling from options, the scene default, or use
// the default stage
var StageClass = (Q._popProperty(options, "stageClass")) ||
(scene && scene.opts.stageClass) || Q.Stage;
// Figure out which stage to use
num = Q._isUndefined(num) ? ((scene && scene.opts.stage) || 0) : num;
// Clean up an existing stage if necessary
if (Q.stages[num]) {
Q.stages[num].destroy();
}
// Make this this the active stage and initialize the stage,
// calling loadScene to popuplate the stage if we have a scene.
Q.activeStage = num;
var stage = Q.stages[num] = new StageClass(scene, options);
// Load an assets object array
if (stage.options.asset) {
stage.loadAssets(stage.options.asset);
}
if (scene) {
stage.loadScene();
}
Q.activeStage = 0;
// If there's no loop active, run the default stageGameLoop
if (!Q.loop) {
Q.gameLoop(Q.stageGameLoop);
}
// Finally return the stage to the user for use if needed
return stage;
};
Q.stageGameLoop = function (dt) {
var i, len, stage;
if (dt < 0) {
dt = 1.0 / 60;
}
if (dt > 1 / 15) {
dt = 1.0 / 15;
}
for (i = 0, len = Q.stages.length; i < len; i++) {
Q.activeStage = i;
stage = Q.stage();
if (stage) {
stage.step(dt);
}
}
if (Q.ctx) {
Q.clear();
}
for (i = 0, len = Q.stages.length; i < len; i++) {
Q.activeStage = i;
stage = Q.stage();
if (stage) {
stage.render(Q.ctx);
}
}
Q.activeStage = 0;
if (Q.input && Q.ctx) {
Q.input.drawCanvas(Q.ctx);
}
};
Q.clearStage = function (num) {
if (Q.stages[num]) {
Q.stages[num].destroy();
Q.stages[num] = null;
}
};
Q.clearStages = function () {
for (var i = 0, len = Q.stages.length; i < len; i++) {
if (Q.stages[i]) {
Q.stages[i].destroy();
}
}
Q.stages.length = 0;
};
};
;/*global Quintus:false */
Quintus.Touch = function (Q) {
if (Q._isUndefined(Quintus.Sprites)) {
throw "Quintus.Touch requires Quintus.Sprites Module";
}
var hasTouch = !!('ontouchstart' in window);
var touchStage = [0];
var touchType = 0;
Q.Evented.extend("TouchSystem", {
init: function () {
var touchSystem = this;
this.boundTouch = function (e) {
touchSystem.touch(e);
};
this.boundDrag = function (e) {
touchSystem.drag(e);
};
this.boundEnd = function (e) {
touchSystem.touchEnd(e);
};
Q.el.addEventListener('touchstart', this.boundTouch);
// Q.el.addEventListener('mousedown', this.boundTouch);
Q.el.addEventListener('touchmove', this.boundDrag);
// Q.el.addEventListener('mousemove', this.boundDrag);
Q.el.addEventListener('touchend', this.boundEnd);
// Q.el.addEventListener('mouseup', this.boundEnd);
Q.el.addEventListener('touchcancel', this.boundEnd);
this.touchPos = new Q.Evented();
this.touchPos.grid = {};
this.touchPos.p = { w: 1, h: 1, cx: 0, cy: 0 };
this.activeTouches = {};
this.touchedObjects = {};
},
destroy: function () {
Q.el.removeEventListener('touchstart', this.boundTouch);
Q.el.removeEventListener('mousedown', this.boundTouch);
Q.el.removeEventListener('touchmove', this.boundDrag);
Q.el.removeEventListener('mousemove', this.boundDrag);
Q.el.removeEventListener('touchend', this.boundEnd);
Q.el.removeEventListener('mouseup', this.boundEnd);
Q.el.removeEventListener('touchcancel', this.boundEnd);
},
normalizeTouch: function (touch, stage) {
var canvasPosX = touch.offsetX,
canvasPosY = touch.offsetY;
if (Q._isUndefined(canvasPosX) || Q._isUndefined(canvasPosY)) {
canvasPosX = touch.layerX;
canvasPosY = touch.layerY;
}
if (Q._isUndefined(canvasPosX) || Q._isUndefined(canvasPosY)) {
if (Q.touch.offsetX === void 0) {
Q.touch.offsetX = 0;
Q.touch.offsetY = 0;
var el = Q.el;
do {
Q.touch.offsetX += el.offsetLeft;
Q.touch.offsetY += el.offsetTop;
} while (el = el.offsetParent);
}
canvasPosX = touch.pageX - Q.touch.offsetX;
canvasPosY = touch.pageY - Q.touch.offsetY;
}
this.touchPos.p.ox = this.touchPos.p.px = canvasPosX / Q.cssWidth * Q.width;
this.touchPos.p.oy = this.touchPos.p.py = canvasPosY / Q.cssHeight * Q.height;
if (stage.viewport) {
this.touchPos.p.px /= stage.viewport.scale;
this.touchPos.p.py /= stage.viewport.scale;
this.touchPos.p.px += stage.viewport.x;
this.touchPos.p.py += stage.viewport.y;
}
this.touchPos.p.x = this.touchPos.p.px;
this.touchPos.p.y = this.touchPos.p.py;
this.touchPos.obj = null;
return this.touchPos;
},
touch: function (e) {
var touches = e.changedTouches || [ e ];
for (var i = 0; i < touches.length; i++) {
for (var stageIdx = 0; stageIdx < touchStage.length; stageIdx++) {
var touch = touches[i],
stage = Q.stage(touchStage[stageIdx]);
if (!stage) {
continue;
}
touch.identifier = touch.identifier || 0;
var pos = this.normalizeTouch(touch, stage);
stage.regrid(pos, true);
var col = stage.search(pos, touchType), obj;
if (col || stageIdx === touchStage.length - 1) {
obj = col && col.obj;
pos.obj = obj;
this.trigger("touch", pos);
}
if (obj && !this.touchedObjects[obj]) {
this.activeTouches[touch.identifier] = {
x: pos.p.px,
y: pos.p.py,
origX: obj.p.x,
origY: obj.p.y,
sx: pos.p.ox,
sy: pos.p.oy,
identifier: touch.identifier,
obj: obj,
stage: stage
};
this.touchedObjects[obj.p.id] = true;
obj.trigger('touch', this.activeTouches[touch.identifier]);
break;
}
}
}
//e.preventDefault();
},
drag: function (e) {
var touches = e.changedTouches || [ e ];
for (var i = 0; i < touches.length; i++) {
var touch = touches[i];
touch.identifier = touch.identifier || 0;
var active = this.activeTouches[touch.identifier],
stage = active && active.stage;
if (active) {
var pos = this.normalizeTouch(touch, stage);
active.x = pos.p.px;
active.y = pos.p.py;
active.dx = pos.p.ox - active.sx;
active.dy = pos.p.oy - active.sy;
active.obj.trigger('drag', active);
}
}
e.preventDefault();
},
touchEnd: function (e) {
var touches = e.changedTouches || [ e ];
for (var i = 0; i < touches.length; i++) {
var touch = touches[i];
touch.identifier = touch.identifier || 0;
var active = this.activeTouches[touch.identifier];
if (active) {
active.obj.trigger('touchEnd', active);
delete this.touchedObjects[active.obj.p.id];
this.activeTouches[touch.identifier] = null;
}
}
e.preventDefault();
}
});
Q.touch = function (type, stage) {
Q.untouch();
touchType = type || Q.SPRITE_UI;
touchStage = stage || [2, 1, 0];
if (!Q._isArray(touchStage)) {
touchStage = [touchStage];
}
if (!Q._touch) {
Q.touchInput = new Q.TouchSystem();
}
return Q;
};
Q.untouch = function () {
if (Q.touchInput) {
Q.touchInput.destroy();
delete Q['touchInput'];
}
return Q;
};
};
;/*global Quintus:false */
Quintus.Anim = function (Q) {
Q._animations = {};
Q.animations = function (sprite, animations) {
if (!Q._animations[sprite]) {
Q._animations[sprite] = {};
}
Q._extend(Q._animations[sprite], animations);
};
Q.animation = function (sprite, name) {
return Q._animations[sprite] && Q._animations[sprite][name];
};
Q.component('animation', {
added: function () {
var p = this.entity.p;
p.animation = null;
p.animationPriority = -1;
p.animationFrame = 0;
p.animationTime = 0;
this.entity.on("step", this, "step");
},
extend: {
play: function (name, priority) {
this.animation.play(name, priority);
}
},
step: function (dt) {
var entity = this.entity,
p = entity.p;
if (p.animation) {
var anim = Q.animation(p.sprite, p.animation),
rate = anim.rate || p.rate,
stepped = 0;
p.animationTime += dt;
if (p.animationChanged) {
p.animationChanged = false;
} else {
p.animationTime += dt;
if (p.animationTime > rate) {
stepped = Math.floor(p.animationTime / rate);
p.animationTime -= stepped * rate;
p.animationFrame += stepped;
}
}
if (stepped > 0) {
if (p.animationFrame >= anim.frames.length) {
if (anim.loop === false || anim.next) {
p.animationFrame = anim.frames.length - 1;
entity.trigger('animEnd');
entity.trigger('animEnd.' + p.animation);
p.animation = null;
p.animationPriority = -1;
if (anim.trigger) {
entity.trigger(anim.trigger, anim.triggerData);
}
if (anim.next) {
this.play(anim.next, anim.nextPriority);
}
return;
} else {
entity.trigger('animLoop');
entity.trigger('animLoop.' + p.animation);
p.animationFrame = p.animationFrame % anim.frames.length;
}
}
entity.trigger("animFrame");
}
p.sheet = anim.sheet || p.sheet;
p.frame = anim.frames[p.animationFrame];
}
},
play: function (name, priority) {
var entity = this.entity,
p = entity.p;
priority = priority || 0;
if (name !== p.animation && priority >= p.animationPriority) {
p.animation = name;
p.animationChanged = true;
p.animationTime = 0;
p.animationFrame = 0;
p.animationPriority = priority;
entity.trigger('anim');
entity.trigger('anim.' + p.animation);
}
}
});
Q.Sprite.extend("Repeater", {
init: function (props) {
this._super(Q._defaults(props, {
speedX: 1,
speedY: 1,
repeatY: true,
repeatX: true,
type: 0
}));
this.p.repeatW = this.p.repeatW || this.p.w;
this.p.repeatH = this.p.repeatH || this.p.h;
},
draw: function (ctx) {
var p = this.p,
asset = this.asset(),
sheet = this.sheet(),
scale = this.stage.viewport ? this.stage.viewport.scale : 1,
viewX = Math.floor(this.stage.viewport ? this.stage.viewport.x : 0),
viewY = Math.floor(this.stage.viewport ? this.stage.viewport.y : 0),
offsetX = Math.floor(p.x + viewX * this.p.speedX),
offsetY = Math.floor(p.y + viewY * this.p.speedY),
curX, curY, startX;
if (p.repeatX) {
curX = -offsetX % p.repeatW;
if (curX > 0) {
curX -= p.repeatW;
}
} else {
curX = p.x - viewX;
}
if (p.repeatY) {
curY = -offsetY % p.repeatH;
if (curY > 0) {
curY -= p.repeatH;
}
} else {
curY = p.y - viewY;
}
startX = curX;
while (curY < Q.height / scale) {
curX = startX;
while (curX < Q.width / scale) {
if (sheet) {
sheet.draw(ctx, curX + viewX, curY + viewY, p.frame);
} else {
ctx.drawImage(asset, curX + viewX, curY + viewY);
}
curX += p.repeatW;
if (!p.repeatX) {
break;
}
}
curY += p.repeatH;
if (!p.repeatY) {
break;
}
}
}
});
Q.Tween = Q.Class.extend({
init: function (entity, properties, duration, easing, options) {
if (Q._isObject(easing)) {
options = easing;
easing = Q.Easing.Linear;
}
if (Q._isObject(duration)) {
options = duration;
duration = 1;
}
this.entity = entity;
//this.p = (entity instanceof Q.Stage) ? entity.viewport : entity.p;
this.duration = duration || 1;
this.time = 0;
this.options = options || {};
this.delay = this.options.delay || 0;
this.easing = easing || this.options.easing || Q.Easing.Linear;
this.startFrame = Q._loopFrame + 1;
this.properties = properties;
this.start = {};
this.diff = {};
},
step: function (dt) {
var property;
if (this.startFrame > Q._loopFrame) {
return true;
}
if (this.delay >= dt) {
this.delay -= dt;
return true;
}
if (this.delay > 0) {
dt -= this.delay;
this.delay = 0;
}
if (this.time === 0) {
// first time running? Initialize the properties to chaining correctly.
var entity = this.entity, properties = this.properties;
this.p = (entity instanceof Q.Stage) ? entity.viewport : entity.p;
for (property in properties) {
this.start[property] = this.p[property];
if (!Q._isUndefined(this.start[property])) {
this.diff[property] = properties[property] - this.start[property];
}
}
}
this.time += dt;
var progress = Math.min(1, this.time / this.duration),
location = this.easing(progress);
for (property in this.start) {
if (!Q._isUndefined(this.p[property])) {
this.p[property] = this.start[property] + this.diff[property] * location;
}
}
if (progress >= 1) {
if (this.options.callback) {
this.options.callback.apply(this.entity);
}
}
return progress < 1;
}
});
// Code ripped directly from Tween.js
// https://github.com/sole/tween.js/blob/master/src/Tween.js
Q.Easing = {
Linear: function (k) {
return k;
},
Quadratic: {
In: function (k) {
return k * k;
},
Out: function (k) {
return k * ( 2 - k );
},
InOut: function (k) {
if ((k *= 2 ) < 1) {
return 0.5 * k * k;
}
return -0.5 * (--k * (k - 2) - 1);
}
}
};
Q.component('tween', {
added: function () {
this._tweens = [];
this.entity.on("step", this, "step");
},
extend: {
animate: function (properties, duration, easing, options) {
this.tween._tweens.push(new Q.Tween(this, properties, duration, easing, options));
return this;
},
chain: function (properties, duration, easing, options) {
if (Q._isObject(easing)) {
options = easing;
easing = Q.Easing.Linear;
}
// Chain an animation to the end
var tweenCnt = this.tween._tweens.length;
if (tweenCnt > 0) {
var lastTween = this.tween._tweens[tweenCnt - 1];
options = options || {};
options['delay'] = lastTween.duration - lastTween.time + lastTween.delay;
}
this.animate(properties, duration, easing, options);
return this;
},
stop: function () {
this.tween._tweens.length = 0;
return this;
}
},
step: function (dt) {
for (var i = 0; i < this._tweens.length; i++) {
if (!this._tweens[i].step(dt)) {
this._tweens.splice(i, 1);
i--;
}
}
}
});
};
;/*global Quintus:false */
Quintus.UI = function (Q) {
if (Q._isUndefined(Quintus.Touch)) {
throw "Quintus.UI requires Quintus.Touch Module";
}
Q.UI = {};
// Draw a rounded rectangle centered on 0,0
Q.UI.roundRect = function (ctx, rect) {
ctx.beginPath();
ctx.moveTo(-rect.cx + rect.radius, -rect.cy);
ctx.lineTo(-rect.cx + rect.w - rect.radius, -rect.cy);
ctx.quadraticCurveTo(-rect.cx + rect.w, -rect.cy, -rect.cx + rect.w, -rect.cy + rect.radius);
ctx.lineTo(-rect.cx + rect.w, -rect.cy + rect.h - rect.radius);
ctx.quadraticCurveTo(-rect.cx + rect.w,
-rect.cy + rect.h,
-rect.cx + rect.w - rect.radius,
-rect.cy + rect.h);
ctx.lineTo(-rect.cx + rect.radius, -rect.cy + rect.h);
ctx.quadraticCurveTo(-rect.cx, -rect.cy + rect.h, -rect.cx, -rect.cy + rect.h - rect.radius);
ctx.lineTo(-rect.cx, -rect.cy + rect.radius);
ctx.quadraticCurveTo(-rect.cx, -rect.cy, -rect.cx + rect.radius, -rect.cy);
ctx.closePath();
};
Q.UI.Container = Q.Sprite.extend("UI.Container", {
init: function (p, defaults) {
var adjustedP = Q._clone(p || {}),
match;
if (p && Q._isString(p.w) && (match = p.w.match(/^[0-9]+%$/))) {
adjustedP.w = parseInt(p.w, 10) * Q.width / 100;
adjustedP.x = Q.width / 2 - adjustedP.w / 2;
}
if (p && Q._isString(p.h) && (match = p.h.match(/^[0-9]+%$/))) {
adjustedP.h = parseInt(p.h, 10) * Q.height / 100;
adjustedP.y = Q.height / 2 - adjustedP.h / 2;
}
this._super(Q._defaults(adjustedP, defaults), {
opacity: 1,
hidden: false, // Set to true to not show the container
fill: null, // Set to color to add background
highlight: null, // Set to color to for button
radius: 5, // Border radius
stroke: "#000",
border: false, // Set to a width to show a border
shadow: false, // Set to true or a shadow offest
shadowColor: false, // Set to a rgba value for the shadow
type: Q.SPRITE_NONE
});
},
insert: function (obj) {
this.stage.insert(obj, this);
return obj;
},
fit: function (paddingY, paddingX) {
if (this.children.length === 0) {
return;
}
if (paddingY === void 0) {
paddingY = 0;
}
if (paddingX === void 0) {
paddingX = paddingY;
}
var minX = Infinity,
minY = Infinity,
maxX = -Infinity,
maxY = -Infinity;
for (var i = 0; i < this.children.length; i++) {
var obj = this.children[i];
var minObjX = obj.p.x - obj.p.cx,
minObjY = obj.p.y - obj.p.cy,
maxObjX = obj.p.x - obj.p.cx + obj.p.w,
maxObjY = obj.p.y - obj.p.cy + obj.p.h;
if (minObjX < minX) {
minX = minObjX;
}
if (minObjY < minY) {
minY = minObjY;
}
if (maxObjX > maxX) {
maxX = maxObjX;
}
if (maxObjY > maxY) {
maxY = maxObjY;
}
}
this.p.cx = -minX + paddingX;
this.p.cy = -minY + paddingY;
this.p.w = maxX - minX + paddingX * 2;
this.p.h = maxY - minY + paddingY * 2;
},
addShadow: function (ctx) {
if (this.p.shadow) {
var shadowAmount = Q._isNumber(this.p.shadow) ? this.p.shadow : 5;
ctx.shadowOffsetX = shadowAmount;
ctx.shadowOffsetY = shadowAmount;
ctx.shadowColor = this.p.shadowColor || "rgba(0,0,50,0.1)";
}
},
clearShadow: function (ctx) {
ctx.shadowColor = "transparent";
},
drawRadius: function (ctx) {
Q.UI.roundRect(ctx, this.p);
this.addShadow(ctx);
ctx.fill();
if (this.p.border) {
this.clearShadow(ctx);
ctx.lineWidth = this.p.border;
ctx.stroke();
}
},
drawSquare: function (ctx) {
this.addShadow(ctx);
if (this.p.fill) {
ctx.fillRect(-this.p.cx, -this.p.cy,
this.p.w, this.p.h);
}
if (this.p.border) {
this.clearShadow(ctx);
ctx.lineWidth = this.p.border;
ctx.strokeRect(-this.p.cx, -this.p.cy,
this.p.w, this.p.h);
}
},
draw: function (ctx) {
if (this.p.hidden) {
return false;
}
if (!this.p.border && !this.p.fill) {
return;
}
ctx.globalAlpha = this.p.opacity;
if (this.p.frame === 1 && this.p.highlight) {
ctx.fillStyle = this.p.highlight;
} else {
ctx.fillStyle = this.p.fill;
}
ctx.strokeStyle = this.p.stroke;
if (this.p.radius > 0) {
this.drawRadius(ctx);
} else {
this.drawSquare(ctx);
}
}
});
Q.UI.ImgContainer = Q.Sprite.extend("UI.ImgContainer", {
init: function (p, defaults) {
var adjustedP = Q._clone(p || {}),
match;
if (p && Q._isString(p.w) && (match = p.w.match(/^[0-9]+%$/))) {
adjustedP.w = parseInt(p.w, 10) * Q.width / 100;
adjustedP.x = Q.width / 2 - adjustedP.w / 2;
}
if (p && Q._isString(p.h) && (match = p.h.match(/^[0-9]+%$/))) {
adjustedP.h = parseInt(p.h, 10) * Q.height / 100;
adjustedP.y = Q.height / 2 - adjustedP.h / 2;
}
this._super(Q._defaults(adjustedP, defaults), {
type: Q.SPRITE_NONE
});
},
insert: function (obj) {
this.stage.insert(obj, this);
return obj;
}
});
Q.UI.Text = Q.Sprite.extend("UI.Text", {
init: function (p, defaultProps) {
this._super(Q._defaults(p || {}, defaultProps), {
type: Q.SPRITE_UI,
size: 24
});
//this.el = document.createElement("canvas");
//this.ctx = this.el.getContext("2d");
if (this.p.label) {
this.calcSize();
}
//this.prerender();
},
calcSize: function () {
this.setFont(Q.ctx);
this.splitLabel = this.p.label.split("\n");
var maxLabel = "";
for (var i = 0; i < this.splitLabel.length; i++) {
if (this.splitLabel[i].length > maxLabel.length) {
maxLabel = this.splitLabel[i];
}
}
var metrics = Q.ctx.measureText(maxLabel);
this.p.h = (this.p.size || 24) * this.splitLabel.length * 1.2;
this.p.w = metrics.width;
this.p.cx = this.p.w / 2;
this.p.cy = this.p.h / 2;
},
prerender: function () {
if (this.p.oldLabel === this.p.label) {
return;
}
this.p.oldLabel = this.p.label;
this.calcSize();
this.el.width = this.p.w;
this.el.height = this.p.h * 4;
this.ctx.clearRect(0, 0, this.p.w, this.p.h);
this.ctx.fillStyle = "#FF0";
this.ctx.fillRect(0, 0, this.p.w, this.p.h / 2);
this.setFont(this.ctx);
this.ctx.fillText(this.p.label, 0, 0);
},
draw: function (ctx) {
//this.prerender();
if (this.p.opacity === 0) {
return;
}
if (this.p.oldLabel !== this.p.label) {
this.calcSize();
}
this.setFont(ctx);
if (this.p.opacity !== void 0) {
ctx.globalAlpha = this.p.opacity;
}
for (var i = 0; i < this.splitLabel.length; i++) {
if (this.p.align === 'center') {
ctx.fillText(this.splitLabel[i], 0, -this.p.cy + i * this.p.size * 1.2);
} else if (this.p.align === 'right') {
ctx.fillText(this.splitLabel[i], this.p.cx, -this.p.cy + i * this.p.size * 1.2);
} else {
ctx.fillText(this.splitLabel[i], -this.p.cx, -this.p.cy + i * this.p.size * 1.2);
}
}
},
asset: function () {
return this.el;
},
setFont: function (ctx) {
ctx.textBaseline = "top";
ctx.font = this.font();
ctx.fillStyle = this.p.color || "black";
ctx.textAlign = this.p.align || "left";
},
font: function () {
if (this.fontString) {
return this.fontString;
}
this.fontString = (this.p.weight || "800") + " " +
(this.p.size || 24) + "px " +
(this.p.family || "Arial");
return this.fontString;
}
});
Q.UI.Button = Q.UI.Container.extend("UI.Button", {
init: function (p, callback) {
this._super(Q._defaults(p, {
type: Q.SPRITE_UI | Q.SPRITE_DEFAULT
}));
if (this.p.label && (!this.p.w || !this.p.h)) {
Q.ctx.save();
this.setFont(Q.ctx);
var metrics = Q.ctx.measureText(this.p.label);
Q.ctx.restore();
if (!this.p.h) {
this.p.h = 24 + 20;
}
if (!this.p.w) {
this.p.w = metrics.width + 20;
}
}
if (isNaN(this.p.cx)) {
this.p.cx = this.p.w / 2;
}
if (isNaN(this.p.cy)) {
this.p.cy = this.p.h / 2;
}
this.callback = callback;
this.on('touch', this, "highlight");
this.on('touchEnd', this, "push");
},
highlight: function () {
if (!this.sheet() || this.sheet().frames > 1) {
this.p.frame = 1;
}
},
push: function () {
this.p.frame = 0;
if (this.callback) {
this.callback();
}
this.trigger('click');
},
draw: function (ctx) {
this._super(ctx);
if (this.p.asset || this.p.sheet) {
Q.Sprite.prototype.draw.call(this, ctx);
}
if (this.p.label) {
ctx.save();
this.setFont(ctx);
ctx.fillText(this.p.label, 0, 0);
ctx.restore();
}
},
setFont: function (ctx) {
ctx.textBaseline = "middle";
ctx.font = this.p.font || "400 24px arial";
ctx.fillStyle = this.p.fontColor || "black";
ctx.textAlign = "center";
}
});
Q.UI.IFrame = Q.Sprite.extend("UI.IFrame", {
init: function (p) {
this._super(p, { opacity: 1, type: Q.SPRITE_UI | Q.SPRITE_DEFAULT });
Q.wrapper.style.overflow = "hidden";
this.iframe = document.createElement("IFRAME");
this.iframe.setAttribute("src", this.p.url);
this.iframe.style.position = "absolute";
this.iframe.style.zIndex = 500;
this.iframe.setAttribute("width", this.p.w);
this.iframe.setAttribute("height", this.p.h);
this.iframe.setAttribute("frameborder", 0);
if (this.p.background) {
this.iframe.style.backgroundColor = this.p.background;
}
Q.wrapper.appendChild(this.iframe);
this.on("inserted", function (parent) {
this.positionIFrame();
parent.on("destroyed", this, "remove");
});
},
positionIFrame: function () {
var x = this.p.x;
var y = this.p.y;
if (this.stage.viewport) {
x -= this.stage.viewport.x;
y -= this.stage.viewport.y;
}
if (this.oldX !== x || this.oldY !== y || this.oldOpacity !== this.p.opacity) {
this.iframe.style.top = (y - this.p.cy) + "px";
this.iframe.style.left = (x - this.p.cx) + "px";
this.iframe.style.opacity = this.p.opacity;
this.oldX = x;
this.oldY = y;
this.oldOpacity = this.p.opacity;
}
},
step: function (dt) {
this._super(dt);
this.positionIFrame();
},
remove: function () {
if (this.iframe) {
Q.wrapper.removeChild(this.iframe);
this.iframe = null;
}
}
});
Q.UI.HTMLElement = Q.Sprite.extend("UI.HTMLElement", {
init: function (p) {
this._super(p, { opacity: 1, type: Q.SPRITE_UI });
Q.wrapper.style.overflow = "hidden";
this.el = document.createElement("div");
this.el.innerHTML = this.p.html;
Q.wrapper.appendChild(this.el);
this.on("inserted", function (parent) {
this.position();
parent.on("destroyed", this, "remove");
parent.on("clear", this, "remove");
});
},
position: function () {
},
step: function (dt) {
this._super(dt);
this.position();
},
remove: function () {
if (this.el) {
Q.wrapper.removeChild(this.el);
this.el = null;
}
}
});
Q.UI.VerticalLayout = Q.Sprite.extend("UI.VerticalLayout", {
init: function (p) {
this.children = [];
this._super(p, { type: 0 });
},
insert: function (sprite) {
this.stage.insert(sprite, this);
this.relayout();
// Bind to destroy
return sprite;
},
relayout: function () {
var totalHeight = 0;
for (var i = 0; i < this.children.length; i++) {
totalHeight += this.children[i].p.h || 0;
}
// Center?
var totalSepartion = this.p.h - totalHeight;
// Make sure all elements have the same space between them
}
});
};
;/*!
* Cookies.js - 0.3.1
* Wednesday, April 24 2013 @ 2:28 AM EST
*
* Copyright (c) 2013, Scott Hamper
* Licensed under the MIT license,
* http://www.opensource.org/licenses/MIT
*/
(function (undefined) {
'use strict';
var Cookies = function (key, value, options) {
return arguments.length === 1 ?
Cookies.get(key) : Cookies.set(key, value, options);
};
// Allows for setter injection in unit tests
Cookies._document = document;
Cookies._navigator = navigator;
Cookies.defaults = {
path: '/'
};
Cookies.get = function (key) {
if (Cookies._cachedDocumentCookie !== Cookies._document.cookie) {
Cookies._renewCache();
}
return Cookies._cache[key];
};
Cookies.set = function (key, value, options) {
options = Cookies._getExtendedOptions(options);
options.expires = Cookies._getExpiresDate(value === undefined ? -1 : options.expires);
Cookies._document.cookie = Cookies._generateCookieString(key, value, options);
return Cookies;
};
Cookies.expire = function (key, options) {
return Cookies.set(key, undefined, options);
};
Cookies._getExtendedOptions = function (options) {
return {
path: options && options.path || Cookies.defaults.path,
domain: options && options.domain || Cookies.defaults.domain,
expires: options && options.expires || Cookies.defaults.expires,
secure: options && options.secure !== undefined ? options.secure : Cookies.defaults.secure
};
};
Cookies._isValidDate = function (date) {
return Object.prototype.toString.call(date) === '[object Date]' && !isNaN(date.getTime());
};
Cookies._getExpiresDate = function (expires, now) {
now = now || new Date();
switch (typeof expires) {
case 'number': expires = new Date(now.getTime() + expires * 1000); break;
case 'string': expires = new Date(expires); break;
}
if (expires && !Cookies._isValidDate(expires)) {
throw new Error('`expires` parameter cannot be converted to a valid Date instance');
}
return expires;
};
Cookies._generateCookieString = function (key, value, options) {
key = encodeURIComponent(key);
value = (value + '').replace(/[^!#$&-+\--:<-\[\]-~]/g, encodeURIComponent);
options = options || {};
var cookieString = key + '=' + value;
cookieString += options.path ? ';path=' + options.path : '';
cookieString += options.domain ? ';domain=' + options.domain : '';
cookieString += options.expires ? ';expires=' + options.expires.toUTCString() : '';
cookieString += options.secure ? ';secure' : '';
return cookieString;
};
Cookies._getCookieObjectFromString = function (documentCookie) {
var cookieObject = {};
var cookiesArray = documentCookie ? documentCookie.split('; ') : [];
for (var i = 0; i < cookiesArray.length; i++) {
var cookieKvp = Cookies._getKeyValuePairFromCookieString(cookiesArray[i]);
if (cookieObject[cookieKvp.key] === undefined) {
cookieObject[cookieKvp.key] = cookieKvp.value;
}
}
return cookieObject;
};
Cookies._getKeyValuePairFromCookieString = function (cookieString) {
// "=" is a valid character in a cookie value according to RFC6265, so cannot `split('=')`
var separatorIndex = cookieString.indexOf('=');
// IE omits the "=" when the cookie value is an empty string
separatorIndex = separatorIndex < 0 ? cookieString.length : separatorIndex;
return {
key: decodeURIComponent(cookieString.substr(0, separatorIndex)),
value: decodeURIComponent(cookieString.substr(separatorIndex + 1))
};
};
Cookies._renewCache = function () {
Cookies._cache = Cookies._getCookieObjectFromString(Cookies._document.cookie);
Cookies._cachedDocumentCookie = Cookies._document.cookie;
};
Cookies._areEnabled = function () {
return Cookies._navigator.cookieEnabled ||
Cookies.set('cookies.js', 1).get('cookies.js') === '1';
};
Cookies.enabled = Cookies._areEnabled();
// AMD support
if (typeof define === 'function' && define.amd) {
define(function () { return Cookies; });
// CommonJS and Node.js module support.
} else if (typeof exports !== 'undefined') {
// Support Node.js specific `module.exports` (which can be a function)
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = Cookies;
}
// But always support CommonJS module 1.1.1 spec (`exports` cannot be a function)
exports.Cookies = Cookies;
} else {
window.Cookies = Cookies;
}
})();;/**
* Created by jiangcheng.wxd on 14-1-16.
*/
(function () {
window.Plana = {};
Plana = {
//求斜率,b
slope: function (v1, v2) {
v1.x === undefined ? (v1.x = 1) : 0;
v1.y === undefined ? (v1.y = 1) : 0;
v2.x === undefined ? (v2.x = 1) : 0;
v2.y === undefined ? (v2.y = 1) : 0;
var k;
if (v2.x === v1.x) {
k = Number.MAX_VALUE;
}
else {
k = (v2.y - v1.y) / (v2.x - v1.x);
}
var b = v1.y - k * (v1.x);
return {
k: k,
b: b
}
},
//两点距离
squares: function (v1, v2) {
return Math.sqrt(Math.pow((v1.x - v2.x),2) + Math.pow(Math.abs(v1.y - v2.y),2));
},
//已知两点的距离,一个向量的坐标,斜率,求另一个向量的坐标.
trapezoid: function (v1, v2, ow) {
var k = -1 / (Plana.slope(v1, v2)).k;
if (Math.abs(k) > 100 && k < 0) k = -100;
if (Math.abs(k) > 100 && k > 0) k = 100;
//已知两点的距离,一个向量的坐标,斜率,求另一个向量的坐标
function getPoints(dis, v1, k) {
var b = v1.y - k * v1.x;
var A = (1 + k * k);
var B = 2 * k * (b - v1.y) - 2 * v1.x;
var C = v1.x * v1.x + (b - v1.y) * (b - v1.y) - dis * dis;
if ((B * B - 4 * A * C) < 0) {
throw error('no solvement');
}
var x1 = (-B + Math.sqrt(B * B - 4 * A * C)) / 2 * A;
var x2 = (-B - Math.sqrt(B * B - 4 * A * C)) / 2 * A;
var y1 = k * x1 + b;
var y2 = k * x2 + b;
return {
X1: x1,
Y1: y1,
X2: x2,
Y2: y2
}
}
return getPoints(ow, v1, k);
},
//向量和.
sum: function (v1, v2) {
v1.x || (v1.x = 0);
v1.y || (v1.y = 0);
v2.x || (v2.x = 0);
v2.y || (v1.y = 0);
return {
x: (v1.x + v2.x),
y: (v1.y + v2.y)
}
},
/*
* 计算两个向量的逆时针夹角
* */
anticlockwise: function(v1,v2){
var dot = v1.x * v2.x + v1.y * v2.y;
var cross = v1.x * v2.y - v2.x * v1.y;
var cosX = dot / ( Math.sqrt(v1.x*v1.x + v1.y*v1.y) * Math.sqrt(v2.x*v2.x + v2.y*v2.y));
var rad = Math.acos(cosX);
var deg;
if(cross < 0){
rad = 2*Math.PI - rad;
}
deg = rad * 180 / Math.PI;
return deg;
},
/*
求夹角.
*/
interSect: function (v1, v2) {
v1.x || (v1.x = 0);
v1.y || (v1.y = 0);
v2.x || (v2.x = 0);
v2.y || (v1.y = 0);
var dot = v1.x * v2.x + v1.y * v2.y;
var cosX = dot / ( Math.sqrt(v1.x * v1.x + v1.y * v1.y) * Math.sqrt(v2.x * v2.x + v2.y * v2.y));
var angleRad = Math.acos(cosX);
var angleDeg = angleRad * 180 / Math.PI;
return angleDeg;
},
/*
向量取样,容忍度(角度)为t.
*/
samplePoints: function (points, t) {
var len = points.length;
var result = [];
var tolerance = (t === undefined ? 30 : t);
if (len >= 3) {
var pivot = {
x: points[1].x - points[0].x,
y: points[1].y - points[0].x
};
result.push({
x: points[0].x,
y: points[0].y
});
var cta;
var temp;
for (var i = 0; i < len - 1; i++) {
temp = {
x: points[i + 1].x - points[i].x,
y: points[i + 1].y - points[i].y
};
cta = Plana.interSect(temp, pivot);
if (cta > tolerance) {
pivot.x = temp.x;
pivot.y = temp.y;
result.push({
x: points[i].x,
y: points[i].y
});
}
}
result.push({
x: points[len - 1].x,
y: points[len - 1].y
});
}
else {
return points;
}
return result;
},
/*
求quadraticCurveTo控制点
*/
quadraticControlPoint: function(v1,v2,t){
//todo.
}
}
}());/**
* Created by jiangcheng.wxd on 14-2-8.
*/
Quintus.Data = function (Q) {
function errorUnit(e,which){
if(wish && wish.alert){
wish.alert(e);
}
else{
alert(e);
}
$('#r_wrapper').addClass('hide');
$(Q.el.parentNode).addClass('hide');
Q.clear();
Q.bless.controller.roundClear();
Q.bless.quitCb();
Q.bless = {};
};
Q.request = {
getLocation: function(cb){
var op = {
// 指示浏览器获取高精度的位置,默认为false
enableHighAcuracy: false,
//获取详细地址描述信息
address:false
};
try{
window.navigator.geolocation.getCurrentPosition(function(e){
cb(JSON.stringify(e));
}, function(e){
cb(null);
}, op);
}
catch (e){
errorUnit(e,'getLocation');
}
},
getNearBy: function(){
Q.request.getLocation(function(loc){
var l = {};
if(loc === null || loc === undefined) {
Q.bless.nearBy = 0;
return;
}
else{
l = JSON.parse(loc).coords || {};
}
try{
window.WindVane.api.server.send(function(e){
try{
var ret = e.ret || '';
ret = ret.join('').toLowerCase();
if(ret.indexOf('session') > -1){
(wish && wish.login());
}
else{
var data = e.data || {};
if(data && data.nearByUserActCount){
Q.bless.nearBy = parseInt(data.nearByUserActCount);
}
else{
Q.bless.nearBy = 0;
}
}
}
catch (ex){
errorUnit(ex,'getNearBy')
}
},function(e){
var ret = e.ret || '';
ret = ret.join('').toLowerCase();
if(ret.indexOf('session') > -1){
(wish && wish.login());
}
else{
Q.bless.nearBy = 0;
}
},{
api: 'mtop.taobao.stargame.getNearUserCount',
v: '1.0', post: '1',
ecode: '1',
param:{
'lat': l.latitude || 0,
'lon': l.longitude || 0,
'accuracy': l.accuracy || 0
}
});
}
catch (e){
errorUnit(e,'getNearBy');
Q.bless.nearBy = 0;
}
});
},
commitStarScore: function(p,cb){
window.WindVane.api.server.send(function(e){
try{
var ret = e.ret || '';
var data = e.data || {};
var result = data.result || [];
ret = ret.join('').toLowerCase();
if(ret.indexOf('success') > -1){
if(result.length > 0){
var starType = -1;
var starScore = -1;
for(var i = 0,len = result.length; i < len; i++){
starType = result[i].starType || -1;
starScore = result[i].starScore || -1;
if(starType === -1 || starScore === -1){
errorUnit('接口返回错误,请刷新重试','commitStarScore');
return;
}
else{
Q.bless.total[starType] = +starScore;
}
}
cb(true);
return;
}
else{
cb(false);
errorUnit('接口返回错误,请刷新重试','commitStarScore');
return;
}
}
else{
if(ret.indexOf('session') > -1){
(wish && wish.login());
}
}
cb(false);
errorUnit(ret,'commitStarScore');
}
catch (e){
cb(false);
errorUnit(e.toString(),'commitStarScore');
}
},function(e){
var ret = e.ret || '接口返回错误,请刷新重试';
ret = ret.join('').toLowerCase();
if(ret.indexOf('session') > -1){
(wish && wish.login());
}
else{
cb(false);
errorUnit(ret,'commitStarScore');
}
},{
api: 'mtop.taobao.stargame.commitStarScore',
v: '1.0', post: '1',
ecode: '1',
param:p
});
},
showShareMenu: function(){
var txt = [
'我正参加手机淘宝#抓住那颗星#游戏,捕获了好多流星,距离和李敏镐亲密接触又近一步,你也来玩!',
'我正参加手机淘宝#抓住那颗星#游戏,玩命捕星星中,距离80天环游世界又进一步啦,你也来玩!',
'我正在参加手机淘宝#抓住那颗星#游戏,努力总会有回报,捕星星ing,离百万海景房又近一步,你也来玩!'
];
var p = {
'image':'http://gtms01.alicdn.com/tps/i1/T1SuWxFphXXXc_KfZM-440-793.jpg',
'url':'http://h5.m.taobao.com/other/cloud-jump.html?actname=wish38',
'title':'抓住那颗星',
'text':txt[Q.rand(0,2)]
};
try{
window.WindVane.api.base.showShareMenu(function(s){
}, function(e){
}, p);
}
catch (e){
errorUnit(e.toString(),showShareMenu);
}
},
rate: function(){
$.ajax({
type: 'GET',
url: 'http://www.taobao.com/go/rgn/bless38.php',
data:{},
dataType:'jsonp',
success: function(data){
if(data.rand){
var rand = data.rand;
for(var i = 0,len = rand.length; i < len; i++){
if(rand[i].type === 'sun'){
Q.bless.likely.sun = +rand[i].rate;
}
if(rand[i].type === 'liquid'){
Q.bless.likely.liquid = +rand[i].rate;
}
if(rand[i].type === 'multiply'){
Q.bless.likely.multiply = +rand[i].rate;
}
if(rand[i].type === 'limit'){
Q.bless.limit = +rand[i].rate;
}
if(rand[i].type === 'lowX'){
if(!Q.bless.hiDPI) rand[i].rate = rand[i].rate/2;
Q.bless.likely.lowX = +rand[i].rate;
}
if(rand[i].type === 'highX'){
if(!Q.bless.hiDPI) rand[i].rate = rand[i].rate/2;
Q.bless.likely.highX = +rand[i].rate;
}
if(rand[i].type === 'lowY'){
if(!Q.bless.hiDPI) rand[i].rate = rand[i].rate/2;
Q.bless.likely.lowY = +rand[i].rate;
}
if(rand[i].type === 'highY'){
if(!Q.bless.hiDPI) rand[i].rate = rand[i].rate/2;
Q.bless.likely.highY = +rand[i].rate;
}
}
}
},
error: function(){
console.log('rand ajax error');
}
});
}
}
};/**
* Created by jiangcheng.wxd on 14-1-22.
*/
Quintus.gameSprites = function (Q) {
Q.rand = function (m, n) {
return Math.round(Math.random() * (n - m) + m);
};
Q.randArr = function (a) {
var len = a.length;
return a[Q.rand(0,len - 1)];
};
//过滤点,同时插入新的结点.
function sample(points,t){
var result = [];
var len = points.length;
if(len >= 2){
var pivot = points[0];
result.push(pivot);
for(var i = 1; i < (len - 1); i++){
if(Plana.squares(pivot,points[i]) > t){
pivot = points[i];
if(i > 1){
result.push({
x: (points[i].x + points[i-1].x)/2,
y: (points[i].y + points[i-1].y)/2
});
}
result.push(points[i]);
}
}
result.push(points[i]);
}
else{
return points;
}
return result;
}
Q.Sprite.extend("Starlet",{
init: function(p) {
this._super(p, {
sprite: 'star.png',
sheet:'star',
w: 50,
h: 50,
ax: 0,
ay: 400,
scale: 0.3,
collisionMask: Q.SPRITE_NONE
});
this.lifetime = 2;
this.age = 0;
this.originalSize = this.p.size;
},
reset: function(param){
this.lifetime = 2;
this.age = 0;
for(var i in param){
if(param.hasOwnProperty(i)){
this.p[i] = param[i]
}
}
this.p.opacity = 1;
},
step: function(dt) {
this.age += dt;
if (this.age > this.lifetime) {
this.destroy();
}
this.p.size = this.originalSize * (1 - (this.age / this.lifetime));
this.p.cx = this.p.size / 2;
this.p.cy = this.p.size / 2;
this.p.vx += this.p.ax * dt;
this.p.vy += this.p.ay * dt + dt * this.p.gravity;
this.p.x += this.p.vx * dt;
this.p.y += this.p.vy * dt;
this.p.scale -= 0.008;
if(this.p.scale <= 0){
Q.bless.mainRootStage.remove(this);
Q.bless.StarLetPool.push(this);
}
}
});
Q.Sprite.extend("Star",{
init: function (p) {
this._super(p, {
x: Q.width/2,
y: Q.height/2,
vx: 0,
vy: 0,
ax: 0,
ay: 0,
scale: (function(){
if(!Q.bless.isPad) return Q.bless.starScale
else return 1;
})(),
collisionMask: Q.SPRITE_DEFAULT,
type: Q.SPRITE_DEFAULT,
points: [
[ -35, -35 ],
[-35, 35 ],
[35, -35 ],
[35, 35 ]
],
sprite: 'star',
sheet: 'star',
w: 85,
h: 85,
frame: 0,
age : 10000000
});
//石化
this.isStone = false;
this.add("2d");
this.on('hit', this, 'collide');
},
collide: function(col){
if(col.obj.isStone && !this.isStone && this.p.frame !== 7){
this.isStone = true;
this.p.frame = 9;
Q.bless.stoneArr.push(this);
if(Q.bless.stoneArr.length >= Q.bless.stoneYLimit){
Q.bless.controller.trigger('thisRoundEnd');
}
(function removeStoneStar(){
var s = [];
var stars = Q.bless.controller.stars;
for(var i = 0,len = stars.length; i < len;i++){
if(!stars[i].isStone) s.push(stars[i]);
}
Q.bless.controller.stars = [];
Q.bless.controller.stars = s;
if(s.length <= 2){
Q.bless.controller.emitStar(Q.bless.limit);
}
})();
}
},
dust:function(){
var _self = this;
var ss = 0.3;
if(Q.bless.hiDPI) ss = 0.4;
var p = _self.p;
var g = 400;
if(p.frame === 9) g = 200;
for (var i = 0; i < 3; i++) {
var x = p.x + (p.cx - Math.random() * p.cx * 3);
var y = p.y + (p.cy - Math.random() * p.cy * 3);
var vx = 100 - Math.random() * 200;
var vy = 100 - Math.random() * 300;
_self.stage.insert(Q.bless.controller.getStarLetPool({x: x, y: y, vx: vx, vy: vy, size: 10, scale: ss, frame: p.frame, gravity: g}));
}
},
collect: function(){
Q.bless.mainRootStage.remove(this);
Q.bless.StarPool.push(this);
},
reset: function(param){
this.isStone = false;
for(var i in param){
if(param.hasOwnProperty(i)){
this.p[i] = param[i]
}
}
},
step: function(dt) {
var p = this.p;
var _self = this;
if(p.still || _self.isStone) return;
function liner(p){
//从左侧飞出
if(p.x <= 0 && p.y < Q.height){
p.x = Q.rand(Q.width/2, Q.width);
p.y = 20;
p.vx = -4;
p.vy = 4;
p.ax = Q.rand(Q.bless.likely.lowX, Q.bless.likely.highX);
p.ay = Q.rand(Q.bless.likely.lowY, Q.bless.likely.highY);
p.angle = 0;
//太阳变成星星.
if(p.frame === 7 || p.frame === 8){
if(Math.random() > 0.5) p.frame = Q.randArr(Q.bless.candidate);
}
}
if(!_self.isStone){
if(p.y >= (Q.height - p.h/4) && p.x > 0 && p.x <= Q.width){
//底部飞出的太阳、星星
if(p.frame !== 7 && p.frame !== 8){
_self.isStone = true;
p.frame = 9;
Q.bless.stoneArr.push(_self);
if(Q.bless.stoneArr.length >= Q.bless.stoneYLimit){
Q.bless.controller.trigger('thisRoundEnd');
}
(function removeStoneStar(){
var s = [];
var stars = Q.bless.controller.stars;
for(var i = 0,len = stars.length; i < len;i++){
if(!stars[i].isStone) s.push(stars[i]);
}
Q.bless.controller.stars = [];
Q.bless.controller.stars = s;
if(s.length <= 2){
Q.bless.controller.emitStar(Q.bless.limit);
}
})();
}
else{
p.x = Q.width;
p.y = 20;
p.vx = -40;
p.vy = 80;
p.angle = 0;
if(Math.random() > 0.5) p.frame = Q.randArr(Q.bless.candidate);
}
}
else{
p.vx += p.ax * dt;
p.x += p.vx * dt;
p.vy += p.ay * dt;
p.y += p.vy * dt;
}
}
}
liner(p);
},
isIn: function(pos){
//石化
if(this.p.frame === 9) return false;
var r1 = {};
if(pos.ox <= pos.cx && pos.oy <= pos.cy){
r1.left = pos.ox;
r1.right = pos.cx;
r1.top = pos.oy;
r1.bottom = pos.cy;
}
if(pos.ox <= pos.cx && pos.oy > pos.cy){
r1.left = pos.ox;
r1.right = pos.cx;
r1.top = pos.cy;
r1.bottom = pos.oy;
}
if(pos.ox > pos.cx && pos.oy >= pos.cy){
r1.left = pos.cx;
r1.right = pos.ox;
r1.top = pos.cy;
r1.bottom = pos.oy;
}
if(pos.ox > pos.cx && pos.oy <= pos.cy){
r1.left = pos.cx;
r1.right = pos.ox;
r1.top = pos.oy;
r1.bottom = pos.cy;
}
var r2 = {};
r2.left = this.p.x - this.p.w/2;
r2.right = this.p.x + this.p.w/2;
r2.top = this.p.y - this.p.h/2;
r2.bottom = this.p.y + this.p.h/2;
var result = !(r2.left > r1.right ||
r2.right < r1.left ||
r2.top > r1.bottom ||
r2.bottom < r1.top);
return result;
}
});
Q.Sprite.extend('Leaf',{
init: function(p) {
this._super(p, {
sprite: 'star-leaf.png',
sheet: 'star-leaf',
w: 50,
h: 50,
scale: (function(){
if(!Q.bless.isPad) return Q.bless.leafScale
else return 1;
})(),
collisionMask: Q.SPRITE_NONE
});
this.lifetime = 10;
this.age = 0;
},
reset: function(param){
this.lifetime = 10;
this.age = 0;
for(var i in param){
if(param.hasOwnProperty(i)){
this.p[i] = param[i]
}
}
this.p.opacity = 1;
},
step: function(dt) {
if(!!this.p.still) return;
this.age += dt;
if (this.age > this.lifetime) {
this.destroy();
}
var p = this.p;
p.vx += p.ax * dt;
p.vy += p.ay * dt;
p.x += p.vx * dt;
p.y += p.vy * dt;
p.opacity -= 0.01;
if(p.opacity <= 0){
Q.bless.mainRootStage.remove(this);
Q.bless.LeafPool.push(this);
}
}
});
Q.Sprite.extend("Box", {
init: function (p) {
this._super(p, {
x: Q.width / 2,
y: Q.height / 2,
w: Q.width,
h: Q.height,
scale: 1,
asset: '',
z: 10,
type: Q.SPRITE_UI
});
this.on('touch',this._touch);
this.on('drag',this._drag);
this.on('touchEnd',this._touchEnd);
this.on('touchcancel',this._cancel);
this.touches = [];
this.tick = 0;
},
_touch: function(e){
this.touches = [];
if(Q.bless.stop) return;
this.touches.push({
x: e.x - Q.width/2,
y: e.y - Q.height / 2
});
this.trigger('movingStart',e);
},
_cancel: function(){
console.log('cancel');
},
_touchEnd: function(e){
if(Q.bless.stop) return;
this.trigger('movingEnd',e);
this.touches = [];
},
_drag: function(e){
if(Q.bless.stop) return;
var len = this.touches.length;
if(len === 0){
this.touches.push({
x: e.x - Q.width/2,
y: e.y - Q.height / 2
});
this.trigger('moving',e);
}
else if(Plana.squares(e,this.touches[len - 1]) > 5){
this.touches.push({
x: e.x - Q.width/2,
y: e.y - Q.height / 2
});
this.trigger('moving',e);
}
},
draw: function(ctx){
if(Q.bless.stop) return;
if(true){
var len = this.touches.length;
if(len < 5) return;
var w = 0;
var stepPlus = 1.5;
var stepMinus = 0.15;
var shadowBlur = 2;
if(Q.bless.hiDPI){
stepPlus *= 2;
stepMinus *= 2;
shadowBlur *= 2;
}
for(var i = len - 5; i < len - 2; i+=2){
if(i < len - 2){
w = w + stepPlus;
}
else{
w = w - stepMinus;
}
ctx.lineWidth = w;
ctx.strokeStyle = "white";
ctx.lineCap = 'round';
ctx.shadowColor = 'white';
ctx.shadowBlur = shadowBlur;
ctx.beginPath();
ctx.moveTo(this.touches[i].x, this.touches[i].y);
ctx.quadraticCurveTo(this.touches[i + 1].x, this.touches[i + 1].y,this.touches[i + 2].x, this.touches[i + 2].y);
ctx.stroke();
ctx.closePath();
}
}
}
});
Q.Sprite.extend('Hand',{
init: function(p){
this._super(p, {
x: Q.width / 2 - 50,
y: Q.height / 2 + 150,
scale: 0.6,
asset: 'hand.png',
type: Q.SPRITE_DEFAULT
});
this.add('animation');
this.add('tween');
},
move: function(cb){
var _self = this;
_self.add('tween');
_self.animate({ x: Q.width / 2 + 100, y: Q.height / 2 - 50},1, Q.Easing.Quadratic.In,{
callback:function(){
cb();
}
});
}
});
Q.Sprite.extend('Dwarf',{
init: function(p){
this._super(p, {
x: Q.bless.pauseDist * 3,
y: 30,
scale: Q.bless.dwarfScale,
sprite: 'dwarf',
sheet: 'dwarf',
frame: 0,
type: Q.SPRITE_DEFAULT
});
this.add('animation');
},
hit: function(){
var _self = this;
_self.play('show');
}
});
Q.Sprite.extend('Award',{
init: function(p){
this._super(p, {
scale: 0.6,
sprite: 'award',
sheet: 'award',
frame: 0,
type: Q.SPRITE_DEFAULT
});
this.lifetime = 1.5;
this.age = 0;
},
step: function(dt) {
this.age += dt;
if (this.age > this.lifetime) {
this.trigger('delete');
}
this.p.scale += 0.008;
if(this.p.scale <= 0){
this.trigger('delete');
}
}
});
Q.Sprite.extend("Pause", {
init: function (p) {
this._super(p, {
x: Q.bless.pauseDist,
y: Q.bless.pauseDist,
scale: (function(){
if(!Q.bless.isPad) return Q.bless.pauseScale
else return 1;
})(),
asset: 'pause.png',
type: Q.SPRITE_UI
});
this.stage = p.stage;
this.on('touch',this._touch);
},
_touch: function(e){
Q.bless.pause();
$('#r_pause').removeClass('hide');
}
});
Q.Sprite.extend('Halo',{
init: function(p){
this._super(p, {
x: 0,
y: 0,
w: Q.width,
h: Q.height,
scale: 1,
asset: 'hand.png',
direct:'L',
type: Q.SPRITE_DEFAULT
});
this.p.d = {};
this.p.d.x = this.p.b.x;
this.p.d.y = this.p.b.y;
this.fill = false;
},
step: function(dt){
if(this.fill){
var d = this.p.direct;
var w = Q.width;
var h = Q.height;
var c = this.p.c;
if(d === 'R'){
if(c.x < w) {
c.x += dt* 1000;
}
else{
c.x = w;
c.y += dt*1000;
this.p.d.x = w;
this.p.d.y = 0;
}
}
if(d === 'D'){
if(c.y < h){
c.y += dt* 1000;
}
else{
c.y = h;
c.x -= dt*1000;
this.p.d.x = w;
this.p.d.y = h;
}
}
if(d === 'L'){
if(c.x > 0){
c.x -= dt* 1000;
}
else{
c.y -= dt*1000;
c.x = 0;
this.p.d.x = 0;
this.p.d.y = h;
}
}
if(d === 'U'){
if(c.y > 0){
c.y -= dt* 1000;
}
else{
c.y = 0;
c.x += dt* 1000;
this.p.d.x = 0;
this.p.d.y = 0;
}
}
}
},
draw: function(ctx){
if(this.p.a){
var p = this.p;
ctx.fillStyle = 'white';
ctx.beginPath();
ctx.moveTo(p.a.x, p.a.y);
ctx.lineTo(p.b.x, p.b.y);
ctx.lineTo(p.d.x, p.d.y);
ctx.lineTo(p.c.x, p.c.y);
ctx.fill();
ctx.closePath();
}
},
padding: function(){
this.fill = true;
}
});
Q.UI.Text.extend('Score',{
init: function(p){
this._super(p, {
color: 'white',
label: "0",
size: Q.bless.scoreSize,
x: (function(){
if(Q.bless.hiDPI) return 180
else return 140;
})(),
y: (function(){
if(Q.bless.hiDPI) return 50
else return 40;
})()
});
},
count: function(s){
this.p.label = '' + s;
}
});
Q.animations('dwarf', {
show: {
frames: [0,1,2,3,0],
rate: 1/6,
loop: false
}
});
}
;/**
* Created by jiangcheng.wxd on 14-1-18.
*/
window.addEventListener("load", function () {
var Q = window.Q = Quintus({
development: true
}).include("Sprites, Scenes, Touch, UI, Anim, gameSprites, 2D, Data");
Q.debug = false;
function Init() {
var w = window.innerWidth;
var h = window.innerHeight;
var devicePixelRatio = window.devicePixelRatio || 1;
var userAgent = navigator.userAgent;
var isIOS = (/iPhone|iPod|iTouch/i).test(userAgent);
var blacklisted = /iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent);
if (devicePixelRatio >= 2 && isIOS && !blacklisted) {
if(!Q.el){
Q.setup({
width: 2*w,
height: 2*h,
cssWidth: w,
cssHeight: h
}).touch(Q.SPRITE_UI);
}
else{
$(Q.el.parentNode).removeClass('hide');
Q.bless.unpause();
}
Q.bless.hiDPI = true;
}
else{
Q.bless.leafScale = 0.5;
Q.bless.starScale = 0.5;
Q.bless.pauseScale = 0.5;
Q.bless.dwarfScale = 0.7;
Q.bless.scoreSize = 20;
Q.bless.pauseDist = 40;
if(!Q.el){
Q.setup({
width: w,
height: h,
cssWidth: w,
cssHeight: h
}).touch(Q.SPRITE_UI);
}
else{
$(Q.el.parentNode).removeClass('hide');
Q.bless.unpause();
}
}
Q.request.rate();
};
Q.Evented.extend('Controller', {
init: function (stage) {
this.stage = stage;
this.pause = new Q.Pause(stage);
this.stage.insert(this.pause);
this.box = new Q.Box();
this.stage.insert(this.box);
this.dwarf = new Q.Dwarf();
this.stage.insert(this.dwarf);
this.score = new Q.Score();
this.stage.insert(this.score);
this.stars = [];
this.kill = 0;
this.eveBind();
},
eveBind: function(){
var _self = this;
var killed = 0;
function moveEnd() {
if(Q.bless.stop) return;
var box = _self.box;
var count = _self.stars.length;
var quit = false;
for (var j = 0; j < count; j++) {
var star = _self.stars[j];
if(quit) break;
quit = false;
if(!star.isDestroyed) {
for (var i = 0, len = box.touches.length; i < len - 1; i++) {
var v1 = {
x: box.touches[i].x + Q.width / 2,
y: box.touches[i].y + Q.height / 2
};
var v2 = {
x: box.touches[i + 1].x + Q.width / 2,
y: box.touches[i + 1].y + Q.height / 2
};
var p = {
ox: v1.x,
oy: v1.y,
cx: v2.x,
cy: v2.y
};
if (star.isIn(p)) {
var a = {
x: v2.x - v1.x,
y: v2.y - v1.y
};
var b = {
x: 1,
y: -2
};
//太阳.
if (star.p.frame === 7) {
var p0 = {
x: star.p.x,
y: star.p.y
};
_self.halo(p0);
star.destroy();
//找到一个即停止.
quit = true;
break;
}
//药水.
else if (star.p.frame === 8) {
var p0 = {
x: star.p.x,
y: star.p.y
};
_self.liquid(p0);
star.destroy();
//找到一个即停止.
quit = true;
break;
}
else {
star.dust();
Q.bless.nearBy = +Q.bless.nearBy;
if(Q.bless.nearBy > 0){
var note = 0;
if(Q.bless.nearBy > 5) note = 5;
else note = Q.bless.nearBy + 1;
_self.kill += note;
killed++;
Q.bless.grade[star.p.frame] += note;
Q.bless.ototal[star.p.frame] = Q.bless.total[star.p.frame];
Q.bless.total[star.p.frame] += note;
}
else{
_self.kill++;
killed++;
Q.bless.grade[star.p.frame]++;
Q.bless.ototal[star.p.frame] = Q.bless.total[star.p.frame];
Q.bless.total[star.p.frame]++;
}
Q.bless.grade[7] = _self.kill;
star.destroy();
//分半
_self.leafUpdate({
x: star.p.x,
y: star.p.y,
frame: star.p.frame,
angle: Plana.anticlockwise(a, b)
});
break;
}
}
}
}
}
//删除.
var remain = [];
for(j = 0;j < count; j++){
//未被划掉,未石化.
if(!_self.stars[j].isDestroyed && _self.stars[j].p.frame !== 9){
remain.push(_self.stars[j]);
}
}
//三连切及以上.
if(killed >= 3){
if(Q.bless.stoneArr.length > 0){
var coll = Q.bless.stoneArr.pop();
coll.dust();
coll.destroy();
}
}
_self.stars = remain;
if(_self.stars.length <= 2){
_self.emitStar(Q.bless.limit);
}
box.touches = [];
}
function moving() {
if(Q.bless.stop) return;
var box = _self.box;
var count = _self.stars.length;
var quit = false;
var len = box.touches.length;
var i = 0;
for (var j = 0; j < count; j++) {
var star = _self.stars[j];
if(quit) break;
quit = false;
if(!star.isDestroyed) {
//最多取样6个点.
if(len >= 6) i = len - 6;
else i = 0;
for(; i < len - 1; i++){
var v1 = {
x: box.touches[i].x + Q.width / 2,
y: box.touches[i].y + Q.height / 2
};
var v2 = {
x: box.touches[i + 1].x + Q.width / 2,
y: box.touches[i + 1].y + Q.height / 2
};
var p = {
ox: v1.x,
oy: v1.y,
cx: v2.x,
cy: v2.y
};
if (star.isIn(p)) {
var a = {
x: v2.x - v1.x,
y: v2.y - v1.y
};
var b = {
x: 1,
y: -2
};
//太阳.
if (star.p.frame === 7) {
var p0 = {
x: star.p.x,
y: star.p.y
};
_self.box.touches = [];
_self.halo(p0);
star.destroy();
//找到一个即停止.
quit = true;
break;
}
//药水.
else if (star.p.frame === 8) {
var p0 = {
x: star.p.x,
y: star.p.y
};
_self.box.touches = [];
_self.liquid(p0);
star.destroy();
//找到一个即停止.
quit = true;
break;
}
else {
star.dust();
Q.bless.nearBy = +Q.bless.nearBy;
if(Q.bless.nearBy > 0){
var note = 0;
if(Q.bless.nearBy > 5) note = 5;
else note = Q.bless.nearBy + 1;
_self.kill += note;
killed++;
Q.bless.grade[star.p.frame] += note;
Q.bless.ototal[star.p.frame] = Q.bless.total[star.p.frame];
Q.bless.total[star.p.frame] += note;
}
else{
_self.kill++;
killed++;
Q.bless.grade[star.p.frame]++;
Q.bless.ototal[star.p.frame] = Q.bless.total[star.p.frame];
Q.bless.total[star.p.frame]++;
}
Q.bless.grade[7] = _self.kill;
Q.bless.sum += _self.kill;
star.destroy();
//分半
_self.leafUpdate({
x: star.p.x,
y: star.p.y,
frame: star.p.frame,
angle: Plana.anticlockwise(a, b)
});
break;
}
}
}
}
}
//删除.
var remain = [];
for(j = 0;j < count; j++){
//未被划掉,未石化.
if(!_self.stars[j].isDestroyed && _self.stars[j].p.frame !== 9){
remain.push(_self.stars[j]);
}
}
//1秒内三连切.
var now = Date.now();
if(now - Q.bless.furyCutterStamp > 1000){
Q.bless.furyCutterStamp = now;
//三连切及以上.
if(killed >= 3){
if(Q.bless.stoneArr.length > 0){
var coll = Q.bless.stoneArr.pop();
coll.dust();
coll.destroy();
}
killed = 0;
}
}
_self.stars = remain;
if(_self.stars.length <= 2){
_self.emitStar(Q.bless.limit);
}
}
function movingStart(){
killed = 0;
}
// _self.box.on('moving', moving);
_self.box.on('movingEnd', moveEnd);
_self.box.on('movingStart', movingStart);
//石头数超限.
_self.on('thisRoundEnd',_self.result);
},
getLeafPool: function(param){
var len = Q.bless.LeafPool.length;
var leaf;
if(len > 0){
leaf = Q.bless.LeafPool.pop();
leaf.reset(param);
}
else{ //当前没有可用对象.
leaf = new Q.Leaf({
x: param.x,
y: param.y,
angle: param.angle,
frame: param.frame,
vx: param.vx,
vy: param.vy,
ax: param.ax,
ay: param.ay
});
}
return leaf;
},
getStarPool: function(param){
var len = Q.bless.StarPool.length;
var star;
if(len > 0){
star = Q.bless.StarPool.pop();
star.reset(param);
}
else{
star = new Q.Star({
x: param.x,
y: param.y,
vx: param.vx,
vy: param.vy,
ax: param.ax,
ay: param.ay,
frame: param.frame,
age: param.age
});
}
return star;
},
getStarLetPool: function(param){
var len = Q.bless.StarLetPool.length;
var starlet;
if(len > 0){
starlet = Q.bless.StarLetPool.pop();
starlet.reset(param);
}
else{
starlet = new Q.Starlet({
x: param.x,
y: param.y,
vx: param.vx,
vy: param.vy,
size: param.size,
scale: param.scale,
frame: param.frame,
gravity: param.gravity
});
}
return starlet;
},
leafUpdate: function (pos) {
var _self = this;
_self.score.count(_self.kill);
_self.dwarf.hit();
var lf = pos.frame * 2;
var rf = lf + 1;
_self.stage.insert(_self.getLeafPool({
x: pos.x,
y: pos.y,
angle: 360 - pos.angle,
frame: rf,
vx: 100,
vy: -100,
ax: -10,
ay: 200
}));
_self.stage.insert(_self.getLeafPool({
x: pos.x,
y: pos.y,
frame: lf,
angle: 360 - pos.angle,
vx: -100,
vy: -100,
ax: 10,
ay: 200
}));
},
//药水.
liquid: function(p0){
var _self = this;
Q.bless.stop = true;
var f = 0;
var r = Math.random();
if(r < Q.bless.likely.multiply){
f = Q.rand(0,3);
}
else{
f = 4;
}
var a = _self.stage.insert(new Q.Award({
x: p0.x,
y: p0.y,
frame: f
}));
//累计得分.
for(var i in Q.bless.total){
Q.bless.total[i] = Math.floor(Q.bless.total[i] * Q.bless.fMap[f]);
}
a.on('delete',function(){
a.destroy();
_self.result(f);
});
},
//阳光.
halo: function (p0) {
var _self = this;
Q.bless.stop = true;
for(var i = 0, len = _self.stars.length; i < len;i++){
_self.stars[i].destroy();
}
var part = 4;
var px = Q.width/part;
var py = Q.height/part;
var A, B, C,D;
A = _self.stage.insert(new Q.Halo({
a: p0,
b: {
x: px,
y: 0
},
c: {
x: 2*px,
y: 0
},
direct:'R'
}));
setTimeout(function(){
B = new Q.Halo({
a: p0,
b: {
x: Q.width,
y: py
},
c: {
x: Q.width,
y: py * 2
},
direct:'D'
});
_self.stage.insert(B);
},300);
setTimeout(function(){
C = new Q.Halo({
a: p0,
b: {
x: 3*px,
y: Q.height
},
c: {
x: 2*px,
y: Q.height
},
direct:'L'
});
_self.stage.insert(C);
},600);
setTimeout(function(){
D = new Q.Halo({
a: p0,
b: {
x: 0,
y: py * 3
},
c: {
x: 0,
y: py * 2
},
direct:'U'
});
_self.stage.insert(D);
A.padding();
B.padding();
C.padding();
D.padding();
setTimeout(function(){
A.destroy();
B.destroy();
C.destroy();
D.destroy();
_self.result();
},1200);
},900);
},
updateScore: function(){
var _self = this;
//更新分数.
var $rn = $('.r_n');
for(var i in Q.bless.grade){
//标题.
if(+i === 7){
$('#r_t_num').text(_self.kill);
}
else{
$rn.eq(+i).find('span').eq(1).text(Q.bless.grade[i] + '+');
(function(i){
setTimeout(function(){
$rn.eq(+i).find('span').eq(2).addClass('shakeAnim');
},1000);
})(i);
}
}
},
result: function(frame){
var _self = this;
Q.bless.pause();
Q.bless.stop = true;
$(Q.el.parentNode).addClass('hide');
$('#r_wrapper').removeClass();
var posClass = {
0: 'double',
1: 'fourfold',
2: 'quintuple',
3: 'triple',
4: 'half'
};
//药水.
var param;
if(!Q._isUndefined(frame)){
$('#r_dec').removeClass().addClass(posClass[frame]);
var calType = 3;
var calVal = Q.bless.fMap[frame];
if(frame === 4){
calType = 4;
calVal = 2;
}
param = {
'calcType': calType,
'calcValue': calVal,
'starOneCount': Q.bless.grade[0],
'starTwoCount': Q.bless.grade[1],
'starThreeCount': Q.bless.grade[2],
'starFourCount': Q.bless.grade[3],
'starFiveCount': Q.bless.grade[4],
'starSixCount': Q.bless.grade[5],
'starSevenCount': Q.bless.grade[6]
};
//request.
Q.request.commitStarScore(param,function(isOK){
//没有更新成功
if(!isOK){
for(var i = 0; i <= 6; i++){
Q.bless.grade[i] = 0;
}
_self.kill = 0;
for(i in Q.bless.ototal){
Q.bless.total[i] = Q.bless.ototal[i];
}
}
_self.updateScore();
});
}
else{ //太阳.
$('#r_dec').addClass('hide');
param = {
'calcType': 0,
'calcValue': 0,
'starOneCount': Q.bless.grade[0],
'starTwoCount': Q.bless.grade[1],
'starThreeCount': Q.bless.grade[2],
'starFourCount': Q.bless.grade[3],
'starFiveCount': Q.bless.grade[4],
'starSixCount': Q.bless.grade[5],
'starSevenCount': Q.bless.grade[6]
};
var isZero = Q.bless.grade[0] || Q.bless.grade[1] || Q.bless.grade[2] || Q.bless.grade[3] || Q.bless.grade[4] || Q.bless.grade[5] || Q.bless.grade[6];
if(isZero !== 0){
Q.request.commitStarScore(param,function(isOK){
//没有更新成功
if(!isOK){
for(var i = 0; i <= 6; i++){
Q.bless.grade[i] = 0;
}
_self.kill = 0;
for(i in Q.bless.ototal){
Q.bless.total[i] = Q.bless.ototal[i];
}
}
_self.updateScore();
});
}
else{
_self.updateScore();
}
}
_self.updateScore();
},
emitStar: function (n) {
var _self = this;
var stage = _self.stage;
var sl = _self.stars.length;
var num = Q.rand(1,n);
for (var i = 0; i < num; i++) {
if (sl <= Q.bless.limit) {
var x = Q.rand(Q.width/2, Q.width);
var y = 20;
var vx = -4;
var vy = 4;
var ax = Q.rand(Q.bless.likely.lowX, Q.bless.likely.highX);
var ay = Q.rand(Q.bless.likely.lowY, Q.bless.likely.highY);
var age = 7;
var rand = Math.random();
var f;
//太阳.
if(rand < Q.bless.likely.sun){
f = 7;
}
else if(rand < (Q.bless.likely.liquid + Q.bless.likely.sun) && rand >= Q.bless.likely.sun && Q.bless.sum < 10000000000){
f = 8;
}
else{
f = Q.randArr(Q.bless.candidate);
}
var s = _self.getStarPool({
x: x,
y: y,
vx: vx,
vy: vy,
ax: ax,
ay: ay,
frame: f,
age: age
});
_self.stars.push(s);
stage.insert(s);
}
else {
return;
}
}
},
roundClear: function(){
var _self = this;
for(var i = 0, len = _self.stars.length; i < len;i++){
_self.stars[i].destroy();
}
_self.stars = [];
//石化星星.
for(i = 0,len = Q.bless.stoneArr.length; i < len;i++){
Q.bless.stoneArr[i].destroy();
}
Q.bless.stoneArr = [];
Q.bless.grade[0] = 0;
Q.bless.grade[1] = 0;
Q.bless.grade[2] = 0;
Q.bless.grade[3] = 0;
Q.bless.grade[4] = 0;
Q.bless.grade[5] = 0;
Q.bless.grade[6] = 0;
Q.bless.grade[7] = 0;
Q.bless.liquidDry = true;
this.score.count(0);
this.kill = 0;
},
roundStart: function () {
Q.bless.stop = false;
this.emitStar(Q.bless.limit);
// this.showNearby();
},
//static.
showNearby: function(){
if(Q.bless.nearBy > 0){
Q.bless.pause();
$(Q.el.parentNode).addClass('hide');
var note = (Q.bless.nearBy > 5 ? 5: Q.bless.nearBy);
$('.nearby_b').text('附近有' + Q.bless.nearBy + '个小伙伴一起玩游戏,1分钟内流星分值翻'+ note +'倍哦~');
$('#r_nearby').removeClass('hide');
setTimeout(function(){
Q.bless.unpause();
$(Q.el.parentNode).removeClass('hide');
$('#r_nearby').addClass('hide');
//一分钟后自动设置为0.
setTimeout(function(){
Q.bless.nearBy = 0;
},60000);
},3000);
}
}
});
Q.scene("mainRoot", function (stage) {
Q.bless.mainRootStage = stage;
Q.bless.controller = new Q.Controller(stage);
Q.bless.controller.roundStart();
$('.r_n span').on('webkitAnimationEnd',function(){
var $this = $(this);
var i = $this.attr('mock-type');
$this.text(Q.bless.total[i]);
});
$('#r_quit')[0].onclick = function(){
try{
$('#r_wrapper').addClass('hide');
$(Q.el.parentNode).addClass('hide');
Q.clear();
Q.bless.pause();
Q.bless.controller.roundClear();
Q.bless.quitCb();
Q.bless = {};
}
catch (e){
alert(e);
}
};
$('#r_replay').on('click',function(){
$('#r_wrapper').addClass('hide');
$(Q.el.parentNode).removeClass('hide');
Q.bless.controller.roundClear();
try{
Q.bless.unpause();
}
catch (e){
alert(e.toString());
}
Q.bless.controller.roundStart();
(window.goldlog && window.goldlog.send("http://gm.mmstat.com/wapmm.6.20", {
logtype: 2
}));
});
$('#r_share').on('click',function(){
Q.request.showShareMenu();
(window.goldlog && window.goldlog.send("http://gm.mmstat.com/wapmm.6.15", {
logtype: 2
}));
});
//继续游戏.
$('.pause_yes').on('click',function(){
Q.bless.unpause();
$('#r_pause').addClass('hide');
});
//退出.
$('.pause_no').on('click',function(){
$('#r_pause').addClass('hide');
Q.bless.controller.result();
});
});
Q.scene('intro', function (stage) {
var s = stage.insert(new Q.Star({
x: Q.width / 2,
y: Q.height / 2,
scale: Q.bless.starScale,
sprite: 'star.png',
sheet: 'star',
frame: 0,
angle: 20,
still: true,
type: Q.SPRITE_DEFAULT
}));
var h = new Q.Hand();
stage.insert(h);
h.move(function () {
stage.insert(new Q.Leaf({
x: Q.width / 2 - 10,
y: Q.height / 2 - 20,
angle: 20,
frame: 0,
scale: Q.bless.leafScale,
still: true
}));
stage.insert(new Q.Leaf({
x: Q.width / 2 + 10,
y: Q.height / 2 + 10,
frame: 1,
angle: 20,
scale: Q.bless.leafScale,
still: true
}));
s.destroy();
setTimeout(function () {
Q.stageScene("mainRoot");
Q.Controller.prototype.showNearby();
}, 1000);
});
});
Q.scene("loading", function (stage) {
stage.insert(new Q.UI.Text({
color: 'white',
label: "Loading...",
x: Q.width / 2,
y: Q.height / 2
}));
});
function loadAssets() {
Q.load([
'bg.png',
'pause.png',
'star-leaf.png',
'num.png',
'dwarf.png',
'award.png',
'hand.png',
'star.png'
], function () {
Q.sheet("star-leaf", "star-leaf.png",
{
"sx": 0,
"sy": 0,
"cols": 18,
"rows": 1,
"tilew": 85,
"tileh": 85
});
Q.sheet("star", "star.png",
{
"sx": 0,
"sy": 0,
"cols": 10,
"rows": 1,
"tilew": 85,
"tileh": 85
});
Q.sheet("num", "num.png",
{
"sx": 0,
"sy": 0,
"cols": 1,
"rows": 10,
"tilew": 56,
"tileh": 84,
"w": 56,
"h": 840
});
Q.sheet("award", "award.png",
{
"sx": 0,
"sy": 0,
"cols": 5,
"rows": 1,
"tilew": 244,
"tileh": 189
});
Q.sheet("dwarf", "dwarf.png",
{
"sx": 0,
"sy": 0,
"cols": 4,
"rows": 1,
"tilew": 93,
"tileh": 115
});
if(!Cookies.get('3_8_love')){
Cookies.set('3_8_love','loveU');
Q.stageScene("intro");
}
else{
setTimeout(function () {
Q.stageScene("mainRoot");
Q.Controller.prototype.showNearby();
}, 1000);
}
});
};
function paramInit(){
Q.bless = {};
Q.bless.hold = false;
Q.bless.mainRootStage = {};
Q.bless.candidate = [];
Q.bless.sum = 0; //总得分.
Q.bless.total = {}; //累计得分.
Q.bless.ototal = {}; //
Q.bless.grade = { //本轮得分.
0: 0,
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
6: 0,
7: 0 //total num
};
Q.bless.limit = 2;
Q.bless.nearBy = 0;
Q.bless.starScale = 1;
Q.bless.leafScale = 1;
Q.bless.pauseScale = 1;
Q.bless.pauseDist = 50;
Q.bless.dwarfScale = 1;
Q.bless.scoreSize = 30;
//sprite 对应的奖励.
Q.bless.fMap = {
0: 2,
1: 4,
2: 5,
3: 3,
4: 0.5
};
//石化数据.
Q.bless.stoneYLimit = 15;
Q.bless.stoneArr = [];
Q.bless.liquidDry = true;
Q.bless.hiDPI = false;
Q.bless.quitCb;
Q.bless.controller = {};
Q.bless.likely = {
sun: 0.05,
liquid: 0.1,
multiply: 0.3,
lowX: -100,
highX: -1,
lowY: 1,
highY: 400
};
//切掉的星星碎片的对象池子.
Q.bless.LeafPool = [];
Q.bless.StarPool = [];
Q.bless.StarLetPool = [];
Q.bless.furyCutterStamp = Date.now();
Q.bless.pause = function(){
Q.pauseGame();
};
Q.bless.unpause = function(){
Q.unpauseGame();
};
Q.bless.isPad = (/iPad/i).test(navigator.userAgent);
};
Q.Boot = function (userInfo, callback) {
paramInit();
Q.bless.total = (userInfo && userInfo.star) || {};
Q.bless.nick = (userInfo && userInfo.nick) || '';
Q.bless.quitCb = callback;
var $rn = $('.r_n');
for(var k in Q.bless.total){
if(Q.bless.total.hasOwnProperty(k)){
Q.bless.total[k] = +Q.bless.total[k];
Q.bless.ototal[k] = Q.bless.total[k];
Q.bless.sum += Q.bless.total[k];
Q.bless.candidate.push(k);
//更新分数.
for(var i in Q.bless.grade){
//标题.
$rn.eq(+i).find('span').eq(2).text(Q.bless.total[i]);
}
}
}
Q.request.getNearBy();
Init();
Q.stageScene("loading");
loadAssets();
};
}); | picacure/_sandBox | bless/index.js | JavaScript | mit | 207,373 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.