answer stringlengths 15 1.25M |
|---|
.nav-bar > li:hover, .nav-bar > li a:hover { color:#a0a774;}
.nav-bar > li.active > a { }
ul.flyout li a:hover, .nav-bar li ul li a:hover {color:#a0a774;}
.flyout {border-top:2px solid #a0a774;}
.sectiontitle {border-left: 4px solid #a0a774;}
::-moz-selection{background:#a0a774;color:#fff;}
::selection{background:#a0a774;color:#fff;}
.ca-menu li:hover .ca-main {color: #a0a774;}
.topborder { border-top:4px solid #a0a774;}
#subheader{background: #a0a774;border-top: 1px solid #a0a774; color: #fff;}
#subheader a {color: #fff;text-decoration: none;}
#subheader a:hover { text-decoration: none; color: #fff; }
.readmore {background:#a0a774;}
#testimonials blockquote cite {color:#a0a774;}
.tags {background:#333;}
ul.pagination li.current a {background: #a0a774;}
.saymore {color:#a0a774;}
.submit {background:#a0a774;}
dl.tabs dd.active { border-top: 3px solid #a0a774;}
ul.accordion > li.active {border-top: 3px solid #a0a774;}
div.alert-box.default { background-color: #a0a774;}
.slide { margin: 0; padding: 0; border-top: solid 4px #a0a774;}
.btn-slide { background:#a0a774 url(../../images/plus.png) no-repeat;}
.btn-slide.active { background: #a0a774 url(../../images/minus.png) no-repeat;}
#footer {border-top:#a0a774 4px solid;}
.back-top a:hover{background-color: #666;}
.sf-shadow ul {border-top:2px solid #a0a774;}
.panel {border-left:4px solid #a0a774;}
.colorbackground {background:#a0a774;}
#homesubheader {background:#222;}
a.projectdetail { background: #ccc;text-shadow:none;color:#111;}
a.projectdetail:hover { background: #ccc;text-shadow:none;color:#111;}
#testimonials {border-left: solid 6px #a0a774;}
.ei-title h2{background:#a0a774;} |
<?php
namespace TYPO3\CMS\Core\Localization;
use TYPO3\CMS\Core\Localization\Exception\<API key>;
use TYPO3\CMS\Core\Localization\Exception\<API key>;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* Language store.
*/
class LanguageStore implements \TYPO3\CMS\Core\SingletonInterface {
/**
* File extension supported by the localization parser
*
* @var array
*/
protected $supportedExtensions;
/**
* Information about parsed file
*
* If data come from the cache, this array does not contain
* any information about this file
*
* @var array
*/
protected $configuration;
/**
* Parsed localization file
*
* @var array
*/
protected $data;
/**
* Constructor
*/
public function __construct() {
$this->initialize();
}
/**
* Initializes the current class.
*
* @return void
*/
public function initialize() {
if (isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['lang']['format']['priority']) && trim($GLOBALS['TYPO3_CONF_VARS']['SYS']['lang']['format']['priority']) !== '') {
$this->supportedExtensions = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['SYS']['lang']['format']['priority']);
} else {
$this->supportedExtensions = array('xlf', 'xml', 'php');
}
}
/**
* Checks if the store contains parsed data.
*
* @param string $fileReference File reference
* @param string $languageKey Valid language key
* @return bool
*/
public function hasData($fileReference, $languageKey) {
if (isset($this->data[$fileReference][$languageKey]) && is_array($this->data[$fileReference][$languageKey])) {
return TRUE;
}
return FALSE;
}
/**
* Retrieves data from the store.
*
* This method returns all parsed languages for the current file reference.
*
* @param string $fileReference File reference
* @return array
*/
public function getData($fileReference) {
return $this->data[$fileReference];
}
/**
* Retrieves data from the store for a language.
*
* @param string $fileReference File reference
* @param string $languageKey Valid language key
* @return array
* @see self::getData()
*/
public function getDataByLanguage($fileReference, $languageKey) {
return $this->data[$fileReference][$languageKey];
}
/**
* Sets data for a specific file reference and a language.
*
* @param string $fileReference File reference
* @param string $languageKey Valid language key
* @param array $data
* @return \TYPO3\CMS\Core\Localization\LanguageStore This instance to allow method chaining
*/
public function setData($fileReference, $languageKey, $data) {
$this->data[$fileReference][$languageKey] = $data;
return $this;
}
/**
* Flushes data.
*
* @param string $fileReference
* @return \TYPO3\CMS\Core\Localization\LanguageStore This instance to allow method chaining
*/
public function flushData($fileReference) {
unset($this->data[$fileReference]);
return $this;
}
/**
* Checks file reference configuration (charset, extension, ...).
*
* @param string $fileReference File reference
* @param string $languageKey Valid language key
* @param string $charset Rendering charset
* @return \TYPO3\CMS\Core\Localization\LanguageStore This instance to allow method chaining
* @throws \TYPO3\CMS\Core\Localization\Exception\<API key>
* @throws \TYPO3\CMS\Core\Localization\Exception\<API key>
*/
public function setConfiguration($fileReference, $languageKey, $charset) {
$this->configuration[$fileReference] = array(
'fileReference' => $fileReference,
'fileExtension' => FALSE,
'parserClass' => NULL,
'languageKey' => $languageKey,
'charset' => $charset
);
$<API key> = GeneralUtility::getFileAbsFileName($this-><API key>($fileReference));
foreach ($this->supportedExtensions as $extension) {
if (@is_file(($<API key> . '.' . $extension))) {
$this->configuration[$fileReference]['fileReference'] = $<API key> . '.' . $extension;
$this->configuration[$fileReference]['fileExtension'] = $extension;
break;
}
}
if ($this->configuration[$fileReference]['fileExtension'] === FALSE) {
throw new <API key>(sprintf('Source localization file (%s) not found', $fileReference), 1306410755);
}
$extension = $this->configuration[$fileReference]['fileExtension'];
if (isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['lang']['parser'][$extension]) && trim($GLOBALS['TYPO3_CONF_VARS']['SYS']['lang']['parser'][$extension]) !== '') {
$this->configuration[$fileReference]['parserClass'] = $GLOBALS['TYPO3_CONF_VARS']['SYS']['lang']['parser'][$extension];
} else {
throw new <API key>('TYPO3 Fatal Error: l10n parser for file extension "' . $extension . '" is not configured! Please check you configuration.', 1301579637);
}
if (!class_exists($this->configuration[$fileReference]['parserClass']) || trim($this->configuration[$fileReference]['parserClass']) === '') {
throw new <API key>('TYPO3 Fatal Error: l10n parser "' . $this->configuration[$fileReference]['parserClass'] . '" cannot be found or is an empty parser!', 1270853900);
}
return $this;
}
/**
* Get the fileReference without the extension
*
* @param string $fileReference File reference
* @return string
*/
public function <API key>($fileReference) {
if (!isset($this->configuration[$fileReference]['<API key>'])) {
$this->configuration[$fileReference]['<API key>'] = preg_replace('/\\.[a-z0-9]+$/i', '', $fileReference);
}
return $this->configuration[$fileReference]['<API key>'];
}
/**
* Returns the correct parser for a specific file reference.
*
* @param string $fileReference File reference
* @return \TYPO3\CMS\Core\Localization\Parser\<API key>
* @throws \TYPO3\CMS\Core\Localization\Exception\<API key>
*/
public function getParserInstance($fileReference) {
if (isset($this->configuration[$fileReference]['parserClass']) && trim($this->configuration[$fileReference]['parserClass']) !== '') {
return GeneralUtility::makeInstance((string)$this->configuration[$fileReference]['parserClass']);
} else {
throw new <API key>(sprintf('Invalid parser configuration for the current file (%s)', $fileReference), 1307293692);
}
}
/**
* Gets the absolute file path.
*
* @param string $fileReference
* @return string
* @throws \<API key>
*/
public function <API key>($fileReference) {
if (isset($this->configuration[$fileReference]['fileReference']) && trim($this->configuration[$fileReference]['fileReference']) !== '') {
return (string)$this->configuration[$fileReference]['fileReference'];
} else {
throw new \<API key>(sprintf('Invalid file reference configuration for the current file (%s)', $fileReference), 1307293693);
}
}
/**
* Get supported extensions
*
* @return array
*/
public function <API key>() {
return $this->supportedExtensions;
}
} |
<?php header("Content-type: text/css");
//this sets up the colors for the core missioncontrol template
require('../../css/color-vars.php');
?>
div#toolbar-box {background:#F5F5F5 !important;width:100%;}
div#content-box {border:0 !important;}
div#toolbar-box div.m {border:0 !important;padding:0 !important;}
#mc-title table.toolbar, #mc-title table.toolbar a.toolbar {margin-top:0;}
#mc-toolbox-wrap {width:100%;position:relative;}
#mc-submenu {margin-top:20px;margin-bottom:-30px;}
#mc-submenu ul#submenu {background:none;line-height:inherit;margin-left:50px;}
#mc-submenu ul#submenu li {padding-top:7px !important;padding-bottom:6px !important;}
#mc-submenu ul#submenu a {border:0;padding: 0 15px;font-size:12px;margin-right:0 !important;}
#mc-submenu ul#submenu a:hover {text-decoration:underline;}
#mc-component {border-radius:0;padding:0;}
form input[type="radio"], form input[type="checkbox"] {height:14px;} |
package net.semanticmetadata.lire.classifiers;
import net.semanticmetadata.lire.builders.DocumentBuilder;
import java.util.LinkedList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
public class ParallelKMeans extends KMeans {
int numThreads = DocumentBuilder.NUM_OF_THREADS;
private LinkedBlockingQueue<Item> queue = new LinkedBlockingQueue<Item>(100);
private ConcurrentHashMap<Integer, Integer> results;
public ParallelKMeans(int numClusters) {
super(numClusters);
}
/**
* Re-shuffle all features.
*/
protected void reOrganizeFeatures() {
results = new ConcurrentHashMap<Integer, Integer>(features.size());
LinkedList<Thread> threads = new LinkedList<Thread>();
Thread thread;
Thread p = new Thread(new ProducerForFeatures());
p.start();
for (int i = 0; i < numThreads; i++) {
thread = new Thread(new FeatureToClass());
thread.start();
threads.add(thread);
}
for (Thread next : threads) {
try {
next.join();
} catch (<API key> e) {
e.printStackTrace();
}
}
for (Integer integer : results.keySet()) {
clusters[results.get(integer)].members.add(integer);
}
threads.clear();
results.clear();
results = null;
}
protected void recomputeMeans() {
LinkedList<Thread> threads = new LinkedList<Thread>();
Thread p = new Thread(new ProducerForClusters());
p.start();
Thread thread;
for (int i = 0; i < numThreads; i++) {
thread = new Thread(new MeanOfCluster());
thread.start();
threads.add(thread);
}
for (Thread next : threads) {
try {
next.join();
} catch (<API key> e) {
e.printStackTrace();
}
}
threads.clear();
}
protected double overallStress() {
double v = 0.0;
LinkedList<ComputeStress> tasks = new LinkedList<ComputeStress>();
LinkedList<Thread> threads = new LinkedList<Thread>();
ComputeStress computeStress;
Thread thread;
Thread p = new Thread(new ProducerForClusters());
p.start();
for (int i = 0; i < numThreads; i++) {
computeStress = new ComputeStress();
thread = new Thread(computeStress);
thread.start();
tasks.add(computeStress);
threads.add(thread);
}
for (Thread next : threads) {
try {
next.join();
} catch (<API key> e) {
e.printStackTrace();
}
}
for (ComputeStress task : tasks) {
v += task.getResult();
}
tasks.clear();
threads.clear();
// for(Cluster cluster : clusters){
// v += cluster.getStress();
return v;
}
private class ComputeStress implements Runnable {
private boolean locallyEnded;
double result;
private ComputeStress() {
this.result = 0.0;
this.locallyEnded = false;
}
public void run() {
Item tmp;
while (!locallyEnded) {
try {
tmp = queue.take();
if (tmp.getNum() == -1) locallyEnded = true;
if (!locallyEnded) { // && tmp != -1
// for (Integer member : tmp.getCluster().members) {
// for (int j = 0; j < length; j++) {
// result += Math.abs(tmp.getCluster().mean[j] - features.get(member)[j]);
result += tmp.getCluster().getStress();
}
} catch (<API key> e) {
e.getMessage();
}
}
}
public double getResult() {
return result;
}
}
private class MeanOfCluster implements Runnable {
private boolean locallyEnded;
private MeanOfCluster() {
this.locallyEnded = false;
}
public void run() {
Cluster cluster;
double[] mean, f;
Item tmp;
double size, stress;
while (!locallyEnded) {
try {
tmp = queue.take();
if (tmp.getNum() == -1) locallyEnded = true;
if (!locallyEnded) { // && tmp != -1
cluster = tmp.getCluster();
mean = cluster.mean;
// for (int j = 0; j < length; j++) {
// mean[j] = 0;
// for (Integer member : cluster.members) {
// mean[j] += features.get(member)[j];
// if (cluster.members.size() > 1)
// mean[j] = mean[j] / (double) cluster.members.size();
for (int j = 0; j < length; j++) {
mean[j] = 0.0;
}
for (Integer member : cluster.members) {
f = features.get(member);
for (int j = 0; j < length; j++) {
mean[j] += f[j];
}
}
if (cluster.members.size() > 1) {
size = (double) cluster.members.size();
for (int j = 0; j < length; j++) {
mean[j] /= size;
}
} else if (cluster.members.size() == 1) {
System.err.println("** There is just one member in cluster " + tmp.getNum());
} else if (cluster.members.size() < 1) {
System.err.println("** There is NO member in cluster " + tmp.getNum());
// fill it with a random member?!?
System.arraycopy(features.get((int) Math.floor(Math.random() * features.size())), 0, mean, 0, mean.length);
}
stress = 0.0;
for (Integer member : cluster.members) {
f = features.get(member);
for (int j = 0; j < length; j++) {
stress += Math.abs(mean[j] - f[j]);
}
}
cluster.setStress(stress);
}
} catch (<API key> e) {
e.getMessage();
}
}
}
}
private class FeatureToClass implements Runnable {
private boolean locallyEnded;
private FeatureToClass() {
this.locallyEnded = false;
}
public void run() {
double v, minDistance;
double[] f;
Item tmp;
int best;
while (!locallyEnded) {
try {
tmp = queue.take();
if (tmp.getNum() == -1) locallyEnded = true;
if (!locallyEnded) { // && tmp != -1
f = tmp.getArray();
best = 0;
minDistance = clusters[0].getDistance(f);
for (int i = 1; i < clusters.length; i++) {
v = clusters[i].getDistance(f);
if (minDistance > v) {
best = i;
minDistance = v;
}
}
results.put(tmp.getNum(), best);
}
} catch (<API key> e) {
e.getMessage();
}
}
}
}
class ProducerForClusters implements Runnable {
private ProducerForClusters() {
queue.clear();
}
public void run() {
int counter = 0;
for(Cluster cluster : clusters){
try {
queue.put(new Item(counter, cluster));
} catch (<API key> e) {
e.printStackTrace();
}
counter++;
}
Cluster cluster = null;
for (int i = 0; i < numThreads * 3; i++) {
try {
queue.put(new Item(-1, cluster));
} catch (<API key> e) {
e.printStackTrace();
}
}
}
}
class ProducerForFeatures implements Runnable {
private ProducerForFeatures() {
queue.clear();
}
public void run() {
int counter = 0;
for (double[] feature : features) {
try {
queue.put(new Item(counter, feature));
} catch (<API key> e) {
e.printStackTrace();
}
counter++;
}
double[] tmp = null;
for (int i = 0; i < numThreads * 3; i++) {
try {
queue.put(new Item(-1, tmp));
} catch (<API key> e) {
e.printStackTrace();
}
}
}
}
private class Item {
private double[] array;
private Cluster cluster;
private int num;
Item(int num, double[] array) {
this.num = num;
this.array = array;
}
Item(int num, Cluster cluster) {
this.num = num;
this.cluster = cluster;
}
private int getNum() { return num; }
private Cluster getCluster() { return cluster; }
private double[] getArray() { return array; }
}
} |
#ifndef <API key>
#define <API key>
#include <platform/mt_typedefs.h>
#include <platform/disp_drv.h>
#include "lcm_drv.h"
#ifdef __cplusplus
extern "C" {
#endif
// UBoot Display Utility Macros
#define AS_UINT32(x) (*(unsigned int *)(x))
#define AS_UINT16(x) (*(unsigned short *)(x))
#define mt6573_DBG 1
#if mt6573_DBG
/*for assert redefined warning*/
/*#define ASSERT(expr) \
do { \
if(!(expr)) { \
printf("<ASSERT> %s:line %d %s\n", \
__FILE__,__LINE__,#expr); \
while (1); \
} \
} while(0);*/
#define NOT_IMPLEMENTED() \
do { \
printf("<NOT_IMPLEMENTED> %s:line %d\n", __FILE__, __LINE__); \
while (1); \
} while(0);
#else // !mt6573_DBG
#define ASSERT(expr)
#define NOT_IMPLEMENTED()
#endif // end of mt6573_DBG
#define NOT_REFERENCED(x) {(x) = (x);}
#define msleep(x) mdelay(x)
#define printk printf
typedef enum {
<API key> = 0,
<API key>,
} <API key>;
// UBoot Display Export Functions
UINT32 <API key>(void);
void mt_disp_init(void *lcdbase);
void mt_disp_power(BOOL on);
void mt_disp_update(UINT32 x, UINT32 y, UINT32 width, UINT32 height);
void mt_disp_wait_idle(void);
UINT32 <API key>(void);
UINT32 <API key>(void);
BOOL DISP_DetectDevice(void);
// -- Utility Functions for Customization --
void* mt_get_logo_db_addr(void);
void* mt_get_fb_addr(void);
void* mt_get_tempfb_addr(void);
UINT32 mt_get_fb_size(void);
void mt_disp_fill_rect(UINT32 left, UINT32 top,
UINT32 right, UINT32 bottom,
UINT32 color);
void <API key>(<API key> direct,
UINT32 left, UINT32 top,
UINT32 right, UINT32 bottom,
UINT32 fgColor, UINT32 bgColor,
UINT32 start_div, UINT32 total_div,
UINT32 occupied_div);
#ifdef __cplusplus
}
#endif
#endif // <API key> |
//12/13/2004
//Written by Gavinius
//based on Nardin and Zjovaz previous script
using System;
using System.Collections;
using DOL.Database;
using DOL.GS.PacketHandler;
using DOL.Language;
namespace DOL.GS
{
[NPCGuildScript("Enchanter")]
public class Enchanter : GameNPC
{
private const string ENCHANT_ITEM_WEAK = "enchanting item";
private int[] BONUS_TABLE = new int[] {5, 5, 10, 15, 20, 25, 30, 30};
<summary>
Adds messages to ArrayList which are sent when object is targeted
</summary>
<param name="player">GamePlayer that is examining this object</param>
<returns>list with string messages</returns>
public override IList GetExamineMessages(GamePlayer player)
{
IList list = new ArrayList();
list.Add(LanguageMgr.GetTranslation(player.Client.Account.Language, "Enchanter.GetExamineMessages.Text1",
GetName(0, false, player.Client.Account.Language, this)));
list.Add(LanguageMgr.GetTranslation(player.Client.Account.Language, "Enchanter.GetExamineMessages.Text2",
GetName(0, false, player.Client.Account.Language, this), GetPronoun(0, true, player.Client.Account.Language),
GetAggroLevelString(player, false)));
return list;
}
public override bool Interact(GamePlayer player)
{
if (base.Interact(player))
{
TurnTo(player, 25000);
string Material;
if (player.Realm == eRealm.Hibernia)
Material = LanguageMgr.GetTranslation(ServerProperties.Properties.DB_LANGUAGE, "Enchanter.Interact.Text1");
else
Material = LanguageMgr.GetTranslation(ServerProperties.Properties.DB_LANGUAGE, "Enchanter.Interact.Text2");
SayTo(player, eChatLoc.CL_ChatWindow, LanguageMgr.GetTranslation(player.Client.Account.Language, "Enchanter.Interact.Text3", Material));
return true;
}
return false;
}
public override bool ReceiveItem(GameLiving source, InventoryItem item)
{
GamePlayer t = source as GamePlayer;
if (t == null || item == null)
return false;
if (item.Level >= 10 && item.IsCrafted)
{
if (item.Object_Type != (int) eObjectType.Magical && item.Object_Type != (int) eObjectType.Bolt && item.Object_Type != (int) eObjectType.Poison)
{
if (item.Bonus == 0)
{
t.TempProperties.setProperty(ENCHANT_ITEM_WEAK, new WeakRef(item));
t.Client.Out.SendCustomDialog(LanguageMgr.GetTranslation(t.Client, "Enchanter.ReceiveItem.Text1", Money.GetString(CalculEnchantPrice(item))), new <API key>(<API key>));
}
else
SayTo(t, eChatLoc.CL_SystemWindow, LanguageMgr.GetTranslation(t.Client, "Enchanter.ReceiveItem.Text2"));
}
else
SayTo(t, eChatLoc.CL_SystemWindow, LanguageMgr.GetTranslation(t.Client, "Enchanter.ReceiveItem.Text3"));
}
else
SayTo(t, eChatLoc.CL_SystemWindow, LanguageMgr.GetTranslation(t.Client, "Enchanter.ReceiveItem.Text4"));
return false;
}
protected void <API key>(GamePlayer player, byte response)
{
WeakReference itemWeak =
(WeakReference) player.TempProperties.getProperty<object>(
ENCHANT_ITEM_WEAK,
new WeakRef(null)
);
player.TempProperties.removeProperty(ENCHANT_ITEM_WEAK);
if (response != 0x01 || !this.IsWithinRadius(player, WorldMgr.INTERACT_DISTANCE))
return;
InventoryItem item = (InventoryItem) itemWeak.Target;
if (item == null || item.SlotPosition == (int) eInventorySlot.Ground
|| item.OwnerID == null || item.OwnerID != player.InternalID)
{
player.Out.SendMessage(LanguageMgr.GetTranslation(player.Client.Account.Language, "Enchanter.<API key>.Text1"), eChatType.CT_System, eChatLoc.CL_SystemWindow);
return;
}
long Fee = CalculEnchantPrice(item);
if (player.GetCurrentMoney() < Fee)
{
SayTo(player, eChatLoc.CL_SystemWindow, LanguageMgr.GetTranslation(player.Client.Account.Language, "Enchanter.<API key>.Text2", Money.GetString(Fee)));
return;
}
if (item.Level < 50)
item.Bonus = BONUS_TABLE[(item.Level/5) - 2];
else
item.Bonus = 35;
item.Name = LanguageMgr.GetTranslation(player.Client.Account.Language, "Enchanter.<API key>.Text3") + " " + item.Name;
player.Out.<API key>(new InventoryItem[] { item });
player.Out.SendMessage(LanguageMgr.GetTranslation(player.Client.Account.Language, "Enchanter.<API key>.Text4",
GetName(0, false, player.Client.Account.Language, this), Money.GetString(Fee)), eChatType.CT_System, eChatLoc.CL_SystemWindow);
player.RemoveMoney(Fee, null);
InventoryLogging.LogInventoryAction(player, this, <API key>.Merchant, Fee);
SayTo(player, eChatLoc.CL_SystemWindow, LanguageMgr.GetTranslation(player.Client.Account.Language, "Enchanter.<API key>.Text5", item.GetName(1, false)));
return;
}
public long CalculEnchantPrice(InventoryItem item)
{
return (item.Price/5);
}
}
} |
#ifndef <API key>
#define <API key>
#pragma once
#include "softlist_dev.h"
#include <cassert>
class <API key> : public device_interface
{
public:
// TODO: find a better home for this helper
template <unsigned Shift, typename T>
static void <API key>(
offs_t length,
offs_t decode_limit,
offs_t decode_mask,
offs_t decode_offset,
offs_t base,
T &&install)
{
assert(!(decode_limit & base));
for (offs_t remain = length, start = 0U; remain && (decode_limit >= start); )
{
unsigned const msb(31 - count_leading_zeros(u32(remain)));
offs_t const chunk(offs_t(1) << msb);
offs_t range((chunk - 1) & decode_limit);
offs_t mirror(decode_limit & ~decode_mask & ~range);
// TODO: deal with small offsets - probably requires breaking into smaller chunks with mirror set
if (decode_offset & range)
throw emu_fatalerror("Can't deal with offset/size combination\n");
range = (range << Shift) | ((offs_t(1) << Shift) - 1);
mirror <<= Shift;
offs_t const begin(start << Shift);
offs_t const end(begin | range);
offs_t const src(start | ((chunk - 1) & decode_offset));
install(base | begin, base | end, mirror, src);
remain ^= chunk;
start ^= chunk;
}
}
// construction/destruction
virtual ~<API key>();
// reading and writing
virtual u8 read_rom(offs_t offset);
virtual u16 read16_rom(offs_t offset, u16 mem_mask);
virtual u32 read32_rom(offs_t offset, u32 mem_mask);
virtual u8 read_ram(offs_t offset);
virtual void write_ram(offs_t offset, u8 data);
virtual void rom_alloc(u32 size, int width, endianness_t end, char const *tag);
virtual void ram_alloc(u32 size);
u8 *get_rom_base() { return m_rom; }
u32 get_rom_size() { return m_rom_size; }
u8 *get_region_base() { return m_region.found() ? m_region->base() : nullptr; }
u32 get_region_size() { return m_region.found() ? m_region->bytes() : 0U; }
u8 *get_ram_base() { return &m_ram[0]; }
u32 get_ram_size() { return m_ram.size(); }
void save_ram() { device().save_item(NAME(m_ram)); }
protected:
<API key>(machine_config const &mconfig, device_t &device);
// this replaces m_rom for non-user configurable carts!
<API key> m_region;
// internal state
std::vector<u8> m_ram;
u8 *m_rom;
u32 m_rom_size;
};
enum
{
GENERIC_ROM8_WIDTH = 1,
GENERIC_ROM16_WIDTH = 2,
GENERIC_ROM32_WIDTH = 4
};
#define <API key> ":cart:rom"
class generic_slot_device : public device_t,
public <API key>,
public <API key><<API key>>
{
public:
virtual ~generic_slot_device();
template <typename... T> void set_device_load(T &&... args) { m_device_image_load.set(std::forward<T>(args)...); }
template <typename... T> void set_device_unload(T &&... args) { <API key>.set(std::forward<T>(args)...); }
void set_interface(char const *interface) { m_interface = interface; }
void set_default_card(char const *def) { m_default_card = def; }
void set_extensions(char const *exts) { m_extensions = exts; }
void set_must_be_loaded(bool mandatory) { m_must_be_loaded = mandatory; }
void set_width(int width) { m_width = width; }
void set_endian(endianness_t end) { m_endianness = end; }
// <API key> implementation
virtual image_init_result call_load() override;
virtual void call_unload() override;
virtual iodevice_t image_type() const noexcept override { return IO_CARTSLOT; }
virtual bool is_readable() const noexcept override { return true; }
virtual bool is_writeable() const noexcept override { return false; }
virtual bool is_creatable() const noexcept override { return false; }
virtual bool must_be_loaded() const noexcept override { return m_must_be_loaded; }
virtual bool is_reset_on_load() const noexcept override { return true; }
virtual char const *image_interface() const noexcept override { return m_interface; }
virtual char const *file_extensions() const noexcept override { return m_extensions; }
// slot interface overrides
virtual std::string <API key>(<API key> &hook) const override;
u32 common_get_size(char const *region);
void common_load_rom(u8 *ROM, u32 len, char const *region);
// reading and writing
virtual u8 read_rom(offs_t offset);
virtual u16 read16_rom(offs_t offset, u16 mem_mask = 0xffff);
virtual u32 read32_rom(offs_t offset, u32 mem_mask = 0xffffffff);
virtual u8 read_ram(offs_t offset);
virtual void write_ram(offs_t offset, u8 data);
virtual void rom_alloc(u32 size, int width, endianness_t end) { if (m_cart) m_cart->rom_alloc(size, width, end, tag()); }
virtual void ram_alloc(u32 size) { if (m_cart) m_cart->ram_alloc(size); }
u8* get_rom_base()
{
if (!m_cart)
return nullptr;
else if (!user_loadable())
return m_cart->get_region_base();
else
return m_cart->get_rom_base();
}
u32 get_rom_size()
{
if (!m_cart)
return 0U;
else if (!user_loadable())
return m_cart->get_region_size();
else
return m_cart->get_rom_size();
}
u8 *get_ram_base() { return m_cart ? m_cart->get_ram_base() : nullptr; }
void save_ram() { if (m_cart && m_cart->get_ram_size()) m_cart->save_ram(); }
protected:
generic_slot_device(machine_config const &mconfig, device_type type, char const *tag, device_t *owner, u32 clock);
// device-level overrides
virtual void device_start() override ATTR_COLD;
// <API key> implementation
virtual <API key> const &<API key>() const override { return <API key>::instance(); }
char const *m_interface;
char const *m_default_card;
char const *m_extensions;
bool m_must_be_loaded;
int m_width;
endianness_t m_endianness;
<API key> *m_cart;
load_delegate m_device_image_load;
unload_delegate <API key>;
};
class <API key> : public generic_slot_device
{
public:
template <typename T>
<API key>(machine_config const &mconfig, char const *tag, device_t *owner, T &&opts, char const *intf, char const *exts = nullptr)
: <API key>(mconfig, tag, owner, u32(0))
{
opts(*this);
set_fixed(false);
set_interface(intf);
if (exts)
set_extensions(exts);
}
<API key>(machine_config const &mconfig, char const *tag, device_t *owner, u32 clock = 0);
virtual iodevice_t image_type() const noexcept override { return IO_ROM; }
};
class <API key> : public generic_slot_device
{
public:
template <typename T>
<API key>(machine_config const &mconfig, char const *tag, device_t *owner, T &&opts, char const *intf, char const *exts = nullptr)
: <API key>(mconfig, tag, owner, u32(0))
{
opts(*this);
set_fixed(false);
set_interface(intf);
if (exts)
set_extensions(exts);
}
<API key>(machine_config const &mconfig, char const *tag, device_t *owner, u32 clock = 0);
virtual iodevice_t image_type() const noexcept override { return IO_CARTSLOT; }
};
// device type definition
DECLARE_DEVICE_TYPE(GENERIC_SOCKET, <API key>)
DECLARE_DEVICE_TYPE(GENERIC_CARTSLOT, <API key>)
#endif // <API key> |
#include <linux/slab.h>
#include <scsi/scsi_tcq.h>
#include <scsi/libiscsi.h>
#include "bnx2i.h"
struct <API key> *<API key>;
struct iscsi_transport <API key>;
static struct scsi_host_template bnx2i_host_template;
/*
* Global endpoint resource info
*/
static DEFINE_SPINLOCK(bnx2i_resc_lock); /* protects global resources */
static int bnx2i_adapter_ready(struct bnx2i_hba *hba)
{
int retval = 0;
if (!hba || !test_bit(ADAPTER_STATE_UP, &hba->adapter_state) ||
test_bit(<API key>, &hba->adapter_state) ||
test_bit(<API key>, &hba->adapter_state))
retval = -EPERM;
return retval;
}
/**
* <API key> - identifies various BD bookmarks
* @cmd: iscsi cmd struct pointer
* @buf_off: absolute buffer offset
* @start_bd_off: u32 pointer to return the offset within the BD
* indicated by 'start_bd_idx' on which 'buf_off' falls
* @start_bd_idx: index of the BD on which 'buf_off' falls
*
* identifies & marks various bd info for scsi command's imm data,
* unsolicited data and the first solicited data seq.
*/
static void <API key>(struct bnx2i_cmd *cmd, u32 buf_off,
u32 *start_bd_off, u32 *start_bd_idx)
{
struct iscsi_bd *bd_tbl = cmd->io_tbl.bd_tbl;
u32 cur_offset = 0;
u32 cur_bd_idx = 0;
if (buf_off) {
while (buf_off >= (cur_offset + bd_tbl->buffer_length)) {
cur_offset += bd_tbl->buffer_length;
cur_bd_idx++;
bd_tbl++;
}
}
*start_bd_off = buf_off - cur_offset;
*start_bd_idx = cur_bd_idx;
}
/**
* <API key> - sets up BD various information
* @task: transport layer's cmd struct pointer
*
* identifies & marks various bd info for scsi command's immediate data,
* unsolicited data and first solicited data seq which includes BD start
* index & BD buf off. his function takes into account iscsi parameter such
* as immediate data and unsolicited data is support on this connection.
*/
static void <API key>(struct iscsi_task *task)
{
struct bnx2i_cmd *cmd = task->dd_data;
u32 start_bd_offset;
u32 start_bd_idx;
u32 buffer_offset = 0;
u32 cmd_len = cmd->req.<API key>;
/* if ImmediateData is turned off & IntialR2T is turned on,
* there will be no immediate or unsolicited data, just return.
*/
if (!<API key>(task) && !task->imm_count)
return;
/* Immediate data */
buffer_offset += task->imm_count;
if (task->imm_count == cmd_len)
return;
if (<API key>(task)) {
<API key>(cmd, buffer_offset,
&start_bd_offset, &start_bd_idx);
cmd->req.ud_buffer_offset = start_bd_offset;
cmd->req.ud_start_bd_index = start_bd_idx;
buffer_offset += task->unsol_r2t.data_length;
}
if (buffer_offset != cmd_len) {
<API key>(cmd, buffer_offset,
&start_bd_offset, &start_bd_idx);
if ((start_bd_offset > task->conn->session->first_burst) ||
(start_bd_idx > scsi_sg_count(cmd->scsi_cmd))) {
int i = 0;
iscsi_conn_printk(KERN_ALERT, task->conn,
"bnx2i- error, buf offset 0x%x "
"bd_valid %d use_sg %d\n",
buffer_offset, cmd->io_tbl.bd_valid,
scsi_sg_count(cmd->scsi_cmd));
for (i = 0; i < cmd->io_tbl.bd_valid; i++)
iscsi_conn_printk(KERN_ALERT, task->conn,
"bnx2i err, bd[%d]: len %x\n",
i, cmd->io_tbl.bd_tbl[i].\
buffer_length);
}
cmd->req.sd_buffer_offset = start_bd_offset;
cmd->req.sd_start_bd_index = start_bd_idx;
}
}
/**
* bnx2i_map_scsi_sg - maps IO buffer and prepares the BD table
* @hba: adapter instance
* @cmd: iscsi cmd struct pointer
*
* map SG list
*/
static int bnx2i_map_scsi_sg(struct bnx2i_hba *hba, struct bnx2i_cmd *cmd)
{
struct scsi_cmnd *sc = cmd->scsi_cmd;
struct iscsi_bd *bd = cmd->io_tbl.bd_tbl;
struct scatterlist *sg;
int byte_count = 0;
int bd_count = 0;
int sg_count;
int sg_len;
u64 addr;
int i;
BUG_ON(scsi_sg_count(sc) > <API key>);
sg_count = scsi_dma_map(sc);
scsi_for_each_sg(sc, sg, sg_count, i) {
sg_len = sg_dma_len(sg);
addr = (u64) sg_dma_address(sg);
bd[bd_count].buffer_addr_lo = addr & 0xffffffff;
bd[bd_count].buffer_addr_hi = addr >> 32;
bd[bd_count].buffer_length = sg_len;
bd[bd_count].flags = 0;
if (bd_count == 0)
bd[bd_count].flags = <API key>;
byte_count += sg_len;
bd_count++;
}
if (bd_count)
bd[bd_count - 1].flags |= <API key>;
BUG_ON(byte_count != scsi_bufflen(sc));
return bd_count;
}
/**
* <API key> - maps SG list
* @cmd: iscsi cmd struct pointer
*
* creates BD list table for the command
*/
static void <API key>(struct bnx2i_cmd *cmd)
{
int bd_count;
bd_count = bnx2i_map_scsi_sg(cmd->conn->hba, cmd);
if (!bd_count) {
struct iscsi_bd *bd = cmd->io_tbl.bd_tbl;
bd[0].buffer_addr_lo = bd[0].buffer_addr_hi = 0;
bd[0].buffer_length = bd[0].flags = 0;
}
cmd->io_tbl.bd_valid = bd_count;
}
/**
* <API key> - unmaps SG list
* @cmd: iscsi cmd struct pointer
*
* unmap IO buffers and invalidate the BD table
*/
void <API key>(struct bnx2i_cmd *cmd)
{
struct scsi_cmnd *sc = cmd->scsi_cmd;
if (cmd->io_tbl.bd_valid && sc) {
scsi_dma_unmap(sc);
cmd->io_tbl.bd_valid = 0;
}
}
static void <API key>(struct bnx2i_cmd *cmd)
{
memset(&cmd->req, 0x00, sizeof(cmd->req));
cmd->req.op_code = 0xFF;
cmd->req.bd_list_addr_lo = (u32) cmd->io_tbl.bd_tbl_dma;
cmd->req.bd_list_addr_hi =
(u32) ((u64) cmd->io_tbl.bd_tbl_dma >> 32);
}
/**
* <API key> - bind conn structure to 'iscsi_cid'
* @hba: pointer to adapter instance
* @conn: pointer to iscsi connection
* @iscsi_cid: iscsi context ID, range 0 - (MAX_CONN - 1)
*
* update iscsi cid table entry with connection pointer. This enables
* driver to quickly get hold of connection structure pointer in
* completion/interrupt thread using iscsi context ID
*/
static int <API key>(struct bnx2i_hba *hba,
struct bnx2i_conn *bnx2i_conn,
u32 iscsi_cid)
{
if (hba && hba->cid_que.conn_cid_tbl[iscsi_cid]) {
iscsi_conn_printk(KERN_ALERT, bnx2i_conn->cls_conn->dd_data,
"conn bind - entry #%d not free\n", iscsi_cid);
return -EBUSY;
}
hba->cid_que.conn_cid_tbl[iscsi_cid] = bnx2i_conn;
return 0;
}
/**
* <API key> - maps an iscsi cid to corresponding conn ptr
* @hba: pointer to adapter instance
* @iscsi_cid: iscsi context ID, range 0 - (MAX_CONN - 1)
*/
struct bnx2i_conn *<API key>(struct bnx2i_hba *hba,
u16 iscsi_cid)
{
if (!hba->cid_que.conn_cid_tbl) {
printk(KERN_ERR "bnx2i: ERROR - missing conn<->cid table\n");
return NULL;
} else if (iscsi_cid >= hba->max_active_conns) {
printk(KERN_ERR "bnx2i: wrong cid #%d\n", iscsi_cid);
return NULL;
}
return hba->cid_que.conn_cid_tbl[iscsi_cid];
}
/**
* <API key> - allocates a iscsi_cid from free pool
* @hba: pointer to adapter instance
*/
static u32 <API key>(struct bnx2i_hba *hba)
{
int idx;
if (!hba->cid_que.cid_free_cnt)
return -1;
idx = hba->cid_que.cid_q_cons_idx;
hba->cid_que.cid_q_cons_idx++;
if (hba->cid_que.cid_q_cons_idx == hba->cid_que.cid_q_max_idx)
hba->cid_que.cid_q_cons_idx = 0;
hba->cid_que.cid_free_cnt
return hba->cid_que.cid_que[idx];
}
/**
* <API key> - returns tcp port to free list
* @hba: pointer to adapter instance
* @iscsi_cid: iscsi context ID to free
*/
static void <API key>(struct bnx2i_hba *hba, u16 iscsi_cid)
{
int idx;
if (iscsi_cid == (u16) -1)
return;
hba->cid_que.cid_free_cnt++;
idx = hba->cid_que.cid_q_prod_idx;
hba->cid_que.cid_que[idx] = iscsi_cid;
hba->cid_que.conn_cid_tbl[iscsi_cid] = NULL;
hba->cid_que.cid_q_prod_idx++;
if (hba->cid_que.cid_q_prod_idx == hba->cid_que.cid_q_max_idx)
hba->cid_que.cid_q_prod_idx = 0;
}
/**
* <API key> - sets up free iscsi cid queue
* @hba: pointer to adapter instance
*
* allocates memory for iscsi cid queue & 'cid - conn ptr' mapping table,
* and initialize table attributes
*/
static int <API key>(struct bnx2i_hba *hba)
{
int mem_size;
int i;
mem_size = hba->max_active_conns * sizeof(u32);
mem_size = (mem_size + (PAGE_SIZE - 1)) & PAGE_MASK;
hba->cid_que.cid_que_base = kmalloc(mem_size, GFP_KERNEL);
if (!hba->cid_que.cid_que_base)
return -ENOMEM;
mem_size = hba->max_active_conns * sizeof(struct bnx2i_conn *);
mem_size = (mem_size + (PAGE_SIZE - 1)) & PAGE_MASK;
hba->cid_que.conn_cid_tbl = kmalloc(mem_size, GFP_KERNEL);
if (!hba->cid_que.conn_cid_tbl) {
kfree(hba->cid_que.cid_que_base);
hba->cid_que.cid_que_base = NULL;
return -ENOMEM;
}
hba->cid_que.cid_que = (u32 *)hba->cid_que.cid_que_base;
hba->cid_que.cid_q_prod_idx = 0;
hba->cid_que.cid_q_cons_idx = 0;
hba->cid_que.cid_q_max_idx = hba->max_active_conns;
hba->cid_que.cid_free_cnt = hba->max_active_conns;
for (i = 0; i < hba->max_active_conns; i++) {
hba->cid_que.cid_que[i] = i;
hba->cid_que.conn_cid_tbl[i] = NULL;
}
return 0;
}
/**
* <API key> - releases 'iscsi_cid' queue resources
* @hba: pointer to adapter instance
*/
static void <API key>(struct bnx2i_hba *hba)
{
kfree(hba->cid_que.cid_que_base);
hba->cid_que.cid_que_base = NULL;
kfree(hba->cid_que.conn_cid_tbl);
hba->cid_que.conn_cid_tbl = NULL;
}
/**
* bnx2i_alloc_ep - allocates ep structure from global pool
* @hba: pointer to adapter instance
*
* routine allocates a free endpoint structure from global pool and
* a tcp port to be used for this connection. Global resource lock,
* 'bnx2i_resc_lock' is held while accessing shared global data structures
*/
static struct iscsi_endpoint *bnx2i_alloc_ep(struct bnx2i_hba *hba)
{
struct iscsi_endpoint *ep;
struct bnx2i_endpoint *bnx2i_ep;
u32 ec_div;
ep = <API key>(sizeof(*bnx2i_ep));
if (!ep) {
printk(KERN_ERR "bnx2i: Could not allocate ep\n");
return NULL;
}
bnx2i_ep = ep->dd_data;
bnx2i_ep->cls_ep = ep;
INIT_LIST_HEAD(&bnx2i_ep->link);
bnx2i_ep->state = EP_STATE_IDLE;
bnx2i_ep->ep_iscsi_cid = (u16) -1;
bnx2i_ep->hba = hba;
bnx2i_ep->hba_age = hba->age;
ec_div = event_coal_div;
while (ec_div >>= 1)
bnx2i_ep->ec_shift += 1;
hba->ofld_conns_active++;
init_waitqueue_head(&bnx2i_ep->ofld_wait);
return ep;
}
/**
* bnx2i_free_ep - free endpoint
* @ep: pointer to iscsi endpoint structure
*/
static void bnx2i_free_ep(struct iscsi_endpoint *ep)
{
struct bnx2i_endpoint *bnx2i_ep = ep->dd_data;
unsigned long flags;
spin_lock_irqsave(&bnx2i_resc_lock, flags);
bnx2i_ep->state = EP_STATE_IDLE;
bnx2i_ep->hba->ofld_conns_active
if (bnx2i_ep->ep_iscsi_cid != (u16) -1)
<API key>(bnx2i_ep->hba, bnx2i_ep->ep_iscsi_cid);
if (bnx2i_ep->conn) {
bnx2i_ep->conn->ep = NULL;
bnx2i_ep->conn = NULL;
}
bnx2i_ep->hba = NULL;
<API key>(&bnx2i_resc_lock, flags);
<API key>(ep);
}
/**
* bnx2i_alloc_bdt - allocates buffer descriptor (BD) table for the command
* @hba: adapter instance pointer
* @session: iscsi session pointer
* @cmd: iscsi command structure
*/
static int bnx2i_alloc_bdt(struct bnx2i_hba *hba, struct iscsi_session *session,
struct bnx2i_cmd *cmd)
{
struct io_bdt *io = &cmd->io_tbl;
struct iscsi_bd *bd;
io->bd_tbl = dma_alloc_coherent(&hba->pcidev->dev,
<API key> * sizeof(*bd),
&io->bd_tbl_dma, GFP_KERNEL);
if (!io->bd_tbl) {
<API key>(KERN_ERR, session, "Could not "
"allocate bdt.\n");
return -ENOMEM;
}
io->bd_valid = 0;
return 0;
}
/**
* <API key> - destroys iscsi command pool and release BD table
* @hba: adapter instance pointer
* @session: iscsi session pointer
* @cmd: iscsi command structure
*/
static void <API key>(struct bnx2i_hba *hba,
struct iscsi_session *session)
{
int i;
for (i = 0; i < session->cmds_max; i++) {
struct iscsi_task *task = session->cmds[i];
struct bnx2i_cmd *cmd = task->dd_data;
if (cmd->io_tbl.bd_tbl)
dma_free_coherent(&hba->pcidev->dev,
<API key> *
sizeof(struct iscsi_bd),
cmd->io_tbl.bd_tbl,
cmd->io_tbl.bd_tbl_dma);
}
}
/**
* <API key> - sets up iscsi command pool for the session
* @hba: adapter instance pointer
* @session: iscsi session pointer
*/
static int <API key>(struct bnx2i_hba *hba,
struct iscsi_session *session)
{
int i;
for (i = 0; i < session->cmds_max; i++) {
struct iscsi_task *task = session->cmds[i];
struct bnx2i_cmd *cmd = task->dd_data;
task->hdr = &cmd->hdr;
task->hdr_max = sizeof(struct iscsi_hdr);
if (bnx2i_alloc_bdt(hba, session, cmd))
goto free_bdts;
}
return 0;
free_bdts:
<API key>(hba, session);
return -ENOMEM;
}
/**
* bnx2i_setup_mp_bdt - allocate BD table resources
* @hba: pointer to adapter structure
*
* Allocate memory for dummy buffer and associated BD
* table to be used by middle path (MP) requests
*/
static int bnx2i_setup_mp_bdt(struct bnx2i_hba *hba)
{
int rc = 0;
struct iscsi_bd *mp_bdt;
u64 addr;
hba->mp_bd_tbl = dma_alloc_coherent(&hba->pcidev->dev, PAGE_SIZE,
&hba->mp_bd_dma, GFP_KERNEL);
if (!hba->mp_bd_tbl) {
printk(KERN_ERR "unable to allocate Middle Path BDT\n");
rc = -1;
goto out;
}
hba->dummy_buffer = dma_alloc_coherent(&hba->pcidev->dev, PAGE_SIZE,
&hba->dummy_buf_dma, GFP_KERNEL);
if (!hba->dummy_buffer) {
printk(KERN_ERR "unable to alloc Middle Path Dummy Buffer\n");
dma_free_coherent(&hba->pcidev->dev, PAGE_SIZE,
hba->mp_bd_tbl, hba->mp_bd_dma);
hba->mp_bd_tbl = NULL;
rc = -1;
goto out;
}
mp_bdt = (struct iscsi_bd *) hba->mp_bd_tbl;
addr = (unsigned long) hba->dummy_buf_dma;
mp_bdt->buffer_addr_lo = addr & 0xffffffff;
mp_bdt->buffer_addr_hi = addr >> 32;
mp_bdt->buffer_length = PAGE_SIZE;
mp_bdt->flags = <API key> |
<API key>;
out:
return rc;
}
/**
* bnx2i_free_mp_bdt - releases ITT back to free pool
* @hba: pointer to adapter instance
*
* free MP dummy buffer and associated BD table
*/
static void bnx2i_free_mp_bdt(struct bnx2i_hba *hba)
{
if (hba->mp_bd_tbl) {
dma_free_coherent(&hba->pcidev->dev, PAGE_SIZE,
hba->mp_bd_tbl, hba->mp_bd_dma);
hba->mp_bd_tbl = NULL;
}
if (hba->dummy_buffer) {
dma_free_coherent(&hba->pcidev->dev, PAGE_SIZE,
hba->dummy_buffer, hba->dummy_buf_dma);
hba->dummy_buffer = NULL;
}
return;
}
/**
* bnx2i_drop_session - notifies iscsid of connection error.
* @hba: adapter instance pointer
* @session: iscsi session pointer
*
* This notifies iscsid that there is a error, so it can initiate
* recovery.
*
* This relies on caller using the iscsi class iterator so the object
* is refcounted and does not disapper from under us.
*/
void bnx2i_drop_session(struct iscsi_cls_session *cls_session)
{
<API key>(cls_session->dd_data, <API key>);
}
/**
* <API key> - add an entry to EP destroy list
* @hba: pointer to adapter instance
* @ep: pointer to endpoint (transport indentifier) structure
*
* EP destroy queue manager
*/
static int <API key>(struct bnx2i_hba *hba,
struct bnx2i_endpoint *ep)
{
write_lock_bh(&hba->ep_rdwr_lock);
list_add_tail(&ep->link, &hba->ep_destroy_list);
write_unlock_bh(&hba->ep_rdwr_lock);
return 0;
}
/**
* <API key> - add an entry to EP destroy list
*
* @hba: pointer to adapter instance
* @ep: pointer to endpoint (transport indentifier) structure
*
* EP destroy queue manager
*/
static int <API key>(struct bnx2i_hba *hba,
struct bnx2i_endpoint *ep)
{
write_lock_bh(&hba->ep_rdwr_lock);
list_del_init(&ep->link);
write_unlock_bh(&hba->ep_rdwr_lock);
return 0;
}
/**
* <API key> - add an entry to ep offload pending list
* @hba: pointer to adapter instance
* @ep: pointer to endpoint (transport indentifier) structure
*
* pending conn offload completion queue manager
*/
static int <API key>(struct bnx2i_hba *hba,
struct bnx2i_endpoint *ep)
{
write_lock_bh(&hba->ep_rdwr_lock);
list_add_tail(&ep->link, &hba->ep_ofld_list);
write_unlock_bh(&hba->ep_rdwr_lock);
return 0;
}
/**
* <API key> - add an entry to ep offload pending list
* @hba: pointer to adapter instance
* @ep: pointer to endpoint (transport indentifier) structure
*
* pending conn offload completion queue manager
*/
static int <API key>(struct bnx2i_hba *hba,
struct bnx2i_endpoint *ep)
{
write_lock_bh(&hba->ep_rdwr_lock);
list_del_init(&ep->link);
write_unlock_bh(&hba->ep_rdwr_lock);
return 0;
}
/**
* <API key> - find iscsi_cid in pending list of endpoints
*
* @hba: pointer to adapter instance
* @iscsi_cid: iscsi context ID to find
*
*/
struct bnx2i_endpoint *
<API key>(struct bnx2i_hba *hba, u32 iscsi_cid)
{
struct list_head *list;
struct list_head *tmp;
struct bnx2i_endpoint *ep;
read_lock_bh(&hba->ep_rdwr_lock);
list_for_each_safe(list, tmp, &hba->ep_ofld_list) {
ep = (struct bnx2i_endpoint *)list;
if (ep->ep_iscsi_cid == iscsi_cid)
break;
ep = NULL;
}
read_unlock_bh(&hba->ep_rdwr_lock);
if (!ep)
printk(KERN_ERR "l5 cid %d not found\n", iscsi_cid);
return ep;
}
/**
* <API key> - find iscsi_cid in destroy list
* @hba: pointer to adapter instance
* @iscsi_cid: iscsi context ID to find
*
*/
struct bnx2i_endpoint *
<API key>(struct bnx2i_hba *hba, u32 iscsi_cid)
{
struct list_head *list;
struct list_head *tmp;
struct bnx2i_endpoint *ep;
read_lock_bh(&hba->ep_rdwr_lock);
list_for_each_safe(list, tmp, &hba->ep_destroy_list) {
ep = (struct bnx2i_endpoint *)list;
if (ep->ep_iscsi_cid == iscsi_cid)
break;
ep = NULL;
}
read_unlock_bh(&hba->ep_rdwr_lock);
if (!ep)
printk(KERN_ERR "l5 cid %d not found\n", iscsi_cid);
return ep;
}
/**
* <API key> - add an entry to ep active list
* @hba: pointer to adapter instance
* @ep: pointer to endpoint (transport indentifier) structure
*
* current active conn queue manager
*/
static void <API key>(struct bnx2i_hba *hba,
struct bnx2i_endpoint *ep)
{
write_lock_bh(&hba->ep_rdwr_lock);
list_add_tail(&ep->link, &hba->ep_active_list);
write_unlock_bh(&hba->ep_rdwr_lock);
}
/**
* <API key> - deletes an entry to ep active list
* @hba: pointer to adapter instance
* @ep: pointer to endpoint (transport indentifier) structure
*
* current active conn queue manager
*/
static void <API key>(struct bnx2i_hba *hba,
struct bnx2i_endpoint *ep)
{
write_lock_bh(&hba->ep_rdwr_lock);
list_del_init(&ep->link);
write_unlock_bh(&hba->ep_rdwr_lock);
}
/**
* <API key> - assigns shost->can_queue param
* @hba: pointer to adapter instance
* @shost: scsi host pointer
*
* Initializes 'can_queue' parameter based on how many outstanding commands
* the device can handle. Each device 5708/5709/57710 has different
* capabilities
*/
static void <API key>(struct bnx2i_hba *hba,
struct Scsi_Host *shost)
{
if (test_bit(BNX2I_NX2_DEV_5708, &hba->cnic_dev_type))
shost->can_queue = <API key>;
else if (test_bit(BNX2I_NX2_DEV_5709, &hba->cnic_dev_type))
shost->can_queue = <API key>;
else if (test_bit(BNX2I_NX2_DEV_57710, &hba->cnic_dev_type))
shost->can_queue = <API key>;
else
shost->can_queue = <API key>;
}
/**
* bnx2i_alloc_hba - allocate and init adapter instance
* @cnic: cnic device pointer
*
* allocate & initialize adapter structure and call other
* support routines to do per adapter initialization
*/
struct bnx2i_hba *bnx2i_alloc_hba(struct cnic_dev *cnic)
{
struct Scsi_Host *shost;
struct bnx2i_hba *hba;
shost = iscsi_host_alloc(&bnx2i_host_template, sizeof(*hba), 0);
if (!shost)
return NULL;
shost->dma_boundary = cnic->pcidev->dma_mask;
shost->transportt = <API key>;
shost->max_id = <API key>;
shost->max_channel = 0;
shost->max_lun = 512;
shost->max_cmd_len = 16;
hba = iscsi_host_priv(shost);
hba->shost = shost;
hba->netdev = cnic->netdev;
/* Get PCI related information and update hba struct members */
hba->pcidev = cnic->pcidev;
pci_dev_get(hba->pcidev);
hba->pci_did = hba->pcidev->device;
hba->pci_vid = hba->pcidev->vendor;
hba->pci_sdid = hba->pcidev->subsystem_device;
hba->pci_svid = hba->pcidev->subsystem_vendor;
hba->pci_func = PCI_FUNC(hba->pcidev->devfn);
hba->pci_devno = PCI_SLOT(hba->pcidev->devfn);
<API key>(hba);
<API key>(hba, shost);
if (test_bit(BNX2I_NX2_DEV_5709, &hba->cnic_dev_type)) {
hba->regview = ioremap_nocache(hba->netdev->base_addr,
BNX2_MQ_CONFIG2);
if (!hba->regview)
goto ioreg_map_err;
} else if (test_bit(BNX2I_NX2_DEV_57710, &hba->cnic_dev_type)) {
hba->regview = ioremap_nocache(hba->netdev->base_addr, 4096);
if (!hba->regview)
goto ioreg_map_err;
}
if (bnx2i_setup_mp_bdt(hba))
goto mp_bdt_mem_err;
INIT_LIST_HEAD(&hba->ep_ofld_list);
INIT_LIST_HEAD(&hba->ep_active_list);
INIT_LIST_HEAD(&hba->ep_destroy_list);
rwlock_init(&hba->ep_rdwr_lock);
hba->mtu_supported = <API key>;
/* different values for 5708/5709/57710 */
hba->max_active_conns = <API key>;
if (<API key>(hba))
goto cid_que_err;
/* SQ/RQ/CQ size can be changed via sysfx interface */
if (test_bit(BNX2I_NX2_DEV_57710, &hba->cnic_dev_type)) {
if (sq_size && sq_size <= <API key>)
hba->max_sqes = sq_size;
else
hba->max_sqes = <API key>;
} else { /* 5706/5708/5709 */
if (sq_size && sq_size <= <API key>)
hba->max_sqes = sq_size;
else
hba->max_sqes = <API key>;
}
hba->max_rqes = rq_size;
hba->max_cqes = hba->max_sqes + rq_size;
if (test_bit(BNX2I_NX2_DEV_57710, &hba->cnic_dev_type)) {
if (hba->max_cqes > <API key>)
hba->max_cqes = <API key>;
} else if (hba->max_cqes > <API key>)
hba->max_cqes = <API key>;
hba->num_ccell = hba->max_sqes / 2;
spin_lock_init(&hba->lock);
mutex_init(&hba->net_dev_lock);
init_waitqueue_head(&hba->eh_wait);
if (test_bit(BNX2I_NX2_DEV_57710, &hba->cnic_dev_type)) {
hba->hba_shutdown_tmo = 30 * HZ;
hba->conn_teardown_tmo = 20 * HZ;
hba-><API key> = 6 * HZ;
} else { /* 5706/5708/5709 */
hba->hba_shutdown_tmo = 20 * HZ;
hba->conn_teardown_tmo = 10 * HZ;
hba-><API key> = 2 * HZ;
}
if (iscsi_host_add(shost, &hba->pcidev->dev))
goto free_dump_mem;
return hba;
free_dump_mem:
<API key>(hba);
cid_que_err:
bnx2i_free_mp_bdt(hba);
mp_bdt_mem_err:
if (hba->regview) {
iounmap(hba->regview);
hba->regview = NULL;
}
ioreg_map_err:
pci_dev_put(hba->pcidev);
scsi_host_put(shost);
return NULL;
}
/**
* bnx2i_free_hba- releases hba structure and resources held by the adapter
* @hba: pointer to adapter instance
*
* free adapter structure and call various cleanup routines.
*/
void bnx2i_free_hba(struct bnx2i_hba *hba)
{
struct Scsi_Host *shost = hba->shost;
iscsi_host_remove(shost);
INIT_LIST_HEAD(&hba->ep_ofld_list);
INIT_LIST_HEAD(&hba->ep_active_list);
INIT_LIST_HEAD(&hba->ep_destroy_list);
pci_dev_put(hba->pcidev);
if (hba->regview) {
iounmap(hba->regview);
hba->regview = NULL;
}
bnx2i_free_mp_bdt(hba);
<API key>(hba);
iscsi_host_free(shost);
}
/**
* <API key> - free DMA resources used for login process
* @hba: pointer to adapter instance
* @bnx2i_conn: iscsi connection pointer
*
* Login related resources, mostly BDT & payload DMA memory is freed
*/
static void <API key>(struct bnx2i_hba *hba,
struct bnx2i_conn *bnx2i_conn)
{
if (bnx2i_conn->gen_pdu.resp_bd_tbl) {
dma_free_coherent(&hba->pcidev->dev, PAGE_SIZE,
bnx2i_conn->gen_pdu.resp_bd_tbl,
bnx2i_conn->gen_pdu.resp_bd_dma);
bnx2i_conn->gen_pdu.resp_bd_tbl = NULL;
}
if (bnx2i_conn->gen_pdu.req_bd_tbl) {
dma_free_coherent(&hba->pcidev->dev, PAGE_SIZE,
bnx2i_conn->gen_pdu.req_bd_tbl,
bnx2i_conn->gen_pdu.req_bd_dma);
bnx2i_conn->gen_pdu.req_bd_tbl = NULL;
}
if (bnx2i_conn->gen_pdu.resp_buf) {
dma_free_coherent(&hba->pcidev->dev,
<API key>,
bnx2i_conn->gen_pdu.resp_buf,
bnx2i_conn->gen_pdu.resp_dma_addr);
bnx2i_conn->gen_pdu.resp_buf = NULL;
}
if (bnx2i_conn->gen_pdu.req_buf) {
dma_free_coherent(&hba->pcidev->dev,
<API key>,
bnx2i_conn->gen_pdu.req_buf,
bnx2i_conn->gen_pdu.req_dma_addr);
bnx2i_conn->gen_pdu.req_buf = NULL;
}
}
/**
* <API key> - alloc DMA resources for login/nop.
* @hba: pointer to adapter instance
* @bnx2i_conn: iscsi connection pointer
*
* Mgmt task DNA resources are allocated in this routine.
*/
static int <API key>(struct bnx2i_hba *hba,
struct bnx2i_conn *bnx2i_conn)
{
/* Allocate memory for login request/response buffers */
bnx2i_conn->gen_pdu.req_buf =
dma_alloc_coherent(&hba->pcidev->dev,
<API key>,
&bnx2i_conn->gen_pdu.req_dma_addr,
GFP_KERNEL);
if (bnx2i_conn->gen_pdu.req_buf == NULL)
goto <API key>;
bnx2i_conn->gen_pdu.req_buf_size = 0;
bnx2i_conn->gen_pdu.req_wr_ptr = bnx2i_conn->gen_pdu.req_buf;
bnx2i_conn->gen_pdu.resp_buf =
dma_alloc_coherent(&hba->pcidev->dev,
<API key>,
&bnx2i_conn->gen_pdu.resp_dma_addr,
GFP_KERNEL);
if (bnx2i_conn->gen_pdu.resp_buf == NULL)
goto <API key>;
bnx2i_conn->gen_pdu.resp_buf_size = <API key>;
bnx2i_conn->gen_pdu.resp_wr_ptr = bnx2i_conn->gen_pdu.resp_buf;
bnx2i_conn->gen_pdu.req_bd_tbl =
dma_alloc_coherent(&hba->pcidev->dev, PAGE_SIZE,
&bnx2i_conn->gen_pdu.req_bd_dma, GFP_KERNEL);
if (bnx2i_conn->gen_pdu.req_bd_tbl == NULL)
goto <API key>;
bnx2i_conn->gen_pdu.resp_bd_tbl =
dma_alloc_coherent(&hba->pcidev->dev, PAGE_SIZE,
&bnx2i_conn->gen_pdu.resp_bd_dma,
GFP_KERNEL);
if (bnx2i_conn->gen_pdu.resp_bd_tbl == NULL)
goto <API key>;
return 0;
<API key>:
dma_free_coherent(&hba->pcidev->dev, PAGE_SIZE,
bnx2i_conn->gen_pdu.req_bd_tbl,
bnx2i_conn->gen_pdu.req_bd_dma);
bnx2i_conn->gen_pdu.req_bd_tbl = NULL;
<API key>:
dma_free_coherent(&hba->pcidev->dev, <API key>,
bnx2i_conn->gen_pdu.resp_buf,
bnx2i_conn->gen_pdu.resp_dma_addr);
bnx2i_conn->gen_pdu.resp_buf = NULL;
<API key>:
dma_free_coherent(&hba->pcidev->dev, <API key>,
bnx2i_conn->gen_pdu.req_buf,
bnx2i_conn->gen_pdu.req_dma_addr);
bnx2i_conn->gen_pdu.req_buf = NULL;
<API key>:
iscsi_conn_printk(KERN_ERR, bnx2i_conn->cls_conn->dd_data,
"login resource alloc failed!!\n");
return -ENOMEM;
}
/**
* <API key> - prepares BD table.
* @bnx2i_conn: iscsi connection pointer
*
* Allocates buffers and BD tables before shipping requests to cnic
* for PDUs prepared by 'iscsid' daemon
*/
static void <API key>(struct bnx2i_conn *bnx2i_conn)
{
struct iscsi_bd *bd_tbl;
bd_tbl = (struct iscsi_bd *) bnx2i_conn->gen_pdu.req_bd_tbl;
bd_tbl->buffer_addr_hi =
(u32) ((u64) bnx2i_conn->gen_pdu.req_dma_addr >> 32);
bd_tbl->buffer_addr_lo = (u32) bnx2i_conn->gen_pdu.req_dma_addr;
bd_tbl->buffer_length = bnx2i_conn->gen_pdu.req_wr_ptr -
bnx2i_conn->gen_pdu.req_buf;
bd_tbl->reserved0 = 0;
bd_tbl->flags = <API key> |
<API key>;
bd_tbl = (struct iscsi_bd *) bnx2i_conn->gen_pdu.resp_bd_tbl;
bd_tbl->buffer_addr_hi = (u64) bnx2i_conn->gen_pdu.resp_dma_addr >> 32;
bd_tbl->buffer_addr_lo = (u32) bnx2i_conn->gen_pdu.resp_dma_addr;
bd_tbl->buffer_length = <API key>;
bd_tbl->reserved0 = 0;
bd_tbl->flags = <API key> |
<API key>;
}
/**
* <API key> - called to send mgmt tasks.
* @task: transport layer task pointer
*
* called to transmit PDUs prepared by the 'iscsid' daemon. iSCSI login,
* Nop-out and Logout requests flow through this path.
*/
static int <API key>(struct iscsi_task *task)
{
struct bnx2i_cmd *cmd = task->dd_data;
struct bnx2i_conn *bnx2i_conn = cmd->conn;
int rc = 0;
char *buf;
int data_len;
<API key>(bnx2i_conn);
switch (task->hdr->opcode & ISCSI_OPCODE_MASK) {
case ISCSI_OP_LOGIN:
<API key>(bnx2i_conn, task);
break;
case ISCSI_OP_NOOP_OUT:
data_len = bnx2i_conn->gen_pdu.req_buf_size;
buf = bnx2i_conn->gen_pdu.req_buf;
if (data_len)
rc = <API key>(bnx2i_conn, task,
buf, data_len, 1);
else
rc = <API key>(bnx2i_conn, task,
NULL, 0, 1);
break;
case ISCSI_OP_LOGOUT:
rc = <API key>(bnx2i_conn, task);
break;
case <API key>:
rc = <API key>(bnx2i_conn, task);
break;
case ISCSI_OP_TEXT:
rc = <API key>(bnx2i_conn, task);
break;
default:
iscsi_conn_printk(KERN_ALERT, bnx2i_conn->cls_conn->dd_data,
"send_gen: unsupported op 0x%x\n",
task->hdr->opcode);
}
return rc;
}
/**
* bnx2i_cpy_scsi_cdb - copies LUN & CDB fields in required format to sq wqe
* @sc: SCSI-ML command pointer
* @cmd: iscsi cmd pointer
*/
static void bnx2i_cpy_scsi_cdb(struct scsi_cmnd *sc, struct bnx2i_cmd *cmd)
{
u32 dword;
int lpcnt;
u8 *srcp;
u32 *dstp;
u32 scsi_lun[2];
int_to_scsilun(sc->device->lun, (struct scsi_lun *) scsi_lun);
cmd->req.lun[0] = be32_to_cpu(scsi_lun[0]);
cmd->req.lun[1] = be32_to_cpu(scsi_lun[1]);
lpcnt = cmd->scsi_cmd->cmd_len / sizeof(dword);
srcp = (u8 *) sc->cmnd;
dstp = (u32 *) cmd->req.cdb;
while (lpcnt
memcpy(&dword, (const void *) srcp, 4);
*dstp = cpu_to_be32(dword);
srcp += 4;
dstp++;
}
if (sc->cmd_len & 0x3) {
dword = (u32) srcp[0] | ((u32) srcp[1] << 8);
*dstp = cpu_to_be32(dword);
}
}
static void bnx2i_cleanup_task(struct iscsi_task *task)
{
struct iscsi_conn *conn = task->conn;
struct bnx2i_conn *bnx2i_conn = conn->dd_data;
struct bnx2i_hba *hba = bnx2i_conn->hba;
/*
* mgmt task or cmd was never sent to us to transmit.
*/
if (!task->sc || task->state == ISCSI_TASK_PENDING)
return;
/*
* need to clean-up task context to claim dma buffers
*/
if (task->state == ISCSI_TASK_ABRT_TMF) {
<API key>(hba, task->dd_data);
spin_unlock_bh(&conn->session->lock);
<API key>(&bnx2i_conn->cmd_cleanup_cmpl,
msecs_to_jiffies(<API key>));
spin_lock_bh(&conn->session->lock);
}
<API key>(task->dd_data);
}
/**
* bnx2i_mtask_xmit - transmit mtask to chip for further processing
* @conn: transport layer conn structure pointer
* @task: transport layer command structure pointer
*/
static int
bnx2i_mtask_xmit(struct iscsi_conn *conn, struct iscsi_task *task)
{
struct bnx2i_conn *bnx2i_conn = conn->dd_data;
struct bnx2i_cmd *cmd = task->dd_data;
memset(bnx2i_conn->gen_pdu.req_buf, 0, <API key>);
<API key>(cmd);
bnx2i_conn->gen_pdu.req_buf_size = task->data_count;
if (task->data_count) {
memcpy(bnx2i_conn->gen_pdu.req_buf, task->data,
task->data_count);
bnx2i_conn->gen_pdu.req_wr_ptr =
bnx2i_conn->gen_pdu.req_buf + task->data_count;
}
cmd->conn = conn->dd_data;
cmd->scsi_cmd = NULL;
return <API key>(task);
}
/**
* bnx2i_task_xmit - transmit iscsi command to chip for further processing
* @task: transport layer command structure pointer
*
* maps SG buffers and send request to chip/firmware in the form of SQ WQE
*/
static int bnx2i_task_xmit(struct iscsi_task *task)
{
struct iscsi_conn *conn = task->conn;
struct iscsi_session *session = conn->session;
struct Scsi_Host *shost = <API key>(session->cls_session);
struct bnx2i_hba *hba = iscsi_host_priv(shost);
struct bnx2i_conn *bnx2i_conn = conn->dd_data;
struct scsi_cmnd *sc = task->sc;
struct bnx2i_cmd *cmd = task->dd_data;
struct iscsi_cmd *hdr = (struct iscsi_cmd *) task->hdr;
if (bnx2i_conn->ep->num_active_cmds + 1 > hba->max_sqes)
return -ENOMEM;
/*
* If there is no scsi_cmnd this must be a mgmt task
*/
if (!sc)
return bnx2i_mtask_xmit(conn, task);
<API key>(cmd);
cmd->req.op_code = ISCSI_OP_SCSI_CMD;
cmd->conn = bnx2i_conn;
cmd->scsi_cmd = sc;
cmd->req.<API key> = scsi_bufflen(sc);
cmd->req.cmd_sn = be32_to_cpu(hdr->cmdsn);
<API key>(cmd);
bnx2i_cpy_scsi_cdb(sc, cmd);
cmd->req.op_attr = ISCSI_ATTR_SIMPLE;
if (sc->sc_data_direction == DMA_TO_DEVICE) {
cmd->req.op_attr |= <API key>;
cmd->req.itt = task->itt |
(<API key> << <API key>);
<API key>(task);
} else {
if (scsi_bufflen(sc))
cmd->req.op_attr |= <API key>;
cmd->req.itt = task->itt |
(<API key> << <API key>);
}
cmd->req.num_bds = cmd->io_tbl.bd_valid;
if (!cmd->io_tbl.bd_valid) {
cmd->req.bd_list_addr_lo = (u32) hba->mp_bd_dma;
cmd->req.bd_list_addr_hi = (u32) ((u64) hba->mp_bd_dma >> 32);
cmd->req.num_bds = 1;
}
<API key>(bnx2i_conn, cmd);
return 0;
}
/**
* <API key> - create a new iscsi session
* @cmds_max: max commands supported
* @qdepth: scsi queue depth to support
* @initial_cmdsn: initial iscsi CMDSN to be used for this session
*
* Creates a new iSCSI session instance on given device.
*/
static struct iscsi_cls_session *
<API key>(struct iscsi_endpoint *ep,
uint16_t cmds_max, uint16_t qdepth,
uint32_t initial_cmdsn)
{
struct Scsi_Host *shost;
struct iscsi_cls_session *cls_session;
struct bnx2i_hba *hba;
struct bnx2i_endpoint *bnx2i_ep;
if (!ep) {
printk(KERN_ERR "bnx2i: missing ep.\n");
return NULL;
}
bnx2i_ep = ep->dd_data;
shost = bnx2i_ep->hba->shost;
hba = iscsi_host_priv(shost);
if (bnx2i_adapter_ready(hba))
return NULL;
/*
* user can override hw limit as long as it is within
* the min/max.
*/
if (cmds_max > hba->max_sqes)
cmds_max = hba->max_sqes;
else if (cmds_max < BNX2I_SQ_WQES_MIN)
cmds_max = BNX2I_SQ_WQES_MIN;
cls_session = iscsi_session_setup(&<API key>, shost,
cmds_max, 0, sizeof(struct bnx2i_cmd),
initial_cmdsn, ISCSI_MAX_TARGET);
if (!cls_session)
return NULL;
if (<API key>(hba, cls_session->dd_data))
goto session_teardown;
return cls_session;
session_teardown:
<API key>(cls_session);
return NULL;
}
/**
* <API key> - destroys iscsi session
* @cls_session: pointer to iscsi cls session
*
* Destroys previously created iSCSI session instance and releases
* all resources held by it
*/
static void <API key>(struct iscsi_cls_session *cls_session)
{
struct iscsi_session *session = cls_session->dd_data;
struct Scsi_Host *shost = <API key>(cls_session);
struct bnx2i_hba *hba = iscsi_host_priv(shost);
<API key>(hba, session);
<API key>(cls_session);
}
/**
* bnx2i_conn_create - create iscsi connection instance
* @cls_session: pointer to iscsi cls session
* @cid: iscsi cid as per rfc (not NX2's CID terminology)
*
* Creates a new iSCSI connection instance for a given session
*/
static struct iscsi_cls_conn *
bnx2i_conn_create(struct iscsi_cls_session *cls_session, uint32_t cid)
{
struct Scsi_Host *shost = <API key>(cls_session);
struct bnx2i_hba *hba = iscsi_host_priv(shost);
struct bnx2i_conn *bnx2i_conn;
struct iscsi_cls_conn *cls_conn;
struct iscsi_conn *conn;
cls_conn = iscsi_conn_setup(cls_session, sizeof(*bnx2i_conn),
cid);
if (!cls_conn)
return NULL;
conn = cls_conn->dd_data;
bnx2i_conn = conn->dd_data;
bnx2i_conn->cls_conn = cls_conn;
bnx2i_conn->hba = hba;
/* 'ep' ptr will be assigned in bind() call */
bnx2i_conn->ep = NULL;
init_completion(&bnx2i_conn->cmd_cleanup_cmpl);
if (<API key>(hba, bnx2i_conn)) {
iscsi_conn_printk(KERN_ALERT, conn,
"conn_new: login resc alloc failed!!\n");
goto free_conn;
}
return cls_conn;
free_conn:
iscsi_conn_teardown(cls_conn);
return NULL;
}
/**
* bnx2i_conn_bind - binds iscsi sess, conn and ep objects together
* @cls_session: pointer to iscsi cls session
* @cls_conn: pointer to iscsi cls conn
* @transport_fd: 64-bit EP handle
* @is_leading: leading connection on this session?
*
* Binds together iSCSI session instance, iSCSI connection instance
* and the TCP connection. This routine returns error code if
* TCP connection does not belong on the device iSCSI sess/conn
* is bound
*/
static int bnx2i_conn_bind(struct iscsi_cls_session *cls_session,
struct iscsi_cls_conn *cls_conn,
uint64_t transport_fd, int is_leading)
{
struct iscsi_conn *conn = cls_conn->dd_data;
struct bnx2i_conn *bnx2i_conn = conn->dd_data;
struct Scsi_Host *shost = <API key>(cls_session);
struct bnx2i_hba *hba = iscsi_host_priv(shost);
struct bnx2i_endpoint *bnx2i_ep;
struct iscsi_endpoint *ep;
int ret_code;
ep = <API key>(transport_fd);
if (!ep)
return -EINVAL;
/*
* Forcefully terminate all in progress connection recovery at the
* earliest, either in bind(), send_pdu(LOGIN), or conn_start()
*/
if (bnx2i_adapter_ready(hba))
return -EIO;
bnx2i_ep = ep->dd_data;
if ((bnx2i_ep->state == <API key>) ||
(bnx2i_ep->state == <API key>))
/* Peer disconnect via' FIN or RST */
return -EINVAL;
if (iscsi_conn_bind(cls_session, cls_conn, is_leading))
return -EINVAL;
if (bnx2i_ep->hba != hba) {
/* Error - TCP connection does not belong to this device
*/
iscsi_conn_printk(KERN_ALERT, cls_conn->dd_data,
"conn bind, ep=0x%p (%s) does not",
bnx2i_ep, bnx2i_ep->hba->netdev->name);
iscsi_conn_printk(KERN_ALERT, cls_conn->dd_data,
"belong to hba (%s)\n",
hba->netdev->name);
return -EEXIST;
}
bnx2i_ep->conn = bnx2i_conn;
bnx2i_conn->ep = bnx2i_ep;
bnx2i_conn->iscsi_conn_cid = bnx2i_ep->ep_iscsi_cid;
bnx2i_conn->fw_cid = bnx2i_ep->ep_cid;
ret_code = <API key>(hba, bnx2i_conn,
bnx2i_ep->ep_iscsi_cid);
/* 5706/5708/5709 FW takes RQ as full when initiated, but for 57710
* driver needs to explicitly replenish RQ index during setup.
*/
if (test_bit(BNX2I_NX2_DEV_57710, &bnx2i_ep->hba->cnic_dev_type))
bnx2i_put_rq_buf(bnx2i_conn, 0);
<API key>(bnx2i_conn->ep, CNIC_ARM_CQE);
return ret_code;
}
/**
* bnx2i_conn_destroy - destroy iscsi connection instance & release resources
* @cls_conn: pointer to iscsi cls conn
*
* Destroy an iSCSI connection instance and release memory resources held by
* this connection
*/
static void bnx2i_conn_destroy(struct iscsi_cls_conn *cls_conn)
{
struct iscsi_conn *conn = cls_conn->dd_data;
struct bnx2i_conn *bnx2i_conn = conn->dd_data;
struct Scsi_Host *shost;
struct bnx2i_hba *hba;
shost = <API key>(<API key>(cls_conn));
hba = iscsi_host_priv(shost);
<API key>(hba, bnx2i_conn);
iscsi_conn_teardown(cls_conn);
}
/**
* bnx2i_ep_get_param - return iscsi ep parameter to caller
* @ep: pointer to iscsi endpoint
* @param: parameter type identifier
* @buf: buffer pointer
*
* returns iSCSI ep parameters
*/
static int bnx2i_ep_get_param(struct iscsi_endpoint *ep,
enum iscsi_param param, char *buf)
{
struct bnx2i_endpoint *bnx2i_ep = ep->dd_data;
struct bnx2i_hba *hba = bnx2i_ep->hba;
int len = -ENOTCONN;
if (!hba)
return -ENOTCONN;
switch (param) {
case <API key>:
mutex_lock(&hba->net_dev_lock);
if (bnx2i_ep->cm_sk)
len = sprintf(buf, "%hu\n", bnx2i_ep->cm_sk->dst_port);
mutex_unlock(&hba->net_dev_lock);
break;
case <API key>:
mutex_lock(&hba->net_dev_lock);
if (bnx2i_ep->cm_sk)
len = sprintf(buf, "%pI4\n", &bnx2i_ep->cm_sk->dst_ip);
mutex_unlock(&hba->net_dev_lock);
break;
default:
return -ENOSYS;
}
return len;
}
/**
* <API key> - returns host (adapter) related parameters
* @shost: scsi host pointer
* @param: parameter type identifier
* @buf: buffer pointer
*/
static int <API key>(struct Scsi_Host *shost,
enum iscsi_host_param param, char *buf)
{
struct bnx2i_hba *hba = iscsi_host_priv(shost);
int len = 0;
switch (param) {
case <API key>:
len = sysfs_format_mac(buf, hba->cnic->mac_addr, 6);
break;
case <API key>:
len = sprintf(buf, "%s\n", hba->netdev->name);
break;
case <API key>: {
struct list_head *active_list = &hba->ep_active_list;
read_lock_bh(&hba->ep_rdwr_lock);
if (!list_empty(&hba->ep_active_list)) {
struct bnx2i_endpoint *bnx2i_ep;
struct cnic_sock *csk;
bnx2i_ep = list_first_entry(active_list,
struct bnx2i_endpoint,
link);
csk = bnx2i_ep->cm_sk;
if (test_bit(SK_F_IPV6, &csk->flags))
len = sprintf(buf, "%pI6\n", csk->src_ip);
else
len = sprintf(buf, "%pI4\n", csk->src_ip);
}
read_unlock_bh(&hba->ep_rdwr_lock);
break;
}
default:
return <API key>(shost, param, buf);
}
return len;
}
/**
* bnx2i_conn_start - completes iscsi connection migration to FFP
* @cls_conn: pointer to iscsi cls conn
*
* last call in FFP migration to handover iscsi conn to the driver
*/
static int bnx2i_conn_start(struct iscsi_cls_conn *cls_conn)
{
struct iscsi_conn *conn = cls_conn->dd_data;
struct bnx2i_conn *bnx2i_conn = conn->dd_data;
bnx2i_conn->ep->state = <API key>;
<API key>(conn);
/*
* this should normally not sleep for a long time so it should
* not disrupt the caller.
*/
bnx2i_conn->ep->ofld_timer.expires = 1 * HZ + jiffies;
bnx2i_conn->ep->ofld_timer.function = bnx2i_ep_ofld_timer;
bnx2i_conn->ep->ofld_timer.data = (unsigned long) bnx2i_conn->ep;
add_timer(&bnx2i_conn->ep->ofld_timer);
/* update iSCSI context for this conn, wait for CNIC to complete */
<API key>(bnx2i_conn->ep->ofld_wait,
bnx2i_conn->ep->state != <API key>);
if (signal_pending(current))
flush_signals(current);
del_timer_sync(&bnx2i_conn->ep->ofld_timer);
iscsi_conn_start(cls_conn);
return 0;
}
/**
* <API key> - returns iSCSI stats
* @cls_conn: pointer to iscsi cls conn
* @stats: pointer to iscsi statistic struct
*/
static void <API key>(struct iscsi_cls_conn *cls_conn,
struct iscsi_stats *stats)
{
struct iscsi_conn *conn = cls_conn->dd_data;
stats->txdata_octets = conn->txdata_octets;
stats->rxdata_octets = conn->rxdata_octets;
stats->scsicmd_pdus = conn->scsicmd_pdus_cnt;
stats->dataout_pdus = conn->dataout_pdus_cnt;
stats->scsirsp_pdus = conn->scsirsp_pdus_cnt;
stats->datain_pdus = conn->datain_pdus_cnt;
stats->r2t_pdus = conn->r2t_pdus_cnt;
stats->tmfcmd_pdus = conn->tmfcmd_pdus_cnt;
stats->tmfrsp_pdus = conn->tmfrsp_pdus_cnt;
stats->custom_length = 3;
strcpy(stats->custom[2].desc, "eh_abort_cnt");
stats->custom[2].value = conn->eh_abort_cnt;
stats->digest_err = 0;
stats->timeout_err = 0;
stats->custom_length = 0;
}
/**
* bnx2i_check_route - checks if target IP route belongs to one of NX2 devices
* @dst_addr: target IP address
*
* check if route resolves to BNX2 device
*/
static struct bnx2i_hba *bnx2i_check_route(struct sockaddr *dst_addr)
{
struct sockaddr_in *desti = (struct sockaddr_in *) dst_addr;
struct bnx2i_hba *hba;
struct cnic_dev *cnic = NULL;
hba = <API key>();
if (hba && hba->cnic)
cnic = hba->cnic->cm_select_dev(desti, CNIC_ULP_ISCSI);
if (!cnic) {
printk(KERN_ALERT "bnx2i: no route,"
"can't connect using cnic\n");
goto no_nx2_route;
}
hba = <API key>(cnic);
if (!hba)
goto no_nx2_route;
if (bnx2i_adapter_ready(hba)) {
printk(KERN_ALERT "bnx2i: check route, hba not found\n");
goto no_nx2_route;
}
if (hba->netdev->mtu > hba->mtu_supported) {
printk(KERN_ALERT "bnx2i: %s network i/f mtu is set to %d\n",
hba->netdev->name, hba->netdev->mtu);
printk(KERN_ALERT "bnx2i: iSCSI HBA can support mtu of %d\n",
hba->mtu_supported);
goto no_nx2_route;
}
return hba;
no_nx2_route:
return NULL;
}
/**
* <API key> - tear down iscsi/tcp connection and free resources
* @hba: pointer to adapter instance
* @ep: endpoint (transport indentifier) structure
*
* destroys cm_sock structure and on chip iscsi context
*/
static int <API key>(struct bnx2i_hba *hba,
struct bnx2i_endpoint *ep)
{
if (test_bit(<API key>, &hba->reg_with_cnic) && ep->cm_sk)
hba->cnic->cm_destroy(ep->cm_sk);
if (test_bit(BNX2I_NX2_DEV_57710, &hba->cnic_dev_type) &&
ep->state == <API key>) {
if (ep->conn && ep->conn->cls_conn &&
ep->conn->cls_conn->dd_data) {
struct iscsi_conn *conn = ep->conn->cls_conn->dd_data;
/* Must suspend all rx queue activity for this ep */
set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
}
/* CONN_DISCONNECT timeout may or may not be an issue depending
* on what transcribed in TCP layer, different targets behave
* differently
*/
printk(KERN_ALERT "bnx2i (%s): - WARN - CONN_DISCON timed out, "
"please submit GRC Dump, NW/PCIe trace, "
"driver msgs to developers for analysis\n",
hba->netdev->name);
}
ep->state = <API key>;
init_timer(&ep->ofld_timer);
ep->ofld_timer.expires = hba-><API key> + jiffies;
ep->ofld_timer.function = bnx2i_ep_ofld_timer;
ep->ofld_timer.data = (unsigned long) ep;
add_timer(&ep->ofld_timer);
<API key>(hba, ep);
/* destroy iSCSI context, wait for it to complete */
if (<API key>(hba, ep))
ep->state = <API key>;
<API key>(ep->ofld_wait,
(ep->state != <API key>));
if (signal_pending(current))
flush_signals(current);
del_timer_sync(&ep->ofld_timer);
<API key>(hba, ep);
if (ep->state != <API key>)
/* should never happen */
printk(KERN_ALERT "bnx2i - conn destroy failed\n");
return 0;
}
/**
* bnx2i_ep_connect - establish TCP connection to target portal
* @shost: scsi host
* @dst_addr: target IP address
* @non_blocking: blocking or non-blocking call
*
* this routine initiates the TCP/IP connection by invoking Option-2 i/f
* with l5_core and the CNIC. This is a multi-step process of resolving
* route to target, create a iscsi connection context, handshaking with
* CNIC module to create/initialize the socket struct and finally
* sending down option-2 request to complete TCP 3-way handshake
*/
static struct iscsi_endpoint *bnx2i_ep_connect(struct Scsi_Host *shost,
struct sockaddr *dst_addr,
int non_blocking)
{
u32 iscsi_cid = BNX2I_CID_RESERVED;
struct sockaddr_in *desti = (struct sockaddr_in *) dst_addr;
struct sockaddr_in6 *desti6;
struct bnx2i_endpoint *bnx2i_ep;
struct bnx2i_hba *hba;
struct cnic_dev *cnic;
struct cnic_sockaddr saddr;
struct iscsi_endpoint *ep;
int rc = 0;
if (shost) {
/* driver is given scsi host to work with */
hba = iscsi_host_priv(shost);
} else
/*
* check if the given destination can be reached through
* a iscsi capable NetXtreme2 device
*/
hba = bnx2i_check_route(dst_addr);
if (!hba) {
rc = -EINVAL;
goto nohba;
}
mutex_lock(&hba->net_dev_lock);
if (bnx2i_adapter_ready(hba) || !hba->cid_que.cid_free_cnt) {
rc = -EPERM;
goto check_busy;
}
cnic = hba->cnic;
ep = bnx2i_alloc_ep(hba);
if (!ep) {
rc = -ENOMEM;
goto check_busy;
}
bnx2i_ep = ep->dd_data;
bnx2i_ep->num_active_cmds = 0;
iscsi_cid = <API key>(hba);
if (iscsi_cid == -1) {
printk(KERN_ALERT "bnx2i (%s): alloc_ep - unable to allocate "
"iscsi cid\n", hba->netdev->name);
rc = -ENOMEM;
bnx2i_free_ep(ep);
goto check_busy;
}
bnx2i_ep->hba_age = hba->age;
rc = bnx2i_alloc_qp_resc(hba, bnx2i_ep);
if (rc != 0) {
printk(KERN_ALERT "bnx2i (%s): ep_conn - alloc QP resc error"
"\n", hba->netdev->name);
rc = -ENOMEM;
goto qp_resc_err;
}
bnx2i_ep->ep_iscsi_cid = (u16)iscsi_cid;
bnx2i_ep->state = EP_STATE_OFLD_START;
<API key>(hba, bnx2i_ep);
init_timer(&bnx2i_ep->ofld_timer);
bnx2i_ep->ofld_timer.expires = 2 * HZ + jiffies;
bnx2i_ep->ofld_timer.function = bnx2i_ep_ofld_timer;
bnx2i_ep->ofld_timer.data = (unsigned long) bnx2i_ep;
add_timer(&bnx2i_ep->ofld_timer);
if (<API key>(hba, bnx2i_ep)) {
if (bnx2i_ep->state == <API key>) {
printk(KERN_ALERT "bnx2i (%s): iscsi cid %d is busy\n",
hba->netdev->name, bnx2i_ep->ep_iscsi_cid);
rc = -EBUSY;
} else
rc = -ENOSPC;
printk(KERN_ALERT "bnx2i (%s): unable to send conn offld kwqe"
"\n", hba->netdev->name);
<API key>(hba, bnx2i_ep);
goto conn_failed;
}
/* Wait for CNIC hardware to setup conn context and return 'cid' */
<API key>(bnx2i_ep->ofld_wait,
bnx2i_ep->state != EP_STATE_OFLD_START);
if (signal_pending(current))
flush_signals(current);
del_timer_sync(&bnx2i_ep->ofld_timer);
<API key>(hba, bnx2i_ep);
if (bnx2i_ep->state != EP_STATE_OFLD_COMPL) {
if (bnx2i_ep->state == <API key>) {
printk(KERN_ALERT "bnx2i (%s): iscsi cid %d is busy\n",
hba->netdev->name, bnx2i_ep->ep_iscsi_cid);
rc = -EBUSY;
} else
rc = -ENOSPC;
goto conn_failed;
}
rc = cnic->cm_create(cnic, CNIC_ULP_ISCSI, bnx2i_ep->ep_cid,
iscsi_cid, &bnx2i_ep->cm_sk, bnx2i_ep);
if (rc) {
rc = -EINVAL;
/* Need to terminate and cleanup the connection */
goto release_ep;
}
bnx2i_ep->cm_sk->rcv_buf = 256 * 1024;
bnx2i_ep->cm_sk->snd_buf = 256 * 1024;
clear_bit(SK_TCP_TIMESTAMP, &bnx2i_ep->cm_sk->tcp_flags);
memset(&saddr, 0, sizeof(saddr));
if (dst_addr->sa_family == AF_INET) {
desti = (struct sockaddr_in *) dst_addr;
saddr.remote.v4 = *desti;
saddr.local.v4.sin_family = desti->sin_family;
} else if (dst_addr->sa_family == AF_INET6) {
desti6 = (struct sockaddr_in6 *) dst_addr;
saddr.remote.v6 = *desti6;
saddr.local.v6.sin6_family = desti6->sin6_family;
}
bnx2i_ep->timestamp = jiffies;
bnx2i_ep->state = <API key>;
if (!test_bit(<API key>, &hba->reg_with_cnic)) {
rc = -EINVAL;
goto conn_failed;
} else
rc = cnic->cm_connect(bnx2i_ep->cm_sk, &saddr);
if (rc)
goto release_ep;
<API key>(hba, bnx2i_ep);
if (<API key>(bnx2i_ep))
goto del_active_ep;
mutex_unlock(&hba->net_dev_lock);
return ep;
del_active_ep:
<API key>(hba, bnx2i_ep);
release_ep:
if (<API key>(hba, bnx2i_ep)) {
mutex_unlock(&hba->net_dev_lock);
return ERR_PTR(rc);
}
conn_failed:
bnx2i_free_qp_resc(hba, bnx2i_ep);
qp_resc_err:
bnx2i_free_ep(ep);
check_busy:
mutex_unlock(&hba->net_dev_lock);
nohba:
return ERR_PTR(rc);
}
/**
* bnx2i_ep_poll - polls for TCP connection establishement
* @ep: TCP connection (endpoint) handle
* @timeout_ms: timeout value in milli secs
*
* polls for TCP connect request to complete
*/
static int bnx2i_ep_poll(struct iscsi_endpoint *ep, int timeout_ms)
{
struct bnx2i_endpoint *bnx2i_ep;
int rc = 0;
bnx2i_ep = ep->dd_data;
if ((bnx2i_ep->state == EP_STATE_IDLE) ||
(bnx2i_ep->state == <API key>) ||
(bnx2i_ep->state == <API key>))
return -1;
if (bnx2i_ep->state == <API key>)
return 1;
rc = <API key>(bnx2i_ep->ofld_wait,
((bnx2i_ep->state ==
<API key>) ||
(bnx2i_ep->state ==
<API key>) ||
(bnx2i_ep->state ==
<API key>)),
msecs_to_jiffies(timeout_ms));
if (bnx2i_ep->state == <API key>)
rc = -1;
if (rc > 0)
return 1;
else if (!rc)
return 0; /* timeout */
else
return rc;
}
/**
* <API key> - check EP state transition
* @ep: endpoint pointer
*
* check if underlying TCP connection is active
*/
static int <API key>(struct bnx2i_endpoint *bnx2i_ep)
{
int ret;
int cnic_dev_10g = 0;
if (test_bit(BNX2I_NX2_DEV_57710, &bnx2i_ep->hba->cnic_dev_type))
cnic_dev_10g = 1;
switch (bnx2i_ep->state) {
case <API key>:
case <API key>:
case <API key>:
ret = 0;
break;
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
ret = 1;
break;
case <API key>:
if (cnic_dev_10g)
ret = 0;
else
ret = 1;
break;
default:
ret = 0;
}
return ret;
}
/*
* <API key> - executes TCP connection teardown process in the hw
* @ep: TCP connection (bnx2i endpoint) handle
*
* executes TCP connection teardown process
*/
int <API key>(struct bnx2i_endpoint *bnx2i_ep)
{
struct bnx2i_hba *hba = bnx2i_ep->hba;
struct cnic_dev *cnic;
struct iscsi_session *session = NULL;
struct iscsi_conn *conn = NULL;
int ret = 0;
int close = 0;
int close_ret = 0;
if (!hba)
return 0;
cnic = hba->cnic;
if (!cnic)
return 0;
if (bnx2i_ep->state == EP_STATE_IDLE ||
bnx2i_ep->state == <API key>)
return 0;
if (!<API key>(bnx2i_ep))
goto destroy_conn;
if (bnx2i_ep->conn) {
conn = bnx2i_ep->conn->cls_conn->dd_data;
session = conn->session;
}
init_timer(&bnx2i_ep->ofld_timer);
bnx2i_ep->ofld_timer.expires = hba->conn_teardown_tmo + jiffies;
bnx2i_ep->ofld_timer.function = bnx2i_ep_ofld_timer;
bnx2i_ep->ofld_timer.data = (unsigned long) bnx2i_ep;
add_timer(&bnx2i_ep->ofld_timer);
if (!test_bit(<API key>, &hba->reg_with_cnic))
goto out;
if (session) {
spin_lock_bh(&session->lock);
if (bnx2i_ep->state != <API key>) {
if (session->state == <API key>) {
if (bnx2i_ep->state == <API key>) {
/* Logout sent, but no resp */
printk(KERN_ALERT "bnx2i (%s): WARNING"
" logout response was not "
"received!\n",
bnx2i_ep->hba->netdev->name);
} else if (bnx2i_ep->state ==
<API key>)
close = 1;
}
} else
close = 1;
spin_unlock_bh(&session->lock);
}
bnx2i_ep->state = <API key>;
if (close)
close_ret = cnic->cm_close(bnx2i_ep->cm_sk);
else
close_ret = cnic->cm_abort(bnx2i_ep->cm_sk);
if (close_ret)
printk(KERN_ALERT "bnx2i (%s): close/abort(%d) returned %d\n",
bnx2i_ep->hba->netdev->name, close, close_ret);
else
/* wait for option-2 conn teardown */
<API key>(bnx2i_ep->ofld_wait,
bnx2i_ep->state != <API key>);
if (signal_pending(current))
flush_signals(current);
del_timer_sync(&bnx2i_ep->ofld_timer);
destroy_conn:
<API key>(hba, bnx2i_ep);
if (<API key>(hba, bnx2i_ep))
return -EINVAL;
out:
bnx2i_ep->state = EP_STATE_IDLE;
return ret;
}
/**
* bnx2i_ep_disconnect - executes TCP connection teardown process
* @ep: TCP connection (iscsi endpoint) handle
*
* executes TCP connection teardown process
*/
static void bnx2i_ep_disconnect(struct iscsi_endpoint *ep)
{
struct bnx2i_endpoint *bnx2i_ep;
struct bnx2i_conn *bnx2i_conn = NULL;
struct iscsi_conn *conn = NULL;
struct bnx2i_hba *hba;
bnx2i_ep = ep->dd_data;
/* driver should not attempt connection cleanup until TCP_CONNECT
* completes either successfully or fails. Timeout is 9-secs, so
* wait for it to complete
*/
while ((bnx2i_ep->state == <API key>) &&
!time_after(jiffies, bnx2i_ep->timestamp + (12 * HZ)))
msleep(250);
if (bnx2i_ep->conn) {
bnx2i_conn = bnx2i_ep->conn;
conn = bnx2i_conn->cls_conn->dd_data;
iscsi_suspend_queue(conn);
}
hba = bnx2i_ep->hba;
mutex_lock(&hba->net_dev_lock);
if (bnx2i_ep->state == <API key>)
goto out;
if (bnx2i_ep->state == EP_STATE_IDLE)
goto free_resc;
if (!test_bit(ADAPTER_STATE_UP, &hba->adapter_state) ||
(bnx2i_ep->hba_age != hba->age)) {
<API key>(hba, bnx2i_ep);
goto free_resc;
}
/* Do all chip cleanup here */
if (<API key>(bnx2i_ep)) {
mutex_unlock(&hba->net_dev_lock);
return;
}
free_resc:
bnx2i_free_qp_resc(hba, bnx2i_ep);
if (bnx2i_conn)
bnx2i_conn->ep = NULL;
bnx2i_free_ep(ep);
out:
mutex_unlock(&hba->net_dev_lock);
<API key>(&hba->eh_wait);
}
/**
* bnx2i_nl_set_path - <API key> user message handler
* @buf: pointer to buffer containing iscsi path message
*
*/
static int bnx2i_nl_set_path(struct Scsi_Host *shost, struct iscsi_path *params)
{
struct bnx2i_hba *hba = iscsi_host_priv(shost);
char *buf = (char *) params;
u16 len = sizeof(*params);
/* handled by cnic driver */
hba->cnic->iscsi_nl_msg_recv(hba->cnic, <API key>, buf,
len);
return 0;
}
static mode_t <API key>(int param_type, int param)
{
switch (param_type) {
case ISCSI_HOST_PARAM:
switch (param) {
case <API key>:
case <API key>:
case <API key>:
return S_IRUGO;
default:
return 0;
}
case ISCSI_PARAM:
switch (param) {
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case ISCSI_PARAM_MAX_R2T:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case ISCSI_PARAM_ERL:
case <API key>:
case ISCSI_PARAM_TPGT:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
return S_IRUGO;
default:
return 0;
}
}
return 0;
}
/*
* 'Scsi_Host_Template' structure and 'iscsi_tranport' structure template
* used while registering with the scsi host and iSCSI transport module.
*/
static struct scsi_host_template bnx2i_host_template = {
.module = THIS_MODULE,
.name = "Broadcom Offload iSCSI Initiator",
.proc_name = "bnx2i",
.queuecommand = iscsi_queuecommand,
.eh_abort_handler = iscsi_eh_abort,
.<API key> = <API key>,
.<API key> = <API key>,
.change_queue_depth = <API key>,
.can_queue = 1024,
.max_sectors = 127,
.cmd_per_lun = 24,
.this_id = -1,
.use_clustering = ENABLE_CLUSTERING,
.sg_tablesize = <API key>,
.shost_attrs = <API key>,
};
struct iscsi_transport <API key> = {
.owner = THIS_MODULE,
.name = "bnx2i",
.caps = CAP_RECOVERY_L0 | CAP_HDRDGST |
CAP_MULTI_R2T | CAP_DATADGST |
<API key> |
CAP_TEXT_NEGO,
.create_session = <API key>,
.destroy_session = <API key>,
.create_conn = bnx2i_conn_create,
.bind_conn = bnx2i_conn_bind,
.destroy_conn = bnx2i_conn_destroy,
.attr_is_visible = <API key>,
.set_param = iscsi_set_param,
.get_conn_param = <API key>,
.get_session_param = <API key>,
.get_host_param = <API key>,
.start_conn = bnx2i_conn_start,
.stop_conn = iscsi_conn_stop,
.send_pdu = iscsi_conn_send_pdu,
.xmit_task = bnx2i_task_xmit,
.get_stats = <API key>,
/* TCP connect - disconnect - option-2 interface calls */
.get_ep_param = bnx2i_ep_get_param,
.ep_connect = bnx2i_ep_connect,
.ep_poll = bnx2i_ep_poll,
.ep_disconnect = bnx2i_ep_disconnect,
.set_path = bnx2i_nl_set_path,
/* Error recovery timeout call */
.<API key> = <API key>,
.cleanup_task = bnx2i_cleanup_task,
}; |
// AUTOMATICALLY GENERATED -- DO NOT EDIT! -*- c++ -*-
#include "drop_multi2.h"
#include "drop_multi2_i.h"
#line 16 "dropsection-ext.cpp"
int
Gen_foo::<API key>()
{
// just do it
} |
#ifndef CCLIPBOARD_H
#define CCLIPBOARD_H
#include "IClipboard.h"
//! Memory buffer clipboard
/*!
This class implements a clipboard that stores data in memory.
*/
class CClipboard : public IClipboard {
public:
CClipboard();
virtual ~CClipboard();
//! @name manipulators
//! Unmarshall clipboard data
/*!
Extract marshalled clipboard data and store it in this clipboard.
Sets the clipboard time to \c time.
*/
void unmarshall(const CString& data, Time time);
//! @name accessors
//! Marshall clipboard data
/*!
Merge this clipboard's data into a single buffer that can be later
unmarshalled to restore the clipboard and return the buffer.
*/
CString marshall() const;
// IClipboard overrides
virtual bool empty();
virtual void add(EFormat, const CString& data);
virtual bool open(Time) const;
virtual void close() const;
virtual Time getTime() const;
virtual bool has(EFormat) const;
virtual CString get(EFormat) const;
private:
mutable bool m_open;
mutable Time m_time;
bool m_owner;
Time m_timeOwned;
bool m_added[kNumFormats];
CString m_data[kNumFormats];
};
#endif |
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/mbcache.h>
#include <linux/quotaops.h>
#include <linux/rwsem.h>
#include "ext4_jbd2.h"
#include "ext4.h"
#include "xattr.h"
#include "acl.h"
#define BHDR(bh) ((struct ext4_xattr_header *)((bh)->b_data))
#define ENTRY(ptr) ((struct ext4_xattr_entry *)(ptr))
#define BFIRST(bh) ENTRY(BHDR(bh)+1)
#define IS_LAST_ENTRY(entry) (*(__u32 *)(entry) == 0)
#ifdef EXT4_XATTR_DEBUG
# define ea_idebug(inode, f...) do { \
printk(KERN_DEBUG "inode %s:%lu: ", \
inode->i_sb->s_id, inode->i_ino); \
printk(f); \
printk("\n"); \
} while (0)
# define ea_bdebug(bh, f...) do { \
char b[BDEVNAME_SIZE]; \
printk(KERN_DEBUG "block %s:%lu: ", \
bdevname(bh->b_bdev, b), \
(unsigned long) bh->b_blocknr); \
printk(f); \
printk("\n"); \
} while (0)
#else
# define ea_idebug(inode, fmt, ...) no_printk(fmt, ##__VA_ARGS__)
# define ea_bdebug(bh, fmt, ...) no_printk(fmt, ##__VA_ARGS__)
#endif
static void <API key>(struct buffer_head *);
static struct buffer_head *<API key>(struct inode *,
struct ext4_xattr_header *,
struct mb_cache_entry **);
static void ext4_xattr_rehash(struct ext4_xattr_header *,
struct ext4_xattr_entry *);
static int ext4_xattr_list(struct dentry *dentry, char *buffer,
size_t buffer_size);
static struct mb_cache *ext4_xattr_cache;
static const struct xattr_handler *<API key>[] = {
[<API key>] = &<API key>,
#ifdef <API key>
[<API key>] = &<API key>,
[<API key>] = &<API key>,
#endif
[<API key>] = &<API key>,
#ifdef <API key>
[<API key>] = &<API key>,
#endif
};
const struct xattr_handler *ext4_xattr_handlers[] = {
&<API key>,
&<API key>,
#ifdef <API key>
&<API key>,
&<API key>,
#endif
#ifdef <API key>
&<API key>,
#endif
NULL
};
static inline const struct xattr_handler *
ext4_xattr_handler(int name_index)
{
const struct xattr_handler *handler = NULL;
if (name_index > 0 && name_index < ARRAY_SIZE(<API key>))
handler = <API key>[name_index];
return handler;
}
/*
* Inode operation listxattr()
*
* dentry->d_inode->i_mutex: don't care
*/
ssize_t
ext4_listxattr(struct dentry *dentry, char *buffer, size_t size)
{
return ext4_xattr_list(dentry, buffer, size);
}
static int
<API key>(struct ext4_xattr_entry *entry, void *end,
void *value_start)
{
struct ext4_xattr_entry *e = entry;
while (!IS_LAST_ENTRY(e)) {
struct ext4_xattr_entry *next = EXT4_XATTR_NEXT(e);
if ((void *)next >= end)
return -EIO;
e = next;
}
while (!IS_LAST_ENTRY(entry)) {
if (entry->e_value_size != 0 &&
(value_start + le16_to_cpu(entry->e_value_offs) <
(void *)e + sizeof(__u32) ||
value_start + le16_to_cpu(entry->e_value_offs) +
le32_to_cpu(entry->e_value_size) > end))
return -EIO;
entry = EXT4_XATTR_NEXT(entry);
}
return 0;
}
static inline int
<API key>(struct buffer_head *bh)
{
if (BHDR(bh)->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC) ||
BHDR(bh)->h_blocks != cpu_to_le32(1))
return -EIO;
return <API key>(BFIRST(bh), bh->b_data + bh->b_size,
bh->b_data);
}
static inline int
<API key>(struct ext4_xattr_entry *entry, size_t size)
{
size_t value_size = le32_to_cpu(entry->e_value_size);
if (entry->e_value_block != 0 || value_size > size ||
le16_to_cpu(entry->e_value_offs) + value_size > size)
return -EIO;
return 0;
}
static int
<API key>(struct ext4_xattr_entry **pentry, int name_index,
const char *name, size_t size, int sorted)
{
struct ext4_xattr_entry *entry;
size_t name_len;
int cmp = 1;
if (name == NULL)
return -EINVAL;
name_len = strlen(name);
entry = *pentry;
for (; !IS_LAST_ENTRY(entry); entry = EXT4_XATTR_NEXT(entry)) {
cmp = name_index - entry->e_name_index;
if (!cmp)
cmp = name_len - entry->e_name_len;
if (!cmp)
cmp = memcmp(name, entry->e_name, name_len);
if (cmp <= 0 && (sorted || cmp == 0))
break;
}
*pentry = entry;
if (!cmp && <API key>(entry, size))
return -EIO;
return cmp ? -ENODATA : 0;
}
static int
<API key>(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
struct buffer_head *bh = NULL;
struct ext4_xattr_entry *entry;
size_t size;
int error;
ea_idebug(inode, "name=%d.%s, buffer=%p, buffer_size=%ld",
name_index, name, buffer, (long)buffer_size);
error = -ENODATA;
if (!EXT4_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %llu",
(unsigned long long)EXT4_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
if (<API key>(bh)) {
bad_block:
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
<API key>(bh);
entry = BFIRST(bh);
error = <API key>(&entry, name_index, name, bh->b_size, 1);
if (error == -EIO)
goto bad_block;
if (error)
goto cleanup;
size = le32_to_cpu(entry->e_value_size);
if (buffer) {
error = -ERANGE;
if (size > buffer_size)
goto cleanup;
memcpy(buffer, bh->b_data + le16_to_cpu(entry->e_value_offs),
size);
}
error = size;
cleanup:
brelse(bh);
return error;
}
static int
<API key>(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
struct <API key> *header;
struct ext4_xattr_entry *entry;
struct ext4_inode *raw_inode;
struct ext4_iloc iloc;
size_t size;
void *end;
int error;
if (!<API key>(inode, EXT4_STATE_XATTR))
return -ENODATA;
error = ext4_get_inode_loc(inode, &iloc);
if (error)
return error;
raw_inode = ext4_raw_inode(&iloc);
header = IHDR(inode, raw_inode);
entry = IFIRST(header);
end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
error = <API key>(entry, end, entry);
if (error)
goto cleanup;
error = <API key>(&entry, name_index, name,
end - (void *)entry, 0);
if (error)
goto cleanup;
size = le32_to_cpu(entry->e_value_size);
if (buffer) {
error = -ERANGE;
if (size > buffer_size)
goto cleanup;
memcpy(buffer, (void *)IFIRST(header) +
le16_to_cpu(entry->e_value_offs), size);
}
error = size;
cleanup:
brelse(iloc.bh);
return error;
}
/*
* ext4_xattr_get()
*
* Copy an extended attribute into the buffer
* provided, or compute the buffer size required.
* Buffer is NULL to compute the size of the buffer required.
*
* Returns a negative error number on failure, or the number of bytes
* used / required on success.
*/
int
ext4_xattr_get(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
int error;
down_read(&EXT4_I(inode)->xattr_sem);
error = <API key>(inode, name_index, name, buffer,
buffer_size);
if (error == -ENODATA)
error = <API key>(inode, name_index, name, buffer,
buffer_size);
up_read(&EXT4_I(inode)->xattr_sem);
return error;
}
static int
<API key>(struct dentry *dentry, struct ext4_xattr_entry *entry,
char *buffer, size_t buffer_size)
{
size_t rest = buffer_size;
for (; !IS_LAST_ENTRY(entry); entry = EXT4_XATTR_NEXT(entry)) {
const struct xattr_handler *handler =
ext4_xattr_handler(entry->e_name_index);
if (handler) {
size_t size = handler->list(dentry, buffer, rest,
entry->e_name,
entry->e_name_len,
handler->flags);
if (buffer) {
if (size > rest)
return -ERANGE;
buffer += size;
}
rest -= size;
}
}
return buffer_size - rest;
}
static int
<API key>(struct dentry *dentry, char *buffer, size_t buffer_size)
{
struct inode *inode = dentry->d_inode;
struct buffer_head *bh = NULL;
int error;
ea_idebug(inode, "buffer=%p, buffer_size=%ld",
buffer, (long)buffer_size);
error = 0;
if (!EXT4_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %llu",
(unsigned long long)EXT4_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
error = -EIO;
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
if (<API key>(bh)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
<API key>(bh);
error = <API key>(dentry, BFIRST(bh), buffer, buffer_size);
cleanup:
brelse(bh);
return error;
}
static int
<API key>(struct dentry *dentry, char *buffer, size_t buffer_size)
{
struct inode *inode = dentry->d_inode;
struct <API key> *header;
struct ext4_inode *raw_inode;
struct ext4_iloc iloc;
void *end;
int error;
if (!<API key>(inode, EXT4_STATE_XATTR))
return 0;
error = ext4_get_inode_loc(inode, &iloc);
if (error)
return error;
raw_inode = ext4_raw_inode(&iloc);
header = IHDR(inode, raw_inode);
end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
error = <API key>(IFIRST(header), end, IFIRST(header));
if (error)
goto cleanup;
error = <API key>(dentry, IFIRST(header),
buffer, buffer_size);
cleanup:
brelse(iloc.bh);
return error;
}
/*
* ext4_xattr_list()
*
* Copy a list of attribute names into the buffer
* provided, or compute the buffer size required.
* Buffer is NULL to compute the size of the buffer required.
*
* Returns a negative error number on failure, or the number of bytes
* used / required on success.
*/
static int
ext4_xattr_list(struct dentry *dentry, char *buffer, size_t buffer_size)
{
int ret, ret2;
down_read(&EXT4_I(dentry->d_inode)->xattr_sem);
ret = ret2 = <API key>(dentry, buffer, buffer_size);
if (ret < 0)
goto errout;
if (buffer) {
buffer += ret;
buffer_size -= ret;
}
ret = <API key>(dentry, buffer, buffer_size);
if (ret < 0)
goto errout;
ret += ret2;
errout:
up_read(&EXT4_I(dentry->d_inode)->xattr_sem);
return ret;
}
/*
* If the <API key> feature of this file system is
* not set, set it.
*/
static void <API key>(handle_t *handle,
struct super_block *sb)
{
if (<API key>(sb, <API key>))
return;
if (<API key>(handle, EXT4_SB(sb)->s_sbh) == 0) {
<API key>(sb, <API key>);
<API key>(handle, sb);
}
}
/*
* Release the xattr block BH: If the reference count is > 1, decrement
* it; otherwise free the block.
*/
static void
<API key>(handle_t *handle, struct inode *inode,
struct buffer_head *bh)
{
struct mb_cache_entry *ce = NULL;
int error = 0;
ce = mb_cache_entry_get(ext4_xattr_cache, bh->b_bdev, bh->b_blocknr);
error = <API key>(handle, bh);
if (error)
goto out;
lock_buffer(bh);
if (BHDR(bh)->h_refcount == cpu_to_le32(1)) {
ea_bdebug(bh, "refcount now=0; freeing");
if (ce)
mb_cache_entry_free(ce);
get_bh(bh);
ext4_free_blocks(handle, inode, bh, 0, 1,
<API key> |
<API key>);
unlock_buffer(bh);
} else {
le32_add_cpu(&BHDR(bh)->h_refcount, -1);
if (ce)
<API key>(ce);
unlock_buffer(bh);
error = <API key>(handle, inode, bh);
if (IS_SYNC(inode))
ext4_handle_sync(handle);
dquot_free_block(inode, EXT4_C2B(EXT4_SB(inode->i_sb), 1));
ea_bdebug(bh, "refcount now=%d; releasing",
le32_to_cpu(BHDR(bh)->h_refcount));
}
out:
ext4_std_error(inode->i_sb, error);
return;
}
/*
* Find the available free space for EAs. This also returns the total number of
* bytes used by EA entries.
*/
static size_t <API key>(struct ext4_xattr_entry *last,
size_t *min_offs, void *base, int *total)
{
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
if (!last->e_value_block && last->e_value_size) {
size_t offs = le16_to_cpu(last->e_value_offs);
if (offs < *min_offs)
*min_offs = offs;
}
if (total)
*total += EXT4_XATTR_LEN(last->e_name_len);
}
return (*min_offs - ((void *)last - base) - sizeof(__u32));
}
struct ext4_xattr_info {
int name_index;
const char *name;
const void *value;
size_t value_len;
};
struct ext4_xattr_search {
struct ext4_xattr_entry *first;
void *base;
void *end;
struct ext4_xattr_entry *here;
int not_found;
};
static int
<API key>(struct ext4_xattr_info *i, struct ext4_xattr_search *s)
{
struct ext4_xattr_entry *last;
size_t free, min_offs = s->end - s->base, name_len = strlen(i->name);
/* Compute min_offs and last. */
last = s->first;
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
if (!last->e_value_block && last->e_value_size) {
size_t offs = le16_to_cpu(last->e_value_offs);
if (offs < min_offs)
min_offs = offs;
}
}
free = min_offs - ((void *)last - s->base) - sizeof(__u32);
if (!s->not_found) {
if (!s->here->e_value_block && s->here->e_value_size) {
size_t size = le32_to_cpu(s->here->e_value_size);
free += EXT4_XATTR_SIZE(size);
}
free += EXT4_XATTR_LEN(name_len);
}
if (i->value) {
if (free < EXT4_XATTR_SIZE(i->value_len) ||
free < EXT4_XATTR_LEN(name_len) +
EXT4_XATTR_SIZE(i->value_len))
return -ENOSPC;
}
if (i->value && s->not_found) {
/* Insert the new name. */
size_t size = EXT4_XATTR_LEN(name_len);
size_t rest = (void *)last - (void *)s->here + sizeof(__u32);
memmove((void *)s->here + size, s->here, rest);
memset(s->here, 0, size);
s->here->e_name_index = i->name_index;
s->here->e_name_len = name_len;
memcpy(s->here->e_name, i->name, name_len);
} else {
if (!s->here->e_value_block && s->here->e_value_size) {
void *first_val = s->base + min_offs;
size_t offs = le16_to_cpu(s->here->e_value_offs);
void *val = s->base + offs;
size_t size = EXT4_XATTR_SIZE(
le32_to_cpu(s->here->e_value_size));
if (i->value && size == EXT4_XATTR_SIZE(i->value_len)) {
/* The old and the new value have the same
size. Just replace. */
s->here->e_value_size =
cpu_to_le32(i->value_len);
memset(val + size - EXT4_XATTR_PAD, 0,
EXT4_XATTR_PAD); /* Clear pad bytes. */
memcpy(val, i->value, i->value_len);
return 0;
}
/* Remove the old value. */
memmove(first_val + size, first_val, val - first_val);
memset(first_val, 0, size);
s->here->e_value_size = 0;
s->here->e_value_offs = 0;
min_offs += size;
/* Adjust all value offsets. */
last = s->first;
while (!IS_LAST_ENTRY(last)) {
size_t o = le16_to_cpu(last->e_value_offs);
if (!last->e_value_block &&
last->e_value_size && o < offs)
last->e_value_offs =
cpu_to_le16(o + size);
last = EXT4_XATTR_NEXT(last);
}
}
if (!i->value) {
/* Remove the old name. */
size_t size = EXT4_XATTR_LEN(name_len);
last = ENTRY((void *)last - size);
memmove(s->here, (void *)s->here + size,
(void *)last - (void *)s->here + sizeof(__u32));
memset(last, 0, size);
}
}
if (i->value) {
/* Insert the new value. */
s->here->e_value_size = cpu_to_le32(i->value_len);
if (i->value_len) {
size_t size = EXT4_XATTR_SIZE(i->value_len);
void *val = s->base + min_offs - size;
s->here->e_value_offs = cpu_to_le16(min_offs - size);
memset(val + size - EXT4_XATTR_PAD, 0,
EXT4_XATTR_PAD); /* Clear the pad bytes. */
memcpy(val, i->value, i->value_len);
}
}
return 0;
}
struct <API key> {
struct ext4_xattr_search s;
struct buffer_head *bh;
};
static int
<API key>(struct inode *inode, struct ext4_xattr_info *i,
struct <API key> *bs)
{
struct super_block *sb = inode->i_sb;
int error;
ea_idebug(inode, "name=%d.%s, value=%p, value_len=%ld",
i->name_index, i->name, i->value, (long)i->value_len);
if (EXT4_I(inode)->i_file_acl) {
/* The inode already has an extended attribute block. */
bs->bh = sb_bread(sb, EXT4_I(inode)->i_file_acl);
error = -EIO;
if (!bs->bh)
goto cleanup;
ea_bdebug(bs->bh, "b_count=%d, refcount=%d",
atomic_read(&(bs->bh->b_count)),
le32_to_cpu(BHDR(bs->bh)->h_refcount));
if (<API key>(bs->bh)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
/* Find the named attribute. */
bs->s.base = BHDR(bs->bh);
bs->s.first = BFIRST(bs->bh);
bs->s.end = bs->bh->b_data + bs->bh->b_size;
bs->s.here = bs->s.first;
error = <API key>(&bs->s.here, i->name_index,
i->name, bs->bh->b_size, 1);
if (error && error != -ENODATA)
goto cleanup;
bs->s.not_found = error;
}
error = 0;
cleanup:
return error;
}
static int
<API key>(handle_t *handle, struct inode *inode,
struct ext4_xattr_info *i,
struct <API key> *bs)
{
struct super_block *sb = inode->i_sb;
struct buffer_head *new_bh = NULL;
struct ext4_xattr_search *s = &bs->s;
struct mb_cache_entry *ce = NULL;
int error = 0;
#define header(x) ((struct ext4_xattr_header *)(x))
if (i->value && i->value_len > sb->s_blocksize)
return -ENOSPC;
if (s->base) {
ce = mb_cache_entry_get(ext4_xattr_cache, bs->bh->b_bdev,
bs->bh->b_blocknr);
error = <API key>(handle, bs->bh);
if (error)
goto cleanup;
lock_buffer(bs->bh);
if (header(s->base)->h_refcount == cpu_to_le32(1)) {
if (ce) {
mb_cache_entry_free(ce);
ce = NULL;
}
ea_bdebug(bs->bh, "modifying in-place");
error = <API key>(i, s);
if (!error) {
if (!IS_LAST_ENTRY(s->first))
ext4_xattr_rehash(header(s->base),
s->here);
<API key>(bs->bh);
}
unlock_buffer(bs->bh);
if (error == -EIO)
goto bad_block;
if (!error)
error = <API key>(handle,
inode,
bs->bh);
if (error)
goto cleanup;
goto inserted;
} else {
int offset = (char *)s->here - bs->bh->b_data;
unlock_buffer(bs->bh);
<API key>(handle, bs->bh);
if (ce) {
<API key>(ce);
ce = NULL;
}
ea_bdebug(bs->bh, "cloning");
s->base = kmalloc(bs->bh->b_size, GFP_NOFS);
error = -ENOMEM;
if (s->base == NULL)
goto cleanup;
memcpy(s->base, BHDR(bs->bh), bs->bh->b_size);
s->first = ENTRY(header(s->base)+1);
header(s->base)->h_refcount = cpu_to_le32(1);
s->here = ENTRY(s->base + offset);
s->end = s->base + bs->bh->b_size;
}
} else {
/* Allocate a buffer where we construct the new block. */
s->base = kzalloc(sb->s_blocksize, GFP_NOFS);
/* assert(header == s->base) */
error = -ENOMEM;
if (s->base == NULL)
goto cleanup;
header(s->base)->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);
header(s->base)->h_blocks = cpu_to_le32(1);
header(s->base)->h_refcount = cpu_to_le32(1);
s->first = ENTRY(header(s->base)+1);
s->here = ENTRY(header(s->base)+1);
s->end = s->base + sb->s_blocksize;
}
error = <API key>(i, s);
if (error == -EIO)
goto bad_block;
if (error)
goto cleanup;
if (!IS_LAST_ENTRY(s->first))
ext4_xattr_rehash(header(s->base), s->here);
inserted:
if (!IS_LAST_ENTRY(s->first)) {
new_bh = <API key>(inode, header(s->base), &ce);
if (new_bh) {
/* We found an identical block in the cache. */
if (new_bh == bs->bh)
ea_bdebug(new_bh, "keeping");
else {
/* The old block is released after updating
the inode. */
error = dquot_alloc_block(inode,
EXT4_C2B(EXT4_SB(sb), 1));
if (error)
goto cleanup;
error = <API key>(handle,
new_bh);
if (error)
goto cleanup_dquot;
lock_buffer(new_bh);
le32_add_cpu(&BHDR(new_bh)->h_refcount, 1);
ea_bdebug(new_bh, "reusing; refcount now=%d",
le32_to_cpu(BHDR(new_bh)->h_refcount));
unlock_buffer(new_bh);
error = <API key>(handle,
inode,
new_bh);
if (error)
goto cleanup_dquot;
}
<API key>(ce);
ce = NULL;
} else if (bs->bh && s->base == bs->bh->b_data) {
/* We were modifying this block in-place. */
ea_bdebug(bs->bh, "keeping this block");
new_bh = bs->bh;
get_bh(new_bh);
} else {
/* We need to allocate a new block */
ext4_fsblk_t goal, block;
goal = <API key>(sb,
EXT4_I(inode)->i_block_group);
/* non-extent files can't have physical blocks past 2^32 */
if (!(<API key>(inode, EXT4_INODE_EXTENTS)))
goal = goal & <API key>;
/*
* take i_data_sem because we will test
* <API key> in ext4_mb_new_blocks
*/
down_read((&EXT4_I(inode)->i_data_sem));
block = <API key>(handle, inode, goal, 0,
NULL, &error);
up_read((&EXT4_I(inode)->i_data_sem));
if (error)
goto cleanup;
if (!(<API key>(inode, EXT4_INODE_EXTENTS)))
BUG_ON(block > <API key>);
ea_idebug(inode, "creating block %llu",
(unsigned long long)block);
new_bh = sb_getblk(sb, block);
if (!new_bh) {
getblk_failed:
ext4_free_blocks(handle, inode, NULL, block, 1,
<API key>);
error = -EIO;
goto cleanup;
}
lock_buffer(new_bh);
error = <API key>(handle, new_bh);
if (error) {
unlock_buffer(new_bh);
goto getblk_failed;
}
memcpy(new_bh->b_data, s->base, new_bh->b_size);
set_buffer_uptodate(new_bh);
unlock_buffer(new_bh);
<API key>(new_bh);
error = <API key>(handle,
inode, new_bh);
if (error)
goto cleanup;
}
}
/* Update the inode. */
EXT4_I(inode)->i_file_acl = new_bh ? new_bh->b_blocknr : 0;
/* Drop the previous xattr block. */
if (bs->bh && bs->bh != new_bh)
<API key>(handle, inode, bs->bh);
error = 0;
cleanup:
if (ce)
<API key>(ce);
brelse(new_bh);
if (!(bs->bh && s->base == bs->bh->b_data))
kfree(s->base);
return error;
cleanup_dquot:
dquot_free_block(inode, EXT4_C2B(EXT4_SB(sb), 1));
goto cleanup;
bad_block:
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
goto cleanup;
#undef header
}
struct <API key> {
struct ext4_xattr_search s;
struct ext4_iloc iloc;
};
static int
<API key>(struct inode *inode, struct ext4_xattr_info *i,
struct <API key> *is)
{
struct <API key> *header;
struct ext4_inode *raw_inode;
int error;
if (EXT4_I(inode)->i_extra_isize == 0)
return 0;
raw_inode = ext4_raw_inode(&is->iloc);
header = IHDR(inode, raw_inode);
is->s.base = is->s.first = IFIRST(header);
is->s.here = is->s.first;
is->s.end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
if (<API key>(inode, EXT4_STATE_XATTR)) {
error = <API key>(IFIRST(header), is->s.end,
IFIRST(header));
if (error)
return error;
/* Find the named attribute. */
error = <API key>(&is->s.here, i->name_index,
i->name, is->s.end -
(void *)is->s.base, 0);
if (error && error != -ENODATA)
return error;
is->s.not_found = error;
}
return 0;
}
static int
<API key>(handle_t *handle, struct inode *inode,
struct ext4_xattr_info *i,
struct <API key> *is)
{
struct <API key> *header;
struct ext4_xattr_search *s = &is->s;
int error;
if (EXT4_I(inode)->i_extra_isize == 0)
return -ENOSPC;
error = <API key>(i, s);
if (error)
return error;
header = IHDR(inode, ext4_raw_inode(&is->iloc));
if (!IS_LAST_ENTRY(s->first)) {
header->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);
<API key>(inode, EXT4_STATE_XATTR);
} else {
header->h_magic = cpu_to_le32(0);
<API key>(inode, EXT4_STATE_XATTR);
}
return 0;
}
/*
* <API key>()
*
* Create, replace or remove an extended attribute for this inode. Value
* is NULL to remove an existing extended attribute, and non-NULL to
* either replace an existing extended attribute, or create a new extended
* attribute. The flags XATTR_REPLACE and XATTR_CREATE
* specify that an extended attribute must exist and must not exist
* previous to the call, respectively.
*
* Returns 0, or a negative error number on failure.
*/
int
<API key>(handle_t *handle, struct inode *inode, int name_index,
const char *name, const void *value, size_t value_len,
int flags)
{
struct ext4_xattr_info i = {
.name_index = name_index,
.name = name,
.value = value,
.value_len = value_len,
};
struct <API key> is = {
.s = { .not_found = -ENODATA, },
};
struct <API key> bs = {
.s = { .not_found = -ENODATA, },
};
unsigned long no_expand;
int error;
if (!name)
return -EINVAL;
if (strlen(name) > 255)
return -ERANGE;
down_write(&EXT4_I(inode)->xattr_sem);
no_expand = <API key>(inode, <API key>);
<API key>(inode, <API key>);
error = <API key>(handle, inode, &is.iloc);
if (error)
goto cleanup;
if (<API key>(inode, EXT4_STATE_NEW)) {
struct ext4_inode *raw_inode = ext4_raw_inode(&is.iloc);
memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
<API key>(inode, EXT4_STATE_NEW);
}
error = <API key>(inode, &i, &is);
if (error)
goto cleanup;
if (is.s.not_found)
error = <API key>(inode, &i, &bs);
if (error)
goto cleanup;
if (is.s.not_found && bs.s.not_found) {
error = -ENODATA;
if (flags & XATTR_REPLACE)
goto cleanup;
error = 0;
if (!value)
goto cleanup;
} else {
error = -EEXIST;
if (flags & XATTR_CREATE)
goto cleanup;
}
if (!value) {
if (!is.s.not_found)
error = <API key>(handle, inode, &i, &is);
else if (!bs.s.not_found)
error = <API key>(handle, inode, &i, &bs);
} else {
error = <API key>(handle, inode, &i, &is);
if (!error && !bs.s.not_found) {
i.value = NULL;
error = <API key>(handle, inode, &i, &bs);
} else if (error == -ENOSPC) {
if (EXT4_I(inode)->i_file_acl && !bs.s.base) {
error = <API key>(inode, &i, &bs);
if (error)
goto cleanup;
}
error = <API key>(handle, inode, &i, &bs);
if (error)
goto cleanup;
if (!is.s.not_found) {
i.value = NULL;
error = <API key>(handle, inode, &i,
&is);
}
}
}
if (!error) {
<API key>(handle, inode->i_sb);
inode->i_ctime = ext4_current_time(inode);
if (!value)
<API key>(inode, <API key>);
error = <API key>(handle, inode, &is.iloc);
/*
* The bh is consumed by <API key>, even with
* error != 0.
*/
is.iloc.bh = NULL;
if (IS_SYNC(inode))
ext4_handle_sync(handle);
}
cleanup:
brelse(is.iloc.bh);
brelse(bs.bh);
if (no_expand == 0)
<API key>(inode, <API key>);
up_write(&EXT4_I(inode)->xattr_sem);
return error;
}
/*
* ext4_xattr_set()
*
* Like <API key>, but start from an inode. This extended
* attribute modification is a filesystem transaction by itself.
*
* Returns 0, or a negative error number on failure.
*/
int
ext4_xattr_set(struct inode *inode, int name_index, const char *name,
const void *value, size_t value_len, int flags)
{
handle_t *handle;
int error, retries = 0;
retry:
handle = ext4_journal_start(inode, <API key>(inode->i_sb));
if (IS_ERR(handle)) {
error = PTR_ERR(handle);
} else {
int error2;
error = <API key>(handle, inode, name_index, name,
value, value_len, flags);
error2 = ext4_journal_stop(handle);
if (error == -ENOSPC &&
<API key>(inode->i_sb, &retries))
goto retry;
if (error == 0)
error = error2;
}
return error;
}
/*
* Shift the EA entries in the inode to create space for the increased
* i_extra_isize.
*/
static void <API key>(struct ext4_xattr_entry *entry,
int value_offs_shift, void *to,
void *from, size_t n, int blocksize)
{
struct ext4_xattr_entry *last = entry;
int new_offs;
/* Adjust the value offsets of the entries */
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
if (!last->e_value_block && last->e_value_size) {
new_offs = le16_to_cpu(last->e_value_offs) +
value_offs_shift;
BUG_ON(new_offs + le32_to_cpu(last->e_value_size)
> blocksize);
last->e_value_offs = cpu_to_le16(new_offs);
}
}
/* Shift the entries by n bytes */
memmove(to, from, n);
}
/*
* Expand an inode by new_extra_isize bytes when EAs are present.
* Returns 0 on success or negative error number on failure.
*/
int <API key>(struct inode *inode, int new_extra_isize,
struct ext4_inode *raw_inode, handle_t *handle)
{
struct <API key> *header;
struct ext4_xattr_entry *entry, *last, *first;
struct buffer_head *bh = NULL;
struct <API key> *is = NULL;
struct <API key> *bs = NULL;
char *buffer = NULL, *b_entry_name = NULL;
size_t min_offs, free;
int total_ino;
void *base, *start, *end;
int extra_isize = 0, error = 0, <API key> = 0;
int s_min_extra_isize = le16_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_min_extra_isize);
down_write(&EXT4_I(inode)->xattr_sem);
retry:
if (EXT4_I(inode)->i_extra_isize >= new_extra_isize) {
up_write(&EXT4_I(inode)->xattr_sem);
return 0;
}
header = IHDR(inode, raw_inode);
entry = IFIRST(header);
/*
* Check if enough free space is available in the inode to shift the
* entries ahead by new_extra_isize.
*/
base = start = entry;
end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size;
min_offs = end - base;
last = entry;
total_ino = sizeof(struct <API key>);
free = <API key>(last, &min_offs, base, &total_ino);
if (free >= new_extra_isize) {
entry = IFIRST(header);
<API key>(entry, EXT4_I(inode)->i_extra_isize
- new_extra_isize, (void *)raw_inode +
<API key> + new_extra_isize,
(void *)header, total_ino,
inode->i_sb->s_blocksize);
EXT4_I(inode)->i_extra_isize = new_extra_isize;
error = 0;
goto cleanup;
}
/*
* Enough free space isn't available in the inode, check if
* EA block can hold new_extra_isize bytes.
*/
if (EXT4_I(inode)->i_file_acl) {
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
error = -EIO;
if (!bh)
goto cleanup;
if (<API key>(bh)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
base = BHDR(bh);
first = BFIRST(bh);
end = bh->b_data + bh->b_size;
min_offs = end - base;
free = <API key>(first, &min_offs, base, NULL);
if (free < new_extra_isize) {
if (!<API key> && s_min_extra_isize) {
<API key>++;
new_extra_isize = s_min_extra_isize;
brelse(bh);
goto retry;
}
error = -1;
goto cleanup;
}
} else {
free = inode->i_sb->s_blocksize;
}
while (new_extra_isize > 0) {
size_t offs, size, entry_size;
struct ext4_xattr_entry *small_entry = NULL;
struct ext4_xattr_info i = {
.value = NULL,
.value_len = 0,
};
unsigned int total_size; /* EA entry size + value size */
unsigned int shift_bytes; /* No. of bytes to shift EAs by? */
unsigned int min_total_size = ~0U;
is = kzalloc(sizeof(struct <API key>), GFP_NOFS);
bs = kzalloc(sizeof(struct <API key>), GFP_NOFS);
if (!is || !bs) {
error = -ENOMEM;
goto cleanup;
}
is->s.not_found = -ENODATA;
bs->s.not_found = -ENODATA;
is->iloc.bh = NULL;
bs->bh = NULL;
last = IFIRST(header);
/* Find the entry best suited to be pushed into EA block */
entry = NULL;
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
total_size =
EXT4_XATTR_SIZE(le32_to_cpu(last->e_value_size)) +
EXT4_XATTR_LEN(last->e_name_len);
if (total_size <= free && total_size < min_total_size) {
if (total_size < new_extra_isize) {
small_entry = last;
} else {
entry = last;
min_total_size = total_size;
}
}
}
if (entry == NULL) {
if (small_entry) {
entry = small_entry;
} else {
if (!<API key> &&
s_min_extra_isize) {
<API key>++;
new_extra_isize = s_min_extra_isize;
kfree(is); is = NULL;
kfree(bs); bs = NULL;
brelse(bh);
goto retry;
}
error = -1;
goto cleanup;
}
}
offs = le16_to_cpu(entry->e_value_offs);
size = le32_to_cpu(entry->e_value_size);
entry_size = EXT4_XATTR_LEN(entry->e_name_len);
i.name_index = entry->e_name_index,
buffer = kmalloc(EXT4_XATTR_SIZE(size), GFP_NOFS);
b_entry_name = kmalloc(entry->e_name_len + 1, GFP_NOFS);
if (!buffer || !b_entry_name) {
error = -ENOMEM;
goto cleanup;
}
/* Save the entry name and the entry value */
memcpy(buffer, (void *)IFIRST(header) + offs,
EXT4_XATTR_SIZE(size));
memcpy(b_entry_name, entry->e_name, entry->e_name_len);
b_entry_name[entry->e_name_len] = '\0';
i.name = b_entry_name;
error = ext4_get_inode_loc(inode, &is->iloc);
if (error)
goto cleanup;
error = <API key>(inode, &i, is);
if (error)
goto cleanup;
/* Remove the chosen entry from the inode */
error = <API key>(handle, inode, &i, is);
if (error)
goto cleanup;
entry = IFIRST(header);
if (entry_size + EXT4_XATTR_SIZE(size) >= new_extra_isize)
shift_bytes = new_extra_isize;
else
shift_bytes = entry_size + size;
/* Adjust the offsets and shift the remaining entries ahead */
<API key>(entry, EXT4_I(inode)->i_extra_isize -
shift_bytes, (void *)raw_inode +
<API key> + extra_isize + shift_bytes,
(void *)header, total_ino - entry_size,
inode->i_sb->s_blocksize);
extra_isize += shift_bytes;
new_extra_isize -= shift_bytes;
EXT4_I(inode)->i_extra_isize = extra_isize;
i.name = b_entry_name;
i.value = buffer;
i.value_len = size;
error = <API key>(inode, &i, bs);
if (error)
goto cleanup;
/* Add entry which was removed from the inode into the block */
error = <API key>(handle, inode, &i, bs);
if (error)
goto cleanup;
kfree(b_entry_name);
kfree(buffer);
b_entry_name = NULL;
buffer = NULL;
brelse(is->iloc.bh);
kfree(is);
kfree(bs);
}
brelse(bh);
up_write(&EXT4_I(inode)->xattr_sem);
return 0;
cleanup:
kfree(b_entry_name);
kfree(buffer);
if (is)
brelse(is->iloc.bh);
kfree(is);
kfree(bs);
brelse(bh);
up_write(&EXT4_I(inode)->xattr_sem);
return error;
}
/*
* <API key>()
*
* Free extended attribute resources associated with this inode. This
* is called immediately before an inode is freed. We have exclusive
* access to the inode.
*/
void
<API key>(handle_t *handle, struct inode *inode)
{
struct buffer_head *bh = NULL;
if (!EXT4_I(inode)->i_file_acl)
goto cleanup;
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
if (!bh) {
EXT4_ERROR_INODE(inode, "block %llu read error",
EXT4_I(inode)->i_file_acl);
goto cleanup;
}
if (BHDR(bh)->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC) ||
BHDR(bh)->h_blocks != cpu_to_le32(1)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
goto cleanup;
}
<API key>(handle, inode, bh);
EXT4_I(inode)->i_file_acl = 0;
cleanup:
brelse(bh);
}
/*
* <API key>()
*
* This is called when a file system is unmounted.
*/
void
<API key>(struct super_block *sb)
{
mb_cache_shrink(sb->s_bdev);
}
/*
* <API key>()
*
* Create a new entry in the extended attribute cache, and insert
* it unless such an entry is already in the cache.
*
* Returns 0, or a negative error number on failure.
*/
static void
<API key>(struct buffer_head *bh)
{
__u32 hash = le32_to_cpu(BHDR(bh)->h_hash);
struct mb_cache_entry *ce;
int error;
ce = <API key>(ext4_xattr_cache, GFP_NOFS);
if (!ce) {
ea_bdebug(bh, "out of memory");
return;
}
error = <API key>(ce, bh->b_bdev, bh->b_blocknr, hash);
if (error) {
mb_cache_entry_free(ce);
if (error == -EBUSY) {
ea_bdebug(bh, "already in cache");
error = 0;
}
} else {
ea_bdebug(bh, "inserting [%x]", (int)hash);
<API key>(ce);
}
}
/*
* ext4_xattr_cmp()
*
* Compare two extended attribute blocks for equality.
*
* Returns 0 if the blocks are equal, 1 if they differ, and
* a negative error number on errors.
*/
static int
ext4_xattr_cmp(struct ext4_xattr_header *header1,
struct ext4_xattr_header *header2)
{
struct ext4_xattr_entry *entry1, *entry2;
entry1 = ENTRY(header1+1);
entry2 = ENTRY(header2+1);
while (!IS_LAST_ENTRY(entry1)) {
if (IS_LAST_ENTRY(entry2))
return 1;
if (entry1->e_hash != entry2->e_hash ||
entry1->e_name_index != entry2->e_name_index ||
entry1->e_name_len != entry2->e_name_len ||
entry1->e_value_size != entry2->e_value_size ||
memcmp(entry1->e_name, entry2->e_name, entry1->e_name_len))
return 1;
if (entry1->e_value_block != 0 || entry2->e_value_block != 0)
return -EIO;
if (memcmp((char *)header1 + le16_to_cpu(entry1->e_value_offs),
(char *)header2 + le16_to_cpu(entry2->e_value_offs),
le32_to_cpu(entry1->e_value_size)))
return 1;
entry1 = EXT4_XATTR_NEXT(entry1);
entry2 = EXT4_XATTR_NEXT(entry2);
}
if (!IS_LAST_ENTRY(entry2))
return 1;
return 0;
}
/*
* <API key>()
*
* Find an identical extended attribute block.
*
* Returns a pointer to the block found, or NULL if such a block was
* not found or an error occurred.
*/
static struct buffer_head *
<API key>(struct inode *inode, struct ext4_xattr_header *header,
struct mb_cache_entry **pce)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb_cache_entry *ce;
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
again:
ce = <API key>(ext4_xattr_cache, inode->i_sb->s_bdev,
hash);
while (ce) {
struct buffer_head *bh;
if (IS_ERR(ce)) {
if (PTR_ERR(ce) == -EAGAIN)
goto again;
break;
}
bh = sb_bread(inode->i_sb, ce->e_block);
if (!bh) {
EXT4_ERROR_INODE(inode, "block %lu read error",
(unsigned long) ce->e_block);
} else if (le32_to_cpu(BHDR(bh)->h_refcount) >=
<API key>) {
ea_idebug(inode, "block %lu refcount %d>=%d",
(unsigned long) ce->e_block,
le32_to_cpu(BHDR(bh)->h_refcount),
<API key>);
} else if (ext4_xattr_cmp(header, BHDR(bh)) == 0) {
*pce = ce;
return bh;
}
brelse(bh);
ce = <API key>(ce, inode->i_sb->s_bdev, hash);
}
return NULL;
}
#define NAME_HASH_SHIFT 5
#define VALUE_HASH_SHIFT 16
/*
* <API key>()
*
* Compute the hash of an extended attribute.
*/
static inline void <API key>(struct ext4_xattr_header *header,
struct ext4_xattr_entry *entry)
{
__u32 hash = 0;
char *name = entry->e_name;
int n;
for (n = 0; n < entry->e_name_len; n++) {
hash = (hash << NAME_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - NAME_HASH_SHIFT)) ^
*name++;
}
if (entry->e_value_block == 0 && entry->e_value_size != 0) {
__le32 *value = (__le32 *)((char *)header +
le16_to_cpu(entry->e_value_offs));
for (n = (le32_to_cpu(entry->e_value_size) +
EXT4_XATTR_ROUND) >> EXT4_XATTR_PAD_BITS; n; n
hash = (hash << VALUE_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - VALUE_HASH_SHIFT)) ^
le32_to_cpu(*value++);
}
}
entry->e_hash = cpu_to_le32(hash);
}
#undef NAME_HASH_SHIFT
#undef VALUE_HASH_SHIFT
#define BLOCK_HASH_SHIFT 16
/*
* ext4_xattr_rehash()
*
* Re-compute the extended attribute hash value after an entry has changed.
*/
static void ext4_xattr_rehash(struct ext4_xattr_header *header,
struct ext4_xattr_entry *entry)
{
struct ext4_xattr_entry *here;
__u32 hash = 0;
<API key>(header, entry);
here = ENTRY(header+1);
while (!IS_LAST_ENTRY(here)) {
if (!here->e_hash) {
/* Block is not shared if an entry's hash value == 0 */
hash = 0;
break;
}
hash = (hash << BLOCK_HASH_SHIFT) ^
(hash >> (8*sizeof(hash) - BLOCK_HASH_SHIFT)) ^
le32_to_cpu(here->e_hash);
here = EXT4_XATTR_NEXT(here);
}
header->h_hash = cpu_to_le32(hash);
}
#undef BLOCK_HASH_SHIFT
int __init
ext4_init_xattr(void)
{
ext4_xattr_cache = mb_cache_create("ext4_xattr", 6);
if (!ext4_xattr_cache)
return -ENOMEM;
return 0;
}
void
ext4_exit_xattr(void)
{
if (ext4_xattr_cache)
mb_cache_destroy(ext4_xattr_cache);
ext4_xattr_cache = NULL;
} |
#ifndef __USB_CORE_HCD_H
#define __USB_CORE_HCD_H
#ifdef __KERNEL__
#include <linux/rwsem.h>
#define MAX_TOPO_LEVEL 6
/* This file contains declarations of usbcore internals that are mostly
* used or exposed by Host Controller Drivers.
*/
/*
* USB Packet IDs (PIDs)
*/
#define USB_PID_EXT 0xf0 /* USB 2.0 LPM ECN */
#define USB_PID_OUT 0xe1
#define USB_PID_ACK 0xd2
#define USB_PID_DATA0 0xc3
#define USB_PID_PING 0xb4 /* USB 2.0 */
#define USB_PID_SOF 0xa5
#define USB_PID_NYET 0x96 /* USB 2.0 */
#define USB_PID_DATA2 0x87 /* USB 2.0 */
#define USB_PID_SPLIT 0x78 /* USB 2.0 */
#define USB_PID_IN 0x69
#define USB_PID_NAK 0x5a
#define USB_PID_DATA1 0x4b
#define USB_PID_PREAMBLE 0x3c /* Token mode */
#define USB_PID_ERR 0x3c /* USB 2.0: handshake mode */
#define USB_PID_SETUP 0x2d
#define USB_PID_STALL 0x1e
#define USB_PID_MDATA 0x0f /* USB 2.0 */
/*
* USB Host Controller Driver (usb_hcd) framework
*
* Since "struct usb_bus" is so thin, you can't share much code in it.
* This framework is a layer over that, and should be more sharable.
*
* @authorized_default: Specifies if new devices are authorized to
* connect by default or they require explicit
* user space authorization; this bit is settable
* through /sys/class/usb_host/X/authorized_default.
* For the rest is RO, so we don't lock to r/w it.
*/
struct usb_hcd {
/*
* housekeeping
*/
struct usb_bus self; /* hcd is-a bus */
struct kref kref; /* reference counter */
const char *product_desc; /* product/vendor string */
int speed; /* Speed for this roothub.
* May be different from
* hcd->driver->flags & HCD_MASK
*/
char irq_descr[24]; /* driver + bus # */
struct timer_list rh_timer; /* drives root-hub polling */
struct urb *status_urb; /* the current status urb */
#ifdef CONFIG_PM_RUNTIME
struct work_struct wakeup_work; /* for remote wakeup */
#endif
/*
* hardware info/state
*/
const struct hc_driver *driver; /* hw-specific hooks */
/*
* OTG and some Host controllers need software interaction with phys;
* other external phys should be <API key>
*/
struct usb_phy *phy;
/* Flags that need to be manipulated atomically because they can
* change while the host controller is running. Always use
* set_bit() or clear_bit() to change their values.
*/
unsigned long flags;
#define <API key> 0 /* at full power */
#define HCD_FLAG_POLL_RH 2 /* poll for rh status? */
#define <API key> 3 /* status has changed? */
#define <API key> 4 /* root hub is resuming? */
#define HCD_FLAG_RH_RUNNING 5 /* root hub is running? */
#define HCD_FLAG_DEAD 6 /* controller has died? */
/* The flags can be tested using these macros; they are likely to
* be slightly faster than test_bit().
*/
#define HCD_HW_ACCESSIBLE(hcd) ((hcd)->flags & (1U << <API key>))
#define HCD_POLL_RH(hcd) ((hcd)->flags & (1U << HCD_FLAG_POLL_RH))
#define HCD_POLL_PENDING(hcd) ((hcd)->flags & (1U << <API key>))
#define HCD_WAKEUP_PENDING(hcd) ((hcd)->flags & (1U << <API key>))
#define HCD_RH_RUNNING(hcd) ((hcd)->flags & (1U << HCD_FLAG_RH_RUNNING))
#define HCD_DEAD(hcd) ((hcd)->flags & (1U << HCD_FLAG_DEAD))
/* Flags that get set only during HCD registration or removal. */
unsigned rh_registered:1;/* is root hub registered? */
unsigned rh_pollable:1; /* may we poll the root hub? */
unsigned msix_enabled:1; /* driver has MSI-X enabled? */
/* The next flag is a stopgap, to be removed when all the HCDs
* support the new root-hub polling mechanism. */
unsigned uses_new_polling:1;
unsigned wireless:1; /* Wireless USB HCD */
unsigned authorized_default:1;
unsigned has_tt:1; /* Integrated TT in root hub */
unsigned tpl_support:1; /* OTG & EH TPL support */
unsigned int irq; /* irq allocated */
void __iomem *regs; /* device memory/io */
resource_size_t rsrc_start; /* memory/io resource start */
resource_size_t rsrc_len; /* memory/io resource length */
unsigned power_budget; /* in mA, 0 = no limit */
/* bandwidth_mutex should be taken before adding or removing
* any new bus bandwidth constraints:
* 1. Before adding a configuration for a new device.
* 2. Before removing the configuration to put the device into
* the addressed state.
* 3. Before selecting a different configuration.
* 4. Before selecting an alternate interface setting.
*
* bandwidth_mutex should be dropped after a successful control message
* to the device, or resetting the bandwidth after a failed attempt.
*/
struct mutex *bandwidth_mutex;
struct usb_hcd *shared_hcd;
struct usb_hcd *primary_hcd;
#define HCD_BUFFER_POOLS 4
struct dma_pool *pool[HCD_BUFFER_POOLS];
int state;
# define __ACTIVE 0x01
# define __SUSPEND 0x04
# define __TRANSIENT 0x80
# define HC_STATE_HALT 0
# define HC_STATE_RUNNING (__ACTIVE)
# define HC_STATE_QUIESCING (__SUSPEND|__TRANSIENT|__ACTIVE)
# define HC_STATE_RESUMING (__SUSPEND|__TRANSIENT)
# define HC_STATE_SUSPENDED (__SUSPEND)
#define HC_IS_RUNNING(state) ((state) & __ACTIVE)
#define HC_IS_SUSPENDED(state) ((state) & __SUSPEND)
/* more shared queuing code would be good; it should support
* smarter scheduling, handle transaction translators, etc;
* input size of periodic table to an interrupt scheduler.
* (ohci 32, uhci 1024, ehci 256/512/1024).
*/
/* The HC driver's private data is stored at the end of
* this structure.
*/
unsigned long hcd_priv[0]
__attribute__ ((aligned(sizeof(s64))));
};
/* 2.4 does this a bit differently ... */
static inline struct usb_bus *hcd_to_bus(struct usb_hcd *hcd)
{
return &hcd->self;
}
static inline struct usb_hcd *bus_to_hcd(struct usb_bus *bus)
{
return container_of(bus, struct usb_hcd, self);
}
struct hcd_timeout { /* timeouts we allocate */
struct list_head timeout_list;
struct timer_list timer;
};
struct hc_driver {
const char *description; /* "ehci-hcd" etc */
const char *product_desc; /* product/vendor string */
size_t hcd_priv_size; /* size of private data */
/* irq handler */
irqreturn_t (*irq) (struct usb_hcd *hcd);
int flags;
#define HCD_MEMORY 0x0001 /* HC regs use memory (else I/O) */
#define HCD_LOCAL_MEM 0x0002 /* HC needs local memory */
#define HCD_SHARED 0x0004 /* Two (or more) usb_hcds share HW */
#define HCD_USB11 0x0010 /* USB 1.1 */
#define HCD_USB2 0x0020 /* USB 2.0 */
#define HCD_USB3 0x0040 /* USB 3.0 */
#define HCD_MASK 0x0070
/* called to init HCD and root hub */
int (*reset) (struct usb_hcd *hcd);
int (*start) (struct usb_hcd *hcd);
/* NOTE: these suspend/resume calls relate to the HC as
* a whole, not just the root hub; they're for PCI bus glue.
*/
/* called after suspending the hub, before entering D3 etc */
int (*pci_suspend)(struct usb_hcd *hcd, bool do_wakeup);
/* called after entering D0 (etc), before resuming the hub */
int (*pci_resume)(struct usb_hcd *hcd, bool hibernated);
/* cleanly make HCD stop writing memory and doing I/O */
void (*stop) (struct usb_hcd *hcd);
/* shutdown HCD */
void (*shutdown) (struct usb_hcd *hcd);
/* return current frame number */
int (*get_frame_number) (struct usb_hcd *hcd);
/* manage i/o requests, device state */
int (*urb_enqueue)(struct usb_hcd *hcd,
struct urb *urb, gfp_t mem_flags);
int (*urb_dequeue)(struct usb_hcd *hcd,
struct urb *urb, int status);
/*
* (optional) these hooks allow an HCD to override the default DMA
* mapping and unmapping routines. In general, they shouldn't be
* necessary unless the host controller has special DMA requirements,
* such as alignment contraints. If these are not specified, the
* general usb_hcd_(un)?map_urb_for_dma functions will be used instead
* (and it may be a good idea to call these functions in your HCD
* implementation)
*/
int (*map_urb_for_dma)(struct usb_hcd *hcd, struct urb *urb,
gfp_t mem_flags);
void (*unmap_urb_for_dma)(struct usb_hcd *hcd, struct urb *urb);
/* hw synch, freeing endpoint resources that urb_dequeue can't */
void (*endpoint_disable)(struct usb_hcd *hcd,
struct usb_host_endpoint *ep);
/* (optional) reset any endpoint state such as sequence number
and current window */
void (*endpoint_reset)(struct usb_hcd *hcd,
struct usb_host_endpoint *ep);
/* root hub support */
int (*hub_status_data) (struct usb_hcd *hcd, char *buf);
int (*hub_control) (struct usb_hcd *hcd,
u16 typeReq, u16 wValue, u16 wIndex,
char *buf, u16 wLength);
int (*bus_suspend)(struct usb_hcd *);
int (*bus_resume)(struct usb_hcd *);
int (*start_port_reset)(struct usb_hcd *, unsigned port_num);
/* force handover of high-speed port to full-speed companion */
void (*relinquish_port)(struct usb_hcd *, int);
/* has a port been handed over to a companion? */
int (*port_handed_over)(struct usb_hcd *, int);
/* CLEAR_TT_BUFFER completion callback */
void (*<API key>)(struct usb_hcd *,
struct usb_host_endpoint *);
/* xHCI specific functions */
/* Called by usb_alloc_dev to alloc HC device structures */
int (*alloc_dev)(struct usb_hcd *, struct usb_device *);
/* Called by usb_disconnect to free HC device structures */
void (*free_dev)(struct usb_hcd *, struct usb_device *);
/* Change a group of bulk endpoints to support multiple stream IDs */
int (*alloc_streams)(struct usb_hcd *hcd, struct usb_device *udev,
struct usb_host_endpoint **eps, unsigned int num_eps,
unsigned int num_streams, gfp_t mem_flags);
/* Reverts a group of bulk endpoints back to not using stream IDs.
* Can fail if we run out of memory.
*/
int (*free_streams)(struct usb_hcd *hcd, struct usb_device *udev,
struct usb_host_endpoint **eps, unsigned int num_eps,
gfp_t mem_flags);
/* Bandwidth computation functions */
/* Note that add_endpoint() can only be called once per endpoint before
* check_bandwidth() or reset_bandwidth() must be called.
* drop_endpoint() can only be called once per endpoint also.
* A call to xhci_drop_endpoint() followed by a call to
* xhci_add_endpoint() will add the endpoint to the schedule with
* possibly new parameters denoted by a different endpoint descriptor
* in usb_host_endpoint. A call to xhci_add_endpoint() followed by a
* call to xhci_drop_endpoint() is not allowed.
*/
/* Allocate endpoint resources and add them to a new schedule */
int (*add_endpoint)(struct usb_hcd *, struct usb_device *,
struct usb_host_endpoint *);
/* Drop an endpoint from a new schedule */
int (*drop_endpoint)(struct usb_hcd *, struct usb_device *,
struct usb_host_endpoint *);
/* Check that a new hardware configuration, set using
* endpoint_enable and endpoint_disable, does not exceed bus
* bandwidth. This must be called before any set configuration
* or set interface requests are sent to the device.
*/
int (*check_bandwidth)(struct usb_hcd *, struct usb_device *);
/* Reset the device schedule to the last known good schedule,
* which was set from a previous successful call to
* check_bandwidth(). This reverts any add_endpoint() and
* drop_endpoint() calls since that last successful call.
* Used for when a check_bandwidth() call fails due to resource
* or bandwidth constraints.
*/
void (*reset_bandwidth)(struct usb_hcd *, struct usb_device *);
/* Returns the hardware-chosen device address */
int (*address_device)(struct usb_hcd *, struct usb_device *udev);
/* Notifies the HCD after a hub descriptor is fetched.
* Will block.
*/
int (*update_hub_device)(struct usb_hcd *, struct usb_device *hdev,
struct usb_tt *tt, gfp_t mem_flags);
int (*reset_device)(struct usb_hcd *, struct usb_device *);
/* Notifies the HCD after a device is connected and its
* address is set
*/
int (*update_device)(struct usb_hcd *, struct usb_device *);
int (*set_usb2_hw_lpm)(struct usb_hcd *, struct usb_device *, int);
/* USB 3.0 Link Power Management */
/* Returns the USB3 hub-encoded value for the U1/U2 timeout. */
int (*<API key>)(struct usb_hcd *,
struct usb_device *, enum usb3_link_state state);
/* The xHCI host controller can still fail the command to
* disable the LPM timeouts, so this can return an error code.
*/
int (*<API key>)(struct usb_hcd *,
struct usb_device *, enum usb3_link_state state);
int (*<API key>)(struct usb_hcd *, int);
};
extern int <API key>(struct usb_hcd *hcd, struct urb *urb);
extern int <API key>(struct usb_hcd *hcd, struct urb *urb,
int status);
extern void <API key>(struct usb_hcd *hcd, struct urb *urb);
extern int usb_hcd_submit_urb(struct urb *urb, gfp_t mem_flags);
extern int usb_hcd_unlink_urb(struct urb *urb, int status);
extern void <API key>(struct usb_hcd *hcd, struct urb *urb,
int status);
extern int <API key>(struct usb_hcd *hcd, struct urb *urb,
gfp_t mem_flags);
extern void <API key>(struct usb_hcd *, struct urb *);
extern void <API key>(struct usb_hcd *, struct urb *);
extern void <API key>(struct usb_device *udev,
struct usb_host_endpoint *ep);
extern void <API key>(struct usb_device *udev,
struct usb_host_endpoint *ep);
extern void <API key>(struct usb_device *udev,
struct usb_host_endpoint *ep);
extern void <API key>(struct usb_device *udev);
extern int <API key>(struct usb_device *udev,
struct usb_host_config *new_config,
struct usb_host_interface *old_alt,
struct usb_host_interface *new_alt);
extern int <API key>(struct usb_device *udev);
extern struct usb_hcd *usb_create_hcd(const struct hc_driver *driver,
struct device *dev, const char *bus_name);
extern struct usb_hcd *<API key>(const struct hc_driver *driver,
struct device *dev, const char *bus_name,
struct usb_hcd *shared_hcd);
extern struct usb_hcd *usb_get_hcd(struct usb_hcd *hcd);
extern void usb_put_hcd(struct usb_hcd *hcd);
extern int <API key>(struct usb_hcd *hcd);
extern int usb_add_hcd(struct usb_hcd *hcd,
unsigned int irqnum, unsigned long irqflags);
extern void usb_remove_hcd(struct usb_hcd *hcd);
extern int <API key>(struct usb_hcd *hcd, int port1);
struct platform_device;
extern void <API key>(struct platform_device *dev);
#ifdef CONFIG_PCI
struct pci_dev;
struct pci_device_id;
extern int usb_hcd_pci_probe(struct pci_dev *dev,
const struct pci_device_id *id);
extern void usb_hcd_pci_remove(struct pci_dev *dev);
extern void <API key>(struct pci_dev *dev);
#ifdef CONFIG_PM
extern const struct dev_pm_ops usb_hcd_pci_pm_ops;
#endif
#endif /* CONFIG_PCI */
/* pci-ish (pdev null is ok) buffer alloc/mapping support */
int hcd_buffer_create(struct usb_hcd *hcd);
void hcd_buffer_destroy(struct usb_hcd *hcd);
void *hcd_buffer_alloc(struct usb_bus *bus, size_t size,
gfp_t mem_flags, dma_addr_t *dma);
void hcd_buffer_free(struct usb_bus *bus, size_t size,
void *addr, dma_addr_t dma);
/* generic bus glue, needed for host controllers that don't use PCI */
extern irqreturn_t usb_hcd_irq(int irq, void *__hcd);
extern void usb_hc_died(struct usb_hcd *hcd);
extern void <API key>(struct usb_hcd *hcd);
extern void <API key>(struct usb_device *hdev,
unsigned int portnum);
extern void <API key>(struct usb_bus *bus, int portnum);
extern void <API key>(struct usb_bus *bus, int portnum);
/* The D0/D1 toggle bits ... USE WITH CAUTION (they're almost hcd-internal) */
#define usb_gettoggle(dev, ep, out) (((dev)->toggle[out] >> (ep)) & 1)
#define usb_dotoggle(dev, ep, out) ((dev)->toggle[out] ^= (1 << (ep)))
#define usb_settoggle(dev, ep, out, bit) \
((dev)->toggle[out] = ((dev)->toggle[out] & ~(1 << (ep))) | \
((bit) << (ep)))
/* Enumeration is only for the hub driver, or HCD virtual root hubs */
extern struct usb_device *usb_alloc_dev(struct usb_device *parent,
struct usb_bus *, unsigned port);
extern int usb_new_device(struct usb_device *dev);
extern void usb_disconnect(struct usb_device **);
extern int <API key>(struct usb_device *dev);
extern void <API key>(struct usb_device *dev);
/*
* HCD Root Hub support
*/
#include <linux/usb/ch11.h>
/*
* As of USB 2.0, full/low speed devices are segregated into trees.
* One type grows from USB 1.1 host controllers (OHCI, UHCI etc).
* The other type grows from high speed hubs when they connect to
* full/low speed devices using "Transaction Translators" (TTs).
*
* TTs should only be known to the hub driver, and high speed bus
* drivers (only EHCI for now). They affect periodic scheduling and
* sometimes control/bulk error recovery.
*/
struct usb_device;
struct usb_tt {
struct usb_device *hub; /* upstream highspeed hub */
int multi; /* true means one TT per port */
unsigned think_time; /* think time in ns */
/* for control/bulk error recovery (CLEAR_TT_BUFFER) */
spinlock_t lock;
struct list_head clear_list; /* of usb_tt_clear */
struct work_struct clear_work;
};
struct usb_tt_clear {
struct list_head clear_list;
unsigned tt;
u16 devinfo;
struct usb_hcd *hcd;
struct usb_host_endpoint *ep;
};
extern int <API key>(struct urb *urb);
extern void usb_ep0_reinit(struct usb_device *);
/* (shifted) direction/type/recipient from the USB 2.0 spec, table 9.2 */
#define DeviceRequest \
((USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE)<<8)
#define DeviceOutRequest \
((USB_DIR_OUT|USB_TYPE_STANDARD|USB_RECIP_DEVICE)<<8)
#define InterfaceRequest \
((USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_INTERFACE)<<8)
#define EndpointRequest \
((USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_INTERFACE)<<8)
#define EndpointOutRequest \
((USB_DIR_OUT|USB_TYPE_STANDARD|USB_RECIP_INTERFACE)<<8)
/* class requests from the USB 2.0 hub spec, table 11-15 */
/* GetBusState and SetHubDescriptor are optional, omitted */
#define ClearHubFeature (0x2000 | <API key>)
#define ClearPortFeature (0x2300 | <API key>)
#define GetHubDescriptor (0xa000 | <API key>)
#define GetHubStatus (0xa000 | USB_REQ_GET_STATUS)
#define GetPortStatus (0xa300 | USB_REQ_GET_STATUS)
#define SetHubFeature (0x2000 | USB_REQ_SET_FEATURE)
#define SetPortFeature (0x2300 | USB_REQ_SET_FEATURE)
/* class requests from USB 3.0 hub spec, table 10-5 */
#define SetHubDepth (0x3000 | HUB_SET_DEPTH)
#define GetPortErrorCount (0x8000 | <API key>)
/*
* Generic bandwidth allocation constants/support
*/
#define FRAME_TIME_USECS 1000L
#define BitTime(bytecount) (7 * 8 * bytecount / 6) /* with integer truncation */
/* Trying not to use worst-case bit-stuffing
* of (7/6 * 8 * bytecount) = 9.33 * bytecount */
/* bytecount = data payload byte count */
#define NS_TO_US(ns) ((ns + 500L) / 1000L)
/* convert & round nanoseconds to microseconds */
/*
* Full/low speed bandwidth allocation constants/support.
*/
#define BW_HOST_DELAY 1000L /* nanoseconds */
#define BW_HUB_LS_SETUP 333L /* nanoseconds */
/* 4 full-speed bit times (est.) */
#define FRAME_TIME_BITS 12000L /* frame = 1 millisecond */
#define <API key> (90L * FRAME_TIME_BITS / 100L)
#define <API key> (90L * FRAME_TIME_USECS / 100L)
/*
* Ceiling [nano/micro]seconds (typical) for that many bytes at high speed
* ISO is a bit less, no ACK ... from USB 2.0 spec, 5.11.3 (and needed
* to preallocate bandwidth)
*/
#define USB2_HOST_DELAY 5 /* nsec, guess */
#define HS_NSECS(bytes) (((55 * 8 * 2083) \
+ (2083UL * (3 + BitTime(bytes))))/1000 \
+ USB2_HOST_DELAY)
#define HS_NSECS_ISO(bytes) (((38 * 8 * 2083) \
+ (2083UL * (3 + BitTime(bytes))))/1000 \
+ USB2_HOST_DELAY)
#define HS_USECS(bytes) NS_TO_US(HS_NSECS(bytes))
#define HS_USECS_ISO(bytes) NS_TO_US(HS_NSECS_ISO(bytes))
extern long usb_calc_bus_time(int speed, int is_input,
int isoc, int bytecount);
extern void <API key>(struct usb_device *udev,
enum usb_device_state new_state);
/* exported only within usbcore */
extern struct list_head usb_bus_list;
extern struct mutex usb_bus_list_lock;
extern wait_queue_head_t usb_kill_urb_queue;
extern int <API key>(struct usb_device *dev,
struct usb_interface *interface);
#define usb_endpoint_out(ep_dir) (!((ep_dir) & USB_DIR_IN))
#ifdef CONFIG_PM
extern void <API key>(struct usb_device *rhdev);
extern int hcd_bus_suspend(struct usb_device *rhdev, pm_message_t msg);
extern int hcd_bus_resume(struct usb_device *rhdev, pm_message_t msg);
#endif /* CONFIG_PM */
#ifdef CONFIG_PM_RUNTIME
extern void <API key>(struct usb_hcd *hcd);
#else
static inline void <API key>(struct usb_hcd *hcd)
{
return;
}
#endif /* CONFIG_PM_RUNTIME */
#if defined(CONFIG_USB_MON) || defined(<API key>)
struct usb_mon_operations {
void (*urb_submit)(struct usb_bus *bus, struct urb *urb);
void (*urb_submit_error)(struct usb_bus *bus, struct urb *urb, int err);
void (*urb_complete)(struct usb_bus *bus, struct urb *urb, int status);
/* void (*urb_unlink)(struct usb_bus *bus, struct urb *urb); */
};
extern struct usb_mon_operations *mon_ops;
static inline void usbmon_urb_submit(struct usb_bus *bus, struct urb *urb)
{
if (bus->monitored)
(*mon_ops->urb_submit)(bus, urb);
}
static inline void <API key>(struct usb_bus *bus, struct urb *urb,
int error)
{
if (bus->monitored)
(*mon_ops->urb_submit_error)(bus, urb, error);
}
static inline void usbmon_urb_complete(struct usb_bus *bus, struct urb *urb,
int status)
{
if (bus->monitored)
(*mon_ops->urb_complete)(bus, urb, status);
}
int usb_mon_register(struct usb_mon_operations *ops);
void usb_mon_deregister(void);
#else
static inline void usbmon_urb_submit(struct usb_bus *bus, struct urb *urb) {}
static inline void <API key>(struct usb_bus *bus, struct urb *urb,
int error) {}
static inline void usbmon_urb_complete(struct usb_bus *bus, struct urb *urb,
int status) {}
#endif /* CONFIG_USB_MON || <API key> */
/* random stuff */
#define RUN_CONTEXT (in_irq() ? "in_irq" \
: (in_interrupt() ? "in_interrupt" : "can sleep"))
/* This rwsem is for use only by the hub driver and ehci-hcd.
* Nobody else should touch it.
*/
extern struct rw_semaphore <API key>;
/* Keep track of which host controller drivers are loaded */
#define USB_UHCI_LOADED 0
#define USB_OHCI_LOADED 1
#define USB_EHCI_LOADED 2
extern unsigned long usb_hcds_loaded;
#endif /* __KERNEL__ */
#endif /* __USB_CORE_HCD_H */ |
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<title>{#table_dlg.merge_cells_title}</title><?php
$file = dirname(__FILE__);
$file = substr($file, 0, stripos($file, "wp-content") );
require( $file . "/wp-load.php");
$url = includes_url();
echo '<script type="text/javascript" src="'.$url.'js/tinymce/tiny_mce_popup.js'.'"></script>';
echo '<script type="text/javascript" src="'.$url.'js/tinymce/utils/mctabs.js'.'"></script>';
echo '<script type="text/javascript" src="'.$url.'js/tinymce/utils/validate.js'.'"></script>';
?>
<!
<script type="text/javascript" src="../../tinymce/tiny_mce_popup.js"></script>
<script type="text/javascript" src="../../tinymce/mctabs.js"></script>
<script type="text/javascript" src="../../tinymce/validate.js"></script>
<script type="text/javascript" src="js/merge_cells.js"></script>
</head>
<body style="margin: 8px" role="application">
<form onsubmit="MergeCellsDialog.merge();return false;" action="
<fieldset>
<legend>{#table_dlg.merge_cells_title}</legend>
<table role="presentation" border="0" cellpadding="0" cellspacing="3" width="100%">
<tr>
<td><label for="numcols">{#table_dlg.cols}</label>:</td>
<td align="right"><input type="text" id="numcols" name="numcols" value="" class="number min1 mceFocus" style="width: 30px" aria-required="true" /></td>
</tr>
<tr>
<td><label for="numrows">{#table_dlg.rows}</label>:</td>
<td align="right"><input type="text" id="numrows" name="numrows" value="" class="number min1" style="width: 30px" aria-required="true" /></td>
</tr>
</table>
</fieldset>
<div class="mceActionPanel">
<input type="submit" id="insert" name="insert" value="{#update}" />
<input type="button" id="cancel" name="cancel" value="{#cancel}" onclick="tinyMCEPopup.close();" />
</div>
</form>
</body>
</html> |
/* GENERAL CSS */
#body_bg {
border-bottom: 1px solid #ddd;
}
#body_left {
background: transparent url(../images/all/fill_left.png) 0 0 repeat-y;
}
#body_right {
background: transparent url(../images/all/fill_right.png) 100% 0 repeat-y;
}
ul.links li {
border-left: 1px solid #d3d3d3; /* LTR */
}
td.section.divider {
border-left: 1px dashed #ddd; /* LTR */
}
.node.teaser {
border-bottom: 1px dashed #ddd;
}
.submitted, .links {
color: #3f3f3f;
}
.comment {
border: 1px solid #d3d3d3;
}
.comment .title {
background: transparent url(../images/all/icon-comment.png) left center no-repeat; /* LTR */
}
blockquote, .messages {
background-color: #eee;
border: 1px solid #ccc;
}
.form-item label, .item-list .title {
color: #222;
}
div.admin-panel .body {
background-color: #f4f4f4;
}
div.admin-panel h3 {
color: #abc;
}
#site-slogan {
color: #000;
}
#search .form-text, #search .form-submit {
border: 1px solid #555;
}
#mission {
color: #535353;
border: solid 1px #ddd;
}
#breadcrumb, #breadcrumb a {
color: #1e201b !important;
}
#footer, #footer a {
color: #888 !important;
}
#footer ul.links li {
border-left: 1px solid #909090;
}
.by, .by a, .by a:hover {
color: #ddd !important;
}
#aggregator .feed-source {
background-color: #eee;
border: 1px solid #ccc;
}
#forum td.forum, #forum td.posts {
background-color: #eee;
}
#forum td.topics, #forum td.last-reply {
background-color: #ddd;
}
#forum td.statistics, #forum td.settings, #forum td.pager {
border: 1px solid #bbb;
}
#forum td.container {
background: #cdcdcd url(../images/all/forum-container.jpg) right top no-repeat; /* LTR */
}
#forum td.container .name a {
background: transparent url(../images/all/forum-link.png) left center no-repeat;
}
#profile .profile {
border: 1px solid #abc;
}
/* MENU & link STYLES */
ul li.leaf {
list-style-image: url(../images/all/menu-leaf.png);
}
ul li.expanded {
list-style-image: url(../images/all/menu-expanded.png);
}
ul li.collapsed {
list-style-image: url(../images/all/menu-collapsed.png); /* LTR */
}
#subnavlist a {
border: 1px solid #ddd;
color: #444 !important;
background-color: #eee;
}
#subnavlist li a:hover {
background-color: #dbdbdb;
}
#navlist2 a {
color: #888 !important;
}
#navlist2 a:hover, #navlist2 a.active,
#footer a:hover, #footer a.active {
color: #333 !important;
}
/* MODULE SPECIFIC STYLES */
.book-navigation .page-links {
border-top: 1px dashed #d3d3d3;
border-bottom: 1px dashed #d3d3d3;
}
.<API key> .arrow-up {
background: transparent url(../images/all/menu-up.png) no-repeat center center !important;
}
.<API key> .arrow-down {
background: transparent url(../images/all/menu-expanded.png) no-repeat center center !important;
}
.<API key> table {
border-top: 1px dashed #ddd !important;
border-left: 1px dashed #ddd !important;
}
.<API key> td {
border-right: 1px dashed #ddd !important;
border-bottom: 1px dashed #ddd !important;
background-color: transparent !important;
}
/* GRAPHICS CSS */
#top_bg {
background: transparent url(../images/fill_top.png) 0 100% repeat-x;
}
#top_left {
background: transparent url(../images/fill_top_left.png) 0 100% no-repeat;
}
#top_right {
background: transparent url(../images/fill_top_right.png) 100% 100% no-repeat;
}
h1, h2, h3 {
color: #777;
}
a, a:link,
.title, .title a,
.node .terms,
#aggregator .news-item .categories, #aggregator .source, #aggregator .age,
#forum td .name,
div.admin-panel .description {
color: #777;
}
.block.themed-block {
background: #fff url(../images/fill_block.png) 0 100% repeat-x;
border: 1px solid #ddd;
}
#navlinks ul li a, #navlist a {
background-color: #777;
color: #fff !important;
text-transform: uppercase;
font-family: "times new roman", sans-serif, Arial, Verdana, Helvetica;
}
#navlinks ul li a:hover, #navlist li a:hover {
color: #777 !important;
background-color: #dbdbdb;
}
/* DROP DOWN LI */
/* set li width & color */
#navlinks ul li.expanded ul li {
border-left: 1px solid #c4c4c4;
border-top: 1px solid #c4c4c4;
border-right: 1px solid #959595;
border-bottom: 1px solid #959595;
}
/* DROP DOWN Anchors */
/* first level */
#navlinks ul li.expanded a.expandfirst {
background: #777 url(../images/nav-down.png) no-repeat 7px 50%;
}
#navlinks ul li.expanded a.expandfirst:hover {
background: #dbdbdb url(../images/nav-down.png) no-repeat 7px 50%;
}
/* sublevels */
#navlinks ul li.expanded a {
background: #aaa;
}
#navlinks ul li ul li a:hover {
color: #fff !important;
background: #999;
}
#navlinks ul li.expanded a.expand,
#navlinks ul li.expanded ul li a.expand {
background: #aaa url(../images/nav-right.png) no-repeat 95% 9px;
}
#navlinks ul li ul li.expanded a.expand:hover {
background: #999 url(../images/nav-right.png) no-repeat 95% 9px;
} |
<?php
namespace FOF30\Model\DataModel\Exception;
use Exception;
defined('_JEXEC') or die;
class <API key> extends TreeInvalidLftRgt
{
public function __construct( $message = '', $code = 500, Exception $previous = null )
{
if (empty($message))
{
$message = \JText::_('<API key>');
}
parent::__construct( $message, $code, $previous );
}
} |
CREATE TABLE `issue_330` (
`a` int(11) DEFAULT NULL COMMENT 'issue_330 `alex`'
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
/*
* Graphics logic for the TRS80 model I, III and friends
*
* - Need to figure out how to interact with console switches
* - Need to add LNW80 graphics modes
*/
#include <kernel.h>
#include <kdata.h>
#include <tty.h>
#include <vt.h>
#include <graphics.h>
#include <devgfx.h>
#include "trs80.h"
__sfr __at 0x00 hrg_off;
__sfr __at 0x04 hrg_data;
__sfr __at 0x79 vdps;
__sfr __at 0x7C chromajs0;
__sfr __at 0x82 gfx_data;
__sfr __at 0x83 gfx_ctrl;
__sfr __at 0xEC le18_data;
__sfr __at 0xEF le18_ctrl;
__sfr __at 0xFF ioctrl;
uint8_t trs80_udg;
uint8_t has_hrg1;
uint8_t has_chroma; /* and thus 2 joystick ports */
uint8_t video_mode;
static uint8_t max_mode = 0;
static struct display trsdisplay[6] = {
/* Text mode */
{
0,
128, 48,
64, 16,
255, 255,
FMT_6PIXEL_128,
HW_UNACCEL,
GFX_MAPPABLE|GFX_MULTIMODE|GFX_TEXT,
1,
0
},
/* Tandy Graphics */
{
1,
640, 240,
640, 240,
255, 255,
FMT_MONO_WB,
HW_TRS80GFX,
GFX_MULTIMODE|GFX_MAPPABLE, /* No overlay control on Model 3 */
32,
0 /* For now lets just worry about map */
},
/* Microlabs Grafyx */
{
1,
512, 192,
512, 192,
255, 255,
FMT_MONO_WB,
HW_MICROLABS,
GFX_MULTIMODE|GFX_MAPPABLE,
12,
0
},
/* HRG1B */
{
1,
384, 192,
384, 192,
255, 255,
FMT_MONO_WB,
HW_HRG1B,
GFX_MULTIMODE|GFX_MAPPABLE|GFX_TEXT,
9,
0
},
/* CHROMAtrs */
{
1,
256, 192,
256, 192,
255, 255,
FMT_VDP,
HW_VDP_9918A,
GFX_MULTIMODE|GFX_MAPPABLE, /* We don't support it as a console yet */
16,
0
},
/* Lowe Electronics LE-18 */
{
1,
384, 192,
384, 192,
255, 255,
FMT_MONO_WB,
HW_LOWE_LE18,
GFX_MULTIMODE|GFX_MAPPABLE|GFX_TEXT,
16,
0
}
};
static struct videomap trsmap[6] = {
{
0,
0,
0x3C00,
0x0400, /* Directly mapped */
0, 0, /* No segmentation */
1, /* Standard spacing */
MAP_FBMEM_SIMPLE|MAP_FBMEM
},
/* Tandy board */
{
0,
0x80, /* I/O ports.. 80-83 + 8C-8E */
0, 0, /* Not mapped into main memory */
0, 0, /* No segmentation */
1, /* Standard spacing */
MAP_PIO
},
/* Microlabs */
{
0,
0xFF,
0x3C00, 0x0400,
0, 0,
1,
MAP_FBMEM|MAP_PIO
},
/* HRG1B */
{
0,
0x00, /* I/O ports.. 0-5 */
0, 0, /* Not mapped into main memory */
0, 0, /* No segmentation */
1, /* Standard spacing */
MAP_PIO
},
/* CHROMAtrs */
{
0,
0x78, /* I/O ports 0x78/79 */
0, 0,
0, 0,
1,
MAP_PIO /* VDP is I/O mapped */
},
/* Lowe Electronics LE-18 */
{
0,
0xEC, /* I/O ports 0xEC-0xEF */
0, 0,
0, 0,
1,
MAP_PIO /* VDP is I/O mapped */
}
};
static uint8_t displaymap[4] = {0, 0, 0, 0};
static int8_t udg_ioctl(uarg_t arg, char *ptr);
/* TODO: Arbitrate graphics between tty 1 and tty 2 */
int gfx_ioctl(uint8_t minor, uarg_t arg, char *ptr)
{
uint8_t m;
if (minor <= 2 && (arg == VTFONTINFO || arg == VTSETFONT || arg == VTSETUDG))
return udg_ioctl(arg, ptr);
if (minor > 2 || (arg >> 8 != 0x03))
return vt_ioctl(minor, arg, ptr);
switch(arg) {
case GFXIOC_GETINFO:
return uput(&trsdisplay[video_mode], ptr, sizeof(struct display));
case GFXIOC_GETMODE:
case GFXIOC_SETMODE:
m = ugetc(ptr);
if (m > max_mode)
break;
m = displaymap[m];
if (arg == GFXIOC_GETMODE)
return uput(&trsdisplay[m], ptr, sizeof(struct display));
video_mode = m;
/* Going back to text mode we need to turn off graphics cards. Going the
other way we let the applications handle it as they may want to do
memory wipes and the like first */
if (video_mode == 0) {
if (displaymap[1] == 1)
gfx_ctrl = 0;
else if (displaymap[1] == 2)
ioctrl = 0x20;
else if (displaymap[1] == 3)
hrg_off = 1;
else if (displaymap[1] == 5)
le18_ctrl = 0;
}
return 0;
case GFXIOC_UNMAP:
return 0;
/* Users can "map" 8) the framebuffer into their process and use the
card directly */
case GFXIOC_MAP:
return uput(&trsmap[video_mode], ptr, sizeof(struct videomap));
}
return -1;
}
void gfx_init(void)
{
if (trs80_model == TRS80_MODEL1 || trs80_model == VIDEOGENIE) {
/* HRG1B support. Might be good to also support 80-Grafix as a UDG
module */
if (hrg_data != 0xFF) { /* We ought to test more carefully */
max_mode = 1;
displaymap[1] = 3;
has_hrg1 = 1;
}
/* LE-18 */
if(trs80_model == VIDEOGENIE && le18_data != 0xFF) {
displaymap[++max_mode] = 5;
trsdisplay[5].mode = max_mode;
}
} else if (trs80_model == TRS80_MODEL3) {
/* The model 3 might have an 80-Grafix UDG card, or a Graphyx
or a Tandy card */
uint8_t *fb = (uint8_t *)0x3C00;
uint8_t c = *fb;
*fb = 128;
ioctrl = 0xB2;
if (*fb != 128) {
/* Hopeful */
*fb = 128;
if (*fb == 128) { /* 80 Grafix only has 6bit wide RAM but wants
the top bit set on writes.. */
displaymap[1] = 2;
max_mode = 1;
} /* else add UDG support FIXME */
}
ioctrl = 0x20;
*fb = c;
if (max_mode == 0 && gfx_data != 0xFF) {
max_mode = 1;
displaymap[1] = 1;
}
}
/* It's possible to have a CHROMAtrs and other adapters as it fits
on the external bus. 70-7C is also a common location for RTC clocks
which makes detection trickier. The clock will show 0 in the upper
bits, the joystick port will not */
if (vdps != 0xFF && (chromajs0 & 0xC0) == 0xC0) {
displaymap[++max_mode] = 4;
trsdisplay[4].mode = max_mode;
has_chroma = 1;
}
}
/*
* UDG drivers
*
* We don't currently address UDG fitted without lower case. That gets
* deeply weird because you get disjoint ranges with one bit magically
* invented by logic. For the UDG only ones we just halve the range, but
* for the PCG80 what about full font ?
*
* (The Tandy (Microfirma) one requires lowercase is fitted according
* to the manual)
*
* One other corner case to consider is that if you have no lower case
* we ought to requisition the UDG and load a font into it then use
* 128-159 for lower case.
*/
static struct fontinfo fonti[4] = {
{ 0, },
{ 0, 255, 0, 255, FONT_INFO_6X12P16 },
{ 128, 191, 128, 191, FONT_INFO_6X12P16 },
{ 128, 255, 128, 255, FONT_INFO_6X12P16 }
};
__sfr __at 130 trshg_nowrite;
__sfr __at 140 trshg_write;
__sfr __at 150 trshg_gfxoff;
__sfr __at 155 trshg_gfxon;
__sfr __at 0xFE pcg80;
__sfr __at 0xFF p80gfx;
static uint8_t old_pcg80;
static uint8_t old_p80gfx;
static uint8_t udgflag; /* So we know what fonts are loaded */
#define SOFTFONT_UDG 1
#define SOFTFONT_ALL 2
static void load_char_pcg80(uint8_t ch, uint8_t *cdata)
{
uint8_t bank = ch >> 6;
uint8_t *addr = (uint8_t *)0x3C00 + ((ch & 0x3F) << 4);
uint8_t i;
pcg80 = old_pcg80 | 0x60 | bank; /* Programming mode on */
for (i = 0; i < 16; i++)
*addr++ = *cdata++ << 1 | 0x80;
pcg80 = old_pcg80;
}
static void load_char_80gfx(uint8_t ch, uint8_t *cdata)
{
uint8_t *addr = (uint8_t *)0x3C00 + ((ch & 0x3F) << 4);
uint8_t i;
p80gfx = old_p80gfx | 0x60;
for (i = 0; i < 16; i++)
*addr++ = *cdata++ << 1 | 0x80;
p80gfx = old_p80gfx;
}
static void load_char_trs(uint8_t ch, uint8_t *cdata)
{
uint8_t *addr = (uint8_t *)0x3C00 + ((ch & 0x3F) << 4);
uint8_t i;
trshg_write = 1;
for (i = 0; i < 16; i++)
*addr++ = *cdata++ << 1 | 0x80;
trshg_nowrite = 1;
}
void (*load_char[4])(uint8_t, uint8_t *) = {
NULL,
load_char_pcg80,
load_char_80gfx,
load_char_trs,
};
static void udg_config(void)
{
switch(trs80_udg) {
case UDG_PCG80:
if (udgflag & SOFTFONT_UDG)
old_pcg80 |= 0x80; /* 128-255 soft font */
if (udgflag & SOFTFONT_ALL)
old_pcg80 |= 0x88;
pcg80 = old_pcg80 | 0x20;
break;
case UDG_80GFX:
if (udgflag & SOFTFONT_UDG)
old_p80gfx |= 0x80;
p80gfx = old_p80gfx | 0x20;
break;
case UDG_MICROFIRMA:
if (udgflag & SOFTFONT_UDG)
trshg_gfxon = 1;
break;
}
}
static int8_t udg_ioctl(uarg_t arg, char *ptr)
{
uint8_t base = fonti[trs80_udg].udg_low;
uint8_t limit = fonti[trs80_udg].udg_high;
int i;
/* Not supported */
if (trs80_udg == UDG_NONE) {
udata.u_error = EOPNOTSUPP;
return -1;
}
/* No lower case available */
if (!video_lower)
limit = 191;
switch(arg) {
case VTFONTINFO:
return uput(fonti + trs80_udg, ptr, sizeof(struct fontinfo));
case VTSETFONT:
base = fonti[trs80_udg].font_low;
limit = fonti[trs80_udg].font_high;
/* Fall through */
case VTSETUDG:
for (i = base; i <= limit; i++) {
uint8_t c[16];
if (uget(c, ptr, 16) == -1)
return -1;
ptr += 16;
load_char[trs80_udg](i, c);
}
if (arg == VTSETUDG)
udgflag |= SOFTFONT_UDG;
else
udgflag |= SOFTFONT_ALL;
udg_config();
return 0;
}
return -1;
} |
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/netfilter_bridge.h>
#include <linux/netfilter/xt_physdev.h>
#include <linux/netfilter/x_tables.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Bart De Schuymer <bdschuym@pandora.be>");
MODULE_DESCRIPTION("Xtables: Bridge physical device match");
MODULE_ALIAS("ipt_physdev");
MODULE_ALIAS("ip6t_physdev");
static bool
physdev_mt(const struct sk_buff *skb, struct xt_action_param *par)
{
static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long))));
const struct xt_physdev_info *info = par->matchinfo;
unsigned long ret;
const char *indev, *outdev;
const struct nf_bridge_info *nf_bridge;
if (!(nf_bridge = skb->nf_bridge)) {
if ((info->bitmask & <API key>) &&
!(info->invert & <API key>))
return false;
if ((info->bitmask & XT_PHYSDEV_OP_ISIN) &&
!(info->invert & XT_PHYSDEV_OP_ISIN))
return false;
if ((info->bitmask & XT_PHYSDEV_OP_ISOUT) &&
!(info->invert & XT_PHYSDEV_OP_ISOUT))
return false;
if ((info->bitmask & XT_PHYSDEV_OP_IN) &&
!(info->invert & XT_PHYSDEV_OP_IN))
return false;
if ((info->bitmask & XT_PHYSDEV_OP_OUT) &&
!(info->invert & XT_PHYSDEV_OP_OUT))
return false;
return true;
}
if ((info->bitmask & <API key>) &&
(!!(nf_bridge->mask & BRNF_BRIDGED) ^
!(info->invert & <API key>)))
return false;
if ((info->bitmask & XT_PHYSDEV_OP_ISIN &&
(!nf_bridge->physindev ^ !!(info->invert & XT_PHYSDEV_OP_ISIN))) ||
(info->bitmask & XT_PHYSDEV_OP_ISOUT &&
(!nf_bridge->physoutdev ^ !!(info->invert & XT_PHYSDEV_OP_ISOUT))))
return false;
if (!(info->bitmask & XT_PHYSDEV_OP_IN))
goto match_outdev;
indev = nf_bridge->physindev ? nf_bridge->physindev->name : nulldevname;
ret = <API key>(indev, info->physindev, info->in_mask);
if (!ret ^ !(info->invert & XT_PHYSDEV_OP_IN))
return false;
match_outdev:
if (!(info->bitmask & XT_PHYSDEV_OP_OUT))
return true;
outdev = nf_bridge->physoutdev ?
nf_bridge->physoutdev->name : nulldevname;
ret = <API key>(outdev, info->physoutdev, info->out_mask);
return (!!ret ^ !(info->invert & XT_PHYSDEV_OP_OUT));
}
static int physdev_mt_check(const struct xt_mtchk_param *par)
{
const struct xt_physdev_info *info = par->matchinfo;
if (!(info->bitmask & XT_PHYSDEV_OP_MASK) ||
info->bitmask & ~XT_PHYSDEV_OP_MASK)
return -EINVAL;
if (info->bitmask & XT_PHYSDEV_OP_OUT &&
(!(info->bitmask & <API key>) ||
info->invert & <API key>) &&
par->hook_mask & ((1 << NF_INET_LOCAL_OUT) |
(1 << NF_INET_FORWARD) | (1 << <API key>))) {
pr_info("using --physdev-out in the OUTPUT, FORWARD and "
"POSTROUTING chains for non-bridged traffic is not "
"supported anymore.\n");
if (par->hook_mask & (1 << NF_INET_LOCAL_OUT))
return -EINVAL;
}
return 0;
}
static struct xt_match physdev_mt_reg __read_mostly = {
.name = "physdev",
.revision = 0,
.family = NFPROTO_UNSPEC,
.checkentry = physdev_mt_check,
.match = physdev_mt,
.matchsize = sizeof(struct xt_physdev_info),
.me = THIS_MODULE,
};
static int __init physdev_mt_init(void)
{
return xt_register_match(&physdev_mt_reg);
}
static void __exit physdev_mt_exit(void)
{
xt_unregister_match(&physdev_mt_reg);
}
module_init(physdev_mt_init);
module_exit(physdev_mt_exit); |
#pragma once
#include <wx/dialog.h>
#include "Core/ActionReplay.h"
class wxTextCtrl;
class ARCodeAddEdit final : public wxDialog
{
public:
ARCodeAddEdit(ActionReplay::ARCode code, wxWindow* parent, wxWindowID id = wxID_ANY,
const wxString& title = _("Edit ActionReplay Code"),
const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize,
long style = <API key>);
const ActionReplay::ARCode& GetCode() const { return m_code; }
private:
void CreateGUI();
void SaveCheatData(wxCommandEvent& event);
ActionReplay::ARCode m_code;
wxTextCtrl* m_txt_cheat_name;
wxTextCtrl* m_cheat_codes;
}; |
#ifndef NCMPCPP_HELP_H
#define NCMPCPP_HELP_H
#include "actions.h"
#include "interfaces.h"
#include "screen.h"
struct Help: Screen<NC::Scrollpad>, Tabbable
{
Help();
virtual void resize() OVERRIDE;
virtual void switchTo() OVERRIDE;
virtual std::wstring title() OVERRIDE;
virtual ScreenType type() OVERRIDE { return ScreenType::Help; }
virtual void update() OVERRIDE { }
virtual void enterPressed() OVERRIDE { }
virtual bool isLockable() OVERRIDE { return true; }
virtual bool isMergable() OVERRIDE { return true; }
};
extern Help *myHelp;
#endif // NCMPCPP_HELP_H |
package org.graalvm.compiler.hotspot.amd64;
import static org.graalvm.compiler.core.common.LocationIdentity.any;
import static org.graalvm.compiler.hotspot.HotSpotBackend.EXCEPTION_HANDLER;
import static org.graalvm.compiler.hotspot.HotSpotBackend.<API key>;
import static org.graalvm.compiler.hotspot.HotSpotBackend.Options.PreferGraalStubs;
import static org.graalvm.compiler.hotspot.<API key>.JUMP_ADDRESS;
import static org.graalvm.compiler.hotspot.<API key>.RegisterEffect.PRESERVES_REGISTERS;
import static org.graalvm.compiler.hotspot.<API key>.Transition.LEAF;
import static org.graalvm.compiler.hotspot.<API key>.Transition.LEAF_NOFP;
import static org.graalvm.compiler.hotspot.HotSpotHostBackend.<API key>;
import static org.graalvm.compiler.hotspot.HotSpotHostBackend.<API key>;
import static org.graalvm.compiler.hotspot.replacements.CRC32Substitutions.UPDATE_BYTES_CRC32;
import static jdk.vm.ci.amd64.AMD64.rax;
import static jdk.vm.ci.amd64.AMD64.rdx;
import static jdk.vm.ci.hotspot.<API key>.NativeCall;
import static jdk.vm.ci.meta.Value.ILLEGAL;
import org.graalvm.compiler.core.common.LIRKind;
import org.graalvm.compiler.core.common.spi.<API key>;
import org.graalvm.compiler.hotspot.<API key>;
import org.graalvm.compiler.hotspot.<API key>;
import org.graalvm.compiler.hotspot.<API key>;
import org.graalvm.compiler.hotspot.meta.<API key>;
import org.graalvm.compiler.hotspot.meta.HotSpotProviders;
import org.graalvm.compiler.word.WordTypes;
import jdk.vm.ci.code.CallingConvention;
import jdk.vm.ci.code.CodeCacheProvider;
import jdk.vm.ci.code.RegisterValue;
import jdk.vm.ci.code.TargetDescription;
import jdk.vm.ci.hotspot.<API key>;
import jdk.vm.ci.meta.MetaAccessProvider;
import jdk.vm.ci.meta.PlatformKind;
import jdk.vm.ci.meta.Value;
public class <API key> extends <API key> {
public static final <API key> ARITHMETIC_SIN_STUB = new <API key>("arithmeticSinStub", double.class, double.class);
public static final <API key> ARITHMETIC_COS_STUB = new <API key>("arithmeticCosStub", double.class, double.class);
public static final <API key> ARITHMETIC_TAN_STUB = new <API key>("arithmeticTanStub", double.class, double.class);
public static final <API key> ARITHMETIC_EXP_STUB = new <API key>("arithmeticExpStub", double.class, double.class);
public static final <API key> ARITHMETIC_POW_STUB = new <API key>("arithmeticPowStub", double.class, double.class, double.class);
public static final <API key> ARITHMETIC_LOG_STUB = new <API key>("arithmeticLogStub", double.class, double.class);
public static final <API key> <API key> = new <API key>("arithmeticLog10Stub", double.class, double.class);
private final Value[] <API key>;
public <API key>(<API key> jvmciRuntime, <API key> runtime, MetaAccessProvider metaAccess, CodeCacheProvider codeCache,
WordTypes wordTypes, Value[] <API key>) {
super(jvmciRuntime, runtime, metaAccess, codeCache, wordTypes);
this.<API key> = <API key>;
}
@Override
public void initialize(HotSpotProviders providers) {
<API key> config = runtime.getVMConfig();
TargetDescription target = providers.getCodeCache().getTarget();
PlatformKind word = target.arch.getWordKind();
// The calling convention for the exception handler stub is (only?) defined in
// <API key>::<API key>()
// in <API key>.cpp around line 1923
RegisterValue exception = rax.asValue(LIRKind.reference(word));
RegisterValue exceptionPc = rdx.asValue(LIRKind.value(word));
CallingConvention exceptionCc = new CallingConvention(0, ILLEGAL, exception, exceptionPc);
register(new <API key>(EXCEPTION_HANDLER, 0L, PRESERVES_REGISTERS, LEAF_NOFP, exceptionCc, null, NOT_REEXECUTABLE, any()));
register(new <API key>(<API key>, JUMP_ADDRESS, PRESERVES_REGISTERS, LEAF_NOFP, exceptionCc, null, NOT_REEXECUTABLE, any()));
if (PreferGraalStubs.getValue()) {
link(new <API key>(providers, target, config, registerStubCall(<API key>, REEXECUTABLE, LEAF, NO_LOCATIONS)));
link(new <API key>(providers, target, config, registerStubCall(<API key>, REEXECUTABLE, LEAF, NO_LOCATIONS)));
}
link(new AMD64MathStub(ARITHMETIC_LOG_STUB, providers, registerStubCall(ARITHMETIC_LOG_STUB, REEXECUTABLE, LEAF, NO_LOCATIONS)));
link(new AMD64MathStub(<API key>, providers, registerStubCall(<API key>, REEXECUTABLE, LEAF, NO_LOCATIONS)));
link(new AMD64MathStub(ARITHMETIC_SIN_STUB, providers, registerStubCall(ARITHMETIC_SIN_STUB, REEXECUTABLE, LEAF, NO_LOCATIONS)));
link(new AMD64MathStub(ARITHMETIC_COS_STUB, providers, registerStubCall(ARITHMETIC_COS_STUB, REEXECUTABLE, LEAF, NO_LOCATIONS)));
link(new AMD64MathStub(ARITHMETIC_TAN_STUB, providers, registerStubCall(ARITHMETIC_TAN_STUB, REEXECUTABLE, LEAF, NO_LOCATIONS)));
link(new AMD64MathStub(ARITHMETIC_EXP_STUB, providers, registerStubCall(ARITHMETIC_EXP_STUB, REEXECUTABLE, LEAF, NO_LOCATIONS)));
link(new AMD64MathStub(ARITHMETIC_POW_STUB, providers, registerStubCall(ARITHMETIC_POW_STUB, REEXECUTABLE, LEAF, NO_LOCATIONS)));
if (config.useCRC32Intrinsics) {
// This stub does callee saving
registerForeignCall(UPDATE_BYTES_CRC32, config.<API key>, NativeCall, PRESERVES_REGISTERS, LEAF_NOFP, NOT_REEXECUTABLE, any());
}
super.initialize(providers);
}
@Override
public Value[] <API key>() {
return <API key>;
}
} |
<?php
namespace Drupal\Tests\views\Functional;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Tests\Traits\Core\CronRunTrait;
/**
* Tests search integration filters.
*
* @group views
*/
class <API key> extends ViewTestBase {
use CronRunTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['node', 'search'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = ['test_search'];
/**
* Tests search integration.
*/
public function <API key>() {
// Create a content type.
$type = $this-><API key>();
// Add three nodes, one containing the word "pizza", one containing
// "sandwich", and one containing "cola is good with pizza". Make the
// second node link to the first.
$node['title'] = 'pizza';
$node['body'] = [['value' => 'pizza']];
$node['type'] = $type->id();
$this->drupalCreateNode($node);
$this->drupalGet('node/1');
$node_url = $this->getUrl();
$node['title'] = 'sandwich';
$node['body'] = [['value' => 'sandwich with a <a href="' . $node_url . '">link to first node</a>']];
$this->drupalCreateNode($node);
$node['title'] = 'cola';
$node['body'] = [['value' => 'cola is good with pizza']];
$node['type'] = $type->id();
$this->drupalCreateNode($node);
// Run cron so that the search index tables are updated.
$this->cronRun();
// Test the various views filters by visiting their pages.
// These are in the test view 'test_search', and they just display the
// titles of the nodes in the result, as links.
// Page with a keyword filter of 'pizza'.
$this->drupalGet('test-filter');
$this->assertLink('pizza');
$this->assertNoLink('sandwich');
$this->assertLink('cola');
// Page with a keyword argument, various argument values.
// Verify that the correct nodes are shown, and only once.
$this->drupalGet('test-arg/pizza');
$this->assertOneLink('pizza');
$this->assertNoLink('sandwich');
$this->assertOneLink('cola');
$this->drupalGet('test-arg/sandwich');
$this->assertNoLink('pizza');
$this->assertOneLink('sandwich');
$this->assertNoLink('cola');
$this->drupalGet('test-arg/pizza OR sandwich');
$this->assertOneLink('pizza');
$this->assertOneLink('sandwich');
$this->assertOneLink('cola');
$this->drupalGet('test-arg/pizza sandwich OR cola');
$this->assertNoLink('pizza');
$this->assertNoLink('sandwich');
$this->assertOneLink('cola');
$this->drupalGet('test-arg/cola pizza');
$this->assertNoLink('pizza');
$this->assertNoLink('sandwich');
$this->assertOneLink('cola');
$this->drupalGet('test-arg/"cola is good"');
$this->assertNoLink('pizza');
$this->assertNoLink('sandwich');
$this->assertOneLink('cola');
// Test sorting.
$node = [
'title' => "Drupal's search rocks.",
'type' => $type->id(),
];
$this->drupalCreateNode($node);
$node['title'] = "Drupal's search rocks <em>really</em> rocks!";
$this->drupalCreateNode($node);
$this->cronRun();
$this->drupalGet('test-arg/rocks');
$xpath = '//div[@class="views-row"]//a';
/** @var \Behat\Mink\Element\NodeElement[] $results */
$results = $this->xpath($xpath);
$this->assertEqual($results[0]->getText(), "Drupal's search rocks <em>really</em> rocks!");
$this->assertEqual($results[1]->getText(), "Drupal's search rocks.");
$this->assertEscaped("Drupal's search rocks <em>really</em> rocks!");
// Test sorting with another set of titles.
$node = [
'title' => "Testing one two two two",
'type' => $type->id(),
];
$this->drupalCreateNode($node);
$node['title'] = "Testing one one one";
$this->drupalCreateNode($node);
$this->cronRun();
$this->drupalGet('test-arg/one');
$xpath = '//div[@class="views-row"]//a';
/** @var \SimpleXMLElement[] $results */
$results = $this->xpath($xpath);
$this->assertEqual($results[0]->getText(), "Testing one one one");
$this->assertEqual($results[1]->getText(), "Testing one two two two");
}
/**
* Asserts that exactly one link exists with the given text.
*
* @param string $label
* Link label to assert.
*
* @return bool
* TRUE if the assertion succeeded, FALSE otherwise.
*/
protected function assertOneLink($label) {
$links = $this->xpath('//a[normalize-space(text())=:label]', [':label' => $label]);
$message = new FormattableMarkup('Link with label %label found once.', ['%label' => $label]);
return $this->assert(isset($links[0]) && !isset($links[1]), $message);
}
} |
// file name : pptable.cpp
// F i l e
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
#include "pptable.h"
#include <wx/tokenzr.h>
#include <set>
#include "CxxLexerAPI.h"
#include "CxxScannerTokens.h"
#include <algorithm>
bool IsWordChar(const wxString& s, int strSize)
{
if(strSize) {
return s.find_first_of(wxT("<API key>")) !=
wxString::npos;
} else {
return s.find_first_of(wxT("<API key>")) != wxString::npos;
}
}
bool IsWordCharA(char c, int strSize)
{
if(strSize) {
return ((c >= 97 && c <= 122) ||
(c >= 65 && c <= 90) ||
(c >= 48 && c <= 57) ||
(c == '_'));
} else {
return ((c >= 97 && c <= 122) ||
(c >= 65 && c <= 90) ||
(c == '_'));
}
}
std::string ReplaceWordA(const std::string& str, const std::string& word, const std::string& replaceWith)
{
char currChar;
char nextChar;
std::string currentWord;
std::string output;
output.reserve(str.length() * 2);
for(size_t i = 0; i < str.length(); i++) {
// Look ahead
if(str.length() > i + 1) {
nextChar = str[i + 1];
} else {
// we are at the end of buffer
nextChar = '\0';
}
currChar = str[i];
if(!IsWordCharA(currChar, currentWord.length())) {
output += str[i];
currentWord.clear();
} else {
currentWord += currChar;
if(IsWordCharA(nextChar, currentWord.length())) {
// do nothing
} else if(!IsWordCharA(nextChar, currentWord.length()) && currentWord == word) {
output += replaceWith;
currentWord.clear();
} else {
output += currentWord;
currentWord.clear();
}
}
}
return output;
}
// Helper string find metho
wxString ReplaceWord(const wxString& str, const wxString& word, const wxString& replaceWith)
{
wxString currChar;
wxString nextChar;
wxString currentWord;
wxString output;
for(size_t i = 0; i < str.Length(); i++) {
// Look ahead
if(str.Length() > i + 1) {
nextChar = str[i + 1];
} else {
// we are at the end of buffer
nextChar = wxT('\0');
}
currChar = str[i];
if(!IsWordChar(currChar, currentWord.Length())) {
output << str[i];
currentWord.Clear();
} else {
currentWord << currChar;
if(IsWordChar(nextChar, currentWord.Length())) {
// do nothing
} else if(!IsWordChar(nextChar, currentWord.Length()) && currentWord == word) {
output << replaceWith;
currentWord.Clear();
} else {
output << currentWord;
currentWord.Clear();
}
}
}
return output;
}
void TokenizeWords(const wxString& str, std::list<wxString>& outputList)
{
outputList.clear();
Scanner_t scanner = ::LexerNew(str);
if(scanner) {
CxxLexerToken token;
while(::LexerNext(scanner, token)) {
if(token.type == T_IDENTIFIER || token.type == T_PP_IDENTIFIER) {
outputList.push_back(token.text);
// put a limit or we might run into memory issues
if(outputList.size() >= 1000) {
break;
}
}
}
// Destroy the lexer
::LexerDestroy(&scanner);
}
}
static PPTable* ms_instance = NULL;
void PPToken::processArgs(const wxString& argsList)
{
args = wxStringTokenize(argsList, wxT(","), wxTOKEN_STRTOK);
// replace all occurances of 'arg' with %1, %2 etc
for(size_t i = 0; i < args.GetCount(); i++) {
wxString replaceWith = wxString::Format(wxT("%%%d"), (int)i);
std::string res = ReplaceWordA(
replacement.To8BitData().data(), args.Item(i).To8BitData().data(), replaceWith.To8BitData().data());
if(res.empty()) {
replacement.clear();
} else {
replacement = wxString::From8BitData(res.c_str());
}
}
}
void PPToken::print(wxFFile& fp)
{
wxString buff;
buff << name << wxT("(") << (flags & IsFunctionLike) << wxT(")") << wxT("=") << replacement << wxT("\n");
fp.Write(buff);
}
wxString PPToken::fullname() const
{
wxString fullname;
fullname << name;
if(flags & IsFunctionLike) {
fullname << wxT("(");
for(size_t i = 0; i < args.size(); i++) {
fullname << wxT("%") << i << wxT(",");
}
if(args.size()) {
fullname.RemoveLast();
}
fullname << wxT(")");
}
return fullname;
}
void PPToken::squeeze()
{
std::set<wxString> <API key>;
// perform the squeeze 5 times max
for(size_t count = 0; count < 5; count++) {
bool modified(false);
// get list of possible macros in the replacement
std::list<wxString> tmpWords;
TokenizeWords(replacement, tmpWords);
wxArrayString words;
if(tmpWords.empty()) break;
// Make room for at least tmpWords.size() items
words.Alloc(tmpWords.size());
// make sure that a word is not been replaced more than once
// this will avoid recursion
// an example (taken from qglobal.h of the Qt library):
// #define qDebug QT_NO_QDEBUG_MACRO
// #define QT_NO_QDEBUG_MACRO if(1); else qDebug
std::for_each(tmpWords.begin(), tmpWords.end(), [&](const wxString& word){
if(<API key>.count(word) == 0) {
<API key>.insert(word);
words.Add(word);
}
});
for(size_t i = 0; i < words.size(); i++) {
PPToken tok = PPTable::Instance()->Token(words.Item(i));
if(tok.flags & IsValid) {
if(tok.flags & IsFunctionLike) {
int where = replacement.Find(words.Item(i));
if(where != wxNOT_FOUND) {
wxString initList;
wxArrayString initListArr;
if(readInitList(replacement, where + words.Item(i).Length(), initList, initListArr)) {
tok.expandOnce(initListArr);
replacement.Remove(where, words.Item(i).Length() + initList.Length());
tok.replacement.Replace(wxT("##"), wxT(""));
replacement.insert(where, tok.replacement);
modified = true;
}
}
} else {
if(replacement.Replace(words.Item(i), tok.replacement)) {
modified = true;
}
}
}
}
if(!modified) break;
}
replacement.Replace(wxT("##"), wxT(""));
}
bool
PPToken::readInitList(const std::string& in, size_t from, std::string& initList, std::vector<std::string>& initListArr)
{
if(in.length() < from) {
return false;
}
std::string tmpString = in.substr(from);
size_t start = tmpString.find('(');
if(start == std::string::npos) {
return false;
}
// skip the open brace
tmpString = tmpString.substr(start + 1);
for(size_t i = 0; i < start; i++) {
initList += " ";
}
initList += "(";
std::string word;
int depth(1);
for(size_t i = 0; i < tmpString.length(); i++) {
char ch = tmpString[i];
initList += ch;
switch(ch) {
case ')':
depth
if(depth == 0) {
initListArr.push_back(word);
return true;
} else {
word += ch;
}
break;
case '(':
depth++;
word += ch;
break;
case ',':
if(depth == 1) {
initListArr.push_back(word);
word.clear();
} else {
word += ch;
}
break;
default:
word += ch;
break;
}
}
return false;
}
bool PPToken::readInitList(const wxString& in, int from, wxString& initList, wxArrayString& initListArr)
{
// sanity
if(in.length() > 100) return false;
if((int)in.Length() < from) {
return false;
}
wxString tmpString = in.Mid(from);
int start = tmpString.Find(wxT("("));
if(start == wxNOT_FOUND) {
return false;
}
tmpString = tmpString.Mid(start + 1);
for(size_t i = 0; i < (size_t)start; i++) {
initList << wxT(" ");
}
initList << wxT("(");
wxString word;
int depth(1);
for(size_t i = 0; i < tmpString.Length(); i++) {
wxChar ch = tmpString[i];
initList << ch;
switch(ch) {
case wxT(')'):
depth
if(depth == 0) {
initListArr.Add(word);
return true;
} else {
word << ch;
}
break;
case wxT('('):
depth++;
word << ch;
break;
case wxT(','):
if(depth == 1) {
initListArr.Add(word);
word.Clear();
} else {
word << ch;
}
break;
default:
word << ch;
break;
}
}
return false;
}
void PPToken::expandOnce(const wxArrayString& initList)
{
if(initList.size() != args.size()) return;
for(size_t i = 0; i < args.size(); i++) {
wxString placeHolder;
placeHolder << wxT("%") << i;
wxString replaceWith = initList.Item(i);
replaceWith.Trim().Trim(false);
if(replaceWith.Contains(placeHolder)) continue;
replacement.Replace(placeHolder, initList.Item(i));
}
}
wxString PPToken::signature() const
{
wxString sig;
if(flags & IsFunctionLike) {
sig << wxT("(");
for(size_t i = 0; i < args.size(); i++) {
sig << wxT("%") << i << wxT(",");
}
if(args.size()) {
sig.RemoveLast();
}
sig << wxT(")");
}
return sig;
}
PPTable::PPTable() {}
PPTable::~PPTable() {}
PPTable* PPTable::Instance()
{
if(ms_instance == NULL) {
ms_instance = new PPTable();
}
return ms_instance;
}
void PPTable::Release()
{
if(ms_instance) {
delete ms_instance;
}
ms_instance = NULL;
}
PPToken PPTable::Token(const wxString& name)
{
std::map<wxString, PPToken>::iterator iter = m_table.find(name);
if(iter == m_table.end()) {
return PPToken();
}
return iter->second;
}
void PPTable::Add(const PPToken& token)
{
if(token.name.IsEmpty()) return;
wxString name = token.name;
name.Trim().Trim(false);
std::map<wxString, PPToken>::iterator iter = m_table.find(name);
if(iter == m_table.end())
m_table[name] = token;
else {
// if the new token's replacement is empty and the current one is NOT empty,
// replace the two (we prefer empty replacements)
if(iter->second.flags & PPToken::IsOverridable && !iter->second.replacement.IsEmpty() &&
token.replacement.IsEmpty()) {
m_table[name] = token;
}
}
}
void PPTable::AddUsed(const wxString& name)
{
if(name.IsEmpty()) {
return;
}
m_namesUsed.insert(name);
}
void PPTable::Print(wxFFile& fp)
{
std::map<wxString, PPToken>::iterator iter = m_table.begin();
for(; iter != m_table.end(); iter++) {
iter->second.print(fp);
}
}
bool PPTable::Contains(const wxString& name)
{
std::map<wxString, PPToken>::iterator iter = m_table.find(name);
return iter != m_table.end();
}
wxString PPTable::Export()
{
wxString table;
std::map<wxString, PPToken>::iterator iter = m_table.begin();
for(; iter != m_table.end(); iter++) {
iter->second.squeeze();
wxString replacement = iter->second.replacement;
replacement.Trim().Trim(false);
// remove extra whitespaces
while(replacement.Replace(wxT(" "), wxT(" "))) {
}
if(replacement.IsEmpty()) {
table << iter->second.fullname() << wxT("\n");
} else if(iter->second.flags & PPToken::IsFunctionLike) {
table << iter->second.fullname() << wxT("=") << replacement << wxT("\n");
} else {
// macros with replacement but they are not in a form of a function
// we take only macros that thier replacement is not a number
long v(-1);
if(!replacement.ToLong(&v) && !replacement.ToLong(&v, 8) && !replacement.ToLong(&v, 16) &&
replacement.find(wxT('"')) == wxString::npos && !replacement.StartsWith(wxT("0x"))) {
table << iter->second.fullname() << wxT("=") << replacement << wxT("\n");
}
}
}
return table;
}
void PPTable::Squeeze()
{
std::map<wxString, PPToken>::iterator iter = m_table.begin();
for(; iter != m_table.end(); iter++) {
m_table[iter->first].squeeze();
}
}
void PPTable::Clear() { m_table.clear(); }
void PPTable::ClearNamesUsed() { m_namesUsed.clear(); }
bool CLReplacePattern(const wxString& in, const wxString& pattern, const wxString& replaceWith, wxString& outStr)
{
int where = pattern.Find(wxT("%0"));
if(where != wxNOT_FOUND) {
wxString replacement(replaceWith);
// a patterened expression
wxString searchFor = pattern.BeforeFirst(wxT('('));
where = in.Find(searchFor);
if(where == wxNOT_FOUND) {
return false;
}
wxString initList;
wxArrayString initListArr;
if(PPToken::readInitList(in, searchFor.Length() + where, initList, initListArr) == false) return false;
outStr = in;
// update the 'replacement' with the actual values ( replace %0..%n)
for(size_t i = 0; i < initListArr.size(); i++) {
wxString placeHolder;
placeHolder << wxT("%") << i;
replacement.Replace(placeHolder, initListArr.Item(i));
}
outStr.Remove(where, searchFor.Length() + initList.Length());
outStr.insert(where, replacement);
return true;
} else {
if(in.Find(pattern) == wxNOT_FOUND) {
return false;
}
// simple replacement
outStr = ReplaceWord(in, pattern, replaceWith);
return outStr != in;
}
}
std::string replacement;
bool CLReplacePatternA(const std::string& in, const CLReplacement& repl, std::string& outStr)
{
if(repl.is_compound) {
size_t where = in.find(repl.searchFor);
if(where == std::string::npos) return false;
std::string initList;
std::vector<std::string> initListArr;
if(PPToken::readInitList(in, repl.searchFor.length() + where, initList, initListArr) == false) return false;
// update the 'replacement' with the actual values ( replace %0..%n)
replacement = repl.replaceWith;
char placeHolder[4];
for(size_t i = 0; i < initListArr.size(); i++) {
memset(placeHolder, 0, sizeof(placeHolder));
sprintf(placeHolder, "%%%d", (int)i);
size_t pos = replacement.find(placeHolder);
const std::string& init = initListArr[i];
while(pos != std::string::npos) {
replacement.replace(pos, strlen(placeHolder), init.c_str());
// search for the next match
pos = replacement.find(placeHolder, pos + 1);
}
}
outStr = in;
where = outStr.find(repl.searchFor);
if(where == std::string::npos) return false;
outStr.replace(where, repl.searchFor.length() + initList.length(), replacement);
return true;
} else {
size_t where = in.find(repl.searchFor);
if(where == std::string::npos) {
return false;
}
outStr = ReplaceWordA(in, repl.searchFor, repl.replaceWith);
// outStr = in;
// outStr.replace(where, repl.searchFor.length(), repl.replaceWith);
// simple replacement
return outStr != in;
}
}
void CLReplacement::construct(const std::string& pattern, const std::string& replacement)
{
is_ok = true;
full_pattern = pattern;
is_compound = full_pattern.find("%0") != std::string::npos;
if(is_compound) {
// a patterened expression
replaceWith = replacement;
size_t where = pattern.find('(');
if(where == std::string::npos) {
is_ok = false;
return;
}
searchFor = pattern.substr(0, where);
if(searchFor.empty()) {
is_ok = false;
return;
}
} else {
// simple Key=Value pair
replaceWith = replacement;
searchFor = full_pattern;
}
} |
<script>
(function() {
(function (i, s, o, g, r, a, m) {
i['<API key>'] = r;
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date();
a = s.createElement(o),
m = s.<API key>(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://google-analytics.com/analytics.js', 'ga');
ga('create', '<?php echo esc_attr( $data[ Ga_Admin::<API key> ] ); ?>', 'auto');
ga('send', 'pageview');
})();
</script> |
#ifndef _GC_IntervalItem_h
#define _GC_IntervalItem_h 1
#include "GoldenCheetah.h"
#include "RideItem.h"
#include "RideItem.h"
#include <QtGui>
#include <QDialog>
#include <QLabel>
#include <QLineEdit>
class IntervalItem
{
public:
// constructors and accessors
IntervalItem(const RideItem *, QString, double, double, double, double, int, QColor, RideFileInterval::IntervalType);
IntervalItem();
// ride item we are in
RideItem* rideItem() { return rideItem_; }
RideItem* rideItem_;
// set from other
void setFrom(IntervalItem &other);
// change basic values, will also apply to ridefile
void setValues(QString name, double duration1, double duration2,
double distance1, double distance2);
// is this interval currently selected ?
bool selected;
// access the metric value
double getForSymbol(QString name, bool useMetricUnits=true);
// as a well formatted string
QString getStringForSymbol(QString name, bool useMetricUnits=true);
// interval details
QString name; // name
RideFileInterval::IntervalType type; // type User, Hill etc
double start, stop; // by Time
double startKM, stopKM; // by Distance
int displaySequence; // order to display on ride plots
QColor color; // color to use on plots that differentiate by color
QUuid route; // the route this interval is for
// order to show on plot
void setDisplaySequence(int seq) { displaySequence = seq; }
// precomputed metrics
void refresh();
QVector<double> metrics_;
QVector<double> &metrics() { return metrics_; }
// extracted sample data
RideFileInterval *rideInterval;
// used by qSort()
bool operator< (IntervalItem right) const {
return (start < right.start);
}
};
class <API key> : public QDialog
{
Q_OBJECT
G_OBJECT
public:
<API key>(QString &, QWidget *);
public slots:
void applyClicked();
void cancelClicked();
private:
QString &string;
QPushButton *applyButton, *cancelButton;
QLineEdit *nameEdit;
};
class ColorButton;
class EditIntervalDialog : public QDialog
{
Q_OBJECT
G_OBJECT
public:
EditIntervalDialog(QWidget *, IntervalItem &);
public slots:
void applyClicked();
void cancelClicked();
private:
IntervalItem &interval;
QPushButton *applyButton, *cancelButton;
QLineEdit *nameEdit;
QTimeEdit *fromEdit, *toEdit;
ColorButton *colorEdit;
};
#endif // _GC_IntervalItem_h |
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/smp.h>
#include <linux/completion.h>
#include <linux/mfd/dbx500-prcmu.h>
#include <asm/cacheflush.h>
#include <asm/smp_plat.h>
#include <mach/context.h>
#include <mach/suspend.h>
#include "pm/cpuidle_dbg.h"
extern volatile int pen_release;
static DECLARE_COMPLETION(cpu_killed);
static inline void <API key>(unsigned int cpu)
{
ux500_ci_dbg_unplug(cpu);
flush_cache_all();
for (;;) {
<API key>();
<API key>();
<API key>(false);
<API key>();
<API key>();
if (pen_release == cpu_logical_map(cpu)) {
/*
* OK, proper wakeup, we're done
*/
break;
}
}
ux500_ci_dbg_plug(cpu);
}
int platform_cpu_kill(unsigned int cpu)
{
int status;
status = <API key>(&cpu_killed, 5000);
/* switch off CPU1 in case of x540 */
status |= prcmu_unplug_cpu1();
return status;
}
/*
* platform-specific code to shutdown a CPU
*
* Called with IRQs disabled
*/
void platform_cpu_die(unsigned int cpu)
{
#ifdef DEBUG
unsigned int this_cpu = <API key>();
if (cpu != this_cpu) {
printk(KERN_CRIT "Eek! platform_cpu_die running on %u, should be %u\n",
this_cpu, cpu);
BUG();
}
#endif
complete(&cpu_killed);
/* directly enter low power state, skipping secure registers */
<API key>(cpu);
}
int <API key>(unsigned int cpu)
{
/*
* we don't allow CPU 0 to be shutdown (it is still too special
* e.g. clock tick interrupts)
*/
return cpu == 0 ? -EPERM : 0;
} |
// clang-format off
#include "<API key>.h"
#include "atom.h"
#include "comm.h"
#include "error.h"
#include "force.h"
#include "kspace.h"
#include "math_extra.h"
#include "memory.h"
#include "neigh_list.h"
#include "neigh_request.h"
#include "neighbor.h"
#include "respa.h"
#include "update.h"
#include <cmath>
#include <cstring>
using namespace LAMMPS_NS;
using namespace MathExtra;
#define EWALD_F 1.12837917
#define EWALD_P 0.3275911
#define A1 0.254829592
#define A2 -0.284496736
#define A3 1.421413741
#define A4 -1.453152027
#define A5 1.061405429
<API key>::<API key>(LAMMPS *lmp) : Pair(lmp)
{
dispersionflag = ewaldflag = pppmflag = 1;
respa_enable = 1;
writedata = 1;
ftable = nullptr;
fdisptable = nullptr;
cut_respa = nullptr;
}
void <API key>::options(char **arg, int order)
{
const char *option[] = {"long", "cut", "off", nullptr};
int i;
if (!*arg) error->all(FLERR,"Illegal pair_style buck/long/coul/long command");
for (i=0; option[i]&&strcmp(arg[0], option[i]); ++i);
switch (i) {
case 0: ewald_order |= 1<<order; break;
case 2: ewald_off |= 1<<order; break;
case 1: break;
default: error->all(FLERR,"Illegal pair_style buck/long/coul/long command");
}
}
void <API key>::settings(int narg, char **arg)
{
if (narg != 3 && narg != 4) error->all(FLERR,"Illegal pair_style command");
ewald_order = 0;
ewald_off = 0;
options(arg,6);
options(++arg,1);
if (!comm->me && ewald_order == ((1<<1) | (1<<6)))
error->warning(FLERR,"Using largest cutoff for buck/long/coul/long");
if (!*(++arg))
error->all(FLERR,"Cutoffs missing in pair_style buck/long/coul/long");
if (!((ewald_order^ewald_off) & (1<<6)))
dispersionflag = 0;
if (ewald_off & (1<<6))
error->all(FLERR,"LJ6 off not supported in pair_style buck/long/coul/long");
if (!((ewald_order^ewald_off) & (1<<1)))
error->all(FLERR,
"Coulomb cut not supported in pair_style buck/long/coul/coul");
cut_buck_global = utils::numeric(FLERR,*(arg++),false,lmp);
if (narg == 4 && ((ewald_order & 0x42) == 0x42))
error->all(FLERR,"Only one cutoff allowed when requesting all long");
if (narg == 4) cut_coul = utils::numeric(FLERR,*arg,false,lmp);
else cut_coul = cut_buck_global;
if (allocated) {
int i,j;
for (i = 1; i <= atom->ntypes; i++)
for (j = i; j <= atom->ntypes; j++)
if (setflag[i][j]) cut_buck[i][j] = cut_buck_global;
}
}
<API key>::~<API key>()
{
if (allocated) {
memory->destroy(setflag);
memory->destroy(cutsq);
memory->destroy(cut_buck_read);
memory->destroy(cut_buck);
memory->destroy(cut_bucksq);
memory->destroy(buck_a_read);
memory->destroy(buck_a);
memory->destroy(buck_c_read);
memory->destroy(buck_c);
memory->destroy(buck_rho_read);
memory->destroy(buck_rho);
memory->destroy(buck1);
memory->destroy(buck2);
memory->destroy(rhoinv);
memory->destroy(offset);
}
if (ftable) free_tables();
if (fdisptable) free_disp_tables();
}
void <API key>::allocate()
{
allocated = 1;
int n = atom->ntypes;
memory->create(setflag,n+1,n+1,"pair:setflag");
for (int i = 1; i <= n; i++)
for (int j = i; j <= n; j++)
setflag[i][j] = 0;
memory->create(cutsq,n+1,n+1,"pair:cutsq");
memory->create(cut_buck_read,n+1,n+1,"pair:cut_buck_read");
memory->create(cut_buck,n+1,n+1,"pair:cut_buck");
memory->create(cut_bucksq,n+1,n+1,"pair:cut_bucksq");
memory->create(buck_a_read,n+1,n+1,"pair:buck_a_read");
memory->create(buck_a,n+1,n+1,"pair:buck_a");
memory->create(buck_c_read,n+1,n+1,"pair:buck_c_read");
memory->create(buck_c,n+1,n+1,"pair:buck_c");
memory->create(buck_rho_read,n+1,n+1,"pair:buck_rho_read");
memory->create(buck_rho,n+1,n+1,"pair:buck_rho");
memory->create(buck1,n+1,n+1,"pair:buck1");
memory->create(buck2,n+1,n+1,"pair:buck2");
memory->create(rhoinv,n+1,n+1,"pair:rhoinv");
memory->create(offset,n+1,n+1,"pair:offset");
}
void *<API key>::extract(const char *id, int &dim)
{
const char *ids[] = {
"B", "ewald_order", "ewald_cut", "ewald_mix", "cut_coul", "cut_LJ", nullptr};
void *ptrs[] = {
buck_c, &ewald_order, &cut_coul, &mix_flag, &cut_coul, &cut_buck_global,
nullptr};
int i;
for (i=0; ids[i]&&strcmp(ids[i], id); ++i);
if (i == 0) dim = 2;
else dim = 0;
return ptrs[i];
}
void <API key>::coeff(int narg, char **arg)
{
if (narg < 5 || narg > 6)
error->all(FLERR,"Incorrect args for pair coefficients");
if (!allocated) allocate();
int ilo,ihi,jlo,jhi;
utils::bounds(FLERR,*(arg++),1,atom->ntypes,ilo,ihi,error);
utils::bounds(FLERR,*(arg++),1,atom->ntypes,jlo,jhi,error);
double buck_a_one = utils::numeric(FLERR,*(arg++),false,lmp);
double buck_rho_one = utils::numeric(FLERR,*(arg++),false,lmp);
double buck_c_one = utils::numeric(FLERR,*(arg++),false,lmp);
double cut_buck_one = cut_buck_global;
if (narg == 6) cut_buck_one = utils::numeric(FLERR,*(arg++),false,lmp);
int count = 0;
for (int i = ilo; i <= ihi; i++) {
for (int j = MAX(jlo,i); j <= jhi; j++) {
buck_a_read[i][j] = buck_a_one;
buck_c_read[i][j] = buck_c_one;
buck_rho_read[i][j] = buck_rho_one;
cut_buck_read[i][j] = cut_buck_one;
setflag[i][j] = 1;
count++;
}
}
if (count == 0) error->all(FLERR,"Incorrect args for pair coefficients");
}
void <API key>::init_style()
{
// require an atom style with charge defined
if (!atom->q_flag && (ewald_order&(1<<1)))
error->all(FLERR,
"Invoking coulombic in pair style buck/long/coul/long "
"requires atom attribute q");
// ensure use of KSpace long-range solver, set two g_ewalds
if (force->kspace == nullptr)
error->all(FLERR,"Pair style requires a KSpace style");
if (ewald_order&(1<<1)) g_ewald = force->kspace->g_ewald;
if (ewald_order&(1<<6)) g_ewald_6 = force->kspace->g_ewald_6;
// set rRESPA cutoffs
if (utils::strmatch(update->integrate_style,"^respa") &&
((Respa *) update->integrate)->level_inner >= 0)
cut_respa = ((Respa *) update->integrate)->cutoff;
else cut_respa = nullptr;
// setup force tables
if (ncoultablebits && (ewald_order&(1<<1))) init_tables(cut_coul,cut_respa);
if (ndisptablebits && (ewald_order&(1<<6))) init_tables_disp(cut_buck_global);
// request regular or rRESPA neighbor lists if neighrequest_flag != 0
if (force->kspace->neighrequest_flag) {
int irequest;
int respa = 0;
if (update->whichflag == 1 && utils::strmatch(update->integrate_style,"^respa")) {
if (((Respa *) update->integrate)->level_inner >= 0) respa = 1;
if (((Respa *) update->integrate)->level_middle >= 0) respa = 2;
}
irequest = neighbor->request(this,instance_me);
if (respa >= 1) {
neighbor->requests[irequest]->respaouter = 1;
neighbor->requests[irequest]->respainner = 1;
}
if (respa == 2) neighbor->requests[irequest]->respamiddle = 1;
}
cut_coulsq = cut_coul * cut_coul;
}
double <API key>::init_one(int i, int j)
{
if (setflag[i][j] == 0) error->all(FLERR,"All pair coeffs are not set");
if (ewald_order&(1<<6)) cut_buck[i][j] = cut_buck_global;
else cut_buck[i][j] = cut_buck_read[i][j];
buck_a[i][j] = buck_a_read[i][j];
buck_c[i][j] = buck_c_read[i][j];
buck_rho[i][j] = buck_rho_read[i][j];
double cut = MAX(cut_buck[i][j],cut_coul);
cutsq[i][j] = cut*cut;
cut_bucksq[i][j] = cut_buck[i][j] * cut_buck[i][j];
buck1[i][j] = buck_a[i][j]/buck_rho[i][j];
buck2[i][j] = 6.0*buck_c[i][j];
rhoinv[i][j] = 1.0/buck_rho[i][j];
// check interior rRESPA cutoff
if (cut_respa && MIN(cut_buck[i][j],cut_coul) < cut_respa[3])
error->all(FLERR,"Pair cutoff < Respa interior cutoff");
if (offset_flag && (cut_buck[i][j] > 0.0)) {
double rexp = exp(-cut_buck[i][j]/buck_rho[i][j]);
offset[i][j] = buck_a[i][j]*rexp - buck_c[i][j]/pow(cut_buck[i][j],6.0);
} else offset[i][j] = 0.0;
cutsq[j][i] = cutsq[i][j];
cut_bucksq[j][i] = cut_bucksq[i][j];
buck_a[j][i] = buck_a[i][j];
buck_c[j][i] = buck_c[i][j];
rhoinv[j][i] = rhoinv[i][j];
buck1[j][i] = buck1[i][j];
buck2[j][i] = buck2[i][j];
offset[j][i] = offset[i][j];
return cut;
}
void <API key>::write_restart(FILE *fp)
{
<API key>(fp);
int i,j;
for (i = 1; i <= atom->ntypes; i++)
for (j = i; j <= atom->ntypes; j++) {
fwrite(&setflag[i][j],sizeof(int),1,fp);
if (setflag[i][j]) {
fwrite(&buck_a_read[i][j],sizeof(double),1,fp);
fwrite(&buck_rho_read[i][j],sizeof(double),1,fp);
fwrite(&buck_c_read[i][j],sizeof(double),1,fp);
fwrite(&cut_buck_read[i][j],sizeof(double),1,fp);
}
}
}
void <API key>::read_restart(FILE *fp)
{
<API key>(fp);
allocate();
int i,j;
int me = comm->me;
for (i = 1; i <= atom->ntypes; i++)
for (j = i; j <= atom->ntypes; j++) {
if (me == 0) utils::sfread(FLERR,&setflag[i][j],sizeof(int),1,fp,nullptr,error);
MPI_Bcast(&setflag[i][j],1,MPI_INT,0,world);
if (setflag[i][j]) {
if (me == 0) {
utils::sfread(FLERR,&buck_a_read[i][j],sizeof(double),1,fp,nullptr,error);
utils::sfread(FLERR,&buck_rho_read[i][j],sizeof(double),1,fp,nullptr,error);
utils::sfread(FLERR,&buck_c_read[i][j],sizeof(double),1,fp,nullptr,error);
utils::sfread(FLERR,&cut_buck_read[i][j],sizeof(double),1,fp,nullptr,error);
}
MPI_Bcast(&buck_a_read[i][j],1,MPI_DOUBLE,0,world);
MPI_Bcast(&buck_rho_read[i][j],1,MPI_DOUBLE,0,world);
MPI_Bcast(&buck_c_read[i][j],1,MPI_DOUBLE,0,world);
MPI_Bcast(&cut_buck_read[i][j],1,MPI_DOUBLE,0,world);
}
}
}
void <API key>::<API key>(FILE *fp)
{
fwrite(&cut_buck_global,sizeof(double),1,fp);
fwrite(&cut_coul,sizeof(double),1,fp);
fwrite(&offset_flag,sizeof(int),1,fp);
fwrite(&mix_flag,sizeof(int),1,fp);
fwrite(&ncoultablebits,sizeof(int),1,fp);
fwrite(&tabinner,sizeof(double),1,fp);
fwrite(&ewald_order,sizeof(int),1,fp);
fwrite(&dispersionflag,sizeof(int),1,fp);
}
void <API key>::<API key>(FILE *fp)
{
if (comm->me == 0) {
utils::sfread(FLERR,&cut_buck_global,sizeof(double),1,fp,nullptr,error);
utils::sfread(FLERR,&cut_coul,sizeof(double),1,fp,nullptr,error);
utils::sfread(FLERR,&offset_flag,sizeof(int),1,fp,nullptr,error);
utils::sfread(FLERR,&mix_flag,sizeof(int),1,fp,nullptr,error);
utils::sfread(FLERR,&ncoultablebits,sizeof(int),1,fp,nullptr,error);
utils::sfread(FLERR,&tabinner,sizeof(double),1,fp,nullptr,error);
utils::sfread(FLERR,&ewald_order,sizeof(int),1,fp,nullptr,error);
utils::sfread(FLERR,&dispersionflag,sizeof(int),1,fp,nullptr,error);
}
MPI_Bcast(&cut_buck_global,1,MPI_DOUBLE,0,world);
MPI_Bcast(&cut_coul,1,MPI_DOUBLE,0,world);
MPI_Bcast(&offset_flag,1,MPI_INT,0,world);
MPI_Bcast(&mix_flag,1,MPI_INT,0,world);
MPI_Bcast(&ncoultablebits,1,MPI_INT,0,world);
MPI_Bcast(&tabinner,1,MPI_DOUBLE,0,world);
MPI_Bcast(&ewald_order,1,MPI_INT,0,world);
MPI_Bcast(&dispersionflag,1,MPI_INT,0,world);
}
void <API key>::write_data(FILE *fp)
{
for (int i = 1; i <= atom->ntypes; i++)
fprintf(fp,"%d %g %g %g\n",i,
buck_a_read[i][i],buck_rho_read[i][i],buck_c_read[i][i]);
}
void <API key>::write_data_all(FILE *fp)
{
for (int i = 1; i <= atom->ntypes; i++) {
for (int j = i; j <= atom->ntypes; j++) {
if (ewald_order & (1<<6)) {
fprintf(fp,"%d %d %g %g\n",i,j,
buck_a_read[i][j],buck_rho_read[i][j]);
} else {
fprintf(fp,"%d %d %g %g %g\n",i,j,
buck_a_read[i][j],buck_rho_read[i][j],buck_c_read[i][j]);
}
}
}
}
void <API key>::compute(int eflag, int vflag)
{
double evdwl,ecoul,fpair;
evdwl = ecoul = 0.0;
ev_init(eflag,vflag);
double **x = atom->x, *x0 = x[0];
double **f = atom->f, *f0 = f[0], *fi = f0;
double *q = atom->q;
int *type = atom->type;
int nlocal = atom->nlocal;
double *special_coul = force->special_coul;
double *special_lj = force->special_lj;
int newton_pair = force->newton_pair;
double qqrd2e = force->qqrd2e;
int i, j, order1 = ewald_order&(1<<1), order6 = ewald_order&(1<<6);
int *ineigh, *ineighn, *jneigh, *jneighn, typei, typej, ni;
double qi = 0.0, qri = 0.0, *cutsqi, *cut_bucksqi,
*buck1i, *buck2i, *buckai, *buckci, *rhoinvi, *offseti;
double r, rsq, r2inv, force_coul, force_buck;
double g2 = g_ewald_6*g_ewald_6, g6 = g2*g2*g2, g8 = g6*g2;
double xi[3], d[3];
ineighn = (ineigh = list->ilist)+list->inum;
for (; ineigh<ineighn; ++ineigh) { // loop over my atoms
i = *ineigh; fi = f0+3*i;
if (order1) qri = (qi = q[i])*qqrd2e; // initialize constants
offseti = offset[typei = type[i]];
buck1i = buck1[typei]; buck2i = buck2[typei];
buckai = buck_a[typei]; buckci = buck_c[typei], rhoinvi = rhoinv[typei];
cutsqi = cutsq[typei]; cut_bucksqi = cut_bucksq[typei];
memcpy(xi, x0+(i+(i<<1)), 3*sizeof(double));
jneighn = (jneigh = list->firstneigh[i])+list->numneigh[i];
for (; jneigh<jneighn; ++jneigh) { // loop over neighbors
j = *jneigh;
ni = sbmask(j);
j &= NEIGHMASK;
{ double *xj = x0+(j+(j<<1));
d[0] = xi[0] - xj[0]; // pair vector
d[1] = xi[1] - xj[1];
d[2] = xi[2] - xj[2]; }
if ((rsq = dot3(d, d)) >= cutsqi[typej = type[j]]) continue;
r2inv = 1.0/rsq;
r = sqrt(rsq);
if (order1 && (rsq < cut_coulsq)) { // coulombic
if (!ncoultablebits || rsq <= tabinnersq) { // series real space
double x1 = g_ewald*r;
double s = qri*q[j], t = 1.0/(1.0+EWALD_P*x1);
if (ni == 0) {
s *= g_ewald*exp(-x1*x1);
force_coul = (t *= ((((t*A5+A4)*t+A3)*t+A2)*t+A1)*s/x1)+EWALD_F*s;
if (eflag) ecoul = t;
} else { // special case
double fc = s*(1.0-special_coul[ni])/r;
s *= g_ewald*exp(-x1*x1);
force_coul = (t *= ((((t*A5+A4)*t+A3)*t+A2)*t+A1)*s/x1)+EWALD_F*s-fc;
if (eflag) ecoul = t-fc;
}
} // table real space
else {
union_int_float_t t;
t.f = rsq;
const int k = (t.i & ncoulmask) >> ncoulshiftbits;
double fc = (rsq-rtable[k])*drtable[k], qiqj = qi*q[j];
if (ni == 0) {
force_coul = qiqj*(ftable[k]+fc*dftable[k]);
if (eflag) ecoul = qiqj*(etable[k]+fc*detable[k]);
}
else { // special case
t.f = (1.0-special_coul[ni])*(ctable[k]+fc*dctable[k]);
force_coul = qiqj*(ftable[k]+fc*dftable[k]-t.f);
if (eflag) ecoul = qiqj*(etable[k]+fc*detable[k]-t.f);
}
}
} else force_coul = ecoul = 0.0;
if (rsq < cut_bucksqi[typej]) { // buckingham
double rn = r2inv*r2inv*r2inv;
double expr = exp(-r*rhoinvi[typej]);
if (order6) { // long-range
if (!ndisptablebits || rsq <= tabinnerdispsq) {
double x2 = g2*rsq, a2 = 1.0/x2;
x2 = a2*exp(-x2)*buckci[typej];
if (ni == 0) {
force_buck =
r*expr*buck1i[typej]-g8*(((6.0*a2+6.0)*a2+3.0)*a2+1.0)*x2*rsq;
if (eflag) evdwl = expr*buckai[typej]-g6*((a2+1.0)*a2+0.5)*x2;
} else { // special case
double fc = special_lj[ni], t = rn*(1.0-fc);
force_buck = fc*r*expr*buck1i[typej]-
g8*(((6.0*a2+6.0)*a2+3.0)*a2+1.0)*x2*rsq+t*buck2i[typej];
if (eflag) evdwl = fc*expr*buckai[typej] -
g6*((a2+1.0)*a2+0.5)*x2+t*buckci[typej];
}
} else { //table real space
union_int_float_t disp_t;
disp_t.f = rsq;
const int disp_k = (disp_t.i & ndispmask)>>ndispshiftbits;
double f_disp = (rsq-rdisptable[disp_k])*drdisptable[disp_k];
if (ni == 0) {
force_buck = r*expr*buck1i[typej]-(fdisptable[disp_k]+f_disp*dfdisptable[disp_k])*buckci[typej];
if (eflag) evdwl = expr*buckai[typej]-(edisptable[disp_k]+f_disp*dedisptable[disp_k])*buckci[typej];
} else { //special case
double fc = special_lj[ni], t = rn*(1.0-fc);
force_buck = fc*r*expr*buck1i[typej] -(fdisptable[disp_k]+f_disp*dfdisptable[disp_k])*buckci[typej] +t*buck2i[typej];
if (eflag) evdwl = fc*expr*buckai[typej] -(edisptable[disp_k]+f_disp*dedisptable[disp_k])*buckci[typej]+t*buckci[typej];
}
}
} else { // cut
if (ni == 0) {
force_buck = r*expr*buck1i[typej]-rn*buck2i[typej];
if (eflag) evdwl = expr*buckai[typej] -
rn*buckci[typej]-offseti[typej];
} else { // special case
double fc = special_lj[ni];
force_buck = fc*(r*expr*buck1i[typej]-rn*buck2i[typej]);
if (eflag)
evdwl = fc*(expr*buckai[typej]-rn*buckci[typej]-offseti[typej]);
}
}
}
else force_buck = evdwl = 0.0;
fpair = (force_coul+force_buck)*r2inv;
if (newton_pair || j < nlocal) {
double *fj = f0+(j+(j<<1)), fp;
fi[0] += fp = d[0]*fpair; fj[0] -= fp;
fi[1] += fp = d[1]*fpair; fj[1] -= fp;
fi[2] += fp = d[2]*fpair; fj[2] -= fp;
}
else {
fi[0] += d[0]*fpair;
fi[1] += d[1]*fpair;
fi[2] += d[2]*fpair;
}
if (evflag) ev_tally(i,j,nlocal,newton_pair,
evdwl,ecoul,fpair,d[0],d[1],d[2]);
}
}
if (vflag_fdotr) <API key>();
}
void <API key>::compute_inner()
{
double r, rsq, r2inv, force_coul = 0.0, force_buck, fpair;
int *type = atom->type;
int nlocal = atom->nlocal;
double *x0 = atom->x[0], *f0 = atom->f[0], *fi = f0, *q = atom->q;
double *special_coul = force->special_coul;
double *special_lj = force->special_lj;
int newton_pair = force->newton_pair;
double qqrd2e = force->qqrd2e;
double cut_out_on = cut_respa[0];
double cut_out_off = cut_respa[1];
double cut_out_diff = cut_out_off - cut_out_on;
double cut_out_on_sq = cut_out_on*cut_out_on;
double cut_out_off_sq = cut_out_off*cut_out_off;
int *ineigh, *ineighn, *jneigh, *jneighn, typei, typej, ni;
int i, j, order1 = (ewald_order|(ewald_off^-1))&(1<<1);
double qri, *cut_bucksqi, *buck1i, *buck2i, *rhoinvi;
double xi[3], d[3];
ineighn = (ineigh = list->ilist_inner) + list->inum_inner;
for (; ineigh<ineighn; ++ineigh) { // loop over my atoms
i = *ineigh; fi = f0+3*i;
if (order1) qri = qqrd2e*q[i];
memcpy(xi, x0+(i+(i<<1)), 3*sizeof(double));
cut_bucksqi = cut_bucksq[typei = type[i]];
buck1i = buck1[typei]; buck2i = buck2[typei]; rhoinvi = rhoinv[typei];
jneighn = (jneigh = list->firstneigh_inner[i])+list->numneigh_inner[i];
for (; jneigh<jneighn; ++jneigh) { // loop over neighbors
j = *jneigh;
ni = sbmask(j);
j &= NEIGHMASK;
{ double *xj = x0+(j+(j<<1));
d[0] = xi[0] - xj[0]; // pair vector
d[1] = xi[1] - xj[1];
d[2] = xi[2] - xj[2]; }
if ((rsq = dot3(d, d)) >= cut_out_off_sq) continue;
r2inv = 1.0/rsq;
r = sqrt(rsq);
if (order1 && (rsq < cut_coulsq)) // coulombic
force_coul = ni == 0 ?
qri*q[j]/r : qri*q[j]/r*special_coul[ni];
if (rsq < cut_bucksqi[typej = type[j]]) { // buckingham
double rn = r2inv*r2inv*r2inv,
expr = exp(-r*rhoinvi[typej]);
force_buck = ni == 0 ?
(r*expr*buck1i[typej]-rn*buck2i[typej]) :
(r*expr*buck1i[typej]-rn*buck2i[typej])*special_lj[ni];
}
else force_buck = 0.0;
fpair = (force_coul + force_buck) * r2inv;
if (rsq > cut_out_on_sq) { // switching
double rsw = (sqrt(rsq) - cut_out_on)/cut_out_diff;
fpair *= 1.0 + rsw*rsw*(2.0*rsw-3.0);
}
if (newton_pair || j < nlocal) { // force update
double *fj = f0+(j+(j<<1)), f;
fi[0] += f = d[0]*fpair; fj[0] -= f;
fi[1] += f = d[1]*fpair; fj[1] -= f;
fi[2] += f = d[2]*fpair; fj[2] -= f;
}
else {
fi[0] += d[0]*fpair;
fi[1] += d[1]*fpair;
fi[2] += d[2]*fpair;
}
}
}
}
void <API key>::compute_middle()
{
double r, rsq, r2inv, force_coul = 0.0, force_buck, fpair;
int *type = atom->type;
int nlocal = atom->nlocal;
double *x0 = atom->x[0], *f0 = atom->f[0], *fi = f0, *q = atom->q;
double *special_coul = force->special_coul;
double *special_lj = force->special_lj;
int newton_pair = force->newton_pair;
double qqrd2e = force->qqrd2e;
double cut_in_off = cut_respa[0];
double cut_in_on = cut_respa[1];
double cut_out_on = cut_respa[2];
double cut_out_off = cut_respa[3];
double cut_in_diff = cut_in_on - cut_in_off;
double cut_out_diff = cut_out_off - cut_out_on;
double cut_in_off_sq = cut_in_off*cut_in_off;
double cut_in_on_sq = cut_in_on*cut_in_on;
double cut_out_on_sq = cut_out_on*cut_out_on;
double cut_out_off_sq = cut_out_off*cut_out_off;
int *ineigh, *ineighn, *jneigh, *jneighn, typei, typej, ni;
int i, j, order1 = (ewald_order|(ewald_off^-1))&(1<<1);
double qri, *cut_bucksqi, *buck1i, *buck2i, *rhoinvi;
double xi[3], d[3];
ineighn = (ineigh = list->ilist_middle)+list->inum_middle;
for (; ineigh<ineighn; ++ineigh) { // loop over my atoms
i = *ineigh; fi = f0+3*i;
if (order1) qri = qqrd2e*q[i];
memcpy(xi, x0+(i+(i<<1)), 3*sizeof(double));
cut_bucksqi = cut_bucksq[typei = type[i]];
buck1i = buck1[typei]; buck2i = buck2[typei]; rhoinvi = rhoinv[typei];
jneighn = (jneigh = list->firstneigh_middle[i])+list->numneigh_middle[i];
for (; jneigh<jneighn; ++jneigh) { // loop over neighbors
j = *jneigh;
ni = sbmask(j);
j &= NEIGHMASK;
{ double *xj = x0+(j+(j<<1));
d[0] = xi[0] - xj[0]; // pair vector
d[1] = xi[1] - xj[1];
d[2] = xi[2] - xj[2]; }
if ((rsq = dot3(d, d)) >= cut_out_off_sq) continue;
if (rsq <= cut_in_off_sq) continue;
r2inv = 1.0/rsq;
r = sqrt(rsq);
if (order1 && (rsq < cut_coulsq)) // coulombic
force_coul = ni == 0 ?
qri*q[j]/r : qri*q[j]/r*special_coul[ni];
if (rsq < cut_bucksqi[typej = type[j]]) { // buckingham
double rn = r2inv*r2inv*r2inv,
expr = exp(-r*rhoinvi[typej]);
force_buck = ni == 0 ?
(r*expr*buck1i[typej]-rn*buck2i[typej]) :
(r*expr*buck1i[typej]-rn*buck2i[typej])*special_lj[ni];
}
else force_buck = 0.0;
fpair = (force_coul + force_buck) * r2inv;
if (rsq < cut_in_on_sq) { // switching
double rsw = (sqrt(rsq) - cut_in_off)/cut_in_diff;
fpair *= rsw*rsw*(3.0 - 2.0*rsw);
}
if (rsq > cut_out_on_sq) {
double rsw = (sqrt(rsq) - cut_out_on)/cut_out_diff;
fpair *= 1.0 + rsw*rsw*(2.0*rsw-3.0);
}
if (newton_pair || j < nlocal) { // force update
double *fj = f0+(j+(j<<1)), f;
fi[0] += f = d[0]*fpair; fj[0] -= f;
fi[1] += f = d[1]*fpair; fj[1] -= f;
fi[2] += f = d[2]*fpair; fj[2] -= f;
}
else {
fi[0] += d[0]*fpair;
fi[1] += d[1]*fpair;
fi[2] += d[2]*fpair;
}
}
}
}
void <API key>::compute_outer(int eflag, int vflag)
{
double evdwl,ecoul,fpair,fvirial;
evdwl = ecoul = 0.0;
ev_init(eflag,vflag);
double **x = atom->x, *x0 = x[0];
double **f = atom->f, *f0 = f[0], *fi = f0;
double *q = atom->q;
int *type = atom->type;
int nlocal = atom->nlocal;
double *special_coul = force->special_coul;
double *special_lj = force->special_lj;
int newton_pair = force->newton_pair;
double qqrd2e = force->qqrd2e;
int i, j, order1 = ewald_order&(1<<1), order6 = ewald_order&(1<<6);
int *ineigh, *ineighn, *jneigh, *jneighn, typei, typej, ni, respa_flag;
double qi = 0.0, qri = 0.0, *cutsqi, *cut_bucksqi,
*buck1i, *buck2i, *buckai, *buckci, *rhoinvi, *offseti;
double r, rsq, r2inv, force_coul, force_buck;
double g2 = g_ewald_6*g_ewald_6, g6 = g2*g2*g2, g8 = g6*g2;
double respa_buck = 0.0, respa_coul = 0.0, frespa = 0.0;
double xi[3], d[3];
double cut_in_off = cut_respa[2];
double cut_in_on = cut_respa[3];
double cut_in_diff = cut_in_on - cut_in_off;
double cut_in_off_sq = cut_in_off*cut_in_off;
double cut_in_on_sq = cut_in_on*cut_in_on;
ineighn = (ineigh = list->ilist)+list->inum;
for (; ineigh<ineighn; ++ineigh) { // loop over my atoms
i = *ineigh; fi = f0+3*i;
if (order1) qri = (qi = q[i])*qqrd2e; // initialize constants
offseti = offset[typei = type[i]];
buck1i = buck1[typei]; buck2i = buck2[typei];
buckai = buck_a[typei]; buckci = buck_c[typei]; rhoinvi = rhoinv[typei];
cutsqi = cutsq[typei]; cut_bucksqi = cut_bucksq[typei];
memcpy(xi, x0+(i+(i<<1)), 3*sizeof(double));
jneighn = (jneigh = list->firstneigh[i])+list->numneigh[i];
for (; jneigh<jneighn; ++jneigh) { // loop over neighbors
j = *jneigh;
ni = sbmask(j);
j &= NEIGHMASK;
{ double *xj = x0+(j+(j<<1));
d[0] = xi[0] - xj[0]; // pair vector
d[1] = xi[1] - xj[1];
d[2] = xi[2] - xj[2]; }
if ((rsq = dot3(d, d)) >= cutsqi[typej = type[j]]) continue;
r2inv = 1.0/rsq;
r = sqrt(rsq);
frespa = 1.0; //check whether and how to compute respa corrections
respa_coul = 0.0;
respa_buck = 0.0;
respa_flag = rsq < cut_in_on_sq ? 1 : 0;
if (respa_flag && (rsq > cut_in_off_sq)) {
double rsw = (r-cut_in_off)/cut_in_diff;
frespa = 1-rsw*rsw*(3.0-2.0*rsw);
}
if (order1 && (rsq < cut_coulsq)) { // coulombic
if (!ncoultablebits || rsq <= tabinnersq) { // series real space
double s = qri*q[j];
if (respa_flag) // correct for respa
respa_coul = ni == 0 ? frespa*s/r : frespa*s/r*special_coul[ni];
double x = g_ewald*r, t = 1.0/(1.0+EWALD_P*x);
if (ni == 0) {
s *= g_ewald*exp(-x*x);
force_coul = (t *= ((((t*A5+A4)*t+A3)*t+A2)*t+A1)*s/x)+EWALD_F*s-respa_coul;
if (eflag) ecoul = t;
}
else { // correct for special
double ri = s*(1.0-special_coul[ni])/r; s *= g_ewald*exp(-x*x);
force_coul = (t *= ((((t*A5+A4)*t+A3)*t+A2)*t+A1)*s/x)+EWALD_F*s-ri-respa_coul;
if (eflag) ecoul = t-ri;
}
} // table real space
else {
if (respa_flag) {
double s = qri*q[j];
respa_coul = ni == 0 ? frespa*s/r : frespa*s/r*special_coul[ni];
}
union_int_float_t t;
t.f = rsq;
const int k = (t.i & ncoulmask) >> ncoulshiftbits;
double f = (rsq-rtable[k])*drtable[k], qiqj = qi*q[j];
if (ni == 0) {
force_coul = qiqj*(ftable[k]+f*dftable[k]);
if (eflag) ecoul = qiqj*(etable[k]+f*detable[k]);
}
else { // correct for special
t.f = (1.0-special_coul[ni])*(ctable[k]+f*dctable[k]);
force_coul = qiqj*(ftable[k]+f*dftable[k]-t.f);
if (eflag) {
t.f = (1.0-special_coul[ni])*(ptable[k]+f*dptable[k]);
ecoul = qiqj*(etable[k]+f*detable[k]-t.f);
}
}
}
}
else force_coul = respa_coul = ecoul = 0.0;
if (rsq < cut_bucksqi[typej]) { // buckingham
double rn = r2inv*r2inv*r2inv,
expr = exp(-r*rhoinvi[typej]);
if (respa_flag) respa_buck = ni == 0 ? // correct for respa
frespa*(r*expr*buck1i[typej]-rn*buck2i[typej]) :
frespa*(r*expr*buck1i[typej]-rn*buck2i[typej])*special_lj[ni];
if (order6) { // long-range form
if (!ndisptablebits || rsq <= tabinnerdispsq) {
double x2 = g2*rsq, a2 = 1.0/x2;
x2 = a2*exp(-x2)*buckci[typej];
if (ni == 0) {
force_buck =
r*expr*buck1i[typej]-g8*(((6.0*a2+6.0)*a2+3.0)*a2+1.0)*x2*rsq-respa_buck;
if (eflag) evdwl = expr*buckai[typej]-g6*((a2+1.0)*a2+0.5)*x2;
}
else { // correct for special
double f = special_lj[ni], t = rn*(1.0-f);
force_buck = f*r*expr*buck1i[typej]-
g8*(((6.0*a2+6.0)*a2+3.0)*a2+1.0)*x2*rsq+t*buck2i[typej]-respa_buck;
if (eflag) evdwl = f*expr*buckai[typej] -
g6*((a2+1.0)*a2+0.5)*x2+t*buckci[typej];
}
}
else { // table real space
union_int_float_t disp_t;
disp_t.f = rsq;
const int disp_k = (disp_t.i & ndispmask)>>ndispshiftbits;
double f_disp = (rsq-rdisptable[disp_k])*drdisptable[disp_k];
double rn = r2inv*r2inv*r2inv;
if (ni == 0) {
force_buck = r*expr*buck1i[typej]-(fdisptable[disp_k]+f_disp*dfdisptable[disp_k])*buckci[typej]-respa_buck;
if (eflag) evdwl = expr*buckai[typej]-(edisptable[disp_k]+f_disp*dedisptable[disp_k])*buckci[typej];
}
else { //special case
double f = special_lj[ni], t = rn*(1.0-f);
force_buck = f*r*expr*buck1i[typej]-(fdisptable[disp_k]+f_disp*dfdisptable[disp_k])*buckci[typej]+t*buck2i[typej]-respa_buck;
if (eflag) evdwl = f*expr*buckai[typej]-(edisptable[disp_k]+f_disp*dedisptable[disp_k])*buckci[typej]+t*buckci[typej];
}
}
}
else { // cut form
if (ni == 0) {
force_buck = r*expr*buck1i[typej]-rn*buck2i[typej]-respa_buck;
if (eflag)
evdwl = expr*buckai[typej]-rn*buckci[typej]-offseti[typej];
}
else { // correct for special
double f = special_lj[ni];
force_buck = f*(r*expr*buck1i[typej]-rn*buck2i[typej])-respa_buck;
if (eflag)
evdwl = f*(expr*buckai[typej]-rn*buckci[typej]-offseti[typej]);
}
}
}
else force_buck = respa_buck = evdwl = 0.0;
fpair = (force_coul+force_buck)*r2inv;
if (newton_pair || j < nlocal) {
double *fj = f0+(j+(j<<1)), f;
fi[0] += f = d[0]*fpair; fj[0] -= f;
fi[1] += f = d[1]*fpair; fj[1] -= f;
fi[2] += f = d[2]*fpair; fj[2] -= f;
}
else {
fi[0] += d[0]*fpair;
fi[1] += d[1]*fpair;
fi[2] += d[2]*fpair;
}
if (evflag) {
fvirial = (force_coul + force_buck + respa_coul + respa_buck)*r2inv;
ev_tally(i,j,nlocal,newton_pair,
evdwl,ecoul,fvirial,d[0],d[1],d[2]);
}
}
}
}
double <API key>::single(int i, int j, int itype, int jtype,
double rsq, double factor_coul, double factor_buck,
double &fforce)
{
double f, r, r2inv, r6inv, force_coul, force_buck;
double g2 = g_ewald_6*g_ewald_6, g6 = g2*g2*g2, g8 = g6*g2, *q = atom->q;
r = sqrt(rsq);
r2inv = 1.0/rsq;
double eng = 0.0;
if ((ewald_order&2) && (rsq < cut_coulsq)) { // coulombic
if (!ncoultablebits || rsq <= tabinnersq) { // series real space
double x = g_ewald*r;
double s = force->qqrd2e*q[i]*q[j], t = 1.0/(1.0+EWALD_P*x);
f = s*(1.0-factor_coul)/r; s *= g_ewald*exp(-x*x);
force_coul = (t *= ((((t*A5+A4)*t+A3)*t+A2)*t+A1)*s/x)+EWALD_F*s-f;
eng += t-f;
} else { // table real space
union_int_float_t t;
t.f = rsq;
const int k = (t.i & ncoulmask) >> ncoulshiftbits;
double f = (rsq-rtable[k])*drtable[k], qiqj = q[i]*q[j];
t.f = (1.0-factor_coul)*(ctable[k]+f*dctable[k]);
force_coul = qiqj*(ftable[k]+f*dftable[k]-t.f);
eng += qiqj*(etable[k]+f*detable[k]-t.f);
}
} else force_coul = 0.0;
if (rsq < cut_bucksq[itype][jtype]) { // buckingham
double expr = factor_buck*exp(-sqrt(rsq)*rhoinv[itype][jtype]);
r6inv = r2inv*r2inv*r2inv;
if (ewald_order&64) { // long-range
double x2 = g2*rsq, a2 = 1.0/x2, t = r6inv*(1.0-factor_buck);
x2 = a2*exp(-x2)*buck_c[itype][jtype];
force_buck = buck1[itype][jtype]*r*expr-
g8*(((6.0*a2+6.0)*a2+3.0)*a2+1.0)*x2*rsq+t*buck2[itype][jtype];
eng += buck_a[itype][jtype]*expr-
g6*((a2+1.0)*a2+0.5)*x2+t*buck_c[itype][jtype];
} else { // cut
force_buck =
factor_buck*(buck1[itype][jtype]*r*expr-buck2[itype][jtype]*r6inv);
eng += buck_a[itype][jtype]*expr-
factor_buck*(buck_c[itype][jtype]*r6inv-offset[itype][jtype]);
}
} else force_buck = 0.0;
fforce = (force_coul+force_buck)*r2inv;
return eng;
} |
# Weak Reference class that does not bother GCing.
# Usage:
# foo = Object.new
# foo = Object.new
# p foo.to_s # original's class
# foo = WeakRef.new(foo)
# p foo.to_s # should be same class
# ObjectSpace.garbage_collect
# p foo.to_s # should raise exception (recycled)
require "delegate"
require 'thread'
class WeakRef < Delegator
class RefError < StandardError
end
@@id_map = {} # obj -> [ref,...]
@@id_rev_map = {} # ref -> obj
@@mutex = Mutex.new
@@final = lambda {|id|
@@mutex.synchronize {
rids = @@id_map[id]
if rids
for rid in rids
@@id_rev_map.delete(rid)
end
@@id_map.delete(id)
end
rid = @@id_rev_map[id]
if rid
@@id_rev_map.delete(id)
@@id_map[rid].delete(id)
@@id_map.delete(rid) if @@id_map[rid].empty?
end
}
}
def initialize(orig)
@__id = orig.object_id
ObjectSpace.define_finalizer orig, @@final
ObjectSpace.define_finalizer self, @@final
@@mutex.synchronize {
@@id_map[@__id] = [] unless @@id_map[@__id]
}
@@id_map[@__id].push self.object_id
@@id_rev_map[self.object_id] = @__id
super
end
def __getobj__
unless @@id_rev_map[self.object_id] == @__id
Kernel::raise RefError, "Invalid Reference - probably recycled", Kernel::caller(2)
end
begin
ObjectSpace._id2ref(@__id)
rescue RangeError
Kernel::raise RefError, "Invalid Reference - probably recycled", Kernel::caller(2)
end
end
def __setobj__(obj)
end
def weakref_alive?
@@id_rev_map[self.object_id] == @__id
end
end
if __FILE__ == $0
# require 'thread'
foo = Object.new
p foo.to_s # original's class
foo = WeakRef.new(foo)
p foo.to_s # should be same class
ObjectSpace.garbage_collect
ObjectSpace.garbage_collect
p foo.to_s # should raise exception (recycled)
end |
<?php
abstract class <API key>
extends <API key> {
/**
* put your comment there...
*
* @var mixed
*/
protected $objectIdKeyName;
/**
* put your comment there...
*
* @var mixed
*/
protected $objectTypeName;
/**
* put your comment there...
*
* @var mixed
*/
protected $relationTypeName;
/**
* put your comment there...
*
* @param mixed $tblPackage
* @param mixed $packageId
*/
protected function save(CJTxTable & $tblPckObjects, $packageId) {
// Initialize.
$register =& $this->register();
// Save Package object ref
$tblPckObjects->setData(array(
'packageId' => $packageId,
'objectId' => $register[$this->objectIdKeyName],
'objectType' => $this->objectTypeName,
'relType' => $this->relationTypeName,
))->save();
// Chain/
return $this;
}
/**
* Do nothing!
*
*/
public function transit() {
// Initialize.
$tblPckObjects = CJTxTable::getInstance('package-objects');
// Query package id.
$tblPck = CJTxTable::getInstance('package');
$pckData = new <API key>($this->getNode());
$tblPck->setData($pckData)
->load(array('name'));
// Add Block-Template-Link=>Package reference.
$this->save($tblPckObjects, $tblPck->get('id'));
// Chain.
return $this;
}
} |
/*
* This client is meant to be used both interactively to check
* that gpm is working, and as a background process to convert gpm events
* to textual strings. I'm using it to handle Linux mouse
* events to emacs
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#include <termios.h>
#include <errno.h>
#include <linux/keyboard.h> /* to use KG_SHIFT and so on */
#define ALL_KEY_MODS ((1<<KG_SHIFT)|(1<<KG_ALT)|(1<<KG_ALTGR)|(1<<KG_CTRL))
#include "headers/message.h" /* messages */
#include "headers/gpm.h"
#define GPM_NAME "gpm"
#define GPM_DATE "X-Mas 2002"
char *prgname;
struct node {char *name; int flag;};
struct node tableEv[]= {
{"move", GPM_MOVE},
{"drag", GPM_DRAG},
{"down", GPM_DOWN},
{"up", GPM_UP},
{"press", GPM_DOWN},
{"release", GPM_UP},
{"motion", GPM_MOVE | GPM_DRAG},
{"hard", GPM_HARD},
{"any", ~0},
{"all", ~0},
{"none", 0},
{NULL,0}
};
struct node tableMod[]= {
{"shift", 1<<KG_SHIFT},
{"anyAlt", 1<<KG_ALT | 1<<KG_ALTGR},
{"leftAlt", 1<<KG_ALT},
{"rightAlt", 1<<KG_ALTGR},
{"control", 1<<KG_CTRL},
{"any", ~0},
{"all", ~0},
{"none", 0},
{NULL,0}
};
/* provide defaults */
int opt_mask = ~0; /* get everything */
int opt_default = ~GPM_HARD; /* pass everithing unused */
int opt_minMod = 0; /* run always */
int opt_maxMod = ~0; /* with any modifier */
int opt_intrct = 0;
int opt_vc = 0; /* by default get the current vc */
int opt_emacs = 0;
int opt_fit = 0;
int opt_pointer = 0;
int user_handler(Gpm_Event *event, void *data)
{
if (opt_fit) Gpm_FitEvent(event);
printf("mouse: event 0x%02X, at %2i,%2i (delta %2i,%2i), "
"buttons %i, modifiers 0x%02X\r\n",
event->type,
event->x, event->y,
event->dx, event->dy,
event->buttons, event->modifiers);
if (event->type & (GPM_DRAG|GPM_DOWN)) {
if (0 != opt_pointer) {
GPM_DRAWPOINTER(event);
}
}
return 0;
}
int emacs_handler(Gpm_Event *event, void *data)
{
int i,j;
static int dragX, dragY;
static char buffer[64];
/* itz Mon Mar 23 20:54:54 PST 1998 emacs likes the modifier bits in
alphabetical order, so I'll use a lookup table instead of a loop; it
is faster anyways */
/* static char *s_mod[]={"S-","M-","C-","M-",NULL}; */
static char *s_mod[] = {
"", /* 000 */
"S-", /* 001 */
"M-", /* 002 */
"M-S-", /* 003 */
"C-", /* 004 */
"C-S-", /* 005 */
"C-M-", /* 006 */
"C-M-S-", /* 007 */
/* idea: maybe we should map AltGr to Emacs Alt instead of Meta? */
"M-", /* 010 */
"M-S-", /* 011 */
"M-", /* 012 */
"M-S-", /* 013 */
"C-M-", /* 014 */
"C-M-S-", /* 015 */
"C-M-", /* 016 */
"C-M-S-", /* 017 */
};
/* itz Mon Mar 23 08:23:14 PST 1998 what emacs calls a `drag' event
is our `up' event with coordinates different from the `down'
event. What gpm calls `drag' is just `mouse-movement' to emacs. */
static char *s_type[]={"mouse-movement", "mouse-movement","down-mouse-","mouse-",NULL};
static char *s_button[]={"3","2","1",NULL};
static char *s_multi[]={"double-", "triple-", 0};
static char s_count[]="23";
char count = '1';
struct timeval tv_cur;
long timestamp;
static long dragTime;
/* itz Mon Mar 23 08:27:53 PST 1998 this flag is needed because even
if the final coordinates of a drag are identical to the initial
ones, it is still a drag if there was any movement in between. Sigh. */
static int dragFlag = 0;
gettimeofday(&tv_cur, 0);
timestamp = ((short)tv_cur.tv_sec) * 1000 + (tv_cur.tv_usec / 1000);
if (opt_fit) Gpm_FitEvent(event);
buffer[0]=0;
/* itz Sun Mar 22 19:09:04 PST 1998 Emacs doesn't understand
modifiers on motion events. */
if (!(event->type & (GPM_MOVE|GPM_DRAG))) {
/* modifiers */
strcpy(buffer, s_mod[event->modifiers & ALL_KEY_MODS]);
/* multiple */
for (i=0, j=GPM_DOUBLE; s_multi[i]; i++, j<<=1)
if (event->type & j) {
count = s_count[i];
strcat(buffer,s_multi[i]);
}
}
if (event->type & GPM_DRAG) {
dragFlag = 1;
}
/* itz Mon Mar 23 08:26:33 PST 1998 up-event after movement is a drag. */
if ((event->type & GPM_UP) && dragFlag) {
strcat(buffer, "drag-");
}
/* type */
for (i=0, j=GPM_MOVE; s_type[i]; i++, j<<=1)
if (event->type & j)
strcat(buffer,s_type[i]);
/* itz Sun Mar 22 19:09:04 PST 1998 Emacs doesn't understand
modifiers on motion events. */
if (!(event->type & (GPM_MOVE|GPM_DRAG)))
/* button */
for (i=0, j=GPM_B_RIGHT; s_button[i]; i++, j<<=1)
if (event->buttons & j)
strcat(buffer,s_button[i]);
if ((event->type & GPM_UP) && dragFlag) {
printf("(%s ((%i . %i) %ld) %c ((%i . %i) %ld))\n",
buffer,
event->x, event->y, timestamp,
count,
dragX, dragY, dragTime);
} else if (event->type & (GPM_DOWN|GPM_UP)) {
printf("(%s ((%i . %i) %ld) %c)\n",
buffer, event->x, event->y, timestamp, count);
} else if (event->type & (GPM_MOVE|GPM_DRAG)) {
printf("(%s ((%i . %i) %ld))\n",
buffer, event->x, event->y, timestamp);
}
if (event->type & GPM_DOWN) {
dragX=event->x;
dragY=event->y;
dragTime=timestamp;
dragFlag = 0;
}
if (event->type & (GPM_DRAG|GPM_DOWN)) {
if (0 == opt_pointer) {
GPM_DRAWPOINTER(event);
}
}
return 0;
}
int usage(void)
{
//printf( "(" GPM_NAME ") " GPM_RELEASE ", " GPM_DATE "\n"
printf( "(" GPM_NAME ") , " GPM_DATE "\n"
"Usage: %s [options]\n",prgname);
printf(" Valid options are\n"
" -C <number> choose virtual console (beware of it)\n"
" -d <number> choose the default mask\n"
" -e <number> choose the eventMask\n"
" -E emacs-mode\n"
" -i accept commands from stdin\n"
" -f fit drag events inside the screen\n"
" -m <number> minimum modifier mask\n"
" -M <number> maximum modifier mask\n"
" -p show pointer while dragging\n"
" -u user-mode (default)\n"
);
return 1;
}
#define PARSE_EVENTS 0
#define PARSE_MODIFIERS 1
void getmask(char *arg, int which, int* where)
{
int last=0, value=0;
char *cur;
struct node *table, *n;
int mode = 0; /* 0 = set, 1 = add, 2 = subtract */
if ('+' == arg[0]) {
mode = 1;
++arg;
} else if ('-' == arg[0]) {
mode = 2;
++arg;
}
if (isdigit(arg[0])) {
switch(mode) {
case 0: *where = atoi(arg); break;
case 1: *where |= atoi(arg); break;
case 2: *where &= ~atoi(arg); break;
} /*switch*/
return;
}
table= (PARSE_MODIFIERS == which) ? tableMod : tableEv;
while (1)
{
while (*arg && !isalnum(*arg)) arg++; /* skip delimiters */
cur=arg;
while(isalnum(*cur)) cur++; /* scan the word */
if (!*cur) last++;
*cur=0;
for (n=table;n->name;n++)
if (!strcmp(n->name,arg))
{
value |= n->flag;
break;
}
if (!n->name) fprintf(stderr,"%s: Incorrect flag \"%s\"\n",prgname,arg);
if (last) break;
cur++; arg=cur;
}
switch(mode) {
case 0: *where = value; break;
case 1: *where |= value; break;
case 2: *where &= ~value; break;
} /*switch*/
}
int cmdline(int argc, char **argv, char *options)
{
int opt;
while ((opt = getopt(argc, argv, options)) != -1)
{
switch (opt)
{
/* itz Tue Mar 24 17:11:52 PST 1998 i hate options that do
too much. Made them orthogonal. */
case 'C': sscanf(optarg,"%x",&opt_vc); break;
case 'd': getmask(optarg, PARSE_EVENTS, &opt_default); break;
case 'e': getmask(optarg, PARSE_EVENTS, &opt_mask); break;
case 'E': opt_emacs = 1; break;
case 'i': opt_intrct=1; break;
case 'f': opt_fit=1; break;
case 'm': getmask(optarg, PARSE_MODIFIERS, &opt_minMod); break;
case 'M': getmask(optarg, PARSE_MODIFIERS, &opt_maxMod); break;
case 'p': opt_pointer =1; break;
case 'u': opt_emacs=0; break;
default: return 1;
}
}
return 0;
}
void
do_snapshot()
{
Gpm_Event event;
int i=Gpm_GetSnapshot(&event);
char *s;
if (-1 == i) {
fprintf(stderr,"Warning: cannot get snapshot!\n");
fprintf(stderr,"Have you run \"configure\" and \"make install\"?\n");
return;
}
fprintf(stderr,"Mouse has %d buttons\n",i);
fprintf(stderr,"Currently sits at (%d,%d)\n",event.x,event.y);
fprintf(stderr,"The window is %d columns by %d rows\n",event.dx,event.dy);
s=Gpm_GetLibVersion(&i);
fprintf(stderr,"The library is version \"%s\" (%i)\n",s,i);
s=<API key>(&i);
fprintf(stderr,"The daemon is version \"%s\" (%i)\n",s,i);
fprintf(stderr,"The current console is %d, with modifiers 0x%02x\n",
event.vc,event.modifiers);
fprintf(stderr,"The button mask is 0x%02X\n",event.buttons);
}
int interact(char *cmd) /* returns 0 on success and !=0 on error */
{
Gpm_Connect conn;
int argc=0;
char *argv[20];
if (*cmd && cmd[strlen(cmd)-1]=='\n')
cmd[strlen(cmd)-1]='\0';
if (!*cmd) return 0;
/*
* Interaction is accomplished by building an argv and passing it to
* cmdline(), to use the same syntax used to invoke the program
*/
while (argc<19)
{
while(isspace(*cmd)) cmd++;
argv[argc++]=cmd;
while (*cmd && isgraph(*cmd)) cmd++;
if (!*cmd) break;
*cmd=0;
cmd++;
}
argv[argc]=NULL;
if (!strcmp(argv[0],"pop")) {
return (Gpm_Close()==0 ? 1 : 0); /* a different convention on ret values */
}
if (!strcmp(argv[0],"info")) {
fprintf(stderr,"The stack of connection info is %i depth\n",gpm_flag);
return 0;
}
if (!strcmp(argv[0],"quit")) {
exit(0);
}
if (!strcmp(argv[0],"snapshot")) {
do_snapshot();
return 0;
}
optind=0; /* scan the entire line */
if (strcmp(argv[0],"push") || cmdline(argc,argv,"d:e:m:M:")) {
fprintf(stderr,"Syntax error in input line\n");
return 0;
}
conn.eventMask=opt_mask;
conn.defaultMask=opt_default;
conn.maxMod=opt_maxMod;
conn.minMod=opt_minMod;
if (Gpm_Open(&conn,opt_vc)==-1)
{
fprintf(stderr,"%s: Can't open mouse connection\r\n",argv[0]);
return 1;
}
return 0;
}
int main(int argc, char **argv)
{
Gpm_Connect conn;
char cmd[128];
Gpm_Handler* my_handler; /* not the real gpm handler! */
fd_set readset;
prgname=argv[0];
if (cmdline(argc,argv,"C:d:e:Efim:M:pu")) exit(usage());
gpm_zerobased = opt_emacs;
conn.eventMask=opt_mask;
conn.defaultMask=opt_default;
conn.maxMod=opt_maxMod;
conn.minMod=opt_minMod;
if (Gpm_Open(&conn,opt_vc) == -1) {
gpm_report(GPM_PR_ERR,"%s: Can't open mouse connection\n",prgname);
exit(1);
} else if (gpm_fd == -2) {
gpm_report(GPM_PR_OOPS,"%s: use rmev to see gpm events in xterm or rxvt\n",prgname);
}
gpm_report(GPM_PR_DEBUG,"STILL RUNNING_1");
my_handler= opt_emacs ? emacs_handler : user_handler;
/* itz Sun Mar 22 09:51:33 PST 1998 needed in case the output is a pipe */
setvbuf(stdout, 0, _IOLBF, 0);
setvbuf(stdin, 0, _IOLBF, 0);
while(1) { /* forever */
FD_ZERO(&readset);
FD_SET(gpm_fd, &readset);
if (opt_intrct) {
FD_SET(STDIN_FILENO, &readset);
}
if (select(gpm_fd+1, &readset, 0, 0, 0) < 0 && errno == EINTR)
continue;
if (FD_ISSET(STDIN_FILENO, &readset)) {
if (0 == fgets(cmd, sizeof(cmd), stdin) || interact(cmd)) {
exit(0); /* ^D typed on input */
}
}
if (FD_ISSET(gpm_fd, &readset)) {
Gpm_Event evt;
if (Gpm_GetEvent(&evt) > 0) {
my_handler(&evt, 0);
} else {
fprintf(stderr, "mev says : Oops, Gpm_GetEvent()\n");
}
}
} /*while*/
/*....................................... Done */
while (Gpm_Close()); /* close all the stack */
exit(0);
} |
<?php
?>
<table width="100%" border="0" cellspacing="2" cellpadding="2">
<tr>
<td class="main"><strong>EP Advanced Export Screen</strong><br>
<?php echo tep_image(DIR_WS_LANGUAGES . $language . '/help/ep/images/epa_start.png','','','','style="border:1px solid #ccc" vspace="5" hspace="5"');?><br>
</td>
</tr>
<tr>
<td valign="top" class="main"><strong>Basic Change with EP Advanced:</strong><br>
The changes here are in the handling of HTML content in descriptions; image path URL's, and EP import filename requirements. You may now import files with html in the text fields and not have it mangled by EP or Excel. URL's for images in subdirectories can be handled and correctly written to the database. Beginning with 2.75, EP Advanced will not install files unless it begins with EPA,and EP Basic will not install files that begin with EPA. This feature is to protect the database from errors related to a new column added to the Easy populate file format. EP Advanced uses the product_id column, this allow for more features to be added. EPA is will also allow you to refine your export file so you can target a specific group of records to edit.</td>
</tr>
<tr>
<td valign="top" class="main"><strong>Select Method to Save Export File:</strong><br>
<?php echo tep_image(DIR_WS_LANGUAGES . $language . '/help/ep/images/epa_sel_export.png','','','','style="border:1px solid #ccc" vspace="5" hspace="5"');?><br>
To export select where you want the export file placed.</td>
</tr>
<tr>
<td valign="top" class="main"><strong>Select Field Set to Export:</strong><br>
<?php echo tep_image(DIR_WS_LANGUAGES . $language . '/help/ep/images/epa_field_group.png','','','','style="border:1px solid #ccc" vspace="5" hspace="5"');?><br>
Next select which group of feilds to export.</td>
</tr>
<tr>
<td valign="top" class="main"><strong>Select Field for Sort Order:</strong><br>
<?php echo tep_image(DIR_WS_LANGUAGES . $language . '/help/ep/images/epa_sortorder.png','','','','style="border:1px solid #ccc" vspace="5" hspace="5"');?><br>
Next select the sort order you want the rows to apear in the export file.</td>
</tr>
<tr>
<td valign="top" class="main"><strong>Limit Number of Products to Export:</strong><br>
If you deal with large export files and find it diffcult to find products to edit. You can use the Limits to make you export files small and target specific groups of records. Not all export files can be limited by all meathods. Meathods can also be combined.</td>
</tr>
<tr>
<td valign="top" class="main"><strong>Select Field for Sort Order:</strong><br>
<?php echo tep_image(DIR_WS_LANGUAGES . $language . '/help/ep/images/epa_sortorder.png','','','','style="border:1px solid #ccc" vspace="5" hspace="5"');?><br>
Next select the sort order you want the rows to apear in the export file.</td>
</tr>
<tr>
<td valign="top" class="main"><strong>Limit By Category:</strong><br>
<?php echo tep_image(DIR_WS_LANGUAGES . $language . '/help/ep/images/epa_limit_cat.png','','','','style="border:1px solid #ccc" vspace="5" hspace="5"');?><br>
If you have TOP showing in the drop down box all categories are looked at. If you have a category showing in the drop down box, the that category and all sub categories will be in the list. The categories drop down is generated from your categories in the database.</td>
</tr>
<tr>
<td valign="top" class="main"><strong>Limit By Manufacture:</strong><br>
<?php echo tep_image(DIR_WS_LANGUAGES . $language . '/help/ep/images/epa_limit_man.png','','','','style="border:1px solid #ccc" vspace="5" hspace="5"');?><br>
If you have Manufactures showing in the drop down box all manufactures are looked at. You can select any manufacture to target just there products. The drop down list of manufacures is read from your manufacters.</td>
</tr>
<tr>
<td valign="top" class="main"><strong>Limit By Product Range:</strong><br>
<?php echo tep_image(DIR_WS_LANGUAGES . $language . '/help/ep/images/epa_limit_prodid.png','','','','style="border:1px solid #ccc" vspace="5" hspace="5"');?><br>
You can use Product Id's to limit your export file.
<ul>
<li>If no product_id's are enter all of the product are in the export file</li>
<li>If the begin product_id and no end product_id is entered. Products from the first product id to the end are in the export file</li>
<li>If no beginning product_id's and only and ending product_ID. From the first id to ending the products are in the export file</li>
<li>If the begin product_id and ending product_id is enter then this range of products are in the export file</li>
</ul></td>
</tr>
</table> |
<?php
namespace TYPO3\CMS\Lowlevel;
use TYPO3\CMS\Core\Utility\File\ExtendedFileUtility;
/**
* Looking for RTE images integrity
*/
class RteImagesCommand extends CleanerCommand {
/**
* @var bool
*/
public $checkRefIndex = TRUE;
/**
* @var ExtendedFileUtility
*/
protected $fileProcObj = NULL;
/**
* Constructor
*/
public function __construct() {
parent::__construct();
// Setting up help:
$this->cli_help['name'] = 'rte_images -- Looking up all occurencies of RTEmagic images in the database and check existence of parent and copy files on the file system plus report possibly lost files of this type.';
$this->cli_help['description'] = trim('
Assumptions:
- a perfect integrity of the reference index table (always update the reference index table before using this tool!)
- that all RTEmagic image files in the database are registered with the soft reference parser "images"
- images found in deleted records are included (means that you might find lost RTEmagic images after flushing deleted records)
The assumptions are not requirements by the TYPO3 API but reflects the de facto implementation of most TYPO3 installations.
However, many custom fields using an RTE will probably not have the "images" soft reference parser registered and so the index will be incomplete and not listing all RTEmagic image files.
The consequence of this limitation is that you should be careful if you wish to delete lost RTEmagic images - they could be referenced from a field not parsed by the "images" soft reference parser!
Automatic Repair of Errors:
- Will search for double-usages of RTEmagic images and make copies as required.
- Lost files can be deleted automatically by setting the value "lostFiles" as an optional parameter to --AUTOFIX, but otherwise delete them manually if you do not recognize them as used somewhere the system does not know about.
Manual repair suggestions:
- Missing files: Re-insert missing files or edit record where the reference is found.
');
$this->cli_help['examples'] = '/.../cli_dispatch.phpsh lowlevel_cleaner rte_images -s -r
Reports problems with RTE images';
}
/**
* Analyse situation with RTE magic images. (still to define what the most useful output is).
* Fix methods: API in \TYPO3\CMS\Core\Database\ReferenceIndex that allows to
* change the value of a reference (we could copy the files) or remove reference
*
* @return array
*/
public function main() {
// Initialize result array:
$resultArray = array(
'message' => $this->cli_help['name'] . LF . LF . $this->cli_help['description'],
'headers' => array(
'completeFileList' => array('Complete list of used RTEmagic files', 'Both parent and copy are listed here including usage count (which should in theory all be "1"). This list does not exclude files that might be missing.', 1),
'RTEmagicFilePairs' => array('Statistical info about RTEmagic files', '(copy used as index)', 0),
'doubleFiles' => array('Duplicate RTEmagic image files', 'These files are RTEmagic images found used in multiple records! RTEmagic images should be used by only one record at a time. A large amount of such images probably stems from previous versions of TYPO3 (before 4.2) which did not support making copies automatically of RTEmagic images in case of new copies / versions.', 3),
'missingFiles' => array('Missing RTEmagic image files', 'These files are not found in the file system! Should be corrected!', 3),
'lostFiles' => array('Lost RTEmagic files from uploads/', 'These files you might be able to delete but only if _all_ RTEmagic images are found by the soft reference parser. If you are using the RTE in third-party extensions it is likely that the soft reference parser is not applied correctly to their RTE and thus these "lost" files actually represent valid RTEmagic images, just not registered. Lost files can be auto-fixed but only if you specifically set "lostFiles" as parameter to the --AUTOFIX option.', 2)
),
'RTEmagicFilePairs' => array(),
'doubleFiles' => array(),
'completeFileList' => array(),
'missingFiles' => array(),
'lostFiles' => array()
);
// Select all RTEmagic files in the reference table (only from soft references of course)
$recs = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*', 'sys_refindex', 'ref_table=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('_FILE', 'sys_refindex') . ' AND ref_string LIKE ' . $GLOBALS['TYPO3_DB']->fullQuoteStr('%/RTEmagic%', 'sys_refindex') . ' AND softref_key=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('images', 'sys_refindex'), '', 'sorting DESC');
// Traverse the files and put into a large table:
if (is_array($recs)) {
foreach ($recs as $rec) {
$filename = basename($rec['ref_string']);
if (\TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($filename, 'RTEmagicC_')) {
$original = 'RTEmagicP_' . preg_replace('/\\.[[:alnum:]]+$/', '', substr($filename, 10));
$infoString = $this->infoStr($rec);
// Build index:
$resultArray['RTEmagicFilePairs'][$rec['ref_string']]['exists'] = @is_file((PATH_site . $rec['ref_string']));
$resultArray['RTEmagicFilePairs'][$rec['ref_string']]['original'] = substr($rec['ref_string'], 0, -strlen($filename)) . $original;
$resultArray['RTEmagicFilePairs'][$rec['ref_string']]['original_exists'] = @is_file((PATH_site . $resultArray['RTEmagicFilePairs'][$rec['ref_string']]['original']));
$resultArray['RTEmagicFilePairs'][$rec['ref_string']]['count']++;
$resultArray['RTEmagicFilePairs'][$rec['ref_string']]['usedIn'][$rec['hash']] = $infoString;
$resultArray['completeFileList'][$resultArray['RTEmagicFilePairs'][$rec['ref_string']]['original']]++;
$resultArray['completeFileList'][$rec['ref_string']]++;
// Missing files:
if (!$resultArray['RTEmagicFilePairs'][$rec['ref_string']]['exists']) {
$resultArray['missingFiles'][$rec['ref_string']] = $resultArray['RTEmagicFilePairs'][$rec['ref_string']]['usedIn'];
}
if (!$resultArray['RTEmagicFilePairs'][$rec['ref_string']]['original_exists']) {
$resultArray['missingFiles'][$resultArray['RTEmagicFilePairs'][$rec['ref_string']]['original']] = $resultArray['RTEmagicFilePairs'][$rec['ref_string']]['usedIn'];
}
}
}
// Searching for duplicates:
foreach ($resultArray['RTEmagicFilePairs'] as $fileName => $fileInfo) {
if ($fileInfo['count'] > 1 && $fileInfo['exists'] && $fileInfo['original_exists']) {
$resultArray['doubleFiles'][$fileName] = $fileInfo['usedIn'];
}
}
}
// Now, ask for RTEmagic files inside uploads/ folder:
$cleanerModules = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['lowlevel']['cleanerModules'];
$cleanerMode = \TYPO3\CMS\Core\Utility\GeneralUtility::getUserObj($cleanerModules['lost_files'][0]);
$resLostFiles = $cleanerMode->main(array(), FALSE, TRUE);
if (is_array($resLostFiles['RTEmagicFiles'])) {
foreach ($resLostFiles['RTEmagicFiles'] as $fileName) {
if (!isset($resultArray['completeFileList'][$fileName])) {
$resultArray['lostFiles'][$fileName] = $fileName;
}
}
}
ksort($resultArray['RTEmagicFilePairs']);
ksort($resultArray['completeFileList']);
ksort($resultArray['missingFiles']);
ksort($resultArray['doubleFiles']);
ksort($resultArray['lostFiles']);
return $resultArray;
}
/**
* Mandatory autofix function
* Will run auto-fix on the result array. Echos status during processing.
*
* @param array $resultArray Result array from main() function
* @return void
*/
public function main_autoFix($resultArray) {
$limitTo = $this->cli_args['--AUTOFIX'][0];
if (is_array($resultArray['doubleFiles'])) {
if (!$limitTo || $limitTo === 'doubleFiles') {
echo 'FIXING double-usages of RTE files in uploads/: ' . LF;
foreach ($resultArray['RTEmagicFilePairs'] as $fileName => $fileInfo) {
// Only fix something if there is a usage count of more than 1 plus if both original and copy exists:
if ($fileInfo['count'] > 1 && $fileInfo['exists'] && $fileInfo['original_exists']) {
// Traverse all records using the file:
$c = 0;
foreach ($fileInfo['usedIn'] as $hash => $recordID) {
if ($c == 0) {
echo ' Keeping file ' . $fileName . ' for record ' . $recordID . LF;
} else {
// CODE below is adapted from \TYPO3\CMS\Impexp\ImportExport where there is support for duplication of RTE images:
echo ' Copying file ' . basename($fileName) . ' for record ' . $recordID . ' ';
// Initialize; Get directory prefix for file and set the original name:
$dirPrefix = dirname($fileName) . '/';
$rteOrigName = basename($fileInfo['original']);
// If filename looks like an RTE file, and the directory is in "uploads/", then process as a RTE file!
if ($rteOrigName && \TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($dirPrefix, 'uploads/') && @is_dir((PATH_site . $dirPrefix))) {
// RTE:
// From the "original" RTE filename, produce a new "original" destination filename which is unused.
$fileProcObj = $this->getFileProcObj();
$origDestName = $fileProcObj->getUniqueName($rteOrigName, PATH_site . $dirPrefix);
// Create copy file name:
$pI = pathinfo($fileName);
$copyDestName = dirname($origDestName) . '/RTEmagicC_' . substr(basename($origDestName), 10) . '.' . $pI['extension'];
if (!@is_file($copyDestName) && !@is_file($origDestName) && $origDestName === \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($origDestName) && $copyDestName === \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($copyDestName)) {
echo ' to ' . basename($copyDestName);
if ($bypass = $this-><API key>($fileName)) {
echo $bypass;
} else {
// Making copies:
\TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move(PATH_site . $fileInfo['original'], $origDestName);
\TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move(PATH_site . $fileName, $copyDestName);
clearstatcache();
if (@is_file($copyDestName)) {
$sysRefObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\ReferenceIndex::class);
$error = $sysRefObj->setReferenceValue($hash, \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($copyDestName));
if ($error) {
echo ' - ERROR: TYPO3\\CMS\\Core\\Database\\ReferenceIndex::setReferenceValue(): ' . $error . LF;
die;
} else {
echo ' - DONE';
}
} else {
echo ' - ERROR: File "' . $copyDestName . '" was not created!';
}
}
} else {
echo ' - ERROR: Could not construct new unique names for file!';
}
} else {
echo ' - ERROR: Maybe directory of file was not within "uploads/"?';
}
echo LF;
}
$c++;
}
}
}
} else {
echo 'Bypassing fixing of double-usages since --AUTOFIX was not "doubleFiles"' . LF;
}
}
if (is_array($resultArray['lostFiles'])) {
if ($limitTo === 'lostFiles') {
echo 'Removing lost RTEmagic files from folders inside uploads/: ' . LF;
foreach ($resultArray['lostFiles'] as $key => $value) {
$absFileName = \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($value);
echo 'Deleting file: "' . $absFileName . '": ';
if ($bypass = $this-><API key>($absFileName)) {
echo $bypass;
} else {
if ($absFileName && @is_file($absFileName)) {
unlink($absFileName);
echo 'DONE';
} else {
echo ' ERROR: File "' . $absFileName . '" was not found!';
}
}
echo LF;
}
}
} else {
echo 'Bypassing fixing of double-usages since --AUTOFIX was not "lostFiles"' . LF;
}
}
/**
* Returns file processing object, initialized only once.
*
* @return ExtendedFileUtility File processor object
*/
public function getFileProcObj() {
if (!is_object($this->fileProcObj)) {
$this->fileProcObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(ExtendedFileUtility::class);
$this->fileProcObj->init(array(), $GLOBALS['TYPO3_CONF_VARS']['BE']['fileExtensions']);
$this->fileProcObj-><API key>();
}
return $this->fileProcObj;
}
} |
using System;
using Server;
using Server.Items;
namespace Server.Items
{
public abstract class BaseSpear : BaseMeleeWeapon
{
public override int DefHitSound{ get{ return 0x23C; } }
public override int DefMissSound{ get{ return 0x238; } }
public override SkillName DefSkill{ get{ return SkillName.Fencing; } }
public override WeaponType DefType{ get{ return WeaponType.Piercing; } }
public override WeaponAnimation DefAnimation{ get{ return WeaponAnimation.Pierce2H; } }
public BaseSpear( int itemID ) : base( itemID )
{
}
public BaseSpear( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
public override void OnHit( Mobile attacker, Mobile defender, double damageBonus )
{
base.OnHit( attacker, defender, damageBonus );
if ( !Core.AOS && Layer == Layer.TwoHanded && (attacker.Skills[SkillName.Anatomy].Value / 400.0) >= Utility.RandomDouble() && Engines.ConPVP.DuelContext.AllowSpecialAbility( attacker, "Paralyzing Blow", false ) )
{
defender.SendMessage( "You receive a paralyzing blow!" ); // Is this not localized?
defender.Freeze( TimeSpan.FromSeconds( 2.0 ) );
attacker.SendMessage( "You deliver a paralyzing blow!" ); // Is this not localized?
attacker.PlaySound( 0x11C );
}
if ( !Core.AOS && Poison != null && PoisonCharges > 0 )
{
--PoisonCharges;
if ( Utility.RandomDouble() >= 0.5 ) // 50% chance to poison
defender.ApplyPoison( attacker, Poison );
}
}
}
} |
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
unsigned int args[2];
pthread_barrier_t barrier;
pthread_t child_thread_2, child_thread_3;
void
sigusr1_handler (int signo)
{
}
void
callme (void)
{
}
void *
child_function_3 (void *arg)
{
int my_number = (long) arg;
volatile int *myp = (int *) &args[my_number];
<API key> (&barrier);
while (*myp > 0)
{
(*myp) ++;
callme (); /* set breakpoint thread 3 here */
}
pthread_exit (NULL);
}
void *
child_function_2 (void *arg)
{
int my_number = (long) arg;
volatile int *myp = (int *) &args[my_number];
<API key> (&barrier);
while (*myp > 0)
{
(*myp) ++;
callme (); /* set breakpoint thread 2 here */
}
pthread_exit (NULL);
}
static int
wait_threads (void)
{
return 1; /* in wait_threads */
}
int
main ()
{
int res;
long i;
signal (SIGUSR1, sigusr1_handler);
/* Call these early so that PLTs for these are resolved soon,
instead of in the threads. RTLD_NOW should work as well. */
usleep (0);
<API key> (&barrier, NULL, 1);
<API key> (&barrier);
<API key> (&barrier, NULL, 2);
i = 0;
args[i] = 1;
res = pthread_create (&child_thread_2,
NULL, child_function_2, (void *) i);
<API key> (&barrier);
callme ();
i = 1;
args[i] = 1;
res = pthread_create (&child_thread_3,
NULL, child_function_3, (void *) i);
<API key> (&barrier);
wait_threads (); /* set wait-threads breakpoint here */
pthread_join (child_thread_2, NULL);
pthread_join (child_thread_3, NULL);
exit(EXIT_SUCCESS);
} |
/** Generated Model - DO NOT CHANGE */
package org.compiere.model;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.Properties;
import org.compiere.util.KeyNamePair;
/** Generated Model for B_Buyer
* @author Adempiere (generated)
* @version Release 3.8.0 - $Id$ */
public class X_B_Buyer extends PO implements I_B_Buyer, I_Persistent
{
private static final long serialVersionUID = 20150223L;
/** Standard Constructor */
public X_B_Buyer (Properties ctx, int B_Buyer_ID, String trxName)
{
super (ctx, B_Buyer_ID, trxName);
/** if (B_Buyer_ID == 0)
{
setAD_User_ID (0);
setName (null);
setValidTo (new Timestamp( System.currentTimeMillis() ));
} */
}
/** Load Constructor */
public X_B_Buyer (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 3 - Client - Org
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_B_Buyer[")
.append(get_ID()).append("]");
return sb.toString();
}
public org.compiere.model.I_AD_User getAD_User() throws RuntimeException
{
return (org.compiere.model.I_AD_User)MTable.get(getCtx(), org.compiere.model.I_AD_User.Table_Name)
.getPO(getAD_User_ID(), get_TrxName()); }
/** Set User/Contact.
@param AD_User_ID
User within the system - Internal or Business Partner Contact
*/
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 1)
set_ValueNoCheck (<API key>, null);
else
set_ValueNoCheck (<API key>, Integer.valueOf(AD_User_ID));
}
/** Get User/Contact.
@return User within the system - Internal or Business Partner Contact
*/
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(<API key>);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (<API key>, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(<API key>);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} |
<?php
namespace Drupal\views\Plugin\views\row;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Renders an RSS item based on fields.
*
* @ViewsRow(
* id = "rss_fields",
* title = @Translation("Fields"),
* help = @Translation("Display fields as RSS items."),
* theme = "views_view_row_rss",
* display_types = {"feed"}
* )
*/
class RssFields extends RowPluginBase {
/**
* Does the row plugin support to add fields to its output.
*
* @var bool
*/
protected $usesFields = TRUE;
protected function defineOptions() {
$options = parent::defineOptions();
$options['title_field'] = ['default' => ''];
$options['link_field'] = ['default' => ''];
$options['description_field'] = ['default' => ''];
$options['creator_field'] = ['default' => ''];
$options['date_field'] = ['default' => ''];
$options['guid_field_options']['contains']['guid_field'] = ['default' => ''];
$options['guid_field_options']['contains']['<API key>'] = ['default' => TRUE];
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$initial_labels = ['' => $this->t('- None -')];
$view_fields_labels = $this->displayHandler->getFieldLabels();
$view_fields_labels = array_merge($initial_labels, $view_fields_labels);
$form['title_field'] = [
'#type' => 'select',
'#title' => $this->t('Title field'),
'#description' => $this->t('The field that is going to be used as the RSS item title for each row.'),
'#options' => $view_fields_labels,
'#default_value' => $this->options['title_field'],
'#required' => TRUE,
];
$form['link_field'] = [
'#type' => 'select',
'#title' => $this->t('Link field'),
'#description' => $this->t('The field that is going to be used as the RSS item link for each row. This must either be an internal unprocessed path like "node/123" or a processed, root-relative URL as produced by fields like "Link to content".'),
'#options' => $view_fields_labels,
'#default_value' => $this->options['link_field'],
'#required' => TRUE,
];
$form['description_field'] = [
'#type' => 'select',
'#title' => $this->t('Description field'),
'#description' => $this->t('The field that is going to be used as the RSS item description for each row.'),
'#options' => $view_fields_labels,
'#default_value' => $this->options['description_field'],
'#required' => TRUE,
];
$form['creator_field'] = [
'#type' => 'select',
'#title' => $this->t('Creator field'),
'#description' => $this->t('The field that is going to be used as the RSS item creator for each row.'),
'#options' => $view_fields_labels,
'#default_value' => $this->options['creator_field'],
'#required' => TRUE,
];
$form['date_field'] = [
'#type' => 'select',
'#title' => $this->t('Publication date field'),
'#description' => $this->t('The field that is going to be used as the RSS item pubDate for each row. It needs to be in RFC 2822 format.'),
'#options' => $view_fields_labels,
'#default_value' => $this->options['date_field'],
'#required' => TRUE,
];
$form['guid_field_options'] = [
'#type' => 'details',
'#title' => $this->t('GUID settings'),
'#open' => TRUE,
];
$form['guid_field_options']['guid_field'] = [
'#type' => 'select',
'#title' => $this->t('GUID field'),
'#description' => $this->t('The globally unique identifier of the RSS item.'),
'#options' => $view_fields_labels,
'#default_value' => $this->options['guid_field_options']['guid_field'],
'#required' => TRUE,
];
$form['guid_field_options']['<API key>'] = [
'#type' => 'checkbox',
'#title' => $this->t('GUID is permalink'),
'#description' => $this->t('The RSS item GUID is a permalink.'),
'#default_value' => $this->options['guid_field_options']['<API key>'],
];
}
public function validate() {
$errors = parent::validate();
$required_options = ['title_field', 'link_field', 'description_field', 'creator_field', 'date_field'];
foreach ($required_options as $required_option) {
if (empty($this->options[$required_option])) {
$errors[] = $this->t('Row style plugin requires specifying which views fields to use for RSS item.');
break;
}
}
// Once more for guid.
if (empty($this->options['guid_field_options']['guid_field'])) {
$errors[] = $this->t('Row style plugin requires specifying which views fields to use for RSS item.');
}
return $errors;
}
public function render($row) {
static $row_index;
if (!isset($row_index)) {
$row_index = 0;
}
if (function_exists('rdf_get_namespaces')) {
// Merge RDF namespaces in the XML namespaces in case they are used
// further in the RSS content.
$xml_rdf_namespaces = [];
foreach (rdf_get_namespaces() as $prefix => $uri) {
$xml_rdf_namespaces['xmlns:' . $prefix] = $uri;
}
$this->view->style_plugin->namespaces += $xml_rdf_namespaces;
}
// Create the RSS item object.
$item = new \stdClass();
$item->title = $this->getField($row_index, $this->options['title_field']);
$item->link = $this->getAbsoluteUrl($this->getField($row_index, $this->options['link_field']));
$field = $this->getField($row_index, $this->options['description_field']);
$item->description = is_array($field) ? $field : ['#markup' => $field];
$item->elements = [
['key' => 'pubDate', 'value' => $this->getField($row_index, $this->options['date_field'])],
[
'key' => 'dc:creator',
'value' => $this->getField($row_index, $this->options['creator_field']),
'namespace' => ['xmlns:dc' => 'http://purl.org/dc/elements/1.1/'],
],
];
$<API key> = 'false';
$item_guid = $this->getField($row_index, $this->options['guid_field_options']['guid_field']);
if ($this->options['guid_field_options']['<API key>']) {
$<API key> = 'true';
$item_guid = $this->getAbsoluteUrl($item_guid);
}
$item->elements[] = [
'key' => 'guid',
'value' => $item_guid,
'attributes' => ['isPermaLink' => $<API key>],
];
$row_index++;
foreach ($item->elements as $element) {
if (isset($element['namespace'])) {
$this->view->style_plugin->namespaces = array_merge($this->view->style_plugin->namespaces, $element['namespace']);
}
}
$build = [
'#theme' => $this->themeFunctions(),
'#view' => $this->view,
'#options' => $this->options,
'#row' => $item,
'#field_alias' => $this->field_alias ?? '',
];
return $build;
}
/**
* Retrieves a views field value from the style plugin.
*
* @param $index
* The index count of the row as expected by views_plugin_style::getField().
* @param $field_id
* The ID assigned to the required field in the display.
*
* @return string|null|\Drupal\Component\Render\MarkupInterface
* An empty string if there is no style plugin, or the field ID is empty.
* NULL if the field value is empty. If neither of these conditions apply,
* a MarkupInterface object containing the rendered field value.
*/
public function getField($index, $field_id) {
if (empty($this->view->style_plugin) || !is_object($this->view->style_plugin) || empty($field_id)) {
return '';
}
return $this->view->style_plugin->getField($index, $field_id);
}
/**
* Convert a rendered URL string to an absolute URL.
*
* @param string $url_string
* The rendered field value ready for display in a normal view.
*
* @return string
* A string with an absolute URL.
*/
protected function getAbsoluteUrl($url_string) {
// If the given URL already starts with a leading slash, it's been processed
// and we need to simply make it an absolute path by prepending the host.
if (strpos($url_string, '/') === 0) {
$host = \Drupal::request()-><API key>();
// @todo Views should expect and store a leading /.
return $host . $url_string;
}
// Otherwise, this is an unprocessed path (e.g. node/123) and we need to run
// it through a Url object to allow outbound path processors to run (path
// aliases, language prefixes, etc).
else {
return Url::fromUserInput('/' . $url_string)->setAbsolute()->toString();
}
}
} |
#include "sha1.h"
#include <string.h>
#include <stdio.h>
void sha1_init(sha1_state_t *ctx)
{
*ctx = g_checksum_new(G_CHECKSUM_SHA1);
}
void sha1_append(sha1_state_t *ctx, const guint8 * message_array, guint len)
{
g_checksum_update(*ctx, message_array, len);
}
void sha1_finish(sha1_state_t *ctx, guint8 digest[SHA1_HASH_SIZE])
{
gsize digest_len = SHA1_HASH_SIZE;
<API key>(*ctx, digest, &digest_len);
g_checksum_free(*ctx);
}
#define HMAC_BLOCK_SIZE 64
/* BitlBee addition: */
void sha1_hmac(const char *key_, size_t key_len, const char *payload, size_t payload_len, guint8 digest[SHA1_HASH_SIZE])
{
sha1_state_t sha1;
guint8 hash[SHA1_HASH_SIZE];
guint8 key[HMAC_BLOCK_SIZE + 1];
int i;
if (key_len == 0) {
key_len = strlen(key_);
}
if (payload_len == 0) {
payload_len = strlen(payload);
}
/* Create K. If our current key is >64 chars we have to hash it,
otherwise just pad. */
memset(key, 0, HMAC_BLOCK_SIZE + 1);
if (key_len > HMAC_BLOCK_SIZE) {
sha1_init(&sha1);
sha1_append(&sha1, (guint8 *) key_, key_len);
sha1_finish(&sha1, key);
} else {
memcpy(key, key_, key_len);
}
/* Inner part: H(K XOR 0x36, text) */
sha1_init(&sha1);
for (i = 0; i < HMAC_BLOCK_SIZE; i++) {
key[i] ^= 0x36;
}
sha1_append(&sha1, key, HMAC_BLOCK_SIZE);
sha1_append(&sha1, (const guint8 *) payload, payload_len);
sha1_finish(&sha1, hash);
/* Final result: H(K XOR 0x5C, inner stuff) */
sha1_init(&sha1);
for (i = 0; i < HMAC_BLOCK_SIZE; i++) {
key[i] ^= 0x36 ^ 0x5c;
}
sha1_append(&sha1, key, HMAC_BLOCK_SIZE);
sha1_append(&sha1, hash, SHA1_HASH_SIZE);
sha1_finish(&sha1, digest);
}
char *sha1_random_uuid(sha1_state_t * context)
{
guint8 dig[SHA1_HASH_SIZE];
char *ret = g_new0(char, 40); /* 36 chars + \0 */
int i, p;
sha1_finish(context, dig);
for (p = i = 0; i < 16; i++) {
if (i == 4 || i == 6 || i == 8 || i == 10) {
ret[p++] = '-';
}
if (i == 6) {
dig[i] = (dig[i] & 0x0f) | 0x40;
}
if (i == 8) {
dig[i] = (dig[i] & 0x30) | 0x80;
}
sprintf(ret + p, "%02x", dig[i]);
p += 2;
}
ret[p] = '\0';
return ret;
} |
<?php
namespace Drupal\Tests\node\Functional;
use Drupal\Core\Database\Database;
use Drupal\user\RoleInterface;
/**
* Tests node administration page functionality.
*
* @group node
*/
class NodeAdminTest extends NodeTestBase {
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'classy';
protected $adminUser;
protected $baseUser1;
protected $baseUser2;
protected $baseUser3;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['views'];
protected function setUp() {
parent::setUp();
// correctly.
<API key>(RoleInterface::AUTHENTICATED_ID, ['view own unpublished content']);
$this->adminUser = $this->drupalCreateUser(['access administration pages', 'access content overview', 'administer nodes', 'bypass node access']);
$this->baseUser1 = $this->drupalCreateUser(['access content overview']);
$this->baseUser2 = $this->drupalCreateUser(['access content overview', 'view own unpublished content']);
$this->baseUser3 = $this->drupalCreateUser(['access content overview', 'bypass node access']);
}
/**
* Tests that the table sorting works on the content admin pages.
*/
public function <API key>() {
$this->drupalLogin($this->adminUser);
$changed = REQUEST_TIME;
$connection = Database::getConnection();
foreach (['dd', 'aa', 'DD', 'bb', 'cc', 'CC', 'AA', 'BB'] as $prefix) {
$changed += 1000;
$node = $this->drupalCreateNode(['title' => $prefix . $this->randomMachineName(6)]);
$connection->update('node_field_data')
->fields(['changed' => $changed])
->condition('nid', $node->id())
->execute();
}
// Test that the default sort by node.changed DESC actually fires properly.
$nodes_query = $connection->select('node_field_data', 'n')
->fields('n', ['title'])
->orderBy('changed', 'DESC')
->execute()
->fetchCol();
$this->drupalGet('admin/content');
foreach ($nodes_query as $delta => $string) {
$elements = $this->xpath('//table[contains(@class, :class)]/tbody/tr[' . ($delta + 1) . ']/td[2]/a[normalize-space(text())=:label]', [':class' => 'views-table', ':label' => $string]);
$this->assertTrue(!empty($elements), 'The node was found in the correct order.');
}
// Compare the rendered HTML node list to a query for the nodes ordered by
// title to account for possible database-dependent sort order.
$nodes_query = $connection->select('node_field_data', 'n')
->fields('n', ['title'])
->orderBy('title')
->execute()
->fetchCol();
$this->drupalGet('admin/content', ['query' => ['sort' => 'asc', 'order' => 'title']]);
foreach ($nodes_query as $delta => $string) {
$elements = $this->xpath('//table[contains(@class, :class)]/tbody/tr[' . ($delta + 1) . ']/td[2]/a[normalize-space(text())=:label]', [':class' => 'views-table', ':label' => $string]);
$this->assertTrue(!empty($elements), 'The node was found in the correct order.');
}
}
public function <API key>() {
$this->drupalLogin($this->adminUser);
// Use an explicit changed time to ensure the expected order in the content
// admin listing. We want these to appear in the table in the same order as
// they appear in the following code, and the 'content' View has a table
// style configuration with a default sort on the 'changed' field DESC.
$time = time();
$nodes['published_page'] = $this->drupalCreateNode(['type' => 'page', 'changed' => $time
$nodes['published_article'] = $this->drupalCreateNode(['type' => 'article', 'changed' => $time
$nodes['unpublished_page_1'] = $this->drupalCreateNode(['type' => 'page', 'changed' => $time--, 'uid' => $this->baseUser1->id(), 'status' => 0]);
$nodes['unpublished_page_2'] = $this->drupalCreateNode(['type' => 'page', 'changed' => $time, 'uid' => $this->baseUser2->id(), 'status' => 0]);
// Verify view, edit, and delete links for any content.
$this->drupalGet('admin/content');
$this->assertResponse(200);
$node_type_labels = $this->xpath('//td[contains(@class, "views-field-type")]');
$delta = 0;
foreach ($nodes as $node) {
$this->assertLinkByHref('node/' . $node->id());
$this->assertLinkByHref('node/' . $node->id() . '/edit');
$this->assertLinkByHref('node/' . $node->id() . '/delete');
// Verify that we can see the content type label.
$this->assertEqual(trim($node_type_labels[$delta]->getText()), $node->type->entity->label());
$delta++;
}
// Verify filtering by publishing status.
$this->drupalGet('admin/content', ['query' => ['status' => TRUE]]);
$this->assertLinkByHref('node/' . $nodes['published_page']->id() . '/edit');
$this->assertLinkByHref('node/' . $nodes['published_article']->id() . '/edit');
$this->assertNoLinkByHref('node/' . $nodes['unpublished_page_1']->id() . '/edit');
// Verify filtering by status and content type.
$this->drupalGet('admin/content', ['query' => ['status' => TRUE, 'type' => 'page']]);
$this->assertLinkByHref('node/' . $nodes['published_page']->id() . '/edit');
$this->assertNoLinkByHref('node/' . $nodes['published_article']->id() . '/edit');
// Verify no operation links are displayed for regular users.
$this->drupalLogout();
$this->drupalLogin($this->baseUser1);
$this->drupalGet('admin/content');
$this->assertResponse(200);
$this->assertLinkByHref('node/' . $nodes['published_page']->id());
$this->assertLinkByHref('node/' . $nodes['published_article']->id());
$this->assertNoLinkByHref('node/' . $nodes['published_page']->id() . '/edit');
$this->assertNoLinkByHref('node/' . $nodes['published_page']->id() . '/delete');
$this->assertNoLinkByHref('node/' . $nodes['published_article']->id() . '/edit');
$this->assertNoLinkByHref('node/' . $nodes['published_article']->id() . '/delete');
$this->assertNoLinkByHref('node/' . $nodes['unpublished_page_1']->id());
$this->assertNoLinkByHref('node/' . $nodes['unpublished_page_1']->id() . '/edit');
$this->assertNoLinkByHref('node/' . $nodes['unpublished_page_1']->id() . '/delete');
// Verify no tableselect.
$this->assertNoFieldByName('nodes[' . $nodes['published_page']->id() . ']', '', 'No tableselect found.');
$this->drupalLogout();
$this->drupalLogin($this->baseUser2);
$this->drupalGet('admin/content');
$this->assertResponse(200);
$this->assertLinkByHref('node/' . $nodes['unpublished_page_2']->id());
// Verify no operation links are displayed.
$this->assertNoLinkByHref('node/' . $nodes['unpublished_page_2']->id() . '/edit');
$this->assertNoLinkByHref('node/' . $nodes['unpublished_page_2']->id() . '/delete');
// Verify user cannot see unpublished content of other users.
$this->assertNoLinkByHref('node/' . $nodes['unpublished_page_1']->id());
$this->assertNoLinkByHref('node/' . $nodes['unpublished_page_1']->id() . '/edit');
$this->assertNoLinkByHref('node/' . $nodes['unpublished_page_1']->id() . '/delete');
// Verify no tableselect.
$this->assertNoFieldByName('nodes[' . $nodes['unpublished_page_2']->id() . ']', '', 'No tableselect found.');
// Verify node access can be bypassed.
$this->drupalLogout();
$this->drupalLogin($this->baseUser3);
$this->drupalGet('admin/content');
$this->assertResponse(200);
foreach ($nodes as $node) {
$this->assertLinkByHref('node/' . $node->id());
$this->assertLinkByHref('node/' . $node->id() . '/edit');
$this->assertLinkByHref('node/' . $node->id() . '/delete');
}
}
} |
#include <linux/err.h>
#include <linux/kernel.h>
#include <linux/reboot.h>
#include <linux/platform_data/emif_plat.h>
#include <linux/io.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/of.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <linux/module.h>
#include <linux/list.h>
#include <linux/spinlock.h>
#include <linux/pm.h>
#include <memory/jedec_ddr.h>
#include "emif.h"
#include "of_memory.h"
/**
* struct emif_data - Per device static data for driver's use
* @duplicate: Whether the DDR devices attached to this EMIF
* instance are exactly same as that on EMIF1. In
* this case we can save some memory and processing
* @temperature_level: Maximum temperature of LPDDR2 devices attached
* to this EMIF - read from MR4 register. If there
* are two devices attached to this EMIF, this
* value is the maximum of the two temperature
* levels.
* @node: node in the device list
* @base: base address of memory-mapped IO registers.
* @dev: device pointer.
* @addressing table with addressing information from the spec
* @regs_cache: An array of 'struct emif_regs' that stores
* calculated register values for different
* frequencies, to avoid re-calculating them on
* each DVFS transition.
* @curr_regs: The set of register values used in the last
* frequency change (i.e. corresponding to the
* frequency in effect at the moment)
* @plat_data: Pointer to saved platform data.
* @debugfs_root: dentry to the root folder for EMIF in debugfs
* @np_ddr: Pointer to ddr device tree node
*/
struct emif_data {
u8 duplicate;
u8 temperature_level;
u8 lpmode;
struct list_head node;
unsigned long irq_state;
void __iomem *base;
struct device *dev;
const struct lpddr2_addressing *addressing;
struct emif_regs *regs_cache[<API key>];
struct emif_regs *curr_regs;
struct emif_platform_data *plat_data;
struct dentry *debugfs_root;
struct device_node *np_ddr;
};
static struct emif_data *emif1;
static spinlock_t emif_lock;
static unsigned long irq_state;
static u32 t_ck; /* DDR clock period in ps */
static LIST_HEAD(device_list);
#ifdef CONFIG_DEBUG_FS
static void <API key>(struct seq_file *s, struct emif_data *emif,
struct emif_regs *regs)
{
u32 type = emif->plat_data->device_info->type;
u32 ip_rev = emif->plat_data->ip_rev;
seq_printf(s, "EMIF register cache dump for %dMHz\n",
regs->freq/1000000);
seq_printf(s, "ref_ctrl_shdw\t: 0x%08x\n", regs->ref_ctrl_shdw);
seq_printf(s, "sdram_tim1_shdw\t: 0x%08x\n", regs->sdram_tim1_shdw);
seq_printf(s, "sdram_tim2_shdw\t: 0x%08x\n", regs->sdram_tim2_shdw);
seq_printf(s, "sdram_tim3_shdw\t: 0x%08x\n", regs->sdram_tim3_shdw);
if (ip_rev == EMIF_4D) {
seq_printf(s, "<API key>\t: 0x%08x\n",
regs-><API key>);
seq_printf(s, "<API key>\t: 0x%08x\n",
regs-><API key>);
} else if (ip_rev == EMIF_4D5) {
seq_printf(s, "<API key>\t: 0x%08x\n",
regs-><API key>);
seq_printf(s, "<API key>\t: 0x%08x\n",
regs-><API key>);
}
if (type == DDR_TYPE_LPDDR2_S2 || type == DDR_TYPE_LPDDR2_S4) {
seq_printf(s, "<API key>\t: 0x%08x\n",
regs-><API key>);
seq_printf(s, "<API key>\t: 0x%08x\n",
regs-><API key>);
seq_printf(s, "<API key>\t: 0x%08x\n",
regs-><API key>);
}
}
static int emif_regdump_show(struct seq_file *s, void *unused)
{
struct emif_data *emif = s->private;
struct emif_regs **regs_cache;
int i;
if (emif->duplicate)
regs_cache = emif1->regs_cache;
else
regs_cache = emif->regs_cache;
for (i = 0; i < <API key> && regs_cache[i]; i++) {
<API key>(s, emif, regs_cache[i]);
seq_printf(s, "\n");
}
return 0;
}
static int emif_regdump_open(struct inode *inode, struct file *file)
{
return single_open(file, emif_regdump_show, inode->i_private);
}
static const struct file_operations emif_regdump_fops = {
.open = emif_regdump_open,
.read = seq_read,
.release = single_release,
};
static int emif_mr4_show(struct seq_file *s, void *unused)
{
struct emif_data *emif = s->private;
seq_printf(s, "MR4=%d\n", emif->temperature_level);
return 0;
}
static int emif_mr4_open(struct inode *inode, struct file *file)
{
return single_open(file, emif_mr4_show, inode->i_private);
}
static const struct file_operations emif_mr4_fops = {
.open = emif_mr4_open,
.read = seq_read,
.release = single_release,
};
static int __init_or_module emif_debugfs_init(struct emif_data *emif)
{
struct dentry *dentry;
int ret;
dentry = debugfs_create_dir(dev_name(emif->dev), NULL);
if (!dentry) {
ret = -ENOMEM;
goto err0;
}
emif->debugfs_root = dentry;
dentry = debugfs_create_file("regcache_dump", S_IRUGO,
emif->debugfs_root, emif, &emif_regdump_fops);
if (!dentry) {
ret = -ENOMEM;
goto err1;
}
dentry = debugfs_create_file("mr4", S_IRUGO,
emif->debugfs_root, emif, &emif_mr4_fops);
if (!dentry) {
ret = -ENOMEM;
goto err1;
}
return 0;
err1:
<API key>(emif->debugfs_root);
err0:
return ret;
}
static void __exit emif_debugfs_exit(struct emif_data *emif)
{
<API key>(emif->debugfs_root);
emif->debugfs_root = NULL;
}
#else
static inline int __init_or_module emif_debugfs_init(struct emif_data *emif)
{
return 0;
}
static inline void __exit emif_debugfs_exit(struct emif_data *emif)
{
}
#endif
/*
* Calculate the period of DDR clock from frequency value
*/
static void set_ddr_clk_period(u32 freq)
{
/* Divide 10^12 by frequency to get period in ps */
t_ck = (u32)DIV_ROUND_UP_ULL(1000000000000ull, freq);
}
/*
* Get bus width used by EMIF. Note that this may be different from the
* bus width of the DDR devices used. For instance two 16-bit DDR devices
* may be connected to a given CS of EMIF. In this case bus width as far
* as EMIF is concerned is 32, where as the DDR bus width is 16 bits.
*/
static u32 get_emif_bus_width(struct emif_data *emif)
{
u32 width;
void __iomem *base = emif->base;
width = (readl(base + EMIF_SDRAM_CONFIG) & NARROW_MODE_MASK)
>> NARROW_MODE_SHIFT;
width = width == 0 ? 32 : 16;
return width;
}
/*
* Get the CL from SDRAM_CONFIG register
*/
static u32 get_cl(struct emif_data *emif)
{
u32 cl;
void __iomem *base = emif->base;
cl = (readl(base + EMIF_SDRAM_CONFIG) & CL_MASK) >> CL_SHIFT;
return cl;
}
static void set_lpmode(struct emif_data *emif, u8 lpmode)
{
u32 temp;
void __iomem *base = emif->base;
/*
* Workaround for errata i743 - LPDDR2 Power-Down State is Not
* Efficient
*
* i743 DESCRIPTION:
* The EMIF supports power-down state for low power. The EMIF
* automatically puts the SDRAM into power-down after the memory is
* not accessed for a defined number of cycles and the
* EMIF_PWR_MGMT_CTRL[10:8] REG_LP_MODE bit field is set to 0x4.
* As the EMIF supports automatic output impedance calibration, a ZQ
* calibration long command is issued every time it exits active
* power-down and precharge power-down modes. The EMIF waits and
* blocks any other command during this calibration.
* The EMIF does not allow selective disabling of ZQ calibration upon
* exit of power-down mode. Due to very short periods of power-down
* cycles, ZQ calibration overhead creates bandwidth issues and
* increases overall system power consumption. On the other hand,
* issuing ZQ calibration long commands when exiting self-refresh is
* still required.
*
* WORKAROUND
* Because there is no power consumption benefit of the power-down due
* to the calibration and there is a performance risk, the guideline
* is to not allow power-down state and, therefore, to not have set
* the EMIF_PWR_MGMT_CTRL[10:8] REG_LP_MODE bit field to 0x4.
*/
if ((emif->plat_data->ip_rev == EMIF_4D) &&
(EMIF_LP_MODE_PWR_DN == lpmode)) {
WARN_ONCE(1,
"REG_LP_MODE = LP_MODE_PWR_DN(4) is prohibited by"
"erratum i743 switch to <API key>(2)\n");
/* rollback LP_MODE to Self-refresh mode */
lpmode = <API key>;
}
temp = readl(base + <API key>);
temp &= ~LP_MODE_MASK;
temp |= (lpmode << LP_MODE_SHIFT);
writel(temp, base + <API key>);
}
static void do_freq_update(void)
{
struct emif_data *emif;
/*
* Workaround for errata i728: Disable LPMODE during FREQ_UPDATE
*
* i728 DESCRIPTION:
* The EMIF automatically puts the SDRAM into self-refresh mode
* after the EMIF has not performed accesses during
* EMIF_PWR_MGMT_CTRL[7:4] REG_SR_TIM number of DDR clock cycles
* and the EMIF_PWR_MGMT_CTRL[10:8] REG_LP_MODE bit field is set
* to 0x2. If during a small window the following three events
* occur:
* - The SR_TIMING counter expires
* - And frequency change is requested
* - And OCP access is requested
* Then it causes instable clock on the DDR interface.
*
* WORKAROUND
* To avoid the occurrence of the three events, the workaround
* is to disable the self-refresh when requesting a frequency
* change. Before requesting a frequency change the software must
* program EMIF_PWR_MGMT_CTRL[10:8] REG_LP_MODE to 0x0. When the
* frequency change has been done, the software can reprogram
* EMIF_PWR_MGMT_CTRL[10:8] REG_LP_MODE to 0x2
*/
list_for_each_entry(emif, &device_list, node) {
if (emif->lpmode == <API key>)
set_lpmode(emif, <API key>);
}
/*
* TODO: Do FREQ_UPDATE here when an API
* is available for this as part of the new
* clock framework
*/
list_for_each_entry(emif, &device_list, node) {
if (emif->lpmode == <API key>)
set_lpmode(emif, <API key>);
}
}
/* Find addressing table entry based on the device's type and density */
static const struct lpddr2_addressing *<API key>(
const struct ddr_device_info *device_info)
{
u32 index, type, density;
type = device_info->type;
density = device_info->density;
switch (type) {
case DDR_TYPE_LPDDR2_S4:
index = density - 1;
break;
case DDR_TYPE_LPDDR2_S2:
switch (density) {
case DDR_DENSITY_1Gb:
case DDR_DENSITY_2Gb:
index = density + 3;
break;
default:
index = density - 1;
}
break;
default:
return NULL;
}
return &<API key>[index];
}
/*
* Find the the right timing table from the array of timing
* tables of the device using DDR clock frequency
*/
static const struct lpddr2_timings *get_timings_table(struct emif_data *emif,
u32 freq)
{
u32 i, min, max, freq_nearest;
const struct lpddr2_timings *timings = NULL;
const struct lpddr2_timings *timings_arr = emif->plat_data->timings;
struct device *dev = emif->dev;
/* Start with a very high frequency - 1GHz */
freq_nearest = 1000000000;
/*
* Find the timings table such that:
* 1. the frequency range covers the required frequency(safe) AND
* 2. the max_freq is closest to the required frequency(optimal)
*/
for (i = 0; i < emif->plat_data->timings_arr_size; i++) {
max = timings_arr[i].max_freq;
min = timings_arr[i].min_freq;
if ((freq >= min) && (freq <= max) && (max < freq_nearest)) {
freq_nearest = max;
timings = &timings_arr[i];
}
}
if (!timings)
dev_err(dev, "%s: couldn't find timings for - %dHz\n",
__func__, freq);
dev_dbg(dev, "%s: timings table: freq %d, speed bin freq %d\n",
__func__, freq, freq_nearest);
return timings;
}
static u32 <API key>(u32 freq,
const struct lpddr2_addressing *addressing)
{
u32 ref_ctrl_shdw = 0, val = 0, freq_khz, t_refi;
/* Scale down frequency and t_refi to avoid overflow */
freq_khz = freq / 1000;
t_refi = addressing->tREFI_ns / 100;
/*
* refresh rate to be set is 'tREFI(in us) * freq in MHz
* division by 10000 to account for change in units
*/
val = t_refi * freq_khz / 10000;
ref_ctrl_shdw |= val << REFRESH_RATE_SHIFT;
return ref_ctrl_shdw;
}
static u32 <API key>(const struct lpddr2_timings *timings,
const struct lpddr2_min_tck *min_tck,
const struct lpddr2_addressing *addressing)
{
u32 tim1 = 0, val = 0;
val = max(min_tck->tWTR, DIV_ROUND_UP(timings->tWTR, t_ck)) - 1;
tim1 |= val << T_WTR_SHIFT;
if (addressing->num_banks == B8)
val = DIV_ROUND_UP(timings->tFAW, t_ck*4);
else
val = max(min_tck->tRRD, DIV_ROUND_UP(timings->tRRD, t_ck));
tim1 |= (val - 1) << T_RRD_SHIFT;
val = DIV_ROUND_UP(timings->tRAS_min + timings->tRPab, t_ck) - 1;
tim1 |= val << T_RC_SHIFT;
val = max(min_tck->tRASmin, DIV_ROUND_UP(timings->tRAS_min, t_ck));
tim1 |= (val - 1) << T_RAS_SHIFT;
val = max(min_tck->tWR, DIV_ROUND_UP(timings->tWR, t_ck)) - 1;
tim1 |= val << T_WR_SHIFT;
val = max(min_tck->tRCD, DIV_ROUND_UP(timings->tRCD, t_ck)) - 1;
tim1 |= val << T_RCD_SHIFT;
val = max(min_tck->tRPab, DIV_ROUND_UP(timings->tRPab, t_ck)) - 1;
tim1 |= val << T_RP_SHIFT;
return tim1;
}
static u32 <API key>(const struct lpddr2_timings *timings,
const struct lpddr2_min_tck *min_tck,
const struct lpddr2_addressing *addressing)
{
u32 tim1 = 0, val = 0;
val = max(min_tck->tWTR, DIV_ROUND_UP(timings->tWTR, t_ck)) - 1;
tim1 = val << T_WTR_SHIFT;
/*
* tFAW is approximately 4 times tRRD. So add 1875*4 = 7500ps
* to tFAW for de-rating
*/
if (addressing->num_banks == B8) {
val = DIV_ROUND_UP(timings->tFAW + 7500, 4 * t_ck) - 1;
} else {
val = DIV_ROUND_UP(timings->tRRD + 1875, t_ck);
val = max(min_tck->tRRD, val) - 1;
}
tim1 |= val << T_RRD_SHIFT;
val = DIV_ROUND_UP(timings->tRAS_min + timings->tRPab + 1875, t_ck);
tim1 |= (val - 1) << T_RC_SHIFT;
val = DIV_ROUND_UP(timings->tRAS_min + 1875, t_ck);
val = max(min_tck->tRASmin, val) - 1;
tim1 |= val << T_RAS_SHIFT;
val = max(min_tck->tWR, DIV_ROUND_UP(timings->tWR, t_ck)) - 1;
tim1 |= val << T_WR_SHIFT;
val = max(min_tck->tRCD, DIV_ROUND_UP(timings->tRCD + 1875, t_ck));
tim1 |= (val - 1) << T_RCD_SHIFT;
val = max(min_tck->tRPab, DIV_ROUND_UP(timings->tRPab + 1875, t_ck));
tim1 |= (val - 1) << T_RP_SHIFT;
return tim1;
}
static u32 <API key>(const struct lpddr2_timings *timings,
const struct lpddr2_min_tck *min_tck,
const struct lpddr2_addressing *addressing,
u32 type)
{
u32 tim2 = 0, val = 0;
val = min_tck->tCKE - 1;
tim2 |= val << T_CKE_SHIFT;
val = max(min_tck->tRTP, DIV_ROUND_UP(timings->tRTP, t_ck)) - 1;
tim2 |= val << T_RTP_SHIFT;
/* tXSNR = tRFCab_ps + 10 ns(tRFCab_ps for LPDDR2). */
val = DIV_ROUND_UP(addressing->tRFCab_ps + 10000, t_ck) - 1;
tim2 |= val << T_XSNR_SHIFT;
/* XSRD same as XSNR for LPDDR2 */
tim2 |= val << T_XSRD_SHIFT;
val = max(min_tck->tXP, DIV_ROUND_UP(timings->tXP, t_ck)) - 1;
tim2 |= val << T_XP_SHIFT;
return tim2;
}
static u32 <API key>(const struct lpddr2_timings *timings,
const struct lpddr2_min_tck *min_tck,
const struct lpddr2_addressing *addressing,
u32 type, u32 ip_rev, u32 derated)
{
u32 tim3 = 0, val = 0, t_dqsck;
val = timings->tRAS_max_ns / addressing->tREFI_ns - 1;
val = val > 0xF ? 0xF : val;
tim3 |= val << T_RAS_MAX_SHIFT;
val = DIV_ROUND_UP(addressing->tRFCab_ps, t_ck) - 1;
tim3 |= val << T_RFC_SHIFT;
t_dqsck = (derated == <API key>) ?
timings->tDQSCK_max_derated : timings->tDQSCK_max;
if (ip_rev == EMIF_4D5)
val = DIV_ROUND_UP(t_dqsck + 1000, t_ck) - 1;
else
val = DIV_ROUND_UP(t_dqsck, t_ck) - 1;
tim3 |= val << T_TDQSCKMAX_SHIFT;
val = DIV_ROUND_UP(timings->tZQCS, t_ck) - 1;
tim3 |= val << ZQ_ZQCS_SHIFT;
val = DIV_ROUND_UP(timings->tCKESR, t_ck);
val = max(min_tck->tCKESR, val) - 1;
tim3 |= val << T_CKESR_SHIFT;
if (ip_rev == EMIF_4D5) {
tim3 |= (EMIF_T_CSTA - 1) << T_CSTA_SHIFT;
val = DIV_ROUND_UP(EMIF_T_PDLL_UL, 128) - 1;
tim3 |= val << T_PDLL_UL_SHIFT;
}
return tim3;
}
static u32 get_zq_config_reg(const struct lpddr2_addressing *addressing,
bool cs1_used, bool <API key>)
{
u32 zq = 0, val = 0;
val = <API key> * 1000 / addressing->tREFI_ns;
zq |= val << <API key>;
val = DIV_ROUND_UP(T_ZQCL_DEFAULT_NS, T_ZQCS_DEFAULT_NS) - 1;
zq |= val << ZQ_ZQCL_MULT_SHIFT;
val = DIV_ROUND_UP(T_ZQINIT_DEFAULT_NS, T_ZQCL_DEFAULT_NS) - 1;
zq |= val << <API key>;
zq |= ZQ_SFEXITEN_ENABLE << ZQ_SFEXITEN_SHIFT;
if (<API key>)
zq |= ZQ_DUALCALEN_ENABLE << ZQ_DUALCALEN_SHIFT;
else
zq |= <API key> << ZQ_DUALCALEN_SHIFT;
zq |= ZQ_CS0EN_MASK; /* CS0 is used for sure */
val = cs1_used ? 1 : 0;
zq |= val << ZQ_CS1EN_SHIFT;
return zq;
}
static u32 <API key>(const struct lpddr2_addressing *addressing,
const struct emif_custom_configs *custom_configs, bool cs1_used,
u32 sdram_io_width, u32 emif_bus_width)
{
u32 alert = 0, interval, devcnt;
if (custom_configs && (custom_configs->mask &
<API key>))
interval = custom_configs-><API key>;
else
interval = <API key>;
interval *= 1000000; /* Convert to ns */
interval /= addressing->tREFI_ns; /* Convert to refresh cycles */
alert |= (interval << <API key>);
/*
* sdram_io_width is in 'log2(x) - 1' form. Convert emif_bus_width
* also to this form and subtract to get TA_DEVCNT, which is
* in log2(x) form.
*/
emif_bus_width = __fls(emif_bus_width) - 1;
devcnt = emif_bus_width - sdram_io_width;
alert |= devcnt << TA_DEVCNT_SHIFT;
/* DEVWDT is in 'log2(x) - 3' form */
alert |= (sdram_io_width - 2) << TA_DEVWDT_SHIFT;
alert |= 1 << TA_SFEXITEN_SHIFT;
alert |= 1 << TA_CS0EN_SHIFT;
alert |= (cs1_used ? 1 : 0) << TA_CS1EN_SHIFT;
return alert;
}
static u32 <API key>(u8 volt_ramp)
{
u32 idle = 0, val = 0;
/*
* Maximum value in normal conditions and increased frequency
* when voltage is ramping
*/
if (volt_ramp)
val = <API key> / t_ck / 64 - 1;
else
val = 0x1FF;
/*
* READ_IDLE_CTRL register in EMIF4D has same offset and fields
* as DLL_CALIB_CTRL in EMIF4D5, so use the same shifts
*/
idle |= val << <API key>;
idle |= <API key> << ACK_WAIT_SHIFT;
return idle;
}
static u32 <API key>(u8 volt_ramp)
{
u32 calib = 0, val = 0;
if (volt_ramp == DDR_VOLTAGE_RAMPING)
val = <API key> / t_ck / 16 - 1;
else
val = 0; /* Disabled when voltage is stable */
calib |= val << <API key>;
calib |= <API key> << ACK_WAIT_SHIFT;
return calib;
}
static u32 <API key>(const struct lpddr2_timings *timings,
u32 freq, u8 RL)
{
u32 phy = <API key>, val = 0;
val = RL + DIV_ROUND_UP(timings->tDQSCK_max, t_ck) - 1;
phy |= val << <API key>;
if (freq <= 100000000)
val = <API key>;
else if (freq <= 200000000)
val = <API key>;
else
val = <API key>;
phy |= val << <API key>;
return phy;
}
static u32 <API key>(u32 freq, u8 cl)
{
u32 phy = <API key>, half_delay;
/*
* DLL operates at 266 MHz. If DDR frequency is near 266 MHz,
* half-delay is not needed else set half-delay
*/
if (freq >= 265000000 && freq < 267000000)
half_delay = 0;
else
half_delay = 1;
phy |= half_delay << <API key>;
phy |= ((cl + DIV_ROUND_UP(<API key>,
t_ck) - 1) << <API key>);
return phy;
}
static u32 <API key>(void)
{
u32 fifo_we_slave_ratio;
fifo_we_slave_ratio = DIV_ROUND_CLOSEST(
<API key> * 256 , t_ck);
return fifo_we_slave_ratio | fifo_we_slave_ratio << 11 |
fifo_we_slave_ratio << 22;
}
static u32 <API key>(void)
{
u32 fifo_we_slave_ratio;
fifo_we_slave_ratio = DIV_ROUND_CLOSEST(
<API key> * 256 , t_ck);
return fifo_we_slave_ratio >> 10 | fifo_we_slave_ratio << 1 |
fifo_we_slave_ratio << 12 | fifo_we_slave_ratio << 23;
}
static u32 <API key>(void)
{
u32 fifo_we_slave_ratio;
fifo_we_slave_ratio = DIV_ROUND_CLOSEST(
<API key> * 256 , t_ck);
return fifo_we_slave_ratio >> 9 | fifo_we_slave_ratio << 2 |
fifo_we_slave_ratio << 13;
}
static u32 get_pwr_mgmt_ctrl(u32 freq, struct emif_data *emif, u32 ip_rev)
{
u32 pwr_mgmt_ctrl = 0, timeout;
u32 lpmode = <API key>;
u32 timeout_perf = <API key>;
u32 timeout_pwr = <API key>;
u32 freq_threshold = <API key>;
u32 mask;
u8 shift;
struct emif_custom_configs *cust_cfgs = emif->plat_data->custom_configs;
if (cust_cfgs && (cust_cfgs->mask & <API key>)) {
lpmode = cust_cfgs->lpmode;
timeout_perf = cust_cfgs-><API key>;
timeout_pwr = cust_cfgs-><API key>;
freq_threshold = cust_cfgs-><API key>;
}
/* Timeout based on DDR frequency */
timeout = freq >= freq_threshold ? timeout_perf : timeout_pwr;
/*
* The value to be set in register is "log2(timeout) - 3"
* if timeout < 16 load 0 in register
* if timeout is not a power of 2, round to next highest power of 2
*/
if (timeout < 16) {
timeout = 0;
} else {
if (timeout & (timeout - 1))
timeout <<= 1;
timeout = __fls(timeout) - 3;
}
switch (lpmode) {
case <API key>:
shift = CS_TIM_SHIFT;
mask = CS_TIM_MASK;
break;
case <API key>:
/* Workaround for errata i735 */
if (timeout < 6)
timeout = 6;
shift = SR_TIM_SHIFT;
mask = SR_TIM_MASK;
break;
case EMIF_LP_MODE_PWR_DN:
shift = PD_TIM_SHIFT;
mask = PD_TIM_MASK;
break;
case <API key>:
default:
mask = 0;
shift = 0;
break;
}
/* Round to maximum in case of overflow, BUT warn! */
if (lpmode != <API key> && timeout > mask >> shift) {
pr_err("TIMEOUT Overflow - lpmode=%d perf=%d pwr=%d freq=%d\n",
lpmode,
timeout_perf,
timeout_pwr,
freq_threshold);
WARN(1, "timeout=0x%02x greater than 0x%02x. Using max\n",
timeout, mask >> shift);
timeout = mask >> shift;
}
/* Setup required timing */
pwr_mgmt_ctrl = (timeout << shift) & mask;
/* setup a default mask for rest of the modes */
pwr_mgmt_ctrl |= (SR_TIM_MASK | CS_TIM_MASK | PD_TIM_MASK) &
~mask;
/* No CS_TIM in EMIF_4D5 */
if (ip_rev == EMIF_4D5)
pwr_mgmt_ctrl &= ~CS_TIM_MASK;
pwr_mgmt_ctrl |= lpmode << LP_MODE_SHIFT;
return pwr_mgmt_ctrl;
}
/*
* Get the temperature level of the EMIF instance:
* Reads the MR4 register of attached SDRAM parts to find out the temperature
* level. If there are two parts attached(one on each CS), then the temperature
* level for the EMIF instance is the higher of the two temperatures.
*/
static void <API key>(struct emif_data *emif)
{
u32 temp, temperature_level;
void __iomem *base;
base = emif->base;
/* Read mode register 4 */
writel(DDR_MR4, base + <API key>);
temperature_level = readl(base + <API key>);
temperature_level = (temperature_level & <API key>) >>
<API key>;
if (emif->plat_data->device_info->cs1_used) {
writel(DDR_MR4 | CS_MASK, base + <API key>);
temp = readl(base + <API key>);
temp = (temp & <API key>)
>> <API key>;
temperature_level = max(temp, temperature_level);
}
/* treat everything less than nominal(3) in MR4 as nominal */
if (unlikely(temperature_level < SDRAM_TEMP_NOMINAL))
temperature_level = SDRAM_TEMP_NOMINAL;
/* if we get reserved value in MR4 persist with the existing value */
if (likely(temperature_level != <API key>))
emif->temperature_level = temperature_level;
}
/*
* Program EMIF shadow registers that are not dependent on temperature
* or voltage
*/
static void setup_registers(struct emif_data *emif, struct emif_regs *regs)
{
void __iomem *base = emif->base;
writel(regs->sdram_tim2_shdw, base + <API key>);
writel(regs->phy_ctrl_1_shdw, base + <API key>);
writel(regs->pwr_mgmt_ctrl_shdw,
base + <API key>);
/* Settings specific for EMIF4D5 */
if (emif->plat_data->ip_rev != EMIF_4D5)
return;
writel(regs->ext_phy_ctrl_2_shdw, base + <API key>);
writel(regs->ext_phy_ctrl_3_shdw, base + <API key>);
writel(regs->ext_phy_ctrl_4_shdw, base + <API key>);
}
/*
* When voltage ramps dll calibration and forced read idle should
* happen more often
*/
static void <API key>(struct emif_data *emif,
struct emif_regs *regs, u32 volt_state)
{
u32 calib_ctrl;
void __iomem *base = emif->base;
/*
* EMIF_READ_IDLE_CTRL in EMIF4D refers to the same register as
* EMIF_DLL_CALIB_CTRL in EMIF4D5 and <API key>*
* is an alias of the respective <API key>* (members of
* a union). So, the below code takes care of both cases
*/
if (volt_state == DDR_VOLTAGE_RAMPING)
calib_ctrl = regs-><API key>;
else
calib_ctrl = regs-><API key>;
writel(calib_ctrl, base + <API key>);
}
/*
* <API key>() - set the timings for temperature
* sensitive registers. This happens once at initialisation time based
* on the temperature at boot time and subsequently based on the temperature
* alert interrupt. Temperature alert can happen when the temperature
* increases or drops. So this function can have the effect of either
* derating the timings or going back to nominal values.
*/
static void <API key>(struct emif_data *emif,
struct emif_regs *regs)
{
u32 tim1, tim3, ref_ctrl, type;
void __iomem *base = emif->base;
u32 temperature;
type = emif->plat_data->device_info->type;
tim1 = regs->sdram_tim1_shdw;
tim3 = regs->sdram_tim3_shdw;
ref_ctrl = regs->ref_ctrl_shdw;
/* No de-rating for non-lpddr2 devices */
if (type != DDR_TYPE_LPDDR2_S2 && type != DDR_TYPE_LPDDR2_S4)
goto out;
temperature = emif->temperature_level;
if (temperature == <API key>) {
ref_ctrl = regs-><API key>;
} else if (temperature == <API key>) {
tim1 = regs-><API key>;
tim3 = regs-><API key>;
ref_ctrl = regs-><API key>;
}
out:
writel(tim1, base + <API key>);
writel(tim3, base + <API key>);
writel(ref_ctrl, base + <API key>);
}
static irqreturn_t handle_temp_alert(void __iomem *base, struct emif_data *emif)
{
u32 old_temp_level;
irqreturn_t ret = IRQ_HANDLED;
struct emif_custom_configs *custom_configs;
spin_lock_irqsave(&emif_lock, irq_state);
old_temp_level = emif->temperature_level;
<API key>(emif);
if (unlikely(emif->temperature_level == old_temp_level)) {
goto out;
} else if (!emif->curr_regs) {
dev_err(emif->dev, "temperature alert before registers are calculated, not de-rating timings\n");
goto out;
}
custom_configs = emif->plat_data->custom_configs;
/*
* IF we detect higher than "nominal rating" from DDR sensor
* on an unsupported DDR part, shutdown system
*/
if (custom_configs && !(custom_configs->mask &
<API key>)) {
if (emif->temperature_level >= <API key>) {
dev_err(emif->dev,
"%s:NOT Extended temperature capable memory."
"Converting MR4=0x%02x as shutdown event\n",
__func__, emif->temperature_level);
/*
* Temperature far too high - do kernel_power_off()
* from thread context
*/
emif->temperature_level = <API key>;
ret = IRQ_WAKE_THREAD;
goto out;
}
}
if (emif->temperature_level < old_temp_level ||
emif->temperature_level == <API key>) {
/*
* Temperature coming down - defer handling to thread OR
* Temperature far too high - do kernel_power_off() from
* thread context
*/
ret = IRQ_WAKE_THREAD;
} else {
/* Temperature is going up - handle immediately */
<API key>(emif, emif->curr_regs);
do_freq_update();
}
out:
<API key>(&emif_lock, irq_state);
return ret;
}
static irqreturn_t <API key>(int irq, void *dev_id)
{
u32 interrupts;
struct emif_data *emif = dev_id;
void __iomem *base = emif->base;
struct device *dev = emif->dev;
irqreturn_t ret = IRQ_HANDLED;
/* Save the status and clear it */
interrupts = readl(base + <API key>);
writel(interrupts, base + <API key>);
/*
* Handle temperature alert
* Temperature alert should be same for all ports
* So, it's enough to process it only for one of the ports
*/
if (interrupts & TA_SYS_MASK)
ret = handle_temp_alert(base, emif);
if (interrupts & ERR_SYS_MASK)
dev_err(dev, "Access error from SYS port - %x\n", interrupts);
if (emif->plat_data->hw_caps & <API key>) {
/* Save the status and clear it */
interrupts = readl(base + <API key>);
writel(interrupts, base + <API key>);
if (interrupts & ERR_LL_MASK)
dev_err(dev, "Access error from LL port - %x\n",
interrupts);
}
return ret;
}
static irqreturn_t emif_threaded_isr(int irq, void *dev_id)
{
struct emif_data *emif = dev_id;
if (emif->temperature_level == <API key>) {
dev_emerg(emif->dev, "SDRAM temperature exceeds operating limit.. Needs shut down!!!\n");
/* If we have Power OFF ability, use it, else try restarting */
if (pm_power_off) {
kernel_power_off();
} else {
WARN(1, "FIXME: NO pm_power_off!!! trying restart\n");
kernel_restart("SDRAM Over-temp Emergency restart");
}
return IRQ_HANDLED;
}
spin_lock_irqsave(&emif_lock, irq_state);
if (emif->curr_regs) {
<API key>(emif, emif->curr_regs);
do_freq_update();
} else {
dev_err(emif->dev, "temperature alert before registers are calculated, not de-rating timings\n");
}
<API key>(&emif_lock, irq_state);
return IRQ_HANDLED;
}
static void <API key>(struct emif_data *emif)
{
void __iomem *base = emif->base;
writel(readl(base + <API key>),
base + <API key>);
if (emif->plat_data->hw_caps & <API key>)
writel(readl(base + <API key>),
base + <API key>);
}
static void <API key>(struct emif_data *emif)
{
void __iomem *base = emif->base;
/* Disable all interrupts */
writel(readl(base + <API key>),
base + <API key>);
if (emif->plat_data->hw_caps & <API key>)
writel(readl(base + <API key>),
base + <API key>);
/* Clear all interrupts */
<API key>(emif);
}
static int __init_or_module setup_interrupts(struct emif_data *emif, u32 irq)
{
u32 interrupts, type;
void __iomem *base = emif->base;
type = emif->plat_data->device_info->type;
<API key>(emif);
/* Enable interrupts for SYS interface */
interrupts = EN_ERR_SYS_MASK;
if (type == DDR_TYPE_LPDDR2_S2 || type == DDR_TYPE_LPDDR2_S4)
interrupts |= EN_TA_SYS_MASK;
writel(interrupts, base + <API key>);
/* Enable interrupts for LL interface */
if (emif->plat_data->hw_caps & <API key>) {
/* TA need not be enabled for LL */
interrupts = EN_ERR_LL_MASK;
writel(interrupts, base + <API key>);
}
/* setup IRQ handlers */
return <API key>(emif->dev, irq,
<API key>,
emif_threaded_isr,
0, dev_name(emif->dev),
emif);
}
static void __init_or_module <API key>(struct emif_data *emif)
{
u32 pwr_mgmt_ctrl, zq, temp_alert_cfg;
void __iomem *base = emif->base;
const struct lpddr2_addressing *addressing;
const struct ddr_device_info *device_info;
device_info = emif->plat_data->device_info;
addressing = <API key>(device_info);
/*
* Init power management settings
* We don't know the frequency yet. Use a high frequency
* value for a conservative timeout setting
*/
pwr_mgmt_ctrl = get_pwr_mgmt_ctrl(1000000000, emif,
emif->plat_data->ip_rev);
emif->lpmode = (pwr_mgmt_ctrl & LP_MODE_MASK) >> LP_MODE_SHIFT;
writel(pwr_mgmt_ctrl, base + <API key>);
/* Init ZQ calibration settings */
zq = get_zq_config_reg(addressing, device_info->cs1_used,
device_info-><API key>);
writel(zq, base + <API key>);
/* Check temperature level temperature level*/
<API key>(emif);
if (emif->temperature_level == <API key>)
dev_emerg(emif->dev, "SDRAM temperature exceeds operating limit.. Needs shut down!!!\n");
/* Init temperature polling */
temp_alert_cfg = <API key>(addressing,
emif->plat_data->custom_configs, device_info->cs1_used,
device_info->io_width, get_emif_bus_width(emif));
writel(temp_alert_cfg, base + <API key>);
/*
* Program external PHY control registers that are not frequency
* dependent
*/
if (emif->plat_data->phy_type != <API key>)
return;
writel(<API key>, base + <API key>);
writel(<API key>, base + <API key>);
writel(<API key>, base + <API key>);
writel(<API key>, base + <API key>);
writel(<API key>, base + <API key>);
writel(<API key>, base + <API key>);
writel(<API key>, base + <API key>);
writel(<API key>, base + <API key>);
writel(<API key>, base + <API key>);
writel(<API key>, base + <API key>);
writel(<API key>, base + <API key>);
writel(<API key>, base + <API key>);
writel(<API key>, base + <API key>);
writel(<API key>, base + <API key>);
writel(<API key>, base + <API key>);
writel(<API key>, base + <API key>);
writel(<API key>, base + <API key>);
writel(<API key>, base + <API key>);
writel(<API key>, base + <API key>);
writel(<API key>, base + <API key>);
writel(<API key>, base + <API key>);
}
static void get_default_timings(struct emif_data *emif)
{
struct emif_platform_data *pd = emif->plat_data;
pd->timings = <API key>;
pd->timings_arr_size = ARRAY_SIZE(<API key>);
dev_warn(emif->dev, "%s: using default timings\n", __func__);
}
static int is_dev_data_valid(u32 type, u32 density, u32 io_width, u32 phy_type,
u32 ip_rev, struct device *dev)
{
int valid;
valid = (type == DDR_TYPE_LPDDR2_S4 ||
type == DDR_TYPE_LPDDR2_S2)
&& (density >= DDR_DENSITY_64Mb
&& density <= DDR_DENSITY_8Gb)
&& (io_width >= DDR_IO_WIDTH_8
&& io_width <= DDR_IO_WIDTH_32);
/* Combinations of EMIF and PHY revisions that we support today */
switch (ip_rev) {
case EMIF_4D:
valid = valid && (phy_type == <API key>);
break;
case EMIF_4D5:
valid = valid && (phy_type == <API key>);
break;
default:
valid = 0;
}
if (!valid)
dev_err(dev, "%s: invalid DDR details\n", __func__);
return valid;
}
static int <API key>(struct emif_custom_configs *cust_cfgs,
struct device *dev)
{
int valid = 1;
if ((cust_cfgs->mask & <API key>) &&
(cust_cfgs->lpmode != <API key>))
valid = cust_cfgs-><API key> &&
cust_cfgs-><API key> &&
cust_cfgs-><API key>;
if (cust_cfgs->mask & <API key>)
valid = valid && cust_cfgs-><API key>;
if (!valid)
dev_warn(dev, "%s: invalid custom configs\n", __func__);
return valid;
}
#if defined(CONFIG_OF)
static void __init_or_module <API key>(struct device_node *np_emif,
struct emif_data *emif)
{
struct emif_custom_configs *cust_cfgs = NULL;
int len;
const __be32 *lpmode, *poll_intvl;
lpmode = of_get_property(np_emif, "low-power-mode", &len);
poll_intvl = of_get_property(np_emif, "<API key>", &len);
if (lpmode || poll_intvl)
cust_cfgs = devm_kzalloc(emif->dev, sizeof(*cust_cfgs),
GFP_KERNEL);
if (!cust_cfgs)
return;
if (lpmode) {
cust_cfgs->mask |= <API key>;
cust_cfgs->lpmode = be32_to_cpup(lpmode);
<API key>(np_emif,
"<API key>",
&cust_cfgs-><API key>);
<API key>(np_emif,
"<API key>",
&cust_cfgs-><API key>);
<API key>(np_emif,
"<API key>",
&cust_cfgs-><API key>);
}
if (poll_intvl) {
cust_cfgs->mask |=
<API key>;
cust_cfgs-><API key> =
be32_to_cpup(poll_intvl);
}
if (of_find_property(np_emif, "extended-temp-part", &len))
cust_cfgs->mask |= <API key>;
if (!<API key>(cust_cfgs, emif->dev)) {
devm_kfree(emif->dev, cust_cfgs);
return;
}
emif->plat_data->custom_configs = cust_cfgs;
}
static void __init_or_module of_get_ddr_info(struct device_node *np_emif,
struct device_node *np_ddr,
struct ddr_device_info *dev_info)
{
u32 density = 0, io_width = 0;
int len;
if (of_find_property(np_emif, "cs1-used", &len))
dev_info->cs1_used = true;
if (of_find_property(np_emif, "cal-resistor-per-cs", &len))
dev_info-><API key> = true;
if (<API key>(np_ddr , "jedec,lpddr2-s4"))
dev_info->type = DDR_TYPE_LPDDR2_S4;
else if (<API key>(np_ddr , "jedec,lpddr2-s2"))
dev_info->type = DDR_TYPE_LPDDR2_S2;
<API key>(np_ddr, "density", &density);
<API key>(np_ddr, "io-width", &io_width);
/* Convert from density in Mb to the density encoding in jedc_ddr.h */
if (density & (density - 1))
dev_info->density = 0;
else
dev_info->density = __fls(density) - 5;
/* Convert from io_width in bits to io_width encoding in jedc_ddr.h */
if (io_width & (io_width - 1))
dev_info->io_width = 0;
else
dev_info->io_width = __fls(io_width) - 1;
}
static struct emif_data * __init_or_module <API key>(
struct device_node *np_emif, struct device *dev)
{
struct emif_data *emif = NULL;
struct ddr_device_info *dev_info = NULL;
struct emif_platform_data *pd = NULL;
struct device_node *np_ddr;
int len;
np_ddr = of_parse_phandle(np_emif, "device-handle", 0);
if (!np_ddr)
goto error;
emif = devm_kzalloc(dev, sizeof(struct emif_data), GFP_KERNEL);
pd = devm_kzalloc(dev, sizeof(*pd), GFP_KERNEL);
dev_info = devm_kzalloc(dev, sizeof(*dev_info), GFP_KERNEL);
if (!emif || !pd || !dev_info) {
dev_err(dev, "%s: Out of memory!!\n",
__func__);
goto error;
}
emif->plat_data = pd;
pd->device_info = dev_info;
emif->dev = dev;
emif->np_ddr = np_ddr;
emif->temperature_level = SDRAM_TEMP_NOMINAL;
if (<API key>(np_emif, "ti,emif-4d"))
emif->plat_data->ip_rev = EMIF_4D;
else if (<API key>(np_emif, "ti,emif-4d5"))
emif->plat_data->ip_rev = EMIF_4D5;
<API key>(np_emif, "phy-type", &pd->phy_type);
if (of_find_property(np_emif, "<API key>", &len))
pd->hw_caps |= <API key>;
of_get_ddr_info(np_emif, np_ddr, dev_info);
if (!is_dev_data_valid(pd->device_info->type, pd->device_info->density,
pd->device_info->io_width, pd->phy_type, pd->ip_rev,
emif->dev)) {
dev_err(dev, "%s: invalid device data!!\n", __func__);
goto error;
}
/*
* For EMIF instances other than EMIF1 see if the devices connected
* are exactly same as on EMIF1(which is typically the case). If so,
* mark it as a duplicate of EMIF1. This will save some memory and
* computation.
*/
if (emif1 && emif1->np_ddr == np_ddr) {
emif->duplicate = true;
goto out;
} else if (emif1) {
dev_warn(emif->dev, "%s: Non-symmetric DDR geometry\n",
__func__);
}
<API key>(np_emif, emif);
emif->plat_data->timings = of_get_ddr_timings(np_ddr, emif->dev,
emif->plat_data->device_info->type,
&emif->plat_data->timings_arr_size);
emif->plat_data->min_tck = of_get_min_tck(np_ddr, emif->dev);
goto out;
error:
return NULL;
out:
return emif;
}
#else
static struct emif_data * __init_or_module <API key>(
struct device_node *np_emif, struct device *dev)
{
return NULL;
}
#endif
static struct emif_data *__init_or_module get_device_details(
struct platform_device *pdev)
{
u32 size;
struct emif_data *emif = NULL;
struct ddr_device_info *dev_info;
struct emif_custom_configs *cust_cfgs;
struct emif_platform_data *pd;
struct device *dev;
void *temp;
pd = pdev->dev.platform_data;
dev = &pdev->dev;
if (!(pd && pd->device_info && is_dev_data_valid(pd->device_info->type,
pd->device_info->density, pd->device_info->io_width,
pd->phy_type, pd->ip_rev, dev))) {
dev_err(dev, "%s: invalid device data\n", __func__);
goto error;
}
emif = devm_kzalloc(dev, sizeof(*emif), GFP_KERNEL);
temp = devm_kzalloc(dev, sizeof(*pd), GFP_KERNEL);
dev_info = devm_kzalloc(dev, sizeof(*dev_info), GFP_KERNEL);
if (!emif || !pd || !dev_info) {
dev_err(dev, "%s:%d: allocation error\n", __func__, __LINE__);
goto error;
}
memcpy(temp, pd, sizeof(*pd));
pd = temp;
memcpy(dev_info, pd->device_info, sizeof(*dev_info));
pd->device_info = dev_info;
emif->plat_data = pd;
emif->dev = dev;
emif->temperature_level = SDRAM_TEMP_NOMINAL;
/*
* For EMIF instances other than EMIF1 see if the devices connected
* are exactly same as on EMIF1(which is typically the case). If so,
* mark it as a duplicate of EMIF1 and skip copying timings data.
* This will save some memory and some computation later.
*/
emif->duplicate = emif1 && (memcmp(dev_info,
emif1->plat_data->device_info,
sizeof(struct ddr_device_info)) == 0);
if (emif->duplicate) {
pd->timings = NULL;
pd->min_tck = NULL;
goto out;
} else if (emif1) {
dev_warn(emif->dev, "%s: Non-symmetric DDR geometry\n",
__func__);
}
/*
* Copy custom configs - ignore allocation error, if any, as
* custom_configs is not very critical
*/
cust_cfgs = pd->custom_configs;
if (cust_cfgs && <API key>(cust_cfgs, dev)) {
temp = devm_kzalloc(dev, sizeof(*cust_cfgs), GFP_KERNEL);
if (temp)
memcpy(temp, cust_cfgs, sizeof(*cust_cfgs));
else
dev_warn(dev, "%s:%d: allocation error\n", __func__,
__LINE__);
pd->custom_configs = temp;
}
/*
* Copy timings and min-tck values from platform data. If it is not
* available or if memory allocation fails, use JEDEC defaults
*/
size = sizeof(struct lpddr2_timings) * pd->timings_arr_size;
if (pd->timings) {
temp = devm_kzalloc(dev, size, GFP_KERNEL);
if (temp) {
memcpy(temp, pd->timings, size);
pd->timings = temp;
} else {
dev_warn(dev, "%s:%d: allocation error\n", __func__,
__LINE__);
get_default_timings(emif);
}
} else {
get_default_timings(emif);
}
if (pd->min_tck) {
temp = devm_kzalloc(dev, sizeof(*pd->min_tck), GFP_KERNEL);
if (temp) {
memcpy(temp, pd->min_tck, sizeof(*pd->min_tck));
pd->min_tck = temp;
} else {
dev_warn(dev, "%s:%d: allocation error\n", __func__,
__LINE__);
pd->min_tck = &<API key>;
}
} else {
pd->min_tck = &<API key>;
}
out:
return emif;
error:
return NULL;
}
static int __init_or_module emif_probe(struct platform_device *pdev)
{
struct emif_data *emif;
struct resource *res;
int irq;
if (pdev->dev.of_node)
emif = <API key>(pdev->dev.of_node, &pdev->dev);
else
emif = get_device_details(pdev);
if (!emif) {
pr_err("%s: error getting device data\n", __func__);
goto error;
}
list_add(&emif->node, &device_list);
emif->addressing = <API key>(emif->plat_data->device_info);
/* Save pointers to each other in emif and device structures */
emif->dev = &pdev->dev;
<API key>(pdev, emif);
res = <API key>(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(emif->dev, "%s: error getting memory resource\n",
__func__);
goto error;
}
emif->base = <API key>(emif->dev, res);
if (IS_ERR(emif->base))
goto error;
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
dev_err(emif->dev, "%s: error getting IRQ resource - %d\n",
__func__, irq);
goto error;
}
<API key>(emif);
emif_debugfs_init(emif);
<API key>(emif);
setup_interrupts(emif, irq);
/* One-time actions taken on probing the first device */
if (!emif1) {
emif1 = emif;
spin_lock_init(&emif_lock);
/*
* TODO: register notifiers for frequency and voltage
* change here once the respective frameworks are
* available
*/
}
dev_info(&pdev->dev, "%s: device configured with addr = %p and IRQ%d\n",
__func__, emif->base, irq);
return 0;
error:
return -ENODEV;
}
static int __exit emif_remove(struct platform_device *pdev)
{
struct emif_data *emif = <API key>(pdev);
emif_debugfs_exit(emif);
return 0;
}
static void emif_shutdown(struct platform_device *pdev)
{
struct emif_data *emif = <API key>(pdev);
<API key>(emif);
}
static int get_emif_reg_values(struct emif_data *emif, u32 freq,
struct emif_regs *regs)
{
u32 cs1_used, ip_rev, phy_type;
u32 cl, type;
const struct lpddr2_timings *timings;
const struct lpddr2_min_tck *min_tck;
const struct ddr_device_info *device_info;
const struct lpddr2_addressing *addressing;
struct emif_data *emif_for_calc;
struct device *dev;
const struct emif_custom_configs *custom_configs;
dev = emif->dev;
/*
* If the devices on this EMIF instance is duplicate of EMIF1,
* use EMIF1 details for the calculation
*/
emif_for_calc = emif->duplicate ? emif1 : emif;
timings = get_timings_table(emif_for_calc, freq);
addressing = emif_for_calc->addressing;
if (!timings || !addressing) {
dev_err(dev, "%s: not enough data available for %dHz",
__func__, freq);
return -1;
}
device_info = emif_for_calc->plat_data->device_info;
type = device_info->type;
cs1_used = device_info->cs1_used;
ip_rev = emif_for_calc->plat_data->ip_rev;
phy_type = emif_for_calc->plat_data->phy_type;
min_tck = emif_for_calc->plat_data->min_tck;
custom_configs = emif_for_calc->plat_data->custom_configs;
set_ddr_clk_period(freq);
regs->ref_ctrl_shdw = <API key>(freq, addressing);
regs->sdram_tim1_shdw = <API key>(timings, min_tck,
addressing);
regs->sdram_tim2_shdw = <API key>(timings, min_tck,
addressing, type);
regs->sdram_tim3_shdw = <API key>(timings, min_tck,
addressing, type, ip_rev, EMIF_NORMAL_TIMINGS);
cl = get_cl(emif);
if (phy_type == <API key> && ip_rev == EMIF_4D) {
regs->phy_ctrl_1_shdw = <API key>(
timings, freq, cl);
} else if (phy_type == <API key> && ip_rev == EMIF_4D5) {
regs->phy_ctrl_1_shdw = <API key>(freq, cl);
regs->ext_phy_ctrl_2_shdw = <API key>();
regs->ext_phy_ctrl_3_shdw = <API key>();
regs->ext_phy_ctrl_4_shdw = <API key>();
} else {
return -1;
}
/* Only timeout values in pwr_mgmt_ctrl_shdw register */
regs->pwr_mgmt_ctrl_shdw =
get_pwr_mgmt_ctrl(freq, emif_for_calc, ip_rev) &
(CS_TIM_MASK | SR_TIM_MASK | PD_TIM_MASK);
if (ip_rev & EMIF_4D) {
regs-><API key> =
<API key>(DDR_VOLTAGE_STABLE);
regs-><API key> =
<API key>(DDR_VOLTAGE_RAMPING);
} else if (ip_rev & EMIF_4D5) {
regs-><API key> =
<API key>(DDR_VOLTAGE_STABLE);
regs-><API key> =
<API key>(DDR_VOLTAGE_RAMPING);
}
if (type == DDR_TYPE_LPDDR2_S2 || type == DDR_TYPE_LPDDR2_S4) {
regs-><API key> = <API key>(freq / 4,
addressing);
regs-><API key> =
<API key>(timings, min_tck,
addressing);
regs-><API key> = <API key>(timings,
min_tck, addressing, type, ip_rev,
<API key>);
}
regs->freq = freq;
return 0;
}
/*
* get_regs() - gets the cached emif_regs structure for a given EMIF instance
* given frequency(freq):
*
* As an optimisation, every EMIF instance other than EMIF1 shares the
* register cache with EMIF1 if the devices connected on this instance
* are same as that on EMIF1(indicated by the duplicate flag)
*
* If we do not have an entry corresponding to the frequency given, we
* allocate a new entry and calculate the values
*
* Upon finding the right reg dump, save it in curr_regs. It can be
* directly used for thermal de-rating and voltage ramping changes.
*/
static struct emif_regs *get_regs(struct emif_data *emif, u32 freq)
{
int i;
struct emif_regs **regs_cache;
struct emif_regs *regs = NULL;
struct device *dev;
dev = emif->dev;
if (emif->curr_regs && emif->curr_regs->freq == freq) {
dev_dbg(dev, "%s: using curr_regs - %u Hz", __func__, freq);
return emif->curr_regs;
}
if (emif->duplicate)
regs_cache = emif1->regs_cache;
else
regs_cache = emif->regs_cache;
for (i = 0; i < <API key> && regs_cache[i]; i++) {
if (regs_cache[i]->freq == freq) {
regs = regs_cache[i];
dev_dbg(dev,
"%s: reg dump found in reg cache for %u Hz\n",
__func__, freq);
break;
}
}
/*
* If we don't have an entry for this frequency in the cache create one
* and calculate the values
*/
if (!regs) {
regs = devm_kzalloc(emif->dev, sizeof(*regs), GFP_ATOMIC);
if (!regs)
return NULL;
if (get_emif_reg_values(emif, freq, regs)) {
devm_kfree(emif->dev, regs);
return NULL;
}
/*
* Now look for an un-used entry in the cache and save the
* newly created struct. If there are no free entries
* over-write the last entry
*/
for (i = 0; i < <API key> && regs_cache[i]; i++)
;
if (i >= <API key>) {
dev_warn(dev, "%s: regs_cache full - reusing a slot!!\n",
__func__);
i = <API key> - 1;
devm_kfree(emif->dev, regs_cache[i]);
}
regs_cache[i] = regs;
}
return regs;
}
static void <API key>(struct emif_data *emif, u32 volt_state)
{
dev_dbg(emif->dev, "%s: voltage notification : %d", __func__,
volt_state);
if (!emif->curr_regs) {
dev_err(emif->dev,
"%s: volt-notify before registers are ready: %d\n",
__func__, volt_state);
return;
}
<API key>(emif, emif->curr_regs, volt_state);
}
/*
* TODO: voltage notify handling should be hooked up to
* regulator framework as soon as the necessary support
* is available in mainline kernel. This function is un-used
* right now.
*/
static void __attribute__((unused)) <API key>(u32 volt_state)
{
struct emif_data *emif;
spin_lock_irqsave(&emif_lock, irq_state);
list_for_each_entry(emif, &device_list, node)
<API key>(emif, volt_state);
do_freq_update();
<API key>(&emif_lock, irq_state);
}
static void <API key>(struct emif_data *emif, u32 new_freq)
{
struct emif_regs *regs;
regs = get_regs(emif, new_freq);
if (!regs)
return;
emif->curr_regs = regs;
/*
* Update the shadow registers:
* Temperature and voltage-ramp sensitive settings are also configured
* in terms of DDR cycles. So, we need to update them too when there
* is a freq change
*/
dev_dbg(emif->dev, "%s: setting up shadow registers for %uHz",
__func__, new_freq);
setup_registers(emif, regs);
<API key>(emif, regs);
<API key>(emif, regs, DDR_VOLTAGE_STABLE);
/*
* Part of workaround for errata i728. See do_freq_update()
* for more details
*/
if (emif->lpmode == <API key>)
set_lpmode(emif, <API key>);
}
/*
* TODO: frequency notify handling should be hooked up to
* clock framework as soon as the necessary support is
* available in mainline kernel. This function is un-used
* right now.
*/
static void __attribute__((unused)) <API key>(u32 new_freq)
{
struct emif_data *emif;
/*
* NOTE: we are taking the spin-lock here and releases it
* only in post-notifier. This doesn't look good and
* Sparse complains about it, but this seems to be
* un-avoidable. We need to lock a sequence of events
* that is split between EMIF and clock framework.
*
* 1. EMIF driver updates EMIF timings in shadow registers in the
* frequency pre-notify callback from clock framework
* 2. clock framework sets up the registers for the new frequency
* 3. clock framework initiates a hw-sequence that updates
* the frequency EMIF timings synchronously.
*
* All these 3 steps should be performed as an atomic operation
* vis-a-vis similar sequence in the EMIF interrupt handler
* for temperature events. Otherwise, there could be race
* conditions that could result in incorrect EMIF timings for
* a given frequency
*/
spin_lock_irqsave(&emif_lock, irq_state);
list_for_each_entry(emif, &device_list, node)
<API key>(emif, new_freq);
}
static void <API key>(struct emif_data *emif)
{
/*
* Part of workaround for errata i728. See do_freq_update()
* for more details
*/
if (emif->lpmode == <API key>)
set_lpmode(emif, <API key>);
}
/*
* TODO: frequency notify handling should be hooked up to
* clock framework as soon as the necessary support is
* available in mainline kernel. This function is un-used
* right now.
*/
static void __attribute__((unused)) <API key>(void)
{
struct emif_data *emif;
list_for_each_entry(emif, &device_list, node)
<API key>(emif);
/*
* Lock is done in pre-notify handler. See <API key>()
* for more details
*/
<API key>(&emif_lock, irq_state);
}
#if defined(CONFIG_OF)
static const struct of_device_id emif_of_match[] = {
{ .compatible = "ti,emif-4d" },
{ .compatible = "ti,emif-4d5" },
{},
};
MODULE_DEVICE_TABLE(of, emif_of_match);
#endif
static struct platform_driver emif_driver = {
.remove = __exit_p(emif_remove),
.shutdown = emif_shutdown,
.driver = {
.name = "emif",
.of_match_table = of_match_ptr(emif_of_match),
},
};
<API key>(emif_driver, emif_probe);
MODULE_DESCRIPTION("TI EMIF SDRAM Controller Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:emif");
MODULE_AUTHOR("Texas Instruments Inc"); |
#!/usr/bin/env python
import pyflag.IO as IO
import pyflag.Registry as Registry
Registry.Init()
import pyflag.FileSystem as FileSystem
from FileSystem import DBFS
case = "demo"
## This gives us a handle to the VFS
fsfd = Registry.FILESYSTEMS.fs['DBFS'](case)
## WE just open a file in the VFS:
#fd=fsfd.open(inode="Itest|S1/2")
## And read it
#print fd.read() |
/*
* Module dependencies
*/
var passport = require('passport')
var LocalStrategy = require('passport-local').Strategy
var User = require('lib/models').User
/**
* Expose AuthStrategy
*/
module.exports = AuthStrategy
/**
* Register Auth Strategies for app
*/
function AuthStrategy () {
/**
* Passport Serialization of logged
* User to Session from request
*/
passport.serializeUser(function (user, done) {
done(null, user._id)
})
/**
* Passport Deserialization of logged
* User by Session into request
*/
passport.deserializeUser(function (userId, done) {
User
.findById(userId)
.exec(done)
})
/**
* Register Local Strategy
*/
passport.use(new LocalStrategy(User.authenticate()))
} |
#ifndef <API key>
#define <API key>
//This file was generated by a program. Do not edit manually.
#include <boost/qvm/enable_if.hpp>
#include <boost/qvm/inline.hpp>
#include <boost/qvm/mat_traits.hpp>
namespace
boost
{
namespace
qvm
{
template <class A,class B>
<API key>
typename enable_if_c<
mat_traits<A>::rows==4 && mat_traits<B>::rows==4 &&
mat_traits<A>::cols==4 && mat_traits<B>::cols==4,
A &>::type
assign( A & a, B const & b )
{
mat_traits<A>::template write_element<0,0>(a)=mat_traits<B>::template read_element<0,0>(b);
mat_traits<A>::template write_element<0,1>(a)=mat_traits<B>::template read_element<0,1>(b);
mat_traits<A>::template write_element<0,2>(a)=mat_traits<B>::template read_element<0,2>(b);
mat_traits<A>::template write_element<0,3>(a)=mat_traits<B>::template read_element<0,3>(b);
mat_traits<A>::template write_element<1,0>(a)=mat_traits<B>::template read_element<1,0>(b);
mat_traits<A>::template write_element<1,1>(a)=mat_traits<B>::template read_element<1,1>(b);
mat_traits<A>::template write_element<1,2>(a)=mat_traits<B>::template read_element<1,2>(b);
mat_traits<A>::template write_element<1,3>(a)=mat_traits<B>::template read_element<1,3>(b);
mat_traits<A>::template write_element<2,0>(a)=mat_traits<B>::template read_element<2,0>(b);
mat_traits<A>::template write_element<2,1>(a)=mat_traits<B>::template read_element<2,1>(b);
mat_traits<A>::template write_element<2,2>(a)=mat_traits<B>::template read_element<2,2>(b);
mat_traits<A>::template write_element<2,3>(a)=mat_traits<B>::template read_element<2,3>(b);
mat_traits<A>::template write_element<3,0>(a)=mat_traits<B>::template read_element<3,0>(b);
mat_traits<A>::template write_element<3,1>(a)=mat_traits<B>::template read_element<3,1>(b);
mat_traits<A>::template write_element<3,2>(a)=mat_traits<B>::template read_element<3,2>(b);
mat_traits<A>::template write_element<3,3>(a)=mat_traits<B>::template read_element<3,3>(b);
return a;
}
namespace
sfinae
{
using ::boost::qvm::assign;
}
namespace
qvm_detail
{
template <int R,int C>
struct assign_mm_defined;
template <>
struct
assign_mm_defined<4,4>
{
static bool const value=true;
};
}
template <class A,class B>
<API key>
typename enable_if_c<
mat_traits<A>::rows==4 && mat_traits<B>::rows==4 &&
mat_traits<A>::cols==1 && mat_traits<B>::cols==1,
A &>::type
assign( A & a, B const & b )
{
mat_traits<A>::template write_element<0,0>(a)=mat_traits<B>::template read_element<0,0>(b);
mat_traits<A>::template write_element<1,0>(a)=mat_traits<B>::template read_element<1,0>(b);
mat_traits<A>::template write_element<2,0>(a)=mat_traits<B>::template read_element<2,0>(b);
mat_traits<A>::template write_element<3,0>(a)=mat_traits<B>::template read_element<3,0>(b);
return a;
}
namespace
sfinae
{
using ::boost::qvm::assign;
}
namespace
qvm_detail
{
template <int R,int C>
struct assign_mm_defined;
template <>
struct
assign_mm_defined<4,1>
{
static bool const value=true;
};
}
template <class A,class B>
<API key>
typename enable_if_c<
mat_traits<A>::rows==1 && mat_traits<B>::rows==1 &&
mat_traits<A>::cols==4 && mat_traits<B>::cols==4,
A &>::type
assign( A & a, B const & b )
{
mat_traits<A>::template write_element<0,0>(a)=mat_traits<B>::template read_element<0,0>(b);
mat_traits<A>::template write_element<0,1>(a)=mat_traits<B>::template read_element<0,1>(b);
mat_traits<A>::template write_element<0,2>(a)=mat_traits<B>::template read_element<0,2>(b);
mat_traits<A>::template write_element<0,3>(a)=mat_traits<B>::template read_element<0,3>(b);
return a;
}
namespace
sfinae
{
using ::boost::qvm::assign;
}
namespace
qvm_detail
{
template <int R,int C>
struct assign_mm_defined;
template <>
struct
assign_mm_defined<1,4>
{
static bool const value=true;
};
}
}
}
#endif |
#import <AppKit/AppKitDefines.h>
#import <Foundation/NSObject.h>
@class NSArray, NSString;
@protocol <API key>;
@interface NSSpeechRecognizer : NSObject {
@private
id <API key>;
}
- (id)init;
- (void)startListening;
- (void)stopListening;
- (id <<API key>>)delegate;
- (void)setDelegate:(id <<API key>>)anObject;
- (NSArray *)commands;
- (void)setCommands:(NSArray *)commands;
- (NSString *)<API key>;
- (void)<API key>:(NSString *)title;
- (BOOL)<API key>;
- (void)<API key>:(BOOL)flag;
- (BOOL)<API key>;
- (void)<API key>:(BOOL)flag;
@end
@protocol <API key> <NSObject>
@optional
- (void)speechRecognizer:(NSSpeechRecognizer *)sender didRecognizeCommand:(id)command;
@end |
(function() {
'use strict';
angular
.module('app.panels')
.directive('panelCollapse', panelCollapse);
function panelCollapse () {
var directive = {
controller: Controller,
restrict: 'A',
scope: false
};
return directive;
}
Controller.$inject = ['$scope', '$element', '$timeout', '$localStorage'];
function Controller ($scope, $element, $timeout, $localStorage) {
var storageKeyName = 'panelState';
// Prepare the panel to be collapsible
var $elem = $($element),
parent = $elem.closest('.panel'), // find the first parent panel
panelId = parent.attr('id');
// Load the saved state if exists
var currentState = loadPanelState( panelId );
if ( typeof currentState !== 'undefined') {
$timeout(function(){
$scope[panelId] = currentState; },
10);
}
// bind events to switch icons
$element.bind('click', function(e) {
e.preventDefault();
savePanelState( panelId, !$scope[panelId] );
});
// Controller helpers
function savePanelState(id, state) {
if(!id) return false;
var data = angular.fromJson($localStorage[storageKeyName]);
if(!data) { data = {}; }
data[id] = state;
$localStorage[storageKeyName] = angular.toJson(data);
}
function loadPanelState(id) {
if(!id) return false;
var data = angular.fromJson($localStorage[storageKeyName]);
if(data) {
return data[id];
}
}
}
})(); |
<?php
// This is a SPIP language file -- Ceci est un fichier langue de SPIP
// ** ne pas modifier le fichier **
if (!defined('_ECRIRE_INC_VERSION')) return;
$GLOBALS[$GLOBALS['idx_lang']] = array(
'aucune_donnee' => 'vide', # NEW
'<API key>' => 'Problème d\'écriture du fichier @fichier@', # NEW
'<API key>' => 'Restaurar la basa',
'<API key>' => 'Oui, je veux écraser ma base avec cette sauvegarde', # NEW
'<API key>' => 'Oui, je veux écraser les tables sélectionnées avec cette sauvegarde', # NEW
'details_sauvegarde' => 'Détails de la sauvegarde :', # NEW
'<API key>' => 'Aucune donnée restaurée', # NEW
'erreur_connect_dump' => 'Un serveur nommé « @dump@ » existe déjà. Renommez-le.', # NEW
'<API key>' => 'Impossible de créer une base SQLite pour la sauvegarde', # NEW
'erreur_nom_fichier' => 'Ce nom de fichier n\'est pas autorisé', # NEW
'<API key>' => 'Corrigez l\'erreur pour pouvoir restaurer.', # NEW
'<API key>' => 'Vous avez déjà une sauvegarde en cours', # NEW
'<API key>' => 'Impossible de faire une sauvegarde SQLite sur votre hébergement', # NEW
'<API key>' => 'Table @table@ absente', # NEW
'<API key>' => 'Table @table@, données manquantes', # NEW
'<API key>' => 'La sauvegarde semble avoir échoué. Le fichier @fichier@ est vide ou absent.', # NEW
'<API key>' => 'Aucune sauvegarde trouvée', # NEW
'<API key>' => 'C\'est fini !. La sauvegarde @archive@ a été restaurée dans votre site. Vous pouvez', # NEW
'<API key>' => 'Restauracion de la sauvagarda @archive@',
'info_sauvegarde' => 'Sauvagarda',
'<API key>' => 'La basa es estada sauvagardada dins @archive@. Podètz',
'<API key>' => 'tornar à la gestion',
'<API key>' => 'dau voastre sit.',
'<API key>' => 'Vous avez choisi de restaurer la sauvegarde @fichier@. Cette opération est irréversible.', # NEW
'<API key>' => 'Ou indiquez le nom du fichier à restaurer', # NEW
'<API key>' => 'Nom du fichier pour la sauvegarde', # NEW
'<API key>' => 'Sélectionnez un fichier dans la liste', # NEW
'nb_donnees' => '@nb@ enregistrements', # NEW
'<API key>' => 'Restauration en cours', # NEW
'sauvegarde_en_cours' => 'Sauvegarde en cours', # NEW
'<API key>' => 'Sauvegardes existantes', # NEW
'<API key>' => 'Sélectionnez les tables à restaurer', # NEW
'texte_admin_tech_01' => 'Aquela opcion vos permete de sauvagardar lo contengut de la basa dins un fichier que serà conservat dins lo repertòri @dossier@. Oblidetz pas manco de recuperar l\'integralitat dau repertòri @img@, que conten lu imatges e lu documents utilisats dins lu articles e rubricas.',
'texte_admin_tech_02' => 'Mèfi: aquela sauvagarda si podrà restaurar SOLAMENT dins un sit installat mé la mema version de SPIP. Cau sobretot pas « vuar la basa » en esperar tornar installar la sauvagarda après una mesa a jorn... Consultatz la <a href="@spipnet@">la documentacion de SPIP</a>.', # MODIF
'<API key>' => 'Restaurar lo contengut d\'una sauvagarda de la basa',
'<API key>' => 'Aquela opcion vos permete de restaurar una sauvagarda de la
basa qu\'aviatz facha avans. Per aquò faire, cau aver plaçat lo fichier que conten
la sauvagarda dins lo repertòri @dossier@.
Siguètz prudent(a) emb aquela foncionalitat: <b>li modificacions e pèrdas eventuali son
irreversibli.</b>',
'texte_sauvegarde' => 'Sauvagardar lo contengut de la basa',
'<API key>' => 'Sauvagardar la basa',
'tout_restaurer' => 'Restaurer toutes les tables', # NEW
'tout_sauvegarder' => 'Sauvegarder toutes les tables', # NEW
'une_donnee' => '1 enregistrement' # NEW
);
?> |
#ifndef <API key>
#define <API key>
typedef short cpu_t;
#define BINDPROCESS 1
#define BINDTHREAD 2
#define PROCESSOR_CLASS_ANY ((cpu_t)(-1))
extern int bindprocessor(int What, int Who, cpu_t Where);
extern cpu_t mycpu(void);
#endif /* <API key> */ |
/* repmct.f -- translated by f2c (version 19980913).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
#include "f2c.h"
/* $Procedure REPMCT ( Replace marker with cardinal text ) */
/* Subroutine */ int repmct_(char *in, char *marker, integer *value, char *
case__, char *out, ftnlen in_len, ftnlen marker_len, ftnlen case_len,
ftnlen out_len)
{
/* Builtin functions */
integer s_cmp(char *, char *, ftnlen, ftnlen);
/* Subroutine */ int s_copy(char *, char *, ftnlen, ftnlen);
integer i_indx(char *, char *, ftnlen, ftnlen);
/* Local variables */
char card[145];
extern /* Subroutine */ int lcase_(char *, char *, ftnlen, ftnlen),
chkin_(char *, ftnlen), ucase_(char *, char *, ftnlen, ftnlen),
errch_(char *, char *, ftnlen, ftnlen), ljust_(char *, char *,
ftnlen, ftnlen);
integer mrknbf;
extern integer lastnb_(char *, ftnlen);
integer mrknbl;
char tmpcas[1];
extern /* Subroutine */ int sigerr_(char *, ftnlen), chkout_(char *,
ftnlen);
extern integer frstnb_(char *, ftnlen);
integer mrkpsb;
extern /* Subroutine */ int repsub_(char *, integer *, integer *, char *,
char *, ftnlen, ftnlen, ftnlen);
integer mrkpse;
extern /* Subroutine */ int setmsg_(char *, ftnlen);
extern logical return_(void);
extern /* Subroutine */ int inttxt_(integer *, char *, ftnlen);
/* $ Abstract */
/* Replace a marker with the text representation of a */
/* cardinal number. */
/* CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. */
/* GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE */
/* ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE */
/* PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" */
/* WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A */
/* PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC */
/* SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE */
/* SOFTWARE AND RELATED MATERIALS, HOWEVER USED. */
/* IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA */
/* BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT */
/* LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, */
/* INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, */
/* REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE */
/* REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. */
/* RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF */
/* THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY */
/* CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE */
/* ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. */
/* $ Required_Reading */
/* None. */
/* $ Keywords */
/* CHARACTER */
/* CONVERSION */
/* STRING */
/* $ Declarations */
/* $ Brief_I/O */
/* VARIABLE I/O DESCRIPTION */
/* IN I Input string. */
/* MARKER I Marker to be replaced. */
/* VALUE I Cardinal value. */
/* CASE I Case of replacement text. */
/* OUT O Output string. */
/* MAXLCN P Maximum length of a cardinal number. */
/* $ Detailed_Input */
/* IN is an arbitrary character string. */
/* MARKER is an arbitrary character string. The first */
/* occurrence of MARKER in the input string is */
/* to be replaced by the text representation of */
/* the cardinal number VALUE. */
/* Leading and trailing blanks in MARKER are NOT */
/* significant. In particular, no substitution is */
/* performed if MARKER is blank. */
/* VALUE is an arbitrary integer. */
/* CASE indicates the case of the replacement text. */
/* CASE may be any of the following: */
/* CASE Meaning Example */
/* U, u Uppercase ONE HUNDRED FIFTY-THREE */
/* L, l Lowercase one hundred fifty-three */
/* C, c Capitalized One hundred fifty-three */
/* $ Detailed_Output */
/* OUT is the string obtained by substituting the text */
/* representation of the cardinal number VALUE for */
/* the first occurrence of MARKER in the input string. */
/* OUT and IN must be identical or disjoint. */
/* $ Parameters */
/* MAXLCN is the maximum expected length of any cardinal */
/* text. 145 characters are sufficient to hold the */
/* text representing any value in the range */
/* ( -10**12, 10**12 ) */
/* An example of a number whose text representation */
/* is of maximum length is */
/* - 777 777 777 777 */
/* $ Exceptions */
/* 1) If OUT does not have sufficient length to accommodate the */
/* result of the substitution, the result will be truncated on */
/* the right. */
/* 2) If MARKER is blank, or if MARKER is not a substring of IN, */
/* no substitution is performed. (OUT and IN are identical.) */
/* 3) If the value of CASE is not recognized, the error */
/* SPICE(INVALIDCASE) is signalled. OUT is not changed. */
/* $ Files */
/* None. */
/* $ Particulars */
/* This is one of a family of related routines for inserting values */
/* into strings. They are typically used to construct messages that */
/* are partly fixed, and partly determined at run time. For example, */
/* a message like */
/* 'Fifty-one pictures were found in directory [USER.DATA].' */
/* might be constructed from the fixed string */
/* '#1 pictures were found in directory #2.' */
/* by the calls */
/* CALL REPMCT ( STRING, '#1', NPICS, 'C', STRING ) */
/* CALL REPMC ( STRING, '#2', DIRNAM, STRING ) */
/* which substitute the cardinal text 'Fifty-one' and the character */
/* string '[USER.DATA]' for the markers '#1' and '#2' respectively. */
/* The complete list of routines is shown below. */
/* REPMC ( Replace marker with character string value ) */
/* REPMD ( Replace marker with double precision value ) */
/* REPMF ( Replace marker with formatted d.p. value ) */
/* REPMI ( Replace marker with integer value ) */
/* REPMCT ( Replace marker with cardinal text) */
/* REPMOT ( Replace marker with ordinal text ) */
/* $ Examples */
/* The following examples illustrate the use of REPMCT to */
/* replace a marker within a string with the cardinal text */
/* corresponding to an integer. */
/* Uppercase */
/* Let */
/* MARKER = '#' */
/* IN = 'INVALID COMMAND. WORD # WAS NOT RECOGNIZED.' */
/* Then following the call, */
/* CALL REPMCT ( IN, '#', 5, 'U', IN ) */
/* IN is */
/* 'INVALID COMMAND. WORD FIVE WAS NOT RECOGNIZED.' */
/* Lowercase */
/* Let */
/* MARKER = ' XX ' */
/* IN = 'Word XX of the XX sentence was misspelled.' */
/* Then following the call, */
/* CALL REPMCT ( IN, ' XX ', 5, 'L', OUT ) */
/* OUT is */
/* 'Word five of the XX sentence was misspelled.' */
/* Capitalized */
/* Let */
/* MARKER = ' XX ' */
/* IN = 'Name: YY. Rank: XX.' */
/* Then following the calls, */
/* CALL REPMC ( IN, 'YY', 'Moriarty', OUT ) */
/* CALL REPMCT ( OUT, 'XX', 1, 'C', OUT ) */
/* OUT is */
/* 'Name: Moriarty. Rank: One.' */
/* $ Restrictions */
/* 1) VALUE must be in the range accepted by subroutine INTTXT. */
/* This range is currently */
/* ( -10**12, 10**12 ) */
/* Note that the endpoints of the interval are excluded. */
/* $ <API key> */
/* None. */
/* $ <API key> */
/* N.J. Bachman (JPL) */
/* B.V. Semenov (JPL) */
/* W.L. Taber (JPL) */
/* I.M. Underwood (JPL) */
/* $ Version */
/* - SPICELIB Version 1.1.0, 21-SEP-2013 (BVS) */
/* and last non-blank characters only once. */
/* - SPICELIB Version 1.0.1, 10-MAR-1992 (WLT) */
/* Comment section for permuted index source lines was added */
/* following the header. */
/* - SPICELIB Version 1.0.0, 30-AUG-1990 (NJB) (IMU) */
/* $ Index_Entries */
/* replace marker with cardinal text */
/* SPICELIB functions */
/* Local variables */
/* Standard SPICE error handling. */
if (return_()) {
return 0;
} else {
chkin_("REPMCT", (ftnlen)6);
}
/* Bail out if CASE is not recognized. */
ljust_(case__, tmpcas, (ftnlen)1, (ftnlen)1);
ucase_(tmpcas, tmpcas, (ftnlen)1, (ftnlen)1);
if (*(unsigned char *)tmpcas != 'U' && *(unsigned char *)tmpcas != 'L' &&
*(unsigned char *)tmpcas != 'C') {
setmsg_("Case (#) must be U, L, or C.", (ftnlen)28);
errch_("#", case__, (ftnlen)1, (ftnlen)1);
sigerr_("SPICE(INVALIDCASE)", (ftnlen)18);
chkout_("REPMCT", (ftnlen)6);
return 0;
}
/* If MARKER is blank, no substitution is possible. */
if (s_cmp(marker, " ", marker_len, (ftnlen)1) == 0) {
s_copy(out, in, out_len, in_len);
chkout_("REPMCT", (ftnlen)6);
return 0;
}
/* Locate the leftmost occurrence of MARKER, if there is one */
/* (ignoring leading and trailing blanks). If MARKER is not */
/* a substring of IN, no substitution can be performed. */
mrknbf = frstnb_(marker, marker_len);
mrknbl = lastnb_(marker, marker_len);
mrkpsb = i_indx(in, marker + (mrknbf - 1), in_len, mrknbl - (mrknbf - 1));
if (mrkpsb == 0) {
s_copy(out, in, out_len, in_len);
chkout_("REPMCT", (ftnlen)6);
return 0;
}
mrkpse = mrkpsb + mrknbl - mrknbf;
/* Okay, CASE is recognized and MARKER has been found. */
/* Generate the cardinal text corresponding to VALUE. */
inttxt_(value, card, (ftnlen)145);
/* CARD is always returned in upper case; change to the specified */
/* case, if required. */
if (*(unsigned char *)tmpcas == 'L') {
lcase_(card, card, (ftnlen)145, (ftnlen)145);
} else if (*(unsigned char *)tmpcas == 'C') {
lcase_(card + 1, card + 1, (ftnlen)144, (ftnlen)144);
}
/* Replace MARKER with CARD. */
repsub_(in, &mrkpsb, &mrkpse, card, out, in_len, lastnb_(card, (ftnlen)
145), out_len);
chkout_("REPMCT", (ftnlen)6);
return 0;
} /* repmct_ */ |
#ifndef fluxFvPatchField_H
#define fluxFvPatchField_H
#include "<API key>.H"
namespace Foam
{
template<class Type>
class fluxFvPatchField
:
public <API key><Type>
{
// Private data
//- Flux
Field<Type> flux_;
//- Reactivity
scalarField reactivity_;
//- Name of diffusion field
word gammaName_;
public:
//- Runtime type information
TypeName("flux");
// Constructors
//- Construct from patch and internal field
fluxFvPatchField
(
const fvPatch&,
const DimensionedField<Type, volMesh>&
);
//- Construct from patch, internal field and dictionary
fluxFvPatchField
(
const fvPatch&,
const DimensionedField<Type, volMesh>&,
const dictionary&
);
//- Construct by mapping given fluxFvPatchField onto a new patch
fluxFvPatchField
(
const fluxFvPatchField<Type>&,
const fvPatch&,
const DimensionedField<Type, volMesh>&,
const fvPatchFieldMapper&
);
//- Construct as copy
fluxFvPatchField
(
const fluxFvPatchField<Type>&
);
//- Construct and return a clone
virtual tmp<fvPatchField<Type> > clone() const
{
return tmp<fvPatchField<Type> >
(
new fluxFvPatchField<Type>(*this)
);
}
//- Construct as copy setting internal field reference
fluxFvPatchField
(
const fluxFvPatchField<Type>&,
const DimensionedField<Type, volMesh>&
);
//- Construct and return a clone setting internal field reference
virtual tmp<fvPatchField<Type> > clone
(
const DimensionedField<Type, volMesh>& iF
) const
{
return tmp<fvPatchField<Type> >
(
new fluxFvPatchField<Type>(*this, iF)
);
}
// Member functions
//- Update the coefficients associated with the patch field
virtual void updateCoeffs();
//- Write
virtual void write(Ostream&) const;
};
} // End namespace Foam
#ifdef NoRepository
# include "fluxFvPatchField.C"
#endif
#endif |
<?php
namespace Dwoo\Plugins\Functions;
use Dwoo\Compiler;
use Dwoo\ICompilable;
use Dwoo\Plugin;
class FunctionAssign extends Plugin implements ICompilable {
public static function compile(Compiler $compiler, $value, $var) {
return '$this->assignInScope(' . $value . ', ' . $var . ')';
}
} |
#ifndef <API key>
#define <API key>
#include "tetPolyPatchField.H"
#include "<API key>.H"
#include "fieldTypes.H"
namespace Foam
{
<API key>
(
generic,
Generic,
tetPointMesh,
tetPolyPatch,
tetPolyPatch,
tetFemMatrix,
TetPolyPatch
);
} // End namespace Foam
#endif |
/// <reference path="../../allors.module.ts" />
namespace Allors.Bootstrap {
export class ImageModalTemplate {
static templateName = "allors/bootstrap/image/modal";
private static view =
`
<div class="modal-header">
<h3 class="modal-title">Image</h3>
</div>
<div class="modal-body">
<div class="row" style="height:20vw;">
<div class="col-sm-12 center-block" style="height:100%;">
<img ng-if="$ctrl.image" ng-src="{{$ctrl.image}}" class="img-responsive img-thumbnail" style="vertical-align: middle; height: 90%"/>
</div>
</div>
</div>
<div class="modal-footer">
<div class="pull-left">
<label class="btn btn-default" for="file-selector">
<input id="file-selector" type="file" style="display:none;" model-data-uri="$ctrl.image">
Upload an image
</label>
</div>
<button ng-enabled="$ctrl.image" class="btn btn-primary" type="button" ng-click="$ctrl.ok()">OK</button>
<button class="btn btn-danger" type="button" ng-click="$ctrl.cancel()">Cancel</button>
</div>
`;
static register(templateCache: angular.<API key>) {
templateCache.put(ImageModalTemplate.templateName, ImageModalTemplate.view);
}
}
export class <API key> {
image = "";
croppedImage = "";
static $inject = ["$scope", "$uibModalInstance", "$log", "$translate", "size", "format", "quality", "aspect"];
constructor(private $scope: angular.IScope, private $uibModalInstance: angular.ui.bootstrap.<API key>, $log: angular.ILogService, $translate: angular.translate.ITranslateService, private size: number, private format: string, private quality: number, private aspect: number) {
}
ok() {
this.$uibModalInstance.close(this.image);
}
cancel() {
this.$uibModalInstance.dismiss("cancel");
}
}
} |
#ifndef PARTITIONMODEL_H
#define PARTITIONMODEL_H
#include "OsproberEntry.h"
#include <QAbstractItemModel>
class Device;
class Partition;
class PartitionNode;
/**
* A Qt tree model which exposes the partitions of a device.
*
* Its depth is only more than 1 if the device has extended partitions.
*
* Note on updating:
*
* The Device class does not notify the outside world of changes on the
* Partition objects it owns. Since a Qt model must notify its views *before*
* and *after* making changes, it is important to make use of
* the PartitionModel::ResetHelper class to wrap changes.
*
* This is what PartitionCoreModule does when it create jobs.
*/
class PartitionModel : public QAbstractItemModel
{
Q_OBJECT
public:
/**
* This helper class must be instantiated on the stack *before* making
* changes to the device represented by this model. It will cause the model
* to emit modelAboutToBeReset() when instantiated and modelReset() when
* destructed.
*/
class ResetHelper
{
public:
ResetHelper( PartitionModel* model );
~ResetHelper();
ResetHelper( const ResetHelper& ) = delete;
ResetHelper& operator=( const ResetHelper& ) = delete;
private:
PartitionModel* m_model;
};
enum
{
// The raw size, as a qlonglong. This is different from the DisplayRole of
// SizeColumn, which is a human-readable string.
SizeRole = Qt::UserRole + 1,
IsFreeSpaceRole,
IsPartitionNewRole,
FileSystemLabelRole,
FileSystemTypeRole,
PartitionPathRole,
PartitionPtrRole, // passed as void*, use sparingly
OsproberNameRole,
OsproberPathRole,
<API key>,
OsproberRawLineRole,
<API key>
};
enum Column
{
NameColumn,
FileSystemColumn,
MountPointColumn,
SizeColumn,
ColumnCount // Must remain last
};
PartitionModel( QObject* parent = 0 );
/**
* device must remain alive for the life of PartitionModel
*/
void init( Device* device, const OsproberEntryList& osproberEntries );
// QAbstractItemModel API
QModelIndex index( int row, int column, const QModelIndex& parent = QModelIndex() ) const override;
QModelIndex parent( const QModelIndex& child ) const override;
int columnCount( const QModelIndex& parent = QModelIndex() ) const override;
int rowCount( const QModelIndex& parent = QModelIndex() ) const override;
QVariant data( const QModelIndex& index, int role = Qt::DisplayRole ) const override;
QVariant headerData( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const override;
Partition* partitionForIndex( const QModelIndex& index ) const;
Device* device() const
{
return m_device;
}
void update();
private:
Device* m_device;
OsproberEntryList m_osproberEntries;
};
#endif /* PARTITIONMODEL_H */ |
export default {
content: {
width: '100%',
padding: 10,
},
header: {
display: 'flex',
justifyContent: 'space-between',
},
title: {
display: 'inline',
},
icon: {
minWidth: 36,
},
}; |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Accordion Static Test : Default</title>
<link rel="stylesheet" href="../static.css" type="text/css" />
<link rel="stylesheet" href="../../../themes/base/jquery.ui.base.css" type="text/css" />
<link rel="stylesheet" href="../../../themes/base/jquery.ui.theme.css" type="text/css" title="ui-theme" />
<script type="text/javascript" src="../../../jquery-1.4.4.js"></script>
<script type="text/javascript" src="../static.js"></script>
</head>
<body>
<div class="ui-accordion ui-widget ui-helper-reset ui-accordion-icons">
<h3 class="ui-accordion-header <API key> ui-helper-reset ui-state-active ui-corner-top" tabindex="0">
<span class="ui-icon <API key>"></span>
<a href="#">Accordion Header 1</a>
</h3>
<div class="<API key> <API key> ui-helper-reset ui-widget-content ui-corner-bottom">
Accordion Content 1
</div>
<h3 class="ui-accordion-header ui-helper-reset ui-state-default ui-corner-all" tabindex="0">
<span class="ui-icon <API key>"></span>
<a href="#">Accordion Header 2</a>
</h3>
<div class="<API key> ui-helper-reset ui-widget-content ui-corner-bottom" style="height: 95px; display: none;">
Accordion Content 2
</div>
<h3 class="ui-accordion-header ui-helper-reset ui-state-default ui-corner-all" tabindex="0">
<span class="ui-icon <API key>"></span>
<a href="#">Accordion Header 3</a>
</h3>
<div class="<API key> ui-helper-reset ui-widget-content ui-corner-bottom" style="height: 95px; display: none;">
Accordion Content 2
</div>
</div>
</body>
</html> |
CREATE TABLE IF NOT EXISTS `buyingstore_items` (
`buyingstore_id` int(10) unsigned NOT NULL,
`index` smallint(5) unsigned NOT NULL,
`item_id` int(10) unsigned NOT NULL,
`amount` smallint(5) unsigned NOT NULL,
`price` int(10) unsigned NOT NULL
) ENGINE=MyISAM;
CREATE TABLE IF NOT EXISTS `buyingstores` (
`id` int(10) unsigned NOT NULL,
`account_id` int(11) unsigned NOT NULL,
`char_id` int(10) unsigned NOT NULL,
`sex` enum('F','M') NOT NULL DEFAULT 'M',
`map` varchar(20) NOT NULL,
`x` smallint(5) unsigned NOT NULL,
`y` smallint(5) unsigned NOT NULL,
`title` varchar(80) NOT NULL,
`limit` int(10) unsigned NOT NULL,
`autotrade` tinyint(4) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM; |
# - Find DC1394 alias libdc1394
# This module finds an installed DC1394 package.
# It sets the following variables:
# DC1394_FOUND - Set to false, or undefined, if DC1394 isn't found.
# DC1394_INCLUDE_DIRS - The DC1394 include directory.
# DC1394_LIBRARIES - The DC1394 library to link against.
find_path(DC1394_INCLUDE_DIRS NAMES dc1394.h PATH_SUFFIXES dc1394)
find_library(DC1394_LIBRARIES NAMES dc1394)
IF (DC1394_INCLUDE_DIRS AND DC1394_LIBRARIES)
SET(DC1394_FOUND TRUE)
#On Mac OS X
if(CMAKE_SYSTEM_NAME MATCHES "Darwin")
set(DC1394_LIBRARIES ${DC1394_LIBRARIES} "-framework CoreServices")
endif(CMAKE_SYSTEM_NAME MATCHES "Darwin")
ENDIF (DC1394_INCLUDE_DIRS AND DC1394_LIBRARIES)
IF (DC1394_FOUND)
# show which DC1394 was found only if not quiet
IF (NOT DC1394_FIND_QUIETLY)
MESSAGE(STATUS "Found DC1394: ${DC1394_LIBRARIES}")
ENDIF (NOT DC1394_FIND_QUIETLY)
ELSE (DC1394_FOUND)
# fatal error if DC1394 is required but not found
IF (<API key>)
MESSAGE(FATAL_ERROR "Could not find DC1394 (libdc1394)")
ENDIF (<API key>)
ENDIF (DC1394_FOUND) |
#include "wxsimagepanel.h"
namespace
{
// Loading images from xpm files
#include "wxImagePanel16.xpm"
#include "wxImagePanel32.xpm"
wxsRegisterItem<wxsImagePanel> Reg(
_T("wxImagePanel"), // Class name
wxsTContainer, // Item type
_T("wxWindows"),
_T("Ron Collins"), // Author
_T("rcoll@theriver.com"), // Author's email
_T(""), // Item's homepage
_T("Contrib"), // Category in palette
60, // Priority in palette
_T("ImagePanel"), // Base part of names for new items
wxsCPP, // List of coding languages supported by this item
1, 0, // Version
wxBitmap(wxImagePanel32_xpm), // 32x32 bitmap
wxBitmap(wxImagePanel16_xpm), // 16x16 bitmap
false); // We do not allow this item inside XRC files
WXS_ST_BEGIN(wxsImagePanelStyles,_T("wxRAISED_BORDER|wxTAB_TRAVERSAL"))
WXS_ST_CATEGORY("wxImagePanel")
WXS_ST_DEFAULTS()
WXS_ST_END()
WXS_EV_BEGIN(wxsImagePanelEvents)
WXS_EV_DEFAULTS()
WXS_EV_END()
}
wxsImagePanel::wxsImagePanel(wxsItemResData* Data):
wxsContainer(
Data,
&Reg.Info,
wxsImagePanelEvents,
wxsImagePanelStyles)
{
mImage = _("<none>");
mStretch = false;
}
wxsImagePanel::~wxsImagePanel() {
}
void wxsImagePanel::OnBuildCreatingCode() {
wxString vname;
wxString iname;
wxsImage *image;
wxString tt;
// we only handle C++ constructs here
if (GetLanguage() != wxsCPP) wxsCodeMarks::Unknown(_T("wxsImagePanel"),GetLanguage());
// who we are
vname = GetVarName();
// get the image record, and the name of the bitmap associated with it
image = (wxsImage *) <API key>::FindTool(this, mImage);
if (image == NULL) {
iname = wxEmptyString;
}
else {
iname = image->GetVarName();
iname += _("_BMP");
};
// include files
AddHeader(_("\"wx/wxImagePanel.h\""), GetInfo().ClassName, 0);
// create the panel
Codef(_T("%C(%W, %I, %P, %S, %T, %N);\n"));
// the stretching flag
Codef(_T("%ASetStretch(%b);\n"), mStretch);
// the image has to be assigned to the panel AFTER the image is created
// since wxsImage is a wxsTool type, that all happens after the panel is created
if (iname.Length() > 0) {
// Locator comment.
tt.Printf(_("// Set the bitmap for %s.\n"), vname.wx_str());
AddEventCode(tt);
#if wxCHECK_VERSION(3, 0, 0)
tt.Printf(_T("%s->SetBitmap(*%s);\n"), vname.wx_str(), iname.wx_str());
#else
tt.Printf(_T("%s->SetBitmap(*%s);\n"), vname.c_str(), iname.c_str());
#endif
AddEventCode(tt);
};
// do the rest of it
<API key>();
// add children
AddChildrenCode();
}
wxObject* wxsImagePanel::OnBuildPreview(wxWindow* Parent, long Flags) {
wxImagePanel *ap;
wxsImage *image;
wxBitmap bmp;
// make a panel
ap = new wxImagePanel(Parent, GetId(), Pos(Parent), Size(Parent), Style());
if (ap == NULL) return NULL;
// get the wxsImage pointer
image = (wxsImage *) <API key>::FindTool(this, mImage);
// and make the preview image
if (image != NULL) {
bmp = ((wxsImage *) image)->GetPreview();
ap->SetBitmap(bmp);
};
// and stretch it?
ap->SetStretch(mStretch);
// set all decorations
SetupWindow(ap, Flags);
// add the children
AddChildrenPreview(ap, Flags);
// done
return ap;
}
void wxsImagePanel::<API key>(cb_unused long Flags) {
static wxString sImageNames[128];
static const wxChar *pImageNames[128];
int i,n,k;
wxsItemResData *res;
wxsTool *tool;
wxString ss, tt;
// find available images, and pointer to current imagelist
res = GetResourceData();
n = 0;
sImageNames[n] = _("<none>");
pImageNames[n] = (const wxChar *) sImageNames[n];
n += 1;
k = res->GetToolsCount();
for(i=0; i<k; i++) {
tool = res->GetTool(i);
ss = tool->GetUserClass();
if ((ss == _T("wxImage")) && (n < 127)) {
ss = tool->GetVarName();
sImageNames[n] = ss;
pImageNames[n] = (const wxChar *) sImageNames[n];
n += 1;
};
};
pImageNames[n] = NULL;
WXS_EDITENUM(wxsImagePanel, mImage, _("Image"), _T("image"), pImageNames, _("<none>"))
// stretch to fit panel?
WXS_BOOL(wxsImagePanel, mStretch, _("Stretch"), _T("stretch"), false);
}; |
#include "base/containers/small_map.h"
#include <stddef.h>
#include <algorithm>
#include <functional>
#include <map>
#include "base/containers/hash_tables.h"
#include "base/logging.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
TEST(SmallMap, General) {
SmallMap<hash_map<int, int> > m;
EXPECT_TRUE(m.empty());
m[0] = 5;
EXPECT_FALSE(m.empty());
EXPECT_EQ(m.size(), 1u);
m[9] = 2;
EXPECT_FALSE(m.empty());
EXPECT_EQ(m.size(), 2u);
EXPECT_EQ(m[9], 2);
EXPECT_EQ(m[0], 5);
EXPECT_FALSE(m.UsingFullMap());
SmallMap<hash_map<int, int> >::iterator iter(m.begin());
ASSERT_TRUE(iter != m.end());
EXPECT_EQ(iter->first, 0);
EXPECT_EQ(iter->second, 5);
++iter;
ASSERT_TRUE(iter != m.end());
EXPECT_EQ((*iter).first, 9);
EXPECT_EQ((*iter).second, 2);
++iter;
EXPECT_TRUE(iter == m.end());
m[8] = 23;
m[1234] = 90;
m[-5] = 6;
EXPECT_EQ(m[ 9], 2);
EXPECT_EQ(m[ 0], 5);
EXPECT_EQ(m[1234], 90);
EXPECT_EQ(m[ 8], 23);
EXPECT_EQ(m[ -5], 6);
EXPECT_EQ(m.size(), 5u);
EXPECT_FALSE(m.empty());
EXPECT_TRUE(m.UsingFullMap());
iter = m.begin();
for (int i = 0; i < 5; i++) {
EXPECT_TRUE(iter != m.end());
++iter;
}
EXPECT_TRUE(iter == m.end());
const SmallMap<hash_map<int, int> >& ref = m;
EXPECT_TRUE(ref.find(1234) != m.end());
EXPECT_TRUE(ref.find(5678) == m.end());
}
TEST(SmallMap, <API key>) {
SmallMap<hash_map<int, int> > m;
m[0] = 5;
m[2] = 3;
{
SmallMap<hash_map<int, int> >::iterator iter(m.begin());
SmallMap<hash_map<int, int> >::iterator last(iter++);
++last;
EXPECT_TRUE(last == iter);
}
{
SmallMap<hash_map<int, int> >::const_iterator iter(m.begin());
SmallMap<hash_map<int, int> >::const_iterator last(iter++);
++last;
EXPECT_TRUE(last == iter);
}
}
// Based on the General testcase.
TEST(SmallMap, CopyConstructor) {
SmallMap<hash_map<int, int> > src;
{
SmallMap<hash_map<int, int> > m(src);
EXPECT_TRUE(m.empty());
}
src[0] = 5;
{
SmallMap<hash_map<int, int> > m(src);
EXPECT_FALSE(m.empty());
EXPECT_EQ(m.size(), 1u);
}
src[9] = 2;
{
SmallMap<hash_map<int, int> > m(src);
EXPECT_FALSE(m.empty());
EXPECT_EQ(m.size(), 2u);
EXPECT_EQ(m[9], 2);
EXPECT_EQ(m[0], 5);
EXPECT_FALSE(m.UsingFullMap());
}
src[8] = 23;
src[1234] = 90;
src[-5] = 6;
{
SmallMap<hash_map<int, int> > m(src);
EXPECT_EQ(m[ 9], 2);
EXPECT_EQ(m[ 0], 5);
EXPECT_EQ(m[1234], 90);
EXPECT_EQ(m[ 8], 23);
EXPECT_EQ(m[ -5], 6);
EXPECT_EQ(m.size(), 5u);
EXPECT_FALSE(m.empty());
EXPECT_TRUE(m.UsingFullMap());
}
}
template<class inner>
static bool SmallMapIsSubset(SmallMap<inner> const& a,
SmallMap<inner> const& b) {
typename SmallMap<inner>::const_iterator it;
for (it = a.begin(); it != a.end(); ++it) {
typename SmallMap<inner>::const_iterator it_in_b = b.find(it->first);
if (it_in_b == b.end() || it_in_b->second != it->second)
return false;
}
return true;
}
template<class inner>
static bool SmallMapEqual(SmallMap<inner> const& a,
SmallMap<inner> const& b) {
return SmallMapIsSubset(a, b) && SmallMapIsSubset(b, a);
}
TEST(SmallMap, AssignmentOperator) {
SmallMap<hash_map<int, int> > src_small;
SmallMap<hash_map<int, int> > src_large;
src_small[1] = 20;
src_small[2] = 21;
src_small[3] = 22;
EXPECT_FALSE(src_small.UsingFullMap());
src_large[1] = 20;
src_large[2] = 21;
src_large[3] = 22;
src_large[5] = 23;
src_large[6] = 24;
src_large[7] = 25;
EXPECT_TRUE(src_large.UsingFullMap());
// Assignments to empty.
SmallMap<hash_map<int, int> > dest_small;
dest_small = src_small;
EXPECT_TRUE(SmallMapEqual(dest_small, src_small));
EXPECT_EQ(dest_small.UsingFullMap(),
src_small.UsingFullMap());
SmallMap<hash_map<int, int> > dest_large;
dest_large = src_large;
EXPECT_TRUE(SmallMapEqual(dest_large, src_large));
EXPECT_EQ(dest_large.UsingFullMap(),
src_large.UsingFullMap());
// Assignments which assign from full to small, and vice versa.
dest_small = src_large;
EXPECT_TRUE(SmallMapEqual(dest_small, src_large));
EXPECT_EQ(dest_small.UsingFullMap(),
src_large.UsingFullMap());
dest_large = src_small;
EXPECT_TRUE(SmallMapEqual(dest_large, src_small));
EXPECT_EQ(dest_large.UsingFullMap(),
src_small.UsingFullMap());
// Double check that SmallMapEqual works:
dest_large[42] = 666;
EXPECT_FALSE(SmallMapEqual(dest_large, src_small));
}
TEST(SmallMap, Insert) {
SmallMap<hash_map<int, int> > sm;
// loop through the transition from small map to map.
for (int i = 1; i <= 10; ++i) {
VLOG(1) << "Iteration " << i;
// insert an element
std::pair<SmallMap<hash_map<int, int> >::iterator,
bool> ret;
ret = sm.insert(std::make_pair(i, 100*i));
EXPECT_TRUE(ret.second);
EXPECT_TRUE(ret.first == sm.find(i));
EXPECT_EQ(ret.first->first, i);
EXPECT_EQ(ret.first->second, 100*i);
// try to insert it again with different value, fails, but we still get an
// iterator back with the original value.
ret = sm.insert(std::make_pair(i, -i));
EXPECT_FALSE(ret.second);
EXPECT_TRUE(ret.first == sm.find(i));
EXPECT_EQ(ret.first->first, i);
EXPECT_EQ(ret.first->second, 100*i);
// check the state of the map.
for (int j = 1; j <= i; ++j) {
SmallMap<hash_map<int, int> >::iterator it = sm.find(j);
EXPECT_TRUE(it != sm.end());
EXPECT_EQ(it->first, j);
EXPECT_EQ(it->second, j * 100);
}
EXPECT_EQ(sm.size(), static_cast<size_t>(i));
EXPECT_FALSE(sm.empty());
}
}
TEST(SmallMap, InsertRange) {
// loop through the transition from small map to map.
for (int elements = 0; elements <= 10; ++elements) {
VLOG(1) << "Elements " << elements;
hash_map<int, int> normal_map;
for (int i = 1; i <= elements; ++i) {
normal_map.insert(std::make_pair(i, 100*i));
}
SmallMap<hash_map<int, int> > sm;
sm.insert(normal_map.begin(), normal_map.end());
EXPECT_EQ(normal_map.size(), sm.size());
for (int i = 1; i <= elements; ++i) {
VLOG(1) << "Iteration " << i;
EXPECT_TRUE(sm.find(i) != sm.end());
EXPECT_EQ(sm.find(i)->first, i);
EXPECT_EQ(sm.find(i)->second, 100*i);
}
}
}
TEST(SmallMap, Erase) {
SmallMap<hash_map<std::string, int> > m;
SmallMap<hash_map<std::string, int> >::iterator iter;
m["monday"] = 1;
m["tuesday"] = 2;
m["wednesday"] = 3;
EXPECT_EQ(m["monday" ], 1);
EXPECT_EQ(m["tuesday" ], 2);
EXPECT_EQ(m["wednesday"], 3);
EXPECT_EQ(m.count("tuesday"), 1u);
EXPECT_FALSE(m.UsingFullMap());
iter = m.begin();
ASSERT_TRUE(iter != m.end());
EXPECT_EQ(iter->first, "monday");
EXPECT_EQ(iter->second, 1);
++iter;
ASSERT_TRUE(iter != m.end());
EXPECT_EQ(iter->first, "tuesday");
EXPECT_EQ(iter->second, 2);
++iter;
ASSERT_TRUE(iter != m.end());
EXPECT_EQ(iter->first, "wednesday");
EXPECT_EQ(iter->second, 3);
++iter;
EXPECT_TRUE(iter == m.end());
EXPECT_EQ(m.erase("tuesday"), 1u);
EXPECT_EQ(m["monday" ], 1);
EXPECT_EQ(m["wednesday"], 3);
EXPECT_EQ(m.count("tuesday"), 0u);
EXPECT_EQ(m.erase("tuesday"), 0u);
iter = m.begin();
ASSERT_TRUE(iter != m.end());
EXPECT_EQ(iter->first, "monday");
EXPECT_EQ(iter->second, 1);
++iter;
ASSERT_TRUE(iter != m.end());
EXPECT_EQ(iter->first, "wednesday");
EXPECT_EQ(iter->second, 3);
++iter;
EXPECT_TRUE(iter == m.end());
m["thursday"] = 4;
m["friday"] = 5;
EXPECT_EQ(m.size(), 4u);
EXPECT_FALSE(m.empty());
EXPECT_FALSE(m.UsingFullMap());
m["saturday"] = 6;
EXPECT_TRUE(m.UsingFullMap());
EXPECT_EQ(m.count("friday"), 1u);
EXPECT_EQ(m.erase("friday"), 1u);
EXPECT_TRUE(m.UsingFullMap());
EXPECT_EQ(m.count("friday"), 0u);
EXPECT_EQ(m.erase("friday"), 0u);
EXPECT_EQ(m.size(), 4u);
EXPECT_FALSE(m.empty());
EXPECT_EQ(m.erase("monday"), 1u);
EXPECT_EQ(m.size(), 3u);
EXPECT_FALSE(m.empty());
m.clear();
EXPECT_FALSE(m.UsingFullMap());
EXPECT_EQ(m.size(), 0u);
EXPECT_TRUE(m.empty());
}
TEST(SmallMap, <API key>) {
SmallMap<hash_map<std::string, int> > m;
SmallMap<hash_map<std::string, int> >::iterator iter;
m["a"] = 0;
m["b"] = 1;
m["c"] = 2;
// Erase first item.
auto following_iter = m.erase(m.begin());
EXPECT_EQ(m.begin(), following_iter);
EXPECT_EQ(2u, m.size());
EXPECT_EQ(m.count("a"), 0u);
EXPECT_EQ(m.count("b"), 1u);
EXPECT_EQ(m.count("c"), 1u);
// Iterate to last item and erase it.
++following_iter;
following_iter = m.erase(following_iter);
ASSERT_EQ(1u, m.size());
EXPECT_EQ(m.end(), following_iter);
EXPECT_EQ(m.count("b"), 0u);
EXPECT_EQ(m.count("c"), 1u);
// Erase remaining item.
following_iter = m.erase(m.begin());
EXPECT_TRUE(m.empty());
EXPECT_EQ(m.end(), following_iter);
}
TEST(SmallMap, NonHashMap) {
SmallMap<std::map<int, int>, 4, std::equal_to<int> > m;
EXPECT_TRUE(m.empty());
m[9] = 2;
m[0] = 5;
EXPECT_EQ(m[9], 2);
EXPECT_EQ(m[0], 5);
EXPECT_EQ(m.size(), 2u);
EXPECT_FALSE(m.empty());
EXPECT_FALSE(m.UsingFullMap());
SmallMap<std::map<int, int>, 4, std::equal_to<int> >::iterator iter(
m.begin());
ASSERT_TRUE(iter != m.end());
EXPECT_EQ(iter->first, 9);
EXPECT_EQ(iter->second, 2);
++iter;
ASSERT_TRUE(iter != m.end());
EXPECT_EQ(iter->first, 0);
EXPECT_EQ(iter->second, 5);
++iter;
EXPECT_TRUE(iter == m.end());
--iter;
ASSERT_TRUE(iter != m.end());
EXPECT_EQ(iter->first, 0);
EXPECT_EQ(iter->second, 5);
m[8] = 23;
m[1234] = 90;
m[-5] = 6;
EXPECT_EQ(m[ 9], 2);
EXPECT_EQ(m[ 0], 5);
EXPECT_EQ(m[1234], 90);
EXPECT_EQ(m[ 8], 23);
EXPECT_EQ(m[ -5], 6);
EXPECT_EQ(m.size(), 5u);
EXPECT_FALSE(m.empty());
EXPECT_TRUE(m.UsingFullMap());
iter = m.begin();
ASSERT_TRUE(iter != m.end());
EXPECT_EQ(iter->first, -5);
EXPECT_EQ(iter->second, 6);
++iter;
ASSERT_TRUE(iter != m.end());
EXPECT_EQ(iter->first, 0);
EXPECT_EQ(iter->second, 5);
++iter;
ASSERT_TRUE(iter != m.end());
EXPECT_EQ(iter->first, 8);
EXPECT_EQ(iter->second, 23);
++iter;
ASSERT_TRUE(iter != m.end());
EXPECT_EQ(iter->first, 9);
EXPECT_EQ(iter->second, 2);
++iter;
ASSERT_TRUE(iter != m.end());
EXPECT_EQ(iter->first, 1234);
EXPECT_EQ(iter->second, 90);
++iter;
EXPECT_TRUE(iter == m.end());
--iter;
ASSERT_TRUE(iter != m.end());
EXPECT_EQ(iter->first, 1234);
EXPECT_EQ(iter->second, 90);
}
TEST(SmallMap, <API key>) {
// If these tests compile, they pass. The EXPECT calls are only there to avoid
// unused variable warnings.
SmallMap<hash_map<int, int> > hm;
EXPECT_EQ(0u, hm.size());
SmallMap<std::map<int, int> > m;
EXPECT_EQ(0u, m.size());
}
namespace {
class hash_map_add_item : public hash_map<int, int> {
public:
hash_map_add_item() {}
explicit hash_map_add_item(const std::pair<int, int>& item) {
insert(item);
}
};
void InitMap(ManualConstructor<hash_map_add_item>* map_ctor) {
map_ctor->Init(std::make_pair(0, 0));
}
class <API key> {
public:
explicit <API key>(int item_to_add)
: item_(item_to_add) {}
<API key>()
: item_(0) {}
void operator()(ManualConstructor<hash_map_add_item>* map_ctor) const {
map_ctor->Init(std::make_pair(item_, item_));
}
int item_;
};
} // anonymous namespace
TEST(SmallMap, <API key>) {
SmallMap<hash_map_add_item, 4, std::equal_to<int>,
void (&)(ManualConstructor<hash_map_add_item>*)> m(InitMap);
EXPECT_TRUE(m.empty());
m[1] = 1;
m[2] = 2;
m[3] = 3;
m[4] = 4;
EXPECT_EQ(4u, m.size());
EXPECT_EQ(0u, m.count(0));
m[5] = 5;
EXPECT_EQ(6u, m.size());
// Our function adds an extra item when we convert to a map.
EXPECT_EQ(1u, m.count(0));
}
TEST(SmallMap, <API key>) {
SmallMap<hash_map_add_item, 4, std::equal_to<int>,
<API key>> m(<API key>(-1));
EXPECT_TRUE(m.empty());
m[1] = 1;
m[2] = 2;
m[3] = 3;
m[4] = 4;
EXPECT_EQ(4u, m.size());
EXPECT_EQ(0u, m.count(-1));
m[5] = 5;
EXPECT_EQ(6u, m.size());
// Our functor adds an extra item when we convert to a map.
EXPECT_EQ(1u, m.count(-1));
}
// This class acts as a basic implementation of a move-only type. The canonical
// example of such a type is scoped_ptr/unique_ptr.
class MoveOnlyType {
public:
MoveOnlyType() : value_(0) {}
explicit MoveOnlyType(int value) : value_(value) {}
MoveOnlyType(MoveOnlyType&& other) {
*this = std::move(other);
}
MoveOnlyType& operator=(MoveOnlyType&& other) {
value_ = other.value_;
other.value_ = 0;
return *this;
}
MoveOnlyType(const MoveOnlyType&) = delete;
MoveOnlyType& operator=(const MoveOnlyType&) = delete;
int value() const { return value_; }
private:
int value_;
};
TEST(SmallMap, MoveOnlyValueType) {
SmallMap<std::map<int, MoveOnlyType>, 2> m;
m[0] = MoveOnlyType(1);
m[1] = MoveOnlyType(2);
m.erase(m.begin());
// SmallMap will move m[1] to an earlier index in the internal array.
EXPECT_EQ(m.size(), 1u);
EXPECT_EQ(m[1].value(), 2);
m[0] = MoveOnlyType(1);
// SmallMap must move the values from the array into the internal std::map.
m[2] = MoveOnlyType(3);
EXPECT_EQ(m.size(), 3u);
EXPECT_EQ(m[0].value(), 1);
EXPECT_EQ(m[1].value(), 2);
EXPECT_EQ(m[2].value(), 3);
m.erase(m.begin());
// SmallMap should also let internal std::map erase with a move-only type.
EXPECT_EQ(m.size(), 2u);
EXPECT_EQ(m[1].value(), 2);
EXPECT_EQ(m[2].value(), 3);
}
} // namespace base |
'use strict';
jest
.disableAutomock()
.dontMock('event-target-shim')
.setMock('NativeModules', {
Networking: {
addListener: function(){},
removeListeners: function(){},
}
});
const XMLHttpRequest = require('XMLHttpRequest');
describe('XMLHttpRequest', function(){
var xhr;
var handleTimeout;
var handleError;
var handleLoad;
var <API key>;
beforeEach(() => {
xhr = new XMLHttpRequest();
xhr.ontimeout = jest.fn();
xhr.onerror = jest.fn();
xhr.onload = jest.fn();
xhr.onreadystatechange = jest.fn();
handleTimeout = jest.fn();
handleError = jest.fn();
handleLoad = jest.fn();
<API key> = jest.fn();
xhr.addEventListener('timeout', handleTimeout);
xhr.addEventListener('error', handleError);
xhr.addEventListener('load', handleLoad);
xhr.addEventListener('readystatechange', <API key>);
xhr.__didCreateRequest(1);
});
afterEach(() => {
xhr = null;
handleTimeout = null;
handleError = null;
handleLoad = null;
});
it('should transition readyState correctly', function() {
expect(xhr.readyState).toBe(xhr.UNSENT);
xhr.open('GET', 'blabla');
expect(xhr.onreadystatechange.mock.calls.length).toBe(1);
expect(<API key>.mock.calls.length).toBe(1);
expect(xhr.readyState).toBe(xhr.OPENED);
});
it('should expose responseType correctly', function() {
expect(xhr.responseType).toBe('');
// Setting responseType to an unsupported value has no effect.
xhr.responseType = '<API key>';
expect(xhr.responseType).toBe('');
xhr.responseType = 'arraybuffer';
expect(xhr.responseType).toBe('arraybuffer');
// Can't change responseType after first data has been received.
xhr.__didReceiveData(1, 'Some data');
expect(() => { xhr.responseType = 'text'; }).toThrow();
});
it('should expose responseText correctly', function() {
xhr.responseType = '';
expect(xhr.responseText).toBe('');
expect(xhr.response).toBe('');
xhr.responseType = 'arraybuffer';
expect(() => xhr.responseText).toThrow();
expect(xhr.response).toBe(null);
xhr.responseType = 'text';
expect(xhr.responseText).toBe('');
expect(xhr.response).toBe('');
// responseText is read-only.
expect(() => { xhr.responseText = 'hi'; }).toThrow();
expect(xhr.responseText).toBe('');
expect(xhr.response).toBe('');
xhr.__didReceiveData(1, 'Some data');
expect(xhr.responseText).toBe('Some data');
});
it('should call ontimeout function when the request times out', function(){
xhr.<API key>(1, 'Timeout', true);
expect(xhr.readyState).toBe(xhr.DONE);
expect(xhr.ontimeout.mock.calls.length).toBe(1);
expect(xhr.onerror).not.toBeCalled();
expect(xhr.onload).not.toBeCalled();
expect(handleTimeout.mock.calls.length).toBe(1);
expect(handleError).not.toBeCalled();
expect(handleLoad).not.toBeCalled();
});
it('should call onerror function when the request times out', function(){
xhr.<API key>(1, 'Generic error');
expect(xhr.readyState).toBe(xhr.DONE);
expect(xhr.onreadystatechange.mock.calls.length).toBe(1);
expect(xhr.onerror.mock.calls.length).toBe(1);
expect(xhr.ontimeout).not.toBeCalled();
expect(xhr.onload).not.toBeCalled();
expect(<API key>.mock.calls.length).toBe(1);
expect(handleError.mock.calls.length).toBe(1);
expect(handleTimeout).not.toBeCalled();
expect(handleLoad).not.toBeCalled();
});
it('should call onload function when there is no error', function(){
xhr.<API key>(1, null);
expect(xhr.readyState).toBe(xhr.DONE);
expect(xhr.onreadystatechange.mock.calls.length).toBe(1);
expect(xhr.onload.mock.calls.length).toBe(1);
expect(xhr.onerror).not.toBeCalled();
expect(xhr.ontimeout).not.toBeCalled();
expect(<API key>.mock.calls.length).toBe(1);
expect(handleLoad.mock.calls.length).toBe(1);
expect(handleError).not.toBeCalled();
expect(handleTimeout).not.toBeCalled();
});
it('should call onload function when there is no error', function() {
xhr.upload.onprogress = jest.fn();
var handleProgress = jest.fn();
xhr.upload.addEventListener('progress', handleProgress);
xhr.__didUploadProgress(1, 42, 100);
expect(xhr.upload.onprogress.mock.calls.length).toBe(1);
expect(handleProgress.mock.calls.length).toBe(1);
expect(xhr.upload.onprogress.mock.calls[0][0].loaded).toBe(42);
expect(xhr.upload.onprogress.mock.calls[0][0].total).toBe(100);
expect(handleProgress.mock.calls[0][0].loaded).toBe(42);
expect(handleProgress.mock.calls[0][0].total).toBe(100);
});
}); |
#ifndef faPatchFieldsFwd_H
#define faPatchFieldsFwd_H
#include "fieldTypes.H"
namespace Foam
{
template<class Type> class faPatchField;
typedef faPatchField<scalar> faPatchScalarField;
typedef faPatchField<vector> faPatchVectorField;
typedef faPatchField<sphericalTensor> <API key>;
typedef faPatchField<symmTensor> <API key>;
typedef faPatchField<tensor> faPatchTensorField;
} // End namespace Foam
#endif |
<?php
// Moodle is free software: you can redistribute it and/or modify
// (at your option) any later version.
// Moodle is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
declare(strict_types=1);
namespace core_reportbuilder\task;
use core_user;
use core\task\adhoc_task;
use core_reportbuilder\local\helpers\schedule as helper;
use core_reportbuilder\local\models\schedule;
class send_schedule extends adhoc_task {
use \core\task\logging_trait;
/**
* Execute the task
*/
public function execute(): void {
global $USER, $DB;
[
'reportid' => $reportid,
'scheduleid' => $scheduleid,
] = (array) $this->get_custom_data();
$schedule = schedule::get_record(['id' => $scheduleid, 'reportid' => $reportid]);
if ($schedule === false) {
$this->log('Invalid schedule', 0);
return;
}
$originaluser = $USER;
$scheduleuserviewas = $schedule->get('userviewas');
$schedulereportempty = $schedule->get('reportempty');
$scheduleattachment = null;
$this->log_start('Sending schedule: ' . $schedule->get_formatted_name());
// Handle schedule configuration as to who the report should be viewed as.
if ($scheduleuserviewas === schedule::<API key>) {
cron_setup_user(core_user::get_user($schedule->get('usercreated')));
$scheduleattachment = helper::<API key>($schedule);
} else if ($scheduleuserviewas !== schedule::<API key>) {
cron_setup_user(core_user::get_user($scheduleuserviewas));
$scheduleattachment = helper::<API key>($schedule);
}
// Apply special handling if report is empty (default is to send it anyway).
if ($schedulereportempty === schedule::<API key> &&
$scheduleattachment !== null && helper::<API key>($schedule) === 0) {
$this->log('Empty report, skipping');
return;
}
$users = helper::<API key>($schedule);
foreach ($users as $user) {
$this->log('Sending to: ' . fullname($user, true));
// If we already created the attachment, send that. Otherwise generate per recipient.
if ($scheduleattachment !== null) {
helper::<API key>($schedule, $user, $scheduleattachment);
} else {
cron_setup_user($user);
if ($schedulereportempty === schedule::<API key> &&
helper::<API key>($schedule) === 0) {
$this->log('Empty report, skipping', 2);
continue;
}
$recipientattachment = helper::<API key>($schedule);
helper::<API key>($schedule, $user, $recipientattachment);
$recipientattachment->delete();
}
}
// Finish, clean up (set persistent property manually to avoid updating it's user/time modified data).
$DB->set_field($schedule::TABLE, 'timelastsent', time(), ['id' => $schedule->get('id')]);
if ($scheduleattachment !== null) {
$scheduleattachment->delete();
}
$this->log_finish('Sending schedule complete');
// Restore cron user to original state.
cron_setup_user($originaluser);
}
} |
# This code is part of Ansible, but is an independent component.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# to the complete work.
# are permitted provided that the following conditions are met:
# and/or other materials provided with the distribution.
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import signal
import socket
import struct
import os
import uuid
from functools import partial
from ansible.module_utils.basic import get_exception
from ansible.module_utils._text import to_bytes, to_native, to_text
def send_data(s, data):
packed_len = struct.pack('!Q', len(data))
return s.sendall(packed_len + data)
def recv_data(s):
header_len = 8 # size of a packed unsigned long long
data = to_bytes("")
while len(data) < header_len:
d = s.recv(header_len - len(data))
if not d:
return None
data += d
data_len = struct.unpack('!Q', data[:header_len])[0]
data = data[header_len:]
while len(data) < data_len:
d = s.recv(data_len - len(data))
if not d:
return None
data += d
return data
def exec_command(module, command):
try:
sf = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sf.connect(module._socket_path)
data = "EXEC: %s" % command
send_data(sf, to_bytes(data.strip()))
rc = int(recv_data(sf), 10)
stdout = recv_data(sf)
stderr = recv_data(sf)
except socket.error:
exc = get_exception()
sf.close()
module.fail_json(msg='unable to connect to socket', err=str(exc))
sf.close()
return rc, to_native(stdout), to_native(stderr)
class Connection:
def __init__(self, module):
self._module = module
def __getattr__(self, name):
try:
return self.__dict__[name]
except KeyError:
if name.startswith('_'):
raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name))
return partial(self.__rpc__, name)
def __rpc__(self, name, *args, **kwargs):
"""Executes the json-rpc and returns the output received
from remote device.
:name: rpc method to be executed over connection plugin that implements jsonrpc 2.0
:args: Ordered list of params passed as arguments to rpc method
:kwargs: Dict of valid key, value pairs passed as arguments to rpc method
For usage refer the respective connection plugin docs.
"""
reqid = str(uuid.uuid4())
req = {'jsonrpc': '2.0', 'method': name, 'id': reqid}
params = list(args) or kwargs or None
if params:
req['params'] = params
if not self._module._socket_path:
self._module.fail_json(msg='provider support not available for this host')
if not os.path.exists(self._module._socket_path):
self._module.fail_json(msg='provider socket does not exist, is the provider running?')
try:
data = self._module.jsonify(req)
rc, out, err = exec_command(self._module, data)
except socket.error:
exc = get_exception()
self._module.fail_json(msg='unable to connect to socket', err=str(exc))
try:
response = self._module.from_json(to_text(out, errors='<API key>'))
except ValueError as exc:
self._module.fail_json(msg=to_text(exc, errors='<API key>'))
if response['id'] != reqid:
self._module.fail_json(msg='invalid id received')
if 'error' in response:
msg = response['error'].get('data') or response['error']['message']
self._module.fail_json(msg=to_text(msg, errors='<API key>'))
return response['result'] |
<!doctype html>
<html><head>
<title>Square border</title>
<style>
div { width: 50px; height: 50px;
border: 10px solid black;
}
</style>
</head>
<body><div></div></body></html> |
// `var x` should not call the getter of an existing global property.
var hit = 0;
Object.defineProperty(this, "x", {
get: function () { return ++hit; },
configurable: true
});
eval("var x;");
assertEq(hit, 0);
// The declaration should not have redefined the global x, either.
assertEq(x, 1);
assertEq(x, 2);
reportCompare(0, 0); |
let cache = {};
export default {
getItem(key) {
var item = cache[key];
return item && JSON.parse(item);
},
setItem(key, val) {
cache[key] = JSON.stringify(val);
},
removeItem(key) {
delete cache[key];
},
keys() {
return Object.keys(cache);
},
}; |
from django import template
register = template.Library()
@register.filter()
def <API key>(user, course):
return course.<API key>(user) |
<?php
$mod_strings = array (
'LBL_ASSIGNED_TO_ID' => 'Id do Usuário Atribuído',
'<API key>' => 'Atribuído à',
'LBL_ID' => 'ID',
'LBL_DATE_ENTERED' => 'Data de Criação',
'LBL_DATE_MODIFIED' => 'Data de Modificação',
'LBL_MODIFIED' => 'Modificado por',
'LBL_MODIFIED_ID' => 'Modificado por Id',
'LBL_MODIFIED_NAME' => 'Modificado por Nome',
'LBL_CREATED' => 'Criado por',
'LBL_CREATED_ID' => 'Criado por Id',
'LBL_DESCRIPTION' => 'Descrição',
'LBL_DELETED' => 'Apagado',
'LBL_NAME' => 'Nome',
'LBL_CREATED_USER' => 'Criado pelo Usuário',
'LBL_MODIFIED_USER' => 'Modificado pelo Usuário',
'LBL_LIST_FORM_TITLE' => 'EditedTextBlocks List',
'LBL_MODULE_NAME' => 'EditedTextBlocks',
'LBL_MODULE_TITLE' => 'EditedTextBlocks',
'LNK_NEW_RECORD' => 'Criar EditedTextBlocks',
'LNK_LIST' => 'EditedTextBlocks',
'<API key>' => 'Procurar EditedTextBlocks',
'<API key>' => 'Histórico',
'<API key>' => 'Atividades',
'<API key>' => 'EditedTextBlocks',
'LBL_NEW_FORM_TITLE' => 'Novo EditedTextBlocks',
);
?> |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def <API key>(apps, schema_editor):
Instance = apps.get_model("treemap", "Instance")
instances = Instance.objects.filter(config__contains='\"terms\":')
for instance in instances:
terms = instance.config.terms
if (('Resource' and 'Resources' in terms
and not isinstance(terms['Resource'], dict))):
new_dict = {'singular': terms['Resource'],
'plural': terms['Resources']}
del terms['Resources']
terms['Resource'] = new_dict
instance.save()
def <API key>(apps, schema_editor):
Instance = apps.get_model("treemap", "Instance")
instances = Instance.objects.filter(config__contains='\"terms\":')
for instance in instances:
terms = instance.config.terms
if (('Resource' in terms
and isinstance(terms['Resource'], dict))):
terms['Resources'] = terms['Resource.plural']
terms['Resource'] = terms['Resource.singular']
instance.save()
class Migration(migrations.Migration):
dependencies = [
('treemap', '<API key>'),
]
operations = [
migrations.RunPython(<API key>, <API key>),
] |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>App `root` Tests</title>
</head>
<body>
<h1>App `root` Tests</h1>
<ul>
<li><a href="#/app/foo/">Foo</a></li>
<li><a href="#/app/bar/">Bar</a></li>
</ul>
<h2 id="page-title"></h2>
<script src="../../../../../build/yui/yui.js"></script>
<script>
YUI({filter: 'raw'}).use('app-base', function (Y) {
var app = new Y.App({
serverRouting: false
});
app.set('root', app._getPathRoot() + 'app/');
app.route('/foo/', function () {
Y.one('#page-title').set('text', 'Foo');
});
app.route('/bar/', function () {
Y.one('#page-title').set('text', 'Bar');
});
app.render().dispatch();
});
</script>
</body>
</html> |
#ifndef __CR_IMGSET_H__
#define __CR_IMGSET_H__
#include "image-desc.h"
#include "log.h"
#include "common/bug.h"
#include "image.h"
struct cr_imgset {
int fd_off;
int fd_nr;
struct cr_img **_imgs;
};
static inline struct cr_img *img_from_set(const struct cr_imgset *imgset, int type)
{
int idx;
idx = type - imgset->fd_off;
BUG_ON(idx > imgset->fd_nr);
return imgset->_imgs[idx];
}
extern struct cr_imgset *glob_imgset;
extern struct cr_fd_desc_tmpl imgset_template[CR_FD_MAX];
extern struct cr_imgset *cr_task_imgset_open(int pid, int mode);
extern struct cr_imgset *<API key>(int pid, int from, int to,
unsigned long flags);
#define cr_imgset_open(pid, type, flags) <API key>(pid, \
_CR_FD_##type##_FROM, _CR_FD_##type##_TO, flags)
extern struct cr_imgset *cr_glob_imgset_open(int mode);
extern void close_cr_imgset(struct cr_imgset **cr_imgset);
#endif /* __CR_IMGSET_H__ */ |
<html>
<head>
<script>
var subFrameDocument;
function test()
{
if (window.internals)
window.internals.settings.<API key>(false);
else
log("Could not lift restrictions on window.blur(), this part of the test will fail.\n")
if (window.testRunner) {
testRunner.dumpAsText();
testRunner.waitUntilDone();
} else {
/*
* Opening a separate window is only necessary for testing in Safari.
* In Safari, window.blur() only blurs the current window if there's another window to focus.
* In DumpRenderTree, it will just cause the window to lose focus regardless.
* The popup blocker needs to be off to pass this test in Safari.
*/
window.open("about:blank", "test");
window.focus();
}
subFrameDocument = document.getElementById('subFrame').contentDocument;
log("Focus the text field in the frame");
subFrameDocument.getElementById('two').focus();
checkFocus(true, true);
log("\nFocus the text field in the main document");
document.getElementById('one').focus();
checkFocus(true, false);
log("\nBlur the window");
window.blur();
checkFocus(false, false);
log("\nFocus the window again");
window.focus();
checkFocus(true, false);
setTimeout(doneHandler, 1);
}
function checkFocus(expectedMain, expectedSub)
{
var mainFocus = document.hasFocus();
var msg = "Main document.hasFocus() should be " + expectedMain;
if (mainFocus != expectedMain)
msg = msg + " : FAIL";
else
msg = msg + " : PASS";
log(msg);
var subFocus = subFrameDocument.hasFocus();
msg = "Sub-frame document.hasFocus() should be " + expectedSub;
if (subFocus != expectedSub)
msg = msg + " : FAIL";
else
msg = msg + " : PASS";
log(msg);
}
function doneHandler()
{
if (window.testRunner)
testRunner.notifyDone();
}
function log(msg)
{
document.getElementById("console").appendChild(document.createTextNode(msg + "\n"));
}
</script>
</head>
<body onload="test()">
<input id="one">
<iframe id="subFrame" src="resources/hasFocus-iframe.html"></iframe>
<br>
<pre id="console"></pre>
</body>
</html> |
#ifndef Pins_Arduino_h
#define Pins_Arduino_h
#include "../generic/common.h"
static const uint8_t SDA = 4;
static const uint8_t SCL = 5;
static const uint8_t LED_BUILTIN = 2;
static const uint8_t LED_BUILTIN_R = 2;
static const uint8_t LED_BUILTIN_G = 4;
static const uint8_t LED_BUILTIN_B = 5;
static const uint8_t BUILTIN_LED = 2;
static const uint8_t BUILTIN_LEDR = 2;
static const uint8_t BUILTIN_LEDG = 4;
static const uint8_t BUILTIN_LEDB = 5;
static const uint8_t BUILTIN_BUTTON = 0;
#endif /* Pins_Arduino_h */ |
<?php
/**
* @class pageWap
* @author NAVER (developers@xpressengine.com)
* @brief wap class page of the module
*/
class pageWap extends page
{
/**
* @brief wap procedure method
*
* Page module does not include the following items on the full content control and output from the mobile class
*/
function procWAP(&$oMobile)
{
if(!$this->grant->access) return $oMobile->setContent(lang('msg_not_permitted'));
// The contents of the widget chuchulham
$oWidgetController = getController('widget');
$content = $oWidgetController->transWidgetCode($this->module_info->content);
$oMobile->setContent($content);
}
}
/* End of file page.wap.php */
/* Location: ./modules/page/page.wap.php */ |
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
#include "AddSplitAction.h"
#include "FEProblem.h"
template<>
InputParameters validParams<AddSplitAction>()
{
InputParameters params = validParams<MooseObjectAction>();
params.addParam<std::string>("type", "Split", "Classname of the split object");
return params;
}
AddSplitAction::AddSplitAction(const std::string & name, InputParameters params) :
MooseObjectAction(name, params)
{
}
void
AddSplitAction::act()
{
_moose_object_pars.set<FEProblem*>("_fe_problem") = _problem;
_problem->getNonlinearSystem().addSplit(_type, getShortName(), _moose_object_pars);
} |
Imports <API key>.DataTypes.Blocks
Imports <API key>.Communication
Imports <API key>.DataTypes
Imports <API key>
Imports <API key>.Projectfiles
Imports <API key>.DataTypes.Blocks.Step7V5
Imports <API key>.DataTypes.Projectfolders.Step5
Imports <API key>.DataTypes.Blocks.Step5
Public Class Form1
Dim myConn As New PLCConnection("myVBExample")
Private Sub cmdShowConfig_Click(sender As System.Object, e As System.EventArgs) Handles cmdShowConfig.Click
'Configuration anzeigen
Configuration.ShowConfiguration("myVBExample", True)
'Config Objekt neu erzeugen (falls Config geändert wurde)
Dim myConn As New PLCConnection("myVBExample")
End Sub
Private Sub cmdReadMW100_Click(sender As System.Object, e As System.EventArgs) Handles cmdReadMW100.Click
myConn.Connect()
Dim val1 As New Communication.PLCTag("MW100")
val1.<API key> = TagDisplayDataType.Hexadecimal
myConn.ReadValue(val1)
MessageBox.Show(val1.ValueAsString)
End Sub
Private Sub cmdWriteMW100_Click(sender As System.Object, e As System.EventArgs) Handles cmdWriteMW100.Click
myConn.Connect()
Dim val1 As New Communication.PLCTag("MW100")
val1.Controlvalue = 44
myConn.WriteValue(val1)
End Sub
Private Sub cmdReadMulti_Click(sender As System.Object, e As System.EventArgs) Handles cmdReadMulti.Click
Dim lst As New List(Of PLCTag)
Dim val1 As New Communication.PLCTag("MW100")
Dim val2 As New Communication.PLCTag("AW100")
Dim val3 As New Communication.PLCTag("EW100")
Dim val4 As New Communication.PLCTag("DB3.DBW4")
val4.TagDataType = TagDataType.DateTime
Dim val5 As New Communication.PLCTag("DB5.DBD6")
val5.TagDataType = TagDataType.CharArray
val5.ArraySize = 20
lst.Add(val1)
lst.Add(val2)
lst.Add(val3)
lst.Add(val4)
lst.Add(val5)
myConn.Connect()
myConn.ReadValues(lst)
MessageBox.Show(val1.ValueAsString)
MessageBox.Show(val2.ValueAsString)
MessageBox.Show(val3.ValueAsString)
MessageBox.Show(val4.ValueAsString)
MessageBox.Show(val5.ValueAsString)
End Sub
Private Sub cmdStopPLC_Click(sender As System.Object, e As System.EventArgs) Handles cmdStopPLC.Click
myConn.Connect()
myConn.PLCStop()
End Sub
Private Sub cmdDiagPuffer_Click(sender As System.Object, e As System.EventArgs) Handles cmdDiagPuffer.Click
myConn.Connect()
Dim lst As List(Of <API key>.DataTypes.DiagnosticEntry)
lst = myConn.<API key>()
For Each entr In lst
MessageBox.Show(entr.ToString)
Next
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim searchValue As String
Dim db As String
Dim tag As PLCTag
Dim prj As Step7ProjectV5
Dim fld As Projectfolders.Step7V5.BlocksOfflineFolder
Dim blk As S7DataBlock
searchValue = "SymbolDB_1000.Modul1.Temp4.Value"
db = searchValue.Split(".")(0)
searchValue = searchValue.Substring(db.Length + 1)
prj = New Step7ProjectV5("C:\\Users\\Jochen Kühner\\Documents\\Step7 Projekte\\Offenau\\Offenau_.s7p", False)
fld = prj.<API key>(1)
For Each projectBlockInfo As S7ProjectBlockInfo In fld.readPlcBlocksList()
If Not projectBlockInfo.SymbolTabelEntry Is Nothing And projectBlockInfo.SymbolTabelEntry.Symbol = db Then
blk = fld.GetBlock(projectBlockInfo)
End If
Next
If Not blk Is Nothing Then
For Each s7DataRow As S7DataRow In s7DataRow.GetChildrowsAsList(blk.<API key>())
If s7DataRow.StructuredName = searchValue Then
tag = s7DataRow.PlcTag
End If
Next
End If
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim PRJ As Projectfiles.Step5Project
Dim fld As Step5BlocksFolder
Dim blk As S5dataBlock
PRJ = Projectfiles.Projects.LoadProject("D:\temp\_M13\M13@@@ST.S5D", False)
fld = PRJ.BlocksFolder
blk = fld.GetBlock("DB5")
End Sub
End Class |
#include "config.h"
#include "IFrameShimSupport.h"
#include "Element.h"
#include "Frame.h"
#include "FrameView.h"
#include "HTMLElement.h"
#include "<API key>.h"
#include "HTMLNames.h"
#include "RenderBox.h"
#include "RenderObject.h"
#include "Widget.h"
#include <wtf/HashSet.h>
// This file provides plugin-related utility functions for iframe shims and is shared by platforms that inherit
// from PluginView (e.g. Qt) and those that do not (e.g. Chromium).
namespace WebCore {
static void getObjectStack(const RenderObject* ro, Vector<const RenderObject*>* roStack)
{
roStack->clear();
while (ro) {
roStack->append(ro);
ro = ro->parent();
}
}
// Returns true if stack1 is at or above stack2
static bool iframeIsAbovePlugin(const Vector<const RenderObject*>& iframeZstack, const Vector<const RenderObject*>& pluginZstack)
{
for (size_t i = 0; i < iframeZstack.size() && i < pluginZstack.size(); i++) {
// The root is at the end of these stacks. We want to iterate
// root-downwards so we index backwards from the end.
const RenderObject* ro1 = iframeZstack[iframeZstack.size() - 1 - i];
const RenderObject* ro2 = pluginZstack[pluginZstack.size() - 1 - i];
if (ro1 != ro2) {
// When we find nodes in the stack that are not the same, then
// we've found the nodes just below the lowest comment ancestor.
// Determine which should be on top.
// See if z-index determines an order.
if (ro1->style() && ro2->style()) {
int z1 = ro1->style()->zIndex();
int z2 = ro2->style()->zIndex();
if (z1 > z2)
return true;
if (z1 < z2)
return false;
}
// If the plugin does not have an explicit z-index it stacks behind the iframe.
// This is for maintaining compatibility with IE.
if (ro2->style()->position() == StaticPosition) {
// The 0'th elements of these RenderObject arrays represent the plugin node and
// the iframe.
const RenderObject* pluginRenderObject = pluginZstack[0];
const RenderObject* iframeRenderObject = iframeZstack[0];
if (pluginRenderObject->style() && iframeRenderObject->style()) {
if (pluginRenderObject->style()->zIndex() > iframeRenderObject->style()->zIndex())
return false;
}
return true;
}
// Inspect the document order. Later order means higher stacking.
const RenderObject* parent = ro1->parent();
if (!parent)
return false;
ASSERT(parent == ro2->parent());
for (const RenderObject* ro = parent->firstChild(); ro; ro = ro->nextSibling()) {
if (ro == ro1)
return false;
if (ro == ro2)
return true;
}
ASSERT(false); // We should have seen ro1 and ro2 by now.
return false;
}
}
return true;
}
// Return a set of rectangles that should not be overdrawn by the
// plugin ("cutouts"). This helps implement the "iframe shim"
// technique of overlaying a windowed plugin with content from the
// page. In a nutshell, iframe elements should occlude plugins when
// they occur higher in the stacking order.
void getPluginOcclusions(Element* element, Widget* parentWidget, const IntRect& frameRect, Vector<IntRect>& occlusions)
{
RenderObject* pluginNode = element->renderer();
ASSERT(pluginNode);
if (!pluginNode->style())
return;
Vector<const RenderObject*> pluginZstack;
Vector<const RenderObject*> iframeZstack;
getObjectStack(pluginNode, &pluginZstack);
if (!parentWidget->isFrameView())
return;
FrameView* parentFrameView = static_cast<FrameView*>(parentWidget);
const HashSet<RefPtr<Widget> >* children = parentFrameView->children();
for (HashSet<RefPtr<Widget> >::const_iterator it = children->begin(); it != children->end(); ++it) {
// We only care about FrameView's because iframes show up as FrameViews.
if (!(*it)->isFrameView())
continue;
const FrameView* frameView = static_cast<const FrameView*>((*it).get());
// Check to make sure we can get both the element and the RenderObject
// for this FrameView, if we can't just move on to the next object.
if (!frameView->frame() || !frameView->frame()->ownerElement()
|| !frameView->frame()->ownerElement()->renderer())
continue;
HTMLElement* element = frameView->frame()->ownerElement();
RenderObject* iframeRenderer = element->renderer();
if (element->hasTagName(HTMLNames::iframeTag)
&& iframeRenderer-><API key>().intersects(frameRect)
&& (!iframeRenderer->style() || iframeRenderer->style()->visibility() == VISIBLE)) {
getObjectStack(iframeRenderer, &iframeZstack);
if (iframeIsAbovePlugin(iframeZstack, pluginZstack)) {
IntPoint point = roundedIntPoint(iframeRenderer->localToAbsolute());
RenderBox* rbox = toRenderBox(iframeRenderer);
IntSize size(rbox->width(), rbox->height());
occlusions.append(IntRect(point, size));
}
}
}
}
} // namespace WebCore |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using SonarAnalyzer.Common;
using SonarAnalyzer.Helpers;
namespace SonarAnalyzer.Rules.CSharp
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
[Rule(DiagnosticId)]
public class <API key> : <API key>
{
internal const string DiagnosticId = "S3427";
private const string MessageFormat =
"This method signature overlaps the one defined on line {0}{1}, the default parameter value {2}.";
private static readonly <API key> rule =
<API key>.GetDescriptor(DiagnosticId, MessageFormat, RspecStrings.ResourceManager);
protected sealed override <API key> Rule => rule;
private class <API key>
{
public IParameterSymbol ParameterToReportOn { get; set; }
public IMethodSymbol HidingMethod { get; set; }
public IMethodSymbol HiddenMethod { get; set; }
}
protected override void Initialize(<API key> context)
{
context.<API key>(
c =>
{
var methodSymbol = c.Symbol as IMethodSymbol;
if (methodSymbol == null ||
methodSymbol.<API key>() ||
!methodSymbol.Parameters.Any(p => p.IsOptional))
{
return;
}
var methods = methodSymbol.ContainingType.GetMembers(methodSymbol.Name)
.OfType<IMethodSymbol>();
var hidingInfos = new List<<API key>>();
var <API key> = methods
.Where(m => m.Parameters.Length < methodSymbol.Parameters.Length)
.Where(m => !m.Parameters.Any(p => p.IsParams));
foreach (var <API key> in <API key>
.Where(<API key> => <API key>(<API key>, methodSymbol))
.Where(<API key> => methodSymbol.Parameters[<API key>.Parameters.Length].IsOptional))
{
hidingInfos.Add(
new <API key>
{
ParameterToReportOn = methodSymbol.Parameters[<API key>.Parameters.Length],
HiddenMethod = methodSymbol,
HidingMethod = <API key>
});
}
foreach (var hidingInfo in hidingInfos)
{
var syntax = hidingInfo.ParameterToReportOn.<API key>.FirstOrDefault()?.GetSyntax();
if (syntax == null)
{
continue;
}
var hidingMethod = hidingInfo.HidingMethod;
if (hidingMethod.<API key> != null)
{
hidingMethod = hidingMethod.<API key>;
}
var hidingMethodSyntax = hidingMethod.<API key>.FirstOrDefault()?.GetSyntax();
if (hidingMethodSyntax == null)
{
continue;
}
var defaultCanBeUsed =
<API key>(hidingInfo) ||
!<API key>(hidingInfo);
var isOtherFile = syntax.SyntaxTree.FilePath != hidingMethodSyntax.SyntaxTree.FilePath;
c.<API key>(Diagnostic.Create(Rule, syntax.GetLocation(),
hidingMethodSyntax.GetLocation().GetLineSpan().StartLinePosition.Line + 1,
isOtherFile
? $" in file '{new FileInfo(hidingMethodSyntax.SyntaxTree.FilePath).Name}'"
: string.Empty,
defaultCanBeUsed
? "can only be used with named arguments"
: "can't be used"));
}
},
SymbolKind.Method);
}
private static bool <API key>(<API key> hidingInfo)
{
for (int i = 0; i < hidingInfo.HidingMethod.Parameters.Length; i++)
{
if (hidingInfo.HidingMethod.Parameters[i].Name !=
hidingInfo.HiddenMethod.Parameters[i].Name)
{
return false;
}
}
return true;
}
private static bool <API key>(<API key> hidingInfo)
{
return hidingInfo.HiddenMethod.Parameters.IndexOf(hidingInfo.ParameterToReportOn) <
hidingInfo.HiddenMethod.Parameters.Count() - 1;
}
private static bool <API key>(IMethodSymbol <API key>, IMethodSymbol method)
{
for (int i = 0; i < <API key>.Parameters.Length; i++)
{
if (!<API key>.Parameters[i].Type.Equals(method.Parameters[i].Type))
{
return false;
}
if (<API key>.Parameters[i].IsOptional != method.Parameters[i].IsOptional)
{
return false;
}
}
return true;
}
}
} |
package org.sonar.server.computation.qualityprofile;
import java.util.Date;
import org.junit.Test;
import org.sonar.api.utils.DateUtils;
import static org.assertj.core.api.Assertions.assertThat;
public class QualityProfileTest {
private static final String SOME_QP_KEY = "qpKey";
private static final String SOME_QP_NAME = "qpName";
private static final String SOME_LANGUAGE_KEY = "languageKey";
private static final Date SOME_DATE = DateUtils.<API key>("2010-05-18T15:50:45+0100");
private static final QualityProfile QUALITY_PROFILE = new QualityProfile(SOME_QP_KEY, SOME_QP_NAME, SOME_LANGUAGE_KEY, SOME_DATE);
@Test(expected = <API key>.class)
public void <API key>() {
new QualityProfile(null, SOME_QP_NAME, SOME_LANGUAGE_KEY, SOME_DATE);
}
@Test(expected = <API key>.class)
public void <API key>() {
new QualityProfile(SOME_QP_KEY, null, SOME_LANGUAGE_KEY, SOME_DATE);
}
@Test(expected = <API key>.class)
public void <API key>() {
new QualityProfile(SOME_QP_KEY, SOME_QP_NAME, null, SOME_DATE);
}
@Test(expected = <API key>.class)
public void <API key>() {
new QualityProfile(SOME_QP_KEY, SOME_QP_NAME, SOME_LANGUAGE_KEY, null);
}
@Test
public void verify_properties() {
assertThat(QUALITY_PROFILE.getQpKey()).isEqualTo(SOME_QP_KEY);
assertThat(QUALITY_PROFILE.getQpName()).isEqualTo(SOME_QP_NAME);
assertThat(QUALITY_PROFILE.getLanguageKey()).isEqualTo(SOME_LANGUAGE_KEY);
assertThat(QUALITY_PROFILE.getRulesUpdatedAt()).isEqualTo(SOME_DATE);
}
@Test
public void <API key>() {
assertThat(QUALITY_PROFILE.getRulesUpdatedAt()).isNotSameAs(SOME_DATE);
}
@Test
public void verify_equals() {
assertThat(QUALITY_PROFILE).isEqualTo(new QualityProfile(SOME_QP_KEY, SOME_QP_NAME, SOME_LANGUAGE_KEY, SOME_DATE));
assertThat(QUALITY_PROFILE).isEqualTo(QUALITY_PROFILE);
assertThat(QUALITY_PROFILE).isNotEqualTo(null);
}
@Test
public void verify_toString() {
assertThat(QUALITY_PROFILE.toString()).isEqualTo("QualityProfile{key=qpKey, name=qpName, language=languageKey, rulesUpdatedAt=1274194245000}");
}
} |
package org.alfresco.repo.imap;
/**
* @author Mike Shavnev
* @since 3.2
*/
public interface AlfrescoImapConst
{
/**
* @author Derek Hulley
* @since 3.2
*/
public static enum ImapViewMode
{
/**
* Defines {@link AlfrescoImapFolder} view mode as virtual mode. Used for IMAP Virtualised View.
* <p>
* In the virtual mode alfresco nodes of cm:content are shown regardless of whether they are IMAP messages.
* <p>
* A template is used to generate a "virtual" email message from a content item that is not an email message.
* <p>
* Only nodes from IMAP favourite sites are shown, non favourite sites are not shown.
*/
VIRTUAL,
/**
* Defines {@link AlfrescoImapFolder} view mode as mixed mode. Used for IMAP Mixed View.
* <p>
* In mixed mode both IMAP messages and Alfresco nodes of other types are shown.
* Only nodes from IMAP favourite sites are shown, non favourite sites are not shown.
*
*/
MIXED,
/**
* Defines {@link AlfrescoImapFolder} view mode as archive mode. Used for Email Archive View.
* <p>
* In archive mode only IMAP messages are shown. Alfresco nodes of other types are not shown.
* And no nodes within sites (favourite or otherwise) are shown.
*/
ARCHIVE
}
public static final char HIERARCHY_DELIMITER = '/';
public static final String NAMESPACE_PREFIX = "
public static final String USER_NAMESPACE = "#mail";
public static final String INBOX_NAME = "INBOX";
public static final String TRASH_NAME = "Trash";
public static final String <API key> = "Body.txt";
public static final String BODY_TEXT_HTML_NAME = "Body.html";
public static final String MESSAGE_PREFIX = "Message_";
public static final String EML_EXTENSION = ".eml";
// Separator for user enties in flag and subscribe properties
public static final String USER_SEPARATOR = ";";
// Default content model email message templates
public static final String <API key> = "/alfresco/templates/imap/<API key>.ftl";
public static final String <API key> = "/alfresco/templates/imap/<API key>.ftl";
public static final String <API key> = "/alfresco/templates/imap/<API key>.ftl";
public static final String <API key> = "/alfresco/templates/imap/<API key>.ftl";
public static final String <API key> = "emailbody";
public static final String <API key> = "org.alfresco.share.sites.imapFavourites";
// AlfrescoImapMessage constants
public static final String MIME_VERSION = "MIME-Version";
public static final String CONTENT_TYPE = "Content-Type";
public static final String <API key> = "<API key>";
public static final String MULTIPART_MIXED = "mixed";
public static final String CONTENT_ID = "Content-ID";
public static final String X_ALF_NODEREF_ID = "<API key>"; // The NodeRef id header
public static final String X_ALF_SERVER_UID = "<API key>"; // The unique identifier of Alfresco server
public static final String EIGHT_BIT_ENCODING = "8bit";
public static final String BASE_64_ENCODING = "base64";
public static final String UTF_8 = "UTF-8";
public static final String CHARSET_UTF8 = ";charset=utf-8";
} |
package org.bladerunnerjs.plugin.bundlers.xml;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.bladerunnerjs.api.Asset;
import org.bladerunnerjs.api.memoization.MemoizedFile;
import org.bladerunnerjs.api.model.exception.NamespaceException;
import org.bladerunnerjs.api.model.exception.<API key>;
import org.bladerunnerjs.api.model.exception.request.<API key>;
import org.bladerunnerjs.api.model.exception.request.<API key>;
public class XmlBundleWriter
{
private boolean outputContinuously = false;
private XmlBundlerConfig xmlBundlerConfig = null;
public XmlBundleWriter(XmlBundlerConfig xmlBundlerConfig)
{
this.xmlBundlerConfig = xmlBundlerConfig;
}
public void concatenateBundle(List<Asset> xmlAssets, final Writer writer) throws <API key> {
try {
writer.write("<bundle>\n");
for(Asset asset : xmlAssets){
try (Reader reader = asset.getReader()) { IOUtils.copy(reader, writer); }
}
writer.write("</bundle>");
} catch (IOException e) {
throw new <API key>( e);
}
};
public void writeBundle(List<Asset> xmlAssets, final Writer writer) throws <API key>, XMLStreamException, IOException {
Map<String, List<XmlSiblingReader>> resourceReaders = null;
try
{
resourceReaders = getResourceReaders(xmlAssets);
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
XMLStreamWriter xmlWriter = outputFactory.<API key>(writer);
writeBundleInternal(resourceReaders, xmlWriter);
}
catch (<API key> | XMLStreamException e) {
throw new <API key>(e, "Error while bundling XML assets '" );
}
finally
{
if (resourceReaders != null)
{
for(List<XmlSiblingReader> siblingReaders : resourceReaders.values())
{
for(XmlSiblingReader siblingReader : siblingReaders)
{
siblingReader.close();
}
}
}
}
}
private void writeBundleInternal(final Map<String, List<XmlSiblingReader>> resourceReaders, final XMLStreamWriter writer)
throws XMLStreamException, <API key>, <API key>, IOException
{
writer.setDefaultNamespace("http://schema.bladerunnerjs.org/xmlBundle");
writer.writeStartDocument();
writer.writeStartElement("bundle");
flush(writer);
for (Map.Entry<String, List<XmlSiblingReader>> readerSetEntry : resourceReaders.entrySet())
{
String resourceName = readerSetEntry.getKey();
List<XmlSiblingReader> readerSet = readerSetEntry.getValue();
writer.writeStartElement("resource");
writer.writeAttribute("name", resourceName);
flush(writer);
Map<String, XmlResourceConfig> configMap = xmlBundlerConfig.getConfigMap();
writeResource(readerSet, writer, configMap.get(resourceName));
<API key>(readerSet);
writer.writeEndElement();
flush(writer);
}
// end document
writer.writeEndElement();
writer.writeEndDocument();
writer.close();
}
/* returns a map of xml root elements to a list of xml sibling readers */
private Map<String, List<XmlSiblingReader>> getResourceReaders(List<Asset> xmlAssets) throws <API key>
{
Map<String, List<XmlSiblingReader>> resourceReaders = new LinkedHashMap<String, List<XmlSiblingReader>>();
System.setProperty("javax.xml.stream.XMLInputFactory", "com.sun.xml.stream.ZephyrParserFactory");
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
for (Asset xmlAsset : xmlAssets)
{
String assetName = xmlAsset.getAssetName();
if(assetName.equals("aliasDefinitions.xml") || assetName.equals("aliases.xml") ){
continue;
}
MemoizedFile document = xmlAsset.file();
try{
XmlSiblingReader siblingReader = new XmlSiblingReader(inputFactory, xmlAsset.getReader());
siblingReader.setAsset(xmlAsset);
siblingReader.setXmlDocument(document);
String rootElement = siblingReader.getElementName();
Map<String, XmlResourceConfig> configMap = xmlBundlerConfig.getConfigMap();
if (!configMap.containsKey(rootElement))
{
siblingReader.close();
throw new <API key>(document, "Document contains unsupported root element: '" + rootElement + "'");
}
else
{
if (!resourceReaders.containsKey(rootElement))
{
resourceReaders.put(rootElement, new ArrayList<XmlSiblingReader>());
}
List<XmlSiblingReader> readerSet = resourceReaders.get(rootElement);
readerSet.add(siblingReader);
}
}catch ( XMLStreamException | IOException e){
throw new <API key>(document, e);
}
}
return resourceReaders;
}
private void writeResource(List<XmlSiblingReader> readers, final XMLStreamWriter writer, final XmlResourceConfig resourceConfig)
throws XMLStreamException, <API key>, <API key>
{
String elementName;
do
{
elementName = getNextElement(readers, resourceConfig);
if (elementName != null)
{
if (resourceConfig.getMergeElements().containsKey(elementName))
{
mergeElements(readers, writer, resourceConfig, elementName);
}
else
{
writer.writeStartElement(elementName);
Map<String, String> <API key> = <API key>(readers, elementName);
if(!<API key>.isEmpty())
{
for(String ns : <API key>.keySet())
{
writer.writeNamespace(ns, <API key>.get(ns));
}
}
flush(writer);
List<XmlSiblingReader> childReaders = getChildReaders(readers, elementName);
writeResource(childReaders, writer, resourceConfig);
<API key>(childReaders);
<API key>(readers, elementName);
writer.writeEndElement();
flush(writer);
}
}
}
while (elementName != null);
}
private Map<String, String> <API key>(List<XmlSiblingReader> readers, String elementName)
{
Map<String, String> <API key> = new LinkedHashMap<String, String>();
for (XmlSiblingReader reader : readers)
{
String srcElementName = reader.getElementName();
if ((srcElementName != null) && (srcElementName.equals(elementName)))
{
for(int i = 0, l = reader.getNamespaceCount(); i < l; ++i)
{
<API key>.put(reader.getNamespacePrefix(i), reader.getNamespaceURI(i));
}
}
}
return <API key>;
}
private void <API key>(List<XmlSiblingReader> readers, String elementName) throws XMLStreamException, <API key>
{
for (XmlSiblingReader reader : readers)
{
if (reader.getElementName().equals(elementName))
{
reader.nextSibling();
}
}
}
private String getNextElement(final List<XmlSiblingReader> readers, final XmlResourceConfig resourceConfig) throws XMLStreamException, <API key>
{
Map<String, Boolean> availableElements = new LinkedHashMap<String, Boolean>();
String nextElement = null;
for (XmlSiblingReader reader : readers)
{
if ((reader.getElementName() != null) && (reader.hasNextSibling()))
{
availableElements.put(reader.getElementName(), Boolean.TRUE);
}
}
if (availableElements.size() > 0)
{
// if a merge element is available, then process that
Map<String, Boolean> mergeElements = resourceConfig.getMergeElements();
for (String availableElement : availableElements.keySet())
{
if (mergeElements.containsKey(availableElement))
{
nextElement = availableElement;
break;
}
}
// otherwise, this must be a template element
if (nextElement == null)
{
// try matching each of the template elements, one at time, until we find the first one that matches what one of the readers currently has
for (String templateElement : resourceConfig.getTemplateElements())
{
if (availableElements.containsKey(templateElement))
{
nextElement = templateElement;
break;
}
}
}
if (nextElement == null)
{
String errorMessage = "None of the available elements '" + StringUtils.join(availableElements.keySet(),
", ") + "' matched any of the expected elements '" + StringUtils.join(resourceConfig.getTemplateElements(), ", ") + "'";
throw new <API key>(errorMessage);
}
}
return nextElement;
}
private void mergeElements(final List<XmlSiblingReader> readers, XMLStreamWriter writer, final XmlResourceConfig resourceConfig, final String elementName)
throws <API key>
{
Map<String, File> processedIdentifers = new LinkedHashMap<String, File>();
String identifierAttribute = resourceConfig.<API key>(elementName);
for (XmlSiblingReader reader : readers)
{
try
{
while (processXMLElement(writer, processedIdentifers, identifierAttribute, reader));
}
catch (Exception e)
{
throw new <API key>(e, "Error while bundling asset ");
}
}
}
private boolean processXMLElement(XMLStreamWriter writer, Map<String, File> processedIdentifers, String identifierAttribute, XmlSiblingReader reader)
throws XMLStreamException, <API key>, <API key>
{
String identifier;
try {
identifier = getIdentifier(identifierAttribute, reader);
} catch (NamespaceException e) {
throw new <API key>(reader.getXmlDocument(), e);
}
if(identifier != null)
{
File <API key> = processedIdentifers.get(identifier);
if(<API key> != null )
{
return reader.skipToNextSibling();
}
processedIdentifers.put(identifier, reader.getXmlDocument());
}
<API key>.cloneElement(reader, writer, outputContinuously);
return reader.nextSibling();
}
/* Throws an exception if the identifer is not in the default XML namespace configured for this reader. */
private String getIdentifier(String identifierAttribute, XmlSiblingReader reader) throws NamespaceException
{
String identifier = reader.getAttributeValue(identifierAttribute);
try {
reader.<API key>(identifier);
}
catch(<API key> e) {
throw new NamespaceException("Require path exception while attempting to validate correctly namespaced identifier", e);
}
return identifier;
}
private void <API key>(final List<XmlSiblingReader> readers) throws XMLStreamException, <API key>
{
for (XmlSiblingReader reader : readers)
{
reader.nextSibling();
}
}
private List<XmlSiblingReader> getChildReaders(final List<XmlSiblingReader> readers, final String elementName) throws <API key>
{
List<XmlSiblingReader> childReaders = new ArrayList<XmlSiblingReader>();
for (XmlSiblingReader reader : readers)
{
try{
if (reader.getElementName().equals(elementName))
{
XmlSiblingReader childReader = reader.getChildReader();
if (childReader != null)
{
childReaders.add(childReader);
}
}
}catch(XMLStreamException | <API key> e){
throw new <API key>(reader.getXmlDocument(), e);
}
}
return childReaders;
}
private void <API key>(final List<XmlSiblingReader> readers) throws IOException
{
for (XmlSiblingReader reader : readers)
{
reader.close();
}
}
/**
* This method is only here to make debugging easier, and it's use is
* enabled within the unit tests
*
* @throws XMLStreamException
*/
private void flush(XMLStreamWriter writer) throws XMLStreamException
{
if (outputContinuously)
{
writer.flush();
}
}
public void outputContinuously()
{
outputContinuously = true;
}
} |
import org.sonar.api.batch.bootstrap.ProjectBuilder;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.bootstrap.ProjectReactor;
import org.sonar.api.config.Settings;
import java.io.File;
/**
* This plugin relates to projects/project-builder sample
*/
public final class CreateSubProjects extends ProjectBuilder {
private Settings settings;
public CreateSubProjects(ProjectReactor reactor, Settings settings) {
super(reactor);
// A real implementation should for example use the configuration
this.settings = settings;
}
@Override
protected void build(ProjectReactor reactor) {
if (!settings.getBoolean("sonar.<API key>")) {
return;
}
System.out.println("---> Creating sub-projects");
ProjectDefinition root = reactor.getRoot();
// add two modules
<API key>(root);
<API key>(root);
}
private ProjectDefinition <API key>(ProjectDefinition root) {
File baseDir = new File(root.getBaseDir(), "module_a");
ProjectDefinition subProject = ProjectDefinition.create();
subProject.setBaseDir(baseDir).setWorkDir(new File(baseDir, "target/.sonar"));
subProject.setKey("com.sonarsource.it.projects.batch:<API key>");
subProject.setVersion(root.getVersion());
subProject.setName("Module A");
subProject.setSourceDirs("src");
root.addSubProject(subProject);
return subProject;
}
private ProjectDefinition <API key>(ProjectDefinition root) {
File baseDir = new File(root.getBaseDir(), "module_b");
ProjectDefinition subProject = ProjectDefinition.create();
subProject.setBaseDir(baseDir).setWorkDir(new File(baseDir, "target/.sonar"));
subProject.setKey("com.sonarsource.it.projects.batch:<API key>");
subProject.setVersion(root.getVersion());
subProject.setName("Module B");
subProject.addSourceFiles("src/HelloB.java");
root.addSubProject(subProject);
return subProject;
}
} |
/**
* the DOM object
* @namespace
* @name cc.DOM
*/
cc.DOM = {};
/**
* @function
* @private
* @param node
*/
cc.DOM._addMethods = function (node) {
for (var funcs in cc.DOM.methods) {
node[funcs] = cc.DOM.methods[funcs];
}
// Redefine getter setter
cc.defineGetterSetter(node, "x", node.getPositionX, node.setPositionX);
cc.defineGetterSetter(node, "y", node.getPositionY, node.setPositionY);
cc.defineGetterSetter(node, "width", node._getWidth, node._setWidth);
cc.defineGetterSetter(node, "height", node._getHeight, node._setHeight);
cc.defineGetterSetter(node, "anchorX", node._getAnchorX, node._setAnchorX);
cc.defineGetterSetter(node, "anchorY", node._getAnchorY, node._setAnchorY);
cc.defineGetterSetter(node, "scale", node.getScale, node.setScale);
cc.defineGetterSetter(node, "scaleX", node.getScaleX, node.setScaleX);
cc.defineGetterSetter(node, "scaleY", node.getScaleY, node.getScaleY);
cc.defineGetterSetter(node, "rotation", node.getRotation, node.setRotation);
cc.defineGetterSetter(node, "skewX", node.getSkewX, node.setSkewX);
cc.defineGetterSetter(node, "skewY", node.getSkewY, node.setSkewY);
cc.defineGetterSetter(node, "visible", node.isVisible, node.setVisible);
cc.defineGetterSetter(node, "parent", node.getParent, node.setParent);
cc.defineGetterSetter(node, "opacity", node.getOpacity, node.setOpacity);
};
cc.DOM.methods = /** @lends cc.DOM# */{
/**
* Replace the set position of ccNode
* @param {cc.Point|Number} x
* @param {Number} y
*/
setPosition:function (x, y) {
if (y === undefined) {
this._position.x = x.x;
this._position.y = x.y;
} else {
this._position.x = x;
this._position.y = y;
}
this.setNodeDirty();
this.dom.translates(this._position.x, -this._position.y);
},
/**
* replace set Position Y of ccNode
* @param {Number} y
*/
setPositionY:function (y) {
this._position.y = y;
this.setNodeDirty();
this.dom.translates(this._position.x, -this._position.y);
},
/**
* replace set Position X of ccNode
* @param {Number} x
*/
setPositionX:function (x) {
this._position.x = x;
this.setNodeDirty();
this.dom.translates(this._position.x, -this._position.y);
},
/**
* replace set Scale of ccNode
* @param {object|Number} scale
* @param {Number} scaleY
*/
setScale:function (scale, scaleY) {
//save dirty region when before change
//this.<API key>(this.<API key>());
this._scaleX = scale;
this._scaleY = scaleY || scale;
//save dirty region when after changed
//this.<API key>(this.<API key>());
this.setNodeDirty();
this.dom.resize(this._scaleX, this._scaleY);
},
/**
* replace set Scale X of ccNode
* @param {Number} x
*/
setScaleX:function (x) {
this._scaleX = x;
this.setNodeDirty();
this.dom.resize(this._scaleX, this._scaleY);
},
/**
* replace set Scale Y of ccNode
* @param {Number} y
*/
setScaleY:function (y) {
this._scaleY = y;
this.setNodeDirty();
this.dom.resize(this._scaleX, this._scaleY);
},
/**
* replace set anchorpoint of ccNode
* @param {cc.Point|Number} point The anchor point of node or The anchor point.x of node.
* @param {Number} [y] The anchor point.y of node.
*/
setAnchorPoint:function (point, y) {
var cmd = this._renderCmd;
var locAnchorPoint = this._anchorPoint;
if (y === undefined) {
locAnchorPoint.x = point.x;
locAnchorPoint.y = point.y;
} else {
locAnchorPoint.x = point;
locAnchorPoint.y = y;
}
var locAPP = cmd.<API key>, locSize = this._contentSize;
locAPP.x = locSize.width * locAnchorPoint.x;
locAPP.y = locSize.height * locAnchorPoint.y;
this.dom.style[cc.$.pfx + 'TransformOrigin'] = '' + locAPP.x + 'px ' + -locAPP.y + 'px';
if (this.ignoreAnchor) {
this.dom.style.marginLeft = 0;
this.dom.style.marginBottom = 0;
} else {
this.dom.style.marginLeft = (this.isToggler) ? 0 : -locAPP.x + 'px';
this.dom.style.marginBottom = -locAPP.y + 'px';
}
this.setNodeDirty();
},
/**
* replace set anchorpoint x of ccNode
* @param {Number} x The anchor x of node.
*/
_setAnchorX:function (x) {
var locAnchorPoint = this._anchorPoint;
var cmd = this._renderCmd;
if (x === locAnchorPoint.x)
return;
locAnchorPoint.x = x;
var locAPP = cmd.<API key>, locSize = this._contentSize;
locAPP.x = locSize.width * locAnchorPoint.x;
this.dom.style[cc.$.pfx + 'TransformOrigin'] = '' + locAPP.x + 'px ' + -locAPP.y + 'px';
if (this.ignoreAnchor) {
this.dom.style.marginLeft = 0;
this.dom.style.marginBottom = 0;
} else {
this.dom.style.marginLeft = (this.isToggler) ? 0 : -locAPP.x + 'px';
}
this.setNodeDirty();
},
/**
* replace set anchorpoint y of ccNode
* @param {Number} y The anchor y of node.
*/
_setAnchorY:function (y) {
var locAnchorPoint = this._anchorPoint;
var cmd = this._renderCmd;
if (y === locAnchorPoint.y)
return;
locAnchorPoint.y = y;
var locAPP = cmd.<API key>, locSize = this._contentSize;
locAPP.y = locSize.height * locAnchorPoint.y;
this.dom.style[cc.$.pfx + 'TransformOrigin'] = '' + locAPP.x + 'px ' + -locAPP.y + 'px';
if (this.ignoreAnchor) {
this.dom.style.marginLeft = 0;
this.dom.style.marginBottom = 0;
} else {
this.dom.style.marginBottom = -locAPP.y + 'px';
}
this.setNodeDirty();
},
/**
* replace set ContentSize of ccNode
* @param {cc.Size|Number} size The untransformed size of the node or The untransformed size's width of the node.
* @param {Number} [height] The untransformed size's height of the node.
*/
setContentSize:function (size, height) {
var cmd = this._renderCmd;
var locContentSize = this._contentSize;
if (height === undefined) {
locContentSize.width = size.width;
locContentSize.height = size.height;
} else {
locContentSize.width = size;
locContentSize.height = height;
}
var locAPP = cmd.<API key>, locAnchorPoint = this._anchorPoint;
locAPP.x = locContentSize.width * locAnchorPoint.x;
locAPP.y = locContentSize.height * locAnchorPoint.y;
this.dom.width = locContentSize.width;
this.dom.height = locContentSize.height;
this.setAnchorPoint(this.getAnchorPoint());
if (this.canvas) {
this.canvas.width = locContentSize.width;
this.canvas.height = locContentSize.height;
}
this.setNodeDirty();
this.redraw();
},
/**
* replace set width of ccNode
* @param {Number} width The untransformed size's width of the node.
*/
_setWidth:function (width) {
var locContentSize = this._contentSize;
var cmd = this._renderCmd;
if (width === locContentSize.width)
return;
locContentSize.width = width;
var locAPP = cmd.<API key>, locAnchorPoint = this._anchorPoint;
locAPP.x = locContentSize.width * locAnchorPoint.x;
this.dom.width = locContentSize.width;
this.anchorX = locAnchorPoint.x;
if (this.canvas) {
this.canvas.width = locContentSize.width;
}
this.setNodeDirty();
this.redraw();
},
/**
* replace set height of ccNode
* @param {Number} height The untransformed size's height of the node.
*/
_setHeight:function (height) {
var locContentSize = this._contentSize;
var cmd = this._renderCmd;
if (height === locContentSize.height)
return;
locContentSize.height = height;
var locAPP = cmd.<API key>, locAnchorPoint = this._anchorPoint;
locAPP.y = locContentSize.height * locAnchorPoint.y;
this.dom.height = locContentSize.height;
this.anchorY = locAnchorPoint.y;
if (this.canvas) {
this.canvas.height = locContentSize.height;
}
this.setNodeDirty();
this.redraw();
},
/**
* replace set Rotation of ccNode
* @param {Number} newRotation
*/
setRotation:function (newRotation) {
if (this._rotation == newRotation)
return;
this._rotationX = this._rotationY = newRotation;
this.setNodeDirty();
this.dom.rotate(newRotation);
},
/**
* replace set SkewX of ccNode
* @param {Number} x
*/
setSkewX:function (x) {
this._skewX = x;
this.setNodeDirty();
this.dom.setSkew(this._skewX, this._skewY);
},
/**
* replace set SkewY of ccNode
* @param {Number} y
*/
setSkewY:function (y) {
this._skewY = y;
this.setNodeDirty();
this.dom.setSkew(this._skewX, this._skewY);
},
/**
* replace set Visible of ccNode
* @param {Boolean} x
*/
setVisible:function (x) {
this._visible = x;
this.setNodeDirty();
if (this.dom)
this.dom.style.display = (x) ? 'block' : 'none';
},
_setLocalZOrder:function (z) {
this._localZOrder = z
this.setNodeDirty();
if (this.dom)
this.dom.zIndex = z;
},
/**
* replace set Parent of ccNode
* @param {cc.Node} p
*/
setParent:function (p) {
this._parent = p;
if (p !== null) {
p.setAnchorPoint(p.getAnchorPoint());
this.setNodeDirty();
cc.DOM.parentDOM(this);
}
},
/**
* replace resume Schedule and actions of ccNode
*/
resume:function () {
this.getScheduler().resumeTarget(this);
this.getActionManager().resumeTarget(this);
cc.eventManager.resumeTarget(this);
//if dom does not have parent, but node has no parent and its running
if (this.dom && !this.dom.parentNode) {
if (!this.getParent()) {
if(this.dom.id == ""){
cc.DOM._createEGLViewDiv(this);
}else{
this.dom.appendTo(cc.container);
}
} else {
cc.DOM.parentDOM(this);
}
}
if (this.dom)
this.dom.style.visibility = "visible";
},
/**
* replace pause Schedule and Actions of ccNode
*/
pause:function () {
this.getScheduler().pauseTarget(this);
this.getActionManager().pauseTarget(this);
cc.eventManager.pauseTarget(this);
if (this.dom) {
this.dom.style.visibility = 'hidden';
}
},
/**
* replace clean up of ccNode
*/
cleanup:function () {
// actions
this.stopAllActions();
this.<API key>();
// timers
this.<API key>(this._children, cc.Node._stateCallbackType.cleanup);
if (this.dom) {
this.dom.remove();
}
},
/**
* replace remove from parent and clean up of ccNode
*/
<API key>:function () {
this.dom.remove();
},
setOpacity:function (o) {
this._opacity = o;
this.dom.style.opacity = o / 255;
},
/**
* refresh/updates the DOM element
*/
redraw:function () {
if (this.isSprite) {
var tmp = this._children;
this._children = [];
cc.Sprite.prototype.visit.call(this, this.ctx);
this._children = tmp;
}
else {
cc.Sprite.prototype.visit.call(this, this.ctx);
}
}
};
cc.DOM._resetEGLViewDiv = function(){
var div = cc.$("#EGLViewDiv");
if(div){
var view = cc.view;
var designSize = view.<API key>();
var viewPortRect = view.getViewPortRect();
var screenSize = view.getFrameSize();
var pixelRatio = view.getDevicePixelRatio();
var designSizeWidth = designSize.width, designSizeHeight = designSize.height;
if((designSize.width === 0) && (designSize.height === 0)){
designSizeWidth = screenSize.width;
designSizeHeight = screenSize.height;
}
var viewPortWidth = viewPortRect.width/pixelRatio;
if((viewPortRect.width === 0) && (viewPortRect.height === 0)){
viewPortWidth = screenSize.width;
}
div.style.position = 'absolute';
//x.dom.style.display='block';
div.style.width = designSizeWidth + "px";
div.style.maxHeight = designSizeHeight + "px";
div.style.margin = 0;
div.resize(view.getScaleX()/pixelRatio, view.getScaleY()/pixelRatio);
if (view.getResolutionPolicy() == view._rpNoBorder) {
div.style.left = (view.getFrameSize().width - designSizeWidth)/2 + "px";
div.style.bottom = (view.getFrameSize().height - designSizeHeight*view.getScaleY()/pixelRatio)/2 + "px";
}
else {
div.style.left = (designSizeWidth*view.getScaleX()/pixelRatio - designSizeWidth) / 2 + "px";
div.style.bottom = "0px";
}
}
};
/**
* @function
* @private
* @param x
* @return {Boolean}
*/
cc.DOM.parentDOM = function (x) {
var p = x.getParent();
//if has parent, parent need to have dom too
if (!p || !x.dom)
return false;
if (!p.dom) {
cc.DOM.placeHolder(p);
p.setParent = cc.DOM.methods.setParent;
}
//if parent have dom, attach self to parent
x.dom.appendTo(p.dom);
p.setAnchorPoint(p.getAnchorPoint());
if (p.getParent()) {
cc.DOM.parentDOM(p);
} else {
//parent has no more parent, if its running, then add it to the container
if (p.isRunning()) {
//find EGLView div
var eglViewDiv = cc.$("#EGLViewDiv");
if (eglViewDiv) {
p.dom.appendTo(eglViewDiv);
} else {
cc.DOM._createEGLViewDiv(p);
}
}
}
return true;
};
cc.DOM._createEGLViewDiv = function(p){
var div = cc.$("#EGLViewDiv");
if(!div){
div = cc.$new("div");
div.id = "EGLViewDiv";
}
var view = cc.view;
var designSize = view.<API key>();
var viewPortRect = view.getViewPortRect();
var screenSize = view.getFrameSize();
var pixelRatio = view.getDevicePixelRatio();
var designSizeWidth = designSize.width, designSizeHeight = designSize.height;
if ((designSize.width === 0) && (designSize.height === 0)) {
designSizeWidth = screenSize.width;
designSizeHeight = screenSize.height;
}
var viewPortWidth = viewPortRect.width/pixelRatio;
if ((viewPortRect.width === 0) && (viewPortRect.height === 0)) {
viewPortWidth = screenSize.width;
}
div.style.position = 'absolute';
//x.dom.style.display='block';
div.style.width = designSizeWidth + "px";
div.style.maxHeight = designSizeHeight + "px";
div.style.margin = 0;
div.resize(view.getScaleX()/pixelRatio, view.getScaleY()/pixelRatio);
if (view.getResolutionPolicy() == view._rpNoBorder) {
div.style.left = (screenSize.width - designSizeWidth)/2 + "px";
div.style.bottom = (screenSize.height - designSizeHeight*view.getScaleY()/pixelRatio)/2 + "px";
}
else {
div.style.left = (designSizeWidth*view.getScaleX()/pixelRatio - designSizeWidth) / 2 + "px";
div.style.bottom = "0px";
}
p.dom.appendTo(div);
div.appendTo(cc.container);
};
/**
* @function
* @private
* @param x
*/
cc.DOM.setTransform = function (x) {
if (x.ctx) {
x.ctx.translate(x.<API key>().x, x.<API key>().y);
if (x.isSprite) {
var tmp = x._children;
x._children = [];
cc.Sprite.prototype.visit.call(x);
x._children = tmp;
}
else {
cc.Sprite.prototype.visit.call(x);
}
}
if (x.dom) {
x.dom.position.x = x.getPositionX();
x.dom.position.y = -x.getPositionY();
x.dom.rotation = x.getRotation();
x.dom.scale = {x:x.getScaleX(), y:x.getScaleY()};
x.dom.skew = {x:x.getSkewX(), y:x.getSkewY()};
if (x.setAnchorPoint)
x.setAnchorPoint(x.getAnchorPoint());
x.dom.transforms();
}
};
/**
* @function
* @private
* @param x
*/
cc.DOM.forSprite = function (x) {
x.dom = cc.$new('div');
x.canvas = cc.$new('canvas');
var locContentSize = x.getContentSize();
x.canvas.width = locContentSize.width;
x.canvas.height = locContentSize.height;
x.dom.style.position = 'absolute';
x.dom.style.bottom = 0;
x.ctx = x.canvas.getContext('2d');
x.dom.appendChild(x.canvas);
if (x.getParent()) {
cc.DOM.parentDOM(x);
}
x.isSprite = true;
};
/**
* This creates divs for parent Nodes that are related to the current node
* @function
* @private
* @param x
*/
cc.DOM.placeHolder = function (x) {
//creating a placeholder dom to simulate other ccNode in the hierachy
x.dom = cc.$new('div');
x.placeholder = true;
x.dom.style.position = 'absolute';
x.dom.style.bottom = 0;
//x.dom.style.display='block';
x.dom.style.width = (x.getContentSize().width || cc.director.getWinSize().width) + "px";
x.dom.style.maxHeight = (x.getContentSize().height || cc.director.getWinSize().height) + "px";
x.dom.style.margin = 0;
cc.DOM.setTransform(x);
x.dom.transforms();
cc.DOM._addMethods(x);
//x.dom.style.border = 'red 1px dotted';
};
/**
* Converts cc.Sprite or cc.MenuItem to DOM elements <br/>
* It currently only supports cc.Sprite and cc.MenuItem
* @function
* @param {cc.Sprite|cc.MenuItem|Array} nodeObject
* @example
* // example
* cc.DOM.convert(Sprite1, Sprite2, Menuitem);
*
* var myDOMElements = [Sprite1, Sprite2, MenuItem];
* cc.DOM.convert(myDOMElements);
*/
cc.DOM.convert = function (nodeObject) {
//if passing by list, make it an array
if (arguments.length > 1) {
cc.DOM.convert(arguments);
return;
} else if (arguments.length == 1 && !arguments[0].length) {
cc.DOM.convert([arguments[0]]);
return;
}
var args = arguments[0];
for (var i = 0; i < args.length; i++) {
//first check if its sprite
if (args[i] instanceof cc.Sprite) {
// create a canvas
if (!args[i].dom)
cc.DOM.forSprite(args[i]);
} else {
cc.log('DOM converter only supports sprite and menuitems yet');
}
cc.DOM._addMethods(args[i]);
args[i].visit = function () {
};
args[i].transform = function () {
};
cc.DOM.setTransform(args[i]);
args[i].setVisible(args[i].isVisible());
}
}; |
// <API key>: Apache-2.0 WITH LLVM-exception
#ifndef LLVM_ANALYSIS_IDF_H
#define LLVM_ANALYSIS_IDF_H
#include "llvm/Support/CFGDiff.h"
#include "llvm/Support/<API key>.h"
namespace llvm {
class BasicBlock;
namespace IDFCalculatorDetail {
Specialization for BasicBlock for the optional use of GraphDiff.
template <bool IsPostDom> struct ChildrenGetterTy<BasicBlock, IsPostDom> {
using NodeRef = BasicBlock *;
using ChildrenTy = SmallVector<BasicBlock *, 8>;
ChildrenGetterTy() = default;
ChildrenGetterTy(const GraphDiff<BasicBlock *, IsPostDom> *GD) : GD(GD) {
assert(GD);
}
ChildrenTy get(const NodeRef &N);
const GraphDiff<BasicBlock *, IsPostDom> *GD = nullptr;
};
} // end of namespace IDFCalculatorDetail
template <bool IsPostDom>
class IDFCalculator final : public IDFCalculatorBase<BasicBlock, IsPostDom> {
public:
using IDFCalculatorBase =
typename llvm::IDFCalculatorBase<BasicBlock, IsPostDom>;
using ChildrenGetterTy = typename IDFCalculatorBase::ChildrenGetterTy;
IDFCalculator(DominatorTreeBase<BasicBlock, IsPostDom> &DT)
: IDFCalculatorBase(DT) {}
IDFCalculator(DominatorTreeBase<BasicBlock, IsPostDom> &DT,
const GraphDiff<BasicBlock *, IsPostDom> *GD)
: IDFCalculatorBase(DT, ChildrenGetterTy(GD)) {
assert(GD);
}
};
using <API key> = IDFCalculator<false>;
using <API key> = IDFCalculator<true>;
// Implementation.
namespace IDFCalculatorDetail {
template <bool IsPostDom>
typename ChildrenGetterTy<BasicBlock, IsPostDom>::ChildrenTy
ChildrenGetterTy<BasicBlock, IsPostDom>::get(const NodeRef &N) {
using OrderedNodeTy =
typename IDFCalculatorBase<BasicBlock, IsPostDom>::OrderedNodeTy;
if (!GD) {
auto Children = children<OrderedNodeTy>(N);
return {Children.begin(), Children.end()};
}
return GD->template getChildren<IsPostDom>(N);
}
} // end of namespace IDFCalculatorDetail
} // end of namespace llvm
#endif |
/*
* dithertest.c
*
* Input is 8 bpp grayscale
* Output file is PostScript, 2 bpp dithered
*/
#include "allheaders.h"
static const l_float32 FACTOR = 0.95;
static const l_float32 GAMMA = 1.0;
main(int argc,
char **argv)
{
char *filein, *fileout;
l_int32 w, h;
l_float32 scale;
FILE *fp;
PIX *pix, *pixs, *pixd;
PIXCMAP *cmap;
static char mainName[] = "dithertest";
if (argc != 3)
exit(ERROR_INT(" Syntax: dithertest filein fileout", mainName, 1));
filein = argv[1];
fileout = argv[2];
if ((pix = pixRead(filein)) == NULL)
exit(ERROR_INT("pix not made", mainName, 1));
if (pixGetDepth(pix) != 8)
exit(ERROR_INT("pix not 8 bpp", mainName, 1));
pixs = pixGammaTRC(NULL, pix, GAMMA, 0, 255);
startTimer();
pixd = pixDitherToBinary(pixs);
fprintf(stderr, " time for binarized dither = %7.3f sec\n", stopTimer());
pixDisplayWrite(pixd, 1);
pixDestroy(&pixd);
/* Dither to 2 bpp, with colormap */
startTimer();
pixd = pixDitherTo2bpp(pixs, 1);
fprintf(stderr, " time for dither = %7.3f sec\n", stopTimer());
pixDisplayWrite(pixd, 1);
cmap = pixGetColormap(pixd);
pixcmapWriteStream(stderr, cmap);
pixDestroy(&pixd);
/* Dither to 2 bpp, without colormap */
startTimer();
pixd = pixDitherTo2bpp(pixs, 0);
fprintf(stderr, " time for dither = %7.3f sec\n", stopTimer());
pixDisplayWrite(pixd, 1);
pixDestroy(&pixd);
/* Dither to 2 bpp, without colormap; output in PostScript */
pixd = pixDitherTo2bpp(pixs, 0);
w = pixGetWidth(pixs);
h = pixGetHeight(pixs);
scale = L_MIN(FACTOR * 2550 / w, FACTOR * 3300 / h);
fp = lept_fopen(fileout, "wb+");
pixWriteStreamPS(fp, pixd, NULL, 300, scale);
lept_fclose(fp);
pixDestroy(&pixd);
/* Dither 2x upscale to 1 bpp */
startTimer();
pixd = <API key>(pixs);
fprintf(stderr, " time for scale/dither = %7.3f sec\n", stopTimer());
pixDisplayWrite(pixd, 1);
pixDestroy(&pixd);
/* Dither 4x upscale to 1 bpp */
startTimer();
pixd = <API key>(pixs);
fprintf(stderr, " time for scale/dither = %7.3f sec\n", stopTimer());
pixDisplayWrite(pixd, 1);
pixDestroy(&pixd);
pixDisplayMultiple("/tmp/junk_write_display*");
pixDestroy(&pix);
pixDestroy(&pixs);
return 0;
} |
package com.intellij.openapi.vcs.changes.committed;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.<API key>;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.changes.issueLinks.IssueLinkRenderer;
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;
import com.intellij.ui.<API key>;
import com.intellij.ui.<API key>;
import com.intellij.util.text.DateFormatUtil;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.plaf.TreeUI;
import javax.swing.plaf.basic.BasicTreeUI;
import javax.swing.tree.<API key>;
import java.awt.*;
import java.util.List;
import static com.intellij.util.text.DateFormatUtil.<API key>;
public class <API key> extends <API key> {
private final IssueLinkRenderer myRenderer;
private final List<? extends <API key>> myDecorators;
private final Project myProject;
private int myDateWidth;
private int myFontSize;
public <API key>(final Project project, final List<? extends <API key>> decorators) {
myProject = project;
myRenderer = new IssueLinkRenderer(project, this);
myDecorators = decorators;
myDateWidth = 0;
myFontSize = -1;
}
@NotNull
public static String <API key>(@NotNull String text) {
return text.replaceAll("\n", "
}
@Contract(pure = true)
public static @NotNull String truncateDescription(@NotNull String initDescription, @NotNull FontMetrics fontMetrics, int maxWidth) {
String description = initDescription;
int descWidth = fontMetrics.stringWidth(description);
while (description.length() > 0 && (descWidth > maxWidth)) {
description = trimLastWord(description);
descWidth = fontMetrics.stringWidth(description + " ");
}
return description;
}
@Override
public void <API key>(@NotNull JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
customize(tree, value, selected, expanded, leaf, row, hasFocus);
}
public void customize(JComponent tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
Object userObject = ((<API key>)value).getUserObject();
if (userObject instanceof CommittedChangeList) {
CommittedChangeList changeList = (CommittedChangeList)userObject;
renderChangeList(tree, changeList);
}
else if (userObject instanceof String) {
append((String)userObject, //NON-NLS See <API key>.buildTreeModel
<API key>.<API key>);
}
}
public void renderChangeList(JComponent tree, CommittedChangeList changeList) {
final Container parent = tree.getParent();
final int rowX = getRowX(myTree, 2);
int availableWidth = parent == null ? 100 : parent.getWidth() - rowX;
final FontMetrics fontMetrics = tree.getFontMetrics(tree.getFont());
final FontMetrics boldMetrics = tree.getFontMetrics(tree.getFont().deriveFont(Font.BOLD));
final FontMetrics italicMetrics = tree.getFontMetrics(tree.getFont().deriveFont(Font.ITALIC));
if (myDateWidth <= 0 || (fontMetrics.getFont().getSize() != myFontSize)) {
myDateWidth = Math.max(fontMetrics.stringWidth(", Yesterday 00:00 PM "), // NON-NLS
fontMetrics.stringWidth(", 00/00/00 00:00 PM ")); // NON-NLS
myDateWidth = Math.max(myDateWidth, fontMetrics.stringWidth(<API key>(DateFormatUtil.getSampleDateTime())));
myFontSize = fontMetrics.getFont().getSize();
}
int dateCommitterSize = myDateWidth + boldMetrics.stringWidth(changeList.getCommitterName());
String description = <API key>(changeList.getName().trim());
for (<API key> decorator : myDecorators) {
final Icon icon = decorator.decorate(changeList);
if (icon != null) {
setIcon(icon);
}
}
int descMaxWidth = availableWidth - dateCommitterSize - 8;
boolean partial = (changeList instanceof ReceivedChangeList) && ((ReceivedChangeList)changeList).isPartial();
int descWidth = 0;
int partialMarkerWidth = 0;
if (partial) {
final String partialMarker = VcsBundle.message("committed.changes.partial.list") + " ";
append(partialMarker, <API key>.<API key>);
partialMarkerWidth = boldMetrics.stringWidth(partialMarker);
descWidth += partialMarkerWidth;
}
descWidth += fontMetrics.stringWidth(description);
int numberWidth = 0;
final AbstractVcs vcs = changeList.getVcs();
if (vcs != null) {
final <API key> provider = vcs.<API key>();
if (provider != null && provider.getChangelistTitle() != null) {
String number = "#" + changeList.getNumber() + " ";
numberWidth = fontMetrics.stringWidth(number);
descWidth += numberWidth;
append(number, <API key>.GRAY_ATTRIBUTES);
}
}
int branchWidth = 0;
String branch = changeList.getBranch();
if (branch != null) {
branch += " ";
branchWidth = italicMetrics.stringWidth(branch);
descWidth += branchWidth;
append(branch, <API key>.<API key>);
}
if (description.isEmpty()) {
append(VcsBundle.message("committed.changes.empty.comment"), <API key>.GRAYED_ATTRIBUTES);
appendTextPadding(descMaxWidth);
}
else if (descMaxWidth < 0) {
myRenderer.appendTextWithLinks(description);
}
else if (descWidth < descMaxWidth) {
myRenderer.appendTextWithLinks(description);
appendTextPadding(descMaxWidth);
}
else {
final String moreMarker = VcsBundle.message("changes.browser.details.marker");
int moreWidth = fontMetrics.stringWidth(moreMarker);
int remainingWidth = descMaxWidth - moreWidth - numberWidth - branchWidth - partialMarkerWidth;
description = truncateDescription(description, fontMetrics, remainingWidth);
myRenderer.appendTextWithLinks(description);
if (!StringUtil.isEmpty(description)) {
append(" ", <API key>.REGULAR_ATTRIBUTES);
append(moreMarker, <API key>.LINK_ATTRIBUTES, new <API key>.MoreLauncher(myProject, changeList));
} else if (remainingWidth > 0) {
append(moreMarker, <API key>.LINK_ATTRIBUTES, new <API key>.MoreLauncher(myProject, changeList));
}
// align value is for the latest added piece
appendTextPadding(descMaxWidth);
}
append(changeList.getCommitterName(), <API key>.<API key>);
if (changeList.getCommitDate() != null) {
append(", " + <API key>(changeList.getCommitDate()), <API key>.REGULAR_ATTRIBUTES);
}
}
private static String trimLastWord(final String description) {
int pos = description.trim().lastIndexOf(' ');
if (pos >= 0) {
return description.substring(0, pos).trim();
}
return description.substring(0, description.length()-1);
}
public static int getRowX(JTree tree, int depth) {
if (tree == null) return 0;
final TreeUI ui = tree.getUI();
if (ui instanceof BasicTreeUI) {
final BasicTreeUI treeUI = ((BasicTreeUI)ui);
return (treeUI.getLeftChildIndent() + treeUI.getRightChildIndent()) * depth;
}
final int leftIndent = UIUtil.<API key>();
final int rightIndent = UIUtil.<API key>();
return (leftIndent + rightIndent) * depth;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ISAAR.MSolve.PreProcessor.Interfaces;
using ISAAR.MSolve.Matrices.Interfaces;
using ISAAR.MSolve.Matrices;
namespace ISAAR.MSolve.PreProcessor.Materials
{
public class ElasticMaterial3D : <API key>
{
private readonly double[] strains = new double[6];
private readonly double[] stresses = new double[6];
private double[,] constitutiveMatrix = null;
public double YoungModulus { get; set; }
public double PoissonRatio { get; set; }
public double[] Coordinates { get; set; }
private double[,] <API key>()
{
double fE1 = YoungModulus / (double)(1 + PoissonRatio);
double fE2 = fE1 * PoissonRatio / (double)(1 - 2 * PoissonRatio);
double fE3 = fE1 + fE2;
double fE4 = fE1 * 0.5;
double[,] afE = new double[6, 6];
afE[0, 0] = fE3;
afE[0, 1] = fE2;
afE[0, 2] = fE2;
afE[1, 0] = fE2;
afE[1, 1] = fE3;
afE[1, 2] = fE2;
afE[2, 0] = fE2;
afE[2, 1] = fE2;
afE[2, 2] = fE3;
afE[3, 3] = fE4;
afE[4, 4] = fE4;
afE[5, 5] = fE4;
Vector<double> s = (new Matrix2D<double>(afE)) * (new Vector<double>(strains));
s.Data.CopyTo(stresses, 0);
return afE;
}
#region <API key> Members
public int ID
{
get { return 1; }
}
public bool Modified
{
get { return false; }
}
public void ResetModified()
{
}
#endregion
#region <API key> Members
public double[] Stresses { get { return stresses; } }
public IMatrix2D<double> ConstitutiveMatrix
{
get
{
if (constitutiveMatrix == null) UpdateMaterial(new double[6]);
return new Matrix2D<double>(constitutiveMatrix);
}
}
public void UpdateMaterial(double[] strains)
{
//throw new <API key>();
strains.CopyTo(this.strains, 0);
constitutiveMatrix = <API key>();
}
public void ClearState()
{
//throw new <API key>();
}
public void SaveState()
{
//throw new <API key>();
}
public void ClearStresses()
{
//throw new <API key>();
}
#endregion
#region ICloneable Members
public object Clone()
{
return new ElasticMaterial3D() { YoungModulus = this.YoungModulus, PoissonRatio = this.PoissonRatio };
}
#endregion
}
} |
package com.gemstone.gemfire.internal.cache;
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
import java.util.UUID;
import java.util.concurrent.atomic.<API key>;
import com.gemstone.gemfire.internal.cache.lru.EnableLRU;
import com.gemstone.gemfire.internal.cache.persistence.DiskRecoveryStore;
import com.gemstone.gemfire.internal.offheap.<API key>;
import com.gemstone.gemfire.internal.offheap.annotations.Released;
import com.gemstone.gemfire.internal.offheap.annotations.Retained;
import com.gemstone.gemfire.internal.offheap.annotations.Unretained;
import com.gemstone.gemfire.internal.util.concurrent.<API key>.HashEntry;
// macros whose definition changes this class:
// disk: DISK
// lru: LRU
// stats: STATS
// versioned: VERSIONED
// offheap: OFFHEAP
// One of the following key macros must be defined:
// key object: KEY_OBJECT
// key int: KEY_INT
// key long: KEY_LONG
// key uuid: KEY_UUID
// key string1: KEY_STRING1
// key string2: KEY_STRING2
/**
* Do not modify this class. It was generated.
* Instead modify LeafRegionEntry.cpp and then run
* bin/<API key>.sh from the directory
* that contains your build.xml.
*/
public class <API key> extends <API key> {
public <API key> (RegionEntryContext context, UUID key,
@Retained
Object value
) {
super(context,
(value instanceof RecoveredEntry ? null : value)
);
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
initialize(context, value);
this.keyMostSigBits = key.<API key>();
this.keyLeastSigBits = key.<API key>();
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// common code
protected int hash;
private HashEntry<Object, Object> next;
@SuppressWarnings("unused")
private volatile long lastModified;
private static final <API key><<API key>> lastModifiedUpdater
= <API key>.newUpdater(<API key>.class, "lastModified");
/**
* All access done using ohAddrUpdater so it is used even though the compiler can not tell it is.
*/
@SuppressWarnings("unused")
@Retained @Released private volatile long ohAddress;
/**
* I needed to add this because I wanted clear to call setValue which normally can only be called while the re is synced.
* But if I sync in that code it causes a lock ordering deadlock with the disk regions because they also get a rw lock in clear.
* Some hardware platforms do not support CAS on a long. If gemfire is run on one of those the <API key> does a sync
* on the re and we will once again be deadlocked.
* I don't know if we support any of the hardware platforms that do not have a 64bit CAS. If we do then we can expect deadlocks
* on disk regions.
*/
private final static <API key><<API key>> ohAddrUpdater = <API key>.newUpdater(<API key>.class, "ohAddress");
@Override
public Token getValueAsToken() {
return <API key>.getValueAsToken(this);
}
@Override
protected Object getValueField() {
return <API key>._getValue(this);
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
@Override
@Unretained
protected void setValueField(@Unretained Object v) {
<API key>.setValue(this, v);
}
@Override
@Retained
public Object _getValueRetain(RegionEntryContext context, boolean decompress) {
return <API key>._getValueRetain(this, decompress, context);
}
@Override
public long getAddress() {
return ohAddrUpdater.get(this);
}
@Override
public boolean setAddress(long expectedAddr, long newAddr) {
return ohAddrUpdater.compareAndSet(this, expectedAddr, newAddr);
}
@Override
@Released
public void release() {
<API key>.releaseEntry(this);
}
@Override
public void returnToPool() {
// Deadcoded for now; never was working
// if (this instanceof <API key>) {
// factory.returnToPool((<API key>)this);
}
protected long <API key>() {
return lastModifiedUpdater.get(this);
}
protected boolean <API key>(long expectedValue, long newValue) {
return lastModifiedUpdater.compareAndSet(this, expectedValue, newValue);
}
/**
* @see HashEntry#getEntryHash()
*/
public final int getEntryHash() {
return this.hash;
}
protected void setEntryHash(int v) {
this.hash = v;
}
/**
* @see HashEntry#getNextEntry()
*/
public final HashEntry<Object, Object> getNextEntry() {
return this.next;
}
/**
* @see HashEntry#setNextEntry
*/
public final void setNextEntry(final HashEntry<Object, Object> n) {
this.next = n;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// disk code
protected void initialize(RegionEntryContext context, Object value) {
diskInitialize(context, value);
}
@Override
public int <API key>(EnableLRU capacityController) {
throw new <API key>("should never be called");
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
private void diskInitialize(RegionEntryContext context, Object value) {
DiskRecoveryStore drs = (DiskRecoveryStore)context;
DiskStoreImpl ds = drs.getDiskStore();
long maxOplogSize = ds.getMaxOplogSize();
//get appropriate instance of DiskId implementation based on maxOplogSize
this.id = DiskId.createDiskId(maxOplogSize, true/* is persistence */, ds.needsLinkedList());
Helper.initialize(this, drs, value);
}
/**
* DiskId
*
* @since 5.1
*/
protected DiskId id;//= new DiskId();
public DiskId getDiskId() {
return this.id;
}
@Override
void setDiskId(RegionEntry old) {
this.id = ((<API key>)old).getDiskId();
}
// // inlining DiskId
// // always have these fields
// /**
// * id consists of
// * most significant
// * 1 byte = users bits
// * 2-8 bytes = oplog id
// * least significant.
// *
// * The highest bit in the oplog id part is set to 1 if the oplog id
// * is negative.
// * @todo this field could be an int for an overflow only region
// */
// private long id;
// /**
// * Length of the bytes on disk.
// * This is always set. If the value is invalid then it will be set to 0.
// * The most significant bit is used by overflow to mark it as needing to be written.
// */
// protected int valueLength = 0;
// // have intOffset or longOffset
// // intOffset
// /**
// * The position in the oplog (the oplog offset) where this entry's value is
// * stored
// */
// private volatile int offsetInOplog;
// // longOffset
// /**
// * The position in the oplog (the oplog offset) where this entry's value is
// * stored
// */
// private volatile long offsetInOplog;
// // have overflowOnly or persistence
// // overflowOnly
// // no fields
// // persistent
// /** unique entry identifier * */
// private long keyId;
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// key code
private final long keyMostSigBits;
private final long keyLeastSigBits;
@Override
public final Object getKey() {
return new UUID(this.keyMostSigBits, this.keyLeastSigBits);
}
@Override
public boolean isKeyEqual(Object k) {
if (k instanceof UUID) {
UUID uuid = (UUID)k;
return uuid.<API key>() == this.keyLeastSigBits && uuid.<API key>() == this.keyMostSigBits;
}
return false;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
} |
#ifndef __ADC_CONFIG_H__
#define __ADC_CONFIG_H__
#include <rtthread.h>
#include <drivers/adc.h>
#ifdef __cplusplus
extern "C" {
#endif
#if defined(BSP_USING_ADC1) || defined(BSP_USING_ADC2) || defined(BSP_USING_ADC3)
#ifndef ADC1_CONFIG
#define ADC1_CONFIG \
{ \
.ADC_Handler = ADC1, \
.name = "adc1", \
}
#endif /* ADC1_CONFIG */
#ifndef ADC2_CONFIG
#define ADC2_CONFIG \
{ \
.ADC_Handler = ADC2, \
.name = "adc2", \
}
#endif /* ADC2_CONFIG */
#ifndef ADC3_CONFIG
#define ADC3_CONFIG \
{ \
.ADC_Handler = ADC3, \
.name = "adc3", \
}
#endif /* ADC3_CONFIG */
#endif
#ifdef __cplusplus
}
#endif
#endif /* __ADC_CONFIG_H__ */ |
package org.elasticsearch.systemd;
import org.elasticsearch.Build;
import org.elasticsearch.common.CheckedConsumer;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.hamcrest.OptionalMatchers;
import org.elasticsearch.threadpool.Scheduler;
import org.elasticsearch.threadpool.ThreadPool;
import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasToString;
import static org.hamcrest.Matchers.instanceOf;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class SystemdPluginTests extends ESTestCase {
private Build.Type <API key> = randomFrom(Build.Type.DEB, Build.Type.RPM);
private Build.Type <API key> =
<API key>(t -> t == Build.Type.DEB || t == Build.Type.RPM, () -> randomFrom(Build.Type.values()));
final Scheduler.Cancellable extender = mock(Scheduler.Cancellable.class);
final ThreadPool threadPool = mock(ThreadPool.class);
{
when(extender.cancel()).thenReturn(true);
when(threadPool.<API key>(any(Runnable.class), eq(TimeValue.timeValueSeconds(15)), eq(ThreadPool.Names.SAME)))
.thenReturn(extender);
}
public void testIsEnabled() {
final SystemdPlugin plugin = new SystemdPlugin(false, <API key>, Boolean.TRUE.toString());
plugin.createComponents(null, null, threadPool, null, null, null, null, null, null, null, null);
assertTrue(plugin.isEnabled());
assertNotNull(plugin.extender());
}
public void <API key>() {
final SystemdPlugin plugin = new SystemdPlugin(false, <API key>, Boolean.TRUE.toString());
plugin.createComponents(null, null, threadPool, null, null, null, null, null, null, null, null);
assertFalse(plugin.isEnabled());
assertNull(plugin.extender());
}
public void <API key>() {
final SystemdPlugin plugin = new SystemdPlugin(false, <API key>, null);
plugin.createComponents(null, null, threadPool, null, null, null, null, null, null, null, null);
assertFalse(plugin.isEnabled());
assertNull(plugin.extender());
}
public void <API key>() {
final SystemdPlugin plugin = new SystemdPlugin(false, <API key>, Boolean.FALSE.toString());
plugin.createComponents(null, null, threadPool, null, null, null, null, null, null, null, null);
assertFalse(plugin.isEnabled());
assertNull(plugin.extender());
}
public void testInvalid() {
final String esSDNotify = <API key>(
s -> Boolean.TRUE.toString().equals(s) || Boolean.FALSE.toString().equals(s),
() -> randomAlphaOfLength(4));
final RuntimeException e = expectThrows(RuntimeException.class,
() -> new SystemdPlugin(false, <API key>, esSDNotify));
assertThat(e, hasToString(containsString("ES_SD_NOTIFY set to unexpected value [" + esSDNotify + "]")));
}
public void <API key>() {
<API key>(
Boolean.TRUE.toString(),
randomIntBetween(0, Integer.MAX_VALUE),
(maybe, plugin) -> {
assertThat(maybe, OptionalMatchers.isEmpty());
verify(plugin.extender()).cancel();
});
}
public void <API key>() {
final int rc = randomIntBetween(Integer.MIN_VALUE, -1);
<API key>(
Boolean.TRUE.toString(),
rc,
(maybe, plugin) -> {
assertThat(maybe, OptionalMatchers.isPresent());
// noinspection <API key>
assertThat(maybe.get(), instanceOf(RuntimeException.class));
assertThat(maybe.get(), hasToString(containsString("sd_notify returned error [" + rc + "]")));
});
}
public void <API key>() {
<API key>(
Boolean.FALSE.toString(),
randomInt(),
(maybe, plugin) -> assertThat(maybe, OptionalMatchers.isEmpty()));
}
private void <API key>(
final String esSDNotify,
final int rc,
final BiConsumer<Optional<Exception>, SystemdPlugin> assertions) {
runTest(esSDNotify, rc, assertions, SystemdPlugin::onNodeStarted, "READY=1");
}
public void testCloseSuccess() {
runTestClose(
Boolean.TRUE.toString(),
randomIntBetween(1, Integer.MAX_VALUE),
(maybe, plugin) -> assertThat(maybe, OptionalMatchers.isEmpty()));
}
public void testCloseFailure() {
runTestClose(
Boolean.TRUE.toString(),
randomIntBetween(Integer.MIN_VALUE, -1),
(maybe, plugin) -> assertThat(maybe, OptionalMatchers.isEmpty()));
}
public void testCloseNotEnabled() {
runTestClose(
Boolean.FALSE.toString(),
randomInt(),
(maybe, plugin) -> assertThat(maybe, OptionalMatchers.isEmpty()));
}
private void runTestClose(
final String esSDNotify,
final int rc,
final BiConsumer<Optional<Exception>, SystemdPlugin> assertions) {
runTest(esSDNotify, rc, assertions, SystemdPlugin::close, "STOPPING=1");
}
private void runTest(
final String esSDNotify,
final int rc,
final BiConsumer<Optional<Exception>, SystemdPlugin> assertions,
final CheckedConsumer<SystemdPlugin, IOException> invocation,
final String expectedState) {
final AtomicBoolean invoked = new AtomicBoolean();
final AtomicInteger <API key> = new AtomicInteger();
final AtomicReference<String> invokedState = new AtomicReference<>();
final SystemdPlugin plugin = new SystemdPlugin(false, <API key>, esSDNotify) {
@Override
int sd_notify(final int unset_environment, final String state) {
invoked.set(true);
<API key>.set(unset_environment);
invokedState.set(state);
return rc;
}
};
plugin.createComponents(null, null, threadPool, null, null, null, null, null, null, null, null);
if (Boolean.TRUE.toString().equals(esSDNotify)) {
assertNotNull(plugin.extender());
} else {
assertNull(plugin.extender());
}
boolean success = false;
try {
invocation.accept(plugin);
success = true;
} catch (final Exception e) {
assertions.accept(Optional.of(e), plugin);
}
if (success) {
assertions.accept(Optional.empty(), plugin);
}
if (Boolean.TRUE.toString().equals(esSDNotify)) {
assertTrue(invoked.get());
assertThat(<API key>.get(), equalTo(0));
assertThat(invokedState.get(), equalTo(expectedState));
} else {
assertFalse(invoked.get());
}
}
} |
// . TODO: if i'm sending to 1 host in a specified group how do you know
// to switch adn try anoher host in the group? What if target host
// has to access disk ,etc...???
// . this class is used for performing multicasting through a UdpServer
// . the Multicast class is used to govern a multicast
// . each UdpSlot in the Multicast class corresponds to an ongoing transaction
// . takes up 24*4 = 96 bytes
// . TODO: have broadcast option for hosts in same network
// . TODO: watch out for director splitting the groups - it may
// change the groups we select
// . TODO: set individual host timeouts yourself based on their std.dev pings
#ifndef _MULTICAST_H_
#define _MULTICAST_H_
#include "Hostdb.h" // getGroup(), getTimes(), stampHost()
#include "UdpServer.h" // sendRequest()
#include "Loop.h" // <API key>()
//#include "Msg34.h"
#include "Threads.h" // MAX_NICENESS
#define MAX_HOSTS_PER_GROUP 10
class Multicast {
public:
Multicast ( ) ;
~Multicast ( ) ;
void constructor ( );
void destructor ( );
// . returns false and sets errno on error
// . returns true on success -- your callback will be called
// . check errno when your callback is called
// . we timeout the whole shebang after "totalTimeout" seconds
// . if "sendToWholeGroup" is true then this sends your msg to all
// hosts in the group with id "groupId"
// . if "sendToWholeGroup" is true we don't call callback until we
// got a non-error reply from each host in the group
// . it will keep re-sending errored replies every 1 second, forever
// . this is useful for safe-sending adds to databases
// . spider will reach max spiders and be stuck until
// . if "sendToWholeGroup" is false we try to get a reply as fast
// as possible from any of the hosts in the group "groupId"
// . callback will be called when a good reply is gotten or when all
// hosts in the group have failed to give us a good reply
// . generally, for querying for data make "sendToWholeGroup" false
// . generally, when adding data make "sendToWholeGroup" true
// . "totalTimeout" is for the whole multicast
// . "key" is used to pick a host in the group if sendToWholeGroup
// is false
// . Msg40 uses largest termId in winning group as the key to ensure
// that queries with the same largest termId go to the same machine
// . likewise, Msg37 uses it to get the term frequency consistently
// so it doesn't jitter
// . if you pass in a "replyBuf" we'll store the reply in there
// . if "doLoadBalancing" is true and sendToWholeGroup is false then
// we send a Msg34 request to all hosts in group "groupId" and ask
// them how much disk load thay have then we send to the best one.
// . if we sent a Msg34 to a host within the last couple of
// milliseconds or so, then Msg34 should use results from last time.
// When we send a Msg0 or Msg20 request we know the approximate
// amount that will be read from disk so we can add this to the
// Load of the handling host by calling Msg34::addLoad() so if we
// call Msg34::getLoad() again before that Msg0/Msg20 request was
// acknowledge, the added load will be included.
bool send ( char *msg ,
int32_t msgSize ,
uint8_t msgType ,
// does this Multicast own this "msg"? if so, it will
// free it when done with it.
bool ownMsg ,
// send this request to a host or hosts who have
// m_groupId equal to this
//uint32_t groupId ,
uint32_t shardNum ,
// should the request be sent to all hosts in the group
// "groupId", or just one host. Msg1 adds data to all
hosts in the group so it sets this to true.
bool sendToWholeShard, // Group,
// if "key" is not 0 then it is used to select
// a host in the group "groupId" to send to.
int32_t key ,
void *state , // callback state
void *state2 , // callback state
void (*callback)(void *state,void *state2),
int32_t totalTimeout , // usually 60 seconds
int32_t niceness = MAX_NICENESS ,
bool realTimeUdp = false ,
int32_t firstHostId = -1 ,// first host to try
char *replyBuf = NULL ,
int32_t replyBufMaxSize = 0 ,
bool freeReplyBuf = true ,
bool doDiskLoadBalancing = false ,
int32_t maxCacheAge = -1 , // no age limit
key_t cacheKey = 0 ,
char rdbId = 0 , // bogus rdbId
int32_t minRecSizes = -1 ,// unknown read size
bool sendToSelf = true ,// if we should.
bool retryForever = true ,// for pick & send
class Hostdb *hostdb = NULL ,
int32_t redirectTimeout = -1 ,
class Host *firstProxyHost = NULL );
// . get the reply from your NON groupSend
// . if *freeReply is true then you are responsible for freeing this
// reply now, otherwise, don't free it
char *getBestReply ( int32_t *replySize ,
int32_t *replyMaxSize,
bool *freeReply ,
bool steal = false);
// free all non-NULL ptrs in all UdpSlots, and free m_msg
void reset ( ) ;
// private:
void <API key> ( UdpSlot *slot );
// keep these public so C wrapper can call them
bool sendToHostLoop ( int32_t key, int32_t hostNumToTry, int32_t firstHostId );
bool sendToHost ( int32_t i );
int32_t pickBestHost2 ( uint32_t key , int32_t hostNumToTry ,
bool preferLocal );
int32_t pickBestHost ( uint32_t key , int32_t hostNumToTry ,
bool preferLocal );
int32_t pickRandomHost( ) ;
void gotReply1 ( UdpSlot *slot ) ;
void closeUpShop ( UdpSlot *slot ) ;
void sendToGroup ( ) ;
void gotReply2 ( UdpSlot *slot ) ;
// . stuff set directly by send() parameters
char *m_msg;
int32_t m_msgSize;
uint8_t m_msgType;
bool m_ownMsg;
int32_t m_numGroups;
//uint32_t m_groupId;
uint32_t m_shardNum;
bool m_sendToWholeGroup;
void *m_state;
void *m_state2;
void (* m_callback)( void *state , void *state2 );
int32_t m_timeoutPerHost; // in seconds
int32_t m_totalTimeout; // in seconds
class UdpSlot *m_slot;
// . m_slots[] is our list of concurrent transactions
// . we delete all the slots only after cast is done
int32_t m_startTime; // seconds since the epoch
// so Msg3a can time response
int64_t m_startTimeMS;
// # of replies we've received
int32_t m_numReplies;
// . the group we're sending to or picking from
// . up to MAX_HOSTS_PER_GROUP hosts
// . m_retired, m_slots, m_errnos correspond with these 1-1
Host *m_hostPtrs[16];
int32_t m_numHosts;
class Hostdb *m_hostdb;
// . hostIds that we've tried to send to but failed
// . pickBestHost() skips over these hostIds
char m_retired [MAX_HOSTS_PER_GROUP];
// we can have up to 8 hosts per group
UdpSlot *m_slots [MAX_HOSTS_PER_GROUP];
// did we have an errno with this slot?
int32_t m_errnos [MAX_HOSTS_PER_GROUP];
// transaction in progress?
char m_inProgress [MAX_HOSTS_PER_GROUP];
int64_t m_launchTime [MAX_HOSTS_PER_GROUP];
// steal this from the slot(s) we get
char *m_readBuf;
int32_t m_readBufSize;
int32_t m_readBufMaxSize;
// if caller passes in a reply buf then we reference it here
char *m_replyBuf;
int32_t m_replyBufSize;
int32_t m_replyBufMaxSize;
// we own it until caller calls getBestReply()
bool m_ownReadBuf;
// are we registered for a callback every 1 second
bool m_registeredSleep;
bool m_registeredSleep2;
int32_t m_niceness;
bool m_realtime;
// . last sending of the request to ONE host in a group (pick & send)
// . in milliseconds
int64_t m_lastLaunch;
Host *m_lastLaunchHost;
// how many launched requests are current outstanding
int32_t m_numLaunched;
// only free m_reply if this is true
bool m_freeReadBuf;
int32_t m_key;
// Msg34 stuff -- for disk load balancing
//Msg34 m_msg34;
//bool <API key>;
key_t m_cacheKey ;
int32_t m_maxCacheAge ;
char m_rdbId ;
int32_t m_minRecSizes ;
// Msg1 might be able to add data to our tree to save a net trans.
bool m_sendToSelf;
bool m_retryForever;
int32_t m_retryCount;
char m_sentToTwin;
bool m_callbackCalled;
int32_t m_redirectTimeout;
char m_inUse;
// for linked list of available Multicasts in Msg4.cpp
class Multicast *m_next;
// host we got reply from. used by Msg3a for timing.
Host *m_replyingHost;
// when the request was launched to the m_replyingHost
int64_t m_replyLaunchTime;
// used by XmlDoc.cpp for gbfacet: stuff
int32_t m_hack32;
int64_t m_hack64;
// more hack stuff used by PageInject.cpp
int32_t m_hackFileId;
int64_t m_hackFileOff;
class ImportState *m_importState;
// hacky crunk use by seo pipeline in xmldoc.cpp
//void *m_hackxd;
//void *m_hackHost;
//void *m_hackQPtr;
//int32_t m_hackPtrCursor;
//char <API key>;
};
#endif |
"""The tests for the device tracker component."""
# pylint: disable=protected-access
import asyncio
import json
import logging
import unittest
from unittest.mock import call, patch
from datetime import datetime, timedelta
import os
from homeassistant.components import zone
from homeassistant.core import callback, State
from homeassistant.setup import setup_component
from homeassistant.helpers import discovery
from homeassistant.loader import get_component
from homeassistant.util.async import <API key>
import homeassistant.util.dt as dt_util
from homeassistant.const import (
ATTR_ENTITY_ID, ATTR_ENTITY_PICTURE, ATTR_FRIENDLY_NAME, ATTR_HIDDEN,
STATE_HOME, STATE_NOT_HOME, CONF_PLATFORM, ATTR_ICON)
import homeassistant.components.device_tracker as device_tracker
from homeassistant.exceptions import HomeAssistantError
from homeassistant.remote import JSONEncoder
from tests.common import (
<API key>, fire_time_changed, <API key>,
patch_yaml_files, <API key>, mock_restore_cache, mock_coro)
from ...test_util.aiohttp import mock_aiohttp_client
TEST_PLATFORM = {device_tracker.DOMAIN: {CONF_PLATFORM: 'test'}}
_LOGGER = logging.getLogger(__name__)
class <API key>(unittest.TestCase):
"""Test the Device tracker."""
hass = None # HomeAssistant
yaml_devices = None # type: str
# pylint: disable=invalid-name
def setUp(self):
"""Setup things to be run when tests are started."""
self.hass = <API key>()
self.yaml_devices = self.hass.config.path(device_tracker.YAML_DEVICES)
# pylint: disable=invalid-name
def tearDown(self):
"""Stop everything that was started."""
if os.path.isfile(self.yaml_devices):
os.remove(self.yaml_devices)
self.hass.stop()
def test_is_on(self):
"""Test is_on method."""
entity_id = device_tracker.ENTITY_ID_FORMAT.format('test')
self.hass.states.set(entity_id, STATE_HOME)
self.assertTrue(device_tracker.is_on(self.hass, entity_id))
self.hass.states.set(entity_id, STATE_NOT_HOME)
self.assertFalse(device_tracker.is_on(self.hass, entity_id))
# pylint: disable=no-self-use
def <API key>(self):
"""Test when known devices contains invalid data."""
files = {'empty.yaml': '',
'nodict.yaml': '100',
'badkey.yaml': '@:\n name: Device',
'noname.yaml': 'my_device:\n',
'allok.yaml': 'My Device:\n name: Device',
'oneok.yaml': ('My Device!:\n name: Device\n'
'bad_device:\n nme: Device')}
args = {'hass': self.hass, 'consider_home': timedelta(seconds=60)}
with patch_yaml_files(files):
assert device_tracker.load_config('empty.yaml', **args) == []
assert device_tracker.load_config('nodict.yaml', **args) == []
assert device_tracker.load_config('noname.yaml', **args) == []
assert device_tracker.load_config('badkey.yaml', **args) == []
res = device_tracker.load_config('allok.yaml', **args)
assert len(res) == 1
assert res[0].name == 'Device'
assert res[0].dev_id == 'my_device'
res = device_tracker.load_config('oneok.yaml', **args)
assert len(res) == 1
assert res[0].name == 'Device'
assert res[0].dev_id == 'my_device'
def <API key>(self):
"""Test the rendering of the YAML configuration."""
dev_id = 'test'
device = device_tracker.Device(
self.hass, timedelta(seconds=180), True, dev_id,
'AB:CD:EF:GH:IJ', 'Test name', picture='http://test.picture',
hide_if_away=True, icon='mdi:kettle')
device_tracker.update_config(self.yaml_devices, dev_id, device)
with <API key>(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN,
TEST_PLATFORM)
config = device_tracker.load_config(self.yaml_devices, self.hass,
device.consider_home)[0]
self.assertEqual(device.dev_id, config.dev_id)
self.assertEqual(device.track, config.track)
self.assertEqual(device.mac, config.mac)
self.assertEqual(device.config_picture, config.config_picture)
self.assertEqual(device.away_hide, config.away_hide)
self.assertEqual(device.consider_home, config.consider_home)
self.assertEqual(device.vendor, config.vendor)
self.assertEqual(device.icon, config.icon)
# pylint: disable=invalid-name
@patch('homeassistant.components.device_tracker._LOGGER.warning')
def <API key>(self, mock_warning):
"""Test adding duplicate MACs or device IDs to DeviceTracker."""
devices = [
device_tracker.Device(self.hass, True, True, 'my_device', 'AB:01',
'My device', None, None, False),
device_tracker.Device(self.hass, True, True, 'your_device',
'AB:01', 'Your device', None, None, False)]
device_tracker.DeviceTracker(self.hass, False, True, devices)
_LOGGER.debug(mock_warning.call_args_list)
assert mock_warning.call_count == 1, \
"The only warning call should be duplicates (check DEBUG)"
args, _ = mock_warning.call_args
assert 'Duplicate device MAC' in args[0], \
'Duplicate MAC warning expected'
mock_warning.reset_mock()
devices = [
device_tracker.Device(self.hass, True, True, 'my_device',
'AB:01', 'My device', None, None, False),
device_tracker.Device(self.hass, True, True, 'my_device',
None, 'Your device', None, None, False)]
device_tracker.DeviceTracker(self.hass, False, True, devices)
_LOGGER.debug(mock_warning.call_args_list)
assert mock_warning.call_count == 1, \
"The only warning call should be duplicates (check DEBUG)"
args, _ = mock_warning.call_args
assert 'Duplicate device IDs' in args[0], \
'Duplicate device IDs warning expected'
def <API key>(self):
"""Test with no YAML file."""
with <API key>(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN,
TEST_PLATFORM)
# pylint: disable=invalid-name
def <API key>(self):
"""Test the adding of unknown devices to configuration file."""
scanner = get_component('device_tracker.test').SCANNER
scanner.reset()
scanner.come_home('DEV1')
with <API key>(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN, {
device_tracker.DOMAIN: {CONF_PLATFORM: 'test'}})
# wait for async calls (macvendor) to finish
self.hass.block_till_done()
config = device_tracker.load_config(self.yaml_devices, self.hass,
timedelta(seconds=0))
assert len(config) == 1
assert config[0].dev_id == 'dev1'
assert config[0].track
def test_gravatar(self):
"""Test the Gravatar generation."""
dev_id = 'test'
device = device_tracker.Device(
self.hass, timedelta(seconds=180), True, dev_id,
'AB:CD:EF:GH:IJ', 'Test name', gravatar='test@example.com')
gravatar_url = ("https:
"<API key>.jpg?s=80&d=wavatar")
self.assertEqual(device.config_picture, gravatar_url)
def <API key>(self):
"""Test that Gravatar overrides picture."""
dev_id = 'test'
device = device_tracker.Device(
self.hass, timedelta(seconds=180), True, dev_id,
'AB:CD:EF:GH:IJ', 'Test name', picture='http://test.picture',
gravatar='test@example.com')
gravatar_url = ("https:
"<API key>.jpg?s=80&d=wavatar")
self.assertEqual(device.config_picture, gravatar_url)
def <API key>(self):
"""Test if vendor string is lookup on macvendors API."""
mac = 'B8:27:EB:00:00:00'
vendor_string = 'Raspberry Pi Foundation'
device = device_tracker.Device(
self.hass, timedelta(seconds=180), True, 'test', mac, 'Test name')
with mock_aiohttp_client() as aioclient_mock:
aioclient_mock.get('http://api.macvendors.com/b8:27:eb',
text=vendor_string)
<API key>(device.set_vendor_for_mac(),
self.hass.loop).result()
assert aioclient_mock.call_count == 1
self.assertEqual(device.vendor, vendor_string)
def <API key>(self):
"""Verify all variations of MAC addresses are handled correctly."""
vendor_string = 'Raspberry Pi Foundation'
with mock_aiohttp_client() as aioclient_mock:
aioclient_mock.get('http://api.macvendors.com/b8:27:eb',
text=vendor_string)
aioclient_mock.get('http://api.macvendors.com/00:27:eb',
text=vendor_string)
mac = 'B8:27:EB:00:00:00'
device = device_tracker.Device(
self.hass, timedelta(seconds=180),
True, 'test', mac, 'Test name')
<API key>(device.set_vendor_for_mac(),
self.hass.loop).result()
self.assertEqual(device.vendor, vendor_string)
mac = '0:27:EB:00:00:00'
device = device_tracker.Device(
self.hass, timedelta(seconds=180),
True, 'test', mac, 'Test name')
<API key>(device.set_vendor_for_mac(),
self.hass.loop).result()
self.assertEqual(device.vendor, vendor_string)
mac = 'PREFIXED_B8:27:EB:00:00:00'
device = device_tracker.Device(
self.hass, timedelta(seconds=180),
True, 'test', mac, 'Test name')
<API key>(device.set_vendor_for_mac(),
self.hass.loop).result()
self.assertEqual(device.vendor, vendor_string)
def <API key>(self):
"""Prevent another mac vendor lookup if was not found first time."""
mac = 'B8:27:EB:00:00:00'
device = device_tracker.Device(
self.hass, timedelta(seconds=180), True, 'test', mac, 'Test name')
with mock_aiohttp_client() as aioclient_mock:
aioclient_mock.get('http://api.macvendors.com/b8:27:eb',
status=404)
<API key>(device.set_vendor_for_mac(),
self.hass.loop).result()
self.assertEqual(device.vendor, 'unknown')
def <API key>(self):
"""Prevent another lookup if failure during API call."""
mac = 'B8:27:EB:00:00:00'
device = device_tracker.Device(
self.hass, timedelta(seconds=180), True, 'test', mac, 'Test name')
with mock_aiohttp_client() as aioclient_mock:
aioclient_mock.get('http://api.macvendors.com/b8:27:eb',
status=500)
<API key>(device.set_vendor_for_mac(),
self.hass.loop).result()
self.assertEqual(device.vendor, 'unknown')
def <API key>(self):
"""Prevent another lookup if exception during API call."""
mac = 'B8:27:EB:00:00:00'
device = device_tracker.Device(
self.hass, timedelta(seconds=180), True, 'test', mac, 'Test name')
with mock_aiohttp_client() as aioclient_mock:
aioclient_mock.get('http://api.macvendors.com/b8:27:eb',
exc=asyncio.TimeoutError())
<API key>(device.set_vendor_for_mac(),
self.hass.loop).result()
self.assertEqual(device.vendor, 'unknown')
def <API key>(self):
"""Test if macvendor is looked up when device is seen."""
mac = 'B8:27:EB:00:00:00'
vendor_string = 'Raspberry Pi Foundation'
tracker = device_tracker.DeviceTracker(
self.hass, timedelta(seconds=60), 0, [])
with mock_aiohttp_client() as aioclient_mock:
aioclient_mock.get('http://api.macvendors.com/b8:27:eb',
text=vendor_string)
<API key>(
tracker.async_see(mac=mac), self.hass.loop).result()
assert aioclient_mock.call_count == 1, \
'No http request for macvendor made!'
self.assertEqual(tracker.devices['b827eb000000'].vendor, vendor_string)
def test_discovery(self):
"""Test discovery."""
scanner = get_component('device_tracker.test').SCANNER
with patch.dict(device_tracker.DISCOVERY_PLATFORMS, {'test': 'test'}):
with patch.object(scanner, 'scan_devices',
autospec=True) as mock_scan:
with <API key>(1, device_tracker.DOMAIN):
assert setup_component(
self.hass, device_tracker.DOMAIN, TEST_PLATFORM)
<API key>(self.hass, 'test', {})
self.assertTrue(mock_scan.called)
@patch(
'homeassistant.components.device_tracker.DeviceTracker.see')
@patch(
'homeassistant.components.device_tracker.demo.setup_scanner',
autospec=True)
def <API key>(self, <API key>, mock_see):
"""Test discovery of device_tracker demo platform."""
assert device_tracker.DOMAIN not in self.hass.config.components
discovery.load_platform(
self.hass, device_tracker.DOMAIN, 'demo', {'test_key': 'test_val'},
{})
self.hass.block_till_done()
assert device_tracker.DOMAIN in self.hass.config.components
assert <API key>.called
assert <API key>.call_args[0] == (
self.hass, {}, mock_see, {'test_key': 'test_val'})
def test_update_stale(self):
"""Test stalled update."""
scanner = get_component('device_tracker.test').SCANNER
scanner.reset()
scanner.come_home('DEV1')
register_time = datetime(2015, 9, 15, 23, tzinfo=dt_util.UTC)
scan_time = datetime(2015, 9, 15, 23, 1, tzinfo=dt_util.UTC)
with patch('homeassistant.components.device_tracker.dt_util.utcnow',
return_value=register_time):
with <API key>(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN, {
device_tracker.DOMAIN: {
CONF_PLATFORM: 'test',
device_tracker.CONF_CONSIDER_HOME: 59,
}})
self.assertEqual(STATE_HOME,
self.hass.states.get('device_tracker.dev1').state)
scanner.leave_home('DEV1')
with patch('homeassistant.components.device_tracker.dt_util.utcnow',
return_value=scan_time):
fire_time_changed(self.hass, scan_time)
self.hass.block_till_done()
self.assertEqual(STATE_NOT_HOME,
self.hass.states.get('device_tracker.dev1').state)
def <API key>(self):
"""Test the entity attributes."""
dev_id = 'test_entity'
entity_id = device_tracker.ENTITY_ID_FORMAT.format(dev_id)
friendly_name = 'Paulus'
picture = 'http://placehold.it/200x200'
icon = 'mdi:kettle'
device = device_tracker.Device(
self.hass, timedelta(seconds=180), True, dev_id, None,
friendly_name, picture, hide_if_away=True, icon=icon)
device_tracker.update_config(self.yaml_devices, dev_id, device)
with <API key>(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN,
TEST_PLATFORM)
attrs = self.hass.states.get(entity_id).attributes
self.assertEqual(friendly_name, attrs.get(ATTR_FRIENDLY_NAME))
self.assertEqual(icon, attrs.get(ATTR_ICON))
self.assertEqual(picture, attrs.get(ATTR_ENTITY_PICTURE))
def test_device_hidden(self):
"""Test hidden devices."""
dev_id = 'test_entity'
entity_id = device_tracker.ENTITY_ID_FORMAT.format(dev_id)
device = device_tracker.Device(
self.hass, timedelta(seconds=180), True, dev_id, None,
hide_if_away=True)
device_tracker.update_config(self.yaml_devices, dev_id, device)
scanner = get_component('device_tracker.test').SCANNER
scanner.reset()
with <API key>(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN,
TEST_PLATFORM)
self.assertTrue(self.hass.states.get(entity_id)
.attributes.get(ATTR_HIDDEN))
def <API key>(self):
"""Test grouping of devices."""
dev_id = 'test_entity'
entity_id = device_tracker.ENTITY_ID_FORMAT.format(dev_id)
device = device_tracker.Device(
self.hass, timedelta(seconds=180), True, dev_id, None,
hide_if_away=True)
device_tracker.update_config(self.yaml_devices, dev_id, device)
scanner = get_component('device_tracker.test').SCANNER
scanner.reset()
with <API key>(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN,
TEST_PLATFORM)
self.hass.block_till_done()
state = self.hass.states.get(device_tracker.<API key>)
self.assertIsNotNone(state)
self.assertEqual(STATE_NOT_HOME, state.state)
self.assertSequenceEqual((entity_id,),
state.attributes.get(ATTR_ENTITY_ID))
@patch('homeassistant.components.device_tracker.DeviceTracker.async_see')
def test_see_service(self, mock_see):
"""Test the see service with a unicode dev_id and NO MAC."""
with <API key>(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN,
TEST_PLATFORM)
params = {
'dev_id': 'some_device',
'host_name': 'example.com',
'location_name': 'Work',
'gps': [.3, .8],
'attributes': {
'test': 'test'
}
}
device_tracker.see(self.hass, **params)
self.hass.block_till_done()
assert mock_see.call_count == 1
self.assertEqual(mock_see.call_count, 1)
self.assertEqual(mock_see.call_args, call(**params))
mock_see.reset_mock()
params['dev_id'] += chr(233) # e' acute accent from icloud
device_tracker.see(self.hass, **params)
self.hass.block_till_done()
assert mock_see.call_count == 1
self.assertEqual(mock_see.call_count, 1)
self.assertEqual(mock_see.call_args, call(**params))
def <API key>(self):
"""Test that the device tracker will fire an event."""
with <API key>(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN,
TEST_PLATFORM)
test_events = []
@callback
def listener(event):
"""Helper method that will verify our event got called."""
test_events.append(event)
self.hass.bus.listen("<API key>", listener)
device_tracker.see(self.hass, 'mac_1', host_name='hello')
device_tracker.see(self.hass, 'mac_1', host_name='hello')
self.hass.block_till_done()
assert len(test_events) == 1
# Assert we can serialize the event
json.dumps(test_events[0].as_dict(), cls=JSONEncoder)
assert test_events[0].data == {
'entity_id': 'device_tracker.hello',
'host_name': 'hello',
}
# pylint: disable=invalid-name
def <API key>(self):
"""Test that the device tracker will not generate invalid YAML."""
with <API key>(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN,
TEST_PLATFORM)
device_tracker.see(self.hass, 'mac_1', host_name='hello')
device_tracker.see(self.hass, 'mac_2', host_name='hello')
self.hass.block_till_done()
config = device_tracker.load_config(self.yaml_devices, self.hass,
timedelta(seconds=0))
assert len(config) == 2
# pylint: disable=invalid-name
def <API key>(self):
"""Test that the device tracker will not allow invalid dev ids."""
with <API key>(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN,
TEST_PLATFORM)
device_tracker.see(self.hass, dev_id='hello-world')
config = device_tracker.load_config(self.yaml_devices, self.hass,
timedelta(seconds=0))
assert len(config) == 0
@patch('homeassistant.components.device_tracker.Device'
'.set_vendor_for_mac', return_value=mock_coro())
def test_see_state(self, mock_set_vendor):
"""Test device tracker see records state correctly."""
self.assertTrue(setup_component(self.hass, device_tracker.DOMAIN,
TEST_PLATFORM))
params = {
'mac': 'AA:BB:CC:DD:EE:FF',
'dev_id': 'some_device',
'host_name': 'example.com',
'location_name': 'Work',
'gps': [.3, .8],
'gps_accuracy': 1,
'battery': 100,
'attributes': {
'test': 'test',
'number': 1,
},
}
device_tracker.see(self.hass, **params)
self.hass.block_till_done()
config = device_tracker.load_config(self.yaml_devices, self.hass,
timedelta(seconds=0))
assert len(config) == 1
state = self.hass.states.get('device_tracker.examplecom')
attrs = state.attributes
self.assertEqual(state.state, 'Work')
self.assertEqual(state.object_id, 'examplecom')
self.assertEqual(state.name, 'example.com')
self.assertEqual(attrs['friendly_name'], 'example.com')
self.assertEqual(attrs['battery'], 100)
self.assertEqual(attrs['latitude'], 0.3)
self.assertEqual(attrs['longitude'], 0.8)
self.assertEqual(attrs['test'], 'test')
self.assertEqual(attrs['gps_accuracy'], 1)
self.assertEqual(attrs['source_type'], 'gps')
self.assertEqual(attrs['number'], 1)
def <API key>(self):
"""Test that the device tracker sets gps for passive trackers."""
register_time = datetime(2015, 9, 15, 23, tzinfo=dt_util.UTC)
scan_time = datetime(2015, 9, 15, 23, 1, tzinfo=dt_util.UTC)
with <API key>(1, zone.DOMAIN):
zone_info = {
'name': 'Home',
'latitude': 1,
'longitude': 2,
'radius': 250,
'passive': False
}
setup_component(self.hass, zone.DOMAIN, {
'zone': zone_info
})
scanner = get_component('device_tracker.test').SCANNER
scanner.reset()
scanner.come_home('dev1')
with patch('homeassistant.components.device_tracker.dt_util.utcnow',
return_value=register_time):
with <API key>(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN, {
device_tracker.DOMAIN: {
CONF_PLATFORM: 'test',
device_tracker.CONF_CONSIDER_HOME: 59,
}})
state = self.hass.states.get('device_tracker.dev1')
attrs = state.attributes
self.assertEqual(STATE_HOME, state.state)
self.assertEqual(state.object_id, 'dev1')
self.assertEqual(state.name, 'dev1')
self.assertEqual(attrs.get('friendly_name'), 'dev1')
self.assertEqual(attrs.get('latitude'), 1)
self.assertEqual(attrs.get('longitude'), 2)
self.assertEqual(attrs.get('gps_accuracy'), 0)
self.assertEqual(attrs.get('source_type'),
device_tracker.SOURCE_TYPE_ROUTER)
scanner.leave_home('dev1')
with patch('homeassistant.components.device_tracker.dt_util.utcnow',
return_value=scan_time):
fire_time_changed(self.hass, scan_time)
self.hass.block_till_done()
state = self.hass.states.get('device_tracker.dev1')
attrs = state.attributes
self.assertEqual(STATE_NOT_HOME, state.state)
self.assertEqual(state.object_id, 'dev1')
self.assertEqual(state.name, 'dev1')
self.assertEqual(attrs.get('friendly_name'), 'dev1')
self.assertEqual(attrs.get('latitude'), None)
self.assertEqual(attrs.get('longitude'), None)
self.assertEqual(attrs.get('gps_accuracy'), None)
self.assertEqual(attrs.get('source_type'),
device_tracker.SOURCE_TYPE_ROUTER)
@patch('homeassistant.components.device_tracker._LOGGER.warning')
def test_see_failures(self, mock_warning):
"""Test that the device tracker see failures."""
tracker = device_tracker.DeviceTracker(
self.hass, timedelta(seconds=60), 0, [])
# MAC is not a string (but added)
tracker.see(mac=567, host_name="Number MAC")
# No device id or MAC(not added)
with self.assertRaises(HomeAssistantError):
<API key>(
tracker.async_see(), self.hass.loop).result()
assert mock_warning.call_count == 0
# Ignore gps on invalid GPS (both added & warnings)
tracker.see(mac='mac_1_bad_gps', gps=1)
tracker.see(mac='mac_2_bad_gps', gps=[1])
tracker.see(mac='mac_3_bad_gps', gps='gps')
self.hass.block_till_done()
config = device_tracker.load_config(self.yaml_devices, self.hass,
timedelta(seconds=0))
assert mock_warning.call_count == 3
assert len(config) == 4
def test_config_failure(self):
"""Test that the device tracker see failures."""
with <API key>(0, device_tracker.DOMAIN):
setup_component(self.hass, device_tracker.DOMAIN,
{device_tracker.DOMAIN: {
device_tracker.CONF_CONSIDER_HOME: -1}})
def <API key>(self):
"""Test that picture and icon are set in initial see."""
tracker = device_tracker.DeviceTracker(
self.hass, timedelta(seconds=60), False, [])
tracker.see(dev_id=11, picture='pic_url', icon='mdi:icon')
self.hass.block_till_done()
config = device_tracker.load_config(self.yaml_devices, self.hass,
timedelta(seconds=0))
assert len(config) == 1
assert config[0].icon == 'mdi:icon'
assert config[0].entity_picture == 'pic_url'
@asyncio.coroutine
def <API key>(hass):
"""Test resoring state."""
attr = {
device_tracker.ATTR_LONGITUDE: 18,
device_tracker.ATTR_LATITUDE: -33,
device_tracker.ATTR_LATITUDE: -33,
device_tracker.ATTR_SOURCE_TYPE: 'gps',
device_tracker.ATTR_GPS_ACCURACY: 2,
device_tracker.ATTR_BATTERY: 100
}
mock_restore_cache(hass, [State('device_tracker.jk', 'home', attr)])
path = hass.config.path(device_tracker.YAML_DEVICES)
files = {
path: 'jk:\n name: JK Phone\n track: True',
}
with patch_yaml_files(files):
yield from device_tracker.async_setup(hass, {})
state = hass.states.get('device_tracker.jk')
assert state
assert state.state == 'home'
for key, val in attr.items():
atr = state.attributes.get(key)
assert atr == val, "{}={} expected: {}".format(key, atr, val)
@asyncio.coroutine
def test_bad_platform(hass):
"""Test bad platform."""
config = {
'device_tracker': [{
'platform': 'bad_platform'
}]
}
with <API key>(0, device_tracker.DOMAIN):
assert (yield from device_tracker.async_setup(hass, config)) |
$packageName = 'PandaFreeAntivirus'
$url = '{{DownloadUrl}}'
$pwd = "$(split-path -parent $MyInvocation.MyCommand.Definition)"
$au3 = Join-Path $pwd 'PandaFreeAntivirus.au3'
try {
$chocTempDir = Join-Path $env:TEMP "chocolatey"
$tempDir = Join-Path $chocTempDir "$packageName"
if (![System.IO.Directory]::Exists($tempDir)) {[System.IO.Directory]::CreateDirectory($tempDir)}
$tempFile = Join-Path $tempDir "$packageName.installer.exe"
<API key> "$packageName" "$tempFile" "$url"
Write-Host "Running AutoIt3 using `'$au3`'"
<API key> "/c AutoIt3.exe `"$au3`" `"$tempFile`"" 'cmd.exe'
<API key> "$packageName"
} catch {
<API key> "$packageName" "$($_.Exception.Message)"
throw
} |
package org.elasticsearch.client;
import org.apache.logging.log4j.message.<API key>;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.ActiveShardCount;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.client.ccr.CcrStatsRequest;
import org.elasticsearch.client.ccr.CcrStatsResponse;
import org.elasticsearch.client.ccr.<API key>;
import org.elasticsearch.client.ccr.FollowInfoRequest;
import org.elasticsearch.client.ccr.FollowInfoResponse;
import org.elasticsearch.client.ccr.FollowStatsRequest;
import org.elasticsearch.client.ccr.FollowStatsResponse;
import org.elasticsearch.client.ccr.<API key>;
import org.elasticsearch.client.ccr.<API key>;
import org.elasticsearch.client.ccr.<API key>;
import org.elasticsearch.client.ccr.IndicesFollowStats;
import org.elasticsearch.client.ccr.IndicesFollowStats.ShardFollowStats;
import org.elasticsearch.client.ccr.PauseFollowRequest;
import org.elasticsearch.client.ccr.<API key>;
import org.elasticsearch.client.ccr.PutFollowRequest;
import org.elasticsearch.client.ccr.PutFollowResponse;
import org.elasticsearch.client.ccr.ResumeFollowRequest;
import org.elasticsearch.client.ccr.UnfollowRequest;
import org.elasticsearch.client.core.<API key>;
import org.elasticsearch.client.core.BroadcastResponse;
import org.elasticsearch.client.indices.CloseIndexRequest;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.seqno.ReplicationTracker;
import org.elasticsearch.test.rest.yaml.ObjectPath;
import org.junit.Before;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
public class CCRIT extends <API key> {
@Before
public void <API key>() throws Exception {
<API key>("local_cluster");
}
public void testIndexFollowing() throws Exception {
CcrClient ccrClient = highLevelClient().ccr();
CreateIndexRequest createIndexRequest = new CreateIndexRequest("leader");
CreateIndexResponse response = highLevelClient().indices().create(createIndexRequest, RequestOptions.DEFAULT);
assertThat(response.isAcknowledged(), is(true));
PutFollowRequest putFollowRequest = new PutFollowRequest("local_cluster", "leader", "follower", ActiveShardCount.ONE);
putFollowRequest.setSettings(Settings.builder().put("index.number_of_replicas", 0L).build());
PutFollowResponse putFollowResponse = execute(putFollowRequest, ccrClient::putFollow, ccrClient::putFollowAsync);
assertThat(putFollowResponse.<API key>(), is(true));
assertThat(putFollowResponse.<API key>(), is(true));
assertThat(putFollowResponse.<API key>(), is(true));
IndexRequest indexRequest = new IndexRequest("leader")
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
.source("{}", XContentType.JSON);
highLevelClient().index(indexRequest, RequestOptions.DEFAULT);
SearchRequest leaderSearchRequest = new SearchRequest("leader");
SearchResponse <API key> = highLevelClient().search(leaderSearchRequest, RequestOptions.DEFAULT);
assertThat(<API key>.getHits().getTotalHits().value, equalTo(1L));
try {
assertBusy(() -> {
FollowInfoRequest followInfoRequest = new FollowInfoRequest("follower");
FollowInfoResponse followInfoResponse =
execute(followInfoRequest, ccrClient::getFollowInfo, ccrClient::getFollowInfoAsync);
assertThat(followInfoResponse.getInfos().size(), equalTo(1));
assertThat(followInfoResponse.getInfos().get(0).getFollowerIndex(), equalTo("follower"));
assertThat(followInfoResponse.getInfos().get(0).getLeaderIndex(), equalTo("leader"));
assertThat(followInfoResponse.getInfos().get(0).getRemoteCluster(), equalTo("local_cluster"));
assertThat(followInfoResponse.getInfos().get(0).getStatus(), equalTo(FollowInfoResponse.Status.ACTIVE));
FollowStatsRequest followStatsRequest = new FollowStatsRequest("follower");
FollowStatsResponse followStatsResponse =
execute(followStatsRequest, ccrClient::getFollowStats, ccrClient::getFollowStatsAsync);
List<ShardFollowStats> shardFollowStats = followStatsResponse.<API key>().getShardFollowStats("follower");
long <API key> = shardFollowStats.stream()
.mapToLong(ShardFollowStats::<API key>)
.max()
.getAsLong();
assertThat(<API key>, equalTo(0L));
SearchRequest <API key> = new SearchRequest("follower");
SearchResponse <API key> = highLevelClient().search(<API key>, RequestOptions.DEFAULT);
assertThat(<API key>.getHits().getTotalHits().value, equalTo(1L));
GetSettingsRequest <API key> = new GetSettingsRequest().indices("follower");
GetSettingsResponse <API key> =
highLevelClient().indices().getSettings(<API key>, RequestOptions.DEFAULT);
assertThat(
IndexMetadata.<API key>.get(<API key>.getIndexToSettings().get("follower")),
equalTo(0));
});
} catch (Exception e) {
IndicesFollowStats followStats = ccrClient.getCcrStats(new CcrStatsRequest(), RequestOptions.DEFAULT).<API key>();
for (Map.Entry<String, List<ShardFollowStats>> entry : followStats.getShardFollowStats().entrySet()) {
for (ShardFollowStats shardFollowStats : entry.getValue()) {
if (shardFollowStats.getFatalException() != null) {
logger.warn(new <API key>("fatal shard follow exception {}", shardFollowStats.getShardId()),
shardFollowStats.getFatalException());
}
}
}
}
PauseFollowRequest pauseFollowRequest = new PauseFollowRequest("follower");
<API key> pauseFollowResponse = execute(pauseFollowRequest, ccrClient::pauseFollow, ccrClient::pauseFollowAsync);
assertThat(pauseFollowResponse.isAcknowledged(), is(true));
highLevelClient().index(indexRequest, RequestOptions.DEFAULT);
ResumeFollowRequest resumeFollowRequest = new ResumeFollowRequest("follower");
<API key> <API key> = execute(resumeFollowRequest, ccrClient::resumeFollow, ccrClient::resumeFollowAsync);
assertThat(<API key>.isAcknowledged(), is(true));
assertBusy(() -> {
FollowStatsRequest followStatsRequest = new FollowStatsRequest("follower");
FollowStatsResponse followStatsResponse =
execute(followStatsRequest, ccrClient::getFollowStats, ccrClient::getFollowStatsAsync);
List<ShardFollowStats> shardFollowStats = followStatsResponse.<API key>().getShardFollowStats("follower");
long <API key> = shardFollowStats.stream()
.mapToLong(ShardFollowStats::<API key>)
.max()
.getAsLong();
assertThat(<API key>, equalTo(1L));
SearchRequest <API key> = new SearchRequest("follower");
SearchResponse <API key> = highLevelClient().search(<API key>, RequestOptions.DEFAULT);
assertThat(<API key>.getHits().getTotalHits().value, equalTo(2L));
});
// Need to pause prior to unfollowing it:
pauseFollowRequest = new PauseFollowRequest("follower");
pauseFollowResponse = execute(pauseFollowRequest, ccrClient::pauseFollow, ccrClient::pauseFollowAsync);
assertThat(pauseFollowResponse.isAcknowledged(), is(true));
assertBusy(() -> {
FollowInfoRequest followInfoRequest = new FollowInfoRequest("follower");
FollowInfoResponse followInfoResponse =
execute(followInfoRequest, ccrClient::getFollowInfo, ccrClient::getFollowInfoAsync);
assertThat(followInfoResponse.getInfos().size(), equalTo(1));
assertThat(followInfoResponse.getInfos().get(0).getFollowerIndex(), equalTo("follower"));
assertThat(followInfoResponse.getInfos().get(0).getLeaderIndex(), equalTo("leader"));
assertThat(followInfoResponse.getInfos().get(0).getRemoteCluster(), equalTo("local_cluster"));
assertThat(followInfoResponse.getInfos().get(0).getStatus(), equalTo(FollowInfoResponse.Status.PAUSED));
});
// Need to close index prior to unfollowing it:
CloseIndexRequest closeIndexRequest = new CloseIndexRequest("follower");
org.elasticsearch.action.support.master.<API key> closeIndexReponse =
highLevelClient().indices().close(closeIndexRequest, RequestOptions.DEFAULT);
assertThat(closeIndexReponse.isAcknowledged(), is(true));
UnfollowRequest unfollowRequest = new UnfollowRequest("follower");
<API key> unfollowResponse = execute(unfollowRequest, ccrClient::unfollow, ccrClient::unfollowAsync);
assertThat(unfollowResponse.isAcknowledged(), is(true));
}
public void testForgetFollower() throws IOException {
final CcrClient ccrClient = highLevelClient().ccr();
final CreateIndexRequest createIndexRequest = new CreateIndexRequest("leader");
final Map<String, String> settings = new HashMap<>(3);
final int numberOfShards = randomIntBetween(1, 2);
settings.put("index.number_of_replicas", "0");
settings.put("index.number_of_shards", Integer.toString(numberOfShards));
createIndexRequest.settings(settings);
final CreateIndexResponse response = highLevelClient().indices().create(createIndexRequest, RequestOptions.DEFAULT);
assertThat(response.isAcknowledged(), is(true));
final PutFollowRequest putFollowRequest = new PutFollowRequest("local_cluster", "leader", "follower", ActiveShardCount.ONE);
final PutFollowResponse putFollowResponse = execute(putFollowRequest, ccrClient::putFollow, ccrClient::putFollowAsync);
assertTrue(putFollowResponse.<API key>());
assertTrue(putFollowResponse.<API key>());
assertTrue(putFollowResponse.<API key>());
final String clusterName = highLevelClient().info(RequestOptions.DEFAULT).getClusterName();
final Request statsRequest = new Request("GET", "/follower/_stats");
final Response statsResponse = client().performRequest(statsRequest);
final ObjectPath statsObjectPath = ObjectPath.createFromResponse(statsResponse);
final String followerIndexUUID = statsObjectPath.evaluate("indices.follower.uuid");
final PauseFollowRequest pauseFollowRequest = new PauseFollowRequest("follower");
<API key> pauseFollowResponse = execute(pauseFollowRequest, ccrClient::pauseFollow, ccrClient::pauseFollowAsync);
assertTrue(pauseFollowResponse.isAcknowledged());
final <API key> <API key> =
new <API key>(clusterName, "follower", followerIndexUUID, "local_cluster", "leader");
final BroadcastResponse <API key> =
execute(<API key>, ccrClient::forgetFollower, ccrClient::forgetFollowerAsync);
assertThat(<API key>.shards().total(), equalTo(numberOfShards));
assertThat(<API key>.shards().successful(), equalTo(numberOfShards));
assertThat(<API key>.shards().skipped(), equalTo(0));
assertThat(<API key>.shards().failed(), equalTo(0));
assertThat(<API key>.shards().failures(), empty());
final Request <API key> = new Request("GET", "/leader/_stats");
<API key>.addParameter("level", "shards");
final Response <API key> = client().performRequest(<API key>);
final Map<?, ?> shardsStats = ObjectPath.createFromResponse(<API key>).evaluate("indices.leader.shards");
assertThat(shardsStats.keySet(), hasSize(numberOfShards));
for (int i = 0; i < numberOfShards; i++) {
final List<?> shardStats = (List<?>) shardsStats.get(Integer.toString(i));
assertThat(shardStats, hasSize(1));
final Map<?, ?> shardStatsAsMap = (Map<?, ?>) shardStats.get(0);
final Map<?, ?> <API key> = (Map<?, ?>) shardStatsAsMap.get("retention_leases");
final List<?> leases = (List<?>) <API key>.get("leases");
for (final Object lease : leases) {
assertThat(((Map<?, ?>) lease).get("source"), equalTo(ReplicationTracker.<API key>));
}
}
}
public void testAutoFollowing() throws Exception {
CcrClient ccrClient = highLevelClient().ccr();
<API key> <API key> =
new <API key>("pattern1", "local_cluster", Collections.singletonList("logs-*"));
<API key>.<API key>("copy-{{leader_index}}");
final int <API key> = randomIntBetween(0, 4);
final Settings <API key> =
Settings.builder().put("index.number_of_replicas", <API key>).build();
<API key>.setSettings(<API key>);
<API key> <API key> =
execute(<API key>, ccrClient::<API key>, ccrClient::<API key>);
assertThat(<API key>.isAcknowledged(), is(true));
CreateIndexRequest createIndexRequest = new CreateIndexRequest("logs-20200101");
CreateIndexResponse response = highLevelClient().indices().create(createIndexRequest, RequestOptions.DEFAULT);
assertThat(response.isAcknowledged(), is(true));
assertBusy(() -> {
CcrStatsRequest ccrStatsRequest = new CcrStatsRequest();
CcrStatsResponse ccrStatsResponse = execute(ccrStatsRequest, ccrClient::getCcrStats, ccrClient::getCcrStatsAsync);
assertThat(ccrStatsResponse.getAutoFollowStats().<API key>(), equalTo(1L));
assertThat(ccrStatsResponse.<API key>().getShardFollowStats("copy-logs-20200101"), notNullValue());
});
assertThat(indexExists("copy-logs-20200101"), is(true));
assertThat(
<API key>("copy-logs-20200101"),
hasEntry("index.number_of_replicas", Integer.toString(<API key>)));
<API key> <API key> =
randomBoolean() ? new <API key>("pattern1") : new <API key>();
<API key> <API key> =
execute(<API key>, ccrClient::<API key>, ccrClient::<API key>);
assertThat(<API key>.getPatterns().size(), equalTo(1));
<API key>.Pattern pattern = <API key>.getPatterns().get("pattern1");
assertThat(pattern, notNullValue());
assertThat(pattern.getRemoteCluster(), equalTo(<API key>.getRemoteCluster()));
assertThat(pattern.<API key>(), equalTo(<API key>.<API key>()));
assertThat(pattern.<API key>(), equalTo(<API key>.<API key>()));
assertThat(pattern.getSettings(), equalTo(<API key>));
// Cleanup:
final <API key> <API key> = new <API key>("pattern1");
<API key> <API key> =
execute(<API key>, ccrClient::<API key>, ccrClient::<API key>);
assertThat(<API key>.isAcknowledged(), is(true));
PauseFollowRequest pauseFollowRequest = new PauseFollowRequest("copy-logs-20200101");
<API key> pauseFollowResponse = ccrClient.pauseFollow(pauseFollowRequest, RequestOptions.DEFAULT);
assertThat(pauseFollowResponse.isAcknowledged(), is(true));
}
} |
#ifndef _CPSPTFQMR_H
#define _CPSPTFQMR_H
#ifdef __cplusplus /* wrapper to enable C++ usage */
extern "C" {
#endif
#include <cpodes/cpodes_spils.h>
#include <sundials/sundials_sptfqmr.h>
SUNDIALS_EXPORT int CPSptfqmr(void *cpode_mem, int pretype, int maxl);
#ifdef __cplusplus
}
#endif
#endif |
<?php
require_once('test_util.php');
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\MapField;
use Foo\TestMessage;
use Foo\TestMessage\Sub;
class MapFieldTest extends <API key> {
# Test int32 field.
public function testInt32() {
$arr = new MapField(GPBType::INT32, GPBType::INT32);
// Test integer argument.
$arr[MAX_INT32] = MAX_INT32;
$this->assertSame(MAX_INT32, $arr[MAX_INT32]);
$arr[MIN_INT32] = MIN_INT32;
$this->assertSame(MIN_INT32, $arr[MIN_INT32]);
$this->assertEquals(2, count($arr));
$this->assertTrue(isset($arr[MAX_INT32]));
$this->assertTrue(isset($arr[MIN_INT32]));
unset($arr[MAX_INT32]);
unset($arr[MIN_INT32]);
$this->assertEquals(0, count($arr));
// Test float argument.
$arr[1.9] = 1.9;
$arr[2.1] = 2.1;
$this->assertSame(1, $arr[1]);
$this->assertSame(2, $arr[2]);
$arr[MAX_INT32_FLOAT] = MAX_INT32_FLOAT;
$this->assertSame(MAX_INT32, $arr[MAX_INT32]);
$arr[MIN_INT32_FLOAT] = MIN_INT32_FLOAT;
$this->assertSame(MIN_INT32, $arr[MIN_INT32]);
$this->assertEquals(4, count($arr));
unset($arr[1.9]);
unset($arr[2.9]);
unset($arr[MAX_INT32_FLOAT]);
unset($arr[MIN_INT32_FLOAT]);
$this->assertEquals(0, count($arr));
// Test string argument.
$arr['2'] = '2';
$this->assertSame(2, $arr[2]);
$arr['3.1'] = '3.1';
$this->assertSame(3, $arr[3]);
$arr[MAX_INT32_STRING] = MAX_INT32_STRING;
$this->assertSame(MAX_INT32, $arr[MAX_INT32]);
$this->assertEquals(3, count($arr));
unset($arr['2']);
unset($arr['3.1']);
unset($arr[MAX_INT32_STRING]);
$this->assertEquals(0, count($arr));
// Test foreach.
$arr = new MapField(GPBType::INT32, GPBType::INT32);
for ($i = 0; $i < 3; $i++) {
$arr[$i] = $i;
}
$i = 0;
$arr_test = [];
foreach ($arr as $key => $val) {
$this->assertSame($key, $val);
$arr_test[] = $key;
$i++;
}
$this->assertTrue(isset($arr_test[0]));
$this->assertTrue(isset($arr_test[1]));
$this->assertTrue(isset($arr_test[2]));
$this->assertSame(3, $i);
}
# Test uint32 field.
public function testUint32() {
$arr = new MapField(GPBType::UINT32, GPBType::UINT32);
// Test integer argument.
$arr[MAX_UINT32] = MAX_UINT32;
$this->assertSame(-1, $arr[-1]);
$this->assertEquals(1, count($arr));
unset($arr[MAX_UINT32]);
$this->assertEquals(0, count($arr));
$arr[-1] = -1;
$this->assertSame(-1, $arr[-1]);
$arr[MIN_UINT32] = MIN_UINT32;
$this->assertSame(MIN_UINT32, $arr[MIN_UINT32]);
$this->assertEquals(2, count($arr));
unset($arr[-1]);
unset($arr[MIN_UINT32]);
$this->assertEquals(0, count($arr));
// Test float argument.
$arr[MAX_UINT32_FLOAT] = MAX_UINT32_FLOAT;
$this->assertSame(-1, $arr[-1]);
$this->assertEquals(1, count($arr));
unset($arr[MAX_UINT32_FLOAT]);
$this->assertEquals(0, count($arr));
$arr[3.1] = 3.1;
$this->assertSame(3, $arr[3]);
$arr[-1.0] = -1.0;
$this->assertSame(-1, $arr[-1]);
$arr[MIN_UINT32_FLOAT] = MIN_UINT32_FLOAT;
$this->assertSame(MIN_UINT32, $arr[MIN_UINT32]);
$this->assertEquals(3, count($arr));
unset($arr[3.1]);
unset($arr[-1.0]);
unset($arr[MIN_UINT32_FLOAT]);
$this->assertEquals(0, count($arr));
// Test string argument.
$arr[MAX_UINT32_STRING] = MAX_UINT32_STRING;
$this->assertSame(-1, $arr[-1]);
$this->assertEquals(1, count($arr));
unset($arr[MAX_UINT32_STRING]);
$this->assertEquals(0, count($arr));
$arr['7'] = '7';
$this->assertSame(7, $arr[7]);
$arr['3.1'] = '3.1';
$this->assertSame(3, $arr[3]);
$arr['-1.0'] = '-1.0';
$this->assertSame(-1, $arr[-1]);
$arr[MIN_UINT32_STRING] = MIN_UINT32_STRING;
$this->assertSame(MIN_UINT32, $arr[MIN_UINT32]);
$this->assertEquals(4, count($arr));
unset($arr['7']);
unset($arr['3.1']);
unset($arr['-1.0']);
unset($arr[MIN_UINT32_STRING]);
$this->assertEquals(0, count($arr));
}
# Test int64 field.
public function testInt64() {
$arr = new MapField(GPBType::INT64, GPBType::INT64);
// Test integer argument.
$arr[MAX_INT64] = MAX_INT64;
$arr[MIN_INT64] = MIN_INT64;
if (PHP_INT_SIZE == 4) {
$this->assertSame(MAX_INT64_STRING, $arr[MAX_INT64_STRING]);
$this->assertSame(MIN_INT64_STRING, $arr[MIN_INT64_STRING]);
} else {
$this->assertSame(MAX_INT64, $arr[MAX_INT64]);
$this->assertSame(MIN_INT64, $arr[MIN_INT64]);
}
$this->assertEquals(2, count($arr));
unset($arr[MAX_INT64]);
unset($arr[MIN_INT64]);
$this->assertEquals(0, count($arr));
// Test float argument.
$arr[1.1] = 1.1;
if (PHP_INT_SIZE == 4) {
$this->assertSame('1', $arr['1']);
} else {
$this->assertSame(1, $arr[1]);
}
$this->assertEquals(1, count($arr));
unset($arr[1.1]);
$this->assertEquals(0, count($arr));
// Test string argument.
$arr['2'] = '2';
$arr['3.1'] = '3.1';
$arr[MAX_INT64_STRING] = MAX_INT64_STRING;
$arr[MIN_INT64_STRING] = MIN_INT64_STRING;
if (PHP_INT_SIZE == 4) {
$this->assertSame('2', $arr['2']);
$this->assertSame('3', $arr['3']);
$this->assertSame(MAX_INT64_STRING, $arr[MAX_INT64_STRING]);
$this->assertSame(MIN_INT64_STRING, $arr[MIN_INT64_STRING]);
} else {
$this->assertSame(2, $arr[2]);
$this->assertSame(3, $arr[3]);
$this->assertSame(MAX_INT64, $arr[MAX_INT64]);
$this->assertSame(MIN_INT64, $arr[MIN_INT64]);
}
$this->assertEquals(4, count($arr));
unset($arr['2']);
unset($arr['3.1']);
unset($arr[MAX_INT64_STRING]);
unset($arr[MIN_INT64_STRING]);
$this->assertEquals(0, count($arr));
}
# Test uint64 field.
public function testUint64() {
$arr = new MapField(GPBType::UINT64, GPBType::UINT64);
// Test integer argument.
$arr[MAX_UINT64] = MAX_UINT64;
if (PHP_INT_SIZE == 4) {
$this->assertSame(MAX_UINT64_STRING, $arr[MAX_UINT64_STRING]);
} else {
$this->assertSame(MAX_UINT64, $arr[MAX_UINT64]);
}
$this->assertEquals(1, count($arr));
unset($arr[MAX_UINT64]);
$this->assertEquals(0, count($arr));
// Test float argument.
$arr[1.1] = 1.1;
if (PHP_INT_SIZE == 4) {
$this->assertSame('1', $arr['1']);
} else {
$this->assertSame(1, $arr[1]);
}
$this->assertEquals(1, count($arr));
unset($arr[1.1]);
$this->assertEquals(0, count($arr));
// Test string argument.
$arr['2'] = '2';
$arr['3.1'] = '3.1';
$arr[MAX_UINT64_STRING] = MAX_UINT64_STRING;
if (PHP_INT_SIZE == 4) {
$this->assertSame('2', $arr['2']);
$this->assertSame('3', $arr['3']);
$this->assertSame(MAX_UINT64_STRING, $arr[MAX_UINT64_STRING]);
} else {
$this->assertSame(2, $arr[2]);
$this->assertSame(3, $arr[3]);
$this->assertSame(MAX_UINT64, $arr[MAX_UINT64]);
}
$this->assertEquals(3, count($arr));
unset($arr['2']);
unset($arr['3.1']);
unset($arr[MAX_UINT64_STRING]);
$this->assertEquals(0, count($arr));
}
# Test float field.
public function testFloat() {
$arr = new MapField(GPBType::INT32, GPBType::FLOAT);
// Test set.
$arr[0] = 1;
$this->assertEquals(1.0, $arr[0], '', MAX_FLOAT_DIFF);
$arr[1] = 1.1;
$this->assertEquals(1.1, $arr[1], '', MAX_FLOAT_DIFF);
$arr[2] = '2';
$this->assertEquals(2.0, $arr[2], '', MAX_FLOAT_DIFF);
$arr[3] = '3.1';
$this->assertEquals(3.1, $arr[3], '', MAX_FLOAT_DIFF);
$this->assertEquals(4, count($arr));
}
# Test double field.
public function testDouble() {
$arr = new MapField(GPBType::INT32, GPBType::DOUBLE);
// Test set.
$arr[0] = 1;
$this->assertEquals(1.0, $arr[0], '', MAX_FLOAT_DIFF);
$arr[1] = 1.1;
$this->assertEquals(1.1, $arr[1], '', MAX_FLOAT_DIFF);
$arr[2] = '2';
$this->assertEquals(2.0, $arr[2], '', MAX_FLOAT_DIFF);
$arr[3] = '3.1';
$this->assertEquals(3.1, $arr[3], '', MAX_FLOAT_DIFF);
$this->assertEquals(4, count($arr));
}
# Test bool field.
public function testBool() {
$arr = new MapField(GPBType::BOOL, GPBType::BOOL);
// Test boolean.
$arr[True] = True;
$this->assertSame(True, $arr[True]);
$this->assertEquals(1, count($arr));
unset($arr[True]);
$this->assertEquals(0, count($arr));
$arr[False] = False;
$this->assertSame(False, $arr[False]);
$this->assertEquals(1, count($arr));
unset($arr[False]);
$this->assertEquals(0, count($arr));
// Test integer.
$arr[-1] = -1;
$this->assertSame(True, $arr[True]);
$this->assertEquals(1, count($arr));
unset($arr[-1]);
$this->assertEquals(0, count($arr));
$arr[0] = 0;
$this->assertSame(False, $arr[False]);
$this->assertEquals(1, count($arr));
unset($arr[0]);
$this->assertEquals(0, count($arr));
// Test float.
$arr[1.1] = 1.1;
$this->assertSame(True, $arr[True]);
$this->assertEquals(1, count($arr));
unset($arr[1.1]);
$this->assertEquals(0, count($arr));
$arr[0.0] = 0.0;
$this->assertSame(False, $arr[False]);
$this->assertEquals(1, count($arr));
unset($arr[0.0]);
$this->assertEquals(0, count($arr));
// Test string.
$arr['a'] = 'a';
$this->assertSame(True, $arr[True]);
$this->assertEquals(1, count($arr));
unset($arr['a']);
$this->assertEquals(0, count($arr));
$arr[''] = '';
$this->assertSame(False, $arr[False]);
$this->assertEquals(1, count($arr));
unset($arr['']);
$this->assertEquals(0, count($arr));
}
# Test string field.
public function testString() {
$arr = new MapField(GPBType::STRING, GPBType::STRING);
// Test set.
$arr['abc'] = 'abc';
$this->assertSame('abc', $arr['abc']);
$this->assertEquals(1, count($arr));
unset($arr['abc']);
$this->assertEquals(0, count($arr));
$arr[1] = 1;
$this->assertSame('1', $arr['1']);
$this->assertEquals(1, count($arr));
unset($arr[1]);
$this->assertEquals(0, count($arr));
$arr[1.1] = 1.1;
$this->assertSame('1.1', $arr['1.1']);
$this->assertEquals(1, count($arr));
unset($arr[1.1]);
$this->assertEquals(0, count($arr));
$arr[True] = True;
$this->assertSame('1', $arr['1']);
$this->assertEquals(1, count($arr));
unset($arr[True]);
$this->assertEquals(0, count($arr));
// Test foreach.
$arr = new MapField(GPBType::STRING, GPBType::STRING);
for ($i = 0; $i < 3; $i++) {
$arr[$i] = $i;
}
$i = 0;
$arr_test = [];
foreach ($arr as $key => $val) {
$this->assertSame($key, $val);
$arr_test[] = $key;
$i++;
}
$this->assertTrue(isset($arr_test['0']));
$this->assertTrue(isset($arr_test['1']));
$this->assertTrue(isset($arr_test['2']));
$this->assertSame(3, $i);
}
# Test message field.
public function testMessage() {
$arr = new MapField(GPBType::INT32,
GPBType::MESSAGE, Sub::class);
// Test append.
$sub_m = new Sub();
$sub_m->setA(1);
$arr[0] = $sub_m;
$this->assertSame(1, $arr[0]->getA());
$this->assertEquals(1, count($arr));
// Test foreach.
$arr = new MapField(GPBType::INT32,
GPBType::MESSAGE, Sub::class);
for ($i = 0; $i < 3; $i++) {
$arr[$i] = new Sub();;
$arr[$i]->setA($i);
}
$i = 0;
$key_test = [];
$value_test = [];
foreach ($arr as $key => $val) {
$key_test[] = $key;
$value_test[] = $val->getA();
$i++;
}
$this->assertTrue(isset($key_test['0']));
$this->assertTrue(isset($key_test['1']));
$this->assertTrue(isset($key_test['2']));
$this->assertTrue(isset($value_test['0']));
$this->assertTrue(isset($value_test['1']));
$this->assertTrue(isset($value_test['2']));
$this->assertSame(3, $i);
}
# Test memory leak
// TODO(teboring): Add it back.
// public function testCycleLeak()
// $arr = new MapField(GPBType::INT32,
// GPBType::MESSAGE, TestMessage::class);
// $arr[0] = new TestMessage;
// $arr[0]->SetMapRecursive($arr);
// // Clean up memory before test.
// gc_collect_cycles();
// $start = memory_get_usage();
// unset($arr);
// // Explicitly trigger garbage collection.
// gc_collect_cycles();
// $end = memory_get_usage();
// $this->assertLessThan($start, $end);
} |
//! moment.js locale configuration
//! locale : English (Canada) [en-ca]
import moment from '../moment';
export default moment.defineLocale('en-ca', {
months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
monthsShort : '<API key>'.split('_'),
weekdays : '<API key>'.split('_'),
weekdaysShort : '<API key>'.split('_'),
weekdaysMin : '<API key>'.split('_'),
longDateFormat : {
LT : 'h:mm A',
LTS : 'h:mm:ss A',
L : 'YYYY-MM-DD',
LL : 'MMMM D, YYYY',
LLL : 'MMMM D, YYYY h:mm A',
LLLL : 'dddd, MMMM D, YYYY h:mm A'
},
calendar : {
sameDay : '[Today at] LT',
nextDay : '[Tomorrow at] LT',
nextWeek : 'dddd [at] LT',
lastDay : '[Yesterday at] LT',
lastWeek : '[Last] dddd [at] LT',
sameElse : 'L'
},
relativeTime : {
future : 'in %s',
past : '%s ago',
s : 'a few seconds',
m : 'a minute',
mm : '%d minutes',
h : 'an hour',
hh : '%d hours',
d : 'a day',
dd : '%d days',
M : 'a month',
MM : '%d months',
y : 'a year',
yy : '%d years'
},
<API key>: /\d{1,2}(st|nd|rd|th)/,
ordinal : function (number) {
var b = number % 10,
output = (~~(number % 100 / 10) === 1) ? 'th' :
(b === 1) ? 'st' :
(b === 2) ? 'nd' :
(b === 3) ? 'rd' : 'th';
return number + output;
}
}); |
"""Mock helpers for Z-Wave component."""
from unittest.mock import MagicMock
from pydispatch import dispatcher
def value_changed(value):
"""Fire a value changed."""
dispatcher.send(
MockNetwork.<API key>,
value=value,
node=value.node,
network=value.node._network,
)
def node_changed(node):
"""Fire a node changed."""
dispatcher.send(MockNetwork.SIGNAL_NODE, node=node, network=node._network)
def notification(node_id, network=None):
"""Fire a notification."""
dispatcher.send(
MockNetwork.SIGNAL_NOTIFICATION, args={"nodeId": node_id}, network=network
)
class MockOption(MagicMock):
"""Mock Z-Wave options."""
def __init__(self, device=None, config_path=None, user_path=None, cmd_line=None):
"""Initialize a Z-Wave mock options."""
super().__init__()
self.device = device
self.config_path = config_path
self.user_path = user_path
self.cmd_line = cmd_line
def _get_child_mock(self, **kw):
"""Create child mocks with right MagicMock class."""
return MagicMock(**kw)
class MockNetwork(MagicMock):
"""Mock Z-Wave network."""
<API key> = "mock_NetworkFailed"
<API key> = "mock_NetworkStarted"
<API key> = "mock_NetworkReady"
<API key> = "mock_NetworkStopped"
<API key> = "mock_DriverResetted"
<API key> = "mock_DriverAwaked"
<API key> = "mock_DriverFailed"
SIGNAL_DRIVER_READY = "mock_DriverReady"
SIGNAL_DRIVER_RESET = "mock_DriverReset"
<API key> = "mock_DriverRemoved"
SIGNAL_GROUP = "mock_Group"
SIGNAL_NODE = "mock_Node"
SIGNAL_NODE_ADDED = "mock_NodeAdded"
SIGNAL_NODE_EVENT = "mock_NodeEvent"
SIGNAL_NODE_NAMING = "mock_NodeNaming"
SIGNAL_NODE_NEW = "mock_NodeNew"
<API key> = "<API key>"
SIGNAL_NODE_READY = "mock_NodeReady"
SIGNAL_NODE_REMOVED = "mock_NodeRemoved"
SIGNAL_SCENE_EVENT = "mock_SceneEvent"
SIGNAL_VALUE = "mock_Value"
SIGNAL_VALUE_ADDED = "mock_ValueAdded"
<API key> = "mock_ValueChanged"
<API key> = "mock_ValueRefreshed"
<API key> = "mock_ValueRemoved"
<API key> = "mock_PollingEnabled"
<API key> = "<API key>"
<API key> = "mock_CreateButton"
<API key> = "mock_DeleteButton"
SIGNAL_BUTTON_ON = "mock_ButtonOn"
SIGNAL_BUTTON_OFF = "mock_ButtonOff"
<API key> = "<API key>"
<API key> = "<API key>"
<API key> = "<API key>"
<API key> = "<API key>"
<API key> = "<API key>"
SIGNAL_MSG_COMPLETE = "mock_MsgComplete"
SIGNAL_NOTIFICATION = "mock_Notification"
<API key> = "<API key>"
<API key> = "<API key>"
STATE_STOPPED = 0
STATE_FAILED = 1
STATE_RESETTED = 3
STATE_STARTED = 5
STATE_AWAKED = 7
STATE_READY = 10
def __init__(self, options=None, *args, **kwargs):
"""Initialize a Z-Wave mock network."""
super().__init__()
self.options = options
self.state = MockNetwork.STATE_STOPPED
class MockNode(MagicMock):
"""Mock Z-Wave node."""
def __init__(
self,
*,
node_id="567",
name="Mock Node",
manufacturer_id="ABCD",
product_id="123",
product_type="678",
command_classes=None,
can_wake_up_value=True,
manufacturer_name="Test Manufacturer",
product_name="Test Product",
network=None,
**kwargs,
):
"""Initialize a Z-Wave mock node."""
super().__init__()
self.node_id = node_id
self.name = name
self.manufacturer_id = manufacturer_id
self.product_id = product_id
self.product_type = product_type
self.manufacturer_name = manufacturer_name
self.product_name = product_name
self.can_wake_up_value = can_wake_up_value
self._command_classes = command_classes or []
if network is not None:
self._network = network
for attr_name in kwargs:
setattr(self, attr_name, kwargs[attr_name])
def has_command_class(self, command_class):
"""Test if mock has a command class."""
return command_class in self._command_classes
def get_battery_level(self):
"""Return mock battery level."""
return 42
def can_wake_up(self):
"""Return whether the node can wake up."""
return self.can_wake_up_value
def _get_child_mock(self, **kw):
"""Create child mocks with right MagicMock class."""
return MagicMock(**kw)
class MockValue(MagicMock):
"""Mock Z-Wave value."""
_mock_value_id = 1234
def __init__(
self,
*,
label="Mock Value",
node=None,
instance=0,
index=0,
value_id=None,
**kwargs,
):
"""Initialize a Z-Wave mock value."""
super().__init__()
self.label = label
self.node = node
self.instance = instance
self.index = index
if value_id is None:
MockValue._mock_value_id += 1
value_id = MockValue._mock_value_id
self.value_id = value_id
self.object_id = value_id
for attr_name in kwargs:
setattr(self, attr_name, kwargs[attr_name])
def _get_child_mock(self, **kw):
"""Create child mocks with right MagicMock class."""
return MagicMock(**kw)
def refresh(self):
"""Mock refresh of node value."""
value_changed(self)
class MockEntityValues:
"""Mock Z-Wave entity values."""
def __init__(self, **kwargs):
"""Initialize the mock zwave values."""
self.primary = None
self.wakeup = None
self.battery = None
self.power = None
for name in kwargs:
setattr(self, name, kwargs[name])
def __iter__(self):
"""Allow iteration over all values."""
return iter(self.__dict__.values()) |
package org.wso2.developerstudio.eclipse.gmf.esb.provider;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.edit.provider.<API key>;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.<API key>;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.<API key>;
import org.eclipse.emf.edit.provider.<API key>;
import org.eclipse.emf.edit.provider.ViewerNotification;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage;
import org.wso2.developerstudio.eclipse.gmf.esb.<API key>;
/**
* This is the item provider adapter for a {@link org.wso2.developerstudio.eclipse.gmf.esb.<API key>} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class <API key>
extends EsbNodeItemProvider
implements
<API key>,
<API key>,
<API key>,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public <API key>(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<<API key>> <API key>(Object object) {
if (<API key> == null) {
super.<API key>(object);
}
return <API key>;
}
/**
* This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an
* {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or
* {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) {
if (childrenFeatures == null) {
super.getChildrenFeatures(object);
childrenFeatures.add(EsbPackage.Literals.<API key>);
}
return childrenFeatures;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EStructuralFeature getChildFeature(Object object, Object child) {
// Check the type of the specified child object and return the proper feature to use for
// adding (see {@link AddCommand}) it as a child.
return super.getChildFeature(object, child);
}
/**
* This returns <API key>.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/<API key>"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
return getString("<API key>");
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(<API key>.class)) {
case EsbPackage.<API key>:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void <API key>(Collection<Object> newChildDescriptors, Object object) {
super.<API key>(newChildDescriptors, object);
newChildDescriptors.add
(<API key>
(EsbPackage.Literals.<API key>,
EsbFactory.eINSTANCE.createMediatorFlow()));
}
} |
package org.togglz.core.manager;
import java.util.Set;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.togglz.core.Feature;
public class ContainsFeature extends BaseMatcher<Set<Feature>> {
private final Feature feature;
public ContainsFeature(Feature feature) {
this.feature = feature;
}
@Override
public boolean matches(Object item) {
@SuppressWarnings("unchecked")
Set<Feature> features = (Set<Feature>) item;
for (Feature f : features) {
if (f.name().equals(feature.name())) {
return true;
}
}
return false;
}
@Override
public void describeTo(Description description) {
description.appendText("a set of features containing " + feature);
}
public static ContainsFeature containsFeature(Feature feature) {
return new ContainsFeature(feature);
}
} |
<table class="statustable">
<tbody>
<tr>
<td colspan="2">Status</td>
</tr>
<tr>
<td>Overview:</td>
<td class="partial">partial draft</td>
</tr>
<tr>
<td>POS tags:</td>
<td class="partial">partial draft</td>
</tr>
<tr>
<td>Features:</td>
<td class="none">template only</td>
</tr>
<tr>
<td>Relations:</td>
<td class="partial">partial draft</td>
</tr>
<tr>
<td>Data:</td>
<td class="none">none</td>
</tr>
</tbody>
</table> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.