answer
stringlengths 15
1.25M
|
|---|
/** @file esetinternal.h
* @brief Xapian::ESet::Internal class
*/
#ifndef <API key>
#define <API key>
#include "xapian/base.h"
#include "xapian/enquire.h"
#include "xapian/types.h"
#include <algorithm>
#include <string>
#include <vector>
namespace Xapian {
class Database;
class ExpandDecider;
namespace Internal {
class ExpandWeight;
Class combining a term and its expand weight.
class ExpandTerm {
friend class Xapian::ESetIterator;
friend class Xapian::ESet::Internal;
The expand weight calculated for this term.
Xapian::weight wt;
The term.
std::string term;
public:
Constructor.
ExpandTerm(Xapian::weight wt_, const std::string & term_)
: wt(wt_), term(term_) { }
Implement custom swap for ESet sorting efficiency.
void swap(ExpandTerm & o) {
std::swap(wt, o.wt);
std::swap(term, o.term);
}
Ordering relation for ESet contents.
bool operator<(const ExpandTerm & o) const {
if (wt > o.wt) return true;
if (wt < o.wt) return false;
return term > o.term;
}
Return a string describing this object.
std::string get_description() const;
};
}
Class which actually implements Xapian::ESet.
class ESet::Internal : public Xapian::Internal::RefCntBase {
friend class ESet;
friend class ESetIterator;
/** This is a lower bound on the ESet size if an infinite number of results
* were requested.
*
* It will of course always be true that: ebound >= items.size()
*/
Xapian::termcount ebound;
The ExpandTerm objects which represent the items in the ESet.
std::vector<Xapian::Internal::ExpandTerm> items;
Don't allow assignment.
void operator=(const Internal &);
Don't allow copying.
Internal(const Internal &);
public:
Construct an empty ESet::Internal.
Internal() : ebound(0) { }
Run the "expand" operation which fills the ESet.
void expand(Xapian::termcount max_esize,
const Xapian::Database & db,
const Xapian::RSet & rset,
const Xapian::ExpandDecider * edecider,
const Xapian::Internal::ExpandWeight & eweight);
Return a string describing this object.
std::string get_description() const;
};
}
#endif // <API key>
|
# encoding: utf8
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = []
operations = [
migrations.CreateModel(
fields = [(u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=True, primary_key=True),), ('name', models.CharField(max_length=255),), ('email', models.EmailField(max_length=75),), ('message', models.TextField(),), ('date', models.DateField(auto_now=True),)],
bases = (models.Model,),
options = {},
name = 'Contact',
),
migrations.CreateModel(
fields = [(u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=True, primary_key=True),), ('date', models.DateTimeField(),), ('title', models.CharField(max_length=255),), ('code', models.CharField(max_length=255),), ('summary', models.TextField(),)],
bases = (models.Model,),
options = {},
name = 'Commits',
),
]
|
#include "constants.h"
#include "velocity_tria3.h"
int velocity_tria3(double *Xin, double **mNodes, unsigned int **mElems,
double *vProbParam, double *vB, double *U)
{
const unsigned int ELEMS = nElems, NODES_IN_ELEM = 3;
unsigned int currentNode, i, j, SinNode, test, xNode, yNode, zNode;
double dx, dy, dz, factor;
double X[3][3];
double Int[3][3][3];
/* Initialize */
U[0] = U[1] = U[2] = 0.0;
factor = 1.0/(8.0*pi*vProbParam[0]);
for(i = 0; i < ELEMS; i++){
for(j = 0; j < NODES_IN_ELEM; j++){
currentNode = mElems[i][j] - 1;
X[j][0] = mNodes[currentNode][0];
X[j][1] = mNodes[currentNode][1];
X[j][2] = mNodes[currentNode][2];
}
/* Check for singular case */
test = 0;
for(j = 0; j < NODES_IN_ELEM; j++){
dx = X[j][0] - Xin[0];
dy = X[j][1] - Xin[1];
dz = X[j][2] - Xin[2];
if(dx == 0.0 && dy == 0.0 && dz == 0.0){
test = 1;
SinNode = j+1;
break;
}
}
if(test == 0) intGStk_tria3(X,Xin,Int);
else <API key>(SinNode,X,Xin,Int);
/* Add cotribution from each node j in element i */
for(j = 0; j < NODES_IN_ELEM; j++){
xNode = mElems[i][j] - 1;
yNode = xNode + nNodes;
zNode = yNode + nNodes;
U[0] -= Int[0][0][j]*vB[xNode] + Int[0][1][j]*vB[yNode] +
Int[0][2][j]*vB[zNode];
U[1] -= Int[1][0][j]*vB[xNode] + Int[1][1][j]*vB[yNode] +
Int[1][2][j]*vB[zNode];
U[2] -= Int[2][0][j]*vB[xNode] + Int[2][1][j]*vB[yNode] +
Int[2][2][j]*vB[zNode];
}
}
U[0] = U[0]*factor;
U[1] = U[1]*factor;
U[2] = U[2]*factor;
return 0;
}
|
<?php
namespace eZ\Publish\Core\Search\Legacy\Content\Location\Gateway\CriterionHandler;
use eZ\Publish\Core\Search\Legacy\Content\Common\Gateway\CriterionHandler;
use eZ\Publish\Core\Search\Legacy\Content\Common\Gateway\CriteriaConverter;
use eZ\Publish\API\Repository\Values\Content\Query\Criterion;
use eZ\Publish\Core\Persistence\Database\SelectQuery;
/**
* Visits the Ancestor criterion.
*/
class Ancestor extends CriterionHandler
{
/**
* Check if this criterion handler accepts to handle the given criterion.
*
* @param \eZ\Publish\API\Repository\Values\Content\Query\Criterion $criterion
*
* @return bool
*/
public function accept(Criterion $criterion)
{
return $criterion instanceof Criterion\Ancestor;
}
/**
* Generate query expression for a Criterion this handler accepts.
*
* accept() must be called before calling this method.
*
* @param \eZ\Publish\Core\Search\Legacy\Content\Common\Gateway\CriteriaConverter $converter
* @param \eZ\Publish\Core\Persistence\Database\SelectQuery $query
* @param \eZ\Publish\API\Repository\Values\Content\Query\Criterion $criterion
* @param array $languageSettings
*
* @return \eZ\Publish\Core\Persistence\Database\Expression
*/
public function handle(
CriteriaConverter $converter,
SelectQuery $query,
Criterion $criterion,
array $languageSettings
) {
$idSet = [];
foreach ($criterion->value as $value) {
foreach (explode('/', trim($value, '/')) as $id) {
$idSet[$id] = true;
}
}
return $query->expr->in(
$this->dbHandler->quoteColumn('node_id', '<API key>'),
array_keys($idSet)
);
}
}
|
using System;
using System.Collections.Generic;
using System.Management;
using System.Security.Principal;
using Microsoft.Win32;
using PowerPointLabs.ActionFramework.Common.Log;
namespace PowerPointLabs.Utils
{
<summary>
A class that allows watching of Registry Key values.
</summary>
class RegistryWatcher<T> where T : IEquatable<T>
{
private readonly string path;
private readonly string key;
private readonly List<T> defaultKey;
private <API key> watcher;
// returns true if the key started as defaultKey and is not modified, else false
public bool IsDefaultKey { get; private set; }
public event EventHandler<T> ValueChanged;
public RegistryWatcher(string path, string key, List<T> defaultKey)
{
this.path = path;
this.key = key;
this.defaultKey = defaultKey;
this.IsDefaultKey = true;
RegisterKeyChanged();
try
{
<API key>();
}
catch (Exception)
{
// There is a possibility no registry entries have been created yet
}
}
<summary>
Fires the event manually
</summary>
public void Fire()
{
Notify();
}
public void Start()
{
watcher.Start();
}
public void Stop()
{
watcher.Stop();
}
public void SetValue(object o)
{
WindowsIdentity currentUser = WindowsIdentity.GetCurrent();
Registry.SetValue(String.Format("{0}\\{1}", currentUser.User.Value, path), key, o);
}
private void RegisterKeyChanged()
{
WindowsIdentity currentUser = WindowsIdentity.GetCurrent();
WqlEventQuery query = new WqlEventQuery(
"SELECT * FROM <API key> WHERE " +
"Hive = 'HKEY_USERS'" +
String.Format(@"AND KeyPath = '{0}\\{1}' AND ValueName='{2}'", currentUser.User.Value, path, key));
watcher = new <API key>(query);
watcher.EventArrived += (object sender, <API key> e) => { Notify(); };
}
private T <API key>()
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(path))
{
object objectValue;
if (key == null || (objectValue = key.GetValue(this.key)) == null)
{
throw new Exceptions.<API key>("Key is null");
}
T result = (T)objectValue;
IsDefaultKey &= defaultKey == null || defaultKey.Contains(result);
return result;
}
}
private void Notify()
{
try
{
T key = <API key>();
if (IsDefaultKey)
{
return;
}
ValueChanged?.Invoke(this, key);
}
catch (Exception e)
{
Logger.LogException(e, nameof(Notify));
}
}
}
}
|
<!DOCTYPE html>
<html>
<body>
<p>The price is OK.</p>
</body>
</html>
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>scipy.special.eval_hermite — SciPy v0.16.1 Reference Guide</title>
<link rel="stylesheet" type="text/css" href="../static_/css/spc-bootstrap.css">
<link rel="stylesheet" type="text/css" href="../static_/css/spc-extend.css">
<link rel="stylesheet" href="../static_/scipy.css" type="text/css" >
<link rel="stylesheet" href="../static_/pygments.css" type="text/css" >
<script type="text/javascript">
var <API key> = {
URL_ROOT: '../',
VERSION: '0.16.1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: false
};
</script>
<script type="text/javascript" src="../static_/jquery.js"></script>
<script type="text/javascript" src="../static_/underscore.js"></script>
<script type="text/javascript" src="../static_/doctools.js"></script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=<API key>"></script>
<script type="text/javascript" src="../static_/js/copybutton.js"></script>
<link rel="top" title="SciPy v0.16.1 Reference Guide" href="../index.html" >
<link rel="up" title="Special functions (scipy.special)" href="../special.html" >
<link rel="next" title="scipy.special.eval_hermitenorm" href="scipy.special.eval_hermitenorm.html" >
<link rel="prev" title="scipy.special.eval_genlaguerre" href="scipy.special.eval_genlaguerre.html" >
</head>
<body>
<div class="container">
<div class="header">
</div>
</div>
<div class="container">
<div class="main">
<div class="row-fluid">
<div class="span12">
<div class="spc-navbar">
<ul class="nav nav-pills pull-left">
<li class="active"><a href="../index.html">SciPy v0.16.1 Reference Guide</a></li>
<li class="active"><a href="../special.html" accesskey="U">Special functions (<tt class="docutils literal"><span class="pre">scipy.special</span></tt>)</a></li>
</ul>
<ul class="nav nav-pills pull-right">
<li class="active">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a>
</li>
<li class="active">
<a href="../py-modindex.html" title="Python Module Index"
>modules</a>
</li>
<li class="active">
<a href="../<API key>.html" title="Python Module Index"
>modules</a>
</li>
<li class="active">
<a href="scipy.special.eval_hermitenorm.html" title="scipy.special.eval_hermitenorm"
accesskey="N">next</a>
</li>
<li class="active">
<a href="scipy.special.eval_genlaguerre.html" title="scipy.special.eval_genlaguerre"
accesskey="P">previous</a>
</li>
</ul>
</div>
</div>
</div>
<div class="row-fluid">
<div class="spc-rightsidebar span3">
<div class="<API key>">
<p class="logo"><a href="../index.html">
<img class="logo" src="../static_/scipyshiny_small.png" alt="Logo">
</a></p>
<h4>Previous topic</h4>
<p class="topless"><a href="scipy.special.eval_genlaguerre.html"
title="previous chapter">scipy.special.eval_genlaguerre</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="scipy.special.eval_hermitenorm.html"
title="next chapter">scipy.special.eval_hermitenorm</a></p>
</div>
</div>
<div class="span9">
<div class="bodywrapper">
<div class="body" id="spc-section-body">
<div class="section" id="<API key>">
<h1>scipy.special.eval_hermite<a class="headerlink" href="
<dl class="data">
<dt id="scipy.special.eval_hermite">
<tt class="descclassname">scipy.special.</tt><tt class="descname">eval_hermite</tt><big>(</big><em>n</em>, <em>x</em>, <em>out=None</em><big>)</big><em class="property"> = <ufunc 'eval_hermite'></em><a class="headerlink" href="
<dd><p>Evaluate Hermite polynomial at a point.</p>
</dd></dl>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container <API key>">
<div class="spc-navbar">
</div>
</div>
<div class="container">
<div class="footer">
<div class="row-fluid">
<ul class="inline pull-left">
<li>
© Copyright 2008-2014, The Scipy community.
</li>
<li>
Last updated on Oct 24, 2015.
</li>
<li>
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2.1.
</li>
</ul>
</div>
</div>
</div>
</body>
</html>
|
<?php
class Panel
{
public function __construct() {
}
}
|
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Amelia Valcarcel</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/freelancer.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="font-awesome-4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/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/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]
</head>
<body id="page-top" class="index">
<!-- Header -->
<header>
<div class="container">
<div class="row">
<div class="col-lg-12">
<img class="img-responsive" src="img/profile.png" alt="">
<div class="intro-text">
<span class="name">Amelia Valcarcel</span>
<hr class="star-light">
<span class="skills">En estos momentos estamos renovando la web, disculpen las molestias</span>
</div>
</div>
</div>
</div>
</header>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<!-- Plugin JavaScript -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<script src="js/classie.js"></script>
<script src="js/cbpAnimatedHeader.js"></script>
<!-- Contact Form JavaScript -->
<script src="js/<API key>.js"></script>
<script src="js/contact_me.js"></script>
<!-- Custom Theme JavaScript -->
<script src="js/freelancer.js"></script>
</body>
</html>
|
<?php
$files = elgg_extract("files", $vars, array());
$folder = elgg_extract("folder", $vars);
$folder_content = elgg_view("file_tools/breadcrumb", array("entity" => $folder));
if(!($sub_folders = <API key>($folder))){
$sub_folders = array();
}
$entities = array_merge($sub_folders, $files) ;
if(!empty($entities)) {
$params = array(
"full_view" => false,
"pagination" => false
);
elgg_push_context("file_tools_selector");
$files_content = <API key>($entities, $params);
elgg_pop_context();
}
if(empty($files_content)){
$files_content = elgg_echo("file_tools:list:files:none");
} else {
$files_content .= "<div class='clearfix'>";
if(<API key>()->canEdit()) {
$files_content .= '<a id="<API key>" href="javascript:void(0);">' . elgg_echo("file_tools:list:delete_selected") . '</a> | ';
}
$files_content .= "<a id='<API key>' href='javascript:void(0);'>" . elgg_echo("file_tools:list:download_selected") . "</a>";
$files_content .= "<a id='<API key>' class='float-alt' href='javascript:void(0);'>";
$files_content .= "<span>" . elgg_echo("file_tools:list:select_all") . "</span>";
$files_content .= "<span class='hidden'>" . elgg_echo("file_tools:list:deselect_all") . "</span>";
$files_content .= "</a>";
$files_content .= "</div>";
}
$files_content .= elgg_view("graphics/ajax_loader");
?>
<div id="<API key>">
<div id="<API key>"></div>
<?php
echo $folder_content;
echo $files_content;
?>
</div>
<?php
$page_owner = <API key>();
if($page_owner->canEdit() || (elgg_instanceof($page_owner, "group") && $page_owner->isMember())) { ?>
<script type="text/javascript">
$(function(){
$("#<API key> .file-tools-file").draggable({
revert: "invalid",
opacity: 0.8,
appendTo: "body",
helper: "clone",
start: function(event, ui) {
$(this).css("visibility", "hidden");
$(ui.helper).width($(this).width());
},
stop: function(event, ui) {
$(this).css("visibility", "visible");
}
});
$("#<API key> .file-tools-folder").droppable({
accept: "#<API key> .file-tools-file",
drop: function(event, ui){
droppable = $(this);
draggable = ui.draggable;
drop_id = droppable.parent().attr("id").split("-").pop();
drag_id = draggable.parent().attr("id").split("-").pop();
elgg.file_tools.move_file(drag_id, drop_id, draggable);
}
});
});
</script>
<?php
}
|
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* Customers Controller
*
* @property \App\Model\Table\CustomersTable $Customers
*/
class CustomersController extends AppController
{
/**
* Index method
*
* @return void
*/
public function index()
{
$this->set('customers', $this->paginate($this->Customers));
$this->set('_serialize', ['customers']);
}
/**
* View method
*
* @param string|null $id Customer id.
* @return void
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function view($id = null)
{
$customer = $this->Customers->get($id, [
'contain' => ['Orders']
]);
$this->set('customer', $customer);
$this->set('_serialize', ['customer']);
}
/**
* Add method
*
* @return void Redirects on successful add, renders view otherwise.
*/
public function add()
{
$customer = $this->Customers->newEntity();
if ($this->request->is('post')) {
$customer = $this->Customers->patchEntity($customer, $this->request->data);
if ($this->Customers->save($customer)) {
$this->Flash->success('The customer has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The customer could not be saved. Please, try again.');
}
}
$this->set(compact('customer'));
$this->set('_serialize', ['customer']);
}
/**
* Edit method
*
* @param string|null $id Customer id.
* @return void Redirects on successful edit, renders view otherwise.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function edit($id = null)
{
$customer = $this->Customers->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$customer = $this->Customers->patchEntity($customer, $this->request->data);
if ($this->Customers->save($customer)) {
$this->Flash->success('The customer has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The customer could not be saved. Please, try again.');
}
}
$this->set(compact('customer'));
$this->set('_serialize', ['customer']);
}
/**
* Delete method
*
* @param string|null $id Customer id.
* @return void Redirects to index.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$customer = $this->Customers->get($id);
if ($this->Customers->delete($customer)) {
$this->Flash->success('The customer has been deleted.');
} else {
$this->Flash->error('The customer could not be deleted. Please, try again.');
}
return $this->redirect(['action' => 'index']);
}
}
|
# force floating point division. Can still use integer with //
from __future__ import division
# This file is used for importing the common utilities classes.
import numpy as np
import matplotlib.pyplot as plt
import sys
sys.path.append("../../../../../")
from EnergyLandscapes.Lifetime_Dudko2008.Python.TestExamples.Util import \
Example_Data
def PlotFit(data,BaseName):
fig = Example_Data.PlotHistograms(data)
fig.savefig(BaseName + "_Histogram.png")
fig = Example_Data.PlotLifetimesAndFit(data)
fig.savefig(BaseName + "_Lifetimes.png")
def run():
# figure 1 from dudko 2008
data = Example_Data.<API key>()
PlotFit(data,"../Out/Dudko2008_Fig1")
# figure 2 frm dudko 2008
data = Example_Data.<API key>()
PlotFit(data,"../Out/Dudko2008_Fig2")
if __name__ == "__main__":
run()
|
// Wildebeest Migration Framework
// This file is part of Wildebeest
// Wildebeest is free software: you can redistribute it and/or modify it under
// Software Foundation.
// Wildebeest is distributed in the hope that it will be useful, but WITHOUT ANY
package co.mv.wb.plugin.generaldatabase.dom;
import co.mv.wb.Asserts;
import co.mv.wb.<API key>;
import co.mv.wb.LoaderFault;
import co.mv.wb.ModelExtensions;
import co.mv.wb.<API key>;
import co.mv.wb.Resource;
import co.mv.wb.fixture.Fixtures;
import co.mv.wb.impl.<API key>;
import co.mv.wb.plugin.base.dom.DomPlugins;
import co.mv.wb.plugin.base.dom.DomResourceLoader;
import co.mv.wb.plugin.generaldatabase.<API key>;
import co.mv.wb.plugin.generaldatabase.<API key>;
import co.mv.wb.plugin.generaldatabase.<API key>;
import co.mv.wb.plugin.generaldatabase.<API key>;
import co.mv.wb.plugin.postgresql.PostgreSqlConstants;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.util.Optional;
import java.util.UUID;
/**
* Unit tests for the DOM persistence services for ANSI SQL plugins.
*
* @since 4.0
*/
public class <API key>
{
@Test
public void <API key>() throws
LoaderFault,
<API key>,
<API key>
{
// Setup
UUID migrationId = UUID.randomUUID();
UUID toStateId = UUID.randomUUID();
String xml = Fixtures
.resourceXmlBuilder()
.resource(PostgreSqlConstants.PostgreSqlDatabase.getUri(), UUID.randomUUID(), "Foo")
.migration("<API key>", migrationId, null, toStateId.toString())
.render();
DomResourceLoader loader = DomPlugins.resourceLoader(
<API key>
.create()
.<API key>()
.build(),
xml);
// Execute
Resource resource = loader.load(new File("."));
// Verify
Assert.assertNotNull("resource", resource);
Assert.assertEquals("resource.migrations.size", 1, resource.getMigrations().size());
<API key> mT = ModelExtensions.as(
resource.getMigrations().get(0),
<API key>.class);
Assert.assertNotNull(
"resourceWithPlugin.resource.migrations[0] expected to be of type <API key>",
mT);
Assert.assertEquals(
"resourceWithPlugin.resource.migrations[0].id",
migrationId,
mT.getMigrationId());
Assert.assertEquals(
"resourceWithPlugin.resource.migrations[0].fromStateId",
Optional.empty(),
mT.getFromState());
Assert.assertEquals(
"resourceWithPlugin.resource.migrations[0].toStateId",
Optional.of(toStateId.toString()),
mT.getToState());
}
@Test
public void <API key>() throws
LoaderFault,
<API key>,
<API key>
{
// Setup
UUID migrationId = UUID.randomUUID();
String toState = UUID.randomUUID().toString();
String xml = Fixtures
.resourceXmlBuilder()
.resource(PostgreSqlConstants.PostgreSqlDatabase.getUri(), UUID.randomUUID(), "Foo")
.migration("AnsiSqlDropDatabase", migrationId, null, toState.toString())
.render();
DomResourceLoader loader = DomPlugins.resourceLoader(
<API key>
.create()
.<API key>()
.build(),
xml);
// Execute
Resource resource = loader.load(new File("."));
// Verify
Assert.assertNotNull("resource", resource);
Assert.assertEquals("resource.migrations.size", 1, resource.getMigrations().size());
<API key> mT = ModelExtensions.as(
resource.getMigrations().get(0),
<API key>.class);
Assert.assertNotNull("resource.migrations[0] expected to be of type <API key>", mT);
Assert.assertEquals(
"resource.migrations[0].id",
migrationId,
mT.getMigrationId());
Assert.assertEquals(
"resource.migrations[0].fromState",
Optional.empty(),
mT.getFromState());
Assert.assertEquals(
"resource.migrations[0].toState",
Optional.of(toState),
mT.getToState());
}
@Test
public void <API key>() throws
LoaderFault,
<API key>,
<API key>
{
// Setup
UUID assertionId = UUID.randomUUID();
String xml = Fixtures
.resourceXmlBuilder()
.resource(PostgreSqlConstants.PostgreSqlDatabase.getUri(), UUID.randomUUID(), "Foo")
.state(UUID.randomUUID(), null)
.assertion("AnsiSqlTableExists", assertionId)
.appendInnerXml("<schemaName>sch</schemaName>")
.appendInnerXml("<tableName>tbl</tableName>")
.build();
DomResourceLoader loader = DomPlugins.resourceLoader(
<API key>
.create()
.<API key>()
.build(),
xml);
// Execute
Resource resource = loader.load(new File("."));
// Verify
Assert.assertNotNull("resource", resource);
Assert.assertEquals("resource.states.size", 1, resource.getStates().size());
Assert.assertEquals(
"resource.states[0].assertions.size",
1,
resource.getStates().get(0).getAssertions().size());
<API key> assertionT = ModelExtensions.as(
resource.getStates().get(0).getAssertions().get(0),
<API key>.class);
Assert.assertNotNull("Expected to be an <API key>", assertionT);
Asserts.<API key>(
assertionId,
"sch",
"tbl",
assertionT,
"resource.states[0].assertions[0]");
}
@Test
public void <API key>() throws
LoaderFault,
<API key>,
<API key>
{
// Setup
UUID assertionId = UUID.randomUUID();
String xml = Fixtures
.resourceXmlBuilder()
.resource(PostgreSqlConstants.PostgreSqlDatabase.getUri(), UUID.randomUUID(), "Foo")
.state(UUID.randomUUID(), null)
.assertion("<API key>", assertionId)
.appendInnerXml("<schemaName>sch</schemaName>")
.appendInnerXml("<tableName>tbl</tableName>")
.build();
DomResourceLoader loader = DomPlugins.resourceLoader(
<API key>
.create()
.<API key>()
.build(),
xml);
// Execute
Resource resource = loader.load(new File("."));
// Verify
Assert.assertNotNull("resource", resource);
Assert.assertEquals("resource.states.size", 1, resource.getStates().size());
Assert.assertEquals(
"resource.states[0].assertions.size",
1,
resource.getStates().get(0).getAssertions().size());
<API key> assertionT = ModelExtensions.as(
resource.getStates().get(0).getAssertions().get(0),
<API key>.class);
Assert.assertNotNull("Expected to be an <API key>", assertionT);
Asserts.<API key>(
assertionId,
"sch",
"tbl",
assertionT,
"resource.states[0].assertions[0]");
}
}
|
# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 2.8
# Relative path conversion top directories.
SET(<API key> "/home/robot/bebop_ws/src/<API key>/navigation_stage")
SET(<API key> "/home/robot/bebop_ws/build/navigation_stage")
# Force unix paths in dependencies.
SET(<API key> 1)
# The C and CXX include file regular expressions for this directory.
SET(<API key> "^.*$")
SET(<API key> "^$")
SET(<API key> ${<API key>})
SET(<API key> ${<API key>})
|
#include <string.h>
#include <sys/time.h>
#include <sys/resource.h>
// Function: trim - Remove "\n" //
int trim(char *line) {
int end_pos = strlen(line) - 1;
if (line[end_pos] == '\n') {
line[end_pos] = '\0';
return 1;
}
return 0;
}
// Function: get_time_cpu - Get CPU time //
long get_time_cpu() {
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
return ru.ru_utime.tv_sec;
}
// Function: get_time - Get time //
long get_time() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec;
}
// Function: count_digit - count digit //
int count_digit(long num) {
int digit = 1;
int quotient;
quotient = int(num / 10);
while (quotient != 0) {
digit ++;
quotient = int(quotient / 10);
}
return digit;
}
// Function: revcomp - convert to reverse complement//
void revcomp(char* str) {
int i, len;
char c;
len = strlen(str);
for(i=0; i<len/2; i++) {
c = str[i];
str[i] = str[len-i-1];
str[len-i-1] = c;
}
for(i=0; i<len; i++) {
if (str[i] == 'A') {
str[i] = 'T';
} else if (str[i] == 'T') {
str[i] = 'A';
} else if (str[i] == 'G') {
str[i] = 'C';
} else if (str[i] == 'C') {
str[i] = 'G';
}
}
}
|
<?php namespace Jenssegers\Mongodb\Relations;
use MongoId;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\Collection as BaseCollection;
use Jenssegers\Mongodb\Eloquent\Collection;
abstract class EmbedsOneOrMany extends Relation {
/**
* The local key of the parent model.
*
* @var string
*/
protected $localKey;
/**
* The foreign key of the parent model.
*
* @var string
*/
protected $foreignKey;
/**
* The "name" of the relationship.
*
* @var string
*/
protected $relation;
/**
* Create a new embeds many relationship instance.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param \Illuminate\Database\Eloquent\Model $parent
* @param string $localKey
* @param string $foreignKey
* @param string $relation
* @return void
*/
public function __construct(Builder $query, Model $parent, Model $related, $localKey, $foreignKey, $relation)
{
$this->query = $query;
$this->parent = $parent;
$this->related = $related;
$this->localKey = $localKey;
$this->foreignKey = $foreignKey;
$this->relation = $relation;
// If this is a nested relation, we need to get the parent query instead.
if ($parentRelation = $this->getParentRelation())
{
$this->query = $parentRelation->getQuery();
}
$this->addConstraints();
}
/**
* Set the base constraints on the relation query.
*
* @return void
*/
public function addConstraints()
{
if (static::$constraints)
{
$this->query->where($this-><API key>(), '=', $this->getParentKey());
}
}
/**
* Set the constraints for an eager load of the relation.
*
* @param array $models
* @return void
*/
public function addEagerConstraints(array $models)
{
// There are no eager loading constraints.
}
/**
* Initialize the relation on a set of models.
*
* @param array $models
* @param string $relation
* @return void
*/
public function initRelation(array $models, $relation)
{
foreach ($models as $model)
{
$model->setParentRelation($this);
$model->setRelation($relation, $this->related->newCollection());
}
return $models;
}
/**
* Match the eagerly loaded results to their parents.
*
* @param array $models
* @param \Illuminate\Database\Eloquent\Collection $results
* @param string $relation
* @return array
*/
public function match(array $models, BaseCollection $results, $relation)
{
foreach ($models as $model)
{
$results = $model->$relation()->getResults();
$model->setParentRelation($this);
$model->setRelation($relation, $results);
}
return $models;
}
/**
* Shorthand to get the results of the relationship.
*
* @return Jenssegers\Mongodb\Eloquent\Collection
*/
public function get()
{
return $this->getResults();
}
/**
* Get the number of embedded models.
*
* @return int
*/
public function count()
{
return count($this->getEmbedded());
}
/**
* Attach a model instance to the parent model.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @return \Illuminate\Database\Eloquent\Model
*/
public function save(Model $model)
{
$model->setParentRelation($this);
return $model->save() ? $model : false;
}
/**
* Attach an array of models to the parent instance.
*
* @param array $models
* @return array
*/
public function saveMany(array $models)
{
array_walk($models, array($this, 'save'));
return $models;
}
/**
* Create a new instance of the related model.
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model
*/
public function create(array $attributes)
{
// Here we will set the raw attributes to avoid hitting the "fill" method so
// that we do not have to worry about a mass accessor rules blocking sets
// on the models. Otherwise, some of these attributes will not get set.
$instance = $this->related->newInstance($attributes);
$instance->setParentRelation($this);
$instance->save();
return $instance;
}
/**
* Create an array of new instances of the related model.
*
* @param array $records
* @return array
*/
public function createMany(array $records)
{
$instances = array();
foreach ($records as $record)
{
$instances[] = $this->create($record);
}
return $instances;
}
/**
* Transform single ID, single Model or array of Models into an array of IDs
*
* @param mixed $ids
* @return array
*/
protected function getIdsArrayFrom($ids)
{
if ( ! is_array($ids)) $ids = array($ids);
foreach ($ids as &$id)
{
if ($id instanceof Model) $id = $id->getKey();
}
return $ids;
}
/**
* Get the embedded records array.
*
* @return array
*/
protected function getEmbedded()
{
// Get raw attributes to skip relations and accessors.
$attributes = $this->parent->getAttributes();
return isset($attributes[$this->localKey]) ? $attributes[$this->localKey] : null;
}
/**
* Set the embedded records array.
*
* @param array $records
* @return \Illuminate\Database\Eloquent\Model
*/
protected function setEmbedded($records)
{
$attributes = $this->parent->getAttributes();
$attributes[$this->localKey] = $records;
// Set raw attributes to skip mutators.
$this->parent->setRawAttributes($attributes);
// Set the relation on the parent.
return $this->parent->setRelation($this->relation, $this->getResults());
}
/**
* Get the foreign key value for the relation.
*
* @param mixed $id
* @return mixed
*/
protected function getForeignKeyValue($id)
{
if ($id instanceof Model)
{
$id = $id->getKey();
}
// Convert the id to MongoId if necessary.
return $this->getBaseQuery()->convertKey($id);
}
/**
* Convert an array of records to a Collection.
*
* @param array $records
* @return Jenssegers\Mongodb\Eloquent\Collection
*/
protected function toCollection(array $records = array())
{
$models = array();
foreach ($records as $attributes)
{
$models[] = $this->toModel($attributes);
}
if (count($models) > 0)
{
$models = $this->eagerLoadRelations($models);
}
return new Collection($models);
}
/**
* Create a related model instanced.
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model
*/
protected function toModel($attributes = array())
{
if (is_null($attributes)) return null;
$model = $this->related->newFromBuilder((array) $attributes);
$model->setParentRelation($this);
$model->setRelation($this->foreignKey, $this->parent);
// If you remove this, you will get segmentation faults!
$model->setHidden(array_merge($model->getHidden(), array($this->foreignKey)));
return $model;
}
/**
* Get the relation instance of the parent.
*
* @return Illuminate\Database\Eloquent\Relations\Relation
*/
protected function getParentRelation()
{
return $this->parent->getParentRelation();
}
/**
* Get the underlying query for the relation.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function getQuery()
{
// Because we are sharing this relation instance to models, we need
// to make sure we use separate query instances.
return clone $this->query;
}
/**
* Get the base query builder driving the Eloquent builder.
*
* @return \Illuminate\Database\Query\Builder
*/
public function getBaseQuery()
{
// Because we are sharing this relation instance to models, we need
// to make sure we use separate query instances.
return clone $this->query->getQuery();
}
/**
* Check if this relation is nested in another relation.
*
* @return boolean
*/
protected function isNested()
{
return $this->getParentRelation() != null;
}
/**
* Get the fully qualified local key name.
*
* @return string
*/
protected function getPathHierarchy($glue = '.')
{
if ($parentRelation = $this->getParentRelation())
{
return $parentRelation->getPathHierarchy($glue) . $glue . $this->localKey;
}
return $this->localKey;
}
/**
* Get the parent's fully qualified key name.
*
* @return string
*/
protected function <API key>()
{
if ($parentRelation = $this->getParentRelation())
{
return $parentRelation->getPathHierarchy() . '.' . $this->parent->getKeyName();
}
return $this->parent->getKeyName();
}
/**
* Get the primary key value of the parent.
*
* @return string
*/
protected function getParentKey()
{
return $this->parent->getKey();
}
}
|
require 'spec_helper'
feature "Searching Entities" do
include CurbHelpers
include SearchHelpers
scenario 'entities are found by name', js: true, search: true do
entity = create(:entity, :with_parent, name: 'Foo bar')
<API key>
<API key>('bar') do|json|
json_item = json['entities'].first
expect(json_item).to have_key('id').with_value(entity.id.to_s)
%w(parent_id name country_code url).each do |key|
expect(json_item).to have_key(key).with_value(entity.send(key.to_sym))
end
%w(address_line_1 address_line_2 state phone email city).each do |key|
expect(json_item).not_to have_key(key)
end
end
end
scenario 'the results have relevant metadata', js: true, search: true do
entity = create(:entity, name: 'Foo bar')
<API key>
<API key>('bar') do|json|
metadata = json['meta']
expect(metadata).to have_key('current_page').with_value(1)
expect(metadata).to have_key('query').with_value("term" => "bar")
end
end
def <API key>(term, options = {})
sleep 1
<API key>(
"entities/search.json",
options.merge(term: term)) do |curb|
json = JSON.parse(curb.body_str)
yield(json) if block_given?
end
end
end
|
<?
if($_GET['action'] == "login") {
$conn = mysql_connect("localhost","user","password"); // your MySQL connection data
$db = mysql_select_db("DATABASENAME"); //put your database name in here
$name = $_POST['user'];
$q_user = mysql_query("SELECT * FROM USERS WHERE login='$name'");
?>
|
# TobiiEyetracking
This is the repository storing the codes for Tobii eye-tracking cases, including the application of Tobii and corresponding various methods of data analysis.
The utility of Tobii for experiment and design is mostly based on Matlab.
The data analysis consists of codes based on Matlab and R. I will try to create a consistent work soon.
|
<?php
namespace Dennis\Tournament\Domain\Model;
/**
* Class PlayerKo
*
* @package Dennis\Tournament\Domain\Model
*/
class PlayerKo extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity {
/**
* name
*
* @var string
*/
protected $name = '';
/**
* Returns the name
*
* @return string $name
*/
public function getName() {
return $this->name;
}
/**
* Sets the name
*
* @param string $name
* @return self
*/
public function setName($name) {
$this->name = $name;
return $this;
}
}
|
#ifndef _INCLUDE_DECODER_H
#define _INCLUDE_DECODER_H
#include <sys/time.h>
#include <string>
#include <map>
using std::string;
using std::map;
enum sensor_e {
TFA_1=0, // IT+ Klimalogg Pro, 30.3180, 30.3181, 30.3199(?)
TFA_2, // IT+ 30.3143, 30.3146(?), 30.3144
TFA_3, // 30.3155
TX22, // LaCrosse TX22
TFA_WHP, // 30.3306 (rain meter), pulse data
TFA_WHB, // TFA WeatherHub
FIREANGEL=0x20 // ST-630+W2
};
typedef struct {
sensor_e type;
uint64_t id;
double temp;
double humidity;
int alarm;
int flags;
int sequence;
time_t ts;
int rssi;
} sensordata_t;
class decoder
{
public:
decoder(sensor_e _type);
void set_params(char *_handler, int _mode, int _dbg);
virtual void store_bit(int bit);
virtual void flush(int rssi, int offset=0);
virtual void store_data(sensordata_t &d);
virtual void execute_handler(sensordata_t &d);
virtual void flush_storage(void);
virtual int has_sync(void) {return synced;};
int count(void) {return data.size();}
sensor_e get_type(void) {return type;}
virtual void store_bytes(uint8_t *d, int len);
protected:
int dbg;
int bad;
int synced;
sensor_e type;
uint8_t rdata[256];
int byte_cnt;
private:
char *handler;
int mode;
map<uint64_t,sensordata_t> data;
};
class demodulator
{
public:
demodulator(decoder *_dec);
virtual void start(int len);
virtual void reset(void){};
virtual int demod(int thresh, int pwr, int index, int16_t *iq);
decoder *dec;
protected:
int last_bit_idx;
};
#endif
|
// Gurux Ltd
// Filename: $HeadURL$
// $Date$
// $Author$
// DESCRIPTION
// This file is a part of Gurux Device Framework.
// Gurux Device Framework is Open Source software; you can redistribute it
// Gurux Device Framework is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
using Gurux.DLMS.Internal;
using Gurux.DLMS.Plc;
using Gurux.DLMS.Plc.Enums;
using System;
using System.Collections.Generic;
namespace Gurux.DLMS
{
<summary>
PLC communication settings.
</summary>
public class GXPlcSettings
{
byte[] _systemTitle;
private GXDLMSSettings settings;
<summary>
Initial credit (IC) tells how many times the frame must be repeated. Maximum value is 7.
</summary>
public byte InitialCredit
{
get;
set;
}
<summary>
The current credit (CC) initial value equal to IC and automatically decremented by the MAC layer after each repetition.
Maximum value is 7.
</summary>
public byte CurrentCredit
{
get;
set;
}
<summary>
Delta credit (DC) is used by the system management application entity
(SMAE) of the Client for credit management, while it has no meaning for a Server or a REPEATER.
It represents the difference(IC-CC) of the last communication originated by the system identified by the DA address to the system identified by the SA address.
Maximum value is 3.
</summary>
public byte DeltaCredit
{
get;
set;
}
<summary>
IEC 61334-4-32 LLC uses 6 bytes long system title. IEC 61334-5-1 uses 8 bytes long system title so we can use the default one.
</summary>
public byte[] SystemTitle
{
get
{
if (settings != null && settings.InterfaceType != Enums.InterfaceType.Plc && settings.Cipher != null)
{
return settings.Cipher.SystemTitle;
}
return _systemTitle;
}
set
{
if (settings != null && settings.InterfaceType != Enums.InterfaceType.Plc && settings.Cipher != null)
{
settings.Cipher.SystemTitle = value;
}
_systemTitle = value;
}
}
<summary>
Source MAC address.
</summary>
public UInt16 MacSourceAddress
{
get;
set;
}
<summary>
Destination MAC address.
</summary>
public UInt16 <API key>
{
get;
set;
}
<summary>
Response probability.
</summary>
public byte ResponseProbability
{
get;
set;
}
<summary>
Allowed time slots.
</summary>
public UInt16 AllowedTimeSlots
{
get;
set;
}
<summary>
Server saves client system title.
</summary>
public byte[] ClientSystemTitle
{
get;
set;
}
<summary>
Set default values.
</summary>
public void Reset()
{
InitialCredit = 7;
CurrentCredit = 7;
DeltaCredit = 0;
//New device addresses are used.
if (settings.InterfaceType == Enums.InterfaceType.Plc)
{
if (settings.IsServer)
{
MacSourceAddress = (UInt16)PlcSourceAddress.New;
<API key> = (UInt16)PlcSourceAddress.Initiator;
}
else
{
MacSourceAddress = (UInt16)PlcSourceAddress.Initiator;
<API key> = (UInt16)<API key>.AllPhysical;
}
}
else
{
if (settings.IsServer)
{
MacSourceAddress = (UInt16)PlcSourceAddress.New;
<API key> = (UInt16)<API key>.Initiator;
}
else
{
MacSourceAddress = (UInt16)<API key>.Initiator;
<API key> = (UInt16)<API key>.AllPhysical;
}
}
ResponseProbability = 100;
if (settings.InterfaceType == Enums.InterfaceType.Plc)
{
AllowedTimeSlots = 10;
}
else
{
AllowedTimeSlots = 0x14;
}
}
internal GXPlcSettings(GXDLMSSettings s)
{
settings = s;
Reset();
}
<summary>
Discover available PLC meters.
</summary>
<returns>Generated bytes.</returns>
public byte[] DiscoverRequest()
{
GXByteBuffer bb = new GXByteBuffer();
if (settings.InterfaceType != Enums.InterfaceType.Plc &&
settings.InterfaceType != Enums.InterfaceType.PlcHdlc)
{
throw new <API key>("Invalid interface type.");
}
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
bb.Set(GXCommon.LLCSendBytes);
}
bb.SetUInt8((byte)Command.DiscoverRequest);
bb.SetUInt8(ResponseProbability);
bb.SetUInt16(AllowedTimeSlots);
//DiscoverReport initial credit
bb.SetUInt8(0);
// IC Equal credit
bb.SetUInt8(0);
int val = 0;
int clientAddress = settings.ClientAddress;
int serverAddress = settings.ServerAddress;
UInt16 da = settings.Plc.<API key>;
UInt16 sa = settings.Plc.MacSourceAddress;
try
{
//10.4.6.4 Source and destination APs and addresses of CI-PDUs
//Client address is No-station in discoverReport.
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
settings.Plc.InitialCredit = 0;
settings.Plc.CurrentCredit = 0;
settings.Plc.MacSourceAddress = 0xC01;
settings.Plc.<API key> = 0xFFF;
settings.ClientAddress = 0x66;
// All-station
settings.ServerAddress = 0x33FF;
}
else
{
val = settings.Plc.InitialCredit << 5;
val |= settings.Plc.CurrentCredit << 2;
val |= settings.Plc.DeltaCredit & 0x3;
settings.Plc.MacSourceAddress = 0xC00;
settings.ClientAddress = 1;
settings.ServerAddress = 0;
}
return GXDLMS.GetMacFrame(settings, 0x13, (byte)val, bb);
}
finally
{
settings.ClientAddress = clientAddress;
settings.ServerAddress = serverAddress;
settings.Plc.<API key> = da;
settings.Plc.MacSourceAddress = sa;
}
}
<summary>
Generates discover report.
</summary>
<param name="systemTitle">System title</param>
<param name="newMeter">Is this a new meter.</param>
<returns>Generated bytes.</returns>
public byte[] DiscoverReport(byte[] systemTitle, bool newMeter)
{
GXByteBuffer bb = new GXByteBuffer();
if (settings.InterfaceType != Enums.InterfaceType.Plc &&
settings.InterfaceType != Enums.InterfaceType.PlcHdlc)
{
throw new <API key>("Invalid interface type.");
}
byte alarmDescription;
if (settings.InterfaceType == Enums.InterfaceType.Plc)
{
alarmDescription = (byte)(newMeter ? 1 : 0x82);
}
else
{
alarmDescription = 0;
}
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
bb.Set(GXCommon.LLCReplyBytes);
}
bb.SetUInt8((byte)Command.DiscoverReport);
bb.SetUInt8(1);
bb.Set(systemTitle);
if (alarmDescription != 0)
{
bb.SetUInt8(1);
}
bb.SetUInt8(alarmDescription);
int clientAddress = settings.ClientAddress;
int serverAddress = settings.ServerAddress;
UInt16 macSourceAddress = settings.Plc.MacSourceAddress;
UInt16 macTargetAddress = settings.Plc.<API key>;
try
{
//10.4.6.4 Source and destination APs and addresses of CI-PDUs
//Client address is No-station in discoverReport.
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
settings.Plc.<API key> = (UInt16) <API key>.Initiator;
}
else
{
settings.ClientAddress = 0;
settings.ServerAddress = 0xFD;
}
return GXDLMS.GetMacFrame(settings, 0x13, 0, bb);
}
finally
{
settings.ClientAddress = clientAddress;
settings.ServerAddress = serverAddress;
settings.Plc.MacSourceAddress = macSourceAddress;
settings.Plc.<API key> = macTargetAddress;
}
}
<summary>
Parse discover reply.
</summary>
<param name="value"></param>
<returns>Array of system titles and alarm descriptor error code</returns>
public List<GXDLMSPlcMeterInfo> ParseDiscover(GXByteBuffer value, UInt16 sa, UInt16 da)
{
List<GXDLMSPlcMeterInfo> list = new List<GXDLMSPlcMeterInfo>();
byte count = value.GetUInt8();
for (int pos = 0; pos != count; ++pos)
{
GXDLMSPlcMeterInfo info = new GXDLMSPlcMeterInfo();
info.SourceAddress = sa;
info.DestinationAddress = da;
//Get System title.
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
info.SystemTitle = new byte[8];
}
else
{
info.SystemTitle = new byte[6];
}
value.Get(info.SystemTitle);
// Alarm descriptor of the reporting system.
// Alarm-Descriptor presence flag
if (value.GetUInt8() != 0)
{
//Alarm-Descriptor
info.AlarmDescriptor = value.GetUInt8();
}
list.Add(info);
}
return list;
}
<summary>
Register PLC meters.
</summary>
<param name="<API key>">Active initiator systemtitle</param>
<param name="systemTitle"></param>
<returns>Generated bytes.</returns>
public byte[] RegisterRequest(byte[] <API key>, byte[] systemTitle)
{
GXByteBuffer bb = new GXByteBuffer();
//Control byte.
bb.SetUInt8((byte)Command.RegisterRequest);
bb.Set(<API key>);
//LEN
bb.SetUInt8(0x1);
bb.Set(systemTitle);
//MAC address.
bb.SetUInt16(MacSourceAddress);
int val = settings.Plc.InitialCredit << 5;
val |= settings.Plc.CurrentCredit << 2;
val |= settings.Plc.DeltaCredit & 0x3;
int clientAddress = settings.ClientAddress;
int serverAddress = settings.ServerAddress;
UInt16 macSourceAddress = settings.Plc.MacSourceAddress;
UInt16 macTargetAddress = settings.Plc.<API key>;
try
{
//10.4.6.4 Source and destination APs and addresses of CI-PDUs
//Client address is No-station in discoverReport.
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
settings.Plc.InitialCredit = 0;
settings.Plc.CurrentCredit = 0;
settings.Plc.MacSourceAddress = 0xC01;
settings.Plc.<API key> = 0xFFF;
settings.ClientAddress = 0x66;
// All-station
settings.ServerAddress = 0x33FF;
}
else
{
settings.ClientAddress = 1;
settings.ServerAddress = 0;
settings.Plc.MacSourceAddress = 0xC00;
settings.Plc.<API key> = 0xFFF;
}
return GXDLMS.GetMacFrame(settings, 0x13, (byte)val, bb);
}
finally
{
settings.ClientAddress = clientAddress;
settings.ServerAddress = serverAddress;
settings.Plc.MacSourceAddress = macSourceAddress;
settings.Plc.<API key> = macTargetAddress;
}
}
<summary>
Parse register request.
</summary>
<param name="value"></param>
<returns>System title mac address.</returns>
public void <API key>(GXByteBuffer value)
{
//Get System title.
byte[] st;
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
st = new byte[8];
}
else
{
st = new byte[6];
}
value.Get(st);
byte count = value.GetUInt8();
for (int pos = 0; pos != count; ++pos)
{
//Get System title.
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
st = new byte[8];
}
else
{
st = new byte[6];
}
value.Get(st);
SystemTitle = st;
//MAC address.
MacSourceAddress = value.GetUInt16();
}
}
<summary>
Parse discover request.
</summary>
<param name="value"></param>
<returns></returns>
public GXDLMSPlcRegister <API key>(GXByteBuffer value)
{
GXDLMSPlcRegister ret = new GXDLMSPlcRegister();
ret.ResponseProbability = value.GetUInt8();
ret.AllowedTimeSlots = value.GetUInt16();
ret.<API key> = value.GetUInt8();
ret.ICEqualCredit = value.GetUInt8();
return ret;
}
<summary>
Ping PLC meter.
</summary>
<returns>Generated bytes.</returns>
public byte[] PingRequest(byte[] systemTitle)
{
GXByteBuffer bb = new GXByteBuffer();
//Control byte.
bb.SetUInt8((byte)Command.PingRequest);
bb.Set(systemTitle);
return GXDLMS.GetMacFrame(settings, 0x13, 0, bb);
}
<summary>
Parse ping response.
</summary>
<param name="value">Received data.</param>
public byte[] ParsePing(GXByteBuffer value)
{
return value.SubArray(1, 6);
}
<summary>
Repear call request.
</summary>
<returns>Generated bytes.</returns>
public byte[] RepeaterCallRequest()
{
GXByteBuffer bb = new GXByteBuffer();
//Control byte.
bb.SetUInt8((byte)Command.RepeatCallRequest);
//MaxAdrMac.
bb.SetUInt16(0x63);
//Nb_Tslot_For_New
bb.SetUInt8(0);
//Reception-Threshold default value
bb.SetUInt8(0);
return GXDLMS.GetMacFrame(settings, 0x13, 0xFC, bb);
}
}
}
|
<!DOCTYPE html PUBLIC "-
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/js.cookie.js"></script>
<title>BenchmarkTest01074</title>
</head>
<body>
<form action="/benchmark/BenchmarkTest01074" method="POST" id="<API key>">
<div><label>Please explain your answer:</label></div>
<br/>
<div><textarea rows="4" cols="50" id="vectorArea" name="vectorArea" value=""></textarea></div>
<div><label>Any additional note for the reviewer:</label></div>
<div><input type="text" id="answer" name="answer"></input></div>
<br/>
<div><label>An AJAX request will be sent with a header named vector and value:</label>
<input type="text" id="vector" name="vector" value="whatever" class="safe"></input></div>
<div><input type="button" id="login-btn" value="Login" /></div>
</form>
<div id="ajax-form-msg1"></div>
<script>
$('.safe').keypress(function (e) {
if (e.which == 13) {
$('#login-btn').trigger('click');
return false;
}
});
$("#login-btn").click(function(){
var formData = $("#<API key>").serializeArray();
var URL = $("#<API key>").attr("action");
var text = $("#<API key> input[id=vector]").val();
$.ajax({
url : URL,
headers: { 'vector': text },
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR){
$("#ajax-form-msg1").html('<pre><code class="prettyprint">'+data+'</code></pre>');
},
error: function (jqXHR, textStatus, errorThrown){ alert(errorThrown);}
});
});
</script>
</body>
</html>
|
// vim: ts=4 sw=4 expandtab ft=c
// This file may only be copied under the terms of the GNU Library General
#ifndef <API key>
#define <API key>
// <API key>.h -
// Definitions for stack layout data structures. These are generated by the
// compiler, and are used by the parts of the runtime system that need to look
// at the stacks (and sometimes the registers) and make sense of their
// contents. The parts of the runtime system that need to do this include
// exception handling, the debugger, and (eventually) the accurate garbage
// collector.
// For a general description of the idea of stack layouts, see the paper
// "Run time type information in Mercury" by Tyson Dowd, Zoltan Somogyi,
// Fergus Henderson, Thomas Conway and David Jeffery, which is available from
// the Mercury web site. The relevant section is section 3.8, but be warned:
// while the general principles remain applicable, the details have changed
// since that paper was written.
// NOTE: The constants and data-structures used here need to be kept in
// sync with the ones generated in the compiler. If you change anything here,
// you may need to change stack_layout.m, layout.m, and/or layout_out.m in
// the compiler directory as well.
#include "mercury_types.h"
#include "mercury_std.h" // for MR_VARIABLE_SIZED
#include "mercury_tags.h"
#include "mercury_type_info.h" // for MR_PseudoTypeInfo
#include "mercury_proc_id.h" // for MR_ProcId
#include "mercury_goto.h" // for MR_PROC_LAYOUT etc
#include "mercury_tabling.h" // for MR_TableTrieStep etc
// Definitions for MR_Determinism.
// The max_soln component of the determinism is encoded in the 1 and 2 bits.
// The can_fail component of the determinism is encoded in the 4 bit.
// The first_solution component of the determinism is encoded in the 8 bit.
// <API key> could also be defined as ((d) & 3) == 3),
// but this would be less efficient, since the C compiler does not know
// that we do not set the 1 bit unless we also set the 2 bit.
// NOTE: this must match the encoding specified by <API key>/1
// in mdbcomp/<API key>.m.
typedef MR_int_least16_t MR_Determinism;
#define MR_DETISM_DET 6
#define MR_DETISM_SEMI 2
#define MR_DETISM_NON 3
#define MR_DETISM_MULTI 7
#define MR_DETISM_ERRONEOUS 4
#define MR_DETISM_FAILURE 0
#define MR_DETISM_CCNON 10
#define MR_DETISM_CCMULTI 14
#define MR_DETISM_MAX 14
#define <API key>(d) (((d) & 3) == 0)
#define <API key>(d) (((d) & 3) == 2)
#define <API key>(d) (((d) & 1) != 0)
#define MR_DETISM_CAN_FAIL(d) (((d) & 4) == 0)
#define <API key>(d) (((d) & 8) != 0)
#define MR_DETISM_DET_STACK(d) (!<API key>(d) \
|| <API key>(d))
// Definitions for MR_LongLval and MR_ShortLval.
// MR_LongLval is an MR_Unsigned which describes a location.
// This includes lvals such as stack slots, general registers, and special
// registers such as succip, hp, etc, as well as locations whose address is
// given as a typeinfo inside the type class info structure pointed to by an
// lval.
// What kind of location an MR_LongLval refers to is encoded using
// a low tag with <API key> bits; the type MR_LongLvalType
// describes the different tag values. The interpretation of the rest of
// the word depends on the location type:
// Locn Rest
// MR_r(Num) Num (register number)
// MR_f(Num) Num (register number)
// MR_stackvar(Num) Num (stack slot number)
// MR_framevar(Num) Num (stack slot number)
// MR_succip
// MR_maxfr
// MR_curfr
// MR_hp
// MR_sp
// constant See below
// indirect(Base, N) See below
// unknown (The location is not known)
// For constants, the rest of the word is a pointer to static data. The
// pointer has only two low tag bits free, so we reserve every four-bit tag
// which has 00 as its bottom two bits for representing them.
// For indirect references, the word exclusive of the tag consists of
// (a) an integer with <API key> bits giving the index of
// the typeinfo inside a type class info (to be interpreted by
// <API key> or the predicate
// private_builtin.<API key>, which calls it) and
// (b) a MR_LongLval value giving the location of the pointer to the
// type class info. This MR_LongLval value will *not* have an indirect tag.
// This data is generated in stack_layout.<API key>,
// which must be kept in sync with the constants and macros defined here.
typedef MR_Unsigned MR_LongLval;
typedef enum {
<API key> = 0,
MR_LONG_LVAL_TYPE_R = 1,
MR_LONG_LVAL_TYPE_F = 2,
<API key> = 3,
<API key> = 4,
<API key> = 5,
<API key> = 6,
<API key> = 7,
<API key> = 8,
<API key> = 9,
<API key> = 10,
<API key> = 11,
<API key> = 12,
<API key> = 13,
<API key> = 14,
<API key> = 15,
<API key> = 16,
<API key> = 17,
<API key> = 20,
<API key> = 24,
<API key> = 28
} MR_LongLvalType;
// This must be in sync with stack_layout.long_lval_tag_bits.
#define <API key> 5
#define <API key> 2
#define MR_LONG_LVAL_TYPE(Locn) \
((MR_LongLvalType) ((Locn) & ((1 << <API key>) - 1)))
#define MR_LONG_LVAL_NUMBER(Locn) \
((int) ((Locn) >> <API key>))
#define MR_LONG_LVAL_CONST(Locn) \
(* (MR_Word *) ((Locn) & ~ ((1 << <API key>) - 1)))
// This must be in sync with stack_layout.offset_bits.
#define <API key> 6
#define <API key>(LocnNumber) \
((int) ((LocnNumber) & ((1 << <API key>) - 1)))
#define <API key>(LocnNumber) \
(((MR_uint_least32_t) (LocnNumber)) >> <API key>)
#define <API key>(n) \
(((n) << <API key>) + <API key>)
#define <API key>(n) \
(((n) << <API key>) + <API key>)
#define <API key>(n) \
(((n) << <API key>) + MR_LONG_LVAL_TYPE_R)
// MR_ShortLval is a MR_uint_least8_t which describes an location. This
// includes lvals such as stack slots and general registers that have small
// numbers, and special registers such as succip, hp, etc.
// What kind of location an MR_LongLval refers to is encoded using
// a low tag with 2 bits; the type MR_ShortLval_Type describes
// the different tag values. The interpretation of the rest of the word
// depends on the location type:
// Locn Tag Rest
// MR_r(Num) 0 Num (register number)
// MR_stackvar(Num) 1 Num (stack slot number)
// MR_framevar(Num) 2 Num (stack slot number)
// special reg 3 MR_LongLvalType
// This data is generated in stack_layout.<API key>,
// which must be kept in sync with the constants and macros defined here.
typedef MR_uint_least8_t MR_ShortLval;
typedef enum {
<API key>,
<API key>,
<API key>,
<API key>
} MR_ShortLval_Type;
// This must be in sync with stack_layout.short_lval_tag_bits.
#define <API key> 2
#define MR_SHORT_LVAL_TYPE(Locn) \
((MR_ShortLval_Type) \
(((MR_Word) Locn) & ((1 << <API key>) - 1)))
#define <API key>(Locn) \
((int) (((MR_Word) Locn) >> <API key>))
#define <API key>(n) \
((MR_ShortLval) (((n) << <API key>) \
+ <API key>))
#define <API key>(n) \
((MR_ShortLval) (((n) << <API key>) \
+ <API key>))
#define MR_SHORT_LVAL_R_REG(n) \
((MR_ShortLval) (((n) << <API key>) \
+ <API key>))
// Definitions for MR_UserEvent and MR_UserEventSpec.
// Our layout structures link to information about user events from two places:
// the label layout structures of labels that correspond to user events,
// and the module layout structures of modules that contain user events.
// Label layout structures link to MR_UserEvent structures; module layout
// structures link to MR_UserEventSpec structures. Most of the information
// is in the MR_UserEventSpec structures; MR_UserEvent structures contain
// only information that may differ between two instances of the same event.
// The fields of MR_UserEvent:
// The event_number field contains the ordinal number of the event in the
// event set the module was compiled with: it gives the identity of the event.
// (Event numbers start at zero.) This field is also the link to the rest of
// the information about the event, contained in the MR_UserEventSpec structure
// linked to by the module layout structure. The MR_user_event_spec macro
// follows this link.
// The next two fields all point to arrays whose length is the number of
// attributes (which is available in the MR_UserEventSpec structure).
// attr_locns[i] gives the location where we can find the value of the
// i'th attribute (the first attribute is attribute zero). This is
// meaningful only if the attribute is not a synthesized attribute.
// attr_var_nums[i] gives the variable number of the i'th attribute;
// if it contains zero, that means the attribute is synthesized. This field
// is used by the debugger to display the associated value just once
// (not twice, as both attribute and variable value) with "print *". (Note
// that we don't delete the variables that are also attributes from the set of
// live variables in layout structures, because that would require any native
// garbage collector to look at the list of attributes as well as the list of
// other variables, slowing it down.)
typedef MR_uint_least16_t MR_HLDSVarNum;
struct MR_UserEvent_Struct {
MR_uint_least16_t MR_ue_event_number;
MR_LongLval *MR_ue_attr_locns;
const MR_HLDSVarNum *MR_ue_attr_var_nums;
};
// The fields of MR_UserEventSpec:
// The event_name field contains the name of the event.
// The num_attrs field gives the number of attributes.
// The next three fields (attr_names, attr_types and synth_attrs) all point
// to arrays whose length is the number of attributes.
// attr_names[i] gives the name of the i'th attribute.
// attr_types[i] is the typeinfo giving the type of the i'th attribute.
// If the i'th attribute is synthesized, synth_attrs[i] points to the
// information required to synthesize it: the number of the attribute
// containing the synthesis function, the number of arguments of the synthesis
// function, and an array of attribute numbers (of length num_arg_attrs)
// giving the list of those arguments. The depend_attrs field will point to
// a list of numbers of the synthesized attributes whose values must be
// materialized before this attribute can be evaluated. (This list will include
// the argument attributes, and will be in a feasible evaluation order.)
// If the i'th attribute is not synthesized, synth_attrs[i] and depend_attrs[i]
// will both be NULL. (For now, depend_attrs[i] will not be filled in for
// synthesized attributes either.)
// The synth_attr_order field points to an array of attribute numbers that
// gives the order in which the values of the synthesized attributes should be
// evaluated. The array is ended by -1 as a sentinel.
// The synth_attrs and synth_attr_order fields will both be NULL for events
// that have no synthesized attributes.
struct MR_SynthAttr_Struct {
MR_int_least16_t MR_sa_func_attr;
MR_int_least16_t MR_sa_num_arg_attrs;
MR_uint_least16_t *MR_sa_arg_attrs;
MR_int_least16_t *MR_sa_depend_attrs;
};
struct <API key> {
const char *MR_ues_event_name;
MR_uint_least16_t MR_ues_num_attrs;
const char **MR_ues_attr_names;
MR_TypeInfo *MR_ues_attr_types;
MR_SynthAttr *MR_ues_synth_attrs;
MR_int_least16_t *<API key>;
};
#define MR_user_event_spec(label_layout) \
label_layout->MR_sll_entry-><API key>-> \
<API key>[label_layout->MR_sll_user_event-> \
MR_ue_event_number]
#define <API key>(label_layout) \
label_layout->MR_sll_entry-><API key>-> \
<API key>
// Definitions for MR_LabelLayout.
// An MR_LabelLayout structure describes the debugging and accurate gc
// information available at a given label.
// The MR_sll_entry field points to the proc layout structure of the procedure
// in which the label occurs.
// The MR_sll_port field will contain a negative number if there is no
// execution tracing port associated with the label. If there is, the
// field will contain a value of type MR_TracePort. For labels associated
// with events, this will be the port of the event. For return labels,
// this port will be exception (since exception events are associated with
// the return from the call that raised the exception).
// The MR_sll_hidden field contains a boolean which is meaningful only if the
// label corresponds to an execution tracing event. It will be MR_HIDDEN if the
// event should have no effects that the user can see (no message printed, no
// increment of the event number etc), and MR_NOT_HIDDEN otherwise. Hidden
// events are sometimes needed by the declarative debugger to provide the
// proper context for other events.
// The MR_sll_goal_path field contains an offset into the module-wide string
// table, leading to a string that gives the goal path associated with the
// label. If there is no meaningful goal path associated with the label,
// the offset will be zero, leading to the empty string. You can use the macro
// MR_label_goal_path to convert the value in the MR_sll_goal_path field to a
// string.
// A possible alternative would be to represent goal paths using statically
// allocated terms of the reverse_goal_path type. An almost-complete diff
// making that change was posted to the mercury-reviews mailing list on
// 30 Sep 2011, but it was not committed, since it lead to a 4% *increase*
// in the size of asm_fast.gc.debug executables. Even though different goal
// paths share a tail (the part of the path near the root) with the
// static reverse_goal_path term representation but not with the string
// representation, the string representation is so much more compact
// (usually taking 4 to 6 bytes for most steps) than the Mercury term
// representation (1 to 4 words for a step, plus 2 words for the rgp_cons,
// totalling at least 24 bytes per step on 64 bit systems), that the string
// representation is significantly more compact overall. The Mercury term
// representation does have the potential to speed up the implementation of
// the operations in the declarative debugger that need to test whether
// two goal paths represent two different direct components of the same parent
// goal. If the two different goal paths are represented as reverse_goal_paths,
// then doing this test on RGPA and RGPB simply requires the test
// RGPA = rgp_cons(ParentRGPA, StepA),
// RGPB = rgp_cons(ParentRGPB, StepB),
// ParentRGPA = ParentRGPB
// and the last step can be done by a pointer comparison. This test can be done
// in constant time, whereas the current implementation of the same test
// (the function <API key> in trace/<API key>.c)
// works in linear time.
// If the label is the label of a user-defined event, then the
// MR_sll_user_event field will point to information about the user event;
// otherwise, the field will be NULL.
// The remaining fields give information about the values live at the given
// label, if this information is available. If it is available, the
// <API key> macro will return true and the fields after the count
// are meaningful; if it is not available, the macro will return false and
// those fields are not meaningful (i.e. you are looking at an
// <API key> structure).
// The format in which we store information about the values live at the label
// is somewhat complicated, due to our desire to make this information compact.
// We can represent a location in one of two ways, as an 8-bit MR_ShortLval
// or as a 32-bit MR_LongLval. We prefer representing a location as an
// MR_ShortLval, but of course not all locations can be represented in
// this way, so those other locations are represented as MR_LongLvals.
// The MR_sll_var_count field, if it is valid, is encoded by the formula
// (#Long << MR_SHORT_COUNT_BITS + #Short), where #Short is the number
// data items whose descriptions fit into an MR_ShortLval and #Long is the
// number of data items whose descriptions do not. (The number of distinct
// values that fit into 8 bits also fits into 8 bits, but since some
// locations hold the value of more than one variable at a time, not all
// the values need to be distinct; this is why MR_SHORT_COUNT_BITS is
// more than 8.)
// The MR_sll_types field points to an array of #Long + #Short
// MR_PseudoTypeInfos each giving the type of a live data item, with
// a small integer instead of a pointer representing a special kind of
// live data item (e.g. a saved succip or hp). This field will be null if
// #Long + #Short is zero.
// The MR_sll_long_locns field points to an array of #Long MR_LongLvals,
// while the MR_sll_short_locns field points to an array of #Short
// MR_ShortLvals. The element at index i in the MR_sll_long_locns vector
// will have its type described by the element at index i in the MR_sll_types
// vector, while the element at index i in the MR_sll_short_locns vector
// will have its type described by the element at index #Long + i in the
// MR_sll_types vector. MR_sll_long_locns will be NULL if #Long is zero,
// and similarly MR_sll_short_locns will be NULL if #Short is zero.
// The MR_sll_var_nums field may be NULL, which means that there is no
// information about the variable numbers of the live values. If the field
// is not NULL, it points to a vector of variable numbers, which has an element
// for each live data item. This is either the live data item's HLDS variable
// number, or one of two special values. Zero means that the live data item
// is not a variable (e.g. it is a saved copy of succip). The largest possible
// 16-bit number on the other hand means "the number of this variable does not
// fit into 16 bits". With the exception of these special values, the value
// in this slot uniquely identifies the live data item. (Not being able to
// uniquely identify nonvariable data items is never a problem. Not being able
// to uniquely identify variables is a problem, at the moment, only to the
// extent that the debugger cannot print their names.)
// The types of the live variables may or may not have type variables in them.
// If they do not, the MR_sll_tvars field will be NULL. If they do, it will
// point to an MR_TypeParamLocns structure that gives the locations of the
// typeinfos for those type variables. This structure gives the number of type
// variables and their locations, so that the code that needs the type
// parameters can materialize all the type parameters from their location
// descriptions in one go. This is an optimization, since the type parameter
// vector could simply be indexed on demand by the type variable's variable
// number stored within the MR_PseudoTypeInfos stored inside the vector
// pointed to by the MR_sll_types field.
// Since we allocate type variable numbers sequentially, the MR_tp_param_locns
// vector will usually be dense. However, after all variables whose types
// include e.g. type variable 2 have gone out of scope, variables whose
// types include type variable 3 may still be around. In cases like this,
// the entry for type variable 2 will be zero; this signals to the code
// in the internal debugger that materializes typeinfo structures that
// this typeinfo structure need not be materialized. Note that the array
// element MR_tp_param_locns[i] describes the location of the typeinfo
// structure for type variable i+1, since array offsets start at zero
// but type variable numbers start at one.
// The <API key> is used for counting the number of times
// the event of this label is executed. It gives the label's index in the
// array pointed to by the module layout's <API key> field;
// whenever the event of this label is executed, the element in that array
// indicated by this index will be incremented (when <API key>
// is set). The array element at index zero is ignored. A label layout will
// have zero in its <API key> field if the label doesn't
// correspond to an event.
// XXX: Presently, inst information is ignored; we assume that all live values
// are ground.
#define MR_HIDDEN 1
#define MR_NOT_HIDDEN 0
struct <API key> {
MR_uint_least32_t MR_tp_param_count;
MR_LongLval MR_tp_param_locns[MR_VARIABLE_SIZED];
};
struct <API key> {
const MR_ProcLayout *MR_sll_entry;
MR_int_least8_t MR_sll_port;
MR_int_least8_t MR_sll_hidden;
MR_uint_least16_t <API key>;
MR_uint_least32_t MR_sll_goal_path;
const MR_UserEvent *MR_sll_user_event;
MR_Integer MR_sll_var_count; // >= 0, encoding Long > 0
const MR_TypeParamLocns *MR_sll_tvars;
const MR_PseudoTypeInfo *MR_sll_types;
const MR_HLDSVarNum *MR_sll_var_nums;
const MR_ShortLval *MR_sll_short_locns;
const MR_LongLval *MR_sll_long_locns;
};
typedef struct <API key> {
const MR_ProcLayout *MR_sll_entry;
MR_int_least8_t MR_sll_port;
MR_int_least8_t MR_sll_hidden;
MR_uint_least16_t <API key>;
MR_uint_least32_t MR_sll_goal_path;
const MR_UserEvent *MR_sll_user_event;
MR_Integer MR_sll_var_count; // >= 0 , encoding Long == 0
const MR_TypeParamLocns *MR_sll_tvars;
const MR_PseudoTypeInfo *MR_sll_types;
const MR_HLDSVarNum *MR_sll_var_nums;
const MR_ShortLval *MR_sll_short_locns;
} MR_LabelLayoutShort;
typedef struct <API key> {
const MR_ProcLayout *MR_sll_entry;
MR_int_least8_t MR_sll_port;
MR_int_least8_t MR_sll_hidden;
MR_uint_least16_t <API key>;
MR_uint_least32_t MR_sll_goal_path;
const MR_UserEvent *MR_sll_user_event;
MR_Integer MR_sll_var_count;
} <API key>;
#define MR_label_goal_path(layout) \
((<API key>((layout)->MR_sll_entry)) ? \
((layout)->MR_sll_entry-><API key> \
->MR_ml_string_table \
+ ((layout)->MR_sll_goal_path >> 1)) \
: "")
#define MR_SHORT_COUNT_BITS 10
#define MR_SHORT_COUNT_MASK ((1 << MR_SHORT_COUNT_BITS) - 1)
#define <API key>(sll) \
(((sll)->MR_sll_var_count) >= 0)
#define <API key>(sll) \
(((sll)->MR_sll_var_count) > 0)
#define <API key>(sll) \
(((sll)->MR_sll_var_count) & MR_SHORT_COUNT_MASK)
#define <API key>(sll) \
(((sll)->MR_sll_var_count) >> MR_SHORT_COUNT_BITS)
#define <API key>(sll) \
(<API key>(sll) + <API key>(sll))
#define MR_var_pti(sll, i) \
((sll)->MR_sll_types[(i)])
#define <API key>(sll, i) \
((sll)->MR_sll_short_locns[(i)])
#define <API key>(sll, i) \
((sll)->MR_sll_long_locns[(i)])
// Define a stack layout for an internal label.
// is the reference to the procedure layout, which allows you to find the
// stack frame size and the succip location, thereby enabling stack tracing.
// For the native garbage collector, we will need to add meaningful
// live value information as well to these macros.
#define <API key>(label) \
MR_PASTE2(<API key>, label)
#define MR_LABEL_LAYOUT_REF(label) \
((const MR_LabelLayout *) &<API key>(MR_add_prefix(label)))
#define <API key>(module, name, arity, mode, label) \
<API key> \
<API key>(module, name, arity, mode, label) = { \
(MR_ProcLayout *) & \
<API key>(module, name, arity, mode), \
0, \
-1, \
MR_FALSE, \
0, \
0, \
-1 /* No info about live values. */ \
}
// These macros are used as shorthands in generated C source files
// for some fields of MR_LabelLayouts.
// We need to cast the addresses of proc layout structures because there
// are several kinds of proc layouts, of different (though compatible) types.
#define MR_LL(e, port, num, path) \
MR_PROC_LAYOUT(MR_add_prefix(e)), \
MR_PASTE2(MR_PORT_, port), \
MR_NOT_HIDDEN, (num), (path), NULL
#define MR_LL_H(e, port, num, path) \
MR_PROC_LAYOUT(MR_add_prefix(e)), \
MR_PASTE2(MR_PORT_, port), \
MR_HIDDEN, (num), (path), NULL
#define MR_LL_U(e, port, num, path, ue) \
MR_PROC_LAYOUT(MR_add_prefix(e)), \
MR_PASTE2(MR_PORT_, port), \
MR_NOT_HIDDEN, (num), (path), (ue)
#define MR_LL_H_U(e, port, num, path, ue) \
MR_PROC_LAYOUT(MR_add_prefix(e)), \
MR_PASTE2(MR_PORT_, port), \
MR_HIDDEN, (num), (path), (ue)
#define MR_LLVS(m, p, h, s) \
&<API key>(m)[p], \
&MR_hlds_var_nums(m)[h], \
&MR_short_locns(m)[s]
#define MR_LLVL(m, p, h, s, l) \
&<API key>(m)[p], \
&MR_hlds_var_nums(m)[h], \
&MR_short_locns(m)[s], \
&MR_long_locns(m)[l]
#define MR_LLVS0(m, p, h, s) \
0, \
MR_LLVS(m, p, h, s)
#define MR_LLVL0(m, p, h, s, l) \
0, \
MR_LLVL(m, p, h, s, l)
#define MR_LLVSC(m, tpt, tpc, p, h, s) \
(const MR_TypeParamLocns *) MR_COMMON(tpt, tpc), \
MR_LLVS(m, p, h, s)
#define MR_LLVLC(m, tpt, tpc, p, h, s, l) \
(const MR_TypeParamLocns *) MR_COMMON(tpt, tpc), \
MR_LLVL(m, p, h, s, l)
#define MR_cast_to_pti1(r1) \
(MR_PseudoTypeInfo) (r1),
#define MR_cast_to_pti2(r1, r2) \
(MR_PseudoTypeInfo) (r1), \
(MR_PseudoTypeInfo) (r2),
#define MR_cast_to_pti3(r1, r2, r3) \
(MR_PseudoTypeInfo) (r1), \
(MR_PseudoTypeInfo) (r2), \
(MR_PseudoTypeInfo) (r3)
#define MR_cast_to_pti4(r1, r2, r3, r4) \
(MR_PseudoTypeInfo) (r1), \
(MR_PseudoTypeInfo) (r2), \
(MR_PseudoTypeInfo) (r3), \
(MR_PseudoTypeInfo) (r4),
#define MR_cast_to_pti5(r1, r2, r3, r4, r5) \
(MR_PseudoTypeInfo) (r1), \
(MR_PseudoTypeInfo) (r2), \
(MR_PseudoTypeInfo) (r3), \
(MR_PseudoTypeInfo) (r4), \
(MR_PseudoTypeInfo) (r5),
#define MR_cast_to_pti6(r1, r2, r3, r4, r5, r6) \
(MR_PseudoTypeInfo) (r1), \
(MR_PseudoTypeInfo) (r2), \
(MR_PseudoTypeInfo) (r3), \
(MR_PseudoTypeInfo) (r4), \
(MR_PseudoTypeInfo) (r5), \
(MR_PseudoTypeInfo) (r6),
#define MR_cast_to_pti7(r1, r2, r3, r4, r5, r6, r7) \
(MR_PseudoTypeInfo) (r1), \
(MR_PseudoTypeInfo) (r2), \
(MR_PseudoTypeInfo) (r3), \
(MR_PseudoTypeInfo) (r4), \
(MR_PseudoTypeInfo) (r5), \
(MR_PseudoTypeInfo) (r6), \
(MR_PseudoTypeInfo) (r7),
#define MR_cast_to_pti8(r1, r2, r3, r4, r5, r6, r7, r8) \
(MR_PseudoTypeInfo) (r1), \
(MR_PseudoTypeInfo) (r2), \
(MR_PseudoTypeInfo) (r3), \
(MR_PseudoTypeInfo) (r4), \
(MR_PseudoTypeInfo) (r5), \
(MR_PseudoTypeInfo) (r6), \
(MR_PseudoTypeInfo) (r7), \
(MR_PseudoTypeInfo) (r8),
#define MR_cast_to_pti9(r1, r2, r3, r4, r5, r6, r7, r8, r9) \
(MR_PseudoTypeInfo) (r1), \
(MR_PseudoTypeInfo) (r2), \
(MR_PseudoTypeInfo) (r3), \
(MR_PseudoTypeInfo) (r4), \
(MR_PseudoTypeInfo) (r5), \
(MR_PseudoTypeInfo) (r6), \
(MR_PseudoTypeInfo) (r7), \
(MR_PseudoTypeInfo) (r8), \
(MR_PseudoTypeInfo) (r9),
#define MR_cast_to_pti10(r1, r2, r3, r4, r5, r6, r7, r8, r9, r10) \
(MR_PseudoTypeInfo) (r1), \
(MR_PseudoTypeInfo) (r2), \
(MR_PseudoTypeInfo) (r3), \
(MR_PseudoTypeInfo) (r4), \
(MR_PseudoTypeInfo) (r5), \
(MR_PseudoTypeInfo) (r6), \
(MR_PseudoTypeInfo) (r7), \
(MR_PseudoTypeInfo) (r8), \
(MR_PseudoTypeInfo) (r9), \
(MR_PseudoTypeInfo) (r10),
// Definitions for MR_ProcLayout.
// The MR_TableIoEntry structure.
// To enable printing and declarative debugging of I/O actions, the compiler
// generates one of these structures for each I/O primitive. The compiler
// transforms the bodies of those primitives to create a block of memory
// (the answerblock, the action's entry in the I/O table), and fill it in with
// - a pointer to the primitive's MR_TableIoEntry structure, and
// - the values of some of the primitive's arguments (excluding the
// I/O states, which are dummies).
// The arguments in the answerblock will always include the output arguments,
// since I/O tabling needs these to make the primitive idempotent.
// If the primitive does not have type class constraints, it will include
// the values of the input arguments as well, for two reasons:
// - to present them to the user on request, either via mdb's browsing
// commands, or via the declarative debugger
// - the input typeinfo arguments are needed to present the value of other
// arguments, both inputs and outputs, to the user.
// In the presence of typeclass constraints on the predicate, we cannot
// guarantee that we can encode the locations of the typeinfos (which may be
// arbitrarily deep inside typeclass_infos) in our fixed size location
// descriptions. We therefore set the have_arg_infos field to false,
// indicating that none of the following fields contain meaningful information.
// In the absence of typeclass constraints on the predicate, we set the
// have_arg_infos field to true. In that case, num_ptis will contain the
// number of arguments in the answer block, the ptis field will point to
// a vector of num_ptis pseudo-typeinfos (one for each argument in the answer
// block), and the type_params field maps the type variables that occur
// in the pseudo-typeinfos to the locations of the typeinfos describing
// the types bound to them.
// The entry_proc field, which is always meaningful, identifies the procedure
// that created the I/O table entry.
typedef struct <API key> {
const MR_ProcLayout *<API key>;
MR_bool <API key>;
MR_Integer <API key>;
const MR_PseudoTypeInfo *<API key>;
const MR_TypeParamLocns *<API key>;
} MR_TableIoEntry;
// MR_TableInfo: compiler generated information describing the tabling
// data structures used by a procedure.
// For I/O tabled procedures, the information is in the io_decl field.
// For other kinds of tabled procedures, it is in the gen field.
// The init field is used for initialization only.
// The MR_table_proc field is not const because the structure it points to
// has fields containing statistics, which are updated at runtime.
typedef union {
const void *MR_table_init;
const MR_TableIoEntry *MR_table_io_entry;
const MR_Table_Gen *MR_table_gen;
MR_ProcTableInfo *MR_table_proc;
} MR_TableInfo;
// The MR_StackTraversal structure contains the following fields:
// The code_addr field points to the start of the procedure's code.
// This allows the profiler to figure out which procedure a sampled program
// counter belongs to, and allows the debugger to implement retry.
// The succip_locn field encodes the location of the saved succip if it is
// saved in a general purpose stack slot. If the succip is saved in a special
// purpose stack slot (as it is for model_non procedures) or if the procedure
// never saves the succip (as in leaf procedures), this field will contain -1.
// The stack_slots field gives the number of general purpose stack slots
// in the procedure.
// The detism field encodes the determinism of the procedure.
typedef struct <API key> {
MR_Code *MR_trav_code_addr;
MR_LongLval MR_trav_succip_locn;
MR_int_least16_t MR_trav_stack_slots;
MR_Determinism MR_trav_detism;
} MR_StackTraversal;
#define <API key>(entry) \
MR_PROC_ID_IS_UCI(entry->MR_sle_proc_id)
// The MR_ExecTrace structure contains the following fields.
// The call_label field points to the label layout structure for the label
// associated with the call event at the entry to the procedure. The purpose
// of this field is to allow the debugger to find out which variables
// are where on entry, so it can reexecute the procedure if asked to do so
// and if the values of the required variables are still available.
// The labels field contains a pointer to an array of pointers to label layout
// structures; the size of the array is given by the num_labels field. The
// initial part of the array will contain a pointer to the label layout
// structure of every interface event in the procedure; the later parts will
// contain a pointer to the label layout structure of every internal event.
// There is no ordering on the events beyond interface first, internal second.
// The used_var_names field points to an array that contains offsets
// into the string table, with the offset at index i-1 giving the name of
// variable i (since variable numbers start at one). If a variable has no name
// or cannot be referred to from an event, the offset will be zero, at which
// offset the string table will contain an empty string.
// The max_named_var_num field gives the number of elements in the
// used_var_names table, which is also the number of the highest numbered
// named variable. Note that unnamed variables may have numbers higher than
// this.
// The max_r_num field tells the debugger which Mercury abstract machine
// registers need saving in MR_trace: besides the special registers, it is
// the general-purpose registers rN for values of N up to and including the
// value of this field. Note that this field contains an upper bound; in
// general, there will be calls to MR_trace at which the number of the highest
// numbered general purpose (i.e. rN) registers is less than this. However,
// storing the upper bound gets us almost all the benefit (of not saving and
// restoring all the thousand rN registers) for a small fraction of the static
// space cost of storing the actual number in label layout structures.
// If the procedure is compiled with deep tracing, the maybe_from_full field
// will contain a negative number. If it is compiled with shallow tracing,
// it will contain the number of the stack slot that holds the flag that says
// whether this incarnation of the procedure was called from deeply traced code
// or not. (The determinism of the procedure decides whether the stack slot
// refers to a stackvar or a framevar.)
// If tabling of I/O actions is enabled, the maybe_io_seq field will contain
// the number of the stack slot that holds the value the I/O action counter
// had on entry to this procedure. Even procedures that do not have I/O state
// arguments will have such a slot, since they or their descendants may call
// unsafe_perform_io.
// If trailing is not enabled, the maybe_trail field will contain a negative
// number. If it is enabled, it will contain number of the first of two stack
// slots used for checkpointing the state of the trail on entry to the
// procedure. The first contains the trail pointer, the second the ticket.
// If the procedure lives on the nondet stack, or if it cannot create any
// temporary nondet stack frames, the maybe_maxfr field will contain a negative
// number. If it lives on the det stack, and can create temporary nondet stack
// frames, it will contain the number number of the stack slot that contains the
// value of maxfr on entry, for use in executing the retry debugger command
// from the middle of the procedure.
// The eval_method field contains a representation of the evaluation method
// used by the procedure. The retry command needs this information if it is
// to reset the call tables of the procedure invocations being retried.
// We cannot put enums into structures as bit fields. To avoid wasting space,
// we put MR_EvalMethodInts into structures instead of MR_EvalMethods
// themselves.
// If the procedure is compiled with some form of tabling, the maybe_call_table
// field contains the number of the stack slot through which we can reach the
// call table entry for this call. In forms of tabling which associate a C
// structure (MR_Subgoal, MR_MemoNonRecord) with a call table entry, the slot
// will point to that structure; in other forms of tabling, it will point
// to the call's MR_TableNode.
// The flags field encodes boolean properties of the procedure. For now,
// the only property is whether the procedure has a pair of I/O state
// arguments.
// If the procedure lives on the nondet stack, or if it cannot create any
// temporary nondet stack frames, the maybe_maxfr field will contain a negative
// number. If it lives on the det stack, and can create temporary nondet stack
// frames, it will contain the number of the stack slot that contains the
// value of maxfr on entry, for use in executing the retry debugger command
// from the middle of the procedure.
#define <API key> MR_EVAL_METHOD_MEMO
#define <API key> MR_EVAL_METHOD_MEMO
#define <API key> MR_EVAL_METHOD_MEMO
typedef enum {
<API key>,
<API key>,
MR_EVAL_METHOD_MEMO,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>
} MR_EvalMethod;
typedef MR_int_least8_t MR_EvalMethodInt;
typedef enum {
<API key>(MR_TRACE_LEVEL_NONE),
<API key>(<API key>),
<API key>(<API key>),
<API key>(<API key>),
<API key>(MR_TRACE_LEVEL_DEEP),
<API key>(<API key>)
} MR_TraceLevel;
typedef MR_int_least8_t MR_TraceLevelInt;
typedef struct MR_ExecTrace_Struct {
const MR_LabelLayout *MR_exec_call_label;
const MR_ModuleLayout *<API key>;
const MR_LabelLayout **MR_exec_labels;
MR_uint_least32_t MR_exec_num_labels;
MR_TableInfo MR_exec_table_info;
const MR_uint_least16_t *<API key>;
const MR_uint_least32_t *<API key>;
MR_uint_least16_t <API key>;
MR_uint_least16_t <API key>;
MR_uint_least16_t MR_exec_max_r_num;
MR_uint_least16_t MR_exec_max_f_num;
MR_int_least8_t <API key>;
MR_int_least8_t <API key>;
MR_int_least8_t MR_exec_maybe_trail;
MR_int_least8_t MR_exec_maybe_maxfr;
MR_EvalMethodInt <API key>;
MR_int_least8_t <API key>;
MR_TraceLevelInt <API key>;
MR_uint_least8_t MR_exec_flags;
MR_int_least8_t <API key>;
} MR_ExecTrace;
#define <API key>(max_mr_num, layout) \
do { \
int max_r_num; \
\
max_r_num = (layout)->MR_sll_entry->MR_sle_max_r_num + \
MR_NUM_SPECIAL_REG; \
max_mr_num = MR_max(max_r_num, <API key>); \
} while (0)
// The code in the compiler that creates the flag field is
// <API key> in stack_layout.m.
#define <API key> 0x1
#define <API key> 0x2
#define <API key>(proc_layout, sp, reused_frames) \
do { \
const MR_ExecTrace *exec_trace; \
int tailrec_slot; \
\
exec_trace = proc_layout->MR_sle_exec_trace; \
if (exec_trace == NULL) { \
(reused_frames) = 0; \
} else { \
tailrec_slot = proc_layout-><API key>; \
if (tailrec_slot <= 0) { \
(reused_frames) = 0; \
} else { \
if (MR_DETISM_DET_STACK(proc_layout->MR_sle_detism)) { \
(reused_frames) = MR_based_stackvar((sp), tailrec_slot);\
} else { \
MR_fatal_error("tailrec reuses nondet stack frames"); \
} \
} \
} \
} while (0)
// Proc layout structures contain one, two or three substructures.
// - The first substructure is the MR_StackTraversal structure, which contains
// information that enables the stack to be traversed, e.g. for accurate gc.
// It is always present if proc layouts are present at all.
// - The second group is the MR_ProcId union, which identifies the
// procedure in terms that are meaningful to both humans and machines.
// It will be generated only if the module is compiled with stack tracing,
// execution tracing or profiling. The MR_ProcId union has two alternatives,
// one for user-defined procedures and one for procedures of the compiler
// generated Unify, Index and Compare predicates.
// - The third group is everything else. Currently, this consists of
// information that is of interest to the debugger, to the deep profiler,
// or both.
// The information that is of interest to the debugger only is stored in
// the MR_ExecTrace structure, which will be generated only if the module
// is compiled with execution tracing. The information that is of interest to
// the deep profiler is stored in the MR_ProcStatic structure, which will be
// generated only if the module is compiled in a deep profiling grade. The
// other fields in the group are of interest to both the debugger and the
// deep profiler, and will be generated if either execution tracing or deep
// profiling is enabled.
// If the body_bytes field is NULL, it means that no representation of the
// procedure body is available. If non-NULL, it contains a pointer to an
// array of bytecodes that represents the body of the procedure. The
// bytecode array should be interpreted by the read_proc_rep predicate in
// mdbcomp/<API key>.m (it starts with an encoded form of the
// array's length). Its contents are generated by compiler/prog_rep.m.
// The <API key> field points to the part of the module layout
// structure of the module containing the procedure that is common to the
// debugger and the deep profiler. Amongst other things, it gives access to
// the string table that the body_bytes fields refers to.
// The runtime system considers all proc layout structures to be of type
// MR_ProcLayout, but must use the macros defined below to check for the
// existence of each substructure before accessing the fields of that
// substructure. The macros are <API key> to check for the
// MR_ProcId substructure, <API key> to check for the
// MR_ExecTrace substructure, and <API key> to check for
// the MR_ProcStatic substructure.
// The reason why some substructures may be missing is to save space.
// If the options with which a module is compiled do not require execution
// tracing, then the MR_ExecTrace substructure will not present, and if the
// options do not require procedure identification, then the MR_ProcId
// substructure will not be present either. The body_bytes and module_layout
// fields cannot be non-NULL unless at least one of exec trace and proc static
// substructures is present, but they are otherwise independent of those
// substructures.
// The compiler itself generates proc layout structures using the following
// three types.
// - When generating only stack traversal information, the compiler will
// generate proc layout structures of type <API key>.
// - When generating stack traversal and procedure id information, plus
// possibly others, the compiler will generate proc layout structures of
// types MR_ProcLayoutUser and MR_ProcLayoutUCI.
struct <API key> {
MR_StackTraversal MR_sle_traversal;
MR_ProcId MR_sle_proc_id;
<API key> MR_ExecTrace *MR_sle_exec_trace;
MR_ProcStatic *MR_sle_proc_static;
const MR_uint_least8_t *MR_sle_body_bytes;
const MR_ModuleLayout *<API key>;
};
typedef struct <API key> {
MR_StackTraversal MR_user_traversal;
MR_UserProcId MR_user_id;
<API key> MR_ExecTrace *MR_sle_exec_trace;
MR_ProcStatic *MR_sle_proc_static;
const MR_uint_least8_t *MR_sle_body_bytes;
const MR_ModuleLayout *<API key>;
} MR_ProcLayoutUser;
typedef struct <API key> {
MR_StackTraversal MR_uci_traversal;
MR_UCIProcId MR_uci_id;
<API key> MR_ExecTrace *MR_sle_exec_trace;
MR_ProcStatic *MR_sle_proc_static;
const MR_uint_least8_t *MR_sle_body_bytes;
const MR_ModuleLayout *<API key>;
} MR_ProcLayoutUCI;
typedef struct <API key> {
MR_StackTraversal MR_trav_traversal;
MR_Word MR_trav_no_proc_id; // will be -1
} <API key>;
#define <API key>(entry) \
(MR_PROC_ID_EXISTS(entry->MR_sle_proc_id))
#define <API key>(entry) \
(<API key>(entry) && \
entry->MR_sle_exec_trace != NULL)
#define <API key>(entry) \
(<API key>(entry) && \
entry->MR_sle_proc_static != NULL)
#define <API key>(entry) \
(<API key>(entry) && \
( entry->MR_sle_exec_trace != NULL \
|| entry->MR_sle_proc_static != NULL))
#define MR_sle_code_addr MR_sle_traversal.MR_trav_code_addr
#define MR_sle_succip_locn MR_sle_traversal.MR_trav_succip_locn
#define MR_sle_stack_slots MR_sle_traversal.MR_trav_stack_slots
#define MR_sle_detism MR_sle_traversal.MR_trav_detism
#define MR_sle_user MR_sle_proc_id.MR_proc_user
#define MR_sle_uci MR_sle_proc_id.MR_proc_uci
#define MR_sle_call_label MR_sle_exec_trace->MR_exec_call_label
#define <API key> MR_sle_exec_trace-><API key>
#define MR_sle_labels MR_sle_exec_trace->MR_exec_labels
#define MR_sle_num_labels MR_sle_exec_trace->MR_exec_num_labels
#define <API key> MR_sle_exec_trace-><API key>
#define MR_sle_table_info MR_sle_exec_trace->MR_exec_table_info
#define <API key> MR_sle_exec_trace-><API key>
#define <API key> MR_sle_exec_trace-><API key>
#define <API key> MR_sle_exec_trace-><API key>
#define <API key> MR_sle_exec_trace-><API key>
#define MR_sle_max_r_num MR_sle_exec_trace->MR_exec_max_r_num
#define MR_sle_max_f_num MR_sle_exec_trace->MR_exec_max_f_num
#define <API key> MR_sle_exec_trace-><API key>
#define MR_sle_maybe_io_seq MR_sle_exec_trace-><API key>
#define MR_sle_maybe_trail MR_sle_exec_trace->MR_exec_maybe_trail
#define MR_sle_maybe_maxfr MR_sle_exec_trace->MR_exec_maybe_maxfr
#define <API key> MR_sle_exec_trace-><API key>
#define <API key> MR_sle_exec_trace-><API key>
#define <API key> MR_sle_exec_trace-><API key>
#define MR_sle_eval_method(proc_layout_ptr) \
((MR_EvalMethod) (proc_layout_ptr)-> \
MR_sle_exec_trace-><API key>)
#define MR_sle_trace_level(proc_layout_ptr) \
((MR_TraceLevel) (proc_layout_ptr)-> \
MR_sle_exec_trace-><API key>)
#define <API key>(proc_layout_ptr) \
((proc_layout_ptr)->MR_sle_exec_trace->MR_exec_flags \
& <API key>)
#define <API key>(proc_layout_ptr) \
((proc_layout_ptr)->MR_sle_exec_trace->MR_exec_flags \
& <API key>)
// Adjust the arity of functions for printing.
#define <API key>(entry) \
((entry)->MR_sle_user.MR_user_arity - \
(((entry)->MR_sle_user.<API key> == MR_FUNCTION) ? 1 : 0))
#define MR_MAX_VARNAME_SIZE 160
// Return the name (if any) of the variable with the given HLDS variable number
// in the procedure indicated by the first argument.
// The name will actually be found by <API key>, so the
// comments there about name size and should_copy apply here as well.
extern MR_ConstString MR_hlds_var_name(const MR_ProcLayout *entry,
int hlds_var_num, int *should_copy);
// Return the name (if any) of the variable with the given name code
// in the given string table.
// Sometimes, the returned name will point to static, const storage,
// whose contents are valid until the end of the program's execution,
// while at other times, it will point to a buffer whose contents
// will be valid only until the next call to <API key>.
// Callers that want to know which is the case should pass a non-NULL
// value for should_copy. The returned name will point to the buffer
// if and only if *should_copy is true. The size of the buffer is
// MR_MAX_VARNAME_SIZE bytes.
extern MR_ConstString <API key>(const char *string_table,
MR_Integer string_table_size,
MR_uint_least32_t name_code, int *should_copy);
// Given a string, see whether its end consists a sequence of digits.
// If yes, return the offset of the first digit in this sequence relative
// to the start of the string. Otherwise, return a negative number.
extern int <API key>(const char *str);
// Define a layout structure for a procedure, containing information
// for stack traversal and procedure identification.
// The slot count and the succip location parameters do not have to be
// supplied for procedures that live on the nondet stack, since for such
// procedures the size of the frame can be deduced from the prevfr field
// and the location of the succip is fixed.
// An unknown slot count should be signalled by <API key>.
// An unknown succip location should be signalled by <API key>.
// For the procedure identification, we always use the same module name
// for the defining and declaring modules, since procedures whose code
// is hand-written as C modules cannot be inlined in other Mercury modules.
// Due to the possibility that code addresses are not static, any use of
// the <API key> macro has to be accompanied by a call to the
// <API key> macro in the initialization code of the C module
// that defines the entry. (The cast in the body of <API key>
// is needed because compiler-generated layout structures may use any of the
// variant types listed above.)
#define <API key> -1
#ifdef <API key>
#define <API key>(entry) MR_ENTRY(entry)
#define <API key>(entry) do { } while (0)
#else
#define <API key>(entry) ((MR_Code *) NULL)
#define <API key>(entry) \
do { \
((MR_ProcLayout *) & \
MR_PASTE2(<API key>, entry)) \
->MR_sle_code_addr = MR_ENTRY(entry); \
} while (0)
#endif
#define <API key>(sc, detism, slots, succip_locn, \
pf, module, name, arity, mode, proc_static) \
MR_declare_entry(<API key>(module, name, \
arity, mode)); \
sc const MR_ProcLayoutUser \
<API key>(module, name, arity, mode) = { \
{ \
<API key>( \
<API key>(module, name, \
arity, mode)), \
succip_locn, \
slots, \
detism \
}, \
{ \
pf, \
MR_STRINGIFY(module), \
MR_STRINGIFY(module), \
MR_STRINGIFY(name), \
arity, \
mode \
}, \
NULL, \
(MR_ProcStatic *) proc_static \
}
#define <API key>(sc, detism, slots, succip_locn, \
module, name, type, arity, mode, proc_static) \
MR_declare_entry(<API key>(module, name, \
type, arity, mode)); \
sc const MR_ProcLayoutUCI \
<API key>(module, name, type, arity, mode) = { \
{ \
<API key>( \
<API key>(module, name, \
type, arity, mode)), \
succip_locn, \
slots, \
detism \
}, \
{ \
MR_STRINGIFY(type), \
MR_STRINGIFY(module), \
MR_STRINGIFY(module), \
MR_STRINGIFY(name), \
arity, \
mode \
}, \
NULL, \
(MR_ProcStatic *) proc_static \
}
#define MR_NO_EXTERN_DECL
#define <API key>(detism, slots, succip_locn, \
pf, module, name, arity, mode) \
<API key>(static, detism, slots, \
succip_locn, pf, module, name, arity, mode, \
&<API key>(module, name, arity, mode))
#define <API key>(detism, slots, succip_locn, \
pf, module, name, arity, mode) \
<API key>(MR_NO_EXTERN_DECL, detism, slots, \
succip_locn, pf, module, name, arity, mode, \
&<API key>(module, name, arity, mode))
#define <API key>(detism, slots, succip_locn, \
module, name, type, arity, mode) \
<API key>(static, detism, slots, \
succip_locn, module, name, type, arity, mode, \
&<API key>(module, name, type, arity, mode))
#define <API key>(detism, slots, succip_locn, \
module, name, type, arity, mode) \
<API key>(MR_NO_EXTERN_DECL, detism, slots, \
succip_locn, module, name, type, arity, mode, \
&<API key>(module, name, type, arity, mode))
#define <API key>(detism, slots, succip_locn, \
pf, module, name, arity, mode) \
<API key>(static, detism, slots, \
succip_locn, pf, module, name, arity, mode, NULL)
#define <API key>(detism, slots, succip_locn, \
pf, module, name, arity, mode) \
<API key>(MR_NO_EXTERN_DECL, detism, slots, \
succip_locn, pf, module, name, arity, mode, NULL)
#define <API key>(mod, n, a) \
const MR_ProcLayoutUCI \
<API key>(mod, __Unify__, n, a, 0); \
const MR_ProcLayoutUCI \
<API key>(mod, __Compare__, n, a, 0); \
const MR_ProcLayoutUCI \
<API key>(mod, __CompareRep__, n, a, 0);
// In procedures compiled with execution tracing, three items are stored
// in stack slots with fixed numbers. They are:
// the event number of the last event before the call event,
// the call number, and
// the call depth.
// Note that the first slot does not store the number of the call event
// itself, but rather the number of the call event minus one. The reason
// for this is that (a) incrementing the number stored in this slot would
// increase executable size, and (b) if the procedure is shallow traced,
// MR_trace may not be called for the call event, so we cannot shift the
// burden of initializing fields to the MR_trace of the call event either.
// The following macros will access the fixed slots. They can be used whenever
// <API key>(entry) is true; which set you should use
// depends on the determinism of the procedure.
// These macros have to be kept in sync with compiler/trace.m.
#define <API key>(base_curfr) MR_based_framevar(base_curfr, 1)
#define <API key>(base_curfr) MR_based_framevar(base_curfr, 2)
#define <API key>(base_curfr) MR_based_framevar(base_curfr, 3)
#define <API key>(base_sp) MR_based_stackvar(base_sp, 1)
#define <API key>(base_sp) MR_based_stackvar(base_sp, 2)
#define <API key>(base_sp) MR_based_stackvar(base_sp, 3)
// In model_non procedures compiled with --trace-redo, one or two other items
// are stored in fixed stack slots. These are
// the address of the layout structure for the redo event
// the saved copy of the from-full flag (only if trace level is shallow)
// The following macros will access these slots. They should be used only from
// within the code that calls MR_trace for the REDO event.
// This macros have to be kept in sync with compiler/trace.m.
#define <API key>(base_curfr) MR_based_framevar(base_curfr, 4)
#define <API key>(base_curfr) MR_based_framevar(base_curfr, 5)
// Definitions for MR_ModuleLayout.
// The layout structure for a module contains the following fields.
// The MR_ml_name field contains the name of the module.
// The MR_ml_string_table field contains the module's string table, which
// contains strings referred to by other layout structures in the module
// (initially only the tables containing variables names, referred to from
// label layout structures). The <API key> field gives the size
// of the table in bytes.
// The MR_ml_procs field points to an array containing pointers to the proc
// layout structures of all the procedures in the module; the MR_ml_proc_count
// field gives the number of entries in the array.
// The <API key> field points to an array of N file layout
// pointers if the module has labels corresponding to contexts that refer
// to the names of N files. For each file, the table gives its name, the
// number of labels in that file in this module, and for each such label,
// it gives its line number and a pointer to its label layout struct.
// The corresponding elements of the label_lineno and label_layout arrays
// refer to the same label. (The reason why they are not stored together
// is space efficiency; adding a 16 bit field to a label layout structure would
// require padding.) The labels are sorted on line number.
// The MR_ml_trace_level field gives the trace level that the module was
// compiled with. If the MR_TraceLevel enum is modified, then the
// corresponding function in compiler/trace_params.m must also be updated.
// The <API key> events field encodes the set of event types
// (ports) that were suppressed when generating code for this module. The bit
// given by the expression (1 << MR_PORT_<PORTTYPE>) will be set in this
// integer iff trace port MR_PORT_<PORTTYPE> is suppressed.
// The <API key> field points to an array of integers, with each
// integer holding the number of times execution has reached a given label.
// Each label's layout structure records the index of that label in this array.
// The most direct way to go the other way, to find out which label owns a
// particular slot in this array, is to search the label arrays in the file
// layout structures, and test their <API key> fields.
// (If we needed faster access, we could add another array with elements
// corresponding to <API key>'s pointing to the labels' layout
// structures.)
// The <API key> field contains the number of elements
// in the <API key> array.
typedef struct <API key> {
MR_ConstString MR_mfl_filename;
MR_Integer MR_mfl_label_count;
// The following fields point to arrays of size MR_mfl_label_count.
const MR_int_least16_t *MR_mfl_label_lineno;
const MR_LabelLayout **MR_mfl_label_layout;
} MR_ModuleFileLayout;
// The version of the data structures in this file -- useful for bootstrapping.
// If you write runtime code that checks this version number and can at least
// handle the previous version of the data structure, it makes it easier to
// bootstrap changes to these data structures.
// This number should be kept in sync with <API key> in
// compiler/layout_out.m.
#define MR_LAYOUT_VERSION <API key>
#define <API key> 1
#define <API key> 2
#define <API key> 3
#define <API key> 4
#define <API key> 5
struct <API key> {
// The fields that are of interest to both deep profiling and debugging.
MR_uint_least8_t <API key>;
MR_ConstString MR_ml_name;
MR_Integer <API key>;
const char *MR_ml_string_table;
// The fields that are of interest only to deep profiling.
MR_Integer <API key>;
const MR_uint_least8_t *MR_ml_oisu_bytes;
MR_Integer <API key>;
const MR_uint_least8_t *<API key>;
// The fields that are of interest only to debugging.
MR_Integer MR_ml_proc_count;
const MR_ProcLayout **MR_ml_procs;
MR_Integer <API key>;
const MR_ModuleFileLayout **<API key>;
MR_TraceLevel MR_ml_trace_level;
MR_int_least32_t <API key>;
MR_int_least32_t <API key>;
MR_Unsigned *<API key>;
const char *<API key>;
const char *<API key>;
MR_int_least16_t <API key>;
MR_int_least16_t <API key>;
MR_UserEventSpec *<API key>;
};
// Definitions for MR_ClosureId.
// Each closure contains an MR_ClosureId structure. The proc_id field
// identifies the procedure called by the closure. The other fields identify
// the context where the closure was created.
// The compiler generates closure id structures as either MR_UserClosureId
// or MR_UCIClosureId structures in order to avoid initializing the
// MR_ProcId union through an inappropriate member.
struct MR_ClosureId_Struct {
MR_ProcId MR_closure_proc_id;
MR_ConstString <API key>;
MR_ConstString <API key>;
MR_Integer <API key>;
MR_ConstString <API key>;
};
struct <API key> {
MR_UserProcId <API key>;
MR_ConstString <API key>;
MR_ConstString <API key>;
MR_Integer <API key>;
MR_ConstString <API key>;
};
struct <API key> {
MR_UCIProcId <API key>;
MR_ConstString <API key>;
MR_ConstString <API key>;
MR_Integer <API key>;
MR_ConstString <API key>;
};
#endif // not <API key>
|
<?php
// flush output buffer
die(json_encode(array(
'variables' => $variables,
'content' => render($page['content']) . render($page['content_bottom']),
)));
?>
|
<?php
$logo = get_option('custom_logo', <API key> . 'style/img/logo-dark.png');
$logo_light = get_option('custom_logo_light', <API key> . 'style/img/logo-light.png');
?>
<div class="nav-container">
<a id="top"></a>
<nav class="nav-centered">
<?php get_template_part('inc/content-header','utility'); ?>
<div class="text-center">
<a href="<?php echo esc_url(home_url('/')); ?>">
<img class="logo logo-light" alt="<?php echo esc_attr(get_bloginfo('title')); ?>" src="<?php echo esc_url($logo_light); ?>" />
<img class="logo logo-dark" alt="<?php echo esc_attr(get_bloginfo('title')); ?>" src="<?php echo esc_url($logo); ?>" />
</a>
</div>
<div class="nav-bar text-center">
<div class="module widget-handle mobile-toggle right visible-sm visible-xs">
<i class="ti-menu"></i>
</div>
<div class="module-group text-left">
<div class="module left">
<?php
if ( has_nav_menu( 'primary' ) ){
wp_nav_menu(
array(
'theme_location' => 'primary',
'depth' => 3,
'container' => false,
'container_class' => false,
'menu_class' => 'menu',
'fallback_cb' => '<API key>::fallback',
'walker' => new <API key>()
)
);
} else {
echo '<ul class="menu"><li><a href="'. admin_url('nav-menus.php') .'">Set up a navigation menu now</a></li></ul>';
}
?>
</div>
<?php
if( 'yes' == get_option('<API key>', 'no') ){
get_template_part('inc/content-header', 'social');
}
if( 'yes' == get_option('<API key>', 'no') ){
get_template_part('inc/content-header', 'button');
}
if( 'yes' == get_option('<API key>', 'yes') ){
get_template_part('inc/content-header', 'search');
}
if( class_exists('Woocommerce') && 'yes' == get_option('foundry_header_cart', 'yes') ){
get_template_part('inc/content-header', 'cart');
}
if( function_exists('icl_get_languages') && 'yes' == get_option('foundry_header_wpml', 'yes') ){
get_template_part('inc/content-header', 'wpml');
}
?>
</div>
</div>
</nav>
</div>
|
/**
*
* Apply your custom CSS here
*
*/
body {
}
a {
}
.page-body.skin-white .sidebar-menu .main-menu li.has-sub>a:before {
color: #666;
}
/*navbar*/
.navbar.horizontal-menu.navbar-minimal.navbar-fixed-top+.page-container>div>.sidebar-menu.fixed .sidebar-menu-inner{
top: 55px;
}
/*validate forms*/
form .form-group.validate-has-error .form-control + div {
display: block;
padding-top: 5px;
font-size: 12px;
color: #cc3f44;
}
form .form-group.validate-has-error .input-group + div {
display: block;
padding-top: 5px;
font-size: 12px;
color: #cc3f44;
}
form .form-group.validate-has-error .ui-select-container + div {
display: block;
padding-top: 5px;
font-size: 12px;
color: #cc3f44;
}
.ui-select-bootstrap button{
color: #333;
background-color: #fff;
border-color: #ccc;
}
|
<?php
$words = new MOD_words();
?>
<div id="tour">
<h1><?php echo $words->get('tour_maps')?></h1>
<h2><?php echo $words->getFormatted('tour_maps_title1')?></h2>
<p><?php echo $words->getFormatted('tour_maps_text1')?></p>
<div class="floatbox">
<img src="images/tour/map2.png" class="float_left" alt="maps" />
<h2><?php echo $words->getFormatted('tour_maps_title2')?></h2>
<p><?php echo $words->getFormatted('tour_maps_text2')?></p>
</div>
<h2><?php echo $words->getFormatted('tour_maps_title3')?></h2>
<p><?php echo $words->getFormatted('tour_maps_text3')?></p>
<h2><a class="bigbutton" href="tour/openness" onclick="this.blur();" style="margin-bottom: 20px"><span><?php echo $words->getFormatted('tour_goNext')?> »</span></a> <?php echo $words->getFormatted('tour_openness')?></h2>
</div>
|
package app.toonido.mindorks.toonido;
import android.app.Application;
import com.parse.Parse;
public class ToonidoApp extends Application {
@Override
public void onCreate() {
super.onCreate();
// Enable Local Datastore.
Parse.<API key>(this);
Parse.initialize(this, ToonidoConstants.<API key>, ToonidoConstants.PARSE_CLIENT_KEY);
}
}
|
/*
* In append_type: added generic register names support
* Alexey Pavluchenko, 16.Nov.2005
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "misc.h"
#include "args.h"
#include "avra.h"
#include "device.h"
/* Only Windows LIBC does support itoa, so we add this
function for other systems here manually. Thank you
Peter Hettkamp for your work. */
#ifndef WIN32
char * itoa(int num, char *str, const int number_format)
{
int num1 = num;
int num_chars = 0;
int pos;
while (num1>0)
{
num_chars++;
num1 /= number_format;
}
if (num_chars == 0)
num_chars = 1;
str[num_chars] = 0;
for (pos = num_chars-1; pos>=0; pos
{
int cur_char = num % number_format;
if (cur_char < 10) /* Insert number */
{
str[pos] = cur_char + '0';
}
else
{
str[pos] = cur_char-10 + 'A';
}
num /= number_format;
}
return(str);
}
#endif
int read_macro(struct prog_info *pi, char *name)
{
int loopok;
int i;
int start;
struct macro *macro;
struct macro_line *macro_line;
struct macro_line **last_macro_line = NULL;
struct macro_label *macro_label;
if (pi->pass == PASS_1)
{
if (!name)
{
print_msg(pi, MSGTYPE_ERROR, "missing macro name");
return(True);
}
get_next_token(name, TERM_END);
for (i = 0; !IS_END_OR_COMMENT(name[i]); i++)
{
if (!IS_LABEL(name[i]))
{
print_msg(pi, MSGTYPE_ERROR, "illegal characters used in macro name '%s'",name);
return(False);
}
}
macro = calloc(1, sizeof(struct macro));
if (!macro)
{
print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL);
return(False);
}
if (pi->last_macro)
pi->last_macro->next = macro;
else
pi->first_macro = macro;
pi->last_macro = macro;
macro->name = malloc(strlen(name) + 1);
if (!macro->name)
{
print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL);
return(False);
}
strcpy(macro->name, name);
macro->include_file = pi->fi->include_file;
macro->first_line_number = pi->fi->line_number;
last_macro_line = ¯o->first_macro_line;
}
else /* pi->pass == PASS_2 */
{
if (pi->list_line && pi->list_on)
{
fprintf(pi->list_file, " %s\n", pi->list_line);
pi->list_line = NULL;
}
// reset macro label running numbers
get_next_token(name, TERM_END);
macro = get_macro(pi, name);
if (!macro)
{
print_msg(pi, MSGTYPE_ERROR, "macro inconsistency in '%s'", name);
return(True);
}
for (macro_label = macro->first_label; macro_label; macro_label = macro_label->next)
{
macro_label->running_number = 0;
}
}
loopok = True;
while (loopok)
{
if (fgets_new(pi,pi->fi->buff, LINEBUFFER_LENGTH, pi->fi->fp))
{
pi->fi->line_number++;
i = 0;
while (IS_HOR_SPACE(pi->fi->buff[i]) && !IS_END_OR_COMMENT(pi->fi->buff[i]))
i++;
if (pi->fi->buff[i] == '.')
{
i++;
if (!nocase_strncmp(&pi->fi->buff[i], "endm", 4))
loopok = False;
if (!nocase_strncmp(&pi->fi->buff[i], "endmacro", 8))
loopok = False;
}
if (pi->pass == PASS_1)
{
if (loopok)
{
i = 0; /* find start of line */
while (IS_HOR_SPACE(pi->fi->buff[i]) && !IS_END_OR_COMMENT(pi->fi->buff[i]))
{
i++;
}
start = i;
/* find end of line */
while (!IS_END_OR_COMMENT(pi->fi->buff[i]) && (IS_LABEL(pi->fi->buff[i]) || pi->fi->buff[i] == ':'))
{
i++;
}
if (pi->fi->buff[i-1] == ':' && (pi->fi->buff[i-2] == '%'
&& (IS_HOR_SPACE(pi->fi->buff[i]) || IS_END_OR_COMMENT(pi->fi->buff[i]))))
{
if (macro->first_label)
{
for (macro_label = macro->first_label; macro_label->next; macro_label=macro_label->next)
{
}
macro_label->next = calloc(1,sizeof(struct macro_label));
macro_label = macro_label->next;
}
else
{
macro_label = calloc(1,sizeof(struct macro_label));
macro->first_label = macro_label;
}
macro_label->label = malloc(strlen(&pi->fi->buff[start])+1);
pi->fi->buff[i-1] = '\0';
strcpy(macro_label->label, &pi->fi->buff[start]);
pi->fi->buff[i-1] = ':';
macro_label->running_number = 0;
}
macro_line = calloc(1, sizeof(struct macro_line));
if (!macro_line)
{
print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL);
return(False);
}
*last_macro_line = macro_line;
last_macro_line = ¯o_line->next;
macro_line->line = malloc(strlen(pi->fi->buff) + 1);
if (!macro_line->line)
{
print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL);
return(False);
}
strcpy(macro_line->line, &pi->fi->buff[start]);
}
}
else if (pi->fi->buff && pi->list_file && pi->list_on)
{
if (pi->fi->buff[i] == ';')
fprintf(pi->list_file, " %s\n", pi->fi->buff);
else
fprintf(pi->list_file, " %s\n", pi->fi->buff);
}
}
else
{
if (feof(pi->fi->fp))
{
print_msg(pi, MSGTYPE_ERROR, "Found no closing .ENDMACRO");
return(True);
}
else
{
perror(pi->fi->include_file->name);
return(False);
}
}
}
return(True);
}
struct macro *get_macro(struct prog_info *pi, char *name)
{
struct macro *macro;
for (macro = pi->first_macro; macro; macro = macro->next)
if (!nocase_strcmp(macro->name, name))
return(macro);
return(NULL);
}
void append_type(struct prog_info *pi, char *name, int c, char *value)
{
int p, l;
struct def *def;
p = strlen(name);
name[p++] = '_';
if (c == 0)
{
name[p++] = 'v';
name[p] = '\0';
return;
}
l = strlen(value);
if ((l==2 || l==3) && (tolower(value[0])=='r') && isdigit(value[1]) && (l==3 ? isdigit(value[2]) : 1) && (atoi(&value[1])<32))
{
itoa((c*8),&name[p],10);
return;
}
for (def = pi->first_def; def; def = def->next)
if (!nocase_strcmp(def->name, value))
{
itoa((c*8),&name[p],10);
return;
}
name[p++] = 'i';
name[p] = '\0';
}
int expand_macro(struct prog_info *pi, struct macro *macro, char *rest_line)
{
int ok = True, macro_arg_count = 0, off, a, b = 0, c, i = 0, j = 0;
char *line = NULL;
char *temp;
char *macro_args[MAX_MACRO_ARGS];
char tmp[7];
char buff[LINEBUFFER_LENGTH];
char arg = False;
char *nmn; //string buffer for 'n'ew 'm'acro 'n'ame
struct macro_line *old_macro_line;
struct macro_call *macro_call;
struct macro_label *macro_label;
if (rest_line)
{
//we reserve some extra space for extended macro parameters
line = malloc(strlen(rest_line) + 20);
if (!line)
{
print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL);
return(False);
}
/* exchange amca word 'src' with YH:YL and 'dst' with ZH:ZL */
for (c = 0, a = strlen(rest_line); c < a; c++)
{
switch (tolower(rest_line[c]))
{
case 's':
if (IS_SEPARATOR(rest_line[c-1]) && (rest_line[c+1] == 'r') && (rest_line[c+2] == 'c') && IS_SEPARATOR(rest_line[c+3]))
{
strcpy(&line[b],"YH:YL");
b += 5;
c += 2;
}
else
{
line[b++] = rest_line[c];
}
break;
case 'd':
if (IS_SEPARATOR(rest_line[c-1]) && (rest_line[c+1] == 's') && (rest_line[c+2] == 't') && IS_SEPARATOR(rest_line[c+3]))
{
strcpy(&line[b],"ZH:ZL");
b += 5;
c += 2;
}
else
{
line[b++] = rest_line[c];
}
break;
// case ';':
// break;
default:
line[b++] = rest_line[c];
}
}
strcpy(&line[b],"\n"); /* set CR/LF at the end of the line */
/* here we split up the macro arguments into "macro_args"
* Extended macro code interpreter added by TW 2002
*/
temp = line;
/* test for advanced parameters */
if ( temp[0] == '[' ) // there must be "[" " then "]", else it is garbage
{
if (!strchr(temp, ']'))
{
print_msg(pi, MSGTYPE_ERROR, "found no closing ']'");
return(False);
}
// Okay now we are within the advanced code interpreter
temp++; // = &temp[1]; // skip the first bracket
nmn = malloc(LINEBUFFER_LENGTH);
if (!nmn)
{
print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL);
return(False);
}
strcpy(nmn,macro->name); // create a new macro name buffer
c = 1; // byte counter
arg = True; // loop flag
while (arg)
{
while (IS_HOR_SPACE(temp[0])) //skip leading spaces
{
temp++; // = &temp[1];
}
off = 0; // pointer offset
do
{
switch (temp[off]) //test current character code
{
case ':':
temp[off] = '\0';
if (off > 0)
{
c++;
macro_args[macro_arg_count++] = temp;
}
else
{
print_msg(pi, MSGTYPE_ERROR, "missing register before ':'",nmn);
return(False);
}
break;
case ']':
arg = False;
case ',':
a = off;
do
temp[a
while ( IS_HOR_SPACE(temp[a]) );
if (off > 0)
{
macro_args[macro_arg_count++] = temp;
append_type(pi, nmn, c, temp);
c = 1;
}
else
{
append_type(pi, nmn, 0, temp);
c = 1;
}
break;
default:
off++;
}
}
while (temp[off] != '\0');
if (arg)
temp = &temp[off+1];
else
break;
}
macro = get_macro(pi,nmn);
if (macro == NULL)
{
print_msg(pi, MSGTYPE_ERROR, "Macro %s is not defined !",nmn);
return(False);
}
free(nmn);
}
/* or else, we handle the macro as normal macro */
else
{
line = malloc(strlen(rest_line) + 1);
if (!line)
{
print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL);
return(False);
}
strcpy(line, rest_line);
temp = line;
while (temp)
{
macro_args[macro_arg_count++] = temp;
temp = get_next_token(temp, TERM_COMMA);
}
}
}
if (pi->pass == PASS_1)
{
macro_call = calloc(1, sizeof(struct macro_call));
if (!macro_call)
{
print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL);
return(False);
}
if (pi->last_macro_call)
pi->last_macro_call->next = macro_call;
else
pi->first_macro_call = macro_call;
pi->last_macro_call = macro_call;
macro_call->line_number = pi->fi->line_number;
macro_call->include_file = pi->fi->include_file;
macro_call->macro = macro;
macro_call->prev_on_stack = pi->macro_call;
if (macro_call->prev_on_stack)
{
macro_call->nest_level = macro_call->prev_on_stack->nest_level + 1;
macro_call->prev_line_index = macro_call->prev_on_stack->line_index;
}
}
else
{
for (macro_call = pi->first_macro_call; macro_call; macro_call = macro_call->next)
{
if ((macro_call->include_file->num == pi->fi->include_file->num) && (macro_call->line_number == pi->fi->line_number))
{
if (pi->macro_call)
{
/* Find correct macro_call when using recursion and nesting */
if (macro_call->prev_on_stack == pi->macro_call)
if ((macro_call->nest_level == (pi->macro_call->nest_level + 1)) && (macro_call->prev_line_index == pi->macro_call->line_index))
break;
}
else
break;
}
}
if (pi->list_line && pi->list_on)
{
fprintf(pi->list_file, "C:%06x + %s\n", pi->cseg_addr, pi->list_line);
pi->list_line = NULL;
}
}
macro_call->line_index = 0;
pi->macro_call = macro_call;
old_macro_line = pi->macro_line;
//printf("\nconvert macro: '%s'\n",macro->name);
for (pi->macro_line = macro->first_macro_line; pi->macro_line && ok; pi->macro_line = pi->macro_line->next)
{
macro_call->line_index++;
if (GET_ARG(pi->args, ARG_LISTMAC))
pi->list_line = buff;
else
pi->list_line = NULL;
/* here we change jumps/calls within macro that corresponds to macro labels.
Only in case there is an entry in macro_label list */
strcpy(buff,"\0");
macro_label = get_macro_label(pi->macro_line->line,macro);
if (macro_label)
{
/* test if the right macro label has been found */
temp = strstr(pi->macro_line->line,macro_label->label);
c = strlen(macro_label->label);
if (temp[c] == ':') /* it is a label definition */
{
macro_label->running_number++;
strncpy(buff, macro_label->label, c - 1);
buff[c - 1] = 0;
i = strlen(buff) + 2; /* we set the process indeafter label */
/* add running number to it */
strcpy(&buff[c-1],itoa(macro_label->running_number, tmp, 10));
strcat(buff, ":\0");
}
else if (IS_HOR_SPACE(temp[c]) || IS_END_OR_COMMENT(temp[c])) /* it is a jump to a macro defined label */
{
strcpy(buff,pi->macro_line->line);
temp = strstr(buff, macro_label->label);
i = temp - buff + strlen(macro_label->label);
strncpy(temp, macro_label->label, c - 1);
strcpy(&temp[c-1], itoa(macro_label->running_number, tmp, 10));
}
}
else
{
i = 0;
}
/* here we check every character of current line */
for (j = i; pi->macro_line->line[i] != '\0'; i++)
{
/* check for register place holders */
if (pi->macro_line->line[i] == '@')
{
i++;
if (!isdigit(pi->macro_line->line[i]))
print_msg(pi, MSGTYPE_ERROR, "@ must be followed by a number");
else if ((pi->macro_line->line[i] - '0') >= macro_arg_count)
print_msg(pi, MSGTYPE_ERROR, "Missing macro argument (for @%c)", pi->macro_line->line[i]);
else
{
/* and replace them with given registers */
strcat(&buff[j], macro_args[pi->macro_line->line[i] - '0']);
j += strlen(macro_args[pi->macro_line->line[i] - '0']);
}
}
else if (pi->macro_line->line[i] == ';')
{
strncat(buff, "\n", 1);
break;
}
else
{
strncat(buff, &pi->macro_line->line[i], 1);
}
}
ok = parse_line(pi, buff);
if (ok)
{
if ((pi->pass == PASS_2) && pi->list_line && pi->list_on)
fprintf(pi->list_file, " %s\n", pi->list_line);
if (pi->error_count >= pi->max_errors)
{
print_msg(pi, MSGTYPE_MESSAGE, "Maximum error count reached. Exiting...");
ok = False;
break;
}
}
}
pi->macro_line = old_macro_line;
pi->macro_call = macro_call->prev_on_stack;
if (rest_line)
free(line);
return(ok);
}
struct macro_label *get_macro_label(char *line, struct macro *macro)
{
char *temp;
struct macro_label *macro_label;
for (macro_label = macro->first_label; macro_label; macro_label = macro_label->next)
{
temp = strstr(line,macro_label->label);
if (temp)
{
return macro_label;
}
}
return NULL;
}
/* end of macro.c */
|
{% extends "base.html" %}
{% load staticfiles %}
{% block head_title %}{% block listing_head_title %}{% endblock %}{% endblock %}
{% block content %}
<div id="account" class="ui centered two column grid stackable container" style="margin-top: 20px;">
<div class="four wide column">
<div class="ui large one item menu">
<a href="{% url 'accounts:listings' %}" class="ui item">
<i class="ui arrow left icon"></i>
Back to Dashboard
</a>
</div>
<div class="ui large vertical fluid menu">
<div class="header center aligned item">
<div class="ui center aligned small header">
Listing Steps
</div>
</div>
<a href="{% url 'listings:<API key>' listing_id=listing.id %}" class=" {% if request.resolver_match.url_name == "<API key>" %}active{% endif %} item">
Description
{% if listing.<API key> %}
<i class="ui green checkmark icon"></i>
{% else %}
<i class="ui grey plus icon"></i>
{% endif %}
</a>
<a href="{% url 'listings:<API key>' listing_id=listing.id %}" class="{% if request.resolver_match.url_name == "<API key>" %}active{% endif %} item">
Location
{% if listing.location_complete %}
<i class="ui green checkmark icon"></i>
{% else %}
<i class="ui grey plus icon"></i>
{% endif %}
</a>
<a href="{% url 'listings:<API key>' listing_id=listing.id %}" class="{% if request.resolver_match.url_name == "<API key>" %}active{% endif %} item">
Details
{% if listing.details_complete %}
<i class="ui green checkmark icon"></i>
{% else %}
<i class="ui grey plus icon"></i>
{% endif %}
</a>
<a href="{% url 'listings:edit_listing_photos' listing_id=listing.id %}" class="{% if request.resolver_match.url_name == "edit_listing_photos" %}active{% endif %} item">
Photos
{% if listing.photos_complete %}
<i class="ui green checkmark icon"></i>
{% else %}
<i class="ui grey plus icon"></i>
{% endif %}
</a>
<a href="{% url 'listings:<API key>' listing_id=listing.id %}" class="{% if request.resolver_match.url_name == "<API key>" %}active{% endif %} item">
Calendar
{% if listing.calendar_complete %}
<i class="ui green checkmark icon"></i>
{% else %}
<i class="ui grey plus icon"></i>
{% endif %}
</a>
</div>
<div class="ui card">
<div class="content">
{% if listing.listing_complete %}
<div class="ui center aligned header">
Ready to publish!
</div>
<div class="description">
You are ready to publish your listing. Don't worry you can come back and edit it later.
</div>
{% elif listing.published %}
<div class="ui center aligned header">
Currently published
</div>
<div class="description">
This listing is currently published and publicly accessible. You can temporarily unpublish the listing.
</div>
{% else %}
<div class="ui center aligned header">
Steps remaining: {{ listing.steps_remaining }}
</div>
<div class="description">
To publish your listing complete the steps above. You can always come back and finish it later.
</div>
{% endif %}
</div>
<div class="extra content">
{% if listing.published %}
<a href="{% url "listings:unpublish_listing" listing_id=listing.id %}" class="ui orange button">Unpublish</a>
{% elif listing.listing_complete %}
<a href="{% url "listings:publish_listing" listing_id=listing.id %}" class="ui green button">Publish</a>
{% else %}
<div class="ui disabled button">Publish</div>
{% endif %}
<a href="{% url "listings:delete_listing" listing_id=listing.id %}" id="delete-listing" class="ui red delete button">Delete</a>
</div>
</div>
</div>
<div class="nine wide column">
{% block listing_content %}
{% endblock %}
</div>
</div>
<div id="confirm_delete" class="ui small modal">
<div class="header">
Delete listing
</div>
<div class="content">
<p>Are you sure you want to delete this listing? You will not be able to retrieve it if deleted.</p>
</div>
<div class="actions">
<div class="ui cancel button">
Cancel
</div>
<div class="ui negative approve right labeled icon button">
Yes
<i class="remove icon"></i>
</div>
</div>
</div>
{% endblock %}
{% block scripts %}
{% block listing_scripts %}
{% endblock %}
<script type="text/javascript">
$('#delete-listing').click(function(){
event.preventDefault();
var deleteLink = $(this).attr("href");
var row = $(this).parents('.ui.row');
var divider = row.prev('.divider');
$('#confirm_delete').modal({
onApprove : function() {
$.get(deleteLink);
divider.hide("medium", function() {
$(this).remove();
});
row.hide("medium", function() {
$(this).remove();
});
}
})
.modal('show');
});
</script>
{% endblock %}
|
#define DEBUG
#include <linux/types.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/kernel.h>
#include <linux/syscalls.h>
#include <linux/stackprotector.h>
#include <linux/string.h>
#include <linux/ctype.h>
#include <linux/delay.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/initrd.h>
#include <linux/bootmem.h>
#include <linux/acpi.h>
#include <linux/tty.h>
#include <linux/percpu.h>
#include <linux/kmod.h>
#include <linux/vmalloc.h>
#include <linux/kernel_stat.h>
#include <linux/start_kernel.h>
#include <linux/security.h>
#include <linux/smp.h>
#include <linux/profile.h>
#include <linux/rcupdate.h>
#include <linux/moduleparam.h>
#include <linux/kallsyms.h>
#include <linux/writeback.h>
#include <linux/cpu.h>
#include <linux/cpuset.h>
#include <linux/cgroup.h>
#include <linux/efi.h>
#include <linux/tick.h>
#include <linux/interrupt.h>
#include <linux/taskstats_kern.h>
#include <linux/delayacct.h>
#include <linux/unistd.h>
#include <linux/rmap.h>
#include <linux/mempolicy.h>
#include <linux/key.h>
#include <linux/buffer_head.h>
#include <linux/page_cgroup.h>
#include <linux/debug_locks.h>
#include <linux/debugobjects.h>
#include <linux/lockdep.h>
#include <linux/kmemleak.h>
#include <linux/pid_namespace.h>
#include <linux/device.h>
#include <linux/kthread.h>
#include <linux/sched.h>
#include <linux/signal.h>
#include <linux/idr.h>
#include <linux/kgdb.h>
#include <linux/ftrace.h>
#include <linux/async.h>
#include <linux/kmemcheck.h>
#include <linux/sfi.h>
#include <linux/shmem_fs.h>
#include <linux/slab.h>
#include <linux/perf_event.h>
#include <linux/file.h>
#include <linux/ptrace.h>
#include <linux/blkdev.h>
#include <linux/elevator.h>
#include <linux/sched_clock.h>
#include <linux/random.h>
#include <asm/io.h>
#include <asm/bugs.h>
#include <asm/setup.h>
#include <asm/sections.h>
#include <asm/cacheflush.h>
#ifdef <API key>
#include <asm/smp.h>
#endif
#ifdef <API key>
#include <linux/msm_rtb.h>
#endif
static int kernel_init(void *);
extern void init_IRQ(void);
extern void fork_init(unsigned long);
extern void mca_init(void);
extern void sbus_init(void);
extern void radix_tree_init(void);
#ifndef CONFIG_DEBUG_RODATA
static inline void mark_rodata_ro(void) { }
#endif
#ifdef CONFIG_TC
extern void tc_init(void);
#endif
bool <API key> __read_mostly;
enum system_states system_state __read_mostly;
EXPORT_SYMBOL(system_state);
#define MAX_INIT_ARGS <API key>
#define MAX_INIT_ENVS <API key>
extern void time_init(void);
void (*__initdata late_time_init)(void);
extern void softirq_init(void);
char __initdata boot_command_line[COMMAND_LINE_SIZE];
char *saved_command_line;
char *hashed_command_line;
static char *static_command_line;
static char *execute_command;
static char *<API key>;
unsigned int reset_devices;
EXPORT_SYMBOL(reset_devices);
static int __init set_reset_devices(char *str)
{
reset_devices = 1;
return 1;
}
__setup("reset_devices", set_reset_devices);
static const char * argv_init[MAX_INIT_ARGS+2] = { "init", NULL, };
const char * envp_init[MAX_INIT_ENVS+2] = { "HOME=/", "TERM=linux", NULL, };
static const char *panic_later, *panic_param;
extern const struct obs_kernel_param __setup_start[], __setup_end[];
static int __init obsolete_checksetup(char *line)
{
const struct obs_kernel_param *p;
int had_early_param = 0;
p = __setup_start;
do {
int n = strlen(p->str);
if (parameqn(line, p->str, n)) {
if (p->early) {
if (line[n] == '\0' || line[n] == '=')
had_early_param = 1;
} else if (!p->setup_func) {
pr_warn("Parameter %s is obsolete, ignored\n",
p->str);
return 1;
} else if (p->setup_func(line + n))
return 1;
}
p++;
} while (p < __setup_end);
return had_early_param;
}
unsigned long loops_per_jiffy = (1<<12);
EXPORT_SYMBOL(loops_per_jiffy);
static int __init debug_kernel(char *str)
{
console_loglevel = 10;
return 0;
}
static int __init quiet_kernel(char *str)
{
console_loglevel = 4;
return 0;
}
early_param("debug", debug_kernel);
early_param("quiet", quiet_kernel);
static int __init loglevel(char *str)
{
int newlevel;
if (get_option(&str, &newlevel)) {
console_loglevel = newlevel;
return 0;
}
return -EINVAL;
}
early_param("loglevel", loglevel);
static int __init repair_env_string(char *param, char *val, const char *unused)
{
if (val) {
if (val == param+strlen(param)+1)
val[-1] = '=';
else if (val == param+strlen(param)+2) {
val[-2] = '=';
memmove(val-1, val, strlen(val)+1);
val
} else
BUG();
}
return 0;
}
static int __init unknown_bootoption(char *param, char *val, const char *unused)
{
repair_env_string(param, val, unused);
if (obsolete_checksetup(param))
return 0;
if (strchr(param, '.') && (!val || strchr(param, '.') < val))
return 0;
if (panic_later)
return 0;
if (val) {
unsigned int i;
for (i = 0; envp_init[i]; i++) {
if (i == MAX_INIT_ENVS) {
panic_later = "Too many boot env vars at `%s'";
panic_param = param;
}
if (!strncmp(param, envp_init[i], val - param))
break;
}
envp_init[i] = param;
} else {
unsigned int i;
for (i = 0; argv_init[i]; i++) {
if (i == MAX_INIT_ARGS) {
panic_later = "Too many boot init vars at `%s'";
panic_param = param;
}
}
argv_init[i] = param;
}
return 0;
}
static int __init init_setup(char *str)
{
unsigned int i;
execute_command = str;
for (i = 1; i < MAX_INIT_ARGS; i++)
argv_init[i] = NULL;
return 1;
}
__setup("init=", init_setup);
static int __init rdinit_setup(char *str)
{
unsigned int i;
<API key> = str;
for (i = 1; i < MAX_INIT_ARGS; i++)
argv_init[i] = NULL;
return 1;
}
__setup("rdinit=", rdinit_setup);
#ifndef CONFIG_SMP
static const unsigned int setup_max_cpus = NR_CPUS;
#ifdef <API key>
static void __init smp_init(void)
{
<API key>();
}
#else
#define smp_init() do { } while (0)
#endif
static inline void setup_nr_cpu_ids(void) { }
static inline void smp_prepare_cpus(unsigned int maxcpus) { }
#endif
static void __init setup_command_line(char *command_line)
{
saved_command_line = alloc_bootmem(strlen (boot_command_line)+1);
static_command_line = alloc_bootmem(strlen (command_line)+1);
strcpy (saved_command_line, boot_command_line);
strcpy (static_command_line, command_line);
}
#define RAW_SN_LEN 4
static void __init hash_sn(void)
{
char *p;
unsigned int td_sf = 0;
size_t cmdline_len, sf_len;
cmdline_len = strlen(saved_command_line);
sf_len = strlen("td.sf=");
hashed_command_line = alloc_bootmem(cmdline_len + 1);
strncpy(hashed_command_line, saved_command_line, cmdline_len);
hashed_command_line[cmdline_len] = '\0';
p = saved_command_line;
for (p = saved_command_line; p < saved_command_line + cmdline_len - sf_len; p++) {
if (!strncmp(p, "td.sf=", sf_len)) {
p += sf_len;
if (*p != '0')
td_sf = 1;
break;
}
}
if (td_sf) {
unsigned int i;
size_t sn_len = 0;
for (p = hashed_command_line; p < hashed_command_line + cmdline_len - strlen("androidboot.serialno="); p++) {
if (!strncmp(p, "androidboot.serialno=", strlen("androidboot.serialno="))) {
p += strlen("androidboot.serialno=");
while (*p != ' ' && *p != '\0') {
sn_len++;
p++;
}
p -= sn_len;
for (i = sn_len - 1; i >= RAW_SN_LEN; i
*p++ = '*';
break;
}
}
}
}
static __initdata DECLARE_COMPLETION(kthreadd_done);
static noinline void __init_refok rest_init(void)
{
int pid;
const struct sched_param param = { .sched_priority = 1 };
<API key>();
kernel_thread(kernel_init, NULL, CLONE_FS | CLONE_SIGHAND);
numa_default_policy();
pid = kernel_thread(kthreadd, NULL, CLONE_FS | CLONE_FILES);
rcu_read_lock();
kthreadd_task = find_task_by_pid_ns(pid, &init_pid_ns);
rcu_read_unlock();
<API key>(kthreadd_task, SCHED_FIFO, ¶m);
complete(&kthreadd_done);
<API key>(current);
<API key>();
cpu_startup_entry(CPUHP_ONLINE);
}
static int __init do_early_param(char *param, char *val, const char *unused)
{
const struct obs_kernel_param *p;
for (p = __setup_start; p < __setup_end; p++) {
if ((p->early && parameq(param, p->str)) ||
(strcmp(param, "console") == 0 &&
strcmp(p->str, "earlycon") == 0)
) {
if (p->setup_func(val) != 0)
pr_warn("Malformed early option '%s'\n", param);
}
}
return 0;
}
void __init parse_early_options(char *cmdline)
{
parse_args("early options", cmdline, NULL, 0, 0, 0, do_early_param);
}
void __init parse_early_param(void)
{
#if defined(CONFIG_EARLY_PRINTK)
void <API key>(void);
#endif
static __initdata int done = 0;
static __initdata char tmp_cmdline[COMMAND_LINE_SIZE];
if (done)
return;
strlcpy(tmp_cmdline, boot_command_line, COMMAND_LINE_SIZE);
parse_early_options(tmp_cmdline);
done = 1;
#if defined(CONFIG_EARLY_PRINTK)
<API key>();
#endif
}
static void __init boot_cpu_init(void)
{
int cpu = smp_processor_id();
set_cpu_online(cpu, true);
set_cpu_active(cpu, true);
set_cpu_present(cpu, true);
set_cpu_possible(cpu, true);
}
void __init __weak <API key>(void)
{
}
# if THREAD_SIZE >= PAGE_SIZE
void __init __weak <API key>(void)
{
}
#endif
static void __init mm_init(void)
{
<API key>();
mem_init();
kmem_cache_init();
percpu_init_late();
pgtable_cache_init();
vmalloc_init();
}
asmlinkage void __init start_kernel(void)
{
char * command_line;
extern const struct kernel_param __start___param[], __stop___param[];
lockdep_init();
<API key>();
<API key>();
cgroup_init_early();
local_irq_disable();
<API key> = true;
boot_cpu_init();
page_address_init();
pr_notice("%s", linux_banner);
setup_arch(&command_line);
<API key>();
mm_init_owner(&init_mm, &init_task);
mm_init_cpumask(&init_mm);
setup_command_line(command_line);
hash_sn();
setup_nr_cpu_ids();
setup_per_cpu_areas();
<API key>();
build_all_zonelists(NULL, NULL);
page_alloc_init();
pr_notice("Kernel command line: %s\n", hashed_command_line);
parse_early_param();
parse_args("Booting kernel", static_command_line, __start___param,
__stop___param - __start___param,
-1, -1, &unknown_bootoption);
jump_label_init();
setup_log_buf(0);
pidhash_init();
<API key>();
sort_main_extable();
trap_init();
mm_init();
sched_init();
preempt_disable();
if (WARN(!irqs_disabled(), "Interrupts were enabled *very* early, fixing it\n"))
local_irq_disable();
idr_init_cache();
perf_event_init();
rcu_init();
tick_nohz_init();
radix_tree_init();
early_irq_init();
init_IRQ();
tick_init();
init_timers();
hrtimers_init();
softirq_init();
timekeeping_init();
time_init();
<API key>();
profile_init();
call_function_init();
WARN(!irqs_disabled(), "Interrupts were enabled early\n");
<API key> = false;
local_irq_enable();
<API key>();
console_init();
if (panic_later)
panic(panic_later, panic_param);
lockdep_info();
locking_selftest();
#ifdef <API key>
if (initrd_start && !<API key> &&
page_to_pfn(virt_to_page((void *)initrd_start)) < min_low_pfn) {
pr_crit("initrd overwritten (0x%08lx < 0x%08lx) - disabling it.\n",
page_to_pfn(virt_to_page((void *)initrd_start)),
min_low_pfn);
initrd_start = 0;
}
#endif
page_cgroup_init();
<API key>();
kmemleak_init();
<API key>();
numa_policy_init();
if (late_time_init)
late_time_init();
sched_clock_init();
calibrate_delay();
pidmap_init();
anon_vma_init();
#ifdef CONFIG_X86
if (efi_enabled(<API key>))
<API key>();
#endif
#ifdef CONFIG_X86_ESPFIX64
init_espfix_bsp();
#endif
<API key>();
cred_init();
fork_init(totalram_pages);
proc_caches_init();
buffer_init();
key_init();
security_init();
dbg_late_init();
vfs_caches_init(totalram_pages);
signals_init();
page_writeback_init();
#ifdef CONFIG_PROC_FS
proc_root_init();
#endif
cgroup_init();
cpuset_init();
<API key>();
delayacct_init();
check_bugs();
acpi_early_init();
sfi_init_late();
if (efi_enabled(<API key>)) {
efi_late_init();
<API key>();
}
ftrace_init();
rest_init();
}
static void __init do_ctors(void)
{
#ifdef CONFIG_CONSTRUCTORS
ctor_fn_t *fn = (ctor_fn_t *) __ctors_start;
for (; fn < (ctor_fn_t *) __ctors_end; fn++)
(*fn)();
#endif
}
bool initcall_debug;
core_param(initcall_debug, initcall_debug, bool, 0644);
static char msgbuf[64];
static int __init_or_module <API key>(initcall_t fn)
{
ktime_t calltime, delta, rettime;
unsigned long long duration;
int ret;
pr_debug("calling %pF @ %i\n", fn, task_pid_nr(current));
calltime = ktime_get();
ret = fn();
rettime = ktime_get();
delta = ktime_sub(rettime, calltime);
duration = (unsigned long long) ktime_to_ns(delta) >> 10;
pr_debug("initcall %pF returned %d after %lld usecs\n",
fn, ret, duration);
return ret;
}
int __init_or_module do_one_initcall(initcall_t fn)
{
int count = preempt_count();
int ret;
#ifdef <API key>
uncached_logk_pc(LOGK_INITCALL, (void *)fn, (void *)(0x00000000));
#endif
if (initcall_debug)
ret = <API key>(fn);
else
ret = fn();
#ifdef <API key>
uncached_logk_pc(LOGK_INITCALL, (void *)fn, (void *)(0xffffffff));
#endif
msgbuf[0] = 0;
if (preempt_count() != count) {
sprintf(msgbuf, "preemption imbalance ");
preempt_count() = count;
}
if (irqs_disabled()) {
strlcat(msgbuf, "disabled interrupts ", sizeof(msgbuf));
local_irq_enable();
}
WARN(msgbuf[0], "initcall %pF returned with %s\n", fn, msgbuf);
return ret;
}
extern initcall_t __initcall_start[];
extern initcall_t __initcall0_start[];
extern initcall_t __initcall1_start[];
extern initcall_t __initcall2_start[];
extern initcall_t __initcall3_start[];
extern initcall_t __initcall4_start[];
extern initcall_t __initcall5_start[];
extern initcall_t __initcall6_start[];
extern initcall_t __initcall7_start[];
extern initcall_t __initcall_end[];
static initcall_t *initcall_levels[] __initdata = {
__initcall0_start,
__initcall1_start,
__initcall2_start,
__initcall3_start,
__initcall4_start,
__initcall5_start,
__initcall6_start,
__initcall7_start,
__initcall_end,
};
static char *<API key>[] __initdata = {
"early",
"core",
"postcore",
"arch",
"subsys",
"fs",
"device",
"late",
};
static void __init do_initcall_level(int level)
{
extern const struct kernel_param __start___param[], __stop___param[];
initcall_t *fn;
strcpy(static_command_line, saved_command_line);
parse_args(<API key>[level],
static_command_line, __start___param,
__stop___param - __start___param,
level, level,
&repair_env_string);
for (fn = initcall_levels[level]; fn < initcall_levels[level+1]; fn++)
do_one_initcall(*fn);
}
static void __init do_initcalls(void)
{
int level;
for (level = 0; level < ARRAY_SIZE(initcall_levels) - 1; level++)
do_initcall_level(level);
}
static void __init do_basic_setup(void)
{
cpuset_init_smp();
usermodehelper_init();
shmem_init();
driver_init();
init_irq_proc();
do_ctors();
<API key>();
do_initcalls();
<API key>();
}
static void __init <API key>(void)
{
initcall_t *fn;
for (fn = __initcall_start; fn < __initcall0_start; fn++)
do_one_initcall(*fn);
}
void __init <API key>(void)
{
<API key>();
}
static int run_init_process(const char *init_filename)
{
argv_init[0] = init_filename;
return do_execve(init_filename,
(const char __user *const __user *)argv_init,
(const char __user *const __user *)envp_init);
}
static noinline void __init <API key>(void);
static int __ref kernel_init(void *unused)
{
<API key>();
<API key>();
free_initmem();
mark_rodata_ro();
system_state = SYSTEM_RUNNING;
numa_default_policy();
flush_delayed_fput();
if (<API key>) {
if (!run_init_process(<API key>))
return 0;
pr_err("Failed to execute %s\n", <API key>);
}
if (execute_command) {
if (!run_init_process(execute_command))
return 0;
pr_err("Failed to execute %s. Attempting defaults...\n",
execute_command);
}
if (!run_init_process("/sbin/init") ||
!run_init_process("/etc/init") ||
!run_init_process("/bin/init") ||
!run_init_process("/bin/sh"))
return 0;
panic("No init found. Try passing init= option to kernel. "
"See Linux Documentation/init.txt for guidance.");
}
static noinline void __init <API key>(void)
{
wait_for_completion(&kthreadd_done);
gfp_allowed_mask = __GFP_BITS_MASK;
set_mems_allowed(node_states[N_MEMORY]);
<API key>(current, cpu_all_mask);
cad_pid = task_pid(current);
smp_prepare_cpus(setup_max_cpus);
<API key>();
<API key>();
smp_init();
#ifdef <API key>
htc_early_rtb_init();
#endif
sched_init_smp();
do_basic_setup();
if (sys_open((const char __user *) "/dev/console", O_RDWR, 0) < 0)
pr_err("Warning: unable to open an initial console.\n");
(void) sys_dup(0);
(void) sys_dup(0);
if (!<API key>)
<API key> = "/init";
if (sys_access((const char __user *) <API key>, 0) != 0) {
<API key> = NULL;
prepare_namespace();
}
<API key>();
}
|
#ifndef <API key>
#define <API key>
#include <algorithm>
#include <vector>
#include "float"
#include "matrix"
#include "affine"
/* __BEGIN__BEGIN__ */
vector4F Affine2Quaternion(affine4F aff);
affine4F Quaternion2Affine(vector4F v, vector4F p);
class edge {
public:
short v0, v1;
short p0, p1;
};
class color4b
{
public:
typedef unsigned char element_t;
typedef unsigned char byte;
enum {
element_size = 4,
};
byte r, g, b, a;
inline color4b() {}
inline color4b(byte i, byte a=255) : r(i), g(i), b(i), a(a) {}
inline color4b(byte r, byte g, byte b, byte a=255) :
r(r), g(g), b(b), a(a) {}
byte* element_array() { return (byte*)this; }
const byte* element_array() const { return (byte*)this; }
void glBind() const { glColor4ubv((const GLubyte*)element_array()); }
};
class color4f
{
public:
typedef unsigned char element_t;
enum {
element_size = 4,
};
float r, g, b, a;
inline color4f() {}
inline color4f(int i, int a=255) : r(i/255.0F), g(i/255.0F), b(i/255.0F), a(a/255.0F) {}
inline color4f(int r, int g, int b, int a=255) :
r(r/255.0F), g(g/255.0F), b(b/255.0F), a(a/255.0F) {}
float* element_array() { return (float*)this; }
const float* element_array() const { return (float*)this; }
void glBind() const { glColor4fv(element_array()); }
};
class colormap
{
public:
typedef color4f color_t;
enum {
map_size = 256,
};
bool load(const char *file);
void fill(const color_t& c) {
std::fill(&map[0], &map[map_size], c);
}
inline color_t& operator [](int i) { return map[i]; }
inline const color_t& operator [](int i) const { return map[i]; }
public:
color_t map[map_size];
};
class polygon;
class polyhedron
{
public:
int numPoints, numPolygons, numEdges;
vector3F *points;
vector3F *texcoord;
short (*polygons)[4];
unsigned char *cindex;
vector3F (*normals)[4];
vector3F *planeNormal;
edge *edges;
char *filename;
GLuint texturename;
colormap cmap;
polyhedron(const char *filename);
~polyhedron();
polyhedron& operator *=(const affine4F &m); //normal vectors are destroyed
inline int polsize(int i) const { return (0 > polygons[i][3]) ? 3 : 4; }
polygon getPolygon(int i) const;
void getNormal();
protected:
void initColormap();
};
polygon access object
class polygon
{
friend class polyhedron;
protected:
inline polygon(const polyhedron& parent, int polynum)
: p(parent), num(polynum) {
size = (p.polygons[num][3] < 0) ? 3 : 4;
}
public:
inline int round(int idx) const { return (idx+size)%size; }
inline int pround(int idx) const { return idx%size; }
inline short ri(int idx) const { return p.polygons[num][idx]; }
inline short i(int idx) const { return p.polygons[num][round(idx)]; }
inline const vector3F& rv(int idx) const { return p.points[ri(idx)]; }
inline const vector3F& v(int idx) const { return p.points[i(idx)]; }
inline const vector3F& rst(int idx) const { return p.texcoord[ri(idx)]; }
inline const vector3F& st(int idx) const { return p.texcoord[i(idx)]; }
inline const vector3F& rn(int idx) const { return p.normals[num][idx]; }
inline const vector3F& n(int idx) const { return p.normals[num][round(idx)]; }
inline const vector3F& n(void) const { return p.planeNormal[num]; }
inline const unsigned char c() const { return p.cindex[num]; }
inline short getv(short vidx) const {
for (int k = 0; size > k; ++k) if (vidx == ri(k)) return k;
return -1;
}
inline short gete(const edge&e, int* way) const {
return gete(e.v0, e.v1, way);
}
inline short gete(short v0, short v1, int* way) const {
for (int k = 0; size > k; ++k) {
if (v0 == ri(k)) {
if (v1 == ri(pround(k+1))) {
*way = +1;
return k;
}
else if (v1 == i(k-1)) {
*way = -1;
return k;
}
}
}
return -1;
}
inline GLenum glBeginSize() const {
return (3 == size) ? GL_TRIANGLES : GL_QUADS;
}
public:
const polyhedron& p;
int num;
int size;
};
inline polygon polyhedron::getPolygon(int i) const {
return polygon(*this, i);
}
class affineanim {
public:
int numFrames;
affine4F *matrices;
affineanim(int num);
affineanim(const char *filename);
~affineanim();
inline const affine4F& operator[](int i) const {
return matrices[i];
}
inline affine4F& operator [](int i) {
return matrices[i];
}
};
class affinemotion {
public:
polyhedron ref;
affineanim anim;
affinemotion(const char *ref, const char *anim);
void write(const char *basename);
inline bool valid() const {
return ref.numPoints > 0 && anim.numFrames > 0;
}
};
class quaternionanim {
public:
int numFrames;
std::vector<vector4F> quaternions;
vector3F origin;
quaternionanim(int num);
quaternionanim(const char *filename);
~quaternionanim();
inline const vector4F& operator[](int i) const {
return quaternions[i];
}
inline const vector4F operator[](float i) const {
if ( i == (int)i ) {
return quaternions[(int)i];
} else {
vector4F q1 = quaternions[(int)i];
vector4F q2 = quaternions[(int)i+1];
if ( q1[1]*q2[1]+q1[2]*q2[2]+q1[3]*q2[3] < 0 )
q2 = -q2;
return q1*(1-(i-(int)i)) + q2*(i-(int)i);
}
}
inline vector4F& operator [](int i) {
return quaternions[i];
}
inline vector4F operator[](float i) {
if ( i == (int)i ) {
return quaternions[(int)i];
} else {
vector4F q1 = quaternions[(int)i];
vector4F q2 = quaternions[(int)i+1];
if ( q1[1]*q2[1]+q1[2]*q2[2]+q1[3]*q2[3] < 0 )
q2 = -q2;
return q1*(1-(i-(int)i)) + q2*(i-(int)i);
}
}
};
class quaternionmotion {
public:
polyhedron ref;
quaternionanim anim;
quaternionmotion(const char *ref, const char *anim);
//void write(const char *basename);
inline bool valid() const {
return ref.numPoints > 0 && anim.numFrames > 0;
}
};
class partsmotion
{
public:
int numParts;
static polyhedron **polyparts;
affineanim *origin;
quaternionanim **qanim;
partsmotion(const char *basename);
virtual ~partsmotion();
virtual bool render(int frame, float xdiff, float ydiff, float zdiff);
virtual bool render(double frame, float xdiff, float ydiff, float zdiff);
virtual bool renderWire(int frame, float xdiff, float ydiff, float zdiff);
virtual bool renderWire(double frame, float xdiff, float ydiff, float zdiff);
virtual bool renderArmOnly(double frame, float xdiff, float ydiff, float zdiff);
private:
void drawleg( float xdiff, float ydiff, float zdiff, bool isWireFrame );
void legIK( vector3F hip, vector3F &knee, vector3F &heel, vector3F toe,
float thighLength, float shinLength, float footSize,
bool isWireFrame );
void drawbody( vector3F neck, vector3F waist, bool isWireFrame );
void renderparts( int partsNum, bool isWireFrame );
};
/* __END__END__ */
#endif
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=windows-1252">
<TITLE></TITLE>
<META NAME="GENERATOR" CONTENT="OpenOffice 4.0.0 (Win32)">
<META NAME="AUTHOR" CONTENT="Jouni Santara">
<META NAME="CREATED" CONTENT="20140315;10351377">
<META NAME="CHANGEDBY" CONTENT="Jouni Santara">
<META NAME="CHANGED" CONTENT="20140321;11410882">
<STYLE>
<!
BODY,DIV,TABLE,THEAD,TBODY,TFOOT,TR,TH,TD,P { font-family:"Arial"; font-size:x-small }
</STYLE>
</HEAD>
<BODY TEXT="#000000">
<TABLE FRAME=VOID CELLSPACING=0 COLS=13 RULES=NONE BORDER=0>
<COLGROUP><COL WIDTH=125><COL WIDTH=82><COL WIDTH=121><COL WIDTH=100><COL WIDTH=86><COL WIDTH=129><COL WIDTH=51><COL WIDTH=52><COL WIDTH=55><COL WIDTH=104><COL WIDTH=67><COL WIDTH=80><COL WIDTH=86></COLGROUP>
<TBODY>
<TR>
<TD WIDTH=125 HEIGHT=24 ALIGN=LEFT><BR></TD>
<TD WIDTH=82 ALIGN=CENTER><BR></TD>
<TD WIDTH=121 ALIGN=CENTER><BR></TD>
<TD WIDTH=100 ALIGN=LEFT><U><FONT SIZE=4>Charts and their options</FONT></U></TD>
<TD WIDTH=86 ALIGN=CENTER><BR></TD>
<TD WIDTH=129 ALIGN=CENTER><BR></TD>
<TD WIDTH=51 ALIGN=CENTER><BR></TD>
<TD WIDTH=52 ALIGN=CENTER><BR></TD>
<TD WIDTH=55 ALIGN=CENTER><BR></TD>
<TD WIDTH=104 ALIGN=LEFT><BR></TD>
<TD WIDTH=67 ALIGN=LEFT><BR></TD>
<TD WIDTH=80 ALIGN=LEFT><BR></TD>
<TD WIDTH=86 ALIGN=LEFT><BR></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=LEFT><BR></TD>
<TD ALIGN=LEFT><BR></TD>
<TD ALIGN=LEFT><BR></TD>
<TD ALIGN=LEFT><BR></TD>
</TR>
<TR>
<TD HEIGHT=24 ALIGN=LEFT><B><FONT SIZE=4><BR></FONT></B></TD>
<TD ALIGN=LEFT>The following options (at least) are available from the different chart's types.</TD>
<TD ALIGN=LEFT><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=LEFT><BR></TD>
<TD ALIGN=LEFT><BR></TD>
<TD ALIGN=LEFT><BR></TD>
<TD ALIGN=LEFT><BR></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=CENTER><BR></TD>
<TD ALIGN=LEFT><BR></TD>
<TD ALIGN=LEFT><BR></TD>
<TD ALIGN=LEFT><BR></TD>
<TD ALIGN=LEFT><BR></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><BR></TD>
<TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000" ALIGN=LEFT><B><FONT COLOR="#808080">Chart Type</FONT></B></TD>
<TD STYLE="border-top: 1px solid #000000" ALIGN=CENTER><FONT COLOR="#808080"><BR></FONT></TD>
<TD STYLE="border-top: 1px solid #000000" ALIGN=CENTER><FONT COLOR="#808080"><BR></FONT></TD>
<TD STYLE="border-top: 1px solid #000000" ALIGN=CENTER><FONT COLOR="#808080"><BR></FONT></TD>
<TD STYLE="border-top: 1px solid #000000" ALIGN=CENTER><FONT COLOR="#808080"><BR></FONT></TD>
<TD STYLE="border-top: 1px solid #000000" ALIGN=CENTER><FONT COLOR="#808080"><BR></FONT></TD>
<TD STYLE="border-top: 1px solid #000000" ALIGN=CENTER><FONT COLOR="#808080"><BR></FONT></TD>
<TD STYLE="border-top: 1px solid #000000" ALIGN=CENTER><FONT COLOR="#808080"><BR></FONT></TD>
<TD STYLE="border-top: 1px solid #000000" ALIGN=LEFT><BR></TD>
<TD STYLE="border-top: 1px solid #000000" ALIGN=LEFT><BR></TD>
<TD STYLE="border-top: 1px solid #000000" ALIGN=LEFT><BR></TD>
<TD STYLE="border-top: 1px solid #000000; border-right: 1px solid #000000" ALIGN=LEFT><BR></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><B><FONT COLOR="#808080">Option</FONT></B></TD>
<TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1 COLOR="#000000">linePlusBar</FONT></B></TD>
<TD STYLE="border-bottom: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1 COLOR="#000000">cumulativeLineData</FONT></B></TD>
<TD STYLE="border-bottom: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1 COLOR="#000000">stackedArea</FONT></B></TD>
<TD STYLE="border-bottom: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1 COLOR="#000000">discreteBar</FONT></B></TD>
<TD STYLE="border-bottom: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1 COLOR="#000000">horizontalMultiBar</FONT></B></TD>
<TD STYLE="border-bottom: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1 COLOR="#000000">Pie</FONT></B></TD>
<TD STYLE="border-bottom: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1 COLOR="#000000">Donut</FONT></B></TD>
<TD STYLE="border-bottom: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1 COLOR="#000000">Bullet</FONT></B></TD>
<TD STYLE="border-bottom: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1>ScatterBubble</FONT></B></TD>
<TD STYLE="border-bottom: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1>MultiBar</FONT></B></TD>
<TD STYLE="border-bottom: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1>viewFinder</FONT></B></TD>
<TD STYLE="border-bottom: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1>simpleLine</FONT></B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">clipEdge</FONT></TD>
<TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">color</FONT></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">donut</FONT></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">donutRatio</FONT></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">groupSpacing</FONT></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">labelThreshold</FONT></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">labelType</FONT></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">reduceXTicks</FONT></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">rightAlignYAxis</FONT></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">rotateLabels</FONT></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">showControls</FONT></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">showDistX</FONT></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">showDistY</FONT></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">showLabels</FONT></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">showLegend</FONT></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">showValues</FONT></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">showXAxis</FONT></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">showYAxis</FONT></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">staggerLabels</FONT></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">tooltips</FONT></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">transitionDuration</FONT></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
</TR>
<TR>
<TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999"><API key></FONT></TD>
<TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
<TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD>
<TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD>
</TR>
</TBODY>
</TABLE>
</BODY>
</HTML>
|
<?php
global $post, $sc_post_class;
$post_id = $post->ID;
$post_obj = new sc_post($post_id);
$post_comments = get_comments_number( $post_id );
?>
<!--item
<div class="entry <?php echo esc_attr( $sc_post_class ); ?> post-item">
<?php
$main_image = $post_obj->get_main_image('thumb-image');
if (!empty( $main_image ) ) { ?>
<figure>
<img src="<?php echo esc_url ( $main_image ); ?>" alt="<?php the_title(); ?>" />
<figcaption><a href="<?php echo esc_url ( $post_obj->get_permalink() ); ?>"><i class="ico eldorado_eyelash"></i> <span><?php _e('View post', 'socialchef'); ?></span></a></figcaption>
</figure>
<?php } ?>
<div class="container">
<h2><a href="<?php echo esc_url ( $post_obj->get_permalink() ); ?>"><?php the_title(); ?></a></h2>
<div class="actions">
<div>
<div class="date"><i class="ico eldorado_calendar_1"></i><?php the_time('F j, Y'); ?></div>
<div class="comments"><i class="ico <API key>"></i><a href="<?php echo esc_url ( $post_obj->get_permalink() ); ?>#comments"><?php echo $post_comments; ?></a></div>
</div>
</div>
<div class="excerpt">
<?php the_excerpt(); ?>
</div>
</div>
</div>
<!--item
|
#include <string.h>
#include <stdlib.h>
#include "../types.h"
#include "x6502.h"
#include "cart.h"
#include "memory.h"
/* 16 are (sort of) reserved for UNIF/iNES and 16 to map other stuff. */
static INLINE void setpageptr(NESCART *ca, int s, uint32 A, uint8 *p, int ram)
{
uint32 AB=A>>11;
int x;
if(p)
for(x=(s>>1)-1;x>=0;x
{
ca->PRGIsRAM[AB+x]=ram;
ca->Page[AB+x]=p-A;
}
else
for(x=(s>>1)-1;x>=0;x
{
ca->PRGIsRAM[AB+x]=0;
ca->Page[AB+x]=0;
}
}
static uint8 nothing[8192];
void FESTAC_Kill(NESCART *ca)
{
free(ca);
}
NESCART *FESTAC_Init(void)
{
int x;
NESCART *ca;
if(!(ca=malloc(sizeof(NESCART)))) return(0);
memset(ca,0,sizeof(NESCART));
for(x=0;x<32;x++)
{
ca->Page[x]=nothing-x*2048;
ca->PRGptr[x]=0;
ca->PRGsize[x]=0;
}
return(ca);
}
void FESTAC_SetupPRG(NESCART *ca, int chip, uint8 *p, uint32 size, int ram)
{
ca->PRGptr[chip]=p;
ca->PRGsize[chip]=size;
ca->PRGmask2[chip]=(size>>11)-1;
ca->PRGmask4[chip]=(size>>12)-1;
ca->PRGmask8[chip]=(size>>13)-1;
ca->PRGmask16[chip]=(size>>14)-1;
ca->PRGmask32[chip]=(size>>15)-1;
ca->PRGram[chip]=ram?1:0;
}
DECLFR(CartBR)
{
NESCART *ca=private;
return ca->Page[A>>11][A];
}
DECLFW(CartBW)
{
NESCART *ca=private;
if(ca->PRGIsRAM[A>>11] && ca->Page[A>>11])
ca->Page[A>>11][A]=V;
}
DECLFR(CartBROB)
{
NESCART *ca=private;
if(!ca->Page[A>>11]) return(DB);
return ca->Page[A>>11][A];
}
void FASTAPASS(3) setprg2r(NESCART *ca, int r, unsigned int A, unsigned int V)
{
V&=ca->PRGmask2[r];
setpageptr(ca,2,A,ca->PRGptr[r]?(&ca->PRGptr[r][V<<11]):0,ca->PRGram[r]);
}
void FASTAPASS(2) setprg2(NESCART *ca, uint32 A, uint32 V)
{
setprg2r(ca,0,A,V);
}
void FASTAPASS(3) setprg4r(NESCART *ca, int r, unsigned int A, unsigned int V)
{
V&=ca->PRGmask4[r];
setpageptr(ca,4,A,ca->PRGptr[r]?(&ca->PRGptr[r][V<<12]):0,ca->PRGram[r]);
}
void FASTAPASS(2) setprg4(NESCART *ca, uint32 A, uint32 V)
{
setprg4r(ca,0,A,V);
}
void FASTAPASS(3) setprg8r(NESCART *ca, int r, unsigned int A, unsigned int V)
{
if(ca->PRGsize[r]>=8192)
{
V&=ca->PRGmask8[r];
setpageptr(ca,8,A,ca->PRGptr[r]?(&ca->PRGptr[r][V<<13]):0,ca->PRGram[r]);
}
else
{
uint32 VA=V<<2;
int x;
for(x=0;x<4;x++)
setpageptr(ca,2,A+(x<<11),ca->PRGptr[r]?(&ca->PRGptr[r][((VA+x)&ca->PRGmask2[r])<<11]):0,ca->PRGram[r]);
}
}
void FASTAPASS(2) setprg8(NESCART *ca, uint32 A, uint32 V)
{
setprg8r(ca,0,A,V);
}
void FASTAPASS(3) setprg16r(NESCART *ca, int r, unsigned int A, unsigned int V)
{
if(ca->PRGsize[r]>=16384)
{
V&=ca->PRGmask16[r];
setpageptr(ca,16,A,ca->PRGptr[r]?(&ca->PRGptr[r][V<<14]):0,ca->PRGram[r]);
}
else
{
uint32 VA=V<<3;
int x;
for(x=0;x<8;x++)
setpageptr(ca,2,A+(x<<11),ca->PRGptr[r]?(&ca->PRGptr[r][((VA+x)&ca->PRGmask2[r])<<11]):0,ca->PRGram[r]);
}
}
void FASTAPASS(2) setprg16(NESCART *ca, uint32 A, uint32 V)
{
setprg16r(ca,0,A,V);
}
void FASTAPASS(3) setprg32r(NESCART *ca, int r,unsigned int A, unsigned int V)
{
if(ca->PRGsize[r]>=32768)
{
V&=ca->PRGmask32[r];
setpageptr(ca,32,A,ca->PRGptr[r]?(&ca->PRGptr[r][V<<15]):0,ca->PRGram[r]);
}
else
{
uint32 VA=V<<4;
int x;
for(x=0;x<16;x++)
setpageptr(ca,2,A+(x<<11),ca->PRGptr[r]?(&ca->PRGptr[r][((VA+x)&ca->PRGmask2[r])<<11]):0,ca->PRGram[r]);
}
}
void FASTAPASS(2) setprg32(NESCART *ca, uint32 A, uint32 V)
{
setprg32r(ca,0,A,V);
}
|
<div class='result'>
add task success<br />
{{task}}<br />
<a href='show'>check</a>
</div>
|
<div id="roomTitle">Welcome to Agavi :: home of the convention nazis :: 911GT2 coming soon :: http:
<div id="watermark" class="transparent50"></div>
<div id="messages">
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="name"><a href="info">RossC0</a></td>
<td class="message">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed eget nulla in lacus suscipit mattis. Vivamus non metus. Pellentesque eu urna sed pede dictum vulputate. Quisque enim nibh, vehicula ac, accumsan nec, sagittis aliquam, enim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla vitae nulla quis est mollis vulputate. Sed lacinia volutpat eros. Mauris cursus dui et nibh. Vestibulum erat nisi, ornare et, adipiscing nec, interdum ut, turpis. Nulla facilisi. Quisque tincidunt est. Etiam gravida pede vestibulum tellus. Vivamus sit amet leo. Integer hendrerit. Fusce et nisl nec ante aliquam vehicula. Etiam pretium tincidunt velit.</td>
<td class="time">00:16</td>
</tr>
<tr>
<td class="name" rowspan="2"><a href="info">kaos|work</a></td>
<td class="message">oh, and it would be cool if there was an easy way injecting my own code in every receive</td>
<td class="time">00:28</td>
</tr>
<tr>
<td class="message">or something which gets called in a regular timeframe</td>
<td class="time">00:29</td>
</tr>
<tr>
<td class="name" rowspan="2"><a href="info">impl</a></td>
<td class="message">timers</td>
<td class="time">00:29</td>
</tr>
<tr class="action">
<td class="message">got it</td>
<td class="time">00:29</td>
</tr>
<tr class="self">
<td class="name"><a href="info">Wombert</a></td>
<td class="message">is that so?</td>
<td class="time">00:32</td>
</tr>
<tr class="highlight">
<td class="name"><a href="info">v-dogg</a></td>
<td class="message">Wombert Zombert :)</td>
<td class="time">00:33</td>
</tr>
<tr>
<td class="name"><a href="info">RossC0</a></td>
<td class="message">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed eget nulla in lacus suscipit mattis. Vivamus non metus. Pellentesque eu urna sed pede dictum vulputate. Quisque enim nibh, vehicula ac, accumsan nec, sagittis aliquam, enim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla vitae nulla quis est mollis vulputate. Sed lacinia volutpat eros. Mauris cursus dui et nibh. Vestibulum erat nisi, ornare et, adipiscing nec, interdum ut, turpis. Nulla facilisi. Quisque tincidunt est. Etiam gravida pede vestibulum tellus. Vivamus sit amet leo. Integer hendrerit. Fusce et nisl nec ante aliquam vehicula. Etiam pretium tincidunt velit.</td>
<td class="time">00:16</td>
</tr>
<tr class="event">
<td class="name"><a href="info">kaos|work</a></td>
<td class="message">has joined the channel</td>
<td class="time">00:23</td>
</tr>
<tr>
<td class="name" rowspan="2"><a href="info">kaos|work</a></td>
<td class="message">oh, and it would be cool if there was an easy way injecting my own code in every receive</td>
<td class="time">00:28</td>
</tr>
<tr>
<td class="message">or something which gets called in a regular timeframe</td>
<td class="time">00:29</td>
</tr>
<tr>
<td class="name" rowspan="2"><a href="info">impl</a></td>
<td class="message">timers</td>
<td class="time">00:29</td>
</tr>
<tr>
<td class="message">got it</td>
<td class="time">00:29</td>
</tr>
<tr class="self">
<td class="name"><a href="info">Wombert</a></td>
<td class="message">is that so?</td>
<td class="time">00:32</td>
</tr>
<tr class="highlight">
<td class="name"><a href="info">v-dogg</a></td>
<td class="message">Wombert Zombert :)</td>
<td class="time">00:33</td>
</tr>
<tr>
<td class="name"><a href="info">RossC0</a></td>
<td class="message">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed eget nulla in lacus suscipit mattis. Vivamus non metus. Pellentesque eu urna sed pede dictum vulputate. Quisque enim nibh, vehicula ac, accumsan nec, sagittis aliquam, enim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla vitae nulla quis est mollis vulputate. Sed lacinia volutpat eros. Mauris cursus dui et nibh. Vestibulum erat nisi, ornare et, adipiscing nec, interdum ut, turpis. Nulla facilisi. Quisque tincidunt est. Etiam gravida pede vestibulum tellus. Vivamus sit amet leo. Integer hendrerit. Fusce et nisl nec ante aliquam vehicula. Etiam pretium tincidunt velit.</td>
<td class="time">00:16</td>
</tr>
<tr>
<td class="name" rowspan="2"><a href="info">kaos|work</a></td>
<td class="message">oh, and it would be cool if there was an easy way injecting my own code in every receive</td>
<td class="time">00:28</td>
</tr>
<tr>
<td class="message">or something which gets called in a regular timeframe</td>
<td class="time">00:29</td>
</tr>
<tr>
<td class="name" rowspan="2"><a href="info">impl</a></td>
<td class="message">timers</td>
<td class="time">00:29</td>
</tr>
<tr>
<td class="message">got it</td>
<td class="time">00:29</td>
</tr>
<tr class="self">
<td class="name"><a href="info">Wombert</a></td>
<td class="message">is that so?</td>
<td class="time">00:32</td>
</tr>
<tr class="highlight">
<td class="name"><a href="info">v-dogg</a></td>
<td class="message">Wombert Zombert :)</td>
<td class="time">00:33</td>
</tr>
<tr>
<td class="name"><a href="info">RossC0</a></td>
<td class="message">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed eget nulla in lacus suscipit mattis. Vivamus non metus. Pellentesque eu urna sed pede dictum vulputate. Quisque enim nibh, vehicula ac, accumsan nec, sagittis aliquam, enim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla vitae nulla quis est mollis vulputate. Sed lacinia volutpat eros. Mauris cursus dui et nibh. Vestibulum erat nisi, ornare et, adipiscing nec, interdum ut, turpis. Nulla facilisi. Quisque tincidunt est. Etiam gravida pede vestibulum tellus. Vivamus sit amet leo. Integer hendrerit. Fusce et nisl nec ante aliquam vehicula. Etiam pretium tincidunt velit.</td>
<td class="time">00:16</td>
</tr>
<tr>
<td class="name" rowspan="2"><a href="info">kaos|work</a></td>
<td class="message">oh, and it would be cool if there was an easy way injecting my own code in every receive</td>
<td class="time">00:28</td>
</tr>
<tr>
<td class="message">or something which gets called in a regular timeframe</td>
<td class="time">00:29</td>
</tr>
<tr>
<td class="name" rowspan="2"><a href="info">impl</a></td>
<td class="message">timers</td>
<td class="time">00:29</td>
</tr>
<tr>
<td class="message">got it</td>
<td class="time">00:29</td>
</tr>
<tr class="self">
<td class="name"><a href="info">Wombert</a></td>
<td class="message">is that so?</td>
<td class="time">00:32</td>
</tr>
<tr class="highlight">
<td class="name"><a href="info">v-dogg</a></td>
<td class="message">Wombert Zombert :)</td>
<td class="time">00:33</td>
</tr>
</table>
</div>
|
#include <linux/etherdevice.h>
#include <linux/ip.h>
#include <linux/fs.h>
#include <net/cfg80211.h>
#include <net/ipv6.h>
#include <net/tcp.h>
#include <net/addrconf.h>
#include "iwl-modparams.h"
#include "fw-api.h"
#include "mvm.h"
void <API key>(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct <API key> *data)
{
struct iwl_mvm *mvm = <API key>(hw);
struct iwl_mvm_vif *mvmvif = <API key>(vif);
if (iwlwifi_mod_params.sw_crypto)
return;
mutex_lock(&mvm->mutex);
memcpy(mvmvif->rekey_data.kek, data->kek, NL80211_KEK_LEN);
memcpy(mvmvif->rekey_data.kck, data->kck, NL80211_KCK_LEN);
mvmvif->rekey_data.replay_ctr =
cpu_to_le64(be64_to_cpup((__be64 *)&data->replay_ctr));
mvmvif->rekey_data.valid = true;
mutex_unlock(&mvm->mutex);
}
#if IS_ENABLED(CONFIG_IPV6)
void <API key>(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct inet6_dev *idev)
{
struct iwl_mvm_vif *mvmvif = <API key>(vif);
struct inet6_ifaddr *ifa;
int idx = 0;
read_lock_bh(&idev->lock);
list_for_each_entry(ifa, &idev->addr_list, if_list) {
mvmvif->target_ipv6_addrs[idx] = ifa->addr;
idx++;
if (idx >= <API key>)
break;
}
read_unlock_bh(&idev->lock);
mvmvif-><API key> = idx;
}
#endif
void <API key>(struct ieee80211_hw *hw,
struct ieee80211_vif *vif, int idx)
{
struct iwl_mvm_vif *mvmvif = <API key>(vif);
mvmvif->tx_key_idx = idx;
}
static void iwl_mvm_convert_p1k(u16 *p1k, __le16 *out)
{
int i;
for (i = 0; i < IWL_P1K_SIZE; i++)
out[i] = cpu_to_le16(p1k[i]);
}
struct wowlan_key_data {
struct <API key> *rsc_tsc;
struct <API key> *tkip;
bool error, use_rsc_tsc, use_tkip;
int wep_key_idx;
};
static void <API key>(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta,
struct ieee80211_key_conf *key,
void *_data)
{
struct iwl_mvm *mvm = <API key>(hw);
struct iwl_mvm_vif *mvmvif = <API key>(vif);
struct wowlan_key_data *data = _data;
struct aes_sc *aes_sc, *aes_tx_sc = NULL;
struct tkip_sc *tkip_sc, *tkip_tx_sc = NULL;
struct iwl_p1k_cache *rx_p1ks;
u8 *rx_mic_key;
struct ieee80211_key_seq seq;
u32 cur_rx_iv32 = 0;
u16 p1k[IWL_P1K_SIZE];
int ret, i;
mutex_lock(&mvm->mutex);
switch (key->cipher) {
case <API key>:
case <API key>: { /* hack it for now */
struct {
struct iwl_mvm_wep_key_cmd wep_key_cmd;
struct iwl_mvm_wep_key wep_key;
} __packed wkc = {
.wep_key_cmd.mac_id_n_color =
cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
mvmvif->color)),
.wep_key_cmd.num_keys = 1,
/* firmware sets <API key> */
.wep_key_cmd.decryption_type = STA_KEY_FLG_WEP,
.wep_key.key_index = key->keyidx,
.wep_key.key_size = key->keylen,
};
/*
* This will fail -- the key functions don't set support
* pairwise WEP keys. However, that's better than silently
* failing WoWLAN. Or maybe not?
*/
if (key->flags & <API key>)
break;
memcpy(&wkc.wep_key.key[3], key->key, key->keylen);
if (key->keyidx == mvmvif->tx_key_idx) {
/* TX key must be at offset 0 */
wkc.wep_key.key_offset = 0;
} else {
/* others start at 1 */
data->wep_key_idx++;
wkc.wep_key.key_offset = data->wep_key_idx;
}
ret = <API key>(mvm, WEP_KEY, CMD_SYNC,
sizeof(wkc), &wkc);
data->error = ret != 0;
mvm->ptk_ivlen = key->iv_len;
mvm->ptk_icvlen = key->icv_len;
mvm->gtk_ivlen = key->iv_len;
mvm->gtk_icvlen = key->icv_len;
/* don't upload key again */
goto out_unlock;
}
default:
data->error = true;
goto out_unlock;
case <API key>:
/*
* Ignore CMAC keys -- the WoWLAN firmware doesn't support them
* but we also shouldn't abort suspend due to that. It does have
* support for the IGTK key renewal, but doesn't really use the
* IGTK for anything. This means we could spuriously wake up or
* be deauthenticated, but that was considered acceptable.
*/
goto out_unlock;
case <API key>:
if (sta) {
tkip_sc = data->rsc_tsc->all_tsc_rsc.tkip.unicast_rsc;
tkip_tx_sc = &data->rsc_tsc->all_tsc_rsc.tkip.tsc;
rx_p1ks = data->tkip->rx_uni;
<API key>(key, &seq);
tkip_tx_sc->iv16 = cpu_to_le16(seq.tkip.iv16);
tkip_tx_sc->iv32 = cpu_to_le32(seq.tkip.iv32);
<API key>(key, seq.tkip.iv32, p1k);
iwl_mvm_convert_p1k(p1k, data->tkip->tx.p1k);
memcpy(data->tkip->mic_keys.tx,
&key->key[<API key>],
IWL_MIC_KEY_SIZE);
rx_mic_key = data->tkip->mic_keys.rx_unicast;
} else {
tkip_sc =
data->rsc_tsc->all_tsc_rsc.tkip.multicast_rsc;
rx_p1ks = data->tkip->rx_multi;
rx_mic_key = data->tkip->mic_keys.rx_mcast;
}
/*
* For non-QoS this relies on the fact that both the uCode and
* mac80211 use TID 0 (as they need to to avoid replay attacks)
* for checking the IV in the frames.
*/
for (i = 0; i < IWL_NUM_RSC; i++) {
<API key>(key, i, &seq);
tkip_sc[i].iv16 = cpu_to_le16(seq.tkip.iv16);
tkip_sc[i].iv32 = cpu_to_le32(seq.tkip.iv32);
/* wrapping isn't allowed, AP must rekey */
if (seq.tkip.iv32 > cur_rx_iv32)
cur_rx_iv32 = seq.tkip.iv32;
}
<API key>(key, vif->bss_conf.bssid,
cur_rx_iv32, p1k);
iwl_mvm_convert_p1k(p1k, rx_p1ks[0].p1k);
<API key>(key, vif->bss_conf.bssid,
cur_rx_iv32 + 1, p1k);
iwl_mvm_convert_p1k(p1k, rx_p1ks[1].p1k);
memcpy(rx_mic_key,
&key->key[<API key>],
IWL_MIC_KEY_SIZE);
data->use_tkip = true;
data->use_rsc_tsc = true;
break;
case <API key>:
if (sta) {
u8 *pn = seq.ccmp.pn;
aes_sc = data->rsc_tsc->all_tsc_rsc.aes.unicast_rsc;
aes_tx_sc = &data->rsc_tsc->all_tsc_rsc.aes.tsc;
<API key>(key, &seq);
aes_tx_sc->pn = cpu_to_le64((u64)pn[5] |
((u64)pn[4] << 8) |
((u64)pn[3] << 16) |
((u64)pn[2] << 24) |
((u64)pn[1] << 32) |
((u64)pn[0] << 40));
} else {
aes_sc = data->rsc_tsc->all_tsc_rsc.aes.multicast_rsc;
}
/*
* For non-QoS this relies on the fact that both the uCode and
* mac80211 use TID 0 for checking the IV in the frames.
*/
for (i = 0; i < IWL_NUM_RSC; i++) {
u8 *pn = seq.ccmp.pn;
<API key>(key, i, &seq);
aes_sc->pn = cpu_to_le64((u64)pn[5] |
((u64)pn[4] << 8) |
((u64)pn[3] << 16) |
((u64)pn[2] << 24) |
((u64)pn[1] << 32) |
((u64)pn[0] << 40));
}
data->use_rsc_tsc = true;
break;
}
/*
* The D3 firmware hardcodes the key offset 0 as the key it uses
* to transmit packets to the AP, i.e. the PTK.
*/
if (key->flags & <API key>) {
key->hw_key_idx = 0;
mvm->ptk_ivlen = key->iv_len;
mvm->ptk_icvlen = key->icv_len;
} else {
/*
* firmware only supports TSC/RSC for a single key,
* so if there are multiple keep overwriting them
* with new ones -- this relies on mac80211 doing
* list_add_tail().
*/
key->hw_key_idx = 1;
mvm->gtk_ivlen = key->iv_len;
mvm->gtk_icvlen = key->icv_len;
}
ret = iwl_mvm_set_sta_key(mvm, vif, sta, key, true);
data->error = ret != 0;
out_unlock:
mutex_unlock(&mvm->mutex);
}
static int <API key>(struct iwl_mvm *mvm,
struct cfg80211_wowlan *wowlan)
{
struct <API key> *pattern_cmd;
struct iwl_host_cmd cmd = {
.id = WOWLAN_PATTERNS,
.dataflags[0] = IWL_HCMD_DFL_NOCOPY,
.flags = CMD_SYNC,
};
int i, err;
if (!wowlan->n_patterns)
return 0;
cmd.len[0] = sizeof(*pattern_cmd) +
wowlan->n_patterns * sizeof(struct iwl_wowlan_pattern);
pattern_cmd = kmalloc(cmd.len[0], GFP_KERNEL);
if (!pattern_cmd)
return -ENOMEM;
pattern_cmd->n_patterns = cpu_to_le32(wowlan->n_patterns);
for (i = 0; i < wowlan->n_patterns; i++) {
int mask_len = DIV_ROUND_UP(wowlan->patterns[i].pattern_len, 8);
memcpy(&pattern_cmd->patterns[i].mask,
wowlan->patterns[i].mask, mask_len);
memcpy(&pattern_cmd->patterns[i].pattern,
wowlan->patterns[i].pattern,
wowlan->patterns[i].pattern_len);
pattern_cmd->patterns[i].mask_size = mask_len;
pattern_cmd->patterns[i].pattern_size =
wowlan->patterns[i].pattern_len;
}
cmd.data[0] = pattern_cmd;
err = iwl_mvm_send_cmd(mvm, &cmd);
kfree(pattern_cmd);
return err;
}
static int <API key>(struct iwl_mvm *mvm,
struct ieee80211_vif *vif)
{
union {
struct <API key> v1;
struct <API key> v2;
struct <API key> v3s;
struct <API key> v3l;
} cmd = {};
struct iwl_host_cmd hcmd = {
.id = <API key>,
.flags = CMD_SYNC,
.data[0] = &cmd,
.dataflags[0] = IWL_HCMD_DFL_DUP,
};
struct <API key> *common;
u32 enabled = 0, size;
u32 capa_flags = mvm->fw->ucode_capa.flags;
#if IS_ENABLED(CONFIG_IPV6)
struct iwl_mvm_vif *mvmvif = <API key>(vif);
int i;
if (capa_flags & <API key> ||
capa_flags & <API key>) {
struct iwl_ns_config *nsc;
struct iwl_targ_addr *addrs;
int n_nsc, n_addrs;
int c;
if (capa_flags & <API key>) {
nsc = cmd.v3s.ns_config;
n_nsc = <API key>;
addrs = cmd.v3s.targ_addrs;
n_addrs = <API key>;
} else {
nsc = cmd.v3l.ns_config;
n_nsc = <API key>;
addrs = cmd.v3l.targ_addrs;
n_addrs = <API key>;
}
if (mvmvif-><API key>)
enabled |= <API key>;
/*
* For each address we have (and that will fit) fill a target
* address struct and combine for NS offload structs with the
* solicited node addresses.
*/
for (i = 0, c = 0;
i < mvmvif-><API key> &&
i < n_addrs && c < n_nsc; i++) {
struct in6_addr solicited_addr;
int j;
<API key>(&mvmvif->target_ipv6_addrs[i],
&solicited_addr);
for (j = 0; j < c; j++)
if (ipv6_addr_cmp(&nsc[j].dest_ipv6_addr,
&solicited_addr) == 0)
break;
if (j == c)
c++;
addrs[i].addr = mvmvif->target_ipv6_addrs[i];
addrs[i].config_num = cpu_to_le32(j);
nsc[j].dest_ipv6_addr = solicited_addr;
memcpy(nsc[j].target_mac_addr, vif->addr, ETH_ALEN);
}
if (capa_flags & <API key>)
cmd.v3s.<API key> = cpu_to_le32(i);
else
cmd.v3l.<API key> = cpu_to_le32(i);
} else if (capa_flags & <API key>) {
if (mvmvif-><API key>) {
enabled |= <API key>;
memcpy(cmd.v2.ndp_mac_addr, vif->addr, ETH_ALEN);
}
BUILD_BUG_ON(sizeof(cmd.v2.target_ipv6_addr[0]) !=
sizeof(mvmvif->target_ipv6_addrs[0]));
for (i = 0; i < min(mvmvif-><API key>,
<API key>); i++)
memcpy(cmd.v2.target_ipv6_addr[i],
&mvmvif->target_ipv6_addrs[i],
sizeof(cmd.v2.target_ipv6_addr[i]));
} else {
if (mvmvif-><API key>) {
enabled |= <API key>;
memcpy(cmd.v1.ndp_mac_addr, vif->addr, ETH_ALEN);
}
BUILD_BUG_ON(sizeof(cmd.v1.target_ipv6_addr[0]) !=
sizeof(mvmvif->target_ipv6_addrs[0]));
for (i = 0; i < min(mvmvif-><API key>,
<API key>); i++)
memcpy(cmd.v1.target_ipv6_addr[i],
&mvmvif->target_ipv6_addrs[i],
sizeof(cmd.v1.target_ipv6_addr[i]));
}
#endif
if (capa_flags & <API key>) {
common = &cmd.v3s.common;
size = sizeof(cmd.v3s);
} else if (capa_flags & <API key>) {
common = &cmd.v3l.common;
size = sizeof(cmd.v3l);
} else if (capa_flags & <API key>) {
common = &cmd.v2.common;
size = sizeof(cmd.v2);
} else {
common = &cmd.v1.common;
size = sizeof(cmd.v1);
}
if (vif->bss_conf.arp_addr_cnt) {
enabled |= <API key>;
common->host_ipv4_addr = vif->bss_conf.arp_addr_list[0];
memcpy(common->arp_mac_addr, vif->addr, ETH_ALEN);
}
if (!enabled)
return 0;
common->enabled = cpu_to_le32(enabled);
hcmd.len[0] = size;
return iwl_mvm_send_cmd(mvm, &hcmd);
}
enum <API key> {
MVM_TCP_TX_SYN,
MVM_TCP_RX_SYNACK,
MVM_TCP_TX_DATA,
MVM_TCP_RX_ACK,
MVM_TCP_RX_WAKE,
MVM_TCP_TX_FIN,
};
static __le16 pseudo_hdr_check(int len, __be32 saddr, __be32 daddr)
{
__sum16 check = tcp_v4_check(len, saddr, daddr, 0);
return cpu_to_le16(be16_to_cpu((__force __be16)check));
}
static void <API key>(struct ieee80211_vif *vif,
struct cfg80211_wowlan_tcp *tcp,
void *_pkt, u8 *mask,
__le16 *pseudo_hdr_csum,
enum <API key> ptype)
{
struct {
struct ethhdr eth;
struct iphdr ip;
struct tcphdr tcp;
u8 data[];
} __packed *pkt = _pkt;
u16 ip_tot_len = sizeof(struct iphdr) + sizeof(struct tcphdr);
int i;
pkt->eth.h_proto = cpu_to_be16(ETH_P_IP),
pkt->ip.version = 4;
pkt->ip.ihl = 5;
pkt->ip.protocol = IPPROTO_TCP;
switch (ptype) {
case MVM_TCP_TX_SYN:
case MVM_TCP_TX_DATA:
case MVM_TCP_TX_FIN:
memcpy(pkt->eth.h_dest, tcp->dst_mac, ETH_ALEN);
memcpy(pkt->eth.h_source, vif->addr, ETH_ALEN);
pkt->ip.ttl = 128;
pkt->ip.saddr = tcp->src;
pkt->ip.daddr = tcp->dst;
pkt->tcp.source = cpu_to_be16(tcp->src_port);
pkt->tcp.dest = cpu_to_be16(tcp->dst_port);
/* overwritten for TX SYN later */
pkt->tcp.doff = sizeof(struct tcphdr) / 4;
pkt->tcp.window = cpu_to_be16(65000);
break;
case MVM_TCP_RX_SYNACK:
case MVM_TCP_RX_ACK:
case MVM_TCP_RX_WAKE:
memcpy(pkt->eth.h_dest, vif->addr, ETH_ALEN);
memcpy(pkt->eth.h_source, tcp->dst_mac, ETH_ALEN);
pkt->ip.saddr = tcp->dst;
pkt->ip.daddr = tcp->src;
pkt->tcp.source = cpu_to_be16(tcp->dst_port);
pkt->tcp.dest = cpu_to_be16(tcp->src_port);
break;
default:
WARN_ON(1);
return;
}
switch (ptype) {
case MVM_TCP_TX_SYN:
/* firmware assumes 8 option bytes - 8 NOPs for now */
memset(pkt->data, 0x01, 8);
ip_tot_len += 8;
pkt->tcp.doff = (sizeof(struct tcphdr) + 8) / 4;
pkt->tcp.syn = 1;
break;
case MVM_TCP_TX_DATA:
ip_tot_len += tcp->payload_len;
memcpy(pkt->data, tcp->payload, tcp->payload_len);
pkt->tcp.psh = 1;
pkt->tcp.ack = 1;
break;
case MVM_TCP_TX_FIN:
pkt->tcp.fin = 1;
pkt->tcp.ack = 1;
break;
case MVM_TCP_RX_SYNACK:
pkt->tcp.syn = 1;
pkt->tcp.ack = 1;
break;
case MVM_TCP_RX_ACK:
pkt->tcp.ack = 1;
break;
case MVM_TCP_RX_WAKE:
ip_tot_len += tcp->wake_len;
pkt->tcp.psh = 1;
pkt->tcp.ack = 1;
memcpy(pkt->data, tcp->wake_data, tcp->wake_len);
break;
}
switch (ptype) {
case MVM_TCP_TX_SYN:
case MVM_TCP_TX_DATA:
case MVM_TCP_TX_FIN:
pkt->ip.tot_len = cpu_to_be16(ip_tot_len);
pkt->ip.check = ip_fast_csum(&pkt->ip, pkt->ip.ihl);
break;
case MVM_TCP_RX_WAKE:
for (i = 0; i < DIV_ROUND_UP(tcp->wake_len, 8); i++) {
u8 tmp = tcp->wake_mask[i];
mask[i + 6] |= tmp << 6;
if (i + 1 < DIV_ROUND_UP(tcp->wake_len, 8))
mask[i + 7] = tmp >> 2;
}
/* fall through for ethernet/IP/TCP headers mask */
case MVM_TCP_RX_SYNACK:
case MVM_TCP_RX_ACK:
mask[0] = 0xff; /* match ethernet */
/*
* match ethernet, ip.version, ip.ihl
* the ip.ihl half byte is really masked out by firmware
*/
mask[1] = 0x7f;
mask[2] = 0x80; /* match ip.protocol */
mask[3] = 0xfc; /* match ip.saddr, ip.daddr */
mask[4] = 0x3f; /* match ip.daddr, tcp.source, tcp.dest */
mask[5] = 0x80; /* match tcp flags */
/* leave rest (0 or set for MVM_TCP_RX_WAKE) */
break;
};
*pseudo_hdr_csum = pseudo_hdr_check(ip_tot_len - sizeof(struct iphdr),
pkt->ip.saddr, pkt->ip.daddr);
}
static int <API key>(struct iwl_mvm *mvm,
struct ieee80211_vif *vif,
struct cfg80211_wowlan_tcp *tcp)
{
struct <API key> *cfg;
struct iwl_host_cmd cmd = {
.id = <API key>,
.len = { sizeof(*cfg), },
.dataflags = { IWL_HCMD_DFL_NOCOPY, },
.flags = CMD_SYNC,
};
int ret;
if (!tcp)
return 0;
cfg = kzalloc(sizeof(*cfg), GFP_KERNEL);
if (!cfg)
return -ENOMEM;
cmd.data[0] = cfg;
cfg->max_syn_retries = 10;
cfg->max_data_retries = 10;
cfg->tcp_syn_ack_timeout = 1; /* seconds */
cfg->tcp_ack_timeout = 1; /* seconds */
/* SYN (TX) */
<API key>(
vif, tcp, cfg->syn_tx.data, NULL,
&cfg->syn_tx.info.<API key>,
MVM_TCP_TX_SYN);
cfg->syn_tx.info.tcp_payload_length = 0;
/* SYN/ACK (RX) */
<API key>(
vif, tcp, cfg->synack_rx.data, cfg->synack_rx.rx_mask,
&cfg->synack_rx.info.<API key>,
MVM_TCP_RX_SYNACK);
cfg->synack_rx.info.tcp_payload_length = 0;
/* KEEPALIVE/ACK (TX) */
<API key>(
vif, tcp, cfg->keepalive_tx.data, NULL,
&cfg->keepalive_tx.info.<API key>,
MVM_TCP_TX_DATA);
cfg->keepalive_tx.info.tcp_payload_length =
cpu_to_le16(tcp->payload_len);
cfg-><API key> = tcp->payload_seq.offset;
/* length must be 0..4, the field is little endian */
cfg-><API key> = tcp->payload_seq.len;
cfg-><API key> = cpu_to_le32(tcp->payload_seq.start);
cfg->keepalive_interval = cpu_to_le16(tcp->data_interval);
if (tcp->payload_tok.len) {
cfg->token_offset = tcp->payload_tok.offset;
cfg->token_length = tcp->payload_tok.len;
cfg->num_tokens =
cpu_to_le16(tcp->tokens_size % tcp->payload_tok.len);
memcpy(cfg->tokens, tcp->payload_tok.token_stream,
tcp->tokens_size);
} else {
/* set tokens to max value to almost never run out */
cfg->num_tokens = cpu_to_le16(65535);
}
/* ACK (RX) */
<API key>(
vif, tcp, cfg->keepalive_ack_rx.data,
cfg->keepalive_ack_rx.rx_mask,
&cfg->keepalive_ack_rx.info.<API key>,
MVM_TCP_RX_ACK);
cfg->keepalive_ack_rx.info.tcp_payload_length = 0;
/* WAKEUP (RX) */
<API key>(
vif, tcp, cfg->wake_rx.data, cfg->wake_rx.rx_mask,
&cfg->wake_rx.info.<API key>,
MVM_TCP_RX_WAKE);
cfg->wake_rx.info.tcp_payload_length =
cpu_to_le16(tcp->wake_len);
/* FIN */
<API key>(
vif, tcp, cfg->fin_tx.data, NULL,
&cfg->fin_tx.info.<API key>,
MVM_TCP_TX_FIN);
cfg->fin_tx.info.tcp_payload_length = 0;
ret = iwl_mvm_send_cmd(mvm, &cmd);
kfree(cfg);
return ret;
}
struct iwl_d3_iter_data {
struct iwl_mvm *mvm;
struct ieee80211_vif *vif;
bool error;
};
static void <API key>(void *_data, u8 *mac,
struct ieee80211_vif *vif)
{
struct iwl_d3_iter_data *data = _data;
struct iwl_mvm_vif *mvmvif = <API key>(vif);
if (vif->type != <API key> || vif->p2p)
return;
if (mvmvif->ap_sta_id == <API key>)
return;
if (data->vif) {
IWL_ERR(data->mvm, "More than one managed interface active!\n");
data->error = true;
return;
}
data->vif = vif;
}
static int <API key>(struct iwl_mvm *mvm, struct ieee80211_vif *vif,
struct ieee80211_sta *ap_sta)
{
struct iwl_mvm_vif *mvmvif = <API key>(vif);
struct <API key> *ctx;
u8 chains_static, chains_dynamic;
struct cfg80211_chan_def chandef;
int ret, i;
struct iwl_binding_cmd binding_cmd = {};
struct iwl_time_quota_cmd quota_cmd = {};
u32 status;
/* add back the PHY */
if (WARN_ON(!mvmvif->phy_ctxt))
return -EINVAL;
rcu_read_lock();
ctx = rcu_dereference(vif->chanctx_conf);
if (WARN_ON(!ctx)) {
rcu_read_unlock();
return -EINVAL;
}
chandef = ctx->def;
chains_static = ctx->rx_chains_static;
chains_dynamic = ctx->rx_chains_dynamic;
rcu_read_unlock();
ret = <API key>(mvm, mvmvif->phy_ctxt, &chandef,
chains_static, chains_dynamic);
if (ret)
return ret;
/* add back the MAC */
mvmvif->uploaded = false;
if (WARN_ON(!vif->bss_conf.assoc))
return -EINVAL;
/* hack */
vif->bss_conf.assoc = false;
ret = <API key>(mvm, vif);
vif->bss_conf.assoc = true;
if (ret)
return ret;
/* add back binding - XXX refactor? */
binding_cmd.id_and_color =
cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->phy_ctxt->id,
mvmvif->phy_ctxt->color));
binding_cmd.action = cpu_to_le32(FW_CTXT_ACTION_ADD);
binding_cmd.phy =
cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->phy_ctxt->id,
mvmvif->phy_ctxt->color));
binding_cmd.macs[0] = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
mvmvif->color));
for (i = 1; i < MAX_MACS_IN_BINDING; i++)
binding_cmd.macs[i] = cpu_to_le32(FW_CTXT_INVALID);
status = 0;
ret = <API key>(mvm, BINDING_CONTEXT_CMD,
sizeof(binding_cmd), &binding_cmd,
&status);
if (ret) {
IWL_ERR(mvm, "Failed to add binding: %d\n", ret);
return ret;
}
if (status) {
IWL_ERR(mvm, "Binding command failed: %u\n", status);
return -EIO;
}
ret = <API key>(mvm, ap_sta, false);
if (ret)
return ret;
rcu_assign_pointer(mvm->fw_id_to_mac_id[mvmvif->ap_sta_id], ap_sta);
ret = <API key>(mvm, vif);
if (ret)
return ret;
/* and some quota */
quota_cmd.quotas[0].id_and_color =
cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->phy_ctxt->id,
mvmvif->phy_ctxt->color));
quota_cmd.quotas[0].quota = cpu_to_le32(100);
quota_cmd.quotas[0].max_duration = cpu_to_le32(1000);
for (i = 1; i < MAX_BINDINGS; i++)
quota_cmd.quotas[i].id_and_color = cpu_to_le32(FW_CTXT_INVALID);
ret = <API key>(mvm, TIME_QUOTA_CMD, CMD_SYNC,
sizeof(quota_cmd), "a_cmd);
if (ret)
IWL_ERR(mvm, "Failed to send quota: %d\n", ret);
return 0;
}
static int <API key>(struct iwl_mvm *mvm,
struct ieee80211_vif *vif)
{
struct iwl_mvm_vif *mvmvif = <API key>(vif);
struct <API key> query_cmd = {
.get_set_flag = cpu_to_le32(IWL_NONQOS_SEQ_GET),
.mac_id_n_color =
cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
mvmvif->color)),
};
struct iwl_host_cmd cmd = {
.id = <API key>,
.flags = CMD_SYNC | CMD_WANT_SKB,
};
int err;
u32 size;
if (mvm->fw->ucode_capa.flags & <API key>) {
cmd.data[0] = &query_cmd;
cmd.len[0] = sizeof(query_cmd);
}
err = iwl_mvm_send_cmd(mvm, &cmd);
if (err)
return err;
size = le32_to_cpu(cmd.resp_pkt->len_n_flags) & <API key>;
size -= sizeof(cmd.resp_pkt->hdr);
if (size < sizeof(__le16)) {
err = -EINVAL;
} else {
err = le16_to_cpup((__le16 *)cmd.resp_pkt->data);
/* new API returns next, not last-used seqno */
if (mvm->fw->ucode_capa.flags &
<API key>)
err = (u16) (err - 0x10);
}
iwl_free_resp(&cmd);
return err;
}
void <API key>(struct iwl_mvm *mvm, struct ieee80211_vif *vif)
{
struct iwl_mvm_vif *mvmvif = <API key>(vif);
struct <API key> query_cmd = {
.get_set_flag = cpu_to_le32(IWL_NONQOS_SEQ_SET),
.mac_id_n_color =
cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
mvmvif->color)),
.value = cpu_to_le16(mvmvif->seqno),
};
/* return if called during restart, not resume from D3 */
if (!mvmvif->seqno_valid)
return;
mvmvif->seqno_valid = false;
if (!(mvm->fw->ucode_capa.flags &
<API key>))
return;
if (<API key>(mvm, <API key>, CMD_SYNC,
sizeof(query_cmd), &query_cmd))
IWL_ERR(mvm, "failed to set non-QoS seqno\n");
}
static int __iwl_mvm_suspend(struct ieee80211_hw *hw,
struct cfg80211_wowlan *wowlan,
bool test)
{
struct iwl_mvm *mvm = <API key>(hw);
struct iwl_d3_iter_data suspend_iter_data = {
.mvm = mvm,
};
struct ieee80211_vif *vif;
struct iwl_mvm_vif *mvmvif;
struct ieee80211_sta *ap_sta;
struct iwl_mvm_sta *mvm_ap_sta;
struct <API key> wowlan_config_cmd = {};
struct <API key> kek_kck_cmd = {};
struct <API key> tkip_cmd = {};
struct <API key> d3_cfg_cmd_data = {
/*
* Program the minimum sleep time to 10 seconds, as many
* platforms have issues processing a wakeup signal while
* still being in the process of suspending.
*/
.min_sleep_time = cpu_to_le32(10 * 1000 * 1000),
};
struct iwl_host_cmd d3_cfg_cmd = {
.id = D3_CONFIG_CMD,
.flags = CMD_SYNC | CMD_WANT_SKB,
.data[0] = &d3_cfg_cmd_data,
.len[0] = sizeof(d3_cfg_cmd_data),
};
struct wowlan_key_data key_data = {
.use_rsc_tsc = false,
.tkip = &tkip_cmd,
.use_tkip = false,
};
int ret, i;
int len __maybe_unused;
u8 old_aux_sta_id, old_ap_sta_id = <API key>;
if (!wowlan) {
/*
* mac80211 shouldn't get here, but for D3 test
* it doesn't warrant a warning
*/
WARN_ON(!test);
return -EINVAL;
}
key_data.rsc_tsc = kzalloc(sizeof(*key_data.rsc_tsc), GFP_KERNEL);
if (!key_data.rsc_tsc)
return -ENOMEM;
mutex_lock(&mvm->mutex);
old_aux_sta_id = mvm->aux_sta.sta_id;
/* see if there's only a single BSS vif and it's associated */
<API key>(
mvm->hw, <API key>,
<API key>, &suspend_iter_data);
if (suspend_iter_data.error || !suspend_iter_data.vif) {
ret = 1;
goto out_noreset;
}
vif = suspend_iter_data.vif;
mvmvif = <API key>(vif);
ap_sta = <API key>(
mvm->fw_id_to_mac_id[mvmvif->ap_sta_id],
lockdep_is_held(&mvm->mutex));
if (IS_ERR_OR_NULL(ap_sta)) {
ret = -EINVAL;
goto out_noreset;
}
mvm_ap_sta = (struct iwl_mvm_sta *)ap_sta->drv_priv;
/* TODO: wowlan_config_cmd.<API key> */
wowlan_config_cmd.is_11n_connection = ap_sta->ht_cap.ht_supported;
/* Query the last used seqno and set it */
ret = <API key>(mvm, vif);
if (ret < 0)
goto out_noreset;
wowlan_config_cmd.non_qos_seq = cpu_to_le16(ret);
/*
* For QoS counters, we store the one to use next, so subtract 0x10
* since the uCode will add 0x10 *before* using the value while we
* increment after using the value (i.e. store the next value to use).
*/
for (i = 0; i < IWL_MAX_TID_COUNT; i++) {
u16 seq = mvm_ap_sta->tid_data[i].seq_number;
seq -= 0x10;
wowlan_config_cmd.qos_seq[i] = cpu_to_le16(seq);
}
if (wowlan->disconnect)
wowlan_config_cmd.wakeup_filter |=
cpu_to_le32(<API key> |
<API key>);
if (wowlan->magic_pkt)
wowlan_config_cmd.wakeup_filter |=
cpu_to_le32(<API key>);
if (wowlan->gtk_rekey_failure)
wowlan_config_cmd.wakeup_filter |=
cpu_to_le32(<API key>);
if (wowlan->eap_identity_req)
wowlan_config_cmd.wakeup_filter |=
cpu_to_le32(<API key>);
if (wowlan->four_way_handshake)
wowlan_config_cmd.wakeup_filter |=
cpu_to_le32(<API key>);
if (wowlan->n_patterns)
wowlan_config_cmd.wakeup_filter |=
cpu_to_le32(<API key>);
if (wowlan->rfkill_release)
wowlan_config_cmd.wakeup_filter |=
cpu_to_le32(<API key>);
if (wowlan->tcp) {
/*
* Set the "link change" (really "link lost") flag as well
* since that implies losing the TCP connection.
*/
wowlan_config_cmd.wakeup_filter |=
cpu_to_le32(<API key> |
<API key> |
<API key> |
<API key>);
}
iwl_mvm_cancel_scan(mvm);
<API key>(mvm->trans);
/*
* The D3 firmware still hardcodes the AP station ID for the
* BSS we're associated with as 0. Store the real STA ID here
* and assign 0. When we leave this function, we'll restore
* the original value for the resume code.
*/
old_ap_sta_id = mvm_ap_sta->sta_id;
mvm_ap_sta->sta_id = 0;
mvmvif->ap_sta_id = 0;
/*
* Set the HW restart bit -- this is mostly true as we're
* going to load new firmware and reprogram that, though
* the reprogramming is going to be manual to avoid adding
* all the MACs that aren't support.
* We don't have to clear up everything though because the
* reprogramming is manual. When we resume, we'll actually
* go through a proper restart sequence again to switch
* back to the runtime firmware image.
*/
set_bit(<API key>, &mvm->status);
/* We reprogram keys and shouldn't allocate new key indices */
memset(mvm->fw_key_table, 0, sizeof(mvm->fw_key_table));
mvm->ptk_ivlen = 0;
mvm->ptk_icvlen = 0;
mvm->ptk_ivlen = 0;
mvm->ptk_icvlen = 0;
/*
* The D3 firmware still hardcodes the AP station ID for the
* BSS we're associated with as 0. As a result, we have to move
* the auxiliary station to ID 1 so the ID 0 remains free for
* the AP station for later.
* We set the sta_id to 1 here, and reset it to its previous
* value (that we stored above) later.
*/
mvm->aux_sta.sta_id = 1;
ret = iwl_mvm_load_d3_fw(mvm);
if (ret)
goto out;
ret = <API key>(mvm, vif, ap_sta);
if (ret)
goto out;
if (!iwlwifi_mod_params.sw_crypto) {
/*
* This needs to be unlocked due to lock ordering
* constraints. Since we're in the suspend path
* that isn't really a problem though.
*/
mutex_unlock(&mvm->mutex);
ieee80211_iter_keys(mvm->hw, vif,
<API key>,
&key_data);
mutex_lock(&mvm->mutex);
if (key_data.error) {
ret = -EIO;
goto out;
}
if (key_data.use_rsc_tsc) {
struct iwl_host_cmd rsc_tsc_cmd = {
.id = <API key>,
.flags = CMD_SYNC,
.data[0] = key_data.rsc_tsc,
.dataflags[0] = IWL_HCMD_DFL_NOCOPY,
.len[0] = sizeof(*key_data.rsc_tsc),
};
ret = iwl_mvm_send_cmd(mvm, &rsc_tsc_cmd);
if (ret)
goto out;
}
if (key_data.use_tkip) {
ret = <API key>(mvm,
WOWLAN_TKIP_PARAM,
CMD_SYNC, sizeof(tkip_cmd),
&tkip_cmd);
if (ret)
goto out;
}
if (mvmvif->rekey_data.valid) {
memset(&kek_kck_cmd, 0, sizeof(kek_kck_cmd));
memcpy(kek_kck_cmd.kck, mvmvif->rekey_data.kck,
NL80211_KCK_LEN);
kek_kck_cmd.kck_len = cpu_to_le16(NL80211_KCK_LEN);
memcpy(kek_kck_cmd.kek, mvmvif->rekey_data.kek,
NL80211_KEK_LEN);
kek_kck_cmd.kek_len = cpu_to_le16(NL80211_KEK_LEN);
kek_kck_cmd.replay_ctr = mvmvif->rekey_data.replay_ctr;
ret = <API key>(mvm,
<API key>,
CMD_SYNC,
sizeof(kek_kck_cmd),
&kek_kck_cmd);
if (ret)
goto out;
}
}
ret = <API key>(mvm, <API key>,
CMD_SYNC, sizeof(wowlan_config_cmd),
&wowlan_config_cmd);
if (ret)
goto out;
ret = <API key>(mvm, wowlan);
if (ret)
goto out;
ret = <API key>(mvm, vif);
if (ret)
goto out;
ret = <API key>(mvm, vif, wowlan->tcp);
if (ret)
goto out;
ret = <API key>(mvm);
if (ret)
goto out;
ret = <API key>(mvm, vif);
if (ret)
goto out;
#ifdef <API key>
if (mvm->d3_wake_sysassert)
d3_cfg_cmd_data.wakeup_flags |=
cpu_to_le32(<API key>);
#endif
/* must be last -- this switches firmware state */
ret = iwl_mvm_send_cmd(mvm, &d3_cfg_cmd);
if (ret)
goto out;
#ifdef <API key>
len = le32_to_cpu(d3_cfg_cmd.resp_pkt->len_n_flags) &
<API key>;
if (len >= sizeof(u32) * 2) {
mvm->d3_test_pme_ptr =
le32_to_cpup((__le32 *)d3_cfg_cmd.resp_pkt->data);
}
#endif
iwl_free_resp(&d3_cfg_cmd);
clear_bit(<API key>, &mvm->status);
<API key>(mvm->trans, test);
out:
mvm->aux_sta.sta_id = old_aux_sta_id;
mvm_ap_sta->sta_id = old_ap_sta_id;
mvmvif->ap_sta_id = old_ap_sta_id;
if (ret < 0)
<API key>(mvm->hw);
out_noreset:
kfree(key_data.rsc_tsc);
mutex_unlock(&mvm->mutex);
return ret;
}
int iwl_mvm_suspend(struct ieee80211_hw *hw, struct cfg80211_wowlan *wowlan)
{
return __iwl_mvm_suspend(hw, wowlan, false);
}
/* converted data from the different status responses */
struct <API key> {
u16 pattern_number;
u16 qos_seq_ctr[8];
u32 wakeup_reasons;
u32 wake_packet_length;
u32 wake_packet_bufsize;
const u8 *wake_packet;
};
static void <API key>(struct iwl_mvm *mvm,
struct ieee80211_vif *vif,
struct <API key> *status)
{
struct sk_buff *pkt = NULL;
struct <API key> wakeup = {
.pattern_idx = -1,
};
struct <API key> *wakeup_report = &wakeup;
u32 reasons = status->wakeup_reasons;
if (reasons == <API key>) {
wakeup_report = NULL;
goto report;
}
if (reasons & <API key>)
wakeup.magic_pkt = true;
if (reasons & <API key>)
wakeup.pattern_idx =
status->pattern_number;
if (reasons & (<API key> |
<API key>))
wakeup.disconnect = true;
if (reasons & <API key>)
wakeup.gtk_rekey_failure = true;
if (reasons & <API key>)
wakeup.rfkill_release = true;
if (reasons & <API key>)
wakeup.eap_identity_req = true;
if (reasons & <API key>)
wakeup.four_way_handshake = true;
if (reasons & <API key>)
wakeup.tcp_connlost = true;
if (reasons & <API key>)
wakeup.tcp_nomoretokens = true;
if (reasons & <API key>)
wakeup.tcp_match = true;
if (status->wake_packet_bufsize) {
int pktsize = status->wake_packet_bufsize;
int pktlen = status->wake_packet_length;
const u8 *pktdata = status->wake_packet;
struct ieee80211_hdr *hdr = (void *)pktdata;
int truncated = pktlen - pktsize;
/* this would be a firmware bug */
if (WARN_ON_ONCE(truncated < 0))
truncated = 0;
if (ieee80211_is_data(hdr->frame_control)) {
int hdrlen = ieee80211_hdrlen(hdr->frame_control);
int ivlen = 0, icvlen = 4; /* also FCS */
pkt = alloc_skb(pktsize, GFP_KERNEL);
if (!pkt)
goto report;
memcpy(skb_put(pkt, hdrlen), pktdata, hdrlen);
pktdata += hdrlen;
pktsize -= hdrlen;
if (<API key>(hdr->frame_control)) {
if (<API key>(hdr->addr1)) {
ivlen = mvm->gtk_ivlen;
icvlen += mvm->gtk_icvlen;
} else {
ivlen = mvm->ptk_ivlen;
icvlen += mvm->ptk_icvlen;
}
}
/* if truncated, FCS/ICV is (partially) gone */
if (truncated >= icvlen) {
icvlen = 0;
truncated -= icvlen;
} else {
icvlen -= truncated;
truncated = 0;
}
pktsize -= ivlen + icvlen;
pktdata += ivlen;
memcpy(skb_put(pkt, pktsize), pktdata, pktsize);
if (<API key>(pkt, vif->addr, vif->type))
goto report;
wakeup.packet = pkt->data;
wakeup.packet_present_len = pkt->len;
wakeup.packet_len = pkt->len - truncated;
wakeup.packet_80211 = false;
} else {
int fcslen = 4;
if (truncated >= 4) {
truncated -= 4;
fcslen = 0;
} else {
fcslen -= truncated;
truncated = 0;
}
pktsize -= fcslen;
wakeup.packet = status->wake_packet;
wakeup.packet_present_len = pktsize;
wakeup.packet_len = pktlen - truncated;
wakeup.packet_80211 = true;
}
}
report:
<API key>(vif, wakeup_report, GFP_KERNEL);
kfree_skb(pkt);
}
static void <API key>(struct aes_sc *sc,
struct ieee80211_key_seq *seq)
{
u64 pn;
pn = le64_to_cpu(sc->pn);
seq->ccmp.pn[0] = pn >> 40;
seq->ccmp.pn[1] = pn >> 32;
seq->ccmp.pn[2] = pn >> 24;
seq->ccmp.pn[3] = pn >> 16;
seq->ccmp.pn[4] = pn >> 8;
seq->ccmp.pn[5] = pn;
}
static void <API key>(struct tkip_sc *sc,
struct ieee80211_key_seq *seq)
{
seq->tkip.iv32 = le32_to_cpu(sc->iv32);
seq->tkip.iv16 = le16_to_cpu(sc->iv16);
}
static void <API key>(struct aes_sc *scs,
struct ieee80211_key_conf *key)
{
int tid;
BUILD_BUG_ON(IWL_NUM_RSC != IEEE80211_NUM_TIDS);
for (tid = 0; tid < IWL_NUM_RSC; tid++) {
struct ieee80211_key_seq seq = {};
<API key>(&scs[tid], &seq);
<API key>(key, tid, &seq);
}
}
static void <API key>(struct tkip_sc *scs,
struct ieee80211_key_conf *key)
{
int tid;
BUILD_BUG_ON(IWL_NUM_RSC != IEEE80211_NUM_TIDS);
for (tid = 0; tid < IWL_NUM_RSC; tid++) {
struct ieee80211_key_seq seq = {};
<API key>(&scs[tid], &seq);
<API key>(key, tid, &seq);
}
}
static void <API key>(struct ieee80211_key_conf *key,
struct <API key> *status)
{
union iwl_all_tsc_rsc *rsc = &status->gtk.rsc.all_tsc_rsc;
switch (key->cipher) {
case <API key>:
<API key>(rsc->aes.multicast_rsc, key);
break;
case <API key>:
<API key>(rsc->tkip.multicast_rsc, key);
break;
default:
WARN_ON(1);
}
}
struct <API key> {
struct <API key> *status;
void *last_gtk;
u32 cipher;
bool find_phase, unhandled_cipher;
int num_keys;
};
static void <API key>(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta,
struct ieee80211_key_conf *key,
void *_data)
{
struct <API key> *data = _data;
if (data->unhandled_cipher)
return;
switch (key->cipher) {
case <API key>:
case <API key>:
/* ignore WEP completely, nothing to do */
return;
case <API key>:
case <API key>:
/* we support these */
break;
default:
/* everything else (even CMAC for MFP) - disconnect from AP */
data->unhandled_cipher = true;
return;
}
data->num_keys++;
/*
* pairwise key - update sequence counters only;
* note that this assumes no TDLS sessions are active
*/
if (sta) {
struct ieee80211_key_seq seq = {};
union iwl_all_tsc_rsc *sc = &data->status->gtk.rsc.all_tsc_rsc;
if (data->find_phase)
return;
switch (key->cipher) {
case <API key>:
<API key>(&sc->aes.tsc, &seq);
<API key>(sc->aes.unicast_rsc, key);
break;
case <API key>:
<API key>(&sc->tkip.tsc, &seq);
<API key>(sc->tkip.unicast_rsc, key);
break;
}
<API key>(key, &seq);
/* that's it for this key */
return;
}
if (data->find_phase) {
data->last_gtk = key;
data->cipher = key->cipher;
return;
}
if (data->status->num_of_gtk_rekeys)
<API key>(key);
else if (data->last_gtk == key)
<API key>(key, data->status);
}
static bool <API key>(struct iwl_mvm *mvm,
struct ieee80211_vif *vif,
struct <API key> *status)
{
struct iwl_mvm_vif *mvmvif = <API key>(vif);
struct <API key> gtkdata = {
.status = status,
};
u32 <API key> =
<API key> |
<API key>;
if (!status || !vif->bss_conf.bssid)
return false;
if (le32_to_cpu(status->wakeup_reasons) & <API key>)
return false;
/* find last GTK that we used initially, if any */
gtkdata.find_phase = true;
ieee80211_iter_keys(mvm->hw, vif,
<API key>, >kdata);
/* not trying to keep connections with MFP/unhandled ciphers */
if (gtkdata.unhandled_cipher)
return false;
if (!gtkdata.num_keys)
goto out;
if (!gtkdata.last_gtk)
return false;
/*
* invalidate all other GTKs that might still exist and update
* the one that we used
*/
gtkdata.find_phase = false;
ieee80211_iter_keys(mvm->hw, vif,
<API key>, >kdata);
if (status->num_of_gtk_rekeys) {
struct ieee80211_key_conf *key;
struct {
struct ieee80211_key_conf conf;
u8 key[32];
} conf = {
.conf.cipher = gtkdata.cipher,
.conf.keyidx = status->gtk.key_index,
};
switch (gtkdata.cipher) {
case <API key>:
conf.conf.keylen = WLAN_KEY_LEN_CCMP;
memcpy(conf.conf.key, status->gtk.decrypt_key,
WLAN_KEY_LEN_CCMP);
break;
case <API key>:
conf.conf.keylen = WLAN_KEY_LEN_TKIP;
memcpy(conf.conf.key, status->gtk.decrypt_key, 16);
/* leave TX MIC key zeroed, we don't use it anyway */
memcpy(conf.conf.key +
<API key>,
status->gtk.tkip_mic_key, 8);
break;
}
key = <API key>(vif, &conf.conf);
if (IS_ERR(key))
return false;
<API key>(key, status);
}
if (status->num_of_gtk_rekeys) {
__be64 replay_ctr =
cpu_to_be64(le64_to_cpu(status->replay_ctr));
<API key>(vif, vif->bss_conf.bssid,
(void *)&replay_ctr, GFP_KERNEL);
}
out:
mvmvif->seqno_valid = true;
/* +0x10 because the set API expects next-to-use, not last-used */
mvmvif->seqno = le16_to_cpu(status->non_qos_seq_ctr) + 0x10;
return true;
}
/* releases the MVM mutex */
static bool <API key>(struct iwl_mvm *mvm,
struct ieee80211_vif *vif)
{
u32 base = mvm->error_event_table;
struct error_table_start {
/* cf. struct <API key> */
u32 valid;
u32 error_id;
} err_info;
struct iwl_host_cmd cmd = {
.id = WOWLAN_GET_STATUSES,
.flags = CMD_SYNC | CMD_WANT_SKB,
};
struct <API key> status;
struct <API key> *status_v6;
int ret, len, status_size, i;
bool keep;
struct ieee80211_sta *ap_sta;
struct iwl_mvm_sta *mvm_ap_sta;
<API key>(mvm->trans, base,
&err_info, sizeof(err_info));
if (err_info.valid) {
IWL_INFO(mvm, "error table is valid (%d)\n",
err_info.valid);
if (err_info.error_id == <API key>) {
struct <API key> wakeup = {
.rfkill_release = true,
};
<API key>(vif, &wakeup,
GFP_KERNEL);
}
goto out_unlock;
}
/* only for tracing for now */
ret = <API key>(mvm, OFFLOADS_QUERY_CMD, CMD_SYNC, 0, NULL);
if (ret)
IWL_ERR(mvm, "failed to query offload statistics (%d)\n", ret);
ret = iwl_mvm_send_cmd(mvm, &cmd);
if (ret) {
IWL_ERR(mvm, "failed to query status (%d)\n", ret);
goto out_unlock;
}
/* RF-kill already asserted again... */
if (!cmd.resp_pkt)
goto out_unlock;
if (mvm->fw->ucode_capa.flags & <API key>)
status_size = sizeof(struct <API key>);
else
status_size = sizeof(struct <API key>);
len = le32_to_cpu(cmd.resp_pkt->len_n_flags) & <API key>;
if (len - sizeof(struct iwl_cmd_header) < status_size) {
IWL_ERR(mvm, "Invalid WoWLAN status response!\n");
goto out_free_resp;
}
if (mvm->fw->ucode_capa.flags & <API key>) {
status_v6 = (void *)cmd.resp_pkt->data;
status.pattern_number = le16_to_cpu(status_v6->pattern_number);
for (i = 0; i < 8; i++)
status.qos_seq_ctr[i] =
le16_to_cpu(status_v6->qos_seq_ctr[i]);
status.wakeup_reasons = le32_to_cpu(status_v6->wakeup_reasons);
status.wake_packet_length =
le32_to_cpu(status_v6->wake_packet_length);
status.wake_packet_bufsize =
le32_to_cpu(status_v6->wake_packet_bufsize);
status.wake_packet = status_v6->wake_packet;
} else {
struct <API key> *status_v4;
status_v6 = NULL;
status_v4 = (void *)cmd.resp_pkt->data;
status.pattern_number = le16_to_cpu(status_v4->pattern_number);
for (i = 0; i < 8; i++)
status.qos_seq_ctr[i] =
le16_to_cpu(status_v4->qos_seq_ctr[i]);
status.wakeup_reasons = le32_to_cpu(status_v4->wakeup_reasons);
status.wake_packet_length =
le32_to_cpu(status_v4->wake_packet_length);
status.wake_packet_bufsize =
le32_to_cpu(status_v4->wake_packet_bufsize);
status.wake_packet = status_v4->wake_packet;
}
if (len - sizeof(struct iwl_cmd_header) !=
status_size + ALIGN(status.wake_packet_bufsize, 4)) {
IWL_ERR(mvm, "Invalid WoWLAN status response!\n");
goto out_free_resp;
}
/* still at hard-coded place 0 for D3 image */
ap_sta = <API key>(
mvm->fw_id_to_mac_id[0],
lockdep_is_held(&mvm->mutex));
if (IS_ERR_OR_NULL(ap_sta))
goto out_free_resp;
mvm_ap_sta = (struct iwl_mvm_sta *)ap_sta->drv_priv;
for (i = 0; i < IWL_MAX_TID_COUNT; i++) {
u16 seq = status.qos_seq_ctr[i];
/* firmware stores last-used value, we store next value */
seq += 0x10;
mvm_ap_sta->tid_data[i].seq_number = seq;
}
/* now we have all the data we need, unlock to avoid mac80211 issues */
mutex_unlock(&mvm->mutex);
<API key>(mvm, vif, &status);
keep = <API key>(mvm, vif, status_v6);
iwl_free_resp(&cmd);
return keep;
out_free_resp:
iwl_free_resp(&cmd);
out_unlock:
mutex_unlock(&mvm->mutex);
return false;
}
static void <API key>(struct iwl_mvm *mvm)
{
#ifdef <API key>
const struct fw_img *img = &mvm->fw->img[IWL_UCODE_WOWLAN];
u32 len = img->sec[<API key>].len;
u32 offs = img->sec[<API key>].offset;
if (!mvm-><API key>)
return;
if (!mvm->d3_resume_sram) {
mvm->d3_resume_sram = kzalloc(len, GFP_KERNEL);
if (!mvm->d3_resume_sram)
return;
}
<API key>(mvm->trans, offs, mvm->d3_resume_sram, len);
#endif
}
static void <API key>(void *data, u8 *mac,
struct ieee80211_vif *vif)
{
/* skip the one we keep connection on */
if (data == vif)
return;
if (vif->type == <API key>)
<API key>(vif);
}
static int __iwl_mvm_resume(struct iwl_mvm *mvm, bool test)
{
struct iwl_d3_iter_data resume_iter_data = {
.mvm = mvm,
};
struct ieee80211_vif *vif = NULL;
int ret;
enum iwl_d3_status d3_status;
bool keep = false;
mutex_lock(&mvm->mutex);
/* get the BSS vif pointer again */
<API key>(
mvm->hw, <API key>,
<API key>, &resume_iter_data);
if (WARN_ON(resume_iter_data.error || !resume_iter_data.vif))
goto out_unlock;
vif = resume_iter_data.vif;
ret = iwl_trans_d3_resume(mvm->trans, &d3_status, test);
if (ret)
goto out_unlock;
if (d3_status != IWL_D3_STATUS_ALIVE) {
IWL_INFO(mvm, "Device was reset during suspend\n");
goto out_unlock;
}
/* query SRAM first in case we want event logging */
<API key>(mvm);
keep = <API key>(mvm, vif);
#ifdef <API key>
if (keep)
mvm->keep_vif = vif;
#endif
/* has unlocked the mutex, so skip that */
goto out;
out_unlock:
mutex_unlock(&mvm->mutex);
out:
if (!test)
<API key>(mvm->hw,
<API key>,
<API key>, keep ? vif : NULL);
/* return 1 to reconfigure the device */
set_bit(<API key>, &mvm->status);
return 1;
}
int iwl_mvm_resume(struct ieee80211_hw *hw)
{
struct iwl_mvm *mvm = <API key>(hw);
return __iwl_mvm_resume(mvm, false);
}
void iwl_mvm_set_wakeup(struct ieee80211_hw *hw, bool enabled)
{
struct iwl_mvm *mvm = <API key>(hw);
<API key>(mvm->trans->dev, enabled);
}
#ifdef <API key>
static int <API key>(struct inode *inode, struct file *file)
{
struct iwl_mvm *mvm = inode->i_private;
int err;
if (mvm->d3_test_active)
return -EBUSY;
file->private_data = inode->i_private;
<API key>(mvm->hw);
synchronize_net();
/* start pseudo D3 */
rtnl_lock();
err = __iwl_mvm_suspend(mvm->hw, mvm->hw->wiphy->wowlan_config, true);
rtnl_unlock();
if (err > 0)
err = -EINVAL;
if (err) {
<API key>(mvm->hw);
return err;
}
mvm->d3_test_active = true;
mvm->keep_vif = NULL;
return 0;
}
static ssize_t <API key>(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct iwl_mvm *mvm = file->private_data;
u32 pme_asserted;
while (true) {
/* read pme_ptr if available */
if (mvm->d3_test_pme_ptr) {
pme_asserted = <API key>(mvm->trans,
mvm->d3_test_pme_ptr);
if (pme_asserted)
break;
}
if (<API key>(100))
break;
}
return 0;
}
static void <API key>(void *_data, u8 *mac,
struct ieee80211_vif *vif)
{
/* skip the one we keep connection on */
if (_data == vif)
return;
if (vif->type == <API key>)
<API key>(vif);
}
static int <API key>(struct inode *inode, struct file *file)
{
struct iwl_mvm *mvm = inode->i_private;
int remaining_time = 10;
mvm->d3_test_active = false;
__iwl_mvm_resume(mvm, true);
<API key>(&mvm->notif_wait);
<API key>(mvm->hw);
/* wait for restart and disconnect all interfaces */
while (test_bit(<API key>, &mvm->status) &&
remaining_time > 0) {
remaining_time
msleep(1000);
}
if (remaining_time == 0)
IWL_ERR(mvm, "Timed out waiting for HW restart to finish!\n");
<API key>(
mvm->hw, <API key>,
<API key>, mvm->keep_vif);
<API key>(mvm->hw);
return 0;
}
const struct file_operations <API key> = {
.llseek = no_llseek,
.open = <API key>,
.read = <API key>,
.release = <API key>,
};
#endif
|
<div class="row">
<div class="col-sm-12">
<div class="row">
<div class="text-center">
<h1 class="tada animated font-xl ">
<span style="position: relative;">
<i class="fa fa-play fa-rotate-90 fa-border fa-4x"></i>
<span>
<?php if($updated): ?>
<b style="position:absolute; right: -30px; top:-10" class="badge bg-color-green font-md"><i class="fa fa-check txt-color-black"></i> </b>
<?php else: ?>
<b style="position:absolute; right: -30px; top:-10" class="badge bg-color-red font-md"><i class="fa fa-refresh error"></i></b>
<?php endif; ?>
</span>
</span>
</h1>
<?php if($updated): ?>
<h2 class="font-xl"><strong>Great! Your FABtotum Personal Fabricator is up to date</strong></h2>
<?php else: ?>
<h2 class="font-xl title"><strong> New important software updates are now available</strong></h2>
<button id="update" class="btn btn-lg bg-color-red txt-color-white">Update now!</button>
<p class="lead semi-bold">
<small class="off-message hidden">Please don't turn off the printer until the operation is completed</small>
</p>
<button data-toggle="modal" data-backdrop="static" data-target="#modal" class="btn btn-xs bg-color-blue txt-color-white " style=""> See what's new!</button>
<?php endif; ?>
</div>
</div>
<?php if(!$updated): ?>
<div class="row">
<div class="col-sm-12">
<div class="text-center margin-top-10">
<div class="well mini">
<p class="text-left">
<span class="download-info">Downloading update files</span> <span class="pull-right"> <span class="percent"></span> </span>
</p>
<div class="progress">
<div class="progress progress-striped">
<div class="progress-bar download-progress bg-color-blue" role="progressbar" style="width: 0%"></div>
</div>
</div>
</div>
<button id="cancel" class="btn btn-lg bg-color-red txt-color-white"> Cancel</button>
</div>
</div>
</div>
<?php endif; ?>
</div>
</div>
<?php if(!$updated): ?>
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×
</button>
<h4 class="modal-title" id="myModalLabel">FABUI v.<?php echo $remote_version; ?> Changelog</h4>
</div>
<div class="modal-body no-padding">
<?php echo fabui_changelog($remote_version) ?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">OK</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
<?php endif; ?>
|
.icon-large{font-size:1.3333333333333333em;margin-top:-4px;padding-top:3px;margin-bottom:-4px;padding-bottom:3px;vertical-align:middle;}
.nav [class^="icon-"],.nav [class*=" icon-"]{vertical-align:inherit;margin-top:-4px;padding-top:3px;margin-bottom:-4px;padding-bottom:3px;}.nav [class^="icon-"].icon-large,.nav [class*=" icon-"].icon-large{vertical-align:-25%;}
.nav-pills [class^="icon-"].icon-large,.nav-tabs [class^="icon-"].icon-large,.nav-pills [class*=" icon-"].icon-large,.nav-tabs [class*=" icon-"].icon-large{line-height:.75em;margin-top:-7px;padding-top:5px;margin-bottom:-5px;padding-bottom:4px;}
.btn [class^="icon-"].pull-left,.btn [class*=" icon-"].pull-left,.btn [class^="icon-"].pull-right,.btn [class*=" icon-"].pull-right{vertical-align:inherit;}
.btn [class^="icon-"].icon-large,.btn [class*=" icon-"].icon-large{margin-top:-0.5em;}
a [class^="icon-"],a [class*=" icon-"]{cursor:pointer;}
.icon-glass{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-music{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-search{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-envelope-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-heart{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-star{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-star-empty{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-user{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-film{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-th-large{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-th{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-th-list{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-ok{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-remove{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-zoom-in{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-zoom-out{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-off{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-power-off{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-signal{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-cog{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-trash{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-home{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-file-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-time{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-road{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-download-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-download{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-upload{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-inbox{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-play-circle{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-repeat{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-rotate-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-refresh{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-list-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-lock{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-flag{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-headphones{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-volume-off{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-volume-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-volume-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-qrcode{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-barcode{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-tag{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-tags{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-book{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bookmark{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-print{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-camera{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-font{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bold{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-italic{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-text-height{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-text-width{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-align-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-align-center{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-align-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-align-justify{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-list{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-indent-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-indent-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-facetime-video{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-picture{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-pencil{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-map-marker{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-adjust{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-tint{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-edit{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-share{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-check{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-move{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-step-backward{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-fast-backward{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-backward{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-play{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-pause{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-stop{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-forward{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-fast-forward{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-step-forward{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-eject{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-chevron-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-chevron-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-plus-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-minus-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-remove-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-ok-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-question-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-info-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-screenshot{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-remove-circle{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-ok-circle{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-ban-circle{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-arrow-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-arrow-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-arrow-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-arrow-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-share-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-mail-forward{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-resize-full{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-resize-small{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-plus{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-minus{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-asterisk{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-gift{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-leaf{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-fire{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-eye-open{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-eye-close{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-warning-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-plane{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-calendar{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-random{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-comment{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-magnet{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-chevron-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-chevron-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-retweet{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-shopping-cart{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-folder-close{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-folder-open{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bar-chart{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-twitter-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-facebook-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-camera-retro{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-key{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-cogs{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-comments{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-thumbs-up-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-star-half{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-heart-empty{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-signout{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-linkedin-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-pushpin{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-external-link{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-signin{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-trophy{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-github-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-upload-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-lemon{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-phone{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-check-empty{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-unchecked{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bookmark-empty{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-phone-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-twitter{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-facebook{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-github{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-unlock{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-credit-card{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-rss{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-hdd{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bullhorn{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bell{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-certificate{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-hand-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-hand-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-hand-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-hand-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-globe{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-wrench{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-tasks{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-filter{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-briefcase{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-fullscreen{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-group{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-link{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-cloud{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-beaker{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-cut{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-copy{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-paper-clip{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-paperclip{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-save{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-sign-blank{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-reorder{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-list-ul{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-list-ol{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-strikethrough{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-underline{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-table{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-magic{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-truck{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-pinterest{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-pinterest-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-google-plus{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-money{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-caret-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-caret-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-caret-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-caret-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-columns{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-sort{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-sort-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-sort-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-envelope{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-linkedin{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-undo{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-rotate-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-legal{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-dashboard{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-comment-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-comments-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bolt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-sitemap{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-umbrella{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-paste{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-lightbulb{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-exchange{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-cloud-download{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-cloud-upload{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-user-md{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-stethoscope{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-suitcase{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bell-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-coffee{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-food{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-file-text-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-building{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-hospital{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-ambulance{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-medkit{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-fighter-jet{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-beer{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-h-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-plus-sign-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-angle-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-angle-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-angle-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-angle-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-desktop{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-laptop{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-tablet{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-mobile-phone{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-circle-blank{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-quote-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-quote-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-spinner{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-circle{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-reply{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-mail-reply{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-github-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-expand-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-collapse-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-smile{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-frown{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-meh{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-gamepad{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-keyboard{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-flag-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-flag-checkered{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-terminal{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-code{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-reply-all{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-mail-reply-all{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-star-half-full{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-location-arrow{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-crop{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-code-fork{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-unlink{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-question{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-info{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-exclamation{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-superscript{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-subscript{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-eraser{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-puzzle-piece{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-microphone{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-microphone-off{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-shield{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-calendar-empty{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-rocket{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-maxcdn{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-html5{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-css3{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-anchor{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-unlock-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bullseye{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-rss-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-play-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-ticket{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-minus-sign-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-check-minus{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-level-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-level-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-check-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-edit-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-share-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-compass{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-collapse{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-collapse-top{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-expand{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-eur{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-euro{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-gbp{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-usd{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-dollar{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-inr{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-rupee{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-jpy{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-yen{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-cny{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-renminbi{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-krw{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-won{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-btc{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bitcoin{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-file{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-file-text{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-sort-by-order{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-thumbs-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-thumbs-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-youtube-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-youtube{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-xing{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-xing-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-youtube-play{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-dropbox{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-stackexchange{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-instagram{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-flickr{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-adn{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bitbucket{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bitbucket-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-tumblr{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-tumblr-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-long-arrow-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.<API key>{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-apple{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-windows{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-android{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-linux{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-dribble{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-skype{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-foursquare{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-trello{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-female{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-male{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-gittip{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-sun{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-moon{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-archive{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bug{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-vk{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-weibo{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-renren{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
|
include ../../Makerules
OBJ=halftrace.o prepare_ref.o ray_lay.o ray_xyz.o refmod_all.o ref_time.o reftrace.o vrefmod.o
%.o:%.f90
$(FC) -c $(FFLAGS) $<
all: compile
compile: $(OBJ)
clean:
@rm -f $(OBJ)
|
<h2 class="page-header"><a href="<?= $Page->Url ?>"><?= $Page->Title ?></a></h2>
<?= $Page->Content ?>
|
<div align="center"><a href="/onestop/metadata-manager">Metadata Manager Documentation Home</a></div>
<hr>
**Estimated Reading Time: 15 minutes**
# Upstream Connecting via Kafka
## Table of Contents
* [Integrating upstream application to the underlying Kafka system](#<API key>)
* [Features](#features)
* [Apache NiFi](#apache-nifi)
* [Nifi as a Producer](#nifi-as-a-producer)
* [Nifi as bidirectional Data Flows](#<API key>)
* [kafka producer](#kafka-producer)
* [Kafka connects](#kafka-connects)
## Integrating upstream application to the underlying Kafka system
Metadata can be published into the OneStop system in two different ways, using Registry application [REST API](<API key>) or directly
integrating upstream applications to the underline OneStop kafka cluster.
This guide will take a look at some approaches for integrating upstream applications and Kafka, and look at some examples regarding the tools Kafka supports.
Before we dive in, it's worth mentioning the single common data format, Apache Avro, which OneStop application is using for ensuring all data sources and integration points comply to it.
Apache Avro is an [open source data serialization format](http://avro.apache.org/docs/1.9.1/). It relies on schema that define fields and their type. Avro also supports schema evolution.
See [Avro schema project](https://github.com/cedardevs/schemas/tree/master/schemas-core) for details.
## Features
- [Using Apache NiFi](#apache-niFi)
- [Using kafka producer](#kafka-producer)
- [Using Kafka connects](#kafka-connects)
Apache NiFi
NiFi is a highly scalable and user friendly UI based system that provides support for data collection and processing. In this case,
Nifi can act as a source and sink to bring data to and from Kafka, which helps in automating the flow of data between systems in a Reliable, efficient, and manageable way.
NiFi is able to support multiple versions of the Kafka client in a single NiFi instance. The Apache NiFi 1.10.0 release contains the following Kafka processors:
- ConsumeKafka & PublishKafka using the 0.9 client
- ConsumeKafka_1_0 & PublishKafka_1_0 using the 1.0 client
- ConsumeKafka_2_0 & PublishKafka_2_0 using the 2.0 client
Kafka does not necessarily provide backward compatibility between versions, so use kafka processors that is compatible with the OneStop kafka broker version.
See [Apache NiFi website](https://nifi.apache.org/) page for details.
# Nifi as a Producer
A simple use case of NiFi is to act as a Kafka producer, which can bring data from sources directly to a NiFi instance, which can then deliver
data to the appropriate Kafka topic. Each instance of PublishKafka could have concurrent tasks executing and each of this tasks publishes messages independently.
Here is the NiFi template with two processors and controller services configuration:

The above example uses GenerateFlowFile processor to create FlowFiles of random data and PublishKafkaRecord processor with the Confluent Schema Registry to publish records to kafka.
Sample Nifi template [download the sample nifi template](sampleCode/<API key>.xml).
# Nifi as bidirectional Data Flows
Additional and more complex use case is combining tools such as Kafka, and kafka stream processing platform with Nifi to create a self-adjusting data flow. Kafka Stream is a lightweight library for creating stream processing applications.
In this case, NiFi brings data to Kafka which makes it available to a stream processing platform with the results being written back to a different Kafka topic for downstream consumers.
kafka producer
kafka producer uses a Kafka producer API to write a producer that can be used to published record directly to kafka broker. see [kafka producer Confluent docs](https://docs.confluent.io/current/clients/producer.html) page for details.
Let's look at a simple Kafka producer implementation using java.
To create a Kafka producer, you need to pass a list of bootstrap servers/Kafka brokers and also specify a client.id that uniquely identifies this Producer client.
you will need to specify a Key_serializer and a value_serializer, which Kafka will use to encode the message id as a Kafka record key, and the message body as the Kafka record value.
Import the Kafka packages and define a constant for the producer to connect to the Kafka broker.
java
import io.confluent.kafka.serializers.<API key>;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
public class KafkaProducerTest {
private final static String TOPIC = "test-topic";
private final static String BOOTSTRAP_SERVERS = "localhost:9092";
private final static String SCHEMA_REGISTRY_URL = "localhost:8081";
private final static String CLIENT_ID = "test-client";
private final static String COMPRESSION_TYPE = "zstd";
private static Producer<Long, String> createProducer() {
props.put(ProducerConfig.<API key>, BOOTSTRAP_SERVERS);
props.put(<API key>.<API key>, SCHEMA_REGISTRY_URL);
props.put(ProducerConfig.CLIENT_ID_CONFIG, CLIENT_ID);
props.put(ProducerConfig.<API key>, COMPRESSION_TYPE);
props.put(ProducerConfig.<API key>, StringSerializer.class.name);
props.put(ProducerConfig.<API key>, KafkaAvroSerializer.class.name);
return new KafkaProducer<>(props);
}
}
The constant <API key> is set to `http://localhost:9092` as default which also can be a comma separated list that the Producer uses to establish an initial connection to the Kafka cluster.
The CLIENT_ID_CONFIG value is an id to pass to the server when making requests so the server can track the source of requests.
The <API key> value is a Kafka Serializer class for Kafka record keys that implements the Kafka Serializer interface. Notice that we set this to StringSerializer as the message ids type.
The <API key> value is a Kafka Serializer class for Kafka record values that implements the Kafka Serializer interface. Notice that we set this to <API key> as the message body in OneStop is in Avro format.
Import an Avro schema packages and changing an incoming message to Avro format.
java
import org.cedar.schemas.avro.psi.Input;
import org.cedar.schemas.avro.psi.Method;
import org.cedar.schemas.avro.psi.OperationType;
import org.cedar.schemas.avro.psi.RecordType;
public class KafkaProducerTest {
private static Input <API key>(Map info) {
Input.Builder builder = Input.newBuilder();
builder.setType(RecordType.collection);
builder.setMethod(Method.PUT);
builder.setContent(String.valueOf(info));
builder.setContentType(CONTENT_TYPE);
builder.setSource(SOURCE);
builder.setOperation(OperationType.NO_OP);
return builder.build();
}
}
The builder is setting the require fields which is define here in the [Input avro schema definition](https://github.com/cedardevs/schemas/blob/master/schemas-core/src/main/resources/avro/psi/input.avsc).
see [sample kafka producer java code](sampleCode/kafkaSampleTest.java) file for detail.
Kafka connects
Kafka connect, which includes source and sink, can also be used to published data from upstream source into kafka broker.
see [kafka connect Confluent page](https://docs.confluent.io/current/connect/index.html) for more details.
<hr>
<div align="center"><a href="#">Top of Page</a></div>
|
<?
session_start();
session_destroy();
header("Location: ../index.html");
?>
|
// <auto-generated>
// This code was generated from a template.
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
namespace XORCISMModel
{
using System;
using System.Collections.Generic;
public partial class LIBRARYREFERENCE
{
public int LibraryReferenceID { get; set; }
}
}
|
<link rel="stylesheet" type="text/css" href="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/css/jquery.jscrollpane.custom.css" />
<link rel="stylesheet" type="text/css" href="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/css/bookblock.css" />
<link rel="stylesheet" type="text/css" href="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/css/custom.css" />
<script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/modernizr.custom.79639.js"></script>
<div id="container" class="container">
<div class="menu-panel">
<h3>Table of Contents</h3>
<ul id="menu-toc" class="menu-toc">
<?php print $menu_items; ?>
</ul>
</div>
<div class="bb-custom-wrapper">
<div id="bb-bookblock" class="bb-bookblock">
<?php print $item_content; ?>
</div>
<nav>
<span id="bb-nav-prev">←</span>
<span id="bb-nav-next">→</span>
</nav>
<span id="tblcontents" class="menu-button">Table of Contents</span>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/jquery.mousewheel.js"></script>
<script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/jquery.jscrollpane.min.js"></script>
<script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/jquerypp.custom.js"></script>
<script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/jquery.bookblock.js"></script>
<script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/page.js"></script>
<script>
$(function() {
Page.init();
});
</script>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect, HttpResponse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from subscriber.models import Consumer, ConsumerType, Recharge, TotalRecharge, ACL
from product.models import Product
from voice_records.models import VoiceRecord, VoiceReg
from sms.models import SMSPayment
# from local_lib.v3 import is_number, is_float
from local_lib.v3 import is_number, is_float, <API key>, is_japanese_number, send_sms
from transaction.models import Transaction, <API key>, BuyerSellerAccount, dueTransaction
from shop_inventory.models import Inventory, <API key>, <API key>
from <API key>.models import Transcriber, <API key>, FailedTranscription
import datetime
from django.db.models import Q
from django.contrib.auth.models import User
from django.contrib.sessions.backends.db import SessionStore
from django.db.models import Count
@csrf_exempt
def login_page(request):
return render(request, 'pages/login.html')
@csrf_exempt
def login_auth(request):
postdata = request.POST
print(postdata)
if 'username' and 'password' in postdata:
print(postdata['username'])
login_username = postdata['username']
print(postdata['password'])
if ACL.objects.filter(loginID=postdata['username'][-9:]).exists():
login_username = login_username[-9:]
else:
login_username = login_username
user = authenticate(username=login_username, password=postdata['password'])
if user is not None:
if user.is_active:
login(request, user)
request.session['user'] = login_username
if user.is_superuser:
res = redirect('/admin')
else:
res = redirect('/')
else:
res = render(request, 'pages/login.html',
{'wrong': True,
'text': 'The password is valid, but the account has been disabled!'})
else:
res = render(request, 'pages/login.html',
{'wrong': True,
'text': 'The username and password you have entered is not correct. Please retry'})
else:
res = render(request, 'pages/login.html', {'wrong': False})
res['<API key>'] = "*"
res['<API key>'] = "Origin, X-Requested-With, Content-Type, Accept"
res['<API key>'] = "PUT, GET, POST, DELETE, OPTIONS"
return res
def logout_now(request):
logout(request)
return render(request, 'pages/login.html')
@login_required(login_url='/login/')
def home(request):
transcriber_name = request.session['user']
print request.session['user']
if ACL.objects.filter(loginID=transcriber_name).exists():
login_user = ACL.objects.get(loginID=transcriber_name)
print(login_user.loginUser.name)
transcriber_name = login_user.loginUser.name
if login_user.loginUser.type.type_name == 'Distributor':
if login_user.loginUser.number_of_child == 'CHANGED !!!':
return render(request, 'pages/Distributor/index.html', {'transcriber_name': transcriber_name})
else:
return redirect('/change_password/')
elif login_user.loginUser.type.type_name == 'SR':
if login_user.loginUser.number_of_child == 'CHANGED !!!':
return render(request, 'pages/SR/index.html', {'transcriber_name': transcriber_name})
else:
return redirect('/change_password/')
elif login_user.loginUser.type.type_name == 'Seller':
if login_user.loginUser.number_of_child == 'CHANGED !!!':
return render(request, 'pages/Shop/index.html', {'transcriber_name': transcriber_name})
else:
return redirect('/change_password/')
elif login_user.loginUser.type.type_name == 'Buyer':
if login_user.loginUser.number_of_child == 'CHANGED !!!':
return render(request, 'pages/Consumer/index.html', {'transcriber_name': transcriber_name})
else:
return redirect('/change_password/')
else:
number_of_reg_calls = VoiceReg.objects.filter().count()
<API key> = VoiceRecord.objects.filter().count()
total = number_of_reg_calls + <API key>
if total > 0:
reg_call_percentage = (number_of_reg_calls / float(total)) * 100
<API key> = (<API key> / float(total)) * 100
else:
<API key> = 0
reg_call_percentage = 0
today_month = datetime.date.today().month
today_year = datetime.date.today().year
count = 1
data_2 = ''
data_3 = ''
data_4 = ''
data_5 = ''
data_6 = ''
max = 0
max_table_2 = 0
total_sell = VoiceRecord.objects.filter(purpose='sell').count()
total_buy = VoiceRecord.objects.filter(purpose='buy').count()
<API key> = SMSPayment.objects.filter().count()
total_for_chart2 = number_of_reg_calls + <API key>
if total_for_chart2 > 0:
sell_percentage = (total_sell / float(total_for_chart2)) * 100
buy_percentage = (total_buy / float(total_for_chart2)) * 100
<API key> = (<API key> / float(total_for_chart2)) * 100
else:
sell_percentage = 0
buy_percentage = 0
<API key> = 0
while count < 32:
total_call_that_day = VoiceRecord.objects.filter(DateAdded__month=today_month,
DateAdded__year=today_year, DateAdded__day=count).count()
total_reg_that_day = VoiceReg.objects.filter(DateAdded__month=today_month,
DateAdded__year=today_year, DateAdded__day=count).count()
if max < total_call_that_day:
max = total_call_that_day + 2
if max < total_reg_that_day:
max = total_reg_that_day + 2
data_2 += '[gd(%s, %s, %s), %s],' % (today_year, today_month, count, total_call_that_day)
data_3 += '[gd(%s, %s, %s), %s],' % (today_year, today_month, count, total_reg_that_day)
total_buy_that_day = VoiceRecord.objects.filter(DateAdded__month=today_month,
DateAdded__year=today_year,
DateAdded__day=count,
purpose='buy').count()
total_sell_that_day = VoiceRecord.objects.filter(DateAdded__month=today_month,
DateAdded__year=today_year,
DateAdded__day=count,
purpose='sell').count()
<API key> = SMSPayment.objects.filter(DateAdded__month=today_month,
DateAdded__year=today_year,
DateAdded__day=count).count()
if max_table_2 < total_buy_that_day:
max_table_2 = total_buy_that_day + 2
if max_table_2 < total_sell_that_day:
max_table_2 = total_sell_that_day + 2
if max_table_2 < <API key>:
max_table_2 = <API key> + 2
data_4 += '[gd(%s, %s, %s), %s],' % (today_year, today_month, count, total_buy_that_day)
data_5 += '[gd(%s, %s, %s), %s],' % (today_year, today_month, count, total_sell_that_day)
data_6 += '[gd(%s, %s, %s), %s],' % (today_year, today_month, count, <API key>)
count += 1
data_2 = data_2[:-1]
data_3 = data_3[:-1]
data_4 = data_4[:-1]
data_5 = data_5[:-1]
data_6 = data_6[:-1]
<API key> = Transaction.objects.filter().count()
<API key> = Transaction.objects.filter(total_due__gt=0).count()
<API key> = Transaction.objects.filter(total_due__lte=0).count()
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
print(<API key>.count)
return render(request, 'pages/index.html', {'shop_list_base': all_shop_for_base,
'number_of_reg_calls': number_of_reg_calls,
'transcriber_name': transcriber_name,
'<API key>': <API key>,
'<API key>' :<API key>,
'reg_call_percentage': reg_call_percentage,
'<API key>': <API key>,
'data_2': data_2,
'data_3': data_3,
'data_4': data_4,
'data_5': data_5,
'data_6': data_6,
'max': max,
'<API key>': <API key>,
'<API key>': <API key>,
'<API key>': <API key>,
'max_table_2': max_table_2,
'total_sell': total_sell,
'total_buy': total_buy,
'<API key>': <API key>,
'sell_percentage': sell_percentage,
'buy_percentage': buy_percentage,
'<API key>': <API key>,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def translator_page(request):
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/translator.html', {'shop_list_base': all_shop_for_base,
'<API key>' :<API key>,
'transcriber_name': transcriber_name,
'all_user_for_base': all_user_for_base})
# all report views are here
@login_required(login_url='/login/')
def report_monthly_shop(request):
get_data = request.GET
if 'ban' in get_data:
bangla = True
else:
bangla = False
shop_name = get_data['shop']
shop_object = Consumer.objects.get(name=shop_name)
shop_id = shop_object.id
total_sell = 0
total_sell_due = 0
total_sell_paid = 0
total_purchase = 0
total_purchase_due = 0
total_purchase_paid = 0
for month_sell in BuyerSellerAccount.objects.filter(seller=shop_object):
total_sell += month_sell.<API key>
total_sell_due += month_sell.total_due
total_sell_paid += month_sell.total_paid
for month_purchase in BuyerSellerAccount.objects.filter(buyer=shop_object):
total_purchase += month_purchase.<API key>
total_purchase_due += month_purchase.total_due
total_purchase_paid += month_purchase.total_paid
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/report_monthly_shop.html', {'shop_list_base': all_shop_for_base,
'shop_name': shop_name,
'shop_id': shop_id,
'<API key>' :<API key>,
'total_sell': total_sell,
'transcriber_name': transcriber_name,
'total_sell_due': total_sell_due,
'total_sell_paid': total_sell_paid,
'bangla': bangla,
'total_purchase': total_purchase,
'total_purchase_due': total_purchase_due,
'total_purchase_paid': total_purchase_paid,
'all_user_for_base': all_user_for_base})
# <API key>
@login_required(login_url='/login/')
def <API key>(request):
get_data = request.GET
shop_name = get_data['shop']
shop_object = Consumer.objects.get(id=shop_name)
shop_inventory = <API key>.objects.filter(shop=shop_object)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
output = '{"data": [ '
if get_data['t'] == '1':
rank = 1
this_year = datetime.date.today().year
# this_month = 1
this_day = 1
for this_month in range(1, 13, 1):
count = 0
for this_day in range(1, 32, 1):
for a_product in Product.objects.all():
product_price = 0
product_name = a_product.name
total_sell = 0
total_due = 0
total_paid = 0
for <API key> in Transaction.objects.filter(seller=shop_object,
DateAdded__year=this_year,
DateAdded__month=this_month,
DateAdded__day=this_day):
total_sell += <API key>.total_amount
total_due += <API key>.total_due
total_paid += <API key>.total_paid
count += 1
total_purchase = 0
total_purchase_due = 0
total_purchase_paid = 0
for <API key> in Transaction.objects.filter(buyer=shop_object,
DateAdded__year=this_year,
DateAdded__month=this_month,
DateAdded__day=this_day):
total_purchase += <API key>.total_amount
total_purchase_due += <API key>.total_due
total_purchase_paid += <API key>.total_paid
count += 1
if count > 0:
output += '["%s/%s/%s","%s","%s","%s","%s","%s","%s"] ,' % (this_day, this_month, this_year,
total_sell, total_paid, total_due,
total_purchase, total_purchase_paid,
total_purchase_due)
count = 0
# this_day += 1
# this_month = this_month + 1
if get_data['t'] == '2':
for <API key> in Transaction.objects.filter(Q(seller=shop_object) | Q(buyer=shop_object)):
# start counting for this product
id = <API key>.pk
date = <API key>.DateAdded
if <API key>.seller == shop_object:
with_trade = <API key>.buyer
trade_type = 'Sell'
elif <API key>.buyer == shop_object:
with_trade = <API key>.seller
trade_type = 'Buy'
number_of_items = <API key>.objects.filter(TID=<API key>).count()
total_amount = <API key>.total_amount
total_paid = <API key>.total_paid
total_due = <API key>.total_due
output += '["%s","%s","%s","%s","%s","%s","%s","%s"] ,' % (id, date, with_trade, trade_type,
number_of_items, total_amount,
total_paid, total_due)
output = output[:-1]
output += ']}'
return HttpResponse(output, content_type="text/plain")
@login_required(login_url='/login/')
def <API key>(request):
get_data = request.GET
shop_name = get_data['shop']
shop_object = Consumer.objects.get(name=shop_name)
shop_id = shop_object.id
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
if 'ban' in get_data:
bangla = True
else:
bangla = False
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/<API key>.html', {'shop_list_base': all_shop_for_base,
'shop_name': shop_name,
'<API key>' :<API key>,
'shop_id': shop_id,
'bangla': bangla,
'transcriber_name': transcriber_name,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def <API key>(request):
get_data = request.GET
shop_name = get_data['shop']
shop_object = Consumer.objects.get(id=shop_name)
shop_inventory = <API key>.objects.filter(shop=shop_object)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
output = '{"data": [ '
if get_data['t'] == '1':
rank = 1
for a_product in Product.objects.all():
count = 0
product_price = 0
product_name = a_product.name
for <API key> in Transaction.objects.filter(seller=shop_object):
# start counting for this product
for <API key> in <API key>.objects.filter(TID=<API key>):
if <API key>.product == a_product:
if <API key>.unit == a_product.bulk_wholesale_unit:
if a_product.bulk_to_retail_unit == 0:
count = count + <API key>.quantity
product_price = product_price + <API key>.price_per_unit
else:
count = count + <API key>.quantity * a_product.bulk_to_retail_unit
product_price = product_price + <API key>.price_per_unit / a_product.bulk_to_retail_unit
else:
count = count + <API key>.quantity
product_price = product_price + <API key>.price_per_unit
if count > 0:
output += '["%s","%s","%s"] ,' % (rank, product_name, str(count) + ' ' + a_product.retail_unit)
rank += 1
if get_data['t'] == '2':
rank = 1
for a_product in Product.objects.all():
count = 0
product_price = 0
<API key> = 0
change = 0
product_name = a_product.name
for <API key> in Transaction.objects.filter(seller=shop_object):
# start counting for this product
for <API key> in <API key>.objects.filter(TID=<API key>):
if <API key>.product == a_product:
if count == 0:
<API key> = <API key>.price_per_unit
product_price = <API key>.price_per_unit
change += abs(<API key> - product_price)
count += 1
if count > 0:
output += '["%s","%s","%s","%s"] ,' % (rank, product_name, count,
change/count)
rank += 1
if get_data['t'] == '3':
this_year = datetime.date.today().year
this_month = datetime.date.today().month
day = 1
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
while day < 32:
day_string = True
rank = 1
for a_product in Product.objects.all():
count = 0
product_price = 0
product_name = a_product.name
for <API key> in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year,
DateAdded__month=this_month, DateAdded__day=day):
# start counting for this product
for <API key> in <API key>.objects.filter(TID=<API key>):
if <API key>.product == a_product:
if <API key>.unit == a_product.bulk_wholesale_unit:
if a_product.bulk_to_retail_unit == 0:
count = count + <API key>.quantity
product_price = product_price + <API key>.price_per_unit
else:
count = count + <API key>.quantity * a_product.bulk_to_retail_unit
product_price = product_price + <API key>.price_per_unit / a_product.bulk_to_retail_unit
else:
count = count + <API key>.quantity
product_price = product_price + <API key>.price_per_unit
if count > 0:
if day_string:
output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
day_string = False
output += '["","%s","%s","%s","%s"] ,' % (rank, product_name,
str(count) + ' ' + a_product.retail_unit,
float(product_price / count))
rank += 1
day += 1
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
if get_data['t'] == '4':
day = 1
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
while day < 8:
day_string = True
rank = 1
for a_product in Product.objects.all():
count = 0
product_price = 0
product_name = a_product.name
for <API key> in Transaction.objects.filter(seller=shop_object, DateAdded__week_day=day):
# start counting for this product
for <API key> in <API key>.objects.filter(TID=<API key>):
if <API key>.product == a_product:
if <API key>.unit == a_product.bulk_wholesale_unit:
if a_product.bulk_to_retail_unit == 0:
count = count + <API key>.quantity
product_price = product_price + <API key>.price_per_unit
else:
count = count + <API key>.quantity * a_product.bulk_to_retail_unit
product_price = product_price + <API key>.price_per_unit / a_product.bulk_to_retail_unit
else:
count = count + <API key>.quantity
product_price = product_price + <API key>.price_per_unit
if count > 0:
if day_string:
if day == 1:
output += '["%s","","","",""] ,' % 'Sunday'
elif day == 2:
output += '["%s","","","",""] ,' % 'Monday'
elif day == 3:
output += '["%s","","","",""] ,' % 'Tuesday'
elif day == 4:
output += '["%s","","","",""] ,' % 'Wednesday'
elif day == 5:
output += '["%s","","","",""] ,' % 'Thursday'
elif day == 6:
output += '["%s","","","",""] ,' % 'Friday'
elif day == 7:
output += '["%s","","","",""] ,' % 'Saturday'
day_string = False
output += '["","%s","%s","%s","%s"] ,' % (rank, product_name,
str(count) + ' ' + a_product.retail_unit,
float(product_price / count))
rank += 1
day += 1
if get_data['t'] == '5':
this_year = datetime.date.today().year
day_string = True
for a_product in Product.objects.all():
count = 0
product_profit = 0
product_name = a_product.name
for <API key> in <API key>.objects.filter(shop_id=shop_object):
# start counting for this product
if <API key>.product == a_product:
product_profit += <API key>.profit
count += 1
output += '["%s","%s"] ,' % (product_name, product_profit)
output = output[:-1]
output += ']}'
return HttpResponse(output, content_type="text/plain")
@login_required(login_url='/login/')
def report_payment(request):
get_data = request.GET
if 'ban' in get_data:
bangla = True
else:
bangla = False
shop_name = get_data['shop']
shop_object = Consumer.objects.get(name=shop_name)
<API key> = Transaction.objects.filter(seller_id=shop_object, total_due__lte=0)
<API key> = Transaction.objects.filter(buyer_id=shop_object, total_due__lte=0)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
buyer_account = BuyerSellerAccount.objects.filter(seller=shop_object, total_due__lte=0)
seller_account = BuyerSellerAccount.objects.filter(buyer=shop_object, total_due__lte=0)
all_user_for_base = Consumer.objects.all()
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
transcriber_name = request.session['user']
return render(request, 'pages/report_payment.html', {'shop_list_base': all_shop_for_base,
'<API key>': <API key>,
'<API key>': <API key>,
'<API key>' :<API key>,
'buyer_account': buyer_account,
'transcriber_name': transcriber_name,
'seller_account': seller_account,
'shop_name': shop_name,
'bangla': bangla,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_due(request):
get_data = request.GET
if 'ban' in get_data:
bangla = True
else:
bangla = False
shop_name = get_data['shop']
shop_object = Consumer.objects.get(name=shop_name)
<API key> = Transaction.objects.filter(seller_id=shop_object, total_due__gt=0)
<API key> = Transaction.objects.filter(buyer_id=shop_object, total_due__gt=0)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
buyer_account = SMSPayment.objects.filter(seller=shop_object)
seller_account = SMSPayment.objects.filter(buyer=shop_object)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/report_due.html', {'shop_list_base': all_shop_for_base,
'<API key>': <API key>,
'<API key>': <API key>,
'buyer_account': buyer_account,
'<API key>' :<API key>,
'bangla': bangla,
'seller_account': seller_account,
'transcriber_name': transcriber_name,
'shop_name': shop_name,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_profit(request):
get_data = request.GET
shop_name = get_data['shop']
shop_object = Consumer.objects.get(name=shop_name)
shop_id = shop_object.id
if 'ban' in get_data:
bangla = True
else:
bangla = False
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/report_profit.html', {'shop_list_base': all_shop_for_base,
'shop_name': shop_name,
'shop_id': shop_id,
'<API key>' :<API key>,
'bangla': bangla,
'transcriber_name': transcriber_name,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_profit_json(request):
get_data = request.GET
shop_name = get_data['shop']
shop_object = Consumer.objects.get(id=shop_name)
shop_inventory = <API key>.objects.filter(shop=shop_object)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
output = '{"data": [ '
if get_data['t'] == '1':
this_year = datetime.date.today().year
this_month = 1
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
while this_month < 13:
day_string = True
for a_product in Product.objects.all():
count = 0
product_profit = 0
product_name = a_product.name
for <API key> in <API key>.objects.filter(shop_id=shop_object,
DateAdded__year=this_year,
DateAdded__month=this_month):
# start counting for this product
if <API key>.product == a_product:
product_profit += <API key>.profit
count += 1
if count > 0:
if day_string:
if this_month == 1:
output += '["January","",""], '
elif this_month == 2:
output += '["February","",""], '
elif this_month == 3:
output += '["March","",""], '
elif this_month == 4:
output += '["April","",""], '
elif this_month == 5:
output += '["May","",""], '
elif this_month == 6:
output += '["June","",""], '
elif this_month == 7:
output += '["July","",""], '
elif this_month == 8:
output += '["August","",""], '
elif this_month == 9:
output += '["September","",""], '
elif this_month == 10:
output += '["October","",""], '
elif this_month == 11:
output += '["November","",""], '
elif this_month == 12:
output += '["December","",""], '
day_string = False
output += '["","%s","%s"] ,' % (product_name, product_profit)
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
this_month += 1
if get_data['t'] == '2':
this_year = datetime.date.today().year
this_month = 1
while this_month < 13:
day = 1
while day < 32:
day_string = True
for a_product in Product.objects.all():
count = 0
product_profit = 0
product_name = a_product.name
for <API key> in <API key>.objects.filter(shop_id=shop_object,
DateAdded__year=this_year,
DateAdded__month=this_month,
DateAdded__day=day):
# start counting for this product
if <API key>.product == a_product:
product_profit += <API key>.profit
count += 1
if count > 0:
if day_string:
output += '["%s/%s/%s","",""] ,' % (day, this_month, this_year)
day_string = False
output += '["","%s","%s"] ,' % (product_name, product_profit)
day += 1
this_month += 1
if get_data['t'] == '3':
this_year = datetime.date.today().year
this_month = datetime.date.today().month
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
day_string = True
for a_product in Product.objects.all():
count = 0
product_profit = 0
product_name = a_product.name
for <API key> in <API key>.objects.filter(shop_id=shop_object,
DateAdded__year=this_year,
DateAdded__month=this_month):
# start counting for this product
if <API key>.product == a_product:
product_profit += <API key>.profit
count += 1
output += '["%s","%s"] ,' % (product_name, product_profit)
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
if get_data['t'] == '4':
this_year = datetime.date.today().year
day_string = True
for a_product in Product.objects.all():
count = 0
product_profit = 0
product_name = a_product.name
for <API key> in <API key>.objects.filter(shop_id=shop_object,
DateAdded__year=this_year):
# start counting for this product
if <API key>.product == a_product:
product_profit += <API key>.profit
count += 1
output += '["%s","%s"] ,' % (product_name, product_profit)
if get_data['t'] == '5':
this_year = datetime.date.today().year
day_string = True
for a_product in Product.objects.all():
count = 0
product_profit = 0
product_name = a_product.name
for <API key> in <API key>.objects.filter(shop_id=shop_object):
# start counting for this product
if <API key>.product == a_product:
product_profit += <API key>.profit
count += 1
output += '["%s","%s"] ,' % (product_name, product_profit)
output = output[:-1]
output += ']}'
return HttpResponse(output, content_type="text/plain")
@login_required(login_url='/login/')
def report_product(request):
get_data = request.GET
shop_name = get_data['shop']
if 'ban' in get_data:
bangla = True
else:
bangla = False
shop_object = Consumer.objects.get(name=shop_name)
shop_id = shop_object.id
shop_inventory = Inventory.objects.filter(shop=shop_object)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
selected_products = <API key>.objects.filter(TID=Transaction.objects.filter(seller=shop_object))
<API key> = <API key>.objects.filter(TID=Transaction.objects.filter(buyer=shop_object))
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/report_product.html', {'shop_list_base': all_shop_for_base,
'shop_inventory': shop_inventory,
'shop_name': shop_name,
'shop_id': shop_id,
'bangla': bangla,
'<API key>' :<API key>,
'transcriber_name': transcriber_name,
'<API key>': <API key>,
'selected_products': selected_products,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_product_json(request):
get_data = request.GET
shop_name = get_data['shop']
shop_object = Consumer.objects.get(id=shop_name)
shop_inventory = Inventory.objects.filter(shop=shop_object)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
output = '{"data": [ '
if get_data['t'] == '1':
this_year = datetime.date.today().year
this_month = datetime.date.today().month
day = 1
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
while day < 32:
day_string = True
for a_product in Product.objects.all():
count = 0
product_price = 0
product_name = a_product.name
for <API key> in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year,
DateAdded__month=this_month, DateAdded__day=day):
# start counting for this product
for <API key> in <API key>.objects.filter(TID=<API key>):
if <API key>.product == a_product:
# if <API key>.unit == a_product.bulk_wholesale_unit:
# if a_product.bulk_to_retail_unit == 0:
# count = count + <API key>.quantity
# product_price = product_price + <API key>.price_per_unit
# else:
# count = count + <API key>.quantity * a_product.bulk_to_retail_unit
# product_price = product_price + <API key>.price_per_unit
# else:
count = count + <API key>.quantity
product_price = product_price + <API key>.price_per_unit * <API key>.quantity
if count > 0:
if day_string:
output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
day_string = False
output += '["","%s","%s","%s","%s"] ,' % (product_name, count,
a_product.retail_unit,
float(product_price / count))
day += 1
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
if get_data['t'] == '2':
this_year = datetime.date.today().year
this_month = datetime.date.today().month
day = 1
while day < 32:
day_string = True
for a_product in Product.objects.all():
count = 0
product_price = 0
product_name = a_product.name
for <API key> in Transaction.objects.filter(buyer=shop_object, DateAdded__year=this_year,
DateAdded__month=this_month, DateAdded__day=day):
# start counting for this product
for <API key> in <API key>.objects.filter(TID=<API key>):
if <API key>.product == a_product:
if <API key>.unit == a_product.bulk_wholesale_unit:
if a_product.bulk_to_retail_unit == 0:
count = count + <API key>.quantity
product_price = product_price + <API key>.price_per_unit
else:
count = count + <API key>.quantity
product_price = product_price + <API key>.price_per_unit
else:
count = count + <API key>.quantity
product_price = product_price + <API key>.price_per_unit
if count > 0:
if day_string:
output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
day_string = False
output += '["","%s","%s","%s","%s"] ,' % (product_name, count,
a_product.bulk_wholesale_unit,
float(product_price / count))
day += 1
if get_data['t'] == '3':
this_year = datetime.date.today().year
this_month = datetime.date.today().month
for a_product in Product.objects.all():
count = 0
product_price = 0
product_name = a_product.name
for <API key> in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year, DateAdded__month=this_month):
# start counting for this product
for <API key> in <API key>.objects.filter(TID=<API key>):
if <API key>.product == a_product:
if <API key>.unit == a_product.bulk_wholesale_unit:
if a_product.bulk_to_retail_unit == 0:
count = count + <API key>.quantity
product_price = product_price + <API key>.price_per_unit
else:
count = count + <API key>.quantity * a_product.bulk_to_retail_unit
product_price = product_price + <API key>.price_per_unit / a_product.bulk_to_retail_unit
else:
count = count + <API key>.quantity
product_price = product_price + <API key>.price_per_unit
if count > 0:
output += '["%s","%s","%s","%s"] ,' % (product_name, count,
a_product.retail_unit,
float(product_price / count))
if get_data['t'] == '4':
this_year = datetime.date.today().year
this_month = datetime.date.today().month
for a_product in Product.objects.all():
count = 0
product_price = 0
product_name = a_product.name
for <API key> in Transaction.objects.filter(buyer=shop_object, DateAdded__year=this_year, DateAdded__month=this_month):
# start counting for this product
for <API key> in <API key>.objects.filter(TID=<API key>):
if <API key>.product == a_product:
if <API key>.unit == a_product.bulk_wholesale_unit:
if a_product.bulk_to_retail_unit == 0:
count = count + <API key>.quantity
product_price = product_price + <API key>.price_per_unit
else:
count = count + <API key>.quantity * a_product.bulk_to_retail_unit
product_price = product_price + <API key>.price_per_unit / a_product.bulk_to_retail_unit
else:
count = count + <API key>.quantity
product_price = product_price + <API key>.price_per_unit
if count > 0:
output += '["%s","%s","%s","%s"] ,' % (product_name, count,
a_product.retail_unit,
float(product_price / count))
output = output[:-1]
output += ']}'
<API key> = <API key>.objects.filter(TID=Transaction.objects.filter(buyer=shop_object))
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
return HttpResponse(output, content_type="text/plain")
# paste the template name of the report_analytical instead of report_product here
@login_required(login_url='/login/')
def report_analytical(request):
all_product = Product.objects.all()
final_output = ''
get_data = request.GET
shop_name = get_data['shop']
shop_object = Consumer.objects.get(name=shop_name)
shop_id = shop_object.id
for product in all_product:
print(product.name)
if <API key>.objects.filter(product=product).exists():
product_output = "[%s, " % product.name
sold_amount = 0
for product_details in <API key>.objects.filter(product=product):
sold_amount = sold_amount + product_details.quantity
product_output += str(sold_amount)
final_output += product_output
final_output += "] ,"
print(final_output)
final_output = final_output[:-1]
print(final_output)
add_notification = False
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/reports_analytical.html',
{'all_product': all_product, 'add_notification': add_notification,
'shop_list_base': all_shop_for_base, 'product_sell': final_output,
'<API key>' :<API key>,
'transcriber_name': transcriber_name,
'shop_name': shop_name,
'shop_id': shop_id,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def <API key>(request):
get_data = request.GET
shop_name = get_data['shop']
shop_object = Consumer.objects.get(id=shop_name)
if get_data['t'] == '1':
all_product = Product.objects.all()
final_output = '{"cols": [ { "id": "", "label": "Topping", "pattern": "", "type": "string" }, ' \
'{ "id": "", "label": "Units", "pattern": "", "type": "number" } ], "rows": [ '
for product in all_product:
print(product.name)
if <API key>.objects.filter(product=product).exists():
product_name = product.name
sold_amount = 0
for transaction_id in Transaction.objects.filter(seller=shop_object):
for product_details in <API key>.objects.filter(product=product, TID=transaction_id):
sold_amount = sold_amount + product_details.quantity
final_output += '{"c": [{"v": "%s","f": null},{"v": %s,"f": null}]},' % (product_name,
sold_amount)
final_output = final_output[:-1]
print(final_output)
if get_data['t'] == '2':
all_product = <API key>.objects.filter(shop=shop_object)
final_output = '{"cols": [ { "id": "", "label": "Topping", "pattern": "", "type": "string" }, ' \
'{ "id": "", "label": "Profit", "pattern": "", "type": "number" } ], "rows": [ '
for product in all_product:
final_output += '{"c": [{"v": "%s","f": null},{"v": %s,"f": null}]},' % (product.product,
product.profit)
final_output = final_output[:-1]
print(final_output)
final_output += ']}'
print(final_output)
return HttpResponse(final_output, content_type="text/plain")
# till this views created based on the list from mail
@login_required(login_url='/login/')
def report_recharge(request):
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/report_recharge.html', {'shop_list_base': all_shop_for_base,
'<API key>' :<API key>,
'transcriber_name': transcriber_name,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_callduration(request):
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/<API key>.html', {'shop_list_base': all_shop_for_base,
'<API key>' :<API key>,
'transcriber_name': transcriber_name,
'all_user_for_base': all_user_for_base})
# not necessary
@login_required(login_url='/login/')
def report_transaction(request):
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/report_transaction.html', {'shop_list_base': all_shop_for_base,
'<API key>' :<API key>,
'transcriber_name': transcriber_name,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def <API key>(request):
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/<API key>.html', {'shop_list_base': all_shop_for_base,
'<API key>' :<API key>,
'transcriber_name': transcriber_name,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_usercall(request):
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/<API key>.html', {'shop_list_base': all_shop_for_base,
'transcriber_name': transcriber_name,
'<API key>' :<API key>,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def transcription_page(request):
print(request.POST)
<API key> = VoiceRecord.objects.filter(transcribed=False).count()
<API key> = VoiceReg.objects.filter(completed=False).count()
type_of_subscriber = ConsumerType.objects.all()
<API key> = VoiceRecord.objects.filter(with_error=True).count()
<API key> = VoiceRecord.objects.filter(with_error=False, transcribed=True).count()
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
return render(request, 'pages/transcription.html',
dict(pending_calls=<API key>, types=type_of_subscriber,
pending_calls_reg=<API key>, <API key>=str(<API key>),
<API key>=<API key>, transcriber_name=transcriber_name,
shop_list_base=all_shop_for_base,<API key>=<API key>,
all_user_for_base=all_user_for_base))
# report views ends here
@login_required(login_url='/login/')
def add_subscriber_page(request):
all_subscriber = Consumer.objects.all()
type_of_subscriber = ConsumerType.objects.all()
add_notification = False
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
notification = ''
if 'delete' in request.GET:
get_data = request.GET
add_notification = True
delID = get_data['delete']
if Consumer.objects.filter(id=delID).exists():
item_for_delete = Consumer.objects.get(id=delID)
notification = 'Daily statement for the user : ' + item_for_delete.name + ' is sent successfully.'
# item_for_delete.delete()
sales_statement = ''
purchase_statement = ''
today_date = datetime.date.today()
today_day = today_date.day
today_month = today_date.month
today_year = today_date.year
# for selling
sell_transactions = Transaction.objects.filter(seller=item_for_delete, DateAdded__day=today_day,
DateAdded__month=today_month, DateAdded__year=today_year)
total_sales = 0
total_due = 0
total_paid = 0
for sell_transaction in sell_transactions:
total_sales += sell_transaction.total_amount
total_paid += sell_transaction.total_paid
total_due += sell_transaction.total_due
if total_sales > 0:
sales_statement = ' bikroy korechen mot: ' + str(total_sales) + ' takar. nogod peyechen : ' + \
str(total_paid) + ' taka ebong baki royeche ' + str(total_due) + ' taka.'
buy_transactions = Transaction.objects.filter(buyer=item_for_delete, DateAdded__day=today_day,
DateAdded__month=today_month, DateAdded__year=today_year)
total_purchase = 0
total_due = 0
total_paid = 0
for buy_transaction in buy_transactions:
total_purchase += buy_transaction.total_amount
total_paid += buy_transaction.total_paid
total_due += buy_transaction.total_due
if total_purchase > 0:
purchase_statement = ' kinechen mot: ' + str(total_purchase) + ' takar. Nogod diyechen : ' + \
str(total_paid) + ' taka ebong baki royeche ' + str(total_due) + ' taka.'
final_text = 'Aj apni' + sales_statement + purchase_statement + ' Dhonnobad'
if total_purchase > 0 or total_sales > 0:
print(final_text)
send_sms(final_text, item_for_delete.phone)
else:
notification = 'Item not found'
return render(request, 'pages/add_subscriber.html',
{'subscribers': all_subscriber, 'types': type_of_subscriber, 'add_notification': add_notification,
'shop_list_base': all_shop_for_base,
'<API key>' :<API key>,
'transcriber_name': transcriber_name,
'notification':notification,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def add_product_page(request):
all_product = Product.objects.all()
add_notification = False
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
notification = ''
if 'delete' in request.GET:
get_data = request.GET
add_notification = True
delID = get_data['delete']
if Product.objects.filter(id=delID).exists():
item_for_delete = Product.objects.get(id=delID)
notification = 'The product : ' + item_for_delete.name + ' is deleted successfully.'
item_for_delete.delete()
else:
notification = 'Item not found'
return render(request, 'pages/add_product.html',
{'all_product': all_product, 'add_notification': add_notification,
'<API key>' :<API key>,
'transcriber_name': transcriber_name,'notification': notification,
'shop_list_base': all_shop_for_base, 'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def <API key>(request):
all_product = Product.objects.all()
add_notification = False
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/<API key>.html',
{'all_product': all_product, 'add_notification': add_notification,
'transcriber_name': transcriber_name,
'<API key>' :<API key>,
'shop_list_base': all_shop_for_base, 'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def <API key>(request):
final_output = '{"data": [ '
for transcriber in Transcriber.objects.all():
<API key> = <API key>.objects.filter(name=transcriber).count()
total_time_taken = 0
<API key> = 0
for <API key> in <API key>.objects.filter(name=transcriber):
total_time_taken += float(<API key>.time_taken)
<API key> += <API key>.number_of_products
if <API key> > 0:
avg_time = total_time_taken / <API key>
avg_product = <API key> / <API key>
final_output += '["%s","%s","%s","%s","%s"] ,' % (transcriber.id, transcriber.name,
<API key>, avg_time, avg_product)
final_output = final_output[:-1]
final_output += ']}'
return HttpResponse(final_output, content_type="text/plain")
@login_required(login_url='/login/')
def <API key>(request):
post_data = request.POST
notification = ''
for all_consumers in Consumer.objects.all():
if Recharge.objects.filter(user=all_consumers).exists():
print('Already_Added')
else:
new_added = Recharge(user=all_consumers)
new_added.save()
if TotalRecharge.objects.filter(user=all_consumers).exists():
print('Already_Added')
else:
new_added = TotalRecharge(user=all_consumers)
new_added.save()
add_notification = False
if 'user' in post_data and 'recharge_amount' in post_data:
user_name = post_data['user']
user_object = Consumer.objects.get(name=user_name)
if is_number(post_data['recharge_amount']) or is_float(post_data['recharge_amount']):
new_recharge_added = Recharge(user=user_object, amount=float(post_data['recharge_amount']))
new_recharge_added.save()
new_recharge_update = TotalRecharge.objects.get(user=user_object)
new_recharge_update.amount += float(post_data['recharge_amount'])
new_recharge_update.save()
add_notification = True
notification = 'Amount %s has been added to the number %s' %(post_data['recharge_amount'],
user_object.phone)
else:
notification = 'Something went wrong. Please try again.'
recharge_all = TotalRecharge.objects.all()
today_date = datetime.date.today()
today_day = today_date.day
today_month = today_date.month
today_year = today_date.year
recharge_today = Recharge.objects.filter(DateAdded__day=today_day,
DateAdded__month=today_month, DateAdded__year=today_year, amount__gt=0)
all_product = Product.objects.all()
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/<API key>.html',
{'all_product': all_product, 'add_notification': add_notification,
'<API key>' :<API key>,
'shop_list_base': all_shop_for_base, 'recharge_all': recharge_all,
'transcriber_name': transcriber_name,
'recharge_today': recharge_today, 'all_user_for_base': all_user_for_base,
'notification': notification})
# views for printing
@login_required(login_url='/login/')
def <API key>(request):
get_data = request.GET
if 'ban' in get_data:
bangla = True
else:
bangla = False
shop_name = get_data['shop']
shop_object = Consumer.objects.get(name=shop_name)
total_sell = 0
total_sell_due = 0
total_sell_paid = 0
total_purchase = 0
total_purchase_due = 0
total_purchase_paid = 0
for month_sell in BuyerSellerAccount.objects.filter(seller=shop_object):
total_sell += month_sell.<API key>
total_sell_due += month_sell.total_due
total_sell_paid += month_sell.total_paid
for month_purchase in BuyerSellerAccount.objects.filter(buyer=shop_object):
total_purchase += month_purchase.<API key>
total_purchase_due += month_purchase.total_due
total_purchase_paid += month_purchase.total_paid
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
transcriber_name = request.session['user']
return render(request, 'print/report_monthly_shop.html', {'shop_list_base': all_shop_for_base,
'shop_name': shop_name,
'<API key>' :<API key>,
'total_sell': total_sell,
'transcriber_name': transcriber_name,
'total_sell_due': total_sell_due,
'total_sell_paid': total_sell_paid,
'bangla': bangla,
'total_purchase': total_purchase,
'total_purchase_due': total_purchase_due,
'total_purchase_paid': total_purchase_paid,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_due_print(request):
get_data = request.GET
if 'ban' in get_data:
bangla = True
else:
bangla = False
shop_name = get_data['shop']
shop_object = Consumer.objects.get(name=shop_name)
<API key> = Transaction.objects.filter(seller_id=shop_object, total_due__gt=0)
<API key> = Transaction.objects.filter(buyer_id=shop_object, total_due__gt=0)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
buyer_account = BuyerSellerAccount.objects.filter(seller=shop_object, total_due__gt=0)
seller_account = BuyerSellerAccount.objects.filter(buyer=shop_object, total_due__gt=0)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'print/report_due.html', {'shop_list_base': all_shop_for_base,
'<API key>': <API key>,
'<API key>': <API key>,
'buyer_account': buyer_account,
'<API key>' :<API key>,
'bangla': bangla,
'seller_account': seller_account,
'transcriber_name': transcriber_name,
'shop_name': shop_name,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def <API key>(request):
get_data = request.GET
if 'ban' in get_data:
bangla = True
else:
bangla = False
shop_name = get_data['shop']
shop_object = Consumer.objects.get(name=shop_name)
<API key> = Transaction.objects.filter(seller_id=shop_object, total_due__lte=0)
<API key> = Transaction.objects.filter(buyer_id=shop_object, total_due__lte=0)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
buyer_account = BuyerSellerAccount.objects.filter(seller=shop_object, total_due__lte=0)
seller_account = BuyerSellerAccount.objects.filter(buyer=shop_object, total_due__lte=0)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'print/report_payment.html', {'shop_list_base': all_shop_for_base,
'<API key>': <API key>,
'<API key>': <API key>,
'<API key>' :<API key>,
'buyer_account': buyer_account,
'transcriber_name': transcriber_name,
'seller_account': seller_account,
'shop_name': shop_name,
'bangla': bangla,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def <API key>(request):
get_data = request.GET
shop_name = get_data['shop']
if 'ban' in get_data:
bangla = True
else:
bangla = False
shop_object = Consumer.objects.get(name=shop_name)
shop_inventory = Inventory.objects.filter(shop=shop_object)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
selected_products = <API key>.objects.filter(TID=Transaction.objects.filter(seller=shop_object))
<API key> = <API key>.objects.filter(TID=Transaction.objects.filter(buyer=shop_object))
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'print/report_product.html', {'shop_list_base': all_shop_for_base,
'shop_inventory': shop_inventory,
'shop_name': shop_name,
'bangla': bangla,
'<API key>' :<API key>,
'transcriber_name': transcriber_name,
'<API key>': <API key>,
'selected_products': selected_products,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def <API key>(request):
get_data = request.GET
shop_name = get_data['shop']
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
transcriber_name = request.session['user']
return render(request, 'print/<API key>.html', {'shop_list_base': all_shop_for_base,
'<API key>' :<API key>,
'shop_name': shop_name,
'transcriber_name': transcriber_name,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_profit_print(request):
get_data = request.GET
shop_name = get_data['shop']
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'print/report_profit.html', {'shop_list_base': all_shop_for_base,
'shop_name': shop_name,
'<API key>':<API key>,
'transcriber_name': transcriber_name,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def <API key>(request):
all_product = Product.objects.all()
add_notification = False
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
<API key> = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'print/<API key>.html',
{'all_product': all_product, 'add_notification': add_notification,
'<API key>':<API key>,
'transcriber_name': transcriber_name,
'shop_list_base': all_shop_for_base, 'all_user_for_base': all_user_for_base})
# SR section
@login_required(login_url='/login/')
def sr_monthly_report(request):
sr_name = request.session['user']
sr_object = ACL.objects.get(loginID=sr_name).loginUser
transcriber_name = sr_object.name
allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object)
return render(request, 'pages/SR/report_monthly.html', {'transcriber_name': transcriber_name,
'allTransaction': allTransaction})
@login_required(login_url='/login/')
def sr_due_report(request):
sr_name = request.session['user']
sr_object = ACL.objects.get(loginID=sr_name).loginUser
transcriber_name = sr_object.name
allBalance = BuyerSellerAccount.objects.filter(seller=sr_object)
sell_transaction = Transaction.objects.filter(seller=sr_object)
dueTransactions = dueTransaction.objects.filter(seller=sr_object)
return render(request, 'pages/SR/report_due.html', {'transcriber_name': transcriber_name,
'sell_transaction': sell_transaction,
'dueTransactions': dueTransactions,
'allBalance': allBalance})
@login_required(login_url='/login/')
def <API key>(request):
sr_name = request.session['user']
sr_object = ACL.objects.get(loginID=sr_name).loginUser
transcriber_name = sr_object.name
post_data = request.POST
print(post_data)
shop_object = sr_object
shop_name = shop_object.name
shop_id = shop_object.id
if 'month' in post_data and 'year' in post_data:
month = post_data['month']
year = post_data['year']
else:
month = datetime.date.today().month
year = datetime.date.today().year
return render(request, 'pages/SR/<API key>.html', {'shop_name': shop_name,
# '<API key>' :<API key>,
'shop_id': shop_id,
# 'bangla': bangla,
'transcriber_name': transcriber_name,
'month': month,
'year': year})
@login_required(login_url='/login/')
def <API key>(request):
get_data = request.GET
shop_name = get_data['shop']
shop_object = Consumer.objects.get(id=shop_name)
shop_inventory = <API key>.objects.filter(shop=shop_object)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
this_year = get_data['year']
print(this_year)
this_month = get_data['month']
output = '{"data": [ '
if get_data['t'] == '1':
rank = 1
for a_product in Product.objects.all():
count = 0
product_price = 0
product_name = a_product.name
for <API key> in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year,
DateAdded__month=this_month):
# start counting for this product
for <API key> in <API key>.objects.filter(TID=<API key>):
if <API key>.product == a_product:
if <API key>.unit == a_product.bulk_wholesale_unit:
if a_product.bulk_to_retail_unit == 0:
count = count + <API key>.quantity
product_price = product_price + <API key>.price_per_unit
else:
count = count + <API key>.quantity * a_product.bulk_to_retail_unit
product_price = product_price + <API key>.price_per_unit / a_product.bulk_to_retail_unit
else:
count = count + <API key>.quantity
product_price = product_price + <API key>.price_per_unit
if count > 0:
output += '["%s","%s","%s"] ,' % (rank, product_name, str(count) + ' ' + a_product.retail_unit)
rank += 1
if get_data['t'] == '2':
rank = 1
for a_product in Product.objects.all():
count = 0
# product_price = 0
<API key> = 0
change = 0
product_name = a_product.name
for <API key> in Transaction.objects.filter(seller=shop_object):
# start counting for this product
for <API key> in <API key>.objects.filter(TID=<API key>):
if <API key>.product == a_product:
if count == 0:
<API key> = <API key>.price_per_unit
product_price = <API key>.price_per_unit
change += abs(<API key> - product_price)
count += 1
if count > 0:
output += '["%s","%s","%s","%s"] ,' % (rank, product_name, count,
change/count)
rank += 1
if get_data['t'] == '3':
print(this_month)
day = 1
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
while day < 32:
day_string = True
rank = 1
for a_product in Product.objects.all():
count = 0
product_price = 0
product_name = a_product.name
for <API key> in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year,
DateAdded__month=this_month, DateAdded__day=day):
# start counting for this product
for <API key> in <API key>.objects.filter(TID=<API key>):
if <API key>.product == a_product:
if <API key>.unit == a_product.bulk_wholesale_unit:
if a_product.bulk_to_retail_unit == 0:
count = count + <API key>.quantity
product_price = product_price + <API key>.price_per_unit
else:
count = count + <API key>.quantity * a_product.bulk_to_retail_unit
product_price = product_price + <API key>.price_per_unit / a_product.bulk_to_retail_unit
else:
count = count + <API key>.quantity
product_price = product_price + <API key>.price_per_unit
if count > 0:
if day_string:
output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
day_string = False
output += '["","%s","%s","%s","%s"] ,' % (rank, product_name,
str(count) + ' ' + a_product.retail_unit,
float(product_price / count))
rank += 1
day += 1
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
if get_data['t'] == '4':
day = 1
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
while day < 8:
day_string = True
rank = 1
for a_product in Product.objects.all():
count = 0
product_price = 0
product_name = a_product.name
for <API key> in Transaction.objects.filter(seller=shop_object, DateAdded__week_day=day):
# start counting for this product
for <API key> in <API key>.objects.filter(TID=<API key>):
if <API key>.product == a_product:
if <API key>.unit == a_product.bulk_wholesale_unit:
if a_product.bulk_to_retail_unit == 0:
count = count + <API key>.quantity
product_price = product_price + <API key>.price_per_unit
else:
count = count + <API key>.quantity * a_product.bulk_to_retail_unit
product_price = product_price + <API key>.price_per_unit / a_product.bulk_to_retail_unit
else:
count = count + <API key>.quantity
product_price = product_price + <API key>.price_per_unit
if count > 0:
if day_string:
if day == 1:
output += '["%s","","","",""] ,' % 'Sunday'
elif day == 2:
output += '["%s","","","",""] ,' % 'Monday'
elif day == 3:
output += '["%s","","","",""] ,' % 'Tuesday'
elif day == 4:
output += '["%s","","","",""] ,' % 'Wednesday'
elif day == 5:
output += '["%s","","","",""] ,' % 'Thursday'
elif day == 6:
output += '["%s","","","",""] ,' % 'Friday'
elif day == 7:
output += '["%s","","","",""] ,' % 'Saturday'
day_string = False
output += '["","%s","%s","%s","%s"] ,' % (rank, product_name,
str(count) + ' ' + a_product.retail_unit,
float(product_price / count))
rank += 1
day += 1
if get_data['t'] == '5':
this_year = datetime.date.today().year
day_string = True
for a_product in Product.objects.all():
count = 0
product_profit = 0
product_name = a_product.name
for <API key> in <API key>.objects.filter(shop_id=shop_object):
# start counting for this product
if <API key>.product == a_product:
product_profit += <API key>.profit
count += 1
output += '["%s","%s"] ,' % (product_name, product_profit)
output = output[:-1]
output += ']}'
return HttpResponse(output, content_type="text/plain")
# Distributor Section
@login_required(login_url='/login/')
def add_sr_page(request):
dr_name = request.session['user']
dr_object = ACL.objects.get(loginID=dr_name).loginUser
transcriber_name = dr_object.name
all_subscriber = ACL.objects.filter(distUser=dr_object)
# type_of_subscriber = ConsumerType.objects.all()
add_notification = False
# shop_consumer = ConsumerType.objects.get(type_name='Seller')
# all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
# all_user_for_base = Consumer.objects.all()
# transcriber_name = request.session['user']
# shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
# <API key> = Consumer.objects.filter(type=shop_consumer2)
notification = ''
if 'delete' in request.GET:
get_data = request.GET
add_notification = True
delID = get_data['delete']
if Consumer.objects.filter(id=delID).exists():
item_for_delete = Consumer.objects.get(id=delID)
notification = 'The Consumer : ' + item_for_delete.name + ' is deleted successfully.'
item_for_delete.delete()
else:
notification = 'Item not found'
return render(request, 'pages/Distributor/add_SR.html',
{'subscribers': all_subscriber,'add_notification': add_notification,
# 'shop_list_base': all_shop_for_base,
# '<API key>' :<API key>,
'transcriber_name': transcriber_name,
'notification': notification})
@login_required(login_url='/login/')
def dr_monthly_report(request):
dr_name = request.session['user']
dr_object = ACL.objects.get(loginID=dr_name).loginUser
transcriber_name = dr_object.name
transcriber_id = dr_object.id
all_subscriber = ACL.objects.filter(distUser=dr_object)
post_data = request.POST
print(post_data)
if 'sr' in post_data:
sr_object = Consumer.objects.get(id=post_data['sr'])
allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object)
return render(request, 'pages/Distributor/report_monthly.html', {'transcriber_name': transcriber_name,
'hasReport': True,
'subscribers': all_subscriber,
'transcriber_id': transcriber_id,
'allTransaction': allTransaction})
else:
# allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object)
return render(request, 'pages/Distributor/report_monthly.html', {'transcriber_name': transcriber_name,
'transcriber_id': transcriber_id,
'subscribers': all_subscriber,
'hasReport': False})
@login_required(login_url='/login/')
def dr_due_report(request):
sr_name = request.session['user']
dr_object = ACL.objects.get(loginID=sr_name).loginUser
transcriber_name = dr_object.name
transcriber_id = dr_object.id
all_subscriber = ACL.objects.filter(distUser=dr_object)
post_data = request.POST
if 'sr' in post_data:
sr_object = Consumer.objects.get(id=post_data['sr'])
allBalance = BuyerSellerAccount.objects.filter(seller=sr_object)
sell_transaction = Transaction.objects.filter(seller=sr_object)
dueTransactions = dueTransaction.objects.filter(seller=sr_object)
# allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object)
return render(request, 'pages/Distributor/report_due.html', {'transcriber_name': transcriber_name,
'sell_transaction': sell_transaction,
'dueTransactions': dueTransactions,
'transcriber_id': transcriber_id,
'hasReport': True,
'subscribers': all_subscriber,
'allBalance': allBalance})
else:
# allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object)
return render(request, 'pages/Distributor/report_due.html', {'transcriber_name': transcriber_name,
'transcriber_id': transcriber_id,
'subscribers': all_subscriber,
'hasReport': False})
@login_required(login_url='/login/')
def <API key>(request):
dr_name = request.session['user']
dr_object = ACL.objects.get(loginID=dr_name).loginUser
transcriber_name = dr_object.name
transcriber_id = dr_object.id
post_data = request.POST
print(post_data)
# shop_object = sr_object
all_subscriber = ACL.objects.filter(distUser=dr_object)
hasReport = False
if 'sr' in post_data:
shop_id = post_data['sr']
shop_name = Consumer.objects.get(id=shop_id).name
hasReport = True
if 'month' in post_data and 'year' in post_data:
month = post_data['month']
year = post_data['year']
else:
month = datetime.date.today().month
year = datetime.date.today().year
return render(request, 'pages/Distributor/<API key>.html', {'shop_name': shop_name,
'transcriber_id': transcriber_id,
'shop_id': shop_id,
'subscribers': all_subscriber,
'transcriber_name': transcriber_name,
'month': month,
'hasReport': hasReport,
'year': year})
else:
return render(request, 'pages/Distributor/<API key>.html', {'shop_name': 'Not Selected',
'transcriber_id': transcriber_id,
'subscribers': all_subscriber,
'transcriber_name': transcriber_name,
'hasReport': hasReport})
# Shop Module
@login_required(login_url='/login/')
def shop_monthly_report(request):
sr_name = request.session['user']
sr_object = ACL.objects.get(loginID=sr_name).loginUser
transcriber_name = sr_object.name
allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object)
allTransactionIn = BuyerSellerAccount.objects.filter(buyer=sr_object)
return render(request, 'pages/Shop/report_monthly.html', {'transcriber_name': transcriber_name,
'allTransactionIn': allTransactionIn,
'allTransaction': allTransaction})
@login_required(login_url='/login/')
def shop_due_report(request):
sr_name = request.session['user']
sr_object = ACL.objects.get(loginID=sr_name).loginUser
transcriber_name = sr_object.name
allBalance = BuyerSellerAccount.objects.filter(seller=sr_object)
sell_transaction = Transaction.objects.filter(seller=sr_object)
dueTransactions = dueTransaction.objects.filter(seller=sr_object)
allBalanceIn = BuyerSellerAccount.objects.filter(buyer=sr_object)
sell_transactionIn = Transaction.objects.filter(buyer=sr_object)
dueTransactionsIn = dueTransaction.objects.filter(buyer=sr_object)
return render(request, 'pages/Shop/report_due.html', {'transcriber_name': transcriber_name,
'sell_transaction': sell_transaction,
'dueTransactions': dueTransactions,
'allBalance': allBalance,
'sell_transactionIn': sell_transactionIn,
'dueTransactionsIn': dueTransactionsIn,
'allBalanceIn': allBalanceIn})
@login_required(login_url='/login/')
def <API key>(request):
sr_name = request.session['user']
sr_object = ACL.objects.get(loginID=sr_name).loginUser
transcriber_name = sr_object.name
post_data = request.POST
print(post_data)
shop_object = sr_object
shop_name = shop_object.name
shop_id = shop_object.id
if 'month' in post_data and 'year' in post_data:
month = post_data['month']
year = post_data['year']
else:
month = datetime.date.today().month
year = datetime.date.today().year
return render(request, 'pages/Shop/<API key>.html', {'shop_name': shop_name,
# '<API key>' :<API key>,
'shop_id': shop_id,
# 'bangla': bangla,
'transcriber_name': transcriber_name,
'month': month,
'year': year})
# Consumer Module
@login_required(login_url='/login/')
def user_monthly_report(request):
sr_name = request.session['user']
sr_object = ACL.objects.get(loginID=sr_name).loginUser
transcriber_name = sr_object.name
# allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object)
allTransactionIn = BuyerSellerAccount.objects.filter(buyer=sr_object)
return render(request, 'pages/Consumer/report_monthly.html', {'transcriber_name': transcriber_name,
'allTransactionIn': allTransactionIn})
@login_required(login_url='/login/')
def user_due_report(request):
sr_name = request.session['user']
sr_object = ACL.objects.get(loginID=sr_name).loginUser
transcriber_name = sr_object.name
# allBalance = BuyerSellerAccount.objects.filter(seller=sr_object)
# sell_transaction = Transaction.objects.filter(seller=sr_object)
# dueTransactions = dueTransaction.objects.filter(seller=sr_object)
allBalanceIn = BuyerSellerAccount.objects.filter(buyer=sr_object)
sell_transactionIn = Transaction.objects.filter(buyer=sr_object)
dueTransactionsIn = dueTransaction.objects.filter(buyer=sr_object)
return render(request, 'pages/Consumer/report_due.html', {'transcriber_name': transcriber_name,
# 'sell_transaction': sell_transaction,
# 'dueTransactions': dueTransactions,
# 'allBalance': allBalance,
'sell_transactionIn': sell_transactionIn,
'dueTransactionsIn': dueTransactionsIn,
'allBalanceIn': allBalanceIn})
@login_required(login_url='/login/')
def change_password(request):
# user = request.session['user']
post_data = request.POST
user_name = request.session['user']
user_object = ACL.objects.get(loginID=user_name).loginUser
transcriber_name = user_object.name
user = user_object.phone[-9:]
wrong = False
text = ''
if 'csrfmiddlewaretoken' in post_data:
if post_data['password'] == post_data['re-password']:
if User.objects.filter(username=user).exists():
u = User.objects.get(username=user)
u.set_password(post_data['password'])
u.save()
user_ID = user_object.id
this_user = Consumer.objects.get(id=user_ID)
this_user.number_of_child = 'CHANGED !!!'
this_user.save()
wrong = True
text = 'Password is successfully changed'
if user_object.type.type_name == 'Distributor':
display = render(request, 'pages/Distributor/index.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'SR':
display = render(request, 'pages/SR/index.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'Seller':
display = render(request, 'pages/Shop/index.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'Buyer':
display = render(request, 'pages/Consumer/index.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
else:
wrong = True
text = 'Something Wrong'
if user_object.type.type_name == 'Distributor':
display = render(request, 'pages/Distributor/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'SR':
display = render(request, 'pages/SR/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'Seller':
display = render(request, 'pages/Shop/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'Buyer':
display = render(request, 'pages/Consumer/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
else:
wrong = True
text = 'Passwords do NOT match. Please try again'
if user_object.type.type_name == 'Distributor':
display = render(request, 'pages/Distributor/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'SR':
display = render(request, 'pages/SR/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'Seller':
display = render(request, 'pages/Shop/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'Buyer':
display = render(request, 'pages/Consumer/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
else:
wrong = False
if user_object.type.type_name == 'Distributor':
display = render(request, 'pages/Distributor/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'SR':
display = render(request, 'pages/SR/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'Seller':
display = render(request, 'pages/Shop/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'Buyer':
display = render(request, 'pages/Consumer/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong})
return display
|
<?php
/**
* Display single product reviews (comments)
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 2.1.0
*/
global $woocommerce, $product;
if ( ! defined( 'ABSPATH' ) )
exit; // Exit if accessed directly
if ( ! comments_open() )
return;
?>
<div id="reviews">
<div id="comments">
<h2><?php
if ( get_option( '<API key>' ) === 'yes' && ( $count = $product->get_rating_count() ) )
printf( _n('%s review for %s', '%s reviews for %s', $count, 'woocommerce'), $count, get_the_title() );
else
_e( 'Reviews', 'woocommerce' );
?></h2>
<?php if ( have_comments() ) : ?>
<ol class="commentlist">
<?php wp_list_comments( apply_filters( '<API key>', array( 'callback' => '<API key>' ) ) ); ?>
</ol>
<?php if ( <API key>() > 1 && get_option( 'page_comments' ) ) :
echo '<nav class="<API key>">';
<API key>( apply_filters( '<API key>', array(
'prev_text' => '←',
'next_text' => '→',
'type' => 'list',
) ) );
echo '</nav>';
endif; ?>
<?php else : ?>
<p class="<API key>"><?php _e( 'There are no reviews yet.', 'woocommerce' ); ?></p>
<?php endif; ?>
</div>
<?php if ( get_option( '<API key>' ) === 'no' || <API key>( '', get_current_user_id(), $product->id ) ) : ?>
<div id="review_form_wrapper">
<div id="review_form">
<?php
$commenter = <API key>();
$comment_form = array(
'title_reply' => have_comments() ? __( 'Add a review', 'woocommerce' ) : __( 'Be the first to review', 'woocommerce' ) . ' “' . get_the_title() . '”',
'title_reply_to' => __( 'Leave a Reply to %s', 'woocommerce' ),
'<API key>' => '',
'comment_notes_after' => '',
'fields' => array(
'author' => '<p class="comment-form-author">' . '<label for="author">' . __( 'Name', 'woocommerce' ) . ' <span class="required">*</span></label> ' .
'<input id="author" name="author" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30" aria-required="true" /></p>',
'email' => '<p class="comment-form-email"><label for="email">' . __( 'Email', 'woocommerce' ) . ' <span class="required">*</span></label> ' .
'<input id="email" name="email" type="text" value="' . esc_attr( $commenter['<API key>'] ) . '" size="30" aria-required="true" /></p>',
),
'label_submit' => __( 'Submit', 'woocommerce' ),
'logged_in_as' => '',
'comment_field' => ''
);
if ( get_option( '<API key>' ) === 'yes' ) {
$comment_form['comment_field'] = '<p class="comment-form-rating"><label for="rating">' . __( 'Your Rating', 'woocommerce' ) .'</label><select name="rating" id="rating">
<option value="">' . __( 'Rate…', 'woocommerce' ) . '</option>
<option value="5">' . __( 'Perfect', 'woocommerce' ) . '</option>
<option value="4">' . __( 'Good', 'woocommerce' ) . '</option>
<option value="3">' . __( 'Average', 'woocommerce' ) . '</option>
<option value="2">' . __( 'Not that bad', 'woocommerce' ) . '</option>
<option value="1">' . __( 'Very Poor', 'woocommerce' ) . '</option>
</select></p>';
}
$comment_form['comment_field'] .= '<p class="<API key>"><label for="comment">' . __( 'Your Review', 'woocommerce' ) . '</label><textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea>' . wp_nonce_field( '<API key>', '_wpnonce', true, false ) . '</p>';
comment_form( apply_filters( '<API key>', $comment_form ) );
?>
</div>
</div>
<?php else : ?>
<p class="<API key>"><?php _e( 'Only logged in customers who have purchased this product may leave a review.', 'woocommerce' ); ?></p>
<?php endif; ?>
<div class="clear"></div>
</div>
|
package com.atux.bean.consulta;
import com.atux.comun.FilterBaseLocal;
public class UnidadFlt extends FilterBaseLocal {
public static final String PICK = "PICK";
public UnidadFlt(String unidad) {
this.unidad = unidad;
}
public UnidadFlt() {
}
private String unidad;
private String coUnidad;
public String getUnidad() {
return unidad;
}
public void setUnidad(String unidad) {
this.unidad = unidad;
}
public String getCoUnidad() {
return coUnidad;
}
public void setCoUnidad(String coUnidad) {
this.coUnidad = coUnidad;
}
}
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Project WiSH</title>
<style fprolloverstyle>A:hover {color: red; font-weight: bold}
</style>
</head>
<body style="<API key>: fixed">
<p align="center">
<A href="http:
<h1 align="center"><b>Linux X10 universal device driver</b></h1>
<h2 align="center"><b>(aka Project WiSH)</b></h2>
<ul>
<li>
<p align="left"><a href="http://wish.sourceforge.net/index1.html">x10dev (Version
1.X</a>) for <b>Kernel 2.4.X:</b> Linux driver for Kernel 2.4 supporting
the CM11A, CM17A, SmartHome PowerLink Serial, and SmartHome PowerLink USB
transceivers.</p></li>
<li>
<p align="left"><a href="http://wish.sourceforge.net/index2.html">x10dev-2 (Version 2.X</a>) for
<b>Kernel 2.6.7+ and Kernel 2.4</b>: for Kernel 2.6.7 and higher supporting the
CM11A, SmartHome PowerLink Serial, and SmartHome PowerLink USB. For
Kernel 2.4 supporting the CM11A and SmartHome PowerLink Serial.</p></li>
<li>
<p align="left"><a href="http://wish.sourceforge.net/x10web.html">x10web (Java GUI) Version 1.X</a>:
Java client GUI and socket server for both wish Version 1.X and Version 2.X</p>
</li>
</ul>
<hr>
<p>
This module is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as publised by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
</p><p>
This module is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
</p><p>
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA
</p><p>
Should you need to contact the author, you can do so by email to
<wsh@sprintmail.com>.
</p>
</body>
</html>
|
<?php
function doc($result, $sumArray, $title, $weightArray, $headerArray){
$config = CoreConfig::readAppConfig();
$active_app = Router::getApplication();
$file = md5(uniqid());
$content = "
<html>
<head>
<title>REPORTE DE ".i18n::strtoupper($title)."</title>
</head>
<body bgcolor='white'>
<div style='font-size:20px;font-family:Verdana;color:#000000'>".i18n::strtoupper($config->application->name)."</div>\n
<div style='font-size:18px;font-family:Verdana;color:#000000'>REPORTE DE ".i18n::strtoupper($title)."</div>\n
<div style='font-size:18px;font-family:Verdana;color:#000000'>".date("Y-m-d H:i")."</div>\n
<br/>
<table cellspacing='0' border=1 style='border:1px solid #969696'>
";
$content.= "<tr bgcolor='#F2F2F2'>\n";
$numberHeaders = count($headerArray);
for($i=0;$i<$numberHeaders;++$i){
$content.= "<th style='font-family:Verdana;font-size:12px'>".$headerArray[$i]."</th>\n";
}
$content.= "</tr>\n";
$l = 5;
foreach($result as $row){
$content.= "<tr bgcolor='white'>\n";
$numberColumns = count($row);
for($i=0;$i<$numberColumns;++$i){
if(is_numeric($row[$i])){
$content.= "<td style='font-family:Verdana;font-size:12px' align='center'>{$row[$i]}</td>";
} else {
$content.= "<td style='font-family:Verdana;font-size:12px'>{$row[$i]} </td>";
}
}
$content.= "</tr>\n";
++$l;
}
file_put_contents("public/temp/$file.doc", $content);
if(isset($raw_output)){
echo "<script type='text/javascript'> window.open('".Core::getInstancePath()."temp/".$file.".doc', null); </script>";
} else {
Generator::formsPrint("<script type='text/javascript'> window.open('".Core::getInstancePath()."temp/".$file.".doc', null); </script>");
}
}
|
#ifndef __INC_USERVIA_H
#define __INC_USERVIA_H
#include "via.h"
extern VIA uservia;
extern ALLEGRO_USTR *prt_clip_str;
extern FILE *prt_fp;
void uservia_reset(void);
void uservia_write(uint16_t addr, uint8_t val);
uint8_t uservia_read(uint16_t addr);
void uservia_savestate(FILE *f);
void uservia_loadstate(FILE *f);
extern uint8_t lpt_dac;
void uservia_set_ca1(int level);
void uservia_set_ca2(int level);
void uservia_set_cb1(int level);
void uservia_set_cb2(int level);
#endif
|
/**
* Provides a DataSchema implementation which can be used to work with
* delimited text data.
*
* @module dataschema
* @submodule dataschema-text
*/
/**
Provides a DataSchema implementation which can be used to work with
delimited text data.
See the `apply` method for usage.
@class DataSchema.Text
@extends DataSchema.Base
@static
**/
var Lang = Y.Lang,
isString = Lang.isString,
isUndef = Lang.isUndefined,
SchemaText = {
// DataSchema.Text static methods
/**
Applies a schema to a string of delimited data, returning a normalized
object with results in the `results` property. The `meta` property of
the response object is present for consistency, but is assigned an
empty object. If the input data is absent or not a string, an `error`
property will be added.
Use _schema.resultDelimiter_ and _schema.fieldDelimiter_ to instruct
`apply` how to split up the string into an array of data arrays for
processing.
Use _schema.resultFields_ to specify the keys in the generated result
objects in `response.results`. The key:value pairs will be assigned
in the order of the _schema.resultFields_ array, assuming the values
in the data records are defined in the same order.
_schema.resultFields_ field identifiers are objects with the following
properties:
* `key` : <strong>(required)</strong> The property name you want
the data value assigned to in the result object (String)
* `parser`: A function or the name of a function on `Y.Parsers` used
to convert the input value into a normalized type. Parser
functions are passed the value as input and are expected to
return a value.
If no value parsing is needed, you can use just the desired property
name string as the field identifier instead of an object (see example
below).
@example
// Process simple csv
var schema = {
resultDelimiter: "\n",
fieldDelimiter: ",",
resultFields: [ 'fruit', 'color' ]
},
data = "Banana,yellow\nOrange,orange\nEggplant,purple";
var response = Y.DataSchema.Text.apply(schema, data);
// response.results[0] is { fruit: "Banana", color: "yellow" }
// Use parsers
schema.resultFields = [
{
key: 'fruit',
parser: function (val) { return val.toUpperCase(); }
},
'color' // mix and match objects and strings
];
response = Y.DataSchema.Text.apply(schema, data);
// response.results[0] is { fruit: "BANANA", color: "yellow" }
@method apply
@param {Object} schema Schema to apply. Supported configuration
properties are:
@param {String} schema.resultDelimiter Character or character
sequence that marks the end of one record and the start of
another.
@param {String} [schema.fieldDelimiter] Character or character
sequence that marks the end of a field and the start of
another within the same record.
@param {Array} [schema.resultFields] Field identifiers to
assign values in the response records. See above for details.
@param {String} data Text data.
@return {Object} An Object with properties `results` and `meta`
@static
**/
apply: function(schema, data) {
var data_in = data,
data_out = { results: [], meta: {} };
if (isString(data) && schema && isString(schema.resultDelimiter)) {
// Parse results data
data_out = SchemaText._parseResults.call(this, schema, data_in, data_out);
} else {
Y.log("Text data could not be schema-parsed: " + Y.dump(data) + " " + Y.dump(data), "error", "dataschema-text");
data_out.error = new Error("Text schema parse failure");
}
return data_out;
},
/**
* Schema-parsed list of results from full data
*
* @method _parseResults
* @param schema {Array} Schema to parse against.
* @param text_in {String} Text to parse.
* @param data_out {Object} In-progress parsed data to update.
* @return {Object} Parsed data object.
* @static
* @protected
*/
_parseResults: function(schema, text_in, data_out) {
var resultDelim = schema.resultDelimiter,
fieldDelim = isString(schema.fieldDelimiter) &&
schema.fieldDelimiter,
fields = schema.resultFields || [],
results = [],
parse = Y.DataSchema.Base.parse,
results_in, fields_in, result, item,
field, key, value, i, j;
// Delete final delimiter at end of string if there
if (text_in.slice(-resultDelim.length) === resultDelim) {
text_in = text_in.slice(0, -resultDelim.length);
}
// Split into results
results_in = text_in.split(schema.resultDelimiter);
if (fieldDelim) {
for (i = results_in.length - 1; i >= 0; --i) {
result = {};
item = results_in[i];
fields_in = item.split(schema.fieldDelimiter);
for (j = fields.length - 1; j >= 0; --j) {
field = fields[j];
key = (!isUndef(field.key)) ? field.key : field;
// FIXME: unless the key is an array index, this test
// for fields_in[key] is useless.
value = (!isUndef(fields_in[key])) ?
fields_in[key] :
fields_in[j];
result[key] = parse.call(this, value, field);
}
results[i] = result;
}
} else {
results = results_in;
}
data_out.results = results;
return data_out;
}
};
Y.DataSchema.Text = Y.mix(SchemaText, Y.DataSchema.Base);
|
<?php
/*
* Page that is shown to the user when the plugin was not correctly installed.
* This is just a fallback in case something went wrong somewhere.
* Maybe it just needs to be removed alltogether.
*/
function <API key>() {
?>
<div class="wrap">
<div id="icon-gwolle-gb"><br /></div>
<h1>Gwolle-GB —
<?php _e('Installation','gwolle-gb'); ?>
</h1>
<div>
<?php
if ( !isset($_REQUEST['install_gwolle_gb']) || $_REQUEST['install_gwolle_gb'] != 'install_gwolle_gb') {
_e('Welcome!<br>It seems that either you\'re using this plugin for the first time or you\'ve deleted all settings.<br>However, to use this plugin we have to setup the database tables. Good for you, we\'ve made this as easy as possible.<br>All you\'ve got to do is click on that button below, and that\'s it.','gwolle-gb');
?>
<br /><br />
<div>
<form action="<?php echo $_SERVER['PHP_SELF'] . '?page=' . $_REQUEST['page']; ?>" method="POST">
<input type="hidden" id="install_gwolle_gb" name="install_gwolle_gb" value="install_gwolle_gb" />
<input type="submit" class="button button-primary" value="<?php esc_attr_e('Sure, let\'s do this!', 'gwolle-gb'); ?>">
</form>
</div>
<?php
} elseif ( isset($_REQUEST['install_gwolle_gb']) && $_REQUEST['install_gwolle_gb'] == 'install_gwolle_gb' && !get_option('gwolle_gb_version') ) {
// perform installation
gwolle_gb_install();
echo sprintf( __('Allright, we\'re done. <a href="%s">Click here to continue...</a>', 'gwolle-gb'), $_SERVER['PHP_SELF'] . '?page=' . $_REQUEST['page'] );
} else {
echo sprintf( __('It looks like there has been an error. <a href="%s">Click here to continue...</a>', 'gwolle-gb'), $_SERVER['PHP_SELF'] . '?page=' . $_REQUEST['page'] );
}
?>
</div>
</div>
<?php
}
|
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
#define <API key>
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>
#include <direct.h>
#include <string.h>
// TODO: reference additional headers your program requires here
|
#include "<API key>.h"
#include <pa_tnc/pa_tnc_msg.h>
#include <bio/bio_writer.h>
#include <bio/bio_reader.h>
#include <utils/debug.h>
typedef struct <API key> <API key>;
/**
* SWID Tag Inventory
* see section 4.10 of TCG TNC SWID Message and Attributes for IF-M
*
* 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Reserved | Tag ID Count |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Request ID Copy |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | EID Epoch |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Last EID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Unique Sequence ID Length |Unique Sequence ID (var length)|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Tag Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Tag (Variable) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
#define SWID_TAG_INV_SIZE 16
#define <API key> 0x00
/**
* Private data of an <API key> object.
*/
struct <API key> {
/**
* Public members of <API key>
*/
<API key> public;
/**
* Vendor-specific attribute type
*/
pen_type_t type;
/**
* Attribute value
*/
chunk_t value;
/**
* Noskip flag
*/
bool noskip_flag;
/**
* Request ID
*/
u_int32_t request_id;
/**
* Event ID Epoch
*/
u_int32_t eid_epoch;
/**
* Last Event ID
*/
u_int32_t last_eid;
/**
* SWID Tag Inventory
*/
swid_inventory_t *inventory;
/**
* Reference count
*/
refcount_t ref;
};
METHOD(pa_tnc_attr_t, get_type, pen_type_t,
<API key> *this)
{
return this->type;
}
METHOD(pa_tnc_attr_t, get_value, chunk_t,
<API key> *this)
{
return this->value;
}
METHOD(pa_tnc_attr_t, get_noskip_flag, bool,
<API key> *this)
{
return this->noskip_flag;
}
METHOD(pa_tnc_attr_t, set_noskip_flag,void,
<API key> *this, bool noskip)
{
this->noskip_flag = noskip;
}
METHOD(pa_tnc_attr_t, build, void,
<API key> *this)
{
bio_writer_t *writer;
swid_tag_t *tag;
enumerator_t *enumerator;
if (this->value.ptr)
{
return;
}
writer = bio_writer_create(SWID_TAG_INV_SIZE);
writer->write_uint8 (writer, <API key>);
writer->write_uint24(writer, this->inventory->get_count(this->inventory));
writer->write_uint32(writer, this->request_id);
writer->write_uint32(writer, this->eid_epoch);
writer->write_uint32(writer, this->last_eid);
enumerator = this->inventory->create_enumerator(this->inventory);
while (enumerator->enumerate(enumerator, &tag))
{
writer->write_data16(writer, tag->get_unique_seq_id(tag));
writer->write_data32(writer, tag->get_encoding(tag));
}
enumerator->destroy(enumerator);
this->value = writer->extract_buf(writer);
writer->destroy(writer);
}
METHOD(pa_tnc_attr_t, process, status_t,
<API key> *this, u_int32_t *offset)
{
bio_reader_t *reader;
u_int32_t tag_count;
u_int8_t reserved;
chunk_t tag_encoding, unique_seq_id;
swid_tag_t *tag;
if (this->value.len < SWID_TAG_INV_SIZE)
{
DBG1(DBG_TNC, "insufficient data for SWID Tag Inventory");
*offset = 0;
return FAILED;
}
reader = bio_reader_create(this->value);
reader->read_uint8 (reader, &reserved);
reader->read_uint24(reader, &tag_count);
reader->read_uint32(reader, &this->request_id);
reader->read_uint32(reader, &this->eid_epoch);
reader->read_uint32(reader, &this->last_eid);
*offset = SWID_TAG_INV_SIZE;
while (tag_count
{
if (!reader->read_data16(reader, &unique_seq_id))
{
DBG1(DBG_TNC, "insufficient data for Unique Sequence ID");
return FAILED;
}
*offset += 2 + unique_seq_id.len;
if (!reader->read_data32(reader, &tag_encoding))
{
DBG1(DBG_TNC, "insufficient data for Tag");
return FAILED;
}
*offset += 4 + tag_encoding.len;
tag = swid_tag_create(tag_encoding, unique_seq_id);
this->inventory->add(this->inventory, tag);
}
reader->destroy(reader);
return SUCCESS;
}
METHOD(pa_tnc_attr_t, get_ref, pa_tnc_attr_t*,
<API key> *this)
{
ref_get(&this->ref);
return &this->public.pa_tnc_attribute;
}
METHOD(pa_tnc_attr_t, destroy, void,
<API key> *this)
{
if (ref_put(&this->ref))
{
this->inventory->destroy(this->inventory);
free(this->value.ptr);
free(this);
}
}
METHOD(<API key>, get_request_id, u_int32_t,
<API key> *this)
{
return this->request_id;
}
METHOD(<API key>, get_last_eid, u_int32_t,
<API key> *this, u_int32_t *eid_epoch)
{
if (eid_epoch)
{
*eid_epoch = this->eid_epoch;
}
return this->last_eid;
}
METHOD(<API key>, get_inventory, swid_inventory_t*,
<API key> *this)
{
return this->inventory;
}
/**
* Described in header.
*/
pa_tnc_attr_t *<API key>(u_int32_t request_id,
u_int32_t eid_epoch, u_int32_t eid,
swid_inventory_t *inventory)
{
<API key> *this;
INIT(this,
.public = {
.pa_tnc_attribute = {
.get_type = _get_type,
.get_value = _get_value,
.get_noskip_flag = _get_noskip_flag,
.set_noskip_flag = _set_noskip_flag,
.build = _build,
.process = _process,
.get_ref = _get_ref,
.destroy = _destroy,
},
.get_request_id = _get_request_id,
.get_last_eid = _get_last_eid,
.get_inventory = _get_inventory,
},
.type = { PEN_TCG, <API key> },
.request_id = request_id,
.eid_epoch = eid_epoch,
.last_eid = eid,
.inventory = inventory,
.ref = 1,
);
return &this->public.pa_tnc_attribute;
}
/**
* Described in header.
*/
pa_tnc_attr_t *<API key>(chunk_t data)
{
<API key> *this;
INIT(this,
.public = {
.pa_tnc_attribute = {
.get_type = _get_type,
.get_value = _get_value,
.get_noskip_flag = _get_noskip_flag,
.set_noskip_flag = _set_noskip_flag,
.build = _build,
.process = _process,
.get_ref = _get_ref,
.destroy = _destroy,
},
.get_request_id = _get_request_id,
.get_last_eid = _get_last_eid,
.get_inventory = _get_inventory,
},
.type = { PEN_TCG, <API key> },
.value = chunk_clone(data),
.inventory = <API key>(TRUE),
.ref = 1,
);
return &this->public.pa_tnc_attribute;
}
|
using System;
namespace Server.Items
{
public class LanternHand : BaseLight, IFlipable
{
public override int LabelNumber { get { return 1011221; } } // lantern
public override int LitItemID { get { return ItemID == 0xA471 ? 0xA472 : 0xA476; } }
public override int UnlitItemID { get { return ItemID == 0xA472 ? 0xA471 : 0xA475; } }
public int NorthID { get { return Burning ? 0xA472 : 0xA471; } }
public int WestID { get { return Burning ? 0xA476 : 0xA475; } }
[Constructable]
public LanternHand()
: base(0xA471)
{
Weight = 1;
}
public void OnFlip(Mobile from)
{
if (ItemID == NorthID)
ItemID = WestID;
else if (ItemID == WestID)
ItemID = NorthID;
}
public LanternHand(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
}
|
class <API key>
{
class StaticMGWeapon
{
class <API key>
{
getIn = "_this call <API key>";
};
};
class StaticMortar
{
class <API key>
{
getIn = "_this call <API key>";
};
};
};
|
<?php
defined('ABSPATH') OR exit;
if(!class_exists('<API key>')){
class <API key>{
private $filter = '';
private $cache_duration = 86400;
private $<API key> = array();
private $image_size_to_add = '';
private $insert_before = '';
private $image_size_array = array();
private $<API key> = array();
public $<API key> = '';
public $post_id_to_exclude = '';
public $<API key> = '';
public $post_tag_to_exclude = '';
public $<API key> = '';
public static function retina_only($default_image_sizes, $image_attributes){
if('full' === $image_attributes['size'][1]){
return array($image_attributes['size'][1]);
}else{
return array(
$image_attributes['size'][1],
$image_attributes['size'][1] . '@2x'
);
}
}
public static function remove_line_breaks($output){
return str_replace("\n", '', $output);
}
public static function min_template($template_file_path, $template, $template_path){
return $template_path . 'min/' . $template . '-template.php';
}
public function apply_to_filter($filter){
$this->filter = $filter;
add_filter($filter, array($this, '<API key>'));
}
public function set_cache_duration($cache_duration){
$this->cache_duration = $cache_duration;
add_filter('<API key>', array($this, '_set_cache_duration'));
}
public function <API key>($image_size){
if('string' === gettype($image_size)){
$this-><API key> = array($image_size, $image_size . '@2x');
}elseif('array' === gettype($image_size)){
$this-><API key> = array();
foreach($image_size as $size){
$this-><API key>[] = $size;
$this-><API key>[] = $size . '@2x';
}
}
add_filter('<API key>', array($this, '<API key>'), 10, 2);
}
public function <API key>($image_size, $insert_before){
$this->image_size_to_add = $image_size;
$this->insert_before = $insert_before;
add_filter('<API key>', array($this, '<API key>'), 10, 2);
add_filter('<API key>', array($this, '<API key>'), 11, 2);
}
public function <API key>($image_size_array){
$this->image_size_array = $image_size_array;
$this-><API key> = $this-><API key>($image_size_array);
add_filter('<API key>', array($this, '<API key>'), 10, 2);
add_filter('<API key>', array($this, '<API key>'), 10, 2);
}
public function <API key>(){
$this->image_size_to_add = 'post-thumbnail';
add_action('init', array($this, '<API key>'));
add_filter('post_thumbnail_html', array($this, '<API key>'), 9, 5);
add_filter('<API key>', array($this, '<API key>'), 10, 2);
add_filter('<API key>', array($this, '<API key>'), 10, 2);
$this->apply_to_filter('post_thumbnail_html');
}
public function exclude_post_type($post){
if($this-><API key> === $post->post_type){
remove_filter('the_content', array(Picturefill_WP::get_instance(), '<API key>'), 11);
}
}
public function exclude_post_id($post){
if($this->post_id_to_exclude === $post->ID){
remove_filter('the_content', array(Picturefill_WP::get_instance(), '<API key>'), 11);
}
}
public function exclude_post_slug($post){
if($this-><API key> === $post->post_name){
remove_filter('the_content', array(Picturefill_WP::get_instance(), '<API key>'), 11);
}
}
public function exclude_post_tag($post){
$post_tags = wp_get_post_tags($post->ID, array('fields' => 'names'));
if(in_array($this->post_tag_to_exclude, $post_tags)){
remove_filter('the_content', array(Picturefill_WP::get_instance(), '<API key>'), 11);
}
}
public function <API key>($post){
$post_tags = <API key>($post->ID, array('fields' => 'names'));
if(in_array($this-><API key>, $post_tags)){
remove_filter('the_content', array(Picturefill_WP::get_instance(), '<API key>'), 11);
}
}
public function <API key>($image_queue, $image_attributes){
$new_image_queue = array();
$minimum_reached = empty($image_attributes['min-size'][1]) ? true : false;
foreach($this-><API key> as $image_name){
if($minimum_reached || $image_attributes['min-size'][1] === $image_name){
$minimum_reached = true;
$new_image_queue[] = $image_name;
$new_image_queue[] = $image_name . '@2x';
}
if($image_attributes['size'][1] === $image_name){
return $new_image_queue;
}
}
return !empty($new_image_queue) ? $new_image_queue : $image_queue;
}
public function <API key>($attachment_data, $id){
$new_attachment_data = array();
foreach($this-><API key> as $size){
$new_attachment_data[$size] = <API key>($id, $size);
}
return array_merge($attachment_data, $new_attachment_data);
}
public function <API key>($default_image_sizes, $image_attributes){
return 'post-thumbnail' === $image_attributes['size'][1] ? array(
'post-thumbnail',
'post-thumbnail@2x'
) : $default_image_sizes;
}
public function <API key>(){
global $<API key>;
add_image_size('post-thumbnail@2x', $<API key>['post-thumbnail']['width'] * 2, $<API key>['post-thumbnail']['height'] * 2, $<API key>['post-thumbnail']['crop']);
}
public function <API key>($html, $post_id, $post_thumbnail_id, $size, $attr){
return preg_replace('/class="([^"]+)"/', 'class="$1 size-' . $size . '"', $html);
}
public function <API key>($image_sizes, $image_attributes){
if('@2x' === substr($this->insert_before, -3)){
return $image_sizes;
}
$position = array_search($this->insert_before, $image_sizes);
if($image_attributes['min_size'] !== $this->insert_before){
if(1 > $position){
return array_merge(array($this->image_size_to_add, $this->image_size_to_add . '@2x'), $image_sizes);
}else{
array_splice($image_sizes, $position, 0, array($this->image_size_to_add, $this->image_size_to_add . '@2x'));
return $image_sizes;
}
}else{
return $image_sizes;
}
}
public function <API key>($attachment_data, $attachment_id){
$new_size_data = array(
$this->image_size_to_add => <API key>($attachment_id, $this->image_size_to_add),
$this->image_size_to_add . '@2x' => <API key>($attachment_id, $this->image_size_to_add . '@2x')
);
return array_merge($attachment_data, $new_size_data);
}
public function <API key>($content){
return Picturefill_WP::get_instance()-><API key>($content, $this->filter);
}
public function _set_cache_duration($old_cache_duration){
return $this->cache_duration;
}
public function <API key>($image_sizes, $image_attributes){
return array_diff($image_sizes, $this-><API key>);
}
private function <API key>($image_size_array){
global $<API key>;
$<API key> = <API key>();
$new_image_queue = array();
foreach($image_size_array as $image_name){
if('@2x' === substr($image_name, -3) || !in_array($image_name, $<API key>)){
return $new_image_queue;
}
if(!in_array($image_name . '@2x', $<API key>)){
add_image_size($image_name . '@2x', $<API key>[$image_name]['width'] * 2, $<API key>[$image_name]['height'] * 2, $<API key>[$image_name]['crop']);
}
$new_image_queue[] = $image_name;
// $new_image_queue[] = $image_name . '@2x';
}
return $new_image_queue;
}
}
}
|
// Code adapted of the original code:
// - it is made into a class for use within the framework
// of the sdr-j DAB/DAB+ software
#include "mp2processor.h"
#include "radio.h"
#include "pad-handler.h"
#ifdef _MSC_VER
#define FASTCALL __fastcall
#else
#define FASTCALL
#endif
// TABLES AND CONSTANTS //
// mode constants
#define STEREO 0
#define JOINT_STEREO 1
#define DUAL_CHANNEL 2
#define MONO 3
// sample rate table
static
const unsigned short sample_rates[8] = {
44100, 48000, 32000, 0, // MPEG-1
22050, 24000, 16000, 0 // MPEG-2
};
// bitrate table
static
const short bitrates[28] = {
32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, // MPEG-1
8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 // MPEG-2
};
// scale factor base values (24-bit fixed-point)
static
const int scf_base [3] = {0x02000000, 0x01965FEA, 0x01428A30};
// synthesis window
static
const int D[512] = {
0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,-0x00001,
-0x00001,-0x00001,-0x00001,-0x00002,-0x00002,-0x00003,-0x00003,-0x00004,
-0x00004,-0x00005,-0x00006,-0x00006,-0x00007,-0x00008,-0x00009,-0x0000A,
-0x0000C,-0x0000D,-0x0000F,-0x00010,-0x00012,-0x00014,-0x00017,-0x00019,
-0x0001C,-0x0001E,-0x00022,-0x00025,-0x00028,-0x0002C,-0x00030,-0x00034,
-0x00039,-0x0003E,-0x00043,-0x00048,-0x0004E,-0x00054,-0x0005A,-0x00060,
-0x00067,-0x0006E,-0x00074,-0x0007C,-0x00083,-0x0008A,-0x00092,-0x00099,
-0x000A0,-0x000A8,-0x000AF,-0x000B6,-0x000BD,-0x000C3,-0x000C9,-0x000CF,
0x000D5, 0x000DA, 0x000DE, 0x000E1, 0x000E3, 0x000E4, 0x000E4, 0x000E3,
0x000E0, 0x000DD, 0x000D7, 0x000D0, 0x000C8, 0x000BD, 0x000B1, 0x000A3,
0x00092, 0x0007F, 0x0006A, 0x00053, 0x00039, 0x0001D,-0x00001,-0x00023,
-0x00047,-0x0006E,-0x00098,-0x000C4,-0x000F3,-0x00125,-0x0015A,-0x00190,
-0x001CA,-0x00206,-0x00244,-0x00284,-0x002C6,-0x0030A,-0x0034F,-0x00396,
-0x003DE,-0x00427,-0x00470,-0x004B9,-0x00502,-0x0054B,-0x00593,-0x005D9,
-0x0061E,-0x00661,-0x006A1,-0x006DE,-0x00718,-0x0074D,-0x0077E,-0x007A9,
-0x007D0,-0x007EF,-0x00808,-0x0081A,-0x00824,-0x00826,-0x0081F,-0x0080E,
0x007F5, 0x007D0, 0x007A0, 0x00765, 0x0071E, 0x006CB, 0x0066C, 0x005FF,
0x00586, 0x00500, 0x0046B, 0x003CA, 0x0031A, 0x0025D, 0x00192, 0x000B9,
-0x0002C,-0x0011F,-0x00220,-0x0032D,-0x00446,-0x0056B,-0x0069B,-0x007D5,
-0x00919,-0x00A66,-0x00BBB,-0x00D16,-0x00E78,-0x00FDE,-0x01148,-0x012B3,
-0x01420,-0x0158C,-0x016F6,-0x0185C,-0x019BC,-0x01B16,-0x01C66,-0x01DAC,
-0x01EE5,-0x02010,-0x0212A,-0x02232,-0x02325,-0x02402,-0x024C7,-0x02570,
-0x025FE,-0x0266D,-0x026BB,-0x026E6,-0x026ED,-0x026CE,-0x02686,-0x02615,
-0x02577,-0x024AC,-0x023B2,-0x02287,-0x0212B,-0x01F9B,-0x01DD7,-0x01BDD,
0x019AE, 0x01747, 0x014A8, 0x011D1, 0x00EC0, 0x00B77, 0x007F5, 0x0043A,
0x00046,-0x003E5,-0x00849,-0x00CE3,-0x011B4,-0x016B9,-0x01BF1,-0x0215B,
-0x026F6,-0x02CBE,-0x032B3,-0x038D3,-0x03F1A,-0x04586,-0x04C15,-0x052C4,
-0x05990,-0x06075,-0x06771,-0x06E80,-0x0759F,-0x07CCA,-0x083FE,-0x08B37,
-0x09270,-0x099A7,-0x0A0D7,-0x0A7FD,-0x0AF14,-0x0B618,-0x0BD05,-0x0C3D8,
-0x0CA8C,-0x0D11D,-0x0D789,-0x0DDC9,-0x0E3DC,-0x0E9BD,-0x0EF68,-0x0F4DB,
-0x0FA12,-0x0FF09,-0x103BD,-0x1082C,-0x10C53,-0x1102E,-0x113BD,-0x116FB,
-0x119E8,-0x11C82,-0x11EC6,-0x120B3,-0x12248,-0x12385,-0x12467,-0x124EF,
0x1251E, 0x124F0, 0x12468, 0x12386, 0x12249, 0x120B4, 0x11EC7, 0x11C83,
0x119E9, 0x116FC, 0x113BE, 0x1102F, 0x10C54, 0x1082D, 0x103BE, 0x0FF0A,
0x0FA13, 0x0F4DC, 0x0EF69, 0x0E9BE, 0x0E3DD, 0x0DDCA, 0x0D78A, 0x0D11E,
0x0CA8D, 0x0C3D9, 0x0BD06, 0x0B619, 0x0AF15, 0x0A7FE, 0x0A0D8, 0x099A8,
0x09271, 0x08B38, 0x083FF, 0x07CCB, 0x075A0, 0x06E81, 0x06772, 0x06076,
0x05991, 0x052C5, 0x04C16, 0x04587, 0x03F1B, 0x038D4, 0x032B4, 0x02CBF,
0x026F7, 0x0215C, 0x01BF2, 0x016BA, 0x011B5, 0x00CE4, 0x0084A, 0x003E6,
-0x00045,-0x00439,-0x007F4,-0x00B76,-0x00EBF,-0x011D0,-0x014A7,-0x01746,
0x019AE, 0x01BDE, 0x01DD8, 0x01F9C, 0x0212C, 0x02288, 0x023B3, 0x024AD,
0x02578, 0x02616, 0x02687, 0x026CF, 0x026EE, 0x026E7, 0x026BC, 0x0266E,
0x025FF, 0x02571, 0x024C8, 0x02403, 0x02326, 0x02233, 0x0212B, 0x02011,
0x01EE6, 0x01DAD, 0x01C67, 0x01B17, 0x019BD, 0x0185D, 0x016F7, 0x0158D,
0x01421, 0x012B4, 0x01149, 0x00FDF, 0x00E79, 0x00D17, 0x00BBC, 0x00A67,
0x0091A, 0x007D6, 0x0069C, 0x0056C, 0x00447, 0x0032E, 0x00221, 0x00120,
0x0002D,-0x000B8,-0x00191,-0x0025C,-0x00319,-0x003C9,-0x0046A,-0x004FF,
-0x00585,-0x005FE,-0x0066B,-0x006CA,-0x0071D,-0x00764,-0x0079F,-0x007CF,
0x007F5, 0x0080F, 0x00820, 0x00827, 0x00825, 0x0081B, 0x00809, 0x007F0,
0x007D1, 0x007AA, 0x0077F, 0x0074E, 0x00719, 0x006DF, 0x006A2, 0x00662,
0x0061F, 0x005DA, 0x00594, 0x0054C, 0x00503, 0x004BA, 0x00471, 0x00428,
0x003DF, 0x00397, 0x00350, 0x0030B, 0x002C7, 0x00285, 0x00245, 0x00207,
0x001CB, 0x00191, 0x0015B, 0x00126, 0x000F4, 0x000C5, 0x00099, 0x0006F,
0x00048, 0x00024, 0x00002,-0x0001C,-0x00038,-0x00052,-0x00069,-0x0007E,
-0x00091,-0x000A2,-0x000B0,-0x000BC,-0x000C7,-0x000CF,-0x000D6,-0x000DC,
-0x000DF,-0x000E2,-0x000E3,-0x000E3,-0x000E2,-0x000E0,-0x000DD,-0x000D9,
0x000D5, 0x000D0, 0x000CA, 0x000C4, 0x000BE, 0x000B7, 0x000B0, 0x000A9,
0x000A1, 0x0009A, 0x00093, 0x0008B, 0x00084, 0x0007D, 0x00075, 0x0006F,
0x00068, 0x00061, 0x0005B, 0x00055, 0x0004F, 0x00049, 0x00044, 0x0003F,
0x0003A, 0x00035, 0x00031, 0x0002D, 0x00029, 0x00026, 0x00023, 0x0001F,
0x0001D, 0x0001A, 0x00018, 0x00015, 0x00013, 0x00011, 0x00010, 0x0000E,
0x0000D, 0x0000B, 0x0000A, 0x00009, 0x00008, 0x00007, 0x00007, 0x00006,
0x00005, 0x00005, 0x00004, 0x00004, 0x00003, 0x00003, 0x00002, 0x00002,
0x00002, 0x00002, 0x00001, 0x00001, 0x00001, 0x00001, 0x00001, 0x00001
};
////////// Table 3-B.2: Possible quantization per subband ///////////////////
// quantizer lookup, step 1: bitrate classes
static uint8_t quant_lut_step1[2][16] = {
// 32, 48, 56, 64, 80, 96,112,128,160,192,224,256,320,384 <- bitrate
{ 0, 0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2 }, // mono
// 16, 24, 28, 32, 40, 48, 56, 64, 80, 96,112,128,160,192 <- BR / chan
{ 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2 } // stereo
};
// quantizer lookup, step 2: bitrate class, sample rate -> B2 table idx, sblimit
#define QUANT_TAB_A (27 | 64) // Table 3-B.2a: high-rate, sblimit = 27
#define QUANT_TAB_B (30 | 64) // Table 3-B.2b: high-rate, sblimit = 30
#define QUANT_TAB_C 8 // Table 3-B.2c: low-rate, sblimit = 8
#define QUANT_TAB_D 12 // Table 3-B.2d: low-rate, sblimit = 12
static
const char quant_lut_step2 [3][4] = {
// 44.1 kHz, 48 kHz, 32 kHz
{ QUANT_TAB_C, QUANT_TAB_C, QUANT_TAB_D }, // 32 - 48 kbit/sec/ch
{ QUANT_TAB_A, QUANT_TAB_A, QUANT_TAB_A }, // 56 - 80 kbit/sec/ch
{ QUANT_TAB_B, QUANT_TAB_A, QUANT_TAB_B }, // 96+ kbit/sec/ch
};
// quantizer lookup, step 3: B2 table, subband -> nbal, row index
// (upper 4 bits: nbal, lower 4 bits: row index)
static
uint8_t quant_lut_step3 [3][32] = {
// low-rate table (3-B.2c and 3-B.2d)
{ 0x44,0x44, // SB 0 - 1
0x34,0x34,0x34,0x34,0x34,0x34,0x34,0x34,0x34,0x34 // SB 2 - 12
},
// high-rate table (3-B.2a and 3-B.2b)
{ 0x43,0x43,0x43, // SB 0 - 2
0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x42, // SB 3 - 10
0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x31, // SB 11 - 22
0x20,0x20,0x20,0x20,0x20,0x20,0x20 // SB 23 - 29
},
// MPEG-2 LSR table (B.2 in ISO 13818-3)
{ 0x45,0x45,0x45,0x45, // SB 0 - 3
0x34,0x34,0x34,0x34,0x34,0x34,0x34, // SB 4 - 10
0x24,0x24,0x24,0x24,0x24,0x24,0x24,0x24,0x24,0x24, // SB 11 -
0x24,0x24,0x24,0x24,0x24,0x24,0x24,0x24,0x24
}
};
// quantizer lookup, step 4: table row, allocation[] value -> quant table index
static
const char quant_lut_step4 [6][16] = {
{ 0, 1, 2, 17 },
{ 0, 1, 2, 3, 4, 5, 6, 17 },
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17 },
{ 0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 },
{ 0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17 },
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }
};
// quantizer table
static
struct quantizer_spec quantizer_table [17] = {
{ 3, 1, 5 },
{ 5, 1, 7 },
{ 7, 0, 3 },
{ 9, 1, 10 },
{ 15, 0, 4 },
{ 31, 0, 5 },
{ 63, 0, 6 },
{ 127, 0, 7 },
{ 255, 0, 8 },
{ 511, 0, 9 },
{ 1023, 0, 10 },
{ 2047, 0, 11 },
{ 4095, 0, 12 },
{ 8191, 0, 13 },
{ 16383, 0, 14 },
{ 32767, 0, 15 },
{ 65535, 0, 16 }
};
// The initialization is now done in the constructor
// (J van Katwijk)
mp2Processor::mp2Processor (RadioInterface *mr,
int16_t bitRate,
RingBuffer<int16_t> *buffer,
RingBuffer<uint8_t> *frameBuffer):
my_padhandler (mr) {
int16_t i, j;
int16_t *nPtr = &N [0][0];
// compute N[i][j]
for (i = 0; i < 64; i ++)
for (j = 0; j < 32; ++j)
*nPtr++ = (int16_t) (256.0 *
cos(((16 + i) * ((j << 1) + 1)) *
0.0490873852123405));
// perform local initialization:
for (i = 0; i < 2; ++i)
for (j = 1023; j >= 0; j
V [i][j] = 0;
myRadioInterface = mr;
this -> buffer = buffer;
this -> bitRate = bitRate;
connect (this, SIGNAL (show_frameErrors (int)),
mr, SLOT (show_frameErrors (int)));
connect (this, SIGNAL (newAudio (int, int)),
mr, SLOT (newAudio (int, int)));
connect (this, SIGNAL (isStereo (bool)),
mr, SLOT (setStereo (bool)));
Voffs = 0;
baudRate = 48000; // default for DAB
MP2framesize = 24 * bitRate; // may be changed
MP2frame = new uint8_t [2 * MP2framesize];
MP2Header_OK = 0;
MP2headerCount = 0;
MP2bitCount = 0;
numberofFrames = 0;
errorFrames = 0;
}
mp2Processor::~mp2Processor() {
delete[] MP2frame;
}
#define valid(x) ((x == 48000) || (x == 24000))
void mp2Processor::setSamplerate (int32_t rate) {
if (baudRate == rate)
return;
if (!valid (rate))
return;
// ourSink -> setMode (0, rate);
baudRate = rate;
}
// INITIALIZATION: is moved into the constructor for the class
int32_t mp2Processor::mp2sampleRate (uint8_t *frame) {
if (!frame)
return 0;
if (( frame[0] != 0xFF) // no valid syncword?
|| ((frame[1] & 0xF6) != 0xF4) // no MPEG-1/2 Audio Layer II?
|| ((frame[2] - 0x10) >= 0xE0)) // invalid bitrate?
return 0;
return sample_rates[(((frame[1] & 0x08) >> 1) ^ 4) // MPEG-1/2 switch
+ ((frame[2] >> 2) & 3)]; // actual rate
}
// DECODE HELPER FUNCTIONS //
struct quantizer_spec*
mp2Processor::read_allocation (int sb, int b2_table) {
int table_idx = quant_lut_step3 [b2_table][sb];
table_idx = quant_lut_step4 [table_idx & 15] [get_bits(table_idx >> 4)];
return table_idx ? (&quantizer_table[table_idx - 1]) : nullptr;
}
void mp2Processor::read_samples (struct quantizer_spec *q,
int scalefactor, int *sample) {
int idx, adj, scale;
int val;
if (!q) {
// no bits allocated for this subband
sample[0] = sample[1] = sample[2] = 0;
return;
}
// resolve scalefactor
if (scalefactor == 63) {
scalefactor = 0;
} else {
adj = scalefactor / 3;
scalefactor = (scf_base[scalefactor % 3] + ((1 << adj) >> 1)) >> adj;
}
// decode samples
adj = q -> nlevels;
if (q -> grouping) { // decode grouped samples
val = get_bits (q -> cw_bits);
sample [0] = val % adj;
val /= adj;
sample [1] = val % adj;
sample [2] = val / adj;
} else { // decode direct samples
for (idx = 0; idx < 3; ++idx)
sample [idx] = get_bits (q -> cw_bits);
}
// postmultiply samples
scale = 65536 / (adj + 1);
adj = ((adj + 1) >> 1) - 1;
for (idx = 0; idx < 3; ++idx) {
// step 1: renormalization to [-1..1]
val = (adj - sample[idx]) * scale;
// step 2: apply scalefactor
sample[idx] = ( val * (scalefactor >> 12) // upper part
+ ((val * (scalefactor & 4095) + 2048) >> 12)) // lower part
>> 12; // scale adjust
}
}
#define show_bits(bit_count) (bit_window >> (24 - (bit_count)))
int32_t mp2Processor::get_bits (int32_t bit_count) {
//int32_t result = show_bits (bit_count);
int32_t result = bit_window >> (24 - bit_count);
bit_window = (bit_window << bit_count) & 0xFFFFFF;
bits_in_window -= bit_count;
while (bits_in_window < 16) {
bit_window |= (*frame_pos++) << (16 - bits_in_window);
bits_in_window += 8;
}
return result;
}
// FRAME DECODE FUNCTION //
int32_t mp2Processor::mp2decodeFrame (uint8_t *frame, int16_t *pcm) {
uint32_t <API key>;
uint32_t sampling_frequency;
uint32_t padding_bit;
uint32_t mode;
uint32_t frame_size;
int32_t bound, sblimit;
int32_t sb, ch, gr, part, idx, nch, i, j, sum;
int32_t table_idx;
numberofFrames ++;
if (numberofFrames >= 25) {
show_frameErrors (errorFrames);
numberofFrames = 0;
errorFrames = 0;
}
// check for valid header: syncword OK, MPEG-Audio Layer 2
if (( frame[0] != 0xFF) // no valid syncword?
|| ((frame[1] & 0xF6) != 0xF4) // no MPEG-1/2 Audio Layer II?
|| ((frame[2] - 0x10) >= 0xE0)) { // invalid bitrate?
errorFrames ++;
return 0;
}
// set up the bitstream reader
bit_window = frame [2] << 16;
bits_in_window = 8;
frame_pos = &frame[3];
// read the rest of the header
<API key> = get_bits(4) - 1;
if (<API key> > 13)
return 0; // invalid bit rate or 'free format'
sampling_frequency = get_bits(2);
if (sampling_frequency == 3)
return 0;
if ((frame[1] & 0x08) == 0) { // MPEG-2
sampling_frequency += 4;
<API key> += 14;
}
padding_bit = get_bits(1);
get_bits(1); // discard private_bit
mode = get_bits(2);
// parse the mode_extension, set up the stereo bound
if (mode == JOINT_STEREO)
bound = (get_bits(2) + 1) << 2;
else {
get_bits(2);
bound = (mode == MONO) ? 0 : 32;
}
emit isStereo ((mode == JOINT_STEREO) || (mode == STEREO));
// discard the last 4 bits of the header and the CRC value, if present
get_bits(4);
if ((frame [1] & 1) == 0)
get_bits(16);
// compute the frame size
frame_size = (144000 * bitrates[<API key>]
/ sample_rates [sampling_frequency]) + padding_bit;
if (!pcm)
return frame_size; // no decoding
// prepare the quantizer table lookups
if (sampling_frequency & 4) {
// MPEG-2 (LSR)
table_idx = 2;
sblimit = 30;
} else {
// MPEG-1
table_idx = (mode == MONO) ? 0 : 1;
table_idx = quant_lut_step1[table_idx][<API key>];
table_idx = quant_lut_step2[table_idx][sampling_frequency];
sblimit = table_idx & 63;
table_idx >>= 6;
}
if (bound > sblimit)
bound = sblimit;
// read the allocation information
for (sb = 0; sb < bound; ++sb)
for (ch = 0; ch < 2; ++ch)
allocation [ch][sb] = read_allocation(sb, table_idx);
for (sb = bound; sb < sblimit; ++sb)
allocation[0][sb] =
allocation[1][sb] = read_allocation (sb, table_idx);
// read scale factor selector information
nch = (mode == MONO) ? 1 : 2;
for (sb = 0; sb < sblimit; ++sb) {
for (ch = 0; ch < nch; ++ch)
if (allocation [ch][sb])
scfsi [ch][sb] = get_bits (2);
if (mode == MONO)
scfsi[1][sb] = scfsi[0][sb];
}
// read scale factors
for (sb = 0; sb < sblimit; ++sb) {
for (ch = 0; ch < nch; ++ch) {
if (allocation[ch][sb]) {
switch (scfsi[ch][sb]) {
case 0: scalefactor[ch][sb][0] = get_bits(6);
scalefactor[ch][sb][1] = get_bits(6);
scalefactor[ch][sb][2] = get_bits(6);
break;
case 1: scalefactor[ch][sb][0] =
scalefactor[ch][sb][1] = get_bits(6);
scalefactor[ch][sb][2] = get_bits(6);
break;
case 2: scalefactor[ch][sb][0] =
scalefactor[ch][sb][1] =
scalefactor[ch][sb][2] = get_bits(6);
break;
case 3: scalefactor[ch][sb][0] = get_bits(6);
scalefactor[ch][sb][1] =
scalefactor[ch][sb][2] = get_bits(6);
break;
}
}
}
if (mode == MONO)
for (part = 0; part < 3; ++part)
scalefactor[1][sb][part] = scalefactor[0][sb][part];
}
// coefficient input and reconstruction
for (part = 0; part < 3; ++part) {
for (gr = 0; gr < 4; ++gr) {
// read the samples
for (sb = 0; sb < bound; ++sb)
for (ch = 0; ch < 2; ++ch)
read_samples (allocation[ch][sb],
scalefactor[ch][sb][part],
&sample[ch][sb][0]);
for (sb = bound; sb < sblimit; ++sb) {
read_samples (allocation[0][sb],
scalefactor[0][sb][part],
&sample[0][sb][0]);
for (idx = 0; idx < 3; ++idx)
sample[1][sb][idx] = sample[0][sb][idx];
}
for (ch = 0; ch < 2; ++ch)
for (sb = sblimit; sb < 32; ++sb)
for (idx = 0; idx < 3; ++idx)
sample[ch][sb][idx] = 0;
// synthesis loop
for (idx = 0; idx < 3; ++idx) {
// shifting step
Voffs = table_idx = (Voffs - 64) & 1023;
for (ch = 0; ch < 2; ++ch) {
// matrixing
for (i = 0; i < 64; ++i) {
sum = 0;
for (j = 0; j < 32; ++j) // 8b*15b=23b
sum += N[i][j] * sample[ch][j][idx];
// intermediate value is 28 bit (23 + 5), clamp to 14b
V [ch][table_idx + i] = (sum + 8192) >> 14;
}
// construction of U
for (i = 0; i < 8; ++i)
for (j = 0; j < 32; ++j) {
U [(i << 6) + j]
= V [ch][(table_idx + (i << 7) + j) & 1023];
U [(i << 6) + j + 32] =
V [ch][(table_idx + (i << 7) + j + 96) & 1023];
}
// apply window
for (i = 0; i < 512; ++i)
U [i] = (U [i] * D [i] + 32) >> 6;
// output samples
for (j = 0; j < 32; ++j) {
sum = 0;
for (i = 0; i < 16; ++i)
sum -= U [(i << 5) + j];
sum = (sum + 8) >> 4;
if (sum < -32768)
sum = -32768;
if (sum > 32767)
sum = 32767;
pcm[(idx << 6) | (j << 1) | ch] = (uint16_t) sum;
}
} // end of synthesis channel loop
} // end of synthesis sub-block loop
// adjust PCM output pointer: decoded 3 * 32 = 96 stereo samples
pcm += 192;
} // decoding of the granule finished
}
return frame_size;
}
// bits to MP2 frames, amount is amount of bits
void mp2Processor::addtoFrame (std::vector<uint8_t> v) {
int16_t i, j;
int16_t lf = baudRate == 48000 ? MP2framesize : 2 * MP2framesize;
int16_t amount = MP2framesize;
uint8_t help [24 * bitRate / 8];
int16_t vLength = 24 * bitRate / 8;
//fprintf (stderr, "baudrate = %d, inputsize = %d\n",
// baudRate, v. size ());
// fprintf (stderr, "\n");
for (i = 0; i < 24 * bitRate / 8; i ++) {
help [i] = 0;
for (j = 0; j < 8; j ++) {
help [i] <<= 1;
help [i] |= v [8 * i + j] & 01;
}
}
{ uint8_t L0 = help [vLength - 1];
uint8_t L1 = help [vLength - 2];
int16_t down = bitRate * 1000 >= 56000 ? 4 : 2;
my_padhandler. processPAD (help, vLength - 2 - down - 1, L1, L0);
}
for (i = 0; i < amount; i ++) {
if (MP2Header_OK == 2) {
addbittoMP2 (MP2frame, v [i], MP2bitCount ++);
if (MP2bitCount >= lf) {
int16_t sample_buf [<API key> * 2];
if (mp2decodeFrame (MP2frame, sample_buf)) {
buffer -> putDataIntoBuffer (sample_buf,
2 * (int32_t)<API key>);
if (buffer -> <API key> () > baudRate / 8)
newAudio (2 * (int32_t)<API key>,
baudRate);
}
MP2Header_OK = 0;
MP2headerCount = 0;
MP2bitCount = 0;
}
} else
if (MP2Header_OK == 0) {
// apparently , we are not in sync yet
if (v [i] == 01) {
if (++ MP2headerCount == 12) {
MP2bitCount = 0;
for (j = 0; j < 12; j ++)
addbittoMP2 (MP2frame, 1, MP2bitCount ++);
MP2Header_OK = 1;
}
}
else
MP2headerCount = 0;
}
else
if (MP2Header_OK == 1) {
addbittoMP2 (MP2frame, v [i], MP2bitCount ++);
if (MP2bitCount == 24) {
setSamplerate (mp2sampleRate (MP2frame));
MP2Header_OK = 2;
}
}
}
}
void mp2Processor::addbittoMP2 (uint8_t *v, uint8_t b, int16_t nm) {
uint8_t byte = v [nm / 8];
int16_t bitnr = 7 - (nm & 7);
uint8_t newbyte = (01 << bitnr);
if (b == 0)
byte &= ~newbyte;
else
byte |= newbyte;
v [nm / 8] = byte;
}
|
#include <QApplication>
#include <QMenuBar>
#include <QMessageBox>
#include <QFileDialog>
#include <QVBoxLayout>
#include <QDockWidget>
#include <QProgressDialog>
#include <QDesktopWidget>
#include "vfs_dialog.h"
#include "save_manager_dialog.h"
#include "kernel_explorer.h"
#include "game_list_frame.h"
#include "debugger_frame.h"
#include "log_frame.h"
#include "settings_dialog.h"
#include "<API key>.h"
#include "cg_disasm_window.h"
#include "<API key>.h"
#include "memory_viewer_panel.h"
#include "rsx_debugger.h"
#include "main_window.h"
#include "emu_settings.h"
#include "about_dialog.h"
#include "<API key>.h"
#include <thread>
#include "stdafx.h"
#include "Emu/System.h"
#include "Emu/Memory/Memory.h"
#include "Crypto/unpkg.h"
#include "Crypto/unself.h"
#include "Loader/PUP.h"
#include "Loader/TAR.h"
#include "Utilities/Thread.h"
#include "Utilities/StrUtil.h"
#include "rpcs3_version.h"
#include "Utilities/sysinfo.h"
#include "ui_main_window.h"
inline std::string sstr(const QString& _in) { return _in.toUtf8().toStdString(); }
main_window::main_window(std::shared_ptr<gui_settings> guiSettings, QWidget *parent) : QMainWindow(parent), guiSettings(guiSettings), m_sys_menu_opened(false), ui(new Ui::main_window)
{
}
main_window::~main_window()
{
delete ui;
}
auto Pause = []()
{
if (Emu.IsReady()) Emu.Run();
else if (Emu.IsPaused()) Emu.Resume();
else if (Emu.IsRunning()) Emu.Pause();
else if (!Emu.GetPath().empty()) Emu.Load();
};
/* An init method is used so that RPCS3App can create the necessary connects before calling init (specifically the stylesheet connect).
* Simplifies logic a bit.
*/
void main_window::Init()
{
ui->setupUi(this);
m_appIcon = QIcon(":/rpcs3.ico");
// hide utilities from the average user
ui->menuUtilities->menuAction()->setVisible(guiSettings->GetValue(GUI::m_showDebugTab).toBool());
// add toolbar widgets (crappy Qt designer is not able to)
ui->toolBar->setObjectName("mw_toolbar");
ui->sizeSlider->setRange(0, GUI::gl_max_slider_pos);
ui->sizeSlider->setSliderPosition(guiSettings->GetValue(GUI::gl_iconSize).toInt());
ui->toolBar->addWidget(ui->sizeSliderContainer);
ui->toolBar->addSeparator();
ui->toolBar->addWidget(ui->mw_searchbar);
// for highdpi resize toolbar icons and height dynamically
// choose factors to mimic Gui-Design in main_window.ui
// TODO: in case Qt::<API key> is enabled in main.cpp we only need the else branch
#ifdef _WIN32
const int toolBarHeight = menuBar()->sizeHint().height() * 1.5;
ui->toolBar->setIconSize(QSize(toolBarHeight, toolBarHeight));
#else
const int toolBarHeight = ui->toolBar->iconSize().height();
#endif
ui->sizeSliderContainer->setFixedWidth(toolBarHeight * 5);
ui->sizeSlider->setFixedHeight(toolBarHeight * 0.65f);
CreateActions();
CreateDockWindows();
setMinimumSize(350, minimumSizeHint().height()); // seems fine on win 10
CreateConnects();
setWindowTitle(QString::fromStdString("RPCS3 v" + rpcs3::version.to_string()));
!m_appIcon.isNull() ? setWindowIcon(m_appIcon) : LOG_WARNING(GENERAL, "AppImage could not be loaded!");
Q_EMIT <API key>(guiSettings-><API key>());
<API key>(true);
RepaintToolBarIcons();
m_gameListFrame->RepaintToolBarIcons();
if (!utils::has_ssse3())
{
QMessageBox::critical(this, "SSSE3 Error (with three S, not two)",
"Your system does not meet the minimum requirements needed to run RPCS3.\n"
"Your CPU does not support SSSE3 (with three S, not two).\n");
std::exit(EXIT_FAILURE);
}
#ifdef BRANCH
if ("RPCS3/rpcs3/master"s != STRINGIZE(BRANCH))
#elif _MSC_VER
fs::stat_t st;
if (!fs::stat(fs::get_config_dir() + "rpcs3.pdb", st) || st.is_directory || st.size < 1024 * 1024 * 100)
#else
if (false)
#endif
{
LOG_WARNING(GENERAL, "Experimental Build Warning! Build origin: " STRINGIZE(BRANCH));
QMessageBox msg;
msg.setWindowTitle("Experimental Build Warning");
msg.setWindowIcon(m_appIcon);
msg.setIcon(QMessageBox::Critical);
msg.setTextFormat(Qt::RichText);
msg.setText("Please understand that this build is not an official RPCS3 release.<br>This build contains changes that may break games, or even <b>damage</b> your data.<br>It's recommended to download and use the official build from <a href='https://rpcs3.net/download'>RPCS3 website</a>.<br><br>Build origin: " STRINGIZE(BRANCH) "<br>Do you wish to use this build anyway?");
msg.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msg.setDefaultButton(QMessageBox::No);
if (msg.exec() == QMessageBox::No)
{
std::exit(EXIT_SUCCESS);
}
}
}
void main_window::<API key>()
{
#ifdef _WIN32
m_icon_thumb_play = QIcon(":/Icons/play_blue.png");
m_icon_thumb_pause = QIcon(":/Icons/pause_blue.png");
m_icon_thumb_stop = QIcon(":/Icons/stop_blue.png");
<API key> = QIcon(":/Icons/restart_blue.png");
m_thumb_bar = new <API key>(this);
m_thumb_bar->setWindow(windowHandle());
m_thumb_playPause = new <API key>(m_thumb_bar);
m_thumb_playPause->setToolTip(tr("Pause"));
m_thumb_playPause->setIcon(m_icon_thumb_pause);
m_thumb_playPause->setEnabled(false);
m_thumb_stop = new <API key>(m_thumb_bar);
m_thumb_stop->setToolTip(tr("Stop"));
m_thumb_stop->setIcon(m_icon_thumb_stop);
m_thumb_stop->setEnabled(false);
m_thumb_restart = new <API key>(m_thumb_bar);
m_thumb_restart->setToolTip(tr("Restart"));
m_thumb_restart->setIcon(<API key>);
m_thumb_restart->setEnabled(false);
m_thumb_bar->addButton(m_thumb_playPause);
m_thumb_bar->addButton(m_thumb_stop);
m_thumb_bar->addButton(m_thumb_restart);
connect(m_thumb_stop, &<API key>::clicked, [=]() { Emu.Stop(); });
connect(m_thumb_restart, &<API key>::clicked, [=]() { Emu.Stop(); Emu.Load(); });
connect(m_thumb_playPause, &<API key>::clicked, Pause);
#endif
}
// returns appIcon
QIcon main_window::GetAppIcon()
{
return m_appIcon;
}
// loads the appIcon from path and embeds it centered into an empty square icon
void main_window::SetAppIconFromPath(const std::string path)
{
// get Icon for the gs_frame from path. this handles presumably all possible use cases
QString qpath = qstr(path);
std::string icon_list[] = { "/ICON0.PNG", "/PS3_GAME/ICON0.PNG" };
std::string path_list[] = { path, sstr(qpath.section("/", 0, -2)), sstr(qpath.section("/", 0, -3)) };
for (std::string pth : path_list)
{
if (!fs::is_dir(pth)) continue;
for (std::string ico : icon_list)
{
ico = pth + ico;
if (fs::is_file(ico))
{
// load the image from path. It will most likely be a rectangle
QImage source = QImage(qstr(ico));
int edgeMax = std::max(source.width(), source.height());
// create a new transparent image with square size and same format as source (maybe handle other formats than RGB32 as well?)
QImage::Format format = source.format() == QImage::Format_RGB32 ? QImage::Format_ARGB32 : source.format();
QImage dest = QImage(edgeMax, edgeMax, format);
dest.fill(QColor("transparent"));
// get the location to draw the source image centered within the dest image.
QPoint destPos = source.width() > source.height() ? QPoint(0, (source.width() - source.height()) / 2)
: QPoint((source.height() - source.width()) / 2, 0);
// Paint the source into/over the dest
QPainter painter(&dest);
painter.drawImage(destPos, source);
painter.end();
// set Icon
m_appIcon = QIcon(QPixmap::fromImage(dest));
return;
}
}
}
// if nothing was found reset the icon to default
m_appIcon = QIcon(":/rpcs3.ico");
}
void main_window::BootElf()
{
bool stopped = false;
if (Emu.IsRunning())
{
Emu.Pause();
stopped = true;
}
QString path_last_ELF = guiSettings->GetValue(GUI::fd_boot_elf).toString();
QString filePath = QFileDialog::getOpenFileName(this, tr("Select (S)ELF To Boot"), path_last_ELF, tr(
"(S)ELF files (*BOOT.BIN *.elf *.self);;"
"ELF files (BOOT.BIN *.elf);;"
"SELF files (EBOOT.BIN *.self);;"
"BOOT files (*BOOT.BIN);;"
"BIN files (*.bin);;"
"All files (*.*)"),
Q_NULLPTR, QFileDialog::DontResolveSymlinks);
if (filePath == NULL)
{
if (stopped) Emu.Resume();
return;
}
LOG_NOTICE(LOADER, "(S)ELF: booting...");
// If we resolved the filepath earlier we would end up setting the last opened dir to the unwanted
// game folder in case of having e.g. a Game Folder with collected links to elf files.
// Don't set last path earlier in case of cancelled dialog
guiSettings->SetValue(GUI::fd_boot_elf, filePath);
const std::string path = sstr(QFileInfo(filePath).canonicalFilePath());
SetAppIconFromPath(path);
Emu.Stop();
if (!Emu.BootGame(path, true))
{
LOG_ERROR(GENERAL, "PS3 executable not found at path (%s)", path);
}
else
{
LOG_SUCCESS(LOADER, "(S)ELF: boot done.");
const std::string serial = Emu.GetTitleID().empty() ? "" : "[" + Emu.GetTitleID() + "] ";
AddRecentAction(GUI::Recent_Game(qstr(Emu.GetBoot()), qstr(serial + Emu.GetTitle())));
m_gameListFrame->Refresh(true);
}
}
void main_window::BootGame()
{
bool stopped = false;
if (Emu.IsRunning())
{
Emu.Pause();
stopped = true;
}
QString path_last_Game = guiSettings->GetValue(GUI::fd_boot_game).toString();
QString dirPath = QFileDialog::<API key>(this, tr("Select Game Folder"), path_last_Game, QFileDialog::ShowDirsOnly);
if (dirPath == NULL)
{
if (stopped) Emu.Resume();
return;
}
Emu.Stop();
guiSettings->SetValue(GUI::fd_boot_game, QFileInfo(dirPath).path());
const std::string path = sstr(dirPath);
SetAppIconFromPath(path);
if (!Emu.BootGame(path))
{
LOG_ERROR(GENERAL, "PS3 executable not found in selected folder (%s)", path);
}
else
{
LOG_SUCCESS(LOADER, "Boot Game: boot done.");
const std::string serial = Emu.GetTitleID().empty() ? "" : "[" + Emu.GetTitleID() + "] ";
AddRecentAction(GUI::Recent_Game(qstr(Emu.GetBoot()), qstr(serial + Emu.GetTitle())));
m_gameListFrame->Refresh(true);
}
}
void main_window::InstallPkg(const QString& dropPath)
{
QString filePath = dropPath;
if (filePath.isEmpty())
{
QString path_last_PKG = guiSettings->GetValue(GUI::fd_install_pkg).toString();
filePath = QFileDialog::getOpenFileName(this, tr("Select PKG To Install"), path_last_PKG, tr("PKG files (*.pkg);;All files (*.*)"));
}
else
{
if (QMessageBox::question(this, tr("PKG Decrypter / Installer"), tr("Install package: %1?").arg(filePath),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
{
LOG_NOTICE(LOADER, "PKG: Cancelled installation from drop. File: %s", sstr(filePath));
return;
}
}
if (filePath == NULL)
{
return;
}
Emu.Stop();
guiSettings->SetValue(GUI::fd_install_pkg, QFileInfo(filePath).path());
const std::string fileName = sstr(QFileInfo(filePath).fileName());
const std::string path = sstr(filePath);
// Open PKG file
fs::file pkg_f(path);
if (!pkg_f || pkg_f.size() < 64)
{
LOG_ERROR(LOADER, "PKG: Failed to open %s", path);
return;
}
//Check header
u32 pkg_signature;
pkg_f.seek(0);
pkg_f.read(pkg_signature);
if (pkg_signature != "\x7FPKG"_u32)
{
LOG_ERROR(LOADER, "PKG: %s is not a pkg file", fileName);
return;
}
// Get title ID
std::vector<char> title_id(9);
pkg_f.seek(55);
pkg_f.read(title_id);
pkg_f.seek(0);
// Get full path
const auto& local_path = Emu.GetHddDir() + "game/" + std::string(std::begin(title_id), std::end(title_id));
if (!fs::create_dir(local_path))
{
if (fs::is_dir(local_path))
{
if (QMessageBox::question(this, tr("PKG Decrypter / Installer"), tr("Another installation found. Do you want to overwrite it?"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
{
LOG_ERROR(LOADER, "PKG: Cancelled installation to existing directory %s", local_path);
return;
}
}
else
{
LOG_ERROR(LOADER, "PKG: Could not create the installation directory %s", local_path);
return;
}
}
QProgressDialog pdlg(tr("Installing package ... please wait ..."), tr("Cancel"), 0, 1000, this);
pdlg.setWindowTitle(tr("RPCS3 Package Installer"));
pdlg.setWindowModality(Qt::WindowModal);
pdlg.setFixedSize(500, pdlg.height());
pdlg.show();
#ifdef _WIN32
QWinTaskbarButton *taskbar_button = new QWinTaskbarButton();
taskbar_button->setWindow(windowHandle());
QWinTaskbarProgress *taskbar_progress = taskbar_button->progress();
taskbar_progress->setRange(0, 1000);
taskbar_progress->setVisible(true);
#endif
// Synchronization variable
atomic_t<double> progress(0.);
{
// Run PKG unpacking asynchronously
scope_thread worker("PKG Installer", [&]
{
if (pkg_install(pkg_f, local_path + '/', progress, path))
{
progress = 1.;
return;
}
// TODO: Ask user to delete files on cancellation/failure?
progress = -1.;
});
// Wait for the completion
while (std::this_thread::sleep_for(5ms), std::abs(progress) < 1.)
{
if (pdlg.wasCanceled())
{
progress -= 1.;
#ifdef _WIN32
taskbar_progress->hide();
taskbar_button->~QWinTaskbarButton();
#endif
if (QMessageBox::question(this, tr("PKG Decrypter / Installer"), tr("Remove incomplete folder?"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes)
{
fs::remove_all(local_path);
m_gameListFrame->Refresh(true);
LOG_SUCCESS(LOADER, "PKG: removed incomplete installation in %s", local_path);
return;
}
break;
}
// Update progress window
pdlg.setValue(static_cast<int>(progress * pdlg.maximum()));
#ifdef _WIN32
taskbar_progress->setValue(static_cast<int>(progress * taskbar_progress->maximum()));
#endif
QCoreApplication::processEvents();
}
if (progress > 0.)
{
pdlg.setValue(pdlg.maximum());
#ifdef _WIN32
taskbar_progress->setValue(taskbar_progress->maximum());
#endif
std::this_thread::sleep_for(100ms);
}
}
if (progress >= 1.)
{
m_gameListFrame->Refresh(true);
LOG_SUCCESS(GENERAL, "Successfully installed %s.", fileName);
guiSettings->ShowInfoBox(GUI::ib_pkg_success, tr("Success!"), tr("Successfully installed software from package!"), this);
#ifdef _WIN32
taskbar_progress->hide();
taskbar_button->~QWinTaskbarButton();
#endif
}
}
void main_window::InstallPup(const QString& dropPath)
{
QString filePath = dropPath;
if (filePath.isEmpty())
{
QString path_last_PUP = guiSettings->GetValue(GUI::fd_install_pup).toString();
filePath = QFileDialog::getOpenFileName(this, tr("Select PS3UPDAT.PUP To Install"), path_last_PUP, tr("PS3 update file (PS3UPDAT.PUP)"));
}
else
{
if (QMessageBox::question(this, tr("RPCS3 Firmware Installer"), tr("Install firmware: %1?").arg(filePath),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
{
LOG_NOTICE(LOADER, "Firmware: Cancelled installation from drop. File: %s", sstr(filePath));
return;
}
}
if (filePath == NULL)
{
return;
}
Emu.Stop();
guiSettings->SetValue(GUI::fd_install_pup, QFileInfo(filePath).path());
const std::string path = sstr(filePath);
fs::file pup_f(path);
pup_object pup(pup_f);
if (!pup)
{
LOG_ERROR(GENERAL, "Error while installing firmware: PUP file is invalid.");
QMessageBox::critical(this, tr("Failure!"), tr("Error while installing firmware: PUP file is invalid."));
return;
}
fs::file update_files_f = pup.get_file(0x300);
tar_object update_files(update_files_f);
auto updatefilenames = update_files.get_filenames();
updatefilenames.erase(std::remove_if(
updatefilenames.begin(), updatefilenames.end(), [](std::string s) { return s.find("dev_flash_") == std::string::npos; }),
updatefilenames.end());
std::string version_string = pup.get_file(0x100).to_string();
version_string.erase(version_string.find('\n'));
const std::string cur_version = "4.81";
if (version_string < cur_version &&
QMessageBox::question(this, tr("RPCS3 Firmware Installer"), tr("Old firmware detected.\nThe newest firmware version is %1 and you are trying to install version %2\nContinue installation?").arg(QString::fromStdString(cur_version), QString::fromStdString(version_string)),
QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::No)
{
return;
}
QProgressDialog pdlg(tr("Installing firmware version %1\nPlease wait...").arg(QString::fromStdString(version_string)), tr("Cancel"), 0, static_cast<int>(updatefilenames.size()), this);
pdlg.setWindowTitle(tr("RPCS3 Firmware Installer"));
pdlg.setWindowModality(Qt::WindowModal);
pdlg.setFixedSize(500, pdlg.height());
pdlg.show();
#ifdef _WIN32
QWinTaskbarButton *taskbar_button = new QWinTaskbarButton();
taskbar_button->setWindow(windowHandle());
QWinTaskbarProgress *taskbar_progress = taskbar_button->progress();
taskbar_progress->setRange(0, static_cast<int>(updatefilenames.size()));
taskbar_progress->setVisible(true);
#endif
// Synchronization variable
atomic_t<int> progress(0);
{
// Run asynchronously
scope_thread worker("Firmware Installer", [&]
{
for (auto updatefilename : updatefilenames)
{
if (progress == -1) break;
fs::file updatefile = update_files.get_file(updatefilename);
SCEDecrypter self_dec(updatefile);
self_dec.LoadHeaders();
self_dec.LoadMetadata(SCEPKG_ERK, SCEPKG_RIV);
self_dec.DecryptData();
auto dev_flash_tar_f = self_dec.MakeFile();
if (dev_flash_tar_f.size() < 3)
{
LOG_ERROR(GENERAL, "Error while installing firmware: PUP contents are invalid.");
QMessageBox::critical(this, tr("Failure!"), tr("Error while installing firmware: PUP contents are invalid."));
progress = -1;
}
tar_object dev_flash_tar(dev_flash_tar_f[2]);
if (!dev_flash_tar.extract(fs::get_config_dir()))
{
LOG_ERROR(GENERAL, "Error while installing firmware: TAR contents are invalid.");
QMessageBox::critical(this, tr("Failure!"), tr("Error while installing firmware: TAR contents are invalid."));
progress = -1;
}
if (progress >= 0)
progress += 1;
}
});
// Wait for the completion
while (std::this_thread::sleep_for(5ms), std::abs(progress) < pdlg.maximum())
{
if (pdlg.wasCanceled())
{
progress = -1;
#ifdef _WIN32
taskbar_progress->hide();
taskbar_button->~QWinTaskbarButton();
#endif
break;
}
// Update progress window
pdlg.setValue(static_cast<int>(progress));
#ifdef _WIN32
taskbar_progress->setValue(static_cast<int>(progress));
#endif
QCoreApplication::processEvents();
}
update_files_f.close();
pup_f.close();
if (progress > 0)
{
pdlg.setValue(pdlg.maximum());
#ifdef _WIN32
taskbar_progress->setValue(taskbar_progress->maximum());
#endif
std::this_thread::sleep_for(100ms);
}
}
if (progress > 0)
{
LOG_SUCCESS(GENERAL, "Successfully installed PS3 firmware version %s.", version_string);
guiSettings->ShowInfoBox(GUI::ib_pup_success, tr("Success!"), tr("Successfully installed PS3 firmware and LLE Modules!"), this);
#ifdef _WIN32
taskbar_progress->hide();
taskbar_button->~QWinTaskbarButton();
#endif
}
}
// This is ugly, but PS3 headers shall not be included there.
extern void <API key>(u64 status, u64 param);
void main_window::<API key>()
{
QString path_last_SPRX = guiSettings->GetValue(GUI::fd_decrypt_sprx).toString();
QStringList modules = QFileDialog::getOpenFileNames(this, tr("Select SPRX files"), path_last_SPRX, tr("SPRX files (*.sprx)"));
if (modules.isEmpty())
{
return;
}
Emu.Stop();
guiSettings->SetValue(GUI::fd_decrypt_sprx, QFileInfo(modules.first()).path());
LOG_NOTICE(GENERAL, "Decrypting SPRX libraries...");
for (QString& module : modules)
{
std::string prx_path = sstr(module);
const std::string& prx_dir = fs::get_parent_dir(prx_path);
fs::file elf_file(prx_path);
if (elf_file && elf_file.size() >= 4 && elf_file.read<u32>() == "SCE\0"_u32)
{
const std::size_t prx_ext_pos = prx_path.find_last_of('.');
const std::string& prx_name = prx_path.substr(prx_dir.size());
elf_file = decrypt_self(std::move(elf_file));
prx_path.erase(prx_path.size() - 4, 1); // change *.sprx to *.prx
if (elf_file)
{
if (fs::file new_file{ prx_path, fs::rewrite })
{
new_file.write(elf_file.to_string());
LOG_SUCCESS(GENERAL, "Decrypted %s", prx_dir + prx_name);
}
else
{
LOG_ERROR(GENERAL, "Failed to create %s", prx_path);
}
}
else
{
LOG_ERROR(GENERAL, "Failed to decrypt %s", prx_dir + prx_name);
}
}
}
LOG_NOTICE(GENERAL, "Finished decrypting all SPRX libraries.");
}
/** Needed so that when a backup occurs of window state in guisettings, the state is current.
* Also, so that on close, the window state is preserved.
*/
void main_window::SaveWindowState()
{
// Save gui settings
guiSettings->SetValue(GUI::mw_geometry, saveGeometry());
guiSettings->SetValue(GUI::mw_windowState, saveState());
guiSettings->SetValue(GUI::mw_mwState, m_mw->saveState());
// Save column settings
m_gameListFrame->SaveSettings();
// Save splitter state
m_debuggerFrame->SaveSettings();
}
void main_window::RepaintToolBarIcons()
{
QColor newColor;
if (guiSettings->GetValue(GUI::m_enableUIColors).toBool())
{
newColor = guiSettings->GetValue(GUI::mw_toolIconColor).value<QColor>();
}
else
{
newColor = GUI::get_Label_Color("toolbar_icon_color");
}
auto icon = [&newColor](const QString& path)
{
return gui_settings::colorizedIcon(QIcon(path), GUI::mw_tool_icon_color, newColor);
};
m_icon_play = icon(":/Icons/play.png");
m_icon_pause = icon(":/Icons/pause.png");
m_icon_stop = icon(":/Icons/stop.png");
m_icon_restart = icon(":/Icons/restart.png");
<API key> = icon(":/Icons/fullscreen.png");
<API key> = icon(":/Icons/fullscreen_invert.png");
ui->toolbar_config ->setIcon(icon(":/Icons/configure.png"));
ui->toolbar_controls->setIcon(icon(":/Icons/controllers.png"));
ui->toolbar_disc ->setIcon(icon(":/Icons/disc.png"));
ui->toolbar_grid ->setIcon(icon(":/Icons/grid.png"));
ui->toolbar_list ->setIcon(icon(":/Icons/list.png"));
ui->toolbar_refresh ->setIcon(icon(":/Icons/refresh.png"));
ui->toolbar_snap ->setIcon(icon(":/Icons/screenshot.png"));
ui->toolbar_sort ->setIcon(icon(":/Icons/sort.png"));
ui->toolbar_stop ->setIcon(icon(":/Icons/stop.png"));
if (Emu.IsRunning())
{
ui->toolbar_start->setIcon(m_icon_pause);
}
else if (Emu.IsStopped() && !Emu.GetPath().empty())
{
ui->toolbar_start->setIcon(m_icon_restart);
}
else
{
ui->toolbar_start->setIcon(m_icon_play);
}
if (isFullScreen())
{
ui->toolbar_fullscreen->setIcon(<API key>);
}
else
{
ui->toolbar_fullscreen->setIcon(<API key>);
}
ui->sizeSlider->setStyleSheet(ui->sizeSlider->styleSheet().append("QSlider::handle:horizontal{ background: rgba(%1, %2, %3, %4); }")
.arg(newColor.red()).arg(newColor.green()).arg(newColor.blue()).arg(newColor.alpha()));
}
void main_window::OnEmuRun()
{
m_debuggerFrame->EnableButtons(true);
#ifdef _WIN32
m_thumb_playPause->setToolTip(tr("Pause emulation"));
m_thumb_playPause->setIcon(m_icon_thumb_pause);
#endif
ui->sysPauseAct->setText(tr("&Pause\tCtrl+P"));
ui->sysPauseAct->setIcon(m_icon_pause);
ui->toolbar_start->setIcon(m_icon_pause);
ui->toolbar_start->setToolTip(tr("Pause emulation"));
EnableMenus(true);
}
void main_window::OnEmuResume()
{
#ifdef _WIN32
m_thumb_playPause->setToolTip(tr("Pause emulation"));
m_thumb_playPause->setIcon(m_icon_thumb_pause);
#endif
ui->sysPauseAct->setText(tr("&Pause\tCtrl+P"));
ui->sysPauseAct->setIcon(m_icon_pause);
ui->toolbar_start->setIcon(m_icon_pause);
ui->toolbar_start->setToolTip(tr("Pause emulation"));
}
void main_window::OnEmuPause()
{
#ifdef _WIN32
m_thumb_playPause->setToolTip(tr("Resume emulation"));
m_thumb_playPause->setIcon(m_icon_thumb_play);
#endif
ui->sysPauseAct->setText(tr("&Resume\tCtrl+E"));
ui->sysPauseAct->setIcon(m_icon_play);
ui->toolbar_start->setIcon(m_icon_play);
ui->toolbar_start->setToolTip(tr("Resume emulation"));
}
void main_window::OnEmuStop()
{
m_debuggerFrame->EnableButtons(false);
m_debuggerFrame->ClearBreakpoints();
ui->sysPauseAct->setText(Emu.IsReady() ? tr("&Start\tCtrl+E") : tr("&Resume\tCtrl+E"));
ui->sysPauseAct->setIcon(m_icon_play);
#ifdef _WIN32
m_thumb_playPause->setToolTip(Emu.IsReady() ? tr("Start emulation") : tr("Resume emulation"));
m_thumb_playPause->setIcon(m_icon_thumb_play);
#endif
EnableMenus(false);
if (!Emu.GetPath().empty())
{
ui->toolbar_start->setEnabled(true);
ui->toolbar_start->setIcon(m_icon_restart);
ui->toolbar_start->setToolTip(tr("Restart emulation"));
ui->sysRebootAct->setEnabled(true);
#ifdef _WIN32
m_thumb_restart->setEnabled(true);
#endif
}
else
{
ui->toolbar_start->setIcon(m_icon_play);
ui->toolbar_start->setToolTip(Emu.IsReady() ? tr("Start emulation") : tr("Resume emulation"));
}
}
void main_window::OnEmuReady()
{
m_debuggerFrame->EnableButtons(true);
#ifdef _WIN32
m_thumb_playPause->setToolTip(Emu.IsReady() ? tr("Start emulation") : tr("Resume emulation"));
m_thumb_playPause->setIcon(m_icon_thumb_play);
#endif
ui->sysPauseAct->setText(Emu.IsReady() ? tr("&Start\tCtrl+E") : tr("&Resume\tCtrl+E"));
ui->sysPauseAct->setIcon(m_icon_play);
ui->toolbar_start->setIcon(m_icon_play);
ui->toolbar_start->setToolTip(Emu.IsReady() ? tr("Start emulation") : tr("Resume emulation"));
EnableMenus(true);
}
void main_window::EnableMenus(bool enabled)
{
// Thumbnail Buttons
#ifdef _WIN32
m_thumb_playPause->setEnabled(enabled);
m_thumb_stop->setEnabled(enabled);
m_thumb_restart->setEnabled(enabled);
#endif
// Toolbar
ui->toolbar_start->setEnabled(enabled);
ui->toolbar_stop->setEnabled(enabled);
// Emulation
ui->sysPauseAct->setEnabled(enabled);
ui->sysStopAct->setEnabled(enabled);
ui->sysRebootAct->setEnabled(enabled);
// PS3 Commands
ui->sysSendOpenMenuAct->setEnabled(enabled);
ui->sysSendExitAct->setEnabled(enabled);
// Tools
ui-><API key>->setEnabled(enabled);
ui-><API key>->setEnabled(enabled);
ui->toolsRsxDebuggerAct->setEnabled(enabled);
ui-><API key>->setEnabled(enabled);
}
void main_window::BootRecentAction(const QAction* act)
{
if (Emu.IsRunning())
{
return;
}
const QString pth = act->data().toString();
QString nam;
bool containsPath = false;
int idx = -1;
for (int i = 0; i < m_rg_entries.count(); i++)
{
if (m_rg_entries.at(i).first == pth)
{
idx = i;
containsPath = true;
nam = m_rg_entries.at(idx).second;
}
}
// path is invalid: remove action from list return
if ((containsPath && nam.isEmpty()) || (!QFileInfo(pth).isDir() && !QFileInfo(pth).isFile()))
{
if (containsPath)
{
// clear menu of actions
for (auto act : m_recentGameActs)
{
ui->bootRecentMenu->removeAction(act);
}
// remove action from list
m_rg_entries.removeAt(idx);
m_recentGameActs.removeAt(idx);
guiSettings->SetValue(GUI::rg_entries, guiSettings->List2Var(m_rg_entries));
LOG_ERROR(GENERAL, "Recent Game not valid, removed from Boot Recent list: %s", sstr(pth));
// refill menu with actions
for (int i = 0; i < m_recentGameActs.count(); i++)
{
m_recentGameActs[i]->setShortcut(tr("Ctrl+%1").arg(i + 1));
m_recentGameActs[i]->setToolTip(m_rg_entries.at(i).second);
ui->bootRecentMenu->addAction(m_recentGameActs[i]);
}
LOG_WARNING(GENERAL, "Boot Recent list refreshed");
return;
}
LOG_ERROR(GENERAL, "Path invalid and not in m_rg_paths: %s", sstr(pth));
return;
}
SetAppIconFromPath(sstr(pth));
Emu.Stop();
if (!Emu.BootGame(sstr(pth), true))
{
LOG_ERROR(LOADER, "Failed to boot %s", sstr(pth));
}
else
{
LOG_SUCCESS(LOADER, "Boot from Recent List: done");
AddRecentAction(GUI::Recent_Game(qstr(Emu.GetBoot()), nam));
m_gameListFrame->Refresh(true);
}
};
QAction* main_window::CreateRecentAction(const q_string_pair& entry, const uint& sc_idx)
{
// if path is not valid remove from list
if (entry.second.isEmpty() || (!QFileInfo(entry.first).isDir() && !QFileInfo(entry.first).isFile()))
{
if (m_rg_entries.contains(entry))
{
LOG_ERROR(GENERAL, "Recent Game not valid, removing from Boot Recent list: %s", sstr(entry.first));
int idx = m_rg_entries.indexOf(entry);
m_rg_entries.removeAt(idx);
guiSettings->SetValue(GUI::rg_entries, guiSettings->List2Var(m_rg_entries));
}
return nullptr;
}
// if name is a path get filename
QString shown_name = entry.second;
if (QFileInfo(entry.second).isFile())
{
shown_name = entry.second.section('/', -1);
}
// create new action
QAction* act = new QAction(shown_name, this);
act->setData(entry.first);
act->setToolTip(entry.second);
act->setShortcut(tr("Ctrl+%1").arg(sc_idx));
// truncate if too long
if (shown_name.length() > 60)
{
act->setText(shown_name.left(27) + "(....)" + shown_name.right(27));
}
// connect boot
connect(act, &QAction::triggered, [=]() {BootRecentAction(act); });
return act;
};
void main_window::AddRecentAction(const q_string_pair& entry)
{
// don't change list on freeze
if (ui->freezeRecentAct->isChecked())
{
return;
}
// create new action, return if not valid
QAction* act = CreateRecentAction(entry, 1);
if (!act)
{
return;
}
// clear menu of actions
for (auto act : m_recentGameActs)
{
ui->bootRecentMenu->removeAction(act);
}
// if path already exists, remove it in order to get it to beginning
if (m_rg_entries.contains(entry))
{
int idx = m_rg_entries.indexOf(entry);
m_rg_entries.removeAt(idx);
m_recentGameActs.removeAt(idx);
}
// remove oldest action at the end if needed
if (m_rg_entries.count() == 9)
{
m_rg_entries.removeLast();
m_recentGameActs.removeLast();
}
else if (m_rg_entries.count() > 9)
{
LOG_ERROR(LOADER, "Recent games entrylist too big");
}
if (m_rg_entries.count() < 9)
{
// add new action at the beginning
m_rg_entries.prepend(entry);
m_recentGameActs.prepend(act);
}
// refill menu with actions
for (int i = 0; i < m_recentGameActs.count(); i++)
{
m_recentGameActs[i]->setShortcut(tr("Ctrl+%1").arg(i+1));
m_recentGameActs[i]->setToolTip(m_rg_entries.at(i).second);
ui->bootRecentMenu->addAction(m_recentGameActs[i]);
}
guiSettings->SetValue(GUI::rg_entries, guiSettings->List2Var(m_rg_entries));
}
void main_window::RepaintGui()
{
m_gameListFrame->RepaintIcons(true);
m_gameListFrame->RepaintToolBarIcons();
RepaintToolbar();
RepaintToolBarIcons();
}
void main_window::RepaintToolbar()
{
if (guiSettings->GetValue(GUI::m_enableUIColors).toBool())
{
QColor tbc = guiSettings->GetValue(GUI::mw_toolBarColor).value<QColor>();
ui->toolBar->setStyleSheet(GUI::stylesheet + QString(
"QToolBar { background-color: rgba(%1, %2, %3, %4); }"
"QToolBar::separator {background-color: rgba(%5, %6, %7, %8); width: 1px; margin-top: 2px; margin-bottom: 2px;}"
"QSlider { background-color: rgba(%1, %2, %3, %4); }"
"QLineEdit { background-color: rgba(%1, %2, %3, %4); }")
.arg(tbc.red()).arg(tbc.green()).arg(tbc.blue()).arg(tbc.alpha())
.arg(tbc.red() - 20).arg(tbc.green() - 20).arg(tbc.blue() - 20).arg(tbc.alpha() - 20)
);
}
else
{
ui->toolBar->setStyleSheet(GUI::stylesheet);
}
}
void main_window::CreateActions()
{
ui->exitAct->setShortcuts(QKeySequence::Quit);
ui->toolbar_start->setEnabled(false);
ui->toolbar_stop->setEnabled(false);
<API key> = new QActionGroup(this);
<API key>->addAction(ui->showCatHDDGameAct);
<API key>->addAction(ui->showCatDiscGameAct);
<API key>->addAction(ui->showCatHomeAct);
<API key>->addAction(ui-><API key>);
<API key>->addAction(ui->showCatGameDataAct);
<API key>->addAction(ui->showCatUnknownAct);
<API key>->addAction(ui->showCatOtherAct);
<API key>->setExclusive(false);
m_iconSizeActGroup = new QActionGroup(this);
m_iconSizeActGroup->addAction(ui->setIconSizeTinyAct);
m_iconSizeActGroup->addAction(ui->setIconSizeSmallAct);
m_iconSizeActGroup->addAction(ui-><API key>);
m_iconSizeActGroup->addAction(ui->setIconSizeLargeAct);
m_listModeActGroup = new QActionGroup(this);
m_listModeActGroup->addAction(ui->setlistModeListAct);
m_listModeActGroup->addAction(ui->setlistModeGridAct);
}
void main_window::CreateConnects()
{
connect(ui->bootElfAct, &QAction::triggered, this, &main_window::BootElf);
connect(ui->bootGameAct, &QAction::triggered, this, &main_window::BootGame);
connect(ui->bootRecentMenu, &QMenu::aboutToShow, [=]
{
// Enable/Disable Recent Games List
const bool stopped = Emu.IsStopped();
for (auto act : ui->bootRecentMenu->actions())
{
if (act != ui->freezeRecentAct && act != ui->clearRecentAct)
{
act->setEnabled(stopped);
}
}
});
connect(ui->clearRecentAct, &QAction::triggered, [this]
{
if (ui->freezeRecentAct->isChecked()) { return; }
m_rg_entries.clear();
for (auto act : m_recentGameActs)
{
ui->bootRecentMenu->removeAction(act);
}
m_recentGameActs.clear();
guiSettings->SetValue(GUI::rg_entries, guiSettings->List2Var(q_pair_list()));
});
connect(ui->freezeRecentAct, &QAction::triggered, [=](bool checked)
{
guiSettings->SetValue(GUI::rg_freeze, checked);
});
connect(ui->bootInstallPkgAct, &QAction::triggered, [this] {InstallPkg(); });
connect(ui->bootInstallPupAct, &QAction::triggered, [this] {InstallPup(); });
connect(ui->exitAct, &QAction::triggered, this, &QWidget::close);
connect(ui->sysPauseAct, &QAction::triggered, Pause);
connect(ui->sysStopAct, &QAction::triggered, [=]() { Emu.Stop(); });
connect(ui->sysRebootAct, &QAction::triggered, [=]() { Emu.Stop(); Emu.Load(); });
connect(ui->sysSendOpenMenuAct, &QAction::triggered, [=]
{
<API key>(m_sys_menu_opened ? 0x0132 /* <API key> */ : 0x0131 /* <API key> */, 0);
m_sys_menu_opened = !m_sys_menu_opened;
ui->sysSendOpenMenuAct->setText(tr("Send &%0 system menu cmd").arg(m_sys_menu_opened ? tr("close") : tr("open")));
});
connect(ui->sysSendExitAct, &QAction::triggered, [=]
{
<API key>(0x0101 /* <API key> */, 0);
});
auto openSettings = [=](int tabIndex)
{
settings_dialog dlg(guiSettings, m_Render_Creator, tabIndex, this);
connect(&dlg, &settings_dialog::<API key>, this, &main_window::SaveWindowState);
connect(&dlg, &settings_dialog::<API key>, [=]() {<API key>(true); });
connect(&dlg, &settings_dialog::<API key>, this, &main_window::<API key>);
connect(&dlg, &settings_dialog::GuiRepaintRequest, this, &main_window::RepaintGui);
dlg.exec();
};
connect(ui->confCPUAct, &QAction::triggered, [=]() { openSettings(0); });
connect(ui->confGPUAct, &QAction::triggered, [=]() { openSettings(1); });
connect(ui->confAudioAct, &QAction::triggered, [=]() { openSettings(2); });
connect(ui->confIOAct, &QAction::triggered, [=]() { openSettings(3); });
connect(ui->confSystemAct, &QAction::triggered, [=]() { openSettings(4); });
connect(ui->confPadsAct, &QAction::triggered, this, [=]
{
<API key> dlg(this);
dlg.exec();
});
connect(ui-><API key>, &QAction::triggered, [=]
{
<API key> dlg(this);
dlg.exec();
});
connect(ui->confVFSDialogAct, &QAction::triggered, [=]
{
vfs_dialog dlg(this);
dlg.exec();
m_gameListFrame->Refresh(true); // dev-hdd0 may have changed. Refresh just in case.
});
connect(ui-><API key>, &QAction::triggered, [=]
{
save_manager_dialog* sdid = new save_manager_dialog();
sdid->show();
});
connect(ui->toolsCgDisasmAct, &QAction::triggered, [=]
{
cg_disasm_window* cgdw = new cg_disasm_window(guiSettings);
cgdw->show();
});
connect(ui-><API key>, &QAction::triggered, [=]
{
kernel_explorer* kernelExplorer = new kernel_explorer(this);
kernelExplorer->show();
});
connect(ui-><API key>, &QAction::triggered, [=]
{
memory_viewer_panel* mvp = new memory_viewer_panel(this);
mvp->show();
});
connect(ui->toolsRsxDebuggerAct, &QAction::triggered, [=]
{
rsx_debugger* rsx = new rsx_debugger(this);
rsx->show();
});
connect(ui-><API key>, &QAction::triggered, [=]
{
<API key>* mss = new <API key>(this);
mss->show();
});
connect(ui-><API key>, &QAction::triggered, this, &main_window::<API key>);
connect(ui->showDebuggerAct, &QAction::triggered, [=](bool checked)
{
checked ? m_debuggerFrame->show() : m_debuggerFrame->hide();
guiSettings->SetValue(GUI::mw_debugger, checked);
});
connect(ui->showLogAct, &QAction::triggered, [=](bool checked)
{
checked ? m_logFrame->show() : m_logFrame->hide();
guiSettings->SetValue(GUI::mw_logger, checked);
});
connect(ui->showGameListAct, &QAction::triggered, [=](bool checked)
{
checked ? m_gameListFrame->show() : m_gameListFrame->hide();
guiSettings->SetValue(GUI::mw_gamelist, checked);
});
connect(ui->showToolBarAct, &QAction::triggered, [=](bool checked)
{
ui->toolBar->setVisible(checked);
guiSettings->SetValue(GUI::mw_toolBarVisible, checked);
});
connect(ui->showGameToolBarAct, &QAction::triggered, [=](bool checked)
{
m_gameListFrame->SetToolBarVisible(checked);
});
connect(ui->refreshGameListAct, &QAction::triggered, [=]
{
m_gameListFrame->Refresh(true);
});
connect(<API key>, &QActionGroup::triggered, [=](QAction* act)
{
QStringList categories;
int id;
const bool& checked = act->isChecked();
if (act == ui->showCatHDDGameAct) categories += category::non_disc_games, id = Category::Non_Disc_Game;
else if (act == ui->showCatDiscGameAct) categories += category::disc_Game, id = Category::Disc_Game;
else if (act == ui->showCatHomeAct) categories += category::home, id = Category::Home;
else if (act == ui-><API key>) categories += category::media, id = Category::Media;
else if (act == ui->showCatGameDataAct) categories += category::data, id = Category::Data;
else if (act == ui->showCatUnknownAct) categories += category::unknown, id = Category::Unknown_Cat;
else if (act == ui->showCatOtherAct) categories += category::others, id = Category::Others;
else LOG_WARNING(GENERAL, "<API key>: category action not found");
m_gameListFrame->SetCategoryActIcon(<API key>->actions().indexOf(act), checked);
m_gameListFrame-><API key>(categories, checked);
guiSettings-><API key>(id, checked);
});
connect(ui->aboutAct, &QAction::triggered, [this]
{
about_dialog dlg(this);
dlg.exec();
});
connect(ui->aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt);
auto resizeIcons = [=](const int& index)
{
int val = ui->sizeSlider->value();
if (val != index)
{
ui->sizeSlider->setSliderPosition(index);
}
if (val != m_gameListFrame->GetSliderValue())
{
if (m_save_slider_pos)
{
m_save_slider_pos = false;
guiSettings->SetValue(GUI::gl_iconSize, index);
}
m_gameListFrame->ResizeIcons(index);
}
};
connect(m_iconSizeActGroup, &QActionGroup::triggered, [=](QAction* act)
{
int index;
if (act == ui->setIconSizeTinyAct) index = 0;
else if (act == ui->setIconSizeSmallAct) index = GUI::get_Index(GUI::gl_icon_size_small);
else if (act == ui-><API key>) index = GUI::get_Index(GUI::gl_icon_size_medium);
else index = GUI::gl_max_slider_pos;
resizeIcons(index);
});
connect (m_gameListFrame, &game_list_frame::<API key>, [=](const int& idx)
{
if (idx < GUI::get_Index((GUI::gl_icon_size_small + GUI::gl_icon_size_min) / 2)) ui->setIconSizeTinyAct->setChecked(true);
else if (idx < GUI::get_Index((GUI::gl_icon_size_medium + GUI::gl_icon_size_small) / 2)) ui->setIconSizeSmallAct->setChecked(true);
else if (idx < GUI::get_Index((GUI::gl_icon_size_max + GUI::gl_icon_size_medium) / 2)) ui-><API key>->setChecked(true);
else ui->setIconSizeLargeAct->setChecked(true);
resizeIcons(idx);
});
connect(m_gameListFrame, &game_list_frame::<API key>, [=](const bool& save)
{
Q_UNUSED(save);
m_save_slider_pos = true;
});
connect(m_gameListFrame, &game_list_frame::<API key>, [=](const bool& isList)
{
isList ? ui->setlistModeListAct->trigger() : ui->setlistModeGridAct->trigger();
});
connect(m_gameListFrame, &game_list_frame::<API key>, [=](const int& id)
{
<API key>->actions().at(id)->trigger();
});
connect(m_listModeActGroup, &QActionGroup::triggered, [=](QAction* act)
{
bool isList = act == ui->setlistModeListAct;
m_gameListFrame->SetListMode(isList);
<API key>->setEnabled(isList);
});
connect(ui->toolbar_disc, &QAction::triggered, this, &main_window::BootGame);
connect(ui->toolbar_refresh, &QAction::triggered, [=]() { m_gameListFrame->Refresh(true); });
connect(ui->toolbar_stop, &QAction::triggered, [=]() { Emu.Stop(); });
connect(ui->toolbar_start, &QAction::triggered, Pause);
connect(ui->toolbar_fullscreen, &QAction::triggered, [=]
{
if (isFullScreen())
{
showNormal();
ui->toolbar_fullscreen->setIcon(<API key>);
}
else
{
showFullScreen();
ui->toolbar_fullscreen->setIcon(<API key>);
}
});
connect(ui->toolbar_controls, &QAction::triggered, [=]() { <API key> dlg(this); dlg.exec(); });
connect(ui->toolbar_config, &QAction::triggered, [=]() { openSettings(0); });
connect(ui->toolbar_list, &QAction::triggered, [=]() { ui->setlistModeListAct->trigger(); });
connect(ui->toolbar_grid, &QAction::triggered, [=]() { ui->setlistModeGridAct->trigger(); });
connect(ui->sizeSlider, &QSlider::valueChanged, resizeIcons);
connect(ui->sizeSlider, &QSlider::sliderReleased, this, [&] { guiSettings->SetValue(GUI::gl_iconSize, ui->sizeSlider->value()); });
connect(ui->sizeSlider, &QSlider::actionTriggered, [&](int action)
{
if (action != QAbstractSlider::SliderNoAction && action != QAbstractSlider::SliderMove)
{ // we only want to save on mouseclicks or slider release (the other connect handles this)
m_save_slider_pos = true; // actionTriggered happens before the value was changed
}
});
connect(ui->mw_searchbar, &QLineEdit::textChanged, m_gameListFrame, &game_list_frame::SetSearchText);
}
void main_window::CreateDockWindows()
{
// new mainwindow widget because existing seems to be bugged for now
m_mw = new QMainWindow();
m_gameListFrame = new game_list_frame(guiSettings, m_Render_Creator, m_mw);
m_gameListFrame->setObjectName("gamelist");
m_debuggerFrame = new debugger_frame(guiSettings, m_mw);
m_debuggerFrame->setObjectName("debugger");
m_logFrame = new log_frame(guiSettings, m_mw);
m_logFrame->setObjectName("logger");
m_mw->addDockWidget(Qt::LeftDockWidgetArea, m_gameListFrame);
m_mw->addDockWidget(Qt::LeftDockWidgetArea, m_logFrame);
m_mw->addDockWidget(Qt::RightDockWidgetArea, m_debuggerFrame);
m_mw-><API key>(true);
setCentralWidget(m_mw);
connect(m_logFrame, &log_frame::LogFrameClosed, [=]()
{
if (ui->showLogAct->isChecked())
{
ui->showLogAct->setChecked(false);
guiSettings->SetValue(GUI::mw_logger, false);
}
});
connect(m_debuggerFrame, &debugger_frame::DebugFrameClosed, [=]()
{
if (ui->showDebuggerAct->isChecked())
{
ui->showDebuggerAct->setChecked(false);
guiSettings->SetValue(GUI::mw_debugger, false);
}
});
connect(m_gameListFrame, &game_list_frame::GameListFrameClosed, [=]()
{
if (ui->showGameListAct->isChecked())
{
ui->showGameListAct->setChecked(false);
guiSettings->SetValue(GUI::mw_gamelist, false);
}
});
connect(m_gameListFrame, &game_list_frame::RequestIconPathSet, this, &main_window::SetAppIconFromPath);
connect(m_gameListFrame, &game_list_frame::<API key>, this, &main_window::AddRecentAction);
connect(m_gameListFrame, &game_list_frame::<API key>, [this](const QStringList& paths)
{
for (const auto& path : paths)
{
InstallPkg(path);
}
});
connect(m_gameListFrame, &game_list_frame::<API key>, this, &main_window::InstallPup);
}
void main_window::<API key>(bool configureAll)
{
// Restore GUI state if needed. We need to if they exist.
QByteArray geometry = guiSettings->GetValue(GUI::mw_geometry).toByteArray();
if (geometry.isEmpty() == false)
{
restoreGeometry(geometry);
}
else
{ // By default, set the window to 70% of the screen and the debugger frame is hidden.
m_debuggerFrame->hide();
QSize defaultSize = QDesktopWidget().availableGeometry().size() * 0.7;
resize(defaultSize);
}
restoreState(guiSettings->GetValue(GUI::mw_windowState).toByteArray());
m_mw->restoreState(guiSettings->GetValue(GUI::mw_mwState).toByteArray());
ui->freezeRecentAct->setChecked(guiSettings->GetValue(GUI::rg_freeze).toBool());
m_rg_entries = guiSettings->Var2List(guiSettings->GetValue(GUI::rg_entries));
// clear recent games menu of actions
for (auto act : m_recentGameActs)
{
ui->bootRecentMenu->removeAction(act);
}
m_recentGameActs.clear();
// Fill the recent games menu
for (int i = 0; i < m_rg_entries.count(); i++)
{
// adjust old unformatted entries (avoid duplication)
m_rg_entries[i] = GUI::Recent_Game(m_rg_entries[i].first, m_rg_entries[i].second);
// create new action
QAction* act = CreateRecentAction(m_rg_entries[i], i + 1);
// add action to menu
if (act)
{
m_recentGameActs.append(act);
ui->bootRecentMenu->addAction(act);
}
else
{
i--; // list count is now an entry shorter so we have to repeat the same index in order to load all other entries
}
}
ui->showLogAct->setChecked(guiSettings->GetValue(GUI::mw_logger).toBool());
ui->showGameListAct->setChecked(guiSettings->GetValue(GUI::mw_gamelist).toBool());
ui->showDebuggerAct->setChecked(guiSettings->GetValue(GUI::mw_debugger).toBool());
ui->showToolBarAct->setChecked(guiSettings->GetValue(GUI::mw_toolBarVisible).toBool());
ui->showGameToolBarAct->setChecked(guiSettings->GetValue(GUI::gl_toolBarVisible).toBool());
m_debuggerFrame->setVisible(ui->showDebuggerAct->isChecked());
m_logFrame->setVisible(ui->showLogAct->isChecked());
m_gameListFrame->setVisible(ui->showGameListAct->isChecked());
m_gameListFrame->SetToolBarVisible(ui->showGameToolBarAct->isChecked());
ui->toolBar->setVisible(ui->showToolBarAct->isChecked());
RepaintToolbar();
ui->showCatHDDGameAct->setChecked(guiSettings-><API key>(Category::Non_Disc_Game));
ui->showCatDiscGameAct->setChecked(guiSettings-><API key>(Category::Disc_Game));
ui->showCatHomeAct->setChecked(guiSettings-><API key>(Category::Home));
ui-><API key>->setChecked(guiSettings-><API key>(Category::Media));
ui->showCatGameDataAct->setChecked(guiSettings-><API key>(Category::Data));
ui->showCatUnknownAct->setChecked(guiSettings-><API key>(Category::Unknown_Cat));
ui->showCatOtherAct->setChecked(guiSettings-><API key>(Category::Others));
int idx = guiSettings->GetValue(GUI::gl_iconSize).toInt();
int index = GUI::gl_max_slider_pos / 4;
if (idx < index) ui->setIconSizeTinyAct->setChecked(true);
else if (idx < index * 2) ui->setIconSizeSmallAct->setChecked(true);
else if (idx < index * 3) ui-><API key>->setChecked(true);
else ui->setIconSizeLargeAct->setChecked(true);
bool isListMode = guiSettings->GetValue(GUI::gl_listMode).toBool();
if (isListMode) ui->setlistModeListAct->setChecked(true);
else ui->setlistModeGridAct->setChecked(true);
<API key>->setEnabled(isListMode);
if (configureAll)
{
// Handle log settings
m_logFrame->LoadSettings();
// Gamelist
m_gameListFrame->LoadSettings();
}
}
void main_window::keyPressEvent(QKeyEvent *keyEvent)
{
if (((keyEvent->modifiers() & Qt::AltModifier) && keyEvent->key() == Qt::Key_Return) || (isFullScreen() && keyEvent->key() == Qt::Key_Escape))
{
ui->toolbar_fullscreen->trigger();
}
if (keyEvent->modifiers() & Qt::ControlModifier)
{
switch (keyEvent->key())
{
case Qt::Key_E: if (Emu.IsPaused()) Emu.Resume(); else if (Emu.IsReady()) Emu.Run(); return;
case Qt::Key_P: if (Emu.IsRunning()) Emu.Pause(); return;
case Qt::Key_S: if (!Emu.IsStopped()) Emu.Stop(); return;
case Qt::Key_R: if (!Emu.GetPath().empty()) { Emu.Stop(); Emu.Run(); } return;
}
}
}
void main_window::<API key>(QMouseEvent *event)
{
if (isFullScreen())
{
if (event->button() == Qt::LeftButton)
{
showNormal();
ui->toolbar_fullscreen->setIcon(<API key>);
}
}
}
/** Override the Qt close event to have the emulator stop and the application die. May add a warning dialog in future.
*/
void main_window::closeEvent(QCloseEvent* closeEvent)
{
Q_UNUSED(closeEvent);
// Cleanly stop the emulator.
Emu.Stop();
SaveWindowState();
// I need the gui settings to sync, and that means having the destructor called as guiSetting's parent is main_window.
setAttribute(Qt::WA_DeleteOnClose);
QMainWindow::close();
// It's possible to have other windows open, like games. So, force the application to die.
QApplication::quit();
}
|
<?php
// Show your sent gifts
<API key>(elgg_echo('gifts:menu'), 'gifts/' . <API key>()->username. '/index');
$title = elgg_echo('gifts:sent');
<API key>($title);
if (elgg_is_logged_in()) {
<API key>('title', [
'name' => 'sendgift',
'href' => "gifts/" . <API key>()->username . "/sendgift",
'text' => elgg_echo('gifts:sendgifts'),
'link_class' => 'elgg-button elgg-button-action',
]);
}
$content = elgg_list_entities([
'type' => 'object',
'subtype' => Gifts::SUBTYPE,
'owner_guid' => <API key>(),
'no_results' => elgg_echo('gifts:nogifts'),
]);
// Format page
$body = elgg_view_layout('content', [
'content' => $content,
'filter' => '',
'title' => $title,
]);
// Draw it
echo elgg_view_page($title, $body);
|
<?php
/**
* Checkout coupon form
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 1.6.4
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
global $woocommerce;
if ( ! WC()->cart->coupons_enabled() )
return;
$info_message = apply_filters( '<API key>', __( 'Have a coupon?', 'woocommerce' ) );
$info_message .= ' <a href="#" class="showcoupon">' . __( 'Click here to enter your code', 'woocommerce' ) . '</a>';
?>
<div class="box woocommerce-box border-box"> <?php echo $info_message;?>
<form class="checkout_coupon <API key>" method="post" style="display:none">
<p class="form-row form-row-first">
<input type="text" name="coupon_code" class="input-text" placeholder="<?php _e( 'Coupon code', 'woocommerce' ); ?>" id="coupon_code" value="" />
</p>
<p class="form-row form-row-last">
<input type="submit" class="button" name="apply_coupon" value="<?php _e( 'Apply Coupon', 'woocommerce' ); ?>" />
</p>
<div class="clear"></div>
</form>
</div>
|
# Mikrotik scripts
Here are specific instruction to scripts created for RouterOS platform and were tested across two sites, both running RouterOS of the same version.
## Prerequisites
- Configure site-to-site IPsec tunnel across both sites. Public IP is a must for both endpoints. This [webpage](http://wiki.mikrotik.com/wiki/Manual:IP/IPsec) is a good place to start. I've been using IPsec in ESP tunnel mode, but other modes should in theory work just fine.
- Set up account on dynamic DNS service provider. The scripts use [freedns.afraid.org](http://freedns.afraid.org/), but other services should work as well. You will just need to modify the scripts to work with different DNS service (make sure they have public API available).
## Description of scripts
The scripts want to access specified interfaces or rules directly on the router. Interfaces are matched using _interface-name_, but rules are represented on router just as entries with number. To identify the specific rule with highest confidence, script finds the match using comment on the rule. Therefore make sure the rules and interfaces have proper comment and put this exact comment into scripts.
mikrotik_dns_update.script
This script tracks assigned IP address on WAN interface of the router. It assumes that the interface has assigned public IP address directly from your ISP. If the ISP assigns new IP address, on next scheduled run will the script update the dynamic DNS service. This script makes the assigned IP available as a global variable available to the whole system and other scripts.
<API key>.script
This script tracks for changes of locally asigned IP address as well as IP change on remote IPsec endpoint. In either cases it will update IPsec policies, peer information and firewall rules.
<API key>.script
This script is not needed in pure IPsec setup. However it may be useful in cases, where there is another VPN on endpoint with dynamic IP. It is running on a client router and is tracking for endpoint IP changes.
## Setup
- Before you import the scripts, you should review them and modify to suit your needs. Albeit they are quite generic, some information should be updated. Put there your credentials to dynamic DNS service, domain names and DNS entry name for your sites. You should also configure, which router rules should be updated. You can find commented examples in the scripts.
- Import the scripts and configure Scheduler to run them periodically. Alternative is to set up a trigger which tracks reachability of given IP.
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_20) on Wed Aug 31 13:06:32 CEST 2011 -->
<TITLE>
Uses of Class com.algebraweb.editor.shared.exceptions.SqlErrorException
</TITLE>
<META NAME="date" CONTENT="2011-08-31">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.algebraweb.editor.shared.exceptions.SqlErrorException";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../com/algebraweb/editor/shared/exceptions/SqlErrorException.html" title="class in com.algebraweb.editor.shared.exceptions"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?com/algebraweb/editor/shared/exceptions//<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="SqlErrorException.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>com.algebraweb.editor.shared.exceptions.SqlErrorException</B></H2>
</CENTER>
No usage of com.algebraweb.editor.shared.exceptions.SqlErrorException
<P>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../com/algebraweb/editor/shared/exceptions/SqlErrorException.html" title="class in com.algebraweb.editor.shared.exceptions"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?com/algebraweb/editor/shared/exceptions//<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="SqlErrorException.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
</BODY>
</HTML>
|
<?php
namespace goztow\<API key>\event;
/**
* @ignore
*/
use Symfony\Component\EventDispatcher\<API key>;
/**
* Event listener
*/
class base_events implements <API key>
{
static public function getSubscribedEvents()
{
return array(
'core.<API key>' => 'edit_topicreview',
);
}
/* @var \phpbb\template\template */
protected $template;
/**
* Constructor
*
* @param \phpbb\controller\helper $helper Controller helper object
* @param \phpbb\template\template $template Template object
*/
public function __construct(\phpbb\template\template $template)
{
$this->template = $template;
}
public function edit_topicreview($event)
{
if ($event['mode'] == 'edit' && topic_review($event['topic_id'], $event['forum_id']))
{
$this->template->assign_var('S_DISPLAY_REVIEW', true);
}
}
}
|
<?php
/**
* Custom template tags for this theme
*
* Eventually, some of the functionality here could be replaced by core features.
*
* @package <API key>
*/
if ( ! function_exists( '<API key>' ) ) :
/**
* Prints HTML with meta information for the current post-date/time and author.
*/
function <API key>() {
$time_string = '<time class="entry-date published updated" datetime="%1$s">%2$s</time>';
if ( get_the_time( 'U' ) !== <API key>( 'U' ) ) {
$time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time><time class="updated" datetime="%3$s">%4$s</time>';
}
$time_string = sprintf( $time_string,
esc_attr( get_the_date( 'c' ) ),
esc_html( get_the_date() ),
esc_attr( <API key>( 'c' ) ),
esc_html( <API key>() )
);
$posted_on = sprintf(
/* translators: %s: post date. */
esc_html_x( 'Posted on %s', 'post date', '<API key>' ),
'<a href="' . esc_url( get_permalink() ) . '" rel="bookmark">' . $time_string . '</a>'
);
$byline = sprintf(
/* translators: %s: post author. */
esc_html_x( 'by %s', 'post author', '<API key>' ),
'<span class="author vcard"><a class="url fn n" href="' . esc_url( <API key>( get_the_author_meta( 'ID' ) ) ) . '">' . esc_html( get_the_author() ) . '</a></span>'
);
echo '<span class="posted-on">' . $posted_on . '</span><span class="byline"> ' . $byline . '</span>'; // WPCS: XSS OK.
}
endif;
if ( ! function_exists( '<API key>' ) ) :
/**
* Prints HTML with meta information for the categories, tags and comments.
*/
function <API key>() {
// Hide category and tag text for pages.
if ( 'post' === get_post_type() ) {
/* translators: used between list items, there is a space after the comma */
$categories_list = <API key>( esc_html__( ', ', '<API key>' ) );
if ( $categories_list ) {
/* translators: 1: list of categories. */
printf( '<span class="cat-links">' . esc_html__( 'Posted in %1$s', '<API key>' ) . '</span>', $categories_list ); // WPCS: XSS OK.
}
/* translators: used between list items, there is a space after the comma */
$tags_list = get_the_tag_list( '', esc_html_x( ', ', 'list item separator', '<API key>' ) );
if ( $tags_list ) {
/* translators: 1: list of tags. */
printf( '<span class="tags-links">' . esc_html__( 'Tagged %1$s', '<API key>' ) . '</span>', $tags_list ); // WPCS: XSS OK.
}
}
if ( ! is_single() && ! <API key>() && ( comments_open() || get_comments_number() ) ) {
echo '<span class="comments-link">';
comments_popup_link(
sprintf(
wp_kses(
/* translators: %s: post title */
__( 'Leave a Comment<span class="screen-reader-text"> on %s</span>', '<API key>' ),
array(
'span' => array(
'class' => array(),
),
)
),
get_the_title()
)
);
echo '</span>';
}
edit_post_link(
sprintf(
wp_kses(
/* translators: %s: Name of current post. Only visible to screen readers */
__( 'Edit <span class="screen-reader-text">%s</span>', '<API key>' ),
array(
'span' => array(
'class' => array(),
),
)
),
get_the_title()
),
'<span class="edit-link">',
'</span>'
);
}
endif;
|
package uq.androidhack.flashspeak;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
import uq.androidhack.flashspeak.interfaces.TargetFileListener;
import uq.androidhack.flashspeak.interfaces.TrialFileListener;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link <API key>.<API key>} interface
* to handle interaction events.
* Use the {@link <API key>#newInstance} factory method to
* create an instance of this fragment.
*/
public class <API key> extends Fragment implements TargetFileListener,TrialFileListener{
private <API key> mListener;
//Here is your URL defined
String url = "http://vprbbc.streamguys.net/vprbbc24.mp3";
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment <API key>.
*/
public static <API key> newInstance() {
<API key> fragment = new <API key>();
Bundle args = new Bundle();
//args.putString(ARG_PARAM1, param1);
//args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public <API key>() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.<API key>, container, false);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (<API key>) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement <API key>");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onFileChange(String uri) {
File file = new File (uri);
ImageView <API key> = (ImageView)getView().findViewById(R.id.<API key>);
<API key>.setImageDrawable(Drawable.createFromPath(file.getAbsolutePath()));
}
@Override
public void onRecording(URI uri) {
ImageView <API key> = (ImageView)getView().findViewById(R.id.<API key>);
<API key>.setImageResource(android.R.color.transparent);
}
@Override
public void onFinishProcessing(String b) {
Log.i("VISUALIZER", "in HERE!");
ImageView <API key> = (ImageView)getView().findViewById(R.id.<API key>);
//<API key>.setImageURI(new URI(b));
new DownloadImageTask(<API key>).execute(b);
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
public interface <API key> {
public void <API key>(Bitmap uri);
}
}
|
using System;
using System.IO;
static class App{
static void PrintRunningGC(int n){
Console.WriteLine("Running GC for generation " + n);
GC.Collect(n);
}
public static void Main(){
FileStream fs = new FileStream("out.txt", FileMode.Create);
// Wait for user to hit <Enter>
Console.WriteLine("Wait for user to hit <Enter>");
Console.ReadLine();
PrintRunningGC(0);
Console.WriteLine("Wait for user to hit <Enter>");
Console.ReadLine();
}
}
|
package jrpsoft;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Ellipse2D;
import java.util.Random;
public class Fantasma extends Actor {
protected static final int FANTASMA_SPEED = 1;
public boolean up, down, right, left;
static Boolean[] dir = new Boolean[4];
int avazarA = 0;
Random random;
public Fantasma(Point puntoIncio, Color colorPrincipal) {
super(puntoIncio, colorPrincipal);
random = new Random();
}
public Point getPoint() {
return p;
}
public void paint(Graphics2D g2) {
g2.setColor(color);
Point pixelPoint = Director.getPxOfCell(p);
Ellipse2D fantasma = new Ellipse2D.Float(pixelPoint.x, pixelPoint.y,
diametro, diametro);
g2.fill(fantasma);
g2.fill(new Ellipse2D.Float(pixelPoint.x - 1, pixelPoint.y + 12, diametro / 2, diametro / 2));
g2.fill(new Ellipse2D.Float(pixelPoint.x + 5, pixelPoint.y + 12, diametro / 2, diametro / 2));
g2.fill(new Ellipse2D.Float(pixelPoint.x + 11, pixelPoint.y + 12, diametro / 2, diametro / 2));
}
public void mover(Pacman pacman, Tablero tablero) {
/*
* System.out.println("ee "+(random.nextInt(5)));
* if(random.nextInt(5)==0){ avanzar((random.nextInt(4)+1),tablero); }
*/
// avazarA=movAleatorio(tablero);
//System.err.println(p);
// avazarA=0;
Astar.getAstar().getPath(p, pacman.p);
Point nextPoint=Astar.getAstar().getNextPoint();
avanzar(getDirToPoint(nextPoint), tablero);
}
/*@SuppressWarnings("unused")
private int movAleatorio(Tablero tablero) {
Point aux = (Point) p.clone();
int randDir = 0;
do {
aux = reverseTranslateDir(aux, randDir);
randDir = random.nextInt(4) + 1;
translateDir(aux, randDir);
// System.out.print("\nwhiling"+randDir+" px:"+aux.x+" py:"+aux.y);
} while (!tablero.isWalkable(aux));
return randDir;
}*/
private void avanzar(int dir, Tablero tablero) {
p=translateDir(p,dir);
/*Point anterior = (Point) p.clone();
translateDir(p, dir);
if (!tablero.isWalkable(p)) {
p = anterior;
}*/
}
public Point translateDir(Point p, int dir) {
switch (dir) {
case DUP:
p.y += UP;
break;
case DDOWN:
p.y += DOWN;
break;
case DLEFT:
p.x += LEFT;
break;
case DRIGHT:
p.x += RIGHT;
break;
default:
break;
}
return p;
}
/*
public Point reverseTranslateDir(Point p, int dir) {
switch (dir) {
case DUP:
p.y -= UP;
break;
case DDOWN:
p.y -= DOWN;
break;
case DLEFT:
p.x -= LEFT;
break;
case DRIGHT:
p.x -= RIGHT;
break;
default:
break;
}
return p;
}
*/
}
|
ALTER TABLE `characters` ADD `i_equip_s` INT NOT NULL DEFAULT 24 AFTER `mesos`;
ALTER TABLE `characters` ADD `i_use_s` INT NOT NULL DEFAULT 24 AFTER `i_equip_s`;
ALTER TABLE `characters` ADD `i_setup_s` INT NOT NULL DEFAULT 24 AFTER `i_use_s`;
ALTER TABLE `characters` ADD `i_etc_s` INT NOT NULL DEFAULT 24 AFTER `i_setup_s`;
ALTER TABLE `characters` ADD `i_cash_s` INT NOT NULL DEFAULT 48 AFTER `i_etc_s`;
|
#include <QtGui>
#include <QtWidgets>
#include <QtNetwork>
#include <iostream>
// for the explanation of the trick, check out:
#define AVG(a,b) ( ((((a)^(b)) & 0xfefefefeUL) >> 1) + ((a)&(b)) )
QImage halfSized(const QImage &source)
{
QImage dest(source.size() * 0.5, QImage::<API key>);
const quint32 *src = reinterpret_cast<const quint32*>(source.bits());
int sx = source.bytesPerLine() >> 2;
int sx2 = sx << 1;
quint32 *dst = reinterpret_cast<quint32*>(dest.bits());
int dx = dest.bytesPerLine() >> 2;
int ww = dest.width();
int hh = dest.height();
for (int y = hh; y; --y, dst += dx, src += sx2) {
const quint32 *p1 = src;
const quint32 *p2 = src + sx;
quint32 *q = dst;
for (int x = ww; x; --x, q++, p1 += 2, p2 += 2)
* q = AVG(AVG(p1[0], p1[1]), AVG(p2[0], p2[1]));
}
return dest;
}
class HalfScaler: public QWidget
{
Q_OBJECT
private:
int m_method;
<API key> m_manager;
QImage m_fastScaled;
QImage m_smoothScaled;
QImage m_optimizedScaled;
public:
HalfScaler(): QWidget(), m_method(0) {
setAcceptDrops(true);
connect(&m_manager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(handleNetworkData(QNetworkReply*)));
setWindowTitle("Drag and drop an image here!");
resize(512, 256);
}
void loadImage(const QImage &image) {
QImage img = image.convertToFormat(QImage::<API key>);
if (img.isNull()) {
resize(512, 256);
setWindowTitle("Can't load the image. Please drag and drop an new image.");
} else {
// we crop the image so that the width and height are even
int ww = img.width() >> 1;
int hh = img.height() >> 1;
img = img.copy(0, 0, ww << 1, hh << 1);
m_fastScaled = img.scaled(ww, hh, Qt::IgnoreAspectRatio, Qt::FastTransformation);
m_smoothScaled = img.scaled(ww, hh, Qt::IgnoreAspectRatio, Qt::<API key>);
m_optimizedScaled = halfSized(img);
resize(20 + ww * 2 + 50, hh * 2 + 30 + 2 * 40);
}
update();
}
public slots:
void handleNetworkData(QNetworkReply *networkReply) {
m_fastScaled = QImage();
m_smoothScaled = QImage();
m_optimizedScaled = QImage();
QUrl url = networkReply->url();
if (networkReply->error()) {
setWindowTitle(QString("Can't download %1: %2").arg(url.toString()).arg(networkReply->errorString()));
} else {
QImage image;
image.load(networkReply, 0);
QString fileName = QFileInfo(url.path()).fileName();
setWindowTitle(QString("%1 - press a key to switch the scaling method").arg(fileName));
loadImage(image);
}
networkReply->deleteLater();
}
protected:
void dragEnterEvent(QDragEnterEvent *event) {
if (event->mimeData()->hasFormat("text/uri-list"))
event-><API key>();
}
void dropEvent(QDropEvent *event) {
QList<QUrl> urls = event->mimeData()->urls();
if (urls.count()) {
QUrl url = urls[0];
if (event->mimeData()->hasImage()) {
QImage img = qvariant_cast<QImage>(event->mimeData()->imageData());
QString fileName = QFileInfo(url.path()).fileName();
setWindowTitle(QString("%1 - press a key to switch the scaling method").arg(fileName));
loadImage(img);
} else {
m_manager.get(QNetworkRequest(url));
setWindowTitle(QString("Loading %1...").arg(url.toString()));
}
event-><API key>();
}
}
void keyPressEvent(QKeyEvent*) {
m_method = (m_method + 1) % 3;
update();
}
void paintEvent(QPaintEvent*) {
if (m_fastScaled.isNull())
return;
int w = m_fastScaled.width();
int h = m_optimizedScaled.height();
QPainter painter;
painter.begin(this);
// top left image: fast
painter.translate(10, 40);
painter.setPen(Qt::black);
painter.drawText(0, -40, w, 40, Qt::AlignCenter, "Qt::FastTransformation");
if (m_method == 0) {
painter.setPen(QPen(Qt::red, 2));
painter.drawRect(-2, -2, w + 4, h + 4);
painter.drawLine(w + 2, h + 2, w + 50 - 10, h + 50 - 10);
}
painter.drawImage(0, 0, m_fastScaled);
// top right image: smooth
painter.translate(w + 50, 0);
painter.setPen(Qt::black);
painter.drawText(0, -40, w, 40, Qt::AlignCenter, "Qt::<API key>");
if (m_method == 1) {
painter.setPen(QPen(Qt::red, 2));
painter.drawRect(-2, -2, w + 4, h + 4);
painter.drawLine(w / 2, h + 2, w / 2, h + 50 - 10);
}
painter.drawImage(0, 0, m_smoothScaled);
// bottom left image: optimized
painter.translate(-w - 50, h + 50);
painter.setPen(Qt::black);
painter.drawText(0, -40, w, 40, Qt::AlignCenter, "Optimized");
if (m_method == 2) {
painter.setPen(QPen(Qt::red, 2));
painter.drawRect(-2, -2, w + 4, h + 4);
painter.drawLine(w + 2, h / 2, w + 50 - 10, h / 2);
}
painter.drawImage(0, 0, m_optimizedScaled);
// bottom right image: chosen by the user
QImage img = (m_method == 0) ? m_fastScaled : (m_method == 1) ? m_smoothScaled : m_optimizedScaled;
painter.translate(w + 50, 0);
painter.drawImage(0, 0, img);
painter.end();
}
};
#include "halfscale.moc"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
HalfScaler widget;
widget.show();
return app.exec();
}
|
package freenet.clients.http;
/import org.tanukisoftware.wrapper.WrapperManager;
import freenet.client.filter.HTMLFilter;
import freenet.client.filter.<API key>;
import freenet.clients.http.<API key>.REFILTER_POLICY;
import freenet.clients.http.PageMaker.THEME;
import freenet.clients.http.bookmark.BookmarkManager;
import freenet.clients.http.updateableelements.PushDataManager;
import freenet.config.<API key>;
import freenet.config.<API key>;
import freenet.config.<API key>;
import freenet.config.SubConfig;
import freenet.crypt.SSL;
import freenet.io.AllowedHosts;
import freenet.io.NetworkInterface;
import freenet.io.SSLNetworkInterface;
import freenet.keys.FreenetURI;
import freenet.l10n.NodeL10n;
import freenet.node.Node;
import freenet.node.NodeClientCore;
import freenet.node.PrioRunnable;
import freenet.node.<API key>;
import freenet.node.SecurityLevels.<API key>;
import freenet.node.SecurityLevels.<API key>;
import freenet.node.useralerts.UserAlertManager;
import freenet.pluginmanager.FredPluginL10n;
import freenet.support.*;
import freenet.support.Logger.LogLevel;
import freenet.support.api.*;
import freenet.support.io.ArrayBucketFactory;
import freenet.support.io.NativeThread;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Random;
/**
* The Toadlet (HTTP) Server
*
* Provide a HTTP server for FProxy
*/
public final class SimpleToadletServer implements ToadletContainer, Runnable, <API key> {
/** List of urlPrefix / Toadlet */
private final LinkedList<ToadletElement> toadlets;
private static class ToadletElement {
public ToadletElement(Toadlet t2, String urlPrefix, String menu, String name) {
t = t2;
prefix = urlPrefix;
this.menu = menu;
this.name = name;
}
Toadlet t;
String prefix;
String menu;
String name;
}
// Socket / Binding
private final int port;
private String bindTo;
private String allowedHosts;
private NetworkInterface networkInterface;
private boolean ssl = false;
public static final int DEFAULT_FPROXY_PORT = 8888;
// ACL
private final AllowedHosts allowedFullAccess;
private boolean publicGatewayMode;
private final boolean <API key>;
// Theme
private THEME cssTheme;
private File cssOverride;
private boolean sendAllThemes;
private boolean advancedModeEnabled;
private final PageMaker pageMaker;
// Control
private Thread myThread;
private final Executor executor;
private final Random random;
private BucketFactory bf;
private volatile NodeClientCore core;
// HTTP Option
private boolean doRobots;
private boolean <API key>;
private boolean <API key>;
private boolean enableActivelinks;
private boolean <API key>;
// Something does not really belongs to here
volatile static boolean <API key>; // move to QueueToadlet ?
volatile static boolean noConfirmPanic;
public BookmarkManager bookmarkManager; // move to WelcomeToadlet / <API key> ?
private volatile boolean <API key>; // ugh?
private volatile boolean <API key>; // ugh?
private volatile boolean <API key>; // hmmm..
private volatile boolean disableProgressPage;
private int <API key>;
private int fproxyConnections;
private boolean finishedStartup;
/** The PushDataManager handles all the pushing tasks*/
public PushDataManager pushDataManager;
/** The <API key> handles interval pushing*/
public <API key> intervalPushManager;
private static volatile boolean logMINOR;
static {
Logger.<API key>(new <API key>(){
@Override
public void shouldUpdate(){
logMINOR = Logger.shouldLog(LogLevel.MINOR, this);
}
});
}
// Config Callbacks
private class FProxySSLCallback extends BooleanCallback {
@Override
public Boolean get() {
return ssl;
}
@Override
public void set(Boolean val) throws <API key> {
if (get().equals(val))
return;
if(!SSL.available()) {
throw new <API key>("Enable SSL support before use ssl with Fproxy");
}
ssl = val;
throw new <API key>("Cannot change SSL on the fly, please restart freenet");
}
@Override
public boolean isReadOnly() {
return true;
}
}
private static class <API key> extends LongCallback {
@Override
public Long get() {
return FProxyToadlet.<API key>;
}
@Override
public void set(Long val) throws <API key> {
if (get().equals(val))
return;
FProxyToadlet.<API key> = val;
}
}
private static class <API key> extends LongCallback {
@Override
public Long get() {
return FProxyToadlet.<API key>;
}
@Override
public void set(Long val) throws <API key> {
if (get().equals(val))
return;
FProxyToadlet.<API key> = val;
}
}
private class FProxyPortCallback extends IntCallback {
@Override
public Integer get() {
return port;
}
@Override
public void set(Integer newPort) throws <API key> {
if(port != newPort) {
throw new <API key>("Port cannot change on the fly");
}
}
}
private class <API key> extends StringCallback {
@Override
public String get() {
return bindTo;
}
@Override
public void set(String bindTo) throws <API key> {
String oldValue = get();
if(!bindTo.equals(oldValue)) {
String[] failedAddresses = networkInterface.setBindTo(bindTo, false);
if(failedAddresses == null) {
SimpleToadletServer.this.bindTo = bindTo;
} else {
// This is an advanced option for reasons of reducing clutter,
// but it is expected to be used by regular users, not devs.
// So we translate the error messages.
networkInterface.setBindTo(oldValue, false);
throw new <API key>(l10n("<API key>", "failedInterfaces", Arrays.toString(failedAddresses)));
}
}
}
}
private class <API key> extends StringCallback {
@Override
public String get() {
return networkInterface.getAllowedHosts();
}
@Override
public void set(String allowedHosts) throws <API key> {
if (!allowedHosts.equals(get())) {
try {
networkInterface.setAllowedHosts(allowedHosts);
} catch(<API key> e) {
throw new <API key>(e);
}
}
}
}
private class <API key> extends StringCallback implements <API key> {
@Override
public String get() {
return cssTheme.code;
}
@Override
public void set(String CSSName) throws <API key> {
if((CSSName.indexOf(':') != -1) || (CSSName.indexOf('/') != -1))
throw new <API key>(l10n("illegalCSSName"));
cssTheme = THEME.themeFromName(CSSName);
pageMaker.setTheme(cssTheme);
NodeClientCore core = SimpleToadletServer.this.core;
if (core.node.pluginManager != null)
core.node.pluginManager.setFProxyTheme(cssTheme);
}
@Override
public String[] getPossibleValues() {
return THEME.possibleValues;
}
}
private class <API key> extends StringCallback {
@Override
public String get() {
return (cssOverride == null ? "" : cssOverride.toString());
}
@Override
public void set(String val) throws <API key> {
NodeClientCore core = SimpleToadletServer.this.core;
if(core == null) return;
if(val.equals(get()) || val.equals(""))
cssOverride = null;
else {
File tmp = new File(val.trim());
if(!core.allowUploadFrom(tmp))
throw new <API key>(l10n("<API key>", "filename", tmp.toString()));
else if(!tmp.canRead() || !tmp.isFile())
throw new <API key>(l10n("cssOverrideCantRead", "filename", tmp.toString()));
File parent = tmp.getParentFile();
// Basic sanity check.
// Prevents user from specifying root dir.
// They can still shoot themselves in the foot, but only when developing themes/using custom themes.
// Because of the .. check above, any malicious thing cannot break out of the dir anyway.
if(parent.getParentFile() == null)
throw new <API key>(l10n("<API key>", "filename", parent.toString()));
cssOverride = tmp;
}
if(cssOverride == null)
pageMaker.setOverride(null);
else {
pageMaker.setOverride(StaticToadlet.OVERRIDE_URL + cssOverride.getName());
}
}
}
private class <API key> extends BooleanCallback {
@Override
public Boolean get() {
synchronized(SimpleToadletServer.this) {
return myThread != null;
}
}
@Override
public void set(Boolean val) throws <API key> {
if (get().equals(val))
return;
synchronized(SimpleToadletServer.this) {
if(val) {
// Start it
myThread = new Thread(SimpleToadletServer.this, "SimpleToadletServer");
} else {
myThread.interrupt();
myThread = null;
SimpleToadletServer.this.notifyAll();
return;
}
}
createFproxy();
myThread.setDaemon(true);
myThread.start();
}
}
private static class <API key> extends BooleanCallback {
private final SimpleToadletServer ts;
<API key>(SimpleToadletServer ts){
this.ts = ts;
}
@Override
public Boolean get() {
return ts.<API key>();
}
@Override
public void set(Boolean val) throws <API key> {
ts.setAdvancedMode(val);
}
}
private static class <API key> extends BooleanCallback {
private final SimpleToadletServer ts;
<API key>(SimpleToadletServer ts){
this.ts = ts;
}
@Override
public Boolean get() {
return ts.<API key>();
}
@Override
public void set(Boolean val) throws <API key> {
if (get().equals(val))
return;
ts.<API key>(val);
}
}
private static class <API key> extends BooleanCallback{
private final SimpleToadletServer ts;
<API key>(SimpleToadletServer ts){
this.ts=ts;
}
@Override
public Boolean get() {
return ts.<API key>();
}
@Override
public void set(Boolean val) throws <API key>, <API key> {
if (get().equals(val))
return;
ts.<API key>(val);
}
}
private boolean haveCalledFProxy = false;
// FIXME factor this out to a global helper class somehow?
private class ReFilterCallback extends StringCallback implements <API key> {
@Override
public String[] getPossibleValues() {
REFILTER_POLICY[] possible = REFILTER_POLICY.values();
String[] ret = new String[possible.length];
for(int i=0;i<possible.length;i++)
ret[i] = possible[i].name();
return ret;
}
@Override
public String get() {
return refilterPolicy.name();
}
@Override
public void set(String val) throws <API key>,
<API key> {
refilterPolicy = REFILTER_POLICY.valueOf(val);
}
};
public void createFproxy() {
NodeClientCore core = this.core;
Node node = core.node;
synchronized(this) {
if(haveCalledFProxy) return;
haveCalledFProxy = true;
}
pushDataManager=new PushDataManager(getTicker());
intervalPushManager=new <API key>(getTicker(), pushDataManager);
bookmarkManager = new BookmarkManager(core, publicGatewayMode());
try {
FProxyToadlet.<API key>(core, node, node.config, this);
} catch (IOException e) {
Logger.error(this, "Could not start fproxy: "+e, e);
System.err.println("Could not start fproxy:");
e.printStackTrace();
}
}
public void setCore(NodeClientCore core) {
this.core = core;
}
/**
* Create a SimpleToadletServer, using the settings from the SubConfig (the fproxy.*
* config).
*/
public SimpleToadletServer(SubConfig fproxyConfig, BucketFactory bucketFactory, Executor executor, Node node) throws IOException, <API key> {
this.executor = executor;
this.core = null; // setCore() will be called later.
this.random = new Random();
int configItemOrder = 0;
fproxyConfig.register("enabled", true, configItemOrder++, true, true, "SimpleToadletServer.enabled", "SimpleToadletServer.enabledLong",
new <API key>());
boolean enabled = fproxyConfig.getBoolean("enabled");
fproxyConfig.register("ssl", false, configItemOrder++, true, true, "SimpleToadletServer.ssl", "SimpleToadletServer.sslLong",
new FProxySSLCallback());
fproxyConfig.register("port", DEFAULT_FPROXY_PORT, configItemOrder++, true, true, "SimpleToadletServer.port", "SimpleToadletServer.portLong",
new FProxyPortCallback(), false);
fproxyConfig.register("bindTo", NetworkInterface.DEFAULT_BIND_TO, configItemOrder++, true, true, "SimpleToadletServer.bindTo", "SimpleToadletServer.bindToLong",
new <API key>());
fproxyConfig.register("css", "clean-dropdown", configItemOrder++, false, false, "SimpleToadletServer.cssName", "SimpleToadletServer.cssNameLong",
new <API key>());
fproxyConfig.register("CSSOverride", "", configItemOrder++, true, false, "SimpleToadletServer.cssOverride", "SimpleToadletServer.cssOverrideLong",
new <API key>());
fproxyConfig.register("sendAllThemes", false, configItemOrder++, true, false, "SimpleToadletServer.sendAllThemes", "SimpleToadletServer.sendAllThemesLong",
new BooleanCallback() {
@Override
public Boolean get() {
return sendAllThemes;
}
@Override
public void set(Boolean val) throws <API key>, <API key> {
sendAllThemes = val;
}
});
sendAllThemes = fproxyConfig.getBoolean("sendAllThemes");
fproxyConfig.register("advancedModeEnabled", false, configItemOrder++, true, false, "SimpleToadletServer.advancedMode", "SimpleToadletServer.advancedModeLong",
new <API key>(this));
fproxyConfig.register("<API key>", false, configItemOrder++, true, false, "SimpleToadletServer.<API key>", "SimpleToadletServer.<API key>",
new BooleanCallback() {
@Override
public Boolean get() {
return <API key>;
}
@Override
public void set(Boolean val) throws <API key>, <API key> {
if(get().equals(val)) return;
<API key> = val;
}
});
fproxyConfig.register("javascriptEnabled", true, configItemOrder++, true, false, "SimpleToadletServer.enableJS", "SimpleToadletServer.enableJSLong",
new <API key>(this));
fproxyConfig.register("webPushingEnabled", false, configItemOrder++, true, false, "SimpleToadletServer.enableWP", "SimpleToadletServer.enableWPLong", new <API key>(this));
fproxyConfig.register("hasCompletedWizard", false, configItemOrder++, true, false, "SimpleToadletServer.hasCompletedWizard", "SimpleToadletServer.<API key>",
new BooleanCallback() {
@Override
public Boolean get() {
return <API key>;
}
@Override
public void set(Boolean val) throws <API key>, <API key> {
if(get().equals(val)) return;
<API key> = val;
}
});
fproxyConfig.register("disableProgressPage", false, configItemOrder++, true, false, "SimpleToadletServer.disableProgressPage", "SimpleToadletServer.<API key>",
new BooleanCallback() {
@Override
public Boolean get() {
return disableProgressPage;
}
@Override
public void set(Boolean val) throws <API key>, <API key> {
disableProgressPage = val;
}
});
<API key> = fproxyConfig.getBoolean("hasCompletedWizard");
<API key> = fproxyConfig.getBoolean("javascriptEnabled");
<API key> = fproxyConfig.getBoolean("webPushingEnabled");
disableProgressPage = fproxyConfig.getBoolean("disableProgressPage");
<API key> = fproxyConfig.getBoolean("<API key>");
fproxyConfig.register("showPanicButton", false, configItemOrder++, true, true, "SimpleToadletServer.panicButton", "SimpleToadletServer.panicButtonLong",
new BooleanCallback(){
@Override
public Boolean get() {
return SimpleToadletServer.<API key>;
}
@Override
public void set(Boolean value) {
if(value == SimpleToadletServer.<API key>) return;
else SimpleToadletServer.<API key> = value;
}
});
fproxyConfig.register("noConfirmPanic", false, configItemOrder++, true, true, "SimpleToadletServer.noConfirmPanic", "SimpleToadletServer.noConfirmPanicLong",
new BooleanCallback() {
@Override
public Boolean get() {
return SimpleToadletServer.noConfirmPanic;
}
@Override
public void set(Boolean val) throws <API key>, <API key> {
if(val == SimpleToadletServer.noConfirmPanic) return;
else SimpleToadletServer.noConfirmPanic = val;
}
});
fproxyConfig.register("publicGatewayMode", false, configItemOrder++, true, true, "SimpleToadletServer.publicGatewayMode", "SimpleToadletServer.<API key>", new BooleanCallback() {
@Override
public Boolean get() {
return publicGatewayMode;
}
@Override
public void set(Boolean val) throws <API key>, <API key> {
if(publicGatewayMode == val) return;
publicGatewayMode = val;
throw new <API key>(l10n("<API key>"));
}
});
<API key> = publicGatewayMode = fproxyConfig.getBoolean("publicGatewayMode");
// This is OFF BY DEFAULT because for example firefox has a limit of 2 persistent
// connections per server, but 8 non-persistent connections per server. We need 8 conns
// more than we need the efficiency gain of reusing connections - especially on first
// install.
fproxyConfig.register("<API key>", false, configItemOrder++, true, false, "SimpleToadletServer.<API key>", "SimpleToadletServer.<API key>",
new BooleanCallback() {
@Override
public Boolean get() {
synchronized(SimpleToadletServer.this) {
return <API key>;
}
}
@Override
public void set(Boolean val) throws <API key> {
synchronized(SimpleToadletServer.this) {
<API key> = val;
}
}
});
<API key> = fproxyConfig.getBoolean("<API key>");
// Off by default.
// I had hoped it would yield a significant performance boost to bootstrap performance
// on browsers with low numbers of simultaneous connections. Unfortunately the bottleneck
// appears to be that the node does very few local requests compared to external requests
// (for anonymity's sake).
fproxyConfig.register("<API key>", false, configItemOrder++, true, false, "SimpleToadletServer.<API key>", "SimpleToadletServer.<API key>",
new BooleanCallback() {
@Override
public Boolean get() {
synchronized(SimpleToadletServer.this) {
return <API key>;
}
}
@Override
public void set(Boolean val) throws <API key> {
synchronized(SimpleToadletServer.this) {
<API key> = val;
}
}
});
<API key> = fproxyConfig.getBoolean("<API key>");
fproxyConfig.register("enableActivelinks", false, configItemOrder++, false, false, "SimpleToadletServer.enableActivelinks", "SimpleToadletServer.<API key>", new BooleanCallback() {
@Override
public Boolean get() {
return enableActivelinks;
}
@Override
public void set(Boolean val) throws <API key>, <API key> {
enableActivelinks = val;
}
});
enableActivelinks = fproxyConfig.getBoolean("enableActivelinks");
fproxyConfig.register("passthroughMaxSize", FProxyToadlet.<API key>, configItemOrder++, true, false, "SimpleToadletServer.passthroughMaxSize", "SimpleToadletServer.<API key>", new <API key>(), true);
FProxyToadlet.<API key> = fproxyConfig.getLong("passthroughMaxSize");
fproxyConfig.register("<API key>", FProxyToadlet.<API key>, configItemOrder++, true, false, "SimpleToadletServer.<API key>", "SimpleToadletServer.<API key>", new <API key>(), true);
FProxyToadlet.<API key> = fproxyConfig.getLong("<API key>");
System.out.println("Set fproxy max length to "+FProxyToadlet.<API key>+" and max length with progress to "+FProxyToadlet.<API key>+" = "+fproxyConfig.getLong("<API key>"));
fproxyConfig.register("allowedHosts", "127.0.0.1,0:0:0:0:0:0:0:1", configItemOrder++, true, true, "SimpleToadletServer.allowedHosts", "SimpleToadletServer.allowedHostsLong",
new <API key>());
fproxyConfig.register("<API key>", "127.0.0.1,0:0:0:0:0:0:0:1", configItemOrder++, true, true, "SimpleToadletServer.allowedFullAccess",
"SimpleToadletServer.<API key>",
new StringCallback() {
@Override
public String get() {
return allowedFullAccess.getAllowedHosts();
}
@Override
public void set(String val) throws <API key> {
try {
allowedFullAccess.setAllowedHosts(val);
} catch(<API key> e) {
throw new <API key>(e);
}
}
});
allowedFullAccess = new AllowedHosts(fproxyConfig.getString("<API key>"));
fproxyConfig.register("doRobots", false, configItemOrder++, true, false, "SimpleToadletServer.doRobots", "SimpleToadletServer.doRobotsLong",
new BooleanCallback() {
@Override
public Boolean get() {
return doRobots;
}
@Override
public void set(Boolean val) throws <API key> {
doRobots = val;
}
});
doRobots = fproxyConfig.getBoolean("doRobots");
// We may not know what the overall thread limit is yet so just set it to 100.
fproxyConfig.register("<API key>", 100, configItemOrder++, true, false, "SimpleToadletServer.<API key>", "SimpleToadletServer.<API key>",
new IntCallback() {
@Override
public Integer get() {
synchronized(SimpleToadletServer.this) {
return <API key>;
}
}
@Override
public void set(Integer val) {
synchronized(SimpleToadletServer.this) {
<API key> = val;
SimpleToadletServer.this.notifyAll();
}
}
}, false);
<API key> = fproxyConfig.getInt("<API key>");
fproxyConfig.register("<API key>", 1, configItemOrder++, true, false, "SimpleToadletServer.<API key>", "SimpleToadletServer.<API key>",
new IntCallback() {
@Override
public Integer get() {
return HTMLFilter.<API key>;
}
@Override
public void set(Integer val)
throws <API key>,
<API key> {
if(val < -1) throw new <API key>("-1 = disabled, 0+ = set a minimum interval"); // FIXME l10n
HTMLFilter.<API key> = val;
}
}, false);
HTMLFilter.<API key> = Math.max(-1, fproxyConfig.getInt("<API key>"));
fproxyConfig.register("<API key>", 1, configItemOrder++, true, false, "SimpleToadletServer.<API key>", "SimpleToadletServer.<API key>",
new IntCallback() {
@Override
public Integer get() {
return HTMLFilter.<API key>;
}
@Override
public void set(Integer val)
throws <API key>,
<API key> {
if(val < -1) throw new <API key>("-1 = disabled, 0+ = set a minimum interval"); // FIXME l10n
HTMLFilter.<API key> = val;
}
}, false);
HTMLFilter.<API key> = Math.max(-1, fproxyConfig.getInt("<API key>"));
fproxyConfig.register("refilterPolicy", "RE_FILTER",
configItemOrder++, true, false, "SimpleToadletServer.refilterPolicy", "SimpleToadletServer.refilterPolicyLong", new ReFilterCallback());
this.refilterPolicy = REFILTER_POLICY.valueOf(fproxyConfig.getString("refilterPolicy"));
// Network seclevel not physical seclevel because bad filtering can cause network level anonymity breaches.
SimpleToadletServer.<API key> = fproxyConfig.getBoolean("showPanicButton");
SimpleToadletServer.noConfirmPanic = fproxyConfig.getBoolean("noConfirmPanic");
this.bf = bucketFactory;
port = fproxyConfig.getInt("port");
bindTo = fproxyConfig.getString("bindTo");
String cssName = fproxyConfig.getString("css");
if((cssName.indexOf(':') != -1) || (cssName.indexOf('/') != -1))
throw new <API key>("CSS name must not contain slashes or colons!");
cssTheme = THEME.themeFromName(cssName);
pageMaker = new PageMaker(cssTheme, node);
if(!fproxyConfig.getOption("CSSOverride").isDefault()) {
cssOverride = new File(fproxyConfig.getString("CSSOverride"));
pageMaker.setOverride(StaticToadlet.OVERRIDE_URL + cssOverride.getName());
} else {
cssOverride = null;
pageMaker.setOverride(null);
}
this.advancedModeEnabled = fproxyConfig.getBoolean("advancedModeEnabled");
toadlets = new LinkedList<ToadletElement>();
if(SSL.available()) {
ssl = fproxyConfig.getBoolean("ssl");
}
this.allowedHosts=fproxyConfig.getString("allowedHosts");
if(!enabled) {
Logger.normal(SimpleToadletServer.this, "Not starting FProxy as it's disabled");
System.out.println("Not starting FProxy as it's disabled");
} else {
<API key>();
myThread = new Thread(this, "SimpleToadletServer");
myThread.setDaemon(true);
}
// Register static toadlet and startup toadlet
StaticToadlet statictoadlet = new StaticToadlet();
register(statictoadlet, null, "/static/", false, false);
// "Freenet is starting up..." page, to be removed at #<API key>()
startupToadlet = new StartupToadlet(statictoadlet);
register(startupToadlet, null, "/", false, false);
}
public StartupToadlet startupToadlet;
public void <API key>() {
// setCore() must have been called first. It is in fact called much earlier on.
synchronized(this) {
unregister(startupToadlet);
// Ready to be GCed
startupToadlet = null;
// Not in the navbar.
}
}
private void <API key>() throws IOException {
if (this.networkInterface!=null) return;
if(ssl) {
this.networkInterface = SSLNetworkInterface.create(port, this.bindTo, allowedHosts, executor, true);
} else {
this.networkInterface = NetworkInterface.create(port, this.bindTo, allowedHosts, executor, true);
}
}
@Override
public boolean doRobots() {
return doRobots;
}
@Override
public boolean publicGatewayMode() {
return <API key>;
}
public void start() {
if(myThread != null) try {
<API key>();
myThread.start();
Logger.normal(this, "Starting FProxy on "+bindTo+ ':' +port);
System.out.println("Starting FProxy on "+bindTo+ ':' +port);
} catch (IOException e) {
Logger.error(this, "Could not bind network port for FProxy?", e);
}
}
public void finishStart() {
core.node.securityLevels.<API key>(new <API key><<API key>>() {
@Override
public void onChange(<API key> oldLevel,
<API key> newLevel) {
// At LOW, we do ACCEPT_OLD.
// Otherwise we do RE_FILTER.
// But we don't change it unless it changes from LOW to not LOW.
if(newLevel == <API key>.LOW && newLevel != oldLevel) {
refilterPolicy = REFILTER_POLICY.ACCEPT_OLD;
} else if(oldLevel == <API key>.LOW && newLevel != oldLevel) {
refilterPolicy = REFILTER_POLICY.RE_FILTER;
}
}
});
core.node.securityLevels.<API key>(new <API key><<API key>> () {
@Override
public void onChange(<API key> oldLevel, <API key> newLevel) {
if(newLevel != oldLevel && newLevel == <API key>.LOW) {
<API key> = false;
} else if(newLevel != oldLevel) {
<API key> = true;
}
}
});
synchronized(this) {
finishedStartup = true;
}
}
@Override
public void register(Toadlet t, String menu, String urlPrefix, boolean atFront, boolean fullOnly) {
register(t, menu, urlPrefix, atFront, null, null, fullOnly, null, null);
}
@Override
public void register(Toadlet t, String menu, String urlPrefix, boolean atFront, String name, String title, boolean fullOnly, LinkEnabledCallback cb) {
register(t, menu, urlPrefix, atFront, name, title, fullOnly, cb, null);
}
@Override
public void register(Toadlet t, String menu, String urlPrefix, boolean atFront, String name, String title, boolean fullOnly, LinkEnabledCallback cb, FredPluginL10n l10n) {
ToadletElement te = new ToadletElement(t, urlPrefix, menu, name);
synchronized(toadlets) {
if(atFront) toadlets.addFirst(te);
else toadlets.addLast(te);
t.container = this;
}
if (menu != null && name != null) {
pageMaker.addNavigationLink(menu, urlPrefix, name, title, fullOnly, cb, l10n);
}
}
public void registerMenu(String link, String name, String title, FredPluginL10n plugin) {
pageMaker.<API key>(link, name, title, plugin);
}
@Override
public void unregister(Toadlet t) {
ToadletElement e = null;
synchronized(toadlets) {
for(Iterator<ToadletElement> i=toadlets.iterator();i.hasNext();) {
e = i.next();
if(e.t == t) {
i.remove();
break;
}
}
}
if(e != null && e.t == t) {
if(e.menu != null && e.name != null) {
pageMaker.<API key>(e.menu, e.name);
}
}
}
public StartupToadlet getStartupToadlet() {
return startupToadlet;
}
@Override
public boolean <API key>() {
return <API key>;
}
@Override
public Toadlet findToadlet(URI uri) throws <API key> {
String path = uri.getPath();
// Show the wizard until dismissed by the user (See bug #2624)
NodeClientCore core = this.core;
if(core != null && core.node != null && !<API key>) {
//If the user has not completed the wizard, only allow access to the wizard and static
//resources. Anything else redirects to the first page of the wizard.
if (!(path.startsWith(<API key>.TOADLET_URL) ||
path.startsWith(StaticToadlet.ROOT_URL) ||
path.startsWith(ExternalLinkToadlet.PATH) ||
path.equals("/favicon.ico"))) {
try {
throw new <API key>(new URI(null, null, null, -1, <API key>.TOADLET_URL, uri.getQuery(), null));
} catch(URISyntaxException e) { throw new Error(e); }
}
}
synchronized(toadlets) {
for(ToadletElement te: toadlets) {
if(path.startsWith(te.prefix))
return te.t;
if(te.prefix.length() > 0 && te.prefix.charAt(te.prefix.length()-1) == '/') {
if(path.equals(te.prefix.substring(0, te.prefix.length()-1))) {
URI newURI;
try {
newURI = new URI(te.prefix);
} catch (URISyntaxException e) {
throw new Error(e);
}
throw new <API key>(newURI);
}
}
}
}
return null;
}
@Override
public void run() {
boolean finishedStartup = false;
while(true) {
synchronized(this) {
while(fproxyConnections > <API key>) {
try {
wait();
} catch (<API key> e) {
// Ignore
}
}
if((!finishedStartup) && this.finishedStartup)
finishedStartup = true;
if(myThread == null) return;
}
Socket conn = networkInterface.accept();
//if (WrapperManager.<API key>())
//return;
if(conn == null)
continue; // timeout
if(logMINOR)
Logger.minor(this, "Accepted connection");
SocketHandler sh = new SocketHandler(conn, finishedStartup);
sh.start();
}
}
public class SocketHandler implements PrioRunnable {
Socket sock;
final boolean finishedStartup;
public SocketHandler(Socket conn, boolean finishedStartup) {
this.sock = conn;
this.finishedStartup = finishedStartup;
}
void start() {
if(finishedStartup)
executor.execute(this, "HTTP socket handler@"+hashCode());
else
new Thread(this).start();
synchronized(SimpleToadletServer.this) {
fproxyConnections++;
}
}
@Override
public void run() {
freenet.support.Logger.OSThread.logPID(this);
if(logMINOR) Logger.minor(this, "Handling connection");
try {
ToadletContextImpl.handle(sock, SimpleToadletServer.this, pageMaker, getUserAlertManager(), bookmarkManager);
} catch (Throwable t) {
System.err.println("Caught in SimpleToadletServer: "+t);
t.printStackTrace();
Logger.error(this, "Caught in SimpleToadletServer: "+t, t);
} finally {
synchronized(SimpleToadletServer.this) {
fproxyConnections
SimpleToadletServer.this.notifyAll();
}
}
if(logMINOR) Logger.minor(this, "Handled connection");
}
@Override
public int getPriority() {
return NativeThread.HIGH_PRIORITY-1;
}
}
@Override
public THEME getTheme() {
return this.cssTheme;
}
public UserAlertManager getUserAlertManager() {
NodeClientCore core = this.core;
if(core == null) return null;
return core.alerts;
}
public void setCSSName(THEME theme) {
this.cssTheme = theme;
}
@Override
public synchronized boolean sendAllThemes() {
return this.sendAllThemes;
}
@Override
public synchronized boolean <API key>() {
return this.advancedModeEnabled;
}
@Override
public void setAdvancedMode(boolean enabled) {
synchronized(this) {
if(advancedModeEnabled == enabled) return;
advancedModeEnabled = enabled;
}
core.node.config.store();
}
@Override
public synchronized boolean <API key>() {
return this.<API key>;
}
public synchronized void <API key>(boolean b){
<API key> = b;
}
@Override
public synchronized boolean <API key>() {
return this.<API key>;
}
public synchronized void <API key>(boolean b){
<API key> = b;
}
@Override
public String getFormPassword() {
if(core == null) return "";
return core.formPassword;
}
@Override
public boolean isAllowedFullAccess(InetAddress remoteAddr) {
return this.allowedFullAccess.allowed(remoteAddr);
}
private static String l10n(String key, String pattern, String value) {
return NodeL10n.getBase().getString("SimpleToadletServer."+key, pattern, value);
}
private static String l10n(String key) {
return NodeL10n.getBase().getString("SimpleToadletServer."+key);
}
@Override
public HTMLNode addFormChild(HTMLNode parentNode, String target, String id) {
HTMLNode formNode =
parentNode.addChild("div")
.addChild("form", new String[] { "action", "method", "enctype", "id", "accept-charset" },
new String[] { target, "post", "multipart/form-data", id, "utf-8"} );
formNode.addChild("input", new String[] { "type", "name", "value" },
new String[] { "hidden", "formPassword", getFormPassword() });
return formNode;
}
public void setBucketFactory(BucketFactory tempBucketFactory) {
this.bf = tempBucketFactory;
}
public boolean isEnabled() {
return myThread != null;
}
public BookmarkManager getBookmarks() {
return bookmarkManager;
}
public FreenetURI[] getBookmarkURIs() {
if(bookmarkManager == null) return new FreenetURI[0];
return bookmarkManager.getBookmarkURIs();
}
@Override
public boolean <API key>() {
return <API key>;
}
@Override
public boolean <API key>() {
return <API key>;
}
@Override
public boolean <API key>() {
return <API key>;
}
@Override
public synchronized boolean allowPosts() {
return !(bf instanceof ArrayBucketFactory);
}
@Override
public synchronized BucketFactory getBucketFactory() {
return bf;
}
@Override
public boolean enableActivelinks() {
return enableActivelinks;
}
@Override
public boolean disableProgressPage() {
return disableProgressPage;
}
@Override
public PageMaker getPageMaker() {
return pageMaker;
}
public Ticker getTicker(){
return core.node.getTicker();
}
public NodeClientCore getCore(){
return core;
}
private REFILTER_POLICY refilterPolicy;
@Override
public REFILTER_POLICY getReFilterPolicy() {
return refilterPolicy;
}
@Override
public File getOverrideFile() {
return cssOverride;
}
@Override
public String getURL() {
return getURL(null);
}
@Override
public String getURL(String host) {
StringBuffer sb = new StringBuffer();
if(ssl)
sb.append("https");
else
sb.append("http");
sb.append(":
if(host == null)
host = "127.0.0.1";
sb.append(host);
sb.append(":");
sb.append(this.port);
sb.append("/");
return sb.toString();
}
@Override
public boolean isSSL() {
return ssl;
}
// <API key> METHODS
/**
* {@inheritDoc}
*/
@Override
public boolean isLinkExcepted(URI link) {
Toadlet toadlet = null;
try {
toadlet = findToadlet(link);
} catch (<API key> pre1) {
/* ignore. */
}
if (toadlet instanceof <API key>) {
return ((<API key>) toadlet).isLinkExcepted(link);
}
return false;
}
@Override
public long generateUniqueID() {
// FIXME increment a counter?
return random.nextLong();
}
}
|
layout: default
title: (unrecognied function)(FIXME!)
[Top](../index.html)
(file name)
hotspot/src/share/vm/prims/jvmtiEnvBase.cpp
(description)
// update the access_flags for the field in the klass
(function name)
void
JvmtiEnvBase::<API key>(fieldDescriptor *fd) {
(body)
{-
(1) fd fieldDescriptor _access_flags ,
instanceKlass fields
instanceKlass* ik = instanceKlass::cast(fd->field_holder());
typeArrayOop fields = ik->fields();
fields->ushort_at_put(fd->index(), (jushort)fd->access_flags().as_short());
}
|
<?php
defined('_JEXEC') or die();
// Check to ensure this file is included in Joomla!
?>
<form action="index.php" method="post" name="adminForm" id="adminForm">
<?php AdminUIHelper::startAdminArea(); ?>
<div id="filter-bar" class="btn-toolbar">
<?php echo $this-><API key>() ?>
</div>
<div class="clearfix"> </div>
<div id="results">
<?php
// split to use ajax search
echo $this->loadTemplate('results'); ?>
</div>
<?php AdminUIHelper::endAdminArea(true); ?>
</form>
|
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>Automated Translation Tries: File Members</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">Automated Translation Tries
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.10 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li class="current"><a href="globals.html"><span>File Members</span></a></li>
</ul>
</div>
<div id="navrow3" class="tabs2">
<ul class="tablist">
<li><a href="globals.html"><span>All</span></a></li>
<li><a href="globals_func.html"><span>Functions</span></a></li>
<li class="current"><a href="globals_defs.html"><span>Macros</span></a></li>
</ul>
</div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('globals_defs.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="<API key>">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="contents">
 <ul>
<li>A
: <a class="el" href="_hashing_utils_8hpp.html#<API key>">HashingUtils.hpp</a>
</li>
<li>B
: <a class="el" href="_hashing_utils_8hpp.html#<API key>">HashingUtils.hpp</a>
</li>
<li>BYTES_ONE_MB
: <a class="el" href="_globals_8hpp.html#<API key>">Globals.hpp</a>
</li>
<li>C
: <a class="el" href="_hashing_utils_8hpp.html#<API key>">HashingUtils.hpp</a>
</li>
<li>DEBUG_OPTION_VALUES
: <a class="el" href="_globals_8hpp.html#<API key>">Globals.hpp</a>
</li>
<li>DEBUG_PARAM_VALUE
: <a class="el" href="_globals_8hpp.html#<API key>">Globals.hpp</a>
</li>
<li><API key>
: <a class="el" href="_globals_8hpp.html#<API key>">Globals.hpp</a>
</li>
<li><API key>
: <a class="el" href="_globals_8hpp.html#<API key>">Globals.hpp</a>
</li>
<li>HASHMAPTRIE_HPP
: <a class="el" href="_hash_map_trie_8hpp.html#<API key>">HashMapTrie.hpp</a>
</li>
<li>INFO_PARAM_VALUE
: <a class="el" href="_globals_8hpp.html#<API key>">Globals.hpp</a>
</li>
<li>LOGER_MAX_LEVEL
: <a class="el" href="_logger_8hpp.html#<API key>">Logger.hpp</a>
</li>
<li>LOGGER
: <a class="el" href="_logger_8hpp.html#<API key>">Logger.hpp</a>
</li>
<li>LOGGER_HPP
: <a class="el" href="_logger_8hpp.html#<API key>">Logger.hpp</a>
</li>
<li>N_GRAM_PARAM
: <a class="el" href="_globals_8hpp.html#<API key>">Globals.hpp</a>
</li>
<li><API key>
: <a class="el" href="_globals_8hpp.html#<API key>">Globals.hpp</a>
</li>
<li><API key>
: <a class="el" href="_logger_8hpp.html#<API key>">Logger.hpp</a>
</li>
<li><API key>
: <a class="el" href="_globals_8hpp.html#<API key>">Globals.hpp</a>
</li>
</ul>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="footer">Generated by
<a href="http:
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.10 </li>
</ul>
</div>
</body>
</html>
|
#include <linux/string.h>
#include <linux/module.h>
#include <linux/scatterlist.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/in6.h>
#include <rdma/ib_verbs.h>
#include <rdma/rdma_cm.h>
#include <target/target_core_base.h>
#include <target/target_core_fabric.h>
#include <target/iscsi/iscsi_transport.h>
#include "isert_proto.h"
#include "ib_isert.h"
#define ISERT_MAX_CONN 8
#define ISER_MAX_RX_CQ_LEN (<API key> * ISERT_MAX_CONN)
#define ISER_MAX_TX_CQ_LEN (<API key> * ISERT_MAX_CONN)
static DEFINE_MUTEX(device_list_mutex);
static LIST_HEAD(device_list);
static struct workqueue_struct *isert_rx_wq;
static struct workqueue_struct *isert_comp_wq;
static struct kmem_cache *isert_cmd_cache;
static void isert_release_work(struct work_struct *work);
static void
<API key>(struct ib_event *e, void *context)
{
struct isert_conn *isert_conn = (struct isert_conn *)context;
pr_err("<API key> event: %d\n", e->event);
switch (e->event) {
case IB_EVENT_COMM_EST:
rdma_notify(isert_conn->conn_cm_id, IB_EVENT_COMM_EST);
break;
case <API key>:
pr_warn("Reached TX <API key>:\n");
break;
default:
break;
}
}
static int
isert_query_device(struct ib_device *ib_dev, struct ib_device_attr *devattr)
{
int ret;
ret = ib_query_device(ib_dev, devattr);
if (ret) {
pr_err("ib_query_device() failed: %d\n", ret);
return ret;
}
pr_debug("devattr->max_sge: %d\n", devattr->max_sge);
pr_debug("devattr->max_sge_rd: %d\n", devattr->max_sge_rd);
return 0;
}
static int
isert_conn_setup_qp(struct isert_conn *isert_conn, struct rdma_cm_id *cma_id)
{
struct isert_device *device = isert_conn->conn_device;
struct ib_qp_init_attr attr;
struct ib_device_attr devattr;
int ret, index, min_index = 0;
memset(&devattr, 0, sizeof(struct ib_device_attr));
ret = isert_query_device(cma_id->device, &devattr);
if (ret)
return ret;
mutex_lock(&device_list_mutex);
for (index = 0; index < device->cqs_used; index++)
if (device->cq_active_qps[index] <
device->cq_active_qps[min_index])
min_index = index;
device->cq_active_qps[min_index]++;
pr_debug("isert_conn_setup_qp: Using min_index: %d\n", min_index);
mutex_unlock(&device_list_mutex);
memset(&attr, 0, sizeof(struct ib_qp_init_attr));
attr.event_handler = <API key>;
attr.qp_context = isert_conn;
attr.send_cq = device->dev_tx_cq[min_index];
attr.recv_cq = device->dev_rx_cq[min_index];
attr.cap.max_send_wr = <API key>;
attr.cap.max_recv_wr = <API key>;
/*
* FIXME: Use devattr.max_sge - 2 for max_send_sge as
* work-around for RDMA_READ..
*/
attr.cap.max_send_sge = devattr.max_sge - 2;
isert_conn->max_sge = attr.cap.max_send_sge;
attr.cap.max_recv_sge = 1;
attr.sq_sig_type = IB_SIGNAL_REQ_WR;
attr.qp_type = IB_QPT_RC;
pr_debug("isert_conn_setup_qp cma_id->device: %p\n",
cma_id->device);
pr_debug("isert_conn_setup_qp conn_pd->device: %p\n",
isert_conn->conn_pd->device);
ret = rdma_create_qp(cma_id, isert_conn->conn_pd, &attr);
if (ret) {
pr_err("rdma_create_qp failed for cma_id %d\n", ret);
return ret;
}
isert_conn->conn_qp = cma_id->qp;
pr_debug("rdma_create_qp() returned success >>>>>>>>>>>>>>>>>>>>>>>>>.\n");
return 0;
}
static void
<API key>(struct ib_event *e, void *context)
{
pr_debug("<API key> event: %d\n", e->event);
}
static int
<API key>(struct isert_conn *isert_conn)
{
struct ib_device *ib_dev = isert_conn->conn_cm_id->device;
struct iser_rx_desc *rx_desc;
struct ib_sge *rx_sg;
u64 dma_addr;
int i, j;
isert_conn->conn_rx_descs = kzalloc(<API key> *
sizeof(struct iser_rx_desc), GFP_KERNEL);
if (!isert_conn->conn_rx_descs)
goto fail;
rx_desc = isert_conn->conn_rx_descs;
for (i = 0; i < <API key>; i++, rx_desc++) {
dma_addr = ib_dma_map_single(ib_dev, (void *)rx_desc,
<API key>, DMA_FROM_DEVICE);
if (<API key>(ib_dev, dma_addr))
goto dma_map_fail;
rx_desc->dma_addr = dma_addr;
rx_sg = &rx_desc->rx_sg;
rx_sg->addr = rx_desc->dma_addr;
rx_sg->length = <API key>;
rx_sg->lkey = isert_conn->conn_mr->lkey;
}
isert_conn->conn_rx_desc_head = 0;
return 0;
dma_map_fail:
rx_desc = isert_conn->conn_rx_descs;
for (j = 0; j < i; j++, rx_desc++) {
ib_dma_unmap_single(ib_dev, rx_desc->dma_addr,
<API key>, DMA_FROM_DEVICE);
}
kfree(isert_conn->conn_rx_descs);
isert_conn->conn_rx_descs = NULL;
fail:
return -ENOMEM;
}
static void
<API key>(struct isert_conn *isert_conn)
{
struct ib_device *ib_dev = isert_conn->conn_device->ib_device;
struct iser_rx_desc *rx_desc;
int i;
if (!isert_conn->conn_rx_descs)
return;
rx_desc = isert_conn->conn_rx_descs;
for (i = 0; i < <API key>; i++, rx_desc++) {
ib_dma_unmap_single(ib_dev, rx_desc->dma_addr,
<API key>, DMA_FROM_DEVICE);
}
kfree(isert_conn->conn_rx_descs);
isert_conn->conn_rx_descs = NULL;
}
static void <API key>(struct ib_cq *, void *);
static void <API key>(struct ib_cq *, void *);
static int
<API key>(struct isert_device *device)
{
struct ib_device *ib_dev = device->ib_device;
struct isert_cq_desc *cq_desc;
int ret = 0, i, j;
device->cqs_used = min_t(int, num_online_cpus(),
device->ib_device->num_comp_vectors);
device->cqs_used = min(ISERT_MAX_CQ, device->cqs_used);
pr_debug("Using %d CQs, device %s supports %d vectors\n",
device->cqs_used, device->ib_device->name,
device->ib_device->num_comp_vectors);
device->cq_desc = kzalloc(sizeof(struct isert_cq_desc) *
device->cqs_used, GFP_KERNEL);
if (!device->cq_desc) {
pr_err("Unable to allocate device->cq_desc\n");
return -ENOMEM;
}
cq_desc = device->cq_desc;
device->dev_pd = ib_alloc_pd(ib_dev);
if (IS_ERR(device->dev_pd)) {
ret = PTR_ERR(device->dev_pd);
pr_err("ib_alloc_pd failed for dev_pd: %d\n", ret);
goto out_cq_desc;
}
for (i = 0; i < device->cqs_used; i++) {
cq_desc[i].device = device;
cq_desc[i].cq_index = i;
device->dev_rx_cq[i] = ib_create_cq(device->ib_device,
<API key>,
<API key>,
(void *)&cq_desc[i],
ISER_MAX_RX_CQ_LEN, i);
if (IS_ERR(device->dev_rx_cq[i])) {
ret = PTR_ERR(device->dev_rx_cq[i]);
device->dev_rx_cq[i] = NULL;
goto out_cq;
}
device->dev_tx_cq[i] = ib_create_cq(device->ib_device,
<API key>,
<API key>,
(void *)&cq_desc[i],
ISER_MAX_TX_CQ_LEN, i);
if (IS_ERR(device->dev_tx_cq[i])) {
ret = PTR_ERR(device->dev_tx_cq[i]);
device->dev_tx_cq[i] = NULL;
goto out_cq;
}
ret = ib_req_notify_cq(device->dev_rx_cq[i], IB_CQ_NEXT_COMP);
if (ret)
goto out_cq;
ret = ib_req_notify_cq(device->dev_tx_cq[i], IB_CQ_NEXT_COMP);
if (ret)
goto out_cq;
}
device->dev_mr = ib_get_dma_mr(device->dev_pd, <API key>);
if (IS_ERR(device->dev_mr)) {
ret = PTR_ERR(device->dev_mr);
pr_err("ib_get_dma_mr failed for dev_mr: %d\n", ret);
goto out_cq;
}
return 0;
out_cq:
for (j = 0; j < i; j++) {
cq_desc = &device->cq_desc[j];
if (device->dev_rx_cq[j]) {
cancel_work_sync(&cq_desc->cq_rx_work);
ib_destroy_cq(device->dev_rx_cq[j]);
}
if (device->dev_tx_cq[j]) {
cancel_work_sync(&cq_desc->cq_tx_work);
ib_destroy_cq(device->dev_tx_cq[j]);
}
}
ib_dealloc_pd(device->dev_pd);
out_cq_desc:
kfree(device->cq_desc);
return ret;
}
static void
<API key>(struct isert_device *device)
{
struct isert_cq_desc *cq_desc;
int i;
for (i = 0; i < device->cqs_used; i++) {
cq_desc = &device->cq_desc[i];
cancel_work_sync(&cq_desc->cq_rx_work);
cancel_work_sync(&cq_desc->cq_tx_work);
ib_destroy_cq(device->dev_rx_cq[i]);
ib_destroy_cq(device->dev_tx_cq[i]);
device->dev_rx_cq[i] = NULL;
device->dev_tx_cq[i] = NULL;
}
ib_dereg_mr(device->dev_mr);
ib_dealloc_pd(device->dev_pd);
kfree(device->cq_desc);
}
static void
<API key>(struct isert_device *device)
{
mutex_lock(&device_list_mutex);
device->refcount
if (!device->refcount) {
<API key>(device);
list_del(&device->dev_node);
kfree(device);
}
mutex_unlock(&device_list_mutex);
}
static struct isert_device *
<API key>(struct rdma_cm_id *cma_id)
{
struct isert_device *device;
int ret;
mutex_lock(&device_list_mutex);
list_for_each_entry(device, &device_list, dev_node) {
if (device->ib_device->node_guid == cma_id->device->node_guid) {
device->refcount++;
mutex_unlock(&device_list_mutex);
return device;
}
}
device = kzalloc(sizeof(struct isert_device), GFP_KERNEL);
if (!device) {
mutex_unlock(&device_list_mutex);
return ERR_PTR(-ENOMEM);
}
INIT_LIST_HEAD(&device->dev_node);
device->ib_device = cma_id->device;
ret = <API key>(device);
if (ret) {
kfree(device);
mutex_unlock(&device_list_mutex);
return ERR_PTR(ret);
}
device->refcount++;
list_add_tail(&device->dev_node, &device_list);
mutex_unlock(&device_list_mutex);
return device;
}
static int
<API key>(struct rdma_cm_id *cma_id, struct rdma_cm_event *event)
{
struct isert_np *isert_np = cma_id->context;
struct iscsi_np *np = isert_np->np;
struct isert_conn *isert_conn;
struct isert_device *device;
struct ib_device *ib_dev = cma_id->device;
int ret = 0;
spin_lock_bh(&np->np_thread_lock);
if (!np->enabled) {
spin_unlock_bh(&np->np_thread_lock);
pr_debug("iscsi_np is not enabled, reject connect request\n");
return rdma_reject(cma_id, NULL, 0);
}
spin_unlock_bh(&np->np_thread_lock);
pr_debug("Entering <API key> cma_id: %p, context: %p\n",
cma_id, cma_id->context);
isert_conn = kzalloc(sizeof(struct isert_conn), GFP_KERNEL);
if (!isert_conn) {
pr_err("Unable to allocate isert_conn\n");
return -ENOMEM;
}
isert_conn->state = ISER_CONN_INIT;
INIT_LIST_HEAD(&isert_conn->conn_accept_node);
init_completion(&isert_conn->conn_login_comp);
init_completion(&isert_conn->conn_wait);
init_completion(&isert_conn->conn_wait_comp_err);
kref_init(&isert_conn->conn_kref);
kref_get(&isert_conn->conn_kref);
mutex_init(&isert_conn->conn_mutex);
INIT_WORK(&isert_conn->release_work, isert_release_work);
cma_id->context = isert_conn;
isert_conn->conn_cm_id = cma_id;
isert_conn->responder_resources = event->param.conn.responder_resources;
isert_conn->initiator_depth = event->param.conn.initiator_depth;
pr_debug("Using responder_resources: %u initiator_depth: %u\n",
isert_conn->responder_resources, isert_conn->initiator_depth);
isert_conn->login_buf = kzalloc(<API key> +
ISER_RX_LOGIN_SIZE, GFP_KERNEL);
if (!isert_conn->login_buf) {
pr_err("Unable to allocate isert_conn->login_buf\n");
ret = -ENOMEM;
goto out;
}
isert_conn->login_req_buf = isert_conn->login_buf;
isert_conn->login_rsp_buf = isert_conn->login_buf +
<API key>;
pr_debug("Set login_buf: %p login_req_buf: %p login_rsp_buf: %p\n",
isert_conn->login_buf, isert_conn->login_req_buf,
isert_conn->login_rsp_buf);
isert_conn->login_req_dma = ib_dma_map_single(ib_dev,
(void *)isert_conn->login_req_buf,
<API key>, DMA_FROM_DEVICE);
ret = <API key>(ib_dev, isert_conn->login_req_dma);
if (ret) {
pr_err("<API key> failed for login_req_dma: %d\n",
ret);
isert_conn->login_req_dma = 0;
goto out_login_buf;
}
isert_conn->login_rsp_dma = ib_dma_map_single(ib_dev,
(void *)isert_conn->login_rsp_buf,
ISER_RX_LOGIN_SIZE, DMA_TO_DEVICE);
ret = <API key>(ib_dev, isert_conn->login_rsp_dma);
if (ret) {
pr_err("<API key> failed for login_rsp_dma: %d\n",
ret);
isert_conn->login_rsp_dma = 0;
goto out_req_dma_map;
}
device = <API key>(cma_id);
if (IS_ERR(device)) {
ret = PTR_ERR(device);
goto out_rsp_dma_map;
}
isert_conn->conn_device = device;
isert_conn->conn_pd = device->dev_pd;
isert_conn->conn_mr = device->dev_mr;
ret = isert_conn_setup_qp(isert_conn, cma_id);
if (ret)
goto out_conn_dev;
mutex_lock(&isert_np->np_accept_mutex);
list_add_tail(&isert_np->np_accept_list, &isert_conn->conn_accept_node);
mutex_unlock(&isert_np->np_accept_mutex);
pr_debug("<API key>() waking up np_accept_wq: %p\n", np);
wake_up(&isert_np->np_accept_wq);
return 0;
out_conn_dev:
<API key>(device);
out_rsp_dma_map:
ib_dma_unmap_single(ib_dev, isert_conn->login_rsp_dma,
ISER_RX_LOGIN_SIZE, DMA_TO_DEVICE);
out_req_dma_map:
ib_dma_unmap_single(ib_dev, isert_conn->login_req_dma,
<API key>, DMA_FROM_DEVICE);
out_login_buf:
kfree(isert_conn->login_buf);
out:
kfree(isert_conn);
return ret;
}
static void
<API key>(struct isert_conn *isert_conn)
{
struct ib_device *ib_dev = isert_conn->conn_cm_id->device;
struct isert_device *device = isert_conn->conn_device;
int cq_index;
pr_debug("Entering <API key>(): >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
if (isert_conn->conn_qp) {
cq_index = ((struct isert_cq_desc *)
isert_conn->conn_qp->recv_cq->cq_context)->cq_index;
pr_debug("<API key>: cq_index: %d\n", cq_index);
isert_conn->conn_device->cq_active_qps[cq_index]
rdma_destroy_qp(isert_conn->conn_cm_id);
}
<API key>(isert_conn);
rdma_destroy_id(isert_conn->conn_cm_id);
if (isert_conn->login_buf) {
ib_dma_unmap_single(ib_dev, isert_conn->login_rsp_dma,
ISER_RX_LOGIN_SIZE, DMA_TO_DEVICE);
ib_dma_unmap_single(ib_dev, isert_conn->login_req_dma,
<API key>,
DMA_FROM_DEVICE);
kfree(isert_conn->login_buf);
}
kfree(isert_conn);
if (device)
<API key>(device);
pr_debug("Leaving <API key> >>>>>>>>>>>>\n");
}
static void
<API key>(struct rdma_cm_id *cma_id)
{
struct isert_conn *isert_conn = cma_id->context;
kref_get(&isert_conn->conn_kref);
}
static void
<API key>(struct kref *kref)
{
struct isert_conn *isert_conn = container_of(kref,
struct isert_conn, conn_kref);
pr_debug("Calling <API key> for final kref %s/%d\n",
current->comm, current->pid);
<API key>(isert_conn);
}
static void
isert_put_conn(struct isert_conn *isert_conn)
{
kref_put(&isert_conn->conn_kref, <API key>);
}
static void
<API key>(struct work_struct *work)
{
struct isert_conn *isert_conn = container_of(work,
struct isert_conn, conn_logout_work);
pr_debug("<API key>(): >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
mutex_lock(&isert_conn->conn_mutex);
if (isert_conn->state == ISER_CONN_UP)
isert_conn->state = <API key>;
if (isert_conn->post_recv_buf_count == 0 &&
atomic_read(&isert_conn->post_send_buf_count) == 0) {
mutex_unlock(&isert_conn->conn_mutex);
goto wake_up;
}
if (!isert_conn->conn_cm_id) {
mutex_unlock(&isert_conn->conn_mutex);
isert_put_conn(isert_conn);
return;
}
if (isert_conn->disconnect) {
/* Send DREQ/DREP towards our initiator */
rdma_disconnect(isert_conn->conn_cm_id);
}
mutex_unlock(&isert_conn->conn_mutex);
wake_up:
complete(&isert_conn->conn_wait);
}
static int
<API key>(struct rdma_cm_id *cma_id, bool disconnect)
{
struct isert_conn *isert_conn;
bool terminating = false;
if (!cma_id->qp) {
struct isert_np *isert_np = cma_id->context;
isert_np->np_cm_id = NULL;
break;
case <API key>:
isert_np->np_cm_id = isert_setup_id(isert_np);
if (IS_ERR(isert_np->np_cm_id)) {
pr_err("isert np %p setup id failed: %ld\n",
isert_np, PTR_ERR(isert_np->np_cm_id));
isert_np->np_cm_id = NULL;
}
break;
default:
pr_err("isert np %p Unexpected event %d\n",
isert_np, event);
}
isert_conn = (struct isert_conn *)cma_id->context;
isert_conn->disconnect = disconnect;
INIT_WORK(&isert_conn->conn_logout_work, <API key>);
schedule_work(&isert_conn->conn_logout_work);
return 0;
}
static int
isert_cma_handler(struct rdma_cm_id *cma_id, struct rdma_cm_event *event)
{
int ret = 0;
bool disconnect = false;
pr_debug("isert_cma_handler: event %d status %d conn %p id %p\n",
event->event, event->status, cma_id->context, cma_id);
switch (event->event) {
case <API key>:
ret = <API key>(cma_id, event);
if (ret)
pr_err("isert_cma_handler failed RDMA_CM_EVENT: 0x%08x %d\n",
event->event, ret);
break;
case <API key>:
<API key>(cma_id);
break;
case <API key>: /* FALLTHRU */
case <API key>: /* FALLTHRU */
case <API key>: /* FALLTHRU */
disconnect = true;
case <API key>: /* FALLTHRU */
ret = <API key>(cma_id, disconnect);
break;
case <API key>:
default:
pr_err("Unhandled RDMA CMA event: %d\n", event->event);
break;
}
return ret;
}
static int
isert_post_recv(struct isert_conn *isert_conn, u32 count)
{
struct ib_recv_wr *rx_wr, *rx_wr_failed;
int i, ret;
unsigned int rx_head = isert_conn->conn_rx_desc_head;
struct iser_rx_desc *rx_desc;
for (rx_wr = isert_conn->conn_rx_wr, i = 0; i < count; i++, rx_wr++) {
rx_desc = &isert_conn->conn_rx_descs[rx_head];
rx_wr->wr_id = (unsigned long)rx_desc;
rx_wr->sg_list = &rx_desc->rx_sg;
rx_wr->num_sge = 1;
rx_wr->next = rx_wr + 1;
rx_head = (rx_head + 1) & (<API key> - 1);
}
rx_wr
rx_wr->next = NULL; /* mark end of work requests list */
isert_conn->post_recv_buf_count += count;
ret = ib_post_recv(isert_conn->conn_qp, isert_conn->conn_rx_wr,
&rx_wr_failed);
if (ret) {
pr_err("ib_post_recv() failed with ret: %d\n", ret);
isert_conn->post_recv_buf_count -= count;
} else {
pr_debug("isert_post_recv(): Posted %d RX buffers\n", count);
isert_conn->conn_rx_desc_head = rx_head;
}
return ret;
}
static int
isert_post_send(struct isert_conn *isert_conn, struct iser_tx_desc *tx_desc)
{
struct ib_device *ib_dev = isert_conn->conn_cm_id->device;
struct ib_send_wr send_wr, *send_wr_failed;
int ret;
<API key>(ib_dev, tx_desc->dma_addr,
ISER_HEADERS_LEN, DMA_TO_DEVICE);
send_wr.next = NULL;
send_wr.wr_id = (unsigned long)tx_desc;
send_wr.sg_list = tx_desc->tx_sg;
send_wr.num_sge = tx_desc->num_sge;
send_wr.opcode = IB_WR_SEND;
send_wr.send_flags = IB_SEND_SIGNALED;
atomic_inc(&isert_conn->post_send_buf_count);
ret = ib_post_send(isert_conn->conn_qp, &send_wr, &send_wr_failed);
if (ret) {
pr_err("ib_post_send() failed, ret: %d\n", ret);
atomic_dec(&isert_conn->post_send_buf_count);
}
return ret;
}
static void
<API key>(struct isert_conn *isert_conn,
struct isert_cmd *isert_cmd,
struct iser_tx_desc *tx_desc)
{
struct ib_device *ib_dev = isert_conn->conn_cm_id->device;
<API key>(ib_dev, tx_desc->dma_addr,
ISER_HEADERS_LEN, DMA_TO_DEVICE);
memset(&tx_desc->iser_header, 0, sizeof(struct iser_hdr));
tx_desc->iser_header.flags = ISER_VER;
tx_desc->num_sge = 1;
tx_desc->isert_cmd = isert_cmd;
if (tx_desc->tx_sg[0].lkey != isert_conn->conn_mr->lkey) {
tx_desc->tx_sg[0].lkey = isert_conn->conn_mr->lkey;
pr_debug("tx_desc %p lkey mismatch, fixing\n", tx_desc);
}
}
static int
isert_init_tx_hdrs(struct isert_conn *isert_conn,
struct iser_tx_desc *tx_desc)
{
struct ib_device *ib_dev = isert_conn->conn_cm_id->device;
u64 dma_addr;
dma_addr = ib_dma_map_single(ib_dev, (void *)tx_desc,
ISER_HEADERS_LEN, DMA_TO_DEVICE);
if (<API key>(ib_dev, dma_addr)) {
pr_err("<API key>() failed\n");
return -ENOMEM;
}
tx_desc->dma_addr = dma_addr;
tx_desc->tx_sg[0].addr = tx_desc->dma_addr;
tx_desc->tx_sg[0].length = ISER_HEADERS_LEN;
tx_desc->tx_sg[0].lkey = isert_conn->conn_mr->lkey;
pr_debug("isert_init_tx_hdrs: Setup tx_sg[0].addr: 0x%llx length: %u"
" lkey: 0x%08x\n", tx_desc->tx_sg[0].addr,
tx_desc->tx_sg[0].length, tx_desc->tx_sg[0].lkey);
return 0;
}
static void
isert_init_send_wr(struct isert_cmd *isert_cmd, struct ib_send_wr *send_wr)
{
isert_cmd->rdma_wr.iser_ib_op = ISER_IB_SEND;
send_wr->wr_id = (unsigned long)&isert_cmd->tx_desc;
send_wr->opcode = IB_WR_SEND;
send_wr->send_flags = IB_SEND_SIGNALED;
send_wr->sg_list = &isert_cmd->tx_desc.tx_sg[0];
send_wr->num_sge = isert_cmd->tx_desc.num_sge;
}
static int
<API key>(struct isert_conn *isert_conn)
{
struct ib_recv_wr rx_wr, *rx_wr_fail;
struct ib_sge sge;
int ret;
memset(&sge, 0, sizeof(struct ib_sge));
sge.addr = isert_conn->login_req_dma;
sge.length = ISER_RX_LOGIN_SIZE;
sge.lkey = isert_conn->conn_mr->lkey;
pr_debug("Setup sge: addr: %llx length: %d 0x%08x\n",
sge.addr, sge.length, sge.lkey);
memset(&rx_wr, 0, sizeof(struct ib_recv_wr));
rx_wr.wr_id = (unsigned long)isert_conn->login_req_buf;
rx_wr.sg_list = &sge;
rx_wr.num_sge = 1;
isert_conn->post_recv_buf_count++;
ret = ib_post_recv(isert_conn->conn_qp, &rx_wr, &rx_wr_fail);
if (ret) {
pr_err("ib_post_recv() failed: %d\n", ret);
isert_conn->post_recv_buf_count
}
pr_debug("ib_post_recv(): returned success >>>>>>>>>>>>>>>>>>>>>>>>\n");
return ret;
}
static int
isert_put_login_tx(struct iscsi_conn *conn, struct iscsi_login *login,
u32 length)
{
struct isert_conn *isert_conn = conn->context;
struct ib_device *ib_dev = isert_conn->conn_cm_id->device;
struct iser_tx_desc *tx_desc = &isert_conn->conn_login_tx_desc;
int ret;
<API key>(isert_conn, NULL, tx_desc);
memcpy(&tx_desc->iscsi_header, &login->rsp[0],
sizeof(struct iscsi_hdr));
isert_init_tx_hdrs(isert_conn, tx_desc);
if (length > 0) {
struct ib_sge *tx_dsg = &tx_desc->tx_sg[1];
<API key>(ib_dev, isert_conn->login_rsp_dma,
length, DMA_TO_DEVICE);
memcpy(isert_conn->login_rsp_buf, login->rsp_buf, length);
<API key>(ib_dev, isert_conn->login_rsp_dma,
length, DMA_TO_DEVICE);
tx_dsg->addr = isert_conn->login_rsp_dma;
tx_dsg->length = length;
tx_dsg->lkey = isert_conn->conn_mr->lkey;
tx_desc->num_sge = 2;
}
if (!login->login_failed) {
if (login->login_complete) {
ret = <API key>(isert_conn);
if (ret)
return ret;
ret = isert_post_recv(isert_conn, ISERT_MIN_POSTED_RX);
if (ret)
return ret;
isert_conn->state = ISER_CONN_UP;
goto post_send;
}
ret = <API key>(isert_conn);
if (ret)
return ret;
}
post_send:
ret = isert_post_send(isert_conn, tx_desc);
if (ret)
return ret;
return 0;
}
static void
isert_rx_login_req(struct iser_rx_desc *rx_desc, int rx_buflen,
struct isert_conn *isert_conn)
{
struct iscsi_conn *conn = isert_conn->conn;
struct iscsi_login *login = conn->conn_login;
int size;
if (!login) {
pr_err("conn->conn_login is NULL\n");
dump_stack();
return;
}
if (login->first_request) {
struct iscsi_login_req *login_req =
(struct iscsi_login_req *)&rx_desc->iscsi_header;
/*
* Setup the initial iscsi_login values from the leading
* login request PDU.
*/
login->leading_connection = (!login_req->tsih) ? 1 : 0;
login->current_stage =
(login_req->flags & <API key>)
>> 2;
login->version_min = login_req->min_version;
login->version_max = login_req->max_version;
memcpy(login->isid, login_req->isid, 6);
login->cmd_sn = be32_to_cpu(login_req->cmdsn);
login->init_task_tag = login_req->itt;
login->initial_exp_statsn = be32_to_cpu(login_req->exp_statsn);
login->cid = be16_to_cpu(login_req->cid);
login->tsih = be16_to_cpu(login_req->tsih);
}
memcpy(&login->req[0], (void *)&rx_desc->iscsi_header, ISCSI_HDR_LEN);
size = min(rx_buflen, MAX_KEY_VALUE_PAIRS);
pr_debug("Using login payload size: %d, rx_buflen: %d MAX_KEY_VALUE_PAIRS: %d\n",
size, rx_buflen, MAX_KEY_VALUE_PAIRS);
memcpy(login->req_buf, &rx_desc->data[0], size);
complete(&isert_conn->conn_login_comp);
}
static void
isert_release_cmd(struct iscsi_cmd *cmd)
{
struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd,
iscsi_cmd);
pr_debug("Entering isert_release_cmd %p >>>>>>>>>>>>>>>.\n", isert_cmd);
kfree(cmd->buf_ptr);
kfree(cmd->tmr_req);
kmem_cache_free(isert_cmd_cache, isert_cmd);
}
static struct iscsi_cmd
*isert_alloc_cmd(struct iscsi_conn *conn, gfp_t gfp)
{
struct isert_conn *isert_conn = (struct isert_conn *)conn->context;
struct isert_cmd *isert_cmd;
isert_cmd = kmem_cache_zalloc(isert_cmd_cache, gfp);
if (!isert_cmd) {
pr_err("Unable to allocate isert_cmd\n");
return NULL;
}
isert_cmd->conn = isert_conn;
isert_cmd->iscsi_cmd.release_cmd = &isert_release_cmd;
return &isert_cmd->iscsi_cmd;
}
static int
<API key>(struct isert_conn *isert_conn,
struct isert_cmd *isert_cmd, struct iser_rx_desc *rx_desc,
unsigned char *buf)
{
struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd;
struct iscsi_conn *conn = isert_conn->conn;
struct iscsi_scsi_req *hdr = (struct iscsi_scsi_req *)buf;
struct scatterlist *sg;
int imm_data, imm_data_len, unsol_data, sg_nents, rc;
bool dump_payload = false;
rc = <API key>(conn, cmd, buf);
if (rc < 0)
return rc;
imm_data = cmd->immediate_data;
imm_data_len = cmd->first_burst_len;
unsol_data = cmd->unsolicited_data;
rc = <API key>(conn, cmd, hdr);
if (rc < 0) {
return 0;
} else if (rc > 0) {
dump_payload = true;
goto sequence_cmd;
}
if (!imm_data)
return 0;
sg = &cmd->se_cmd.t_data_sg[0];
sg_nents = max(1UL, DIV_ROUND_UP(imm_data_len, PAGE_SIZE));
pr_debug("Copying Immediate SG: %p sg_nents: %u from %p imm_data_len: %d\n",
sg, sg_nents, &rx_desc->data[0], imm_data_len);
sg_copy_from_buffer(sg, sg_nents, &rx_desc->data[0], imm_data_len);
cmd->write_data_done += imm_data_len;
if (cmd->write_data_done == cmd->se_cmd.data_length) {
spin_lock_bh(&cmd->istate_lock);
cmd->cmd_flags |= <API key>;
cmd->i_state = <API key>;
spin_unlock_bh(&cmd->istate_lock);
}
sequence_cmd:
rc = iscsit_sequence_cmd(conn, cmd, buf, hdr->cmdsn);
if (!rc && dump_payload == false && unsol_data)
<API key>(cmd);
else if (dump_payload && imm_data)
target_put_sess_cmd(conn->sess->se_sess, &cmd->se_cmd);
return 0;
}
static int
<API key>(struct isert_conn *isert_conn,
struct iser_rx_desc *rx_desc, unsigned char *buf)
{
struct scatterlist *sg_start;
struct iscsi_conn *conn = isert_conn->conn;
struct iscsi_cmd *cmd = NULL;
struct iscsi_data *hdr = (struct iscsi_data *)buf;
u32 unsol_data_len = ntoh24(hdr->dlength);
int rc, sg_nents, sg_off, page_off;
rc = <API key>(conn, buf, &cmd);
if (rc < 0)
return rc;
else if (!cmd)
return 0;
/*
* FIXME: Unexpected unsolicited_data out
*/
if (!cmd->unsolicited_data) {
pr_err("Received unexpected solicited data payload\n");
dump_stack();
return -1;
}
pr_debug("Unsolicited DataOut unsol_data_len: %u, write_data_done: %u, data_length: %u\n",
unsol_data_len, cmd->write_data_done, cmd->se_cmd.data_length);
sg_off = cmd->write_data_done / PAGE_SIZE;
sg_start = &cmd->se_cmd.t_data_sg[sg_off];
sg_nents = max(1UL, DIV_ROUND_UP(unsol_data_len, PAGE_SIZE));
page_off = cmd->write_data_done % PAGE_SIZE;
/*
* FIXME: Non page-aligned unsolicited_data out
*/
if (page_off) {
pr_err("Received unexpected non-page aligned data payload\n");
dump_stack();
return -1;
}
pr_debug("Copying DataOut: sg_start: %p, sg_off: %u sg_nents: %u from %p %u\n",
sg_start, sg_off, sg_nents, &rx_desc->data[0], unsol_data_len);
sg_copy_from_buffer(sg_start, sg_nents, &rx_desc->data[0],
unsol_data_len);
rc = <API key>(cmd, hdr, false);
if (rc < 0)
return rc;
return 0;
}
static int
isert_rx_opcode(struct isert_conn *isert_conn, struct iser_rx_desc *rx_desc,
uint32_t read_stag, uint64_t read_va,
uint32_t write_stag, uint64_t write_va)
{
struct iscsi_hdr *hdr = &rx_desc->iscsi_header;
struct iscsi_conn *conn = isert_conn->conn;
struct iscsi_cmd *cmd;
struct isert_cmd *isert_cmd;
int ret = -EINVAL;
u8 opcode = (hdr->opcode & ISCSI_OPCODE_MASK);
switch (opcode) {
case ISCSI_OP_SCSI_CMD:
cmd = iscsit_allocate_cmd(conn, GFP_KERNEL);
if (!cmd)
break;
isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd);
isert_cmd->read_stag = read_stag;
isert_cmd->read_va = read_va;
isert_cmd->write_stag = write_stag;
isert_cmd->write_va = write_va;
ret = <API key>(isert_conn, isert_cmd,
rx_desc, (unsigned char *)hdr);
break;
case ISCSI_OP_NOOP_OUT:
cmd = iscsit_allocate_cmd(conn, GFP_KERNEL);
if (!cmd)
break;
ret = <API key>(conn, cmd, (unsigned char *)hdr);
break;
case <API key>:
ret = <API key>(isert_conn, rx_desc,
(unsigned char *)hdr);
break;
case <API key>:
cmd = iscsit_allocate_cmd(conn, GFP_KERNEL);
if (!cmd)
break;
ret = <API key>(conn, cmd,
(unsigned char *)hdr);
break;
case ISCSI_OP_LOGOUT:
cmd = iscsit_allocate_cmd(conn, GFP_KERNEL);
if (!cmd)
break;
ret = <API key>(conn, cmd, (unsigned char *)hdr);
if (ret > 0)
<API key>(&conn->conn_logout_comp,
<API key> *
HZ);
break;
default:
pr_err("Got unknown iSCSI OpCode: 0x%02x\n", opcode);
dump_stack();
break;
}
return ret;
}
static void
isert_rx_do_work(struct iser_rx_desc *rx_desc, struct isert_conn *isert_conn)
{
struct iser_hdr *iser_hdr = &rx_desc->iser_header;
uint64_t read_va = 0, write_va = 0;
uint32_t read_stag = 0, write_stag = 0;
int rc;
switch (iser_hdr->flags & 0xF0) {
case ISCSI_CTRL:
if (iser_hdr->flags & ISER_RSV) {
read_stag = be32_to_cpu(iser_hdr->read_stag);
read_va = be64_to_cpu(iser_hdr->read_va);
pr_debug("ISER_RSV: read_stag: 0x%08x read_va: 0x%16llx\n",
read_stag, (unsigned long long)read_va);
}
if (iser_hdr->flags & ISER_WSV) {
write_stag = be32_to_cpu(iser_hdr->write_stag);
write_va = be64_to_cpu(iser_hdr->write_va);
pr_debug("ISER_WSV: write__stag: 0x%08x write_va: 0x%16llx\n",
write_stag, (unsigned long long)write_va);
}
pr_debug("ISER ISCSI_CTRL PDU\n");
break;
case ISER_HELLO:
pr_err("iSER Hello message\n");
break;
default:
pr_warn("Unknown iSER hdr flags: 0x%02x\n", iser_hdr->flags);
break;
}
rc = isert_rx_opcode(isert_conn, rx_desc,
read_stag, read_va, write_stag, write_va);
}
static void
isert_rx_completion(struct iser_rx_desc *desc, struct isert_conn *isert_conn,
unsigned long xfer_len)
{
struct ib_device *ib_dev = isert_conn->conn_cm_id->device;
struct iscsi_hdr *hdr;
u64 rx_dma;
int rx_buflen, outstanding;
if ((char *)desc == isert_conn->login_req_buf) {
rx_dma = isert_conn->login_req_dma;
rx_buflen = ISER_RX_LOGIN_SIZE;
pr_debug("ISER login_buf: Using rx_dma: 0x%llx, rx_buflen: %d\n",
rx_dma, rx_buflen);
} else {
rx_dma = desc->dma_addr;
rx_buflen = <API key>;
pr_debug("ISER req_buf: Using rx_dma: 0x%llx, rx_buflen: %d\n",
rx_dma, rx_buflen);
}
<API key>(ib_dev, rx_dma, rx_buflen, DMA_FROM_DEVICE);
hdr = &desc->iscsi_header;
pr_debug("iSCSI opcode: 0x%02x, ITT: 0x%08x, flags: 0x%02x dlen: %d\n",
hdr->opcode, hdr->itt, hdr->flags,
(int)(xfer_len - ISER_HEADERS_LEN));
if ((char *)desc == isert_conn->login_req_buf)
isert_rx_login_req(desc, xfer_len - ISER_HEADERS_LEN,
isert_conn);
else
isert_rx_do_work(desc, isert_conn);
<API key>(ib_dev, rx_dma, rx_buflen,
DMA_FROM_DEVICE);
isert_conn->post_recv_buf_count
pr_debug("iSERT: Decremented post_recv_buf_count: %d\n",
isert_conn->post_recv_buf_count);
if ((char *)desc == isert_conn->login_req_buf)
return;
outstanding = isert_conn->post_recv_buf_count;
if (outstanding + ISERT_MIN_POSTED_RX <= <API key>) {
int err, count = min(<API key> - outstanding,
ISERT_MIN_POSTED_RX);
err = isert_post_recv(isert_conn, count);
if (err) {
pr_err("isert_post_recv() count: %d failed, %d\n",
count, err);
}
}
}
static void
isert_unmap_cmd(struct isert_cmd *isert_cmd, struct isert_conn *isert_conn)
{
struct isert_rdma_wr *wr = &isert_cmd->rdma_wr;
struct ib_device *ib_dev = isert_conn->conn_cm_id->device;
pr_debug("isert_unmap_cmd >>>>>>>>>>>>>>>>>>>>>>>\n");
if (wr->sge) {
ib_dma_unmap_sg(ib_dev, wr->sge, wr->num_sge, DMA_TO_DEVICE);
wr->sge = NULL;
}
kfree(wr->send_wr);
wr->send_wr = NULL;
kfree(isert_cmd->ib_sge);
isert_cmd->ib_sge = NULL;
}
static void
isert_put_cmd(struct isert_cmd *isert_cmd, bool comp_err)
{
struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd;
struct isert_conn *isert_conn = isert_cmd->conn;
struct iscsi_conn *conn = isert_conn->conn;
pr_debug("Entering isert_put_cmd: %p\n", isert_cmd);
switch (cmd->iscsi_opcode) {
case ISCSI_OP_SCSI_CMD:
spin_lock_bh(&conn->cmd_lock);
if (!list_empty(&cmd->i_conn_node))
list_del_init(&cmd->i_conn_node);
spin_unlock_bh(&conn->cmd_lock);
if (cmd->data_direction == DMA_TO_DEVICE) {
<API key>(cmd);
/*
* Check for special case during comp_err where
* WRITE_PENDING has been handed off from core,
* but requires an extra target_put_sess_cmd()
* before <API key>() below.
*/
if (comp_err &&
cmd->se_cmd.t_state == <API key>) {
struct se_cmd *se_cmd = &cmd->se_cmd;
target_put_sess_cmd(se_cmd->se_sess, se_cmd);
}
}
isert_unmap_cmd(isert_cmd, isert_conn);
<API key>(&cmd->se_cmd, 0);
break;
case <API key>:
spin_lock_bh(&conn->cmd_lock);
if (!list_empty(&cmd->i_conn_node))
list_del_init(&cmd->i_conn_node);
spin_unlock_bh(&conn->cmd_lock);
<API key>(&cmd->se_cmd, 0);
break;
case ISCSI_OP_REJECT:
case ISCSI_OP_NOOP_OUT:
spin_lock_bh(&conn->cmd_lock);
if (!list_empty(&cmd->i_conn_node))
list_del_init(&cmd->i_conn_node);
spin_unlock_bh(&conn->cmd_lock);
/*
* Handle special case for REJECT when iscsi_add_reject*() has
* overwritten the original iscsi_opcode assignment, and the
* associated cmd->se_cmd needs to be released.
*/
if (cmd->se_cmd.se_tfo != NULL) {
pr_debug("Calling <API key> from"
" isert_put_cmd for 0x%02x\n",
cmd->iscsi_opcode);
<API key>(&cmd->se_cmd, 0);
break;
}
/*
* Fall-through
*/
default:
isert_release_cmd(cmd);
break;
}
}
static void
isert_unmap_tx_desc(struct iser_tx_desc *tx_desc, struct ib_device *ib_dev)
{
if (tx_desc->dma_addr != 0) {
pr_debug("Calling ib_dma_unmap_single for tx_desc->dma_addr\n");
ib_dma_unmap_single(ib_dev, tx_desc->dma_addr,
ISER_HEADERS_LEN, DMA_TO_DEVICE);
tx_desc->dma_addr = 0;
}
}
static void
<API key>(struct iser_tx_desc *tx_desc, struct isert_cmd *isert_cmd,
struct ib_device *ib_dev, bool comp_err)
{
if (isert_cmd->sense_buf_dma != 0) {
pr_debug("Calling ib_dma_unmap_single for isert_cmd->sense_buf_dma\n");
ib_dma_unmap_single(ib_dev, isert_cmd->sense_buf_dma,
isert_cmd->sense_buf_len, DMA_TO_DEVICE);
isert_cmd->sense_buf_dma = 0;
}
isert_unmap_tx_desc(tx_desc, ib_dev);
isert_put_cmd(isert_cmd, comp_err);
}
static void
<API key>(struct iser_tx_desc *tx_desc,
struct isert_cmd *isert_cmd)
{
struct isert_rdma_wr *wr = &isert_cmd->rdma_wr;
struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd;
struct se_cmd *se_cmd = &cmd->se_cmd;
struct ib_device *ib_dev = isert_cmd->conn->conn_cm_id->device;
<API key>(cmd);
if (wr->sge) {
pr_debug("<API key>: Unmapping wr->sge from t_data_sg\n");
ib_dma_unmap_sg(ib_dev, wr->sge, wr->num_sge, DMA_TO_DEVICE);
wr->sge = NULL;
}
if (isert_cmd->ib_sge) {
pr_debug("<API key>: Freeing isert_cmd->ib_sge\n");
kfree(isert_cmd->ib_sge);
isert_cmd->ib_sge = NULL;
}
cmd->write_data_done = se_cmd->data_length;
wr->send_wr_num = 0;
pr_debug("<API key>, calling target_execute_cmd\n");
spin_lock_bh(&cmd->istate_lock);
cmd->cmd_flags |= <API key>;
cmd->i_state = <API key>;
spin_unlock_bh(&cmd->istate_lock);
target_execute_cmd(se_cmd);
}
static void
<API key>(struct work_struct *work)
{
struct isert_cmd *isert_cmd = container_of(work,
struct isert_cmd, comp_work);
struct isert_conn *isert_conn = isert_cmd->conn;
struct ib_device *ib_dev = isert_conn->conn_cm_id->device;
struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd;
switch (cmd->i_state) {
case <API key>:
pr_debug("Calling <API key> >>>>>>>>>>>>>>>>>\n");
atomic_dec(&isert_conn->post_send_buf_count);
<API key>(cmd, cmd->conn);
cmd->i_state = ISTATE_SENT_STATUS;
<API key>(&isert_cmd->tx_desc, isert_cmd, ib_dev, false);
break;
case ISTATE_SEND_REJECT:
pr_debug("Got <API key> ISTATE_SEND_REJECT: >>>\n");
atomic_dec(&isert_conn->post_send_buf_count);
cmd->i_state = ISTATE_SENT_STATUS;
<API key>(&isert_cmd->tx_desc, isert_cmd, ib_dev, false);
break;
case <API key>:
pr_debug("Calling <API key> >>>>>>>>>>>>>>\n");
atomic_dec(&isert_conn->post_send_buf_count);
<API key>(cmd, cmd->conn);
break;
default:
pr_err("Unknown do_control_comp i_state %d\n", cmd->i_state);
dump_stack();
break;
}
}
static void
<API key>(struct iser_tx_desc *tx_desc,
struct isert_cmd *isert_cmd,
struct isert_conn *isert_conn,
struct ib_device *ib_dev)
{
struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd;
struct isert_rdma_wr *wr = &isert_cmd->rdma_wr;
if (cmd->i_state == <API key> ||
cmd->i_state == <API key> ||
cmd->i_state == ISTATE_SEND_REJECT) {
isert_unmap_tx_desc(tx_desc, ib_dev);
INIT_WORK(&isert_cmd->comp_work, <API key>);
queue_work(isert_comp_wq, &isert_cmd->comp_work);
return;
}
atomic_sub(wr->send_wr_num + 1, &isert_conn->post_send_buf_count);
cmd->i_state = ISTATE_SENT_STATUS;
<API key>(tx_desc, isert_cmd, ib_dev, false);
}
static void
<API key>(struct iser_tx_desc *tx_desc,
struct isert_conn *isert_conn)
{
struct ib_device *ib_dev = isert_conn->conn_cm_id->device;
struct isert_cmd *isert_cmd = tx_desc->isert_cmd;
struct isert_rdma_wr *wr;
if (!isert_cmd) {
atomic_dec(&isert_conn->post_send_buf_count);
isert_unmap_tx_desc(tx_desc, ib_dev);
return;
}
wr = &isert_cmd->rdma_wr;
switch (wr->iser_ib_op) {
case ISER_IB_RECV:
pr_err("<API key>: Got ISER_IB_RECV\n");
dump_stack();
break;
case ISER_IB_SEND:
pr_debug("<API key>: Got ISER_IB_SEND\n");
<API key>(tx_desc, isert_cmd,
isert_conn, ib_dev);
break;
case ISER_IB_RDMA_WRITE:
pr_err("<API key>: Got ISER_IB_RDMA_WRITE\n");
dump_stack();
break;
case ISER_IB_RDMA_READ:
pr_debug("<API key>: Got ISER_IB_RDMA_READ:\n");
atomic_sub(wr->send_wr_num, &isert_conn->post_send_buf_count);
<API key>(tx_desc, isert_cmd);
break;
default:
pr_err("Unknown wr->iser_ib_op: 0x%02x\n", wr->iser_ib_op);
dump_stack();
break;
}
}
static void
<API key>(struct iser_tx_desc *tx_desc, struct isert_conn *isert_conn)
{
struct ib_device *ib_dev = isert_conn->conn_cm_id->device;
struct isert_cmd *isert_cmd = tx_desc->isert_cmd;
if (!isert_cmd)
isert_unmap_tx_desc(tx_desc, ib_dev);
else
<API key>(tx_desc, isert_cmd, ib_dev, true);
}
static void
<API key>(struct isert_conn *isert_conn)
{
struct iscsi_conn *conn = isert_conn->conn;
if (isert_conn->post_recv_buf_count)
return;
if (conn->sess) {
<API key>(conn->sess->se_sess);
<API key>(conn->sess->se_sess);
}
while (atomic_read(&isert_conn->post_send_buf_count))
msleep(3000);
mutex_lock(&isert_conn->conn_mutex);
isert_conn->state = ISER_CONN_DOWN;
mutex_unlock(&isert_conn->conn_mutex);
<API key>(isert_conn->conn, 0);
complete(&isert_conn->conn_wait_comp_err);
}
static void
isert_cq_tx_work(struct work_struct *work)
{
struct isert_cq_desc *cq_desc = container_of(work,
struct isert_cq_desc, cq_tx_work);
struct isert_device *device = cq_desc->device;
int cq_index = cq_desc->cq_index;
struct ib_cq *tx_cq = device->dev_tx_cq[cq_index];
struct isert_conn *isert_conn;
struct iser_tx_desc *tx_desc;
struct ib_wc wc;
while (ib_poll_cq(tx_cq, 1, &wc) == 1) {
tx_desc = (struct iser_tx_desc *)(unsigned long)wc.wr_id;
isert_conn = wc.qp->qp_context;
if (wc.status == IB_WC_SUCCESS) {
<API key>(tx_desc, isert_conn);
} else {
pr_debug("TX wc.status != IB_WC_SUCCESS >>>>>>>>>>>>>>\n");
pr_debug("TX wc.status: 0x%08x\n", wc.status);
atomic_dec(&isert_conn->post_send_buf_count);
<API key>(tx_desc, isert_conn);
}
}
ib_req_notify_cq(tx_cq, IB_CQ_NEXT_COMP);
}
static void
<API key>(struct ib_cq *cq, void *context)
{
struct isert_cq_desc *cq_desc = (struct isert_cq_desc *)context;
INIT_WORK(&cq_desc->cq_tx_work, isert_cq_tx_work);
queue_work(isert_comp_wq, &cq_desc->cq_tx_work);
}
static void
isert_cq_rx_work(struct work_struct *work)
{
struct isert_cq_desc *cq_desc = container_of(work,
struct isert_cq_desc, cq_rx_work);
struct isert_device *device = cq_desc->device;
int cq_index = cq_desc->cq_index;
struct ib_cq *rx_cq = device->dev_rx_cq[cq_index];
struct isert_conn *isert_conn;
struct iser_rx_desc *rx_desc;
struct ib_wc wc;
unsigned long xfer_len;
while (ib_poll_cq(rx_cq, 1, &wc) == 1) {
rx_desc = (struct iser_rx_desc *)(unsigned long)wc.wr_id;
isert_conn = wc.qp->qp_context;
if (wc.status == IB_WC_SUCCESS) {
xfer_len = (unsigned long)wc.byte_len;
isert_rx_completion(rx_desc, isert_conn, xfer_len);
} else {
pr_debug("RX wc.status != IB_WC_SUCCESS >>>>>>>>>>>>>>\n");
if (wc.status != IB_WC_WR_FLUSH_ERR)
pr_debug("RX wc.status: 0x%08x\n", wc.status);
isert_conn->post_recv_buf_count
<API key>(isert_conn);
}
}
ib_req_notify_cq(rx_cq, IB_CQ_NEXT_COMP);
}
static void
<API key>(struct ib_cq *cq, void *context)
{
struct isert_cq_desc *cq_desc = (struct isert_cq_desc *)context;
INIT_WORK(&cq_desc->cq_rx_work, isert_cq_rx_work);
queue_work(isert_rx_wq, &cq_desc->cq_rx_work);
}
static int
isert_post_response(struct isert_conn *isert_conn, struct isert_cmd *isert_cmd)
{
struct ib_send_wr *wr_failed;
int ret;
atomic_inc(&isert_conn->post_send_buf_count);
ret = ib_post_send(isert_conn->conn_qp, &isert_cmd->tx_desc.send_wr,
&wr_failed);
if (ret) {
pr_err("ib_post_send failed with %d\n", ret);
atomic_dec(&isert_conn->post_send_buf_count);
return ret;
}
return ret;
}
static int
isert_put_response(struct iscsi_conn *conn, struct iscsi_cmd *cmd)
{
struct isert_cmd *isert_cmd = container_of(cmd,
struct isert_cmd, iscsi_cmd);
struct isert_conn *isert_conn = (struct isert_conn *)conn->context;
struct ib_send_wr *send_wr = &isert_cmd->tx_desc.send_wr;
struct iscsi_scsi_rsp *hdr = (struct iscsi_scsi_rsp *)
&isert_cmd->tx_desc.iscsi_header;
<API key>(isert_conn, isert_cmd, &isert_cmd->tx_desc);
<API key>(cmd, conn, true, hdr);
isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc);
/*
* Attach SENSE DATA payload to iSCSI Response PDU
*/
if (cmd->se_cmd.sense_buffer &&
((cmd->se_cmd.se_cmd_flags & <API key>) ||
(cmd->se_cmd.se_cmd_flags & <API key>))) {
struct ib_device *ib_dev = isert_conn->conn_cm_id->device;
struct ib_sge *tx_dsg = &isert_cmd->tx_desc.tx_sg[1];
u32 padding, sense_len;
put_unaligned_be16(cmd->se_cmd.scsi_sense_length,
cmd->sense_buffer);
cmd->se_cmd.scsi_sense_length += sizeof(__be16);
padding = -(cmd->se_cmd.scsi_sense_length) & 3;
hton24(hdr->dlength, (u32)cmd->se_cmd.scsi_sense_length);
sense_len = cmd->se_cmd.scsi_sense_length + padding;
isert_cmd->sense_buf_dma = ib_dma_map_single(ib_dev,
(void *)cmd->sense_buffer, sense_len,
DMA_TO_DEVICE);
isert_cmd->sense_buf_len = sense_len;
tx_dsg->addr = isert_cmd->sense_buf_dma;
tx_dsg->length = sense_len;
tx_dsg->lkey = isert_conn->conn_mr->lkey;
isert_cmd->tx_desc.num_sge = 2;
}
isert_init_send_wr(isert_cmd, send_wr);
pr_debug("Posting SCSI Response IB_WR_SEND >>>>>>>>>>>>>>>>>>>>>>\n");
return isert_post_response(isert_conn, isert_cmd);
}
static int
isert_put_nopin(struct iscsi_cmd *cmd, struct iscsi_conn *conn,
bool nopout_response)
{
struct isert_cmd *isert_cmd = container_of(cmd,
struct isert_cmd, iscsi_cmd);
struct isert_conn *isert_conn = (struct isert_conn *)conn->context;
struct ib_send_wr *send_wr = &isert_cmd->tx_desc.send_wr;
<API key>(isert_conn, isert_cmd, &isert_cmd->tx_desc);
<API key>(cmd, conn, (struct iscsi_nopin *)
&isert_cmd->tx_desc.iscsi_header,
nopout_response);
isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc);
isert_init_send_wr(isert_cmd, send_wr);
pr_debug("Posting NOPIN Reponse IB_WR_SEND >>>>>>>>>>>>>>>>>>>>>>\n");
return isert_post_response(isert_conn, isert_cmd);
}
static int
<API key>(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
{
struct isert_cmd *isert_cmd = container_of(cmd,
struct isert_cmd, iscsi_cmd);
struct isert_conn *isert_conn = (struct isert_conn *)conn->context;
struct ib_send_wr *send_wr = &isert_cmd->tx_desc.send_wr;
<API key>(isert_conn, isert_cmd, &isert_cmd->tx_desc);
<API key>(cmd, conn, (struct iscsi_logout_rsp *)
&isert_cmd->tx_desc.iscsi_header);
isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc);
isert_init_send_wr(isert_cmd, send_wr);
pr_debug("Posting Logout Response IB_WR_SEND >>>>>>>>>>>>>>>>>>>>>>\n");
return isert_post_response(isert_conn, isert_cmd);
}
static int
isert_put_tm_rsp(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
{
struct isert_cmd *isert_cmd = container_of(cmd,
struct isert_cmd, iscsi_cmd);
struct isert_conn *isert_conn = (struct isert_conn *)conn->context;
struct ib_send_wr *send_wr = &isert_cmd->tx_desc.send_wr;
<API key>(isert_conn, isert_cmd, &isert_cmd->tx_desc);
<API key>(cmd, conn, (struct iscsi_tm_rsp *)
&isert_cmd->tx_desc.iscsi_header);
isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc);
isert_init_send_wr(isert_cmd, send_wr);
pr_debug("Posting Task Management Response IB_WR_SEND >>>>>>>>>>>>>>>>>>>>>>\n");
return isert_post_response(isert_conn, isert_cmd);
}
static int
isert_put_reject(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
{
struct isert_cmd *isert_cmd = container_of(cmd,
struct isert_cmd, iscsi_cmd);
struct isert_conn *isert_conn = (struct isert_conn *)conn->context;
struct ib_send_wr *send_wr = &isert_cmd->tx_desc.send_wr;
struct ib_device *ib_dev = isert_conn->conn_cm_id->device;
struct ib_sge *tx_dsg = &isert_cmd->tx_desc.tx_sg[1];
struct iscsi_reject *hdr =
(struct iscsi_reject *)&isert_cmd->tx_desc.iscsi_header;
<API key>(isert_conn, isert_cmd, &isert_cmd->tx_desc);
iscsit_build_reject(cmd, conn, hdr);
isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc);
hton24(hdr->dlength, ISCSI_HDR_LEN);
isert_cmd->sense_buf_dma = ib_dma_map_single(ib_dev,
(void *)cmd->buf_ptr, ISCSI_HDR_LEN,
DMA_TO_DEVICE);
isert_cmd->sense_buf_len = ISCSI_HDR_LEN;
tx_dsg->addr = isert_cmd->sense_buf_dma;
tx_dsg->length = ISCSI_HDR_LEN;
tx_dsg->lkey = isert_conn->conn_mr->lkey;
isert_cmd->tx_desc.num_sge = 2;
isert_init_send_wr(isert_cmd, send_wr);
pr_debug("Posting Reject IB_WR_SEND >>>>>>>>>>>>>>>>>>>>>>\n");
return isert_post_response(isert_conn, isert_cmd);
}
static int
isert_build_rdma_wr(struct isert_conn *isert_conn, struct isert_cmd *isert_cmd,
struct ib_sge *ib_sge, struct ib_send_wr *send_wr,
u32 data_left, u32 offset)
{
struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd;
struct scatterlist *sg_start, *tmp_sg;
struct ib_device *ib_dev = isert_conn->conn_cm_id->device;
u32 sg_off, page_off;
int i = 0, sg_nents;
sg_off = offset / PAGE_SIZE;
sg_start = &cmd->se_cmd.t_data_sg[sg_off];
sg_nents = min(cmd->se_cmd.t_data_nents - sg_off, isert_conn->max_sge);
page_off = offset % PAGE_SIZE;
send_wr->sg_list = ib_sge;
send_wr->num_sge = sg_nents;
send_wr->wr_id = (unsigned long)&isert_cmd->tx_desc;
/*
* Perform mapping of TCM scatterlist memory ib_sge dma_addr.
*/
for_each_sg(sg_start, tmp_sg, sg_nents, i) {
pr_debug("ISER RDMA from SGL dma_addr: 0x%16llx dma_len: %u, page_off: %u\n",
(unsigned long long)tmp_sg->dma_address,
tmp_sg->length, page_off);
ib_sge->addr = ib_sg_dma_address(ib_dev, tmp_sg) + page_off;
ib_sge->length = min_t(u32, data_left,
ib_sg_dma_len(ib_dev, tmp_sg) - page_off);
ib_sge->lkey = isert_conn->conn_mr->lkey;
pr_debug("RDMA ib_sge: addr: 0x%16llx length: %u\n",
ib_sge->addr, ib_sge->length);
page_off = 0;
data_left -= ib_sge->length;
ib_sge++;
pr_debug("Incrementing ib_sge pointer to %p\n", ib_sge);
}
pr_debug("Set outgoing sg_list: %p num_sg: %u from TCM SGLs\n",
send_wr->sg_list, send_wr->num_sge);
return sg_nents;
}
static int
isert_put_datain(struct iscsi_conn *conn, struct iscsi_cmd *cmd)
{
struct se_cmd *se_cmd = &cmd->se_cmd;
struct isert_cmd *isert_cmd = container_of(cmd,
struct isert_cmd, iscsi_cmd);
struct isert_rdma_wr *wr = &isert_cmd->rdma_wr;
struct isert_conn *isert_conn = (struct isert_conn *)conn->context;
struct ib_send_wr *wr_failed, *send_wr;
struct ib_device *ib_dev = isert_conn->conn_cm_id->device;
struct ib_sge *ib_sge;
struct scatterlist *sg;
u32 offset = 0, data_len, data_left, rdma_write_max;
int rc, ret = 0, count, sg_nents, i, ib_sge_cnt;
pr_debug("RDMA_WRITE: data_length: %u\n", se_cmd->data_length);
sg = &se_cmd->t_data_sg[0];
sg_nents = se_cmd->t_data_nents;
count = ib_dma_map_sg(ib_dev, sg, sg_nents, DMA_TO_DEVICE);
if (unlikely(!count)) {
pr_err("Unable to map put_datain SGs\n");
return -EINVAL;
}
wr->sge = sg;
wr->num_sge = sg_nents;
pr_debug("Mapped IB count: %u sg: %p sg_nents: %u for RDMA_WRITE\n",
count, sg, sg_nents);
ib_sge = kzalloc(sizeof(struct ib_sge) * sg_nents, GFP_KERNEL);
if (!ib_sge) {
pr_warn("Unable to allocate datain ib_sge\n");
ret = -ENOMEM;
goto unmap_sg;
}
isert_cmd->ib_sge = ib_sge;
pr_debug("Allocated ib_sge: %p from t_data_ents: %d for RDMA_WRITE\n",
ib_sge, se_cmd->t_data_nents);
wr->send_wr_num = DIV_ROUND_UP(sg_nents, isert_conn->max_sge);
wr->send_wr = kzalloc(sizeof(struct ib_send_wr) * wr->send_wr_num,
GFP_KERNEL);
if (!wr->send_wr) {
pr_err("Unable to allocate wr->send_wr\n");
ret = -ENOMEM;
goto unmap_sg;
}
pr_debug("Allocated wr->send_wr: %p wr->send_wr_num: %u\n",
wr->send_wr, wr->send_wr_num);
<API key>(cmd, conn->sess);
cmd->stat_sn = conn->stat_sn++;
wr->isert_cmd = isert_cmd;
rdma_write_max = isert_conn->max_sge * PAGE_SIZE;
data_left = se_cmd->data_length;
for (i = 0; i < wr->send_wr_num; i++) {
send_wr = &isert_cmd->rdma_wr.send_wr[i];
data_len = min(data_left, rdma_write_max);
send_wr->opcode = IB_WR_RDMA_WRITE;
send_wr->send_flags = 0;
send_wr->wr.rdma.remote_addr = isert_cmd->read_va + offset;
send_wr->wr.rdma.rkey = isert_cmd->read_stag;
ib_sge_cnt = isert_build_rdma_wr(isert_conn, isert_cmd, ib_sge,
send_wr, data_len, offset);
ib_sge += ib_sge_cnt;
if (i + 1 == wr->send_wr_num)
send_wr->next = &isert_cmd->tx_desc.send_wr;
else
send_wr->next = &wr->send_wr[i + 1];
offset += data_len;
data_left -= data_len;
}
/*
* Build isert_conn->tx_desc for iSCSI response PDU and attach
*/
<API key>(isert_conn, isert_cmd, &isert_cmd->tx_desc);
<API key>(cmd, conn, false, (struct iscsi_scsi_rsp *)
&isert_cmd->tx_desc.iscsi_header);
isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc);
isert_init_send_wr(isert_cmd, &isert_cmd->tx_desc.send_wr);
atomic_add(wr->send_wr_num + 1, &isert_conn->post_send_buf_count);
rc = ib_post_send(isert_conn->conn_qp, wr->send_wr, &wr_failed);
if (rc) {
pr_warn("ib_post_send() failed for IB_WR_RDMA_WRITE\n");
atomic_sub(wr->send_wr_num + 1, &isert_conn->post_send_buf_count);
}
pr_debug("Posted RDMA_WRITE + Response for iSER Data READ\n");
return 1;
unmap_sg:
ib_dma_unmap_sg(ib_dev, sg, sg_nents, DMA_TO_DEVICE);
return ret;
}
static int
isert_get_dataout(struct iscsi_conn *conn, struct iscsi_cmd *cmd, bool recovery)
{
struct se_cmd *se_cmd = &cmd->se_cmd;
struct isert_cmd *isert_cmd = container_of(cmd,
struct isert_cmd, iscsi_cmd);
struct isert_rdma_wr *wr = &isert_cmd->rdma_wr;
struct isert_conn *isert_conn = (struct isert_conn *)conn->context;
struct ib_send_wr *wr_failed, *send_wr;
struct ib_sge *ib_sge;
struct ib_device *ib_dev = isert_conn->conn_cm_id->device;
struct scatterlist *sg_start;
u32 sg_off, sg_nents, page_off, va_offset = 0;
u32 offset = 0, data_len, data_left, rdma_write_max;
int rc, ret = 0, count, i, ib_sge_cnt;
pr_debug("RDMA_READ: data_length: %u write_data_done: %u\n",
se_cmd->data_length, cmd->write_data_done);
sg_off = cmd->write_data_done / PAGE_SIZE;
sg_start = &cmd->se_cmd.t_data_sg[sg_off];
page_off = cmd->write_data_done % PAGE_SIZE;
pr_debug("RDMA_READ: sg_off: %d, sg_start: %p page_off: %d\n",
sg_off, sg_start, page_off);
data_left = se_cmd->data_length - cmd->write_data_done;
sg_nents = se_cmd->t_data_nents - sg_off;
pr_debug("RDMA_READ: data_left: %d, sg_nents: %d\n",
data_left, sg_nents);
count = ib_dma_map_sg(ib_dev, sg_start, sg_nents, DMA_FROM_DEVICE);
if (unlikely(!count)) {
pr_err("Unable to map get_dataout SGs\n");
return -EINVAL;
}
wr->sge = sg_start;
wr->num_sge = sg_nents;
pr_debug("Mapped IB count: %u sg_start: %p sg_nents: %u for RDMA_READ\n",
count, sg_start, sg_nents);
ib_sge = kzalloc(sizeof(struct ib_sge) * sg_nents, GFP_KERNEL);
if (!ib_sge) {
pr_warn("Unable to allocate dataout ib_sge\n");
ret = -ENOMEM;
goto unmap_sg;
}
isert_cmd->ib_sge = ib_sge;
pr_debug("Using ib_sge: %p from sg_ents: %d for RDMA_READ\n",
ib_sge, sg_nents);
wr->send_wr_num = DIV_ROUND_UP(sg_nents, isert_conn->max_sge);
wr->send_wr = kzalloc(sizeof(struct ib_send_wr) * wr->send_wr_num,
GFP_KERNEL);
if (!wr->send_wr) {
pr_debug("Unable to allocate wr->send_wr\n");
ret = -ENOMEM;
goto unmap_sg;
}
pr_debug("Allocated wr->send_wr: %p wr->send_wr_num: %u\n",
wr->send_wr, wr->send_wr_num);
isert_cmd->tx_desc.isert_cmd = isert_cmd;
wr->iser_ib_op = ISER_IB_RDMA_READ;
wr->isert_cmd = isert_cmd;
rdma_write_max = isert_conn->max_sge * PAGE_SIZE;
offset = cmd->write_data_done;
for (i = 0; i < wr->send_wr_num; i++) {
send_wr = &isert_cmd->rdma_wr.send_wr[i];
data_len = min(data_left, rdma_write_max);
send_wr->opcode = IB_WR_RDMA_READ;
send_wr->wr.rdma.remote_addr = isert_cmd->write_va + va_offset;
send_wr->wr.rdma.rkey = isert_cmd->write_stag;
ib_sge_cnt = isert_build_rdma_wr(isert_conn, isert_cmd, ib_sge,
send_wr, data_len, offset);
ib_sge += ib_sge_cnt;
if (i + 1 == wr->send_wr_num)
send_wr->send_flags = IB_SEND_SIGNALED;
else
send_wr->next = &wr->send_wr[i + 1];
offset += data_len;
va_offset += data_len;
data_left -= data_len;
}
atomic_add(wr->send_wr_num, &isert_conn->post_send_buf_count);
rc = ib_post_send(isert_conn->conn_qp, wr->send_wr, &wr_failed);
if (rc) {
pr_warn("ib_post_send() failed for IB_WR_RDMA_READ\n");
atomic_sub(wr->send_wr_num, &isert_conn->post_send_buf_count);
}
pr_debug("Posted RDMA_READ memory for ISER Data WRITE\n");
return 0;
unmap_sg:
ib_dma_unmap_sg(ib_dev, sg_start, sg_nents, DMA_FROM_DEVICE);
return ret;
}
static int
<API key>(struct iscsi_conn *conn, struct iscsi_cmd *cmd, int state)
{
int ret;
switch (state) {
case <API key>:
ret = isert_put_nopin(cmd, conn, false);
break;
default:
pr_err("Unknown immediate state: 0x%02x\n", state);
ret = -EINVAL;
break;
}
return ret;
}
static int
<API key>(struct iscsi_conn *conn, struct iscsi_cmd *cmd, int state)
{
int ret;
switch (state) {
case <API key>:
ret = <API key>(cmd, conn);
if (!ret) {
pr_debug("Returning iSER Logout -EAGAIN\n");
ret = -EAGAIN;
}
break;
case ISTATE_SEND_NOPIN:
ret = isert_put_nopin(cmd, conn, true);
break;
case <API key>:
ret = isert_put_tm_rsp(cmd, conn);
break;
case ISTATE_SEND_REJECT:
ret = isert_put_reject(cmd, conn);
break;
case ISTATE_SEND_STATUS:
/*
* Special case for sending non GOOD SCSI status from TX thread
* context during pre se_cmd excecution failure.
*/
ret = isert_put_response(conn, cmd);
break;
default:
pr_err("Unknown response state: 0x%02x\n", state);
ret = -EINVAL;
break;
}
return ret;
}
struct rdma_cm_id *
isert_setup_id(struct isert_np *isert_np)
{
struct iscsi_np *np = isert_np->np;
struct rdma_cm_id *id;
struct sockaddr *sa;
int ret;
sa = (struct sockaddr *)&np->np_sockaddr;
pr_debug("ksockaddr: %p, sa: %p\n", &np->np_sockaddr, sa);
id = rdma_create_id(isert_cma_handler, isert_np,
RDMA_PS_TCP, IB_QPT_RC);
if (IS_ERR(id)) {
pr_err("rdma_create_id() failed: %ld\n", PTR_ERR(id));
ret = PTR_ERR(id);
goto out;
}
pr_debug("id %p context %p\n", id, id->context);
ret = rdma_bind_addr(id, sa);
if (ret) {
pr_err("rdma_bind_addr() failed: %d\n", ret);
goto out_id;
}
ret = rdma_listen(id, <API key>);
if (ret) {
pr_err("rdma_listen() failed: %d\n", ret);
goto out_id;
}
return id;
out_id:
rdma_destroy_id(id);
out:
return ERR_PTR(ret);
}
static int
isert_setup_np(struct iscsi_np *np,
struct <API key> *ksockaddr)
{
struct isert_np *isert_np;
struct rdma_cm_id *isert_lid;
int ret;
isert_np = kzalloc(sizeof(struct isert_np), GFP_KERNEL);
if (!isert_np) {
pr_err("Unable to allocate struct isert_np\n");
return -ENOMEM;
}
init_waitqueue_head(&isert_np->np_accept_wq);
mutex_init(&isert_np->np_accept_mutex);
INIT_LIST_HEAD(&isert_np->np_accept_list);
init_completion(&isert_np->np_login_comp);
isert_np->np = np;
/*
* Setup the np->np_sockaddr from the passed sockaddr setup
* in <API key>.c code..
*/
memcpy(&np->np_sockaddr, ksockaddr,
sizeof(struct <API key>));
isert_lid = isert_setup_id(isert_np);
if (IS_ERR(isert_lid)) {
ret = PTR_ERR(isert_lid);
goto out;
}
isert_np->np_cm_id = isert_lid;
np->np_context = isert_np;
return 0;
out:
kfree(isert_np);
return ret;
}
static int
<API key>(struct isert_np *isert_np)
{
int empty;
mutex_lock(&isert_np->np_accept_mutex);
empty = list_empty(&isert_np->np_accept_list);
mutex_unlock(&isert_np->np_accept_mutex);
return empty;
}
static int
isert_rdma_accept(struct isert_conn *isert_conn)
{
struct rdma_cm_id *cm_id = isert_conn->conn_cm_id;
struct rdma_conn_param cp;
int ret;
memset(&cp, 0, sizeof(struct rdma_conn_param));
cp.responder_resources = isert_conn->responder_resources;
cp.initiator_depth = isert_conn->initiator_depth;
cp.retry_count = 7;
cp.rnr_retry_count = 7;
pr_debug("Before rdma_accept >>>>>>>>>>>>>>>>>>>>.\n");
ret = rdma_accept(cm_id, &cp);
if (ret) {
pr_err("rdma_accept() failed with: %d\n", ret);
return ret;
}
pr_debug("After rdma_accept >>>>>>>>>>>>>>>>>>>>>.\n");
return 0;
}
static int
isert_get_login_rx(struct iscsi_conn *conn, struct iscsi_login *login)
{
struct isert_conn *isert_conn = (struct isert_conn *)conn->context;
int ret;
pr_debug("isert_get_login_rx before conn_login_comp conn: %p\n", conn);
ret = <API key>(&isert_conn->conn_login_comp);
if (ret)
return ret;
pr_debug("isert_get_login_rx processing login->req: %p\n", login->req);
return 0;
}
static void
isert_set_conn_info(struct iscsi_np *np, struct iscsi_conn *conn,
struct isert_conn *isert_conn)
{
struct rdma_cm_id *cm_id = isert_conn->conn_cm_id;
struct rdma_route *cm_route = &cm_id->route;
struct sockaddr_in *sock_in;
struct sockaddr_in6 *sock_in6;
conn->login_family = np->np_sockaddr.ss_family;
if (np->np_sockaddr.ss_family == AF_INET6) {
sock_in6 = (struct sockaddr_in6 *)&cm_route->addr.dst_addr;
snprintf(conn->login_ip, sizeof(conn->login_ip), "%pI6c",
&sock_in6->sin6_addr.in6_u);
conn->login_port = ntohs(sock_in6->sin6_port);
sock_in6 = (struct sockaddr_in6 *)&cm_route->addr.src_addr;
snprintf(conn->local_ip, sizeof(conn->local_ip), "%pI6c",
&sock_in6->sin6_addr.in6_u);
conn->local_port = ntohs(sock_in6->sin6_port);
} else {
sock_in = (struct sockaddr_in *)&cm_route->addr.dst_addr;
sprintf(conn->login_ip, "%pI4",
&sock_in->sin_addr.s_addr);
conn->login_port = ntohs(sock_in->sin_port);
sock_in = (struct sockaddr_in *)&cm_route->addr.src_addr;
sprintf(conn->local_ip, "%pI4",
&sock_in->sin_addr.s_addr);
conn->local_port = ntohs(sock_in->sin_port);
}
}
static int
isert_accept_np(struct iscsi_np *np, struct iscsi_conn *conn)
{
struct isert_np *isert_np = (struct isert_np *)np->np_context;
struct isert_conn *isert_conn;
int max_accept = 0, ret;
accept_wait:
ret = <API key>(isert_np->np_accept_wq,
!<API key>(isert_np) ||
np->np_thread_state == <API key>);
if (max_accept > 5)
return -ENODEV;
spin_lock_bh(&np->np_thread_lock);
if (np->np_thread_state >= <API key>) {
spin_unlock_bh(&np->np_thread_lock);
pr_debug("np_thread_state %d for isert_accept_np\n",
np->np_thread_state);
/**
* No point in stalling here when np_thread
* is in state RESET/SHUTDOWN/EXIT - bail
**/
return -ENODEV;
}
spin_unlock_bh(&np->np_thread_lock);
mutex_lock(&isert_np->np_accept_mutex);
if (list_empty(&isert_np->np_accept_list)) {
mutex_unlock(&isert_np->np_accept_mutex);
max_accept++;
goto accept_wait;
}
isert_conn = list_first_entry(&isert_np->np_accept_list,
struct isert_conn, conn_accept_node);
list_del_init(&isert_conn->conn_accept_node);
mutex_unlock(&isert_np->np_accept_mutex);
conn->context = isert_conn;
isert_conn->conn = conn;
max_accept = 0;
ret = <API key>(isert_conn);
if (ret)
return ret;
ret = isert_rdma_accept(isert_conn);
if (ret)
return ret;
isert_set_conn_info(np, conn, isert_conn);
pr_debug("Processing isert_accept_np: isert_conn: %p\n", isert_conn);
return 0;
}
static void
isert_free_np(struct iscsi_np *np)
{
struct isert_np *isert_np = (struct isert_np *)np->np_context;
if (isert_np->np_cm_id)
rdma_destroy_id(isert_np->np_cm_id);
np->np_context = NULL;
kfree(isert_np);
}
static void isert_wait_conn(struct iscsi_conn *conn)
{
struct isert_conn *isert_conn = conn->context;
pr_debug("isert_wait_conn: Starting \n");
mutex_lock(&isert_conn->conn_mutex);
if (isert_conn->conn_cm_id) {
pr_debug("Calling rdma_disconnect from isert_wait_conn\n");
rdma_disconnect(isert_conn->conn_cm_id);
}
/*
* Only wait for conn_wait_comp_err if the isert_conn made it
* into full feature phase..
*/
if (isert_conn->state == ISER_CONN_INIT) {
mutex_unlock(&isert_conn->conn_mutex);
return;
}
if (isert_conn->state == ISER_CONN_UP)
isert_conn->state = <API key>;
mutex_unlock(&isert_conn->conn_mutex);
wait_for_completion(&isert_conn->conn_wait_comp_err);
wait_for_completion(&isert_conn->conn_wait);
isert_put_conn(isert_conn);
}
static void isert_free_conn(struct iscsi_conn *conn)
{
struct isert_conn *isert_conn = conn->context;
isert_put_conn(isert_conn);
}
static struct iscsit_transport <API key> = {
.name = "IB/iSER",
.transport_type = ISCSI_INFINIBAND,
.owner = THIS_MODULE,
.iscsit_setup_np = isert_setup_np,
.iscsit_accept_np = isert_accept_np,
.iscsit_free_np = isert_free_np,
.iscsit_wait_conn = isert_wait_conn,
.iscsit_free_conn = isert_free_conn,
.iscsit_alloc_cmd = isert_alloc_cmd,
.iscsit_get_login_rx = isert_get_login_rx,
.iscsit_put_login_tx = isert_put_login_tx,
.<API key> = <API key>,
.<API key> = <API key>,
.iscsit_get_dataout = isert_get_dataout,
.<API key> = isert_put_datain,
.iscsit_queue_status = isert_put_response,
};
static int __init isert_init(void)
{
int ret;
isert_rx_wq = alloc_workqueue("isert_rx_wq", 0, 0);
if (!isert_rx_wq) {
pr_err("Unable to allocate isert_rx_wq\n");
return -ENOMEM;
}
isert_comp_wq = alloc_workqueue("isert_comp_wq", 0, 0);
if (!isert_comp_wq) {
pr_err("Unable to allocate isert_comp_wq\n");
ret = -ENOMEM;
goto destroy_rx_wq;
}
isert_cmd_cache = kmem_cache_create("isert_cmd_cache",
sizeof(struct isert_cmd), __alignof__(struct isert_cmd),
0, NULL);
if (!isert_cmd_cache) {
pr_err("Unable to create isert_cmd_cache\n");
ret = -ENOMEM;
goto destroy_tx_cq;
}
<API key>(&<API key>);
pr_debug("iSER_TARGET[0] - Loaded <API key>\n");
return 0;
destroy_tx_cq:
destroy_workqueue(isert_comp_wq);
destroy_rx_wq:
destroy_workqueue(isert_rx_wq);
return ret;
}
static void __exit isert_exit(void)
{
<API key>();
kmem_cache_destroy(isert_cmd_cache);
destroy_workqueue(isert_comp_wq);
destroy_workqueue(isert_rx_wq);
<API key>(&<API key>);
pr_debug("iSER_TARGET[0] - Released <API key>\n");
}
MODULE_DESCRIPTION("iSER-Target for mainline target infrastructure");
MODULE_VERSION("0.1");
MODULE_AUTHOR("nab@Linux-iSCSI.org");
MODULE_LICENSE("GPL");
module_init(isert_init);
module_exit(isert_exit);
|
// <API key>: GPL-2.0-or-later
#pragma once
#include <string>
#include <utility>
Base class for controls with a tooltip
class ctrlBaseTooltip
{
public:
ctrlBaseTooltip(std::string tooltip = "") : tooltip_(std::move(tooltip)) {}
virtual ~ctrlBaseTooltip();
void SetTooltip(const std::string& tooltip) { tooltip_ = tooltip; }
const std::string& GetTooltip() const { return tooltip_; }
Swap the tooltips of those controls
void SwapTooltip(ctrlBaseTooltip& other);
void ShowTooltip() const;
Show a temporary tooltip
void ShowTooltip(const std::string& tooltip) const;
void HideTooltip() const;
protected:
std::string tooltip_;
};
|
// Microsoft.VisualBasic.* Test Cases
// Authors:
// Gert Driesen (drieseng@users.sourceforge.net)
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Globalization;
using System.IO;
using System.Text;
using NUnit.Framework;
namespace MonoTests.Microsoft.VisualBasic
{
<summary>
Test ICodeGenerator's <API key>, along with a
minimal set CodeDom components.
</summary>
[TestFixture]
public class <API key> : <API key>
{
CodeNamespace codeNamespace = null;
[SetUp]
public void Init ()
{
InitBase ();
codeNamespace = new CodeNamespace ();
}
protected override string Generate (<API key> options)
{
StringWriter writer = new StringWriter ();
writer.NewLine = NewLine;
generator.<API key> (codeNamespace, writer, options);
writer.Close ();
return writer.ToString ();
}
[Test]
[ExpectedException (typeof (<API key>))]
public void NullNamespaceTest ()
{
codeNamespace = null;
Generate ();
}
[Test]
public void <API key> ()
{
codeNamespace.Name = null;
Assert.AreEqual ("\n", Generate ());
}
[Test]
public void <API key> ()
{
Assert.AreEqual ("\n", Generate ());
}
[Test]
public void SimpleNamespaceTest ()
{
codeNamespace.Name = "A";
Assert.AreEqual ("\nNamespace A\nEnd Namespace\n", Generate ());
}
[Test]
public void <API key> ()
{
codeNamespace.Name = "A,B";
Assert.AreEqual ("\nNamespace A,B\nEnd Namespace\n", Generate ());
}
[Test]
public void <API key> ()
{
<API key> comment = new <API key> ("a");
codeNamespace.Comments.Add (comment);
Assert.AreEqual ("\n'a\n", Generate ());
}
[Test]
public void ImportsTest ()
{
codeNamespace.Imports.Add (new CodeNamespaceImport ("System"));
codeNamespace.Imports.Add (new CodeNamespaceImport ("System.Collections"));
Assert.AreEqual (string.Format(CultureInfo.InvariantCulture,
"Imports System{0}" +
"Imports System.Collections{0}" +
"{0}", NewLine), Generate (), "
codeNamespace.Name = "A";
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"Imports System{0}" +
"Imports System.Collections{0}" +
"{0}" +
"Namespace A{0}" +
"End Namespace{0}", NewLine), Generate (), "
codeNamespace.Name = null;
codeNamespace.Comments.Add (new <API key> ("a"));
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"Imports System{0}" +
"Imports System.Collections{0}" +
"{0}" +
"'a{0}", NewLine), Generate (), "
codeNamespace.Name = "A";
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"Imports System{0}" +
"Imports System.Collections{0}" +
"{0}" +
"'a{0}" +
"Namespace A{0}" +
"End Namespace{0}", NewLine), Generate (), "
}
[Test]
public void TypeTest ()
{
codeNamespace.Types.Add (new CodeTypeDeclaration ("Person"));
Assert.AreEqual (string.Format(CultureInfo.InvariantCulture,
"{0}" +
"{0}" +
"Public Class Person{0}" +
"End Class{0}", NewLine), Generate (), "
<API key> options = new <API key> ();
options.<API key> = false;
Assert.AreEqual (string.Format(CultureInfo.InvariantCulture,
"{0}" +
"Public Class Person{0}" +
"End Class{0}", NewLine), Generate (options), "
codeNamespace.Name = "A";
Assert.AreEqual (string.Format(CultureInfo.InvariantCulture,
"{0}" +
"Namespace A{0}" +
" {0}" +
" Public Class Person{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace A{0}" +
" Public Class Person{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (options), "
}
[Test]
public void Type_TypeParameters ()
{
codeNamespace.Name = "SomeNS";
CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass");
codeNamespace.Types.Add (type);
type.TypeParameters.Add (new CodeTypeParameter ("T"));
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass(Of T){0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "
type.TypeParameters.Add (new CodeTypeParameter ("As"));
type.TypeParameters.Add (new CodeTypeParameter ("New"));
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass(Of T, As, New){0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "
CodeTypeParameter typeParamR = new CodeTypeParameter ("R");
typeParamR.Constraints.Add (new CodeTypeReference (typeof (IComparable)));
type.TypeParameters.Add (typeParamR);
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass(Of T, As, New, R As System.IComparable){0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "
type.TypeParameters.Add (new CodeTypeParameter ("S"));
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass(Of T, As, New, R As System.IComparable, S){0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "
}
[Test]
public void <API key> ()
{
codeNamespace.Name = "SomeNS";
CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass");
codeNamespace.Types.Add (type);
CodeTypeParameter typeParamT = new CodeTypeParameter ("T");
typeParamT.Constraints.Add (new CodeTypeReference (typeof (IComparable)));
type.TypeParameters.Add (typeParamT);
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass(Of T As System.IComparable){0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "
typeParamT.Constraints.Add (new CodeTypeReference (typeof (ICloneable)));
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass(Of T As {{System.IComparable, System.ICloneable}}){0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "
typeParamT.<API key> = true;
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass(Of T As {{System.IComparable, System.ICloneable, New}}){0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "
CodeTypeParameter typeParamS = new CodeTypeParameter ("S");
typeParamS.Constraints.Add (new CodeTypeReference (typeof (IDisposable)));
type.TypeParameters.Add (typeParamS);
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass(Of T As {{System.IComparable, System.ICloneable, New}}, S As System.IDisposable){0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "
CodeTypeParameter typeParamR = new CodeTypeParameter ("R");
typeParamR.<API key> = true;
type.TypeParameters.Add (typeParamR);
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass(Of T As {{System.IComparable, System.ICloneable, New}}, S As System.IDisposable, R As New){0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "
}
[Test]
public void <API key> ()
{
codeNamespace.Name = "SomeNS";
CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass");
codeNamespace.Types.Add (type);
CodeTypeParameter typeParam = new CodeTypeParameter ("T");
typeParam.<API key> = true;
type.TypeParameters.Add (typeParam);
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass(Of T As New){0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate ());
}
[Test]
public void <API key> ()
{
codeNamespace.Name = "SomeNS";
CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass");
codeNamespace.Types.Add (type);
CodeMemberMethod method = new CodeMemberMethod ();
method.Name = "SomeMethod";
type.Members.Add (method);
method.TypeParameters.Add (new CodeTypeParameter ("T"));
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass{0}" +
" {0}" +
" Private Sub SomeMethod(Of T)(){0}" +
" End Sub{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "
method.TypeParameters.Add (new CodeTypeParameter ("As"));
method.TypeParameters.Add (new CodeTypeParameter ("New"));
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass{0}" +
" {0}" +
" Private Sub SomeMethod(Of T, As, New)(){0}" +
" End Sub{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "
CodeTypeParameter typeParamR = new CodeTypeParameter ("R");
typeParamR.Constraints.Add (new CodeTypeReference (typeof (IComparable)));
method.TypeParameters.Add (typeParamR);
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass{0}" +
" {0}" +
" Private Sub SomeMethod(Of T, As, New, R As System.IComparable)(){0}" +
" End Sub{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "
method.TypeParameters.Add (new CodeTypeParameter ("S"));
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass{0}" +
" {0}" +
" Private Sub SomeMethod(Of T, As, New, R As System.IComparable, S)(){0}" +
" End Sub{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "
}
[Test]
public void <API key> ()
{
codeNamespace.Name = "SomeNS";
CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass");
codeNamespace.Types.Add (type);
CodeMemberMethod method = new CodeMemberMethod ();
method.Name = "SomeMethod";
type.Members.Add (method);
CodeTypeParameter typeParamT = new CodeTypeParameter ("T");
typeParamT.Constraints.Add (new CodeTypeReference (typeof (IComparable)));
method.TypeParameters.Add (typeParamT);
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass{0}" +
" {0}" +
" Private Sub SomeMethod(Of T As System.IComparable)(){0}" +
" End Sub{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "
typeParamT.Constraints.Add (new CodeTypeReference (typeof (ICloneable)));
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass{0}" +
" {0}" +
" Private Sub SomeMethod(Of T As {{System.IComparable, System.ICloneable}})(){0}" +
" End Sub{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "
typeParamT.<API key> = true;
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass{0}" +
" {0}" +
" Private Sub SomeMethod(Of T As {{System.IComparable, System.ICloneable, New}})(){0}" +
" End Sub{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "
CodeTypeParameter typeParamS = new CodeTypeParameter ("S");
typeParamS.Constraints.Add (new CodeTypeReference (typeof (IDisposable)));
method.TypeParameters.Add (typeParamS);
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass{0}" +
" {0}" +
" Private Sub SomeMethod(Of T As {{System.IComparable, System.ICloneable, New}}, S As System.IDisposable)(){0}" +
" End Sub{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "
CodeTypeParameter typeParamR = new CodeTypeParameter ("R");
typeParamR.<API key> = true;
method.TypeParameters.Add (typeParamR);
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass{0}" +
" {0}" +
" Private Sub SomeMethod(Of T As {{System.IComparable, System.ICloneable, New}}, S As System.IDisposable, R As New)(){0}" +
" End Sub{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "
}
[Test]
public void <API key> ()
{
codeNamespace.Name = "SomeNS";
CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass");
codeNamespace.Types.Add (type);
CodeMemberMethod method = new CodeMemberMethod ();
method.Name = "SomeMethod";
type.Members.Add (method);
CodeTypeParameter typeParam = new CodeTypeParameter ("T");
typeParam.<API key> = true;
method.TypeParameters.Add (typeParam);
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass{0}" +
" {0}" +
" Private Sub SomeMethod(Of T As New)(){0}" +
" End Sub{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate ());
}
}
}
|
<div class="patient-details container ng-cloak" ng-cloak>
<div ng-if="vm.patient == null">
Es wurde kein Patient ausgewählt!
</div>
<div ng-if="vm.patient != null">
<h1 class="header">Patient</h1>
<div class="clearfix">
<div class="patient-personal patient-abstract">
<h2 class="sub-header">Persönliche Daten</h2>
<span class="table list">
<span class="table-row">
<span class="table-cell">Vorname</span>
<span class="table-cell">{{ vm.patient.firstname }}</span>
</span>
<span class="table-row">
<span class="table-cell">Nachname</span>
<span class="table-cell">{{ vm.patient.lastname }}</span>
</span>
<span class="table-row">
<span class="table-cell">Straße</span>
<span class="table-cell">{{ vm.patient.street }}</span>
</span>
<span class="table-row">
<span class="table-cell">PLZ / Ort</span>
<span class="table-cell">{{ vm.patient.postal }} {{ vm.patient.city }}</span>
</span>
</span>
<span class="table list">
<span class="table-row">
<span class="table-cell">Telefon</span>
<span class="table-cell">{{ vm.patient.phone }}</span>
</span>
<span class="table-row">
<span class="table-cell">Geschäftlich</span>
<span class="table-cell">{{ vm.patient.office }}</span>
</span>
<span class="table-row">
<span class="table-cell">Mobil</span>
<span class="table-cell">{{ vm.patient.mobile }}</span>
</span>
</span>
<a ng-click="vm.showPersonalDetails = !vm.showPersonalDetails" ng-hide="vm.showPersonalDetails" style="display: block; margin-bottom: 0.3em;">Details anzeigen</a>
<a ng-click="vm.showPersonalDetails = !vm.showPersonalDetails" ng-show="vm.showPersonalDetails" style="display: block; margin-bottom: 0.3em;">Details verbergen</a>
<span class="table list" ng-show="vm.showPersonalDetails">
<span class="table-row">
<span class="table-cell">Geburtstag</span>
<span class="table-cell">{{ vm.patient.birthday }}</span>
</span>
<span class="table-row">
<span class="table-cell">Familienstatus</span>
<span class="table-cell">{{ vm.patient.status }}</span>
</span>
<span class="table-row">
<span class="table-cell">Beruf</span>
<span class="table-cell">{{ vm.patient.profession }}</span>
</span>
<span class="table-row">
<span class="table-cell">Versicherung</span>
<span class="table-cell">{{ vm.patient.insurance.type }} {{ vm.patient.insurance.name }}</span>
</span>
<span class="table-row">
<span class="table-cell">Bemerkungen</span>
<span class="table-cell">{{ vm.patient.notes }}</span>
</span>
</span>
</div>
<div class="patient-attributes patient-abstract">
<div class="patient-attention">
<h2 class="sub-header">Vermerk</h2>
<span>{{ vm.patient.attention }}</span>
</div>
<span class="table list">
<span class="table-row">
<span class="table-cell">Referenz durch</span>
<span class="table-cell">{{ vm.patient.reference }}</span>
</span>
<span class="table-row">
<span class="table-cell">Behandelnder Arzt</span>
<span class="table-cell">{{ vm.patient.doctor }}</span>
</span>
<span class="table-row">
<span class="table-cell">Papierakte?</span>
<span class="table-cell">
<span ng-if="vm.patient.paperfile">Ja</span>
<span ng-if="!vm.patient.paperfile">Nein</span>
</span>
</span>
</span>
</div>
</div>
<div class="patient-abstract">
<h2 class="sub-header">Aktuelles</h2>
<span class="table list">
<span class="table-row">
<span class="table-cell">Befunde</span>
<span class="table-cell">{{ vm.patient.findings }}</span>
</span>
<span class="table-row">
<span class="table-cell">Therapie</span>
<span class="table-cell">{{ vm.patient.therapy }}</span>
</span>
</span>
</div>
<div class="patient-abstract">
<h2 class="sub-header">Krankengeschichte</h2>
<span class="table list">
<span class="table-row">
<span class="table-cell">Operationen </span>
<span class="table-cell">{{ vm.patient.history.operations }}</span>
</span>
<span class="table-row">
<span class="table-cell">Unfälle</span>
<span class="table-cell">{{ vm.patient.history.accidents }}</span>
</span>
<span class="table-row">
<span class="table-cell">Vorerkrankungen</span>
<span class="table-cell">{{ vm.patient.history.disease }}</span>
</span>
</span>
</div>
<div class="patient-abstract">
<div class="patient-current">
<h2 class="sub-header">Risikofaktoren</h2>
<span class="table list">
<span class="table-row">
<span class="table-cell">Allergien</span>
<span class="table-cell">{{ vm.patient.risks.allergy }}</span>
</span>
<span class="table-row">
<span class="table-cell">Medikation</span>
<span class="table-cell">{{ vm.patient.risks.medicine }}</span>
</span>
</span>
</div>
</div>
</div>
</div>
<div class="footer">
<a class="button" ng-click="vm.goBack()">Zurück</a>
<a class="button" ng-click="vm.editPatient()">Editieren</a>
<a class="button" ng-click="vm.showTreatment()">Behandlungsakte</a>
</div>
|
#include <R_ext/Complex.h>
#include <R_ext/RS.h>
/* use declarations in R_ext/Lapack.h (instead of having them there *and* here)
but ``delete'' the 'extern' there : */
#define La_extern
#define BLAS_extern
#include <R_ext/Lapack.h>
#undef La_extern
#undef BLAS_extern
|
/* $Id: tstCAPIGlue.c 109358 2016-07-31 17:11:31Z bird $ */
/** @file tstCAPIGlue.c
* Demonstrator program to illustrate use of C bindings of Main API.
*
* It has sample code showing how to retrieve all available error information,
* and how to handle active (event delivery through callbacks) or passive
* (event delivery through a polling mechanism) event listeners.
*/
/** @todo
* Our appologies for the 256+ missing return code checks in this sample file.
*
* We strongly recomment users of the VBoxCAPI to check all return codes!
*/
#include "VBoxCAPIGlue.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#ifndef WIN32
# include <signal.h>
# include <unistd.h>
# include <sys/poll.h>
#endif
#ifdef ___iprt_cdefs_h
# error "not supposed to involve any IPRT or VBox headers here."
#endif
/**
* Select between active event listener (defined) and passive event listener
* (undefined). The active event listener case needs much more code, and
* additionally requires a lot more platform dependent code.
*/
#undef <API key>
/** Set by Ctrl+C handler. */
static volatile int g_fStop = 0;
#ifdef <API key>
# ifdef WIN32
/** The COM type information for IEventListener, for implementing IDispatch. */
static ITypeInfo *<API key> = NULL;
# endif /* WIN32 */
#endif /* <API key> */
static const char *GetStateName(MachineState_T machineState)
{
switch (machineState)
{
case MachineState_Null: return "<null>";
case <API key>: return "PoweredOff";
case MachineState_Saved: return "Saved";
case <API key>: return "Teleported";
case <API key>: return "Aborted";
case <API key>: return "Running";
case MachineState_Paused: return "Paused";
case MachineState_Stuck: return "Stuck";
case <API key>: return "Teleporting";
case <API key>: return "LiveSnapshotting";
case <API key>: return "Starting";
case <API key>: return "Stopping";
case MachineState_Saving: return "Saving";
case <API key>: return "Restoring";
case <API key>: return "TeleportingPausedVM";
case <API key>: return "TeleportingIn";
case <API key>: return "<API key>";
case <API key>: return "<API key>";
case <API key>: return "<API key>";
case <API key>: return "RestoringSnapshot";
case <API key>: return "DeletingSnapshot";
case <API key>: return "SettingUp";
default: return "no idea";
}
}
/**
* Ctrl+C handler, terminate event listener.
*
* Remember that most function calls are not allowed in this context (including
* printf!), so make sure that this does as little as possible.
*
* @param iInfo Platform dependent detail info (ignored).
*/
static BOOL VBOX_WINAPI ctrlCHandler(DWORD iInfo)
{
(void)iInfo;
g_fStop = 1;
return TRUE;
}
/**
* Sample event processing function, dumping some event information.
* Shared between active and passive event demo, to highlight that this part
* is identical between the two.
*/
static HRESULT <API key>(IEvent *event)
{
VBoxEventType_T evType;
HRESULT rc;
if (!event)
{
printf("event null\n");
return S_OK;
}
evType = <API key>;
rc = IEvent_get_Type(event, &evType);
if (FAILED(rc))
{
printf("cannot get event type, rc=%#x\n", rc);
return S_OK;
}
switch (evType)
{
case <API key>:
printf("<API key>\n");
break;
case <API key>:
printf("<API key>\n");
break;
case <API key>:
printf("<API key>\n");
break;
case <API key>:
{
IStateChangedEvent *ev = NULL;
enum MachineState state;
rc = <API key>(event, &<API key>, (void **)&ev);
if (FAILED(rc))
{
printf("cannot get StateChangedEvent interface, rc=%#x\n", rc);
return S_OK;
}
if (!ev)
{
printf("StateChangedEvent reference null\n");
return S_OK;
}
rc = <API key>(ev, &state);
if (FAILED(rc))
printf("warning: cannot get state, rc=%#x\n", rc);
<API key>(ev);
printf("OnStateChanged: %s\n", GetStateName(state));
fflush(stdout);
if ( state == <API key>
|| state == MachineState_Saved
|| state == <API key>
|| state == <API key>
)
g_fStop = 1;
break;
}
case <API key>:
printf("<API key>\n");
break;
case <API key>:
printf("<API key>\n");
break;
case <API key>:
printf("OnSerialPortChanged\n");
break;
case <API key>:
printf("<API key>\n");
break;
case <API key>:
printf("<API key>\n");
break;
case <API key>:
printf("OnMediumChanged\n");
break;
case <API key>:
printf("OnVRDEServerChanged\n");
break;
case <API key>:
printf("<API key>\n");
break;
case <API key>:
printf("<API key>\n");
break;
case <API key>:
printf("<API key>\n");
break;
case <API key>:
printf("OnRuntimeError\n");
break;
case <API key>:
printf("OnCanShowWindow\n");
break;
case <API key>:
printf("OnShowWindow\n");
break;
default:
printf("unknown event: %d\n", evType);
}
return S_OK;
}
#ifdef <API key>
struct IEventListenerDemo;
typedef struct IEventListenerDemo IEventListenerDemo;
typedef struct <API key>
{
HRESULT (*QueryInterface)(IEventListenerDemo *pThis, REFIID riid, void **ppvObject);
ULONG (*AddRef)(IEventListenerDemo *pThis);
ULONG (*Release)(IEventListenerDemo *pThis);
#ifdef WIN32
HRESULT (*GetTypeInfoCount)(IEventListenerDemo *pThis, UINT *pctinfo);
HRESULT (*GetTypeInfo)(IEventListenerDemo *pThis, UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo);
HRESULT (*GetIDsOfNames)(IEventListenerDemo *pThis, REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId);
HRESULT (*Invoke)(IEventListenerDemo *pThis, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr);
#endif
HRESULT (*HandleEvent)(IEventListenerDemo *pThis, IEvent *aEvent);
} <API key>;
typedef struct IEventListenerDemo
{
struct <API key> *lpVtbl;
int cRef;
#ifdef WIN32
/* Active event delivery needs a free threaded marshaler, as the default
* proxy marshaling cannot deal correctly with this case. */
IUnknown *pUnkMarshaler;
#endif
} IEventListenerDemo;
/* Defines for easily calling IEventListenerDemo functions. */
/* IUnknown functions. */
#define <API key>(This,riid,ppvObject) \
( (This)->lpVtbl->QueryInterface(This,riid,ppvObject) )
#define <API key>(This) \
( (This)->lpVtbl->AddRef(This) )
#define <API key>(This) \
( (This)->lpVtbl->Release(This) )
#ifdef WIN32
/* IDispatch functions. */
#define <API key>(This,pctinfo) \
( (This)->lpVtbl->GetTypeInfoCount(This,pctinfo) )
#define <API key>(This,iTInfo,lcid,ppTInfo) \
( (This)->lpVtbl->GetTypeInfo(This,iTInfo,lcid,ppTInfo) )
#define <API key>(This,riid,rgszNames,cNames,lcid,rgDispId) \
( (This)->lpVtbl->GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) )
#define <API key>(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \
( (This)->lpVtbl->Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) )
#endif
/* IEventListener functions. */
#define <API key>(This,aEvent) \
( (This)->lpVtbl->HandleEvent(This,aEvent) )
/**
* Event handler function, for active event processing.
*/
static HRESULT <API key>(IEventListenerDemo *pThis, IEvent *event)
{
return <API key>(event);
}
static HRESULT <API key>(IEventListenerDemo *pThis, const IID *iid, void **resultp)
{
/* match iid */
if ( !memcmp(iid, &IID_IEventListener, sizeof(IID))
|| !memcmp(iid, &IID_IDispatch, sizeof(IID))
|| !memcmp(iid, &IID_IUnknown, sizeof(IID)))
{
<API key>(pThis);
*resultp = pThis;
return S_OK;
}
#ifdef WIN32
if (!memcmp(iid, &IID_IMarshal, sizeof(IID)))
return <API key>(pThis->pUnkMarshaler, iid, resultp);
#endif
return E_NOINTERFACE;
}
static HRESULT <API key>(IEventListenerDemo *pThis)
{
return ++(pThis->cRef);
}
static HRESULT <API key>(IEventListenerDemo *pThis)
{
HRESULT c;
c = --(pThis->cRef);
if (!c)
free(pThis);
return c;
}
#ifdef WIN32
static HRESULT <API key>(IEventListenerDemo *pThis, UINT *pctinfo)
{
if (!pctinfo)
return E_POINTER;
*pctinfo = 1;
return S_OK;
}
static HRESULT <API key>(IEventListenerDemo *pThis, UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo)
{
if (!ppTInfo)
return E_POINTER;
ITypeInfo_AddRef(<API key>);
*ppTInfo = <API key>;
return S_OK;
}
static HRESULT <API key>(IEventListenerDemo *pThis, REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId)
{
return <API key>(<API key>, rgszNames, cNames, rgDispId);
}
static HRESULT <API key>(IEventListenerDemo *pThis, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
return ITypeInfo_Invoke(<API key>, (IDispatch *)pThis, dispIdMember, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
}
static HRESULT LoadTypeInfo(REFIID riid, ITypeInfo **pTInfo)
{
HRESULT rc;
ITypeLib *pTypeLib;
rc = LoadRegTypeLib(&LIBID_VirtualBox, 1 /* major */, 0 /* minor */, 0 /* lcid */, &pTypeLib);
if (FAILED(rc))
return rc;
rc = <API key>(pTypeLib, riid, pTInfo);
/* No longer need access to the type lib, release it. */
ITypeLib_Release(pTypeLib);
return rc;
}
#endif
#ifdef __GNUC__
typedef struct <API key>
{
ptrdiff_t offset_to_top;
void *typeinfo;
<API key> lpVtbl;
} <API key>;
static <API key> <API key> =
{
0, /* offset_to_top */
NULL, /* typeinfo, not vital */
{
<API key>,
<API key>,
<API key>,
#ifdef WIN32
<API key>,
<API key>,
<API key>,
<API key>,
#endif
<API key>
}
};
#elif defined(_MSC_VER)
typedef struct <API key>
{
<API key> lpVtbl;
} <API key>;
static <API key> <API key> =
{
{
<API key>,
<API key>,
<API key>,
#ifdef WIN32
<API key>,
<API key>,
<API key>,
<API key>,
#endif
<API key>
}
};
#else
# error Port me!
#endif
/**
* Register active event listener for the selected VM.
*
* @param virtualBox ptr to IVirtualBox object
* @param session ptr to ISession object
*/
static void <API key>(IVirtualBox *virtualBox, ISession *session)
{
IConsole *console = NULL;
HRESULT rc;
rc = <API key>(session, &console);
if ((SUCCEEDED(rc)) && console)
{
IEventSource *es = NULL;
rc = <API key>(console, &es);
if (SUCCEEDED(rc) && es)
{
static const ULONG <API key>[] =
{
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>
};
SAFEARRAY *interestingEventsSA = NULL;
IEventListenerDemo *consoleListener = NULL;
/* The VirtualBox API expects enum values as VT_I4, which in the
* future can be hopefully relaxed. */
interestingEventsSA = g_pVBoxFuncs-><API key>(VT_I4, 0,
sizeof(<API key>)
/ sizeof(<API key>[0]));
g_pVBoxFuncs-><API key>(interestingEventsSA, &<API key>,
sizeof(<API key>));
consoleListener = calloc(1, sizeof(IEventListenerDemo));
if (consoleListener)
{
consoleListener->lpVtbl = &(<API key>.lpVtbl);
#ifdef WIN32
<API key>((IUnknown *)consoleListener, &consoleListener->pUnkMarshaler);
#endif
<API key>(consoleListener);
rc = <API key>(es, (IEventListener *)consoleListener,
<API key>(interestingEventsSA),
1 /* active */);
if (SUCCEEDED(rc))
{
/* Just wait here for events, no easy way to do this better
* as there's not much to do after this completes. */
printf("Entering event loop, PowerOff the machine to exit or press Ctrl-C to terminate\n");
fflush(stdout);
#ifdef WIN32
<API key>(ctrlCHandler, TRUE);
#else
signal(SIGINT, (void (*)(int))ctrlCHandler);
#endif
while (!g_fStop)
g_pVBoxFuncs-><API key>(250);
#ifdef WIN32
<API key>(ctrlCHandler, FALSE);
#else
signal(SIGINT, SIG_DFL);
#endif
}
else
printf("Failed to register event listener.\n");
<API key>(es, (IEventListener *)consoleListener);
#ifdef WIN32
if (consoleListener->pUnkMarshaler)
IUnknown_Release(consoleListener->pUnkMarshaler);
#endif
<API key>(consoleListener);
}
else
printf("Failed while allocating memory for console event listener.\n");
g_pVBoxFuncs->pfnSafeArrayDestroy(interestingEventsSA);
<API key>(es);
}
else
printf("Failed to get the event source instance.\n");
IConsole_Release(console);
}
}
#else /* !<API key> */
/**
* Register passive event listener for the selected VM.
*
* @param virtualBox ptr to IVirtualBox object
* @param session ptr to ISession object
*/
static void <API key>(ISession *session)
{
IConsole *console = NULL;
HRESULT rc;
rc = <API key>(session, &console);
if (SUCCEEDED(rc) && console)
{
IEventSource *es = NULL;
rc = <API key>(console, &es);
if (SUCCEEDED(rc) && es)
{
static const ULONG <API key>[] =
{
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>
};
SAFEARRAY *interestingEventsSA = NULL;
IEventListener *consoleListener = NULL;
/* The VirtualBox API expects enum values as VT_I4, which in the
* future can be hopefully relaxed. */
interestingEventsSA = g_pVBoxFuncs-><API key>(VT_I4, 0,
sizeof(<API key>)
/ sizeof(<API key>[0]));
g_pVBoxFuncs-><API key>(interestingEventsSA, &<API key>,
sizeof(<API key>));
rc = <API key>(es, &consoleListener);
if (SUCCEEDED(rc) && consoleListener)
{
rc = <API key>(es, consoleListener,
<API key>(interestingEventsSA),
0 /* passive */);
if (SUCCEEDED(rc))
{
/* Just wait here for events, no easy way to do this better
* as there's not much to do after this completes. */
printf("Entering event loop, PowerOff the machine to exit or press Ctrl-C to terminate\n");
fflush(stdout);
#ifdef WIN32
<API key>(ctrlCHandler, TRUE);
#else
signal(SIGINT, (void (*)(int))ctrlCHandler);
#endif
while (!g_fStop)
{
IEvent *ev = NULL;
rc = <API key>(es, consoleListener, 250, &ev);
if (FAILED(rc))
{
printf("Failed getting event: %#x\n", rc);
g_fStop = 1;
continue;
}
/* handle timeouts, resulting in NULL events */
if (!ev)
continue;
rc = <API key>(ev);
if (FAILED(rc))
{
printf("Failed processing event: %#x\n", rc);
g_fStop = 1;
/* finish processing the event */
}
rc = <API key>(es, consoleListener, ev);
if (FAILED(rc))
{
printf("Failed to mark event as processed: %#x\n", rc);
g_fStop = 1;
/* continue with event release */
}
if (ev)
{
IEvent_Release(ev);
ev = NULL;
}
}
#ifdef WIN32
<API key>(ctrlCHandler, FALSE);
#else
signal(SIGINT, SIG_DFL);
#endif
}
else
printf("Failed to register event listener.\n");
<API key>(es, (IEventListener *)consoleListener);
<API key>(consoleListener);
}
else
printf("Failed to create an event listener instance.\n");
g_pVBoxFuncs->pfnSafeArrayDestroy(interestingEventsSA);
<API key>(es);
}
else
printf("Failed to get the event source instance.\n");
IConsole_Release(console);
}
}
#endif /* !<API key> */
/**
* Print detailed error information if available.
* @param pszExecutable string with the executable name
* @param pszErrorMsg string containing the code location specific error message
* @param rc COM/XPCOM result code
*/
static void PrintErrorInfo(const char *pszExecutable, const char *pszErrorMsg, HRESULT rc)
{
IErrorInfo *ex;
HRESULT rc2;
fprintf(stderr, "%s: %s (rc=%#010x)\n", pszExecutable, pszErrorMsg, (unsigned)rc);
rc2 = g_pVBoxFuncs->pfnGetException(&ex);
if (SUCCEEDED(rc2) && ex)
{
<API key> *ei;
rc2 = <API key>(ex, &<API key>, (void **)&ei);
if (SUCCEEDED(rc2) && ei != NULL)
{
/* got extended error info, maybe multiple infos */
do
{
LONG resultCode = S_OK;
BSTR componentUtf16 = NULL;
char *component = NULL;
BSTR textUtf16 = NULL;
char *text = NULL;
<API key> *ei_next = NULL;
fprintf(stderr, "Extended error info (<API key>):\n");
<API key>(ei, &resultCode);
fprintf(stderr, " resultCode=%#010x\n", (unsigned)resultCode);
<API key>(ei, &componentUtf16);
g_pVBoxFuncs->pfnUtf16ToUtf8(componentUtf16, &component);
g_pVBoxFuncs->pfnComUnallocString(componentUtf16);
fprintf(stderr, " component=%s\n", component);
g_pVBoxFuncs->pfnUtf8Free(component);
<API key>(ei, &textUtf16);
g_pVBoxFuncs->pfnUtf16ToUtf8(textUtf16, &text);
g_pVBoxFuncs->pfnComUnallocString(textUtf16);
fprintf(stderr, " text=%s\n", text);
g_pVBoxFuncs->pfnUtf8Free(text);
rc2 = <API key>(ei, &ei_next);
if (FAILED(rc2))
ei_next = NULL;
<API key>(ei);
ei = ei_next;
} while (ei);
}
IErrorInfo_Release(ex);
g_pVBoxFuncs->pfnClearException();
}
}
/**
* Start a VM.
*
* @param argv0 executable name
* @param virtualBox ptr to IVirtualBox object
* @param session ptr to ISession object
* @param id identifies the machine to start
*/
static void startVM(const char *argv0, IVirtualBox *virtualBox, ISession *session, BSTR id)
{
HRESULT rc;
IMachine *machine = NULL;
IProgress *progress = NULL;
BSTR env = NULL;
BSTR sessionType;
SAFEARRAY *groupsSA = g_pVBoxFuncs-><API key>();
rc = <API key>(virtualBox, id, &machine);
if (FAILED(rc) || !machine)
{
PrintErrorInfo(argv0, "Error: Couldn't get the Machine reference", rc);
return;
}
rc = IMachine_get_Groups(machine, <API key>(groupsSA, BSTR));
if (SUCCEEDED(rc))
{
BSTR *groups = NULL;
ULONG cbGroups = 0;
ULONG i, cGroups;
g_pVBoxFuncs-><API key>((void **)&groups, &cbGroups, VT_BSTR, groupsSA);
g_pVBoxFuncs->pfnSafeArrayDestroy(groupsSA);
cGroups = cbGroups / sizeof(groups[0]);
for (i = 0; i < cGroups; ++i)
{
/* Note that the use of %S might be tempting, but it is not
* available on all platforms, and even where it is usable it
* may depend on correct compiler options to make wchar_t a
* 16 bit number. So better play safe and use UTF-8. */
char *group;
g_pVBoxFuncs->pfnUtf16ToUtf8(groups[i], &group);
printf("Groups[%d]: %s\n", i, group);
g_pVBoxFuncs->pfnUtf8Free(group);
}
for (i = 0; i < cGroups; ++i)
g_pVBoxFuncs->pfnComUnallocString(groups[i]);
g_pVBoxFuncs->pfnArrayOutFree(groups);
}
g_pVBoxFuncs->pfnUtf8ToUtf16("gui", &sessionType);
rc = <API key>(machine, session, sessionType, env, &progress);
g_pVBoxFuncs->pfnUtf16Free(sessionType);
if (SUCCEEDED(rc))
{
BOOL completed;
LONG resultCode;
printf("Waiting for the remote session to open...\n");
<API key>(progress, -1);
rc = <API key>(progress, &completed);
if (FAILED(rc))
fprintf(stderr, "Error: GetCompleted status failed\n");
<API key>(progress, &resultCode);
if (FAILED(resultCode))
{
<API key> *errorInfo;
BSTR textUtf16;
char *text;
<API key>(progress, &errorInfo);
<API key>(errorInfo, &textUtf16);
g_pVBoxFuncs->pfnUtf16ToUtf8(textUtf16, &text);
printf("Error: %s\n", text);
g_pVBoxFuncs->pfnComUnallocString(textUtf16);
g_pVBoxFuncs->pfnUtf8Free(text);
<API key>(errorInfo);
}
else
{
fprintf(stderr, "VM process has been successfully started\n");
/* Kick off the event listener demo part, which is quite separate.
* Ignore it if you need a more basic sample. */
#ifdef <API key>
<API key>(virtualBox, session);
#else
<API key>(session);
#endif
}
IProgress_Release(progress);
}
else
PrintErrorInfo(argv0, "Error: LaunchVMProcess failed", rc);
/* It's important to always release resources. */
IMachine_Release(machine);
}
/**
* List the registered VMs.
*
* @param argv0 executable name
* @param virtualBox ptr to IVirtualBox object
* @param session ptr to ISession object
*/
static void listVMs(const char *argv0, IVirtualBox *virtualBox, ISession *session)
{
HRESULT rc;
SAFEARRAY *machinesSA = g_pVBoxFuncs-><API key>();
IMachine **machines = NULL;
ULONG machineCnt = 0;
ULONG i;
unsigned start_id;
/*
* Get the list of all registered VMs.
*/
rc = <API key>(virtualBox, <API key>(machinesSA, IMachine *));
if (FAILED(rc))
{
PrintErrorInfo(argv0, "could not get list of machines", rc);
return;
}
/*
* Extract interface pointers from machinesSA, and update the reference
* counter of each object, as destroying machinesSA would call Release.
*/
g_pVBoxFuncs-><API key>((IUnknown ***)&machines, &machineCnt, machinesSA);
g_pVBoxFuncs->pfnSafeArrayDestroy(machinesSA);
if (!machineCnt)
{
g_pVBoxFuncs->pfnArrayOutFree(machines);
printf("\tNo VMs\n");
return;
}
printf("VM List:\n\n");
/*
* Iterate through the collection.
*/
for (i = 0; i < machineCnt; ++i)
{
IMachine *machine = machines[i];
BOOL isAccessible = FALSE;
printf("\tMachine #%u\n", (unsigned)i);
if (!machine)
{
printf("\t(skipped, NULL)\n");
continue;
}
<API key>(machine, &isAccessible);
if (isAccessible)
{
BSTR machineNameUtf16;
char *machineName;
IMachine_get_Name(machine, &machineNameUtf16);
g_pVBoxFuncs->pfnUtf16ToUtf8(machineNameUtf16,&machineName);
g_pVBoxFuncs->pfnComUnallocString(machineNameUtf16);
printf("\tName: %s\n", machineName);
g_pVBoxFuncs->pfnUtf8Free(machineName);
}
else
printf("\tName: <inaccessible>\n");
{
BSTR uuidUtf16;
char *uuidUtf8;
IMachine_get_Id(machine, &uuidUtf16);
g_pVBoxFuncs->pfnUtf16ToUtf8(uuidUtf16, &uuidUtf8);
g_pVBoxFuncs->pfnComUnallocString(uuidUtf16);
printf("\tUUID: %s\n", uuidUtf8);
g_pVBoxFuncs->pfnUtf8Free(uuidUtf8);
}
if (isAccessible)
{
{
BSTR configFileUtf16;
char *configFileUtf8;
<API key>(machine, &configFileUtf16);
g_pVBoxFuncs->pfnUtf16ToUtf8(configFileUtf16, &configFileUtf8);
g_pVBoxFuncs->pfnComUnallocString(configFileUtf16);
printf("\tConfig file: %s\n", configFileUtf8);
g_pVBoxFuncs->pfnUtf8Free(configFileUtf8);
}
{
ULONG memorySize;
<API key>(machine, &memorySize);
printf("\tMemory size: %uMB\n", memorySize);
}
{
BSTR typeId;
BSTR osNameUtf16;
char *osName;
IGuestOSType *osType = NULL;
<API key>(machine, &typeId);
<API key>(virtualBox, typeId, &osType);
g_pVBoxFuncs->pfnComUnallocString(typeId);
<API key>(osType, &osNameUtf16);
g_pVBoxFuncs->pfnUtf16ToUtf8(osNameUtf16,&osName);
g_pVBoxFuncs->pfnComUnallocString(osNameUtf16);
printf("\tGuest OS: %s\n\n", osName);
g_pVBoxFuncs->pfnUtf8Free(osName);
<API key>(osType);
}
}
}
/*
* Let the user chose a machine to start.
*/
printf("Type Machine# to start (0 - %u) or 'quit' to do nothing: ",
(unsigned)(machineCnt - 1));
fflush(stdout);
if (scanf("%u", &start_id) == 1 && start_id < machineCnt)
{
IMachine *machine = machines[start_id];
if (machine)
{
BSTR uuidUtf16 = NULL;
IMachine_get_Id(machine, &uuidUtf16);
startVM(argv0, virtualBox, session, uuidUtf16);
g_pVBoxFuncs->pfnComUnallocString(uuidUtf16);
}
}
/*
* Don't forget to release the objects in the array.
*/
for (i = 0; i < machineCnt; ++i)
{
IMachine *machine = machines[i];
if (machine)
IMachine_Release(machine);
}
g_pVBoxFuncs->pfnArrayOutFree(machines);
}
/* Main - Start the ball rolling. */
int main(int argc, char **argv)
{
IVirtualBoxClient *vboxclient = NULL;
IVirtualBox *vbox = NULL;
ISession *session = NULL;
ULONG revision = 0;
BSTR versionUtf16 = NULL;
BSTR homefolderUtf16 = NULL;
HRESULT rc; /* Result code of various function (method) calls. */
(void)argc;
printf("Starting main()\n");
if (VBoxCGlueInit())
{
fprintf(stderr, "%s: FATAL: VBoxCGlueInit failed: %s\n",
argv[0], g_szVBoxErrMsg);
return EXIT_FAILURE;
}
{
unsigned ver = g_pVBoxFuncs->pfnGetVersion();
printf("VirtualBox version: %u.%u.%u\n", ver / 1000000, ver / 1000 % 1000, ver % 1000);
ver = g_pVBoxFuncs->pfnGetAPIVersion();
printf("VirtualBox API version: %u.%u\n", ver / 1000, ver % 1000);
}
g_pVBoxFuncs->pfnClientInitialize(NULL, &vboxclient);
if (!vboxclient)
{
fprintf(stderr, "%s: FATAL: could not get VirtualBoxClient reference\n", argv[0]);
return EXIT_FAILURE;
}
printf("
rc = <API key>(vboxclient, &vbox);
if (FAILED(rc) || !vbox)
{
PrintErrorInfo(argv[0], "FATAL: could not get VirtualBox reference", rc);
return EXIT_FAILURE;
}
rc = <API key>(vboxclient, &session);
if (FAILED(rc) || !session)
{
PrintErrorInfo(argv[0], "FATAL: could not get Session reference", rc);
return EXIT_FAILURE;
}
#ifdef <API key>
# ifdef WIN32
rc = LoadTypeInfo(&IID_IEventListener, &<API key>);
if (FAILED(rc) || !<API key>)
{
PrintErrorInfo(argv[0], "FATAL: could not get type information for IEventListener", rc);
return EXIT_FAILURE;
}
# endif /* WIN32 */
#endif /* <API key> */
/*
* Now ask for revision, version and home folder information of
* this vbox. Were not using fancy macros here so it
* remains easy to see how we access C++'s vtable.
*/
/* 1. Revision */
rc = <API key>(vbox, &revision);
if (SUCCEEDED(rc))
printf("\tRevision: %u\n", revision);
else
PrintErrorInfo(argv[0], "GetRevision() failed", rc);
/* 2. Version */
rc = <API key>(vbox, &versionUtf16);
if (SUCCEEDED(rc))
{
char *version = NULL;
g_pVBoxFuncs->pfnUtf16ToUtf8(versionUtf16, &version);
printf("\tVersion: %s\n", version);
g_pVBoxFuncs->pfnUtf8Free(version);
g_pVBoxFuncs->pfnComUnallocString(versionUtf16);
}
else
PrintErrorInfo(argv[0], "GetVersion() failed", rc);
/* 3. Home Folder */
rc = <API key>(vbox, &homefolderUtf16);
if (SUCCEEDED(rc))
{
char *homefolder = NULL;
g_pVBoxFuncs->pfnUtf16ToUtf8(homefolderUtf16, &homefolder);
printf("\tHomeFolder: %s\n", homefolder);
g_pVBoxFuncs->pfnUtf8Free(homefolder);
g_pVBoxFuncs->pfnComUnallocString(homefolderUtf16);
}
else
PrintErrorInfo(argv[0], "GetHomeFolder() failed", rc);
listVMs(argv[0], vbox, session);
<API key>(session);
printf("
/*
* Do as mom told us: always clean up after yourself.
*/
#ifdef <API key>
# ifdef WIN32
if (<API key>)
{
ITypeInfo_Release(<API key>);
<API key> = NULL;
}
# endif /* WIN32 */
#endif /* <API key> */
if (session)
{
ISession_Release(session);
session = NULL;
}
if (vbox)
{
IVirtualBox_Release(vbox);
vbox = NULL;
}
if (vboxclient)
{
<API key>(vboxclient);
vboxclient = NULL;
}
g_pVBoxFuncs-><API key>();
VBoxCGlueTerm();
printf("Finished main()\n");
return 0;
}
/* vim: set ts=4 sw=4 et: */
|
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http:
<head>
<title>schrodinger.graphics3d.polyhedron.MaestroIcosahedron</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
>2015-2Schrodinger Python API</th>
</tr></table></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%">
<span class="breadcrumbs">
<a href="schrodinger-module.html">Package schrodinger</a> ::
<a href="schrodinger.graphics3d-module.html">Package graphics3d</a> ::
<a href="schrodinger.graphics3d.polyhedron-module.html">Module polyhedron</a> ::
Class MaestroIcosahedron
</span>
</td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span></td></tr>
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="schrodinger.graphics3d.polyhedron.<API key>.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<h1 class="epydoc">Class MaestroIcosahedron</h1><p class="nomargin-top"></p>
<pre class="base-tree">
<a href="object-class.html">object</a>
|
<a href="schrodinger.graphics3d.common.Primitive-class.html">common.Primitive</a>
|
<a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html">Polyhedron</a>
|
<a href="schrodinger.graphics3d.polyhedron.<API key>.html"><API key></a>
|
<strong class="uidshort">MaestroIcosahedron</strong>
</pre>
<dl><dt>Known Subclasses:</dt>
<dd>
<ul class="subclass-list">
<li><a href="schrodinger.graphics3d.polyhedron.Icosahedron-class.html">Icosahedron</a></li> </ul>
</dd></dl>
<hr />
<p>Class to draw a 3D icosahedron in Maestro's Workspace.</p>
<p>See <a href="schrodinger.graphics3d.polyhedron.Tetrahedron-class.html"
class="link">Tetrahedron</a> doc string for more details.</p>
<a name="<API key>"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Instance Methods</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#<API key>"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="schrodinger.graphics3d.polyhedron.<API key>.html#__init__" class="summary-sig-name">__init__</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">center</span>,
<span class="summary-sig-arg">mode</span>,
<span class="summary-sig-arg">length</span>=<span class="summary-sig-default">None</span>,
<span class="summary-sig-arg">radius</span>=<span class="summary-sig-default">None</span>,
<span class="summary-sig-arg">volume</span>=<span class="summary-sig-default">None</span>,
<span class="summary-sig-arg">color</span>=<span class="summary-sig-default"><code class="variable-quote">'</code><code class="variable-string">red</code><code class="variable-quote">'</code></span>,
<span class="summary-sig-arg">opacity</span>=<span class="summary-sig-default">1.0</span>,
<span class="summary-sig-arg">style</span>=<span class="summary-sig-default">1</span>)</span><br />
Create a polyhedron centered at <code>center</code>.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="schrodinger.graphics3d.polyhedron.<API key>.html#getVertices" class="summary-sig-name">getVertices</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">center</span>,
<span class="summary-sig-arg">length</span>=<span class="summary-sig-default">None</span>,
<span class="summary-sig-arg">radius</span>=<span class="summary-sig-default">None</span>,
<span class="summary-sig-arg">volume</span>=<span class="summary-sig-default">None</span>)</span><br />
Get a list of vertices.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="schrodinger.graphics3d.polyhedron.<API key>.html#getIndices" class="summary-sig-name">getIndices</a>(<span class="summary-sig-arg">self</span>)</span><br />
@return The indices of the faces</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="<API key>"><b>Inherited from <code><a href="schrodinger.graphics3d.polyhedron.<API key>.html"><API key></a></code></b>:
<code><a href="schrodinger.graphics3d.polyhedron.<API key>.html#getFaces">getFaces</a></code>,
<code><a href="schrodinger.graphics3d.polyhedron.<API key>.html#updateVertices">updateVertices</a></code>
</p>
<div class="private"> <p class="<API key>"><b>Inherited from <code><a href="schrodinger.graphics3d.polyhedron.<API key>.html"><API key></a></code></b> (private):
<code><a href="schrodinger.graphics3d.polyhedron.<API key>.html#_checkSizeArgs" onclick="show_private();">_checkSizeArgs</a></code>,
<code><a href="schrodinger.graphics3d.polyhedron.<API key>.html#<API key>" onclick="show_private();"><API key></a></code>
</p></div>
<p class="<API key>"><b>Inherited from <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html">Polyhedron</a></code></b>:
<code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#setStyle">setStyle</a></code>,
<code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#update">update</a></code>
</p>
<div class="private"> <p class="<API key>"><b>Inherited from <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html">Polyhedron</a></code></b> (private):
<code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#<API key>" onclick="show_private();"><API key></a></code>,
<code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_draw" onclick="show_private();">_draw</a></code>,
<code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_setNormals" onclick="show_private();">_setNormals</a></code>
</p></div>
<p class="<API key>"><b>Inherited from <code><a href="schrodinger.graphics3d.common.Primitive-class.html">common.Primitive</a></code></b>:
<code><a href="schrodinger.graphics3d.common.Primitive-class.html#__del__">__del__</a></code>,
<code><a href="schrodinger.graphics3d.common.Primitive-class.html#groupHidden">groupHidden</a></code>,
<code><a href="schrodinger.graphics3d.common.Primitive-class.html#groupShown">groupShown</a></code>,
<code><a href="schrodinger.graphics3d.common.Primitive-class.html#hide">hide</a></code>,
<code><a href="schrodinger.graphics3d.common.Primitive-class.html#isGroupShown">isGroupShown</a></code>,
<code><a href="schrodinger.graphics3d.common.Primitive-class.html#isShown">isShown</a></code>,
<code><a href="schrodinger.graphics3d.common.Primitive-class.html#setEntryID">setEntryID</a></code>,
<code><a href="schrodinger.graphics3d.common.Primitive-class.html#show">show</a></code>
</p>
<p class="<API key>"><b>Inherited from <code><a href="object-class.html">object</a></code></b>:
<code><a href="object-class.html#__delattr__">__delattr__</a></code>,
<code><a href="object-class.html#__format__">__format__</a></code>,
<code><a href="object-class.html#__getattribute__">__getattribute__</a></code>,
<code><a href="object-class.html#__hash__">__hash__</a></code>,
<code><a href="object-class.html#__new__">__new__</a></code>,
<code><a href="object-class.html#__reduce__">__reduce__</a></code>,
<code><a href="object-class.html#__reduce_ex__">__reduce_ex__</a></code>,
<code><a href="object-class.html#__repr__">__repr__</a></code>,
<code><a href="object-class.html#__setattr__">__setattr__</a></code>,
<code><a href="object-class.html#__sizeof__">__sizeof__</a></code>,
<code><a href="object-class.html#__str__">__str__</a></code>,
<code><a href="object-class.html#__subclasshook__">__subclasshook__</a></code>
</p>
</td>
</tr>
</table>
<a name="<API key>"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Static Methods</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#<API key>"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<div class="private"> <p class="<API key>"><b>Inherited from <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html">Polyhedron</a></code></b> (private):
<code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_glReset" onclick="show_private();">_glReset</a></code>,
<code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_glSetup" onclick="show_private();">_glSetup</a></code>
</p></div>
</td>
</tr>
</table>
<a name="<API key>"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Class Variables</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#<API key>"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<div class="private"> <p class="<API key>"><b>Inherited from <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html">Polyhedron</a></code></b> (private):
<code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_blend" onclick="show_private();">_blend</a></code>,
<code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_cull" onclick="show_private();">_cull</a></code>,
<code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_lighting" onclick="show_private();">_lighting</a></code>,
<code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_lighting_model" onclick="show_private();">_lighting_model</a></code>,
<code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_polygon_mode" onclick="show_private();">_polygon_mode</a></code>,
<code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_shading_model" onclick="show_private();">_shading_model</a></code>,
<code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_smooth_point" onclick="show_private();">_smooth_point</a></code>
</p></div>
</td>
</tr>
</table>
<a name="<API key>"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Instance Variables</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#<API key>"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="<API key>"><b>Inherited from <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html">Polyhedron</a></code></b>:
<code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#faces">faces</a></code>,
<code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#normals">normals</a></code>,
<code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#vertices">vertices</a></code>
</p>
</td>
</tr>
</table>
<a name="section-Properties"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Properties</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Properties"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="<API key>"><b>Inherited from <code><a href="object-class.html">object</a></code></b>:
<code><a href="object-class.html#__class__">__class__</a></code>
</p>
</td>
</tr>
</table>
<a name="<API key>"></a>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Method Details</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#<API key>"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
</table>
<a name="__init__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__init__</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">center</span>,
<span class="sig-arg">mode</span>,
<span class="sig-arg">length</span>=<span class="sig-default">None</span>,
<span class="sig-arg">radius</span>=<span class="sig-default">None</span>,
<span class="sig-arg">volume</span>=<span class="sig-default">None</span>,
<span class="sig-arg">color</span>=<span class="sig-default"><code class="variable-quote">'</code><code class="variable-string">red</code><code class="variable-quote">'</code></span>,
<span class="sig-arg">opacity</span>=<span class="sig-default">1.0</span>,
<span class="sig-arg">style</span>=<span class="sig-default">1</span>)</span>
<br /><em class="fname">(Constructor)</em>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<p>Create a polyhedron centered at <code>center</code>. Note that one of
<code>length</code>, <code>radius</code>, <code>volume</code> is needed
to create the shape.</p>
<dl class="fields">
<dt>Parameters:</dt>
<dd><ul class="nomargin-top">
<li><strong class="pname"><code>center</code></strong> - List of 3 Angstrom values indicating the center coordinate of the
tetrahedron.</li>
<li><strong class="pname"><code>length</code></strong> - Length in Angstroms of each of the edges of the tetrahedron.</li>
<li><strong class="pname"><code>radius</code></strong> - Circumsphere radius in Angstroms from center of tetrahedron.</li>
<li><strong class="pname"><code>volume</code></strong> - Volume in cubed Angstroms of the object.</li>
<li><strong class="pname"><code>color</code></strong> - One of - Color object, Color name (string), or Tuple of (R, G, B)
(each 0.0-1.0)</li>
<li><strong class="pname"><code>opacity</code></strong> - 0.0 (invisible) through 1.0 (opaque). Defaults to 1.0</li>
<li><strong class="pname"><code>style</code></strong> - LINE or FILL. Default is FILL.</li>
</ul></dd>
<dt>Raises:</dt>
<dd><ul class="nomargin-top">
<li><code><strong class='fraise'>RuntimeError</strong></code> - If a single option from <code>length</code>, <code>radius</code>,
and <code>volume</code> does not have a value.</li>
<li><code><strong class='fraise'>ValueError</strong></code> - If the size parameter (<code>length</code>, <code>radius</code>, or
<code>volume</code>) is not a float.</li>
<li><code><strong class='fraise'>NotImplementedError</strong></code> - If the initiating subclass does not have a <code>getVertices</code>
or <code>getFaces</code> method.</li>
</ul></dd>
<dt>Overrides:
object.__init__
</dt>
</dl>
<div class="fields"> <p><strong>See Also:</strong>
<a
href="schrodinger.graphics3d.polyhedron.<API key>.html#__init__"
class="link"><API key>.__init__</a>
</p>
</div></td></tr></table>
</div>
<a name="getVertices"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">getVertices</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">center</span>,
<span class="sig-arg">length</span>=<span class="sig-default">None</span>,
<span class="sig-arg">radius</span>=<span class="sig-default">None</span>,
<span class="sig-arg">volume</span>=<span class="sig-default">None</span>)</span>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<p>Get a list of vertices. If the center coordinates are considered the
origin the vertices will have a base on the y-plane, a vertex on the
x-axis and a vertex directly in the +z-axis from the
<code>center</code>.</p>
<dl class="fields">
<dt>Parameters:</dt>
<dd><ul class="nomargin-top">
<li><strong class="pname"><code>center</code></strong> (List) - List of 3 Angstrom values indicating the center coordinate of the
icosahedron.</li>
<li><strong class="pname"><code>length</code></strong> (float) - Length in Angstroms of each of the sides of the icosahedron.
Note: <code>length</code> or <code>radius</code> must be
specified to create icosahedron.</li>
<li><strong class="pname"><code>radius</code></strong> (float) - Circumsphere radius in Angstroms from center of icosahedron.
Note: <code>length</code> or <code>radius</code> must be
specified to create icosahedron.</li>
<li><strong class="pname"><code>volume</code></strong> (float) - Volume in cubed Angstroms of the object.</li>
</ul></dd>
<dt>Overrides:
<a href="schrodinger.graphics3d.polyhedron.<API key>.html#getVertices"><API key>.getVertices</a>
</dt>
</dl>
</td></tr></table>
</div>
<a name="getIndices"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">getIndices</span>(<span class="sig-arg">self</span>)</span>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<p>@return The indices of the faces</p>
<dl class="fields">
<dt>Overrides:
<a href="schrodinger.graphics3d.polyhedron.<API key>.html#getIndices"><API key>.getIndices</a>
</dt>
</dl>
</td></tr></table>
</div>
<br />
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
>2015-2Schrodinger Python API</th>
</tr></table></th>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">
Generated by Epydoc 3.0.1 on Sat May 9 06:31:22 2015
</td>
<td align="right" class="footer">
<a target="mainFrame" href="http://epydoc.sourceforge.net"
>http://epydoc.sourceforge.net</a>
</td>
</tr>
</table>
<script type="text/javascript">
<!
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
</script>
</body>
</html>
|
#!/usr/bin/env python
from datetime import timedelta
import numpy as np
from opendrift.readers import <API key>
from opendrift.readers import <API key>
from opendrift.models.oceandrift import OceanDrift
# Seeding at a grid at regular interval
o = OceanDrift(loglevel=20) # Set loglevel to 0 for debug information
reader_norkyst = <API key>.Reader(o.test_data_folder() +
'<API key>/<API key>.nc')
# Landmask
reader_landmask = <API key>.Reader(
extent=[4.0, 5.5, 59.9, 61.2])
o.add_reader([reader_landmask, reader_norkyst])
# Seeding some particles
lons = np.linspace(4.4, 4.6, 10)
lats = np.linspace(60.0, 60.1, 10)
lons, lats = np.meshgrid(lons, lats)
lons = lons.ravel()
lats = lats.ravel()
# Seed oil elements on a grid at regular time interval
start_time = reader_norkyst.start_time
time_step = timedelta(hours=6)
num_steps = 10
for i in range(num_steps+1):
o.seed_elements(lons, lats, radius=0, number=100,
time=start_time + i*time_step)
# Running model for 60 hours
o.run(steps=60*4, time_step=900, time_step_output=3600)
# Print and plot results
print(o)
o.animation(fast=True)
# .. image:: /gallery/animations/example_grid_time_0.gif
|
#ifndef INCLUDE_SETTING_H_
#define INCLUDE_SETTING_H_
//#define MATRIX
//#define MATRIX_CSR
//#define MATRIX_VECTOR
#define MATRIX_MAP
#define COL_SIZE (1000)
#define ROW_SIZE (1000)
#define VAL_RANGE_START (1)
#define VAL_RANGE_END (10)
#define VAL_PER_COL (6)
#ifdef MATRIX
#include <matrix.h>
typedef matrix::Matrix matrix_t;
#define TEST_MULTI_THREAD (0)
#endif
#ifdef MATRIX_CSR
#include <matrix_csr.h>
typedef matrix::MatrixCSR matrix_t;
#define TEST_MULTI_THREAD (0)
#endif
#ifdef MATRIX_MAP
#include <sparse_matrix2.h>
typedef matrix::SparseMatrix2 matrix_t;
#define TEST_MULTI_THREAD (1)
#endif
#ifdef MATRIX_VECTOR
#include <sparse_matrix.h>
typedef matrix::SparseMatrix matrix_t;
#define TEST_MULTI_THREAD (1)
#endif
#include "matrix_error.h"
#endif /* INCLUDE_SETTING_H_ */
|
#ifndef KTIMETRACKER_TASK_H
#define KTIMETRACKER_TASK_H
#include "desktoplist.h" // Required b/c DesktopList is a typedef not a class.
#include "taskview.h" // Required b/c of static cast below.
#include <KCalCore/Todo>
#include <QDateTime>
#include <QPixmap>
#include <QVector>
class QObject;
class QPixmap;
class QString;
class timetrackerstorage;
/** \brief A class representing a task
*
* A "Task" object stores information about a task such as it's name,
* total and session times.
*
* It can log when the task is started, stoped or deleted.
*
* If a task is associated with some desktop's activity it can remember that
* too.
*
* It can also contain subtasks - these are managed using the
* QListViewItem class.
*/
class Task : public QObject, public QTreeWidgetItem
{
Q_OBJECT
public:
Task( const QString& taskname, const QString& taskdescription, long minutes, long sessionTime,
DesktopList desktops, TaskView* parent = 0, bool konsolemode=false );
Task( const QString& taskname, const QString& taskdescription, long minutes, long sessionTime,
DesktopList desktops, Task* parent = 0);
Task( const KCalCore::Todo::Ptr &incident, TaskView* parent, bool konsolemode=false );
/* destructor */
~Task();
/** return parent Task or null in case of TaskView.
* same as QListViewItem::parent()
*/
Task* parent() const { return (Task*)QTreeWidgetItem::parent(); }
/** Return task view for this task */
TaskView* taskView() const
{ return static_cast<TaskView *>( treeWidget() ); }
/** Return unique iCalendar Todo ID for this task. */
QString uid() const;
int depth();
void delete_recursive();
/**
* Set unique id for the task.
*
* The uid is the key used to update the storage.
*
* @param uid The new unique id.
*/
void setUid( const QString &uid );
/** cut Task out of parent Task or the TaskView */
void cut();
/** cut Task out of parent Task or the TaskView and into the
* destination Task */
void move(Task* destination);
/** insert Task into the destination Task */
void paste(Task* destination);
//@{ timing related functions
/**
* Change task time. Adds minutes to both total time and session time by adding an event.
*
* @param minutes minutes to add to - may be negative
* @param storage Pointer to timetrackerstorage instance.
* If zero, don't save changes.
*/
void changeTime( long minutes, timetrackerstorage* storage );
/**
* Add minutes to time and session time by adding an event, and write to storage.
*
* @param minutesSession minutes to add to task session time
* @param minutes minutes to add to task time
* @param storage Pointer to timetrackerstorage instance.
* If zero, don't save changes.
*/
void changeTimes
( long minutesSession, long minutes, timetrackerstorage* storage=0 );
/** adds minutes to total and session time by adding an event
*
* @param minutesSession minutes to add to task total session time
* @param minutes minutes to add to task total time
*/
void changeTotalTimes( long minutesSession, long minutes );
/** Adds minutes to the time of the task and the total time of its supertasks. This does not add an event.
*
* @param minutes minutes to add to the time
* @returns A QString with the error message, in case of no error an empty QString.
*
*/
QString addTime( long minutes );
/** Adds minutes to the total time of the task and its supertasks. This does not add an event.
*
* @param minutes minutes to add to the time
* @returns A QString with the error message, in case of no error an empty QString.
*
*/
QString addTotalTime( long minutes );
/** Adds minutes to the task's session time and its supertasks' total session time. This does not add an event.
*
* @param minutes minutes to add to the session time
* @returns A QString with the error message, in case of no error an empty QString.
*
*/
QString addSessionTime( long minutes );
/** Adds minutes to the task's and its supertasks' total session time. This does not add an event.
*
* @param minutes minutes to add to the session time
* @returns A QString with the error message, in case of no error an empty QString.
*
*/
QString addTotalSessionTime( long minutes );
/** Sets the time (not session time). This does not add an event.
*
* @param minutes minutes to set time to
*
*/
QString setTime( long minutes );
/** Sets the total time, does not change the parent's total time.
This means the parent's total time can run out of sync.
*/
void setTotalTime( long minutes ) { mTotalTime=minutes; };
/** Sets the total session time, does not change the parent's total session time.
This means the parent's total session time can run out of sync.
*/
void setTotalSessionTime( long minutes ) { mTotalSessionTime=minutes; };
/** A recursive function to calculate the total time of a task. */
QString <API key>();
/** A recursive function to calculate the total session time of a task. */
QString <API key>();
/** Sets the session time.
* Set the session time without changing totalTime nor sessionTime.
* Do not change the parent's totalTime.
* Do not add an event.
* See also: changeTimes(long, long) and resetTimes
*
* @param minutes minutes to set session time to
*
*/
QString setSessionTime( long minutes );
/**
* Reset all times to 0 and adjust parent task's totalTiMes.
*/
void resetTimes();
/** @return time in minutes */
long time() const;
/** @return total time in minutes */
long totalTime() const { return mTotalTime; };
long sessionTime() const;
long totalSessionTime() const { return mTotalSessionTime; };
KDateTime sessionStartTiMe() const;
/**
* Return time the task was started.
*/
QDateTime startTime() const;
/** sets session time to zero. */
void startNewSession();
//@{ desktop related functions
void setDesktopList ( DesktopList dl );
DesktopList desktops() const;
QString getDesktopStr() const;
//@{ name related functions
/** sets the name of the task
* @param name a pointer to the name. A deep copy will be made.
* @param storage a pointer to a timetrackerstorage object.
*/
void setName( const QString& name, timetrackerstorage* storage );
/** sets the description of the task
*/
void setDescription( const QString& description);
/** returns the name of this task.
* @return a pointer to the name.
*/
QString name() const;
/** returns the description of this task.
* @return a pointer to the description.
*/
QString description() const;
/**
* Returns that task name, prefixed by parent tree up to root.
*
* Task names are separated by a forward slash: /
*/
QString fullName() const;
/** Update the display of the task (all columns) in the UI. */
void update();
//@{ the state of a Task - stopped, running
/** starts or stops a task
* @param on true or false for starting or stopping a task
* @param storage a pointer to a timetrackerstorage object.
* @param when time when the task was started or stopped. Normally
QDateTime::currentDateTime, but if calendar has
been changed by another program and being reloaded
the task is set to running with another start date
*/
void setRunning( bool on, timetrackerstorage* storage,
const QDateTime &when = QDateTime::currentDateTime() );
/** Resume the running state of a task.
* This is the same as setrunning, but the storage is not modified.
*/
void resumeRunning();
/** return the state of a task - if it's running or not
* @return true or false depending on whether the task is running
*/
bool isRunning() const;
/**
* Parses an incidence. This is needed e.g. when you create a task out of a todo.
* You read the todo, extract its custom properties (like session time)
* and use these data to initialize the task.
*/
bool parseIncidence( const KCalCore::Incidence::Ptr &,
long& sessionMinutes);
/**
* Load the todo passed in with this tasks info.
*/
KCalCore::Todo::Ptr asTodo(KCalCore::Todo::Ptr &calendar) const;
/**
* Set a task's description
* A description is a comment.
*/
void setDescription( QString desc, timetrackerstorage* storage );
/**
* Add a comment to this task.
* A comment is called "description" in the context of KCalCore::ToDo
*/
void addComment( const QString &comment, timetrackerstorage* storage );
/** Retrieve the entire comment for the task. */
QString comment() const;
/** tells you whether this task is the root of the task tree */
bool isRoot() const { return parent() == 0; }
/** remove Task with all it's children
* @param storage a pointer to a timetrackerstorage object.
*/
bool remove( timetrackerstorage* storage );
/**
* Update percent complete for this task.
*
* Tasks that are complete (i.e., percent = 100) do not show up in
* taskview. If percent NULL, set to zero. If greater than 100, set to
* 100. If less than zero, set to zero.
*/
void setPercentComplete(const int percent, timetrackerstorage *storage);
int percentComplete() const;
/**
* Update priority for this task.
*
* Priority is allowed from 0 to 9. 0 unspecified, 1 highest and 9 lowest.
*/
void setPriority( int priority );
int priority() const;
/** Sets an appropriate icon for this task based on its level of
* completion */
void setPixmapProgress();
/** Return true if task is complete (percent complete equals 100). */
bool isComplete();
protected:
void <API key>( long minutesSession, long minutes );
Q_SIGNALS:
void totalTimesChanged( long minutesSession, long minutes);
/** signal that we're about to delete a task */
void deletingTask(Task* thisTask);
protected Q_SLOTS:
/** animate the active icon */
void updateActiveIcon();
private:
// Original KCalCore::Todo object
KCalCore::Todo::Ptr taskTodo;
/** if the time or session time is negative set them to zero */
void noNegativeTimes();
/** populate a ToDo with provided data */
void populateTodo(const QString& taskName, const QString& taskDescription, long minutes, long sessionTime, DesktopList desktops);
/** initialize a task */
void init(bool konsolemode=false);
static QVector<QPixmap*> *icons;
/** Last time this task was started. */
QDateTime mLastStart;
/** totals of the whole subtree including self */
long mTotalTime;
long mTotalSessionTime;
QTimer *mTimer;
int mCurrentPic;
/** Don't need to update storage when deleting task from list. */
bool mRemoving;
};
#endif // KTIMETRACKER_TASK_H
|
# CONFIG
ROOTPWD="1234"
USERNAME="cubie"
USERPASS="1234"
#Main Section
if [[ $EUID -ne 0 ]]; then
echo "You must be a root user" 2>&1
exit 1
fi
useradd -m -U -d /home/$USERNAME -s /bin/bash $USERNAME
# set User password to 1234
(echo $USERPASS;echo $USERPASS;) | passwd $USERNAME
# Do NOT force password change upon first login as it will prevent autologin :(
adduser $USERNAME sudo
DEST_LANG="en_US"
DEST_LANGUAGE="en"
echo -e $DEST_LANG'.UTF-8 UTF-8\n' >> /etc/locale.gen
echo -e 'fr_FR.UTF-8 UTF-8\n' >> /etc/locale.gen
echo -e 'LANG="'$DEST_LANG'.UTF-8"\nLANGUAGE="'$DEST_LANG':'$DEST_LANGUAGE'"\n' > /etc/default/locale
dpkg-reconfigure -f noninteractive locales
update-locale
# Setup apt-sources
sourcesFile="/etc/apt/sources.list"
rm $sourcesFile
touch $sourcesFile
#Get all info running : sudo netselect-apt -a armhf -n -s -c fr jessie
# Or : sudo netselect-apt -a armhf -n -s -c fr wheezy
#Edit output file to add wheezy updates and uncomment security + backports
#Jessie
echo "# Debian packages for Jessie" >> $sourcesFile
echo "deb http://debian.mirrors.ovh.net/debian/ jessie main contrib non-free" >> $sourcesFile
echo "deb http://debian.mirrors.ovh.net/debian/ jessie-updates main contrib non-free" >> $sourcesFile
echo "#Security updates for stable" >> $sourcesFile
echo "deb http://security.debian.org/ stable/updates main contrib non-free" >> $sourcesFile
echo "deb http://ftp.debian.org/debian/ jessie-backports main contrib non-free" >> $sourcesFile
# Wheezy
echo "# Debian packages for wheezy" >> $sourcesFile
echo "deb http://debian.mirrors.ovh.net/debian/ wheezy main contrib non-free" >> $sourcesFile
echo "deb http://debian.mirrors.ovh.net/debian/ wheezy-updates main contrib non-free" >> $sourcesFile
echo "#Security updates for stable" >> $sourcesFile
echo "deb http://security.debian.org/ stable/updates main contrib non-free" >> $sourcesFile
echo "deb http://ftp.debian.org/debian/ wheezy-backports main contrib non-free" >> $sourcesFile
apt-get update
#Change Timezones
echo "Europe/Paris" > /etc/timezone
dpkg-reconfigure -f noninteractive tzdata
#UnusedTo configure keyboard :
#apt-get install console-data
# Install packages
#Put all packages here :)
INSTPKG="hdparm hddtemp console-setup console-data netselect-apt"
INSTPKG+=" bash-completion parted cpufrequtils unzip mosh"
INSTPKG+=" vim tmux htop sudo locate tree ncdu toilet figlet git mosh"
INSTPKG+=" xorg <API key> openbox xterm xinit obconf xscreensaver xscreensaver-gl menu obmenu"
INSTPKG+=" lightdm iceweasel x11vnc"
echo $INSTPKG
apt-get -y upgrade
export DEBIAN_FRONTEND=noninteractive; apt-get -y install $INSTPKG
#For wheezy only
export DEBIAN_FRONTEND=noninteractive; apt-get -y install -t wheezy-backports $INSTPKG
#Disable Sshd root login
#sed -e "s/PermitRootLogin no/PermitRootLogin yes/g" -i /etc/ssh/sshd_config
# Overclock - DANGER
#sudo sed -i "s/echo -n 1100000/echo -n 1008000/g" /etc/init.d/cpufrequtils
# Install RAMLOG - No ramlog in Jessie
#dpkg -i /tmp/ramlog_2.0.0_all.deb
#if ! grep -q "TMPFS_RAMFS_SIZE=256m" /etc/default/ramlog; then
# sed -e 's/TMPFS_RAMFS_SIZE=/TMPFS_RAMFS_SIZE=256m/g' -i /etc/default/ramlog
# sed -e 's/# Required-Start: $remote_fs $time/# Required-Start: $remote_fs $time ramlog/g' -i /etc/init.d/rsyslog
# sed -e 's/# Required-Stop: umountnfs $time/# Required-Stop: umountnfs $time ramlog/g' -i /etc/init.d/rsyslog
#rm /tmp/ramlog_2.0.0_all.deb
#insserv
# Cleanup APT
apt-get -y clean
# set root password to 1234
(echo $ROOTPWD;echo $ROOTPWD;) | passwd root
# force password change upon first login
chage -d 0 root
#Configure Xserver autostart
dpkg-reconfigure <API key>
adduser $USERNAME video
if ! grep -q $USERNAME /etc/lightdm/lightdm.conf; then
sed -i "s/#autologin-user=/autologin-user=$USERNAME/g" /etc/lightdm/lightdm.conf
sed -i "s/#<API key>=0/<API key>=0/g" /etc/lightdm/lightdm.conf
fi
#To enable connexion using crontab on DISPLAY :0.0
sed -i "s/xserver-allow-tcp=false/xserver-allow-tcp=true/g" /etc/lightdm/lightdm.conf
mkdir -p /home/$USERNAME/.config/openbox
echo "xhost +localhost &" > /home/$USERNAME/.config/openbox/autostart
echo "setxkbmap fr &" >> /home/$USERNAME/.config/openbox/autostart
echo "xterm -e '/sbin/ifconfig eth0 && read a' &" >> /home/$USERNAME/.config/openbox/autostart
echo "xset -dpms &" >> /home/$USERNAME/.config/openbox/autostart
echo "xset s noblank;xset s 0 0;xset s off" >> /home/$USERNAME/.config/openbox/autostart
chown -R $USERNAME:$USERNAME /home/$USERNAME/.config/openbox/autostart
chmod 755 /home/$USERNAME/.config/openbox/autostart
#Setup tmpfs for firefox profiles - All profiles will be in RAMDISK
mkdir -p /home/$USERNAME/.mozilla/firefox/
chown -R $USERNAME:$USERNAME /home/cubie/.mozilla/firefox
mkdir -p /media/ramdrive
if ! grep -q ramdrive /etc/fstab
then
echo "adding line to fstab"
echo 'ramdrive /media/ramdrive tmpfs size=225M,user,auto,exec,rw 0 0' | tee -a /etc/fstab
mount -a
fi
#Screensaver & Screen blanking stuff
#export DISPLAY=":0.0"
#xset -dpms
xset s noblank;xset s 0 0;xset s off
#xset + dpms
#A inverser pour les xset s
#xset s activate
#xset s reset
#xset dpms force on off suspend standby
#For Cubie2 Jessie
#Config
export DISPLAY=":0.0"
xhost +localhost &
xset s off
xset -dpms
#Turn Off
xset dpms force off
#Turn On
reboot
#For rpi2 (some commands need root others don't)
#config
export DISPLAY=":0.0"
xhost +localhost &
xset s off
xset -dpms
#Turn off
tvservice --off > /dev/null
#Turn on
tvservice --preferred > /dev/null
fbset -depth 8; fbset -depth 16; xrefresh
|
// C++ Implementation: Audio::OggStream
#include "config.h"
#ifdef HAVE_OGG
#include "OggStream.h"
#include "OggData.h"
#include "config.h"
#include <utility>
#include <limits>
#include <stdlib.h>
#include <vorbis/vorbisfile.h>
#include "vsfilesystem.h"
#ifndef OGG_BUFFER_SIZE
#define OGG_BUFFER_SIZE 4096*2*2
#endif
namespace Audio {
OggStream::OggStream(const std::string& path, VSFileSystem::VSFileType type) throw(Exception)
: Stream(path)
{
if ( file.OpenReadOnly(path, type) <= VSFileSystem::Ok )
throw FileOpenException("Error opening file \"" + path + "\"");
oggData = new __impl::OggData(file, getFormatInternal(), 0);
// Cache duration in case ov_time_total gets expensive
duration = ov_time_total( &oggData->vorbisFile, oggData->streamIndex );
// Allocate read buffer
readBufferSize = OGG_BUFFER_SIZE;
readBufferAvail = 0;
readBuffer = malloc(readBufferSize);
}
OggStream::~OggStream()
{
// destructor closes the file already
delete oggData;
}
double OggStream::getLengthImpl() const throw(Exception)
{
return duration;
}
double OggStream::getPositionImpl() const throw()
{
return ov_time_tell( &oggData->vorbisFile );
}
void OggStream::seekImpl(double position) throw(Exception)
{
if (position >= duration)
throw <API key>();
readBufferAvail = 0;
switch (ov_time_seek(&oggData->vorbisFile, position)) {
case 0: break;
case OV_ENOSEEK: throw Exception("Stream not seekable");
case OV_EINVAL: throw Exception("Invalid argument or state");
case OV_EREAD: throw Exception("Read error");
case OV_EFAULT: throw Exception("Internal logic fault, bug or heap/stack corruption");
case OV_EBADLINK:throw <API key>(false);
default: throw Exception("Unidentified error code");
}
}
void OggStream::getBufferImpl(void *&buffer, unsigned int &bufferSize) throw(Exception)
{
if (readBufferAvail == 0)
throw NoBufferException();
buffer = readBuffer;
bufferSize = readBufferAvail;
}
void OggStream::nextBufferImpl() throw(Exception)
{
int curStream = oggData->streamIndex;
long ovr;
switch( ovr = ov_read(&oggData->vorbisFile,
(char*)readBuffer, readBufferSize,
0, 2, 1, &curStream) )
{
case OV_HOLE: throw <API key>(false);
case OV_EBADLINK: throw <API key>(false);
case 0: throw <API key>();
default: readBufferSize = ovr;
}
}
};
#endif // HAVE_OGG
|
angular.module('component').component('getGit', {
template: `
<section>
<h1>GIT : Repro</h1>
<div class="controller" >
<div git-repro="user : 'gaetanV',repositories :'angular_directive',branch:'master',path:'angular1/directive/gitRepro.directive.js'" > </div>
</div>
</section>
`,
});
|
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta name="Generator" content="ReWorX 1.1 (021204) - http:
<meta name="Originator" content="Microsoft Word 9" />
<title>N_int32</title>
<link rel="StyleSheet" type="text/css" href="SNAP%20Graphics%20Architecture.css" />
<script language="JavaScript" src="RePublicoToolbar.js">
</script>
<script type="text/javascript" src="RePublico.js">
</script>
</head>
<body style="tab-interval:.5in;" lang="EN-US" link="blue" vlink="purple" class="rpomain" onbeforeprint="JavaScript:<API key>();" onafterprint="JavaScript:<API key>();" onload="JavaScript:RePublicoTrack('index.html','toc',true);RePublicoShowHide();RePublicoBanner(2);">
<table class="RpoToolbar" cellpadding="0" cellspacing="0" onselectstart="javascript:return false;">
<tr valign="middle">
<td>
<table title="Supported Browsers" class="buttonOff" cellpadding="0" cellspacing="0" onmouseover="javascript:mouseoverButton(this);" onmouseout="javascript:mouseoutButton(this);" onmousedown="javascript:mousedownButton(this);" onmouseup="javascript:mouseupButton(this);" href="JavaScript:executeButton('SupportedBrowsers.html','');" onimage="./Images/RpoButtonHomeOn.gif" offimage="./Images/RpoButtonHomeOff.gif">
<tr valign="middle">
<td class="buttonText">
<img hspace="1" height="16" width="16" border="0" alt="Supported Browsers" src="./Images/RpoButtonHomeOff.gif" />
</td>
<td class="buttonText">
Home
</td>
</tr>
</table>
</td>
<td>
<table title="N_int16" class="buttonOff" cellpadding="0" cellspacing="0" onmouseover="javascript:mouseoverButton(this);" onmouseout="javascript:mouseoutButton(this);" onmousedown="javascript:mousedownButton(this);" onmouseup="javascript:mouseupButton(this);" href="JavaScript:executeButton('N_int16.html','');" onimage="./Images/RpoButtonPreviousOn.gif" offimage="./Images/<API key>.gif">
<tr valign="middle">
<td class="buttonText">
<img hspace="1" height="16" width="16" border="0" alt="N_int16" src="./Images/<API key>.gif" />
</td>
<td class="buttonText">
Previous
</td>
</tr>
</table>
</td>
<td>
<table title="N_int8" class="buttonOff" cellpadding="0" cellspacing="0" onmouseover="javascript:mouseoverButton(this);" onmouseout="javascript:mouseoutButton(this);" onmousedown="javascript:mousedownButton(this);" onmouseup="javascript:mouseupButton(this);" href="JavaScript:executeButton('N_int8.html','');" onimage="./Images/RpoButtonNextOn.gif" offimage="./Images/RpoButtonNextOff.gif">
<tr valign="middle">
<td class="buttonText">
<img hspace="1" height="16" width="16" border="0" alt="N_int8" src="./Images/RpoButtonNextOff.gif" />
</td>
<td class="buttonText">
Next
</td>
</tr>
</table>
</td>
<td>
<table title="Type Definitions" class="buttonOff" cellpadding="0" cellspacing="0" onmouseover="javascript:mouseoverButton(this);" onmouseout="javascript:mouseoutButton(this);" onmousedown="javascript:mousedownButton(this);" onmouseup="javascript:mouseupButton(this);" href="JavaScript:executeButton('TypeDefinitions.html','');" onimage="./Images/RpoButtonUpOn.gif" offimage="./Images/RpoButtonUpOff.gif">
<tr valign="middle">
<td class="buttonText">
<img hspace="1" height="16" width="16" border="0" alt="Type Definitions" src="./Images/RpoButtonUpOff.gif" />
</td>
<td class="buttonText">
Up
</td>
</tr>
</table>
</td>
<td width="100%">
</td>
</tr>
</table>
<div class="Section3">
<p style="tab-stops:'.45in .7in .95in 1.2in';" class="FuncHeading3">
N_int32
</p>
<p style="tab-stops:'.45in .7in .95in 1.2in';" class="MethodSection">
Declaration
</p>
<p style="tab-stops:'.45in .7in .95in 1.2in';" class="Preformatted">
typedef long N_int32
</p>
<p style="tab-stops:'.45in .7in .95in 1.2in';" class="MethodSection">
Prototype In
</p>
<p style="tab-stops:'.45in .7in .95in 1.2in';" class="MsoBodyText">
snap/common.h
</p>
<p style="tab-stops:'.45in .7in .95in 1.2in';" class="MethodSection">
Description
</p>
<p style="tab-stops:'.45in .7in .95in 1.2in';" class="MsoBodyText">
Fundamental type definition for a 32-bit signed value.
</p>
</div>
<p class="CitationBody">
Copyright &
</p>
</body>
</html>
|
/* <API key>: GPL-2.0-or-later */
#ifndef _UFSHCD_H
#define _UFSHCD_H
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/rwsem.h>
#include <linux/workqueue.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/wait.h>
#include <linux/bitops.h>
#include <linux/pm_runtime.h>
#include <linux/clk.h>
#include <linux/completion.h>
#include <linux/regulator/consumer.h>
#include <linux/bitfield.h>
#include <linux/devfreq.h>
#include <linux/blk-crypto-profile.h>
#include "unipro.h"
#include <asm/irq.h>
#include <asm/byteorder.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_tcq.h>
#include <scsi/scsi_dbg.h>
#include <scsi/scsi_eh.h>
#include "ufs.h"
#include "ufs_quirks.h"
#include "ufshci.h"
#define UFSHCD "ufshcd"
#define <API key> "0.2"
struct ufs_hba;
enum dev_cmd_type {
DEV_CMD_TYPE_NOP = 0x0,
DEV_CMD_TYPE_QUERY = 0x1,
};
enum ufs_event_type {
/* uic specific errors */
UFS_EVT_PA_ERR = 0,
UFS_EVT_DL_ERR,
UFS_EVT_NL_ERR,
UFS_EVT_TL_ERR,
UFS_EVT_DME_ERR,
/* fatal errors */
<API key>,
UFS_EVT_FATAL_ERR,
<API key>,
UFS_EVT_RESUME_ERR,
UFS_EVT_SUSPEND_ERR,
UFS_EVT_WL_SUSP_ERR,
UFS_EVT_WL_RES_ERR,
/* abnormal events */
UFS_EVT_DEV_RESET,
UFS_EVT_HOST_RESET,
UFS_EVT_ABORT,
UFS_EVT_CNT,
};
/**
* struct uic_command - UIC command structure
* @command: UIC command
* @argument1: UIC command argument 1
* @argument2: UIC command argument 2
* @argument3: UIC command argument 3
* @cmd_active: Indicate if UIC command is outstanding
* @done: UIC command completion
*/
struct uic_command {
u32 command;
u32 argument1;
u32 argument2;
u32 argument3;
int cmd_active;
struct completion done;
};
/* Used to differentiate the power management options */
enum ufs_pm_op {
UFS_RUNTIME_PM,
UFS_SYSTEM_PM,
UFS_SHUTDOWN_PM,
};
/* Host <-> Device UniPro Link state */
enum uic_link_state {
UIC_LINK_OFF_STATE = 0, /* Link powered down or disabled */
<API key> = 1, /* Link is in Fast/Slow/Sleep state */
<API key> = 2, /* Link is in Hibernate state */
<API key> = 3, /* Link is in broken state */
};
#define ufshcd_is_link_off(hba) ((hba)->uic_link_state == UIC_LINK_OFF_STATE)
#define <API key>(hba) ((hba)->uic_link_state == \
<API key>)
#define <API key>(hba) ((hba)->uic_link_state == \
<API key>)
#define <API key>(hba) ((hba)->uic_link_state == \
<API key>)
#define ufshcd_set_link_off(hba) ((hba)->uic_link_state = UIC_LINK_OFF_STATE)
#define <API key>(hba) ((hba)->uic_link_state = \
<API key>)
#define <API key>(hba) ((hba)->uic_link_state = \
<API key>)
#define <API key>(hba) ((hba)->uic_link_state = \
<API key>)
#define <API key>(h) \
((h)->curr_dev_pwr_mode = UFS_ACTIVE_PWR_MODE)
#define <API key>(h) \
((h)->curr_dev_pwr_mode = UFS_SLEEP_PWR_MODE)
#define <API key>(h) \
((h)->curr_dev_pwr_mode = <API key>)
#define <API key>(h) \
((h)->curr_dev_pwr_mode = <API key>)
#define <API key>(h) \
((h)->curr_dev_pwr_mode == UFS_ACTIVE_PWR_MODE)
#define <API key>(h) \
((h)->curr_dev_pwr_mode == UFS_SLEEP_PWR_MODE)
#define <API key>(h) \
((h)->curr_dev_pwr_mode == <API key>)
#define <API key>(h) \
((h)->curr_dev_pwr_mode == <API key>)
/*
* UFS Power management levels.
* Each level is in increasing order of power savings, except DeepSleep
* which is lower than PowerDown with power on but not PowerDown with
* power off.
*/
enum ufs_pm_level {
UFS_PM_LVL_0,
UFS_PM_LVL_1,
UFS_PM_LVL_2,
UFS_PM_LVL_3,
UFS_PM_LVL_4,
UFS_PM_LVL_5,
UFS_PM_LVL_6,
UFS_PM_LVL_MAX
};
struct ufs_pm_lvl_states {
enum ufs_dev_pwr_mode dev_state;
enum uic_link_state link_state;
};
/**
* struct ufshcd_lrb - local reference block
* @utr_descriptor_ptr: UTRD address of the command
* @ucd_req_ptr: UCD address of the command
* @ucd_rsp_ptr: Response UPIU address for this command
* @ucd_prdt_ptr: PRDT address of the command
* @utrd_dma_addr: UTRD dma address for debug
* @ucd_prdt_dma_addr: PRDT dma address for debug
* @ucd_rsp_dma_addr: UPIU response dma address for debug
* @ucd_req_dma_addr: UPIU request dma address for debug
* @cmd: pointer to SCSI command
* @sense_buffer: pointer to sense buffer address of the SCSI command
* @sense_bufflen: Length of the sense buffer
* @scsi_status: SCSI status of the command
* @command_type: SCSI, UFS, Query.
* @task_tag: Task tag of the command
* @lun: LUN of the command
* @intr_cmd: Interrupt command (doesn't participate in interrupt aggregation)
* @issue_time_stamp: time stamp for debug purposes
* @compl_time_stamp: time stamp for statistics
* @crypto_key_slot: the key slot to use for inline crypto (-1 if none)
* @data_unit_num: the data unit number for the first block for inline crypto
* @req_abort_skip: skip request abort task flag
*/
struct ufshcd_lrb {
struct <API key> *utr_descriptor_ptr;
struct utp_upiu_req *ucd_req_ptr;
struct utp_upiu_rsp *ucd_rsp_ptr;
struct ufshcd_sg_entry *ucd_prdt_ptr;
dma_addr_t utrd_dma_addr;
dma_addr_t ucd_req_dma_addr;
dma_addr_t ucd_rsp_dma_addr;
dma_addr_t ucd_prdt_dma_addr;
struct scsi_cmnd *cmd;
u8 *sense_buffer;
unsigned int sense_bufflen;
int scsi_status;
int command_type;
int task_tag;
u8 lun; /* UPIU LUN id field is only 8-bit wide */
bool intr_cmd;
ktime_t issue_time_stamp;
ktime_t compl_time_stamp;
#ifdef <API key>
int crypto_key_slot;
u64 data_unit_num;
#endif
bool req_abort_skip;
};
/**
* struct ufs_query - holds relevant data structures for query request
* @request: request upiu and function
* @descriptor: buffer for sending/receiving descriptor
* @response: response upiu and response
*/
struct ufs_query {
struct ufs_query_req request;
u8 *descriptor;
struct ufs_query_res response;
};
/**
* struct ufs_dev_cmd - all assosiated fields with device management commands
* @type: device management command type - Query, NOP OUT
* @lock: lock to allow one command at a time
* @complete: internal commands completion
*/
struct ufs_dev_cmd {
enum dev_cmd_type type;
struct mutex lock;
struct completion *complete;
struct ufs_query query;
};
/**
* struct ufs_clk_info - UFS clock related info
* @list: list headed by hba->clk_list_head
* @clk: clock node
* @name: clock name
* @max_freq: maximum frequency supported by the clock
* @min_freq: min frequency that can be used for clock scaling
* @curr_freq: indicates the current frequency that it is set to
* @keep_link_active: indicates that the clk should not be disabled if
link is active
* @enabled: variable to check against multiple enable/disable
*/
struct ufs_clk_info {
struct list_head list;
struct clk *clk;
const char *name;
u32 max_freq;
u32 min_freq;
u32 curr_freq;
bool keep_link_active;
bool enabled;
};
enum <API key> {
PRE_CHANGE,
POST_CHANGE,
};
struct ufs_pa_layer_attr {
u32 gear_rx;
u32 gear_tx;
u32 lane_rx;
u32 lane_tx;
u32 pwr_rx;
u32 pwr_tx;
u32 hs_rate;
};
struct ufs_pwr_mode_info {
bool is_valid;
struct ufs_pa_layer_attr info;
};
struct ufs_hba_variant_ops {
const char *name;
int (*init)(struct ufs_hba *);
void (*exit)(struct ufs_hba *);
u32 (*get_ufs_hci_version)(struct ufs_hba *);
int (*clk_scale_notify)(struct ufs_hba *, bool,
enum <API key>);
int (*setup_clocks)(struct ufs_hba *, bool,
enum <API key>);
int (*hce_enable_notify)(struct ufs_hba *,
enum <API key>);
int (*link_startup_notify)(struct ufs_hba *,
enum <API key>);
int (*pwr_change_notify)(struct ufs_hba *,
enum <API key> status,
struct ufs_pa_layer_attr *,
struct ufs_pa_layer_attr *);
void (*setup_xfer_req)(struct ufs_hba *, int, bool);
void (*setup_task_mgmt)(struct ufs_hba *, int, u8);
void (*hibern8_notify)(struct ufs_hba *, enum uic_cmd_dme,
enum <API key>);
int (*apply_dev_quirks)(struct ufs_hba *hba);
void (*fixup_dev_quirks)(struct ufs_hba *hba);
int (*suspend)(struct ufs_hba *, enum ufs_pm_op,
enum <API key>);
int (*resume)(struct ufs_hba *, enum ufs_pm_op);
void (*dbg_register_dump)(struct ufs_hba *hba);
int (*phy_initialization)(struct ufs_hba *);
int (*device_reset)(struct ufs_hba *hba);
void (*<API key>)(struct ufs_hba *hba,
struct devfreq_dev_profile *profile,
void *data);
int (*program_key)(struct ufs_hba *hba,
const union <API key> *cfg, int slot);
void (*event_notify)(struct ufs_hba *hba,
enum ufs_event_type evt, void *data);
};
/* clock gating state */
enum clk_gating_state {
CLKS_OFF,
CLKS_ON,
REQ_CLKS_OFF,
REQ_CLKS_ON,
};
/**
* struct ufs_clk_gating - UFS clock gating related info
* @gate_work: worker to turn off clocks after some delay as specified in
* delay_ms
* @ungate_work: worker to turn on clocks that will be used in case of
* interrupt context
* @state: the current clocks state
* @delay_ms: gating delay in ms
* @is_suspended: clk gating is suspended when set to 1 which can be used
* during suspend/resume
* @delay_attr: sysfs attribute to control delay_attr
* @enable_attr: sysfs attribute to enable/disable clock gating
* @is_enabled: Indicates the current status of clock gating
* @is_initialized: Indicates whether clock gating is initialized or not
* @active_reqs: number of requests that are pending and should be waited for
* completion before gating clocks.
*/
struct ufs_clk_gating {
struct delayed_work gate_work;
struct work_struct ungate_work;
enum clk_gating_state state;
unsigned long delay_ms;
bool is_suspended;
struct device_attribute delay_attr;
struct device_attribute enable_attr;
bool is_enabled;
bool is_initialized;
int active_reqs;
struct workqueue_struct *clk_gating_workq;
};
struct ufs_saved_pwr_info {
struct ufs_pa_layer_attr info;
bool is_valid;
};
/**
* struct ufs_clk_scaling - UFS clock scaling related data
* @active_reqs: number of requests that are pending. If this is zero when
* devfreq ->target() function is called then schedule "suspend_work" to
* suspend devfreq.
* @tot_busy_t: Total busy time in current polling window
* @window_start_t: Start time (in jiffies) of the current polling window
* @busy_start_t: Start time of current busy period
* @enable_attr: sysfs attribute to enable/disable clock scaling
* @saved_pwr_info: UFS power mode may also be changed during scaling and this
* one keeps track of previous power mode.
* @workq: workqueue to schedule devfreq suspend/resume work
* @suspend_work: worker to suspend devfreq
* @resume_work: worker to resume devfreq
* @min_gear: lowest HS gear to scale down to
* @is_enabled: tracks if scaling is currently enabled or not, controlled by
clkscale_enable sysfs node
* @is_allowed: tracks if scaling is currently allowed or not, used to block
clock scaling which is not invoked from devfreq governor
* @is_initialized: Indicates whether clock scaling is initialized or not
* @is_busy_started: tracks if busy period has started or not
* @is_suspended: tracks if devfreq is suspended or not
*/
struct ufs_clk_scaling {
int active_reqs;
unsigned long tot_busy_t;
ktime_t window_start_t;
ktime_t busy_start_t;
struct device_attribute enable_attr;
struct ufs_saved_pwr_info saved_pwr_info;
struct workqueue_struct *workq;
struct work_struct suspend_work;
struct work_struct resume_work;
u32 min_gear;
bool is_enabled;
bool is_allowed;
bool is_initialized;
bool is_busy_started;
bool is_suspended;
};
#define <API key> 8
/**
* struct ufs_event_hist - keeps history of errors
* @pos: index to indicate cyclic buffer position
* @reg: cyclic buffer for registers value
* @tstamp: cyclic buffer for time stamp
* @cnt: error counter
*/
struct ufs_event_hist {
int pos;
u32 val[<API key>];
ktime_t tstamp[<API key>];
unsigned long long cnt;
};
/**
* struct ufs_stats - keeps usage/err statistics
* @last_intr_status: record the last interrupt status.
* @last_intr_ts: record the last interrupt timestamp.
* @hibern8_exit_cnt: Counter to keep track of number of exits,
* reset this after link-startup.
* @<API key>: Set time after the hibern8 exit.
* Clear after the first successful command completion.
*/
struct ufs_stats {
u32 last_intr_status;
ktime_t last_intr_ts;
u32 hibern8_exit_cnt;
ktime_t <API key>;
struct ufs_event_hist event[UFS_EVT_CNT];
};
/**
* enum ufshcd_state - UFS host controller state
* @UFSHCD_STATE_RESET: Link is not operational. Postpone SCSI command
* processing.
* @<API key>: The host controller is operational and can process
* SCSI commands.
* @<API key>: The error handler has been scheduled.
* SCSI commands may be submitted to the controller.
* @<API key>: The error handler has been scheduled. Fail
* newly submitted SCSI commands with error code DID_BAD_TARGET.
* @UFSHCD_STATE_ERROR: An unrecoverable error occurred, e.g. link recovery
* failed. Fail all SCSI commands with error code DID_ERROR.
*/
enum ufshcd_state {
UFSHCD_STATE_RESET,
<API key>,
<API key>,
<API key>,
UFSHCD_STATE_ERROR,
};
enum ufshcd_quirks {
/* Interrupt aggregation support is broken */
<API key> = 1 << 0,
/*
* delay before each dme command is required as the unipro
* layer has shown instabilities
*/
<API key> = 1 << 1,
/*
* If UFS host controller is having issue in processing LCC (Line
* Control Command) coming from device then enable this quirk.
* When this quirk is enabled, host controller driver should disable
* the LCC transmission on UFS device (by clearing TX_LCC_ENABLE
* attribute of device to 0).
*/
<API key> = 1 << 2,
/*
* The attribute PA_RXHSUNTERMCAP specifies whether or not the
* inbound Link supports unterminated line in HS mode. Setting this
* attribute to 1 fixes moving to HS gear.
*/
<API key> = 1 << 3,
/*
* This quirk needs to be enabled if the host controller only allows
* accessing the peer dme attributes in AUTO mode (FAST AUTO or
* SLOW AUTO).
*/
<API key> = 1 << 4,
/*
* This quirk needs to be enabled if the host controller doesn't
* advertise the correct version in UFS_VER register. If this quirk
* is enabled, standard UFS host driver will call the vendor specific
* ops (get_ufs_hci_version) to get the correct version.
*/
<API key> = 1 << 5,
/*
* Clear handling for transfer/task request list is just opposite.
*/
<API key> = 1 << 6,
/*
* This quirk needs to be enabled if host controller doesn't allow
* that the interrupt aggregation timer and counter are reset by s/w.
*/
<API key> = 1 << 7,
/*
* This quirks needs to be enabled if host controller cannot be
* enabled via HCE register.
*/
<API key> = 1 << 8,
/*
* This quirk needs to be enabled if the host controller regards
* resolution of the values of PRDTO and PRDTL in UTRD as byte.
*/
<API key> = 1 << 9,
/*
* This quirk needs to be enabled if the host controller reports
* OCS FATAL ERROR with device error through sense data
*/
<API key> = 1 << 10,
/*
* This quirk needs to be enabled if the host controller has
* auto-hibernate capability but it doesn't work.
*/
<API key> = 1 << 11,
/*
* This quirk needs to disable manual flush for write booster
*/
<API key> = 1 << 12,
/*
* This quirk needs to disable unipro timeout values
* before power mode change
*/
<API key> = 1 << 13,
/*
* This quirk allows only sg entries aligned with page size.
*/
<API key> = 1 << 14,
};
enum ufshcd_caps {
/* Allow dynamic clk gating */
<API key> = 1 << 0,
/* Allow hiberb8 with clk gating */
<API key> = 1 << 1,
/* Allow dynamic clk scaling */
<API key> = 1 << 2,
/* Allow auto bkops to enabled during runtime suspend */
<API key> = 1 << 3,
/*
* This capability allows host controller driver to use the UFS HCI's
* interrupt aggregation capability.
* CAUTION: Enabling this might reduce overall UFS throughput.
*/
<API key> = 1 << 4,
/*
* This capability allows the device auto-bkops to be always enabled
* except during suspend (both runtime and suspend).
* Enabling this capability means that device will always be allowed
* to do background operation when it's active but it might degrade
* the performance of ongoing read/write operations.
*/
<API key> = 1 << 5,
/*
* This capability allows host controller driver to automatically
* enable runtime power management by itself instead of waiting
* for userspace to control the power management.
*/
<API key> = 1 << 6,
/*
* This capability allows the host controller driver to turn-on
* WriteBooster, if the underlying device supports it and is
* provisioned to be used. This would increase the write performance.
*/
UFSHCD_CAP_WB_EN = 1 << 7,
/*
* This capability allows the host controller driver to use the
* inline crypto engine, if it is present
*/
UFSHCD_CAP_CRYPTO = 1 << 8,
/*
* This capability allows the controller regulators to be put into
* lpm mode aggressively during clock gating.
* This would increase power savings.
*/
<API key> = 1 << 9,
/*
* This capability allows the host controller driver to use DeepSleep,
* if it is supported by the UFS device. The host controller driver must
* support device hardware reset via the hba->device_reset() callback,
* in order to exit DeepSleep state.
*/
<API key> = 1 << 10,
/*
* This capability allows the host controller driver to use temperature
* notification if it is supported by the UFS device.
*/
<API key> = 1 << 11,
};
struct <API key> {
struct devfreq_dev_profile devfreq_profile;
struct <API key> ondemand_data;
u16 hba_enable_delay_us;
u32 wb_flush_threshold;
};
#ifdef CONFIG_SCSI_UFS_HPB
/**
* struct ufshpb_dev_info - UFSHPB device related info
* @num_lu: the number of user logical unit to check whether all lu finished
* initialization
* @rgn_size: device reported HPB region size
* @srgn_size: device reported HPB sub-region size
* @slave_conf_cnt: counter to check all lu finished initialization
* @hpb_disabled: flag to check if HPB is disabled
* @max_hpb_single_cmd: device reported <API key> value
* @is_legacy: flag to check HPB 1.0
* @control_mode: either host or device
*/
struct ufshpb_dev_info {
int num_lu;
int rgn_size;
int srgn_size;
atomic_t slave_conf_cnt;
bool hpb_disabled;
u8 max_hpb_single_cmd;
bool is_legacy;
u8 control_mode;
};
#endif
struct ufs_hba_monitor {
unsigned long chunk_size;
unsigned long nr_sec_rw[2];
ktime_t total_busy[2];
unsigned long nr_req[2];
/* latencies*/
ktime_t lat_sum[2];
ktime_t lat_max[2];
ktime_t lat_min[2];
u32 nr_queued[2];
ktime_t busy_start_ts[2];
ktime_t enabled_ts;
bool enabled;
};
struct ufs_hba {
void __iomem *mmio_base;
/* Virtual memory reference */
struct <API key> *ucdl_base_addr;
struct <API key> *utrdl_base_addr;
struct utp_task_req_desc *utmrdl_base_addr;
/* DMA memory reference */
dma_addr_t ucdl_dma_addr;
dma_addr_t utrdl_dma_addr;
dma_addr_t utmrdl_dma_addr;
struct Scsi_Host *host;
struct device *dev;
struct request_queue *cmd_queue;
/*
* This field is to keep a reference to "scsi_device" corresponding to
* "UFS device" W-LU.
*/
struct scsi_device *sdev_ufs_device;
struct scsi_device *sdev_rpmb;
#ifdef <API key>
struct device *hwmon_device;
#endif
enum ufs_dev_pwr_mode curr_dev_pwr_mode;
enum uic_link_state uic_link_state;
/* Desired UFS power management level during runtime PM */
enum ufs_pm_level rpm_lvl;
/* Desired UFS power management level during system PM */
enum ufs_pm_level spm_lvl;
struct device_attribute rpm_lvl_attr;
struct device_attribute spm_lvl_attr;
int pm_op_in_progress;
/* Auto-Hibernate Idle Timer register value */
u32 ahit;
struct ufshcd_lrb *lrb;
unsigned long outstanding_tasks;
spinlock_t outstanding_lock;
unsigned long outstanding_reqs;
u32 capabilities;
int nutrs;
int nutmrs;
u32 ufs_version;
const struct ufs_hba_variant_ops *vops;
struct <API key> *vps;
void *priv;
unsigned int irq;
bool is_irq_enabled;
enum ufs_ref_clk_freq dev_ref_clk_freq;
unsigned int quirks; /* Deviations from standard UFSHCI spec. */
/* Device deviations from standard UFS device spec. */
unsigned int dev_quirks;
struct blk_mq_tag_set tmf_tag_set;
struct request_queue *tmf_queue;
struct request **tmf_rqs;
struct uic_command *active_uic_cmd;
struct mutex uic_cmd_mutex;
struct completion *uic_async_done;
enum ufshcd_state ufshcd_state;
u32 eh_flags;
u32 intr_mask;
u16 ee_ctrl_mask; /* Exception event mask */
u16 ee_drv_mask; /* Exception event mask for driver */
u16 ee_usr_mask; /* Exception event mask for user (via debugfs) */
struct mutex ee_ctrl_mutex;
bool is_powered;
bool shutting_down;
struct semaphore host_sem;
/* Work Queues */
struct workqueue_struct *eh_wq;
struct work_struct eh_work;
struct work_struct eeh_work;
/* HBA Errors */
u32 errors;
u32 uic_error;
u32 saved_err;
u32 saved_uic_err;
struct ufs_stats ufs_stats;
bool force_reset;
bool force_pmc;
bool silence_err_logs;
/* Device management request data */
struct ufs_dev_cmd dev_cmd;
ktime_t last_dme_cmd_tstamp;
int nop_out_timeout;
/* Keeps information of the UFS device connected to this host */
struct ufs_dev_info dev_info;
bool auto_bkops_enabled;
struct ufs_vreg_info vreg_info;
struct list_head clk_list_head;
/* Number of requests aborts */
int req_abort_count;
/* Number of lanes available (1 or 2) for Rx/Tx */
u32 lanes_per_direction;
struct ufs_pa_layer_attr pwr_info;
struct ufs_pwr_mode_info max_pwr_info;
struct ufs_clk_gating clk_gating;
/* Control to enable/disable host capabilities */
u32 caps;
struct devfreq *devfreq;
struct ufs_clk_scaling clk_scaling;
bool is_sys_suspended;
enum bkops_status urgent_bkops_lvl;
bool <API key>;
struct rw_semaphore clk_scaling_lock;
unsigned char desc_size[QUERY_DESC_IDN_MAX];
atomic_t scsi_block_reqs_cnt;
struct device bsg_dev;
struct request_queue *bsg_queue;
struct delayed_work <API key>;
#ifdef CONFIG_SCSI_UFS_HPB
struct ufshpb_dev_info ufshpb_dev;
#endif
struct ufs_hba_monitor monitor;
#ifdef <API key>
union <API key> crypto_capabilities;
union <API key> *crypto_cap_array;
u32 crypto_cfg_register;
struct blk_crypto_profile crypto_profile;
#endif
#ifdef CONFIG_DEBUG_FS
struct dentry *debugfs_root;
struct delayed_work debugfs_ee_work;
u32 <API key>;
#endif
u32 luns_avail;
bool complete_put;
};
/* Returns true if clocks can be gated. Otherwise false */
static inline bool <API key>(struct ufs_hba *hba)
{
return hba->caps & <API key>;
}
static inline bool <API key>(struct ufs_hba *hba)
{
return hba->caps & <API key>;
}
static inline int <API key>(struct ufs_hba *hba)
{
return hba->caps & <API key>;
}
static inline bool <API key>(struct ufs_hba *hba)
{
return hba->caps & <API key>;
}
static inline bool <API key>(struct ufs_hba *hba)
{
return hba->caps & <API key>;
}
static inline bool <API key>(struct ufs_hba *hba)
{
return (hba->caps & <API key>) &&
!(hba->quirks & <API key>);
}
static inline bool <API key>(struct ufs_hba *hba)
{
return !!(<API key>(hba) &&
(hba->caps & <API key>));
}
static inline bool <API key>(struct ufs_hba *hba)
{
return (hba->capabilities & <API key>) &&
!(hba->quirks & <API key>);
}
static inline bool <API key>(struct ufs_hba *hba)
{
return FIELD_GET(<API key>, hba->ahit) ? true : false;
}
static inline bool <API key>(struct ufs_hba *hba)
{
return hba->caps & UFSHCD_CAP_WB_EN;
}
static inline bool <API key>(struct ufs_hba *hba)
{
return !hba->shutting_down;
}
#define ufshcd_writel(hba, val, reg) \
writel((val), (hba)->mmio_base + (reg))
#define ufshcd_readl(hba, reg) \
readl((hba)->mmio_base + (reg))
/**
* ufshcd_rmwl - read modify write into a register
* @hba - per adapter instance
* @mask - mask to apply on read value
* @val - actual value to write
* @reg - register address
*/
static inline void ufshcd_rmwl(struct ufs_hba *hba, u32 mask, u32 val, u32 reg)
{
u32 tmp;
tmp = ufshcd_readl(hba, reg);
tmp &= ~mask;
tmp |= (val & mask);
ufshcd_writel(hba, tmp, reg);
}
int ufshcd_alloc_host(struct device *, struct ufs_hba **);
void ufshcd_dealloc_host(struct ufs_hba *);
int ufshcd_hba_enable(struct ufs_hba *hba);
int ufshcd_init(struct ufs_hba *, void __iomem *, unsigned int);
int <API key>(struct ufs_hba *hba);
int <API key>(struct ufs_hba *hba);
void ufshcd_remove(struct ufs_hba *);
int <API key>(struct ufs_hba *hba);
int <API key>(struct ufs_hba *hba);
void ufshcd_delay_us(unsigned long us, unsigned long tolerance);
int <API key>(struct ufs_hba *hba, u32 reg, u32 mask,
u32 val, unsigned long interval_us,
unsigned long timeout_ms);
void <API key>(struct ufs_hba *hba, struct clk *refclk);
void <API key>(struct ufs_hba *hba, u32 id, u32 val);
void ufshcd_hba_stop(struct ufs_hba *hba);
static inline void check_upiu_size(void)
{
BUILD_BUG_ON(ALIGNED_UPIU_SIZE <
<API key> + QUERY_DESC_MAX_SIZE);
}
/**
* ufshcd_set_variant - set variant specific data to the hba
* @hba - per adapter instance
* @variant - pointer to variant specific data
*/
static inline void ufshcd_set_variant(struct ufs_hba *hba, void *variant)
{
BUG_ON(!hba);
hba->priv = variant;
}
/**
* ufshcd_get_variant - get variant specific data from the hba
* @hba - per adapter instance
*/
static inline void *ufshcd_get_variant(struct ufs_hba *hba)
{
BUG_ON(!hba);
return hba->priv;
}
static inline bool <API key>(
struct ufs_hba *hba)
{
return hba->caps & <API key>;
}
static inline u8 <API key>(struct ufs_hba *hba)
{
if (hba->dev_info.wb_buffer_type == <API key>)
return hba->dev_info.wb_dedicated_lu;
return 0;
}
#ifdef <API key>
void ufs_hwmon_probe(struct ufs_hba *hba, u8 mask);
void ufs_hwmon_remove(struct ufs_hba *hba);
void <API key>(struct ufs_hba *hba, u8 ee_mask);
#else
static inline void ufs_hwmon_probe(struct ufs_hba *hba, u8 mask) {}
static inline void ufs_hwmon_remove(struct ufs_hba *hba) {}
static inline void <API key>(struct ufs_hba *hba, u8 ee_mask) {}
#endif
#ifdef CONFIG_PM
extern int <API key>(struct device *dev);
extern int <API key>(struct device *dev);
#endif
#ifdef CONFIG_PM_SLEEP
extern int <API key>(struct device *dev);
extern int <API key>(struct device *dev);
#endif
extern int ufshcd_shutdown(struct ufs_hba *hba);
extern int <API key>(struct ufs_hba *hba,
int agreed_gear,
int adapt_val);
extern int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
u8 attr_set, u32 mib_val, u8 peer);
extern int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
u32 *mib_val, u8 peer);
extern int <API key>(struct ufs_hba *hba,
struct ufs_pa_layer_attr *desired_pwr_mode);
/* UIC command interfaces for DME primitives */
#define DME_LOCAL 0
#define DME_PEER 1
#define ATTR_SET_NOR 0 /* NORMAL */
#define ATTR_SET_ST 1 /* STATIC */
static inline int ufshcd_dme_set(struct ufs_hba *hba, u32 attr_sel,
u32 mib_val)
{
return ufshcd_dme_set_attr(hba, attr_sel, ATTR_SET_NOR,
mib_val, DME_LOCAL);
}
static inline int ufshcd_dme_st_set(struct ufs_hba *hba, u32 attr_sel,
u32 mib_val)
{
return ufshcd_dme_set_attr(hba, attr_sel, ATTR_SET_ST,
mib_val, DME_LOCAL);
}
static inline int ufshcd_dme_peer_set(struct ufs_hba *hba, u32 attr_sel,
u32 mib_val)
{
return ufshcd_dme_set_attr(hba, attr_sel, ATTR_SET_NOR,
mib_val, DME_PEER);
}
static inline int <API key>(struct ufs_hba *hba, u32 attr_sel,
u32 mib_val)
{
return ufshcd_dme_set_attr(hba, attr_sel, ATTR_SET_ST,
mib_val, DME_PEER);
}
static inline int ufshcd_dme_get(struct ufs_hba *hba,
u32 attr_sel, u32 *mib_val)
{
return ufshcd_dme_get_attr(hba, attr_sel, mib_val, DME_LOCAL);
}
static inline int ufshcd_dme_peer_get(struct ufs_hba *hba,
u32 attr_sel, u32 *mib_val)
{
return ufshcd_dme_get_attr(hba, attr_sel, mib_val, DME_PEER);
}
static inline bool ufshcd_is_hs_mode(struct ufs_pa_layer_attr *pwr_info)
{
return (pwr_info->pwr_rx == FAST_MODE ||
pwr_info->pwr_rx == FASTAUTO_MODE) &&
(pwr_info->pwr_tx == FAST_MODE ||
pwr_info->pwr_tx == FASTAUTO_MODE);
}
static inline int <API key>(struct ufs_hba *hba)
{
return ufshcd_dme_set(hba, UIC_ARG_MIB(<API key>), 0);
}
/* Expose Query-Request API */
int <API key>(struct ufs_hba *hba,
enum query_opcode opcode,
enum desc_idn idn, u8 index,
u8 selector,
u8 *desc_buf, int *buf_len);
int <API key>(struct ufs_hba *hba,
enum desc_idn desc_id,
int desc_index,
u8 param_offset,
u8 *param_read_buf,
u8 param_size);
int <API key>(struct ufs_hba *hba, enum query_opcode opcode,
enum attr_idn idn, u8 index, u8 selector,
u32 *attr_val);
int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
enum attr_idn idn, u8 index, u8 selector, u32 *attr_val);
int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
enum flag_idn idn, u8 index, bool *flag_res);
void <API key>(struct ufs_hba *hba);
void <API key>(struct ufs_hba *hba, u32 ahit);
void <API key>(struct ufs_hba *hba, struct ufs_dev_fix *fixups);
#define SD_ASCII_STD true
#define SD_RAW false
int <API key>(struct ufs_hba *hba, u8 desc_index,
u8 **buf, bool ascii);
int ufshcd_hold(struct ufs_hba *hba, bool async);
void ufshcd_release(struct ufs_hba *hba);
void <API key>(struct ufs_hba *hba, enum desc_idn desc_id,
int *desc_length);
u32 <API key>(struct ufs_hba *hba);
int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd);
int <API key>(struct ufs_hba *hba,
struct utp_upiu_req *req_upiu,
struct utp_upiu_req *rsp_upiu,
int msgcode,
u8 *desc_buff, int *buff_len,
enum query_opcode desc_op);
int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable);
int <API key>(struct device *dev);
void <API key>(struct device *dev);
/* Wrapper functions for safely calling variant operations */
static inline const char *ufshcd_get_var_name(struct ufs_hba *hba)
{
if (hba->vops)
return hba->vops->name;
return "";
}
static inline int ufshcd_vops_init(struct ufs_hba *hba)
{
if (hba->vops && hba->vops->init)
return hba->vops->init(hba);
return 0;
}
static inline void ufshcd_vops_exit(struct ufs_hba *hba)
{
if (hba->vops && hba->vops->exit)
return hba->vops->exit(hba);
}
static inline u32 <API key>(struct ufs_hba *hba)
{
if (hba->vops && hba->vops->get_ufs_hci_version)
return hba->vops->get_ufs_hci_version(hba);
return ufshcd_readl(hba, REG_UFS_VERSION);
}
static inline int <API key>(struct ufs_hba *hba,
bool up, enum <API key> status)
{
if (hba->vops && hba->vops->clk_scale_notify)
return hba->vops->clk_scale_notify(hba, up, status);
return 0;
}
static inline void <API key>(struct ufs_hba *hba,
enum ufs_event_type evt,
void *data)
{
if (hba->vops && hba->vops->event_notify)
hba->vops->event_notify(hba, evt, data);
}
static inline int <API key>(struct ufs_hba *hba, bool on,
enum <API key> status)
{
if (hba->vops && hba->vops->setup_clocks)
return hba->vops->setup_clocks(hba, on, status);
return 0;
}
static inline int <API key>(struct ufs_hba *hba,
bool status)
{
if (hba->vops && hba->vops->hce_enable_notify)
return hba->vops->hce_enable_notify(hba, status);
return 0;
}
static inline int <API key>(struct ufs_hba *hba,
bool status)
{
if (hba->vops && hba->vops->link_startup_notify)
return hba->vops->link_startup_notify(hba, status);
return 0;
}
static inline int <API key>(struct ufs_hba *hba)
{
if (hba->vops && hba->vops->phy_initialization)
return hba->vops->phy_initialization(hba);
return 0;
}
static inline int <API key>(struct ufs_hba *hba,
enum <API key> status,
struct ufs_pa_layer_attr *dev_max_params,
struct ufs_pa_layer_attr *dev_req_params)
{
if (hba->vops && hba->vops->pwr_change_notify)
return hba->vops->pwr_change_notify(hba, status,
dev_max_params, dev_req_params);
return -ENOTSUPP;
}
static inline void <API key>(struct ufs_hba *hba,
int tag, u8 tm_function)
{
if (hba->vops && hba->vops->setup_task_mgmt)
return hba->vops->setup_task_mgmt(hba, tag, tm_function);
}
static inline void <API key>(struct ufs_hba *hba,
enum uic_cmd_dme cmd,
enum <API key> status)
{
if (hba->vops && hba->vops->hibern8_notify)
return hba->vops->hibern8_notify(hba, cmd, status);
}
static inline int <API key>(struct ufs_hba *hba)
{
if (hba->vops && hba->vops->apply_dev_quirks)
return hba->vops->apply_dev_quirks(hba);
return 0;
}
static inline void <API key>(struct ufs_hba *hba)
{
if (hba->vops && hba->vops->fixup_dev_quirks)
hba->vops->fixup_dev_quirks(hba);
}
static inline int ufshcd_vops_suspend(struct ufs_hba *hba, enum ufs_pm_op op,
enum <API key> status)
{
if (hba->vops && hba->vops->suspend)
return hba->vops->suspend(hba, op, status);
return 0;
}
static inline int ufshcd_vops_resume(struct ufs_hba *hba, enum ufs_pm_op op)
{
if (hba->vops && hba->vops->resume)
return hba->vops->resume(hba, op);
return 0;
}
static inline void <API key>(struct ufs_hba *hba)
{
if (hba->vops && hba->vops->dbg_register_dump)
hba->vops->dbg_register_dump(hba);
}
static inline int <API key>(struct ufs_hba *hba)
{
if (hba->vops && hba->vops->device_reset)
return hba->vops->device_reset(hba);
return -EOPNOTSUPP;
}
static inline void <API key>(struct ufs_hba *hba,
struct devfreq_dev_profile
*profile, void *data)
{
if (hba->vops && hba->vops-><API key>)
hba->vops-><API key>(hba, profile, data);
}
extern struct ufs_pm_lvl_states ufs_pm_lvl_states[];
/*
* <API key> - maps scsi LUN to UPIU LUN
* @scsi_lun: scsi LUN id
*
* Returns UPIU LUN id
*/
static inline u8 <API key>(unsigned int scsi_lun)
{
if (scsi_is_wlun(scsi_lun))
return (scsi_lun & <API key>)
| UFS_UPIU_WLUN_ID;
else
return scsi_lun & <API key>;
}
int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
const char *prefix);
int <API key>(struct ufs_hba *hba, u32 ee_ctrl_mask);
int <API key>(struct ufs_hba *hba);
int <API key>(struct ufs_hba *hba, u16 *mask, u16 *other_mask,
u16 set, u16 clr);
static inline int <API key>(struct ufs_hba *hba,
u16 set, u16 clr)
{
return <API key>(hba, &hba->ee_drv_mask,
&hba->ee_usr_mask, set, clr);
}
static inline int <API key>(struct ufs_hba *hba,
u16 set, u16 clr)
{
return <API key>(hba, &hba->ee_usr_mask,
&hba->ee_drv_mask, set, clr);
}
static inline int ufshcd_rpm_get_sync(struct ufs_hba *hba)
{
return pm_runtime_get_sync(&hba->sdev_ufs_device->sdev_gendev);
}
static inline int ufshcd_rpm_put_sync(struct ufs_hba *hba)
{
return pm_runtime_put_sync(&hba->sdev_ufs_device->sdev_gendev);
}
static inline int ufshcd_rpm_put(struct ufs_hba *hba)
{
return pm_runtime_put(&hba->sdev_ufs_device->sdev_gendev);
}
#endif /* End of Header */
|
// This file is part of Pixy CMUcam5 or "Pixy" for short
// All Pixy source code is provided under the terms of the
// Those wishing to use Pixy source code, software and/or
// technologies under different licensing terms should contact us at
// cmucam@cs.cmu.edu. Such licensing terms are available for
// all portions of the Pixy codebase presented here.
#include <math.h>
#include "pixy_init.h"
#include "misc.h"
#include "power.h"
static const ProcModule g_module[] =
{
{
"pwr_getVin",
(ProcPtr)pwr_getVin,
{END},
"Get Vin (JP1) voltage"
"@r voltage in millivolts"
},
{
"pwr_get5V",
(ProcPtr)pwr_get5v,
{END},
"Get 5V voltage"
"@r voltage in millivolts"
},
{
"pwr_getVbus",
(ProcPtr)pwr_getVbus,
{END},
"Get USB VBUS voltage"
"@r voltage in millivolts"
},
{
"pwr_USBpowered",
(ProcPtr)pwr_USBpowered,
{END},
"Determine if camera power is from USB host."
"@r 0 if power is from Vin (JP1), nonzero if power is from USB"
},
END
};
uint32_t pwr_getVin()
{
uint32_t vin;
vin = adc_get(VIN_ADCCHAN)*10560/1024 + 330; // 10560 = 3.3*3.2*1000, 330 is diode drop
return vin;
}
uint32_t pwr_get5v()
{
uint32_t v5;
v5 = adc_get(V5_ADCCHAN)*5293/1024; // 5293=3.3*1.604*1000
return v5;
}
uint32_t pwr_getVbus()
{
uint32_t vbus;
vbus = adc_get(VBUS_ADCCHAN)*5293/1024; // 5293=3.3*1.604*1000
return vbus;
}
uint32_t pwr_USBpowered()
{
if (LPC_GPIO_PORT->PIN[5]&0x0100)
return 1;
else
return 0;
}
void pwr_init()
{
LPC_GPIO_PORT->DIR[5] |= 0x0100;
// choose USB power or vin
if (pwr_getVin()>6430) // 6430=5000+1100(ldo)+330(diode)
LPC_GPIO_PORT->PIN[5] &= ~0x0100;
else // switch usb on
LPC_GPIO_PORT->PIN[5] |= 0x0100;
#if 0 // Undergrad robotics mod, no need for usb shit fuck my ass nigga please
g_chirpUsb->registerModule(g_module);
#endif
}
|
#include "VideoCommon/GeometryShaderGen.h"
#include <cmath>
#include <cstring>
#include "Common/CommonTypes.h"
#include "VideoCommon/DriverDetails.h"
#include "VideoCommon/LightingShaderGen.h"
#include "VideoCommon/VideoCommon.h"
#include "VideoCommon/VideoConfig.h"
#include "VideoCommon/XFMemory.h"
constexpr std::array<const char*, 4> primitives_ogl = {
{"points", "lines", "triangles", "triangles"}};
constexpr std::array<const char*, 4> primitives_d3d = {{"point", "line", "triangle", "triangle"}};
bool <API key>::IsPassthrough() const
{
const bool stereo = g_ActiveConfig.iStereoMode > 0;
const bool wireframe = g_ActiveConfig.bWireFrame;
return primitive_type >= static_cast<u32>(PrimitiveType::Triangles) && !stereo && !wireframe;
}
GeometryShaderUid <API key>(PrimitiveType primitive_type)
{
ShaderUid<<API key>> out;
<API key>* uid_data = out.GetUidData<<API key>>();
memset(uid_data, 0, sizeof(<API key>));
uid_data->primitive_type = static_cast<u32>(primitive_type);
uid_data->numTexGens = xfmem.numTexGen.numTexGens;
return out;
}
static void EmitVertex(ShaderCode& out, const ShaderHostConfig& host_config,
const <API key>* uid_data, const char* vertex,
APIType ApiType, bool wireframe, bool pixel_lighting,
bool first_vertex = false);
static void EndPrimitive(ShaderCode& out, const ShaderHostConfig& host_config,
const <API key>* uid_data, APIType ApiType, bool wireframe,
bool pixel_lighting);
ShaderCode <API key>(APIType ApiType, const ShaderHostConfig& host_config,
const <API key>* uid_data)
{
ShaderCode out;
// Non-uid template parameters will write to the dummy data (=> gets optimized out)
const bool wireframe = host_config.wireframe;
const bool pixel_lighting = g_ActiveConfig.<API key>;
const bool msaa = host_config.msaa;
const bool ssaa = host_config.ssaa;
const bool stereo = host_config.stereo;
const PrimitiveType primitive_type = static_cast<PrimitiveType>(uid_data->primitive_type);
const unsigned <API key> = static_cast<unsigned>(uid_data->primitive_type);
const unsigned vertex_in = std::min(static_cast<unsigned>(<API key>) + 1, 3u);
unsigned vertex_out = primitive_type == PrimitiveType::TriangleStrip ? 3 : 4;
const unsigned int layers = host_config.more_layers * 2 + (int)(stereo) + 1;
if (wireframe)
vertex_out++;
if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan)
{
// Insert layout parameters
if (host_config.<API key>)
{
out.Write("layout(%s, invocations = %d) in;\n", primitives_ogl[<API key>],
layers);
out.Write("layout(%s_strip, max_vertices = %d) out;\n", wireframe ? "line" : "triangle",
vertex_out);
}
else
{
out.Write("layout(%s) in;\n", primitives_ogl[<API key>]);
out.Write("layout(%s_strip, max_vertices = %d) out;\n", wireframe ? "line" : "triangle",
vertex_out * layers);
}
}
out.Write("%s", s_lighting_struct);
// uniforms
if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan)
out.Write("UBO_BINDING(std140, 3) uniform GSBlock {\n");
else
out.Write("cbuffer GSBlock {\n");
out.Write("\tfloat4 " I_STEREOPARAMS ";\n"
"\tfloat4 " I_LINEPTPARAMS ";\n"
"\tint4 " I_TEXOFFSET ";\n"
"};\n");
out.Write("struct VS_OUTPUT {\n");
<API key><ShaderCode>(out, ApiType, uid_data->numTexGens, pixel_lighting, "");
out.Write("};\n");
if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan)
{
if (host_config.<API key>)
out.Write("#define InstanceID gl_InvocationID\n");
out.Write("VARYING_LOCATION(0) in VertexData {\n");
<API key><ShaderCode>(out, ApiType, uid_data->numTexGens, pixel_lighting,
<API key>(msaa, ssaa, true, true));
out.Write("} vs[%d];\n", vertex_in);
out.Write("VARYING_LOCATION(0) out VertexData {\n");
<API key><ShaderCode>(out, ApiType, uid_data->numTexGens, pixel_lighting,
<API key>(msaa, ssaa, true, false));
if (stereo || host_config.more_layers)
out.Write("\tflat int layer;\n");
out.Write("} ps;\n");
out.Write("void main()\n{\n");
}
else // D3D
{
out.Write("struct VertexData {\n");
out.Write("\tVS_OUTPUT o;\n");
if (stereo || host_config.more_layers)
out.Write("\tuint layer : <API key>;\n");
out.Write("};\n");
if (host_config.<API key>)
{
out.Write("[maxvertexcount(%d)]\n[instance(%d)]\n", vertex_out, layers);
out.Write("void main(%s VS_OUTPUT o[%d], inout %sStream<VertexData> output, in uint "
"InstanceID : SV_GSInstanceID)\n{\n",
primitives_d3d[<API key>], vertex_in, wireframe ? "Line" : "Triangle");
}
else
{
out.Write("[maxvertexcount(%d)]\n", vertex_out * layers);
out.Write("void main(%s VS_OUTPUT o[%d], inout %sStream<VertexData> output)\n{\n",
primitives_d3d[<API key>], vertex_in, wireframe ? "Line" : "Triangle");
}
out.Write("\tVertexData ps;\n");
}
if (primitive_type == PrimitiveType::Lines)
{
if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan)
{
out.Write("\tVS_OUTPUT start, end;\n");
<API key>(out, "start", "vs[0]", uid_data->numTexGens, pixel_lighting);
<API key>(out, "end", "vs[1]", uid_data->numTexGens, pixel_lighting);
}
else
{
out.Write("\tVS_OUTPUT start = o[0];\n");
out.Write("\tVS_OUTPUT end = o[1];\n");
}
// GameCube/Wii's line drawing algorithm is a little quirky. It does not
// use the correct line caps. Instead, the line caps are vertical or
// horizontal depending the slope of the line.
out.Write("\tfloat2 offset;\n"
"\tfloat2 to = abs(end.pos.xy / end.pos.w - start.pos.xy / start.pos.w);\n"
// FIXME: What does real hardware do when line is at a 45-degree angle?
// FIXME: Lines aren't drawn at the correct width. See Twilight Princess map.
"\tif (" I_LINEPTPARAMS ".y * to.y > " I_LINEPTPARAMS ".x * to.x) {\n"
// Line is more tall. Extend geometry left and right.
// Lerp LineWidth/2 from [0..VpWidth] to [-1..1]
"\t\toffset = float2(" I_LINEPTPARAMS ".z / " I_LINEPTPARAMS ".x, 0);\n"
"\t} else {\n"
// Line is more wide. Extend geometry up and down.
// Lerp LineWidth/2 from [0..VpHeight] to [1..-1]
"\t\toffset = float2(0, -" I_LINEPTPARAMS ".z / " I_LINEPTPARAMS ".y);\n"
"\t}\n");
}
else if (primitive_type == PrimitiveType::Points)
{
if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan)
{
out.Write("\tVS_OUTPUT center;\n");
<API key>(out, "center", "vs[0]", uid_data->numTexGens, pixel_lighting);
}
else
{
out.Write("\tVS_OUTPUT center = o[0];\n");
}
// Offset from center to upper right vertex
// Lerp PointSize/2 from [0,0..VpWidth,VpHeight] to [-1,1..1,-1]
out.Write("\tfloat2 offset = float2(" I_LINEPTPARAMS ".w / " I_LINEPTPARAMS
".x, -" I_LINEPTPARAMS ".w / " I_LINEPTPARAMS ".y) * center.pos.w;\n");
}
if (stereo || host_config.more_layers)
{
// If the GPU supports invocation we don't need a for loop and can simply use the
// invocation identifier to determine which layer we're rendering.
if (host_config.<API key>)
out.Write("\tint eye = InstanceID;\n");
else
out.Write("\tfor (int eye = 0; eye < %d; ++eye) {\n", layers);
}
if (wireframe)
out.Write("\tVS_OUTPUT first;\n");
out.Write("\tfor (int i = 0; i < %d; ++i) {\n", vertex_in);
if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan)
{
out.Write("\tVS_OUTPUT f;\n");
<API key>(out, "f", "vs[i]", uid_data->numTexGens, pixel_lighting);
if (host_config.backend_depth_clamp &&
DriverDetails::HasBug(DriverDetails::<API key>))
{
// On certain GPUs we have to consume the clip distance from the vertex shader
// or else the other vertex shader outputs will get corrupted.
out.Write("\tf.clipDist0 = gl_in[i].gl_ClipDistance[0];\n");
out.Write("\tf.clipDist1 = gl_in[i].gl_ClipDistance[1];\n");
}
}
else
{
out.Write("\tVS_OUTPUT f = o[i];\n");
}
if (host_config.vr)
{
// Select the output layer
out.Write("\tps.layer = eye;\n");
if (ApiType == APIType::OpenGL)
out.Write("\tgl_Layer = eye;\n");
// StereoParams[eye] = camera shift in game units * projection[0][0]
// StereoParams[eye+2] = offaxis shift from Oculus projection[0][2]
out.Write("\tf.clipPos.x += " I_STEREOPARAMS "[eye] - " I_STEREOPARAMS
"[eye+2] * f.clipPos.w;\n");
out.Write("\tf.pos.x += " I_STEREOPARAMS "[eye] - " I_STEREOPARAMS "[eye+2] * f.pos.w;\n");
}
else if (stereo || host_config.more_layers)
{
// Select the output layer
out.Write("\tps.layer = eye;\n");
if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan)
out.Write("\tgl_Layer = eye;\n");
// For stereoscopy add a small horizontal offset in Normalized Device Coordinates proportional
// to the depth of the vertex. We retrieve the depth value from the w-component of the projected
// vertex which contains the negated z-component of the original vertex.
// For negative parallax (out-of-screen effects) we subtract a convergence value from
// the depth value. This results in objects at a distance smaller than the convergence
// distance to seemingly appear in front of the screen.
// This formula is based on page 13 of the "Nvidia 3D Vision Automatic, Best Practices Guide"
out.Write("\tfloat hoffset = (eye == 0) ? " I_STEREOPARAMS ".x : " I_STEREOPARAMS ".y;\n");
out.Write("\tf.pos.x += hoffset * (f.pos.w - " I_STEREOPARAMS ".z);\n");
}
if (primitive_type == PrimitiveType::Lines)
{
out.Write("\tVS_OUTPUT l = f;\n"
"\tVS_OUTPUT r = f;\n");
out.Write("\tl.pos.xy -= offset * l.pos.w;\n"
"\tr.pos.xy += offset * r.pos.w;\n");
out.Write("\tif (" I_TEXOFFSET "[2] != 0) {\n");
out.Write("\tfloat texOffset = 1.0 / float(" I_TEXOFFSET "[2]);\n");
for (unsigned int i = 0; i < uid_data->numTexGens; ++i)
{
out.Write("\tif (((" I_TEXOFFSET "[0] >> %d) & 0x1) != 0)\n", i);
out.Write("\t\tr.tex%d.x += texOffset;\n", i);
}
out.Write("\t}\n");
EmitVertex(out, host_config, uid_data, "l", ApiType, wireframe, pixel_lighting, true);
EmitVertex(out, host_config, uid_data, "r", ApiType, wireframe, pixel_lighting);
}
else if (primitive_type == PrimitiveType::Points)
{
out.Write("\tVS_OUTPUT ll = f;\n"
"\tVS_OUTPUT lr = f;\n"
"\tVS_OUTPUT ul = f;\n"
"\tVS_OUTPUT ur = f;\n");
out.Write("\tll.pos.xy += float2(-1,-1) * offset;\n"
"\tlr.pos.xy += float2(1,-1) * offset;\n"
"\tul.pos.xy += float2(-1,1) * offset;\n"
"\tur.pos.xy += offset;\n");
out.Write("\tif (" I_TEXOFFSET "[3] != 0) {\n");
out.Write("\tfloat2 texOffset = float2(1.0 / float(" I_TEXOFFSET
"[3]), 1.0 / float(" I_TEXOFFSET "[3]));\n");
for (unsigned int i = 0; i < uid_data->numTexGens; ++i)
{
out.Write("\tif (((" I_TEXOFFSET "[1] >> %d) & 0x1) != 0) {\n", i);
out.Write("\t\tul.tex%d.xy += float2(0,1) * texOffset;\n", i);
out.Write("\t\tur.tex%d.xy += texOffset;\n", i);
out.Write("\t\tlr.tex%d.xy += float2(1,0) * texOffset;\n", i);
out.Write("\t}\n");
}
out.Write("\t}\n");
EmitVertex(out, host_config, uid_data, "ll", ApiType, wireframe, pixel_lighting, true);
EmitVertex(out, host_config, uid_data, "lr", ApiType, wireframe, pixel_lighting);
EmitVertex(out, host_config, uid_data, "ul", ApiType, wireframe, pixel_lighting);
EmitVertex(out, host_config, uid_data, "ur", ApiType, wireframe, pixel_lighting);
}
else
{
EmitVertex(out, host_config, uid_data, "f", ApiType, wireframe, pixel_lighting, true);
}
out.Write("\t}\n");
EndPrimitive(out, host_config, uid_data, ApiType, wireframe, pixel_lighting);
if ((stereo || host_config.more_layers) && !host_config.<API key>)
out.Write("\t}\n");
out.Write("}\n");
return out;
}
static void EmitVertex(ShaderCode& out, const ShaderHostConfig& host_config,
const <API key>* uid_data, const char* vertex,
APIType ApiType, bool wireframe, bool pixel_lighting, bool first_vertex)
{
if (wireframe && first_vertex)
out.Write("\tif (i == 0) first = %s;\n", vertex);
if (ApiType == APIType::OpenGL)
{
out.Write("\tgl_Position = %s.pos;\n", vertex);
if (host_config.backend_depth_clamp)
{
out.Write("\tgl_ClipDistance[0] = %s.clipDist0;\n", vertex);
out.Write("\tgl_ClipDistance[1] = %s.clipDist1;\n", vertex);
}
<API key>(out, "ps", vertex, uid_data->numTexGens, pixel_lighting);
}
else if (ApiType == APIType::Vulkan)
{
// Vulkan NDC space has Y pointing down (right-handed NDC space).
out.Write("\tgl_Position = %s.pos;\n", vertex);
out.Write("\tgl_Position.y = -gl_Position.y;\n");
<API key>(out, "ps", vertex, uid_data->numTexGens, pixel_lighting);
}
else
{
out.Write("\tps.o = %s;\n", vertex);
}
if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan)
out.Write("\tEmitVertex();\n");
else
out.Write("\toutput.Append(ps);\n");
}
static void EndPrimitive(ShaderCode& out, const ShaderHostConfig& host_config,
const <API key>* uid_data, APIType ApiType, bool wireframe,
bool pixel_lighting)
{
if (wireframe)
EmitVertex(out, host_config, uid_data, "first", ApiType, wireframe, pixel_lighting);
if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan)
out.Write("\tEndPrimitive();\n");
else
out.Write("\toutput.RestartStrip();\n");
}
void <API key>(const std::function<void(const GeometryShaderUid&)>& callback)
{
GeometryShaderUid uid;
std::memset(&uid, 0, sizeof(uid));
const std::array<PrimitiveType, 3> primitive_lut = {
{g_ActiveConfig.backend_info.<API key> ? PrimitiveType::TriangleStrip :
PrimitiveType::Triangles,
PrimitiveType::Lines, PrimitiveType::Points}};
for (PrimitiveType primitive : primitive_lut)
{
auto* guid = uid.GetUidData<<API key>>();
guid->primitive_type = static_cast<u32>(primitive);
for (u32 texgens = 0; texgens <= 8; texgens++)
{
guid->numTexGens = texgens;
callback(uid);
}
}
}
template <class T>
static T <API key>(PrimitiveType primitive_type, APIType ApiType, const ShaderHostConfig& host_config)
{
T out;
const bool wireframe = host_config.wireframe;
const bool pixel_lighting = g_ActiveConfig.<API key>;
const bool stereo = host_config.stereo;
// Non-uid template parameters will write to the dummy data (=> gets optimized out)
<API key> dummy_data;
<API key>* uid_data = out.template GetUidData<<API key>>();
if (uid_data == nullptr)
uid_data = &dummy_data;
const unsigned <API key> = static_cast<unsigned>(primitive_type);
uid_data->primitive_type = <API key>;
const unsigned vertex_in = std::min(static_cast<unsigned>(<API key>) + 1, 3u);
unsigned vertex_out = primitive_type == PrimitiveType::TriangleStrip ? 3 : 4;
const unsigned int layers = host_config.more_layers * 2 + host_config.stereo + 1;
if (wireframe)
vertex_out++;
if (ApiType == APIType::OpenGL)
{
// Insert layout parameters
if (host_config.<API key>)
{
out.Write("layout(%s, invocations = %d) in;\n", primitives_ogl[<API key>],
layers);
out.Write("layout(%s_strip, max_vertices = %d) out;\n",
wireframe ? "line" : "triangle", vertex_out);
}
else
{
out.Write("layout(%s) in;\n", primitives_ogl[<API key>]);
out.Write("layout(%s_strip, max_vertices = %d) out;\n",
wireframe ? "line" : "triangle",
vertex_out * layers);
}
}
// uniforms
if (ApiType == APIType::OpenGL)
out.Write("layout(std140%s) uniform GSBlock {\n",
g_ActiveConfig.backend_info.<API key> ? ", binding = 3" : "");
else
out.Write("cbuffer GSBlock {\n");
out.Write("\tfloat4 " I_STEREOPARAMS ";\n"
"\tfloat4 " I_LINEPTPARAMS ";\n"
"\tint4 " I_TEXOFFSET ";\n"
"};\n");
uid_data->numTexGens = 1;
const char* qualifier = "";
out.Write("struct VS_OUTPUT {\n");
DefineOutputMember(out, ApiType, qualifier, "float4", "pos", -1, "POSITION");
DefineOutputMember(out, ApiType, qualifier, "float4", "colors_", 0, "COLOR", 0);
DefineOutputMember(out, ApiType, qualifier, "float3", "tex", 0, "TEXCOORD", 0);
out.Write("};\n");
if (ApiType == APIType::OpenGL)
{
if (host_config.<API key>)
out.Write("#define InstanceID gl_InvocationID\n");
out.Write("in VertexData {\n");
qualifier = g_ActiveConfig.backend_info.<API key> ? "centroid" : "centroid in";
DefineOutputMember(out, ApiType, qualifier, "float4", "pos", -1, "POSITION");
DefineOutputMember(out, ApiType, qualifier, "float4", "colors_", 0, "COLOR", 0);
DefineOutputMember(out, ApiType, qualifier, "float3", "tex", 0, "TEXCOORD", 0);
out.Write("} vs[%d];\n", vertex_in);
out.Write("out VertexData {\n");
qualifier = g_ActiveConfig.backend_info.<API key> ? "centroid" : "centroid out";
DefineOutputMember(out, ApiType, qualifier, "float4", "pos", -1, "POSITION");
DefineOutputMember(out, ApiType, qualifier, "float4", "colors_", 0, "COLOR", 0);
DefineOutputMember(out, ApiType, qualifier, "float3", "tex", 0, "TEXCOORD", 0);
if (stereo || host_config.more_layers)
out.Write("\tflat int layer;\n");
out.Write("} ps;\n");
out.Write("void main()\n{\n");
}
else // D3D
{
out.Write("struct VertexData {\n");
out.Write("\tVS_OUTPUT o;\n");
if (stereo || host_config.more_layers)
out.Write("\tuint layer : <API key>;\n");
out.Write("};\n");
if (host_config.<API key>)
{
out.Write("[maxvertexcount(%d)]\n[instance(%d)]\n", vertex_out, layers);
out.Write("void main(%s VS_OUTPUT o[%d], inout %sStream<VertexData> output, in uint "
"InstanceID : SV_GSInstanceID)\n{\n",
primitives_d3d[<API key>], vertex_in,
wireframe ? "Line" : "Triangle");
}
else
{
out.Write("[maxvertexcount(%d)]\n", vertex_out * layers);
out.Write("void main(%s VS_OUTPUT o[%d], inout %sStream<VertexData> output)\n{\n",
primitives_d3d[<API key>], vertex_in,
wireframe ? "Line" : "Triangle");
}
out.Write("\tVertexData ps;\n");
}
if (primitive_type == PrimitiveType::Lines)
{
if (ApiType == APIType::OpenGL)
{
out.Write("\tVS_OUTPUT start, end;\n");
const char* a = "start";
const char* b = "vs[0]";
out.Write("\t%s.pos = %s.pos;\n", a, b);
out.Write("\t%s.colors_0 = %s.colors_0;\n", a, b);
out.Write("\t%s.tex%d = %s.tex%d;\n", a, 0, b, 0);
a = "end";
b = "vs[1]";
out.Write("\t%s.pos = %s.pos;\n", a, b);
out.Write("\t%s.colors_0 = %s.colors_0;\n", a, b);
out.Write("\t%s.tex%d = %s.tex%d;\n", a, 0, b, 0);
}
else
{
out.Write("\tVS_OUTPUT start = o[0];\n");
out.Write("\tVS_OUTPUT end = o[1];\n");
}
// GameCube/Wii's line drawing algorithm is a little quirky. It does not
// use the correct line caps. Instead, the line caps are vertical or
// horizontal depending the slope of the line.
out.Write("\tfloat2 offset;\n"
"\tfloat2 to = abs(end.pos.xy - start.pos.xy);\n"
// FIXME: What does real hardware do when line is at a 45-degree angle?
// FIXME: Lines aren't drawn at the correct width. See Twilight Princess map.
"\tif (" I_LINEPTPARAMS ".y * to.y > " I_LINEPTPARAMS ".x * to.x) {\n"
// Line is more tall. Extend geometry left and right.
// Lerp LineWidth/2 from [0..VpWidth] to [-1..1]
"\t\toffset = float2(" I_LINEPTPARAMS ".z / " I_LINEPTPARAMS ".x, 0);\n"
"\t} else {\n"
// Line is more wide. Extend geometry up and down.
// Lerp LineWidth/2 from [0..VpHeight] to [1..-1]
"\t\toffset = float2(0, -" I_LINEPTPARAMS ".z / " I_LINEPTPARAMS ".y);\n"
"\t}\n");
}
else if (primitive_type == PrimitiveType::Points)
{
if (ApiType == APIType::OpenGL)
{
const char* a = "center";
const char* b = "vs[0]";
out.Write("\tVS_OUTPUT center;\n");
out.Write("\t%s.pos = %s.pos;\n", a, b);
out.Write("\t%s.colors_0 = %s.colors_0;\n", a, b);
out.Write("\t%s.tex%d = %s.tex%d;\n", a, 0, b, 0);
}
else
{
out.Write("\tVS_OUTPUT center = o[0];\n");
}
// Offset from center to upper right vertex
// Lerp PointSize/2 from [0,0..VpWidth,VpHeight] to [-1,1..1,-1]
out.Write("\tfloat2 offset = float2(" I_LINEPTPARAMS ".w / " I_LINEPTPARAMS
".x, -" I_LINEPTPARAMS ".w / " I_LINEPTPARAMS ".y) * center.pos.w;\n");
}
if (stereo || host_config.more_layers)
{
// If the GPU supports invocation we don't need a for loop and can simply use the
// invocation identifier to determine which layer we're rendering.
if (host_config.<API key>)
out.Write("\tint eye = InstanceID;\n");
else
out.Write("\tfor (int eye = 0; eye < 2; ++eye) {\n");
}
if (wireframe)
out.Write("\tVS_OUTPUT first;\n");
out.Write("\tfor (int i = 0; i < %d; ++i) {\n", vertex_in);
if (ApiType == APIType::OpenGL)
{
out.Write("\tVS_OUTPUT f;\n");
const char* a = "f";
const char* b = "vs[i]";
out.Write("\t%s.pos = %s.pos;\n", a, b);
out.Write("\t%s.colors_0 = %s.colors_0;\n", a, b);
out.Write("\t%s.tex%d = %s.tex%d;\n", a, 0, b, 0);
}
else
{
out.Write("\tVS_OUTPUT f = o[i];\n");
}
if (host_config.vr)
{
// Select the output layer
out.Write("\tps.layer = eye;\n");
if (ApiType == APIType::OpenGL)
out.Write("\tgl_Layer = eye;\n");
// StereoParams[eye] = camera shift in game units * projection[0][0]
// StereoParams[eye+2] = offaxis shift from Oculus projection[0][2]
// out.Write("\tf.clipPos.x += " I_STEREOPARAMS"[eye] - " I_STEREOPARAMS"[eye+2] *
// f.clipPos.w;\n");
out.Write("\tf.pos.x += " I_STEREOPARAMS "[eye] - " I_STEREOPARAMS "[eye+2] * f.pos.w;\n");
}
else if (stereo || host_config.more_layers)
{
// Select the output layer
out.Write("\tps.layer = eye;\n");
if (ApiType == APIType::OpenGL)
out.Write("\tgl_Layer = eye;\n");
// For stereoscopy add a small horizontal offset in Normalized Device Coordinates proportional
// to the depth of the vertex. We retrieve the depth value from the w-component of the projected
// vertex which contains the negated z-component of the original vertex.
// For negative parallax (out-of-screen effects) we subtract a convergence value from
// the depth value. This results in objects at a distance smaller than the convergence
// distance to seemingly appear in front of the screen.
// This formula is based on page 13 of the "Nvidia 3D Vision Automatic, Best Practices Guide"
// out.Write("\tf.clipPos.x += " I_STEREOPARAMS"[eye] * (f.clipPos.w - "
// I_STEREOPARAMS"[2]);\n");
out.Write("\tf.pos.x += " I_STEREOPARAMS "[eye] * (f.pos.w - " I_STEREOPARAMS "[2]);\n");
}
if (primitive_type == PrimitiveType::Lines)
{
out.Write("\tVS_OUTPUT l = f;\n"
"\tVS_OUTPUT r = f;\n");
out.Write("\tl.pos.xy -= offset * l.pos.w;\n"
"\tr.pos.xy += offset * r.pos.w;\n");
out.Write("\tif (" I_TEXOFFSET "[2] != 0) {\n");
out.Write("\tfloat texOffset = 1.0 / float(" I_TEXOFFSET "[2]);\n");
for (unsigned int i = 0; i < uid_data->numTexGens; ++i)
{
out.Write("\tif (((" I_TEXOFFSET "[0] >> %d) & 0x1) != 0)\n", i);
out.Write("\t\tr.tex%d.x += texOffset;\n", i);
}
out.Write("\t}\n");
EmitVertex(out, host_config, uid_data, "l", ApiType, wireframe, pixel_lighting, true);
EmitVertex(out, host_config, uid_data, "r", ApiType, wireframe, pixel_lighting);
}
else if (primitive_type == PrimitiveType::Points)
{
out.Write("\tVS_OUTPUT ll = f;\n"
"\tVS_OUTPUT lr = f;\n"
"\tVS_OUTPUT ul = f;\n"
"\tVS_OUTPUT ur = f;\n");
out.Write("\tll.pos.xy += float2(-1,-1) * offset;\n"
"\tlr.pos.xy += float2(1,-1) * offset;\n"
"\tul.pos.xy += float2(-1,1) * offset;\n"
"\tur.pos.xy += offset;\n");
out.Write("\tif (" I_TEXOFFSET "[3] != 0) {\n");
out.Write("\tfloat2 texOffset = float2(1.0 / float(" I_TEXOFFSET
"[3]), 1.0 / float(" I_TEXOFFSET "[3]));\n");
for (unsigned int i = 0; i < 1; ++i)
{
out.Write("\tif (((" I_TEXOFFSET "[1] >> %d) & 0x1) != 0) {\n", i);
out.Write("\t\tll.tex%d.xy += float2(0,1) * texOffset;\n", i);
out.Write("\t\tlr.tex%d.xy += texOffset;\n", i);
out.Write("\t\tur.tex%d.xy += float2(1,0) * texOffset;\n", i);
out.Write("\t}\n");
}
out.Write("\t}\n");
EmitVertex(out, host_config, uid_data, "ll", ApiType, wireframe, pixel_lighting, true);
EmitVertex(out, host_config, uid_data, "lr", ApiType, wireframe, pixel_lighting);
EmitVertex(out, host_config, uid_data, "ul", ApiType, wireframe, pixel_lighting);
EmitVertex(out, host_config, uid_data, "ur", ApiType, wireframe, pixel_lighting);
}
else
{
EmitVertex(out, host_config, uid_data, "f", ApiType, wireframe, pixel_lighting, true);
}
out.Write("\t}\n");
EndPrimitive(out, host_config, uid_data, ApiType, wireframe, pixel_lighting);
if ((stereo || host_config.more_layers) && !host_config.<API key>)
out.Write("\t}\n");
out.Write("}\n");
return out;
}
ShaderCode <API key>(PrimitiveType primitive_type, APIType ApiType, const ShaderHostConfig& host_config)
{
return <API key><ShaderCode>(primitive_type, ApiType, host_config);
}
|
/**
* @test
* @summary Spliterator traversing and splitting tests
* @library ../stream/bootlib
* @build java.base/java.util.<API key>
* java.base/java.util.<API key>
* @run testng <API key>
* @bug 8020016 8071477 8072784 8169838
*/
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.nio.CharBuffer;
import java.util.AbstractCollection;
import java.util.AbstractList;
import java.util.AbstractSet;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.RandomAccess;
import java.util.Set;
import java.util.SortedSet;
import java.util.Spliterator;
import java.util.<API key>;
import java.util.<API key>;
import java.util.Spliterators;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import java.util.WeakHashMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.<API key>;
import java.util.concurrent.<API key>;
import java.util.concurrent.<API key>;
import java.util.concurrent.<API key>;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.<API key>;
import java.util.function.Consumer;
import java.util.function.DoubleConsumer;
import java.util.function.Function;
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
public class <API key> extends <API key> {
private static final List<Integer> SIZES = Arrays.asList(0, 1, 10, 42);
private static final String LOW = new String(new char[] {Character.MIN_LOW_SURROGATE});
private static final String HIGH = new String(new char[] {Character.MIN_HIGH_SURROGATE});
private static final String HIGH_LOW = HIGH + LOW;
private static final String CHAR_HIGH_LOW = "A" + HIGH_LOW;
private static final String HIGH_LOW_CHAR = HIGH_LOW + "A";
private static final String CHAR_HIGH_LOW_CHAR = "A" + HIGH_LOW + "A";
private static final List<String> STRINGS = generateTestStrings();
private static List<String> generateTestStrings() {
List<String> strings = new ArrayList<>();
for (int n : Arrays.asList(1, 2, 3, 16, 17)) {
strings.add(generate("A", n));
strings.add(generate(LOW, n));
strings.add(generate(HIGH, n));
strings.add(generate(HIGH_LOW, n));
strings.add(generate(CHAR_HIGH_LOW, n));
strings.add(generate(HIGH_LOW_CHAR, n));
strings.add(generate(CHAR_HIGH_LOW_CHAR, n));
}
return strings;
}
private static String generate(String s, int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(s);
}
return sb.toString();
}
private static class <API key><T> {
List<Object[]> data;
List<T> exp;
Map<T, T> mExp;
<API key>(List<Object[]> data, List<T> exp) {
this.data = data;
this.exp = exp;
this.mExp = createMap(exp);
}
Map<T, T> createMap(List<T> l) {
Map<T, T> m = new LinkedHashMap<>();
for (T t : l) {
m.put(t, t);
}
return m;
}
void add(String description, Collection<?> expected, Supplier<Spliterator<?>> s) {
description = joiner(description).toString();
data.add(new Object[]{description, expected, s});
}
void add(String description, Supplier<Spliterator<?>> s) {
add(description, exp, s);
}
void addCollection(Function<Collection<T>, ? extends Collection<T>> c) {
add("new " + c.apply(Collections.<T>emptyList()).getClass().getName() + ".spliterator()",
() -> c.apply(exp).spliterator());
}
void addList(Function<Collection<T>, ? extends List<T>> l) {
addCollection(l);
addCollection(l.andThen(list -> list.subList(0, list.size())));
}
void addMap(Function<Map<T, T>, ? extends Map<T, T>> m) {
String description = "new " + m.apply(Collections.<T, T>emptyMap()).getClass().getName();
addMap(m, description);
}
void addMap(Function<Map<T, T>, ? extends Map<T, T>> m, String description) {
add(description + ".keySet().spliterator()", () -> m.apply(mExp).keySet().spliterator());
add(description + ".values().spliterator()", () -> m.apply(mExp).values().spliterator());
add(description + ".entrySet().spliterator()", mExp.entrySet(), () -> m.apply(mExp).entrySet().spliterator());
}
StringBuilder joiner(String description) {
return new StringBuilder(description).
append(" {").
append("size=").append(exp.size()).
append("}");
}
}
static Object[][] <API key>;
@DataProvider(name = "Spliterator<Integer>")
public static Object[][] <API key>() {
if (<API key> != null) {
return <API key>;
}
List<Object[]> data = new ArrayList<>();
for (int size : SIZES) {
List<Integer> exp = listIntRange(size);
<API key><Integer> db = new <API key><>(data, exp);
// Direct spliterator methods
db.add("Spliterators.spliterator(Collection, ...)",
() -> Spliterators.spliterator(exp, 0));
db.add("Spliterators.spliterator(Iterator, ...)",
() -> Spliterators.spliterator(exp.iterator(), exp.size(), 0));
db.add("Spliterators.<API key>(Iterator, ...)",
() -> Spliterators.<API key>(exp.iterator(), 0));
db.add("Spliterators.spliterator(Spliterators.<API key>(Spliterator ), ...)",
() -> Spliterators.spliterator(Spliterators.iterator(exp.spliterator()), exp.size(), 0));
db.add("Spliterators.spliterator(T[], ...)",
() -> Spliterators.spliterator(exp.toArray(new Integer[0]), 0));
db.add("Arrays.spliterator(T[], ...)",
() -> Arrays.spliterator(exp.toArray(new Integer[0])));
class <API key> extends Spliterators.AbstractSpliterator<Integer> {
Iterator<Integer> it;
<API key>(Iterator<Integer> it, long est) {
super(est, Spliterator.SIZED);
this.it = it;
}
@Override
public boolean tryAdvance(Consumer<? super Integer> action) {
if (action == null)
throw new <API key>();
if (it.hasNext()) {
action.accept(it.next());
return true;
}
else {
return false;
}
}
}
db.add("new Spliterators.AbstractSpliterator()",
() -> new <API key>(exp.iterator(), exp.size()));
// Collections
// default method implementations
class <API key> extends AbstractCollection<Integer> {
Collection<Integer> c;
<API key>(Collection<Integer> c) {
this.c = c;
}
@Override
public Iterator<Integer> iterator() {
return c.iterator();
}
@Override
public int size() {
return c.size();
}
}
db.addCollection(
c -> new <API key>(c));
class AbstractListImpl extends AbstractList<Integer> {
List<Integer> l;
AbstractListImpl(Collection<Integer> c) {
this.l = new ArrayList<>(c);
}
@Override
public Integer get(int index) {
return l.get(index);
}
@Override
public int size() {
return l.size();
}
}
db.addCollection(
c -> new AbstractListImpl(c));
class AbstractSetImpl extends AbstractSet<Integer> {
Set<Integer> s;
AbstractSetImpl(Collection<Integer> c) {
this.s = new HashSet<>(c);
}
@Override
public Iterator<Integer> iterator() {
return s.iterator();
}
@Override
public int size() {
return s.size();
}
}
db.addCollection(
c -> new AbstractSetImpl(c));
class <API key> extends AbstractSet<Integer> implements SortedSet<Integer> {
SortedSet<Integer> s;
<API key>(Collection<Integer> c) {
this.s = new TreeSet<>(c);
}
@Override
public Iterator<Integer> iterator() {
return s.iterator();
}
@Override
public int size() {
return s.size();
}
@Override
public Comparator<? super Integer> comparator() {
return s.comparator();
}
@Override
public SortedSet<Integer> subSet(Integer fromElement, Integer toElement) {
return s.subSet(fromElement, toElement);
}
@Override
public SortedSet<Integer> headSet(Integer toElement) {
return s.headSet(toElement);
}
@Override
public SortedSet<Integer> tailSet(Integer fromElement) {
return s.tailSet(fromElement);
}
@Override
public Integer first() {
return s.first();
}
@Override
public Integer last() {
return s.last();
}
@Override
public Spliterator<Integer> spliterator() {
return SortedSet.super.spliterator();
}
}
db.addCollection(
c -> new <API key>(c));
class IterableWrapper implements Iterable<Integer> {
final Iterable<Integer> it;
IterableWrapper(Iterable<Integer> it) {
this.it = it;
}
@Override
public Iterator<Integer> iterator() {
return it.iterator();
}
}
db.add("new Iterable.spliterator()",
() -> new IterableWrapper(exp).spliterator());
db.add("Arrays.asList().spliterator()",
() -> Spliterators.spliterator(Arrays.asList(exp.toArray(new Integer[0])), 0));
db.addList(ArrayList::new);
db.addList(LinkedList::new);
db.addList(Vector::new);
class <API key> extends AbstractList<Integer> implements RandomAccess {
Integer[] ia;
<API key>(Collection<Integer> c) {
this.ia = c.toArray(new Integer[c.size()]);
}
@Override
public Integer get(int index) {
return ia[index];
}
@Override
public int size() {
return ia.length;
}
}
db.addList(<API key>::new);
class <API key> implements List<Integer>, RandomAccess {
Integer[] ia;
List<Integer> l;
<API key>(Collection<Integer> c) {
this.ia = c.toArray(new Integer[c.size()]);
this.l = Arrays.asList(ia);
}
@Override
public Integer get(int index) {
return ia[index];
}
@Override
public Integer set(int index, Integer element) {
throw new <API key>();
}
@Override
public void add(int index, Integer element) {
throw new <API key>();
}
@Override
public Integer remove(int index) {
throw new <API key>();
}
@Override
public int indexOf(Object o) {
return l.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return Arrays.asList(ia).lastIndexOf(o);
}
@Override
public ListIterator<Integer> listIterator() {
return l.listIterator();
}
@Override
public ListIterator<Integer> listIterator(int index) {
return l.listIterator(index);
}
@Override
public List<Integer> subList(int fromIndex, int toIndex) {
return l.subList(fromIndex, toIndex);
}
@Override
public int size() {
return ia.length;
}
@Override
public boolean isEmpty() {
return size() != 0;
}
@Override
public boolean contains(Object o) {
return l.contains(o);
}
@Override
public Iterator<Integer> iterator() {
return l.iterator();
}
@Override
public Object[] toArray() {
return l.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return l.toArray(a);
}
@Override
public boolean add(Integer integer) {
throw new <API key>();
}
@Override
public boolean remove(Object o) {
throw new <API key>();
}
@Override
public boolean containsAll(Collection<?> c) {
return l.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends Integer> c) {
throw new <API key>();
}
@Override
public boolean addAll(int index, Collection<? extends Integer> c) {
throw new <API key>();
}
@Override
public boolean removeAll(Collection<?> c) {
throw new <API key>();
}
@Override
public boolean retainAll(Collection<?> c) {
throw new <API key>();
}
@Override
public void clear() {
throw new <API key>();
}
}
db.addList(<API key>::new);
db.addCollection(HashSet::new);
db.addCollection(LinkedHashSet::new);
db.addCollection(TreeSet::new);
db.addCollection(c -> { Stack<Integer> s = new Stack<>(); s.addAll(c); return s;});
db.addCollection(PriorityQueue::new);
db.addCollection(ArrayDeque::new);
db.addCollection(<API key>::new);
if (size > 0) {
db.addCollection(c -> {
ArrayBlockingQueue<Integer> abq = new ArrayBlockingQueue<>(size);
abq.addAll(c);
return abq;
});
}
db.addCollection(<API key>::new);
db.addCollection(LinkedBlockingQueue::new);
db.addCollection(LinkedTransferQueue::new);
db.addCollection(<API key>::new);
db.addCollection(LinkedBlockingDeque::new);
db.addCollection(<API key>::new);
db.addCollection(CopyOnWriteArraySet::new);
if (size == 0) {
db.addCollection(c -> Collections.<Integer>emptySet());
db.addList(c -> Collections.<Integer>emptyList());
}
else if (size == 1) {
db.addCollection(c -> Collections.singleton(exp.get(0)));
db.addCollection(c -> Collections.singletonList(exp.get(0)));
}
{
Integer[] ai = new Integer[size];
Arrays.fill(ai, 1);
db.add(String.format("Collections.nCopies(%d, 1)", exp.size()),
Arrays.asList(ai),
() -> Collections.nCopies(exp.size(), 1).spliterator());
}
// Collections.synchronized/unmodifiable/checked wrappers
db.addCollection(Collections::<API key>);
db.addCollection(c -> Collections.unmodifiableSet(new HashSet<>(c)));
db.addCollection(c -> Collections.<API key>(new TreeSet<>(c)));
db.addList(c -> Collections.unmodifiableList(new ArrayList<>(c)));
db.addMap(Collections::unmodifiableMap);
db.addMap(m -> Collections.<API key>(new TreeMap<>(m)));
db.addCollection(Collections::<API key>);
db.addCollection(c -> Collections.synchronizedSet(new HashSet<>(c)));
db.addCollection(c -> Collections.<API key>(new TreeSet<>(c)));
db.addList(c -> Collections.synchronizedList(new ArrayList<>(c)));
db.addMap(Collections::synchronizedMap);
db.addMap(m -> Collections.<API key>(new TreeMap<>(m)));
db.addCollection(c -> Collections.checkedCollection(c, Integer.class));
db.addCollection(c -> Collections.checkedQueue(new ArrayDeque<>(c), Integer.class));
db.addCollection(c -> Collections.checkedSet(new HashSet<>(c), Integer.class));
db.addCollection(c -> Collections.checkedSortedSet(new TreeSet<>(c), Integer.class));
db.addList(c -> Collections.checkedList(new ArrayList<>(c), Integer.class));
db.addMap(c -> Collections.checkedMap(c, Integer.class, Integer.class));
db.addMap(m -> Collections.checkedSortedMap(new TreeMap<>(m), Integer.class, Integer.class));
// Maps
db.addMap(HashMap::new);
db.addMap(m -> {
// Create a Map ensuring that for large sizes
// buckets will contain 2 or more entries
HashMap<Integer, Integer> cm = new HashMap<>(1, m.size() + 1);
// Don't use putAll which inflates the table by
// m.size() * loadFactor, thus creating a very sparse
// map for 1000 entries defeating the purpose of this test,
// in addition it will cause the split until null test to fail
// because the number of valid splits is larger than the
// threshold
for (Map.Entry<Integer, Integer> e : m.entrySet())
cm.put(e.getKey(), e.getValue());
return cm;
}, "new java.util.HashMap(1, size + 1)");
db.addMap(LinkedHashMap::new);
db.addMap(IdentityHashMap::new);
db.addMap(WeakHashMap::new);
db.addMap(m -> {
// Create a Map ensuring that for large sizes
// buckets will be consist of 2 or more entries
WeakHashMap<Integer, Integer> cm = new WeakHashMap<>(1, m.size() + 1);
for (Map.Entry<Integer, Integer> e : m.entrySet())
cm.put(e.getKey(), e.getValue());
return cm;
}, "new java.util.WeakHashMap(1, size + 1)");
// @@@ Descending maps etc
db.addMap(TreeMap::new);
db.addMap(ConcurrentHashMap::new);
db.addMap(<API key>::new);
if (size == 0) {
db.addMap(m -> Collections.<Integer, Integer>emptyMap());
}
else if (size == 1) {
db.addMap(m -> Collections.singletonMap(exp.get(0), exp.get(0)));
}
}
return <API key> = data.toArray(new Object[0][]);
}
private static List<Integer> listIntRange(int upTo) {
List<Integer> exp = new ArrayList<>();
for (int i = 0; i < upTo; i++)
exp.add(i);
return Collections.unmodifiableList(exp);
}
@Test(dataProvider = "Spliterator<Integer>")
public void <API key>(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
executeAndCatch(<API key>.class, () -> s.get().forEachRemaining(null));
executeAndCatch(<API key>.class, () -> s.get().tryAdvance(null));
}
@Test(dataProvider = "Spliterator<Integer>")
public void testForEach(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
testForEach(exp, s, UnaryOperator.identity());
}
@Test(dataProvider = "Spliterator<Integer>")
public void testTryAdvance(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
testTryAdvance(exp, s, UnaryOperator.identity());
}
@Test(dataProvider = "Spliterator<Integer>")
public void <API key>(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
<API key>(exp, s, UnaryOperator.identity());
}
@Test(dataProvider = "Spliterator<Integer>")
public void <API key>(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
<API key>(exp, s, UnaryOperator.identity());
}
@Test(dataProvider = "Spliterator<Integer>")
public void <API key>(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
<API key>(s, UnaryOperator.identity());
}
@Test(dataProvider = "Spliterator<Integer>")
public void testSplitOnce(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
testSplitOnce(exp, s, UnaryOperator.identity());
}
@Test(dataProvider = "Spliterator<Integer>")
public void testSplitSixDeep(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
testSplitSixDeep(exp, s, UnaryOperator.identity());
}
@Test(dataProvider = "Spliterator<Integer>")
public void testSplitUntilNull(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
testSplitUntilNull(exp, s, UnaryOperator.identity());
}
private static class <API key> {
List<Object[]> data;
String s;
List<Integer> expChars;
List<Integer> expCodePoints;
<API key>(List<Object[]> data, String s) {
this.data = data;
this.s = s;
this.expChars = transform(s, false);
this.expCodePoints = transform(s, true);
}
static List<Integer> transform(String s, boolean toCodePoints) {
List<Integer> l = new ArrayList<>();
if (!toCodePoints) {
for (int i = 0; i < s.length(); i++) {
l.add((int) s.charAt(i));
}
}
else {
for (int i = 0; i < s.length();) {
char c1 = s.charAt(i++);
int cp = c1;
if (Character.isHighSurrogate(c1) && i < s.length()) {
char c2 = s.charAt(i);
if (Character.isLowSurrogate(c2)) {
i++;
cp = Character.toCodePoint(c1, c2);
}
}
l.add(cp);
}
}
return l;
}
void add(String description, Function<String, CharSequence> f) {
description = description.replace("%s", s);
{
Supplier<Spliterator.OfInt> supplier = () -> f.apply(s).chars().spliterator();
data.add(new Object[]{description + ".chars().spliterator()", expChars, supplier});
}
{
Supplier<Spliterator.OfInt> supplier = () -> f.apply(s).codePoints().spliterator();
data.add(new Object[]{description + ".codePoints().spliterator()", expCodePoints, supplier});
}
}
}
static Object[][] <API key>;
@DataProvider(name = "Spliterator.OfInt")
public static Object[][] <API key>() {
if (<API key> != null) {
return <API key>;
}
List<Object[]> data = new ArrayList<>();
for (int size : SIZES) {
int exp[] = arrayIntRange(size);
<API key> db = new <API key>(data, listIntRange(size));
db.add("Spliterators.spliterator(int[], ...)",
() -> Spliterators.spliterator(exp, 0));
db.add("Arrays.spliterator(int[], ...)",
() -> Arrays.spliterator(exp));
db.add("Spliterators.spliterator(PrimitiveIterator.OfInt, ...)",
() -> Spliterators.spliterator(Spliterators.iterator(Arrays.spliterator(exp)), exp.length, 0));
db.add("Spliterators.<API key>(PrimitiveIterator.OfInt, ...)",
() -> Spliterators.<API key>(Spliterators.iterator(Arrays.spliterator(exp)), 0));
class <API key> extends Spliterators.<API key> {
int[] a;
int index = 0;
<API key>(int[] a) {
super(a.length, Spliterator.SIZED);
this.a = a;
}
@Override
public boolean tryAdvance(IntConsumer action) {
if (action == null)
throw new <API key>();
if (index < a.length) {
action.accept(a[index++]);
return true;
}
else {
return false;
}
}
}
db.add("new Spliterators.<API key>()",
() -> new <API key>(exp));
}
// Class for testing default methods
class CharSequenceImpl implements CharSequence {
final String s;
public CharSequenceImpl(String s) {
this.s = s;
}
@Override
public int length() {
return s.length();
}
@Override
public char charAt(int index) {
return s.charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) {
return s.subSequence(start, end);
}
@Override
public String toString() {
return s;
}
}
for (String string : STRINGS) {
<API key> cdb = new <API key>(data, string);
cdb.add("\"%s\"", s -> s);
cdb.add("new CharSequenceImpl(\"%s\")", CharSequenceImpl::new);
cdb.add("new StringBuilder(\"%s\")", StringBuilder::new);
cdb.add("new StringBuffer(\"%s\")", StringBuffer::new);
cdb.add("CharBuffer.wrap(\"%s\".toCharArray())", s -> CharBuffer.wrap(s.toCharArray()));
}
return <API key> = data.toArray(new Object[0][]);
}
private static int[] arrayIntRange(int upTo) {
int[] exp = new int[upTo];
for (int i = 0; i < upTo; i++)
exp[i] = i;
return exp;
}
@Test(dataProvider = "Spliterator.OfInt")
public void <API key>(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
executeAndCatch(<API key>.class, () -> s.get().forEachRemaining((IntConsumer) null));
executeAndCatch(<API key>.class, () -> s.get().tryAdvance((IntConsumer) null));
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntForEach(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testForEach(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntTryAdvance(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testTryAdvance(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfInt")
public void <API key>(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
<API key>(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfInt")
public void <API key>(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
<API key>(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfInt")
public void <API key>(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
<API key>(s, intBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntSplitOnce(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testSplitOnce(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntSplitSixDeep(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testSplitSixDeep(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfInt")
public void <API key>(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testSplitUntilNull(exp, s, intBoxingConsumer());
}
private static class <API key> {
List<Object[]> data;
List<Long> exp;
<API key>(List<Object[]> data, List<Long> exp) {
this.data = data;
this.exp = exp;
}
void add(String description, List<Long> expected, Supplier<Spliterator.OfLong> s) {
description = joiner(description).toString();
data.add(new Object[]{description, expected, s});
}
void add(String description, Supplier<Spliterator.OfLong> s) {
add(description, exp, s);
}
StringBuilder joiner(String description) {
return new StringBuilder(description).
append(" {").
append("size=").append(exp.size()).
append("}");
}
}
static Object[][] <API key>;
@DataProvider(name = "Spliterator.OfLong")
public static Object[][] <API key>() {
if (<API key> != null) {
return <API key>;
}
List<Object[]> data = new ArrayList<>();
for (int size : SIZES) {
long exp[] = arrayLongRange(size);
<API key> db = new <API key>(data, listLongRange(size));
db.add("Spliterators.spliterator(long[], ...)",
() -> Spliterators.spliterator(exp, 0));
db.add("Arrays.spliterator(long[], ...)",
() -> Arrays.spliterator(exp));
db.add("Spliterators.spliterator(PrimitiveIterator.OfLong, ...)",
() -> Spliterators.spliterator(Spliterators.iterator(Arrays.spliterator(exp)), exp.length, 0));
db.add("Spliterators.<API key>(PrimitiveIterator.OfLong, ...)",
() -> Spliterators.<API key>(Spliterators.iterator(Arrays.spliterator(exp)), 0));
class <API key> extends Spliterators.<API key> {
long[] a;
int index = 0;
<API key>(long[] a) {
super(a.length, Spliterator.SIZED);
this.a = a;
}
@Override
public boolean tryAdvance(LongConsumer action) {
if (action == null)
throw new <API key>();
if (index < a.length) {
action.accept(a[index++]);
return true;
}
else {
return false;
}
}
}
db.add("new Spliterators.<API key>()",
() -> new <API key>(exp));
}
return <API key> = data.toArray(new Object[0][]);
}
private static List<Long> listLongRange(int upTo) {
List<Long> exp = new ArrayList<>();
for (long i = 0; i < upTo; i++)
exp.add(i);
return Collections.unmodifiableList(exp);
}
private static long[] arrayLongRange(int upTo) {
long[] exp = new long[upTo];
for (int i = 0; i < upTo; i++)
exp[i] = i;
return exp;
}
@Test(dataProvider = "Spliterator.OfLong")
public void <API key>(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
executeAndCatch(<API key>.class, () -> s.get().forEachRemaining((LongConsumer) null));
executeAndCatch(<API key>.class, () -> s.get().tryAdvance((LongConsumer) null));
}
@Test(dataProvider = "Spliterator.OfLong")
public void testLongForEach(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
testForEach(exp, s, longBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfLong")
public void testLongTryAdvance(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
testTryAdvance(exp, s, longBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfLong")
public void <API key>(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
<API key>(exp, s, longBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfLong")
public void <API key>(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
<API key>(exp, s, longBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfLong")
public void <API key>(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
<API key>(s, longBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfLong")
public void testLongSplitOnce(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
testSplitOnce(exp, s, longBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfLong")
public void <API key>(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
testSplitSixDeep(exp, s, longBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfLong")
public void <API key>(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
testSplitUntilNull(exp, s, longBoxingConsumer());
}
private static class <API key> {
List<Object[]> data;
List<Double> exp;
<API key>(List<Object[]> data, List<Double> exp) {
this.data = data;
this.exp = exp;
}
void add(String description, List<Double> expected, Supplier<Spliterator.OfDouble> s) {
description = joiner(description).toString();
data.add(new Object[]{description, expected, s});
}
void add(String description, Supplier<Spliterator.OfDouble> s) {
add(description, exp, s);
}
StringBuilder joiner(String description) {
return new StringBuilder(description).
append(" {").
append("size=").append(exp.size()).
append("}");
}
}
static Object[][] <API key>;
@DataProvider(name = "Spliterator.OfDouble")
public static Object[][] <API key>() {
if (<API key> != null) {
return <API key>;
}
List<Object[]> data = new ArrayList<>();
for (int size : SIZES) {
double exp[] = arrayDoubleRange(size);
<API key> db = new <API key>(data, listDoubleRange(size));
db.add("Spliterators.spliterator(double[], ...)",
() -> Spliterators.spliterator(exp, 0));
db.add("Arrays.spliterator(double[], ...)",
() -> Arrays.spliterator(exp));
db.add("Spliterators.spliterator(PrimitiveIterator.OfDouble, ...)",
() -> Spliterators.spliterator(Spliterators.iterator(Arrays.spliterator(exp)), exp.length, 0));
db.add("Spliterators.<API key>(PrimitiveIterator.OfDouble, ...)",
() -> Spliterators.<API key>(Spliterators.iterator(Arrays.spliterator(exp)), 0));
class <API key> extends Spliterators.<API key> {
double[] a;
int index = 0;
<API key>(double[] a) {
super(a.length, Spliterator.SIZED);
this.a = a;
}
@Override
public boolean tryAdvance(DoubleConsumer action) {
if (action == null)
throw new <API key>();
if (index < a.length) {
action.accept(a[index++]);
return true;
}
else {
return false;
}
}
}
db.add("new Spliterators.<API key>()",
() -> new <API key>(exp));
}
return <API key> = data.toArray(new Object[0][]);
}
private static List<Double> listDoubleRange(int upTo) {
List<Double> exp = new ArrayList<>();
for (double i = 0; i < upTo; i++)
exp.add(i);
return Collections.unmodifiableList(exp);
}
private static double[] arrayDoubleRange(int upTo) {
double[] exp = new double[upTo];
for (int i = 0; i < upTo; i++)
exp[i] = i;
return exp;
}
@Test(dataProvider = "Spliterator.OfDouble")
public void <API key>(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
executeAndCatch(<API key>.class, () -> s.get().forEachRemaining((DoubleConsumer) null));
executeAndCatch(<API key>.class, () -> s.get().tryAdvance((DoubleConsumer) null));
}
@Test(dataProvider = "Spliterator.OfDouble")
public void testDoubleForEach(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
testForEach(exp, s, <API key>());
}
@Test(dataProvider = "Spliterator.OfDouble")
public void <API key>(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
testTryAdvance(exp, s, <API key>());
}
@Test(dataProvider = "Spliterator.OfDouble")
public void <API key>(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
<API key>(exp, s, <API key>());
}
@Test(dataProvider = "Spliterator.OfDouble")
public void <API key>(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
<API key>(exp, s, <API key>());
}
@Test(dataProvider = "Spliterator.OfDouble")
public void <API key>(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
<API key>(s, <API key>());
}
@Test(dataProvider = "Spliterator.OfDouble")
public void testDoubleSplitOnce(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
testSplitOnce(exp, s, <API key>());
}
@Test(dataProvider = "Spliterator.OfDouble")
public void <API key>(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
testSplitSixDeep(exp, s, <API key>());
}
@Test(dataProvider = "Spliterator.OfDouble")
public void <API key>(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
testSplitUntilNull(exp, s, <API key>());
}
}
|
<template name="recipeContext">
<span class="menu-header">
Options <i class="pull-right icon icon-vert-dots"></i>
</span>
<div class="menu">
{{#each settings}}
<label class="menu-row">
<input
type="checkbox"
data-key={{key}}
checked="{{#if value}}checked{{/if}}"
class="change-setting checkbox">
{{_ label}}
</label>
{{/each}}
</div>
</template>
|
<!-- BEGINS HERO IMAGE -->
<!-- build:remove -->
<div class="hero">
<img class="img-responsive" src='images/<API key>/1.png' alt='This is a typical header image' />
</div>
<!-- /build -->
<t4 type="navigation" id="106" />
<!-- ENDS HERO IMAGE -->
|
#include "net/eathena/itemrecv.h"
#include "actormanager.h"
#include "itemcolormanager.h"
#include "logger.h"
#include "const/resources/item/cards.h"
#include "net/messagein.h"
#include "debug.h"
extern int packetVersion;
extern bool packets_zero;
namespace EAthena
{
void ItemRecv::processItemDropped(Net::MessageIn &msg)
{
const BeingId id = msg.readBeingId("id");
const int itemId = msg.readItemId("item id");
ItemTypeT itemType = ItemType::Unknown;
if (msg.getVersion() >= 20130000)
itemType = static_cast<ItemTypeT>(msg.readInt16("type"));
const Identified identified = fromInt(
msg.readUInt8("identify"), Identified);
const int x = msg.readInt16("x");
const int y = msg.readInt16("y");
const int subX = CAST_S32(msg.readInt8("subx"));
const int subY = CAST_S32(msg.readInt8("suby"));
const int amount = msg.readInt16("count");
if (packets_zero || packetVersion >= 20180418)
{
msg.readUInt8("show drop effect");
msg.readInt16("show effect mode");
}
if (actorManager != nullptr)
{
actorManager->createItem(id,
itemId,
x, y,
itemType,
amount,
0,
ItemColor_one,
identified,
Damaged_false,
subX, subY,
nullptr);
}
}
void ItemRecv::processItemDropped2(Net::MessageIn &msg)
{
const BeingId id = msg.readBeingId("id");
const int itemId = msg.readInt16("item id"); // +++ need use int32
const ItemTypeT itemType = static_cast<ItemTypeT>(msg.readUInt8("type"));
const Identified identified = fromInt(
msg.readUInt8("identify"), Identified);
const Damaged damaged = fromBool(msg.readUInt8("attribute"), Damaged);
const uint8_t refine = msg.readUInt8("refine");
int cards[maxCards];
for (int f = 0; f < maxCards; f++)
cards[f] = msg.readUInt16("card"); // ++ need use int32
const int x = msg.readInt16("x");
const int y = msg.readInt16("y");
const int amount = msg.readInt16("amount");
const int subX = CAST_S32(msg.readInt8("subx"));
const int subY = CAST_S32(msg.readInt8("suby"));
// +++ probably need add drop effect fields?
if (actorManager != nullptr)
{
actorManager->createItem(id,
itemId,
x, y,
itemType,
amount,
refine,
ItemColorManager::getColorFromCards(&cards[0]),
identified,
damaged,
subX, subY,
&cards[0]);
}
}
void ItemRecv::<API key>(Net::MessageIn &msg)
{
UNIMPLEMENTEDPACKET;
msg.readInt16("len");
msg.readUInt8("type");
msg.readItemId("item id");
msg.readUInt8("len");
msg.readString(24, "name");
msg.readUInt8("monster name len");
msg.readString(24, "monster name");
}
void ItemRecv::processItemVisible(Net::MessageIn &msg)
{
const BeingId id = msg.readBeingId("item object id");
const int itemId = msg.readItemId("item id");
const Identified identified = fromInt(
msg.readUInt8("identify"), Identified);
const int x = msg.readInt16("x");
const int y = msg.readInt16("y");
const int amount = msg.readInt16("amount");
const int subX = CAST_S32(msg.readInt8("sub x"));
const int subY = CAST_S32(msg.readInt8("sub y"));
if (actorManager != nullptr)
{
actorManager->createItem(id,
itemId,
x, y,
ItemType::Unknown,
amount,
0,
ItemColor_one,
identified,
Damaged_false,
subX, subY,
nullptr);
}
}
void ItemRecv::processItemVisible2(Net::MessageIn &msg)
{
const BeingId id = msg.readBeingId("item object id");
const int itemId = msg.readInt16("item id"); // +++ need use int32
const ItemTypeT itemType = static_cast<ItemTypeT>(
msg.readUInt8("type"));
const Identified identified = fromInt(
msg.readUInt8("identify"), Identified);
const Damaged damaged = fromBool(msg.readUInt8("attribute"), Damaged);
const uint8_t refine = msg.readUInt8("refine");
int cards[maxCards];
for (int f = 0; f < maxCards; f++)
cards[f] = msg.readUInt16("card"); // +++ need use int32
const int x = msg.readInt16("x");
const int y = msg.readInt16("y");
const int amount = msg.readInt16("amount");
const int subX = CAST_S32(msg.readInt8("sub x"));
const int subY = CAST_S32(msg.readInt8("sub y"));
if (actorManager != nullptr)
{
actorManager->createItem(id,
itemId,
x, y,
itemType,
amount,
refine,
ItemColorManager::getColorFromCards(&cards[0]),
identified,
damaged,
subX, subY,
&cards[0]);
}
}
} // namespace EAthena
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_07) on Tue Sep 12 14:14:15 CEST 2006 -->
<TITLE>
<API key>
</TITLE>
<META NAME="keywords" CONTENT="test.org.peertrust.event.<API key> class">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="<API key>";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/<API key>.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../test/org/peertrust/event/PTEventTestA.html" title="class in test.org.peertrust.event"><B>PREV CLASS</B></A>
<A HREF="../../../../test/org/peertrust/event/PTEventTestB.html" title="class in test.org.peertrust.event"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?test/org/peertrust/event/<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="<API key>.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#<API key>.peertrust.event.PTEvent">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | METHOD</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<H2>
<FONT SIZE="-1">
test.org.peertrust.event</FONT>
<BR>
Class <API key></H2>
<PRE>
java.lang.Object
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><A HREF="../../../../org/peertrust/event/PTEvent.html" title="class in org.peertrust.event">org.peertrust.event.PTEvent</A>
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><A HREF="../../../../test/org/peertrust/event/PTEventTestA.html" title="class in test.org.peertrust.event">test.org.peertrust.event.PTEventTestA</A>
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>test.org.peertrust.event.<API key></B>
</PRE>
<DL>
<DT><B>All Implemented Interfaces:</B> <DD>java.lang.Cloneable</DD>
</DL>
<HR>
<DL>
<DT><PRE>public class <B><API key></B><DT>extends <A HREF="../../../../test/org/peertrust/event/PTEventTestA.html" title="class in test.org.peertrust.event">PTEventTestA</A></DL>
</PRE>
<P>
$Id: <API key>.html,v 1.1 2006/09/20 15:25:16 jldecoi Exp $
<P>
<P>
<DL>
<DT><B>Author:</B></DT>
<DD>olmedilla</DD>
</DL>
<HR>
<P>
<A NAME="constructor_summary"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../test/org/peertrust/event/<API key>.html#<API key>(java.lang.Object)"><API key></A></B>(java.lang.Object source)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<A NAME="method_summary"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
</TABLE>
<A NAME="<API key>.peertrust.event.PTEvent"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="<API key>">
<TH ALIGN="left"><B>Methods inherited from class org.peertrust.event.<A HREF="../../../../org/peertrust/event/PTEvent.html" title="class in org.peertrust.event">PTEvent</A></B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><A HREF="../../../../org/peertrust/event/PTEvent.html#getSource()">getSource</A></CODE></TD>
</TR>
</TABLE>
<A NAME="<API key>.lang.Object"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="<API key>">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<A NAME="constructor_detail"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="<API key>(java.lang.Object)"></A><H3>
<API key></H3>
<PRE>
public <B><API key></B>(java.lang.Object source)</PRE>
<DL>
<DL>
<DT><B>Parameters:</B><DD><CODE>source</CODE> - </DL>
</DL>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/<API key>.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../test/org/peertrust/event/PTEventTestA.html" title="class in test.org.peertrust.event"><B>PREV CLASS</B></A>
<A HREF="../../../../test/org/peertrust/event/PTEventTestB.html" title="class in test.org.peertrust.event"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?test/org/peertrust/event/<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="<API key>.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#<API key>.peertrust.event.PTEvent">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | METHOD</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
</BODY>
</HTML>
|
package com.owncloud.android.ui.fragment;
import android.animation.LayoutTransition;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.DrawableRes;
import android.support.annotation.StringRes;
import android.support.design.widget.<API key>;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.getbase.<API key>.<API key>;
import com.getbase.<API key>.FloatingActionsMenu;
import com.owncloud.android.MainApp;
import com.owncloud.android.R;
import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.files.SearchOperation;
import com.owncloud.android.ui.ExtendedListView;
import com.owncloud.android.ui.activity.FileDisplayActivity;
import com.owncloud.android.ui.activity.<API key>;
import com.owncloud.android.ui.activity.<API key>;
import com.owncloud.android.ui.activity.UploadFilesActivity;
import com.owncloud.android.ui.adapter.FileListListAdapter;
import com.owncloud.android.ui.adapter.<API key>;
import com.owncloud.android.ui.events.SearchEvent;
import org.greenrobot.eventbus.EventBus;
import org.parceler.Parcel;
import java.util.ArrayList;
import third_parties.in.srain.cube.<API key>;
import static android.content.res.Configuration.<API key>;
public class <API key> extends Fragment
implements OnItemClickListener, <API key>, SearchView.OnQueryTextListener {
protected static final String TAG = <API key>.class.getSimpleName();
protected static final String <API key> = "SAVED_LIST_POSITION";
private static final String KEY_INDEXES = "INDEXES";
private static final String KEY_FIRST_POSITIONS = "FIRST_POSITIONS";
private static final String KEY_TOPS = "TOPS";
private static final String KEY_HEIGHT_CELL = "HEIGHT_CELL";
private static final String <API key> = "EMPTY_LIST_MESSAGE";
private static final String KEY_IS_GRID_VISIBLE = "IS_GRID_VISIBLE";
protected SwipeRefreshLayout mRefreshListLayout;
private SwipeRefreshLayout mRefreshGridLayout;
protected SwipeRefreshLayout mRefreshEmptyLayout;
protected LinearLayout mEmptyListContainer;
protected TextView mEmptyListMessage;
protected TextView mEmptyListHeadline;
protected ImageView mEmptyListIcon;
protected ProgressBar mEmptyListProgress;
private FloatingActionsMenu mFabMain;
private <API key> mFabUpload;
private <API key> mFabMkdir;
private <API key> mFabUploadFromApp;
// Save the state of the scroll in browsing
private ArrayList<Integer> mIndexes;
private ArrayList<Integer> mFirstPositions;
private ArrayList<Integer> mTops;
private int mHeightCell = 0;
private SwipeRefreshLayout.OnRefreshListener mOnRefreshListener = null;
protected AbsListView mCurrentListView;
private ExtendedListView mListView;
private View mListFooterView;
private <API key> mGridView;
private View mGridFooterView;
private BaseAdapter mAdapter;
protected SearchView searchView;
private Handler handler = new Handler();
@Parcel
public enum SearchType {
NO_SEARCH,
REGULAR_FILTER,
FILE_SEARCH,
FAVORITE_SEARCH,
<API key>,
VIDEO_SEARCH,
VIDEO_SEARCH_FILTER,
PHOTO_SEARCH,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
// not a real filter, but nevertheless
SHARED_FILTER
}
protected void setListAdapter(BaseAdapter listAdapter) {
mAdapter = listAdapter;
mCurrentListView.setAdapter(listAdapter);
mCurrentListView.invalidateViews();
}
protected AbsListView getListView() {
return mCurrentListView;
}
public <API key> getFabUpload() {
return mFabUpload;
}
public <API key> getFabUploadFromApp() {
return mFabUploadFromApp;
}
public <API key> getFabMkdir() {
return mFabMkdir;
}
public FloatingActionsMenu getFabMain() {
return mFabMain;
}
public void switchToGridView() {
if (!isGridEnabled()) {
mListView.setAdapter(null);
mRefreshListLayout.setVisibility(View.GONE);
mRefreshGridLayout.setVisibility(View.VISIBLE);
mCurrentListView = mGridView;
setListAdapter(mAdapter);
}
}
public void switchToListView() {
if (isGridEnabled()) {
mGridView.setAdapter(null);
mRefreshGridLayout.setVisibility(View.GONE);
mRefreshListLayout.setVisibility(View.VISIBLE);
mCurrentListView = mListView;
setListAdapter(mAdapter);
}
}
public boolean isGridEnabled() {
return (mCurrentListView != null && mCurrentListView.equals(mGridView));
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
final MenuItem item = menu.findItem(R.id.action_search);
searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.<API key>(this);
final Handler handler = new Handler();
DisplayMetrics displaymetrics = new DisplayMetrics();
Activity activity;
if ((activity = getActivity()) != null) {
activity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;
if (getResources().getConfiguration().orientation == <API key>) {
searchView.setMaxWidth((int) (width * 0.4));
} else {
if (activity instanceof <API key>) {
searchView.setMaxWidth((int) (width * 0.8));
} else {
searchView.setMaxWidth((int) (width * 0.7));
}
}
}
searchView.<API key>(new View.<API key>() {
@Override
public void onFocusChange(View v, final boolean hasFocus) {
if (hasFocus) {
mFabMain.collapse();
}
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (getActivity() != null && !(getActivity() instanceof <API key>)) {
setFabEnabled(!hasFocus);
boolean searchSupported = AccountUtils.hasSearchSupport(AccountUtils.
<API key>(MainApp.getAppContext()));
if (getResources().getBoolean(R.bool.<API key>) && searchSupported) {
<API key> <API key> = (<API key>) getActivity().
findViewById(R.id.<API key>);
if (hasFocus) {
<API key>.setVisibility(View.GONE);
} else {
<API key>.setVisibility(View.VISIBLE);
}
}
}
}
}, 100);
}
});
final View mSearchEditFrame = searchView
.findViewById(android.support.v7.appcompat.R.id.search_edit_frame);
ViewTreeObserver vto = mSearchEditFrame.getViewTreeObserver();
vto.<API key>(new ViewTreeObserver.<API key>() {
int oldVisibility = -1;
@Override
public void onGlobalLayout() {
int currentVisibility = mSearchEditFrame.getVisibility();
if (currentVisibility != oldVisibility) {
if (currentVisibility == View.VISIBLE) {
setEmptyListMessage(SearchType.REGULAR_FILTER);
} else {
setEmptyListMessage(SearchType.NO_SEARCH);
}
oldVisibility = currentVisibility;
}
}
});
LinearLayout searchBar = (LinearLayout) searchView.findViewById(R.id.search_bar);
searchBar.setLayoutTransition(new LayoutTransition());
}
public boolean onQueryTextChange(final String query) {
if (getFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT)
instanceof <API key>){
performSearch(query, false);
return true;
} else {
return false;
}
}
@Override
public boolean onQueryTextSubmit(String query) {
if (getFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT)
instanceof <API key>){
performSearch(query, true);
return true;
} else {
return false;
}
}
private void performSearch(final String query, boolean isSubmit) {
handler.<API key>(null);
if (!TextUtils.isEmpty(query)) {
int delay = 500;
if (isSubmit) {
delay = 0;
}
if (mAdapter != null && mAdapter instanceof FileListListAdapter) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (AccountUtils.hasSearchSupport(AccountUtils.
<API key>(MainApp.getAppContext()))) {
EventBus.getDefault().post(new SearchEvent(query, SearchOperation.SearchType.FILE_SEARCH,
SearchEvent.UnsetType.NO_UNSET));
} else {
FileListListAdapter fileListListAdapter = (FileListListAdapter) mAdapter;
fileListListAdapter.getFilter().filter(query);
}
}
}, delay);
} else if (mAdapter != null && mAdapter instanceof <API key>) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
<API key> <API key> = (<API key>) mAdapter;
<API key>.filter(query);
}
}, delay);
}
if (searchView != null && delay == 0) {
searchView.clearFocus();
}
} else {
Activity activity;
if ((activity = getActivity()) != null) {
if (activity instanceof FileDisplayActivity) {
((FileDisplayActivity) activity).<API key>(true);
} else if (activity instanceof UploadFilesActivity) {
<API key> <API key> = (<API key>) mAdapter;
<API key>.filter(query);
} else if (activity instanceof <API key>) {
((<API key>) activity).<API key>(true);
}
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log_OC.d(TAG, "onCreateView");
View v = inflater.inflate(R.layout.list_fragment, null);
setupEmptyList(v);
mListView = (ExtendedListView) (v.findViewById(R.id.list_root));
mListView.<API key>(this);
mListFooterView = inflater.inflate(R.layout.list_footer, null, false);
mGridView = (<API key>) (v.findViewById(R.id.grid_root));
mGridView.setNumColumns(GridView.AUTO_FIT);
mGridView.<API key>(this);
mGridFooterView = inflater.inflate(R.layout.list_footer, null, false);
// Pull-down to refresh layout
mRefreshListLayout = (SwipeRefreshLayout) v.findViewById(R.id.<API key>);
mRefreshGridLayout = (SwipeRefreshLayout) v.findViewById(R.id.<API key>);
mRefreshEmptyLayout = (SwipeRefreshLayout) v.findViewById(R.id.<API key>);
<API key>(mRefreshListLayout);
<API key>(mRefreshGridLayout);
<API key>(mRefreshEmptyLayout);
mListView.setEmptyView(mRefreshEmptyLayout);
mGridView.setEmptyView(mRefreshEmptyLayout);
mFabMain = (FloatingActionsMenu) v.findViewById(R.id.fab_main);
mFabUpload = (<API key>) v.findViewById(R.id.fab_upload);
mFabMkdir = (<API key>) v.findViewById(R.id.fab_mkdir);
mFabUploadFromApp = (<API key>) v.findViewById(R.id.fab_upload_from_app);
boolean searchSupported = AccountUtils.hasSearchSupport(AccountUtils.
<API key>(MainApp.getAppContext()));
if (getResources().getBoolean(R.bool.<API key>) && searchSupported) {
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mFabMain.getLayoutParams();
final float scale = v.getResources().getDisplayMetrics().density;
<API key> <API key> = (<API key>)
v.findViewById(R.id.<API key>);
// convert the DP into pixel
int pixel = (int) (32 * scale + 0.5f);
layoutParams.setMargins(0, 0, pixel / 2, <API key>.getMeasuredHeight() + pixel * 2);
}
mCurrentListView = mListView; // list by default
if (savedInstanceState != null) {
if (savedInstanceState.getBoolean(KEY_IS_GRID_VISIBLE, false)) {
switchToGridView();
}
int referencePosition = savedInstanceState.getInt(<API key>);
if (isGridEnabled()) {
Log_OC.v(TAG, "Setting grid position " + referencePosition);
mGridView.setSelection(referencePosition);
} else {
Log_OC.v(TAG, "Setting and centering around list position " + referencePosition);
mListView.<API key>(referencePosition);
}
}
return v;
}
protected void setupEmptyList(View view) {
mEmptyListContainer = (LinearLayout) view.findViewById(R.id.empty_list_view);
mEmptyListMessage = (TextView) view.findViewById(R.id.<API key>);
mEmptyListHeadline = (TextView) view.findViewById(R.id.<API key>);
mEmptyListIcon = (ImageView) view.findViewById(R.id.empty_list_icon);
mEmptyListProgress = (ProgressBar) view.findViewById(R.id.empty_list_progress);
}
/**
* {@inheritDoc}
*/
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mIndexes = savedInstanceState.getIntegerArrayList(KEY_INDEXES);
mFirstPositions = savedInstanceState.getIntegerArrayList(KEY_FIRST_POSITIONS);
mTops = savedInstanceState.getIntegerArrayList(KEY_TOPS);
mHeightCell = savedInstanceState.getInt(KEY_HEIGHT_CELL);
<API key>(savedInstanceState.getString(<API key>));
} else {
mIndexes = new ArrayList<>();
mFirstPositions = new ArrayList<>();
mTops = new ArrayList<>();
mHeightCell = 0;
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log_OC.d(TAG, "onSaveInstanceState()");
savedInstanceState.putBoolean(KEY_IS_GRID_VISIBLE, isGridEnabled());
savedInstanceState.putInt(<API key>, <API key>());
savedInstanceState.putIntegerArrayList(KEY_INDEXES, mIndexes);
savedInstanceState.putIntegerArrayList(KEY_FIRST_POSITIONS, mFirstPositions);
savedInstanceState.putIntegerArrayList(KEY_TOPS, mTops);
savedInstanceState.putInt(KEY_HEIGHT_CELL, mHeightCell);
savedInstanceState.putString(<API key>, getEmptyViewText());
}
/**
* Calculates the position of the item that will be used as a reference to
* reposition the visible items in the list when the device is turned to
* other position.
*
* The current policy is take as a reference the visible item in the center
* of the screen.
*
* @return The position in the list of the visible item in the center of the
* screen.
*/
protected int <API key>() {
if (mCurrentListView != null) {
return (mCurrentListView.<API key>() +
mCurrentListView.<API key>()) / 2;
} else {
return 0;
}
}
/*
* Restore index and position
*/
protected void <API key>() {
if (mIndexes.size() > 0) {
// needs to be checked; not every browse-up had a browse-down before
int index = mIndexes.remove(mIndexes.size() - 1);
final int firstPosition = mFirstPositions.remove(mFirstPositions.size() - 1);
int top = mTops.remove(mTops.size() - 1);
Log_OC.v(TAG, "Setting selection to position: " + firstPosition + "; top: "
+ top + "; index: " + index);
if (mCurrentListView != null && mCurrentListView.equals(mListView)) {
if (mHeightCell * index <= mListView.getHeight()) {
mListView.setSelectionFromTop(firstPosition, top);
} else {
mListView.setSelectionFromTop(index, 0);
}
} else {
if (mHeightCell * index <= mGridView.getHeight()) {
mGridView.setSelection(firstPosition);
//mGridView.<API key>(firstPosition);
} else {
mGridView.setSelection(index);
//mGridView.<API key>(index);
}
}
}
}
/*
* Save index and top position
*/
protected void <API key>(int index) {
mIndexes.add(index);
int firstPosition = mCurrentListView.<API key>();
mFirstPositions.add(firstPosition);
View view = mCurrentListView.getChildAt(0);
int top = (view == null) ? 0 : view.getTop();
mTops.add(top);
// Save the height of a cell
mHeightCell = (view == null || mHeightCell != 0) ? mHeightCell : view.getHeight();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// to be @overriden
}
@Override
public void onRefresh() {
if (searchView != null) {
searchView.<API key>();
Activity activity;
if ((activity = getActivity()) != null && activity instanceof FileDisplayActivity) {
FileDisplayActivity fileDisplayActivity = (FileDisplayActivity) activity;
fileDisplayActivity.<API key>(fileDisplayActivity.<API key>());
}
}
mRefreshListLayout.setRefreshing(false);
mRefreshGridLayout.setRefreshing(false);
mRefreshEmptyLayout.setRefreshing(false);
if (mOnRefreshListener != null) {
mOnRefreshListener.onRefresh();
}
}
public void <API key>(<API key> listener) {
mOnRefreshListener = listener;
}
/**
* Disables swipe gesture.
*
* Sets the 'enabled' state of the refresh layouts contained in the fragment.
*
* When 'false' is set, prevents user gestures but keeps the option to refresh programatically,
*
* @param enabled Desired state for capturing swipe gesture.
*/
public void setSwipeEnabled(boolean enabled) {
mRefreshListLayout.setEnabled(enabled);
mRefreshGridLayout.setEnabled(enabled);
mRefreshEmptyLayout.setEnabled(enabled);
}
/**
* Sets the 'visibility' state of the FAB contained in the fragment.
*
* When 'false' is set, FAB visibility is set to View.GONE programmatically,
*
* @param enabled Desired visibility for the FAB.
*/
public void setFabEnabled(boolean enabled) {
if (enabled) {
mFabMain.setVisibility(View.VISIBLE);
} else {
mFabMain.setVisibility(View.GONE);
}
}
/**
* Set message for empty list view.
*/
public void <API key>(String message) {
if (mEmptyListContainer != null && mEmptyListMessage != null) {
mEmptyListMessage.setText(message);
}
}
/**
* displays an empty list information with a headline, a message and an icon.
*
* @param headline the headline
* @param message the message
* @param icon the icon to be shown
*/
public void <API key>(@StringRes final int headline, @StringRes final int message, @DrawableRes final int icon) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if (mEmptyListContainer != null && mEmptyListMessage != null) {
mEmptyListHeadline.setText(headline);
mEmptyListMessage.setText(message);
mEmptyListIcon.setImageResource(icon);
mEmptyListIcon.setVisibility(View.VISIBLE);
mEmptyListProgress.setVisibility(View.GONE);
}
}
});
}
public void setEmptyListMessage(final SearchType searchType) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if (searchType == SearchType.NO_SEARCH) {
<API key>(
R.string.<API key>,
R.string.file_list_empty,
R.drawable.<API key>
);
} else if (searchType == SearchType.FILE_SEARCH) {
<API key>(R.string.<API key>,
R.string.file_list_empty, R.drawable.<API key>);
} else if (searchType == SearchType.FAVORITE_SEARCH) {
<API key>(R.string.<API key>,
R.string.<API key>, R.drawable.ic_star_light_grey);
} else if (searchType == SearchType.VIDEO_SEARCH) {
<API key>(R.string.<API key>,
R.string.<API key>, R.drawable.ic_list_empty_video);
} else if (searchType == SearchType.PHOTO_SEARCH) {
<API key>(R.string.<API key>,
R.string.<API key>, R.drawable.ic_list_empty_image);
} else if (searchType == SearchType.<API key>) {
<API key>(R.string.<API key>,
R.string.<API key>, R.drawable.<API key>);
} else if (searchType == SearchType.<API key>) {
<API key>(R.string.<API key>,
R.string.<API key>, R.drawable.<API key>);
} else if (searchType == SearchType.REGULAR_FILTER) {
<API key>(R.string.<API key>,
R.string.<API key>, R.drawable.<API key>);
} else if (searchType == SearchType.<API key>) {
<API key>(R.string.<API key>,
R.string.<API key>, R.drawable.ic_star_light_grey);
} else if (searchType == SearchType.VIDEO_SEARCH_FILTER) {
<API key>(R.string.<API key>,
R.string.<API key>, R.drawable.ic_list_empty_video);
} else if (searchType == SearchType.<API key>) {
<API key>(R.string.<API key>,
R.string.<API key>, R.drawable.ic_list_empty_image);
} else if (searchType == SearchType.<API key>) {
<API key>(R.string.<API key>,
R.string.<API key>, R.drawable.<API key>);
} else if (searchType == SearchType.<API key>) {
<API key>(R.string.<API key>,
R.string.<API key>, R.drawable.<API key>);
} else if (searchType == SearchType.SHARED_FILTER) {
<API key>(R.string.<API key>,
R.string.<API key>, R.drawable.<API key>);
}
}
});
}
/**
* Set message for empty list view.
*/
public void <API key>() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if (mEmptyListContainer != null && mEmptyListMessage != null) {
mEmptyListHeadline.setText(R.string.file_list_loading);
mEmptyListMessage.setText("");
mEmptyListIcon.setVisibility(View.GONE);
mEmptyListProgress.setVisibility(View.VISIBLE);
}
}
});
}
/**
* Get the text of EmptyListMessage TextView.
*
* @return String empty text view text-value
*/
public String getEmptyViewText() {
return (mEmptyListContainer != null && mEmptyListMessage != null) ? mEmptyListMessage.getText().toString() : "";
}
protected void <API key>(SwipeRefreshLayout refreshLayout) {
// Colors in animations
refreshLayout.<API key>(R.color.color_accent, R.color.primary, R.color.primary_dark);
refreshLayout.<API key>(this);
}
@Override
public void onRefresh(boolean ignoreETag) {
mRefreshListLayout.setRefreshing(false);
mRefreshGridLayout.setRefreshing(false);
mRefreshEmptyLayout.setRefreshing(false);
if (mOnRefreshListener != null) {
mOnRefreshListener.onRefresh();
}
}
protected void setChoiceMode(int choiceMode) {
mListView.setChoiceMode(choiceMode);
mGridView.setChoiceMode(choiceMode);
}
protected void <API key>(AbsListView.<API key> listener) {
mListView.<API key>(listener);
mGridView.<API key>(listener);
}
/**
* TODO doc
* To be called before setAdapter, or <API key> will throw an exception
*
* @param enabled flag if footer should be shown/calculated
*/
protected void setFooterEnabled(boolean enabled) {
if (enabled) {
if (mGridView.getFooterViewCount() == 0 && mGridView.isCorrectAdapter()) {
if (mGridFooterView.getParent() != null) {
((ViewGroup) mGridFooterView.getParent()).removeView(mGridFooterView);
}
mGridView.addFooterView(mGridFooterView, null, false);
}
mGridFooterView.invalidate();
if (mListView.getFooterViewsCount() == 0) {
if (mListFooterView.getParent() != null) {
((ViewGroup) mListFooterView.getParent()).removeView(mListFooterView);
}
mListView.addFooterView(mListFooterView, null, false);
}
mListFooterView.invalidate();
} else {
mGridView.removeFooterView(mGridFooterView);
mListView.removeFooterView(mListFooterView);
}
}
/**
* set the list/grid footer text.
*
* @param text the footer text
*/
protected void setFooterText(String text) {
if (text != null && text.length() > 0) {
((TextView) mListFooterView.findViewById(R.id.footerText)).setText(text);
((TextView) mGridFooterView.findViewById(R.id.footerText)).setText(text);
setFooterEnabled(true);
} else {
setFooterEnabled(false);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.