answer
stringlengths 15
1.25M
|
|---|
package netP5;
import java.net.DatagramPacket;
import java.util.Vector;
/**
*
* @author andreas schlegel
*
*/
public class UdpServer extends AbstractUdpServer implements UdpPacketListener {
protected Object _myParent;
protected NetPlug _myNetPlug;
/**
* new UDP server.
* by default the buffersize of a udp packet is 1536 bytes. you can set
* your own individual buffersize with the third parameter int in the constructor.
* @param theObject Object
* @param thePort int
* @param theBufferSize int
*/
public UdpServer(
final Object theObject,
final int thePort,
final int theBufferSize) {
super(null, thePort, theBufferSize);
_myParent = theObject;
_myListener = this;
_myNetPlug = new NetPlug(_myParent);
start();
}
public UdpServer(
final Object theObject,
final int thePort) {
super(null, thePort, 1536);
_myParent = theObject;
_myListener = this;
_myNetPlug = new NetPlug(_myParent);
start();
}
/**
* @invisible
* @param theListener
* @param thePort
* @param theBufferSize
*/
public UdpServer(
final UdpPacketListener theListener,
final int thePort,
final int theBufferSize) {
super(theListener, thePort, theBufferSize);
}
/**
* @invisible
* @param theListener
* @param theAddress
* @param thePort
* @param theBufferSize
*/
protected UdpServer(
final UdpPacketListener theListener,
final String theAddress,
final int thePort,
final int theBufferSize) {
super(theListener, theAddress, thePort, theBufferSize);
}
/**
* @invisible
* @param thePacket DatagramPacket
* @param thePort int
*/
public void process(DatagramPacket thePacket, int thePort) {
_myNetPlug.process(thePacket,thePort);
}
/**
* add a listener to the udp server. each incoming packet will be forwarded
* to the listener.
* @param theListener
* @related NetListener
*/
public void addListener(NetListener theListener) {
_myNetPlug.addListener(theListener);
}
/**
*
* @param theListener
* @related NetListener
*/
public void removeListener(NetListener theListener) {
_myNetPlug.removeListener(theListener);
}
/**
*
* @param theIndex
* @related NetListener
* @return
*/
public NetListener getListener(int theIndex) {
return _myNetPlug.getListener(theIndex);
}
/**
* @related NetListener
* @return
*/
public Vector getListeners() {
return _myNetPlug.getListeners();
}
}
|
package org.openhab.binding.innogysmarthome.internal.listener;
import org.openhab.binding.innogysmarthome.internal.InnogyWebSocket;
/**
* The {@link EventListener} is called by the {@link InnogyWebSocket} on new Events and if the {@link InnogyWebSocket}
* closed the connection.
*
* @author Oliver Kuhl - Initial contribution
*/
public interface EventListener {
/**
* This method is called, whenever a new event comes from the innogy service (like a device change for example).
*
* @param msg
*/
public void onEvent(String msg);
/**
* This method is called, when the evenRunner stops abnormally (statuscode <> 1000).
*/
public void connectionClosed();
}
|
from sys import *
from pdflib_py import *
p = PDF_new()
PDF_open_file(p, "gradients.pdf")
PDF_set_parameter(p, "usercoordinates", "true")
PDF_set_value(p, "compress", 0)
PDF_set_info(p, "Author", "pdflib")
PDF_set_info(p, "Creator", "pdflib_py")
PDF_set_info(p, "Title", "gradients")
width = 1024
height = 800
PDF_begin_page(p, width, height)
type,x,params = "radial",0,"r0=0 r1=320"
y = 0
PDF_setcolor(p, "fill", "rgb", 0.0, 0.0, 0.0, 1.0)
shading = PDF_shading(p, type, 160+x,160+y, 160+x, 160+y, 1.0, 1.0, 1.0, 1.0, params) #axial|radial
pattern = PDF_shading_pattern(p,shading,"")
PDF_setcolor(p, "fill", "pattern", pattern,0,0,0)
PDF_moveto(p, x,y)
PDF_curveto(p, x+80, y+80, x+80, y+240, x, y+320)
PDF_curveto(p, x+80, y+240, x+240, y+240, x+320, y+320)
PDF_curveto(p, x+240, y+240, x+240, y+80, x+320, y)
PDF_curveto(p, x+240, y+80, x+80, y+80, x, y)
PDF_fill(p)
PDF_moveto(p, x,y)
PDF_curveto(p, x+80, y+80, x+80, y+240, x, y+320)
PDF_curveto(p, x+80, y+240, x+240, y+240, x+320, y+320)
PDF_curveto(p, x+240, y+240, x+240, y+80, x+320, y)
PDF_curveto(p, x+240, y+80, x+80, y+80, x, y)
PDF_stroke(p)
type,x,params = "axial",200,""
y = 0
PDF_setcolor(p, "fill", "rgb", 0.0, 0.0, 0.4, 1.0)
shading = PDF_shading(p, type, 0+x,0+y, 320+x,320+y, 1.0, 1.0, 1.0, 1.0, params) #axial|radial
pattern = PDF_shading_pattern(p,shading,"")
PDF_setcolor(p, "fill", "pattern", pattern,0,0,0)
PDF_moveto(p, x,y)
PDF_curveto(p, x+80, y+80, x+80, y+240, x, y+320)
PDF_curveto(p, x+80, y+240, x+240, y+240, x+320, y+320)
PDF_curveto(p, x+240, y+240, x+240, y+80, x+320, y)
PDF_curveto(p, x+240, y+80, x+80, y+80, x, y)
PDF_fill(p)
PDF_moveto(p, x,y)
PDF_curveto(p, x+80, y+80, x+80, y+240, x, y+320)
PDF_curveto(p, x+80, y+240, x+240, y+240, x+320, y+320)
PDF_curveto(p, x+240, y+240, x+240, y+80, x+320, y)
PDF_curveto(p, x+240, y+80, x+80, y+80, x, y)
PDF_stroke(p)
type,x,params = "radial",500,"r0=0 r1=220"
y = 0
PDF_setcolor(p, "fill", "rgb", 0.0, 0.0, 0.4, 1.0)
shading = PDF_shading(p, type, 120+x, 340+y, 120+x, 340+y, 1.0, 1.0, 1.0, 1.0, params) #axial|radial
pattern = PDF_shading_pattern(p,shading,"")
PDF_setcolor(p, "fill", "pattern", pattern,0,0,0)
PDF_moveto(p, x+80, y+80)
PDF_lineto(p, x+80, y+640)
PDF_lineto(p, x+160, y+640)
PDF_lineto(p, x+160, y+80)
PDF_lineto(p, x+80, y+80)
PDF_fill(p)
PDF_moveto(p, x+80, y+80)
PDF_lineto(p, x+80, y+640)
PDF_lineto(p, x+160, y+640)
PDF_lineto(p, x+160, y+80)
PDF_lineto(p, x+80, y+80)
PDF_stroke(p)
type,x,params = "axial",600,""
y = 0
PDF_setcolor(p, "fill", "rgb", 0.0, 0.0, 0.4, 1.0)
shading = PDF_shading(p, type, 80+x, 80+y, 80+x, 640+y, 1.0, 1.0, 1.0, 1.0, params) #axial|radial
pattern = PDF_shading_pattern(p,shading,"")
PDF_setcolor(p, "fill", "pattern", pattern,0,0,0)
PDF_moveto(p, x+80, y+80)
PDF_lineto(p, x+80, y+640)
PDF_lineto(p, x+160, y+640)
PDF_lineto(p, x+160, y+80)
PDF_lineto(p, x+80, y+80)
PDF_fill(p)
PDF_moveto(p, x+80, y+80)
PDF_lineto(p, x+80, y+640)
PDF_lineto(p, x+160, y+640)
PDF_lineto(p, x+160, y+80)
PDF_lineto(p, x+80, y+80)
PDF_stroke(p)
type,x,params = "axial",50,""
y = 300
PDF_setcolor(p, "fill", "rgb", 0.0, 0.0, 0.4, 1.0)
shading = PDF_shading(p, type, 80+x, 80+y, 400+x, 80+y, 1.0, 1.0, 1.0, 1.0, params) #axial|radial
pattern = PDF_shading_pattern(p,shading,"")
PDF_setcolor(p, "fill", "pattern", pattern,0,0,0)
PDF_moveto(p, x+80, y+80)
PDF_lineto(p, x+80, y+160)
PDF_lineto(p, x+400, y+160)
PDF_lineto(p, x+400, y+80)
PDF_lineto(p, x+80, y+80)
PDF_fill(p)
PDF_moveto(p, x+80, y+80)
PDF_lineto(p, x+80, y+160)
PDF_lineto(p, x+400, y+160)
PDF_lineto(p, x+400, y+80)
PDF_lineto(p, x+80, y+80)
PDF_stroke(p)
PDF_end_page(p)
PDF_close(p)
PDF_delete(p);
|
<?php
/**
* <API key>
*
* @since 2.0
*/
class <API key> extends Types_Page_Abstract {
private static $instance;
private $redirect_url = false;
public static function get_instance() {
if( null == self::$instance ) {
self::$instance = new self();
self::$instance-><API key>();
}
}
public function <API key>() {
add_submenu_page(
'options.php', // hidden
$this->get_title(),
$this->get_title(),
$this-><API key>(),
$this->get_page_name(),
array( $this, $this->get_load_callback() )
);
}
public function get_title() {
return 'Loading...';
}
public function get_render_callback() {
return null;
}
public function get_load_callback() {
return 'route';
}
public function get_page_name() {
return Types_Admin_Menu::PAGE_NAME_HELPER;
}
public function <API key>() {
return 'manage_options';
}
public function route() {
$this->redirect_url = false;
if( isset( $_GET['action'] ) && isset( $_GET['type'] ) ) {
switch( $_GET['action'] ) {
case 'new-form':
$this->redirect_url = $this->new_form_action( $_GET['type'] );
break;
case 'new-view':
$this->redirect_url = $this->new_view_action( $_GET['type'] );
break;
case 'new-layout-template':
$this->redirect_url = $this-><API key>( $_GET['type'] );
break;
case '<API key>':
$this->redirect_url = $this-><API key>( $_GET['type'] );
break;
case '<API key>':
$this->redirect_url = $this-><API key>( $_GET['type'] );
break;
case '<API key>':
$this->redirect_url = $this-><API key>( $_GET['type'] );
break;
}
}
$this->redirect_url = $this->add_params_to_url( $this->redirect_url );
$this->redirect();
}
private function new_form_action( $type ) {
$new_form = new <API key>();
if( $id = $new_form->for_post( $type ) ) {
return get_edit_post_link( $id, 'Please WordPress, be so nice and do not encode &.' );
}
return false;
}
private function new_view_action( $type ) {
$new_view = new <API key>();
if( $id = $new_view->for_post( $type ) ) {
return admin_url() . 'admin.php?page=views-editor&view_id='.$id;
}
return false;
}
private function <API key>( $type ) {
$new_layout = new <API key>();
if( $id = $new_layout->for_post( $type ) ) {
return admin_url() . 'admin.php?page=dd_layouts_edit&action=edit&layout_id='.$id;
}
return false;
}
private function <API key>( $type ) {
$new_layout = new <API key>();
if( $id = $new_layout->for_post( $type ) ) {
return admin_url() . 'admin.php?page=ct-editor&ct_id='.$id;
}
return false;
}
private function <API key>( $type ) {
$<API key> = new <API key>();
if( $id = $<API key>->for_post( $type ) ) {
return admin_url() . 'admin.php?page=<API key>&view_id='.$id;
}
return false;
}
private function <API key>( $type ) {
$type_object = <API key>( $type );
$title = sprintf( __( 'Field Group for %s', 'types' ), $type_object->labels->name );
$name = sanitize_title( $title );
$<API key> = <API key>::get_instance()->create( $name, $title, 'publish' );
if( ! $<API key> )
return false;
$<API key>->assign_post_type( $type );
$url = isset( $_GET['ref'] )
? 'admin.php?page=wpcf-edit&group_id='.$<API key>->get_id().'&ref='.$_GET['ref']
: 'admin.php?page=wpcf-edit&group_id='.$<API key>->get_id();
return admin_url( $url );
}
private function add_params_to_url( $url ) {
// forward parameter toolset_help_video
if( isset( $_GET['toolset_help_video'] ) )
$url = add_query_arg( 'toolset_help_video', $_GET['toolset_help_video'], $url );
// forward parameter ref
if( isset( $_GET['ref'] ) )
$url = add_query_arg( 'ref', $_GET['ref'], $url );
return $url;
}
/**
* hidden page, but only when redirect after doing what we have to do
*/
private function redirect() {
// shouldn't happen but if we have no redirect_url here: goto admin main page.
if( ! $this->redirect_url )
$this->redirect_url = admin_url();
die( '<script type="text/javascript">'.'window.location = "' . $this->redirect_url . '";'.'</script>' );
}
}
|
#include "mcu.h"
#include "mcu_periph/sys_time.h"
#include "led.h"
#include "subsystems/datalink/downlink.h"
#include "mcu_periph/uart.h"
#include "mcu_periph/can.h"
static inline void main_init( void );
static inline void main_periodic_task( void );
static inline void main_event_task( void );
void main_on_can_msg(uint32_t id, uint8_t *data, int len);
uint8_t tx_data[8];
uint8_t rx_data[8];
bool new_can_data = false;
int main(void) {
main_init();
tx_data[0] = 0;
tx_data[1] = 0;
tx_data[2] = 0;
tx_data[3] = 0;
tx_data[4] = 0;
tx_data[5] = 0;
tx_data[6] = 0;
tx_data[7] = 0;
new_can_data = false;
while(1) {
if (<API key>(0))
main_periodic_task();
main_event_task();
}
return 0;
}
static inline void main_init( void ) {
mcu_init();
<API key>((0.5/PERIODIC_FREQUENCY), NULL);
ppz_can_init(main_on_can_msg);
}
static inline void main_periodic_task( void ) {
tx_data[0]+=1;
ppz_can_transmit(0, tx_data, 8);
LED_PERIODIC();
DOWNLINK_SEND_ALIVE(DefaultChannel, DefaultDevice, 16, MD5SUM);
}
static inline void main_event_task( void ) {
if (new_can_data) {
if (rx_data[0] & 0x10) {
LED_ON(2);
} else {
LED_OFF(2);
}
}
if (new_can_data) {
if (rx_data[0] & 0x20) {
LED_ON(3);
} else {
LED_OFF(3);
}
}
if (new_can_data) {
if (rx_data[0] & 0x40) {
LED_ON(4);
} else {
LED_OFF(4);
}
}
if (new_can_data) {
if (rx_data[0] & 0x80) {
LED_ON(5);
} else {
LED_OFF(5);
}
}
}
void main_on_can_msg(uint32_t id, uint8_t *data, int len)
{
for (int i = 0; i<8; i++) {
rx_data[i] = data[i];
}
new_can_data = true;
}
|
// This Source Code Form is subject to the terms of the Mozilla Public
//! \addtogroup spdiagview
//! Class for storing data required to extract and set the diagonals of a sparse matrix
template<typename eT>
class spdiagview : public Base<eT, spdiagview<eT> >
{
public:
typedef eT elem_type;
typedef typename get_pod_type<eT>::result pod_type;
arma_aligned const SpMat<eT>& m;
static const bool is_row = false;
static const bool is_col = true;
const uword row_offset;
const uword col_offset;
const uword n_rows; // equal to n_elem
const uword n_elem;
static const uword n_cols = 1;
protected:
arma_inline spdiagview(const SpMat<eT>& in_m, const uword in_row_offset, const uword in_col_offset, const uword len);
public:
inline ~spdiagview();
inline void operator=(const spdiagview& x);
inline void operator+=(const eT val);
inline void operator-=(const eT val);
inline void operator*=(const eT val);
inline void operator/=(const eT val);
template<typename T1> inline void operator= (const Base<eT,T1>& x);
template<typename T1> inline void operator+=(const Base<eT,T1>& x);
template<typename T1> inline void operator-=(const Base<eT,T1>& x);
template<typename T1> inline void operator%=(const Base<eT,T1>& x);
template<typename T1> inline void operator/=(const Base<eT,T1>& x);
template<typename T1> inline void operator= (const SpBase<eT,T1>& x);
template<typename T1> inline void operator+=(const SpBase<eT,T1>& x);
template<typename T1> inline void operator-=(const SpBase<eT,T1>& x);
template<typename T1> inline void operator%=(const SpBase<eT,T1>& x);
template<typename T1> inline void operator/=(const SpBase<eT,T1>& x);
inline eT at_alt (const uword ii) const;
inline SpValProxy< SpMat<eT> > operator[](const uword ii);
inline eT operator[](const uword ii) const;
inline SpValProxy< SpMat<eT> > at(const uword ii);
inline eT at(const uword ii) const;
inline SpValProxy< SpMat<eT> > operator()(const uword ii);
inline eT operator()(const uword ii) const;
inline SpValProxy< SpMat<eT> > at(const uword in_n_row, const uword);
inline eT at(const uword in_n_row, const uword) const;
inline SpValProxy< SpMat<eT> > operator()(const uword in_n_row, const uword in_n_col);
inline eT operator()(const uword in_n_row, const uword in_n_col) const;
inline void fill(const eT val);
inline void zeros();
inline void ones();
inline void randu();
inline void randn();
inline static void extract(Mat<eT>& out, const spdiagview& in);
private:
friend class SpMat<eT>;
spdiagview();
};
|
#include <linux/module.h>
#include <mach/irqs.h>
#include <asm/mach-types.h>
#include <mach/gpiomux.h>
#include "gpiomux_lge_325.h"
#include "devices_lge_325.h"
#ifdef <API key>
#ifdef <API key>
static struct gpiomux_setting <API key> = /* BOOT_CONFIG_0 */
{
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct msm_gpiomux_config <API key>[] __initdata = {
/* BOOT_CONFIG_0 */
{
.gpio = 81,
.settings = {
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
};
#else
static struct gpiomux_setting <API key> = /* BOOT_CONFIG_0 */
{
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_UP,
};
static struct gpiomux_setting <API key> = /* BOOT_CONFIG_1 */
{
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_UP,
};
static struct gpiomux_setting <API key> = /* BOOT_CONFIG_6*/
{
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_UP,
};
static struct msm_gpiomux_config <API key>[] __initdata = {
/* BOOT_CONFIG_0 */
{
.gpio = 81,
.settings = {
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* BOOT_CONFIG_1 */
{
.gpio = 84,
.settings = {
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* BOOT_CONFIG_6*/
{
.gpio = 76,
.settings = {
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
};
//for atnt rock_bottom end
#endif
#endif
static struct gpiomux_setting console_uart = {
.func = GPIOMUX_FUNC_2,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting wifi_active = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_UP,
};
/* The SPI configurations apply to GSBI1 and GSBI10 */
static struct gpiomux_setting spi_active = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_DOWN,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
};
/* This I2C active configuration applies to GSBI3 and GSBI4 */
static struct gpiomux_setting i2c_active = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_NONE,
};
#ifdef <API key>
static struct gpiomux_setting gsbi5 = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_NONE,
};
#endif
static struct gpiomux_setting i2c_active_gsbi7 = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_12MA,
.pull = GPIOMUX_PULL_NONE,
};
/* This I2C suspended configuration applies to GSBI3, GSBI4 and GSBI7 */
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting gsbi8 = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
};
#ifdef CONFIG_LGE_IRDA
static struct gpiomux_setting gsbi8_irda = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_DOWN,
};
static struct gpiomux_setting gsbi8_irda_active = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_DOWN,
};
static struct gpiomux_setting irda_pwdn_suspended = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
.dir = GPIOMUX_OUT_HIGH,
};
/*
static struct gpiomux_setting irda_pwdn_active = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_UP,
.dir = GPIOMUX_OUT_HIGH,
};
*/
#endif
#ifdef CONFIG_LGE_FELICA
static struct gpiomux_setting uart10dm_active = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_8MA ,
.pull = GPIOMUX_PULL_DOWN,
};
#endif
static struct gpiomux_setting gsbi10 = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_NONE,
};
#if defined(<API key>) || defined(<API key>)
static struct gpiomux_setting gsbi11 = {
.func = GPIOMUX_FUNC_2,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting bcast_ctrl_pin = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_NONE,
};
#if defined (<API key>)
static struct gpiomux_setting DMB_INT = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_NONE,
};
#endif
#endif
#if defined (<API key>) || defined (<API key>)
static struct gpiomux_setting gsbi11 = {
.func = GPIOMUX_FUNC_2,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_NONE,
};
#endif
static struct gpiomux_setting gsbi12 = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting ps_hold = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_12MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_DOWN,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_10MA,
.pull = GPIOMUX_PULL_UP,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_10MA,
.pull = GPIOMUX_PULL_UP,
};
static struct gpiomux_setting sdcc1_clk_actv_cfg = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_16MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_UP,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_2,
.drv = GPIOMUX_DRV_10MA,
.pull = GPIOMUX_PULL_UP,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_2,
.drv = GPIOMUX_DRV_10MA,
.pull = GPIOMUX_PULL_UP,
};
static struct gpiomux_setting sdcc2_clk_actv_cfg = {
.func = GPIOMUX_FUNC_2,
.drv = GPIOMUX_DRV_16MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_UP,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_2,
.drv = GPIOMUX_DRV_10MA,
.pull = GPIOMUX_PULL_UP,
};
static struct gpiomux_setting sdcc5_clk_actv_cfg = {
.func = GPIOMUX_FUNC_2,
.drv = GPIOMUX_DRV_16MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_UP,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting uart1dm_active = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting uart1dm_suspended = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_DOWN,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_DOWN,
};
static struct gpiomux_setting hdmi_suspend_cfg = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_DOWN,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting hdmi_active_1_cfg = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_UP,
};
static struct gpiomux_setting hdmi_active_2_cfg = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_16MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting hdmi_active_3_cfg = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_16MA,
.pull = GPIOMUX_PULL_DOWN,
};
static struct gpiomux_setting pmic_suspended_cfg = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
};
#ifdef <API key>
static struct gpiomux_setting uart9dm_active = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_8MA ,
.pull = GPIOMUX_PULL_DOWN,
};
static struct gpiomux_setting gsbi9 = {
.func = GPIOMUX_FUNC_1,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_NONE,
};
#endif
static struct gpiomux_setting ap2mdm_cfg = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_DOWN,
};
static struct gpiomux_setting mdm2ap_status_cfg = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_UP,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_DOWN,
};
static struct gpiomux_setting mdm2ap_errfatal_cfg = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_16MA,
.pull = GPIOMUX_PULL_DOWN,
};
static struct gpiomux_setting ap2mdm_kpdpwr_n_cfg = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_NONE,
};
#ifdef CONFIG_LGE_AUDIO
#if 0 /* error CAMCORDER_MIC_EN180 greater than max:173 */
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
.dir = GPIOMUX_OUT_LOW,
};
#endif
static struct gpiomux_setting motor_en_cfg = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
.dir = GPIOMUX_OUT_LOW,
};
static struct gpiomux_setting lin_motor_pwm_cfg = {
.func = GPIOMUX_FUNC_2,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
// .dir = GPIOMUX_OUT_LOW,
};
#ifdef <API key>
static struct gpiomux_setting ear_mic_en_cfg = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
.dir = GPIOMUX_OUT_LOW,
};
static struct gpiomux_setting earpole_detect_cfg = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
.dir = GPIOMUX_IN,
};
#endif
#endif
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
};
#ifdef CONFIG_LGE_FELICA
static struct gpiomux_setting felica_pon_cfg = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
};
static struct gpiomux_setting felica_lockcont_cfg = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
};
#endif
#if defined(<API key>)
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_DOWN,
.dir = GPIOMUX_OUT_LOW,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_DOWN,
.dir = GPIOMUX_IN,
};
static struct gpiomux_setting <API key> = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_8MA,
.pull = GPIOMUX_PULL_DOWN,
.dir = GPIOMUX_OUT_LOW,
};
#endif
#ifdef <API key>
static struct gpiomux_setting mhl_detect_cfg = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
.dir = GPIOMUX_IN,
};
static struct gpiomux_setting mhl_reset_n_cfg = {
.func = GPIOMUX_FUNC_GPIO,
.drv = GPIOMUX_DRV_2MA,
.pull = GPIOMUX_PULL_NONE,
.dir = GPIOMUX_OUT_LOW,
};
static struct msm_gpiomux_config msm8x60_mhl_configs[] __initdata = {
/* MHL_INT */
{
.gpio = 30,
.settings = {
[GPIOMUX_SUSPENDED] = &mhl_detect_cfg,
},
},
/* USB_MHL_SEL */
#if defined(<API key>) || defined(<API key>)
{
.gpio = 33,
.settings = {
[GPIOMUX_SUSPENDED] = &mhl_reset_n_cfg,
},
},
#else
{
.gpio = 139,
.settings = {
[GPIOMUX_SUSPENDED] = &mhl_reset_n_cfg,
},
},
#endif
/* MHL_RESET_N */
{
.gpio = 142,
.settings = {
[GPIOMUX_SUSPENDED] = &mhl_reset_n_cfg,
},
},
/* MHL_WAKE_UP */
{
.gpio = 153,
.settings = {
[GPIOMUX_SUSPENDED] = &mhl_reset_n_cfg,
},
},
};
#endif
static struct msm_gpiomux_config <API key>[] __initdata = {
#if defined(<API key>) || defined(<API key>)
#ifndef <API key>
{
.gpio = 33,
.settings = {
[GPIOMUX_SUSPENDED] = &<API key>,
[GPIOMUX_ACTIVE] = &spi_active,
},
},
#endif
#else
{
.gpio = 33,
.settings = {
[GPIOMUX_SUSPENDED] = &<API key>,
[GPIOMUX_ACTIVE] = &spi_active,
},
},
#endif
{
.gpio = 34,
.settings = {
//[GPIOMUX_SUSPENDED] = &<API key>,
//[GPIOMUX_ACTIVE] = &spi_active,
[GPIOMUX_ACTIVE] = &wifi_active,
[GPIOMUX_SUSPENDED] = &wifi_active,
},
},
{
.gpio = 35,
.settings = {
[GPIOMUX_SUSPENDED] = &<API key>,
[GPIOMUX_ACTIVE] = &spi_active,
},
},
{
.gpio = 36,
.settings = {
[GPIOMUX_SUSPENDED] = &<API key>,
[GPIOMUX_ACTIVE] = &spi_active,
},
},
{
.gpio = 43,
.settings = {
[GPIOMUX_SUSPENDED] = &<API key>,
[GPIOMUX_ACTIVE] = &i2c_active,
},
},
{
.gpio = 44,
.settings = {
[GPIOMUX_SUSPENDED] = &<API key>,
[GPIOMUX_ACTIVE] = &i2c_active,
},
},
#if defined(<API key>)
{
.gpio = 46,
.settings = {
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
#endif
{
.gpio = 47,
.settings = {
[GPIOMUX_SUSPENDED] = &<API key>,
[GPIOMUX_ACTIVE] = &i2c_active,
},
},
{
.gpio = 48,
.settings = {
[GPIOMUX_SUSPENDED] = &<API key>,
[GPIOMUX_ACTIVE] = &i2c_active,
},
},
#ifdef <API key>
{
.gpio = 51,
.settings = {
[GPIOMUX_SUSPENDED] = &gsbi5,
},
},
{
.gpio = 52,
.settings = {
[GPIOMUX_SUSPENDED] = &gsbi5,
},
},
#endif
{
.gpio = 59,
.settings = {
[GPIOMUX_SUSPENDED] = &<API key>,
[GPIOMUX_ACTIVE] = &i2c_active_gsbi7,
},
},
{
.gpio = 60,
.settings = {
[GPIOMUX_SUSPENDED] = &<API key>,
[GPIOMUX_ACTIVE] = &i2c_active_gsbi7,
},
},
{
.gpio = 64,
.settings = {
[GPIOMUX_SUSPENDED] = &gsbi8,
},
},
{
.gpio = 65,
.settings = {
[GPIOMUX_SUSPENDED] = &gsbi8,
},
},
#ifdef <API key>
{
.gpio = 72,
.settings = {
[GPIOMUX_SUSPENDED] = &gsbi10,
},
},
{
.gpio = 73,
.settings = {
[GPIOMUX_SUSPENDED] = &gsbi10,
},
},
#endif
// 2011-05-05 ella.hwang added for 1Seg Driver SPI porting - [Ends]
{
.gpio = 115,
.settings = {
[GPIOMUX_SUSPENDED] = &gsbi12,
},
},
{
.gpio = 116,
.settings = {
[GPIOMUX_SUSPENDED] = &gsbi12,
},
},
#ifdef CONFIG_LGE_FELICA /* FELICA PON */
{
.gpio = 107,
.settings = {
[GPIOMUX_SUSPENDED] = &felica_pon_cfg,
},
}, /* FELICA RFS */
{
.gpio = 128,
.settings = {
[GPIOMUX_SUSPENDED] = &felica_pon_cfg,
},
}, /* FELICA INT */
{
.gpio = 125,
.settings = {
[GPIOMUX_SUSPENDED] = &felica_pon_cfg,
},
}, /* FELICA CEN */
{
.gpio = 123,
.settings = {
[GPIOMUX_SUSPENDED] = &felica_lockcont_cfg,
},
},
#endif
// 2011-05-05 ella.hwang added for 1Seg Driver SPI porting - [Begins]
#if defined(<API key>) || defined(<API key>)
/* DTV_RESET */
{
.gpio = 101,
.settings = {
[GPIOMUX_SUSPENDED] = &bcast_ctrl_pin,
},
},
/* DTV EN */
{
.gpio = 102,
.settings = {
[GPIOMUX_SUSPENDED] = &bcast_ctrl_pin,
},
},
/* DTV SPI CLOCK */
{
.gpio = 103,
.settings = {
[GPIOMUX_SUSPENDED] = &gsbi11,
},
},
/* DTV SPI CS */
{
.gpio = 104,
.settings = {
[GPIOMUX_SUSPENDED] = &gsbi11,
},
},
/* DTV SPI MISO */
{
.gpio = 105,
.settings = {
[GPIOMUX_SUSPENDED] = &gsbi11,
},
},
/* DTV SPI MOSI */
{
.gpio = 106,
.settings = {
[GPIOMUX_SUSPENDED] = &gsbi11,
},
},
#if defined(<API key>)
/* DMB_INT_N */
{
.gpio = 107,
.settings = {
[GPIOMUX_SUSPENDED] = &DMB_INT,
},
},
#endif
#endif
};
#if defined(<API key>)
static struct msm_gpiomux_config <API key>[] __initdata = {
{
.gpio = 123,
.settings = {
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
{
.gpio = 130,
.settings = {
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
};
#endif
#if defined(<API key>) || defined(<API key>)
#endif
static struct msm_gpiomux_config <API key>[] __initdata = {
{ /* UARTDM_TX */
.gpio = 53,
.settings = {
[GPIOMUX_ACTIVE] = &uart1dm_active,
[GPIOMUX_SUSPENDED] = &uart1dm_suspended,
},
},
{ /* UARTDM_RX */
.gpio = 54,
.settings = {
[GPIOMUX_ACTIVE] = &uart1dm_active,
[GPIOMUX_SUSPENDED] = &uart1dm_suspended,
},
},
{ /* UARTDM_CTS */
.gpio = 55,
.settings = {
[GPIOMUX_ACTIVE] = &uart1dm_active,
[GPIOMUX_SUSPENDED] = &uart1dm_suspended,
},
},
{ /* UARTDM_RFR */
.gpio = 56,
.settings = {
[GPIOMUX_ACTIVE] = &uart1dm_active,
[GPIOMUX_SUSPENDED] = &uart1dm_suspended,
},
},
{
.gpio = 115,
.settings = {
[GPIOMUX_SUSPENDED] = &console_uart,
},
},
{
.gpio = 116,
.settings = {
[GPIOMUX_SUSPENDED] = &console_uart,
},
},
#if !defined(<API key>) && !defined(<API key>)
/* USB ISP1763 may also use 117 GPIO */
{
.gpio = 117,
.settings = {
[GPIOMUX_SUSPENDED] = &console_uart,
},
},
#endif
{
.gpio = 118,
.settings = {
[GPIOMUX_SUSPENDED] = &console_uart,
},
},
};
#ifdef <API key>
static struct msm_gpiomux_config <API key>[] __initdata = {
{ /* UART9DM RX */
.gpio = 66,
.settings = {
[GPIOMUX_ACTIVE] = &uart9dm_active,
[GPIOMUX_SUSPENDED] = &gsbi9,
},
},
{ /* UART9DM TX */
.gpio = 67,
.settings = {
[GPIOMUX_ACTIVE] = &uart9dm_active,
[GPIOMUX_SUSPENDED] = &gsbi9,
},
},
};
#endif
#ifdef CONFIG_LGE_IRDA
static struct msm_gpiomux_config <API key>[] __initdata = {
{
.gpio = 62,
.settings = {
[GPIOMUX_ACTIVE] = &gsbi8_irda_active,
[GPIOMUX_SUSPENDED] = &gsbi8_irda,
},
},
{
.gpio = 63,
.settings = {
[GPIOMUX_ACTIVE] = &gsbi8_irda_active,
[GPIOMUX_SUSPENDED] = &gsbi8_irda,
},
},
{
.gpio = 169,
.settings = {
[GPIOMUX_SUSPENDED] = &irda_pwdn_suspended,
// [GPIOMUX_ACTIVE] =&irda_pwdn_active,
},
},
};
#endif
#ifdef CONFIG_LGE_FELICA
static struct msm_gpiomux_config <API key>[] __initdata = {
{ /* UART10DM RX */
.gpio = 70,
.settings = {
[GPIOMUX_ACTIVE] = &uart10dm_active,
[GPIOMUX_SUSPENDED] = &gsbi10,
},
},
{ /* UART10DM TX */
.gpio = 71,
.settings = {
[GPIOMUX_ACTIVE] = &uart10dm_active,
[GPIOMUX_SUSPENDED] = &gsbi10,
},
},
};
#endif
static struct msm_gpiomux_config <API key>[] __initdata = {
{
.gpio = 111,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
{
.gpio = 112,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
{
.gpio = 113,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
{
.gpio = 114,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
};
static struct msm_gpiomux_config msm8x60_sdc_configs[] __initdata = {
/* SDCC1 data[0] */
{
.gpio = 159,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC1 data[1] */
{
.gpio = 160,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC1 data[2] */
{
.gpio = 161,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC1 data[3] */
{
.gpio = 162,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC1 data[4] */
{
.gpio = 163,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC1 data[5] */
{
.gpio = 164,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC1 data[6] */
{
.gpio = 165,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC1 data[7] */
{
.gpio = 166,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC1 CLK */
{
.gpio = 167,
.settings = {
[GPIOMUX_ACTIVE] = &sdcc1_clk_actv_cfg,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC1 CMD */
{
.gpio = 168,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
};
static struct msm_gpiomux_config <API key>[] __initdata = {
/* SDCC5 cmd */
{
.gpio = 95,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC5 data[3]*/
{
.gpio = 96,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC5 clk */
{
.gpio = 97,
.settings = {
[GPIOMUX_ACTIVE] = &sdcc5_clk_actv_cfg,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC5 data[2]*/
{
.gpio = 98,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC5 data[1]*/
{
.gpio = 99,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC5 data[0]*/
{
.gpio = 100,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* MDM2AP_SYNC */
{
.gpio = 129,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* MDM2AP_VDDMIN */
{
.gpio = 140,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC2 data[0] */
{
.gpio = 143,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC2 data[1] */
{
.gpio = 144,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC2 data[2] */
{
.gpio = 145,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC2 data[3] */
{
.gpio = 146,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC2 data[4] */
{
.gpio = 147,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC2 data[5] */
{
.gpio = 148,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC2 data[6] */
{
.gpio = 149,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC2 data[7] */
{
.gpio = 150,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC2 CMD */
{
.gpio = 151,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* SDCC2 CLK */
{
.gpio = 152,
.settings = {
[GPIOMUX_ACTIVE] = &sdcc2_clk_actv_cfg,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
};
static struct msm_gpiomux_config msm8x60_snd_configs[] __initdata = {
{
.gpio = 108,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
{
.gpio = 109,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
};
static struct msm_gpiomux_config <API key>[] __initdata = {
{
.gpio = 28,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
};
static struct msm_gpiomux_config <API key>[] __initdata = {
{
.gpio = 169,
.settings = {
[GPIOMUX_ACTIVE] = &hdmi_active_1_cfg,
[GPIOMUX_SUSPENDED] = &hdmi_suspend_cfg,
},
},
{
.gpio = 170,
.settings = {
[GPIOMUX_ACTIVE] = &hdmi_active_2_cfg,
[GPIOMUX_SUSPENDED] = &hdmi_suspend_cfg,
},
},
{
.gpio = 171,
.settings = {
[GPIOMUX_ACTIVE] = &hdmi_active_2_cfg,
[GPIOMUX_SUSPENDED] = &hdmi_suspend_cfg,
},
},
{
.gpio = 172,
.settings = {
[GPIOMUX_ACTIVE] = &hdmi_active_3_cfg,
[GPIOMUX_SUSPENDED] = &hdmi_suspend_cfg,
},
},
};
/* Because PMIC drivers do not use gpio-management routines and PMIC
* gpios must never sleep, a "good enough" config is obtained by placing
* the active config in the 'suspended' slot and leaving the active
* config invalid: the suspended config will be installed at boot
* and never replaced.
*/
static struct msm_gpiomux_config <API key>[] __initdata = {
{
.gpio = 88,
.settings = {
[GPIOMUX_SUSPENDED] = &pmic_suspended_cfg,
},
},
{
.gpio = 91,
.settings = {
[GPIOMUX_SUSPENDED] = &pmic_suspended_cfg,
},
},
};
static struct msm_gpiomux_config <API key>[] __initdata = {
/* MDM2AP_STATUS */
{
.gpio = 77,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
},
},
/* PS_HOLD */
{
.gpio = 92,
.settings = {
[GPIOMUX_SUSPENDED] = &ps_hold,
},
},
};
static struct msm_gpiomux_config <API key>[] __initdata = {
/* AP2MDM_WAKEUP */
{
.gpio = 135,
.settings = {
[GPIOMUX_SUSPENDED] = &ap2mdm_cfg,
}
},
/* MDM2AP_VFR */
{
.gpio = 94,
.settings = {
[GPIOMUX_ACTIVE] = &<API key>,
[GPIOMUX_SUSPENDED] = &<API key>,
}
},
/* AP2MDM_STATUS */
{
.gpio = 136,
.settings = {
[GPIOMUX_SUSPENDED] = &ap2mdm_cfg,
}
},
/* MDM2AP_STATUS */
{
.gpio = 134,
.settings = {
[GPIOMUX_SUSPENDED] = &mdm2ap_status_cfg,
}
},
/* MDM2AP_WAKEUP */
{
.gpio = 40,
.settings = {
[GPIOMUX_SUSPENDED] = &ap2mdm_cfg,
}
},
/* MDM2AP_ERRFATAL */
{
.gpio = 133,
.settings = {
[GPIOMUX_SUSPENDED] = &mdm2ap_errfatal_cfg,
}
},
/* AP2MDM_ERRFATAL */
{
.gpio = 93,
.settings = {
[GPIOMUX_SUSPENDED] = &ap2mdm_cfg,
}
},
/* AP2MDM_KPDPWR_N */
{
.gpio = 132,
.settings = {
[GPIOMUX_SUSPENDED] = &ap2mdm_kpdpwr_n_cfg,
}
},
/* AP2MDM_PMIC_RESET_N */
{
.gpio = 131,
.settings = {
[GPIOMUX_SUSPENDED] = &ap2mdm_kpdpwr_n_cfg,
}
}
};
#ifdef CONFIG_LGE_AUDIO
static struct msm_gpiomux_config <API key>[] __initdata = {
#if 0 /* error CAMCORDER_MIC_EN180 greater than max:173 */
/* CAMCORDER_MIC_EN */
{
.gpio = <API key>,
.settings = {
[GPIOMUX_SUSPENDED] = &<API key>,
}
},
#endif
/* MOTOR_EN*/
{
.gpio = GPIO_LIN_MOTOR_EN,
.settings = {
[GPIOMUX_SUSPENDED] = &motor_en_cfg,
}
},
/* LIN_MOTOR_PWM*/
{
.gpio = GPIO_LIN_MOTOR_PWM,
.settings = {
[GPIOMUX_SUSPENDED] = &lin_motor_pwm_cfg,
}
},
#ifdef <API key>
/* EAR_MIC_EN */
{
.gpio = GPIO_EAR_MIC_EN,
.settings = {
[GPIOMUX_SUSPENDED] = &ear_mic_en_cfg,
}
},
/* EARPOL_DETECT */
{
.gpio = GPIO_EARPOL_DETECT,
.settings = {
[GPIOMUX_SUSPENDED] = &earpole_detect_cfg,
}
},
#endif
};
#endif
#if 0
struct msm_gpiomux_configs
<API key>[] __initdata = {
{<API key>, ARRAY_SIZE(<API key>)},
{<API key>, ARRAY_SIZE(<API key>)},
#ifdef <API key>
{<API key>, ARRAY_SIZE(<API key>)},
#endif
#ifdef CONFIG_LGE_FELICA
{<API key>, ARRAY_SIZE(<API key>)},
#endif
{msm8x60_ts_configs, ARRAY_SIZE(msm8x60_ts_configs)},
{<API key>, ARRAY_SIZE(<API key>)},
{msm8x60_sdc_configs, ARRAY_SIZE(msm8x60_sdc_configs)},
{msm8x60_snd_configs, ARRAY_SIZE(msm8x60_snd_configs)},
{<API key>, ARRAY_SIZE(<API key>)},
{<API key>, ARRAY_SIZE(<API key>)},
{<API key>, ARRAY_SIZE(<API key>)},
{<API key>, ARRAY_SIZE(<API key>)},
{<API key>, ARRAY_SIZE(<API key>)},
{<API key>, ARRAY_SIZE(<API key>)},
{msm8x60_cam_configs, ARRAY_SIZE(msm8x60_cam_configs)},
{<API key>, ARRAY_SIZE(<API key>)},
{<API key>, ARRAY_SIZE(<API key>)},
{<API key>, ARRAY_SIZE(<API key>)},
{NULL, 0},
};
#endif
struct msm_gpiomux_configs
<API key>[] __initdata = {
#ifdef <API key>
{<API key>, ARRAY_SIZE(<API key>)}, //for rock_bottom
#endif
#ifdef <API key>
{msm8x60_mhl_configs, ARRAY_SIZE(msm8x60_mhl_configs)},
#endif
{<API key>, ARRAY_SIZE(<API key>)},
{<API key>, ARRAY_SIZE(<API key>)},
#ifdef <API key>
{<API key>, ARRAY_SIZE(<API key>)},
#endif
#ifdef CONFIG_LGE_IRDA
{<API key>, ARRAY_SIZE(<API key>)},
#endif
{<API key>, ARRAY_SIZE(<API key>)},
{msm8x60_sdc_configs, ARRAY_SIZE(msm8x60_sdc_configs)},
{msm8x60_snd_configs, ARRAY_SIZE(msm8x60_snd_configs)},
{<API key>, ARRAY_SIZE(<API key>)},
{<API key>, ARRAY_SIZE(<API key>)},
{<API key>, ARRAY_SIZE(<API key>)},
{<API key>, ARRAY_SIZE(<API key>)},
{<API key>, ARRAY_SIZE(<API key>)},
{<API key>, ARRAY_SIZE(<API key>)},
#ifdef CONFIG_LGE_AUDIO
{<API key>, ARRAY_SIZE(<API key>)},
#endif
#if defined(CONFIG_LGE_FELICA)
{<API key>, ARRAY_SIZE(<API key>)},
#endif
#if defined(<API key>)
{<API key>, ARRAY_SIZE(<API key>)},
#endif
{NULL, 0},
};
void __init <API key>(struct msm_gpiomux_configs *cfgs)
{
int rc;
rc = msm_gpiomux_init(NR_GPIO_IRQS);
if (rc) {
pr_err("%s failure: %d\n", __func__, rc);
return;
}
while (cfgs->cfg) {
msm_gpiomux_install(cfgs->cfg, cfgs->ncfg);
++cfgs;
}
}
|
/* { dg-final { <API key> "**" "" "-DCHECK_ASM" } } */
#include "test_sve_acle.h"
/*
** <API key>:
** sqdmlalt z0\.d, z4\.s, z5\.s\[0\]
** ret
*/
TEST_DUAL_Z (<API key>, svint64_t, svint32_t,
z0 = svqdmlalt_lane_s64 (z0, z4, z5, 0),
z0 = svqdmlalt_lane (z0, z4, z5, 0))
/*
** <API key>:
** mov (z[0-9]+)\.d, z0\.d
** movprfx z0, z4
** sqdmlalt z0\.d, \1\.s, z1\.s\[0\]
** ret
*/
TEST_DUAL_Z_REV (<API key>, svint64_t, svint32_t,
z0_res = svqdmlalt_lane_s64 (z4, z0, z1, 0),
z0_res = svqdmlalt_lane (z4, z0, z1, 0))
/*
** <API key>:
** mov (z[0-9]+)\.d, z0\.d
** movprfx z0, z4
** sqdmlalt z0\.d, z1\.s, \1\.s\[0\]
** ret
*/
TEST_DUAL_Z_REV (<API key>, svint64_t, svint32_t,
z0_res = svqdmlalt_lane_s64 (z4, z1, z0, 0),
z0_res = svqdmlalt_lane (z4, z1, z0, 0))
/*
** <API key>:
** movprfx z0, z1
** sqdmlalt z0\.d, z4\.s, z5\.s\[0\]
** ret
*/
TEST_DUAL_Z (<API key>, svint64_t, svint32_t,
z0 = svqdmlalt_lane_s64 (z1, z4, z5, 0),
z0 = svqdmlalt_lane (z1, z4, z5, 0))
/*
** <API key>:
** str d15, \[sp, -16\]!
** sqdmlalt z0\.d, z1\.s, z15\.s\[1\]
** ldr d15, \[sp\], 16
** ret
*/
TEST_DUAL_LANE_REG (<API key>, svint64_t, svint32_t, z15,
z0 = svqdmlalt_lane_s64 (z0, z1, z15, 1),
z0 = svqdmlalt_lane (z0, z1, z15, 1))
/*
** <API key>:
** mov (z[0-9]|z1[0-5])\.d, z16\.d
** sqdmlalt z0\.d, z1\.s, \1\.s\[1\]
** ret
*/
TEST_DUAL_LANE_REG (<API key>, svint64_t, svint32_t, z16,
z0 = svqdmlalt_lane_s64 (z0, z1, z16, 1),
z0 = svqdmlalt_lane (z0, z1, z16, 1))
|
#include <linux/module.h>
#include <linux/net.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <net/af_rxrpc.h>
#include "ar-internal.h"
static void <API key>(struct work_struct *work);
static LIST_HEAD(rxrpc_transports);
static DEFINE_RWLOCK(<API key>);
static unsigned long <API key> = 3600 * 24;
static <API key>(<API key>, <API key>);
/*
* allocate a new transport session manager
*/
static struct rxrpc_transport *<API key>(struct rxrpc_local *local,
struct rxrpc_peer *peer,
gfp_t gfp)
{
struct rxrpc_transport *trans;
_enter("");
trans = kzalloc(sizeof(struct rxrpc_transport), gfp);
if (trans) {
trans->local = local;
trans->peer = peer;
INIT_LIST_HEAD(&trans->link);
trans->bundles = RB_ROOT;
trans->client_conns = RB_ROOT;
trans->server_conns = RB_ROOT;
skb_queue_head_init(&trans->error_queue);
spin_lock_init(&trans->client_lock);
rwlock_init(&trans->conn_lock);
atomic_set(&trans->usage, 1);
trans->debug_id = <API key>(&rxrpc_debug_id);
if (peer->srx.transport.family == AF_INET) {
switch (peer->srx.transport_type) {
case SOCK_DGRAM:
INIT_WORK(&trans->error_handler,
<API key>);
break;
default:
BUG();
break;
}
} else {
BUG();
}
}
_leave(" = %p", trans);
return trans;
}
/*
* obtain a transport session for the nominated endpoints
*/
struct rxrpc_transport *rxrpc_get_transport(struct rxrpc_local *local,
struct rxrpc_peer *peer,
gfp_t gfp)
{
struct rxrpc_transport *trans, *candidate;
const char *new = "old";
int usage;
_enter("{%pI4+%hu},{%pI4+%hu},",
&local->srx.transport.sin.sin_addr,
ntohs(local->srx.transport.sin.sin_port),
&peer->srx.transport.sin.sin_addr,
ntohs(peer->srx.transport.sin.sin_port));
/* search the transport list first */
read_lock_bh(&<API key>);
list_for_each_entry(trans, &rxrpc_transports, link) {
if (trans->local == local && trans->peer == peer)
goto <API key>;
}
read_unlock_bh(&<API key>);
/* not yet present - create a candidate for a new record and then
* redo the search */
candidate = <API key>(local, peer, gfp);
if (!candidate) {
_leave(" = -ENOMEM");
return ERR_PTR(-ENOMEM);
}
write_lock_bh(&<API key>);
list_for_each_entry(trans, &rxrpc_transports, link) {
if (trans->local == local && trans->peer == peer)
goto found_extant_second;
}
/* we can now add the new candidate to the list */
trans = candidate;
candidate = NULL;
usage = atomic_read(&trans->usage);
rxrpc_get_local(trans->local);
atomic_inc(&trans->peer->usage);
list_add_tail(&trans->link, &rxrpc_transports);
write_unlock_bh(&<API key>);
new = "new";
success:
_net("TRANSPORT %s %d local %d -> peer %d",
new,
trans->debug_id,
trans->local->debug_id,
trans->peer->debug_id);
_leave(" = %p {u=%d}", trans, usage);
return trans;
/* we found the transport in the list immediately */
<API key>:
usage = atomic_inc_return(&trans->usage);
read_unlock_bh(&<API key>);
goto success;
/* we found the transport on the second time through the list */
found_extant_second:
usage = atomic_inc_return(&trans->usage);
write_unlock_bh(&<API key>);
kfree(candidate);
goto success;
}
/*
* find the transport connecting two endpoints
*/
struct rxrpc_transport *<API key>(struct rxrpc_local *local,
struct rxrpc_peer *peer)
{
struct rxrpc_transport *trans;
_enter("{%pI4+%hu},{%pI4+%hu},",
&local->srx.transport.sin.sin_addr,
ntohs(local->srx.transport.sin.sin_port),
&peer->srx.transport.sin.sin_addr,
ntohs(peer->srx.transport.sin.sin_port));
/* search the transport list */
read_lock_bh(&<API key>);
list_for_each_entry(trans, &rxrpc_transports, link) {
if (trans->local == local && trans->peer == peer)
goto <API key>;
}
read_unlock_bh(&<API key>);
_leave(" = NULL");
return NULL;
<API key>:
atomic_inc(&trans->usage);
read_unlock_bh(&<API key>);
_leave(" = %p", trans);
return trans;
}
/*
* release a transport session
*/
void rxrpc_put_transport(struct rxrpc_transport *trans)
{
_enter("%p{u=%d}", trans, atomic_read(&trans->usage));
ASSERTCMP(atomic_read(&trans->usage), >, 0);
trans->put_time = get_seconds();
if (unlikely(atomic_dec_and_test(&trans->usage))) {
_debug("zombie");
/* let the reaper determine the timeout to avoid a race with
* overextending the timeout if the reaper is running at the
* same time */
<API key>(&<API key>, 0);
}
_leave("");
}
/*
* clean up a transport session
*/
static void <API key>(struct rxrpc_transport *trans)
{
_net("DESTROY TRANS %d", trans->debug_id);
rxrpc_purge_queue(&trans->error_queue);
rxrpc_put_local(trans->local);
rxrpc_put_peer(trans->peer);
kfree(trans);
}
/*
* reap dead transports that have passed their expiry date
*/
static void <API key>(struct work_struct *work)
{
struct rxrpc_transport *trans, *_p;
unsigned long now, earliest, reap_time;
LIST_HEAD(graveyard);
_enter("");
now = get_seconds();
earliest = ULONG_MAX;
/* extract all the transports that have been dead too long */
write_lock_bh(&<API key>);
<API key>(trans, _p, &rxrpc_transports, link) {
_debug("reap TRANS %d { u=%d t=%ld }",
trans->debug_id, atomic_read(&trans->usage),
(long) now - (long) trans->put_time);
if (likely(atomic_read(&trans->usage) > 0))
continue;
reap_time = trans->put_time + <API key>;
if (reap_time <= now)
list_move_tail(&trans->link, &graveyard);
else if (reap_time < earliest)
earliest = reap_time;
}
write_unlock_bh(&<API key>);
if (earliest != ULONG_MAX) {
_debug("reschedule reaper %ld", (long) earliest - now);
ASSERTCMP(earliest, >, now);
<API key>(&<API key>,
(earliest - now) * HZ);
}
/* then destroy all those pulled out */
while (!list_empty(&graveyard)) {
trans = list_entry(graveyard.next, struct rxrpc_transport,
link);
list_del_init(&trans->link);
ASSERTCMP(atomic_read(&trans->usage), ==, 0);
<API key>(trans);
}
_leave("");
}
/*
* preemptively destroy all the transport session records rather than waiting
* for them to time out
*/
void __exit <API key>(void)
{
_enter("");
<API key> = 0;
cancel_delayed_work(&<API key>);
<API key>(&<API key>, 0);
_leave("");
}
|
// file name : depends_dlg.h
// F i l e
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
#ifndef __depends_dlg__
#define __depends_dlg__
#include <wx/wx.h>
#include <wx/choicebk.h>
#include <wx/statline.h>
#include <wx/button.h>
Class DependenciesDlg
class DependenciesDlg : public wxDialog
{
private:
protected:
wxChoicebook* m_book;
wxStaticLine* m_staticline1;
wxButton* m_buttonOK;
wxButton* m_buttonCancel;
wxString m_projectName;
void Init();
void DoSelectProject();
virtual void OnButtonOK(wxCommandEvent& event);
virtual void OnButtonCancel(wxCommandEvent& event);
public:
DependenciesDlg(wxWindow* parent,
const wxString& projectName,
int id = wxID_ANY,
wxString title = _("Build Order"),
wxPoint pos = wxDefaultPosition,
wxSize size = wxSize(700, 450),
int style = <API key> | wxRESIZE_BORDER);
virtual ~DependenciesDlg();
};
#endif //__depends_dlg__
|
package org.graalvm.compiler.jtt.optimize;
import org.junit.Test;
import org.graalvm.compiler.jtt.JTTTest;
/*
* Test case for local load elimination. It makes sure that the second field store is not eliminated, because
* it is recognized that the first store changes the field "field1", so it is no longer guaranteed that it
* has its default value 0.
*/
public class LLE_01 extends JTTTest {
private static class TestClass {
int field1;
}
public static int test() {
TestClass o = new TestClass();
o.field1 = 1;
o.field1 = 0;
return o.field1;
}
@Test
public void run0() throws Throwable {
runTest("test");
}
}
|
<?php
namespace TYPO3\CMS\Core\Log\Writer;
/**
* Abstract implementation of a log writer
*
* @author Ingo Renner <ingo@typo3.org>
*/
abstract class AbstractWriter implements \TYPO3\CMS\Core\Log\Writer\WriterInterface {
/**
* Constructs this log writer
*
* @param array $options Configuration options - depends on the actual log writer
* @throws \<API key>
*/
public function __construct(array $options = array()) {
foreach ($options as $optionKey => $optionValue) {
$methodName = 'set' . ucfirst($optionKey);
if (method_exists($this, $methodName)) {
$this->{$methodName}($optionValue);
} else {
throw new \<API key>('Invalid log writer option "' . $optionKey . '" for log writer of type "' . get_class($this) . '"', 1321696152);
}
}
}
}
|
/* the viewport to use */
wxUint32 renderState; /* render state */
wxUint32 textureState; /* texture state */
wxUint8 triCount; /* how many tris? */
wxUint8 vtxV0; /* where to load verts? */
wxUint8 vtxCount; /* how many verts? */
wxUint32 rdpCmds; /* ptr (segment address) to RDP DL */
wxUint8 flag, v2, v1, v0; /* flag is which one for flat shade */
|
package org.graalvm.compiler.hotspot.replacements;
import java.lang.reflect.Method;
import java.util.EnumMap;
import org.graalvm.compiler.api.directives.GraalDirectives;
import org.graalvm.compiler.api.replacements.Snippet;
import org.graalvm.compiler.debug.GraalError;
import org.graalvm.compiler.hotspot.replacements.arraycopy.ArrayCopyCallNode;
import org.graalvm.compiler.nodes.java.DynamicNewArrayNode;
import org.graalvm.compiler.nodes.java.NewArrayNode;
import org.graalvm.compiler.replacements.Snippets;
import jdk.vm.ci.meta.JavaKind;
public class ObjectCloneSnippets implements Snippets {
public static final EnumMap<JavaKind, Method> arrayCloneMethods = new EnumMap<>(JavaKind.class);
static {
arrayCloneMethods.put(JavaKind.Boolean, getCloneMethod("booleanArrayClone", boolean[].class));
arrayCloneMethods.put(JavaKind.Byte, getCloneMethod("byteArrayClone", byte[].class));
arrayCloneMethods.put(JavaKind.Char, getCloneMethod("charArrayClone", char[].class));
arrayCloneMethods.put(JavaKind.Short, getCloneMethod("shortArrayClone", short[].class));
arrayCloneMethods.put(JavaKind.Int, getCloneMethod("intArrayClone", int[].class));
arrayCloneMethods.put(JavaKind.Float, getCloneMethod("floatArrayClone", float[].class));
arrayCloneMethods.put(JavaKind.Long, getCloneMethod("longArrayClone", long[].class));
arrayCloneMethods.put(JavaKind.Double, getCloneMethod("doubleArrayClone", double[].class));
arrayCloneMethods.put(JavaKind.Object, getCloneMethod("objectArrayClone", Object[].class));
}
private static Method getCloneMethod(String name, Class<?> param) {
try {
return ObjectCloneSnippets.class.getDeclaredMethod(name, param);
} catch (SecurityException | <API key> e) {
throw new GraalError(e);
}
}
@Snippet
public static boolean[] booleanArrayClone(boolean[] src) {
boolean[] result = (boolean[]) NewArrayNode.<API key>(Boolean.TYPE, src.length);
ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Boolean);
return result;
}
@Snippet
public static byte[] byteArrayClone(byte[] src) {
byte[] result = (byte[]) NewArrayNode.<API key>(Byte.TYPE, src.length);
ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Byte);
return result;
}
@Snippet
public static short[] shortArrayClone(short[] src) {
short[] result = (short[]) NewArrayNode.<API key>(Short.TYPE, src.length);
ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Short);
return result;
}
@Snippet
public static char[] charArrayClone(char[] src) {
char[] result = (char[]) NewArrayNode.<API key>(Character.TYPE, src.length);
ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Char);
return result;
}
@Snippet
public static int[] intArrayClone(int[] src) {
int[] result = (int[]) NewArrayNode.<API key>(Integer.TYPE, src.length);
ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Int);
return result;
}
@Snippet
public static float[] floatArrayClone(float[] src) {
float[] result = (float[]) NewArrayNode.<API key>(Float.TYPE, src.length);
ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Float);
return result;
}
@Snippet
public static long[] longArrayClone(long[] src) {
long[] result = (long[]) NewArrayNode.<API key>(Long.TYPE, src.length);
ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Long);
return result;
}
@Snippet
public static double[] doubleArrayClone(double[] src) {
double[] result = (double[]) NewArrayNode.<API key>(Double.TYPE, src.length);
ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Double);
return result;
}
@Snippet
public static Object[] objectArrayClone(Object[] src) {
/* Since this snippet is lowered early the array must be initialized */
Object[] result = (Object[]) DynamicNewArrayNode.newArray(GraalDirectives.guardingNonNull(src.getClass().getComponentType()), src.length, JavaKind.Object);
ArrayCopyCallNode.<API key>(src, 0, result, 0, src.length, JavaKind.Object);
return result;
}
}
|
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/gpio.h>
#include <linux/mfd/pm8xxx/pm8921.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <sound/pcm.h>
#include <sound/jack.h>
#include <asm/mach-types.h>
#include <mach/socinfo.h>
#include <linux/mfd/wcd9xxx/core.h>
#include "../../../sound/soc/codecs/wcd9310.h"
#include "../sound/soc/msm/msm-pcm-routing.h"
#include "board-elite.h"
#include <mach/cable_detect.h>
#include <mach/board.h>
#define MSM_SPK_ON 1
#define MSM_SPK_OFF 0
#define <API key> 2
#define <API key> 4
#define SAMPLE_RATE_8KHZ 8000
#define SAMPLE_RATE_16KHZ 16000
#define BOTTOM_SPK_AMP_POS 0x1
#define BOTTOM_SPK_AMP_NEG 0x2
#define TOP_SPK_AMP_POS 0x4
#define TOP_SPK_AMP_NEG 0x8
#define DOCK_SPK_AMP_POS 0x10
#define DOCK_SPK_AMP_NEG 0x20
#define GPIO_AUX_PCM_DOUT 63
#define GPIO_AUX_PCM_DIN 64
#define GPIO_AUX_PCM_SYNC 65
#define GPIO_AUX_PCM_CLK 66
#define TABLA_EXT_CLK_RATE 12288000
#define <API key> (<API key>(3))
#define top_spk_pamp_gpio (<API key>(19))
#define <API key> (<API key>(18))
#define DOCK_SPK_PAMP_GPIO (<API key>(1))
#define USB_ID_ADC_GPIO (<API key>(4))
static int msm_spk_control;
static int <API key>;
static int <API key>;
static int <API key>;
static int msm_slim_0_rx_ch = 1;
static int msm_slim_0_tx_ch = 1;
static int msm_btsco_rate = SAMPLE_RATE_8KHZ;
static int msm_btsco_ch = 1;
static int msm_auxpcm_rate = SAMPLE_RATE_8KHZ;
static int <API key>;
static struct clk *codec_clk;
static int clk_users;
extern void <API key>(void);
static struct snd_soc_jack hs_jack;
static struct snd_soc_jack button_jack;
static int <API key>(struct snd_soc_codec *codec, int enable,
bool dapm);
extern void <API key>(void);
static struct mutex cdc_mclk_mutex;
static void <API key>(u32);
static void <API key>(enum usb_connect_type online)
{
if (<API key>() != <API key>) {
pr_debug("accessory is not AUDIO_DOCK\n");
return;
}
switch(online) {
case CONNECT_TYPE_NONE:
pr_debug("%s, VBUS is removed\n", __func__);
<API key>(DOCK_SPK_AMP_POS|DOCK_SPK_AMP_NEG);
<API key>();
break;
default:
break;
}
return;
}
static struct mutex audio_notifier_lock;
static struct <API key> audio_dock_notifier =
{
.name = "elite_audio_8960",
.func = <API key>,
};
static void <API key>(u32 spk_amp_gpio)
{
int ret = 0;
struct pm_gpio param = {
.direction = PM_GPIO_DIR_OUT,
.output_buffer = <API key>,
.output_value = 1,
.pull = PM_GPIO_PULL_NO,
.vin_sel = PM_GPIO_VIN_S4,
.out_strength = <API key>,
.function = PM_GPIO_FUNC_NORMAL,
};
if (spk_amp_gpio == <API key>) {
ret = gpio_request(<API key>, "BOTTOM_SPK_AMP");
if (ret) {
pr_err("%s: Error requesting BOTTOM SPK AMP GPIO %u\n",
__func__, <API key>);
return;
}
ret = pm8xxx_gpio_config(<API key>, ¶m);
if (ret)
pr_err("%s: Failed to configure Bottom Spk Ampl"
" gpio %u\n", __func__, <API key>);
else {
pr_debug("%s: enable Bottom spkr amp gpio\n", __func__);
<API key>(<API key>, 1);
}
} else if (spk_amp_gpio == top_spk_pamp_gpio) {
ret = gpio_request(top_spk_pamp_gpio, "TOP_SPK_AMP");
if (ret) {
pr_err("%s: Error requesting GPIO %d\n", __func__,
top_spk_pamp_gpio);
return;
}
ret = pm8xxx_gpio_config(top_spk_pamp_gpio, ¶m);
if (ret)
pr_err("%s: Failed to configure Top Spk Ampl"
" gpio %u\n", __func__, top_spk_pamp_gpio);
else {
pr_debug("%s: enable Top spkr amp gpio\n", __func__);
<API key>(top_spk_pamp_gpio, 1);
}
} else if (spk_amp_gpio == DOCK_SPK_PAMP_GPIO) {
ret = gpio_request(DOCK_SPK_PAMP_GPIO, "DOCK_SPK_AMP");
if (ret) {
pr_err("%s: Error requesting GPIO %d\n", __func__,
DOCK_SPK_PAMP_GPIO);
return;
}
ret = pm8xxx_gpio_config(DOCK_SPK_PAMP_GPIO, ¶m);
if (ret)
pr_err("%s: Failed to configure Dock Spk Ampl"
" gpio %u\n", __func__, DOCK_SPK_PAMP_GPIO);
else {
pr_debug("%s: enable dock amp gpio\n", __func__);
<API key>(DOCK_SPK_PAMP_GPIO, 1);
}
ret = gpio_request(USB_ID_ADC_GPIO, "USB_ID_ADC");
if (ret) {
pr_err("%s: Error requesting USB_ID_ADC PMIC GPIO %u\n",
__func__, USB_ID_ADC_GPIO);
return;
}
ret = pm8xxx_gpio_config(USB_ID_ADC_GPIO, ¶m);
if (ret)
pr_err("%s: Failed to configure USB_ID_ADC PMIC"
" gpio %u\n", __func__, USB_ID_ADC_GPIO);
} else {
pr_err("%s: ERROR : Invalid External Speaker Ampl GPIO."
" gpio = %u\n", __func__, spk_amp_gpio);
return;
}
}
static void <API key>(u32 spk)
{
if (spk & (BOTTOM_SPK_AMP_POS | BOTTOM_SPK_AMP_NEG)) {
if ((<API key> & BOTTOM_SPK_AMP_POS) &&
(<API key> & BOTTOM_SPK_AMP_NEG)) {
pr_debug("%s() External Bottom Speaker Ampl already "
"turned on. spk = 0x%08x\n", __func__, spk);
return;
}
<API key> |= spk;
if ((<API key> & BOTTOM_SPK_AMP_POS) &&
(<API key> & BOTTOM_SPK_AMP_NEG)) {
<API key>(<API key>);
pr_debug("%s: slepping 4 ms after turning on external "
" Bottom Speaker Ampl\n", __func__);
usleep_range(4000, 4000);
}
} else if (spk & (TOP_SPK_AMP_POS | TOP_SPK_AMP_NEG)) {
if ((<API key> & TOP_SPK_AMP_POS) &&
(<API key> & TOP_SPK_AMP_NEG)) {
pr_debug("%s() External Top Speaker Ampl already"
"turned on. spk = 0x%08x\n", __func__, spk);
return;
}
<API key> |= spk;
if ((<API key> & TOP_SPK_AMP_POS) &&
(<API key> & TOP_SPK_AMP_NEG)) {
<API key>(top_spk_pamp_gpio);
pr_debug("%s: sleeping 4 ms after turning on "
" external HAC Ampl\n", __func__);
usleep_range(4000, 4000);
}
} else if (spk & (DOCK_SPK_AMP_POS | DOCK_SPK_AMP_NEG)) {
mutex_lock(&audio_notifier_lock);
if ((<API key> & DOCK_SPK_AMP_POS) &&
(<API key> & DOCK_SPK_AMP_NEG)) {
pr_debug("%s() External Dock Speaker Ampl already"
"turned on. spk = 0x%08x\n", __func__, spk);
return;
}
<API key> |= spk;
if ((<API key> & DOCK_SPK_AMP_POS) &&
(<API key> & DOCK_SPK_AMP_NEG)) {
<API key>(DOCK_SPK_PAMP_GPIO);
pr_debug("%s: sleeping 4 ms after turning on "
" external DOCK Ampl\n", __func__);
usleep_range(4000, 4000);
}
mutex_unlock(&audio_notifier_lock);
} else {
pr_err("%s: ERROR : Invalid External Speaker Ampl. spk = 0x%08x\n",
__func__, spk);
return;
}
}
static void <API key>(u32 spk)
{
struct pm_gpio param = {
.direction = PM_GPIO_DIR_IN,
.output_buffer = <API key>,
.pull = PM_GPIO_PULL_NO,
.vin_sel = PM_GPIO_VIN_S4,
.out_strength = <API key>,
.function = PM_GPIO_FUNC_NORMAL,
};
pr_debug("%s, spk = %d\n", __func__, spk);
if (spk & (BOTTOM_SPK_AMP_POS | BOTTOM_SPK_AMP_NEG)) {
if (!<API key>)
return;
<API key>(<API key>, 0);
gpio_free(<API key>);
<API key> = 0;
pr_debug("%s: sleeping 4 ms after turning off external Bottom"
" Speaker Ampl\n", __func__);
usleep_range(4000, 4000);
} else if (spk & (TOP_SPK_AMP_POS | TOP_SPK_AMP_NEG)) {
if (!<API key>)
return;
<API key>(top_spk_pamp_gpio, 0);
gpio_free(top_spk_pamp_gpio);
<API key> = 0;
pr_debug("%s: sleeping 4 ms after turning off external"
" HAC Ampl\n", __func__);
usleep_range(4000, 4000);
} else if (spk & (DOCK_SPK_AMP_POS | DOCK_SPK_AMP_NEG)) {
mutex_lock(&audio_notifier_lock);
if (!<API key>) {
mutex_unlock(&audio_notifier_lock);
return;
}
<API key>(DOCK_SPK_PAMP_GPIO);
gpio_free(DOCK_SPK_PAMP_GPIO);
<API key>(USB_ID_ADC_GPIO);
if (pm8xxx_gpio_config(USB_ID_ADC_GPIO, ¶m))
pr_err("%s: Failed to configure USB_ID_ADC PMIC"
" gpio %u\n", __func__, USB_ID_ADC_GPIO);
gpio_free(USB_ID_ADC_GPIO);
<API key> = 0;
mutex_unlock(&audio_notifier_lock);
pr_debug("%s: sleeping 4 ms after turning off external"
" DOCK Ampl\n", __func__);
usleep_range(4000, 4000);
} else {
pr_err("%s: ERROR : Invalid Ext Spk Ampl. spk = 0x%08x\n",
__func__, spk);
return;
}
}
static void msm_ext_control(struct snd_soc_codec *codec)
{
struct <API key> *dapm = &codec->dapm;
mutex_lock(&dapm->codec->mutex);
pr_debug("%s: msm_spk_control = %d", __func__, msm_spk_control);
if (msm_spk_control == MSM_SPK_ON) {
<API key>(dapm, "Ext Spk Bottom Pos");
<API key>(dapm, "Ext Spk Bottom Neg");
<API key>(dapm, "Ext Spk Top Pos");
<API key>(dapm, "Ext Spk Top Neg");
<API key>(dapm, "Dock Spk Pos");
<API key>(dapm, "Dock Spk Neg");
} else {
<API key>(dapm, "Ext Spk Bottom Pos");
<API key>(dapm, "Ext Spk Bottom Neg");
<API key>(dapm, "Ext Spk Top Pos");
<API key>(dapm, "Ext Spk Top Neg");
<API key>(dapm, "Dock Spk Pos");
<API key>(dapm, "Dock Spk Neg");
}
snd_soc_dapm_sync(dapm);
mutex_unlock(&dapm->codec->mutex);
}
static int msm_get_spk(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm_spk_control = %d", __func__, msm_spk_control);
ucontrol->value.integer.value[0] = msm_spk_control;
return 0;
}
static int msm_set_spk(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
pr_debug("%s()\n", __func__);
if (msm_spk_control == ucontrol->value.integer.value[0])
return 0;
msm_spk_control = ucontrol->value.integer.value[0];
msm_ext_control(codec);
return 1;
}
static int msm_spkramp_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *k, int event)
{
pr_debug("%s() %x\n", __func__, <API key>(event));
if (<API key>(event)) {
if (!strncmp(w->name, "Ext Spk Bottom Pos", 18))
<API key>(BOTTOM_SPK_AMP_POS);
else if (!strncmp(w->name, "Ext Spk Bottom Neg", 18))
<API key>(BOTTOM_SPK_AMP_NEG);
else if (!strncmp(w->name, "Ext Spk Top Pos", 15))
<API key>(TOP_SPK_AMP_POS);
else if (!strncmp(w->name, "Ext Spk Top Neg", 15))
<API key>(TOP_SPK_AMP_NEG);
else if (!strncmp(w->name, "Dock Spk Pos", 12))
<API key>(DOCK_SPK_AMP_POS);
else if (!strncmp(w->name, "Dock Spk Neg", 12))
<API key>(DOCK_SPK_AMP_NEG);
else {
pr_err("%s() Invalid Speaker Widget = %s\n",
__func__, w->name);
return -EINVAL;
}
} else {
if (!strncmp(w->name, "Ext Spk Bottom Pos", 18))
<API key>(BOTTOM_SPK_AMP_POS);
else if (!strncmp(w->name, "Ext Spk Bottom Neg", 18))
<API key>(BOTTOM_SPK_AMP_NEG);
else if (!strncmp(w->name, "Ext Spk Top Pos", 15))
<API key>(TOP_SPK_AMP_POS);
else if (!strncmp(w->name, "Ext Spk Top Neg", 15))
<API key>(TOP_SPK_AMP_NEG);
else if (!strncmp(w->name, "Dock Spk Pos", 12))
<API key>(DOCK_SPK_AMP_POS);
else if (!strncmp(w->name, "Dock Spk Neg", 12))
<API key>(DOCK_SPK_AMP_NEG);
else {
pr_err("%s() Invalid Speaker Widget = %s\n",
__func__, w->name);
return -EINVAL;
}
}
return 0;
}
static int <API key>(struct snd_soc_codec *codec, int enable,
bool dapm)
{
int r = 0;
pr_debug("%s: enable = %d\n", __func__, enable);
mutex_lock(&cdc_mclk_mutex);
if (enable) {
clk_users++;
pr_debug("%s: clk_users = %d\n", __func__, clk_users);
if (clk_users == 1) {
if (codec_clk) {
clk_set_rate(codec_clk, TABLA_EXT_CLK_RATE);
clk_prepare_enable(codec_clk);
tabla_mclk_enable(codec, 1, dapm);
} else {
pr_err("%s: Error setting Tabla MCLK\n",
__func__);
clk_users
r = -EINVAL;
}
}
} else {
if (clk_users > 0) {
clk_users
pr_debug("%s: clk_users = %d\n", __func__, clk_users);
if (clk_users == 0) {
pr_debug("%s: disabling MCLK. clk_users = %d\n",
__func__, clk_users);
tabla_mclk_enable(codec, 0, dapm);
<API key>(codec_clk);
}
} else {
pr_err("%s: Error releasing Tabla MCLK\n", __func__);
r = -EINVAL;
}
}
mutex_unlock(&cdc_mclk_mutex);
return r;
}
static int msm_mclk_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
pr_debug("%s: event = %d\n", __func__, event);
switch (event) {
case <API key>:
return <API key>(w->codec, 1, true);
case <API key>:
return <API key>(w->codec, 0, true);
}
return 0;
}
enum {
RX_SWITCH_INDEX = 0,
TX_SWITCH_INDEX,
SWITCH_MAX,
};
static const struct snd_kcontrol_new <API key> =
SOC_DAPM_SINGLE("Switch", RX_SWITCH_INDEX, 0, 1, 0);
static const struct snd_kcontrol_new <API key> =
SOC_DAPM_SINGLE("Switch", RX_SWITCH_INDEX, 0, 1, 0);
static const struct snd_kcontrol_new <API key> =
SOC_DAPM_SINGLE("Switch", RX_SWITCH_INDEX, 0, 1, 0);
static const struct snd_kcontrol_new <API key> =
SOC_DAPM_SINGLE("Switch", TX_SWITCH_INDEX, 0, 1, 0);
static const struct snd_soc_dapm_widget elite_dapm_widgets[] = {
SND_SOC_DAPM_MIXER("Lineout Mixer", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SPK AMP EN", SND_SOC_NOPM, 0, 0, &<API key>, 1),
SND_SOC_DAPM_MIXER("HAC AMP EN", SND_SOC_NOPM, 0, 0, &<API key>, 1),
SND_SOC_DAPM_MIXER("DOCK AMP EN", SND_SOC_NOPM, 0, 0, &<API key>, 1),
SND_SOC_DAPM_MIXER("DUAL MICBIAS", SND_SOC_NOPM, 0, 0, &<API key>, 1),
};
static const struct snd_soc_dapm_widget msm_dapm_widgets[] = {
SND_SOC_DAPM_SUPPLY("MCLK", SND_SOC_NOPM, 0, 0,
msm_mclk_event, <API key> | <API key>),
SND_SOC_DAPM_SPK("Ext Spk Bottom Pos", msm_spkramp_event),
SND_SOC_DAPM_SPK("Ext Spk Bottom Neg", msm_spkramp_event),
SND_SOC_DAPM_SPK("Ext Spk Top Pos", msm_spkramp_event),
SND_SOC_DAPM_SPK("Ext Spk Top Neg", msm_spkramp_event),
SND_SOC_DAPM_SPK("Dock Spk Pos", msm_spkramp_event),
SND_SOC_DAPM_SPK("Dock Spk Neg", msm_spkramp_event),
SND_SOC_DAPM_MIC("Handset Mic", NULL),
SND_SOC_DAPM_MIC("Headset Mic", NULL),
SND_SOC_DAPM_MIC("Back Mic", NULL),
SND_SOC_DAPM_MIC("Digital Mic1", NULL),
SND_SOC_DAPM_MIC("ANCRight Headset Mic", NULL),
SND_SOC_DAPM_MIC("ANCLeft Headset Mic", NULL),
SND_SOC_DAPM_MIC("Digital Mic1", NULL),
SND_SOC_DAPM_MIC("Digital Mic2", NULL),
SND_SOC_DAPM_MIC("Digital Mic3", NULL),
SND_SOC_DAPM_MIC("Digital Mic4", NULL),
SND_SOC_DAPM_MIC("Digital Mic5", NULL),
SND_SOC_DAPM_MIC("Digital Mic6", NULL),
};
static const struct snd_soc_dapm_route tabla_1_x_audio_map[] = {
{"Lineout Mixer", NULL, "LINEOUT2"},
{"Lineout Mixer", NULL, "LINEOUT1"},
};
static const struct snd_soc_dapm_route tabla_2_x_audio_map[] = {
{"Lineout Mixer", NULL, "LINEOUT3"},
{"Lineout Mixer", NULL, "LINEOUT1"},
};
static const struct snd_soc_dapm_route common_audio_map[] = {
{"RX_BIAS", NULL, "MCLK"},
{"LDO_H", NULL, "MCLK"},
{"Ext Spk Bottom Pos", NULL, "SPK AMP EN"},
{"Ext Spk Bottom Neg", NULL, "SPK AMP EN"},
{"SPK AMP EN", "Switch", "Lineout Mixer"},
{"Ext Spk Top Pos", NULL, "HAC AMP EN"},
{"Ext Spk Top Neg", NULL, "HAC AMP EN"},
{"HAC AMP EN", "Switch", "Lineout Mixer"},
{"Dock Spk Pos", NULL, "DOCK AMP EN"},
{"Dock Spk Neg", NULL, "DOCK AMP EN"},
{"DOCK AMP EN", "Switch", "Lineout Mixer"},
{"AMIC1", NULL, "DUAL MICBIAS"},
{"DUAL MICBIAS", NULL, "MIC BIAS1 External"},
{"MIC BIAS1 External", NULL, "Handset Mic"},
{"DUAL MICBIAS", "Switch", "MIC BIAS3 External"},
{"AMIC2", NULL, "MIC BIAS2 External"},
{"MIC BIAS2 External", NULL, "Headset Mic"},
{"AMIC3", NULL, "MIC BIAS3 External"},
{"MIC BIAS3 External", NULL, "Back Mic"},
{"HEADPHONE", NULL, "LDO_H"},
};
static const char *spk_function[] = {"Off", "On"};
static const char *slim0_rx_ch_text[] = {"One", "Two"};
static const char *slim0_tx_ch_text[] = {"One", "Two", "Three", "Four"};
static const struct soc_enum msm_enum[] = {
SOC_ENUM_SINGLE_EXT(2, spk_function),
SOC_ENUM_SINGLE_EXT(2, slim0_rx_ch_text),
SOC_ENUM_SINGLE_EXT(4, slim0_tx_ch_text),
};
static const char *stereo_mic_voice[] = {"Off", "On"};
static const struct soc_enum elite_msm_enum[] = {
SOC_ENUM_SINGLE_EXT(2, stereo_mic_voice),
};
static const char *btsco_rate_text[] = {"8000", "16000"};
static const struct soc_enum msm_btsco_enum[] = {
SOC_ENUM_SINGLE_EXT(2, btsco_rate_text),
};
static const char *auxpcm_rate_text[] = {"rate_8000", "rate_16000"};
static const struct soc_enum msm_auxpcm_enum[] = {
SOC_ENUM_SINGLE_EXT(2, auxpcm_rate_text),
};
static int <API key>(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm_slim_0_rx_ch = %d\n", __func__,
msm_slim_0_rx_ch);
ucontrol->value.integer.value[0] = msm_slim_0_rx_ch - 1;
return 0;
}
static int <API key>(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
msm_slim_0_rx_ch = ucontrol->value.integer.value[0] + 1;
pr_debug("%s: msm_slim_0_rx_ch = %d\n", __func__,
msm_slim_0_rx_ch);
return 1;
}
static int <API key>(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm_slim_0_tx_ch = %d\n", __func__,
msm_slim_0_tx_ch);
ucontrol->value.integer.value[0] = msm_slim_0_tx_ch - 1;
return 0;
}
static int <API key>(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
msm_slim_0_tx_ch = ucontrol->value.integer.value[0] + 1;
pr_debug("%s: msm_slim_0_tx_ch = %d\n", __func__,
msm_slim_0_tx_ch);
return 1;
}
static int <API key>(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: <API key> = %d\n", __func__,
<API key>);
ucontrol->value.integer.value[0] = <API key>;
return 0;
}
static int <API key>(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int ret = 0;
struct pm_gpio param = {
.direction = PM_GPIO_DIR_OUT,
.output_buffer = <API key>,
.output_value = 1,
.pull = PM_GPIO_PULL_NO,
.vin_sel = PM_GPIO_VIN_L17,
.out_strength = <API key>,
.function = PM_GPIO_FUNC_NORMAL,
};
if (<API key> == ucontrol->value.integer.value[0])
return 0;
<API key> = ucontrol->value.integer.value[0];
pr_debug("%s: <API key> = %d\n", __func__,
<API key>);
switch (ucontrol->value.integer.value[0]) {
case 0:
<API key>(<API key>, 1);
gpio_free(<API key>);
break;
case 1:
ret = gpio_request(<API key>, "A1028_SWITCH");
if (ret) {
pr_err("%s: Failed to request gpio %d\n", __func__,
<API key>);
return ret;
}
ret = pm8xxx_gpio_config(<API key>, ¶m);
if (ret)
pr_err("%s: Failed to configure gpio %d\n", __func__,
<API key>);
else
<API key>(<API key>, 0);
break;
}
return ret;
}
static int msm_btsco_rate_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm_btsco_rate = %d", __func__, msm_btsco_rate);
ucontrol->value.integer.value[0] = msm_btsco_rate;
return 0;
}
static int msm_btsco_rate_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
switch (ucontrol->value.integer.value[0]) {
case 0:
msm_btsco_rate = SAMPLE_RATE_8KHZ;
break;
case 1:
msm_btsco_rate = SAMPLE_RATE_16KHZ;
break;
default:
msm_btsco_rate = SAMPLE_RATE_8KHZ;
break;
}
pr_debug("%s: msm_btsco_rate = %d\n", __func__, msm_btsco_rate);
return 0;
}
static int msm_auxpcm_rate_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm_auxpcm_rate = %d", __func__,
msm_auxpcm_rate);
ucontrol->value.integer.value[0] = msm_auxpcm_rate;
return 0;
}
static int msm_auxpcm_rate_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
switch (ucontrol->value.integer.value[0]) {
case 0:
msm_auxpcm_rate = SAMPLE_RATE_8KHZ;
break;
case 1:
msm_auxpcm_rate = SAMPLE_RATE_16KHZ;
break;
default:
msm_auxpcm_rate = SAMPLE_RATE_8KHZ;
break;
}
pr_debug("%s: msm_auxpcm_rate = %d"
"ucontrol->value.integer.value[0] = %d\n", __func__,
msm_auxpcm_rate,
(int)ucontrol->value.integer.value[0]);
return 0;
}
static const struct snd_kcontrol_new tabla_msm_controls[] = {
SOC_ENUM_EXT("Speaker Function", msm_enum[0], msm_get_spk,
msm_set_spk),
SOC_ENUM_EXT("SLIM_0_RX Channels", msm_enum[1],
<API key>, <API key>),
SOC_ENUM_EXT("SLIM_0_TX Channels", msm_enum[2],
<API key>, <API key>),
SOC_ENUM_EXT("Internal BTSCO SampleRate", msm_btsco_enum[0],
msm_btsco_rate_get, msm_btsco_rate_put),
SOC_ENUM_EXT("AUX PCM SampleRate", msm_auxpcm_enum[0],
msm_auxpcm_rate_get, msm_auxpcm_rate_put),
SOC_ENUM_EXT("Stereo Selection", elite_msm_enum[0], <API key>,
<API key>),
};
static int msm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
int ret = 0;
unsigned int rx_ch[SLIM_MAX_RX_PORTS], tx_ch[SLIM_MAX_TX_PORTS];
unsigned int rx_ch_cnt = 0, tx_ch_cnt = 0;
if (substream->stream == <API key>) {
pr_debug("%s: %s rx_dai_id = %d num_ch = %d\n", __func__,
codec_dai->name, codec_dai->id, msm_slim_0_rx_ch);
ret = <API key>(codec_dai,
&tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch);
if (ret < 0) {
pr_err("%s: failed to get codec chan map\n", __func__);
goto end;
}
ret = <API key>(cpu_dai, 0, 0,
msm_slim_0_rx_ch, rx_ch);
if (ret < 0) {
pr_err("%s: failed to set cpu chan map\n", __func__);
goto end;
}
ret = <API key>(codec_dai, 0, 0,
msm_slim_0_rx_ch, rx_ch);
if (ret < 0) {
pr_err("%s: failed to set codec channel map\n",
__func__);
goto end;
}
} else {
pr_debug("%s: %s tx_dai_id = %d num_ch = %d\n", __func__,
codec_dai->name, codec_dai->id, msm_slim_0_tx_ch);
ret = <API key>(codec_dai,
&tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch);
if (ret < 0) {
pr_err("%s: failed to get codec chan map\n", __func__);
goto end;
}
ret = <API key>(cpu_dai,
msm_slim_0_tx_ch, tx_ch, 0 , 0);
if (ret < 0) {
pr_err("%s: failed to set cpu chan map\n", __func__);
goto end;
}
ret = <API key>(codec_dai,
msm_slim_0_tx_ch, tx_ch, 0, 0);
if (ret < 0) {
pr_err("%s: failed to set codec channel map\n",
__func__);
goto end;
}
}
end:
return ret;
}
static int <API key>(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
int ret = 0;
unsigned int rx_ch[SLIM_MAX_RX_PORTS], tx_ch[SLIM_MAX_TX_PORTS];
unsigned int rx_ch_cnt = 0, tx_ch_cnt = 0;
unsigned int num_tx_ch = 0;
unsigned int num_rx_ch = 0;
if (substream->stream == <API key>) {
num_rx_ch = params_channels(params);
pr_debug("%s: %s rx_dai_id = %d num_ch = %d\n", __func__,
codec_dai->name, codec_dai->id, num_rx_ch);
ret = <API key>(codec_dai,
&tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch);
if (ret < 0) {
pr_err("%s: failed to get codec chan map\n", __func__);
goto end;
}
ret = <API key>(cpu_dai, 0, 0,
num_rx_ch, rx_ch);
if (ret < 0) {
pr_err("%s: failed to set cpu chan map\n", __func__);
goto end;
}
ret = <API key>(codec_dai, 0, 0,
num_rx_ch, rx_ch);
if (ret < 0) {
pr_err("%s: failed to set codec channel map\n",
__func__);
goto end;
}
} else {
num_tx_ch = params_channels(params);
pr_debug("%s: %s tx_dai_id = %d num_ch = %d\n", __func__,
codec_dai->name, codec_dai->id, num_tx_ch);
ret = <API key>(codec_dai,
&tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch);
if (ret < 0) {
pr_err("%s: failed to get codec chan map\n", __func__);
goto end;
}
ret = <API key>(cpu_dai,
num_tx_ch, tx_ch, 0 , 0);
if (ret < 0) {
pr_err("%s: failed to set cpu chan map\n", __func__);
goto end;
}
ret = <API key>(codec_dai,
num_tx_ch, tx_ch, 0, 0);
if (ret < 0) {
pr_err("%s: failed to set codec channel map\n",
__func__);
goto end;
}
}
end:
return ret;
}
static int msm_audrx_init(struct snd_soc_pcm_runtime *rtd)
{
int err;
struct snd_soc_codec *codec = rtd->codec;
struct <API key> *dapm = &codec->dapm;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
pr_debug("%s(), dev_name: %s\n", __func__, dev_name(cpu_dai->dev));
<API key>(dapm, msm_dapm_widgets,
ARRAY_SIZE(msm_dapm_widgets));
<API key>(dapm, elite_dapm_widgets,
ARRAY_SIZE(elite_dapm_widgets));
<API key>(dapm, common_audio_map,
ARRAY_SIZE(common_audio_map));
pr_debug("%s(), %s\n", __func__, codec->name);
if (!strncmp(codec->name, "tabla1x_codec", 13))
<API key>(dapm, tabla_1_x_audio_map,
ARRAY_SIZE(tabla_1_x_audio_map));
else
<API key>(dapm, tabla_2_x_audio_map,
ARRAY_SIZE(tabla_2_x_audio_map));
<API key>(dapm, "Ext Spk Bottom Pos");
<API key>(dapm, "Ext Spk Bottom Neg");
<API key>(dapm, "Ext Spk Top Pos");
<API key>(dapm, "Ext Spk Top Neg");
<API key>(dapm, "Dock Spk Pos");
<API key>(dapm, "Dock Spk Neg");
snd_soc_dapm_sync(dapm);
err = snd_soc_jack_new(codec, "Headset Jack",
(SND_JACK_HEADSET | SND_JACK_OC_HPHL |
SND_JACK_OC_HPHR | <API key>),
&hs_jack);
if (err) {
pr_err("failed to create new jack\n");
return err;
}
err = snd_soc_jack_new(codec, "Button Jack",
<API key>, &button_jack);
if (err) {
pr_err("failed to create new jack\n");
return err;
}
codec_clk = clk_get(cpu_dai->dev, "osr_clk");
return err;
}
static int <API key>(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
<API key>);
struct snd_interval *channels = hw_param_interval(params,
<API key>);
pr_debug("%s()\n", __func__);
rate->min = rate->max = 48000;
channels->min = channels->max = msm_slim_0_rx_ch;
return 0;
}
static int <API key>(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
<API key>);
struct snd_interval *channels = hw_param_interval(params,
<API key>);
pr_debug("%s()\n", __func__);
rate->min = rate->max = 48000;
channels->min = channels->max = msm_slim_0_tx_ch;
return 0;
}
static int <API key>(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
<API key>);
pr_debug("%s()\n", __func__);
rate->min = rate->max = 48000;
return 0;
}
static int <API key>(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
<API key>);
struct snd_interval *channels = hw_param_interval(params,
<API key>);
pr_debug("%s channels->min %u channels->max %u ()\n", __func__,
channels->min, channels->max);
rate->min = rate->max = 48000;
return 0;
}
static int <API key>(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
<API key>);
struct snd_interval *channels = hw_param_interval(params,
<API key>);
rate->min = rate->max = msm_btsco_rate;
channels->min = channels->max = msm_btsco_ch;
return 0;
}
static int <API key>(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
<API key>);
struct snd_interval *channels = hw_param_interval(params,
<API key>);
rate->min = rate->max = msm_auxpcm_rate;
channels->min = channels->max = 1;
return 0;
}
static int <API key>(void)
{
int ret = 0;
pr_debug("%s\n", __func__);
ret = gpio_request(GPIO_AUX_PCM_DOUT, "AUX PCM DOUT");
if (ret < 0) {
pr_err("%s: Failed to request gpio(%d): AUX PCM DOUT",
__func__, GPIO_AUX_PCM_DOUT);
goto fail_dout;
}
ret = gpio_request(GPIO_AUX_PCM_DIN, "AUX PCM DIN");
if (ret < 0) {
pr_err("%s: Failed to request gpio(%d): AUX PCM DIN",
__func__, GPIO_AUX_PCM_DIN);
goto fail_din;
}
ret = gpio_request(GPIO_AUX_PCM_SYNC, "AUX PCM SYNC");
if (ret < 0) {
pr_err("%s: Failed to request gpio(%d): AUX PCM SYNC",
__func__, GPIO_AUX_PCM_SYNC);
goto fail_sync;
}
ret = gpio_request(GPIO_AUX_PCM_CLK, "AUX PCM CLK");
if (ret < 0) {
pr_err("%s: Failed to request gpio(%d): AUX PCM CLK",
__func__, GPIO_AUX_PCM_CLK);
goto fail_clk;
}
return 0;
fail_clk:
gpio_free(GPIO_AUX_PCM_SYNC);
fail_sync:
gpio_free(GPIO_AUX_PCM_DIN);
fail_din:
gpio_free(GPIO_AUX_PCM_DOUT);
fail_dout:
return ret;
}
static int <API key>(void)
{
gpio_free(GPIO_AUX_PCM_DIN);
gpio_free(GPIO_AUX_PCM_DOUT);
gpio_free(GPIO_AUX_PCM_SYNC);
gpio_free(GPIO_AUX_PCM_CLK);
return 0;
}
static int msm_startup(struct snd_pcm_substream *substream)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
pr_debug("%s(): dai_link_str_name = %s cpu_dai = %s codec_dai = %s\n",
__func__, rtd->dai_link->stream_name,
rtd->dai_link->cpu_dai_name, rtd->dai_link->codec_dai_name);
return 0;
}
static int msm_auxpcm_startup(struct snd_pcm_substream *substream)
{
int ret = 0;
pr_debug("%s(): substream = %s\n", __func__, substream->name);
ret = <API key>();
if (ret < 0) {
pr_err("%s: Aux PCM GPIO request failed\n", __func__);
return -EINVAL;
}
return 0;
}
static void msm_auxpcm_shutdown(struct snd_pcm_substream *substream)
{
pr_debug("%s(): substream = %s\n", __func__, substream->name);
<API key>();
}
static void msm_shutdown(struct snd_pcm_substream *substream)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
pr_debug("%s(): dai_link str_name = %s cpu_dai = %s codec_dai = %s\n",
__func__, rtd->dai_link->stream_name,
rtd->dai_link->cpu_dai_name, rtd->dai_link->codec_dai_name);
}
static struct snd_soc_ops msm_be_ops = {
.startup = msm_startup,
.hw_params = msm_hw_params,
.shutdown = msm_shutdown,
};
static struct snd_soc_ops msm_auxpcm_be_ops = {
.startup = msm_auxpcm_startup,
.shutdown = msm_auxpcm_shutdown,
};
static struct snd_soc_ops <API key> = {
.startup = msm_startup,
.hw_params = <API key>,
.shutdown = msm_shutdown,
};
static struct snd_soc_dai_link msm_dai_common[] = {
{
.name = "MSM8960 Media1",
.stream_name = "MultiMedia1",
.cpu_dai_name = "MultiMedia1",
.platform_name = "msm-pcm-dsp",
.dynamic = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.trigger = {<API key>, <API key>},
.ignore_suspend = 1,
.ignore_pmdown_time = 1,
.be_id = <API key>
},
{
.name = "MSM8960 Media2",
.stream_name = "MultiMedia2",
.cpu_dai_name = "MultiMedia2",
.platform_name = "<API key>",
.dynamic = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.trigger = {<API key>, <API key>},
.ignore_suspend = 1,
.ignore_pmdown_time = 1,
.be_id = <API key>,
},
{
.name = "Circuit-Switch Voice",
.stream_name = "CS-Voice",
.cpu_dai_name = "CS-VOICE",
.platform_name = "msm-pcm-voice",
.dynamic = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.trigger = {<API key>, <API key>},
.no_host_mode = <API key>,
.ignore_suspend = 1,
.ignore_pmdown_time = 1,
.be_id = <API key>,
},
{
.name = "MSM VoIP",
.stream_name = "VoIP",
.cpu_dai_name = "VoIP",
.platform_name = "msm-voip-dsp",
.dynamic = 1,
.trigger = {<API key>, <API key>},
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.ignore_suspend = 1,
.ignore_pmdown_time = 1,
.be_id = <API key>,
},
{
.name = "MSM8960 LPA",
.stream_name = "LPA",
.cpu_dai_name = "MultiMedia3",
.platform_name = "msm-pcm-lpa",
.dynamic = 1,
.trigger = {<API key>, <API key>},
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.ignore_suspend = 1,
.ignore_pmdown_time = 1,
.be_id = <API key>,
},
{
.name = "SLIMBUS_0 Hostless",
.stream_name = "SLIMBUS_0 Hostless",
.cpu_dai_name = "SLIMBUS0_HOSTLESS",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.trigger = {<API key>, <API key>},
.no_host_mode = <API key>,
.ignore_suspend = 1,
.ignore_pmdown_time = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
},
{
.name = "INT_FM Hostless",
.stream_name = "INT_FM Hostless",
.cpu_dai_name = "INT_FM_HOSTLESS",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.trigger = {<API key>, <API key>},
.no_host_mode = <API key>,
.ignore_suspend = 1,
.ignore_pmdown_time = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
},
{
.name = "MSM AFE-PCM RX",
.stream_name = "AFE-PROXY RX",
.cpu_dai_name = "msm-dai-q6.241",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.platform_name = "msm-pcm-afe",
.ignore_suspend = 1,
.ignore_pmdown_time = 1,
},
{
.name = "MSM AFE-PCM TX",
.stream_name = "AFE-PROXY TX",
.cpu_dai_name = "msm-dai-q6.240",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.platform_name = "msm-pcm-afe",
.ignore_suspend = 1,
},
{
.name = "MSM8960 Compr",
.stream_name = "COMPR",
.cpu_dai_name = "MultiMedia4",
.platform_name = "msm-compr-dsp",
.dynamic = 1,
.trigger = {<API key>, <API key>},
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.ignore_suspend = 1,
.ignore_pmdown_time = 1,
.be_id = <API key>,
},
{
.name = "AUXPCM Hostless",
.stream_name = "AUXPCM Hostless",
.cpu_dai_name = "AUXPCM_HOSTLESS",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.trigger = {<API key>, <API key>},
.no_host_mode = <API key>,
.ignore_suspend = 1,
.ignore_pmdown_time = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
},
{
.name = "HDMI_RX_HOSTLESS",
.stream_name = "HDMI_RX_HOSTLESS",
.cpu_dai_name = "HDMI_HOSTLESS",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.trigger = {<API key>, <API key>},
.no_host_mode = <API key>,
.ignore_suspend = 1,
.ignore_pmdown_time = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
},
{
.name = "VoLTE",
.stream_name = "VoLTE",
.cpu_dai_name = "VoLTE",
.platform_name = "msm-pcm-voice",
.dynamic = 1,
.trigger = {<API key>, <API key>},
.no_host_mode = <API key>,
.ignore_suspend = 1,
.ignore_pmdown_time = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.be_id = <API key>,
},
{
.name = "Voice2",
.stream_name = "Voice2",
.cpu_dai_name = "Voice2",
.platform_name = "msm-pcm-voice",
.dynamic = 1,
.trigger = {<API key>,
<API key>},
.no_host_mode = <API key>,
.ignore_suspend = 1,
.ignore_pmdown_time = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.be_id = <API key>,
},
{
.name = "MSM8960 LowLatency",
.stream_name = "MultiMedia5",
.cpu_dai_name = "MultiMedia5",
.platform_name = "<API key>",
.dynamic = 1,
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.trigger = {<API key>,
<API key>},
.ignore_suspend = 1,
/* this dainlink has playback support */
.ignore_pmdown_time = 1,
.be_id = <API key>,
},
{
.name = <API key>,
.stream_name = "Internal BT-SCO Playback",
.cpu_dai_name = "msm-dai-q6.12288",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = <API key>,
.be_hw_params_fixup = <API key>,
.ignore_pmdown_time = 1,
},
{
.name = <API key>,
.stream_name = "Internal BT-SCO Capture",
.cpu_dai_name = "msm-dai-q6.12289",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = <API key>,
.be_hw_params_fixup = <API key>,
},
{
.name = LPASS_BE_INT_FM_RX,
.stream_name = "Internal FM Playback",
.cpu_dai_name = "msm-dai-q6.12292",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = <API key>,
.be_hw_params_fixup = <API key>,
.ignore_pmdown_time = 1,
},
{
.name = LPASS_BE_INT_FM_TX,
.stream_name = "Internal FM Capture",
.cpu_dai_name = "msm-dai-q6.12293",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = <API key>,
.be_hw_params_fixup = <API key>,
},
{
.name = LPASS_BE_HDMI,
.stream_name = "HDMI Playback",
.cpu_dai_name = "msm-dai-q6-hdmi.8",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = <API key>,
.be_hw_params_fixup = <API key>,
.ignore_pmdown_time = 1,
},
{
.name = LPASS_BE_AFE_PCM_RX,
.stream_name = "AFE Playback",
.cpu_dai_name = "msm-dai-q6.224",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = <API key>,
.ignore_pmdown_time = 1,
},
{
.name = LPASS_BE_AFE_PCM_TX,
.stream_name = "AFE Capture",
.cpu_dai_name = "msm-dai-q6.225",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = <API key>,
},
{
.name = LPASS_BE_AUXPCM_RX,
.stream_name = "AUX PCM Playback",
.cpu_dai_name = "msm-dai-q6.2",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = <API key>,
.be_hw_params_fixup = <API key>,
.ops = &msm_auxpcm_be_ops,
.ignore_pmdown_time = 1,
},
{
.name = LPASS_BE_AUXPCM_TX,
.stream_name = "AUX PCM Capture",
.cpu_dai_name = "msm-dai-q6.3",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = <API key>,
.be_hw_params_fixup = <API key>,
},
{
.name = <API key>,
.stream_name = "Voice Farend Playback",
.cpu_dai_name = "msm-dai-q6.32773",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = <API key>,
.be_hw_params_fixup = <API key>,
},
{
.name = <API key>,
.stream_name = "Voice Uplink Capture",
.cpu_dai_name = "msm-dai-q6.32772",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = <API key>,
.be_hw_params_fixup = <API key>,
},
{
.name = <API key>,
.stream_name = "Voice Downlink Capture",
.cpu_dai_name = "msm-dai-q6.32771",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = <API key>,
.be_hw_params_fixup = <API key>,
.ignore_pmdown_time = 1,
},
{
.name = "MSM8960 Media6",
.stream_name = "MultiMedia6",
.cpu_dai_name = "MultiMedia6",
.platform_name = "<API key>",
.dynamic = 1,
.trigger = {<API key>,
<API key>},
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.ignore_suspend = 1,
.ignore_pmdown_time = 1,
.be_id = <API key>
},
{
.name = "MSM8960 Compr2",
.stream_name = "COMPR2",
.cpu_dai_name = "MultiMedia7",
.platform_name = "msm-compr-dsp",
.dynamic = 1,
.trigger = {<API key>,
<API key>},
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.ignore_suspend = 1,
.ignore_pmdown_time = 1,
.be_id = <API key>,
},
{
.name = "MSM8960 Compr3",
.stream_name = "COMPR3",
.cpu_dai_name = "MultiMedia8",
.platform_name = "msm-compr-dsp",
.dynamic = 1,
.trigger = {<API key>,
<API key>},
.codec_dai_name = "snd-soc-dummy-dai",
.codec_name = "snd-soc-dummy",
.ignore_suspend = 1,
.ignore_pmdown_time = 1,
.be_id = <API key>,
},
};
static struct snd_soc_dai_link <API key>[] = {
{
.name = <API key>,
.stream_name = "Slimbus Playback",
.cpu_dai_name = "msm-dai-q6.16384",
.platform_name = "msm-pcm-routing",
.codec_name = "tabla1x_codec",
.codec_dai_name = "tabla_rx1",
.no_pcm = 1,
.be_id = <API key>,
.init = &msm_audrx_init,
.be_hw_params_fixup = <API key>,
.ops = &msm_be_ops,
.ignore_pmdown_time = 1,
},
{
.name = <API key>,
.stream_name = "Slimbus Capture",
.cpu_dai_name = "msm-dai-q6.16385",
.platform_name = "msm-pcm-routing",
.codec_name = "tabla1x_codec",
.codec_dai_name = "tabla_tx1",
.no_pcm = 1,
.be_id = <API key>,
.be_hw_params_fixup = <API key>,
.ops = &msm_be_ops,
},
{
.name = "SLIMBUS_2 Hostless Capture",
.stream_name = "SLIMBUS_2 Hostless Capture",
.cpu_dai_name = "msm-dai-q6.16389",
.platform_name = "msm-pcm-hostless",
.codec_name = "tabla1x_codec",
.codec_dai_name = "tabla_tx2",
.ignore_suspend = 1,
.no_host_mode = <API key>,
.ops = &<API key>,
},
{
.name = "SLIMBUS_2 Hostless Playback",
.stream_name = "SLIMBUS_2 Hostless Playback",
.cpu_dai_name = "msm-dai-q6.16388",
.platform_name = "msm-pcm-hostless",
.codec_name = "tabla1x_codec",
.codec_dai_name = "tabla_rx3",
.ignore_suspend = 1,
.no_host_mode = <API key>,
.ops = &<API key>,
},
};
static struct snd_soc_dai_link <API key>[] = {
{
.name = <API key>,
.stream_name = "Slimbus Playback",
.cpu_dai_name = "msm-dai-q6.16384",
.platform_name = "msm-pcm-routing",
.codec_name = "tabla_codec",
.codec_dai_name = "tabla_rx1",
.no_pcm = 1,
.be_id = <API key>,
.init = &msm_audrx_init,
.be_hw_params_fixup = <API key>,
.ops = &msm_be_ops,
.ignore_pmdown_time = 1,
},
{
.name = <API key>,
.stream_name = "Slimbus Capture",
.cpu_dai_name = "msm-dai-q6.16385",
.platform_name = "msm-pcm-routing",
.codec_name = "tabla_codec",
.codec_dai_name = "tabla_tx1",
.no_pcm = 1,
.be_id = <API key>,
.be_hw_params_fixup = <API key>,
.ops = &msm_be_ops,
},
{
.name = "SLIMBUS_2 Hostless Capture",
.stream_name = "SLIMBUS_2 Hostless Capture",
.cpu_dai_name = "msm-dai-q6.16389",
.platform_name = "msm-pcm-hostless",
.codec_name = "tabla_codec",
.codec_dai_name = "tabla_tx2",
.ignore_suspend = 1,
.no_host_mode = <API key>,
.ops = &<API key>,
},
{
.name = "SLIMBUS_2 Hostless Playback",
.stream_name = "SLIMBUS_2 Hostless Playback",
.cpu_dai_name = "msm-dai-q6.16388",
.platform_name = "msm-pcm-hostless",
.codec_name = "tabla_codec",
.codec_dai_name = "tabla_rx3",
.ignore_suspend = 1,
.no_host_mode = <API key>,
.ops = &<API key>,
},
};
static struct snd_soc_dai_link msm_tabla1x_dai[
ARRAY_SIZE(msm_dai_common) +
ARRAY_SIZE(<API key>)];
static struct snd_soc_dai_link msm_dai[
ARRAY_SIZE(msm_dai_common) +
ARRAY_SIZE(<API key>)];
static struct snd_soc_card <API key> = {
.name = "<API key>",
.dai_link = msm_tabla1x_dai,
.num_links = ARRAY_SIZE(msm_tabla1x_dai),
.controls = tabla_msm_controls,
.num_controls = ARRAY_SIZE(tabla_msm_controls),
};
static struct snd_soc_card snd_soc_card_msm = {
.name = "msm-snd-card",
.dai_link = msm_dai,
.num_links = ARRAY_SIZE(msm_dai),
.controls = tabla_msm_controls,
.num_controls = ARRAY_SIZE(tabla_msm_controls),
};
static struct platform_device *msm_snd_device;
static struct platform_device *<API key>;
static int __init elite_audio_init(void)
{
int ret;
if (!cpu_is_msm8960()) {
pr_err("%s: Not the right machine type\n", __func__);
return -ENODEV;
}
pr_debug("%s", __func__);
msm_snd_device = <API key>("soc-audio", 0);
if (!msm_snd_device) {
pr_err("Platform device allocation failed\n");
return -ENOMEM;
}
memcpy(msm_dai, msm_dai_common, sizeof(msm_dai_common));
memcpy(msm_dai + ARRAY_SIZE(msm_dai_common),
<API key>, sizeof(<API key>));
<API key>(msm_snd_device, &snd_soc_card_msm);
ret = platform_device_add(msm_snd_device);
if (ret) {
platform_device_put(msm_snd_device);
return ret;
}
<API key> = <API key>("soc-audio", 1);
if (!<API key>) {
pr_err("Platform device allocation failed\n");
return -ENOMEM;
}
memcpy(msm_tabla1x_dai, msm_dai_common,
sizeof(msm_dai_common));
memcpy(msm_tabla1x_dai + ARRAY_SIZE(msm_dai_common),
<API key>, sizeof(<API key>));
<API key>(<API key>,
&<API key>);
ret = platform_device_add(<API key>);
if (ret) {
platform_device_put(<API key>);
return ret;
}
mutex_init(&audio_notifier_lock);
pr_debug("%s: register cable detect func for dock", __func__);
ret = <API key>(&audio_dock_notifier);
mutex_init(&cdc_mclk_mutex);
return ret;
}
late_initcall(elite_audio_init);
static void __exit elite_audio_exit(void)
{
if (!cpu_is_msm8960()) {
pr_err("%s: Not the right machine type\n", __func__);
return;
}
pr_debug("%s", __func__);
<API key>(msm_snd_device);
<API key>(<API key>);
mutex_destroy(&audio_notifier_lock);
mutex_destroy(&cdc_mclk_mutex);
}
module_exit(elite_audio_exit);
MODULE_DESCRIPTION("ALSA Platform Elite");
MODULE_LICENSE("GPL v2");
|
<?php
namespace Ramsey\Uuid\Provider\Node;
use Ramsey\Uuid\Provider\<API key>;
/**
* <API key> attempts to gain the system host ID from an array of
* providers, falling back to the next in line in the event a host ID can not be
* obtained
*/
class <API key> implements <API key>
{
/**
* @var <API key>[]
*/
private $nodeProviders;
/**
* Constructs a `<API key>` using an array of node providers
*
* @param <API key>[] $providers Array of node providers
*/
public function __construct(array $providers)
{
$this->nodeProviders = $providers;
}
/**
* Returns the system node ID by iterating over an array of node providers
* and returning the first non-empty value found
*
* @return string System node ID as a hexadecimal string
* @throws \Exception
*/
public function getNode()
{
foreach ($this->nodeProviders as $provider) {
if ($node = $provider->getNode()) {
return $node;
}
}
return null;
}
}
|
# This file is part of WhatWeb and may be subject to
# web site for more information on licensing and terms of use.
Plugin.define "SQLiteManager" do
author "Brendan Coles <bcoles@gmail.com>" # 2012-01-14
version "0.1"
description "SQLiteManager - Web-based SQLite administration - Homepage: http:
# Google results as at 2012-01-14 #
# 33 for intitle:"SQLite version" "Welcome to SQLiteManager version"
# 26 for inurl:"main.php?dbsel="
# Dorks #
dorks [
'intitle:"SQLite version" "Welcome to SQLiteManager version"'
]
# Matches #
matches [
# HTML Comments
{ :text=>'<!-- <API key>.class.php : propView() -->' },
{ :text=>'<!-- common.lib.php : displayMenuTitle() -->' },
# Form
{ :text=>'<td style="white-space: nowrap"> <form name="database" action="main.php" enctype="multipart/form-data" method="POST" onSubmit="checkPath();" target="main">' },
# h2 class="sqlmVersion"
{ :text=>'<h2 class="sqlmVersion">Database : <a href="main.php?dbsel=' },
# Title # SQLite Version Detection
{ :string=>/<title>(SQLite version [\d\.\s-]+)(undefined)?<\/title>/ },
# h2 class="sqlmVersion" # Version Detection
{ :version=>/<h2 class="sqlmVersion">Welcome to <a href="http:\/\/www\.sqlitemanager\.org" target="_blank">SQLiteManager<\/a> version ([^\s^>]+)<\/h2>/ },
# h4 class="serverInfo" # SQLite Version Detection
{ :string=>/<h4 class="serverInfo">(SQLite version [\d\.\s-]+)(undefined)? \/ PHP version 5.2.17<\/h4>/ },
# h4 class="serverInfo" # SQLite Version Detection
{ :string=>/<h4 class="serverInfo">SQLite version [\d\.\s-]+(undefined)? \/ (PHP version [^\s^<]+)<\/h4>/, :offset=>1 },
]
end
|
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/random.h>
#include <linux/rculist.h>
#include "nvmet.h"
static struct nvmet_fabrics_ops *nvmet_transports[NVMF_TRTYPE_MAX];
static DEFINE_IDA(cntlid_ida);
/*
* This read/write semaphore is used to synchronize access to configuration
* information on a target system that will result in discovery log page
* information change for at least one host.
* The full list of resources to protected by this semaphore is:
*
* - subsystems list
* - per-subsystem allowed hosts list
* - allow_any_host subsystem attribute
* - nvmet_genctr
* - the nvmet_transports array
*
* When updating any of those lists/structures write lock should be obtained,
* while when reading (popolating discovery log page or checking host-subsystem
* link) read lock is obtained to allow concurrent reads.
*/
DECLARE_RWSEM(nvmet_config_sem);
static struct nvmet_subsys *<API key>(struct nvmet_port *port,
const char *subsysnqn);
u16 nvmet_copy_to_sgl(struct nvmet_req *req, off_t off, const void *buf,
size_t len)
{
if (<API key>(req->sg, req->sg_cnt, buf, len, off) != len)
return <API key> | NVME_SC_DNR;
return 0;
}
u16 nvmet_copy_from_sgl(struct nvmet_req *req, off_t off, void *buf, size_t len)
{
if (sg_pcopy_to_buffer(req->sg, req->sg_cnt, buf, len, off) != len)
return <API key> | NVME_SC_DNR;
return 0;
}
static u32 <API key>(struct nvmet_async_event *aen)
{
return aen->event_type | (aen->event_info << 8) | (aen->log_page << 16);
}
static void <API key>(struct nvmet_ctrl *ctrl)
{
struct nvmet_req *req;
while (1) {
mutex_lock(&ctrl->lock);
if (!ctrl->nr_async_event_cmds) {
mutex_unlock(&ctrl->lock);
return;
}
req = ctrl->async_event_cmds[--ctrl->nr_async_event_cmds];
mutex_unlock(&ctrl->lock);
nvmet_req_complete(req, NVME_SC_INTERNAL | NVME_SC_DNR);
}
}
static void <API key>(struct work_struct *work)
{
struct nvmet_ctrl *ctrl =
container_of(work, struct nvmet_ctrl, async_event_work);
struct nvmet_async_event *aen;
struct nvmet_req *req;
while (1) {
mutex_lock(&ctrl->lock);
aen = <API key>(&ctrl->async_events,
struct nvmet_async_event, entry);
if (!aen || !ctrl->nr_async_event_cmds) {
mutex_unlock(&ctrl->lock);
return;
}
req = ctrl->async_event_cmds[--ctrl->nr_async_event_cmds];
nvmet_set_result(req, <API key>(aen));
list_del(&aen->entry);
kfree(aen);
mutex_unlock(&ctrl->lock);
nvmet_req_complete(req, 0);
}
}
static void <API key>(struct nvmet_ctrl *ctrl, u8 event_type,
u8 event_info, u8 log_page)
{
struct nvmet_async_event *aen;
aen = kmalloc(sizeof(*aen), GFP_KERNEL);
if (!aen)
return;
aen->event_type = event_type;
aen->event_info = event_info;
aen->log_page = log_page;
mutex_lock(&ctrl->lock);
list_add_tail(&aen->entry, &ctrl->async_events);
mutex_unlock(&ctrl->lock);
schedule_work(&ctrl->async_event_work);
}
int <API key>(struct nvmet_fabrics_ops *ops)
{
int ret = 0;
down_write(&nvmet_config_sem);
if (nvmet_transports[ops->type])
ret = -EINVAL;
else
nvmet_transports[ops->type] = ops;
up_write(&nvmet_config_sem);
return ret;
}
EXPORT_SYMBOL_GPL(<API key>);
void <API key>(struct nvmet_fabrics_ops *ops)
{
down_write(&nvmet_config_sem);
nvmet_transports[ops->type] = NULL;
up_write(&nvmet_config_sem);
}
EXPORT_SYMBOL_GPL(<API key>);
int nvmet_enable_port(struct nvmet_port *port)
{
struct nvmet_fabrics_ops *ops;
int ret;
lockdep_assert_held(&nvmet_config_sem);
ops = nvmet_transports[port->disc_addr.trtype];
if (!ops) {
up_write(&nvmet_config_sem);
request_module("nvmet-transport-%d", port->disc_addr.trtype);
down_write(&nvmet_config_sem);
ops = nvmet_transports[port->disc_addr.trtype];
if (!ops) {
pr_err("transport type %d not supported\n",
port->disc_addr.trtype);
return -EINVAL;
}
}
if (!try_module_get(ops->owner))
return -EINVAL;
ret = ops->add_port(port);
if (ret) {
module_put(ops->owner);
return ret;
}
port->enabled = true;
return 0;
}
void nvmet_disable_port(struct nvmet_port *port)
{
struct nvmet_fabrics_ops *ops;
lockdep_assert_held(&nvmet_config_sem);
port->enabled = false;
ops = nvmet_transports[port->disc_addr.trtype];
ops->remove_port(port);
module_put(ops->owner);
}
static void <API key>(struct work_struct *work)
{
struct nvmet_ctrl *ctrl = container_of(to_delayed_work(work),
struct nvmet_ctrl, ka_work);
pr_err("ctrl %d keep-alive timer (%d seconds) expired!\n",
ctrl->cntlid, ctrl->kato);
<API key>(ctrl);
}
static void <API key>(struct nvmet_ctrl *ctrl)
{
pr_debug("ctrl %d start keep-alive timer for %d secs\n",
ctrl->cntlid, ctrl->kato);
INIT_DELAYED_WORK(&ctrl->ka_work, <API key>);
<API key>(&ctrl->ka_work, ctrl->kato * HZ);
}
static void <API key>(struct nvmet_ctrl *ctrl)
{
pr_debug("ctrl %d stop keep-alive\n", ctrl->cntlid);
<API key>(&ctrl->ka_work);
}
static struct nvmet_ns *<API key>(struct nvmet_ctrl *ctrl,
__le32 nsid)
{
struct nvmet_ns *ns;
<API key>(ns, &ctrl->subsys->namespaces, dev_link) {
if (ns->nsid == le32_to_cpu(nsid))
return ns;
}
return NULL;
}
struct nvmet_ns *<API key>(struct nvmet_ctrl *ctrl, __le32 nsid)
{
struct nvmet_ns *ns;
rcu_read_lock();
ns = <API key>(ctrl, nsid);
if (ns)
percpu_ref_get(&ns->ref);
rcu_read_unlock();
return ns;
}
static void <API key>(struct percpu_ref *ref)
{
struct nvmet_ns *ns = container_of(ref, struct nvmet_ns, ref);
complete(&ns->disable_done);
}
void nvmet_put_namespace(struct nvmet_ns *ns)
{
percpu_ref_put(&ns->ref);
}
int nvmet_ns_enable(struct nvmet_ns *ns)
{
struct nvmet_subsys *subsys = ns->subsys;
struct nvmet_ctrl *ctrl;
int ret = 0;
mutex_lock(&subsys->lock);
if (ns->enabled)
goto out_unlock;
ns->bdev = blkdev_get_by_path(ns->device_path, FMODE_READ | FMODE_WRITE,
NULL);
if (IS_ERR(ns->bdev)) {
pr_err("failed to open block device %s: (%ld)\n",
ns->device_path, PTR_ERR(ns->bdev));
ret = PTR_ERR(ns->bdev);
ns->bdev = NULL;
goto out_unlock;
}
ns->size = i_size_read(ns->bdev->bd_inode);
ns->blksize_shift = blksize_bits(<API key>(ns->bdev));
ret = percpu_ref_init(&ns->ref, <API key>,
0, GFP_KERNEL);
if (ret)
goto out_blkdev_put;
if (ns->nsid > subsys->max_nsid)
subsys->max_nsid = ns->nsid;
/*
* The namespaces list needs to be sorted to simplify the implementation
* of the Identify Namepace List subcommand.
*/
if (list_empty(&subsys->namespaces)) {
list_add_tail_rcu(&ns->dev_link, &subsys->namespaces);
} else {
struct nvmet_ns *old;
<API key>(old, &subsys->namespaces, dev_link) {
BUG_ON(ns->nsid == old->nsid);
if (ns->nsid < old->nsid)
break;
}
list_add_tail_rcu(&ns->dev_link, &old->dev_link);
}
list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry)
<API key>(ctrl, <API key>, 0, 0);
ns->enabled = true;
ret = 0;
out_unlock:
mutex_unlock(&subsys->lock);
return ret;
out_blkdev_put:
blkdev_put(ns->bdev, FMODE_WRITE|FMODE_READ);
ns->bdev = NULL;
goto out_unlock;
}
void nvmet_ns_disable(struct nvmet_ns *ns)
{
struct nvmet_subsys *subsys = ns->subsys;
struct nvmet_ctrl *ctrl;
mutex_lock(&subsys->lock);
if (!ns->enabled)
goto out_unlock;
ns->enabled = false;
list_del_rcu(&ns->dev_link);
mutex_unlock(&subsys->lock);
/*
* Now that we removed the namespaces from the lookup list, we
* can kill the per_cpu ref and wait for any remaining references
* to be dropped, as well as a RCU grace period for anyone only
* using the namepace under rcu_read_lock(). Note that we can't
* use call_rcu here as we need to ensure the namespaces have
* been fully destroyed before unloading the module.
*/
percpu_ref_kill(&ns->ref);
synchronize_rcu();
wait_for_completion(&ns->disable_done);
percpu_ref_exit(&ns->ref);
mutex_lock(&subsys->lock);
list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry)
<API key>(ctrl, <API key>, 0, 0);
if (ns->bdev)
blkdev_put(ns->bdev, FMODE_WRITE|FMODE_READ);
out_unlock:
mutex_unlock(&subsys->lock);
}
void nvmet_ns_free(struct nvmet_ns *ns)
{
nvmet_ns_disable(ns);
kfree(ns->device_path);
kfree(ns);
}
struct nvmet_ns *nvmet_ns_alloc(struct nvmet_subsys *subsys, u32 nsid)
{
struct nvmet_ns *ns;
ns = kzalloc(sizeof(*ns), GFP_KERNEL);
if (!ns)
return NULL;
INIT_LIST_HEAD(&ns->dev_link);
init_completion(&ns->disable_done);
ns->nsid = nsid;
ns->subsys = subsys;
uuid_gen(&ns->uuid);
return ns;
}
static void <API key>(struct nvmet_req *req, u16 status)
{
if (status)
nvmet_set_status(req, status);
if (req->sq->size)
req->sq->sqhd = (req->sq->sqhd + 1) % req->sq->size;
req->rsp->sq_head = cpu_to_le16(req->sq->sqhd);
req->rsp->sq_id = cpu_to_le16(req->sq->qid);
req->rsp->command_id = req->cmd->common.command_id;
if (req->ns)
nvmet_put_namespace(req->ns);
req->ops->queue_response(req);
}
void nvmet_req_complete(struct nvmet_req *req, u16 status)
{
<API key>(req, status);
percpu_ref_put(&req->sq->ref);
}
EXPORT_SYMBOL_GPL(nvmet_req_complete);
void nvmet_cq_setup(struct nvmet_ctrl *ctrl, struct nvmet_cq *cq,
u16 qid, u16 size)
{
cq->qid = qid;
cq->size = size;
ctrl->cqs[qid] = cq;
}
void nvmet_sq_setup(struct nvmet_ctrl *ctrl, struct nvmet_sq *sq,
u16 qid, u16 size)
{
sq->sqhd = 0;
sq->qid = qid;
sq->size = size;
ctrl->sqs[qid] = sq;
}
static void nvmet_confirm_sq(struct percpu_ref *ref)
{
struct nvmet_sq *sq = container_of(ref, struct nvmet_sq, ref);
complete(&sq->confirm_done);
}
void nvmet_sq_destroy(struct nvmet_sq *sq)
{
/*
* If this is the admin queue, complete all AERs so that our
* queue doesn't have outstanding requests on it.
*/
if (sq->ctrl && sq->ctrl->sqs && sq->ctrl->sqs[0] == sq)
<API key>(sq->ctrl);
<API key>(&sq->ref, nvmet_confirm_sq);
wait_for_completion(&sq->confirm_done);
wait_for_completion(&sq->free_done);
percpu_ref_exit(&sq->ref);
if (sq->ctrl) {
nvmet_ctrl_put(sq->ctrl);
sq->ctrl = NULL; /* allows reusing the queue later */
}
}
EXPORT_SYMBOL_GPL(nvmet_sq_destroy);
static void nvmet_sq_free(struct percpu_ref *ref)
{
struct nvmet_sq *sq = container_of(ref, struct nvmet_sq, ref);
complete(&sq->free_done);
}
int nvmet_sq_init(struct nvmet_sq *sq)
{
int ret;
ret = percpu_ref_init(&sq->ref, nvmet_sq_free, 0, GFP_KERNEL);
if (ret) {
pr_err("percpu_ref init failed!\n");
return ret;
}
init_completion(&sq->free_done);
init_completion(&sq->confirm_done);
return 0;
}
EXPORT_SYMBOL_GPL(nvmet_sq_init);
bool nvmet_req_init(struct nvmet_req *req, struct nvmet_cq *cq,
struct nvmet_sq *sq, struct nvmet_fabrics_ops *ops)
{
u8 flags = req->cmd->common.flags;
u16 status;
req->cq = cq;
req->sq = sq;
req->ops = ops;
req->sg = NULL;
req->sg_cnt = 0;
req->rsp->status = 0;
/* no support for fused commands yet */
if (unlikely(flags & (NVME_CMD_FUSE_FIRST | <API key>))) {
status = <API key> | NVME_SC_DNR;
goto fail;
}
/* either variant of SGLs is fine, as we don't support metadata */
if (unlikely((flags & NVME_CMD_SGL_ALL) != <API key> &&
(flags & NVME_CMD_SGL_ALL) != <API key>)) {
status = <API key> | NVME_SC_DNR;
goto fail;
}
if (unlikely(!req->sq->ctrl))
/* will return an error for any Non-connect command: */
status = <API key>(req);
else if (likely(req->sq->qid != 0))
status = nvmet_parse_io_cmd(req);
else if (req->cmd->common.opcode == <API key>)
status = <API key>(req);
else if (req->sq->ctrl->subsys->type == NVME_NQN_DISC)
status = <API key>(req);
else
status = <API key>(req);
if (status)
goto fail;
if (unlikely(!<API key>(&sq->ref))) {
status = <API key> | NVME_SC_DNR;
goto fail;
}
return true;
fail:
<API key>(req, status);
return false;
}
EXPORT_SYMBOL_GPL(nvmet_req_init);
void nvmet_req_uninit(struct nvmet_req *req)
{
percpu_ref_put(&req->sq->ref);
}
EXPORT_SYMBOL_GPL(nvmet_req_uninit);
static inline bool nvmet_cc_en(u32 cc)
{
return (cc >> NVME_CC_EN_SHIFT) & 0x1;
}
static inline u8 nvmet_cc_css(u32 cc)
{
return (cc >> NVME_CC_CSS_SHIFT) & 0x7;
}
static inline u8 nvmet_cc_mps(u32 cc)
{
return (cc >> NVME_CC_MPS_SHIFT) & 0xf;
}
static inline u8 nvmet_cc_ams(u32 cc)
{
return (cc >> NVME_CC_AMS_SHIFT) & 0x7;
}
static inline u8 nvmet_cc_shn(u32 cc)
{
return (cc >> NVME_CC_SHN_SHIFT) & 0x3;
}
static inline u8 nvmet_cc_iosqes(u32 cc)
{
return (cc >> <API key>) & 0xf;
}
static inline u8 nvmet_cc_iocqes(u32 cc)
{
return (cc >> <API key>) & 0xf;
}
static void nvmet_start_ctrl(struct nvmet_ctrl *ctrl)
{
lockdep_assert_held(&ctrl->lock);
if (nvmet_cc_iosqes(ctrl->cc) != NVME_NVM_IOSQES ||
nvmet_cc_iocqes(ctrl->cc) != NVME_NVM_IOCQES ||
nvmet_cc_mps(ctrl->cc) != 0 ||
nvmet_cc_ams(ctrl->cc) != 0 ||
nvmet_cc_css(ctrl->cc) != 0) {
ctrl->csts = NVME_CSTS_CFS;
return;
}
ctrl->csts = NVME_CSTS_RDY;
}
static void nvmet_clear_ctrl(struct nvmet_ctrl *ctrl)
{
lockdep_assert_held(&ctrl->lock);
/* XXX: tear down queues? */
ctrl->csts &= ~NVME_CSTS_RDY;
ctrl->cc = 0;
}
void nvmet_update_cc(struct nvmet_ctrl *ctrl, u32 new)
{
u32 old;
mutex_lock(&ctrl->lock);
old = ctrl->cc;
ctrl->cc = new;
if (nvmet_cc_en(new) && !nvmet_cc_en(old))
nvmet_start_ctrl(ctrl);
if (!nvmet_cc_en(new) && nvmet_cc_en(old))
nvmet_clear_ctrl(ctrl);
if (nvmet_cc_shn(new) && !nvmet_cc_shn(old)) {
nvmet_clear_ctrl(ctrl);
ctrl->csts |= <API key>;
}
if (!nvmet_cc_shn(new) && nvmet_cc_shn(old))
ctrl->csts &= ~<API key>;
mutex_unlock(&ctrl->lock);
}
static void nvmet_init_cap(struct nvmet_ctrl *ctrl)
{
/* command sets supported: NVMe command set: */
ctrl->cap = (1ULL << 37);
/* CC.EN timeout in 500msec units: */
ctrl->cap |= (15ULL << 24);
/* maximum queue entries supported: */
ctrl->cap |= NVMET_QUEUE_SIZE - 1;
}
u16 nvmet_ctrl_find_get(const char *subsysnqn, const char *hostnqn, u16 cntlid,
struct nvmet_req *req, struct nvmet_ctrl **ret)
{
struct nvmet_subsys *subsys;
struct nvmet_ctrl *ctrl;
u16 status = 0;
subsys = <API key>(req->port, subsysnqn);
if (!subsys) {
pr_warn("connect request for invalid subsystem %s!\n",
subsysnqn);
req->rsp->result.u32 = <API key>(subsysnqn);
return <API key> | NVME_SC_DNR;
}
mutex_lock(&subsys->lock);
list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry) {
if (ctrl->cntlid == cntlid) {
if (strncmp(hostnqn, ctrl->hostnqn, NVMF_NQN_SIZE)) {
pr_warn("hostnqn mismatch.\n");
continue;
}
if (!<API key>(&ctrl->ref))
continue;
*ret = ctrl;
goto out;
}
}
pr_warn("could not find controller %d for subsys %s / host %s\n",
cntlid, subsysnqn, hostnqn);
req->rsp->result.u32 = <API key>(cntlid);
status = <API key> | NVME_SC_DNR;
out:
mutex_unlock(&subsys->lock);
nvmet_subsys_put(subsys);
return status;
}
u16 <API key>(struct nvmet_req *req, struct nvme_command *cmd)
{
if (unlikely(!(req->sq->ctrl->cc & NVME_CC_ENABLE))) {
pr_err("got io cmd %d while CC.EN == 0 on qid = %d\n",
cmd->common.opcode, req->sq->qid);
return <API key> | NVME_SC_DNR;
}
if (unlikely(!(req->sq->ctrl->csts & NVME_CSTS_RDY))) {
pr_err("got io cmd %d while CSTS.RDY == 0 on qid = %d\n",
cmd->common.opcode, req->sq->qid);
req->ns = NULL;
return <API key> | NVME_SC_DNR;
}
return 0;
}
static bool <API key>(struct nvmet_subsys *subsys,
const char *hostnqn)
{
struct nvmet_host_link *p;
if (subsys->allow_any_host)
return true;
list_for_each_entry(p, &subsys->hosts, entry) {
if (!strcmp(nvmet_host_name(p->host), hostnqn))
return true;
}
return false;
}
static bool <API key>(struct nvmet_req *req,
const char *hostnqn)
{
struct nvmet_subsys_link *s;
list_for_each_entry(s, &req->port->subsystems, entry) {
if (<API key>(s->subsys, hostnqn))
return true;
}
return false;
}
bool nvmet_host_allowed(struct nvmet_req *req, struct nvmet_subsys *subsys,
const char *hostnqn)
{
lockdep_assert_held(&nvmet_config_sem);
if (subsys->type == NVME_NQN_DISC)
return <API key>(req, hostnqn);
else
return <API key>(subsys, hostnqn);
}
u16 nvmet_alloc_ctrl(const char *subsysnqn, const char *hostnqn,
struct nvmet_req *req, u32 kato, struct nvmet_ctrl **ctrlp)
{
struct nvmet_subsys *subsys;
struct nvmet_ctrl *ctrl;
int ret;
u16 status;
status = <API key> | NVME_SC_DNR;
subsys = <API key>(req->port, subsysnqn);
if (!subsys) {
pr_warn("connect request for invalid subsystem %s!\n",
subsysnqn);
req->rsp->result.u32 = <API key>(subsysnqn);
goto out;
}
status = <API key> | NVME_SC_DNR;
down_read(&nvmet_config_sem);
if (!nvmet_host_allowed(req, subsys, hostnqn)) {
pr_info("connect by host %s for subsystem %s not allowed\n",
hostnqn, subsysnqn);
req->rsp->result.u32 = <API key>(hostnqn);
up_read(&nvmet_config_sem);
status = <API key> | NVME_SC_DNR;
goto out_put_subsystem;
}
up_read(&nvmet_config_sem);
status = NVME_SC_INTERNAL;
ctrl = kzalloc(sizeof(*ctrl), GFP_KERNEL);
if (!ctrl)
goto out_put_subsystem;
mutex_init(&ctrl->lock);
nvmet_init_cap(ctrl);
INIT_WORK(&ctrl->async_event_work, <API key>);
INIT_LIST_HEAD(&ctrl->async_events);
memcpy(ctrl->subsysnqn, subsysnqn, NVMF_NQN_SIZE);
memcpy(ctrl->hostnqn, hostnqn, NVMF_NQN_SIZE);
kref_init(&ctrl->ref);
ctrl->subsys = subsys;
ctrl->cqs = kcalloc(subsys->max_qid + 1,
sizeof(struct nvmet_cq *),
GFP_KERNEL);
if (!ctrl->cqs)
goto out_free_ctrl;
ctrl->sqs = kcalloc(subsys->max_qid + 1,
sizeof(struct nvmet_sq *),
GFP_KERNEL);
if (!ctrl->sqs)
goto out_free_cqs;
ret = ida_simple_get(&cntlid_ida,
NVME_CNTLID_MIN, NVME_CNTLID_MAX,
GFP_KERNEL);
if (ret < 0) {
status = <API key> | NVME_SC_DNR;
goto out_free_sqs;
}
ctrl->cntlid = ret;
ctrl->ops = req->ops;
if (ctrl->subsys->type == NVME_NQN_DISC) {
/* Don't accept keep-alive timeout for discovery controllers */
if (kato) {
status = <API key> | NVME_SC_DNR;
goto out_free_sqs;
}
/*
* Discovery controllers use some arbitrary high value in order
* to cleanup stale discovery sessions
*
* From the latest base diff RC:
* "The Keep Alive command is not supported by
* Discovery controllers. A transport may specify a
* fixed Discovery controller activity timeout value
* (e.g., 2 minutes). If no commands are received
* by a Discovery controller within that time
* period, the controller may perform the
* actions for Keep Alive Timer expiration".
*/
ctrl->kato = NVMET_DISC_KATO;
} else {
/* keep-alive timeout in seconds */
ctrl->kato = DIV_ROUND_UP(kato, 1000);
}
<API key>(ctrl);
mutex_lock(&subsys->lock);
list_add_tail(&ctrl->subsys_entry, &subsys->ctrls);
mutex_unlock(&subsys->lock);
*ctrlp = ctrl;
return 0;
out_free_sqs:
kfree(ctrl->sqs);
out_free_cqs:
kfree(ctrl->cqs);
out_free_ctrl:
kfree(ctrl);
out_put_subsystem:
nvmet_subsys_put(subsys);
out:
return status;
}
static void nvmet_ctrl_free(struct kref *ref)
{
struct nvmet_ctrl *ctrl = container_of(ref, struct nvmet_ctrl, ref);
struct nvmet_subsys *subsys = ctrl->subsys;
<API key>(ctrl);
mutex_lock(&subsys->lock);
list_del(&ctrl->subsys_entry);
mutex_unlock(&subsys->lock);
flush_work(&ctrl->async_event_work);
cancel_work_sync(&ctrl->fatal_err_work);
ida_simple_remove(&cntlid_ida, ctrl->cntlid);
nvmet_subsys_put(subsys);
kfree(ctrl->sqs);
kfree(ctrl->cqs);
kfree(ctrl);
}
void nvmet_ctrl_put(struct nvmet_ctrl *ctrl)
{
kref_put(&ctrl->ref, nvmet_ctrl_free);
}
static void <API key>(struct work_struct *work)
{
struct nvmet_ctrl *ctrl =
container_of(work, struct nvmet_ctrl, fatal_err_work);
pr_err("ctrl %d fatal error occurred!\n", ctrl->cntlid);
ctrl->ops->delete_ctrl(ctrl);
}
void <API key>(struct nvmet_ctrl *ctrl)
{
mutex_lock(&ctrl->lock);
if (!(ctrl->csts & NVME_CSTS_CFS)) {
ctrl->csts |= NVME_CSTS_CFS;
INIT_WORK(&ctrl->fatal_err_work, <API key>);
schedule_work(&ctrl->fatal_err_work);
}
mutex_unlock(&ctrl->lock);
}
EXPORT_SYMBOL_GPL(<API key>);
static struct nvmet_subsys *<API key>(struct nvmet_port *port,
const char *subsysnqn)
{
struct nvmet_subsys_link *p;
if (!port)
return NULL;
if (!strncmp(<API key>, subsysnqn,
NVMF_NQN_SIZE)) {
if (!<API key>(&nvmet_disc_subsys->ref))
return NULL;
return nvmet_disc_subsys;
}
down_read(&nvmet_config_sem);
list_for_each_entry(p, &port->subsystems, entry) {
if (!strncmp(p->subsys->subsysnqn, subsysnqn,
NVMF_NQN_SIZE)) {
if (!<API key>(&p->subsys->ref))
break;
up_read(&nvmet_config_sem);
return p->subsys;
}
}
up_read(&nvmet_config_sem);
return NULL;
}
struct nvmet_subsys *nvmet_subsys_alloc(const char *subsysnqn,
enum nvme_subsys_type type)
{
struct nvmet_subsys *subsys;
subsys = kzalloc(sizeof(*subsys), GFP_KERNEL);
if (!subsys)
return NULL;
subsys->ver = NVME_VS(1, 3, 0); /* NVMe 1.3.0 */
/* generate a random serial number as our controllers are ephemeral: */
get_random_bytes(&subsys->serial, sizeof(subsys->serial));
switch (type) {
case NVME_NQN_NVME:
subsys->max_qid = NVMET_NR_QUEUES;
break;
case NVME_NQN_DISC:
subsys->max_qid = 0;
break;
default:
pr_err("%s: Unknown Subsystem type - %d\n", __func__, type);
kfree(subsys);
return NULL;
}
subsys->type = type;
subsys->subsysnqn = kstrndup(subsysnqn, NVMF_NQN_SIZE,
GFP_KERNEL);
if (!subsys->subsysnqn) {
kfree(subsys);
return NULL;
}
kref_init(&subsys->ref);
mutex_init(&subsys->lock);
INIT_LIST_HEAD(&subsys->namespaces);
INIT_LIST_HEAD(&subsys->ctrls);
INIT_LIST_HEAD(&subsys->hosts);
return subsys;
}
static void nvmet_subsys_free(struct kref *ref)
{
struct nvmet_subsys *subsys =
container_of(ref, struct nvmet_subsys, ref);
WARN_ON_ONCE(!list_empty(&subsys->namespaces));
kfree(subsys->subsysnqn);
kfree(subsys);
}
void <API key>(struct nvmet_subsys *subsys)
{
struct nvmet_ctrl *ctrl;
mutex_lock(&subsys->lock);
list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry)
ctrl->ops->delete_ctrl(ctrl);
mutex_unlock(&subsys->lock);
}
void nvmet_subsys_put(struct nvmet_subsys *subsys)
{
kref_put(&subsys->ref, nvmet_subsys_free);
}
static int __init nvmet_init(void)
{
int error;
error = <API key>();
if (error)
goto out;
error = nvmet_init_configfs();
if (error)
goto out_exit_discovery;
return 0;
out_exit_discovery:
<API key>();
out:
return error;
}
static void __exit nvmet_exit(void)
{
nvmet_exit_configfs();
<API key>();
ida_destroy(&cntlid_ida);
BUILD_BUG_ON(sizeof(struct <API key>) != 1024);
BUILD_BUG_ON(sizeof(struct <API key>) != 1024);
}
module_init(nvmet_init);
module_exit(nvmet_exit);
MODULE_LICENSE("GPL v2");
|
#include <linux/module.h>
#include <linux/param.h>
#include <linux/jiffies.h>
#include <linux/workqueue.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/power_supply.h>
#include <linux/idr.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <asm/unaligned.h>
#include <linux/time.h>
#include <linux/mfd/pmic8058.h>
#include <linux/regulator/pmic8058-regulator.h>
#include <linux/gpio.h>
#include <linux/regulator/consumer.h>
#include <linux/regulator/machine.h>
#include <linux/err.h>
#include <linux/qpnp-charger.h>
#include <linux/i2c/bq27520.h> /* use the same platform data as bq27520 */
#include <linux/of_gpio.h> //sjc0623 add
#ifdef <API key>
/*OPPO 2013-09-22 liaofuchun add for bq27541 encryption*/
#include <linux/random.h>
#include <linux/rtc.h>
extern char *<API key>(char *Message,char *Key,char *result);
#endif //<API key>
#ifdef <API key>
/* OPPO 2014-06-23 sjc Add begin for 14021 */
static int mcu_en_gpio = 0;
void mcu_en_gpio_set(int value)
{
if (value) {
if (gpio_is_valid(mcu_en_gpio))
gpio_set_value(mcu_en_gpio, 0);
} else {
if (gpio_is_valid(mcu_en_gpio)) {
gpio_set_value(mcu_en_gpio, 1);
usleep_range(10000, 10000);
gpio_set_value(mcu_en_gpio, 0);
}
}
}
#else
void mcu_en_gpio_set(int value)
{
return;
}
#endif //<API key>
extern int load_soc(void);//sjc1121
extern void backup_soc_ex(int soc); /* yangfangbiao@oneplus.cn, 2015/01/19 Add for sync with android 4.4 */
/* OPPO 2013-12-20 liaofuchun add for fastchg firmware update */
#ifdef <API key>
extern unsigned char <API key>[];
extern int pic_fw_ver_count;
extern int pic_need_to_up_fw;
extern int pic_have_updated;
extern int pic16f_fw_update(bool pull96);
#endif
/* OPPO 2013-12-20 liaofuchun add end */
#define DRIVER_VERSION "1.1.0"
/* Bq27541 standard data commands */
#define BQ27541_REG_CNTL 0x00
#define BQ27541_REG_AR 0x02
#define BQ27541_REG_ARTTE 0x04
#define BQ27541_REG_TEMP 0x06
#define BQ27541_REG_VOLT 0x08
#define BQ27541_REG_FLAGS 0x0A
#define BQ27541_REG_NAC 0x0C
#define BQ27541_REG_FAC 0x0e
#define BQ27541_REG_RM 0x10
#define BQ27541_REG_FCC 0x12
#define BQ27541_REG_AI 0x14
#define BQ27541_REG_TTE 0x16
#define BQ27541_REG_TTF 0x18
#define BQ27541_REG_SI 0x1a
#define BQ27541_REG_STTE 0x1c
#define BQ27541_REG_MLI 0x1e
#define BQ27541_REG_MLTTE 0x20
#define BQ27541_REG_AE 0x22
#define BQ27541_REG_AP 0x24
#define BQ27541_REG_TTECP 0x26
#define BQ27541_REG_SOH 0x28
#define BQ27541_REG_SOC 0x2c
#define BQ27541_REG_NIC 0x2e
#define BQ27541_REG_ICR 0x30
#define BQ27541_REG_LOGIDX 0x32
#define BQ27541_REG_LOGBUF 0x34
#define BQ27541_FLAG_DSC BIT(0)
#define BQ27541_FLAG_FC BIT(9)
#define BQ27541_CS_DLOGEN BIT(15)
#define BQ27541_CS_SS BIT(13)
/* Control subcommands */
#define <API key> 0x0000
#define <API key> 0x0001
#define <API key> 0x0002
#define <API key> 0x0003
#define <API key> 0x0004
#define <API key> 0x0007
#define <API key> 0x0008
#define <API key> 0x0009
#define <API key> 0x000a
#define <API key> 0x000b
#define BQ27541_SUBCMD_OCV 0x000c
#define <API key> 0x000d
#define <API key> 0x000e
#define <API key> 0x0011
#define <API key> 0x0012
#define <API key> 0x0013
#define <API key> 0x0014
#define <API key> 0x0015
#define <API key> 0x0018
#define <API key> 0x0019
#define <API key> 0x0020
#define <API key> 0x0021
#define <API key> 0x0023
#define <API key> 0x0040
#define <API key> 0x0041
#define <API key> (-2731)
#define BQ27541_INIT_DELAY ((HZ)*1)
/* OPPO 2013-08-24 wangjc Add begin for filter soc. */
#ifdef <API key>
#define <API key> 4
#define <API key> 13//40sec
#ifdef <API key>
/* yangfangbiao@oneplus.cn, 2015/01/06 Add for sync with KK charge standard */
#define <API key> 20//40 1min
#define <API key> 50//60 2.5min
#define <API key> 100//120 5min
#define <API key> 20//30 1min
#endif /*<API key>*/
#define <API key> 20 /* yangfangbiao@oneplus.cn, 2015/01/06 Add for sync with KK charge standard */
#define TEN_MINUTES 600
#endif
/* OPPO 2013-08-24 wangjc Add end */
/* If the system has several batteries we need a different name for each
* of them...
*/
static DEFINE_IDR(battery_id);
static DEFINE_MUTEX(battery_mutex);
struct bq27541_device_info;
struct <API key> {
int (*read)(u8 reg, int *rt_value, int b_single,
struct bq27541_device_info *di);
};
struct bq27541_device_info {
struct device *dev;
int id;
struct <API key> *bus;
struct i2c_client *client;
struct work_struct counter;
/* 300ms delay is needed after bq27541 is powered up
* and before any successful I2C transaction
*/
struct delayed_work hw_config;
/* OPPO 2013-08-24 wangjc Add begin for filter soc. */
#ifdef <API key>
int cc_pre;
int fcc_pre;
int soc_pre;
int temp_pre;
int batt_vol_pre;
int current_pre;
int saltate_counter;
int report_count;
bool is_authenticated; //wangjc add for authentication
bool fast_chg_started;
bool <API key>;
bool fast_normal_to_warm; //lfc add for fastchg over temp
int battery_type; //lfc add for battery type
struct power_supply *batt_psy;
int irq;
struct work_struct fastcg_work;
bool alow_reading;
struct timer_list watchdog;
struct wake_lock fastchg_wake_lock;
bool fast_chg_allow;
bool fast_low_temp_full;
/* jingchun.wang@Onlinerd.Driver, 2014/02/12 Add for retry when config fail */
int retry_count;
/* jingchun.wang@Onlinerd.Driver, 2014/02/27 Add for get right soc when sleep long time */
unsigned long rtc_resume_time;
unsigned long rtc_suspend_time;
atomic_t suspended;
#endif
bool fast_chg_ing;
/* OPPO 2013-08-24 wangjc Add end */
};
static int coulomb_counter;
static spinlock_t lock; /* protect access to coulomb_counter */
static struct bq27541_device_info *bq27541_di;
static int <API key>(u8 reg, unsigned short subcmd,
struct bq27541_device_info *di);
static int bq27541_read(u8 reg, int *rt_value, int b_single,
struct bq27541_device_info *di)
{
return di->bus->read(reg, rt_value, b_single, di);
}
/*
* Return the battery temperature in tenths of degree Celsius
* Or < 0 if something fails.
*/
static int <API key>(struct bq27541_device_info *di)
{
int ret;
int temp = 0;
static int count = 0;
#ifdef <API key>
/* jingchun.wang@Onlinerd.Driver, 2014/02/27 Add for get right soc when sleep long time */
if(atomic_read(&di->suspended) == 1) {
return di->temp_pre + <API key>;
}
#endif /*<API key>*/
if(di->alow_reading == true) {
ret = bq27541_read(BQ27541_REG_TEMP, &temp, 0, di);
#ifdef <API key>
/* jingchun.wang@Onlinerd.Driver, 2014/01/08 Add for don't report battery not connect when reading error once. */
if (ret) {
count++;
dev_err(di->dev, "error reading temperature\n");
if(count > 1) {
count = 0;
/* jingchun.wang@Onlinerd.Driver, 2014/01/22 Add for it report bad status when plug out battery */
di->temp_pre = -400 - <API key>;
return -400;
} else {
return di->temp_pre + <API key>;
}
}
count = 0;
#endif /*<API key>*/
} else {
return di->temp_pre + <API key>;
}
di->temp_pre = temp;
return temp + <API key>;
}
/* OPPO 2013-08-24 wangjc Add begin for add adc interface. */
#ifdef <API key>
#define BQ27541_REG_CC 0x2a
static int bq27541_battery_cc(struct bq27541_device_info *di)/* yangfangbiao@oneplus.cn, 2015/02/13 Add cc interface */
{
int ret;
int cc = 0;
if (atomic_read(&di->suspended) == 1)
return di->cc_pre;
if (di->alow_reading == true) {
ret = bq27541_read(BQ27541_REG_CC, &cc, 0, di);
if (ret) {
dev_err(di->dev, "error reading cc.\n");
return ret;
}
} else {
return di->cc_pre;
}
di->cc_pre = cc;
return cc;
}
static int bq27541_battery_fcc(struct bq27541_device_info *di)//sjc20150105
{
int ret;
int fcc = 0;
if (di->alow_reading == true) {
ret = bq27541_read(BQ27541_REG_FCC, &fcc, 0, di);
if (ret) {
dev_err(di->dev, "error reading fcc.\n");
return ret;
}
}
return fcc;
}
static int <API key>(struct bq27541_device_info *di)
{
int ret;
int cap = 0;
if(di->alow_reading == true) {
ret = bq27541_read(BQ27541_REG_RM, &cap, 0, di);
if (ret) {
dev_err(di->dev, "error reading capacity.\n");
return ret;
}
}
return cap;
}
static int <API key>(struct bq27541_device_info *di);
extern int get_charging_status(void);
extern int <API key>(void);
static int <API key>(struct bq27541_device_info *di, int soc)
{
union <API key> ret = {0,};
unsigned int soc_calib;
int counter_temp = 0;
static int charging_status = 0;//sjc1121
static int charging_status_pre = 0; /* yangfangbiao@oneplus.cn, 2015/01/06 Modify for sync with KK charge standard */
int soc_load;//sjc1121
int soc_temp;
if(!di->batt_psy){
di->batt_psy = <API key>("battery");
//get the soc before reboot
soc_load = load_soc();
if (soc_load == -1) {
//get last soc error
di->soc_pre = soc;
} else if(abs(soc - soc_load) > <API key>) {
//the battery maybe changed
di->soc_pre = soc;
} else {
//compare the soc and the last soc
if(soc_load > soc) {
di->soc_pre = soc_load -1;
} else {
di->soc_pre = soc_load;
}
}
#ifdef <API key>
/* yangfangbiao@oneplus.cn, 2015/02/3 Modify for V2.4 charge standard */
if (!di->batt_psy) {
return di->soc_pre;
}
#endif /*<API key>*/
//store the soc when boot first time
backup_soc_ex(di->soc_pre);
}
soc_temp = di->soc_pre;
if(di->batt_psy){
ret.intval = get_charging_status();//sjc20150104
if(ret.intval == <API key> || ret.intval == <API key>) { // is charging
charging_status = 1;
} else {
charging_status = 0;
}
if (charging_status ^ charging_status_pre) {
charging_status_pre = charging_status;
di->saltate_counter = 0;
}
if (charging_status) { // is charging
/* yangfangbiao@oneplus.cn, 2015/01/06 Modify begin for sync with KK charge standard */
if (ret.intval == <API key>) {
soc_calib = di->soc_pre;
if (di->soc_pre < 100
&& (<API key>() == <API key>
|| <API key>() == <API key>)) {//sjc20150104
if (di->saltate_counter < <API key>) {
di->saltate_counter++;
} else {
soc_calib = di->soc_pre + 1;
di->saltate_counter = 0;
}
}
} else {
/* yangfangbiao@oneplus.cn, 2015/01/06 Modify end for sync with KK charge standard */
if(abs(soc - di->soc_pre) > 0) {
di->saltate_counter++;
if(di->saltate_counter < <API key>)
return di->soc_pre;
else
di->saltate_counter = 0;
}
else
di->saltate_counter = 0;
if(soc > di->soc_pre) {
soc_calib = di->soc_pre + 1;
} else if(soc < (di->soc_pre - 2)) {
/* jingchun.wang@Onlinerd.Driver, 2013/04/14 Add for allow soc fail when charging. */
soc_calib = di->soc_pre - 1;
} else {
soc_calib = di->soc_pre;
}
/* jingchun.wang@Onlinerd.Driver, 2013/12/12 Add for set capacity to 100 when full in normal temp */
if(ret.intval == <API key>) {
if(soc > 94) {
soc_calib = 100;
}
}
}
} else { // not charging
if ((abs(soc - di->soc_pre) > 0)
|| (di->batt_vol_pre <= 3300 * 1000 && di->batt_vol_pre > 2500 * 1000)) {//sjc1118 add for batt_vol is too low but soc is not jumping
di->saltate_counter++;
if(di->soc_pre == 100) {
counter_temp = <API key>;//t>=5min
} else if (di->soc_pre > 95) {
counter_temp = <API key>;///t>=2.5min
} else if (di->soc_pre > 60) {
counter_temp = <API key>;//t>=1min
} else {
counter_temp = <API key>;//t>=40sec
}
/* sjc1020, when batt_vol is too low(and soc is jumping), decrease faster to avoid dead battery shutdown */
if (di->batt_vol_pre <= 3300 * 1000 && di->batt_vol_pre > 2500 * 1000 && di->soc_pre <= 10) {
if (<API key>(di) <= 3300 * 1000 && <API key>(di) > 2500 * 1000) {//check again
counter_temp = <API key> - 1;//about 9s
}
}
if(di->saltate_counter < counter_temp)
return di->soc_pre;
else
di->saltate_counter = 0;
}
else
di->saltate_counter = 0;
if(soc < di->soc_pre)
soc_calib = di->soc_pre - 1;
else if (di->batt_vol_pre <= 3300 * 1000 && di->batt_vol_pre > 2500 * 1000 && di->soc_pre > 0)//sjc1118 add for batt_vol is too low but soc is not jumping
soc_calib = di->soc_pre - 1;
else
soc_calib = di->soc_pre;
}
} else {
soc_calib = soc;
}
if(soc_calib > 100)
soc_calib = 100;
di->soc_pre = soc_calib;
if(soc_temp != soc_calib) {
//store when soc changed
backup_soc_ex(soc_calib);
pr_info("soc:%d, soc_calib:%d\n", soc, soc_calib);
}
return soc_calib;
}
static int bq27541_battery_soc(struct bq27541_device_info *di, bool raw)
{
int ret;
int soc = 0;
#ifdef <API key>
/* jingchun.wang@Onlinerd.Driver, 2014/02/27 Add for get right soc when sleep long time */
if(atomic_read(&di->suspended) == 1) {
return di->soc_pre;
}
#endif /*<API key>*/
if(di->alow_reading == true) {
ret = bq27541_read(BQ27541_REG_SOC, &soc, 0, di);
if (ret) {
dev_err(di->dev, "error reading soc.ret:%d\n",ret);
goto read_soc_err;
}
} else {
if(di->soc_pre)
return di->soc_pre;
else
return 0;
}
if (raw == true) {
if(soc > 90) {
soc += 2;
}
if(soc <= di->soc_pre) {
di->soc_pre = soc;
}
}
soc = <API key>(di,soc);
return soc;
read_soc_err:
if(di->soc_pre)
return di->soc_pre;
else
return 0;
}
static int <API key>(struct bq27541_device_info *di)
{
int ret;
int curr = 0;
#ifdef <API key>
/* jingchun.wang@Onlinerd.Driver, 2014/02/27 Add for get right soc when sleep long time */
if(atomic_read(&di->suspended) == 1) {
return -di->current_pre;
}
#endif /*<API key>*/
if(di->alow_reading == true) {
ret = bq27541_read(BQ27541_REG_AI, &curr, 0, di);
if (ret) {
dev_err(di->dev, "error reading current.\n");
return ret;
}
} else {
return -di->current_pre;
}
// negative current
if(curr&0x8000)
curr = -((~(curr-1))&0xFFFF);
di->current_pre = curr;
return -curr;
}
#endif
/* OPPO 2013-08-24 wangjc Add end */
/*
* Return the battery Voltage in milivolts
* Or < 0 if something fails.
*/
static int <API key>(struct bq27541_device_info *di)
{
int ret;
int volt = 0;
#ifdef <API key>
/* jingchun.wang@Onlinerd.Driver, 2014/02/27 Add for get right soc when sleep long time */
if(atomic_read(&di->suspended) == 1) {
return di->batt_vol_pre;
}
#endif /*<API key>*/
if(di->alow_reading == true) {
ret = bq27541_read(BQ27541_REG_VOLT, &volt, 0, di);
if (ret) {
dev_err(di->dev, "error reading voltage,ret:%d\n",ret);
return ret;
}
} else {
return di->batt_vol_pre;
}
di->batt_vol_pre = volt * 1000;
return volt * 1000;
}
static void bq27541_cntl_cmd(struct bq27541_device_info *di,
int subcmd)
{
<API key>(BQ27541_REG_CNTL, subcmd, di);
}
/*
* i2c specific code
*/
static int <API key>(u8 reg, unsigned short subcmd,
struct bq27541_device_info *di)
{
struct i2c_msg msg;
unsigned char data[3];
int ret;
if (!di->client)
return -ENODEV;
memset(data, 0, sizeof(data));
data[0] = reg;
data[1] = subcmd & 0x00FF;
data[2] = (subcmd & 0xFF00) >> 8;
msg.addr = di->client->addr;
msg.flags = 0;
msg.len = 3;
msg.buf = data;
ret = i2c_transfer(di->client->adapter, &msg, 1);
if (ret < 0)
return -EIO;
return 0;
}
static int bq27541_chip_config(struct bq27541_device_info *di)
{
int flags = 0, ret = 0;
bq27541_cntl_cmd(di, <API key>);
udelay(66);
ret = bq27541_read(BQ27541_REG_CNTL, &flags, 0, di);
if (ret < 0) {
dev_err(di->dev, "error reading register %02x ret = %d\n",
BQ27541_REG_CNTL, ret);
return ret;
}
udelay(66);
bq27541_cntl_cmd(di, <API key>);
udelay(66);
if (!(flags & BQ27541_CS_DLOGEN)) {
bq27541_cntl_cmd(di, <API key>);
udelay(66);
}
return 0;
}
static void <API key>(struct work_struct *work)
{
int value = 0, temp = 0, index = 0, ret = 0;
struct bq27541_device_info *di;
unsigned long flags;
int count = 0;
di = container_of(work, struct bq27541_device_info, counter);
/* retrieve 30 values from FIFO of coulomb data logging buffer
* and average over time
*/
do {
ret = bq27541_read(BQ27541_REG_LOGBUF, &temp, 0, di);
if (ret < 0)
break;
if (temp != 0x7FFF) {
++count;
value += temp;
}
/* delay 66uS, waiting time between continuous reading
* results
*/
udelay(66);
ret = bq27541_read(BQ27541_REG_LOGIDX, &index, 0, di);
if (ret < 0)
break;
udelay(66);
} while (index != 0 || temp != 0x7FFF);
if (ret < 0) {
dev_err(di->dev, "Error reading datalog register\n");
return;
}
if (count) {
spin_lock_irqsave(&lock, flags);
coulomb_counter = value/count;
<API key>(&lock, flags);
}
}
static int <API key>(void)
{
return <API key>(bq27541_di);
}
static int <API key>(void)
{
return <API key>(bq27541_di);
}
static int <API key>(void)
{
return 1;
}
static int <API key>(void)
{
return 1;
}
static int <API key>(void)
{
return 1;
}
/* OPPO 2013-08-24 wangjc Add begin for add adc interface. */
#ifdef <API key>
static int bq27541_get_batt_cc(void)/* yangfangbiao@oneplus.cn, 2015/02/13 Add cc interface */
{
return bq27541_battery_cc(bq27541_di);
}
static int <API key>(void)//sjc20150105
{
return bq27541_battery_fcc(bq27541_di);
}
static int <API key>(void)
{
return <API key>(bq27541_di);
}
static int <API key>(void)
{
return bq27541_battery_soc(bq27541_di, false);
}
static int <API key>(void)
{
return <API key>(bq27541_di);
}
//wangjc add for authentication
static int <API key>(void)
{
if(bq27541_di) {
return bq27541_di->is_authenticated;
}
return false;
}
static int <API key>(void)
{
if(bq27541_di) {
return bq27541_di->fast_chg_started;
}
return false;
}
static int <API key>(void)
{
if(bq27541_di) {
//pr_err("%s <API key>:%d\n",__func__,bq27541_di-><API key>);
return bq27541_di-><API key>;
}
return false;
}
static int <API key>(void)
{
if(bq27541_di) {
bq27541_di-><API key> = false;
}
return 0;
}
static int <API key>(void)
{
if(bq27541_di) {
return bq27541_di->fast_low_temp_full;
}
return false;
}
static int <API key>(void)
{
if(bq27541_di) {
return bq27541_di->fast_low_temp_full = false;
}
return 0;
}
#endif
/* OPPO 2013-08-24 wangjc Add end */
/* OPPO 2013-12-12 liaofuchun add for set/get fastchg allow begin*/
static int <API key>(void)
{
if(bq27541_di) {
//pr_err("%s <API key>:%d\n",__func__,bq27541_di-><API key>);
return bq27541_di->fast_normal_to_warm;
}
return 0;
}
static int <API key>(void)
{
if(bq27541_di) {
bq27541_di->fast_normal_to_warm = false;
}
return 0;
}
static int <API key>(int enable)
{
if(bq27541_di) {
bq27541_di->fast_chg_allow = enable;
}
return 0;
}
static int <API key>(void)
{
if(bq27541_di) {
return bq27541_di->fast_chg_allow;
}
return 0;
}
static int <API key>(void)
{
if(bq27541_di) {
return bq27541_di->fast_chg_ing;
}
return 0;
}
/* OPPO 2013-12-12 liaofuchun add for set/get fastchg allow end */
static struct qpnp_battery_gauge bq27541_batt_gauge = {
.get_battery_mvolts = <API key>,
.<API key> = <API key>,
.is_battery_present = <API key>,
.<API key> = <API key>,
.is_battery_id_valid = <API key>,
/* OPPO 2013-09-30 wangjc Add begin for add new interface */
#ifdef <API key>
.get_batt_cc = bq27541_get_batt_cc, /* yangfangbiao@oneplus.cn, 2015/02/13 Add cc interface */
.get_batt_fcc = <API key>, /* yangfangbiao@oneplus.cn, 2015/01/06 Add for sync with KK charge standard */
.<API key> = <API key>,
.get_battery_soc = <API key>,
.get_average_current = <API key>,
//wangjc add for authentication
.<API key> = <API key>,
.fast_chg_started = <API key>,
.<API key> = <API key>,
.<API key> = <API key>,
.set_fast_chg_allow = <API key>,
.get_fast_chg_allow = <API key>,
.fast_normal_to_warm = <API key>,
.<API key> = <API key>,
.get_fast_chg_ing = <API key>,
.<API key> = <API key>,
.<API key> = <API key>,
#endif
/* OPPO 2013-09-30 wangjc Add end */
};
static bool <API key>(struct i2c_client *client);
static int <API key>(struct i2c_client *client);
static void bq27541_hw_config(struct work_struct *work)
{
int ret = 0, flags = 0, type = 0, fw_ver = 0;
struct bq27541_device_info *di;
di = container_of(work, struct bq27541_device_info, hw_config.work);
ret = bq27541_chip_config(di);
if (ret) {
dev_err(di->dev, "Failed to config Bq27541\n");
#ifdef <API key>
/* jingchun.wang@Onlinerd.Driver, 2014/02/12 Add for retry when config fail */
di->retry_count
if(di->retry_count > 0) {
<API key>(&di->hw_config, HZ);
}
#endif /*<API key>*/
return;
}
<API key>(&bq27541_batt_gauge);
bq27541_cntl_cmd(di, <API key>);
udelay(66);
bq27541_read(BQ27541_REG_CNTL, &flags, 0, di);
bq27541_cntl_cmd(di, <API key>);
udelay(66);
bq27541_read(BQ27541_REG_CNTL, &type, 0, di);
bq27541_cntl_cmd(di, <API key>);
udelay(66);
bq27541_read(BQ27541_REG_CNTL, &fw_ver, 0, di);
#ifdef <API key>
/*OPPO 2013-09-18 liaofuchun add begin for check authenticate data*/
di->is_authenticated = <API key>(di->client);
di->battery_type = <API key>(di->client);
#endif //<API key>
dev_info(di->dev, "DEVICE_TYPE is 0x%02X, FIRMWARE_VERSION is 0x%02X\n",
type, fw_ver);
dev_info(di->dev, "Complete bq27541 configuration 0x%02X\n", flags);
}
static int bq27541_read_i2c(u8 reg, int *rt_value, int b_single,
struct bq27541_device_info *di)
{
struct i2c_client *client = di->client;
/* OPPO 2013-12-09 wangjc Modify begin for use standard i2c interface */
#ifndef <API key>
struct i2c_msg msg[1];
#else
struct i2c_msg msg[2];
#endif
/* OPPO 2013-12-09 wangjc Modify end */
unsigned char data[2];
int err;
if (!client->adapter)
return -ENODEV;
/* OPPO 2013-09-30 wangjc Add begin for eliminate conflict */
#ifdef <API key>
mutex_lock(&battery_mutex);
#endif
/* OPPO 2013-09-30 wangjc Add end */
/* OPPO 2013-12-09 wangjc Modify begin for use standard i2c interface */
#ifndef <API key>
msg->addr = client->addr;
msg->flags = 0;
msg->len = 1;
msg->buf = data;
data[0] = reg;
err = i2c_transfer(client->adapter, msg, 1);
if (err >= 0) {
if (!b_single)
msg->len = 2;
else
msg->len = 1;
msg->flags = I2C_M_RD;
err = i2c_transfer(client->adapter, msg, 1);
if (err >= 0) {
if (!b_single)
*rt_value = get_unaligned_le16(data);
else
*rt_value = data[0];
mutex_unlock(&battery_mutex);
return 0;
}
}
#else
/* Write register */
msg[0].addr = client->addr;
msg[0].flags = 0;
msg[0].len = 1;
msg[0].buf = data;
data[0] = reg;
/* Read data */
msg[1].addr = client->addr;
msg[1].flags = I2C_M_RD;
if (!b_single)
msg[1].len = 2;
else
msg[1].len = 1;
msg[1].buf = data;
err = i2c_transfer(client->adapter, msg, 2);
if (err >= 0) {
if (!b_single)
*rt_value = get_unaligned_le16(data);
else
*rt_value = data[0];
mutex_unlock(&battery_mutex);
return 0;
}
#endif
/* OPPO 2013-12-09 wangjc Modify end */
/* OPPO 2013-09-30 wangjc Add begin for eliminate conflict */
#ifdef <API key>
mutex_unlock(&battery_mutex);
#endif
/* OPPO 2013-09-30 wangjc Add end */
return err;
}
#ifdef <API key>
static int reg;
static int subcmd;
static ssize_t bq27541_read_stdcmd(struct device *dev,
struct device_attribute *attr, char *buf)
{
int ret;
int temp = 0;
struct platform_device *client;
struct bq27541_device_info *di;
client = to_platform_device(dev);
di = <API key>(client);
if (reg <= BQ27541_REG_ICR && reg > 0x00) {
ret = bq27541_read(reg, &temp, 0, di);
if (ret)
ret = snprintf(buf, PAGE_SIZE, "Read Error!\n");
else
ret = snprintf(buf, PAGE_SIZE, "0x%02x\n", temp);
} else
ret = snprintf(buf, PAGE_SIZE, "Register Error!\n");
return ret;
}
static ssize_t <API key>(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
ssize_t ret = strnlen(buf, PAGE_SIZE);
int cmd;
sscanf(buf, "%x", &cmd);
reg = cmd;
return ret;
}
static ssize_t bq27541_read_subcmd(struct device *dev,
struct device_attribute *attr, char *buf)
{
int ret;
int temp = 0;
struct platform_device *client;
struct bq27541_device_info *di;
client = to_platform_device(dev);
di = <API key>(client);
if (subcmd == <API key> ||
subcmd == <API key> ||
subcmd == <API key> ||
subcmd == <API key>) {
bq27541_cntl_cmd(di, subcmd); /* Retrieve Chip status */
udelay(66);
ret = bq27541_read(BQ27541_REG_CNTL, &temp, 0, di);
if (ret)
ret = snprintf(buf, PAGE_SIZE, "Read Error!\n");
else
ret = snprintf(buf, PAGE_SIZE, "0x%02x\n", temp);
} else
ret = snprintf(buf, PAGE_SIZE, "Register Error!\n");
return ret;
}
static ssize_t <API key>(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
ssize_t ret = strnlen(buf, PAGE_SIZE);
int cmd;
sscanf(buf, "%x", &cmd);
subcmd = cmd;
return ret;
}
static DEVICE_ATTR(std_cmd, S_IRUGO|S_IWUGO, bq27541_read_stdcmd,
<API key>);
static DEVICE_ATTR(sub_cmd, S_IRUGO|S_IWUGO, bq27541_read_subcmd,
<API key>);
static struct attribute *fs_attrs[] = {
&dev_attr_std_cmd.attr,
&dev_attr_sub_cmd.attr,
NULL,
};
static struct attribute_group fs_attr_group = {
.attrs = fs_attrs,
};
static struct platform_device this_device = {
.name = "bq27541-test",
.id = -1,
.dev.platform_data = NULL,
};
#endif
#ifdef <API key>
/*OPPO 2013-09-18 liaofuchun add begin for bq27541 authenticate */
#define BLOCKDATACTRL 0X61
#define DATAFLASHBLOCK 0X3F
#define AUTHENDATA 0X40
#define AUTHENCHECKSUM 0X54
#define MESSAGE_LEN 20
#define KEY_LEN 16
/* OPPO 2014-02-25 sjc Modify begin for FIND7OP not use authenticate */
#if defined (<API key>) || defined (<API key>)
static bool <API key>(struct i2c_client *client)
{
return true;
}
#else
static bool <API key>(struct i2c_client *client)
{
char recv_buf[MESSAGE_LEN]={0x0};
char send_buf[MESSAGE_LEN]={0x0};
char result[MESSAGE_LEN]={0x0};
char Key[KEY_LEN]={0x77,0x30,0xa1,0x28,0x0a,0xa1,0x13,0x20,0xef,0xcd,0xab,0x89,0x67,0x45,0x23,0x01};
char checksum_buf[1] ={0x0};
char authen_cmd_buf[1] = {0x00};
int i,rc;
pr_info("%s Enter\n",__func__);
// step 0: produce 20 bytes random data and checksum
get_random_bytes(send_buf,20);
for(i = 0;i < 20;i++){
checksum_buf[0] = checksum_buf[0] + send_buf[i];
}
checksum_buf[0] = 0xff - (checksum_buf[0]&0xff);
/* step 1: unseal mode->write 0x01 to blockdatactrl
authen_cmd_buf[0] = 0x01;
rc = <API key>(client,BLOCKDATACTRL,1,&authen_cmd_buf[0]);
} */
// step 1: seal mode->write 0x00 to dataflashblock
rc = <API key>(client,DATAFLASHBLOCK,1,&authen_cmd_buf[0]);
if( rc < 0 ){
pr_info("%s i2c write error\n",__func__);
return false;
}
// step 2: write 20 bytes to authendata_reg
<API key>(client,AUTHENDATA,MESSAGE_LEN,&send_buf[0]);
msleep(1);
// step 3: write checksum to authenchecksum_reg for compute
<API key>(client,AUTHENCHECKSUM,1,&checksum_buf[0]);
msleep(50);
// step 4: read authendata
<API key>(client,AUTHENDATA,MESSAGE_LEN,&recv_buf[0]);
// step 5: phone do hmac(sha1-generic) algorithm
<API key>(send_buf,Key,result);
// step 6: compare recv_buf from bq27541 and result by phone
rc = strncmp(recv_buf,result,MESSAGE_LEN);
if(rc == 0){
pr_info("<API key> success\n");
return true;
}
pr_info("<API key> error,dump buf:\n");
for(i = 0;i < 20;i++){
pr_info("send_buf[%d]:0x%x,recv_buf[%d]:0x%x ?= result[%d]:0x%x\n",i,send_buf[i],i,recv_buf[i],i,result[i]);
}
return false;
}
#endif //<API key>
/* OPPO 2014-02-25 sjc Modify end */
#endif //<API key>
#ifdef <API key>
//Fuchun.Liao@EXP.Driver,2014/01/10 add for check battery type
#define BATTERY_2700MA 0
#define BATTERY_3000MA 1
#define TYPE_INFO_LEN 8
#if defined (<API key>) || defined (<API key>)
static int <API key>(struct i2c_client *client)
{
return BATTERY_3000MA;
}
#else //defined (<API key>) || defined (<API key>)
/* jingchun.wang@Onlinerd.Driver, 2014/03/10 Modify for 14001 */
static int <API key>(struct i2c_client *client)
{
char blockA_cmd_buf[1] = {0x01};
char rc = 0;
char recv_buf[TYPE_INFO_LEN] = {0x0};
int i = 0;
rc = <API key>(client,DATAFLASHBLOCK,1,&blockA_cmd_buf[0]);
if( rc < 0 ){
pr_info("%s i2c write error\n",__func__);
return 0;
}
msleep(30); //it is needed
<API key>(client,AUTHENDATA,TYPE_INFO_LEN,&recv_buf[0]);
if((recv_buf[0] == 0x01) && (recv_buf[1] == 0x09) && (recv_buf[2] == 0x08) && (recv_buf[3] == 0x06))
rc = BATTERY_2700MA;
else if((recv_buf[0] == 0x02) && (recv_buf[1] == 0x00) && (recv_buf[2] == 0x01) && (recv_buf[3] == 0x03))
rc = BATTERY_3000MA;
else {
for(i = 0;i < TYPE_INFO_LEN;i++)
pr_info("%s error,recv_buf[%d]:0x%x\n",__func__,i,recv_buf[i]);
rc = BATTERY_2700MA;
}
pr_info("%s battery_type:%d\n",__func__,rc);
return rc;
}
#endif //defined (<API key>) || defined (<API key>)
#endif //<API key>
/* OPPO 2013-12-12 liaofuchun add for fastchg */
#ifdef <API key>
#define AP_TX_EN GPIO_CFG(0, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define AP_TX_DIS GPIO_CFG(0, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA)
static irqreturn_t irq_rx_handler(int irq, void *dev_id)
{
struct bq27541_device_info *di = dev_id;
//pr_info("%s\n", __func__);
schedule_work(&di->fastcg_work);
return IRQ_HANDLED;
}
#define AP_SWITCH_USB GPIO_CFG(96, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
static void fastcg_work_func(struct work_struct *work)
{
int data = 0;
int i;
int bit = 0;
int retval = 0;
int ret_info = 0;
static int fw_ver_info = 0;
int volt = 0;
int temp = 0;
int soc = 0;
int current_now = 0;
int remain_cap = 0;
static bool isnot_power_on = 0;
free_irq(bq27541_di->irq, bq27541_di);
for(i = 0; i < 7; i++) {
gpio_set_value(0, 0);
gpio_tlmm_config(AP_TX_EN, GPIO_CFG_ENABLE);
usleep_range(1000,1000);
gpio_set_value(0, 1);
gpio_tlmm_config(AP_TX_DIS, GPIO_CFG_ENABLE);
usleep_range(19000,19000);
bit = gpio_get_value(1);
data |= bit<<(6-i);
if((i == 2) && (data != 0x50) && (!fw_ver_info)){ //data recvd not start from "101"
pr_err("%s data err:%d\n",__func__,data);
if(bq27541_di->fast_chg_started == true) {
bq27541_di->alow_reading = true;
bq27541_di->fast_chg_started = false;
bq27541_di->fast_chg_allow = false;
bq27541_di-><API key> = false;
bq27541_di->fast_normal_to_warm = false;
bq27541_di->fast_chg_ing = false;
gpio_set_value(96, 0);
mcu_en_gpio_set(1);//sjc0623 add
retval = gpio_tlmm_config(AP_SWITCH_USB, GPIO_CFG_ENABLE);
if (retval) {
pr_err("%s switch usb error %d\n", __func__, retval);
}
<API key>(bq27541_di->batt_psy);
}
goto out;
}
}
pr_err("%s recv data:0x%x\n", __func__, data);
//lfc add for <API key> NULL pointer when batt_psy unregistered
if(bq27541_di->batt_psy == NULL){
msleep(2);
gpio_tlmm_config(GPIO_CFG(1,0,GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),1);
<API key>(1, 0);
retval = request_irq(bq27541_di->irq, irq_rx_handler, IRQF_TRIGGER_RISING, "mcu_data", bq27541_di); //0X01:rising edge,0x02:falling edge
if(retval < 0)
pr_err("%s request ap rx irq failed.\n", __func__);
return ;
}
if(data == 0x52) {
//request fast charging
wake_lock(&bq27541_di->fastchg_wake_lock);
pic_need_to_up_fw = 0;
fw_ver_info = 0;
bq27541_di->alow_reading = false;
bq27541_di->fast_chg_started = true;
bq27541_di->fast_chg_allow = false;
bq27541_di->fast_normal_to_warm = false;
mod_timer(&bq27541_di->watchdog,
jiffies + msecs_to_jiffies(10000));
if(!isnot_power_on){
isnot_power_on = 1;
ret_info = 0x1;
} else {
ret_info = 0x2;
}
} else if(data == 0x54) {
//fast charge stopped
bq27541_di->alow_reading = true;
bq27541_di->fast_chg_started = false;
bq27541_di->fast_chg_allow = false;
bq27541_di-><API key> = false;
bq27541_di->fast_normal_to_warm = false;
bq27541_di->fast_chg_ing = false;
//switch off fast chg
pr_info("%s fastchg stop unexpectly,switch off fastchg\n", __func__);
gpio_set_value(96, 0);
mcu_en_gpio_set(1);//sjc0623 add
retval = gpio_tlmm_config(AP_SWITCH_USB, GPIO_CFG_ENABLE);
if (retval) {
pr_err("%s switch usb error %d\n", __func__, retval);
}
del_timer(&bq27541_di->watchdog);
ret_info = 0x2;
} else if(data == 0x58) {
//tell ap can read i2c
bq27541_di->alow_reading = true;
//reading
bq27541_di->fast_chg_ing = true;
volt = <API key>();
temp = <API key>();
remain_cap = <API key>();
soc = <API key>();
current_now = <API key>();
pr_err("%s volt:%d,temp:%d,remain_cap:%d,soc:%d,current:%d\n",__func__,volt,temp,
remain_cap,soc,current_now);
//don't read
bq27541_di->alow_reading = false;
mod_timer(&bq27541_di->watchdog,
jiffies + msecs_to_jiffies(10000));
ret_info = 0x2;
} else if(data == 0x5a){
//fastchg full,vbatt > 4350
#if 0 //lfc modify for it(set <API key> ture) is earlier than usb_plugged_out irq(set it false)
bq27541_di-><API key> = true;
bq27541_di->alow_reading = true;
bq27541_di->fast_chg_started = false;
bq27541_di->fast_chg_allow = false;
#endif
//switch off fast chg
pr_info("%s fastchg full,switch off fastchg,set GPIO96 0\n", __func__);
gpio_set_value(96, 0);
mcu_en_gpio_set(1);//sjc0623 add
retval = gpio_tlmm_config(AP_SWITCH_USB, GPIO_CFG_ENABLE);
if (retval) {
pr_err("%s switch usb error %d\n", __func__, retval);
}
del_timer(&bq27541_di->watchdog);
ret_info = 0x2;
} else if(data == 0x53){
if (bq27541_di->battery_type == BATTERY_3000MA){ //13097 ATL battery
//if temp:10~20 decigec,vddmax = 4250mv
//switch off fast chg
pr_info("%s fastchg low temp full,switch off fastchg,set GPIO96 0\n", __func__);
gpio_set_value(96, 0);
mcu_en_gpio_set(1);//sjc0623 add
retval = gpio_tlmm_config(AP_SWITCH_USB, GPIO_CFG_ENABLE);
if (retval) {
pr_err("%s switch usb error %d\n", __func__, retval);
}
}
del_timer(&bq27541_di->watchdog);
ret_info = 0x2;
} else if(data == 0x59){
//usb bad connected,stop fastchg
#if 0 //lfc modify for it(set <API key> ture) is earlier than usb_plugged_out irq(set it false)
bq27541_di->alow_reading = true;
bq27541_di->fast_chg_started = false;
bq27541_di->fast_chg_allow = false;
bq27541_di-><API key> = true;
#endif
//switch off fast chg
pr_info("%s usb bad connect,switch off fastchg\n", __func__);
gpio_set_value(96, 0);
mcu_en_gpio_set(1);//sjc0623 add
retval = gpio_tlmm_config(AP_SWITCH_USB, GPIO_CFG_ENABLE);
if (retval) {
pr_err("%s switch usb error %d\n", __func__, retval);
}
del_timer(&bq27541_di->watchdog);
ret_info = 0x2;
} else if(data == 0x5c){
//fastchg temp over 45 or under 20
pr_info("%s fastchg temp > 45 or < 20,switch off fastchg,set GPIO96 0\n", __func__);
gpio_set_value(96, 0);
mcu_en_gpio_set(1);//sjc0623 add
retval = gpio_tlmm_config(AP_SWITCH_USB, GPIO_CFG_ENABLE);
if (retval) {
pr_err("%s switch usb error %d\n", __func__, retval);
}
del_timer(&bq27541_di->watchdog);
ret_info = 0x2;
} else if(data == 0x56){
//ready to get fw_ver
fw_ver_info = 1;
ret_info = 0x2;
} else if(fw_ver_info){
//get fw_ver
//fw in local is large than mcu1503_fw_ver
if((!pic_have_updated) && (<API key>[pic_fw_ver_count - 4] > data)){
ret_info = 0x2;
pic_need_to_up_fw = 1; //need to update fw
}else{
ret_info = 0x1;
pic_need_to_up_fw = 0; //fw is already new,needn't to up
}
pr_info("local_fw:0x%x,need_to_up_fw:%d\n",<API key>[pic_fw_ver_count - 4],pic_need_to_up_fw);
fw_ver_info = 0;
} else {
gpio_set_value(96, 0);
mcu_en_gpio_set(1);//sjc0623 add
retval = gpio_tlmm_config(AP_SWITCH_USB, GPIO_CFG_ENABLE);
if (retval) {
pr_err("%s data err(101xxxx) switch usb error %d\n", __func__, retval);
goto out; //avoid i2c conflict
}
msleep(500); //avoid i2c conflict
//data err
bq27541_di->alow_reading = true;
bq27541_di->fast_chg_started = false;
bq27541_di->fast_chg_allow = false;
bq27541_di-><API key> = false;
bq27541_di->fast_normal_to_warm = false;
bq27541_di->fast_chg_ing = false;
//data err
pr_info("%s data err(101xxxx),switch off fastchg\n", __func__);
<API key>(bq27541_di->batt_psy);
goto out;
}
msleep(2);
gpio_tlmm_config(GPIO_CFG(1,0,GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),1);
<API key>(1, 0);
for(i = 0; i < 3; i++) {
if(i == 0){ //tell mcu1503 battery_type
gpio_set_value(1, ret_info >> 1);
} else if(i == 1){
gpio_set_value(1, ret_info & 0x1);
} else {
gpio_set_value(1,bq27541_di->battery_type);
}
gpio_set_value(0, 0);
gpio_tlmm_config(AP_TX_EN, GPIO_CFG_ENABLE);
usleep_range(1000,1000);
gpio_set_value(0, 1);
gpio_tlmm_config(AP_TX_DIS, GPIO_CFG_ENABLE);
usleep_range(19000,19000);
}
out:
gpio_tlmm_config(GPIO_CFG(1,0,GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),1);
<API key>(1);
//lfc add for it is faster than usb_plugged_out irq to send 0x5a(fast_chg full and usb bad connected) to AP
if(data == 0x5a || data == 0x59){
usleep_range(180000,180000);
bq27541_di-><API key> = true;
bq27541_di->alow_reading = true;
bq27541_di->fast_chg_started = false;
bq27541_di->fast_chg_allow = false;
bq27541_di->fast_chg_ing = false;
}
//fastchg temp over( > 45 or < 20)
//lfc add to set fastchg vddmax = 4250mv during 10 ~ 20 decigec for ATL 3000mAH battery
if(data == 0x53){
if(bq27541_di->battery_type == BATTERY_3000MA){ //13097 ATL battery
usleep_range(180000,180000);
bq27541_di->fast_low_temp_full = true;
bq27541_di->alow_reading = true;
bq27541_di->fast_chg_started = false;
bq27541_di->fast_chg_allow = false;
bq27541_di->fast_chg_ing = false;
}
}
//lfc add to set fastchg vddmax = 4250mv end
if(data == 0x5c){
usleep_range(180000,180000);
bq27541_di->fast_normal_to_warm = true;
bq27541_di->alow_reading = true;
bq27541_di->fast_chg_started = false;
bq27541_di->fast_chg_allow = false;
bq27541_di->fast_chg_ing = false;
}
if(pic_need_to_up_fw){
msleep(500);
del_timer(&bq27541_di->watchdog);
pic16f_fw_update(false);
pic_need_to_up_fw = 0;
mod_timer(&bq27541_di->watchdog,
jiffies + msecs_to_jiffies(10000));
}
retval = request_irq(bq27541_di->irq, irq_rx_handler, IRQF_TRIGGER_RISING, "mcu_data", bq27541_di); //0X01:rising edge,0x02:falling edge
if(retval < 0) {
pr_err("%s request ap rx irq failed.\n", __func__);
}
if((data == 0x52) || (data == 0x58)){
<API key>(bq27541_di->batt_psy);
}
if(data == 0x53){
if(bq27541_di->battery_type == BATTERY_3000MA){
<API key>(bq27541_di->batt_psy);
wake_unlock(&bq27541_di->fastchg_wake_lock);
}
}
if((data == 0x54) || (data == 0x5a) || (data == 0x59) || (data == 0x5c)){
<API key>(bq27541_di->batt_psy);
wake_unlock(&bq27541_di->fastchg_wake_lock);
}
}
void di_watchdog(unsigned long data)
{
struct bq27541_device_info *di = (struct bq27541_device_info *)data;
int ret = 0;
pr_err("di_watchdog can't receive mcu data\n");
di->alow_reading = true;
di->fast_chg_started = false;
di-><API key> = false;
di->fast_low_temp_full = false;
di->fast_chg_allow = false;
di->fast_normal_to_warm = false;
di->fast_chg_ing = false;
//switch off fast chg
pr_info("%s switch off fastchg\n", __func__);
gpio_set_value(96, 0);
mcu_en_gpio_set(1);//sjc0623 add
ret = gpio_tlmm_config(AP_SWITCH_USB, GPIO_CFG_ENABLE);
if (ret) {
pr_info("%s switch usb error %d\n", __func__, ret);
}
wake_unlock(&bq27541_di->fastchg_wake_lock);
}
#endif
/* OPPO 2013-12-12 liaofuchun add for fastchg */
#define MAX_RETRY_COUNT 5
static int <API key>(struct i2c_client *client,
const struct i2c_device_id *id)
{
char *name;
struct bq27541_device_info *di;
struct <API key> *bus;
int num;
int retval = 0;
#ifdef <API key>
/* OPPO 2014-06-23 sjc Add begin for 14021 */
struct device_node *dev_node = client->dev.of_node;
int ret;
if (dev_node) {
mcu_en_gpio = of_get_named_gpio(dev_node, "microchip,mcu-en-gpio", 0);
} else {
mcu_en_gpio = 0;
printk(KERN_ERR "%s: mcu_en_gpio failed\n", __func__);
}
if (gpio_is_valid(mcu_en_gpio)) {
ret = gpio_request(mcu_en_gpio, "mcu_en_gpio");
if (ret) {
printk(KERN_ERR "%s: gpio_request failed for %d ret=%d\n", __func__, mcu_en_gpio, ret);
} else {
gpio_set_value(mcu_en_gpio, 0);
}
}
#endif //<API key>
pr_info("%s\n", __func__);
if (!<API key>(client->adapter, I2C_FUNC_I2C))
return -ENODEV;
/* Get new ID for the new battery device */
retval = idr_pre_get(&battery_id, GFP_KERNEL);
if (retval == 0)
return -ENOMEM;
mutex_lock(&battery_mutex);
retval = idr_get_new(&battery_id, client, &num);
mutex_unlock(&battery_mutex);
if (retval < 0)
return retval;
name = kasprintf(GFP_KERNEL, "%s-%d", id->name, num);
if (!name) {
dev_err(&client->dev, "failed to allocate device name\n");
retval = -ENOMEM;
goto batt_failed_1;
}
di = kzalloc(sizeof(*di), GFP_KERNEL);
if (!di) {
dev_err(&client->dev, "failed to allocate device info data\n");
retval = -ENOMEM;
goto batt_failed_2;
}
di->id = num;
bus = kzalloc(sizeof(*bus), GFP_KERNEL);
if (!bus) {
dev_err(&client->dev, "failed to allocate access method "
"data\n");
retval = -ENOMEM;
goto batt_failed_3;
}
i2c_set_clientdata(client, di);
di->dev = &client->dev;
bus->read = &bq27541_read_i2c;
di->bus = bus;
di->client = client;
/* OPPO 2013-08-19 wangjc Add begin for error temp */
#ifdef <API key>
di->temp_pre = 0;
#endif
/* OPPO 2013-08-19 wangjc Add end */
di->alow_reading = true;
di->fast_chg_ing = false;
di->fast_low_temp_full = false;
#ifdef <API key>
/* jingchun.wang@Onlinerd.Driver, 2014/02/12 Add for retry when config fail */
di->retry_count = MAX_RETRY_COUNT;
atomic_set(&di->suspended, 0);
#endif /*<API key>*/
#ifdef <API key>
<API key>(&this_device, di);
retval = <API key>(&this_device);
if (!retval) {
retval = sysfs_create_group(&this_device.dev.kobj,
&fs_attr_group);
if (retval)
goto batt_failed_4;
} else
goto batt_failed_4;
#endif
if (retval) {
dev_err(&client->dev, "failed to setup bq27541\n");
goto batt_failed_4;
}
if (retval) {
dev_err(&client->dev, "failed to powerup bq27541\n");
goto batt_failed_4;
}
spin_lock_init(&lock);
bq27541_di = di;
INIT_WORK(&di->counter, <API key>);
INIT_DELAYED_WORK(&di->hw_config, bq27541_hw_config);
<API key>(&di->hw_config, 0);
/* OPPO 2013-12-22 wangjc add for fastchg*/
#ifdef <API key>
init_timer(&di->watchdog);
di->watchdog.data = (unsigned long)di;
di->watchdog.function = di_watchdog;
wake_lock_init(&di->fastchg_wake_lock,
WAKE_LOCK_SUSPEND, "fastcg_wake_lock");
INIT_WORK(&di->fastcg_work,fastcg_work_func);
gpio_request(1, "mcu_clk");
gpio_tlmm_config(GPIO_CFG(1,0,GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),1);
<API key>(1);
di->irq = gpio_to_irq(1);
retval = request_irq(di->irq, irq_rx_handler, IRQF_TRIGGER_RISING, "mcu_data", di); //0X01:rising edge,0x02:falling edge
if(retval < 0) {
pr_err("%s request ap rx irq failed.\n", __func__);
}
#endif
/* OPPO 2013-12-22 wangjc add end*/
return 0;
batt_failed_4:
kfree(bus);
batt_failed_3:
kfree(di);
batt_failed_2:
kfree(name);
batt_failed_1:
mutex_lock(&battery_mutex);
idr_remove(&battery_id, num);
mutex_unlock(&battery_mutex);
return retval;
}
static int <API key>(struct i2c_client *client)
{
struct bq27541_device_info *di = i2c_get_clientdata(client);
#ifdef <API key>
/* OPPO 2014-06-23 sjc Add begin for 14021 */
if (gpio_is_valid(mcu_en_gpio))//sjc0623 add
gpio_free(mcu_en_gpio);
#endif
<API key>(&bq27541_batt_gauge);
bq27541_cntl_cmd(di, <API key>);
udelay(66);
bq27541_cntl_cmd(di, <API key>);
<API key>(&di->hw_config);
kfree(di->bus);
mutex_lock(&battery_mutex);
idr_remove(&battery_id, di->id);
mutex_unlock(&battery_mutex);
kfree(di);
return 0;
}
static int <API key>(struct i2c_client *client, pm_message_t message)
{
struct bq27541_device_info *di = i2c_get_clientdata(client);
atomic_set(&di->suspended, 1);
return 0;
}
/*1 minute*/
#define RESUME_TIME 1*60
static int <API key>(struct i2c_client *client)
{
struct bq27541_device_info *di = i2c_get_clientdata(client);
atomic_set(&di->suspended, 0);
bq27541_battery_soc(bq27541_di, true);
return 0;
}
static const struct of_device_id bq27541_match[] = {
{ .compatible = "ti,bq27541-battery" },
{ },
};
static const struct i2c_device_id bq27541_id[] = {
{ "bq27541-battery", 1 },
{},
};
MODULE_DEVICE_TABLE(i2c, BQ27541_id);
static struct i2c_driver <API key> = {
.driver = {
.name = "bq27541-battery",
.owner = THIS_MODULE,
.of_match_table = bq27541_match,
},
.probe = <API key>,
.remove = <API key>,
.suspend = <API key> ,
.resume = <API key>,
.id_table = bq27541_id,
};
static int __init <API key>(void)
{
int ret;
ret = i2c_add_driver(&<API key>);
if (ret)
printk(KERN_ERR "Unable to register BQ27541 driver\n");
return ret;
}
module_init(<API key>);
static void __exit <API key>(void)
{
i2c_del_driver(&<API key>);
}
module_exit(<API key>);
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Qualcomm Innovation Center, Inc.");
MODULE_DESCRIPTION("BQ27541 battery monitor driver");
|
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/dcache.h>
#include <linux/init.h>
#include <linux/quotaops.h>
#include <linux/slab.h>
#include <linux/writeback.h>
#include <linux/module.h>
#include <linux/backing-dev.h>
#include <linux/wait.h>
#include <linux/rwsem.h>
#include <linux/hash.h>
#include <linux/swap.h>
#include <linux/security.h>
#include <linux/pagemap.h>
#include <linux/cdev.h>
#include <linux/bootmem.h>
#include <linux/inotify.h>
#include <linux/fsnotify.h>
#include <linux/mount.h>
#include <linux/async.h>
#include <linux/posix_acl.h>
/*
* This is needed for the following functions:
* - inode_has_buffers
* - <API key>
* - invalidate_bdev
*
* FIXME: remove all knowledge of the buffer layer from this file
*/
#include <linux/buffer_head.h>
/*
* New inode.c implementation.
*
* This implementation has the basic premise of trying
* to be extremely low-overhead and SMP-safe, yet be
* simple enough to be "obviously correct".
*
* Famous last words.
*/
/* inode dynamic allocation 1999, Andrea Arcangeli <andrea@suse.de> */
/* #define INODE_PARANOIA 1 */
/* #define INODE_DEBUG 1 */
/*
* Inode lookup is no longer as critical as it used to be:
* most of the lookups are going to be through the dcache.
*/
#define I_HASHBITS i_hash_shift
#define I_HASHMASK i_hash_mask
static unsigned int i_hash_mask __read_mostly;
static unsigned int i_hash_shift __read_mostly;
/*
* Each inode can be on two separate lists. One is
* the hash list of the inode, used for lookups. The
* other linked list is the "type" list:
* "in_use" - valid inode, i_count > 0, i_nlink > 0
* "dirty" - as "in_use" but also dirty
* "unused" - valid inode, i_count = 0
*
* A "dirty" list is maintained for each super block,
* allowing for low-overhead inode sync() operations.
*/
LIST_HEAD(inode_in_use);
LIST_HEAD(inode_unused);
static struct hlist_head *inode_hashtable __read_mostly;
/*
* A simple spinlock to protect the list manipulations.
*
* NOTE! You also have to own the lock if you change
* the i_state of an inode while it is in use..
*/
DEFINE_SPINLOCK(inode_lock);
/*
* iprune_sem provides exclusion between the kswapd or try_to_free_pages
* icache shrinking path, and the umount path. Without this exclusion,
* by the time prune_icache calls iput for the inode whose pages it has
* been invalidating, or by the time it calls clear_inode & destroy_inode
* from its final dispose_list, the struct super_block they refer to
* (for inode->i_sb->s_op) may already have been freed and reused.
*
* We make this an rwsem because the fastpath is icache shrinking. In
* some cases a filesystem may be doing a significant amount of work in
* its inode reclaim code, so this should improve parallelism.
*/
static DECLARE_RWSEM(iprune_sem);
/*
* Statistics gathering..
*/
struct inodes_stat_t inodes_stat;
static struct kmem_cache *inode_cachep __read_mostly;
static void wake_up_inode(struct inode *inode)
{
/*
* Prevent speculative execution through spin_unlock(&inode_lock);
*/
smp_mb();
wake_up_bit(&inode->i_state, __I_LOCK);
}
/**
* inode_init_always - perform inode structure intialisation
* @sb: superblock inode belongs to
* @inode: inode to initialise
*
* These are initializations that need to be done on every inode
* allocation as the fields are not initialised by slab allocation.
*/
int inode_init_always(struct super_block *sb, struct inode *inode)
{
static const struct <API key> empty_aops;
static const struct inode_operations empty_iops;
static const struct file_operations empty_fops;
struct address_space *const mapping = &inode->i_data;
inode->i_sb = sb;
inode->i_blkbits = sb->s_blocksize_bits;
inode->i_flags = 0;
atomic_set(&inode->i_count, 1);
inode->i_op = &empty_iops;
inode->i_fop = &empty_fops;
inode->i_nlink = 1;
inode->i_uid = 0;
inode->i_gid = 0;
atomic_set(&inode->i_writecount, 0);
inode->i_size = 0;
inode->i_blocks = 0;
inode->i_bytes = 0;
inode->i_generation = 0;
#ifdef CONFIG_QUOTA
memset(&inode->i_dquot, 0, sizeof(inode->i_dquot));
#endif
inode->i_pipe = NULL;
inode->i_bdev = NULL;
inode->i_cdev = NULL;
inode->i_rdev = 0;
inode->dirtied_when = 0;
if (<API key>(inode))
goto out;
spin_lock_init(&inode->i_lock);
lockdep_set_class(&inode->i_lock, &sb->s_type->i_lock_key);
mutex_init(&inode->i_mutex);
lockdep_set_class(&inode->i_mutex, &sb->s_type->i_mutex_key);
init_rwsem(&inode->i_alloc_sem);
lockdep_set_class(&inode->i_alloc_sem, &sb->s_type->i_alloc_sem_key);
mapping->a_ops = &empty_aops;
mapping->host = inode;
mapping->flags = 0;
<API key>(mapping, <API key>);
mapping->assoc_mapping = NULL;
mapping->backing_dev_info = &<API key>;
mapping->writeback_index = 0;
/*
* If the block_device provides a backing_dev_info for client
* inodes then use that. Otherwise the inode share the bdev's
* backing_dev_info.
*/
if (sb->s_bdev) {
struct backing_dev_info *bdi;
bdi = sb->s_bdev->bd_inode->i_mapping->backing_dev_info;
mapping->backing_dev_info = bdi;
}
inode->i_private = NULL;
inode->i_mapping = mapping;
#ifdef CONFIG_FS_POSIX_ACL
inode->i_acl = inode->i_default_acl = ACL_NOT_CACHED;
#endif
#ifdef CONFIG_FSNOTIFY
inode->i_fsnotify_mask = 0;
#endif
return 0;
out:
return -ENOMEM;
}
EXPORT_SYMBOL(inode_init_always);
static struct inode *alloc_inode(struct super_block *sb)
{
struct inode *inode;
if (sb->s_op->alloc_inode)
inode = sb->s_op->alloc_inode(sb);
else
inode = kmem_cache_alloc(inode_cachep, GFP_KERNEL);
if (!inode)
return NULL;
if (unlikely(inode_init_always(sb, inode))) {
if (inode->i_sb->s_op->destroy_inode)
inode->i_sb->s_op->destroy_inode(inode);
else
kmem_cache_free(inode_cachep, inode);
return NULL;
}
return inode;
}
void __destroy_inode(struct inode *inode)
{
BUG_ON(inode_has_buffers(inode));
security_inode_free(inode);
<API key>(inode);
#ifdef CONFIG_FS_POSIX_ACL
if (inode->i_acl && inode->i_acl != ACL_NOT_CACHED)
posix_acl_release(inode->i_acl);
if (inode->i_default_acl && inode->i_default_acl != ACL_NOT_CACHED)
posix_acl_release(inode->i_default_acl);
#endif
}
EXPORT_SYMBOL(__destroy_inode);
void destroy_inode(struct inode *inode)
{
__destroy_inode(inode);
if (inode->i_sb->s_op->destroy_inode)
inode->i_sb->s_op->destroy_inode(inode);
else
kmem_cache_free(inode_cachep, (inode));
}
/*
* These are initializations that only need to be done
* once, because the fields are idempotent across use
* of the inode, so let the slab aware of that.
*/
void inode_init_once(struct inode *inode)
{
memset(inode, 0, sizeof(*inode));
INIT_HLIST_NODE(&inode->i_hash);
INIT_LIST_HEAD(&inode->i_dentry);
INIT_LIST_HEAD(&inode->i_devices);
INIT_RADIX_TREE(&inode->i_data.page_tree, GFP_ATOMIC);
spin_lock_init(&inode->i_data.tree_lock);
spin_lock_init(&inode->i_data.i_mmap_lock);
INIT_LIST_HEAD(&inode->i_data.private_list);
spin_lock_init(&inode->i_data.private_lock);
<API key>(&inode->i_data.i_mmap);
INIT_LIST_HEAD(&inode->i_data.i_mmap_nonlinear);
i_size_ordered_init(inode);
#ifdef CONFIG_INOTIFY
INIT_LIST_HEAD(&inode->inotify_watches);
mutex_init(&inode->inotify_mutex);
#endif
#ifdef CONFIG_FSNOTIFY
INIT_HLIST_HEAD(&inode-><API key>);
#endif
}
EXPORT_SYMBOL(inode_init_once);
static void init_once(void *foo)
{
struct inode *inode = (struct inode *) foo;
inode_init_once(inode);
}
/*
* inode_lock must be held
*/
void __iget(struct inode *inode)
{
if (atomic_read(&inode->i_count)) {
atomic_inc(&inode->i_count);
return;
}
atomic_inc(&inode->i_count);
if (!(inode->i_state & (I_DIRTY|I_SYNC)))
list_move(&inode->i_list, &inode_in_use);
inodes_stat.nr_unused
}
/**
* clear_inode - clear an inode
* @inode: inode to clear
*
* This is called by the filesystem to tell us
* that the inode is no longer useful. We just
* terminate it with extreme prejudice.
*/
void clear_inode(struct inode *inode)
{
might_sleep();
<API key>(inode);
BUG_ON(inode->i_data.nrpages);
BUG_ON(!(inode->i_state & I_FREEING));
BUG_ON(inode->i_state & I_CLEAR);
inode_sync_wait(inode);
vfs_dq_drop(inode);
if (inode->i_sb->s_op->clear_inode)
inode->i_sb->s_op->clear_inode(inode);
if (S_ISBLK(inode->i_mode) && inode->i_bdev)
bd_forget(inode);
if (S_ISCHR(inode->i_mode) && inode->i_cdev)
cd_forget(inode);
inode->i_state = I_CLEAR;
}
EXPORT_SYMBOL(clear_inode);
/*
* dispose_list - dispose of the contents of a local list
* @head: the head of the list to free
*
* Dispose-list gets a local list with local inodes in it, so it doesn't
* need to worry about list corruption and SMP locks.
*/
static void dispose_list(struct list_head *head)
{
int nr_disposed = 0;
while (!list_empty(head)) {
struct inode *inode;
inode = list_first_entry(head, struct inode, i_list);
list_del(&inode->i_list);
if (inode->i_data.nrpages)
<API key>(&inode->i_data, 0);
clear_inode(inode);
spin_lock(&inode_lock);
hlist_del_init(&inode->i_hash);
list_del_init(&inode->i_sb_list);
spin_unlock(&inode_lock);
wake_up_inode(inode);
destroy_inode(inode);
nr_disposed++;
}
spin_lock(&inode_lock);
inodes_stat.nr_inodes -= nr_disposed;
spin_unlock(&inode_lock);
}
/*
* Invalidate all inodes for a device.
*/
static int invalidate_list(struct list_head *head, struct list_head *dispose)
{
struct list_head *next;
int busy = 0, count = 0;
next = head->next;
for (;;) {
struct list_head *tmp = next;
struct inode *inode;
/*
* We can reschedule here without worrying about the list's
* consistency because the per-sb list of inodes must not
* change during umount anymore, and because iprune_sem keeps
* <API key>() away.
*/
cond_resched_lock(&inode_lock);
next = next->next;
if (tmp == head)
break;
inode = list_entry(tmp, struct inode, i_sb_list);
if (inode->i_state & I_NEW)
continue;
<API key>(inode);
if (!atomic_read(&inode->i_count)) {
list_move(&inode->i_list, dispose);
WARN_ON(inode->i_state & I_NEW);
inode->i_state |= I_FREEING;
count++;
continue;
}
busy = 1;
}
/* only unused inodes may be cached with i_count zero */
inodes_stat.nr_unused -= count;
return busy;
}
/**
* invalidate_inodes - discard the inodes on a device
* @sb: superblock
*
* Discard all of the inodes for a given superblock. If the discard
* fails because there are busy inodes then a non zero value is returned.
* If the discard is successful all the inodes have been discarded.
*/
int invalidate_inodes(struct super_block *sb)
{
int busy;
LIST_HEAD(throw_away);
down_write(&iprune_sem);
spin_lock(&inode_lock);
<API key>(&sb->s_inodes);
<API key>(&sb->s_inodes);
busy = invalidate_list(&sb->s_inodes, &throw_away);
spin_unlock(&inode_lock);
dispose_list(&throw_away);
up_write(&iprune_sem);
return busy;
}
EXPORT_SYMBOL(invalidate_inodes);
static int can_unuse(struct inode *inode)
{
if (inode->i_state)
return 0;
if (inode_has_buffers(inode))
return 0;
if (atomic_read(&inode->i_count))
return 0;
if (inode->i_data.nrpages)
return 0;
return 1;
}
/*
* Scan `goal' inodes on the unused list for freeable ones. They are moved to
* a temporary list and then are freed outside inode_lock by dispose_list().
*
* Any inodes which are pinned purely because of attached pagecache have their
* pagecache removed. We expect the final iput() on that inode to add it to
* the front of the inode_unused list. So look for it there and if the
* inode is still freeable, proceed. The right inode is found 99.9% of the
* time in testing on a 4-way.
*
* If the inode has metadata buffers attached to mapping->private_list then
* try to remove them.
*/
static void prune_icache(int nr_to_scan)
{
LIST_HEAD(freeable);
int nr_pruned = 0;
int nr_scanned;
unsigned long reap = 0;
down_read(&iprune_sem);
spin_lock(&inode_lock);
for (nr_scanned = 0; nr_scanned < nr_to_scan; nr_scanned++) {
struct inode *inode;
if (list_empty(&inode_unused))
break;
inode = list_entry(inode_unused.prev, struct inode, i_list);
if (inode->i_state || atomic_read(&inode->i_count)) {
list_move(&inode->i_list, &inode_unused);
continue;
}
if (inode_has_buffers(inode) || inode->i_data.nrpages) {
__iget(inode);
spin_unlock(&inode_lock);
if (<API key>(inode))
reap += <API key>(&inode->i_data,
0, -1);
iput(inode);
spin_lock(&inode_lock);
if (inode != list_entry(inode_unused.next,
struct inode, i_list))
continue; /* wrong inode or list_empty */
if (!can_unuse(inode))
continue;
}
list_move(&inode->i_list, &freeable);
WARN_ON(inode->i_state & I_NEW);
inode->i_state |= I_FREEING;
nr_pruned++;
}
inodes_stat.nr_unused -= nr_pruned;
if (current_is_kswapd())
__count_vm_events(KSWAPD_INODESTEAL, reap);
else
__count_vm_events(PGINODESTEAL, reap);
spin_unlock(&inode_lock);
dispose_list(&freeable);
up_read(&iprune_sem);
}
/*
* <API key>() will attempt to reclaim some unused inodes. Here,
* "unused" means that no dentries are referring to the inodes: the files are
* not open and the dcache references to those inodes have already been
* reclaimed.
*
* This function is passed the number of inodes to scan, and it returns the
* total number of remaining <API key> inodes.
*/
static int <API key>(int nr, gfp_t gfp_mask)
{
if (nr) {
/*
* Nasty deadlock avoidance. We may hold various FS locks,
* and we don't want to recurse into the FS that called us
* in clear_inode() and friends..
*/
if (!(gfp_mask & __GFP_FS))
return -1;
prune_icache(nr);
}
return (inodes_stat.nr_unused / 100) * <API key>;
}
static struct shrinker icache_shrinker = {
.shrink = <API key>,
.seeks = DEFAULT_SEEKS,
};
static void <API key>(struct inode *inode);
/*
* Called with the inode lock held.
* NOTE: we are not increasing the inode-refcount, you must call __iget()
* by hand after calling find_inode now! This simplifies iunique and won't
* add any additional branch in the common code.
*/
static struct inode *find_inode(struct super_block *sb,
struct hlist_head *head,
int (*test)(struct inode *, void *),
void *data)
{
struct hlist_node *node;
struct inode *inode = NULL;
repeat:
<API key>(inode, node, head, i_hash) {
if (inode->i_sb != sb)
continue;
if (!test(inode, data))
continue;
if (inode->i_state & (I_FREEING|I_CLEAR|I_WILL_FREE)) {
<API key>(inode);
goto repeat;
}
break;
}
return node ? inode : NULL;
}
/*
* find_inode_fast is the fast path version of find_inode, see the comment at
* iget_locked for details.
*/
static struct inode *find_inode_fast(struct super_block *sb,
struct hlist_head *head, unsigned long ino)
{
struct hlist_node *node;
struct inode *inode = NULL;
repeat:
<API key>(inode, node, head, i_hash) {
if (inode->i_ino != ino)
continue;
if (inode->i_sb != sb)
continue;
if (inode->i_state & (I_FREEING|I_CLEAR|I_WILL_FREE)) {
<API key>(inode);
goto repeat;
}
break;
}
return node ? inode : NULL;
}
static unsigned long hash(struct super_block *sb, unsigned long hashval)
{
unsigned long tmp;
tmp = (hashval * (unsigned long)sb) ^ (GOLDEN_RATIO_PRIME + hashval) /
L1_CACHE_BYTES;
tmp = tmp ^ ((tmp ^ GOLDEN_RATIO_PRIME) >> I_HASHBITS);
return tmp & I_HASHMASK;
}
static inline void
<API key>(struct super_block *sb, struct hlist_head *head,
struct inode *inode)
{
inodes_stat.nr_inodes++;
list_add(&inode->i_list, &inode_in_use);
list_add(&inode->i_sb_list, &sb->s_inodes);
if (head)
hlist_add_head(&inode->i_hash, head);
}
/**
* inode_add_to_lists - add a new inode to relevant lists
* @sb: superblock inode belongs to
* @inode: inode to mark in use
*
* When an inode is allocated it needs to be accounted for, added to the in use
* list, the owning superblock and the inode hash. This needs to be done under
* the inode_lock, so export a function to do this rather than the inode lock
* itself. We calculate the hash list to add to here so it is all internal
* which requires the caller to have already set up the inode number in the
* inode to add.
*/
void inode_add_to_lists(struct super_block *sb, struct inode *inode)
{
struct hlist_head *head = inode_hashtable + hash(sb, inode->i_ino);
spin_lock(&inode_lock);
<API key>(sb, head, inode);
spin_unlock(&inode_lock);
}
EXPORT_SYMBOL_GPL(inode_add_to_lists);
/**
* new_inode - obtain an inode
* @sb: superblock
*
* Allocates a new inode for given superblock. The default gfp_mask
* for allocations related to inode->i_mapping is <API key>.
* If HIGHMEM pages are unsuitable or it is known that pages allocated
* for the page cache are not reclaimable or migratable,
* <API key>() must be called with suitable flags on the
* newly created inode's mapping
*
*/
struct inode *new_inode(struct super_block *sb)
{
/*
* On a 32bit, non LFS stat() call, glibc will generate an EOVERFLOW
* error if st_ino won't fit in target struct field. Use 32bit counter
* here to attempt to avoid that.
*/
static unsigned int last_ino;
struct inode *inode;
spin_lock_prefetch(&inode_lock);
inode = alloc_inode(sb);
if (inode) {
spin_lock(&inode_lock);
<API key>(sb, NULL, inode);
inode->i_ino = ++last_ino;
inode->i_state = 0;
spin_unlock(&inode_lock);
}
return inode;
}
EXPORT_SYMBOL(new_inode);
void unlock_new_inode(struct inode *inode)
{
#ifdef <API key>
if (inode->i_mode & S_IFDIR) {
struct file_system_type *type = inode->i_sb->s_type;
/* Set new key only if filesystem hasn't already changed it */
if (!lockdep_match_class(&inode->i_mutex,
&type->i_mutex_key)) {
/*
* ensure nobody is actually holding i_mutex
*/
mutex_destroy(&inode->i_mutex);
mutex_init(&inode->i_mutex);
lockdep_set_class(&inode->i_mutex,
&type->i_mutex_dir_key);
}
}
#endif
/*
* This is special! We do not need the spinlock when clearing I_LOCK,
* because we're guaranteed that nobody else tries to do anything about
* the state of the inode when it is locked, as we just created it (so
* there can be no old holders that haven't tested I_LOCK).
* However we must emit the memory barrier so that other CPUs reliably
* see the clearing of I_LOCK after the other inode initialisation has
* completed.
*/
smp_mb();
WARN_ON((inode->i_state & (I_LOCK|I_NEW)) != (I_LOCK|I_NEW));
inode->i_state &= ~(I_LOCK|I_NEW);
wake_up_inode(inode);
}
EXPORT_SYMBOL(unlock_new_inode);
/*
* This is called without the inode lock held.. Be careful.
*
* We no longer cache the sb_flags in i_flags - see fs.h
* -- rmk@arm.uk.linux.org
*/
static struct inode *get_new_inode(struct super_block *sb,
struct hlist_head *head,
int (*test)(struct inode *, void *),
int (*set)(struct inode *, void *),
void *data)
{
struct inode *inode;
inode = alloc_inode(sb);
if (inode) {
struct inode *old;
spin_lock(&inode_lock);
/* We released the lock, so.. */
old = find_inode(sb, head, test, data);
if (!old) {
if (set(inode, data))
goto set_failed;
<API key>(sb, head, inode);
inode->i_state = I_LOCK|I_NEW;
spin_unlock(&inode_lock);
/* Return the locked inode with I_NEW set, the
* caller is responsible for filling in the contents
*/
return inode;
}
/*
* Uhhuh, somebody else created the same inode under
* us. Use the old inode instead of the one we just
* allocated.
*/
__iget(old);
spin_unlock(&inode_lock);
destroy_inode(inode);
inode = old;
wait_on_inode(inode);
}
return inode;
set_failed:
spin_unlock(&inode_lock);
destroy_inode(inode);
return NULL;
}
/*
* get_new_inode_fast is the fast path version of get_new_inode, see the
* comment at iget_locked for details.
*/
static struct inode *get_new_inode_fast(struct super_block *sb,
struct hlist_head *head, unsigned long ino)
{
struct inode *inode;
inode = alloc_inode(sb);
if (inode) {
struct inode *old;
spin_lock(&inode_lock);
/* We released the lock, so.. */
old = find_inode_fast(sb, head, ino);
if (!old) {
inode->i_ino = ino;
<API key>(sb, head, inode);
inode->i_state = I_LOCK|I_NEW;
spin_unlock(&inode_lock);
/* Return the locked inode with I_NEW set, the
* caller is responsible for filling in the contents
*/
return inode;
}
/*
* Uhhuh, somebody else created the same inode under
* us. Use the old inode instead of the one we just
* allocated.
*/
__iget(old);
spin_unlock(&inode_lock);
destroy_inode(inode);
inode = old;
wait_on_inode(inode);
}
return inode;
}
/**
* iunique - get a unique inode number
* @sb: superblock
* @max_reserved: highest reserved inode number
*
* Obtain an inode number that is unique on the system for a given
* superblock. This is used by file systems that have no natural
* permanent inode numbering system. An inode number is returned that
* is higher than the reserved limit but unique.
*
* BUGS:
* With a large number of inodes live on the file system this function
* currently becomes quite slow.
*/
ino_t iunique(struct super_block *sb, ino_t max_reserved)
{
/*
* On a 32bit, non LFS stat() call, glibc will generate an EOVERFLOW
* error if st_ino won't fit in target struct field. Use 32bit counter
* here to attempt to avoid that.
*/
static unsigned int counter;
struct inode *inode;
struct hlist_head *head;
ino_t res;
spin_lock(&inode_lock);
do {
if (counter <= max_reserved)
counter = max_reserved + 1;
res = counter++;
head = inode_hashtable + hash(sb, res);
inode = find_inode_fast(sb, head, res);
} while (inode != NULL);
spin_unlock(&inode_lock);
return res;
}
EXPORT_SYMBOL(iunique);
struct inode *igrab(struct inode *inode)
{
spin_lock(&inode_lock);
if (!(inode->i_state & (I_FREEING|I_CLEAR|I_WILL_FREE)))
__iget(inode);
else
/*
* Handle the case where s_op->clear_inode is not been
* called yet, and somebody is calling igrab
* while the inode is getting freed.
*/
inode = NULL;
spin_unlock(&inode_lock);
return inode;
}
EXPORT_SYMBOL(igrab);
/**
* ifind - internal function, you want ilookup5() or iget5().
* @sb: super block of file system to search
* @head: the head of the list to search
* @test: callback used for comparisons between inodes
* @data: opaque data pointer to pass to @test
* @wait: if true wait for the inode to be unlocked, if false do not
*
* ifind() searches for the inode specified by @data in the inode
* cache. This is a generalized version of ifind_fast() for file systems where
* the inode number is not sufficient for unique identification of an inode.
*
* If the inode is in the cache, the inode is returned with an incremented
* reference count.
*
* Otherwise NULL is returned.
*
* Note, @test is called with the inode_lock held, so can't sleep.
*/
static struct inode *ifind(struct super_block *sb,
struct hlist_head *head, int (*test)(struct inode *, void *),
void *data, const int wait)
{
struct inode *inode;
spin_lock(&inode_lock);
inode = find_inode(sb, head, test, data);
if (inode) {
__iget(inode);
spin_unlock(&inode_lock);
if (likely(wait))
wait_on_inode(inode);
return inode;
}
spin_unlock(&inode_lock);
return NULL;
}
/**
* ifind_fast - internal function, you want ilookup() or iget().
* @sb: super block of file system to search
* @head: head of the list to search
* @ino: inode number to search for
*
* ifind_fast() searches for the inode @ino in the inode cache. This is for
* file systems where the inode number is sufficient for unique identification
* of an inode.
*
* If the inode is in the cache, the inode is returned with an incremented
* reference count.
*
* Otherwise NULL is returned.
*/
static struct inode *ifind_fast(struct super_block *sb,
struct hlist_head *head, unsigned long ino)
{
struct inode *inode;
spin_lock(&inode_lock);
inode = find_inode_fast(sb, head, ino);
if (inode) {
__iget(inode);
spin_unlock(&inode_lock);
wait_on_inode(inode);
return inode;
}
spin_unlock(&inode_lock);
return NULL;
}
/**
* ilookup5_nowait - search for an inode in the inode cache
* @sb: super block of file system to search
* @hashval: hash value (usually inode number) to search for
* @test: callback used for comparisons between inodes
* @data: opaque data pointer to pass to @test
*
* ilookup5() uses ifind() to search for the inode specified by @hashval and
* @data in the inode cache. This is a generalized version of ilookup() for
* file systems where the inode number is not sufficient for unique
* identification of an inode.
*
* If the inode is in the cache, the inode is returned with an incremented
* reference count. Note, the inode lock is not waited upon so you have to be
* very careful what you do with the returned inode. You probably should be
* using ilookup5() instead.
*
* Otherwise NULL is returned.
*
* Note, @test is called with the inode_lock held, so can't sleep.
*/
struct inode *ilookup5_nowait(struct super_block *sb, unsigned long hashval,
int (*test)(struct inode *, void *), void *data)
{
struct hlist_head *head = inode_hashtable + hash(sb, hashval);
return ifind(sb, head, test, data, 0);
}
EXPORT_SYMBOL(ilookup5_nowait);
/**
* ilookup5 - search for an inode in the inode cache
* @sb: super block of file system to search
* @hashval: hash value (usually inode number) to search for
* @test: callback used for comparisons between inodes
* @data: opaque data pointer to pass to @test
*
* ilookup5() uses ifind() to search for the inode specified by @hashval and
* @data in the inode cache. This is a generalized version of ilookup() for
* file systems where the inode number is not sufficient for unique
* identification of an inode.
*
* If the inode is in the cache, the inode lock is waited upon and the inode is
* returned with an incremented reference count.
*
* Otherwise NULL is returned.
*
* Note, @test is called with the inode_lock held, so can't sleep.
*/
struct inode *ilookup5(struct super_block *sb, unsigned long hashval,
int (*test)(struct inode *, void *), void *data)
{
struct hlist_head *head = inode_hashtable + hash(sb, hashval);
return ifind(sb, head, test, data, 1);
}
EXPORT_SYMBOL(ilookup5);
/**
* ilookup - search for an inode in the inode cache
* @sb: super block of file system to search
* @ino: inode number to search for
*
* ilookup() uses ifind_fast() to search for the inode @ino in the inode cache.
* This is for file systems where the inode number is sufficient for unique
* identification of an inode.
*
* If the inode is in the cache, the inode is returned with an incremented
* reference count.
*
* Otherwise NULL is returned.
*/
struct inode *ilookup(struct super_block *sb, unsigned long ino)
{
struct hlist_head *head = inode_hashtable + hash(sb, ino);
return ifind_fast(sb, head, ino);
}
EXPORT_SYMBOL(ilookup);
/**
* iget5_locked - obtain an inode from a mounted file system
* @sb: super block of file system
* @hashval: hash value (usually inode number) to get
* @test: callback used for comparisons between inodes
* @set: callback used to initialize a new struct inode
* @data: opaque data pointer to pass to @test and @set
*
* iget5_locked() uses ifind() to search for the inode specified by @hashval
* and @data in the inode cache and if present it is returned with an increased
* reference count. This is a generalized version of iget_locked() for file
* systems where the inode number is not sufficient for unique identification
* of an inode.
*
* If the inode is not in cache, get_new_inode() is called to allocate a new
* inode and this is returned locked, hashed, and with the I_NEW flag set. The
* file system gets to fill it in before unlocking it via unlock_new_inode().
*
* Note both @test and @set are called with the inode_lock held, so can't sleep.
*/
struct inode *iget5_locked(struct super_block *sb, unsigned long hashval,
int (*test)(struct inode *, void *),
int (*set)(struct inode *, void *), void *data)
{
struct hlist_head *head = inode_hashtable + hash(sb, hashval);
struct inode *inode;
inode = ifind(sb, head, test, data, 1);
if (inode)
return inode;
/*
* get_new_inode() will do the right thing, re-trying the search
* in case it had to block at any point.
*/
return get_new_inode(sb, head, test, set, data);
}
EXPORT_SYMBOL(iget5_locked);
/**
* iget_locked - obtain an inode from a mounted file system
* @sb: super block of file system
* @ino: inode number to get
*
* iget_locked() uses ifind_fast() to search for the inode specified by @ino in
* the inode cache and if present it is returned with an increased reference
* count. This is for file systems where the inode number is sufficient for
* unique identification of an inode.
*
* If the inode is not in cache, get_new_inode_fast() is called to allocate a
* new inode and this is returned locked, hashed, and with the I_NEW flag set.
* The file system gets to fill it in before unlocking it via
* unlock_new_inode().
*/
struct inode *iget_locked(struct super_block *sb, unsigned long ino)
{
struct hlist_head *head = inode_hashtable + hash(sb, ino);
struct inode *inode;
inode = ifind_fast(sb, head, ino);
if (inode)
return inode;
/*
* get_new_inode_fast() will do the right thing, re-trying the search
* in case it had to block at any point.
*/
return get_new_inode_fast(sb, head, ino);
}
EXPORT_SYMBOL(iget_locked);
int insert_inode_locked(struct inode *inode)
{
struct super_block *sb = inode->i_sb;
ino_t ino = inode->i_ino;
struct hlist_head *head = inode_hashtable + hash(sb, ino);
inode->i_state |= I_LOCK|I_NEW;
while (1) {
struct hlist_node *node;
struct inode *old = NULL;
spin_lock(&inode_lock);
<API key>(old, node, head, i_hash) {
if (old->i_ino != ino)
continue;
if (old->i_sb != sb)
continue;
if (old->i_state & (I_FREEING|I_CLEAR|I_WILL_FREE))
continue;
break;
}
if (likely(!node)) {
hlist_add_head(&inode->i_hash, head);
spin_unlock(&inode_lock);
return 0;
}
__iget(old);
spin_unlock(&inode_lock);
wait_on_inode(old);
if (unlikely(!hlist_unhashed(&old->i_hash))) {
iput(old);
return -EBUSY;
}
iput(old);
}
}
EXPORT_SYMBOL(insert_inode_locked);
int <API key>(struct inode *inode, unsigned long hashval,
int (*test)(struct inode *, void *), void *data)
{
struct super_block *sb = inode->i_sb;
struct hlist_head *head = inode_hashtable + hash(sb, hashval);
inode->i_state |= I_LOCK|I_NEW;
while (1) {
struct hlist_node *node;
struct inode *old = NULL;
spin_lock(&inode_lock);
<API key>(old, node, head, i_hash) {
if (old->i_sb != sb)
continue;
if (!test(old, data))
continue;
if (old->i_state & (I_FREEING|I_CLEAR|I_WILL_FREE))
continue;
break;
}
if (likely(!node)) {
hlist_add_head(&inode->i_hash, head);
spin_unlock(&inode_lock);
return 0;
}
__iget(old);
spin_unlock(&inode_lock);
wait_on_inode(old);
if (unlikely(!hlist_unhashed(&old->i_hash))) {
iput(old);
return -EBUSY;
}
iput(old);
}
}
EXPORT_SYMBOL(<API key>);
/**
* __insert_inode_hash - hash an inode
* @inode: unhashed inode
* @hashval: unsigned long value used to locate this object in the
* inode_hashtable.
*
* Add an inode to the inode hash for this superblock.
*/
void __insert_inode_hash(struct inode *inode, unsigned long hashval)
{
struct hlist_head *head = inode_hashtable + hash(inode->i_sb, hashval);
spin_lock(&inode_lock);
hlist_add_head(&inode->i_hash, head);
spin_unlock(&inode_lock);
}
EXPORT_SYMBOL(__insert_inode_hash);
/**
* remove_inode_hash - remove an inode from the hash
* @inode: inode to unhash
*
* Remove an inode from the superblock.
*/
void remove_inode_hash(struct inode *inode)
{
spin_lock(&inode_lock);
hlist_del_init(&inode->i_hash);
spin_unlock(&inode_lock);
}
EXPORT_SYMBOL(remove_inode_hash);
/*
* Tell the filesystem that this inode is no longer of any interest and should
* be completely destroyed.
*
* We leave the inode in the inode hash table until *after* the filesystem's
* ->delete_inode completes. This ensures that an iget (such as nfsd might
* instigate) will always find up-to-date information either in the hash or on
* disk.
*
* I_FREEING is set so that no-one will take a new reference to the inode while
* it is being deleted.
*/
void <API key>(struct inode *inode)
{
const struct super_operations *op = inode->i_sb->s_op;
list_del_init(&inode->i_list);
list_del_init(&inode->i_sb_list);
WARN_ON(inode->i_state & I_NEW);
inode->i_state |= I_FREEING;
inodes_stat.nr_inodes
spin_unlock(&inode_lock);
<API key>(inode);
if (op->delete_inode) {
void (*delete)(struct inode *) = op->delete_inode;
if (!is_bad_inode(inode))
vfs_dq_init(inode);
/* Filesystems implementing their own
* s_op->delete_inode are required to call
* <API key> and clear_inode()
* internally */
delete(inode);
} else {
<API key>(&inode->i_data, 0);
clear_inode(inode);
}
spin_lock(&inode_lock);
hlist_del_init(&inode->i_hash);
spin_unlock(&inode_lock);
wake_up_inode(inode);
BUG_ON(inode->i_state != I_CLEAR);
destroy_inode(inode);
}
EXPORT_SYMBOL(<API key>);
/**
* <API key> - remove inode from inode lists
* @inode: inode to remove
*
* Remove inode from inode lists, write it if it's dirty. This is just an
* internal VFS helper exported for hugetlbfs. Do not use!
*
* Returns 1 if inode should be completely destroyed.
*/
int <API key>(struct inode *inode)
{
struct super_block *sb = inode->i_sb;
if (!hlist_unhashed(&inode->i_hash)) {
if (!(inode->i_state & (I_DIRTY|I_SYNC)))
list_move(&inode->i_list, &inode_unused);
inodes_stat.nr_unused++;
if (sb->s_flags & MS_ACTIVE) {
spin_unlock(&inode_lock);
return 0;
}
WARN_ON(inode->i_state & I_NEW);
inode->i_state |= I_WILL_FREE;
spin_unlock(&inode_lock);
write_inode_now(inode, 1);
spin_lock(&inode_lock);
WARN_ON(inode->i_state & I_NEW);
inode->i_state &= ~I_WILL_FREE;
inodes_stat.nr_unused
hlist_del_init(&inode->i_hash);
}
list_del_init(&inode->i_list);
list_del_init(&inode->i_sb_list);
WARN_ON(inode->i_state & I_NEW);
inode->i_state |= I_FREEING;
inodes_stat.nr_inodes
spin_unlock(&inode_lock);
return 1;
}
EXPORT_SYMBOL_GPL(<API key>);
static void <API key>(struct inode *inode)
{
if (!<API key>(inode))
return;
if (inode->i_data.nrpages)
<API key>(&inode->i_data, 0);
clear_inode(inode);
wake_up_inode(inode);
destroy_inode(inode);
}
/*
* Normal UNIX filesystem behaviour: delete the
* inode when the usage count drops to zero, and
* i_nlink is zero.
*/
void generic_drop_inode(struct inode *inode)
{
if (!inode->i_nlink)
<API key>(inode);
else
<API key>(inode);
}
EXPORT_SYMBOL_GPL(generic_drop_inode);
/*
* Called when we're dropping the last reference
* to an inode.
*
* Call the FS "drop()" function, defaulting to
* the legacy UNIX filesystem behaviour..
*
* NOTE! NOTE! NOTE! We're called with the inode lock
* held, and the drop function is supposed to release
* the lock!
*/
static inline void iput_final(struct inode *inode)
{
const struct super_operations *op = inode->i_sb->s_op;
void (*drop)(struct inode *) = generic_drop_inode;
if (op && op->drop_inode)
drop = op->drop_inode;
drop(inode);
}
/**
* iput - put an inode
* @inode: inode to put
*
* Puts an inode, dropping its usage count. If the inode use count hits
* zero, the inode is then freed and may also be destroyed.
*
* Consequently, iput() can sleep.
*/
void iput(struct inode *inode)
{
if (inode) {
BUG_ON(inode->i_state == I_CLEAR);
if (atomic_dec_and_lock(&inode->i_count, &inode_lock))
iput_final(inode);
}
}
EXPORT_SYMBOL(iput);
/**
* bmap - find a block number in a file
* @inode: inode of file
* @block: block to find
*
* Returns the block number on the device holding the inode that
* is the disk block number for the block of the file requested.
* That is, asked for block 4 of inode 1 the function will return the
* disk block relative to the disk start that holds that block of the
* file.
*/
sector_t bmap(struct inode *inode, sector_t block)
{
sector_t res = 0;
if (inode->i_mapping->a_ops->bmap)
res = inode->i_mapping->a_ops->bmap(inode->i_mapping, block);
return res;
}
EXPORT_SYMBOL(bmap);
/*
* With relative atime, only update atime if the previous atime is
* earlier than either the ctime or mtime or if at least a day has
* passed since the last atime update.
*/
static int <API key>(struct vfsmount *mnt, struct inode *inode,
struct timespec now)
{
if (!(mnt->mnt_flags & MNT_RELATIME))
return 1;
/*
* Is mtime younger than atime? If yes, update atime:
*/
if (timespec_compare(&inode->i_mtime, &inode->i_atime) >= 0)
return 1;
/*
* Is ctime younger than atime? If yes, update atime:
*/
if (timespec_compare(&inode->i_ctime, &inode->i_atime) >= 0)
return 1;
/*
* Is the previous atime value older than a day? If yes,
* update atime:
*/
if ((long)(now.tv_sec - inode->i_atime.tv_sec) >= 24*60*60)
return 1;
return 0;
}
/**
* touch_atime - update the access time
* @mnt: mount the inode is accessed on
* @dentry: dentry accessed
*
* Update the accessed time on an inode and mark it for writeback.
* This function automatically handles read only file systems and media,
* as well as the "noatime" flag and inode specific "noatime" markers.
*/
void touch_atime(struct vfsmount *mnt, struct dentry *dentry)
{
struct inode *inode = dentry->d_inode;
struct timespec now;
if (inode->i_flags & S_NOATIME)
return;
if (IS_NOATIME(inode))
return;
if ((inode->i_sb->s_flags & MS_NODIRATIME) && S_ISDIR(inode->i_mode))
return;
if (mnt->mnt_flags & MNT_NOATIME)
return;
if ((mnt->mnt_flags & MNT_NODIRATIME) && S_ISDIR(inode->i_mode))
return;
now = current_fs_time(inode->i_sb);
if (!<API key>(mnt, inode, now))
return;
if (timespec_equal(&inode->i_atime, &now))
return;
if (mnt_want_write(mnt))
return;
inode->i_atime = now;
<API key>(inode);
mnt_drop_write(mnt);
}
EXPORT_SYMBOL(touch_atime);
/**
* file_update_time - update mtime and ctime time
* @file: file accessed
*
* Update the mtime and ctime members of an inode and mark the inode
* for writeback. Note that this function is meant exclusively for
* usage in the file write path of filesystems, and filesystems may
* choose to explicitly ignore update via this function with the
* S_NOCMTIME inode flag, e.g. for network filesystem where these
* timestamps are handled by the server.
*/
void file_update_time(struct file *file)
{
struct inode *inode = file->f_path.dentry->d_inode;
struct timespec now;
enum { S_MTIME = 1, S_CTIME = 2, S_VERSION = 4 } sync_it = 0;
/* First try to exhaust all avenues to not sync */
if (IS_NOCMTIME(inode))
return;
now = current_fs_time(inode->i_sb);
if (!timespec_equal(&inode->i_mtime, &now))
sync_it = S_MTIME;
if (!timespec_equal(&inode->i_ctime, &now))
sync_it |= S_CTIME;
if (IS_I_VERSION(inode))
sync_it |= S_VERSION;
if (!sync_it)
return;
/* Finally allowed to write? Takes lock. */
if (mnt_want_write_file(file))
return;
/* Only change inode inside the lock region */
if (sync_it & S_VERSION)
inode_inc_iversion(inode);
if (sync_it & S_CTIME)
inode->i_ctime = now;
if (sync_it & S_MTIME)
inode->i_mtime = now;
<API key>(inode);
mnt_drop_write(file->f_path.mnt);
}
EXPORT_SYMBOL(file_update_time);
int inode_needs_sync(struct inode *inode)
{
if (IS_SYNC(inode))
return 1;
if (S_ISDIR(inode->i_mode) && IS_DIRSYNC(inode))
return 1;
return 0;
}
EXPORT_SYMBOL(inode_needs_sync);
int inode_wait(void *word)
{
schedule();
return 0;
}
EXPORT_SYMBOL(inode_wait);
/*
* If we try to find an inode in the inode hash while it is being
* deleted, we have to wait until the filesystem completes its
* deletion before reporting that it isn't found. This function waits
* until the deletion _might_ have completed. Callers are responsible
* to recheck inode state.
*
* It doesn't matter if I_LOCK is not set initially, a call to
* wake_up_inode() after removing from the hash list will DTRT.
*
* This is called with inode_lock held.
*/
static void <API key>(struct inode *inode)
{
wait_queue_head_t *wq;
DEFINE_WAIT_BIT(wait, &inode->i_state, __I_LOCK);
wq = bit_waitqueue(&inode->i_state, __I_LOCK);
prepare_to_wait(wq, &wait.wait, <API key>);
spin_unlock(&inode_lock);
schedule();
finish_wait(wq, &wait.wait);
spin_lock(&inode_lock);
}
static __initdata unsigned long ihash_entries;
static int __init set_ihash_entries(char *str)
{
if (!str)
return 0;
ihash_entries = simple_strtoul(str, &str, 0);
return 1;
}
__setup("ihash_entries=", set_ihash_entries);
/*
* Initialize the waitqueues and inode hash table.
*/
void __init inode_init_early(void)
{
int loop;
/* If hashes are distributed across NUMA nodes, defer
* hash allocation until vmalloc space is available.
*/
if (hashdist)
return;
inode_hashtable =
<API key>("Inode-cache",
sizeof(struct hlist_head),
ihash_entries,
14,
HASH_EARLY,
&i_hash_shift,
&i_hash_mask,
0);
for (loop = 0; loop < (1 << i_hash_shift); loop++)
INIT_HLIST_HEAD(&inode_hashtable[loop]);
}
void __init inode_init(void)
{
int loop;
/* inode slab cache */
inode_cachep = kmem_cache_create("inode_cache",
sizeof(struct inode),
0,
(<API key>|SLAB_PANIC|
SLAB_MEM_SPREAD),
init_once);
register_shrinker(&icache_shrinker);
/* Hash may have been set up in inode_init_early */
if (!hashdist)
return;
inode_hashtable =
<API key>("Inode-cache",
sizeof(struct hlist_head),
ihash_entries,
14,
0,
&i_hash_shift,
&i_hash_mask,
0);
for (loop = 0; loop < (1 << i_hash_shift); loop++)
INIT_HLIST_HEAD(&inode_hashtable[loop]);
}
void init_special_inode(struct inode *inode, umode_t mode, dev_t rdev)
{
inode->i_mode = mode;
if (S_ISCHR(mode)) {
inode->i_fop = &def_chr_fops;
inode->i_rdev = rdev;
} else if (S_ISBLK(mode)) {
inode->i_fop = &def_blk_fops;
inode->i_rdev = rdev;
} else if (S_ISFIFO(mode))
inode->i_fop = &def_fifo_fops;
else if (S_ISSOCK(mode))
inode->i_fop = &bad_sock_fops;
else
printk(KERN_DEBUG "init_special_inode: bogus i_mode (%o) for"
" inode %s:%lu\n", mode, inode->i_sb->s_id,
inode->i_ino);
}
EXPORT_SYMBOL(init_special_inode);
|
/*#define DEBUG 1*/
/*#define VERBOSE_DEBUG 1*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/i2c.h>
#include <linux/io.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/i2c-tegra.h>
#include <linux/of_i2c.h>
#include <linux/spinlock.h>
#include <asm/unaligned.h>
#include <mach/clk.h>
#include <mach/pinmux.h>
#define TEGRA_I2C_TIMEOUT (msecs_to_jiffies(1000))
#define TEGRA_I2C_RETRIES 3
#define BYTES_PER_FIFO_WORD 4
#define <API key> 500
#define I2C_CNFG 0x000
#define <API key> 12
#define <API key> (1<<10)
#define <API key> (1<<11)
#define I2C_STATUS 0x01C
#define I2C_STATUS_BUSY (1<<8)
#define I2C_SL_CNFG 0x020
#define I2C_SL_CNFG_NACK (1<<1)
#define I2C_SL_CNFG_NEWSL (1<<2)
#define I2C_SL_ADDR1 0x02c
#define I2C_SL_ADDR2 0x030
#define I2C_TX_FIFO 0x050
#define I2C_RX_FIFO 0x054
#define <API key> 0x058
#define I2C_FIFO_CONTROL 0x05c
#define <API key> (1<<1)
#define <API key> (1<<0)
#define <API key> 5
#define <API key> 2
#define I2C_FIFO_STATUS 0x060
#define <API key> 0xF0
#define <API key> 4
#define <API key> 0x0F
#define <API key> 0
#define I2C_INT_MASK 0x064
#define I2C_INT_STATUS 0x068
#define <API key> (1<<7)
#define <API key> (1<<6)
#define <API key> (1<<5)
#define <API key> (1<<4)
#define I2C_INT_NO_ACK (1<<3)
#define <API key> (1<<2)
#define <API key> (1<<1)
#define <API key> (1<<0)
#define I2C_CLK_DIVISOR 0x06c
#define DVC_CTRL_REG1 0x000
#define <API key> (1<<10)
#define DVC_CTRL_REG2 0x004
#define DVC_CTRL_REG3 0x008
#define <API key> (1<<26)
#define <API key> (1<<30)
#define DVC_STATUS 0x00c
#define <API key> (1<<30)
#define I2C_ERR_NONE 0x00
#define I2C_ERR_NO_ACK 0x01
#define <API key> 0x02
#define <API key> 0x04
#define <API key> 0x08
#define <API key> 28
#define <API key> 16
#define <API key> 12
#define <API key> (1<<4)
#define <API key> (1<<22)
#define <API key> (1<<21)
#define <API key> (1<<20)
#define I2C_HEADER_READ (1<<19)
#define <API key> (1<<18)
#define <API key> (1<<17)
#define <API key> (1<<16)
#define <API key> (1<<15)
#define <API key> 12
#define <API key> 1
#define SL_ADDR1(addr) (addr & 0xff)
#define SL_ADDR2(addr) ((addr >> 8) & 0xff)
/*
* msg_end_type: The bus control which need to be send at end of transfer.
* @MSG_END_STOP: Send stop pulse at end of transfer.
* @<API key>: Send repeat start at end of transfer.
* @MSG_END_CONTINUE: The following on message is coming and so do not send
* stop or repeat start.
*/
enum msg_end_type {
MSG_END_STOP,
<API key>,
MSG_END_CONTINUE,
};
struct tegra_i2c_dev;
struct tegra_i2c_bus {
struct tegra_i2c_dev *dev;
const struct <API key> *mux;
int mux_len;
unsigned long bus_clk_rate;
struct i2c_adapter adapter;
int scl_gpio;
int sda_gpio;
};
/**
* struct tegra_i2c_dev - per device i2c context
* @dev: device reference for power management
* @adapter: core i2c layer adapter information
* @clk: clock reference for i2c controller
* @i2c_clk: clock reference for i2c bus
* @base: ioremapped registers cookie
* @cont_id: i2c controller id, used for for packet header
* @irq: irq number of transfer complete interrupt
* @is_dvc: identifies the DVC i2c controller, has a different register layout
* @msg_complete: transfer completion notifier
* @msg_err: error code for completed message
* @msg_buf: pointer to current message data
* @msg_buf_remaining: size of unsent data in the message buffer
* @msg_read: identifies read transfers
* @bus_clk_rate: current i2c bus clock rate
* @is_suspended: prevents i2c controller accesses after suspend is called
*/
struct tegra_i2c_dev {
struct device *dev;
struct clk *div_clk;
struct clk *fast_clk;
struct rt_mutex dev_lock;
spinlock_t fifo_lock;
void __iomem *base;
int cont_id;
int irq;
bool irq_disabled;
int is_dvc;
struct completion msg_complete;
int msg_err;
u8 *msg_buf;
u32 packet_header;
u32 payload_size;
u32 io_header;
size_t msg_buf_remaining;
int msg_read;
struct i2c_msg *msgs;
int msg_add;
int msgs_num;
bool is_suspended;
int bus_count;
const struct <API key> *last_mux;
int last_mux_len;
unsigned long last_bus_clk_rate;
u16 slave_addr;
bool is_clkon_always;
bool <API key>;
u16 hs_master_code;
int (*arb_recovery)(int scl_gpio, int sda_gpio);
struct tegra_i2c_bus busses[1];
};
static void dvc_writel(struct tegra_i2c_dev *i2c_dev, u32 val, unsigned long reg)
{
writel(val, i2c_dev->base + reg);
}
static u32 dvc_readl(struct tegra_i2c_dev *i2c_dev, unsigned long reg)
{
return readl(i2c_dev->base + reg);
}
static void dvc_i2c_mask_irq(struct tegra_i2c_dev *i2c_dev, u32 mask)
{
u32 int_mask = dvc_readl(i2c_dev, DVC_CTRL_REG3);
int_mask &= ~mask;
dvc_writel(i2c_dev, int_mask, DVC_CTRL_REG3);
}
static void dvc_i2c_unmask_irq(struct tegra_i2c_dev *i2c_dev, u32 mask)
{
u32 int_mask = dvc_readl(i2c_dev, DVC_CTRL_REG3);
int_mask |= mask;
dvc_writel(i2c_dev, int_mask, DVC_CTRL_REG3);
}
/*
* i2c_writel and i2c_readl will offset the register if necessary to talk
* to the I2C block inside the DVC block
*/
static unsigned long tegra_i2c_reg_addr(struct tegra_i2c_dev *i2c_dev,
unsigned long reg)
{
if (i2c_dev->is_dvc)
reg += (reg >= I2C_TX_FIFO) ? 0x10 : 0x40;
return reg;
}
static void i2c_writel(struct tegra_i2c_dev *i2c_dev, u32 val,
unsigned long reg)
{
writel(val, i2c_dev->base + tegra_i2c_reg_addr(i2c_dev, reg));
/* Read back register to make sure that register writes completed */
if (reg != I2C_TX_FIFO)
readl(i2c_dev->base + tegra_i2c_reg_addr(i2c_dev, reg));
}
static u32 i2c_readl(struct tegra_i2c_dev *i2c_dev, unsigned long reg)
{
return readl(i2c_dev->base + tegra_i2c_reg_addr(i2c_dev, reg));
}
static void i2c_writesl(struct tegra_i2c_dev *i2c_dev, void *data,
unsigned long reg, int len)
{
writesl(i2c_dev->base + tegra_i2c_reg_addr(i2c_dev, reg), data, len);
}
static void i2c_readsl(struct tegra_i2c_dev *i2c_dev, void *data,
unsigned long reg, int len)
{
readsl(i2c_dev->base + tegra_i2c_reg_addr(i2c_dev, reg), data, len);
}
static void tegra_i2c_mask_irq(struct tegra_i2c_dev *i2c_dev, u32 mask)
{
u32 int_mask = i2c_readl(i2c_dev, I2C_INT_MASK);
int_mask &= ~mask;
i2c_writel(i2c_dev, int_mask, I2C_INT_MASK);
}
static void <API key>(struct tegra_i2c_dev *i2c_dev, u32 mask)
{
u32 int_mask = i2c_readl(i2c_dev, I2C_INT_MASK);
int_mask |= mask;
i2c_writel(i2c_dev, int_mask, I2C_INT_MASK);
}
static int <API key>(struct tegra_i2c_dev *i2c_dev)
{
unsigned long timeout = jiffies + HZ;
u32 val = i2c_readl(i2c_dev, I2C_FIFO_CONTROL);
val |= <API key> | <API key>;
i2c_writel(i2c_dev, val, I2C_FIFO_CONTROL);
while (i2c_readl(i2c_dev, I2C_FIFO_CONTROL) &
(<API key> | <API key>)) {
if (time_after(jiffies, timeout)) {
dev_warn(i2c_dev->dev, "timeout waiting for fifo flush\n");
return -ETIMEDOUT;
}
msleep(1);
}
return 0;
}
static int <API key>(struct tegra_i2c_dev *i2c_dev)
{
u32 val;
int rx_fifo_avail;
u8 *buf = i2c_dev->msg_buf;
size_t buf_remaining = i2c_dev->msg_buf_remaining;
int words_to_transfer;
val = i2c_readl(i2c_dev, I2C_FIFO_STATUS);
rx_fifo_avail = (val & <API key>) >>
<API key>;
/* Rounds down to not include partial word at the end of buf */
words_to_transfer = buf_remaining / BYTES_PER_FIFO_WORD;
if (words_to_transfer > rx_fifo_avail)
words_to_transfer = rx_fifo_avail;
i2c_readsl(i2c_dev, buf, I2C_RX_FIFO, words_to_transfer);
buf += words_to_transfer * BYTES_PER_FIFO_WORD;
buf_remaining -= words_to_transfer * BYTES_PER_FIFO_WORD;
rx_fifo_avail -= words_to_transfer;
/*
* If there is a partial word at the end of buf, handle it manually to
* prevent overwriting past the end of buf
*/
if (rx_fifo_avail > 0 && buf_remaining > 0) {
BUG_ON(buf_remaining > 3);
val = i2c_readl(i2c_dev, I2C_RX_FIFO);
memcpy(buf, &val, buf_remaining);
buf_remaining = 0;
rx_fifo_avail
}
BUG_ON(rx_fifo_avail > 0 && buf_remaining > 0);
i2c_dev->msg_buf_remaining = buf_remaining;
i2c_dev->msg_buf = buf;
return 0;
}
static int <API key>(struct tegra_i2c_dev *i2c_dev)
{
u32 val;
int tx_fifo_avail;
u8 *buf;
size_t buf_remaining;
int words_to_transfer;
unsigned long flags;
spin_lock_irqsave(&i2c_dev->fifo_lock, flags);
if (!i2c_dev->msg_buf_remaining) {
<API key>(&i2c_dev->fifo_lock, flags);
return 0;
}
buf = i2c_dev->msg_buf;
buf_remaining = i2c_dev->msg_buf_remaining;
val = i2c_readl(i2c_dev, I2C_FIFO_STATUS);
tx_fifo_avail = (val & <API key>) >>
<API key>;
/* Rounds down to not include partial word at the end of buf */
words_to_transfer = buf_remaining / BYTES_PER_FIFO_WORD;
/* It's very common to have < 4 bytes, so optimize that case. */
if (words_to_transfer) {
if (words_to_transfer > tx_fifo_avail)
words_to_transfer = tx_fifo_avail;
/*
* Update state before writing to FIFO. If this casues us
* to finish writing all bytes (AKA buf_remaining goes to 0) we
* have a potential for an interrupt (<API key> is
* not maskable). We need to make sure that the isr sees
* buf_remaining as 0 and doesn't call us back re-entrantly.
*/
buf_remaining -= words_to_transfer * BYTES_PER_FIFO_WORD;
tx_fifo_avail -= words_to_transfer;
i2c_dev->msg_buf_remaining = buf_remaining;
i2c_dev->msg_buf = buf +
words_to_transfer * BYTES_PER_FIFO_WORD;
barrier();
i2c_writesl(i2c_dev, buf, I2C_TX_FIFO, words_to_transfer);
buf += words_to_transfer * BYTES_PER_FIFO_WORD;
}
/*
* If there is a partial word at the end of buf, handle it manually to
* prevent reading past the end of buf, which could cross a page
* boundary and fault.
*/
if (tx_fifo_avail > 0 && buf_remaining > 0) {
if (buf_remaining > 3) {
dev_err(i2c_dev->dev,
"Remaining buffer more than 3 %d\n",
buf_remaining);
BUG();
}
memcpy(&val, buf, buf_remaining);
/* Again update before writing to FIFO to make sure isr sees. */
i2c_dev->msg_buf_remaining = 0;
i2c_dev->msg_buf = NULL;
barrier();
i2c_writel(i2c_dev, val, I2C_TX_FIFO);
}
<API key>(&i2c_dev->fifo_lock, flags);
return 0;
}
/*
* One of the Tegra I2C blocks is inside the DVC (Digital Voltage Controller)
* block. This block is identical to the rest of the I2C blocks, except that
* it only supports master mode, it has registers moved around, and it needs
* some extra init to get it into I2C mode. The register moves are handled
* by i2c_readl and i2c_writel
*/
static void tegra_dvc_init(struct tegra_i2c_dev *i2c_dev)
{
u32 val = 0;
val = dvc_readl(i2c_dev, DVC_CTRL_REG3);
val |= <API key>;
dvc_writel(i2c_dev, val, DVC_CTRL_REG3);
val = dvc_readl(i2c_dev, DVC_CTRL_REG1);
val |= <API key>;
dvc_writel(i2c_dev, val, DVC_CTRL_REG1);
}
static void <API key>(struct tegra_i2c_dev *i2c_dev)
{
u32 val = I2C_SL_CNFG_NEWSL | I2C_SL_CNFG_NACK;
i2c_writel(i2c_dev, val, I2C_SL_CNFG);
if (i2c_dev->slave_addr) {
u16 addr = i2c_dev->slave_addr;
i2c_writel(i2c_dev, SL_ADDR1(addr), I2C_SL_ADDR1);
i2c_writel(i2c_dev, SL_ADDR2(addr), I2C_SL_ADDR2);
}
}
static inline int <API key>(struct tegra_i2c_dev *i2c_dev)
{
int ret;
ret = clk_enable(i2c_dev->fast_clk);
if (ret < 0) {
dev_err(i2c_dev->dev,
"Error in enabling fast clock err %d\n", ret);
return ret;
}
ret = clk_enable(i2c_dev->div_clk);
if (ret < 0) {
dev_err(i2c_dev->dev,
"Error in enabling div clock err %d\n", ret);
clk_disable(i2c_dev->fast_clk);
}
return ret;
}
static inline void <API key>(struct tegra_i2c_dev *i2c_dev)
{
clk_disable(i2c_dev->div_clk);
clk_disable(i2c_dev->fast_clk);
}
static int tegra_i2c_init(struct tegra_i2c_dev *i2c_dev)
{
u32 val;
int err = 0;
<API key>(i2c_dev);
/* Interrupt generated before sending stop signal so
* wait for some time so that stop signal can be send proerly */
mdelay(1);
<API key>(i2c_dev->div_clk);
udelay(2);
<API key>(i2c_dev->div_clk);
if (i2c_dev->is_dvc)
tegra_dvc_init(i2c_dev);
val = <API key> | <API key> |
(0x2 << <API key>);
i2c_writel(i2c_dev, val, I2C_CNFG);
i2c_writel(i2c_dev, 0, I2C_INT_MASK);
clk_set_rate(i2c_dev->div_clk, i2c_dev->last_bus_clk_rate * 8);
i2c_writel(i2c_dev, 0x3, I2C_CLK_DIVISOR);
if (!i2c_dev->is_dvc) {
u32 sl_cfg = i2c_readl(i2c_dev, I2C_SL_CNFG);
sl_cfg |= I2C_SL_CNFG_NACK | I2C_SL_CNFG_NEWSL;
i2c_writel(i2c_dev, sl_cfg, I2C_SL_CNFG);
i2c_writel(i2c_dev, 0xfc, I2C_SL_ADDR1);
i2c_writel(i2c_dev, 0x00, I2C_SL_ADDR2);
}
val = 7 << <API key> |
0 << <API key>;
i2c_writel(i2c_dev, val, I2C_FIFO_CONTROL);
if (!i2c_dev->is_dvc)
<API key>(i2c_dev);
if (<API key>(i2c_dev))
err = -ETIMEDOUT;
<API key>(i2c_dev);
if (i2c_dev->irq_disabled) {
i2c_dev->irq_disabled = 0;
enable_irq(i2c_dev->irq);
}
return err;
}
static irqreturn_t tegra_i2c_isr(int irq, void *dev_id)
{
u32 status;
const u32 status_err = I2C_INT_NO_ACK | <API key> | <API key>;
struct tegra_i2c_dev *i2c_dev = dev_id;
int times = 0;
status = i2c_readl(i2c_dev, I2C_INT_STATUS);
if (status == 0) {
printk(KERN_INFO "[I2C]Unknown interrupt happen\n");
//Read I2C INT STATUS repetitiously for timing issue
while(status == 0 && times < <API key>){
status = i2c_readl(i2c_dev, I2C_INT_STATUS);
times++;
if(times == (<API key> -1) ){
dev_warn(i2c_dev->dev, "unknown interrupt Add 0x%02x\n",i2c_dev->msg_add);
i2c_dev->msg_err |= <API key>;
goto err;
}
}
printk(KERN_INFO "[I2C]Retry unknown interrupt success\n");
}
if (unlikely(status & status_err)) {
dev_warn(i2c_dev->dev, "I2c error status 0x%08x\n", status);
if (status & I2C_INT_NO_ACK) {
i2c_dev->msg_err |= I2C_ERR_NO_ACK;
dev_warn(i2c_dev->dev, "no acknowledge from address"
" 0x%x\n", i2c_dev->msg_add);
dev_warn(i2c_dev->dev, "Packet status 0x%08x\n",
i2c_readl(i2c_dev, <API key>));
}
if (status & <API key>) {
i2c_dev->msg_err |= <API key>;
dev_warn(i2c_dev->dev, "arbitration lost during "
" communicate to add 0x%x\n", i2c_dev->msg_add);
dev_warn(i2c_dev->dev, "Packet status 0x%08x\n",
i2c_readl(i2c_dev, <API key>));
}
if (status & <API key>) {
i2c_dev->msg_err |= <API key>;
dev_warn(i2c_dev->dev, "Tx fifo overflow during "
" communicate to add 0x%x\n", i2c_dev->msg_add);
dev_warn(i2c_dev->dev, "Packet status 0x%08x\n",
i2c_readl(i2c_dev, <API key>));
}
goto err;
}
if (unlikely((i2c_readl(i2c_dev, I2C_STATUS) & I2C_STATUS_BUSY)
&& (status == <API key>)
&& i2c_dev->msg_read
&& i2c_dev->msg_buf_remaining)) {
dev_warn(i2c_dev->dev, "unexpected status\n");
i2c_dev->msg_err |= <API key>;
if (!i2c_dev->irq_disabled) {
disable_irq_nosync(i2c_dev->irq);
i2c_dev->irq_disabled = 1;
}
goto err;
}
if (i2c_dev->msg_read && (status & <API key>)) {
if (i2c_dev->msg_buf_remaining)
<API key>(i2c_dev);
else
BUG();
}
if (!i2c_dev->msg_read && (status & <API key>)) {
if (i2c_dev->msg_buf_remaining)
<API key>(i2c_dev);
else
tegra_i2c_mask_irq(i2c_dev, <API key>);
}
i2c_writel(i2c_dev, status, I2C_INT_STATUS);
if (i2c_dev->is_dvc)
dvc_writel(i2c_dev, <API key>, DVC_STATUS);
if (status & <API key>) {
BUG_ON(i2c_dev->msg_buf_remaining);
complete(&i2c_dev->msg_complete);
}
return IRQ_HANDLED;
err:
dev_dbg(i2c_dev->dev, "reg: 0x%08x 0x%08x 0x%08x 0x%08x\n",
i2c_readl(i2c_dev, I2C_CNFG), i2c_readl(i2c_dev, I2C_STATUS),
i2c_readl(i2c_dev, I2C_INT_STATUS),
i2c_readl(i2c_dev, <API key>));
dev_dbg(i2c_dev->dev, "packet: 0x%08x %u 0x%08x\n",
i2c_dev->packet_header, i2c_dev->payload_size,
i2c_dev->io_header);
if (i2c_dev->msgs) {
struct i2c_msg *msgs = i2c_dev->msgs;
int i;
for (i = 0; i < i2c_dev->msgs_num; i++)
dev_dbg(i2c_dev->dev,
"msgs[%d] %c, addr=0x%04x, len=%d\n",
i, (msgs[i].flags & I2C_M_RD) ? 'R' : 'W',
msgs[i].addr, msgs[i].len);
}
/* An error occurred, mask all interrupts */
tegra_i2c_mask_irq(i2c_dev, I2C_INT_NO_ACK | <API key> |
<API key> | <API key> |
<API key> | <API key>);
i2c_writel(i2c_dev, status, I2C_INT_STATUS);
/* An error occured, mask dvc interrupt */
if (i2c_dev->is_dvc)
dvc_i2c_mask_irq(i2c_dev, <API key>);
if (i2c_dev->is_dvc)
dvc_writel(i2c_dev, <API key>, DVC_STATUS);
complete(&i2c_dev->msg_complete);
return IRQ_HANDLED;
}
static int tegra_i2c_xfer_msg(struct tegra_i2c_bus *i2c_bus,
struct i2c_msg *msg, enum msg_end_type end_state)
{
struct tegra_i2c_dev *i2c_dev = i2c_bus->dev;
u32 int_mask;
int ret;
int arb_stat;
if (msg->len == 0)
return -EINVAL;
<API key>(i2c_dev);
/* Toggle the direction flag if rev dir is selected */
if (msg->flags & I2C_M_REV_DIR_ADDR)
msg->flags ^= I2C_M_RD;
i2c_dev->msg_buf = msg->buf;
i2c_dev->msg_buf_remaining = msg->len;
i2c_dev->msg_err = I2C_ERR_NONE;
i2c_dev->msg_read = (msg->flags & I2C_M_RD);
INIT_COMPLETION(i2c_dev->msg_complete);
i2c_dev->msg_add = msg->addr;
i2c_dev->packet_header = (0 << <API key>) |
<API key> |
(i2c_dev->cont_id << <API key>) |
(1 << <API key>);
i2c_writel(i2c_dev, i2c_dev->packet_header, I2C_TX_FIFO);
i2c_dev->payload_size = msg->len - 1;
i2c_writel(i2c_dev, i2c_dev->payload_size, I2C_TX_FIFO);
i2c_dev->io_header = <API key>;
if (end_state == MSG_END_CONTINUE)
i2c_dev->io_header |= <API key>;
else if (end_state == <API key>)
i2c_dev->io_header |= <API key>;
if (msg->flags & I2C_M_TEN) {
i2c_dev->io_header |= msg->addr;
i2c_dev->io_header |= <API key>;
} else {
i2c_dev->io_header |= (msg->addr << <API key>);
}
if (msg->flags & I2C_M_IGNORE_NAK)
i2c_dev->io_header |= <API key>;
if (msg->flags & I2C_M_RD)
i2c_dev->io_header |= I2C_HEADER_READ;
if (i2c_dev-><API key>) {
i2c_dev->io_header |= <API key>;
i2c_dev->io_header |= ((i2c_dev->hs_master_code & 0x7) << <API key>);
}
i2c_writel(i2c_dev, i2c_dev->io_header, I2C_TX_FIFO);
if (!(msg->flags & I2C_M_RD))
<API key>(i2c_dev);
if (i2c_dev->is_dvc)
dvc_i2c_unmask_irq(i2c_dev, <API key>);
int_mask = I2C_INT_NO_ACK | <API key> | <API key>;
if (msg->flags & I2C_M_RD)
int_mask |= <API key>;
else if (i2c_dev->msg_buf_remaining)
int_mask |= <API key>;
<API key>(i2c_dev, int_mask);
dev_dbg(i2c_dev->dev, "unmasked irq: %02x\n",
i2c_readl(i2c_dev, I2C_INT_MASK));
ret = <API key>(&i2c_dev->msg_complete,
TEGRA_I2C_TIMEOUT);
tegra_i2c_mask_irq(i2c_dev, int_mask);
if (i2c_dev->is_dvc)
dvc_i2c_mask_irq(i2c_dev, <API key>);
/* Restore the message flag */
if (msg->flags & I2C_M_REV_DIR_ADDR)
msg->flags ^= I2C_M_RD;
if (WARN_ON(ret == 0)) {
dev_err(i2c_dev->dev,
"i2c transfer timed out, addr 0x%04x, data 0x%02x\n",
msg->addr, msg->buf[0]);
tegra_i2c_init(i2c_dev);
return -ETIMEDOUT;
}
dev_dbg(i2c_dev->dev, "transfer complete: %d %d %d\n",
ret, completion_done(&i2c_dev->msg_complete), i2c_dev->msg_err);
if (likely(i2c_dev->msg_err == I2C_ERR_NONE))
return 0;
/* Arbitration Lost occurs, Start recovery */
if (i2c_dev->msg_err == <API key>) {
if (i2c_dev->arb_recovery) {
arb_stat = i2c_dev->arb_recovery(i2c_bus->scl_gpio, i2c_bus->sda_gpio);
if (!arb_stat)
return -EAGAIN;
}
}
/*
* NACK interrupt is generated before the I2C controller generates the
* STOP condition on the bus. So wait for 2 clock periods before resetting
* the controller so that STOP condition has been delivered properly.
*/
if (i2c_dev->msg_err == I2C_ERR_NO_ACK)
udelay(DIV_ROUND_UP(2 * 1000000, i2c_dev->last_bus_clk_rate));
tegra_i2c_init(i2c_dev);
if (i2c_dev->msg_err == I2C_ERR_NO_ACK) {
if (msg->flags & I2C_M_IGNORE_NAK)
return 0;
return -EREMOTEIO;
}
if (i2c_dev->msg_err & <API key>)
return -EAGAIN;
return -EIO;
}
bool tegra_i2c_is_ready(struct i2c_adapter *adap)
{
struct tegra_i2c_bus *i2c_bus = i2c_get_adapdata(adap);
struct tegra_i2c_dev *i2c_dev = i2c_bus->dev;
return !(i2c_dev->is_suspended);
}
EXPORT_SYMBOL(tegra_i2c_is_ready);
static int tegra_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msgs[],
int num)
{
struct tegra_i2c_bus *i2c_bus = i2c_get_adapdata(adap);
struct tegra_i2c_dev *i2c_dev = i2c_bus->dev;
int i;
int ret = 0;
rt_mutex_lock(&i2c_dev->dev_lock);
if (i2c_dev->is_suspended) {
rt_mutex_unlock(&i2c_dev->dev_lock);
return -EBUSY;
}
if (i2c_dev->last_mux != i2c_bus->mux) {
<API key>(i2c_dev->last_mux,
i2c_dev->last_mux_len);
<API key>(i2c_bus->mux,
i2c_bus->mux_len);
i2c_dev->last_mux = i2c_bus->mux;
i2c_dev->last_mux_len = i2c_bus->mux_len;
}
if (i2c_dev->last_bus_clk_rate != i2c_bus->bus_clk_rate) {
clk_set_rate(i2c_dev->div_clk, i2c_bus->bus_clk_rate * 8);
i2c_dev->last_bus_clk_rate = i2c_bus->bus_clk_rate;
}
i2c_dev->msgs = msgs;
i2c_dev->msgs_num = num;
<API key>(i2c_dev);
for (i = 0; i < num; i++) {
enum msg_end_type end_type = MSG_END_STOP;
if (i < (num - 1)) {
if (msgs[i + 1].flags & I2C_M_NOSTART)
end_type = MSG_END_CONTINUE;
else
end_type = <API key>;
}
ret = tegra_i2c_xfer_msg(i2c_bus, &msgs[i], end_type);
if (ret)
break;
}
<API key>(i2c_dev);
rt_mutex_unlock(&i2c_dev->dev_lock);
i2c_dev->msgs = NULL;
i2c_dev->msgs_num = 0;
return ret ?: i;
}
static u32 tegra_i2c_func(struct i2c_adapter *adap)
{
return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL | I2C_FUNC_10BIT_ADDR |
<API key>;
}
static const struct i2c_algorithm tegra_i2c_algo = {
.master_xfer = tegra_i2c_xfer,
.functionality = tegra_i2c_func,
};
static int __devinit tegra_i2c_probe(struct platform_device *pdev)
{
struct tegra_i2c_dev *i2c_dev;
struct <API key> *plat = pdev->dev.platform_data;
struct resource *res;
struct clk *div_clk;
struct clk *fast_clk = NULL;
const unsigned int *prop;
void *base;
int irq;
int nbus;
int i = 0;
int ret = 0;
if (!plat) {
dev_err(&pdev->dev, "no platform data?\n");
return -ENODEV;
}
if (plat->bus_count <= 0 || plat->adapter_nr < 0) {
dev_err(&pdev->dev, "invalid platform data?\n");
return -ENODEV;
}
WARN_ON(plat->bus_count > TEGRA_I2C_MAX_BUS);
nbus = min(TEGRA_I2C_MAX_BUS, plat->bus_count);
res = <API key>(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev, "no mem resource\n");
return -EINVAL;
}
base = <API key>(&pdev->dev, res);
if (!base) {
dev_err(&pdev->dev, "Cannot request/ioremap I2C registers\n");
return -EADDRNOTAVAIL;
}
res = <API key>(pdev, IORESOURCE_IRQ, 0);
if (!res) {
dev_err(&pdev->dev, "no irq resource\n");
return -EINVAL;
}
irq = res->start;
div_clk = devm_clk_get(&pdev->dev, "i2c-div");
if (IS_ERR(div_clk)) {
dev_err(&pdev->dev, "missing controller clock");
return PTR_ERR(div_clk);
}
fast_clk = devm_clk_get(&pdev->dev, "i2c-fast");
if (IS_ERR(fast_clk)) {
dev_err(&pdev->dev, "missing controller fast clock");
return PTR_ERR(fast_clk);
}
i2c_dev = devm_kzalloc(&pdev->dev, sizeof(struct tegra_i2c_dev) +
(nbus-1) * sizeof(struct tegra_i2c_bus), GFP_KERNEL);
if (!i2c_dev) {
dev_err(&pdev->dev, "Could not allocate struct tegra_i2c_dev");
return -ENOMEM;
}
i2c_dev->base = base;
i2c_dev->div_clk = div_clk;
i2c_dev->fast_clk = fast_clk;
i2c_dev->irq = irq;
i2c_dev->cont_id = pdev->id;
i2c_dev->dev = &pdev->dev;
i2c_dev->is_clkon_always = plat->is_clkon_always;
i2c_dev->last_bus_clk_rate = 100000; /* default clock rate */
if (plat) {
i2c_dev->last_bus_clk_rate = plat->bus_clk_rate[0];
} else if (i2c_dev->dev->of_node) { /* if there is a device tree node ... */
/* TODO: DAN: this doesn't work for DT */
prop = of_get_property(i2c_dev->dev->of_node,
"clock-frequency", NULL);
if (prop)
i2c_dev->last_bus_clk_rate = be32_to_cpup(prop);
}
i2c_dev-><API key> = plat-><API key>;
i2c_dev->last_bus_clk_rate = plat->bus_clk_rate[0] ?: 100000;
i2c_dev->msgs = NULL;
i2c_dev->msgs_num = 0;
rt_mutex_init(&i2c_dev->dev_lock);
spin_lock_init(&i2c_dev->fifo_lock);
i2c_dev->slave_addr = plat->slave_addr;
i2c_dev->hs_master_code = plat->hs_master_code;
i2c_dev->is_dvc = plat->is_dvc;
i2c_dev->arb_recovery = plat->arb_recovery;
init_completion(&i2c_dev->msg_complete);
<API key>(pdev, i2c_dev);
if (i2c_dev->is_clkon_always)
<API key>(i2c_dev);
ret = tegra_i2c_init(i2c_dev);
if (ret) {
dev_err(&pdev->dev, "Failed to initialize i2c controller");
return ret;
}
ret = devm_request_irq(&pdev->dev, i2c_dev->irq,
tegra_i2c_isr, IRQF_NO_SUSPEND, pdev->name, i2c_dev);
if (ret) {
dev_err(&pdev->dev, "Failed to request irq %i\n", i2c_dev->irq);
return ret;
}
for (i = 0; i < nbus; i++) {
struct tegra_i2c_bus *i2c_bus = &i2c_dev->busses[i];
i2c_bus->dev = i2c_dev;
i2c_bus->mux = plat->bus_mux[i];
i2c_bus->mux_len = plat->bus_mux_len[i];
i2c_bus->bus_clk_rate = plat->bus_clk_rate[i] ?: 100000;
i2c_bus->scl_gpio = plat->scl_gpio[i];
i2c_bus->sda_gpio = plat->sda_gpio[i];
i2c_bus->adapter.dev.of_node = pdev->dev.of_node;
i2c_bus->adapter.algo = &tegra_i2c_algo;
i2c_set_adapdata(&i2c_bus->adapter, i2c_bus);
i2c_bus->adapter.owner = THIS_MODULE;
i2c_bus->adapter.class = I2C_CLASS_HWMON;
strlcpy(i2c_bus->adapter.name, "Tegra I2C adapter",
sizeof(i2c_bus->adapter.name));
i2c_bus->adapter.dev.parent = &pdev->dev;
i2c_bus->adapter.nr = plat->adapter_nr + i;
if (plat->retries)
i2c_bus->adapter.retries = plat->retries;
else
i2c_bus->adapter.retries = TEGRA_I2C_RETRIES;
if (plat->timeout)
i2c_bus->adapter.timeout = plat->timeout;
ret = <API key>(&i2c_bus->adapter);
if (ret) {
dev_err(&pdev->dev, "Failed to add I2C adapter\n");
goto err_del_bus;
}
<API key>(&i2c_bus->adapter);
i2c_dev->bus_count++;
}
return 0;
err_del_bus:
while (i2c_dev->bus_count
i2c_del_adapter(&i2c_dev->busses[i2c_dev->bus_count].adapter);
return ret;
}
static int __devexit tegra_i2c_remove(struct platform_device *pdev)
{
struct tegra_i2c_dev *i2c_dev = <API key>(pdev);
while (i2c_dev->bus_count
i2c_del_adapter(&i2c_dev->busses[i2c_dev->bus_count].adapter);
if (i2c_dev->is_clkon_always)
<API key>(i2c_dev);
return 0;
}
#ifdef CONFIG_PM
static int <API key>(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct tegra_i2c_dev *i2c_dev = <API key>(pdev);
rt_mutex_lock(&i2c_dev->dev_lock);
i2c_dev->is_suspended = true;
if (i2c_dev->is_clkon_always)
<API key>(i2c_dev);
rt_mutex_unlock(&i2c_dev->dev_lock);
return 0;
}
static int <API key>(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct tegra_i2c_dev *i2c_dev = <API key>(pdev);
int ret;
rt_mutex_lock(&i2c_dev->dev_lock);
if (i2c_dev->is_clkon_always)
<API key>(i2c_dev);
ret = tegra_i2c_init(i2c_dev);
if (ret) {
rt_mutex_unlock(&i2c_dev->dev_lock);
return ret;
}
i2c_dev->is_suspended = false;
rt_mutex_unlock(&i2c_dev->dev_lock);
return 0;
}
static const struct dev_pm_ops tegra_i2c_pm = {
.suspend_noirq = <API key>,
.resume_noirq = <API key>,
};
#define TEGRA_I2C_PM (&tegra_i2c_pm)
#else
#define TEGRA_I2C_PM NULL
#endif
#if defined(CONFIG_OF)
/* Match table for of_platform binding */
static const struct of_device_id tegra_i2c_of_match[] __devinitconst = {
{ .compatible = "nvidia,tegra20-i2c", },
{},
};
MODULE_DEVICE_TABLE(of, tegra_i2c_of_match);
#endif
static struct platform_driver tegra_i2c_driver = {
.probe = tegra_i2c_probe,
.remove = __devexit_p(tegra_i2c_remove),
.driver = {
.name = "tegra-i2c",
.owner = THIS_MODULE,
.of_match_table = of_match_ptr(tegra_i2c_of_match),
.pm = TEGRA_I2C_PM,
},
};
static int __init <API key>(void)
{
return <API key>(&tegra_i2c_driver);
}
static void __exit <API key>(void)
{
<API key>(&tegra_i2c_driver);
}
subsys_initcall(<API key>);
module_exit(<API key>);
MODULE_DESCRIPTION("nVidia Tegra2 I2C Bus Controller driver");
MODULE_AUTHOR("Colin Cross");
MODULE_LICENSE("GPL v2");
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_25) on Wed Jul 23 10:47:42 EDT 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Deprecated List</title>
<meta name="date" content="2014-07-23">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Deprecated List";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar_top">
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li><a href="overview-tree.html">Tree</a></li>
<li class="navBarCell1Rev">Deprecated</li>
<li><a href="index-files/index-1.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?deprecated-list.html" target="_top">Frames</a></li>
<li><a href="deprecated-list.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<h1 title="Deprecated API" class="title">Deprecated API</h1>
<h2 title="Contents">Contents</h2>
</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li><a href="overview-tree.html">Tree</a></li>
<li class="navBarCell1Rev">Deprecated</li>
<li><a href="index-files/index-1.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?deprecated-list.html" target="_top">Frames</a></li>
<li><a href="deprecated-list.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip-navbar_bottom">
</a></div>
</body>
</html>
|
#include <pthread.h>
struct user_desc {
unsigned int entry_number;
unsigned long base_addr;
unsigned int limit;
unsigned int seg_32bit:1;
unsigned int contents:2;
unsigned int read_exec_only:1;
unsigned int limit_in_pages:1;
unsigned int seg_not_present:1;
unsigned int useable:1;
unsigned int empty:25;
};
extern int __set_thread_area(struct user_desc *u_info);
/* the following can't be const, since the first call will
* update the 'entry_number' field
*/
static struct user_desc _tls_desc =
{
-1,
0,
0x1000,
1,
0,
0,
1,
0,
1,
0
};
static pthread_mutex_t _tls_desc_lock = <API key>;
struct _thread_area_head {
void *self;
};
/* we implement thread local storage through the gs: segment descriptor
* we create a segment descriptor for the tls
*/
int __set_tls(void *ptr)
{
int rc, segment;
pthread_mutex_lock(&_tls_desc_lock);
_tls_desc.base_addr = (unsigned long)ptr;
/* We also need to write the location of the tls to ptr[0] */
((struct _thread_area_head *)ptr)->self = ptr;
rc = __set_thread_area( &_tls_desc );
if (rc != 0)
{
/* could not set thread local area */
<API key>(&_tls_desc_lock);
return -1;
}
/* this weird computation comes from GLibc */
segment = _tls_desc.entry_number*8 + 3;
asm __volatile__ (
" movw %w0, %%gs" :: "q"(segment)
);
<API key>(&_tls_desc_lock);
return 0;
}
|
RTGUI 0.6.1 Release Notes
This is mainly a bug fixing release. Now the window system can be used
intensively.
# Running Environment
In theory, new RTGUI can run on all the devices running old RTGUI. There is
a simulator which run on Windows to help evaluating the new RTGUI. The default
running environment is RealTouch. The simulator in RT-Thread could also be used.
Because RT-Thread has removed all the RTGUI components from the source tree, in
order to run RTGUI in the upstream RT-Thread, you have to copy the
`components/rtgui` to the `components` folder in RTT. If you need demo, files
in `demo/examples` should also be copied into `examples/gui`.
# Main Changes
0. Simplified the windows showing algorithm. Children window will always be
shown when parent window has been shown. 257589a
0. Move `calibration.c` in bsps into RTGUI. There is no need to write it's
own `calibration.c` for all the bsps. calibration in RTGUI provides
`<API key>` and `<API key>` API, by which the user
could use to skip the calibration or save calibration data. The example is
in bsp/stm31f10x . bd7c6e4
# Bug fixes
- 3ce204d: fixed the children window of root window could not be modaled bug.
- 4d5564d: `<API key>` could not be used on window. Thanks to
xiao for reporting the bug.
- dfb477e: repaint the whole window tree when one window in the tree has been activated.
- f42adc2: delete useless RTM\_EXPORT. Thanks to prife for bug reporting.
- cb3bf9a: fixed clip updating bug when hiding widgets. Thanks to xiao for
bug reporting.
- 110e0c6: When file fonts has been enabled but the file could not be opened,
fire a warning on console. Thanks to prife, and wnnwoo .
- 7611e37: fixed compiling error in demo\_view\_listctrl . Thanks to znfc2 .
- 3b1f698: added a underflow check on `ref_count` in `rtgui_app_exit`.
|
<?php
/**
* PayPal Standard payment "form"
*/
class <API key> extends <API key>
{
/**
* Payment method code
* @var string
*/
protected $_methodCode = <API key>::METHOD_WPP_EXPRESS;
/**
* Set template and redirect message
*/
protected function _construct()
{
$result = parent::_construct();
$this->setRedirectMessage(Mage::helper('paypal')->__('You will be redirected to the PayPal website.'));
return $result;
}
/**
* Set data to block
*
* @return <API key>
*/
protected function _beforeToHtml()
{
$customerId = Mage::getSingleton('customer/session')->getCustomerId();
if (Mage::helper('paypal')-><API key>($this->_config, $customerId)
&& $this-><API key>()) {
$this->setCreateBACode(<API key>::<API key>);
}
return parent::_beforeToHtml();
}
}
|
CKEDITOR.plugins.setLang( 'elementspath', 'si', {
eleLabel: 'මුලද්රව්ය මාර්ගය',
eleTitle: '%1 මුල'
} );
|
'use strict';
import H from './Globals.js';
import './Utilities.js';
import './Options.js';
import './Series.js';
var pick = H.pick,
seriesType = H.seriesType;
/**
* Spline series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.spline
*
* @augments Highcarts.Series
*/
seriesType(
'spline',
'line',
/**
* A spline series is a special type of line series, where the segments
* between the data points are smoothed.
*
* @sample {highcharts} highcharts/demo/<API key>/
* Spline chart
* @sample {highstock} stock/demo/spline/
* Spline chart
*
* @extends plotOptions.series
* @excluding step
* @product highcharts highstock
* @optionparent plotOptions.spline
*/
{
},
/** @lends seriesTypes.spline.prototype */ {
/**
* Get the spline segment from a given point's previous neighbour to the
* given point.
*
* @private
* @function Highcharts.seriesTypes.spline#getPointSpline
*
* @param {Array<Highcharts.Point>}
*
* @param {Highcharts.Point} point
*
* @param {number} i
*
* @return {Highcharts.SVGPathArray}
*/
getPointSpline: function (points, point, i) {
var
// 1 means control points midway between points, 2 means 1/3
// from the point, 3 is 1/4 etc
smoothing = 1.5,
denom = smoothing + 1,
plotX = point.plotX,
plotY = point.plotY,
lastPoint = points[i - 1],
nextPoint = points[i + 1],
leftContX,
leftContY,
rightContX,
rightContY,
ret;
function doCurve(otherPoint) {
return otherPoint &&
!otherPoint.isNull &&
otherPoint.doCurve !== false &&
!point.isCliff; // #6387, area splines next to null
}
// Find control points
if (doCurve(lastPoint) && doCurve(nextPoint)) {
var lastX = lastPoint.plotX,
lastY = lastPoint.plotY,
nextX = nextPoint.plotX,
nextY = nextPoint.plotY,
correction = 0;
leftContX = (smoothing * plotX + lastX) / denom;
leftContY = (smoothing * plotY + lastY) / denom;
rightContX = (smoothing * plotX + nextX) / denom;
rightContY = (smoothing * plotY + nextY) / denom;
// Have the two control points make a straight line through main
// point
if (rightContX !== leftContX) { // #5016, division by zero
correction = (
((rightContY - leftContY) * (rightContX - plotX)) /
(rightContX - leftContX) + plotY - rightContY
);
}
leftContY += correction;
rightContY += correction;
// to prevent false extremes, check that control points are
// between neighbouring points' y values
if (leftContY > lastY && leftContY > plotY) {
leftContY = Math.max(lastY, plotY);
// mirror of left control point
rightContY = 2 * plotY - leftContY;
} else if (leftContY < lastY && leftContY < plotY) {
leftContY = Math.min(lastY, plotY);
rightContY = 2 * plotY - leftContY;
}
if (rightContY > nextY && rightContY > plotY) {
rightContY = Math.max(nextY, plotY);
leftContY = 2 * plotY - rightContY;
} else if (rightContY < nextY && rightContY < plotY) {
rightContY = Math.min(nextY, plotY);
leftContY = 2 * plotY - rightContY;
}
// record for drawing in next point
point.rightContX = rightContX;
point.rightContY = rightContY;
}
// Visualize control points for debugging
/*
if (leftContX) {
this.chart.renderer.circle(
leftContX + this.chart.plotLeft,
leftContY + this.chart.plotTop,
2
)
.attr({
stroke: 'red',
'stroke-width': 2,
fill: 'none',
zIndex: 9
})
.add();
this.chart.renderer.path(['M', leftContX + this.chart.plotLeft,
leftContY + this.chart.plotTop,
'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
.attr({
stroke: 'red',
'stroke-width': 2,
zIndex: 9
})
.add();
}
if (rightContX) {
this.chart.renderer.circle(
rightContX + this.chart.plotLeft,
rightContY + this.chart.plotTop,
2
)
.attr({
stroke: 'green',
'stroke-width': 2,
fill: 'none',
zIndex: 9
})
.add();
this.chart.renderer.path(['M', rightContX + this.chart.plotLeft,
rightContY + this.chart.plotTop,
'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
.attr({
stroke: 'green',
'stroke-width': 2,
zIndex: 9
})
.add();
}
// */
ret = [
'C',
pick(lastPoint.rightContX, lastPoint.plotX),
pick(lastPoint.rightContY, lastPoint.plotY),
pick(leftContX, plotX),
pick(leftContY, plotY),
plotX,
plotY
];
// reset for updating series later
lastPoint.rightContX = lastPoint.rightContY = null;
return ret;
}
}
);
/**
* A `spline` series. If the [type](#series.spline.type) option is
* not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.spline
* @excluding dataParser, dataURL, step
* @product highcharts highstock
* @apioption series.spline
*/
/**
* An array of data points for the series. For the `spline` series type,
* points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values will be
* interpreted as `y` options. The `x` values will be automatically
* calculated, either starting at 0 and incremented by 1, or from
* `pointStart` and `pointInterval` given in the series options. If the axis
* has categories, these will be used. Example:
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of arrays with 2 values. In this case, the values correspond to
* `x,y`. If the first value is a string, it is applied as the name of the
* point, and the `x` value is inferred.
* ```js
* data: [
* [0, 9],
* [1, 2],
* [2, 8]
* ]
* ```
*
* 3. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.spline.turboThreshold), this option is not
* available.
* ```js
* data: [{
* x: 1,
* y: 9,
* name: "Point2",
* color: "#00FF00"
* }, {
* x: 1,
* y: 0,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/<API key>/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/<API key>/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/<API key>/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/<API key>/
* Config objects
*
* @type {Array<number|Array<(number|string),number>|*>}
* @extends series.line.data
* @product highcharts highstock
* @apioption series.spline.data
*/
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
# This file is part of Ansible
# Ansible is free software: you can redistribute it and/or modify
# (at your option) any later version.
# Ansible is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# Module to Reset to factory settings of Lenovo Switches
# Lenovo Networking
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
EXAMPLES = '''
Tasks : The following are examples of using the module cnos_reload. These are written in the main.yml file of the tasks directory.
- name: Test Reset to factory
cnos_factory:
host: "{{ inventory_hostname }}"
username: "{{ hostvars[inventory_hostname]['ansible_ssh_user'] }}"
password: "{{ hostvars[inventory_hostname]['ansible_ssh_pass'] }}"
deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"
outputfile: "./results/test_factory_{{ inventory_hostname }}_output.txt"
'''
RETURN = '''
msg:
description: Success or failure message
returned: always
type: string
sample: "Switch Startup Config is Reset to factory settings"
'''
import sys
try:
import paramiko
HAS_PARAMIKO = True
except ImportError:
HAS_PARAMIKO = False
import time
import socket
import array
import json
import time
import re
try:
from ansible.module_utils.network.cnos import cnos
HAS_LIB = True
except:
HAS_LIB = False
from ansible.module_utils.basic import AnsibleModule
from collections import defaultdict
def main():
module = AnsibleModule(
argument_spec=dict(
outputfile=dict(required=True),
host=dict(required=True),
username=dict(required=True),
password=dict(required=True, no_log=True),
enablePassword=dict(required=False, no_log=True),
deviceType=dict(required=True),),
supports_check_mode=False)
username = module.params['username']
password = module.params['password']
enablePassword = module.params['enablePassword']
cliCommand = "save erase \n"
outputfile = module.params['outputfile']
hostIP = module.params['host']
deviceType = module.params['deviceType']
output = ""
if not HAS_PARAMIKO:
module.fail_json(msg='paramiko is required for this module')
# Create instance of SSHClient object
remote_conn_pre = paramiko.SSHClient()
# Automatically add untrusted hosts (make sure okay for security policy in your environment)
remote_conn_pre.<API key>(paramiko.AutoAddPolicy())
# initiate SSH connection with the switch
remote_conn_pre.connect(hostIP, username=username, password=password)
time.sleep(2)
# Use invoke_shell to establish an 'interactive session'
remote_conn = remote_conn_pre.invoke_shell()
time.sleep(2)
# Enable and enter configure terminal then send command
output = output + cnos.<API key>("\n", ">", 2, remote_conn)
output = output + cnos.<API key>(enablePassword, 3, remote_conn)
# Make terminal length = 0
output = output + cnos.<API key>("terminal length 0\n", "#", 2, remote_conn)
# cnos.debugOutput(cliCommand)
# Send the CLi command
output = output + cnos.<API key>(cliCommand, "[n]", 2, remote_conn)
output = output + cnos.<API key>("y" + "\n", "#", 2, remote_conn)
# Save it into the file
file = open(outputfile, "a")
file.write(output)
file.close()
errorMsg = cnos.checkOutputForError(output)
if(errorMsg is None):
module.exit_json(changed=True, msg="Switch Startup Config is Reset to factory settings ")
else:
module.fail_json(msg=errorMsg)
if __name__ == '__main__':
main()
|
#ifndef <API key>
#define <API key>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <interleaver_fifo.h>
class qa_interleaver_fifo : public CppUnit::TestCase {
private:
interleaver_fifo<int> *fifo;
public:
void tearDown (){
delete fifo;
fifo = 0;
}
CPPUNIT_TEST_SUITE (qa_interleaver_fifo);
CPPUNIT_TEST (t0);
CPPUNIT_TEST (t1);
CPPUNIT_TEST (t2);
<API key> ();
private:
void t0 ();
void t1 ();
void t2 ();
};
#endif /* <API key> */
|
package org.zarroboogs.weibo.dao;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.zarroboogs.util.net.HttpUtility;
import org.zarroboogs.util.net.WeiboException;
import org.zarroboogs.util.net.HttpUtility.HttpMethod;
import org.zarroboogs.utils.ImageUtility;
import org.zarroboogs.utils.WeiBoURLs;
import org.zarroboogs.utils.file.FileLocationMethod;
import org.zarroboogs.utils.file.FileManager;
import org.zarroboogs.weibo.support.asyncdrawable.TaskCache;
import android.graphics.Bitmap;
import android.text.TextUtils;
import java.util.HashMap;
import java.util.Map;
public class MapDao {
public Bitmap getMap() throws WeiboException {
String url = WeiBoURLs.STATIC_MAP;
Map<String, String> map = new HashMap<String, String>();
map.put("access_token", access_token);
String coordinates = String.valueOf(lat) + "," + String.valueOf(lan);
map.put("center_coordinate", coordinates);
map.put("zoom", "14");
map.put("size", "600x380");
String jsonData = HttpUtility.getInstance().executeNormalTask(HttpMethod.Get, url, map);
String mapUrl = "";
try {
JSONObject jsonObject = new JSONObject(jsonData);
JSONArray array = jsonObject.optJSONArray("map");
jsonObject = array.getJSONObject(0);
mapUrl = jsonObject.getString("image_url");
} catch (JSONException e) {
}
if (TextUtils.isEmpty(mapUrl)) {
return null;
}
String filePath = FileManager.getFilePathFromUrl(mapUrl, FileLocationMethod.map);
boolean downloaded = TaskCache.<API key>(mapUrl, null, filePath, FileLocationMethod.map);
if (!downloaded) {
return null;
}
Bitmap bitmap = ImageUtility.readNormalPic(FileManager.getFilePathFromUrl(mapUrl, FileLocationMethod.map), -1, -1);
return bitmap;
}
public MapDao(String token, double lan, double lat) {
this.access_token = token;
this.lan = lan;
this.lat = lat;
}
private String access_token;
private double lan;
private double lat;
}
|
/**
* Class: mxHandle
*
* Implements a single custom handle for vertices.
*
* Constructor: mxHandle
*
* Constructs a new handle for the given state.
*
* Parameters:
*
* state - <mxCellState> of the cell to be handled.
*/
function mxHandle(state, cursor, image)
{
this.graph = state.view.graph;
this.state = state;
this.cursor = (cursor != null) ? cursor : this.cursor;
this.image = (image != null) ? image : this.image;
this.init();
};
/**
* Variable: cursor
*
* Specifies the cursor to be used for this handle. Default is 'default'.
*/
mxHandle.prototype.cursor = 'default';
/**
* Variable: image
*
* Specifies the <mxImage> to be used to render the handle. Default is null.
*/
mxHandle.prototype.image = null;
/**
* Variable: image
*
* Specifies the <mxImage> to be used to render the handle. Default is null.
*/
mxHandle.prototype.ignoreGrid = false;
/**
* Function: getPosition
*
* Hook for subclassers to return the current position of the handle.
*/
mxHandle.prototype.getPosition = function(bounds) { };
/**
* Function: setPosition
*
* Hooks for subclassers to update the style in the <state>.
*/
mxHandle.prototype.setPosition = function(bounds, pt, me) { };
/**
* Function: execute
*
* Hook for subclassers to execute the handle.
*/
mxHandle.prototype.execute = function() { };
/**
* Function: copyStyle
*
* Sets the cell style with the given name to the corresponding value in <state>.
*/
mxHandle.prototype.copyStyle = function(key)
{
this.graph.setCellStyles(key, this.state.style[key], [this.state.cell]);
};
/**
* Function: processEvent
*
* Processes the given <mxMouseEvent> and invokes <setPosition>.
*/
mxHandle.prototype.processEvent = function(me)
{
var scale = this.graph.view.scale;
var tr = this.graph.view.translate;
var pt = new mxPoint(me.getGraphX() / scale - tr.x, me.getGraphY() / scale - tr.y);
// Center shape on mouse cursor
if (this.shape != null && this.shape.bounds != null)
{
pt.x -= this.shape.bounds.width / scale / 4;
pt.y -= this.shape.bounds.height / scale / 4;
}
// Snaps to grid for the rotated position then applies the rotation for the direction after that
var alpha1 = -mxUtils.toRadians(this.getRotation());
var alpha2 = -mxUtils.toRadians(this.getTotalRotation()) - alpha1;
pt = this.flipPoint(this.rotatePoint(this.snapPoint(this.rotatePoint(pt, alpha1),
this.ignoreGrid || !this.graph.isGridEnabledEvent(me.getEvent())), alpha2));
this.setPosition(this.state.getPaintBounds(), pt, me);
this.positionChanged();
this.redraw();
};
/**
* Function: positionChanged
*
* Called after <setPosition> has been called in <processEvent>. This repaints
* the state using <mxCellRenderer>.
*/
mxHandle.prototype.positionChanged = function()
{
if (this.state.text != null)
{
this.state.text.apply(this.state);
}
if (this.state.shape != null)
{
this.state.shape.apply(this.state);
}
this.graph.cellRenderer.redraw(this.state, true);
};
/**
* Function: getRotation
*
* Returns the rotation defined in the style of the cell.
*/
mxHandle.prototype.getRotation = function()
{
if (this.state.shape != null)
{
return this.state.shape.getRotation();
}
return 0;
};
/**
* Function: getTotalRotation
*
* Returns the rotation from the style and the rotation from the direction of
* the cell.
*/
mxHandle.prototype.getTotalRotation = function()
{
if (this.state.shape != null)
{
return this.state.shape.getShapeRotation();
}
return 0;
};
/**
* Function: init
*
* Creates and initializes the shapes required for this handle.
*/
mxHandle.prototype.init = function()
{
var html = this.isHtmlRequired();
if (this.image != null)
{
this.shape = new mxImageShape(new mxRectangle(0, 0, this.image.width, this.image.height), this.image.src);
this.shape.preserveImageAspect = false;
}
else
{
this.shape = this.createShape(html);
}
this.initShape(html);
};
/**
* Function: createShape
*
* Creates and returns the shape for this handle.
*/
mxHandle.prototype.createShape = function(html)
{
var bounds = new mxRectangle(0, 0, mxConstants.HANDLE_SIZE, mxConstants.HANDLE_SIZE);
return new mxRectangleShape(bounds, mxConstants.HANDLE_FILLCOLOR, mxConstants.HANDLE_STROKECOLOR);
};
/**
* Function: initShape
*
* Initializes <shape> and sets its cursor.
*/
mxHandle.prototype.initShape = function(html)
{
if (html && this.shape.isHtmlAllowed())
{
this.shape.dialect = mxConstants.DIALECT_STRICTHTML;
this.shape.init(this.graph.container);
}
else
{
this.shape.dialect = (this.graph.dialect != mxConstants.DIALECT_SVG) ? mxConstants.DIALECT_MIXEDHTML : mxConstants.DIALECT_SVG;
if (this.cursor != null)
{
this.shape.init(this.graph.getView().getOverlayPane());
}
}
mxEvent.redirectMouseEvents(this.shape.node, this.graph, this.state);
this.shape.node.style.cursor = this.cursor;
};
/**
* Function: redraw
*
* Renders the shape for this handle.
*/
mxHandle.prototype.redraw = function()
{
if (this.shape != null && this.state.shape != null)
{
var pt = this.getPosition(this.state.getPaintBounds());
if (pt != null)
{
var alpha = mxUtils.toRadians(this.getTotalRotation());
pt = this.rotatePoint(this.flipPoint(pt), alpha);
var scale = this.graph.view.scale;
var tr = this.graph.view.translate;
this.shape.bounds.x = Math.floor((pt.x + tr.x) * scale - this.shape.bounds.width / 2);
this.shape.bounds.y = Math.floor((pt.y + tr.y) * scale - this.shape.bounds.height / 2);
// Needed to force update of text bounds
this.state.unscaledWidth = null;
this.shape.redraw();
}
}
};
/**
* Function: isHtmlRequired
*
* Returns true if this handle should be rendered in HTML. This returns true if
* the text node is in the graph container.
*/
mxHandle.prototype.isHtmlRequired = function()
{
return this.state.text != null && this.state.text.node.parentNode == this.graph.container;
};
/**
* Function: rotatePoint
*
* Rotates the point by the given angle.
*/
mxHandle.prototype.rotatePoint = function(pt, alpha)
{
var bounds = this.state.getCellBounds();
var cx = new mxPoint(bounds.getCenterX(), bounds.getCenterY());
var cos = Math.cos(alpha);
var sin = Math.sin(alpha);
return mxUtils.getRotatedPoint(pt, cos, sin, cx);
};
/**
* Function: flipPoint
*
* Flips the given point vertically and/or horizontally.
*/
mxHandle.prototype.flipPoint = function(pt)
{
if (this.state.shape != null)
{
var bounds = this.state.getCellBounds();
if (this.state.shape.flipH)
{
pt.x = 2 * bounds.x + bounds.width - pt.x;
}
if (this.state.shape.flipV)
{
pt.y = 2 * bounds.y + bounds.height - pt.y;
}
}
return pt;
};
/**
* Function: snapPoint
*
* Snaps the given point to the grid if ignore is false. This modifies
* the given point in-place and also returns it.
*/
mxHandle.prototype.snapPoint = function(pt, ignore)
{
if (!ignore)
{
pt.x = this.graph.snap(pt.x);
pt.y = this.graph.snap(pt.y);
}
return pt;
};
/**
* Function: setVisible
*
* Shows or hides this handle.
*/
mxHandle.prototype.setVisible = function(visible)
{
if (this.shape != null && this.shape.node != null)
{
this.shape.node.style.display = (visible) ? '' : 'none';
}
};
/**
* Function: reset
*
* Resets the state of this handle by setting its visibility to true.
*/
mxHandle.prototype.reset = function()
{
this.setVisible(true);
this.state.style = this.graph.getCellStyle(this.state.cell);
this.positionChanged();
};
/**
* Function: destroy
*
* Destroys this handle.
*/
mxHandle.prototype.destroy = function()
{
if (this.shape != null)
{
this.shape.destroy();
this.shape = null;
}
};
|
# Deploy 64-bit Mac OS X standalones
You can now deploy both 32-bit and 64-bit standalones for Mac OS X,
and you can select which engines you'd like to include in the
standalone builder.
**This feature was sponsored by the community Feature Exchange.**
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>[ 593705 ] Use of < comparison symbol confuses Tidy</title>
<script type="text/javascript">
function foo( bar, baz )
{
return ( bar < baz ? true : false );
}
</script>
</head>
<body>
<p>Does the script confuse Tidy?</p>
</body>
</html>
|
version: 8.0.0-dp-3
# LiveCode Builder Language
## Handler definitions
* The syntax for declaring the type of the return value from a handler
(or handler type) is now `[ 'returns' 'nothing' | 'returns' <Type> ]`.
# [14906] Change 'as <Type>' to 'returns nothing' or 'returns <Type>' in handler return type definitions.
# [14926] LCB-Language: Remove deprecated handler return type syntax.
|
// This file is part of the ClearCanvas RIS/PACS open source project.
// The ClearCanvas RIS/PACS open source project is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// The ClearCanvas RIS/PACS open source project is distributed in the hope that it
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// the ClearCanvas RIS/PACS open source project. If not, see
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using ClearCanvas.Common;
using ClearCanvas.Desktop;
using ClearCanvas.Enterprise.Common;
using ClearCanvas.Ris.Application.Common;
using ClearCanvas.Ris.Application.Common.Admin.LocationAdmin;
using ClearCanvas.Ris.Application.Common.Admin.FacilityAdmin;
using ClearCanvas.Desktop.Validation;
namespace ClearCanvas.Ris.Client.Admin
{
<summary>
Extension point for views onto <see cref="<API key>"/>
</summary>
[ExtensionPoint]
public class <API key> : ExtensionPoint<<API key>>
{
}
<summary>
<API key> class
</summary>
[AssociateView(typeof(<API key>))]
public class <API key> : <API key>
{
private List<FacilitySummary> _facilityChoices;
private LocationDetail _locationDetail;
private EntityRef _locationRef;
private readonly bool _isNew;
private LocationSummary _locationSummary;
<summary>
Constructor
</summary>
public <API key>()
{
_isNew = true;
}
public <API key>(EntityRef locationRef)
{
_isNew = false;
_locationRef = locationRef;
}
public LocationSummary LocationSummary
{
get { return _locationSummary; }
}
public override void Start()
{
if (_isNew)
{
_locationDetail = new LocationDetail();
}
else
{
Platform.GetService(
delegate(<API key> service)
{
var response = service.LoadLocationForEdit(new <API key>(_locationRef));
_locationRef = response.LocationDetail.LocationRef;
_locationDetail = response.LocationDetail;
});
}
Platform.GetService(
delegate(<API key> service)
{
var response = service.ListAllFacilities(new <API key>());
_facilityChoices = response.Facilities;
if (_isNew && _locationDetail.Facility == null && response.Facilities.Count > 0)
{
_locationDetail.Facility = response.Facilities[0];
}
});
base.Start();
}
public LocationDetail LocationDetail
{
get { return _locationDetail; }
set { _locationDetail = value; }
}
#region Presentation Model
[ValidateNotNull]
public string Id
{
get { return _locationDetail.Id; }
set
{
_locationDetail.Id = value;
this.Modified = true;
}
}
[ValidateNotNull]
public string Name
{
get { return _locationDetail.Name; }
set
{
_locationDetail.Name = value;
this.Modified = true;
}
}
public string Description
{
get { return _locationDetail.Description; }
set
{
_locationDetail.Description = value;
this.Modified = true;
}
}
public IList FacilityChoices
{
get { return _facilityChoices; }
}
[ValidateNotNull]
public FacilitySummary Facility
{
get { return _locationDetail.Facility; }
set
{
_locationDetail.Facility = value;
this.Modified = true;
}
}
public string FormatFacility(object item)
{
var f = (FacilitySummary) item;
return f.Name;
}
public string Building
{
get { return _locationDetail.Building; }
set
{
_locationDetail.Building = value;
this.Modified = true;
}
}
public string Floor
{
get { return _locationDetail.Floor; }
set
{
_locationDetail.Floor = value;
this.Modified = true;
}
}
public string PointOfCare
{
get { return _locationDetail.PointOfCare; }
set
{
_locationDetail.PointOfCare = value;
this.Modified = true;
}
}
public void Accept()
{
if (this.HasValidationErrors)
{
this.ShowValidation(true);
}
else
{
try
{
SaveChanges();
this.Exit(<API key>.Accepted);
}
catch (Exception e)
{
ExceptionHandler.Report(e, SR.<API key>, this.Host.DesktopWindow,
delegate
{
this.ExitCode = <API key>.Error;
this.Host.Exit();
});
}
}
}
public void Cancel()
{
this.ExitCode = <API key>.None;
Host.Exit();
}
public bool AcceptEnabled
{
get { return this.Modified; }
}
#endregion
private void SaveChanges()
{
if (_isNew)
{
Platform.GetService(
delegate(<API key> service)
{
var response = service.AddLocation(new AddLocationRequest(_locationDetail));
_locationRef = response.Location.LocationRef;
_locationSummary = response.Location;
});
}
else
{
Platform.GetService(
delegate(<API key> service)
{
var response = service.UpdateLocation(new <API key>(_locationDetail));
_locationRef = response.Location.LocationRef;
_locationSummary = response.Location;
});
}
}
public event EventHandler <API key>
{
add { this.ModifiedChanged += value; }
remove { this.ModifiedChanged -= value; }
}
}
}
|
// This file is part of the ClearCanvas RIS/PACS open source project.
// The ClearCanvas RIS/PACS open source project is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// The ClearCanvas RIS/PACS open source project is distributed in the hope that it
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// the ClearCanvas RIS/PACS open source project. If not, see
#endregion
using System;
using System.Diagnostics;
using System.IO;
using ClearCanvas.Common;
using ClearCanvas.Common.Utilities;
using ClearCanvas.Dicom.Utilities.Command;
using ClearCanvas.ImageServer.Common;
using ClearCanvas.ImageServer.Common.Utilities;
using ClearCanvas.ImageServer.Core.Command;
using ClearCanvas.ImageServer.Core.Data;
using ClearCanvas.ImageServer.Core.Validation;
using ClearCanvas.ImageServer.Enterprise.Command;
using ClearCanvas.ImageServer.Model;
namespace ClearCanvas.ImageServer.Services.WorkQueue.CleanupReconcile
{
<summary>
For processing 'CleanupReconcile' WorkQueue items.
</summary>
[<API key>(ValidationTypes = <API key>.None)]
class <API key> : BaseItemProcessor
{
private <API key> _reconcileQueueData;
protected override bool CanStart()
{
return true;
}
protected override void ProcessItem(Model.WorkQueue item)
{
Platform.<API key>(item, "item");
Platform.<API key>(item.Data, "item.Data");
_reconcileQueueData = XmlUtils.Deserialize<<API key>>(WorkQueueItem.Data);
LoadUids(item);
if (WorkQueueUidList.Count == 0)
{
DirectoryUtility.DeleteIfEmpty(_reconcileQueueData.StoragePath);
Platform.Log(LogLevel.Info, "Reconcile Cleanup is completed. GUID={0}.", WorkQueueItem.GetKey());
PostProcessing(WorkQueueItem,
<API key>.Complete,
<API key>.ResetQueueState);
}
else
{
Platform.Log(LogLevel.Info,
"Starting Cleanup of Reconcile Queue item for study {0} for Patient {1} (PatientId:{2} A#:{3}) on Partition {4}, {5} objects",
Study.StudyInstanceUid, Study.PatientsName, Study.PatientId,
Study.AccessionNumber, ServerPartition.Description,
WorkQueueUidList.Count);
ProcessUidList();
Platform.Log(LogLevel.Info, "Successfully complete Reconcile Cleanup. GUID={0}. {0} uids processed.", WorkQueueItem.GetKey(), WorkQueueUidList.Count);
PostProcessing(WorkQueueItem,
<API key>.Pending,
<API key>.None);
}
}
private void ProcessUidList()
{
Platform.<API key>(WorkQueueUidList, "WorkQueueUidList");
foreach(WorkQueueUid uid in WorkQueueUidList)
{
ProcessUid(uid);
}
}
private void ProcessUid(WorkQueueUid uid)
{
Platform.<API key>(uid, "uid");
string imagePath = GetUidPath(uid);
using (<API key> processor = new <API key>(String.Format("Deleting {0}", uid.SopInstanceUid)))
{
// If the file for some reason doesn't exist, we just ignore it
if (File.Exists(imagePath))
{
Platform.Log(ServerPlatform.InstanceLogLevel, "Deleting {0}", imagePath);
FileDeleteCommand deleteFile = new FileDeleteCommand(imagePath, true);
processor.AddCommand(deleteFile);
}
else
{
Platform.Log(LogLevel.Warn, "WARNING {0} is missing.", imagePath);
}
<API key> deleteUid = new <API key>(uid);
processor.AddCommand(deleteUid);
if (!processor.Execute())
{
throw new Exception(String.Format("Unable to delete image {0}", uid.SopInstanceUid));
}
}
}
private string GetUidPath(WorkQueueUid sop)
{
string imagePath = Path.Combine(_reconcileQueueData.StoragePath, sop.SopInstanceUid + ServerPlatform.DicomFileExtension);
Debug.Assert(String.IsNullOrEmpty(imagePath)==false);
return imagePath;
}
}
}
|
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <gnuradio/io_signature.h>
#include "<API key>.h"
#include <complex>
#include <gnuradio/expj.h>
#include <gnuradio/math.h>
namespace gr {
namespace dtv {
//Number of symbols in a frame
const int dvbt_pilot_gen::d_symbols_per_frame = SYMBOLS_PER_FRAME;
//Number of frames in a superframe
const int dvbt_pilot_gen::<API key> = <API key>;
// 2k mode
// Scattered pilots # of carriers
const int dvbt_pilot_gen::<API key> = <API key>;
// Continual pilots # of carriers and positions
const int dvbt_pilot_gen::<API key> = <API key>;
const int dvbt_pilot_gen::<API key>[dvbt_pilot_gen::<API key>] = {
0, 48, 54, 87, 141, 156, 192, \
201, 255, 279, 282, 333, 432, 450, \
483, 525, 531, 618, 636, 714, 759, \
765, 780, 804, 873, 888, 918, 939, \
942, 969, 984, 1050, 1101, 1107, 1110, \
1137, 1140, 1146, 1206, 1269, 1323, 1377, \
1491, 1683, 1704
};
// TPS pilots # of carriers and positions
const int dvbt_pilot_gen::<API key> = TPS_PILOT_SIZE_2k;
const int dvbt_pilot_gen::d_tps_carriers_2k[dvbt_pilot_gen::<API key>] = {
34, 50, 209, 346, 413, \
569, 595, 688, 790, 901, \
1073, 1219, 1262, 1286, 1469, \
1594, 1687
};
// 8k mode
// Scattered pilots # of carriers
const int dvbt_pilot_gen::<API key> = <API key>;
// Continual pilots # of carriers and positions
const int dvbt_pilot_gen::<API key> = <API key>;
const int dvbt_pilot_gen::<API key>[dvbt_pilot_gen::<API key>] = {
0, 48, 54, 87, 141, 156, 192,
201, 255, 279, 282, 333, 432, 450,
483, 525, 531, 618, 636, 714, 759,
765, 780, 804, 873, 888, 918, 939,
942, 969, 984, 1050, 1101, 1107, 1110,
1137, 1140, 1146, 1206, 1269, 1323, 1377,
1491, 1683, 1704, 1752, 1758, 1791, 1845,
1860, 1896, 1905, 1959, 1983, 1986, 2037,
2136, 2154, 2187, 2229, 2235, 2322, 2340,
2418, 2463, 2469, 2484, 2508, 2577, 2592,
2622, 2643, 2646, 2673, 2688, 2754, 2805,
2811, 2814, 2841, 2844, 2850, 2910, 2973,
3027, 3081, 3195, 3387, 3408, 3456, 3462,
3495, 3549, 3564, 3600, 3609, 3663, 3687,
3690, 3741, 3840, 3858, 3891, 3933, 3939,
4026, 4044, 4122, 4167, 4173, 4188, 4212,
4281, 4296, 4326, 4347, 4350, 4377, 4392,
4458, 4509, 4515, 4518, 4545, 4548, 4554,
4614, 4677, 4731, 4785, 4899, 5091, 5112,
5160, 5166, 5199, 5253, 5268, 5304, 5313,
5367, 5391, 5394, 5445, 5544, 5562, 5595,
5637, 5643, 5730, 5748, 5826, 5871, 5877,
5892, 5916, 5985, 6000, 6030, 6051, 6054,
6081, 6096, 6162, 6213, 6219, 6222, 6249,
6252, 6258, 6318, 6381, 6435, 6489, 6603,
6795, 6816
};
// TPS pilots # of carriers and positions
const int dvbt_pilot_gen::<API key> = TPS_PILOT_SIZE_8k;
const int dvbt_pilot_gen::d_tps_carriers_8k[dvbt_pilot_gen::<API key>] = {
34, 50, 209, 346, 413, 569, 595, 688, \
790, 901, 1073, 1219, 1262, 1286, 1469, 1594, \
1687, 1738, 1754, 1913, 2050, 2117, 2273, 2299, \
2392, 2494, 2605, 2777, 2923, 2966, 2990, 3173, \
3298, 3391, 3442, 3458, 3617, 3754, 3821, 3977, \
4003, 4096, 4198, 4309, 4481, 4627, 4670, 4694, \
4877, 5002, 5095, 5146, 5162, 5321, 5458, 5525, \
5681, 5707, 5800, 5902, 6013, 6185, 6331, 6374, \
6398, 6581, 6706, 6799
};
// TPS sync sequence for odd and even frames
const int dvbt_pilot_gen::d_tps_sync_size = 16; // TODO
const int dvbt_pilot_gen::d_tps_sync_even[d_tps_sync_size] = {
0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0
};
const int dvbt_pilot_gen::d_tps_sync_odd[d_tps_sync_size] = {
1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1
};
/*
* Constructor of class
*/
dvbt_pilot_gen::dvbt_pilot_gen(const dvbt_configure &c) : config(c),
d_spilot_index(0),
d_cpilot_index(0),
d_tpilot_index(0),
d_symbol_index(0),
<API key>(0),
d_frame_index(0),
d_superframe_index(0),
d_freq_offset_max(8),
d_trigger_index(0),
d_payload_index(0),
d_chanestim_index(0),
<API key>(0),
d_mod_symbol_index(0)
{
//Determine parameters from config file
d_Kmin = config.d_Kmin;
d_Kmax = config.d_Kmax;
d_fft_length = config.d_fft_length;
d_payload_length = config.d_payload_length;
d_zeros_on_left = config.d_zeros_on_left;
d_zeros_on_right = config.d_zeros_on_right;
d_cp_length = config.d_cp_length;
//Set-up pilot data depending on transmission mode
if (config.d_transmission_mode == T2k) {
<API key> = <API key>;
<API key> = <API key>;
d_cpilot_carriers = <API key>;
d_tps_carriers_size = <API key>;
d_tps_carriers = d_tps_carriers_2k;
}
else if (config.d_transmission_mode == T8k) {
<API key> = <API key>;
<API key> = <API key>;
d_cpilot_carriers = <API key>;
d_tps_carriers_size = <API key>;
d_tps_carriers = d_tps_carriers_8k;
}
else {
<API key> = <API key>;
<API key> = <API key>;
d_cpilot_carriers = <API key>;
d_tps_carriers_size = <API key>;
d_tps_carriers = d_tps_carriers_2k;
}
d_freq_offset = 0;
<API key> = 0.0;
<API key> = 0.0;
//allocate PRBS buffer
d_wk = new char[d_Kmax - d_Kmin + 1];
if (d_wk == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_wk." << std::endl;
throw std::bad_alloc();
}
// Generate wk sequence
generate_prbs();
// allocate buffer for scattered pilots
<API key> = new (std::nothrow) gr_complex[d_Kmax - d_Kmin + 1];
if (<API key> == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for <API key>." << std::endl;
delete [] d_wk;
throw std::bad_alloc();
}
// allocate buffer for channel gains (for each useful carrier)
d_channel_gain = new (std::nothrow) gr_complex[d_Kmax - d_Kmin + 1];
if (d_channel_gain == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_channel_gain." << std::endl;
delete [] <API key>;
delete [] d_wk;
throw std::bad_alloc();
}
// Allocate buffer for continual pilots phase diffs
d_known_phase_diff = new (std::nothrow) float[<API key> - 1];
if (d_known_phase_diff == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_known_phase_diff." << std::endl;
delete [] d_channel_gain;
delete [] <API key>;
delete [] d_wk;
throw std::bad_alloc();
}
// Obtain phase diff for all continual pilots
for (int i = 0; i < (<API key> - 1); i++) {
d_known_phase_diff[i] = \
norm(get_cpilot_value(d_cpilot_carriers[i + 1]) - get_cpilot_value(d_cpilot_carriers[i]));
}
d_cpilot_phase_diff = new (std::nothrow) float[<API key> - 1];
if (d_cpilot_phase_diff == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_cpilot_phase_diff." << std::endl;
delete [] d_known_phase_diff;
delete [] d_channel_gain;
delete [] <API key>;
delete [] d_wk;
throw std::bad_alloc();
}
// Allocate buffer for derotated input symbol
d_derot_in = new (std::nothrow) gr_complex[d_fft_length];
if (d_derot_in == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_derot_in." << std::endl;
delete [] d_cpilot_phase_diff;
delete [] d_known_phase_diff;
delete [] d_channel_gain;
delete [] <API key>;
delete [] d_wk;
throw std::bad_alloc();
}
// allocate buffer for first tps symbol constellation
d_tps_carriers_val = new (std::nothrow) gr_complex[d_tps_carriers_size];
if (d_tps_carriers_val == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_tps_carriers_val." << std::endl;
delete [] d_derot_in;
delete [] d_cpilot_phase_diff;
delete [] d_known_phase_diff;
delete [] d_channel_gain;
delete [] <API key>;
delete [] d_wk;
throw std::bad_alloc();
}
// allocate tps data buffer
d_tps_data = new (std::nothrow) unsigned char[d_symbols_per_frame];
if (d_tps_data == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_tps_data." << std::endl;
delete [] d_tps_carriers_val;
delete [] d_derot_in;
delete [] d_cpilot_phase_diff;
delete [] d_known_phase_diff;
delete [] d_channel_gain;
delete [] <API key>;
delete [] d_wk;
throw std::bad_alloc();
}
d_prev_tps_symbol = new (std::nothrow) gr_complex[d_tps_carriers_size];
if (d_prev_tps_symbol == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_prev_tps_symbol." << std::endl;
delete [] d_tps_data;
delete [] d_tps_carriers_val;
delete [] d_derot_in;
delete [] d_cpilot_phase_diff;
delete [] d_known_phase_diff;
delete [] d_channel_gain;
delete [] <API key>;
delete [] d_wk;
throw std::bad_alloc();
}
memset(d_prev_tps_symbol, 0, d_tps_carriers_size * sizeof(gr_complex));
d_tps_symbol = new (std::nothrow) gr_complex[d_tps_carriers_size];
if (d_tps_symbol == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_tps_symbol." << std::endl;
delete [] d_prev_tps_symbol;
delete [] d_tps_data;
delete [] d_tps_carriers_val;
delete [] d_derot_in;
delete [] d_cpilot_phase_diff;
delete [] d_known_phase_diff;
delete [] d_channel_gain;
delete [] <API key>;
delete [] d_wk;
throw std::bad_alloc();
}
memset(d_tps_symbol, 0, d_tps_carriers_size * sizeof(gr_complex));
// Init receive TPS data vector
for (int i = 0; i < d_symbols_per_frame; i++) {
d_rcv_tps_data.push_back(0);
}
// Init TPS sync sequence
for (int i = 0; i < d_tps_sync_size; i++) {
d_tps_sync_evenv.push_back(d_tps_sync_even[i]);
d_tps_sync_oddv.push_back(d_tps_sync_odd[i]);
}
// Allocate buffer for channel estimation carriers
<API key> = new (std::nothrow) int[d_Kmax - d_Kmin + 1];
if (<API key> == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for <API key>." << std::endl;
delete [] d_tps_symbol;
delete [] d_prev_tps_symbol;
delete [] d_tps_data;
delete [] d_tps_carriers_val;
delete [] d_derot_in;
delete [] d_cpilot_phase_diff;
delete [] d_known_phase_diff;
delete [] d_channel_gain;
delete [] <API key>;
delete [] d_wk;
throw std::bad_alloc();
}
// Allocate buffer for payload carriers
d_payload_carriers = new (std::nothrow) int[d_Kmax - d_Kmin + 1];
if (d_payload_carriers == NULL) {
std::cerr << "Reference Signals, cannot allocate memory for d_payload_carriers." << std::endl;
delete [] <API key>;
delete [] d_tps_symbol;
delete [] d_prev_tps_symbol;
delete [] d_tps_data;
delete [] d_tps_carriers_val;
delete [] d_derot_in;
delete [] d_cpilot_phase_diff;
delete [] d_known_phase_diff;
delete [] d_channel_gain;
delete [] <API key>;
delete [] d_wk;
throw std::bad_alloc();
}
// Reset the pilot generator
<API key>();
// Format TPS data with current values
format_tps_data();
}
/*
* Destructor of class
*/
dvbt_pilot_gen::~dvbt_pilot_gen()
{
delete [] d_payload_carriers;
delete [] <API key>;
delete [] d_tps_symbol;
delete [] d_prev_tps_symbol;
delete [] d_tps_data;
delete [] d_tps_carriers_val;
delete [] d_derot_in;
delete [] d_cpilot_phase_diff;
delete [] d_known_phase_diff;
delete [] d_channel_gain;
delete [] <API key>;
delete [] d_wk;
}
/*
* Generate PRBS sequence
* X^11 + X^2 + 1
* en 300 744 - section 4.5.2
*/
void
dvbt_pilot_gen::generate_prbs()
{
// init PRBS register with 1s
unsigned int reg_prbs = (1 << 11) - 1;
for (int k = 0; k < (d_Kmax - d_Kmin + 1); k++) {
d_wk[k] = (char)(reg_prbs & 0x01);
int new_bit = ((reg_prbs >> 2) ^ (reg_prbs >> 0)) & 0x01;
reg_prbs = (reg_prbs >> 1) | (new_bit << 10);
}
}
/*
* Generate shortened BCH(67, 53) codes from TPS data
* Extend the code with 60 bits and use BCH(127, 113)
*/
void
dvbt_pilot_gen::generate_bch_code()
{
//TODO
//DO other way: if (feedback == 1) reg = reg ^ polymomial
//else nothing
//(n, k) = (127, 113) = (60+67, 60+53)
unsigned int reg_bch = 0;
unsigned char data_in[113];
//fill in 60 zeros
memset(&data_in[0], 0, 60);
//fill in TPS data - start bit not included
memcpy(&data_in[60], &d_tps_data[1], 53);
//X^14+X^9+X^8+X^6+X^5+X^4+X^2+X+1
for (int i = 0; i < 113; i++) {
int feedback = 0x1 & (data_in[i] ^ reg_bch);
reg_bch = reg_bch >> 1;
reg_bch |= feedback << 13;
reg_bch = reg_bch \
^ (feedback << 12) ^ (feedback << 11) \
^ (feedback << 9) ^ (feedback << 8) \
^ (feedback << 7) ^ (feedback << 5) \
^ (feedback << 4);
}
for (int i = 0; i < 14; i++) {
d_tps_data[i + 54] = 0x1 & (reg_bch >> i);
}
}
int
dvbt_pilot_gen::verify_bch_code(std::deque<char> data)
{
int ret = 0;
//TODO
//DO other way: if (feedback == 1) reg = reg ^ polymomial
//else nothing
//(n, k) = (127, 113) = (60+67, 60+53)
unsigned int reg_bch = 0;
unsigned char data_in[113];
//fill in 60 zeros
memset(&data_in[0], 0, 60);
//fill in TPS data - start bit not included
//memcpy(&data_in[60], &data[1], 53);
for (int i = 0; i < 53; i++) {
data_in[60 + i] = data[1 + i];
}
//X^14+X^9+X^8+X^6+X^5+X^4+X^2+X+1
for (int i = 0; i < 113; i++) {
int feedback = 0x1 & (data_in[i] ^ reg_bch);
reg_bch = reg_bch >> 1;
reg_bch |= feedback << 13;
reg_bch = reg_bch \
^ (feedback << 12) ^ (feedback << 11) \
^ (feedback << 9) ^ (feedback << 8) \
^ (feedback << 7) ^ (feedback << 5) \
^ (feedback << 4);
}
for (int i = 0; i < 14; i++) {
if ((unsigned int)data[i + 54] != (0x1 & (reg_bch >> i))) {
ret = -1;
break;
}
}
return ret;
}
void
dvbt_pilot_gen::set_symbol_index(int sindex)
{
d_symbol_index = sindex;
}
int
dvbt_pilot_gen::get_symbol_index()
{
return d_symbol_index;
}
void
dvbt_pilot_gen::set_tps_data()
{
}
void
dvbt_pilot_gen::get_tps_data()
{
}
/*
* Reset pilot generator
*/
void
dvbt_pilot_gen::<API key>()
{
d_spilot_index = 0; d_cpilot_index = 0; d_tpilot_index = 0;
d_payload_index = 0; d_chanestim_index = 0;
d_symbol_index = 0; d_frame_index = 0; d_superframe_index = 0;
<API key> = 0;
d_equalizer_ready = 0;
}
/*
* Init scattered pilot generator
*/
int
dvbt_pilot_gen::get_current_spilot(int sindex) const
{
//TODO - can be optimized for same symbol_index
return (d_Kmin + 3 * (sindex % 4) + 12 * d_spilot_index);
}
gr_complex
dvbt_pilot_gen::get_spilot_value(int spilot)
{
// TODO - can be calculated at the beginning
return gr_complex(4 * 2 * (0.5 - d_wk[spilot]) / 3, 0);
}
void
dvbt_pilot_gen::set_spilot_value(int spilot, gr_complex val)
{
<API key>[spilot] = val;
}
void
dvbt_pilot_gen::set_channel_gain(int spilot, gr_complex val)
{
// Gain gval=rxval/txval
d_channel_gain[spilot] = gr_complex((4 * 2 * (0.5 - d_wk[spilot]) / 3), 0) / val;
}
void
dvbt_pilot_gen::advance_spilot(int sindex)
{
//TODO - do in a simpler way?
int size = <API key>;
if (sindex == 0) {
size = <API key> + 1;
}
// TODO - fix this - what value should we use?
++d_spilot_index;
d_spilot_index = d_spilot_index % size;
}
int
dvbt_pilot_gen::get_first_spilot()
{
d_spilot_index = 0;
return (d_Kmin + 3 * (d_symbol_index % 4));
}
int
dvbt_pilot_gen::get_last_spilot() const
{
int size = <API key> - 1;
if (d_symbol_index == 0) {
size = <API key>;
}
return (d_Kmin + 3 * (d_symbol_index % 4) + 12 * size);
}
int
dvbt_pilot_gen::get_next_spilot()
{
int pilot = (d_Kmin + 3 * (d_symbol_index % 4) + 12 * (++d_spilot_index));
if (pilot > d_Kmax) {
pilot = d_Kmax;
}
return pilot;
}
int
dvbt_pilot_gen::process_spilot_data(const gr_complex * in)
{
// This is channel estimator
// Interpolate the gain between carriers to obtain
// gain for non pilot carriers - we use linear interpolation
// Find out the OFDM symbol index (value 0 to 3) sent
// in current block by correlating scattered symbols with
// current block - result is (symbol index % 4)
float max = 0; float sum = 0;
for (int scount = 0; scount < 4; scount++) {
d_spilot_index = 0; d_cpilot_index = 0;
d_chanestim_index = 0;
for (int k = 0; k < (d_Kmax - d_Kmin + 1); k++) {
// Keep data for channel estimation
if (k == get_current_spilot(scount)) {
<API key>(k);
advance_spilot(scount);
advance_chanestim();
}
}
gr_complex c = gr_complex(0.0, 0.0);
// This should be of range 0 to d_chanestim_index bit for now we use just a
// small number of spilots to obtain the symbol index
for (int j = 0; j < 10; j++) {
c += get_spilot_value(<API key>[j]) * conj(in[d_zeros_on_left + <API key>[j]]);
}
sum = norm(c);
if (sum > max) {
max = sum;
d_mod_symbol_index = scount;
}
}
// Keep data for channel estimator
// This method interpolates scattered measurements across one OFDM symbol
// It does not use measurements from the previous OFDM symbols (does not use history)
// as it may have encountered a phase change for the current phase only
d_spilot_index = 0; d_cpilot_index = 0;
d_chanestim_index = 0;
for (int k = 0; k < (d_Kmax - d_Kmin + 1); k++) {
// Keep data for channel estimation
if (k == get_current_spilot(d_mod_symbol_index)) {
<API key>(k);
advance_spilot(d_mod_symbol_index);
advance_chanestim();
}
// Keep data for channel estimation
if (k == get_current_cpilot()) {
<API key>(k);
advance_cpilot();
advance_chanestim();
}
}
// We use both scattered pilots and continual pilots
for (int i = 0, startk = <API key>[0]; i < d_chanestim_index; i++) {
// Get a carrier from the list of carriers
// used for channel estimation
int k = <API key>[i];
set_channel_gain(k, in[k + d_zeros_on_left]);
// Calculate tg(alpha) due to linear interpolation
gr_complex tg_alpha = (d_channel_gain[k] - d_channel_gain[startk]) / gr_complex(11.0, 0.0);
// Calculate interpolation for all intermediate values
for (int j = 1; j < (k - startk); j++) {
gr_complex current = d_channel_gain[startk] + tg_alpha * gr_complex(j, 0.0);
d_channel_gain[startk + j] = current;
}
startk = k;
}
// Signal that equalizer is ready
d_equalizer_ready = 1;
int diff_sindex = (d_mod_symbol_index - <API key> + 4) % 4;
<API key> = d_mod_symbol_index;
return diff_sindex;
}
/*
* Init continual pilot generator
*/
int
dvbt_pilot_gen::get_current_cpilot() const
{
return d_cpilot_carriers[d_cpilot_index];
}
gr_complex
dvbt_pilot_gen::get_cpilot_value(int cpilot)
{
//TODO - can be calculated at the beginning
return gr_complex((float)(4 * 2 * (0.5 - d_wk[cpilot])) / 3, 0);
}
void
dvbt_pilot_gen::advance_cpilot()
{
++d_cpilot_index;
d_cpilot_index = d_cpilot_index % <API key>;
}
void
dvbt_pilot_gen::process_cpilot_data(const gr_complex * in)
{
// Look for maximum correlation for cpilots
// in order to obtain post FFT integer frequency correction
float max = 0; float sum = 0;
int start = 0;
float phase;
for (int i = d_zeros_on_left - d_freq_offset_max; i < d_zeros_on_left + d_freq_offset_max; i++) {
sum = 0;
for (int j = 0; j < (<API key> - 1); j++) {
phase = norm(in[i + d_cpilot_carriers[j + 1]] - in[i + d_cpilot_carriers[j]]);
sum += d_known_phase_diff[j] * phase;
}
if (sum > max) {
max = sum;
start = i;
}
}
d_freq_offset = start - d_zeros_on_left;
}
void
dvbt_pilot_gen::<API key>(const gr_complex * in)
{
gr_complex left_corr_sum = 0.0; gr_complex right_corr_sum = 0.0;
int half_size = (<API key> - 1) / 2;
// TODO init this in constructor
float carrier_coeff = 1.0 / (2 * M_PI * (1 + float (d_cp_length) / float (d_fft_length)) * 2);
float sampling_coeff = 1.0 / (2 * M_PI * ((1 + float (d_cp_length) / float (d_fft_length)) * ((float)<API key> / 2.0)));
float left_angle, right_angle;
// Compute cpilots correlation between previous symbol and current symbol
// in both halves of the cpilots. The cpilots are distributed evenly
// on left and right sides of the center frequency.
for (int j = 0; j < half_size; j++) {
left_corr_sum += in[d_freq_offset + d_zeros_on_left + d_cpilot_carriers[j]] * \
std::conj(in[d_freq_offset + d_fft_length + d_zeros_on_left + d_cpilot_carriers[j]]);
}
for (int j = half_size + 1; j < <API key>; j++) {
right_corr_sum += in[d_freq_offset + d_zeros_on_left + d_cpilot_carriers[j]] * \
std::conj(in[d_freq_offset + d_fft_length + d_zeros_on_left + d_cpilot_carriers[j]]);
}
left_angle = std::arg(left_corr_sum);
right_angle = std::arg(right_corr_sum);
<API key> = (right_angle + left_angle) * carrier_coeff;
<API key> = (right_angle - left_angle) * sampling_coeff;
}
gr_complex *
dvbt_pilot_gen::<API key>(const gr_complex * in, gr_complex * out)
{
// TODO - use PI control loop to calculate tracking corrections
int symbol_count = 1;
for (int k = 0; k < d_fft_length; k++) {
// TODO - for 2k mode the continuous pilots are not split evenly
// between left/right center frequency. Probably the scattered
// pilots needs to be added.
float correction = (float)d_freq_offset + <API key>;
gr_complex c = gr_expj(-2 * M_PI * correction * \
(d_fft_length + d_cp_length) / d_fft_length * symbol_count);
// TODO - vectorize this operation
out[k] = c * in[k + d_freq_offset];
}
return (out);
}
/*
* Init tps sequence, return values for first position
* If first symbol then init tps DBPSK data
*/
int
dvbt_pilot_gen::get_current_tpilot() const
{
return d_tps_carriers[d_tpilot_index];
}
gr_complex
dvbt_pilot_gen::get_tpilot_value(int tpilot)
{
//TODO - it can be calculated at the beginnning
if (d_symbol_index == 0) {
d_tps_carriers_val[d_tpilot_index] = gr_complex(2 * (0.5 - d_wk[tpilot]), 0);
}
else {
if (d_tps_data[d_symbol_index] == 1) {
d_tps_carriers_val[d_tpilot_index] = gr_complex(-d_tps_carriers_val[d_tpilot_index].real(), 0);
}
}
return d_tps_carriers_val[d_tpilot_index];
}
void
dvbt_pilot_gen::advance_tpilot()
{
++d_tpilot_index;
d_tpilot_index = d_tpilot_index % d_tps_carriers_size;
}
/*
* Set a number of bits to a specified value
*/
void
dvbt_pilot_gen::set_tps_bits(int start, int stop, unsigned int data)
{
for (int i = start; i >= stop; i
d_tps_data[i] = data & 0x1;
data = data >> 1;
}
}
/*
* Clause 4.6
* Format data that will be sent with TPS signals
* en 300 744 - section 4.6.2
* s0 Initialization
* s1-s16 Synchronization word
* s17-s22 Length Indicator
* s23-s24 Frame Number
* S25-s26 Constellation
* s27, s28, s29 Hierarchy information
* s30, s31, s32 Code rate, HP stream
* s33, s34, s35 Code rate, LP stream
* s36, s37 Guard interval
* s38, s39 Transmission mode
* s40, s47 Cell identifier
* s48-s53 All set to "0"
* s54-s67 Error protection (BCH code)
*/
void
dvbt_pilot_gen::format_tps_data()
{
//Clause 4.6.3
set_tps_bits(0, 0, d_wk[0]);
//Clause 4.6.2.2
if (d_frame_index % 2) {
set_tps_bits(16, 1, 0xca11);
}
else {
set_tps_bits(16, 1, 0x35ee);
}
//Clause 4.6.2.3
if (config.d_include_cell_id) {
set_tps_bits(22, 17, 0x1f);
}
else {
set_tps_bits(22, 17, 0x17);
}
//Clause 4.6.2.4
set_tps_bits(24, 23, d_frame_index);
//Clause 4.6.2.5
set_tps_bits(26, 25, config.d_constellation);
//Clause 4.6.2.6
set_tps_bits(29, 27, config.d_hierarchy);
//Clause 4.6.2.7
switch (config.d_code_rate_HP) {
case C1_2:
set_tps_bits(32, 30, 0);
break;
case C2_3:
set_tps_bits(32, 30, 1);
break;
case C3_4:
set_tps_bits(32, 30, 2);
break;
case C5_6:
set_tps_bits(32, 30, 3);
break;
case C7_8:
set_tps_bits(32, 30, 4);
break;
default:
set_tps_bits(32, 30, 0);
break;
}
switch (config.d_code_rate_LP) {
case C1_2:
set_tps_bits(35, 33, 0);
break;
case C2_3:
set_tps_bits(35, 33, 1);
break;
case C3_4:
set_tps_bits(35, 33, 2);
break;
case C5_6:
set_tps_bits(35, 33, 3);
break;
case C7_8:
set_tps_bits(35, 33, 4);
break;
default:
set_tps_bits(35, 33, 0);
break;
}
//Clause 4.6.2.8
set_tps_bits(37, 36, config.d_guard_interval);
//Clause 4.6.2.9
set_tps_bits(39, 38, config.d_transmission_mode);
//Clause 4.6.2.10
set_tps_bits(47, 40, config.d_cell_id);
//These bits are set to zero
set_tps_bits(53, 48, 0);
//Clause 4.6.2.11
generate_bch_code();
}
int
dvbt_pilot_gen::process_tps_data(const gr_complex * in, const int diff_symbol_index)
{
int end_frame = 0;
// Look for TPS data only - demodulate DBPSK
// Calculate phase difference between previous symbol
// and current one to determine the current bit.
// Use majority voting for decision
int tps_majority_zero = 0;
for (int k = 0; k < d_tps_carriers_size; k++) {
// Use equalizer to correct data and frequency correction
gr_complex val = in[d_zeros_on_left + d_tps_carriers[k]] * d_channel_gain[d_tps_carriers[k]];
if (!<API key> || (d_symbol_index != 0)) {
gr_complex phdiff = val * conj(d_prev_tps_symbol[k]);
if (phdiff.real() >= 0.0) {
tps_majority_zero++;
}
else {
tps_majority_zero
}
}
d_prev_tps_symbol[k] = val;
}
// Insert obtained TPS bit into FIFO
// Insert the same bit into FIFO in the case
// diff_symbol_index is more than one. This will happen
// in the case of losing 1 to 3 symbols.
// This could be corrected by BCH decoder afterwards.
for (int i = 0; i < diff_symbol_index; i++) {
// Take out the front entry first
d_rcv_tps_data.pop_front();
// Add data at tail
if (!<API key> || (d_symbol_index != 0)) {
if (tps_majority_zero >= 0) {
d_rcv_tps_data.push_back(0);
}
else {
d_rcv_tps_data.push_back(1);
}
}
else {
d_rcv_tps_data.push_back(0);
}
}
// Match synchronization signatures
if (std::equal(d_rcv_tps_data.begin() + 1, d_rcv_tps_data.begin() + d_tps_sync_evenv.size(), d_tps_sync_evenv.begin())) {
// Verify parity for TPS data
if (!verify_bch_code(d_rcv_tps_data)) {
d_frame_index = (d_rcv_tps_data[23] << 1) | (d_rcv_tps_data[24]);
<API key> = 1;
end_frame = 1;
}
else {
<API key> = 0;
end_frame = 0;
}
// Clear up FIFO
for (int i = 0; i < d_symbols_per_frame; i++) {
d_rcv_tps_data[i] = 0;
}
}
else if (std::equal(d_rcv_tps_data.begin() + 1, d_rcv_tps_data.begin() + d_tps_sync_oddv.size(), d_tps_sync_oddv.begin())) {
// Verify parity for TPS data
if (!verify_bch_code(d_rcv_tps_data)) {
d_frame_index = (d_rcv_tps_data[23] << 1) | (d_rcv_tps_data[24]);
<API key> = 1;
end_frame = 1;
}
else {
<API key> = 0;
end_frame = 0;
}
// Clear up FIFO
for (int i = 0; i < d_symbols_per_frame; i++) {
d_rcv_tps_data[i] = 0;
}
}
return end_frame;
}
void
dvbt_pilot_gen::<API key>(int k)
{
<API key>[d_chanestim_index] = k;
}
void
dvbt_pilot_gen::advance_chanestim()
{
d_chanestim_index++;
}
int
dvbt_pilot_gen::get_current_payload()
{
return d_payload_carriers[d_payload_index];
}
void
dvbt_pilot_gen::set_payload_carrier(int k)
{
d_payload_carriers[d_payload_index] = k;
}
void
dvbt_pilot_gen::advance_payload()
{
d_payload_index++;
}
void
dvbt_pilot_gen::<API key>(const gr_complex *in, gr_complex *out)
{
//reset indexes
d_spilot_index = 0; d_cpilot_index = 0; d_tpilot_index = 0;
d_payload_index = 0;d_chanestim_index = 0;
int is_payload = 1;
//process one block - one symbol
for (int k = 0; k < (d_Kmax - d_Kmin + 1); k++) {
is_payload = 1;
// Keep data for channel estimation
// This depends on the symbol index
if (k == get_current_spilot(d_mod_symbol_index)) {
advance_spilot(d_mod_symbol_index);
is_payload = 0;
}
// Keep data for frequency correction
// and channel estimation
if (k == get_current_cpilot()) {
advance_cpilot();
is_payload = 0;
}
if (k == get_current_tpilot()) {
advance_tpilot();
is_payload = 0;
}
// Keep payload carrier number
// This depends on the symbol index
if (is_payload) {
set_payload_carrier(k);
advance_payload();
}
}
if (d_equalizer_ready) {
// Equalize payload data according to channel estimator
for (int i = 0; i < d_payload_index; i++) {
out[i] = in[d_zeros_on_left + d_payload_carriers[i]] * d_channel_gain[d_payload_carriers[i]];
}
}
else {
// If equ not ready, return 0
for (int i = 0; i < d_payload_length; i++) {
out[0] = gr_complex(0.0, 0.0);
}
}
}
void
dvbt_pilot_gen::update_output(const gr_complex *in, gr_complex *out)
{
int is_payload = 1;
int payload_count = 0;
//move to the next symbol
//re-genereate TPS data
format_tps_data();
//reset indexes
payload_count = 0;
d_spilot_index = 0; d_cpilot_index = 0; d_tpilot_index = 0;
for (int i = 0; i < d_zeros_on_left; i++) {
out[i] = gr_complex(0.0, 0.0);
}
//process one block - one symbol
for (int k = d_Kmin; k < (d_Kmax - d_Kmin + 1); k++) {
is_payload = 1;
if (k == get_current_spilot(d_symbol_index)) {
out[d_zeros_on_left + k] = get_spilot_value(k);
advance_spilot(d_symbol_index);
is_payload = 0;
}
if (k == get_current_cpilot()) {
out[d_zeros_on_left + k] = get_cpilot_value(k);
advance_cpilot();
is_payload = 0;
}
if (k == get_current_tpilot()) {
out[d_zeros_on_left + k] = get_tpilot_value(k);
advance_tpilot();
is_payload = 0;
}
if (is_payload == 1) {
out[d_zeros_on_left + k] = in[payload_count++];
}
}
// update indexes
if (++d_symbol_index == d_symbols_per_frame) {
d_symbol_index = 0;
if (++d_frame_index == <API key>) {
d_frame_index = 0;
d_superframe_index++;
}
}
for (int i = (d_fft_length - d_zeros_on_right); i < d_fft_length; i++) {
out[i] = gr_complex(0.0, 0.0);
}
}
int
dvbt_pilot_gen::parse_input(const gr_complex *in, gr_complex *out, int * symbol_index, int * frame_index)
{
d_trigger_index++;
// Obtain frequency correction based on cpilots.
// Obtain channel estimation based on both
// cpilots and spilots.
// We use spilot correlation for finding the symbol index modulo 4
// The diff between previous sym index and current index is used
// to advance the symbol index inside a frame (0 to 67)
// Then based on the TPS data we find out the start of a frame
// Process cpilot data
// This is post FFT integer frequency offset estimation
// This is called before all other processing
process_cpilot_data(in);
// Compute one shot Post-FFT Carrier and Sampling Frequency Tracking
// Obtain fractional Carrer and Sampling frequency corrections
// Before this moment it is assumed to have corrected this:
// - symbol timing (pre-FFT)
// - symbol frequency correction (pre-FFT)
// - integer frequency correction (post-FFT)
// TODO - call this just in the aquisition mode
<API key>(in);
// Gather all corrections and obtain a corrected OFDM symbol:
// - input symbol shift (post-FFT)
// - integer frequency correction (post-FFT)
// - fractional frequency (carrier and sampling) corrections (post-FFT)
// TODO - use PI to update the corrections
<API key>(in, d_derot_in);
// Process spilot data
// This is channel estimation function
int diff_symbol_index = process_spilot_data(d_derot_in);
// Correct symbol index so that all subsequent processing
// use correct symbol index
d_symbol_index = (d_symbol_index + diff_symbol_index) % d_symbols_per_frame;
// Symbol index is used in other modules too
*symbol_index = d_symbol_index;
// Frame index is used in other modules too
*frame_index = d_frame_index;
// Process TPS data
// If a frame is recognized then signal end of frame
int frame_end = process_tps_data(d_derot_in, diff_symbol_index);
// We are just at the end of a frame
if (frame_end) {
d_symbol_index = d_symbols_per_frame - 1;
}
// Process payload data with correct symbol index
<API key>(d_derot_in, out);
// noutput_items should be 1 in this case
return 1;
}
<API key>::sptr
<API key>::make(int itemsize, int ninput, int noutput, \
dvb_constellation_t constellation, dvbt_hierarchy_t hierarchy, \
dvb_code_rate_t code_rate_HP, dvb_code_rate_t code_rate_LP, \
dvb_guardinterval_t guard_interval, <API key> transmission_mode, \
int include_cell_id, int cell_id)
{
return gnuradio::get_initial_sptr
(new <API key>(itemsize, ninput, \
noutput, constellation, hierarchy, code_rate_HP, code_rate_LP, \
guard_interval, transmission_mode, include_cell_id, cell_id));
}
/*
* The private constructor
*/
<API key>::<API key>(int itemsize, int ninput, int noutput, \
dvb_constellation_t constellation, dvbt_hierarchy_t hierarchy, dvb_code_rate_t code_rate_HP,\
dvb_code_rate_t code_rate_LP, dvb_guardinterval_t guard_interval,\
<API key> transmission_mode, int include_cell_id, int cell_id)
: block("<API key>",
io_signature::make(1, 1, itemsize * ninput),
io_signature::make(1, 1, itemsize * noutput)),
config(constellation, hierarchy, code_rate_HP, code_rate_LP, \
guard_interval, transmission_mode, include_cell_id, cell_id),
d_pg(config)
{
d_ninput = ninput;
d_noutput = noutput;
}
/*
* Our virtual destructor.
*/
<API key>::~<API key>()
{
}
void
<API key>::forecast (int noutput_items, gr_vector_int &<API key>)
{
<API key>[0] = noutput_items;
}
int
<API key>::general_work (int noutput_items,
gr_vector_int &ninput_items,
<API key> &input_items,
gr_vector_void_star &output_items)
{
const gr_complex *in = (const gr_complex *) input_items[0];
gr_complex *out = (gr_complex *) output_items[0];
for (int i = 0; i < noutput_items; i++) {
d_pg.update_output(&in[i * d_ninput], &out[i * d_noutput]);
}
// Tell runtime system how many input items we consumed on
// each input stream.
consume_each (noutput_items);
// Tell runtime system how many output items we produced.
return noutput_items;
}
} /* namespace dtv */
} /* namespace gr */
|
YUI.add('anim-scroll', function (Y, NAME) {
/**
* Adds support for the <code>scroll</code> property in <code>to</code>
* and <code>from</code> attributes.
* @module anim
* @submodule anim-scroll
*/
var NUM = Number;
//TODO: deprecate for scrollTop/Left properties?
Y.Anim.behaviors.scroll = {
set: function(anim, att, from, to, elapsed, duration, fn) {
var
node = anim._node,
val = ([
fn(elapsed, NUM(from[0]), NUM(to[0]) - NUM(from[0]), duration),
fn(elapsed, NUM(from[1]), NUM(to[1]) - NUM(from[1]), duration)
]);
if (val[0]) {
node.set('scrollLeft', val[0]);
}
if (val[1]) {
node.set('scrollTop', val[1]);
}
},
get: function(anim) {
var node = anim._node;
return [node.get('scrollLeft'), node.get('scrollTop')];
}
};
}, '3.8.0', {"requires": ["anim-base"]});
|
/**
* Check if Bind method exists in current enviroment. If not, it creates an implementation of
* this useful method.
*/
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP
? this
: oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
/**
* @namespace for Spacebrew library
*/
var Spacebrew = Spacebrew || {};
/**
* create placeholder var for WebSocket object, if it does not already exist
*/
var WebSocket = WebSocket || {};
/**
* Check if Running in Browser or Server (Node) Environment *
*/
// check if window object already exists to determine if running browswer
var window = window || undefined;
// check if module object already exists to determine if this is a node application
var module = module || undefined;
// if app is running in a browser, then define the getQueryString method
if (window) {
if (!window['getQueryString']){
/**
* Get parameters from a query string
* @param {String} name Name of query string to parse (w/o '?' or '&')
* @return {String} value of parameter (or empty string if not found)
*/
window.getQueryString = function( name ) {
if (!window.location) return;
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null ) return "";
else return results[1];
}
}
}
// if app is running in a node server environment then package Spacebrew library as a module.
// WebSocket module (ws) needs to be saved in a node_modules so that it can be imported.
if (!window && module) {
WebSocket = require("ws");
module.exports = {
Spacebrew: Spacebrew
}
}
/**
* Define the Spacebrew Library *
*/
/**
* Spacebrew client!
* @constructor
* @param {String} server (Optional) Base address of Spacebrew server. This server address is overwritten if server defined in query string; defaults to localhost.
* @param {String} name (Optional) Base name of app. Base name is overwritten if "name" is defined in query string; defaults to window.location.href.
* @param {String} description (Optional) Base description of app. Description name is overwritten if "description" is defined in query string;
* @param {Object} options (Optional) An object that holds the optional parameters described below
* port (Optional) Port number for the Spacebrew server
* admin (Optional) Flag that identifies when app should register for admin privileges with server
* debug (Optional) Debug flag that turns on info and debug messaging (limited use)
*/
Spacebrew.Client = function( server, name, description, options ){
var options = options || {};
// check if the server variable is an object that holds all config values
if (server != undefined) {
if (toString.call(server) !== '[object String]') {
options.port = server.port || undefined;
options.debug = server.debug || false;
options.reconnect = server.reconnect || false;
description = server.description || undefined;
name = server.name || undefined;
server = server.server || undefined;
}
}
this.debug = (window.getQueryString('debug') === "true" ? true : (options.debug || false));
this.reconnect = options.reconnect || true;
this.reconnect_timer = undefined;
this.send_interval = 16;
this.send_blocked = false;
this.msg = {};
/**
* Name of app
* @type {String}
*/
this._name = name || "javascript client
if (window) {
this._name = (window.getQueryString('name') !== "" ? unescape(window.getQueryString('name')) : this._name);
}
/**
* Description of your app
* @type {String}
*/
this._description = description || "spacebrew javascript client";
if (window) {
this._description = (window.getQueryString('description') !== "" ? unescape(window.getQueryString('description')) : this._description);
}
/**
* Spacebrew server to which the app will connect
* @type {String}
*/
this.server = server || "sandbox.spacebrew.cc";
if (window) {
this.server = (window.getQueryString('server') !== "" ? unescape(window.getQueryString('server')) : this.server);
}
/**
* Port number on which Spacebrew server is running
* @type {Integer}
*/
this.port = options.port || 9000;
if (window) {
port = window.getQueryString('port');
if (port !== "" && !isNaN(port)) {
this.port = port;
}
}
/**
* Reference to WebSocket
* @type {WebSocket}
*/
this.socket = null;
/**
* Configuration file for Spacebrew
* @type {Object}
*/
this.client_config = {
name: this._name,
description: this._description,
publish:{
messages:[]
},
subscribe:{
messages:[]
},
options:{}
};
this.admin = {}
/**
* Are we connected to a Spacebrew server?
* @type {Boolean}
*/
this._isConnected = false;
}
/**
* Connect to Spacebrew
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype.connect = function(){
try {
this.socket = new WebSocket("ws://" + this.server + ":" + this.port);
this.socket.onopen = this._onOpen.bind(this);
this.socket.onmessage = this._onMessage.bind(this);
this.socket.onclose = this._onClose.bind(this);
} catch(e){
this._isConnected = false;
console.log("[connect:Spacebrew] connection attempt failed")
}
}
/**
* Close Spacebrew connection
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype.close = function(){
try {
if (this._isConnected) {
this.socket.close();
this._isConnected = false;
console.log("[close:Spacebrew] closing websocket connection")
}
} catch (e) {
this._isConnected = false;
}
}
/**
* Override in your app to receive on open event for connection
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onOpen = function( name, value ){}
/**
* Override in your app to receive on close event for connection
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onClose = function( name, value ){}
/**
* Override in your app to receive "range" messages, e.g. sb.onRangeMessage = yourRangeFunction
* @param {String} name Name of incoming route
* @param {String} value [description]
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onRangeMessage = function( name, value ){}
/**
* Override in your app to receive "boolean" messages, e.g. sb.onBooleanMessage = yourBoolFunction
* @param {String} name Name of incoming route
* @param {String} value [description]
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onBooleanMessage = function( name, value ){}
/**
* Override in your app to receive "string" messages, e.g. sb.onStringMessage = yourStringFunction
* @param {String} name Name of incoming route
* @param {String} value [description]
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onStringMessage = function( name, value ){}
/**
* Override in your app to receive "custom" messages, e.g. sb.onCustomMessage = yourStringFunction
* @param {String} name Name of incoming route
* @param {String} value [description]
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onCustomMessage = function( name, value, type ){}
/**
* Add a route you are publishing on
* @param {String} name Name of incoming route
* @param {String} type "boolean", "range", or "string"
* @param {String} def default value
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.addPublish = function( name, type, def ){
this.client_config.publish.messages.push({"name":name, "type":type, "default":def});
this.updatePubSub();
}
/**
* [addSubscriber description]
* @param {String} name Name of outgoing route
* @param {String} type "boolean", "range", or "string"
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.addSubscribe = function( name, type ){
this.client_config.subscribe.messages.push({"name":name, "type":type });
this.updatePubSub();
}
/**
* Update publishers and subscribers
* @memberOf Spacebrew.Client
* @private
*/
Spacebrew.Client.prototype.updatePubSub = function(){
if (this._isConnected) {
this.socket.send(JSON.stringify({"config": this.client_config}));
}
}
/**
* Send a route to Spacebrew
* @param {String} name Name of outgoing route (must match something in addPublish)
* @param {String} type "boolean", "range", or "string"
* @param {String} value Value to send
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.send = function( name, type, value ){
var self = this;
this.msg = {
"message": {
"clientName":this._name,
"name": name,
"type": type,
"value": value
}
}
// if send block is not active then send message
if (!this.send_blocked) {
this.socket.send(JSON.stringify(this.msg));
this.send_blocked = true;
this.msg = undefined;
// set the timer to unblock message sending
setTimeout(function() {
self.send_blocked = false; // remove send block
if (self.msg != undefined) { // if message exists then sent it
self.send(self.msg.message.name, self.msg.message.type, self.msg.message.value);
}
}, self.send_interval);
}
}
/**
* Called on WebSocket open
* @private
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype._onOpen = function() {
console.log("[_onOpen:Spacebrew] Spacebrew connection opened, client name is: " + this._name);
this._isConnected = true;
if (this.admin.active) this.connectAdmin();
// if reconnect functionality is activated then clear interval timer when connection succeeds
if (this.reconnect_timer) {
console.log("[_onOpen:Spacebrew] tearing down reconnect timer")
this.reconnect_timer = clearInterval(this.reconnect_timer);
this.reconnect_timer = undefined;
}
// send my config
this.updatePubSub();
this.onOpen();
}
/**
* Called on WebSocket message
* @private
* @param {Object} e
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype._onMessage = function( e ){
var data = JSON.parse(e.data)
, name
, type
, value
;
// handle client messages
if (data["message"]) {
// check to make sure that this is not an admin message
if (!data.message["clientName"]) {
name = data.message.name;
type = data.message.type;
value = data.message.value;
switch( type ){
case "boolean":
this.onBooleanMessage( name, value == "true" );
break;
case "string":
this.onStringMessage( name, value );
break;
case "range":
this.onRangeMessage( name, Number(value) );
break;
default:
this.onCustomMessage( name, value, type );
}
}
}
// handle admin messages
else {
if (this.admin.active) {
this.<API key>( data );
}
}
}
/**
* Called on WebSocket close
* @private
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype._onClose = function() {
var self = this;
console.log("[_onClose:Spacebrew] Spacebrew connection closed");
this._isConnected = false;
if (this.admin.active) this.admin.remoteAddress = undefined;
// if reconnect functionality is activated set interval timer if connection dies
if (this.reconnect && !this.reconnect_timer) {
console.log("[_onClose:Spacebrew] setting up reconnect timer");
this.reconnect_timer = setInterval(function () {
if (self.isConnected != false) {
self.connect();
console.log("[reconnect:Spacebrew] attempting to reconnect to spacebrew");
}
}, 5000);
}
this.onClose();
};
/**
* name Method that sets or gets the spacebrew app name. If parameter is provided then it sets the name, otherwise
* it just returns the current app name.
* @param {String} newName New name of the spacebrew app
* @return {String} Returns the name of the spacebrew app if called as a getter function. If called as a
* setter function it will return false if the method is called after connecting to spacebrew,
* because the name must be configured before connection is made.
*/
Spacebrew.Client.prototype.name = function (newName){
if (newName) { // if a name has been passed in then update it
if (this._isConnected) return false; // if already connected we can't update name
this._name = newName;
if (window) {
this._name = (window.getQueryString('name') !== "" ? unescape(window.getQueryString('name')) : this._name);
}
this.client_config.name = this._name; // update spacebrew config file
}
return this._name;
};
/**
* name Method that sets or gets the spacebrew app description. If parameter is provided then it sets the description,
* otherwise it just returns the current app description.
* @param {String} newDesc New description of the spacebrew app
* @return {String} Returns the description of the spacebrew app if called as a getter function. If called as a
* setter function it will return false if the method is called after connecting to spacebrew,
* because the description must be configured before connection is made.
*/
Spacebrew.Client.prototype.description = function (newDesc){
if (newDesc) { // if a description has been passed in then update it
if (this._isConnected) return false; // if already connected we can't update description
this._description = newDesc || "spacebrew javascript client";
if (window) {
this._description = (window.getQueryString('description') !== "" ? unescape(window.getQueryString('description')) : this._description);
}
this.client_config.description = this._description; // update spacebrew config file
}
return this._description;
};
/**
* isConnected Method that returns current connection state of the spacebrew client.
* @return {Boolean} Returns true if currently connected to Spacebrew
*/
Spacebrew.Client.prototype.isConnected = function (){
return this._isConnected;
};
Spacebrew.Client.prototype.extend = function ( mixin ) {
for (var prop in mixin) {
if (mixin.hasOwnProperty(prop)) {
this[prop] = mixin[prop];
}
}
};
|
#!/bin/bash
# Numenta Platform for Intelligent Computing (NuPIC)
# following terms and conditions apply:
# This program is free software: you can redistribute it and/or modify
# published by the Free Software Foundation.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
echo
echo Running before_install-osx.sh...
echo
# Get Darwin64 libs for OSX
echo ">>> Cloning nupic-darwin64 at <SHA1-like>..."
git clone https://github.com/numenta/nupic-darwin64.git
(cd nupic-darwin64 && git reset --hard <SHA1-like>) || exit
echo ">>> Activating nupic-darwin64..."
source nupic-darwin64/bin/activate
# Install and start MySQL on OSX
echo ">>> brew install mysql"
brew install mysql
echo ">>> mysql.server start"
mysql.server start
|
#ifndef _NTLM_AUTH_PROTO_H_
#define _NTLM_AUTH_PROTO_H_
/* The following definitions come from utils/ntlm_auth.c */
const char *get_winbind_domain(void);
const char *<API key>(void);
DATA_BLOB get_challenge(void) ;
NTSTATUS <API key>(const char *username,
const char *domain,
const char *workstation,
const DATA_BLOB *challenge,
const DATA_BLOB *lm_response,
const DATA_BLOB *nt_response,
uint32_t flags,
uint32_t <API key>,
uint8_t lm_key[8],
uint8_t user_session_key[16],
uint8_t *pauthoritative,
char **error_string,
char **unix_name);
/* The following definitions come from utils/<API key>.c */
bool diagnose_ntlm_auth(void);
int <API key>(void);
#endif /* _NTLM_AUTH_PROTO_H_ */
|
// This file is part of the ClearCanvas RIS/PACS open source project.
// The ClearCanvas RIS/PACS open source project is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// The ClearCanvas RIS/PACS open source project is distributed in the hope that it
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// the ClearCanvas RIS/PACS open source project. If not, see
#endregion
using System;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using ClearCanvas.Common;
using ClearCanvas.Dicom.Utilities.Xml;
namespace ClearCanvas.Dicom.Samples
{
public class EditSop
{
private readonly string _sourceFilename;
private DicomFile _dicomFile;
public EditSop(string file)
{
_sourceFilename = file;
}
public DicomFile DicomFile
{
get { return _dicomFile; }
}
public void Load()
{
_dicomFile = new DicomFile(_sourceFilename);
try
{
_dicomFile.Load();
}
catch (Exception e)
{
Platform.Log(LogLevel.Error, e, "Unexpected exception loading DICOM file: {0}", _sourceFilename);
}
}
public string <API key>()
{
var theDoc = GetXmlDoc();
var xmlSettings = new XmlWriterSettings
{
Encoding = Encoding.UTF8,
ConformanceLevel = ConformanceLevel.Document,
Indent = true,
NewLineOnAttributes = false,
CheckCharacters = true,
IndentChars = " "
};
StringBuilder sb = new StringBuilder();
XmlWriter tw = XmlWriter.Create(sb, xmlSettings);
theDoc.WriteTo(tw);
tw.Flush();
tw.Close();
return sb.ToString();
}
private XmlDocument GetXmlDoc()
{
var theDocument = new XmlDocument();
XmlElement instance = theDocument.CreateElement("Instance");
XmlAttribute sopInstanceUid = theDocument.CreateAttribute("UID");
sopInstanceUid.Value = _dicomFile.<API key>;
instance.Attributes.Append(sopInstanceUid);
XmlAttribute sopClassAttribute = theDocument.CreateAttribute("SopClassUID");
sopClassAttribute.Value = _dicomFile.SopClass.Uid;
instance.Attributes.Append(sopClassAttribute);
theDocument.AppendChild(instance);
foreach (DicomAttribute attribute in _dicomFile.DataSet)
{
XmlElement instanceElement = <API key>(theDocument, attribute.Tag, "Attribute");
if (attribute is DicomAttributeSQ || attribute is DicomAttributeOW || attribute is DicomAttributeUN ||
attribute is DicomAttributeOF || attribute is DicomAttributeOB)
{
continue;
}
instanceElement.InnerText = XmlEscapeString(attribute);
instance.AppendChild(instanceElement);
}
return theDocument;
}
private static XmlElement <API key>(XmlDocument document, DicomTag dicomTag, string name)
{
XmlElement <API key> = document.CreateElement(name);
XmlAttribute tag = document.CreateAttribute("Tag");
tag.Value = "$" + dicomTag.VariableName;
XmlAttribute vr = document.CreateAttribute("VR");
vr.Value = dicomTag.VR.ToString();
<API key>.Attributes.Append(tag);
<API key>.Attributes.Append(vr);
return <API key>;
}
private static string XmlEscapeString(string input)
{
string result = input ?? string.Empty;
result = SecurityElement.Escape(result);
// Do the regular expression to escape out other invalid XML characters in the string not caught by the above.
// NOTE: the \x sequences you see below are C# escapes, not Regex escapes
result = Regex.Replace(result, "[^\x9\xA\xD\x20-\xFFFD]", m => string.Format("&#x{0:X};", (int)m.Value[0]));
return result;
}
public void UpdateTags(string xml)
{
var theDoc = new XmlDocument();
try
{
theDoc.LoadXml(xml);
var instanceXml = new InstanceXml(theDoc.DocumentElement, null);
<API key> queryMessage = instanceXml.Collection;
if (queryMessage == null)
{
Platform.Log(LogLevel.Error, "Unexpected error parsing move message");
return;
}
foreach (var attribute in queryMessage)
{
_dicomFile.DataSet[attribute.Tag] = attribute.Copy();
}
}
catch (Exception x)
{
Platform.Log(LogLevel.Error, x, "Unable to perform update");
}
}
public void Save(string filename)
{
try
{
_dicomFile.Save(filename);
}
catch (Exception e)
{
Platform.Log(LogLevel.Error, e, "Unexpected exception saving dicom file: {0}", filename);
}
}
}
}
|
<!DOCTYPE html>
<html>
<title>Service Workers: ServiceWorker</title>
<head>
<link rel="help" href="https://w3c.github.io/ServiceWorker/#service-worker-obj">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src=/resources/WebIDLParser.js></script>
<script src=/resources/idlharness.js></script>
</head>
<body>
<script type=text/plain id="idl_0">
[Constructor()] // no-op constructor
interface ServiceWorker : Worker {
readonly attribute DOMString scope;
readonly attribute DOMString url;
readonly attribute ServiceWorkerState state;
// event
attribute EventHandler onstatechange;
};
enum ServiceWorkerState {
"installing",
"installed",
"activating",
"activated",
"redundant"
};
</pre>
<!
The `ServiceWorker` interface represents the document-side view of a Service
Worker. This object provides a no-op constructor. Callers should note that only
`ServiceWorker` objects created by the user agent (see
`navigator.serviceWorker.installing`, `navigator.serviceWorker.waiting`,
`navigator.serviceWorker.active` and `navigator.serviceWorker.controller`) will
provide meaningful functionality.
<script type=text/plain id="untested_idls">
interface EventHandler {};
interface Worker {};
</pre>
<script>
var idl_array = new IdlArray();
idl_array.add_untested_idls(document.getElementById("untested_idls").textContent);
idl_array.add_idls(document.getElementById("idl_0").textContent);
idl_array.add_objects({
ServiceWorker: ["throw new Error ('No object defined for the ServiceWorker interface')"],
ServiceWorkerState: ["throw new Error ('No object defined for the ServiceWorkerState enum')"]
});
idl_array.test();
</script>
</body>
</html>
|
// This file is part of the go-ethereum library.
// The go-ethereum library is free software: you can redistribute it and/or modify
// (at your option) any later version.
// The go-ethereum library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
package netutil
import "net"
// AddrIP gets the IP address contained in addr. It returns nil if no address is present.
func AddrIP(addr net.Addr) net.IP {
switch a := addr.(type) {
case *net.IPAddr:
return a.IP
case *net.TCPAddr:
return a.IP
case *net.UDPAddr:
return a.IP
default:
return nil
}
}
|
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
$module_name = 'lm_FaxMan';
$_module_name = 'lm_faxman';
$searchFields['lm_FaxMan'] =
array (
'document_name' => array( 'query_type'=>'default'),
'category_id'=> array('query_type'=>'default', 'options' => '<API key>', 'template_var' => 'CATEGORY_OPTIONS'),
'subcategory_id'=> array('query_type'=>'default', 'options' => '<API key>', 'template_var' => 'SUBCATEGORY_OPTIONS'),
'active_date'=> array('query_type'=>'default'),
'exp_date'=> array('query_type'=>'default'),
//Range Search Support
'range_date_entered' => array ('query_type' => 'default', 'enable_range_search' => true, 'is_date_field' => true),
'<API key>' => array ('query_type' => 'default', 'enable_range_search' => true, 'is_date_field' => true),
'<API key>' => array ('query_type' => 'default', 'enable_range_search' => true, 'is_date_field' => true),
'range_date_modified' => array ('query_type' => 'default', 'enable_range_search' => true, 'is_date_field' => true),
'<API key>' => array ('query_type' => 'default', 'enable_range_search' => true, 'is_date_field' => true),
'<API key>' => array ('query_type' => 'default', 'enable_range_search' => true, 'is_date_field' => true),
//Range Search Support
);
?>
|
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
function <API key>($fields) {
static $mod_strings;
if(empty($mod_strings)) {
global $current_language;
$mod_strings = <API key>($current_language, 'Meetings');
}
$overlib_string = '';
//Modify by jchi 6/27/2008 1515pm china time , bug 20626.
if(!empty($fields['DATE_START']))
$overlib_string .= '<b>'. $mod_strings['LBL_DATE_TIME'] . '</b> ' . $fields['DATE_START'] . ' <br>';
if(isset($fields['DURATION_HOURS']) || isset($fields['DURATION_MINUTES'])) {
$overlib_string .= '<b>'. $mod_strings['LBL_DURATION'] . '</b> ';
if(isset($fields['DURATION_HOURS'])) {
$overlib_string .= $fields['DURATION_HOURS'] . $mod_strings['LBL_HOURS_ABBREV'] . ' ';
}
if(isset($fields['DURATION_MINUTES'])) {
$overlib_string .= $fields['DURATION_MINUTES'] . $mod_strings['LBL_MINSS_ABBREV'];
}
$overlib_string .= '<br>';
}
if (!empty($fields['PARENT_ID']))
{
$overlib_string .= "<b>". $mod_strings['LBL_RELATED_TO'] . "</b> ".
"<a href='index.php?module=".$fields['PARENT_TYPE']."&action=DetailView&record=".$fields['PARENT_ID']."'>".
$fields['PARENT_NAME'] . "</a>";
$overlib_string .= '<br>';
}
if(!empty($fields['DESCRIPTION'])) {
$overlib_string .= '<b>'. $mod_strings['LBL_DESCRIPTION'] . '</b> ' . substr($fields['DESCRIPTION'], 0, 300);
if(strlen($fields['DESCRIPTION']) > 300) $overlib_string .= '...';
$overlib_string .= '<br>';
}
$editLink = "index.php?action=EditView&module=Meetings&record={$fields['ID']}";
$viewLink = "index.php?action=DetailView&module=Meetings&record={$fields['ID']}";
return array('fieldToAddTo' => 'NAME',
'string' => $overlib_string,
'editLink' => $editLink,
'viewLink' => $viewLink);
}
?>
|
# Contributor Code of Conduct
As contributors and maintainers of this project, and in the interest of
fostering an open and welcoming community, we pledge to respect all people who
contribute through reporting issues, posting feature requests, updating
documentation, submitting pull requests or patches, and other activities.
We are committed to making participation in this project a harassment-free
experience for everyone, regardless of level of experience, gender, gender
identity and expression, sexual orientation, disability, personal appearance,
body size, race, ethnicity, age, religion, or nationality.
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery
* Personal attacks
* Trolling or insulting/derogatory comments
* Public or private harassment
* Publishing other's private information, such as physical or electronic
addresses, without explicit permission
* Other unethical or unprofessional conduct
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
By adopting this Code of Conduct, project maintainers commit themselves to
fairly and consistently applying these principles to every aspect of managing
this project. Project maintainers who do not follow or enforce the Code of
Conduct may be permanently removed from the project team.
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community.
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting a project maintainer at <kytrinyx@exercism.io>. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. Maintainers are
obligated to maintain confidentiality with regard to the reporter of an
incident.
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 1.3.0, available at
[http://<API key>.org/version/1/3/0/][version]
[homepage]: http://<API key>.org
[version]: http://<API key>.org/version/1/3/0/
|
#include <errno.h>
#include <stdio.h>
#define lib_io_c
#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include "lj_obj.h"
#include "lj_gc.h"
#include "lj_err.h"
#include "lj_str.h"
#include "lj_state.h"
#include "lj_ff.h"
#include "lj_lib.h"
/* Userdata payload for I/O file. */
typedef struct IOFileUD {
FILE *fp; /* File handle. */
uint32_t type; /* File type. */
} IOFileUD;
#define IOFILE_TYPE_FILE 0 /* Regular file. */
#define IOFILE_TYPE_PIPE 1 /* Pipe. */
#define IOFILE_TYPE_STDF 2 /* Standard file handle. */
#define IOFILE_TYPE_MASK 3
#define IOFILE_FLAG_CLOSE 4 /* Close after io.lines() iterator. */
#define IOSTDF_UD(L, id) (&gcref(G(L)->gcroot[(id)])->ud)
#define IOSTDF_IOF(L, id) ((IOFileUD *)uddata(IOSTDF_UD(L, (id))))
static IOFileUD *io_tofilep(lua_State *L)
{
if (!(L->base < L->top && tvisudata(L->base) &&
udataV(L->base)->udtype == UDTYPE_IO_FILE))
lj_err_argtype(L, 1, "FILE*");
return (IOFileUD *)uddata(udataV(L->base));
}
static IOFileUD *io_tofile(lua_State *L)
{
IOFileUD *iof = io_tofilep(L);
if (iof->fp == NULL)
lj_err_caller(L, LJ_ERR_IOCLFL);
return iof;
}
static FILE *io_stdfile(lua_State *L, ptrdiff_t id)
{
IOFileUD *iof = IOSTDF_IOF(L, id);
if (iof->fp == NULL)
lj_err_caller(L, LJ_ERR_IOSTDCL);
return iof->fp;
}
static IOFileUD *io_file_new(lua_State *L)
{
IOFileUD *iof = (IOFileUD *)lua_newuserdata(L, sizeof(IOFileUD));
GCudata *ud = udataV(L->top-1);
ud->udtype = UDTYPE_IO_FILE;
/* NOBARRIER: The GCudata is new (marked white). */
setgcrefr(ud->metatable, curr_func(L)->c.env);
iof->fp = NULL;
iof->type = IOFILE_TYPE_FILE;
return iof;
}
static IOFileUD *io_file_open(lua_State *L, const char *mode)
{
const char *fname = strdata(lj_lib_checkstr(L, 1));
IOFileUD *iof = io_file_new(L);
iof->fp = fopen(fname, mode);
if (iof->fp == NULL)
luaL_argerror(L, 1, lj_str_pushf(L, "%s: %s", fname, strerror(errno)));
return iof;
}
static int io_file_close(lua_State *L, IOFileUD *iof)
{
int ok;
if ((iof->type & IOFILE_TYPE_MASK) == IOFILE_TYPE_FILE) {
ok = (fclose(iof->fp) == 0);
} else if ((iof->type & IOFILE_TYPE_MASK) == IOFILE_TYPE_PIPE) {
int stat = -1;
#if LJ_TARGET_POSIX
stat = pclose(iof->fp);
#elif LJ_TARGET_WINDOWS
stat = _pclose(iof->fp);
#else
lua_assert(0);
return 0;
#endif
#if LJ_52
iof->fp = NULL;
return luaL_execresult(L, stat);
#else
ok = (stat != -1);
#endif
} else {
lua_assert((iof->type & IOFILE_TYPE_MASK) == IOFILE_TYPE_STDF);
setnilV(L->top++);
lua_pushliteral(L, "cannot close standard file");
return 2;
}
iof->fp = NULL;
return luaL_fileresult(L, ok, NULL);
}
static int io_file_readnum(lua_State *L, FILE *fp)
{
lua_Number d;
if (fscanf(fp, LUA_NUMBER_SCAN, &d) == 1) {
if (LJ_DUALNUM) {
int32_t i = lj_num2int(d);
if (d == (lua_Number)i && !tvismzero((cTValue *)&d)) {
setintV(L->top++, i);
return 1;
}
}
setnumV(L->top++, d);
return 1;
} else {
setnilV(L->top++);
return 0;
}
}
static int io_file_readline(lua_State *L, FILE *fp, MSize chop)
{
MSize m = LUAL_BUFFERSIZE, n = 0, ok = 0;
char *buf;
for (;;) {
buf = lj_str_needbuf(L, &G(L)->tmpbuf, m);
if (fgets(buf+n, m-n, fp) == NULL) break;
n += (MSize)strlen(buf+n);
ok |= n;
if (n && buf[n-1] == '\n') { n -= chop; break; }
if (n >= m - 64) m += m;
}
setstrV(L, L->top++, lj_str_new(L, buf, (size_t)n));
lj_gc_check(L);
return (int)ok;
}
static void io_file_readall(lua_State *L, FILE *fp)
{
MSize m, n;
for (m = LUAL_BUFFERSIZE, n = 0; ; m += m) {
char *buf = lj_str_needbuf(L, &G(L)->tmpbuf, m);
n += (MSize)fread(buf+n, 1, m-n, fp);
if (n != m) {
setstrV(L, L->top++, lj_str_new(L, buf, (size_t)n));
lj_gc_check(L);
return;
}
}
}
static int io_file_readlen(lua_State *L, FILE *fp, MSize m)
{
if (m) {
char *buf = lj_str_needbuf(L, &G(L)->tmpbuf, m);
MSize n = (MSize)fread(buf, 1, m, fp);
setstrV(L, L->top++, lj_str_new(L, buf, (size_t)n));
lj_gc_check(L);
return (n > 0 || m == 0);
} else {
int c = getc(fp);
ungetc(c, fp);
setstrV(L, L->top++, &G(L)->strempty);
return (c != EOF);
}
}
static int io_file_read(lua_State *L, FILE *fp, int start)
{
int ok, n, nargs = (int)(L->top - L->base) - start;
clearerr(fp);
if (nargs == 0) {
ok = io_file_readline(L, fp, 1);
n = start+1; /* Return 1 result. */
} else {
/* The results plus the buffers go on top of the args. */
luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
ok = 1;
for (n = start; nargs-- && ok; n++) {
if (tvisstr(L->base+n)) {
const char *p = strVdata(L->base+n);
if (p[0] != '*')
lj_err_arg(L, n+1, LJ_ERR_INVOPT);
if (p[1] == 'n')
ok = io_file_readnum(L, fp);
else if ((p[1] & ~0x20) == 'L')
ok = io_file_readline(L, fp, (p[1] == 'l'));
else if (p[1] == 'a')
io_file_readall(L, fp);
else
lj_err_arg(L, n+1, LJ_ERR_INVFMT);
} else if (tvisnumber(L->base+n)) {
ok = io_file_readlen(L, fp, (MSize)lj_lib_checkint(L, n+1));
} else {
lj_err_arg(L, n+1, LJ_ERR_INVOPT);
}
}
}
if (ferror(fp))
return luaL_fileresult(L, 0, NULL);
if (!ok)
setnilV(L->top-1); /* Replace last result with nil. */
return n - start;
}
static int io_file_write(lua_State *L, FILE *fp, int start)
{
cTValue *tv;
int status = 1;
for (tv = L->base+start; tv < L->top; tv++) {
if (tvisstr(tv)) {
MSize len = strV(tv)->len;
status = status && (fwrite(strVdata(tv), 1, len, fp) == len);
} else if (tvisint(tv)) {
char buf[LJ_STR_INTBUF];
char *p = lj_str_bufint(buf, intV(tv));
size_t len = (size_t)(buf+LJ_STR_INTBUF-p);
status = status && (fwrite(p, 1, len, fp) == len);
} else if (tvisnum(tv)) {
status = status && (fprintf(fp, LUA_NUMBER_FMT, numV(tv)) > 0);
} else {
lj_err_argt(L, (int)(tv - L->base) + 1, LUA_TSTRING);
}
}
if (LJ_52 && status) {
L->top = L->base+1;
if (start == 0)
setudataV(L, L->base, IOSTDF_UD(L, GCROOT_IO_OUTPUT));
return 1;
}
return luaL_fileresult(L, status, NULL);
}
static int io_file_iter(lua_State *L)
{
GCfunc *fn = curr_func(L);
IOFileUD *iof = uddata(udataV(&fn->c.upvalue[0]));
int n = fn->c.nupvalues - 1;
if (iof->fp == NULL)
lj_err_caller(L, LJ_ERR_IOCLFL);
L->top = L->base;
if (n) { /* Copy upvalues with options to stack. */
if (n > LUAI_MAXCSTACK)
lj_err_caller(L, LJ_ERR_STKOV);
lj_state_checkstack(L, (MSize)n);
memcpy(L->top, &fn->c.upvalue[1], n*sizeof(TValue));
L->top += n;
}
n = io_file_read(L, iof->fp, 0);
if (ferror(iof->fp))
lj_err_callermsg(L, strVdata(L->top-2));
if (tvisnil(L->base) && (iof->type & IOFILE_FLAG_CLOSE)) {
io_file_close(L, iof); /* Return values are ignored. */
return 0;
}
return n;
}
static int io_file_lines(lua_State *L)
{
int n = (int)(L->top - L->base);
if (n > LJ_MAX_UPVAL)
lj_err_caller(L, LJ_ERR_UNPACK);
lua_pushcclosure(L, io_file_iter, n);
return 1;
}
#define <API key>
LJLIB_CF(io_method_close)
{
IOFileUD *iof = L->base < L->top ? io_tofile(L) :
IOSTDF_IOF(L, GCROOT_IO_OUTPUT);
return io_file_close(L, iof);
}
LJLIB_CF(io_method_read)
{
return io_file_read(L, io_tofile(L)->fp, 1);
}
LJLIB_CF(io_method_write) LJLIB_REC(io_write 0)
{
return io_file_write(L, io_tofile(L)->fp, 1);
}
LJLIB_CF(io_method_flush) LJLIB_REC(io_flush 0)
{
return luaL_fileresult(L, fflush(io_tofile(L)->fp) == 0, NULL);
}
LJLIB_CF(io_method_seek)
{
FILE *fp = io_tofile(L)->fp;
int opt = lj_lib_checkopt(L, 2, 1, "\3set\3cur\3end");
int64_t ofs = 0;
cTValue *o;
int res;
if (opt == 0) opt = SEEK_SET;
else if (opt == 1) opt = SEEK_CUR;
else if (opt == 2) opt = SEEK_END;
o = L->base+2;
if (o < L->top) {
if (tvisint(o))
ofs = (int64_t)intV(o);
else if (tvisnum(o))
ofs = (int64_t)numV(o);
else if (!tvisnil(o))
lj_err_argt(L, 3, LUA_TNUMBER);
}
#if LJ_TARGET_POSIX
res = fseeko(fp, ofs, opt);
#elif _MSC_VER >= 1400
res = _fseeki64(fp, ofs, opt);
#elif defined(__MINGW32__)
res = fseeko64(fp, ofs, opt);
#else
res = fseek(fp, (long)ofs, opt);
#endif
if (res)
return luaL_fileresult(L, 0, NULL);
#if LJ_TARGET_POSIX
ofs = ftello(fp);
#elif _MSC_VER >= 1400
ofs = _ftelli64(fp);
#elif defined(__MINGW32__)
ofs = ftello64(fp);
#else
ofs = (int64_t)ftell(fp);
#endif
setint64V(L->top-1, ofs);
return 1;
}
LJLIB_CF(io_method_setvbuf)
{
FILE *fp = io_tofile(L)->fp;
int opt = lj_lib_checkopt(L, 2, -1, "\4full\4line\2no");
size_t sz = (size_t)lj_lib_optint(L, 3, LUAL_BUFFERSIZE);
if (opt == 0) opt = _IOFBF;
else if (opt == 1) opt = _IOLBF;
else if (opt == 2) opt = _IONBF;
return luaL_fileresult(L, setvbuf(fp, NULL, opt, sz) == 0, NULL);
}
LJLIB_CF(io_method_lines)
{
io_tofile(L);
return io_file_lines(L);
}
LJLIB_CF(io_method___gc)
{
IOFileUD *iof = io_tofilep(L);
if (iof->fp != NULL && (iof->type & IOFILE_TYPE_MASK) != IOFILE_TYPE_STDF)
io_file_close(L, iof);
return 0;
}
LJLIB_CF(<API key>)
{
IOFileUD *iof = io_tofilep(L);
if (iof->fp != NULL)
lua_pushfstring(L, "file (%p)", iof->fp);
else
lua_pushliteral(L, "file (closed)");
return 1;
}
LJLIB_PUSH(top-1) LJLIB_SET(__index)
#include "lj_libdef.h"
#define LJLIB_MODULE_io
LJLIB_PUSH(top-2) LJLIB_SET(!) /* Set environment. */
LJLIB_CF(io_open)
{
const char *fname = strdata(lj_lib_checkstr(L, 1));
GCstr *s = lj_lib_optstr(L, 2);
const char *mode = s ? strdata(s) : "r";
IOFileUD *iof = io_file_new(L);
iof->fp = fopen(fname, mode);
return iof->fp != NULL ? 1 : luaL_fileresult(L, 0, fname);
}
LJLIB_CF(io_popen)
{
#if LJ_TARGET_POSIX || LJ_TARGET_WINDOWS
const char *fname = strdata(lj_lib_checkstr(L, 1));
GCstr *s = lj_lib_optstr(L, 2);
const char *mode = s ? strdata(s) : "r";
IOFileUD *iof = io_file_new(L);
iof->type = IOFILE_TYPE_PIPE;
#if LJ_TARGET_POSIX
fflush(NULL);
iof->fp = popen(fname, mode);
#else
iof->fp = _popen(fname, mode);
#endif
return iof->fp != NULL ? 1 : luaL_fileresult(L, 0, fname);
#else
return luaL_error(L, LUA_QL("popen") " not supported");
#endif
}
LJLIB_CF(io_tmpfile)
{
IOFileUD *iof = io_file_new(L);
#if LJ_TARGET_PS3 || LJ_TARGET_PS4 || LJ_TARGET_PSVITA
iof->fp = NULL; errno = ENOSYS;
#else
iof->fp = tmpfile();
#endif
return iof->fp != NULL ? 1 : luaL_fileresult(L, 0, NULL);
}
LJLIB_CF(io_close)
{
return <API key>(L);
}
LJLIB_CF(io_read)
{
return io_file_read(L, io_stdfile(L, GCROOT_IO_INPUT), 0);
}
LJLIB_CF(io_write) LJLIB_REC(io_write GCROOT_IO_OUTPUT)
{
return io_file_write(L, io_stdfile(L, GCROOT_IO_OUTPUT), 0);
}
LJLIB_CF(io_flush) LJLIB_REC(io_flush GCROOT_IO_OUTPUT)
{
return luaL_fileresult(L, fflush(io_stdfile(L, GCROOT_IO_OUTPUT)) == 0, NULL);
}
static int io_std_getset(lua_State *L, ptrdiff_t id, const char *mode)
{
if (L->base < L->top && !tvisnil(L->base)) {
if (tvisudata(L->base)) {
io_tofile(L);
L->top = L->base+1;
} else {
io_file_open(L, mode);
}
/* NOBARRIER: The standard I/O handles are GC roots. */
setgcref(G(L)->gcroot[id], gcV(L->top-1));
} else {
setudataV(L, L->top++, IOSTDF_UD(L, id));
}
return 1;
}
LJLIB_CF(io_input)
{
return io_std_getset(L, GCROOT_IO_INPUT, "r");
}
LJLIB_CF(io_output)
{
return io_std_getset(L, GCROOT_IO_OUTPUT, "w");
}
LJLIB_CF(io_lines)
{
if (L->base == L->top) setnilV(L->top++);
if (!tvisnil(L->base)) { /* io.lines(fname) */
IOFileUD *iof = io_file_open(L, "r");
iof->type = IOFILE_TYPE_FILE|IOFILE_FLAG_CLOSE;
L->top
setudataV(L, L->base, udataV(L->top));
} else { /* io.lines() iterates over stdin. */
setudataV(L, L->base, IOSTDF_UD(L, GCROOT_IO_INPUT));
}
return io_file_lines(L);
}
LJLIB_CF(io_type)
{
cTValue *o = lj_lib_checkany(L, 1);
if (!(tvisudata(o) && udataV(o)->udtype == UDTYPE_IO_FILE))
setnilV(L->top++);
else if (((IOFileUD *)uddata(udataV(o)))->fp != NULL)
lua_pushliteral(L, "file");
else
lua_pushliteral(L, "closed file");
return 1;
}
#include "lj_libdef.h"
static GCobj *io_std_new(lua_State *L, FILE *fp, const char *name)
{
IOFileUD *iof = (IOFileUD *)lua_newuserdata(L, sizeof(IOFileUD));
GCudata *ud = udataV(L->top-1);
ud->udtype = UDTYPE_IO_FILE;
/* NOBARRIER: The GCudata is new (marked white). */
setgcref(ud->metatable, gcV(L->top-3));
iof->fp = fp;
iof->type = IOFILE_TYPE_STDF;
lua_setfield(L, -2, name);
return obj2gco(ud);
}
LUALIB_API int luaopen_io(lua_State *L)
{
LJ_LIB_REG(L, NULL, io_method);
copyTV(L, L->top, L->top-1); L->top++;
lua_setfield(L, LUA_REGISTRYINDEX, LUA_FILEHANDLE);
LJ_LIB_REG(L, LUA_IOLIBNAME, io);
setgcref(G(L)->gcroot[GCROOT_IO_INPUT], io_std_new(L, stdin, "stdin"));
setgcref(G(L)->gcroot[GCROOT_IO_OUTPUT], io_std_new(L, stdout, "stdout"));
io_std_new(L, stderr, "stderr");
return 1;
}
|
/**
* @defgroup cpu_cc2538_gptimer CC2538 General Purpose Timer
* @ingroup cpu_cc2538_regs
* @{
*
* @file
* @brief CC2538 General Purpose Timer (GPTIMER) driver
*
* @author Ian Martin <ian@locicontrols.com>
* @author Sebastian Meiling <s@mlng.net>
*/
#ifndef CC2538_GPTIMER_H
#define CC2538_GPTIMER_H
#include <stdint.h>
#include "cc2538.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Timer modes
*/
enum {
<API key> = 1, /**< GPTIMER one-shot mode */
<API key> = 2, /**< GPTIMER periodic mode */
<API key> = 3, /**< GPTIMER capture mode */
};
/**
* @brief Timer width configuration
*/
enum {
<API key> = 0, /**< 32-bit timer configuration */
<API key> = 1, /**< 32-bit real-time clock */
<API key> = 4, /**< 16-bit timer configuration */
};
/**
* @brief GPTIMER component registers
*/
typedef struct {
cc2538_reg_t CFG; /**< GPTIMER Configuration */
cc2538_reg_t TAMR; /**< GPTIMER Timer A mode */
cc2538_reg_t TBMR; /**< GPTIMER Timer B mode */
cc2538_reg_t CTL; /**< GPTIMER Control */
cc2538_reg_t SYNC; /**< GPTIMER Synchronize */
cc2538_reg_t RESERVED2; /**< Reserved word */
cc2538_reg_t IMR; /**< GPTIMER Interrupt Mask */
cc2538_reg_t RIS; /**< GPTIMER Raw Interrupt Status */
cc2538_reg_t MIS; /**< GPTIMER Masked Interrupt Status */
cc2538_reg_t ICR; /**< GPTIMER Interrupt Clear */
cc2538_reg_t TAILR; /**< GPTIMER Timer A Interval Load */
cc2538_reg_t TBILR; /**< GPTIMER Timer B Interval Load */
cc2538_reg_t TAMATCHR; /**< GPTIMER Timer A Match */
cc2538_reg_t TBMATCHR; /**< GPTIMER Timer B Match */
cc2538_reg_t TAPR; /**< GPTIMER Timer A Prescale Register */
cc2538_reg_t TBPR; /**< GPTIMER Timer B Prescale Register */
cc2538_reg_t TAPMR; /**< GPTIMER Timer A Prescale Match Register */
cc2538_reg_t TBPMR; /**< GPTIMER Timer B Prescale Match Register */
cc2538_reg_t TAR; /**< GPTIMER Timer A */
cc2538_reg_t TBR; /**< GPTIMER Timer B */
cc2538_reg_t TAV; /**< GPTIMER Timer A Value */
cc2538_reg_t TBV; /**< GPTIMER Timer B Value */
cc2538_reg_t RESERVED3; /**< Reserved word */
cc2538_reg_t TAPS; /**< GPTIMER Timer A Prescale Snapshot */
cc2538_reg_t TBPS; /**< GPTIMER Timer B Prescale Snapshot */
cc2538_reg_t TAPV; /**< GPTIMER Timer A Prescale Value */
cc2538_reg_t TBPV; /**< GPTIMER Timer B Prescale Value */
cc2538_reg_t RESERVED[981]; /**< Reserved */
cc2538_reg_t PP; /**< GPTIMER Peripheral Properties */
cc2538_reg_t RESERVED4[15]; /**< Reserved */
} cc2538_gptimer_t;
#ifdef __cplusplus
} /* end extern "C" */
#endif
#endif /* CC2538_GPTIMER_H */
|
/**
* @defgroup cpu_nrf52 Nordic nRF52 MCU
* @ingroup cpu
* @brief Nordic nRF52 family of CPUs
* @{
*
* @file
* @brief nRF52 specific CPU configuration
*
* @author Hauke Petersen <hauke.petersen@fu-berlin.de>
*
*/
#ifndef CPU_CONF_H
#define CPU_CONF_H
#include "cpu_conf_common.h"
#ifdef <API key>
#include "vendor/nrf52.h"
#include "vendor/nrf52_bitfields.h"
#elif defined(<API key>)
#include "vendor/nrf52840.h"
#include "vendor/nrf52840_bitfields.h"
#else
#error "The CPU_MODEL of your board is currently not supported"
#endif
#ifdef __cplusplus
extern "C" {
#endif
/**
* @name ARM Cortex-M specific CPU configuration
* @{
*/
#define <API key> (2U)
#define CPU_FLASH_BASE (0x00000000)
#ifdef <API key>
#define CPU_IRQ_NUMOF (38U)
#elif <API key>
#define CPU_IRQ_NUMOF (46U)
#endif
/**
* @brief Flash page configuration
* @{
*/
#define FLASHPAGE_SIZE (4096U)
#if defined(<API key>)
#define FLASHPAGE_NUMOF (128U)
#elif defined(<API key>)
#define FLASHPAGE_NUMOF (256U)
#endif
/* The minimum block size which can be written is 4B. However, the erase
* block is always FLASHPAGE_SIZE.
*/
#define <API key> (4U)
/* Writing should be always 4 bytes aligned */
#define <API key> (4U)
/**
* @brief SoftDevice settings
* @{
*/
#ifdef SOFTDEVICE_PRESENT
#ifndef DONT_OVERRIDE_NVIC
#include "nrf_soc.h"
#undef NVIC_SetPriority
#define NVIC_SetPriority sd_nvic_SetPriority
#endif /* DONT_OVERRIDE_NVIC */
#endif /* SOFTDEVICE_PRESENT */
/**
* @brief Put the CPU in the low-power 'wait for event' state
*/
static inline void nrf52_sleep(void)
{
__SEV();
__WFE();
__asm("nop");
}
#ifdef __cplusplus
}
#endif
#endif /* CPU_CONF_H */
|
/**
* @ingroup net_fib
* @{
*
* @file
* @brief Functions to manage FIB entries
*
* @author Martin Landsmann <martin.landsmann@haw-hamburg.de>
* @author Oliver Hahm <oliver.hahm@inria.fr>
*
* @}
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <errno.h>
#include "thread.h"
#include "mutex.h"
#include "msg.h"
#include "xtimer.h"
#include "timex.h"
#include "utlist.h"
#define ENABLE_DEBUG (0)
#include "debug.h"
#include "net/fib.h"
#include "net/fib/table.h"
#ifdef MODULE_IPV6_ADDR
#include "net/ipv6/addr.h"
static char addr_str[<API key>];
#endif
#ifdef MODULE_IPV6_ADDR
#define FIB_ADDR_PRINT_LEN 39
#else
#define FIB_ADDR_PRINT_LEN 32
#if FIB_ADDR_PRINT_LEN != (<API key> * 2)
#error "FIB_ADDR_PRINT_LEN MUST BE (<API key> * 2)"
#endif
#endif
#define <API key>(X)
#define <API key>(X) <API key>(X)
#define FIB_ADDR_PRINT_LENS <API key>(FIB_ADDR_PRINT_LEN)
/**
* @brief convert an offset given in ms to absolute time in time in us
* @param[in] ms the milliseconds to be converted
* @param[out] target the converted point in time
*/
static void <API key>(uint32_t ms, uint64_t *target)
{
*target = xtimer_now_usec64() + (ms * US_PER_MS);
}
/**
* @brief returns pointer to the entry for the given destination address
*
* @param[in] table the FIB table to search in
* @param[in] dst the destination address
* @param[in] dst_size the destination address size
* @param[out] entry_arr the array to scribe the found match
* @param[in, out] entry_arr_size the number of entries provided by entry_arr (should be always 1)
* this value is overwritten with the actual found number
*
* @return 0 if we found a next-hop prefix
* 1 if we found the exact address next-hop
* -EHOSTUNREACH if no fitting next-hop is available
*/
static int fib_find_entry(fib_table_t *table, uint8_t *dst, size_t dst_size,
fib_entry_t **entry_arr, size_t *entry_arr_size) {
uint64_t now = xtimer_now_usec64();
size_t count = 0;
size_t prefix_size = 0;
size_t match_size = dst_size << 3;
int ret = -EHOSTUNREACH;
bool is_all_zeros_addr = true;
#if ENABLE_DEBUG
DEBUG("[fib_find_entry] dst =");
for (size_t i = 0; i < dst_size; i++) {
DEBUG(" %02x", dst[i]);
}
DEBUG("\n");
#endif
for (size_t i = 0; i < dst_size; ++i) {
if (dst[i] != 0) {
is_all_zeros_addr = false;
break;
}
}
for (size_t i = 0; i < table->size; ++i) {
/* autoinvalidate if the entry lifetime is not set to not expire */
if (table->data.entries[i].lifetime != <API key>) {
/* check if the lifetime expired */
if (table->data.entries[i].lifetime < now) {
/* remove this entry if its lifetime expired */
table->data.entries[i].lifetime = 0;
table->data.entries[i].global_flags = 0;
table->data.entries[i].next_hop_flags = 0;
table->data.entries[i].iface_id = KERNEL_PID_UNDEF;
if (table->data.entries[i].global != NULL) {
<API key>(table->data.entries[i].global);
table->data.entries[i].global = NULL;
}
if (table->data.entries[i].next_hop != NULL) {
<API key>(table->data.entries[i].next_hop);
table->data.entries[i].next_hop = NULL;
}
}
}
if ((prefix_size < (dst_size<<3)) && (table->data.entries[i].global != NULL)) {
int ret_comp = <API key>(table->data.entries[i].global, dst, &match_size);
/* If we found an exact match */
if ((ret_comp == <API key>)
|| (is_all_zeros_addr && (ret_comp == <API key>))) {
entry_arr[0] = &(table->data.entries[i]);
*entry_arr_size = 1;
/* we will not find a better one so we return */
return 1;
}
else {
/* we try to find the most fitting prefix */
if (ret_comp == <API key>) {
if (table->data.entries[i].global_flags & <API key>) {
/* we shift the most upper flag byte back to get the number of prefix bits */
size_t global_prefix_len = (table->data.entries[i].global_flags
& <API key>) >> <API key>;
if ((match_size >= global_prefix_len) &&
((prefix_size == 0) || (match_size > prefix_size))) {
entry_arr[0] = &(table->data.entries[i]);
/* we could find a better one so we move on */
ret = 0;
prefix_size = match_size;
count = 1;
}
}
}
else if (ret_comp == <API key>) {
/* we found the default gateway entry, e.g. ::/0 for IPv6
* and we keep it only if there is no better one
*/
if (prefix_size == 0) {
entry_arr[0] = &(table->data.entries[i]);
/* we could find a better one so we move on */
ret = 0;
count = 1;
}
}
match_size = dst_size<<3;
}
}
}
#if ENABLE_DEBUG
if (count > 0) {
DEBUG("[fib_find_entry] found prefix on interface %d:", entry_arr[0]->iface_id);
for (size_t i = 0; i < entry_arr[0]->global->address_size; i++) {
DEBUG(" %02x", entry_arr[0]->global->address[i]);
}
DEBUG("\n");
}
#endif
*entry_arr_size = count;
return ret;
}
/**
* @brief updates the next hop the lifetime and the interface id for a given entry
*
* @param[in] entry the entry to be updated
* @param[in] next_hop the next hop address to be updated
* @param[in] next_hop_size the next hop address size
* @param[in] next_hop_flags the next-hop address flags
* @param[in] lifetime the lifetime in ms
*
* @return 0 if the entry has been updated
* -ENOMEM if the entry cannot be updated due to insufficient RAM
*/
static int fib_upd_entry(fib_entry_t *entry, uint8_t *next_hop,
size_t next_hop_size, uint32_t next_hop_flags,
uint32_t lifetime)
{
<API key> *container = <API key>(next_hop, next_hop_size);
if (container == NULL) {
return -ENOMEM;
}
<API key>(entry->next_hop);
entry->next_hop = container;
entry->next_hop_flags = next_hop_flags;
if (lifetime != (uint32_t)<API key>) {
<API key>(lifetime, &entry->lifetime);
}
else {
entry->lifetime = <API key>;
}
return 0;
}
/**
* @brief creates a new FIB entry with the provided parameters
*
* @param[in] table the FIB table to create the entry in
* @param[in] iface_id the interface ID
* @param[in] dst the destination address
* @param[in] dst_size the destination address size
* @param[in] dst_flags the destination address flags
* @param[in] next_hop the next hop address
* @param[in] next_hop_size the next hop address size
* @param[in] next_hop_flags the next-hop address flags
* @param[in] lifetime the lifetime in ms
*
* @return 0 on success
* -ENOMEM if no new entry can be created
*/
static int fib_create_entry(fib_table_t *table, kernel_pid_t iface_id,
uint8_t *dst, size_t dst_size, uint32_t dst_flags,
uint8_t *next_hop, size_t next_hop_size, uint32_t
next_hop_flags, uint32_t lifetime)
{
for (size_t i = 0; i < table->size; ++i) {
if (table->data.entries[i].lifetime == 0) {
table->data.entries[i].global = <API key>(dst, dst_size);
if (table->data.entries[i].global != NULL) {
table->data.entries[i].global_flags = dst_flags;
table->data.entries[i].next_hop = <API key>(next_hop, next_hop_size);
table->data.entries[i].next_hop_flags = next_hop_flags;
}
if (table->data.entries[i].next_hop != NULL) {
/* everything worked fine */
table->data.entries[i].iface_id = iface_id;
if (lifetime != (uint32_t) <API key>) {
<API key>(lifetime, &table->data.entries[i].lifetime);
}
else {
table->data.entries[i].lifetime = <API key>;
}
return 0;
}
}
}
return -ENOMEM;
}
/**
* @brief removes the given entry
*
* @param[in] entry the entry to be removed
*
* @return 0 on success
*/
static int fib_remove(fib_entry_t *entry)
{
if (entry->global != NULL) {
<API key>(entry->global);
}
if (entry->next_hop) {
<API key>(entry->next_hop);
}
entry->global = NULL;
entry->global_flags = 0;
entry->next_hop = NULL;
entry->next_hop_flags = 0;
entry->iface_id = KERNEL_PID_UNDEF;
entry->lifetime = 0;
return 0;
}
/**
* @brief signals (sends a message to) all registered routing protocols
* registered with a matching prefix (usually this should be only one).
* The receiver MUST copy the content, i.e. the address before reply.
*
* @param[in] table the fib instance to use
* @param[in] type the kind of signal
* @param[in] dat the data to send
* @param[in] dat_size the data size in bytes
* @param[in] dat_flags the data flags
*
* @return 0 on a new available entry,
* -ENOENT if no suiting entry is provided.
*/
static int fib_signal_rp(fib_table_t *table, uint16_t type, uint8_t *dat,
size_t dat_size, uint32_t dat_flags)
{
msg_t msg, reply;
rp_address_msg_t rp_addr_msg;
int ret = -ENOENT;
void *content = NULL;
if (type != <API key>) {
/* the passed data is an address */
rp_addr_msg.address = dat;
rp_addr_msg.address_size = dat_size;
rp_addr_msg.address_flags = dat_flags;
content = (void *)&rp_addr_msg;
}
else {
/* the passed data is a sr head
* dat_size and dat_flags are not used in this case
*/
content = (void *)dat;
}
msg.type = type;
msg.content.ptr = content;
for (size_t i = 0; i < <API key>; ++i) {
if (table->notify_rp[i] != KERNEL_PID_UNDEF) {
DEBUG("[fib_signal_rp] send msg@: %p to pid[%d]: %d\n", \
msg.content.ptr, (int)i, (int)(table->notify_rp[i]));
/* do only signal a RP if its registered prefix matches */
if (type != <API key>) {
size_t dat_size_in_bits = dat_size<<3;
if (<API key>(table->prefix_rp[i], dat,
&dat_size_in_bits) != -ENOENT) {
/* the receiver, i.e. the RP, MUST copy the content value.
* using the provided pointer after replying this message
* will lead to errors
*/
msg_send_receive(&msg, &reply, table->notify_rp[i]);
DEBUG("[fib_signal_rp] got reply.\n");
ret = 0;
}
}
else {
fib_sr_t *temp_sr = (fib_sr_t *)dat;
size_t dat_size_in_bits = temp_sr->sr_dest->address->address_size << 3;
if (<API key>(table->prefix_rp[i],
temp_sr->sr_dest->address->address,
&dat_size_in_bits) != -ENOENT) {
/* the receiver, i.e. the RP, MUST copy the content value.
* using the provided pointer after replying this message
* will lead to errors
*/
msg_send_receive(&msg, &reply, table->notify_rp[i]);
DEBUG("[fib_signal_rp] got reply.\n");
ret = 0;
}
}
}
}
return ret;
}
int fib_add_entry(fib_table_t *table,
kernel_pid_t iface_id, uint8_t *dst, size_t dst_size,
uint32_t dst_flags, uint8_t *next_hop, size_t next_hop_size,
uint32_t next_hop_flags, uint32_t lifetime)
{
mutex_lock(&(table->mtx_access));
DEBUG("[fib_add_entry]\n");
size_t count = 1;
fib_entry_t *entry[count];
/* check if dst and next_hop are valid pointers */
if ((dst == NULL) || (next_hop == NULL)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
int ret = fib_find_entry(table, dst, dst_size, &(entry[0]), &count);
if (ret == 1) {
/* we must take the according entry and update the values */
ret = fib_upd_entry(entry[0], next_hop, next_hop_size, next_hop_flags, lifetime);
}
else {
ret = fib_create_entry(table, iface_id, dst, dst_size, dst_flags,
next_hop, next_hop_size, next_hop_flags, lifetime);
}
mutex_unlock(&(table->mtx_access));
return ret;
}
int fib_update_entry(fib_table_t *table, uint8_t *dst, size_t dst_size,
uint8_t *next_hop, size_t next_hop_size,
uint32_t next_hop_flags, uint32_t lifetime)
{
mutex_lock(&(table->mtx_access));
DEBUG("[fib_update_entry]\n");
size_t count = 1;
fib_entry_t *entry[count];
int ret = -ENOMEM;
/* check if dst and next_hop are valid pointers */
if ((dst == NULL) || (next_hop == NULL)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (fib_find_entry(table, dst, dst_size, &(entry[0]), &count) == 1) {
DEBUG("[fib_update_entry] found entry: %p\n", (void *)(entry[0]));
/* we must take the according entry and update the values */
ret = fib_upd_entry(entry[0], next_hop, next_hop_size, next_hop_flags, lifetime);
}
else {
/* we have ambiguous entries, i.e. count > 1
* this should never happen
*/
DEBUG("[fib_update_entry] ambiguous entries detected!!!\n");
}
mutex_unlock(&(table->mtx_access));
return ret;
}
void fib_remove_entry(fib_table_t *table, uint8_t *dst, size_t dst_size)
{
mutex_lock(&(table->mtx_access));
DEBUG("[fib_remove_entry]\n");
size_t count = 1;
fib_entry_t *entry[count];
int ret = fib_find_entry(table, dst, dst_size, &(entry[0]), &count);
if (ret == 1) {
/* we must take the according entry and update the values */
fib_remove(entry[0]);
}
else {
/* we have ambiguous entries, i.e. count > 1
* this should never happen
*/
DEBUG("[fib_update_entry] ambiguous entries detected!!!\n");
}
mutex_unlock(&(table->mtx_access));
}
void fib_flush(fib_table_t *table, kernel_pid_t interface)
{
mutex_lock(&(table->mtx_access));
DEBUG("[fib_flush]\n");
for (size_t i = 0; i < table->size; ++i) {
if ((interface == KERNEL_PID_UNDEF) ||
(interface == table->data.entries[i].iface_id)) {
fib_remove(&table->data.entries[i]);
}
}
mutex_unlock(&(table->mtx_access));
}
int fib_get_next_hop(fib_table_t *table, kernel_pid_t *iface_id,
uint8_t *next_hop, size_t *next_hop_size,
uint32_t *next_hop_flags, uint8_t *dst, size_t dst_size,
uint32_t dst_flags)
{
mutex_lock(&(table->mtx_access));
DEBUG("[fib_get_next_hop]\n");
size_t count = 1;
fib_entry_t *entry[count];
if ((iface_id == NULL)
|| (next_hop_size == NULL)
|| (next_hop_flags == NULL)) {
mutex_unlock(&(table->mtx_access));
return -EINVAL;
}
if ((dst == NULL) || (next_hop == NULL)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
int ret = fib_find_entry(table, dst, dst_size, &(entry[0]), &count);
if (!(ret == 0 || ret == 1)) {
/* notify all responsible RPs for unknown next-hop for the destination address */
if (fib_signal_rp(table, <API key>,
dst, dst_size, dst_flags) == 0) {
count = 1;
/* now lets see if the RRPs have found a valid next-hop */
ret = fib_find_entry(table, dst, dst_size, &(entry[0]), &count);
}
}
if (ret == 0 || ret == 1) {
uint8_t *address_ret = <API key>(entry[0]->next_hop,
next_hop, next_hop_size);
if (address_ret == NULL) {
mutex_unlock(&(table->mtx_access));
return -ENOBUFS;
}
}
else {
mutex_unlock(&(table->mtx_access));
return -EHOSTUNREACH;
}
*iface_id = entry[0]->iface_id;
*next_hop_flags = entry[0]->next_hop_flags;
mutex_unlock(&(table->mtx_access));
return 0;
}
int <API key>(fib_table_t *table, uint8_t *prefix,
size_t prefix_size,
<API key> *dst_set,
size_t* dst_set_size)
{
mutex_lock(&(table->mtx_access));
int ret = -EHOSTUNREACH;
size_t found_entries = 0;
for (size_t i = 0; i < table->size; ++i) {
if ((table->data.entries[i].global != NULL) &&
(<API key>(table->data.entries[i].global, prefix, prefix_size<<3) >= <API key>)) {
if( (dst_set != NULL) && (found_entries < *dst_set_size) ) {
/* set the size to full byte usage */
dst_set[found_entries].dest_size = sizeof(dst_set[found_entries].dest);
<API key>(table->data.entries[i].global,
dst_set[found_entries].dest,
&dst_set[found_entries].dest_size);
}
found_entries++;
}
}
if (found_entries > *dst_set_size) {
ret = -ENOBUFS;
}
else if (found_entries > 0) {
ret = 0;
}
*dst_set_size = found_entries;
mutex_unlock(&(table->mtx_access));
return ret;
}
void fib_init(fib_table_t *table)
{
DEBUG("[fib_init] hello. Initializing some stuff.\n");
mutex_init(&(table->mtx_access));
mutex_lock(&(table->mtx_access));
for (size_t i = 0; i < <API key>; ++i) {
table->notify_rp[i] = KERNEL_PID_UNDEF;
table->prefix_rp[i] = NULL;
}
table->notify_rp_pos = 0;
if (table->table_type == FIB_TABLE_TYPE_SR) {
memset(table->data.source_routes->headers, 0,
sizeof(fib_sr_t) * table->size);
memset(table->data.source_routes->entry_pool, 0,
sizeof(fib_sr_entry_t) * table->data.source_routes->entry_pool_size);
}
else {
memset(table->data.entries, 0, (table->size * sizeof(fib_entry_t)));
}
<API key>();
mutex_unlock(&(table->mtx_access));
}
void fib_deinit(fib_table_t *table)
{
DEBUG("[fib_deinit] hello. De-Initializing stuff.\n");
mutex_lock(&(table->mtx_access));
for (size_t i = 0; i < <API key>; ++i) {
table->notify_rp[i] = KERNEL_PID_UNDEF;
table->prefix_rp[i] = NULL;
}
table->notify_rp_pos = 0;
if (table->table_type == FIB_TABLE_TYPE_SR) {
memset(table->data.source_routes->headers, 0,
sizeof(fib_sr_t) * table->size);
memset(table->data.source_routes->entry_pool, 0,
sizeof(fib_sr_entry_t) * table->data.source_routes->entry_pool_size);
}
else {
memset(table->data.entries, 0, (table->size * sizeof(fib_entry_t)));
}
<API key>();
mutex_unlock(&(table->mtx_access));
}
int fib_register_rp(fib_table_t *table, uint8_t *prefix, size_t <API key>)
{
mutex_lock(&(table->mtx_access));
if (table->notify_rp_pos >= <API key>) {
mutex_unlock(&(table->mtx_access));
return -ENOMEM;
}
if ((prefix == NULL) || (<API key> == 0)) {
mutex_unlock(&(table->mtx_access));
return -EINVAL;
}
if (table->notify_rp_pos < <API key>) {
table->notify_rp[table->notify_rp_pos] = sched_active_pid;
<API key> *container = <API key>(prefix,
<API key>);
table->prefix_rp[table->notify_rp_pos] = container;
table->notify_rp_pos++;
}
mutex_unlock(&(table->mtx_access));
return 0;
}
int <API key>(fib_table_t *table)
{
mutex_lock(&(table->mtx_access));
size_t used_entries = 0;
for (size_t i = 0; i < table->size; ++i) {
used_entries += (size_t)(table->data.entries[i].global != NULL);
}
mutex_unlock(&(table->mtx_access));
return used_entries;
}
/* source route handling */
int fib_sr_create(fib_table_t *table, fib_sr_t **fib_sr, kernel_pid_t sr_iface_id,
uint32_t sr_flags, uint32_t sr_lifetime)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (sr_lifetime == 0)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
for (size_t i = 0; i < table->size; ++i) {
if (table->data.source_routes->headers[i].sr_lifetime == 0) {
table->data.source_routes->headers[i].sr_iface_id = sr_iface_id;
table->data.source_routes->headers[i].sr_flags = sr_flags;
table->data.source_routes->headers[i].sr_path = NULL;
table->data.source_routes->headers[i].sr_dest = NULL;
if (sr_lifetime < (uint32_t)<API key>) {
<API key>(sr_lifetime,
&table->data.source_routes->headers[i].sr_lifetime);
}
else {
table->data.source_routes->headers[i].sr_lifetime = <API key>;
}
*fib_sr = &table->data.source_routes->headers[i];
mutex_unlock(&(table->mtx_access));
return 0;
}
}
mutex_unlock(&(table->mtx_access));
return -ENOBUFS;
}
/**
* @brief Internal function:
* checks the lifetime and removes the entry in case it expired
*/
static int <API key>(fib_sr_t *fib_sr)
{
uint64_t tm = fib_sr->sr_lifetime - xtimer_now_usec64();
/* check if the lifetime expired */
if ((int64_t)tm < 0) {
/* remove this sr if its lifetime expired */
fib_sr->sr_lifetime = 0;
if (fib_sr->sr_path != NULL) {
fib_sr_entry_t *elt = NULL;
LL_FOREACH(fib_sr->sr_path, elt) {
<API key>(elt->address);
}
fib_sr->sr_path = NULL;
}
/* and return an errorcode */
return -ENOENT;
}
return 0;
}
/**
* @brief Internal function:
* creates a new entry in the table entry pool for a hop in a source route
*/
static int fib_sr_new_entry(fib_table_t *table, uint8_t *addr, size_t addr_size,
fib_sr_entry_t **new_entry)
{
for (size_t i = 0; i < table->data.source_routes->entry_pool_size; ++i) {
if (table->data.source_routes->entry_pool[i].address == NULL) {
table->data.source_routes->entry_pool[i].address = <API key>(addr, addr_size);
if (table->data.source_routes->entry_pool[i].address == NULL) {
return -ENOMEM;
}
else {
(void)new_entry;
*new_entry = &table->data.source_routes->entry_pool[i];
return 0;
}
}
}
return -ENOMEM;
}
/**
* @brief Internal function:
* checks if the source route belongs to the given table
*/
static int fib_is_sr_in_table(fib_table_t *table, fib_sr_t *fib_sr)
{
for (size_t i = 0; i < table->size; ++i) {
if (&(table->data.source_routes->headers[i]) == fib_sr) {
return 0;
}
}
return -ENOENT;
}
int fib_sr_read_head(fib_table_t *table, fib_sr_t *fib_sr, kernel_pid_t *iface_id,
uint32_t *sr_flags, uint32_t *sr_lifetime)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (iface_id == NULL) || (sr_flags == NULL)
|| (sr_lifetime == NULL) || (fib_is_sr_in_table(table, fib_sr) == -ENOENT) ) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (<API key>(fib_sr) == -ENOENT) {
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
*iface_id = fib_sr->sr_iface_id;
*sr_flags = fib_sr->sr_flags;
*sr_lifetime = fib_sr->sr_lifetime - xtimer_now_usec64();
mutex_unlock(&(table->mtx_access));
return 0;
}
int <API key>(fib_table_t *table, fib_sr_t *fib_sr,
uint8_t *dst, size_t *dst_size)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (dst == NULL) || (dst_size == NULL)
|| (fib_is_sr_in_table(table, fib_sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (<API key>(fib_sr) == -ENOENT) {
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
if (fib_sr->sr_dest == NULL) {
mutex_unlock(&(table->mtx_access));
return -EHOSTUNREACH;
}
if (<API key>(fib_sr->sr_dest->address, dst, dst_size) == NULL) {
mutex_unlock(&(table->mtx_access));
return -ENOBUFS;
}
mutex_unlock(&(table->mtx_access));
return 0;
}
int fib_sr_set(fib_table_t *table, fib_sr_t *fib_sr, kernel_pid_t *sr_iface_id,
uint32_t *sr_flags, uint32_t *sr_lifetime)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (fib_is_sr_in_table(table, fib_sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (<API key>(fib_sr) == -ENOENT) {
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
if (sr_iface_id != NULL) {
fib_sr->sr_iface_id = *sr_iface_id;
}
if (sr_flags != NULL) {
fib_sr->sr_flags = *sr_flags;
}
if (sr_lifetime != NULL) {
<API key>(*sr_lifetime, &(fib_sr->sr_lifetime));
}
mutex_unlock(&(table->mtx_access));
return 0;
}
int fib_sr_delete(fib_table_t *table, fib_sr_t *fib_sr)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (fib_is_sr_in_table(table, fib_sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
fib_sr->sr_lifetime = 0;
if (fib_sr->sr_path != NULL) {
fib_sr_entry_t *elt = NULL, *tmp = NULL;
LL_FOREACH_SAFE(fib_sr->sr_path, elt, tmp) {
<API key>(elt->address);
elt->address = NULL;
LL_DELETE(fib_sr->sr_path, elt);
}
fib_sr->sr_path = NULL;
}
mutex_unlock(&(table->mtx_access));
return 0;
}
int fib_sr_next(fib_table_t *table, fib_sr_t *fib_sr, fib_sr_entry_t **sr_path_entry)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (sr_path_entry == NULL)
|| (fib_is_sr_in_table(table, fib_sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (fib_sr->sr_path == NULL) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (<API key>(fib_sr) == -ENOENT) {
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
/* if we reach the destination entry, i.e. the last entry we just return 1 */
if (*sr_path_entry == fib_sr->sr_dest) {
mutex_unlock(&(table->mtx_access));
return 1;
}
/* when we start, we pass the first entry */
if (*sr_path_entry == NULL) {
*sr_path_entry = fib_sr->sr_path;
}
else {
/* in any other case we just return the next entry */
*sr_path_entry = (*sr_path_entry)->next;
}
mutex_unlock(&(table->mtx_access));
return 0;
}
int fib_sr_search(fib_table_t *table, fib_sr_t *fib_sr, uint8_t *addr, size_t addr_size,
fib_sr_entry_t **sr_path_entry)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (addr == NULL) || (sr_path_entry == NULL)
|| (fib_is_sr_in_table(table, fib_sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (<API key>(fib_sr) == -ENOENT) {
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
fib_sr_entry_t *elt = NULL;
LL_FOREACH(fib_sr->sr_path, elt) {
size_t addr_size_match = addr_size << 3;
if (<API key>(elt->address, addr, &addr_size_match) == <API key>) {
/* temporary workaround to calm compiler */
(void)sr_path_entry;
*sr_path_entry = elt;
mutex_unlock(&(table->mtx_access));
return 0;
}
}
mutex_unlock(&(table->mtx_access));
return -EHOSTUNREACH;
}
int fib_sr_entry_append(fib_table_t *table, fib_sr_t *fib_sr,
uint8_t *addr, size_t addr_size)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (addr == NULL)
|| (fib_is_sr_in_table(table, fib_sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (<API key>(fib_sr) == -ENOENT) {
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
fib_sr_entry_t *elt = NULL;
LL_FOREACH(fib_sr->sr_path, elt) {
size_t addr_size_match = addr_size << 3;
if (<API key>(elt->address, addr, &addr_size_match) == <API key>) {
mutex_unlock(&(table->mtx_access));
return -EINVAL;
}
}
fib_sr_entry_t *new_entry[1];
int ret = fib_sr_new_entry(table, addr, addr_size, &new_entry[0]);
if (ret == 0) {
fib_sr_entry_t *tmp = fib_sr->sr_dest;
if (tmp != NULL) {
/* we append the new entry behind the former destination */
tmp->next = new_entry[0];
}
else {
/* this is also our first entry */
fib_sr->sr_path = new_entry[0];
}
fib_sr->sr_dest = new_entry[0];
}
mutex_unlock(&(table->mtx_access));
return ret;
}
int fib_sr_entry_add(fib_table_t *table, fib_sr_t *fib_sr,
fib_sr_entry_t *sr_path_entry, uint8_t *addr, size_t addr_size,
bool <API key>)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (sr_path_entry == NULL) || (addr == NULL)
|| (fib_is_sr_in_table(table, fib_sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (<API key>(fib_sr) == -ENOENT) {
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
bool found = false;
fib_sr_entry_t *elt = NULL;
LL_FOREACH(fib_sr->sr_path, elt) {
size_t addr_size_match = addr_size << 3;
if (<API key>(elt->address, addr, &addr_size_match) == <API key>) {
mutex_unlock(&(table->mtx_access));
return -EINVAL;
}
if (sr_path_entry == elt) {
found = true;
break;
}
}
int ret = -ENOENT;
if (found) {
fib_sr_entry_t *new_entry[1];
ret = fib_sr_new_entry(table, addr, addr_size, &new_entry[0]);
if (ret == 0) {
fib_sr_entry_t *remaining = sr_path_entry->next;
sr_path_entry->next = new_entry[0];
if (<API key>) {
new_entry[0]->next = remaining;
}
else {
fib_sr_entry_t *elt = NULL, *tmp = NULL;
LL_FOREACH_SAFE(remaining, elt, tmp) {
<API key>(elt->address);
elt->address = NULL;
LL_DELETE(remaining, elt);
}
new_entry[0]->next = NULL;
fib_sr->sr_dest = new_entry[0];
}
}
}
mutex_unlock(&(table->mtx_access));
return ret;
}
int fib_sr_entry_delete(fib_table_t *table, fib_sr_t *fib_sr, uint8_t *addr, size_t addr_size,
bool <API key>)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (fib_is_sr_in_table(table, fib_sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (<API key>(fib_sr) == -ENOENT) {
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
fib_sr_entry_t *elt = NULL, *tmp;
tmp = fib_sr->sr_path;
LL_FOREACH(fib_sr->sr_path, elt) {
size_t addr_size_match = addr_size << 3;
if (<API key>(elt->address, addr, &addr_size_match) == <API key>) {
<API key>(elt->address);
if (<API key>) {
tmp->next = elt->next;
}
else {
fib_sr_entry_t *elt_del = NULL, *tmp_del = NULL;
LL_FOREACH_SAFE(tmp, elt_del, tmp_del) {
<API key>(elt_del->address);
elt_del->address = NULL;
LL_DELETE(tmp, elt_del);
}
}
if (elt == fib_sr->sr_path) {
/* if we remove the first entry we must adjust the path start */
fib_sr->sr_path = elt->next;
}
if (elt == fib_sr->sr_dest) {
/* if we remove the last entry we must adjust the destination */
fib_sr->sr_dest = tmp;
}
mutex_unlock(&(table->mtx_access));
return 0;
}
tmp = elt;
}
return -ENOENT;
}
int <API key>(fib_table_t *table, fib_sr_t *fib_sr,
uint8_t *addr_old, size_t addr_old_size,
uint8_t *addr_new, size_t addr_new_size)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (addr_old == NULL) || (addr_new == NULL)
|| (fib_is_sr_in_table(table, fib_sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (<API key>(fib_sr) == -ENOENT) {
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
fib_sr_entry_t *elt = NULL, *elt_repl;
elt_repl = NULL;
LL_FOREACH(fib_sr->sr_path, elt) {
size_t addr_old_size_match = addr_old_size << 3;
size_t addr_new_size_match = addr_old_size << 3;
if (<API key>(elt->address, addr_old, &addr_old_size_match) == <API key>) {
elt_repl = elt;
}
if (<API key>(elt->address, addr_new, &addr_new_size_match) == <API key>) {
mutex_unlock(&(table->mtx_access));
return -EINVAL;
}
}
if (elt_repl != NULL) {
<API key>(elt_repl->address);
<API key> *add = <API key>(addr_new, addr_new_size);
if (add == NULL) {
/* if this happened we deleted one entry, i.e. decreased the usecount
* adding a new one was not possible since lack of memory
* so we add back the old entry, i.e. increasing the usecount
*/
<API key>(addr_old, addr_old_size);
mutex_unlock(&(table->mtx_access));
return -ENOMEM;
}
elt_repl->address = add;
}
mutex_unlock(&(table->mtx_access));
return 0;
}
int <API key>(fib_table_t *table, fib_sr_t *fib_sr, fib_sr_entry_t *sr_entry,
uint8_t *addr, size_t *addr_size)
{
mutex_lock(&(table->mtx_access));
if ((fib_sr == NULL) || (fib_is_sr_in_table(table, fib_sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
if (<API key>(fib_sr) == -ENOENT) {
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
fib_sr_entry_t *elt = NULL;
LL_FOREACH(fib_sr->sr_path, elt) {
if (elt == sr_entry) {
if (<API key>(elt->address, addr, addr_size) != NULL) {
mutex_unlock(&(table->mtx_access));
return 0;
}
else {
mutex_unlock(&(table->mtx_access));
return -ENOMEM;
}
}
}
mutex_unlock(&(table->mtx_access));
return -ENOENT;
}
/**
* @brief helper function to search a partial path to a given destination,
* and iff successful to create a new source route
*
* @param[in] table the fib table the entry should be added to
* @param[in] dst pointer to the destination address bytes
* @param[in] dst_size the size in bytes of the destination address type
* @param[in] check_free_entry position to start the search for a free entry
* @param[out] error the state of of this operation when finished
*
* @return pointer to the new source route on success
* NULL otherwise
*/
static fib_sr_t* <API key>(fib_table_t *table, uint8_t *dst, size_t dst_size,
int check_free_entry, int *error) {
fib_sr_t* hit = NULL;
for (size_t i = 0; i < table->size; ++i) {
if (table->data.source_routes->headers[i].sr_lifetime != 0) {
fib_sr_entry_t *elt = NULL;
LL_FOREACH(table->data.source_routes->headers[i].sr_path, elt) {
size_t addr_size_match = dst_size << 3;
if (<API key>(elt->address, dst, &addr_size_match) == <API key>) {
/* we create a new sr */
if (check_free_entry == -1) {
/* we have no room to create a new sr
* so we just return and NOT tell the RPs to find a route
* since we cannot save it
*/
*error = -ENOBUFS;
return NULL;
}
else {
/* we check if there is a free place for the new sr */
fib_sr_t *new_sr = NULL;
for (size_t j = check_free_entry; j < table->size; ++j) {
if (table->data.source_routes->headers[j].sr_lifetime != 0) {
/* not this one, maybe the next one */
continue;
}
else {
/* there it is, so we copy the header */
new_sr = &table->data.source_routes->headers[j];
new_sr->sr_iface_id = table->data.source_routes->headers[i].sr_iface_id;
new_sr->sr_flags = table->data.source_routes->headers[i].sr_flags;
new_sr->sr_lifetime = table->data.source_routes->headers[i].sr_lifetime;
new_sr->sr_path = NULL;
/* and the path until the searched destination */
fib_sr_entry_t *elt_iter = NULL, *elt_add = NULL;
LL_FOREACH(table->data.source_routes->headers[i].sr_path, elt_iter) {
fib_sr_entry_t *new_entry;
if (fib_sr_new_entry(table, elt_iter->address->address,
elt_iter->address->address_size,
&new_entry) != 0) {
/* we could not create a new entry
* so we return to clean up the partial route
*/
*error = -ENOBUFS;
return new_sr;
}
if (new_sr->sr_path == NULL) {
new_sr->sr_path = new_entry;
elt_add = new_sr->sr_path;
}
else {
elt_add->next = new_entry;
elt_add = elt_add->next;
}
if (elt_iter == elt) {
/* we copied until the destination */
new_sr->sr_dest = new_entry;
hit = new_sr;
/* tell the RPs that a new sr has been created
* the size and the flags parameters are ignored
*/
if (fib_signal_rp(table, <API key>,
(uint8_t *)new_sr, 0, 0) != 0) {
/* if no RP can handle the source route
* then the host is not directly reachable
*/
*error = -EHOSTUNREACH;
}
/* break from iterating for copy */
break;
}
}
}
}
/* break from iterating the found path */
break;
}
}
}
if (hit != NULL) {
/* break iterating all sr since we have a path now */
break;
}
}
}
return hit;
}
int fib_sr_get_route(fib_table_t *table, uint8_t *dst, size_t dst_size, kernel_pid_t *sr_iface_id,
uint32_t *sr_flags,
uint8_t *addr_list, size_t *addr_list_elements, size_t *element_size,
bool reverse, fib_sr_t **fib_sr)
{
mutex_lock(&(table->mtx_access));
if ((dst == NULL) || (sr_iface_id == NULL) || (sr_flags == NULL)
|| (addr_list == NULL) || (addr_list_elements == NULL) || (element_size == NULL)) {
mutex_unlock(&(table->mtx_access));
return -EFAULT;
}
fib_sr_t *hit = NULL;
fib_sr_t *tmp_hit = NULL;
int check_free_entry = -1;
bool skip = (fib_sr != NULL) && (*fib_sr != NULL)?true:false;
/* Case 1 - check if we know a direct route */
for (size_t i = 0; i < table->size; ++i) {
if (<API key>(&table->data.source_routes->headers[i]) == -ENOENT) {
/* expired, so skip this sr and remember its position */
if (check_free_entry == -1) {
/* we want to fill up the source routes from the beginning */
check_free_entry = i;
}
continue;
}
if( skip ) {
if(*fib_sr == &table->data.source_routes->headers[i]) {
skip = false;
}
/* we skip all entries upon the consecutive one to start search */
continue;
}
size_t addr_size_match = dst_size << 3;
if (<API key>(table->data.source_routes->headers[i].sr_dest->address,
dst, &addr_size_match) == <API key>) {
if (*sr_flags == table->data.source_routes->headers[i].sr_flags) {
/* found a perfect matching sr, no need to search further */
hit = &table->data.source_routes->headers[i];
tmp_hit = NULL;
if (check_free_entry == -1) {
check_free_entry = i;
}
break;
}
else {
/* found a sr to the destination but with different flags,
* maybe we find a better one.
*/
tmp_hit = &table->data.source_routes->headers[i];
}
}
}
if (hit == NULL) {
/* we didn't find a perfect sr, but one with distinct flags */
hit = tmp_hit;
}
/* Case 2 - if no hit is found check if there is a matching entry in one sr_path
* @note the first match wins, if we find one we will NOT continue searching,
* since this search is very expensive in terms of compare operations
*/
if (hit == NULL) {
int error = 0;
hit = <API key>(table, dst, dst_size, check_free_entry, &error);
if ((error != 0) && (error != -EHOSTUNREACH)) {
/* something went wrong, so we clean up our mess
*
* @note we could handle -EHOSTUNREACH differently here,
* since it says that we have a partial source route but no RP
* to manage it.
* That's why I let it pass for now.
*/
if (hit != NULL) {
hit->sr_lifetime = 0;
if (hit->sr_path != NULL) {
fib_sr_entry_t *elt = NULL, *tmp = NULL;
LL_FOREACH_SAFE(hit->sr_path, elt, tmp) {
<API key>(elt->address);
elt->address = NULL;
LL_DELETE(hit->sr_path, elt);
}
hit->sr_path = NULL;
}
}
mutex_unlock(&(table->mtx_access));
return error;
}
}
/* Final step - copy the list in the desired order */
if (hit != NULL) {
/* store the current hit to enable consecutive searches */
if( fib_sr != NULL ) {
*fib_sr = hit;
}
/* check the list size and if the sr entries will fit */
int count;
fib_sr_entry_t *elt = NULL;
LL_COUNT(hit->sr_path, elt, count);
if (((size_t)count > *addr_list_elements)
|| (sizeof(hit->sr_path->address->address) > *element_size)) {
*addr_list_elements = count;
*element_size = sizeof(hit->sr_path->address->address);
mutex_unlock(&(table->mtx_access));
return -ENOBUFS;
}
/* start copy the individual entries in the desired order */
uint8_t *next_entry = addr_list;
int one_address_size = *element_size;
if (reverse) {
/* we move to the last list element */
next_entry += (count - 1) * sizeof(hit->sr_path->address->address);
/* and set the storing direction during the iteration */
one_address_size *= -1;
}
elt = NULL;
LL_FOREACH(hit->sr_path, elt) {
size_t tmp_size = sizeof(hit->sr_path->address->address);
<API key>(elt->address, next_entry, &tmp_size);
next_entry += one_address_size;
}
*sr_iface_id = hit->sr_iface_id;
*sr_flags = hit->sr_flags;
*addr_list_elements = count;
*element_size = sizeof(hit->sr_path->address->address);
}
else {
/* trigger RPs for route discovery */
fib_signal_rp(table, <API key>, dst, dst_size, *sr_flags);
mutex_unlock(&(table->mtx_access));
return -EHOSTUNREACH;
}
mutex_unlock(&(table->mtx_access));
if (tmp_hit == NULL) {
return 0;
}
else {
return 1;
}
}
/* print functions */
void fib_print_notify_rp(fib_table_t *table)
{
mutex_lock(&(table->mtx_access));
for (size_t i = 0; i < <API key>; ++i) {
printf("[fib_print_notify_rp] pid[%d]: %d\n", (int)i, (int)(table->notify_rp[i]));
}
mutex_unlock(&(table->mtx_access));
}
void fib_print_fib_table(fib_table_t *table)
{
mutex_lock(&(table->mtx_access));
for (size_t i = 0; i < table->size; ++i) {
printf("[fib_print_table] %d) iface_id: %d, global: %p, next hop: %p, lifetime: %"PRIu32"\n",
(int)i, (int)table->data.entries[i].iface_id,
(void *)table->data.entries[i].global,
(void *)table->data.entries[i].next_hop,
(uint32_t)(table->data.entries[i].lifetime / 1000));
}
mutex_unlock(&(table->mtx_access));
}
void fib_print_sr(fib_table_t *table, fib_sr_t *sr)
{
/* does not adjust the lifetime */
mutex_lock(&(table->mtx_access));
if ((sr == NULL) || (fib_is_sr_in_table(table, sr) == -ENOENT)) {
mutex_unlock(&(table->mtx_access));
return;
}
printf("\n-= Source route (%p) =-\nIface: %d\nflags: %x\npath: %p\ndest: ",
(void *)sr, sr->sr_iface_id, (unsigned int)sr->sr_flags, (void *)sr->sr_path);
if (sr->sr_dest != NULL) {
<API key>(sr->sr_dest->address);
} else {
puts("Not set.");
}
fib_sr_entry_t *nxt = sr->sr_path;
while (nxt) {
<API key>(nxt->address);
nxt = nxt->next;
}
printf("-= END (%p) =-\n", (void *)sr);
mutex_unlock(&(table->mtx_access));
}
static void fib_print_address(<API key> *entry)
{
uint8_t address[<API key>];
size_t addr_size = <API key>;
uint8_t *ret = <API key>(entry, address, &addr_size);
if (ret == address) {
#ifdef MODULE_IPV6_ADDR
if (addr_size == sizeof(ipv6_addr_t)) {
printf("%-" FIB_ADDR_PRINT_LENS "s",
ipv6_addr_to_str(addr_str, (ipv6_addr_t *) address, sizeof(addr_str)));
return;
}
#endif
for (size_t i = 0; i < <API key>; ++i) {
if (i <= addr_size) {
printf("%02x", address[i]);
}
else {
printf(" ");
}
}
#ifdef MODULE_IPV6_ADDR
/* print trailing whitespaces */
for (size_t i = 0; i < FIB_ADDR_PRINT_LEN - (<API key> * 2); ++i) {
printf(" ");
}
#endif
}
}
void fib_print_routes(fib_table_t *table)
{
mutex_lock(&(table->mtx_access));
uint64_t now = xtimer_now_usec64();
if (table->table_type == FIB_TABLE_TYPE_SH) {
printf("%-" FIB_ADDR_PRINT_LENS "s %-17s %-" FIB_ADDR_PRINT_LENS "s %-10s %-16s"
" Interface\n" , "Destination", "Flags", "Next Hop", "Flags", "Expires");
for (size_t i = 0; i < table->size; ++i) {
if (table->data.entries[i].lifetime != 0) {
fib_print_address(table->data.entries[i].global);
printf(" 0x%08"PRIx32" ", table->data.entries[i].global_flags);
if(table->data.entries[i].global_flags & <API key>) {
uint32_t prefix = (table->data.entries[i].global_flags
& <API key>);
printf("N /%-3d ", (int)(prefix >> <API key>));
} else {
printf("H ");
}
fib_print_address(table->data.entries[i].next_hop);
printf(" 0x%08"PRIx32" ", table->data.entries[i].next_hop_flags);
if (table->data.entries[i].lifetime != <API key>) {
uint64_t tm = table->data.entries[i].lifetime - now;
/* we must interpret the values as signed */
if ((int64_t)tm < 0 ) {
printf("%-16s ", "EXPIRED");
}
else {
printf("%"PRIu32".%05"PRIu32, (uint32_t)(tm / 1000000),
(uint32_t)(tm % 1000000));
}
}
else {
printf("%-16s ", "NEVER");
}
printf("%d\n", (int)table->data.entries[i].iface_id);
}
}
}
else if (table->table_type == FIB_TABLE_TYPE_SR) {
printf("%-" FIB_ADDR_PRINT_LENS "s %-" FIB_ADDR_PRINT_LENS "s %-6s %-16s Interface\n"
, "SR Destination", "SR First Hop", "SR Flags", "Expires");
for (size_t i = 0; i < table->size; ++i) {
if (table->data.source_routes->headers[i].sr_lifetime != 0) {
fib_print_address(table->data.source_routes->headers[i].sr_dest->address);
fib_print_address(table->data.source_routes->headers[i].sr_path->address);
printf(" 0x%04"PRIx32" ", table->data.source_routes->headers[i].sr_flags);
if (table->data.source_routes->headers[i].sr_lifetime != <API key>) {
uint64_t tm = table->data.source_routes->headers[i].sr_lifetime - now;
/* we must interpret the values as signed */
if ((int64_t)tm < 0 ) {
printf("%-16s ", "EXPIRED");
}
else {
printf("%"PRIu32".%05"PRIu32, (uint32_t)(tm / 1000000),
(uint32_t)(tm % 1000000));
}
}
else {
printf("%-16s ", "NEVER");
}
printf("%d\n", (int)table->data.source_routes->headers[i].sr_iface_id);
}
}
}
mutex_unlock(&(table->mtx_access));
}
#if FIB_DEVEL_HELPER
int <API key>(fib_table_t *table, uint64_t *lifetime, uint8_t *dst,
size_t dst_size)
{
if (table->table_type == FIB_TABLE_TYPE_SH) {
size_t count = 1;
fib_entry_t *entry[count];
int ret = fib_find_entry(table, dst, dst_size, &(entry[0]), &count);
if (ret == 1 ) {
/* only return lifetime of exact matches */
*lifetime = entry[0]->lifetime;
return 0;
}
return -EHOSTUNREACH;
}
else if (table->table_type == FIB_TABLE_TYPE_SR) {
size_t addr_size_match = dst_size << 3;
/* first hit wins here */
for (size_t i = 0; i < table->size; ++i) {
if (<API key>(table->data.source_routes->headers[i].sr_dest->address,
dst, &addr_size_match) == <API key>) {
*lifetime = table->data.source_routes->headers[i].sr_lifetime;
return 0;
}
}
return -EHOSTUNREACH;
}
return -EFAULT;
}
#endif
|
/*
| Welcome to Arco AM/PM Mini-Market. We
| would like to advise our customers
| that any individual who offers to
| pump gas, wash windows or solicit
| products is not employed by or
| associated with this facility. We
| discourage any contact with these
| individuals and ask that you report
| any problems to uniformed personal
| inside. Thankyou for shopping at
| Arco, and have a nice day.
*/
#include <config.h>
#include <stdlib.h>
#include <stdio.h>
#include "librsync.h"
/*
* TODO: (Suggestion by tridge) Add a function which outputs a
* complete text description of a job, including only the fields
* relevant to the current encoding function.
*/
/** \brief Translate from rs_result to human-readable messages. */
char const *rs_strerror(rs_result r)
{
switch (r) {
case RS_DONE:
return "OK";
case RS_RUNNING:
return "still running";
case RS_BLOCKED:
return "blocked waiting for input or output buffers";
case RS_BAD_MAGIC:
return "bad magic number at start of stream";
case RS_INPUT_ENDED:
return "unexpected end of input";
case RS_CORRUPT:
return "stream corrupt";
case RS_UNIMPLEMENTED:
return "unimplemented case";
case RS_MEM_ERROR:
return "out of memory";
case RS_IO_ERROR:
return "IO error";
case RS_SYNTAX_ERROR:
return "bad command line syntax";
case RS_INTERNAL_ERROR:
return "library internal error";
default:
return "unexplained problem";
}
}
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_25) on Thu Sep 26 14:06:50 PDT 2013 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>LognormalDistr</title>
<meta name="date" content="2013-09-26">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="LognormalDistr";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar_top">
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/LognormalDistr.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/cloudbus/cloudsim/distributions/GammaDistr.html" title="class in org.cloudbus.cloudsim.distributions"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/cloudbus/cloudsim/distributions/LomaxDistribution.html" title="class in org.cloudbus.cloudsim.distributions"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/cloudbus/cloudsim/distributions/LognormalDistr.html" target="_top">Frames</a></li>
<li><a href="LognormalDistr.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<div class="subTitle">org.cloudbus.cloudsim.distributions</div>
<h2 title="Class LognormalDistr" class="title">Class LognormalDistr</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.cloudbus.cloudsim.distributions.LognormalDistr</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><a href="../../../../org/cloudbus/cloudsim/distributions/<API key>.html" title="interface in org.cloudbus.cloudsim.distributions"><API key></a></dd>
</dl>
<hr>
<br>
<pre>public class <span class="strong">LognormalDistr</span>
extends java.lang.Object
implements <a href="../../../../org/cloudbus/cloudsim/distributions/<API key>.html" title="interface in org.cloudbus.cloudsim.distributions"><API key></a></pre>
<div class="block">The Class LognormalDistr.</div>
<dl><dt><span class="strong">Since:</span></dt>
<dd>CloudSim Toolkit 1.0</dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../org/cloudbus/cloudsim/distributions/LognormalDistr.html#LognormalDistr(double, double)">LognormalDistr</a></strong>(double mean,
double dev)</code>
<div class="block">Instantiates a new lognormal distr.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../../org/cloudbus/cloudsim/distributions/LognormalDistr.html#LognormalDistr(java.util.Random, double, double)">LognormalDistr</a></strong>(java.util.Random seed,
double mean,
double dev)</code>
<div class="block">Instantiates a new lognormal distr.</div>
</td>
</tr>
</table>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="method_summary">
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>double</code></td>
<td class="colLast"><code><strong><a href="../../../../org/cloudbus/cloudsim/distributions/LognormalDistr.html#sample()">sample</a></strong>()</code>
<div class="block">Sample the random number generator.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="<API key>.lang.Object">
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
</a>
<h3>Constructor Detail</h3>
<a name="LognormalDistr(java.util.Random, double, double)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>LognormalDistr</h4>
<pre>public LognormalDistr(java.util.Random seed,
double mean,
double dev)</pre>
<div class="block">Instantiates a new lognormal distr.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>seed</code> - the seed</dd><dd><code>mean</code> - the mean</dd><dd><code>dev</code> - the dev</dd></dl>
</li>
</ul>
<a name="LognormalDistr(double, double)">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>LognormalDistr</h4>
<pre>public LognormalDistr(double mean,
double dev)</pre>
<div class="block">Instantiates a new lognormal distr.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>mean</code> - the mean</dd><dd><code>dev</code> - the dev</dd></dl>
</li>
</ul>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="method_detail">
</a>
<h3>Method Detail</h3>
<a name="sample()">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>sample</h4>
<pre>public double sample()</pre>
<div class="block"><strong>Description copied from interface: <code><a href="../../../../org/cloudbus/cloudsim/distributions/<API key>.html#sample()"><API key></a></code></strong></div>
<div class="block">Sample the random number generator.</div>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../org/cloudbus/cloudsim/distributions/<API key>.html#sample()">sample</a></code> in interface <code><a href="../../../../org/cloudbus/cloudsim/distributions/<API key>.html" title="interface in org.cloudbus.cloudsim.distributions"><API key></a></code></dd>
<dt><span class="strong">Returns:</span></dt><dd>The sample</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/LognormalDistr.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/cloudbus/cloudsim/distributions/GammaDistr.html" title="class in org.cloudbus.cloudsim.distributions"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/cloudbus/cloudsim/distributions/LomaxDistribution.html" title="class in org.cloudbus.cloudsim.distributions"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/cloudbus/cloudsim/distributions/LognormalDistr.html" target="_top">Frames</a></li>
<li><a href="LognormalDistr.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
</a></div>
</body>
</html>
|
package crazypants.enderio.machine.capbank.network;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import cofh.api.energy.<API key>;
import crazypants.enderio.EnderIO;
import crazypants.enderio.machine.capbank.TileCapBank;
public class InventoryImpl implements IInventory {
public static boolean isInventoryEmtpy(TileCapBank cap) {
for (ItemStack st : cap.getInventory()) {
if(st != null) {
return false;
}
}
return true;
}
public static boolean isInventoryEmtpy(ItemStack[] inv) {
if(inv == null) {
return true;
}
for (ItemStack st : inv) {
if(st != null) {
return false;
}
}
return true;
}
private ItemStack[] inventory;
private TileCapBank capBank;
public InventoryImpl() {
}
public TileCapBank getCapBank() {
return capBank;
}
public void setCapBank(TileCapBank cap) {
capBank = cap;
if(cap == null) {
inventory = null;
return;
}
inventory = cap.getInventory();
}
public boolean isEmtpy() {
return isInventoryEmtpy(inventory);
}
public ItemStack[] getStacks() {
return inventory;
}
@Override
public ItemStack getStackInSlot(int slot) {
if(inventory == null) {
return null;
}
if(slot < 0 || slot >= inventory.length) {
return null;
}
return inventory[slot];
}
@Override
public ItemStack decrStackSize(int fromSlot, int amount) {
if(inventory == null) {
return null;
}
if(fromSlot < 0 || fromSlot >= inventory.length) {
return null;
}
ItemStack item = inventory[fromSlot];
if(item == null) {
return null;
}
if(item.stackSize <= amount) {
ItemStack result = item.copy();
inventory[fromSlot] = null;
return result;
}
item.stackSize -= amount;
return item.copy();
}
@Override
public void <API key>(int slot, ItemStack itemstack) {
if(inventory == null) {
return;
}
if(slot < 0 || slot >= inventory.length) {
return;
}
inventory[slot] = itemstack;
}
@Override
public int getSizeInventory() {
return 4;
}
@Override
public ItemStack <API key>(int p_70304_1_) {
return null;
}
@Override
public String getInventoryName() {
return EnderIO.blockCapBank.getUnlocalizedName() + ".name";
}
@Override
public boolean <API key>() {
return false;
}
@Override
public int <API key>() {
return 1;
}
@Override
public boolean isUseableByPlayer(EntityPlayer p_70300_1_) {
return true;
}
@Override
public boolean isItemValidForSlot(int slot, ItemStack itemstack) {
if(itemstack == null) {
return false;
}
return itemstack.getItem() instanceof <API key>;
}
@Override
public void openInventory() {
}
@Override
public void closeInventory() {
}
@Override
public void markDirty() {
}
}
|
-- +goose Up
-- SQL in section 'Up' is executed when this migration is applied
alter table deliveryservice add logs_enabled tinyint(1);
-- +goose Down
-- SQL section 'Down' is executed when this migration is rolled back
alter table deliveryservice drop column logs_enabled;
|
// Use, modification and distribution are subject to the
# include <pch.hpp>
#ifndef <API key>
# define <API key>
#endif
#include <boost/math/tr1.hpp>
#include <boost/math/special_functions/next.hpp>
#include "c_policy.hpp"
namespace boost{ namespace math{ namespace tr1{
extern "C" long double BOOST_MATH_TR1_DECL boost_nexttowardl <API key>(long double x, long double y) <API key>
{
return c_policies::nextafter <API key>(x, y);
}
}}}
|
"""Support for MySensors covers."""
from homeassistant.components import mysensors
from homeassistant.components.cover import ATTR_POSITION, DOMAIN, CoverDevice
from homeassistant.const import STATE_OFF, STATE_ON
async def <API key>(
hass, config, async_add_entities, discovery_info=None):
"""Set up the mysensors platform for covers."""
mysensors.<API key>(
hass, DOMAIN, discovery_info, MySensorsCover,
async_add_entities=async_add_entities)
class MySensorsCover(mysensors.device.MySensorsEntity, CoverDevice):
"""Representation of the value of a MySensors Cover child node."""
@property
def assumed_state(self):
"""Return True if unable to access real state of entity."""
return self.gateway.optimistic
@property
def is_closed(self):
"""Return True if cover is closed."""
set_req = self.gateway.const.SetReq
if set_req.V_DIMMER in self._values:
return self._values.get(set_req.V_DIMMER) == 0
return self._values.get(set_req.V_LIGHT) == STATE_OFF
@property
def <API key>(self):
"""Return current position of cover.
None is unknown, 0 is closed, 100 is fully open.
"""
set_req = self.gateway.const.SetReq
return self._values.get(set_req.V_DIMMER)
async def async_open_cover(self, **kwargs):
"""Move the cover up."""
set_req = self.gateway.const.SetReq
self.gateway.set_child_value(
self.node_id, self.child_id, set_req.V_UP, 1)
if self.gateway.optimistic:
# Optimistically assume that cover has changed state.
if set_req.V_DIMMER in self._values:
self._values[set_req.V_DIMMER] = 100
else:
self._values[set_req.V_LIGHT] = STATE_ON
self.<API key>()
async def async_close_cover(self, **kwargs):
"""Move the cover down."""
set_req = self.gateway.const.SetReq
self.gateway.set_child_value(
self.node_id, self.child_id, set_req.V_DOWN, 1)
if self.gateway.optimistic:
# Optimistically assume that cover has changed state.
if set_req.V_DIMMER in self._values:
self._values[set_req.V_DIMMER] = 0
else:
self._values[set_req.V_LIGHT] = STATE_OFF
self.<API key>()
async def <API key>(self, **kwargs):
"""Move the cover to a specific position."""
position = kwargs.get(ATTR_POSITION)
set_req = self.gateway.const.SetReq
self.gateway.set_child_value(
self.node_id, self.child_id, set_req.V_DIMMER, position)
if self.gateway.optimistic:
# Optimistically assume that cover has changed state.
self._values[set_req.V_DIMMER] = position
self.<API key>()
async def async_stop_cover(self, **kwargs):
"""Stop the device."""
set_req = self.gateway.const.SetReq
self.gateway.set_child_value(
self.node_id, self.child_id, set_req.V_STOP, 1)
|
"""Tests for Airly."""
|
/**
* This class is generated by jOOQ
*/
package io.cattle.platform.core.model.tables;
/**
* This class is generated by jOOQ.
*/
@javax.annotation.Generated(value = { "http:
comments = "This class is generated by jOOQ")
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class AgentTable extends org.jooq.impl.TableImpl<io.cattle.platform.core.model.tables.records.AgentRecord> {
private static final long serialVersionUID = -328097319;
/**
* The singleton instance of <code>cattle.agent</code>
*/
public static final io.cattle.platform.core.model.tables.AgentTable AGENT = new io.cattle.platform.core.model.tables.AgentTable();
/**
* The class holding records for this type
*/
@Override
public java.lang.Class<io.cattle.platform.core.model.tables.records.AgentRecord> getRecordType() {
return io.cattle.platform.core.model.tables.records.AgentRecord.class;
}
/**
* The column <code>cattle.agent.id</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.Long> ID = createField("id", org.jooq.impl.SQLDataType.BIGINT.nullable(false), this, "");
/**
* The column <code>cattle.agent.name</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.String> NAME = createField("name", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, "");
/**
* The column <code>cattle.agent.account_id</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.Long> ACCOUNT_ID = createField("account_id", org.jooq.impl.SQLDataType.BIGINT, this, "");
/**
* The column <code>cattle.agent.kind</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.String> KIND = createField("kind", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, "");
/**
* The column <code>cattle.agent.uuid</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.String> UUID = createField("uuid", org.jooq.impl.SQLDataType.VARCHAR.length(128).nullable(false), this, "");
/**
* The column <code>cattle.agent.description</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.String> DESCRIPTION = createField("description", org.jooq.impl.SQLDataType.VARCHAR.length(1024), this, "");
/**
* The column <code>cattle.agent.state</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.String> STATE = createField("state", org.jooq.impl.SQLDataType.VARCHAR.length(128).nullable(false), this, "");
/**
* The column <code>cattle.agent.created</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.util.Date> CREATED = createField("created", org.jooq.impl.SQLDataType.TIMESTAMP.asConvertedDataType(new io.cattle.platform.db.jooq.converter.DateConverter()), this, "");
/**
* The column <code>cattle.agent.removed</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.util.Date> REMOVED = createField("removed", org.jooq.impl.SQLDataType.TIMESTAMP.asConvertedDataType(new io.cattle.platform.db.jooq.converter.DateConverter()), this, "");
/**
* The column <code>cattle.agent.remove_time</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.util.Date> REMOVE_TIME = createField("remove_time", org.jooq.impl.SQLDataType.TIMESTAMP.asConvertedDataType(new io.cattle.platform.db.jooq.converter.DateConverter()), this, "");
/**
* The column <code>cattle.agent.data</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.util.Map<String,Object>> DATA = createField("data", org.jooq.impl.SQLDataType.CLOB.length(16777215).asConvertedDataType(new io.cattle.platform.db.jooq.converter.DataConverter()), this, "");
/**
* The column <code>cattle.agent.uri</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.String> URI = createField("uri", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, "");
/**
* The column <code>cattle.agent.managed_config</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.Boolean> MANAGED_CONFIG = createField("managed_config", org.jooq.impl.SQLDataType.BIT.nullable(false).defaulted(true), this, "");
/**
* The column <code>cattle.agent.agent_group_id</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.Long> AGENT_GROUP_ID = createField("agent_group_id", org.jooq.impl.SQLDataType.BIGINT, this, "");
/**
* The column <code>cattle.agent.zone_id</code>.
*/
public final org.jooq.TableField<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.Long> ZONE_ID = createField("zone_id", org.jooq.impl.SQLDataType.BIGINT, this, "");
/**
* Create a <code>cattle.agent</code> table reference
*/
public AgentTable() {
this("agent", null);
}
/**
* Create an aliased <code>cattle.agent</code> table reference
*/
public AgentTable(java.lang.String alias) {
this(alias, io.cattle.platform.core.model.tables.AgentTable.AGENT);
}
private AgentTable(java.lang.String alias, org.jooq.Table<io.cattle.platform.core.model.tables.records.AgentRecord> aliased) {
this(alias, aliased, null);
}
private AgentTable(java.lang.String alias, org.jooq.Table<io.cattle.platform.core.model.tables.records.AgentRecord> aliased, org.jooq.Field<?>[] parameters) {
super(alias, io.cattle.platform.core.model.CattleTable.CATTLE, aliased, parameters, "");
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Identity<io.cattle.platform.core.model.tables.records.AgentRecord, java.lang.Long> getIdentity() {
return io.cattle.platform.core.model.Keys.IDENTITY_AGENT;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.UniqueKey<io.cattle.platform.core.model.tables.records.AgentRecord> getPrimaryKey() {
return io.cattle.platform.core.model.Keys.KEY_AGENT_PRIMARY;
}
/**
* {@inheritDoc}
*/
@Override
public java.util.List<org.jooq.UniqueKey<io.cattle.platform.core.model.tables.records.AgentRecord>> getKeys() {
return java.util.Arrays.<org.jooq.UniqueKey<io.cattle.platform.core.model.tables.records.AgentRecord>>asList(io.cattle.platform.core.model.Keys.KEY_AGENT_PRIMARY, io.cattle.platform.core.model.Keys.<API key>);
}
/**
* {@inheritDoc}
*/
@Override
public java.util.List<org.jooq.ForeignKey<io.cattle.platform.core.model.tables.records.AgentRecord, ?>> getReferences() {
return java.util.Arrays.<org.jooq.ForeignKey<io.cattle.platform.core.model.tables.records.AgentRecord, ?>>asList(io.cattle.platform.core.model.Keys.<API key>, io.cattle.platform.core.model.Keys.<API key>, io.cattle.platform.core.model.Keys.FK_AGENT__ZONE_ID);
}
/**
* {@inheritDoc}
*/
@Override
public io.cattle.platform.core.model.tables.AgentTable as(java.lang.String alias) {
return new io.cattle.platform.core.model.tables.AgentTable(alias, this);
}
/**
* Rename this table
*/
public io.cattle.platform.core.model.tables.AgentTable rename(java.lang.String name) {
return new io.cattle.platform.core.model.tables.AgentTable(name, null);
}
}
|
import { expect } from 'chai';
import parse from 'url-parse';
import { buildDfpVideoUrl, buildAdpodVideoUrl } from 'modules/dfpAdServerVideo.js';
import adUnit from 'test/fixtures/video/adUnit.json';
import * as utils from 'src/utils.js';
import { config } from 'src/config.js';
import { targeting } from 'src/targeting.js';
import { auctionManager } from 'src/auctionManager.js';
import { gdprDataHandler, uspDataHandler } from 'src/adapterManager.js';
import * as adpod from 'modules/adpod.js';
import { server } from 'test/mocks/xhr.js';
const bid = {
videoCacheKey: 'abc',
adserverTargeting: {
hb_uuid: 'abc',
hb_cache_id: 'abc',
},
};
describe('The DFP video support module', function () {
it('should make a legal request URL when given the required params', function () {
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bid,
params: {
'iu': 'my/adUnit',
'description_url': 'someUrl.com',
}
}));
expect(url.protocol).to.equal('https:');
expect(url.host).to.equal('securepubads.g.doubleclick.net');
const queryParams = utils.parseQS(url.query);
expect(queryParams).to.have.property('correlator');
expect(queryParams).to.have.property('description_url', 'someUrl.com');
expect(queryParams).to.have.property('env', 'vp');
expect(queryParams).to.have.property('gdfp_req', '1');
expect(queryParams).to.have.property('iu', 'my/adUnit');
expect(queryParams).to.have.property('output', 'vast');
expect(queryParams).to.have.property('sz', '640x480');
expect(queryParams).to.have.property('<API key>', '1');
expect(queryParams).to.have.property('url');
});
it('can take an adserver url as a parameter', function () {
const bidCopy = utils.deepClone(bid);
bidCopy.vastUrl = 'vastUrl.example';
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
url: 'https://video.adserver.example/',
}));
expect(url.host).to.equal('video.adserver.example');
const queryObject = utils.parseQS(url.query);
expect(queryObject.description_url).to.equal('vastUrl.example');
});
it('requires a params object or url', function () {
const url = buildDfpVideoUrl({
adUnit: adUnit,
bid: bid,
});
expect(url).to.be.undefined;
});
it('overwrites url params when both url and params object are given', function () {
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bid,
url: 'https://video.adserver.example/ads?sz=640x480&iu=/123/aduniturl&impl=s',
params: { iu: 'my/adUnit' }
}));
const queryObject = utils.parseQS(url.query);
expect(queryObject.iu).to.equal('my/adUnit');
});
it('should override param defaults with user-provided ones', function () {
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bid,
params: {
'iu': 'my/adUnit',
'output': 'vast',
}
}));
expect(utils.parseQS(url.query)).to.have.property('output', 'vast');
});
it('should include the cache key and adserver targeting in cust_params', function () {
const bidCopy = utils.deepClone(bid);
bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, {
hb_adid: 'ad_id',
});
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
params: {
'iu': 'my/adUnit'
}
}));
const queryObject = utils.parseQS(url.query);
const customParams = utils.parseQS('?' + decodeURIComponent(queryObject.cust_params));
expect(customParams).to.have.property('hb_adid', 'ad_id');
expect(customParams).to.have.property('hb_uuid', bid.videoCacheKey);
expect(customParams).to.have.property('hb_cache_id', bid.videoCacheKey);
});
it('should include the us_privacy key when USP Consent is available', function () {
let uspDataHandlerStub = sinon.stub(uspDataHandler, 'getConsentData');
uspDataHandlerStub.returns('1YYY');
const bidCopy = utils.deepClone(bid);
bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, {
hb_adid: 'ad_id',
});
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
params: {
'iu': 'my/adUnit'
}
}));
const queryObject = utils.parseQS(url.query);
expect(queryObject.us_privacy).to.equal('1YYY');
uspDataHandlerStub.restore();
});
it('should not include the us_privacy key when USP Consent is not available', function () {
const bidCopy = utils.deepClone(bid);
bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, {
hb_adid: 'ad_id',
});
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
params: {
'iu': 'my/adUnit'
}
}));
const queryObject = utils.parseQS(url.query);
expect(queryObject.us_privacy).to.equal(undefined);
});
it('should include the GDPR keys when GDPR Consent is available', function () {
let gdprDataHandlerStub = sinon.stub(gdprDataHandler, 'getConsentData');
gdprDataHandlerStub.returns({
gdprApplies: true,
consentString: 'consent',
addtlConsent: 'moreConsent'
});
const bidCopy = utils.deepClone(bid);
bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, {
hb_adid: 'ad_id',
});
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
params: {
'iu': 'my/adUnit'
}
}));
const queryObject = utils.parseQS(url.query);
expect(queryObject.gdpr).to.equal('1');
expect(queryObject.gdpr_consent).to.equal('consent');
expect(queryObject.addtl_consent).to.equal('moreConsent');
gdprDataHandlerStub.restore();
});
it('should not include the GDPR keys when GDPR Consent is not available', function () {
const bidCopy = utils.deepClone(bid);
bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, {
hb_adid: 'ad_id',
});
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
params: {
'iu': 'my/adUnit'
}
}));
const queryObject = utils.parseQS(url.query);
expect(queryObject.gdpr).to.equal(undefined);
expect(queryObject.gdpr_consent).to.equal(undefined);
expect(queryObject.addtl_consent).to.equal(undefined);
});
it('should only include the GDPR keys for GDPR Consent fields with values', function () {
let gdprDataHandlerStub = sinon.stub(gdprDataHandler, 'getConsentData');
gdprDataHandlerStub.returns({
gdprApplies: true,
consentString: 'consent',
});
const bidCopy = utils.deepClone(bid);
bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, {
hb_adid: 'ad_id',
});
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
params: {
'iu': 'my/adUnit'
}
}));
const queryObject = utils.parseQS(url.query);
expect(queryObject.gdpr).to.equal('1');
expect(queryObject.gdpr_consent).to.equal('consent');
expect(queryObject.addtl_consent).to.equal(undefined);
gdprDataHandlerStub.restore();
});
describe('special targeting unit test', function () {
const allTargetingData = {
'hb_format': 'video',
'hb_source': 'client',
'hb_size': '640x480',
'hb_pb': '5.00',
'hb_adid': '2c4f6cc3ba128a',
'hb_bidder': 'testBidder2',
'<API key>': 'video',
'<API key>': 'client',
'hb_size_testBidder2': '640x480',
'hb_pb_testBidder2': '5.00',
'hb_adid_testBidder2': '2c4f6cc3ba128a',
'<API key>': 'testBidder2',
'hb_format_appnexus': 'video',
'hb_source_appnexus': 'client',
'hb_size_appnexus': '640x480',
'hb_pb_appnexus': '5.00',
'hb_adid_appnexus': '44e0b5f2e5cace',
'hb_bidder_appnexus': 'appnexus'
};
let targetingStub;
before(function () {
targetingStub = sinon.stub(targeting, 'getAllTargeting');
targetingStub.returns({'video1': allTargetingData});
config.setConfig({
enableSendAllBids: true
});
});
after(function () {
config.resetConfig();
targetingStub.restore();
});
it('should include all adserver targeting in cust_params if pbjs.enableSendAllBids is true', function () {
const adUnitsCopy = utils.deepClone(adUnit);
adUnitsCopy.bids.push({
'bidder': 'testBidder2',
'params': {
'placementId': '9333431',
'video': {
'skipppable': false,
'playback_methods': ['auto_play_sound_off']
}
}
});
const bidCopy = utils.deepClone(bid);
bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, {
hb_adid: 'ad_id',
});
const url = parse(buildDfpVideoUrl({
adUnit: adUnitsCopy,
bid: bidCopy,
params: {
'iu': 'my/adUnit'
}
}));
const queryObject = utils.parseQS(url.query);
const customParams = utils.parseQS('?' + decodeURIComponent(queryObject.cust_params));
expect(customParams).to.have.property('hb_adid', 'ad_id');
expect(customParams).to.have.property('hb_uuid', bid.videoCacheKey);
expect(customParams).to.have.property('hb_cache_id', bid.videoCacheKey);
expect(customParams).to.have.property('hb_bidder_appnexus', 'appnexus');
expect(customParams).to.have.property('<API key>', 'testBidder2');
});
});
it('should merge the user-provided cust_params with the default ones', function () {
const bidCopy = utils.deepClone(bid);
bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, {
hb_adid: 'ad_id',
});
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
params: {
'iu': 'my/adUnit',
cust_params: {
'my_targeting': 'foo',
},
},
}));
const queryObject = utils.parseQS(url.query);
const customParams = utils.parseQS('?' + decodeURIComponent(queryObject.cust_params));
expect(customParams).to.have.property('hb_adid', 'ad_id');
expect(customParams).to.have.property('my_targeting', 'foo');
});
it('should merge the user-provided cust-params with the default ones when using url object', function () {
const bidCopy = utils.deepClone(bid);
bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, {
hb_adid: 'ad_id',
});
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
url: 'https://video.adserver.example/ads?sz=640x480&iu=/123/aduniturl&impl=s&cust_params=section%3dblog%26mykey%3dmyvalue'
}));
const queryObject = utils.parseQS(url.query);
const customParams = utils.parseQS('?' + decodeURIComponent(queryObject.cust_params));
expect(customParams).to.have.property('hb_adid', 'ad_id');
expect(customParams).to.have.property('section', 'blog');
expect(customParams).to.have.property('mykey', 'myvalue');
expect(customParams).to.have.property('hb_uuid', 'abc');
expect(customParams).to.have.property('hb_cache_id', 'abc');
});
it('should not overwrite an existing description_url for object input and cache disabled', function () {
const bidCopy = utils.deepClone(bid);
bidCopy.vastUrl = 'vastUrl.example';
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
params: {
iu: 'my/adUnit',
description_url: 'descriptionurl.example'
}
}));
const queryObject = utils.parseQS(url.query);
expect(queryObject.description_url).to.equal('descriptionurl.example');
});
it('should work with nobid responses', function () {
const url = buildDfpVideoUrl({
adUnit: adUnit,
params: { 'iu': 'my/adUnit' }
});
expect(url).to.be.a('string');
});
it('should include hb_uuid and hb_cache_id in cust_params when both keys are exluded from overwritten bidderSettings', function () {
const bidCopy = utils.deepClone(bid);
delete bidCopy.adserverTargeting.hb_uuid;
delete bidCopy.adserverTargeting.hb_cache_id;
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
params: {
'iu': 'my/adUnit'
}
}));
const queryObject = utils.parseQS(url.query);
const customParams = utils.parseQS('?' + decodeURIComponent(queryObject.cust_params));
expect(customParams).to.have.property('hb_uuid', bid.videoCacheKey);
expect(customParams).to.have.property('hb_cache_id', bid.videoCacheKey);
});
it('should include hb_uuid and hb_cache_id in cust params from overwritten standard bidderSettings', function () {
const bidCopy = utils.deepClone(bid);
bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, {
hb_uuid: 'def',
hb_cache_id: 'def'
});
const url = parse(buildDfpVideoUrl({
adUnit: adUnit,
bid: bidCopy,
params: {
'iu': 'my/adUnit'
}
}));
const queryObject = utils.parseQS(url.query);
const customParams = utils.parseQS('?' + decodeURIComponent(queryObject.cust_params));
expect(customParams).to.have.property('hb_uuid', 'def');
expect(customParams).to.have.property('hb_cache_id', 'def');
});
describe('adpod unit tests', function () {
let amStub;
let amGetAdUnitsStub;
before(function () {
let adUnits = [{
code: 'adUnitCode-1',
mediaTypes: {
video: {
context: 'adpod',
playerSize: [640, 480],
adPodDurationSec: 60,
durationRangeSec: [15, 30],
<API key>: true
}
},
bids: [
{
bidder: 'appnexus',
params: {
placementId: 14542875,
}
}
]
}];
amGetAdUnitsStub = sinon.stub(auctionManager, 'getAdUnits');
amGetAdUnitsStub.returns(adUnits);
amStub = sinon.stub(auctionManager, 'getBidsReceived');
});
beforeEach(function () {
config.setConfig({
adpod: {
<API key>: true,
deferCaching: false
}
});
})
afterEach(function() {
config.resetConfig();
});
after(function () {
amGetAdUnitsStub.restore();
amStub.restore();
});
it('should return masterTag url', function() {
amStub.returns(getBidsReceived());
let uspDataHandlerStub = sinon.stub(uspDataHandler, 'getConsentData');
uspDataHandlerStub.returns('1YYY');
let gdprDataHandlerStub = sinon.stub(gdprDataHandler, 'getConsentData');
gdprDataHandlerStub.returns({
gdprApplies: true,
consentString: 'consent',
addtlConsent: 'moreConsent'
});
let url;
parse(buildAdpodVideoUrl({
code: 'adUnitCode-1',
callback: handleResponse,
params: {
'iu': 'my/adUnit',
'description_url': 'someUrl.com',
}
}));
function handleResponse(err, masterTag) {
if (err) {
return;
}
url = parse(masterTag);
expect(url.protocol).to.equal('https:');
expect(url.host).to.equal('securepubads.g.doubleclick.net');
const queryParams = utils.parseQS(url.query);
expect(queryParams).to.have.property('correlator');
expect(queryParams).to.have.property('description_url', 'someUrl.com');
expect(queryParams).to.have.property('env', 'vp');
expect(queryParams).to.have.property('gdfp_req', '1');
expect(queryParams).to.have.property('iu', 'my/adUnit');
expect(queryParams).to.have.property('output', 'vast');
expect(queryParams).to.have.property('sz', '640x480');
expect(queryParams).to.have.property('<API key>', '1');
expect(queryParams).to.have.property('url');
expect(queryParams).to.have.property('cust_params');
expect(queryParams).to.have.property('us_privacy', '1YYY');
expect(queryParams).to.have.property('gdpr', '1');
expect(queryParams).to.have.property('gdpr_consent', 'consent');
expect(queryParams).to.have.property('addtl_consent', 'moreConsent');
const custParams = utils.parseQS(decodeURIComponent(queryParams.cust_params));
expect(custParams).to.have.property('hb_cache_id', '123');
expect(custParams).to.have.property('hb_pb_cat_dur', '15.00_395_15s,15.00_406_30s,10.00_395_15s');
uspDataHandlerStub.restore();
gdprDataHandlerStub.restore();
}
});
it('should return masterTag url with correct custom params when <API key> is false', function() {
config.setConfig({
adpod: {
<API key>: false,
}
});
function getBids() {
let bids = [
createBid(10, 'adUnitCode-1', 15, '10.00_15s', '123', '395', '10.00'),
createBid(15, 'adUnitCode-1', 15, '15.00_15s', '123', '395', '15.00'),
createBid(25, 'adUnitCode-1', 30, '15.00_30s', '123', '406', '25.00'),
];
bids.forEach((bid) => {
delete bid.meta;
});
return bids;
}
amStub.returns(getBids());
let url;
parse(buildAdpodVideoUrl({
code: 'adUnitCode-1',
callback: handleResponse,
params: {
'iu': 'my/adUnit',
'description_url': 'someUrl.com',
}
}));
function handleResponse(err, masterTag) {
if (err) {
return;
}
url = parse(masterTag);
expect(url.protocol).to.equal('https:');
expect(url.host).to.equal('securepubads.g.doubleclick.net');
const queryParams = utils.parseQS(url.query);
expect(queryParams).to.have.property('correlator');
expect(queryParams).to.have.property('description_url', 'someUrl.com');
expect(queryParams).to.have.property('env', 'vp');
expect(queryParams).to.have.property('gdfp_req', '1');
expect(queryParams).to.have.property('iu', 'my/adUnit');
expect(queryParams).to.have.property('output', 'xml_vast3');
expect(queryParams).to.have.property('sz', '640x480');
expect(queryParams).to.have.property('<API key>', '1');
expect(queryParams).to.have.property('url');
expect(queryParams).to.have.property('cust_params');
const custParams = utils.parseQS(decodeURIComponent(queryParams.cust_params));
expect(custParams).to.have.property('hb_cache_id', '123');
expect(custParams).to.have.property('hb_pb_cat_dur', '10.00_15s,15.00_15s,15.00_30s');
}
});
it('should handle error when cache fails', function() {
config.setConfig({
adpod: {
<API key>: true,
deferCaching: true
}
});
amStub.returns(getBidsReceived());
parse(buildAdpodVideoUrl({
code: 'adUnitCode-1',
callback: handleResponse,
params: {
'iu': 'my/adUnit',
'description_url': 'someUrl.com',
}
}));
server.requests[0].respond(503, {
'Content-Type': 'plain/text',
}, 'The server could not save anything at the moment.');
function handleResponse(err, masterTag) {
expect(masterTag).to.be.null;
expect(err).to.be.an('error');
}
});
})
});
function getBidsReceived() {
return [
createBid(10, 'adUnitCode-1', 15, '10.00_395_15s', '123', '395', '10.00'),
createBid(15, 'adUnitCode-1', 15, '15.00_395_15s', '123', '395', '15.00'),
createBid(25, 'adUnitCode-1', 30, '15.00_406_30s', '123', '406', '25.00'),
]
}
function createBid(cpm, adUnitCode, durationBucket, <API key>, uuid, label, hbpb) {
return {
'bidderCode': 'appnexus',
'width': 640,
'height': 360,
'statusMessage': 'Bid available',
'adId': '28f24ced14586c',
'mediaType': 'video',
'source': 'client',
'requestId': '28f24ced14586c',
'cpm': cpm,
'creativeId': 97517771,
'currency': 'USD',
'netRevenue': true,
'ttl': 3600,
'adUnitCode': adUnitCode,
'video': {
'context': 'adpod',
'durationBucket': durationBucket
},
'appnexus': {
'buyerMemberId': 9325
},
'vastUrl': 'http://some-vast-url.com',
'vastImpUrl': 'http://some-vast-imp-url.com',
'auctionId': '<API key>',
'responseTimestamp': 1548442460888,
'requestTimestamp': 1548442460827,
'bidder': 'appnexus',
'timeToRespond': 61,
'pbLg': '5.00',
'pbMg': '5.00',
'pbHg': '5.00',
'pbAg': '5.00',
'pbDg': '5.00',
'pbCg': '',
'size': '640x360',
'adserverTargeting': {
'hb_bidder': 'appnexus',
'hb_adid': '28f24ced14586c',
'hb_pb': hbpb,
'hb_size': '640x360',
'hb_source': 'client',
'hb_format': 'video',
'hb_pb_cat_dur': <API key>,
'hb_cache_id': uuid
},
'customCacheKey': `${<API key>}_${uuid}`,
'meta': {
'primaryCatId': 'iab-1',
'adServerCatId': label
},
'videoCacheKey': '<API key>'
}
}
|
#include <Wt/WApplication>
#include <Wt/WStandardItemModel>
#include <Wt/WTableView>
#include "../treeview-dragdrop/CsvUtil.h"
SAMPLE_BEGIN(SmallTableView)
Wt::WTableView *tableView = new Wt::WTableView();
tableView->setModel(csvToModel(Wt::WApplication::appRoot() + "table.csv",
tableView));
tableView-><API key>(false);
tableView->setColumnAlignment(0, Wt::AlignCenter);
tableView->setHeaderAlignment(0, Wt::AlignCenter);
tableView-><API key>(true);
tableView->setRowHeight(28);
tableView->setHeaderHeight(28);
tableView->setSelectionMode(Wt::SingleSelection);
tableView->setEditTriggers(Wt::WAbstractItemView::NoEditTrigger);
/*
* Configure column widths and matching table width
*/
const int WIDTH = 120;
for (int i = 0; i < tableView->model()->columnCount(); ++i)
tableView->setColumnWidth(i, 120);
/*
* 7 pixels are padding/border per column
* 2 pixels are border of the entire table
*/
tableView->setWidth((WIDTH + 7) * tableView->model()->columnCount() + 2);
SAMPLE_END(return tableView)
|
// "Replace with 'Stream.mapToLong().sum()'" "true"
import java.util.Collection;
import java.util.List;
class Test {
void foo(List<List<String>> s) {
long count = s.stream().peek(System.out::println).flatMap(Collection::stream).c<caret>ount();
}
}
|
#!/usr/bin/env python
import xml.etree.ElementTree as ET
class <API key>(object):
"""Auto generated class.
"""
def __init__(self, **kwargs):
self._callback = kwargs.pop('callback')
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name = ET.SubElement(standard, "name")
name.text = kwargs.pop('name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id = ET.SubElement(seq, "seq-id")
seq_id.text = kwargs.pop('seq_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
action = ET.SubElement(seq, "action")
action.text = kwargs.pop('action')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_host_any_sip = ET.SubElement(seq, "src-host-any-sip")
src_host_any_sip.text = kwargs.pop('src_host_any_sip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_host_ip = ET.SubElement(seq, "src-host-ip")
src_host_ip.text = kwargs.pop('src_host_ip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_mask = ET.SubElement(seq, "src-mask")
src_mask.text = kwargs.pop('src_mask')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
count = ET.SubElement(seq, "count")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
log = ET.SubElement(seq, "log")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name = ET.SubElement(extended, "name")
name.text = kwargs.pop('name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id = ET.SubElement(seq, "seq-id")
seq_id.text = kwargs.pop('seq_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
action = ET.SubElement(seq, "action")
action.text = kwargs.pop('action')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
protocol_type = ET.SubElement(seq, "protocol-type")
protocol_type.text = kwargs.pop('protocol_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_host_any_sip = ET.SubElement(seq, "src-host-any-sip")
src_host_any_sip.text = kwargs.pop('src_host_any_sip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_host_ip = ET.SubElement(seq, "src-host-ip")
src_host_ip.text = kwargs.pop('src_host_ip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_mask = ET.SubElement(seq, "src-mask")
src_mask.text = kwargs.pop('src_mask')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport = ET.SubElement(seq, "sport")
sport.text = kwargs.pop('sport')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_lt_tcp = ET.SubElement(seq, "sport-number-lt-tcp")
sport_number_lt_tcp.text = kwargs.pop('sport_number_lt_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_gt_tcp = ET.SubElement(seq, "sport-number-gt-tcp")
sport_number_gt_tcp.text = kwargs.pop('sport_number_gt_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_lt_udp = ET.SubElement(seq, "sport-number-lt-udp")
sport_number_lt_udp.text = kwargs.pop('sport_number_lt_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_gt_udp = ET.SubElement(seq, "sport-number-gt-udp")
sport_number_gt_udp.text = kwargs.pop('sport_number_gt_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dst_host_any_dip = ET.SubElement(seq, "dst-host-any-dip")
dst_host_any_dip.text = kwargs.pop('dst_host_any_dip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dst_host_ip = ET.SubElement(seq, "dst-host-ip")
dst_host_ip.text = kwargs.pop('dst_host_ip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dst_mask = ET.SubElement(seq, "dst-mask")
dst_mask.text = kwargs.pop('dst_mask')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport = ET.SubElement(seq, "dport")
dport.text = kwargs.pop('dport')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_lt_tcp = ET.SubElement(seq, "dport-number-lt-tcp")
dport_number_lt_tcp.text = kwargs.pop('dport_number_lt_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_gt_tcp = ET.SubElement(seq, "dport-number-gt-tcp")
dport_number_gt_tcp.text = kwargs.pop('dport_number_gt_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_lt_udp = ET.SubElement(seq, "dport-number-lt-udp")
dport_number_lt_udp.text = kwargs.pop('dport_number_lt_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_gt_udp = ET.SubElement(seq, "dport-number-gt-udp")
dport_number_gt_udp.text = kwargs.pop('dport_number_gt_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dscp = ET.SubElement(seq, "dscp")
dscp.text = kwargs.pop('dscp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
urg = ET.SubElement(seq, "urg")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
ack = ET.SubElement(seq, "ack")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
push = ET.SubElement(seq, "push")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
fin = ET.SubElement(seq, "fin")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
rst = ET.SubElement(seq, "rst")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sync = ET.SubElement(seq, "sync")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
vlan = ET.SubElement(seq, "vlan")
vlan.text = kwargs.pop('vlan')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
count = ET.SubElement(seq, "count")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
log = ET.SubElement(seq, "log")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name = ET.SubElement(standard, "name")
name.text = kwargs.pop('name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id = ET.SubElement(seq, "seq-id")
seq_id.text = kwargs.pop('seq_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
action = ET.SubElement(seq, "action")
action.text = kwargs.pop('action')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_host_any_sip = ET.SubElement(seq, "src-host-any-sip")
src_host_any_sip.text = kwargs.pop('src_host_any_sip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_host_ip = ET.SubElement(seq, "src-host-ip")
src_host_ip.text = kwargs.pop('src_host_ip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_mask = ET.SubElement(seq, "src-mask")
src_mask.text = kwargs.pop('src_mask')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
count = ET.SubElement(seq, "count")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
log = ET.SubElement(seq, "log")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name = ET.SubElement(extended, "name")
name.text = kwargs.pop('name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id = ET.SubElement(seq, "seq-id")
seq_id.text = kwargs.pop('seq_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
action = ET.SubElement(seq, "action")
action.text = kwargs.pop('action')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
protocol_type = ET.SubElement(seq, "protocol-type")
protocol_type.text = kwargs.pop('protocol_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_host_any_sip = ET.SubElement(seq, "src-host-any-sip")
src_host_any_sip.text = kwargs.pop('src_host_any_sip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_host_ip = ET.SubElement(seq, "src-host-ip")
src_host_ip.text = kwargs.pop('src_host_ip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
src_mask = ET.SubElement(seq, "src-mask")
src_mask.text = kwargs.pop('src_mask')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport = ET.SubElement(seq, "sport")
sport.text = kwargs.pop('sport')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_lt_tcp = ET.SubElement(seq, "sport-number-lt-tcp")
sport_number_lt_tcp.text = kwargs.pop('sport_number_lt_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_gt_tcp = ET.SubElement(seq, "sport-number-gt-tcp")
sport_number_gt_tcp.text = kwargs.pop('sport_number_gt_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_lt_udp = ET.SubElement(seq, "sport-number-lt-udp")
sport_number_lt_udp.text = kwargs.pop('sport_number_lt_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sport_number_gt_udp = ET.SubElement(seq, "sport-number-gt-udp")
sport_number_gt_udp.text = kwargs.pop('sport_number_gt_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dst_host_any_dip = ET.SubElement(seq, "dst-host-any-dip")
dst_host_any_dip.text = kwargs.pop('dst_host_any_dip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dst_host_ip = ET.SubElement(seq, "dst-host-ip")
dst_host_ip.text = kwargs.pop('dst_host_ip')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dst_mask = ET.SubElement(seq, "dst-mask")
dst_mask.text = kwargs.pop('dst_mask')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport = ET.SubElement(seq, "dport")
dport.text = kwargs.pop('dport')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_lt_tcp = ET.SubElement(seq, "dport-number-lt-tcp")
dport_number_lt_tcp.text = kwargs.pop('dport_number_lt_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_gt_tcp = ET.SubElement(seq, "dport-number-gt-tcp")
dport_number_gt_tcp.text = kwargs.pop('dport_number_gt_tcp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_lt_udp = ET.SubElement(seq, "dport-number-lt-udp")
dport_number_lt_udp.text = kwargs.pop('dport_number_lt_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dport_number_gt_udp = ET.SubElement(seq, "dport-number-gt-udp")
dport_number_gt_udp.text = kwargs.pop('dport_number_gt_udp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
<API key> = ET.SubElement(seq, "<API key>")
<API key>.text = kwargs.pop('<API key>')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
dscp = ET.SubElement(seq, "dscp")
dscp.text = kwargs.pop('dscp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
urg = ET.SubElement(seq, "urg")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
ack = ET.SubElement(seq, "ack")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
push = ET.SubElement(seq, "push")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
fin = ET.SubElement(seq, "fin")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
rst = ET.SubElement(seq, "rst")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
sync = ET.SubElement(seq, "sync")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
vlan = ET.SubElement(seq, "vlan")
vlan.text = kwargs.pop('vlan')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
count = ET.SubElement(seq, "count")
callback = kwargs.pop('callback', self._callback)
return callback(config)
def <API key>(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:<API key>")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
extended = ET.SubElement(access_list, "extended")
name_key = ET.SubElement(extended, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_ext = ET.SubElement(extended, "hide-ip-acl-ext")
seq = ET.SubElement(hide_ip_acl_ext, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
log = ET.SubElement(seq, "log")
callback = kwargs.pop('callback', self._callback)
return callback(config)
|
#include "board.h"
#include "uart.h"
#include "app_util_platform.h"
#include "nrf_drv_common.h"
#include "nrf_systick.h"
#include "nrf_rtc.h"
#include "nrf_drv_clock.h"
#include "softdevice_handler.h"
#include "nrf_drv_uart.h"
#include "nrf_gpio.h"
#include <rtthread.h>
#include <rthw.h>
#if 0
void <API key>(void)
{
<API key>(SysTick_IRQn, <API key>);
<API key>(SystemCoreClock / RT_TICK_PER_SECOND);
<API key>();
nrf_systick_csr_set(<API key> | <API key>
| <API key>);
}
/**
* This is the timer interrupt service routine.
*
*/
void SysTick_Handler(void)
{
if (rt_thread_self() != RT_NULL)
{
/* enter interrupt */
rt_interrupt_enter();
rt_tick_increase();
/* leave interrupt */
rt_interrupt_leave();
}
}
#else
#define TICK_RATE_HZ RT_TICK_PER_SECOND
#define SYSTICK_CLOCK_HZ ( 32768UL )
#define NRF_RTC_REG NRF_RTC1
/* IRQn used by the selected RTC */
#define NRF_RTC_IRQn RTC1_IRQn
/* Constants required to manipulate the NVIC. */
#define NRF_RTC_PRESCALER ( (uint32_t) (ROUNDED_DIV(SYSTICK_CLOCK_HZ, TICK_RATE_HZ) - 1) )
/* Maximum RTC ticks */
#define NRF_RTC_MAXTICKS ((1U<<24)-1U)
static volatile uint32_t <API key> = 0;
#define NRF_RTC_BITWIDTH 24
#define OSTick_Handler RTC1_IRQHandler
#define <API key> 2
void <API key>(void)
{
<API key>(NULL);
/* Configure SysTick to interrupt at the requested rate. */
<API key>(NRF_RTC_REG, NRF_RTC_PRESCALER);
nrf_rtc_int_enable (NRF_RTC_REG, <API key>);
<API key> (NRF_RTC_REG, NRF_RTC_TASK_CLEAR);
<API key> (NRF_RTC_REG, NRF_RTC_TASK_START);
<API key>(NRF_RTC_REG, <API key>);
NVIC_SetPriority(NRF_RTC_IRQn, 0xF);
NVIC_EnableIRQ(NRF_RTC_IRQn);
}
static rt_tick_t _tick_distance(void)
{
nrf_rtc_event_clear(NRF_RTC_REG, <API key>);
uint32_t systick_counter = nrf_rtc_counter_get(NRF_RTC_REG);
nrf_rtc_event_clear(NRF_RTC_REG, NRF_RTC_EVENT_TICK);
/* check for overflow in TICK counter */
if(<API key>(NRF_RTC_REG, <API key>))
{
nrf_rtc_event_clear(NRF_RTC_REG, <API key>);
<API key>++;
}
return ((<API key> << NRF_RTC_BITWIDTH) + systick_counter) - rt_tick_get();
}
void OSTick_Handler( void )
{
uint32_t diff;
diff = _tick_distance();
while((diff
{
if (rt_thread_self() != RT_NULL)
{
/* enter interrupt */
rt_interrupt_enter();
rt_tick_increase();
/* leave interrupt */
rt_interrupt_leave();
}
}
}
static void _wakeup_tick_adjust(void)
{
uint32_t diff;
uint32_t level;
level = <API key>();
diff = _tick_distance();
rt_tick_set(rt_tick_get() + diff);
if (rt_thread_self() != RT_NULL)
{
struct rt_thread *thread;
/* check time slice */
thread = rt_thread_self();
if (thread->remaining_tick <= diff)
{
/* change to initialized tick */
thread->remaining_tick = thread->init_tick;
/* yield */
rt_thread_yield();
}
else
{
thread->remaining_tick -= diff;
}
/* check timer */
rt_timer_check();
}
<API key>(level);
}
static void _sleep_ongo( uint32_t sleep_tick )
{
uint32_t enterTime;
uint32_t entry_tick;
/* Make sure the SysTick reload value does not overflow the counter. */
if ( sleep_tick > NRF_RTC_MAXTICKS - <API key> )
{
sleep_tick = NRF_RTC_MAXTICKS - <API key>;
}
rt_enter_critical();
enterTime = nrf_rtc_counter_get(NRF_RTC_REG);
{
uint32_t wakeupTime = (enterTime + sleep_tick) & NRF_RTC_MAXTICKS;
/* Stop tick events */
nrf_rtc_int_disable(NRF_RTC_REG, <API key>);
/* Configure CTC interrupt */
nrf_rtc_cc_set(NRF_RTC_REG, 0, wakeupTime);
nrf_rtc_event_clear(NRF_RTC_REG, <API key>);
nrf_rtc_int_enable(NRF_RTC_REG, <API key>);
entry_tick = rt_tick_get();
__DSB();
if ( sleep_tick > 0 )
{
#ifdef SOFTDEVICE_PRESENT
if (<API key>())
{
uint32_t err_code = sd_app_evt_wait();
APP_ERROR_CHECK(err_code);
}
else
#endif
{
/* No SD - we would just block interrupts globally.
* BASEPRI cannot be used for that because it would prevent WFE from wake up.
*/
do{
__WFE();
} while (0 == (NVIC->ISPR[0] | NVIC->ISPR[1]));
}
}
nrf_rtc_int_disable(NRF_RTC_REG, <API key>);
nrf_rtc_event_clear(NRF_RTC_REG, <API key>);
_wakeup_tick_adjust();
/* Correct the system ticks */
{
nrf_rtc_event_clear(NRF_RTC_REG, NRF_RTC_EVENT_TICK);
nrf_rtc_int_enable (NRF_RTC_REG, <API key>);
/* It is important that we clear pending here so that our corrections are latest and in sync with tick_interrupt handler */
<API key>(NRF_RTC_IRQn);
}
rt_kprintf("entry tick:%u, expected:%u, current tick:%u\n", entry_tick, sleep_tick, rt_tick_get());
}
rt_exit_critical();
}
#endif
void <API key>(void)
{
uint32_t sleep_tick;
sleep_tick = <API key>() - rt_tick_get();
if ( sleep_tick >= <API key>)
{
// rt_kprintf("sleep entry:%u\n", rt_tick_get());
_sleep_ongo( sleep_tick );
}
}
void rt_hw_board_init(void)
{
// <API key>(<API key>);
/* Activate deep sleep mode */
SCB->SCR |= <API key>;
nrf_drv_clock_init();
// <API key>(0);
<API key>();
<API key>(<API key>);
rt_hw_uart_init();
#ifdef RT_USING_CONSOLE
<API key>(<API key>);
#endif
#ifdef <API key>
<API key>();
#endif
}
|
// file at the top-level directory of this distribution and at
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// no-pretty-expanded FIXME #15189
#[derive(PartialEq, Eq, PartialOrd, Ord)]
enum E<T> {
E0,
E1(T),
E2(T,T)
}
pub fn main() {
let e0 = E::E0;
let e11 = E::E1(1);
let e12 = E::E1(2);
let e21 = E::E2(1, 1);
let e22 = E::E2(1, 2);
// in order for both PartialOrd and Ord
let es = [e0, e11, e12, e21, e22];
for (i, e1) in es.iter().enumerate() {
for (j, e2) in es.iter().enumerate() {
let ord = i.cmp(&j);
let eq = i == j;
let lt = i < j;
let le = i <= j;
let gt = i > j;
let ge = i >= j;
// PartialEq
assert_eq!(*e1 == *e2, eq);
assert_eq!(*e1 != *e2, !eq);
// PartialOrd
assert_eq!(*e1 < *e2, lt);
assert_eq!(*e1 > *e2, gt);
assert_eq!(*e1 <= *e2, le);
assert_eq!(*e1 >= *e2, ge);
// Ord
assert_eq!(e1.cmp(e2), ord);
}
}
}
|
cask "paragon-ntfs" do
version "15"
sha256 :no_check # required as upstream package is updated in-place
url "https://dl.paragon-software.com/demo/ntfsmac#{version}_trial.dmg"
name "Paragon NTFS for Mac"
homepage "https:
auto_updates true
installer manual: "FSInstaller.app"
uninstall kext: "com.paragon-software.filesystems.ntfs",
launchctl: "com.paragon-software.ntfs*",
pkgutil: "com.paragon-software.pkg.ntfs",
quit: "com.paragon-software.ntfs*",
signal: [
["KILL", "com.paragon-software.ntfs.FSMenuApp"],
["KILL", "com.paragon-software.ntfs.notification-agent"],
]
zap trash: "~/Library/Preferences/com.paragon-software.ntfs.fsapp.plist"
end
|
<?php
namespace ZendTest\Feed\Writer\Renderer\Entry;
use Zend\Feed\Writer\Renderer;
use Zend\Feed\Writer;
use Zend\Feed\Reader;
/**
* @group Zend_Feed
* @group Zend_Feed_Writer
*/
class RssTest extends \<API key>
{
protected $validWriter = null;
protected $validEntry = null;
public function setUp()
{
$this->validWriter = new Writer\Feed;
$this->validWriter->setType('rss');
$this->validWriter->setTitle('This is a test feed.');
$this->validWriter->setDescription('This is a test description.');
$this->validWriter->setLink('http:
$this->validEntry = $this->validWriter->createEntry();
$this->validEntry->setTitle('This is a test entry.');
$this->validEntry->setDescription('This is a test entry description.');
$this->validEntry->setLink('http:
$this->validWriter->addEntry($this->validEntry);
}
public function tearDown()
{
$this->validWriter = null;
$this->validEntry = null;
}
public function <API key>()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$renderer->render();
}
public function <API key>()
{
$this->validWriter->setEncoding('iso-8859-1');
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('iso-8859-1', $entry->getEncoding());
}
public function <API key>()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('UTF-8', $entry->getEncoding());
}
public function <API key>()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('This is a test entry.', $entry->getTitle());
}
/**
* @expectedException Zend\Feed\Writer\Exception\ExceptionInterface
*/
public function <API key>()
{
$atomFeed = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->remove('title');
$this->validEntry->remove('description');
$atomFeed->render();
}
public function <API key>()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setTitle('<>&\'"áéíóú');
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('<>&\'"áéíóú', $entry->getTitle());
}
public function <API key>()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('This is a test entry description.', $entry->getDescription());
}
/**
* @expectedException Zend\Feed\Writer\Exception\ExceptionInterface
*/
public function <API key>()
{
$atomFeed = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->remove('description');
$this->validEntry->remove('title');
$atomFeed->render();
}
public function <API key>()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setDescription('<>&\'"áéíóú');
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('<>&\'"áéíóú', $entry->getDescription());
}
public function <API key>()
{
$this->validEntry->setContent('This is test entry content.');
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('This is test entry content.', $entry->getContent());
}
public function <API key>()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setContent('<>&\'"áéíóú');
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('<>&\'"áéíóú', $entry->getContent());
}
public function <API key>()
{
$this->validEntry->setDateModified(1234567890);
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals(1234567890, $entry->getDateModified()->getTimestamp());
}
public function <API key>()
{
$this->validEntry->setDateCreated(1234567000);
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals(1234567000, $entry->getDateCreated()->getTimestamp());
}
public function <API key>()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('http:
}
public function <API key>()
{
$this->validEntry->addAuthor(array('name' => 'Jane',
'email'=> 'jane@example.com',
'uri' => 'http:
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$author = $entry->getAuthor();
$this->assertEquals(array('name'=> 'Jane'), $entry->getAuthor());
}
public function testEntry<API key>()
{
$this->validEntry->addAuthor(array('name' => '<>&\'"áéíóú',
'email'=> 'jane@example.com',
'uri' => 'http:
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$author = $entry->getAuthor();
$this->assertEquals(array('name'=> '<>&\'"áéíóú'), $entry->getAuthor());
}
public function <API key>()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setEnclosure(array(
'type' => 'audio/mpeg',
'length' => '1337',
'uri' => 'http://example.com/audio.mp3'
));
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$enc = $entry->getEnclosure();
$this->assertEquals('audio/mpeg', $enc->type);
$this->assertEquals('1337', $enc->length);
$this->assertEquals('http://example.com/audio.mp3', $enc->url);
}
/**
* @expectedException Zend\Feed\Writer\Exception\ExceptionInterface
*/
public function <API key>()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setEnclosure(array(
'uri' => 'http://example.com/audio.mp3',
'length' => '1337'
));
$renderer->render();
}
/**
* @expectedException Zend\Feed\Writer\Exception\ExceptionInterface
*/
public function <API key>()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setEnclosure(array(
'type' => 'audio/mpeg',
'uri' => 'http://example.com/audio.mp3'
));
$renderer->render();
}
/**
* @expectedException Zend\Feed\Writer\Exception\ExceptionInterface
*/
public function <API key>()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setEnclosure(array(
'type' => 'audio/mpeg',
'uri' => 'http://example.com/audio.mp3',
'length' => 'abc'
));
$renderer->render();
}
/**
* @expectedException Zend\Feed\Writer\Exception\ExceptionInterface
*/
public function <API key>()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setEnclosure(array(
'type' => 'audio/mpeg',
'uri' => 'http://example.com/audio.mp3',
'length' => -23
));
$renderer->render();
}
public function <API key>()
{
$this->validEntry->setId('urn:uuid:<API key>');
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('urn:uuid:<API key>', $entry->getId());
}
public function <API key>()
{
$this->markTestIncomplete('Untest due to ZFR potential bug');
}
public function <API key>()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals($entry->getLink(), $entry->getId());
}
public function <API key>()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setCommentLink('http:
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals('http:
}
public function <API key>()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setCommentCount(22);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$this->assertEquals(22, $entry->getCommentCount());
}
public function <API key>()
{
$renderer = new Renderer\Feed\Rss($this->validWriter);
$this->validEntry->setCommentFeedLinks(array(
array('uri' => 'http:
'type'=> 'atom'),
array('uri' => 'http:
'type'=> 'rss'),
));
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
// Skipped assertion is because RSS has no facility to show Atom feeds without an extension
$this->assertEquals('http:
}
public function <API key>()
{
$this->validEntry->addCategories(array(
array('term' => 'cat_dog',
'label' => 'Cats & Dogs',
'scheme' => 'http://example.com/schema1'),
array('term'=> 'cat_dog2')
));
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$expected = array(
array('term' => 'cat_dog',
'label' => 'cat_dog',
'scheme' => 'http://example.com/schema1'),
array('term' => 'cat_dog2',
'label' => 'cat_dog2',
'scheme' => null)
);
$this->assertEquals($expected, (array) $entry->getCategories());
}
/**
* @group ZFWCHARDATA01
*/
public function <API key>()
{
$this->validEntry->addCategories(array(
array('term' => '<>&\'"áéíóú',
'label' => 'Cats & Dogs',
'scheme' => 'http://example.com/schema1'),
array('term'=> 'cat_dog2')
));
$renderer = new Renderer\Feed\Rss($this->validWriter);
$feed = Reader\Reader::importString($renderer->render()->saveXml());
$entry = $feed->current();
$expected = array(
array('term' => '<>&\'"áéíóú',
'label' => '<>&\'"áéíóú',
'scheme' => 'http://example.com/schema1'),
array('term' => 'cat_dog2',
'label' => 'cat_dog2',
'scheme' => null)
);
$this->assertEquals($expected, (array) $entry->getCategories());
}
}
|
def <API key>():
from nose.util import is_generator, isgenerator
|
#ifndef FORM_H
#define FORM_H
#include "form.d"
PublicFnDecl FORM *FORM_read(char const *filename, int isBuffer);
PublicFnDecl PAGE_Action FORM_handler(
FORM *form, CUR_WINDOW *win, PAGE_Action action
);
PublicFnDecl void FORM_menuToForm();
PublicFnDecl void FORM_centerFormElts(FORM *fptr, int width);
#endif
|
#ifndef <API key>
#define <API key>
#include <string>
#include "ppapi/c/pp_stdint.h"
#include "ppapi/tests/test_case.h"
class <API key> : public TestCase {
public:
explicit <API key>(TestingInstance* instance);
// TestCase implementation.
virtual bool Init();
virtual void RunTests(const std::string& filter);
private:
std::string TestResolve();
};
#endif // <API key>
|
#include "cc/scheduler/scheduler_settings.h"
#include "cc/trees/layer_tree_settings.h"
namespace cc {
SchedulerSettings::SchedulerSettings()
: <API key>(true),
<API key>(true),
<API key>(false),
impl_side_painting(false),
<API key>(true),
<API key>(3),
<API key>(false),
<API key>(true) {
}
SchedulerSettings::SchedulerSettings(const LayerTreeSettings& settings)
: <API key>(settings.<API key>),
<API key>(settings.<API key>),
<API key>(
settings.<API key>),
impl_side_painting(settings.impl_side_painting),
<API key>(
settings.<API key>),
<API key>(
settings.<API key>),
<API key>(
settings.<API key>),
<API key>(settings.<API key>) {
}
SchedulerSettings::~SchedulerSettings() {}
scoped_ptr<base::Value> SchedulerSettings::AsValue() const {
scoped_ptr<base::DictionaryValue> state(new base::DictionaryValue);
state->SetBoolean("<API key>",
<API key>);
state->SetBoolean("<API key>",
<API key>);
state->SetBoolean("<API key>",
<API key>);
state->SetBoolean("impl_side_painting", impl_side_painting);
state->SetBoolean("<API key>",
<API key>);
state->SetInteger("<API key>",
<API key>);
state->SetBoolean("<API key>",
<API key>);
state->SetBoolean("<API key>", <API key>);
return state.PassAs<base::Value>();
}
} // namespace cc
|
#pragma once
#include <osquery/enroll.h>
#include <osquery/flags.h>
#include "osquery/remote/requests.h"
#include "osquery/remote/transports/tls.h"
namespace osquery {
DECLARE_string(tls_enroll_override);
DECLARE_string(tls_hostname);
DECLARE_bool(tls_node_api);
DECLARE_bool(tls_secret_always);
/**
* @brief Helper class for allowing TLS plugins to easily kick off requests
*
* There are many static functions in this class that have very similar
* behaviour, which allow them to be used in many context. Some methods accept
* parameters, some don't require them. Some have built-in retry logic, some
* don't. Some return results in a ptree, some return results in JSON, etc.
*/
class TLSRequestHelper {
public:
/**
* @brief Using the `tls_hostname` flag and an endpoint, construct a URI
*
* @param endpoint is the URI endpoint to be combined with `tls_hostname`
* @return a string representing the uri
*/
static std::string makeURI(const std::string& endpoint) {
auto node_key = getNodeKey("tls");
auto uri = "https://" + FLAGS_tls_hostname;
if (FLAGS_tls_node_api) {
// The TLS API should treat clients as nodes.
// In this case the node_key acts as an identifier (node) and the
// endpoints
// (if provided) are treated as edges from the nodes.
uri += "/" + node_key;
}
uri += endpoint;
// Some APIs may require persistent identification.
if (<API key>) {
uri += ((uri.find("?") != std::string::npos) ? "&" : "?") +
<API key> + "=" + getEnrollSecret();
}
return std::move(uri);
}
/**
* @brief Send a TLS request
*
* @param uri is the URI to send the request to
* @param params is a ptree of the params to send to the server. This isn't
* const because it will be modified to include node_key.
* @param output is the ptree which will be populated with the deserialized
* results
*
* @return a Status object indicating the success or failure of the operation
*/
template <class TSerializer>
static Status go(const std::string& uri,
boost::property_tree::ptree& params,
boost::property_tree::ptree& output) {
auto node_key = getNodeKey("tls");
// If using a GET request, append the node_key to the URI variables.
std::string uri_suffix;
if (FLAGS_tls_node_api) {
uri_suffix = "&node_key=" + node_key;
} else {
params.put<std::string>("node_key", node_key);
}
// Again check for GET to call with/without parameters.
auto request = Request<TLSTransport, TSerializer>(uri + uri_suffix);
auto status = (FLAGS_tls_node_api) ? request.call() : request.call(params);
if (!status.ok()) {
return status;
}
// The call succeeded, store the enrolled key.
status = request.getResponse(output);
if (!status.ok()) {
return status;
}
// Receive config or key rejection
if (output.count("node_invalid") > 0 || output.count("error") > 0) {
return Status(1, "Request failed: Invalid node key");
}
return Status(0, "OK");
}
/**
* @brief Send a TLS request
*
* @param uri is the URI to send the request to
* @param params is a ptree of the params to send to the server. This isn't
* const because it will be modified to include node_key.
*
* @return a Status object indicating the success or failure of the operation
*/
template <class TSerializer>
static Status go(const std::string& uri,
boost::property_tree::ptree& output) {
boost::property_tree::ptree params;
return TLSRequestHelper::go<TSerializer>(uri, params, output);
}
/**
* @brief Send a TLS request
*
* @param uri is the URI to send the request to
* @param params is a ptree of the params to send to the server. This isn't
* const because it will be modified to include node_key.
* @param output is the string which will be populated with the deserialized
* results
*
* @return a Status object indicating the success or failure of the operation
*/
template <class TSerializer>
static Status go(const std::string& uri,
boost::property_tree::ptree& params,
std::string& output) {
boost::property_tree::ptree recv;
auto s = TLSRequestHelper::go<TSerializer>(uri, params, recv);
if (s.ok()) {
auto serializer = TSerializer();
return serializer.serialize(recv, output);
}
return s;
}
/**
* @brief Send a TLS request
*
* @param uri is the URI to send the request to
* @param output is the string which will be populated with the deserialized
* results
*
* @return a Status object indicating the success or failure of the operation
*/
template <class TSerializer>
static Status go(const std::string& uri, std::string& output) {
boost::property_tree::ptree params;
return TLSRequestHelper::go<TSerializer>(uri, params, output);
}
/**
* @brief Send a TLS request
*
* @param uri is the URI to send the request to
* @param params is a ptree of the params to send to the server. This isn't
* const because it will be modified to include node_key.
* @param output is the string which will be populated with the deserialized
* results
* @param attempts is the number of attempts to make if the request fails
*
* @return a Status object indicating the success or failure of the operation
*/
template <class TSerializer>
static Status go(const std::string& uri,
boost::property_tree::ptree& params,
std::string& output,
const size_t attempts) {
Status s;
for (size_t i = 1; i <= attempts; i++) {
s = TLSRequestHelper::go<TSerializer>(uri, params, output);
if (s.ok()) {
return s;
}
if (i == attempts) {
break;
}
::sleep(i * i);
}
return s;
}
/**
* @brief Send a TLS request
*
* @param uri is the URI to send the request to
* @param output is the string which will be populated with the deserialized
* results
* @param attempts is the number of attempts to make if the request fails
*
* @return a Status object indicating the success or failure of the operation
*/
template <class TSerializer>
static Status go(const std::string& uri,
std::string& output,
const size_t attempts) {
boost::property_tree::ptree params;
return TLSRequestHelper::go<TSerializer>(uri, params, output, attempts);
}
};
}
|
#include <stdint.h>
#include <utility>
#include <vector>
#include "base/strings/string16.h"
#include "content/common/content_export.h"
#include "ipc/ipc_message_macros.h"
#undef IPC_MESSAGE_EXPORT
#define IPC_MESSAGE_EXPORT CONTENT_EXPORT
#define IPC_MESSAGE_START <API key>
#ifndef <API key>
#define <API key>
// The macros can't handle a complex template declaration, so we typedef it.
typedef std::pair<base::string16, base::string16> DWriteStringPair;
#endif // <API key>
// Locates the index of the specified font family within the system collection.
<API key>(<API key>,
base::string16 /* family_name */,
uint32_t /* out index */)
// Returns the number of font families in the system collection.
<API key>(<API key>,
uint32_t /* out count */)
// Returns the list of locale and family name pairs for the font family at the
// specified index.
<API key>(
<API key>,
uint32_t /* family_index */,
std::vector<DWriteStringPair> /* out family_names */)
// Returns the list of font file paths in the system font directory that contain
// font data for the font family at the specified index.
<API key>(<API key>,
uint32_t /* family_index */,
std::vector<base::string16> /* out file_paths */)
|
"""test a warning is triggered when using for a lists comprehension variable"""
__revision__ = 'yo'
TEST_LC = [C for C in __revision__ if C.isalpha()]
print C # WARN
C = 4
print C # this one shouldn't trigger any warning
B = [B for B in __revision__ if B.isalpha()]
print B # nor this one
for var1, var2 in TEST_LC:
var1 = var2 + 4
print var1 # WARN
for note in __revision__:
note.something()
for line in __revision__:
for note in line:
A = note.anotherthing()
for x in []:
pass
for x in range(3):
print (lambda : x)()
|
#include "chrome/browser/ui/app_list/search/people/people_result.h"
#include <vector>
#include "base/bind.h"
#include "base/memory/ref_counted.h"
#include "base/strings/<API key>.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/profile_o<API key>.h"
#include "chrome/browser/signin/<API key>.h"
#include "chrome/browser/ui/app_list/search/common/url_icon_source.h"
#include "chrome/browser/ui/app_list/search/people/person.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/common/extensions/api/hangouts_private.h"
#include "components/signin/core/browser/<API key>.h"
#include "components/signin/core/browser/signin_manager.h"
#include "content/public/browser/user_metrics.h"
#include "extensions/browser/event_router.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
namespace OnHangoutRequested =
extensions::api::hangouts_private::OnHangoutRequested;
using extensions::api::hangouts_private::User;
using extensions::api::hangouts_private::HangoutRequest;
namespace {
const int kIconSize = 32;
const char kImageSizePath[] = "s64-p/";
const char kEmailUrlPrefix[] = "mailto:";
const char* const <API key>[] = {
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>"
};
// Add a query parameter to specify the size to fetch the image in. The
// original profile image can be of an arbitrary size, we ask the server to
// crop it to a square 64x64 using its smart cropping algorithm.
GURL GetImageUrl(const GURL& url) {
std::string image_filename = url.ExtractFileName();
if (image_filename.empty())
return url;
return url.Resolve(kImageSizePath + image_filename);
}
} // namespace
namespace app_list {
PeopleResult::PeopleResult(Profile* profile, scoped_ptr<Person> person)
: profile_(profile), person_(person.Pass()), weak_factory_(this) {
set_id(person_->id);
set_title(base::UTF8ToUTF16(person_->display_name));
set_relevance(person_->interaction_rank);
set_details(base::UTF8ToUTF16(person_->email));
<API key>();
SetDefaultActions();
image_ = gfx::ImageSkia(
new UrlIconSource(base::Bind(&PeopleResult::OnIconLoaded,
weak_factory_.GetWeakPtr()),
profile_->GetRequestContext(),
GetImageUrl(person_->image_url),
kIconSize,
<API key>),
gfx::Size(kIconSize, kIconSize));
SetIcon(image_);
}
PeopleResult::~PeopleResult() {
}
void PeopleResult::Open(int event_flags) {
// Action 0 will always be our default action.
InvokeAction(0, event_flags);
}
void PeopleResult::InvokeAction(int action_index, int event_flags) {
if (<API key>.empty()) {
// If the hangouts app is not available, the only option we are showing
// to the user is 'Send Email'.
SendEmail();
} else {
switch (action_index) {
case 0:
OpenChat();
break;
case 1:
SendEmail();
break;
default:
LOG(ERROR) << "Invalid people search action: " << action_index;
}
}
}
scoped_ptr<ChromeSearchResult> PeopleResult::Duplicate() {
return scoped_ptr<ChromeSearchResult>(
new PeopleResult(profile_, person_->Duplicate().Pass())).Pass();
}
void PeopleResult::OnIconLoaded() {
// Remove the existing image reps since the icon data is loaded and they
// need to be re-created.
const std::vector<gfx::ImageSkiaRep>& image_reps = image_.image_reps();
for (size_t i = 0; i < image_reps.size(); ++i)
image_.<API key>(image_reps[i].scale());
SetIcon(image_);
}
void PeopleResult::SetDefaultActions() {
Actions actions;
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
if (!<API key>.empty()) {
actions.push_back(Action(
*bundle.GetImageSkiaNamed(<API key>),
*bundle.GetImageSkiaNamed(<API key>),
*bundle.GetImageSkiaNamed(<API key>),
l10n_util::GetStringUTF16(<API key>)));
}
actions.push_back(Action(
*bundle.GetImageSkiaNamed(<API key>),
*bundle.GetImageSkiaNamed(<API key>),
*bundle.GetImageSkiaNamed(<API key>),
l10n_util::GetStringUTF16(<API key>)));
SetActions(actions);
}
void PeopleResult::OpenChat() {
HangoutRequest request;
request.type = extensions::api::hangouts_private::HANGOUT_TYPE_CHAT;
// from: the user this chat request is originating from.
SigninManagerBase* signin_manager =
<API key>::GetInstance()->GetForProfile(profile_);
DCHECK(signin_manager);
request.from = signin_manager->Get<API key>();
// to: list of users with whom to start this hangout is with.
linked_ptr<User> target(new User());
target->id = person_->owner_id;
request.to.push_back(target);
scoped_ptr<extensions::Event> event(
new extensions::Event(OnHangoutRequested::kEventName,
OnHangoutRequested::Create(request)));
// TODO(rkc): Change this once we remove the hangoutsPrivate API.
// See crbug.com/306672
extensions::EventRouter::Get(profile_)
-><API key>(<API key>, event.Pass());
content::RecordAction(base::UserMetricsAction("<API key>"));
}
void PeopleResult::SendEmail() {
chrome::NavigateParams params(profile_,
GURL(kEmailUrlPrefix + person_->email),
content::<API key>);
// If no window exists, this will open a new window this one tab.
params.disposition = NEW_FOREGROUND_TAB;
chrome::Navigate(¶ms);
content::RecordAction(base::UserMetricsAction("<API key>"));
}
void PeopleResult::<API key>() {
// TODO(rkc): Change this once we remove the hangoutsPrivate API.
// See crbug.com/306672
for (size_t i = 0; i < arraysize(<API key>); ++i) {
if (extensions::EventRouter::Get(profile_)-><API key>(
<API key>[i], OnHangoutRequested::kEventName)) {
<API key> = <API key>[i];
return;
}
}
<API key>.clear();
}
<API key> PeopleResult::GetType() {
return <API key>;
}
} // namespace app_list
|
#include <set>
#include <string>
#include <math.h>
#include <gtest/gtest.h>
#include "agent.h"
#include "bid.h"
#include "bid_portfolio.h"
#include "composition.h"
#include "equality_helpers.h"
#include "exchange_context.h"
#include "facility.h"
#include "material.h"
#include "request.h"
#include "request_portfolio.h"
#include "resource_exchange.h"
#include "resource_helpers.h"
#include "test_context.h"
#include "test_agents/test_facility.h"
using cyclus::Bid;
using cyclus::BidPortfolio;
using cyclus::CommodMap;
using cyclus::Composition;
using cyclus::Context;
using cyclus::ExchangeContext;
using cyclus::Facility;
using cyclus::Material;
using cyclus::Agent;
using cyclus::PrefMap;
using cyclus::Request;
using cyclus::RequestPortfolio;
using cyclus::ResourceExchange;
using cyclus::TestContext;
using std::set;
using std::string;
class Requester: public TestFacility {
public:
Requester(Context* ctx, int i = 1)
: TestFacility(ctx),
i_(i),
req_ctr_(0),
pref_ctr_(0) {}
virtual cyclus::Agent* Clone() {
Requester* m = new Requester(context());
m->InitFrom(this);
m->i_ = i_;
m->port_ = port_;
return m;
}
set<RequestPortfolio<Material>::Ptr> GetMatlRequests() {
set<RequestPortfolio<Material>::Ptr> rps;
RequestPortfolio<Material>::Ptr rp(new RequestPortfolio<Material>());
rps.insert(port_);
req_ctr_++;
return rps;
}
// increments counter and squares all preferences
virtual void AdjustMatlPrefs(PrefMap<Material>::type& prefs) {
std::map<Request<Material>*,
std::map<Bid<Material>*, double> >::iterator p_it;
for (p_it = prefs.begin(); p_it != prefs.end(); ++p_it) {
std::map<Bid<Material>*, double>& map = p_it->second;
std::map<Bid<Material>*, double>::iterator m_it;
for (m_it = map.begin(); m_it != map.end(); ++m_it) {
m_it->second = std::pow(m_it->second, 2);
}
}
pref_ctr_++;
}
RequestPortfolio<Material>::Ptr port_;
int i_;
int pref_ctr_;
int req_ctr_;
};
class Bidder: public TestFacility {
public:
Bidder(Context* ctx, std::string commod)
: TestFacility(ctx),
commod_(commod),
bid_ctr_(0) {}
virtual cyclus::Agent* Clone() {
Bidder* m = new Bidder(context(), commod_);
m->InitFrom(this);
m->port_ = port_;
return m;
}
set<BidPortfolio<Material>::Ptr> GetMatlBids(
CommodMap<Material>::type& commod_requests) {
set<BidPortfolio<Material>::Ptr> bps;
bps.insert(port_);
bid_ctr_++;
return bps;
}
BidPortfolio<Material>::Ptr port_;
std::string commod_;
int bid_ctr_;
};
class <API key>: public ::testing::Test {
protected:
TestContext tc;
Requester* reqr;
Bidder* bidr;
ResourceExchange<Material>* exchng;
string commod;
double pref;
Material::Ptr mat;
Request<Material>* req;
Bid<Material>* bid;
virtual void SetUp() {
commod = "name";
pref = 2.4;
cyclus::CompMap cm;
cm[92235] = 1.0;
Composition::Ptr comp = Composition::CreateFromMass(cm);
double qty = 1.0;
mat = Material::CreateUntracked(qty, comp);
reqr = new Requester(tc.get());
exchng = new ResourceExchange<Material>(tc.get());
}
virtual void TearDown() {
delete exchng;
}
};
TEST_F(<API key>, Requests) {
RequestPortfolio<Material>::Ptr rp(new RequestPortfolio<Material>());
req = rp->AddRequest(mat, reqr, commod, pref);
reqr->port_ = rp;
Facility* clone = dynamic_cast<Facility*>(reqr->Clone());
clone->Build(NULL);
Requester* rcast = dynamic_cast<Requester*>(clone);
EXPECT_EQ(0, rcast->req_ctr_);
exchng->AddAllRequests();
EXPECT_EQ(1, rcast->req_ctr_);
EXPECT_EQ(1, exchng->ex_ctx().requesters.size());
ExchangeContext<Material>& ctx = exchng->ex_ctx();
const std::vector<RequestPortfolio<Material>::Ptr>& obsvp = ctx.requests;
EXPECT_EQ(1, obsvp.size());
EXPECT_TRUE(RPEq(*rp.get(), *obsvp[0].get()));
const std::vector<Request<Material>*>& obsvr = ctx.commod_requests[commod];
EXPECT_EQ(1, obsvr.size());
std::vector<Request<Material>*> vr;
vr.push_back(req);
EXPECT_EQ(vr, obsvr);
clone->Decommission();
}
TEST_F(<API key>, Bids) {
ExchangeContext<Material>& ctx = exchng->ex_ctx();
RequestPortfolio<Material>::Ptr rp(new RequestPortfolio<Material>());
req = rp->AddRequest(mat, reqr, commod, pref);
Request<Material>* req1 = rp->AddRequest(mat, reqr, commod, pref);
ctx.AddRequestPortfolio(rp);
const std::vector<Request<Material>*>& reqs = ctx.commod_requests[commod];
EXPECT_EQ(2, reqs.size());
Bidder* bidr = new Bidder(tc.get(), commod);
BidPortfolio<Material>::Ptr bp(new BidPortfolio<Material>());
bid = bp->AddBid(req, mat, bidr);
Bid<Material>* bid1 = bp->AddBid(req1, mat, bidr);
std::vector<Bid<Material>*> bids;
bids.push_back(bid);
bids.push_back(bid1);
bidr->port_ = bp;
Facility* clone = dynamic_cast<Facility*>(bidr->Clone());
clone->Build(NULL);
Bidder* bcast = dynamic_cast<Bidder*>(clone);
EXPECT_EQ(0, bcast->bid_ctr_);
exchng->AddAllBids();
EXPECT_EQ(1, bcast->bid_ctr_);
EXPECT_EQ(1, exchng->ex_ctx().bidders.size());
const std::vector<BidPortfolio<Material>::Ptr>& obsvp = ctx.bids;
EXPECT_EQ(1, obsvp.size());
EXPECT_TRUE(BPEq(*bp.get(), *obsvp[0].get()));
const cyclus::BidPortfolio<Material>& lhs = *bp;
const cyclus::BidPortfolio<Material>& rhs = *obsvp[0];
EXPECT_TRUE(BPEq(*bp, *obsvp[0]));
const std::vector<Bid<Material>*>& obsvb = ctx.bids_by_request[req];
EXPECT_EQ(1, obsvb.size());
std::vector<Bid<Material>*> vb;
vb.push_back(bid);
EXPECT_EQ(vb, obsvb);
const std::vector<Bid<Material>*>& obsvb1 = ctx.bids_by_request[req1];
EXPECT_EQ(1, obsvb1.size());
vb.clear();
vb.push_back(bid1);
EXPECT_EQ(vb, obsvb1);
clone->Decommission();
}
TEST_F(<API key>, PrefCalls) {
Facility* parent = dynamic_cast<Facility*>(reqr->Clone());
Facility* child = dynamic_cast<Facility*>(reqr->Clone());
parent->Build(NULL);
child->Build(parent);
Requester* pcast = dynamic_cast<Requester*>(parent);
Requester* ccast = dynamic_cast<Requester*>(child);
ASSERT_TRUE(pcast != NULL);
ASSERT_TRUE(ccast != NULL);
ASSERT_TRUE(pcast->parent() == NULL);
ASSERT_TRUE(ccast->parent() == dynamic_cast<Agent*>(pcast));
ASSERT_TRUE(pcast->manager() == dynamic_cast<Agent*>(pcast));
ASSERT_TRUE(ccast->manager() == dynamic_cast<Agent*>(ccast));
// doin a little magic to simulate each requester making their own request
RequestPortfolio<Material>::Ptr rp1(new RequestPortfolio<Material>());
Request<Material>* preq = rp1->AddRequest(mat, pcast, commod, pref);
pcast->port_ = rp1;
RequestPortfolio<Material>::Ptr rp2(new RequestPortfolio<Material>());
Request<Material>* creq = rp2->AddRequest(mat, ccast, commod, pref);
ccast->port_ = rp2;
EXPECT_EQ(0, pcast->req_ctr_);
EXPECT_EQ(0, ccast->req_ctr_);
exchng->AddAllRequests();
EXPECT_EQ(2, exchng->ex_ctx().requesters.size());
EXPECT_EQ(1, pcast->req_ctr_);
EXPECT_EQ(1, ccast->req_ctr_);
EXPECT_EQ(0, pcast->pref_ctr_);
EXPECT_EQ(0, ccast->pref_ctr_);
EXPECT_NO_THROW(exchng->AdjustAll());
// child gets to adjust once - its own request
// parent gets called twice - its request and adjusting its child's request
EXPECT_EQ(2, pcast->pref_ctr_);
EXPECT_EQ(1, ccast->pref_ctr_);
child->Decommission();
parent->Decommission();
}
TEST_F(<API key>, PrefValues) {
Facility* parent = dynamic_cast<Facility*>(reqr->Clone());
Facility* child = dynamic_cast<Facility*>(reqr->Clone());
parent->Build(NULL);
child->Build(parent);
Requester* pcast = dynamic_cast<Requester*>(parent);
Requester* ccast = dynamic_cast<Requester*>(child);
// doin a little magic to simulate each requester making their own request
RequestPortfolio<Material>::Ptr rp1(new RequestPortfolio<Material>());
Request<Material>* preq = rp1->AddRequest(mat, pcast, commod, pref);
pcast->port_ = rp1;
RequestPortfolio<Material>::Ptr rp2(new RequestPortfolio<Material>());
Request<Material>* creq = rp2->AddRequest(mat, ccast, commod, pref);
ccast->port_ = rp2;
Bidder* bidr = new Bidder(tc.get(), commod);
BidPortfolio<Material>::Ptr bp(new BidPortfolio<Material>());
Bid<Material>* pbid = bp->AddBid(preq, mat, bidr);
Bid<Material>* cbid = bp->AddBid(creq, mat, bidr);
std::vector<Bid<Material>*> bids;
bids.push_back(pbid);
bids.push_back(cbid);
bidr->port_ = bp;
Facility* bclone = dynamic_cast<Facility*>(bidr->Clone());
bclone->Build(NULL);
EXPECT_NO_THROW(exchng->AddAllRequests());
EXPECT_NO_THROW(exchng->AddAllBids());
PrefMap<Material>::type pobs;
pobs[preq].insert(std::make_pair(pbid, preq->preference()));
PrefMap<Material>::type cobs;
cobs[creq].insert(std::make_pair(cbid, creq->preference()));
ExchangeContext<Material>& context = exchng->ex_ctx();
EXPECT_EQ(context.trader_prefs[parent], pobs);
EXPECT_EQ(context.trader_prefs[child], cobs);
EXPECT_NO_THROW(exchng->AdjustAll());
pobs[preq].begin()->second = std::pow(preq->preference(), 2);
cobs[creq].begin()->second = std::pow(std::pow(creq->preference(), 2), 2);
EXPECT_EQ(context.trader_prefs[parent], pobs);
EXPECT_EQ(context.trader_prefs[child], cobs);
child->Decommission();
parent->Decommission();
}
|
<?php
class Foo_Bar_Model_Baz
{
}
|
<!DOCTYPE html>
<!-- DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py. -->
<title>OffscreenCanvas test: 2d.composite.uncovered.fill.copy</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/html/canvas/resources/canvas-tests.js"></script>
<h1>2d.composite.uncovered.fill.copy</h1>
<p class="desc">fill() draws pixels not covered by the source object as (0,0,0,0), and does not leave the pixels unchanged.</p>
<script>
var t = async_test("fill() draws pixels not covered by the source object as (0,0,0,0), and does not leave the pixels unchanged.");
var t_pass = t.done.bind(t);
var t_fail = t.step_func(function(reason) {
throw reason;
});
t.step(function() {
var offscreenCanvas = new OffscreenCanvas(100, 50);
var ctx = offscreenCanvas.getContext('2d');
ctx.fillStyle = 'rgba(0, 255, 0, 0.5)';
ctx.fillRect(0, 0, 100, 50);
ctx.<API key> = 'copy';
ctx.fillStyle = 'rgba(0, 0, 255, 0.75)';
ctx.translate(0, 25);
ctx.fillRect(0, 50, 100, 50);
_assertPixelApprox(offscreenCanvas, 50,25, 0,0,0,0, "50,25", "0,0,0,0", 5);
t.done();
});
</script>
|
#ifndef <API key>
#define <API key>
#pragma once
#include <vector>
namespace chrome_page_zoom {
// Return a sorted vector of zoom factors. The vector will consist of preset
// values along with a custom value (if the custom value is not already
// represented.)
std::vector<double> PresetZoomFactors(double custom_factor);
// Return a sorted vector of zoom levels. The vector will consist of preset
// values along with a custom value (if the custom value is not already
// represented.)
std::vector<double> PresetZoomLevels(double custom_level);
} // namespace chrome_page_zoom
#endif // <API key>
|
import py_utils
from telemetry import story as story_module
from telemetry.page import page as page_module
from telemetry.page import shared_page_state
class <API key>(shared_page_state.<API key>):
def <API key>(self):
return True
class LeakDetectionPage(page_module.Page):
def __init__(self, url, page_set, name=''):
super(LeakDetectionPage, self).__init__(
url=url, page_set=page_set, name=name,
<API key>=<API key>)
def RunNavigateSteps(self, action_runner):
tabs = action_runner.tab.browser.tabs
new_tab = tabs.New()
new_tab.action_runner.Navigate('about:blank')
new_tab.action_runner.<API key>()
new_tab.action_runner.MeasureMemory()
new_tab.action_runner.Navigate(self.url)
self.<API key>(new_tab.action_runner)
new_tab.action_runner.Navigate('about:blank')
new_tab.action_runner.<API key>()
new_tab.action_runner.MeasureMemory()
new_tab.Close()
def <API key>(self, action_runner):
py_utils.WaitFor(action_runner.tab.<API key>, timeout=30)
# Some websites have a script that loads resources continuously, in which cases
# <API key> would not be reached. This class waits for document ready
# state to be complete to avoid timeout for those pages.
class <API key>(LeakDetectionPage):
def <API key>(self, action_runner):
action_runner.tab.<API key>()
class <API key>(story_module.StorySet):
def __init__(self):
super(<API key>, self).__init__(
archive_data_file='data/leak_detection.json',
<API key>=story_module.PARTNER_BUCKET)
urls_list = [
# Alexa top websites
'https:
'https:
'https:
'https:
'https:
'https://world.taobao.com/',
'https:
'http:
'http:
'https:
'http:
'https://vk.com/',
'https://outlook.live.com',
'https:
'https://weibo.com/',
'https:
'https:
'https://yandex.ru/',
'https:
'https:
'https:
'https:
'https:
'https:
'https:
'https:
# TODO(keishi): Memory dump fails flakily crbug.com/963273
# TODO(keishi): Memory dump fails flakily crbug.com/963273
# TODO(keishi): Memory dump fails flakily crbug.com/963273
'https://mail.ru/',
'https:
'http:
'https:
'https:
'https:
'https:
'https://news.google.com/',
'https:
'https:
# TODO(keishi): Memory dump fails flakily crbug.com/963273
'https://weather.com/',
'https:
'https://docs.google.com/',
'https://wordpress.com/',
# TODO(yuzus): This test crashes.
'https://play.google.com/store',
'https:
'https://soundcloud.com/',
'https://vimeo.com/',
'https:
'https:
'https:
'https:
'https:
'https:
# TODO(keishi): Memory dump fails flakily crbug.com/963273
'https:
'https:
'https://9gag.com/',
'https:
'https:
'https:
'https:
# TODO(keishi): Memory dump fails flakily crbug.com/963273
'https:
# Times out waiting for <API key> - crbug.com/927427
'https:
'https:
'https:
'https://archive.org/',
'https:
'https://answers.yahoo.com/',
# TODO(crbug.com/985552): Memory dump fails flakily.
'https:
'http:
'http://siteadvisor.com/',
'https:
'https:
'http://europa.eu/',
'https://translate.google.com/',
'https:
'http:
'https://play.na.leagueoflegends.com/',
'https:
'https:
'https:
'https:
'https:
'https:
# India Alexa top websites
'https://porn555.com/',
'https:
'https:
'https:
'https:
'https://stackoverflow.com/',
# TODO(crbug.com/1005035) Memory dump fails flakily.
'https:
'https:
'https://uidai.gov.in/',
'https://billdesk.com/',
'https:
# US Alexa top websites
'https://imgur.com/',
'https:
'https:
# TODO(892352): tumblr started timing out due to a catapult roll. See
'https:
'https://edition.cnn.com/',
'https:
# TODO(keishi): Memory dump fails flakily crbug.com/963273
'https://github.com/',
'https:
# Japan Alexa top websites
'https:
'http:
'https://fc2.com/',
'https://ameblo.jp/',
'http://kakaku.com/',
'https:
'https:
# websites which were found to be leaking in the past
'https:
# TODO(keishi): Memory dump fails flakily crbug.com/963273
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
# TODO(953195): Test times out.
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http://zzz.com.ua',
'http://a-rakumo.appspot.com',
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http://whu.edu.cn',
'http://support.wordpress.com',
'http:
'http:
'http:
'http://hdu.edu.cn',
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http:
'http://makfax.com.mk',
'http://game.co.za',
'http:
'http:
]
<API key> = [
'https:
'https:
# TODO(keishi): Memory dump fails flakily crbug.com/963273
'http:
'https:
'http://infomoney.com.br',
'http:
'https:
'https:
'http:
'http:
'http:
]
for url in urls_list:
self.AddStory(LeakDetectionPage(url, self, url))
for url in <API key>:
self.AddStory(<API key>(url, self, url))
|
#ifndef <API key>
#define <API key>
#include "aom_dsp/blend.h"
#include "aom_dsp/x86/synonyms.h"
static const uint8_t <API key>[32] = {
0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15,
0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15,
};
// Common kernels
static INLINE __m128i blend_4(const uint8_t *src0, const uint8_t *src1,
const __m128i *v_m0_w, const __m128i *v_m1_w) {
const __m128i v_s0_b = xx_loadl_32(src0);
const __m128i v_s1_b = xx_loadl_32(src1);
const __m128i v_s0_w = _mm_cvtepu8_epi16(v_s0_b);
const __m128i v_s1_w = _mm_cvtepu8_epi16(v_s1_b);
const __m128i v_p0_w = _mm_mullo_epi16(v_s0_w, *v_m0_w);
const __m128i v_p1_w = _mm_mullo_epi16(v_s1_w, *v_m1_w);
const __m128i v_sum_w = _mm_add_epi16(v_p0_w, v_p1_w);
const __m128i v_res_w = xx_roundn_epu16(v_sum_w, <API key>);
return v_res_w;
}
static INLINE __m128i blend_8(const uint8_t *src0, const uint8_t *src1,
const __m128i *v_m0_w, const __m128i *v_m1_w) {
const __m128i v_s0_b = xx_loadl_64(src0);
const __m128i v_s1_b = xx_loadl_64(src1);
const __m128i v_s0_w = _mm_cvtepu8_epi16(v_s0_b);
const __m128i v_s1_w = _mm_cvtepu8_epi16(v_s1_b);
const __m128i v_p0_w = _mm_mullo_epi16(v_s0_w, *v_m0_w);
const __m128i v_p1_w = _mm_mullo_epi16(v_s1_w, *v_m1_w);
const __m128i v_sum_w = _mm_add_epi16(v_p0_w, v_p1_w);
const __m128i v_res_w = xx_roundn_epu16(v_sum_w, <API key>);
return v_res_w;
}
static INLINE __m128i blend_4_u8(const uint8_t *src0, const uint8_t *src1,
const __m128i *v_m0_b, const __m128i *v_m1_b,
const __m128i *rounding) {
const __m128i v_s0_b = xx_loadl_32(src0);
const __m128i v_s1_b = xx_loadl_32(src1);
const __m128i v_p0_w = _mm_maddubs_epi16(_mm_unpacklo_epi8(v_s0_b, v_s1_b),
_mm_unpacklo_epi8(*v_m0_b, *v_m1_b));
const __m128i v_res_w = _mm_mulhrs_epi16(v_p0_w, *rounding);
const __m128i v_res = _mm_packus_epi16(v_res_w, v_res_w);
return v_res;
}
static INLINE __m128i blend_8_u8(const uint8_t *src0, const uint8_t *src1,
const __m128i *v_m0_b, const __m128i *v_m1_b,
const __m128i *rounding) {
const __m128i v_s0_b = xx_loadl_64(src0);
const __m128i v_s1_b = xx_loadl_64(src1);
const __m128i v_p0_w = _mm_maddubs_epi16(_mm_unpacklo_epi8(v_s0_b, v_s1_b),
_mm_unpacklo_epi8(*v_m0_b, *v_m1_b));
const __m128i v_res_w = _mm_mulhrs_epi16(v_p0_w, *rounding);
const __m128i v_res = _mm_packus_epi16(v_res_w, v_res_w);
return v_res;
}
static INLINE __m128i blend_16_u8(const uint8_t *src0, const uint8_t *src1,
const __m128i *v_m0_b, const __m128i *v_m1_b,
const __m128i *rounding) {
const __m128i v_s0_b = xx_loadu_128(src0);
const __m128i v_s1_b = xx_loadu_128(src1);
const __m128i v_p0_w = _mm_maddubs_epi16(_mm_unpacklo_epi8(v_s0_b, v_s1_b),
_mm_unpacklo_epi8(*v_m0_b, *v_m1_b));
const __m128i v_p1_w = _mm_maddubs_epi16(_mm_unpackhi_epi8(v_s0_b, v_s1_b),
_mm_unpackhi_epi8(*v_m0_b, *v_m1_b));
const __m128i v_res0_w = _mm_mulhrs_epi16(v_p0_w, *rounding);
const __m128i v_res1_w = _mm_mulhrs_epi16(v_p1_w, *rounding);
const __m128i v_res = _mm_packus_epi16(v_res0_w, v_res1_w);
return v_res;
}
typedef __m128i (*blend_unit_fn)(const uint16_t *src0, const uint16_t *src1,
const __m128i v_m0_w, const __m128i v_m1_w);
static INLINE __m128i blend_4_b10(const uint16_t *src0, const uint16_t *src1,
const __m128i v_m0_w, const __m128i v_m1_w) {
const __m128i v_s0_w = xx_loadl_64(src0);
const __m128i v_s1_w = xx_loadl_64(src1);
const __m128i v_p0_w = _mm_mullo_epi16(v_s0_w, v_m0_w);
const __m128i v_p1_w = _mm_mullo_epi16(v_s1_w, v_m1_w);
const __m128i v_sum_w = _mm_add_epi16(v_p0_w, v_p1_w);
const __m128i v_res_w = xx_roundn_epu16(v_sum_w, <API key>);
return v_res_w;
}
static INLINE __m128i blend_8_b10(const uint16_t *src0, const uint16_t *src1,
const __m128i v_m0_w, const __m128i v_m1_w) {
const __m128i v_s0_w = xx_loadu_128(src0);
const __m128i v_s1_w = xx_loadu_128(src1);
const __m128i v_p0_w = _mm_mullo_epi16(v_s0_w, v_m0_w);
const __m128i v_p1_w = _mm_mullo_epi16(v_s1_w, v_m1_w);
const __m128i v_sum_w = _mm_add_epi16(v_p0_w, v_p1_w);
const __m128i v_res_w = xx_roundn_epu16(v_sum_w, <API key>);
return v_res_w;
}
static INLINE __m128i blend_4_b12(const uint16_t *src0, const uint16_t *src1,
const __m128i v_m0_w, const __m128i v_m1_w) {
const __m128i v_s0_w = xx_loadl_64(src0);
const __m128i v_s1_w = xx_loadl_64(src1);
// Interleave
const __m128i v_m01_w = _mm_unpacklo_epi16(v_m0_w, v_m1_w);
const __m128i v_s01_w = _mm_unpacklo_epi16(v_s0_w, v_s1_w);
// Multiply-Add
const __m128i v_sum_d = _mm_madd_epi16(v_s01_w, v_m01_w);
// Scale
const __m128i v_ssum_d =
_mm_srli_epi32(v_sum_d, <API key> - 1);
// Pack
const __m128i v_pssum_d = _mm_packs_epi32(v_ssum_d, v_ssum_d);
// Round
const __m128i v_res_w = xx_round_epu16(v_pssum_d);
return v_res_w;
}
static INLINE __m128i blend_8_b12(const uint16_t *src0, const uint16_t *src1,
const __m128i v_m0_w, const __m128i v_m1_w) {
const __m128i v_s0_w = xx_loadu_128(src0);
const __m128i v_s1_w = xx_loadu_128(src1);
// Interleave
const __m128i v_m01l_w = _mm_unpacklo_epi16(v_m0_w, v_m1_w);
const __m128i v_m01h_w = _mm_unpackhi_epi16(v_m0_w, v_m1_w);
const __m128i v_s01l_w = _mm_unpacklo_epi16(v_s0_w, v_s1_w);
const __m128i v_s01h_w = _mm_unpackhi_epi16(v_s0_w, v_s1_w);
// Multiply-Add
const __m128i v_suml_d = _mm_madd_epi16(v_s01l_w, v_m01l_w);
const __m128i v_sumh_d = _mm_madd_epi16(v_s01h_w, v_m01h_w);
// Scale
const __m128i v_ssuml_d =
_mm_srli_epi32(v_suml_d, <API key> - 1);
const __m128i v_ssumh_d =
_mm_srli_epi32(v_sumh_d, <API key> - 1);
// Pack
const __m128i v_pssum_d = _mm_packs_epi32(v_ssuml_d, v_ssumh_d);
// Round
const __m128i v_res_w = xx_round_epu16(v_pssum_d);
return v_res_w;
}
#endif // <API key>
|
// libjingle
// modification, are permitted provided that the following conditions are met:
// and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 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.
// Implementation of VideoRecorder and FileVideoCapturer.
#include "talk/media/devices/filevideocapturer.h"
#include "talk/base/bytebuffer.h"
#include "talk/base/logging.h"
#include "talk/base/thread.h"
namespace cricket {
// Implementation of class VideoRecorder
bool VideoRecorder::Start(const std::string& filename, bool write_header) {
Stop();
write_header_ = write_header;
int err;
if (!video_file_.Open(filename, "wb", &err)) {
LOG(LS_ERROR) << "Unable to open file " << filename << " err=" << err;
return false;
}
return true;
}
void VideoRecorder::Stop() {
video_file_.Close();
}
bool VideoRecorder::RecordFrame(const CapturedFrame& frame) {
if (talk_base::SS_CLOSED == video_file_.GetState()) {
LOG(LS_ERROR) << "File not opened yet";
return false;
}
uint32 size = 0;
if (!frame.GetDataSize(&size)) {
LOG(LS_ERROR) << "Unable to calculate the data size of the frame";
return false;
}
if (write_header_) {
// Convert the frame header to bytebuffer.
talk_base::ByteBuffer buffer;
buffer.WriteUInt32(frame.width);
buffer.WriteUInt32(frame.height);
buffer.WriteUInt32(frame.fourcc);
buffer.WriteUInt32(frame.pixel_width);
buffer.WriteUInt32(frame.pixel_height);
buffer.WriteUInt64(frame.elapsed_time);
buffer.WriteUInt64(frame.time_stamp);
buffer.WriteUInt32(size);
// Write the bytebuffer to file.
if (talk_base::SR_SUCCESS != video_file_.Write(buffer.Data(),
buffer.Length(),
NULL,
NULL)) {
LOG(LS_ERROR) << "Failed to write frame header";
return false;
}
}
// Write the frame data to file.
if (talk_base::SR_SUCCESS != video_file_.Write(frame.data,
size,
NULL,
NULL)) {
LOG(LS_ERROR) << "Failed to write frame data";
return false;
}
return true;
}
// Definition of private class FileReadThread that periodically reads
// frames from a file.
class FileVideoCapturer::FileReadThread
: public talk_base::Thread, public talk_base::MessageHandler {
public:
explicit FileReadThread(FileVideoCapturer* capturer)
: capturer_(capturer),
finished_(false) {
}
// Override virtual method of parent Thread. Context: Worker Thread.
virtual void Run() {
// Read the first frame and start the message pump. The pump runs until
// Stop() is called externally or Quit() is called by OnMessage().
int waiting_time_ms = 0;
if (capturer_ && capturer_->ReadFrame(true, &waiting_time_ms)) {
PostDelayed(waiting_time_ms, this);
Thread::Run();
}
finished_ = true;
}
// Override virtual method of parent MessageHandler. Context: Worker Thread.
virtual void OnMessage(talk_base::Message* /*pmsg*/) {
int waiting_time_ms = 0;
if (capturer_ && capturer_->ReadFrame(false, &waiting_time_ms)) {
PostDelayed(waiting_time_ms, this);
} else {
Quit();
}
}
// Check if Run() is finished.
bool Finished() const { return finished_; }
private:
FileVideoCapturer* capturer_;
bool finished_;
<API key>(FileReadThread);
};
// Implementation of class FileVideoCapturer
static const int64 <API key> = 1000000;
const char* FileVideoCapturer::<API key> = "video-file:";
FileVideoCapturer::FileVideoCapturer()
: frame_buffer_size_(0),
file_read_thread_(NULL),
repeat_(0),
start_time_ns_(0),
<API key>(0),
ignore_framerate_(false) {
}
FileVideoCapturer::~FileVideoCapturer() {
Stop();
delete[] static_cast<char*>(captured_frame_.data);
}
bool FileVideoCapturer::Init(const Device& device) {
if (!FileVideoCapturer::<API key>(device)) {
return false;
}
std::string filename(device.name);
if (IsRunning()) {
LOG(LS_ERROR) << "The file video capturer is already running";
return false;
}
// Open the file.
int err;
if (!video_file_.Open(filename, "rb", &err)) {
LOG(LS_ERROR) << "Unable to open the file " << filename << " err=" << err;
return false;
}
// Read the first frame's header to determine the supported format.
CapturedFrame frame;
if (talk_base::SR_SUCCESS != ReadFrameHeader(&frame)) {
LOG(LS_ERROR) << "Failed to read the first frame header";
video_file_.Close();
return false;
}
// Seek back to the start of the file.
if (!video_file_.SetPosition(0)) {
LOG(LS_ERROR) << "Failed to seek back to beginning of the file";
video_file_.Close();
return false;
}
// Enumerate the supported formats. We have only one supported format. We set
// the frame interval to kMinimumInterval here. In Start(), if the capture
// format's interval is greater than kMinimumInterval, we use the interval;
// otherwise, we use the timestamp in the file to control the interval.
VideoFormat format(frame.width, frame.height, VideoFormat::kMinimumInterval,
frame.fourcc);
std::vector<VideoFormat> supported;
supported.push_back(format);
SetId(device.id);
SetSupportedFormats(supported);
return true;
}
bool FileVideoCapturer::Init(const std::string& filename) {
return Init(FileVideoCapturer::<API key>(filename));
}
CaptureState FileVideoCapturer::Start(const VideoFormat& capture_format) {
if (IsRunning()) {
LOG(LS_ERROR) << "The file video capturer is already running";
return CS_FAILED;
}
if (talk_base::SS_CLOSED == video_file_.GetState()) {
LOG(LS_ERROR) << "File not opened yet";
return CS_NO_DEVICE;
} else if (!video_file_.SetPosition(0)) {
LOG(LS_ERROR) << "Failed to seek back to beginning of the file";
return CS_FAILED;
}
SetCaptureFormat(&capture_format);
// Create a thread to read the file.
file_read_thread_ = new FileReadThread(this);
bool ret = file_read_thread_->Start();
start_time_ns_ = <API key> *
static_cast<int64>(talk_base::Time());
if (ret) {
LOG(LS_INFO) << "File video capturer '" << GetId() << "' started";
return CS_RUNNING;
} else {
LOG(LS_ERROR) << "File video capturer '" << GetId() << "' failed to start";
return CS_FAILED;
}
}
bool FileVideoCapturer::IsRunning() {
return file_read_thread_ && !file_read_thread_->Finished();
}
void FileVideoCapturer::Stop() {
if (file_read_thread_) {
file_read_thread_->Stop();
file_read_thread_ = NULL;
LOG(LS_INFO) << "File video capturer '" << GetId() << "' stopped";
}
SetCaptureFormat(NULL);
}
bool FileVideoCapturer::GetPreferredFourccs(std::vector<uint32>* fourccs) {
if (!fourccs) {
return false;
}
fourccs->push_back(GetSupportedFormats()->at(0).fourcc);
return true;
}
talk_base::StreamResult FileVideoCapturer::ReadFrameHeader(
CapturedFrame* frame) {
// We first read kFrameHeaderSize bytes from the file stream to a memory
// buffer, then construct a bytebuffer from the memory buffer, and finally
// read the frame header from the bytebuffer.
char header[CapturedFrame::kFrameHeaderSize];
talk_base::StreamResult sr;
size_t bytes_read;
int error;
sr = video_file_.Read(header,
CapturedFrame::kFrameHeaderSize,
&bytes_read,
&error);
LOG(LS_VERBOSE) << "Read frame header: stream_result = " << sr
<< ", bytes read = " << bytes_read << ", error = " << error;
if (talk_base::SR_SUCCESS == sr) {
if (CapturedFrame::kFrameHeaderSize != bytes_read) {
return talk_base::SR_EOS;
}
talk_base::ByteBuffer buffer(header, CapturedFrame::kFrameHeaderSize);
buffer.ReadUInt32(reinterpret_cast<uint32*>(&frame->width));
buffer.ReadUInt32(reinterpret_cast<uint32*>(&frame->height));
buffer.ReadUInt32(&frame->fourcc);
buffer.ReadUInt32(&frame->pixel_width);
buffer.ReadUInt32(&frame->pixel_height);
buffer.ReadUInt64(reinterpret_cast<uint64*>(&frame->elapsed_time));
buffer.ReadUInt64(reinterpret_cast<uint64*>(&frame->time_stamp));
buffer.ReadUInt32(&frame->data_size);
}
return sr;
}
// Executed in the context of FileReadThread.
bool FileVideoCapturer::ReadFrame(bool first_frame, int* wait_time_ms) {
uint32 start_read_time_ms = talk_base::Time();
// 1. Signal the previously read frame to downstream.
if (!first_frame) {
captured_frame_.time_stamp = <API key> *
static_cast<int64>(start_read_time_ms);
captured_frame_.elapsed_time = captured_frame_.time_stamp - start_time_ns_;
SignalFrameCaptured(this, &captured_frame_);
}
// 2. Read the next frame.
if (talk_base::SS_CLOSED == video_file_.GetState()) {
LOG(LS_ERROR) << "File not opened yet";
return false;
}
// 2.1 Read the frame header.
talk_base::StreamResult result = ReadFrameHeader(&captured_frame_);
if (talk_base::SR_EOS == result) { // Loop back if repeat.
if (repeat_ != talk_base::kForever) {
if (repeat_ > 0) {
--repeat_;
} else {
return false;
}
}
if (video_file_.SetPosition(0)) {
result = ReadFrameHeader(&captured_frame_);
}
}
if (talk_base::SR_SUCCESS != result) {
LOG(LS_ERROR) << "Failed to read the frame header";
return false;
}
// 2.2 Reallocate memory for the frame data if necessary.
if (frame_buffer_size_ < captured_frame_.data_size) {
frame_buffer_size_ = captured_frame_.data_size;
delete[] static_cast<char*>(captured_frame_.data);
captured_frame_.data = new char[frame_buffer_size_];
}
// 2.3 Read the frame adata.
if (talk_base::SR_SUCCESS != video_file_.Read(captured_frame_.data,
captured_frame_.data_size,
NULL, NULL)) {
LOG(LS_ERROR) << "Failed to read frame data";
return false;
}
// 3. Decide how long to wait for the next frame.
*wait_time_ms = 0;
// If the capture format's interval is not kMinimumInterval, we use it to
// control the rate; otherwise, we use the timestamp in the file to control
// the rate.
if (!first_frame && !ignore_framerate_) {
int64 interval_ns =
GetCaptureFormat()->interval > VideoFormat::kMinimumInterval ?
GetCaptureFormat()->interval :
captured_frame_.time_stamp - <API key>;
int interval_ms = static_cast<int>(interval_ns / <API key>);
interval_ms -= talk_base::Time() - start_read_time_ms;
if (interval_ms > 0) {
*wait_time_ms = interval_ms;
}
}
// Keep the original timestamp read from the file.
<API key> = captured_frame_.time_stamp;
return true;
}
} // namespace cricket
|
package collectors
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"bosun.org/metadata"
"bosun.org/opentsdb"
)
var (
rmqQueueStatusMap = map[string]int{
"running": 0,
"syncing": 1,
"flow": 2,
"idle": 3,
"down": 4,
}
)
const (
defaultRabbitmqURL string = "http://guest:guest@localhost:15672"
rmqPrefix = "rabbitmq."
)
func init() {
collectors = append(collectors, &IntervalCollector{F: c_rabbitmq_overview, Enable: enableRabbitmq})
collectors = append(collectors, &IntervalCollector{F: c_rabbitmq_queues, Enable: enableRabbitmq})
collectors = append(collectors, &IntervalCollector{F: c_rabbitmq_nodes, Enable: enableRabbitmq})
}
// RabbitMQ registers a RabbitMQ collector.
func RabbitMQ(url string) error {
safeURL, err := urlUserHost(url)
if err != nil {
return err
}
collectors = append(collectors,
&IntervalCollector{
F: func() (opentsdb.MultiDataPoint, error) {
return rabbitmqOverview(url)
},
name: fmt.Sprintf("rabbitmq-overview-%s", safeURL),
},
&IntervalCollector{
F: func() (opentsdb.MultiDataPoint, error) {
return rabbitmqNodes(url)
},
name: fmt.Sprintf("rabbitmq-nodes-%s", safeURL),
},
&IntervalCollector{
F: func() (opentsdb.MultiDataPoint, error) {
return rabbitmqQueues(url)
},
name: fmt.Sprintf("rabbitmq-queues-%s", safeURL),
})
return nil
}
func enableRabbitmq() bool {
return enableURL(defaultRabbitmqURL)()
}
func c_rabbitmq_overview() (opentsdb.MultiDataPoint, error) {
return rabbitmqOverview(defaultRabbitmqURL)
}
func c_rabbitmq_nodes() (opentsdb.MultiDataPoint, error) {
return rabbitmqNodes(defaultRabbitmqURL)
}
func c_rabbitmq_queues() (opentsdb.MultiDataPoint, error) {
return rabbitmqQueues(defaultRabbitmqURL)
}
func rabbitmqOverview(s string) (opentsdb.MultiDataPoint, error) {
p := rmqPrefix + "overview."
res, err := http.Get(s + "/api/overview")
if err != nil {
return nil, err
}
defer res.Body.Close()
var o rmqOverview
if err := json.NewDecoder(res.Body).Decode(&o); err != nil {
return nil, err
}
var md opentsdb.MultiDataPoint
splitNode := strings.Split(o.Node, "@")
if len(splitNode) < 2 {
return nil, fmt.Errorf("Error: invalid RabbitMQ node name, can not split '%s'", o.Node)
}
host := splitNode[1]
ts := opentsdb.TagSet{"host": host}
Add(&md, p+"channels", o.ObjectTotals.Channels, ts, metadata.Gauge, metadata.Channel, <API key>)
Add(&md, p+"connections", o.ObjectTotals.Connections, ts, metadata.Gauge, metadata.Connection, <API key>)
Add(&md, p+"consumers", o.ObjectTotals.Consumers, ts, metadata.Gauge, metadata.Consumer, <API key>)
Add(&md, p+"exchanges", o.ObjectTotals.Exchanges, ts, metadata.Gauge, metadata.Exchange, <API key>)
Add(&md, p+"queues", o.ObjectTotals.Queues, ts, metadata.Gauge, metadata.Queue, <API key>)
msgStats := <API key>(p, ts, o.MessageStats)
md = append(md, msgStats...)
return md, nil
}
func rabbitmqQueues(s string) (opentsdb.MultiDataPoint, error) {
p := rmqPrefix + "queue."
res, err := http.Get(s + "/api/queues")
if err != nil {
return nil, err
}
defer res.Body.Close()
var qs []rmqQueue
if err := json.NewDecoder(res.Body).Decode(&qs); err != nil {
return nil, err
}
var md opentsdb.MultiDataPoint
for _, q := range qs {
if strings.HasPrefix(q.Name, "amq.gen-") {
continue // skip auto-generated queues
}
splitNode := strings.Split(q.Node, "@")
if len(splitNode) < 2 {
return nil, fmt.Errorf("Error: invalid RabbitMQ node name, can not split '%s'", q.Node)
}
host := splitNode[1]
ts := opentsdb.TagSet{"host": host, "queue": q.Name, "vhost": q.Vhost}
Add(&md, p+"consumers", q.Consumers, ts, metadata.Gauge, metadata.Consumer, DescRmqConsumers)
Add(&md, p+"memory", q.Memory, ts, metadata.Gauge, metadata.Bytes, DescRmqMemory)
Add(&md, p+"message_bytes_total", q.MessageBytes, ts, metadata.Gauge, metadata.Bytes, DescRmqMessageBytes)
Add(&md, p+"<API key>", q.<API key>, ts, metadata.Gauge, metadata.Bytes, <API key>)
Add(&md, p+"<API key>", q.MessageBytesRAM, ts, metadata.Gauge, metadata.Bytes, <API key>)
Add(&md, p+"message_bytes_ready", q.MessageBytesReady, ts, metadata.Gauge, metadata.Bytes, <API key>)
Add(&md, p+"message_bytes_unack", q.<API key>, ts, metadata.Gauge, metadata.Bytes, <API key>)
Add(&md, p+"<API key>", q.Messages, ts, metadata.Gauge, metadata.Message, DescRmqMessages)
Add(&md, p+"messages_persistent", q.MessagesPersistent, ts, metadata.Gauge, metadata.Message, <API key>)
Add(&md, p+"messages_transient", q.MessagesRAM, ts, metadata.Gauge, metadata.Message, DescRmqMessagesRAM)
Add(&md, p+"<API key>", q.MessagesReady, ts, metadata.Gauge, metadata.Message, <API key>)
Add(&md, p+"<API key>", q.MessagesReadyRAM, ts, metadata.Gauge, metadata.Message, <API key>)
Add(&md, p+"<API key>", q.<API key>, ts, metadata.Gauge, metadata.Message, <API key>)
Add(&md, p+"<API key>", q.<API key>, ts, metadata.Gauge, metadata.Message, <API key>)
if sn, ok := q.SlaveNodes.([]interface{}); ok {
Add(&md, p+"slave_nodes", len(sn), ts, metadata.Gauge, metadata.Node, DescRmqSlaveNodes)
}
if dsn, ok := q.DownSlaveNodes.([]interface{}); ok {
Add(&md, p+"down_slave_nodes", len(dsn), ts, metadata.Gauge, metadata.Node, <API key>)
}
if ssn, ok := q.<API key>.([]interface{}); ok {
Add(&md, p+"sync_slave_nodes", len(ssn), ts, metadata.Gauge, metadata.Node, <API key>)
}
if cu, ok := q.ConsumerUtilisation.(float64); ok {
Add(&md, p+"<API key>", cu, ts, metadata.Gauge, metadata.Fraction, <API key>)
}
msgStats := <API key>(p, ts, q.MessageStats)
md = append(md, msgStats...)
backingQueueStatus := <API key>(p+"backing_queue.", ts, q.BackingQueueStatus)
md = append(md, backingQueueStatus...)
if state, ok := rmqQueueStatusMap[q.State]; ok {
Add(&md, p+"state", state, ts, metadata.Gauge, metadata.StatusCode, DescRmqState)
} else {
Add(&md, p+"state", -1, ts, metadata.Gauge, metadata.StatusCode, DescRmqState)
}
}
return md, nil
}
func rabbitmqNodes(s string) (opentsdb.MultiDataPoint, error) {
p := rmqPrefix + "node."
res, err := http.Get(s + "/api/nodes")
if err != nil {
return nil, err
}
defer res.Body.Close()
var ns []rmqNode
if err := json.NewDecoder(res.Body).Decode(&ns); err != nil {
return nil, err
}
var md opentsdb.MultiDataPoint
for _, n := range ns {
splitName := strings.Split(n.Name, "@")
if len(splitName) < 2 {
return nil, fmt.Errorf("Error: invalid RabbitMQ node name, can not split '%s'", n.Name)
}
host := splitName[1]
ts := opentsdb.TagSet{"host": host}
Add(&md, p+"disk_free", n.DiskFree, ts, metadata.Gauge, metadata.Consumer, DescRmqDiskFree)
Add(&md, p+"disk_free_alarm", n.DiskFreeAlarm, ts, metadata.Gauge, metadata.Bool, <API key>)
Add(&md, p+"disk_free_limit", n.DiskFreeLimit, ts, metadata.Gauge, metadata.Consumer, <API key>)
Add(&md, p+"fd_total", n.FDTotal, ts, metadata.Gauge, metadata.Files, DescRmqFDTotal)
Add(&md, p+"fd_used", n.FDUsed, ts, metadata.Gauge, metadata.Files, DescRmqFDUsed)
Add(&md, p+"mem_used", n.MemUsed, ts, metadata.Gauge, metadata.Bytes, DescRmqMemUsed)
Add(&md, p+"mem_alarm", n.MemAlarm, ts, metadata.Gauge, metadata.Bool, DescRmqMemAlarm)
Add(&md, p+"mem_limit", n.MemLimit, ts, metadata.Gauge, metadata.Bytes, DescRmqMemLimit)
Add(&md, p+"proc_used", n.ProcUsed, ts, metadata.Gauge, metadata.Process, DescRmqProcUsed)
Add(&md, p+"proc_total", n.ProcTotal, ts, metadata.Gauge, metadata.Process, DescRmqProcTotal)
Add(&md, p+"sockets_used", n.SocketsUsed, ts, metadata.Gauge, metadata.Socket, DescRmqSocketsUsed)
Add(&md, p+"sockets_total", n.SocketsTotal, ts, metadata.Gauge, metadata.Socket, DescRmqSocketsTotal)
Add(&md, p+"uptime", n.Uptime, ts, metadata.Gauge, metadata.Second, DescRmqUptime)
Add(&md, p+"running", n.Running, ts, metadata.Gauge, metadata.StatusCode, DescRmqRunning)
if partitions, ok := n.Partitions.([]interface{}); ok {
Add(&md, p+"partitions", len(partitions), ts, metadata.Gauge, metadata.Node, DescRmqPartitions)
}
}
return md, nil
}
func <API key>(p string, ts opentsdb.TagSet, ms rmqMessageStats) opentsdb.MultiDataPoint {
var md opentsdb.MultiDataPoint
Add(&md, p+"message_stats", ms.Ack, ts.Copy().Merge(opentsdb.TagSet{"method": "ack"}),
metadata.Counter, metadata.Message, <API key>)
Add(&md, p+"message_stats", ms.Confirm, ts.Copy().Merge(opentsdb.TagSet{"method": "confirm"}),
metadata.Counter, metadata.Message, <API key>)
Add(&md, p+"message_stats", ms.Deliver, ts.Copy().Merge(opentsdb.TagSet{"method": "deliver"}),
metadata.Counter, metadata.Message, <API key>)
Add(&md, p+"message_stats", ms.DeliverGet, ts.Copy().Merge(opentsdb.TagSet{"method": "deliver_get"}),
metadata.Counter, metadata.Message, <API key>)
Add(&md, p+"message_stats", ms.DeliverNoAck, ts.Copy().Merge(opentsdb.TagSet{"method": "deliver_noack"}),
metadata.Counter, metadata.Message, <API key>)
Add(&md, p+"message_stats", ms.Get, ts.Copy().Merge(opentsdb.TagSet{"method": "get"}),
metadata.Counter, metadata.Message, <API key>)
Add(&md, p+"message_stats", ms.GetNoAck, ts.Copy().Merge(opentsdb.TagSet{"method": "get_noack"}),
metadata.Counter, metadata.Message, <API key>)
Add(&md, p+"message_stats", ms.Publish, ts.Copy().Merge(opentsdb.TagSet{"method": "publish"}),
metadata.Counter, metadata.Message, <API key>)
Add(&md, p+"message_stats", ms.PublishIn, ts.Copy().Merge(opentsdb.TagSet{"method": "publish_in"}),
metadata.Counter, metadata.Message, <API key>)
Add(&md, p+"message_stats", ms.PublishOut, ts.Copy().Merge(opentsdb.TagSet{"method": "publish_out"}),
metadata.Counter, metadata.Message, <API key>)
Add(&md, p+"message_stats", ms.Redeliver, ts.Copy().Merge(opentsdb.TagSet{"method": "redeliver"}),
metadata.Counter, metadata.Message, <API key>)
Add(&md, p+"message_stats", ms.Return, ts.Copy().Merge(opentsdb.TagSet{"method": "return"}),
metadata.Counter, metadata.Message, <API key>)
return md
}
func <API key>(p string, ts opentsdb.TagSet, bqs <API key>) opentsdb.MultiDataPoint {
var md opentsdb.MultiDataPoint
Add(&md, p+"avg_rate", bqs.AvgAckEgressRate, ts.Copy().Merge(opentsdb.TagSet{"method": "ack", "direction": "out"}),
metadata.Rate, metadata.Message, <API key>)
Add(&md, p+"avg_rate", bqs.AvgAckIngressRate, ts.Copy().Merge(opentsdb.TagSet{"method": "ack", "direction": "in"}),
metadata.Rate, metadata.Message, <API key>)
Add(&md, p+"avg_rate", bqs.AvgEgressRate, ts.Copy().Merge(opentsdb.TagSet{"method": "noack", "direction": "out"}),
metadata.Rate, metadata.Message, <API key>)
Add(&md, p+"avg_rate", bqs.AvgIngressRate, ts.Copy().Merge(opentsdb.TagSet{"method": "noack", "direction": "in"}),
metadata.Rate, metadata.Message, <API key>)
Add(&md, p+"len", bqs.Len, ts,
metadata.Gauge, metadata.Message, <API key>)
return md
}
func urlUserHost(s string) (string, error) {
u, err := url.Parse(s)
if err != nil {
return "", err
}
if u.User != nil {
res := fmt.Sprintf("%s@%s", u.User.Username(), u.Host)
return res, nil
}
res := fmt.Sprintf("%s", u.Host)
return res, nil
}
type rmqOverview struct {
ClusterName string `json:"cluster_name"`
MessageStats rmqMessageStats `json:"message_stats"`
QueueTotals struct {
Messages int `json:"messages"`
MessagesReady int `json:"messages_ready"`
<API key> int `json:"<API key>"`
} `json:"queue_totals"`
ObjectTotals struct {
Consumers int `json:"consumers"`
Queues int `json:"queues"`
Exchanges int `json:"exchanges"`
Connections int `json:"connections"`
Channels int `json:"channels"`
} `json:"object_totals"`
Node string `json:"node"`
}
type rmqNode struct {
DiskFree int64 `json:"disk_free"`
DiskFreeAlarm bool `json:"disk_free_alarm"`
DiskFreeLimit int `json:"disk_free_limit"`
FDTotal int `json:"fd_total"`
FDUsed int `json:"fd_used"`
MemAlarm bool `json:"mem_alarm"`
MemLimit int64 `json:"mem_limit"`
MemUsed int `json:"mem_used"`
Name string `json:"name"`
Partitions interface{} `json:"partitions"`
ProcTotal int `json:"proc_total"`
ProcUsed int `json:"proc_used"`
Processors int `json:"processors"`
RunQueue int `json:"run_queue"`
Running bool `json:"running"`
SocketsTotal int `json:"sockets_total"`
SocketsUsed int `json:"sockets_used"`
Uptime int `json:"uptime"`
}
type rmqQueue struct {
Messages int `json:"messages"`
MessagesReady int `json:"messages_ready"`
<API key> int `json:"<API key>"`
Consumers int `json:"consumers"`
ConsumerUtilisation interface{} `json:"<API key>"`
Memory int `json:"memory"`
SlaveNodes interface{} `json:"slave_nodes"`
<API key> interface{} `json:"<API key>"`
DownSlaveNodes interface{} `json:"down_slave_nodes"`
BackingQueueStatus <API key> `json:"<API key>"`
State string `json:"state"`
MessagesRAM int `json:"messages_ram"`
MessagesReadyRAM int `json:"messages_ready_ram"`
<API key> int `json:"<API key>"`
MessagesPersistent int `json:"messages_persistent"`
MessageBytes int `json:"message_bytes"`
MessageBytesReady int `json:"message_bytes_ready"`
<API key> int `json:"<API key>"`
MessageBytesRAM int `json:"message_bytes_ram"`
<API key> int `json:"<API key>"`
Name string `json:"name"`
Vhost string `json:"vhost"`
Durable bool `json:"durable"`
Node string `json:"node"`
MessageStats rmqMessageStats `json:"message_stats"`
}
type rmqMessageStats struct {
Ack int `json:"ack"`
Confirm int `json:"confirm"`
Deliver int `json:"deliver"`
DeliverGet int `json:"deliver_get"`
DeliverNoAck int `json:"deliver_no_ack"`
Get int `json:"get"`
GetAck int `json:"get_ack"`
GetNoAck int `json:"get_noack"`
Publish int `json:"publish"`
PublishIn int `json:"publish_in"`
PublishOut int `json:"publish_out"`
Redeliver int `json:"redeliver"`
Return int `json:"return"`
}
type <API key> struct {
Len int `json:"len"`
AvgIngressRate float64 `json:"avg_ingress_rate"`
AvgEgressRate float64 `json:"avg_egress_rate"`
AvgAckIngressRate float64 `json:"<API key>"`
AvgAckEgressRate float64 `json:"avg_ack_egress_rate"`
MirrorSeen int `json:"mirror_seen"`
MirrorSenders int `json:"mirror_senders"`
}
const (
<API key> = "Rate at which unacknowledged message records leave RAM, e.g. because acks arrive or unacked messages are paged out"
<API key> = "Rate at which unacknowledged message records enter RAM, e.g. because messages are delivered requiring acknowledgement"
<API key> = "Average egress (outbound) rate, not including messages that straight through to auto-acking consumers."
<API key> = "Average ingress (inbound) rate, not including messages that straight through to auto-acking consumers."
<API key> = "Total backing queue length."
DescRmqConsumers = "Number of consumers."
<API key> = "Fraction of the time (between 0.0 and 1.0) that the queue is able to immediately deliver messages to consumers. This can be less than 1.0 if consumers are limited by network congestion or prefetch count."
<API key> = "Whether the disk alarm has gone off."
DescRmqDiskFree = "Disk free space in bytes."
<API key> = "Point at which the disk alarm will go off."
<API key> = "Count of down nodes having a copy of the queue."
DescRmqFDTotal = "File descriptors available."
DescRmqFDUsed = "Used file descriptors."
<API key> = "Average wall time (milliseconds) for each disk read operation in the last statistics interval."
DescRmqIOReadBytes = "Total number of bytes read from disk by the persister."
DescRmqIOReadCount = "Total number of read operations by the persister."
<API key> = "Total number of times the persister has needed to recycle file handles between queues. In an ideal world this number will be zero; if the number is large, performance might be improved by increasing the number of file handles available to RabbitMQ."
<API key> = "Average wall time (milliseconds) for each seek operation in the last statistics interval."
DescRmqIOSeekCount = "Total number of seek operations by the persister."
<API key> = "Average wall time (milliseconds) for each sync operation in the last statistics interval."
DescRmqIOSyncCount = "Total number of fsync() operations by the persister."
<API key> = "Average wall time (milliseconds) for each write operation in the last statistics interval."
DescRmqIOWriteBytes = "Total number of bytes written to disk by the persister."
DescRmqIOWriteCount = "Total number of write operations by the persister."
DescRmqMemAlarm = ""
DescRmqMemLimit = "Point at which the memory alarm will go off."
DescRmqMemory = "Bytes of memory consumed by the Erlang process associated with the queue, including stack, heap and internal structures."
DescRmqMemUsed = "Memory used in bytes."
<API key> = "Like messageBytes but counting only those messages which are persistent."
<API key> = "Like messageBytes but counting only those messages which are in RAM."
<API key> = "Like messageBytes but counting only those messages ready to be delivered to clients."
DescRmqMessageBytes = "Sum of the size of all message bodies in the queue. This does not include the message properties (including headers) or any overhead."
<API key> = "Like messageBytes but counting only those messages delivered to clients but not yet acknowledged."
<API key> = "Total number of persistent messages in the queue (will always be 0 for transient queues)."
DescRmqMessagesRAM = "Total number of messages which are resident in ram."
<API key> = "Number of messages ready to be delivered to clients."
<API key> = "Number of messages from messagesReady which are resident in ram."
DescRmqMessages = "Sum of ready and unacknowledged messages (queue depth)."
<API key> = "Count of acknowledged messages."
<API key> = "Count of messages confirmed."
<API key> = "Count of messages delivered in acknowledgement mode to consumers."
<API key> = "Sum of deliver, deliverNoack, get, getNoack."
<API key> = "Count of messages delivered in no-acknowledgement mode to consumers."
<API key> = "Count of messages delivered in acknowledgement mode in response to basic.get."
<API key> = "Count of messages delivered in no-acknowledgement mode in response to basic.get."
<API key> = "Count of messages published."
<API key> = "Count of messages published \"in\" to an exchange, i.e. not taking account of routing."
<API key> = "Count of messages published \"out\" of an exchange, i.e. taking account of routing."
<API key> = "Count of subset of messages in deliverGet which had the redelivered flag set."
<API key> = "Count of messages returned to publisher as unroutable."
<API key> = "Number of messages delivered to clients but not yet acknowledged."
<API key> = "Number of messages from <API key> which are resident in ram."
<API key> = "Number of Mnesia transactions which have been performed that required writes to disk. (e.g. creating a durable queue). Only transactions which originated on this node are included."
<API key> = "Number of Mnesia transactions which have been performed that did not require writes to disk. (e.g. creating a transient queue). Only transactions which originated on this node are included."
<API key> = "Number of messages which have been read from the message store."
<API key> = "Number of messages which have been written to the message store."
<API key> = "Overall number of channels."
<API key> = "Overall number of connections."
<API key> = "Overall number of consumers."
<API key> = "Overall number of exchanges."
<API key> = "Overall number of queues."
DescRmqPartitions = "Count of network partitions this node is seeing."
DescRmqProcessors = "Number of cores detected and usable by Erlang."
DescRmqProcTotal = "Maximum number of Erlang processes."
DescRmqProcUsed = "Number of Erlang processes in use."
<API key> = "Number of records written to the queue index journal. Each record represents a message being published to a queue, being delivered from a queue, and being acknowledged in a queue."
<API key> = "Number of records read from the queue index."
<API key> = "Number of records written to the queue index."
<API key> = "Overall sum of ready and unacknowledged messages (queue depth)."
<API key> = "Overall number of messages ready to be delivered to clients."
<API key> = "Overall number of messages delivered to clients but not yet acknowledged."
DescRmqRunning = "Boolean for whether this node is up. Obviously if this is false, most other stats will be missing."
DescRmqRunQueue = "Average number of Erlang processes waiting to run."
DescRmqSlaveNodes = "Count of nodes having a copy of the queue."
DescRmqSocketsTotal = "File descriptors available for use as sockets."
DescRmqSocketsUsed = "File descriptors used as sockets."
DescRmqState = "The state of the queue. Unknown=> -1, Running=> 0, Syncing=> 1, Flow=> 2, Down=> 3"
<API key> = "Count of nodes having synchronised copy of the queue."
DescRmqSyncMessages = "Count of already synchronised messages on a slave node."
DescRmqUptime = "Node uptime in seconds."
)
|
require "spec_helper"
describe ProjectWiki, models: true do
let(:project) { create(:empty_project) }
let(:repository) { project.repository }
let(:user) { project.owner }
let(:gitlab_shell) { Gitlab::Shell.new }
let(:project_wiki) { ProjectWiki.new(project, user) }
subject { project_wiki }
before { project_wiki.wiki }
describe "#path_with_namespace" do
it "returns the project path with namespace with the .wiki extension" do
expect(subject.path_with_namespace).to eq(project.path_with_namespace + ".wiki")
end
end
describe '#web_url' do
it 'returns the full web URL to the wiki' do
expect(subject.web_url).to eq("#{Gitlab.config.gitlab.url}/#{project.path_with_namespace}/wikis/home")
end
end
describe "#url_to_repo" do
it "returns the correct ssh url to the repo" do
expect(subject.url_to_repo).to eq(gitlab_shell.url_to_repo(subject.path_with_namespace))
end
end
describe "#ssh_url_to_repo" do
it "equals #url_to_repo" do
expect(subject.ssh_url_to_repo).to eq(subject.url_to_repo)
end
end
describe "#http_url_to_repo" do
it "provides the full http url to the repo" do
gitlab_url = Gitlab.config.gitlab.url
repo_http_url = "#{gitlab_url}/#{subject.path_with_namespace}.git"
expect(subject.http_url_to_repo).to eq(repo_http_url)
end
end
describe "#wiki_base_path" do
it "returns the wiki base path" do
wiki_base_path = "#{Gitlab.config.gitlab.relative_url_root}/#{project.path_with_namespace}/wikis"
expect(subject.wiki_base_path).to eq(wiki_base_path)
end
end
describe "#wiki" do
it "contains a Gollum::Wiki instance" do
expect(subject.wiki).to be_a Gollum::Wiki
end
it "creates a new wiki repo if one does not yet exist" do
expect(project_wiki.create_page("index", "test content")).to be_truthy
end
it "raises <API key> if it can't create the wiki repository" do
allow(project_wiki).to receive(:init_repo).and_return(false)
expect { project_wiki.send(:create_repo!) }.to raise_exception(ProjectWiki::<API key>)
end
end
describe "#empty?" do
context "when the wiki repository is empty" do
before do
<API key>(Gitlab::Shell).to receive(:add_repository) do
create_temp_repo("#{Rails.root}/tmp/test-git-base-path/non-existant.wiki.git")
end
allow(project).to receive(:path_with_namespace).and_return("non-existant")
end
describe '#empty?' do
subject { super().empty? }
it { is_expected.to be_truthy }
end
end
context "when the wiki has pages" do
before do
project_wiki.create_page("index", "This is an awesome new Gollum Wiki")
end
describe '#empty?' do
subject { super().empty? }
it { is_expected.to be_falsey }
end
end
end
describe "#pages" do
before do
create_page("index", "This is an awesome new Gollum Wiki")
@pages = subject.pages
end
after do
destroy_page(@pages.first.page)
end
it "returns an array of WikiPage instances" do
expect(@pages.first).to be_a WikiPage
end
it "returns the correct number of pages" do
expect(@pages.count).to eq(1)
end
end
describe "#find_page" do
before do
create_page("index page", "This is an awesome Gollum Wiki")
end
after do
destroy_page(subject.pages.first.page)
end
it "returns the latest version of the page if it exists" do
page = subject.find_page("index page")
expect(page.title).to eq("index page")
end
it "returns nil if the page does not exist" do
expect(subject.find_page("non-existant")).to eq(nil)
end
it "can find a page by slug" do
page = subject.find_page("index-page")
expect(page.title).to eq("index page")
end
it "returns a WikiPage instance" do
page = subject.find_page("index page")
expect(page).to be_a WikiPage
end
end
describe '#find_file' do
before do
file = Gollum::File.new(subject.wiki)
<API key>(Gollum::Wiki).
to receive(:file).with('image.jpg', 'master', true).
and_return(file)
<API key>(Gollum::File).
to receive(:mime_type).
and_return('image/jpeg')
<API key>(Gollum::Wiki).
to receive(:file).with('non-existant', 'master', true).
and_return(nil)
end
after do
<API key>(Gollum::Wiki).to receive(:file).and_call_original
<API key>(Gollum::File).to receive(:mime_type).and_call_original
end
it 'returns the latest version of the file if it exists' do
file = subject.find_file('image.jpg')
expect(file.mime_type).to eq('image/jpeg')
end
it 'returns nil if the page does not exist' do
expect(subject.find_file('non-existant')).to eq(nil)
end
it 'returns a Gollum::File instance' do
file = subject.find_file('image.jpg')
expect(file).to be_a Gollum::File
end
end
describe "#create_page" do
after do
destroy_page(subject.pages.first.page)
end
it "creates a new wiki page" do
expect(subject.create_page("test page", "this is content")).not_to eq(false)
expect(subject.pages.count).to eq(1)
end
it "returns false when a duplicate page exists" do
subject.create_page("test page", "content")
expect(subject.create_page("test page", "content")).to eq(false)
end
it "stores an error message when a duplicate page exists" do
2.times { subject.create_page("test page", "content") }
expect(subject.error_message).to match(/Duplicate page:/)
end
it "sets the correct commit message" do
subject.create_page("test page", "some content", :markdown, "commit message")
expect(subject.pages.first.page.version.message).to eq("commit message")
end
it 'updates project activity' do
expect(subject).to receive(:<API key>)
subject.create_page('Test Page', 'This is content')
end
end
describe "#update_page" do
before do
create_page("update-page", "some content")
@gollum_page = subject.wiki.paged("update-page")
subject.update_page(@gollum_page, "some other content", :markdown, "updated page")
@page = subject.pages.first.page
end
after do
destroy_page(@page)
end
it "updates the content of the page" do
expect(@page.raw_data).to eq("some other content")
end
it "sets the correct commit message" do
expect(@page.version.message).to eq("updated page")
end
it 'updates project activity' do
expect(subject).to receive(:<API key>)
subject.update_page(@gollum_page, 'Yet more content', :markdown, 'Updated page again')
end
end
describe "#delete_page" do
before do
create_page("index", "some content")
@page = subject.wiki.paged("index")
end
it "deletes the page" do
subject.delete_page(@page)
expect(subject.pages.count).to eq(0)
end
it 'updates project activity' do
expect(subject).to receive(:<API key>)
subject.delete_page(@page)
end
end
describe '#create_repo!' do
it 'creates a repository' do
expect(subject).to receive(:init_repo).
with(subject.path_with_namespace).
and_return(true)
expect(subject.repository).to receive(:after_create)
expect(subject.create_repo!).to be_an_instance_of(Gollum::Wiki)
end
end
describe '#hook_attrs' do
it 'returns a hash with values' do
expect(subject.hook_attrs).to be_a Hash
expect(subject.hook_attrs.keys).to contain_exactly(:web_url, :git_ssh_url, :git_http_url, :path_with_namespace, :default_branch)
end
end
private
def create_temp_repo(path)
FileUtils.mkdir_p path
system(*%W(#{Gitlab.config.git.bin_path} init --quiet --bare -- #{path}))
end
def remove_temp_repo(path)
FileUtils.rm_rf path
end
def commit_details
{ name: user.name, email: user.email, message: "test commit" }
end
def create_page(name, content)
subject.wiki.write_page(name, :markdown, content, commit_details)
end
def destroy_page(page)
subject.wiki.delete_page(page, commit_details)
end
end
|
class StaticController < <API key>
def guidelines
@title = t('static.guidelines.title')
end
def guidelines_tips
@title = t('static.guidelines_tips.title')
end
def faq
@title = t('static.faq.title')
end
def thank_you
backer = Backer.find session[:thank_you_backer_id]
redirect_to [backer.project, backer]
end
def sitemap
# TODO: update this sitemap to use new homepage logic
@home_page ||= Project.includes(:user, :category).visible.limit(6).all
@expiring ||= Project.includes(:user, :category).visible.expiring.not_expired.order("(projects.expires_at), created_at DESC").limit(3).all
@recent ||= Project.includes(:user, :category).visible.not_expiring.not_expired.where("projects.user_id <> 7329").order('created_at DESC').limit(3).all
@successful ||= Project.includes(:user, :category).visible.successful.order("(projects.expires_at) DESC").limit(3).all
return render 'sitemap'
end
end
|
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
// This object is used to wrap a bunch of ConnectAsync operations
// on behalf of a single user call to ConnectAsync with a DnsEndPoint
internal abstract class <API key>
{
protected <API key> _userArgs;
protected <API key> _internalArgs;
protected DnsEndPoint _endPoint;
protected IPAddress[] _addressList;
protected int _nextAddress;
private enum State
{
NotStarted,
DnsQuery,
ConnectAttempt,
Completed,
Canceled,
}
private State _state;
private object _lockObject = new object();
// Called by Socket to kick off the ConnectAsync process. We'll complete the user's SAEA
// when it's done. Returns true if the operation will be asynchronous, false if it has failed synchronously
public bool StartConnectAsync(<API key> args, DnsEndPoint endPoint)
{
lock (_lockObject)
{
if (endPoint.AddressFamily != AddressFamily.Unspecified &&
endPoint.AddressFamily != AddressFamily.InterNetwork &&
endPoint.AddressFamily != AddressFamily.InterNetworkV6)
{
NetEventSource.Fail(this, $"Unexpected endpoint address family: {endPoint.AddressFamily}");
}
_userArgs = args;
_endPoint = endPoint;
// If Cancel() was called before we got the lock, it only set the state to Canceled: we need to
// fail synchronously from here. Once State.DnsQuery is set, the Cancel() call will handle calling AsyncFail.
if (_state == State.Canceled)
{
SyncFail(new SocketException((int)SocketError.OperationAborted));
return false;
}
if (_state != State.NotStarted)
{
NetEventSource.Fail(this, "<API key>.StartConnectAsync(): Unexpected object state");
}
_state = State.DnsQuery;
IAsyncResult result = Dns.<API key>(endPoint.Host, new AsyncCallback(DnsCallback), null);
if (result.<API key>)
{
return DoDnsCallback(result, true);
}
else
{
return true;
}
}
}
// Callback which fires when the Dns Resolve is complete
private void DnsCallback(IAsyncResult result)
{
if (!result.<API key>)
{
DoDnsCallback(result, false);
}
}
// Called when the DNS query completes (either synchronously or asynchronously). Checks for failure and
// starts the first connection attempt if it succeeded. Returns true if the operation will be asynchronous,
// false if it has failed synchronously.
private bool DoDnsCallback(IAsyncResult result, bool sync)
{
Exception exception = null;
lock (_lockObject)
{
// If the connection attempt was canceled during the dns query, the user's callback has already been
// called asynchronously and we simply need to return.
if (_state == State.Canceled)
{
return true;
}
if (_state != State.DnsQuery)
{
NetEventSource.Fail(this, "<API key>.DoDnsCallback(): Unexpected object state");
}
try
{
_addressList = Dns.EndGetHostAddresses(result);
if (_addressList == null)
{
NetEventSource.Fail(this, "<API key>.DoDnsCallback(): EndGetHostAddresses returned null!");
}
}
catch (Exception e)
{
_state = State.Completed;
exception = e;
}
// If the dns query succeeded, try to connect to the first address
if (exception == null)
{
_state = State.ConnectAttempt;
_internalArgs = new <API key>();
_internalArgs.Completed += <API key>;
_internalArgs.CopyBufferFrom(_userArgs);
exception = AttemptConnection();
if (exception != null)
{
// There was a synchronous error while connecting
_state = State.Completed;
}
}
}
// Call this outside of the lock because it might call the user's callback.
if (exception != null)
{
return Fail(sync, exception);
}
else
{
return true;
}
}
// Callback which fires when an internal connection attempt completes.
// If it failed and there are more addresses to try, do it.
private void <API key>(object sender, <API key> args)
{
Exception exception = null;
lock (_lockObject)
{
if (_state == State.Canceled)
{
// If Cancel was called before we got the lock, the Socket will be closed soon. We need to report
// OperationAborted (even though the connection actually completed), or the user will try to use a
// closed Socket.
exception = new SocketException((int)SocketError.OperationAborted);
}
else
{
Debug.Assert(_state == State.ConnectAttempt);
if (args.SocketError == SocketError.Success)
{
// The connection attempt succeeded; go to the completed state.
// The callback will be called outside the lock.
_state = State.Completed;
}
else if (args.SocketError == SocketError.OperationAborted)
{
// The socket was closed while the connect was in progress. This can happen if the user
// closes the socket, and is equivalent to a call to CancelConnectAsync
exception = new SocketException((int)SocketError.OperationAborted);
_state = State.Canceled;
}
else
{
// Keep track of this because it will be overwritten by AttemptConnection
SocketError currentFailure = args.SocketError;
Exception connectException = AttemptConnection();
if (connectException == null)
{
// don't call the callback, another connection attempt is successfully started
return;
}
else
{
SocketException socketException = connectException as SocketException;
if (socketException != null && socketException.SocketErrorCode == SocketError.NoData)
{
// If the error is NoData, that means there are no more IPAddresses to attempt
// a connection to. Return the last error from an actual connection instead.
exception = new SocketException((int)currentFailure);
}
else
{
exception = connectException;
}
_state = State.Completed;
}
}
}
}
if (exception == null)
{
Succeed();
}
else
{
AsyncFail(exception);
}
}
// Called to initiate a connection attempt to the next address in the list. Returns an exception
// if the attempt failed synchronously, or null if it was successfully initiated.
private Exception AttemptConnection()
{
try
{
Socket attemptSocket;
IPAddress attemptAddress = GetNextAddress(out attemptSocket);
if (attemptAddress == null)
{
return new SocketException((int)SocketError.NoData);
}
_internalArgs.RemoteEndPoint = new IPEndPoint(attemptAddress, _endPoint.Port);
return AttemptConnection(attemptSocket, _internalArgs);
}
catch (Exception e)
{
if (e is <API key>)
{
NetEventSource.Fail(this, "unexpected <API key>");
}
return e;
}
}
private Exception AttemptConnection(Socket attemptSocket, <API key> args)
{
try
{
if (attemptSocket == null)
{
NetEventSource.Fail(null, "attemptSocket is null!");
}
bool pending = attemptSocket.ConnectAsync(args);
if (!pending)
{
<API key>(null, args);
}
}
catch (<API key>)
{
// This can happen if the user closes the socket, and is equivalent to a call
// to CancelConnectAsync
return new SocketException((int)SocketError.OperationAborted);
}
catch (Exception e)
{
return e;
}
return null;
}
protected abstract void OnSucceed();
private void Succeed()
{
OnSucceed();
_userArgs.<API key>(_internalArgs.ConnectSocket, _internalArgs.BytesTransferred, _internalArgs.SocketFlags);
_internalArgs.Dispose();
}
protected abstract void OnFail(bool abortive);
private bool Fail(bool sync, Exception e)
{
if (sync)
{
SyncFail(e);
return false;
}
else
{
AsyncFail(e);
return true;
}
}
private void SyncFail(Exception e)
{
OnFail(false);
if (_internalArgs != null)
{
_internalArgs.Dispose();
}
SocketException socketException = e as SocketException;
if (socketException != null)
{
_userArgs.<API key>(socketException, 0, SocketFlags.None);
}
else
{
<API key>.Throw(e);
}
}
private void AsyncFail(Exception e)
{
OnFail(false);
if (_internalArgs != null)
{
_internalArgs.Dispose();
}
_userArgs.<API key>(e, 0, SocketFlags.None);
}
public void Cancel()
{
bool callOnFail = false;
lock (_lockObject)
{
switch (_state)
{
case State.NotStarted:
// Cancel was called before the Dns query was started. The dns query won't be started
// and the connection attempt will fail synchronously after the state change to DnsQuery.
// All we need to do here is close all the sockets.
callOnFail = true;
break;
case State.DnsQuery:
// Cancel was called after the Dns query was started, but before it finished. We can't
// actually cancel the Dns query, but we'll fake it by failing the connect attempt asynchronously
// from here, and silently dropping the connection attempt when the Dns query finishes.
Task.Factory.StartNew(
s => CallAsyncFail(s),
null,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
callOnFail = true;
break;
case State.ConnectAttempt:
// Cancel was called after the Dns query completed, but before we had a connection result to give
// to the user. Closing the sockets will cause any in-progress ConnectAsync call to fail immediately
// with OperationAborted, and will cause <API key> from any new calls to ConnectAsync
// (which will be translated to OperationAborted by AttemptConnection).
callOnFail = true;
break;
case State.Completed:
// Cancel was called after we locked in a result to give to the user. Ignore it and give the user
// the real completion.
break;
default:
NetEventSource.Fail(this, "Unexpected object state");
break;
}
_state = State.Canceled;
}
// Call this outside the lock because Socket.Close may block
if (callOnFail)
{
OnFail(true);
}
}
// Call AsyncFail on a threadpool thread so it's asynchronous with respect to Cancel().
private void CallAsyncFail(object ignored)
{
AsyncFail(new SocketException((int)SocketError.OperationAborted));
}
protected abstract IPAddress GetNextAddress(out Socket attemptSocket);
}
// Used when the instance ConnectAsync method is called, or when the DnsEndPoint specified
// an AddressFamily. There's only one Socket, and we only try addresses that match its
// AddressFamily
internal sealed class <API key> : <API key>
{
private Socket _socket;
private bool _userSocket;
public <API key>(Socket socket, bool userSocket)
{
_socket = socket;
_userSocket = userSocket;
}
protected override IPAddress GetNextAddress(out Socket attemptSocket)
{
_socket.<API key>();
IPAddress rval = null;
do
{
if (_nextAddress >= _addressList.Length)
{
attemptSocket = null;
return null;
}
rval = _addressList[_nextAddress];
++_nextAddress;
}
while (!_socket.CanTryAddressFamily(rval.AddressFamily));
attemptSocket = _socket;
return rval;
}
protected override void OnFail(bool abortive)
{
// Close the socket if this is an abortive failure (CancelConnectAsync)
// or if we created it internally
if (abortive || !_userSocket)
{
_socket.Dispose();
}
}
// nothing to do on success
protected override void OnSucceed() { }
}
// This is used when the static ConnectAsync method is called. We don't know the address family
// ahead of time, so we create both IPv4 and IPv6 sockets.
internal sealed class <API key> : <API key>
{
private Socket _socket4;
private Socket _socket6;
public <API key>(SocketType socketType, ProtocolType protocolType)
{
if (Socket.OSSupportsIPv4)
{
_socket4 = new Socket(AddressFamily.InterNetwork, socketType, protocolType);
}
if (Socket.OSSupportsIPv6)
{
_socket6 = new Socket(AddressFamily.InterNetworkV6, socketType, protocolType);
}
}
protected override IPAddress GetNextAddress(out Socket attemptSocket)
{
IPAddress rval = null;
attemptSocket = null;
while (attemptSocket == null)
{
if (_nextAddress >= _addressList.Length)
{
return null;
}
rval = _addressList[_nextAddress];
++_nextAddress;
if (rval.AddressFamily == AddressFamily.InterNetworkV6)
{
attemptSocket = _socket6;
}
else if (rval.AddressFamily == AddressFamily.InterNetwork)
{
attemptSocket = _socket4;
}
}
attemptSocket?.<API key>();
return rval;
}
// on success, close the socket that wasn't used
protected override void OnSucceed()
{
if (_socket4 != null && !_socket4.Connected)
{
_socket4.Dispose();
}
if (_socket6 != null && !_socket6.Connected)
{
_socket6.Dispose();
}
}
// close both sockets whether its abortive or not - we always create them internally
protected override void OnFail(bool abortive)
{
_socket4?.Dispose();
_socket6?.Dispose();
}
}
}
|
package org.knowm.xchange.ccex.dto.account;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
public class CCEXBalance {
private String Currency;
private BigDecimal Balance;
private BigDecimal Available;
private BigDecimal Pending;
private String CryptoAddress;
public CCEXBalance(
@JsonProperty("Currency") String currency,
@JsonProperty("Balance") BigDecimal balance,
@JsonProperty("Available") BigDecimal available,
@JsonProperty("Pending") BigDecimal pending,
@JsonProperty("CryptoAddress") String cryptoAddress) {
super();
Currency = currency;
Balance = balance;
Available = available;
Pending = pending;
CryptoAddress = cryptoAddress;
}
public String getCurrency() {
return Currency;
}
public void setCurrency(String currency) {
Currency = currency;
}
public BigDecimal getBalance() {
return Balance;
}
public void setBalance(BigDecimal balance) {
Balance = balance;
}
public BigDecimal getAvailable() {
return Available;
}
public void setAvailable(BigDecimal available) {
Available = available;
}
public BigDecimal getPending() {
return Pending;
}
public void setPending(BigDecimal pending) {
Pending = pending;
}
public String getCryptoAddress() {
return CryptoAddress;
}
public void setCryptoAddress(String cryptoAddress) {
CryptoAddress = cryptoAddress;
}
@Override
public String toString() {
return "CCEXBalance [Currency="
+ Currency
+ ", Balance="
+ Balance
+ ", Available="
+ Available
+ ", Pending="
+ Pending
+ ", CryptoAddress="
+ CryptoAddress
+ "]";
}
}
|
angular.module('ordercloud-address', [])
.directive('<API key>', <API key>)
.directive('<API key>', <API key>)
.filter('address', AddressFilter)
;
function <API key>(OCGeography) {
return {
restrict: 'E',
scope: {
address: '=',
isbilling: '='
},
templateUrl: 'common/address/templates/address.form.tpl.html',
link: function(scope) {
scope.countries = OCGeography.Countries;
scope.states = OCGeography.States;
}
};
}
function <API key>() {
return {
restrict: 'E',
scope: {
addressid: '@'
},
templateUrl: 'common/address/templates/address.info.tpl.html',
controller: 'AddressInfoCtrl',
controllerAs: 'addressInfo'
};
}
function AddressFilter() {
return function(address, option) {
if (!address) return null;
if (option === 'full') {
var result = [];
if (address.AddressName) {
result.push(address.AddressName);
}
result.push((address.FirstName ? address.FirstName + ' ' : '') + address.LastName);
result.push(address.Street1);
if (address.Street2) {
result.push(address.Street2);
}
result.push(address.City + ', ' + address.State + ' ' + address.Zip);
return result.join('\n');
}
else {
return address.Street1 + (address.Street2 ? ', ' + address.Street2 : '');
}
}
}
|
#pragma once
namespace graphic
{
class cCube
{
public:
cCube();
cCube(const Vector3 &vMin, const Vector3 &vMax );
void SetCube(const Vector3 &vMin, const Vector3 &vMax );
void SetTransform( const Matrix44 &tm );
void SetColor( DWORD color);
const Matrix44& GetTransform() const;
const Vector3& GetMin() const;
const Vector3& GetMax() const;
void Render(const Matrix44 &tm);
protected:
void InitCube();
private:
cVertexBuffer m_vtxBuff;
cIndexBuffer m_idxBuff;
Vector3 m_min;
Vector3 m_max;
Matrix44 m_tm;
};
inline void cCube::SetTransform( const Matrix44 &tm ) { m_tm = tm; }
inline const Matrix44& cCube::GetTransform() const { return m_tm; }
inline const Vector3& cCube::GetMin() const { return m_min; }
inline const Vector3& cCube::GetMax() const { return m_max; }
}
|
// RUN: %clang_cc1 -verify -fopenmp=libiomp5 %s
void foo() {
}
bool foobool(int argc) {
return argc;
}
struct S1; // expected-note {{declared here}}
template <class T, typename S, int N, int ST> // expected-note {{declared here}}
T tmain(T argc, S **argv) { //expected-note 2 {{declared here}}
#pragma omp parallel for collapse // expected-error {{expected '(' after 'collapse'}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp parallel for collapse ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp parallel for collapse () // expected-error {{expected expression}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
// expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}}
// expected-error@+2 2 {{expression is not an integral constant expression}}
// expected-note@+1 2 {{read of non-const variable 'argc' is not allowed in a constant expression}}
#pragma omp parallel for collapse (argc
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
// expected-error@+1 2 {{argument to 'collapse' clause must be a positive integer value}}
#pragma omp parallel for collapse (ST // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp parallel for collapse (1)) // expected-warning {{extra tokens at the end of '#pragma omp parallel for' are ignored}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp parallel for collapse ((ST > 0) ? 1 + ST : 2) // expected-note 2 {{as specified in 'collapse' clause}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error 2 {{expected 2 for loops after '#pragma omp parallel for', but found only 1}}
// expected-error@+3 2 {{directive '#pragma omp parallel for' cannot contain more than one 'collapse' clause}}
// expected-error@+2 2 {{argument to 'collapse' clause must be a positive integer value}}
// expected-error@+1 2 {{expression is not an integral constant expression}}
#pragma omp parallel for collapse (foobool(argc)), collapse (true), collapse (-5)
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp parallel for collapse (S) // expected-error {{'S' does not refer to a value}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
// expected-error@+1 2 {{expression is not an integral constant expression}}
#pragma omp parallel for collapse (argv[1]=2) // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp parallel for collapse (1)
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp parallel for collapse (N) // expected-error {{argument to 'collapse' clause must be a positive integer value}}
for (T i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp parallel for collapse (2) // expected-note {{as specified in 'collapse' clause}}
foo(); // expected-error {{expected 2 for loops after '#pragma omp parallel for'}}
return argc;
}
int main(int argc, char **argv) {
#pragma omp parallel for collapse // expected-error {{expected '(' after 'collapse'}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
#pragma omp parallel for collapse ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
#pragma omp parallel for collapse () // expected-error {{expected expression}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
#pragma omp parallel for collapse (4 // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-note {{as specified in 'collapse' clause}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error {{expected 4 for loops after '#pragma omp parallel for', but found only 1}}
#pragma omp parallel for collapse (2+2)) // expected-warning {{extra tokens at the end of '#pragma omp parallel for' are ignored}} expected-note {{as specified in 'collapse' clause}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error {{expected 4 for loops after '#pragma omp parallel for', but found only 1}}
#pragma omp parallel for collapse (foobool(1) > 0 ? 1 : 2) // expected-error {{expression is not an integral constant expression}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
// expected-error@+3 {{expression is not an integral constant expression}}
// expected-error@+2 2 {{directive '#pragma omp parallel for' cannot contain more than one 'collapse' clause}}
// expected-error@+1 2 {{argument to 'collapse' clause must be a positive integer value}}
#pragma omp parallel for collapse (foobool(argc)), collapse (true), collapse (-5)
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
#pragma omp parallel for collapse (S1) // expected-error {{'S1' does not refer to a value}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
// expected-error@+1 {{expression is not an integral constant expression}}
#pragma omp parallel for collapse (argv[1]=2) // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
// expected-error@+3 {{statement after '#pragma omp parallel for' must be a for loop}}
// expected-note@+1 {{in instantiation of function template specialization 'tmain<int, char, -1, -2>' requested here}}
#pragma omp parallel for collapse(collapse(tmain<int, char, -1, -2>(argc, argv) // expected-error 2 {{expected ')'}} expected-note 2 {{to match this '('}}
foo();
#pragma omp parallel for collapse (2) // expected-note {{as specified in 'collapse' clause}}
foo(); // expected-error {{expected 2 for loops after '#pragma omp parallel for'}}
// expected-note@+1 {{in instantiation of function template specialization 'tmain<int, char, 1, 0>' requested here}}
return tmain<int, char, 1, 0>(argc, argv);
}
|
#!/bin/bash
export ORIGINAL_PATH=`pwd`
|
// SeqAn - The Library for Sequence Analysis
// modification, are permitted provided that the following conditions are met:
// documentation and/or other materials provided with the distribution.
// * Neither the name of Knut Reinert or the FU Berlin nor the names of
// its contributors may be used to endorse or promote products derived
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, 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.
// Shuffling.
#ifndef <API key>
#define <API key>
namespace seqan {
// Forwards, Tags.
// Classes
// Metafunctions
// Functions
/*!
* @fn shuffle
* @brief Shuffle the given container.
*
* @signature void shuffle(container, rng);
*
* @param[in,out] container The container to shuffle.
* @param[in,out] rng The random number generator to use.
*/
/**
.Function.shuffle
..summary:Shuffle the given container.
..cat:Random
..include:seqan/random.h
..signature:shuffle(container, rng)
..param.container:Container to shuffle elements of.
..param.rng:Random number generator to use.
type:Class.Rng
..wiki:Tutorial/Randomness#Shuffling|Tutorial: Randomness
*/
template <typename TContainer, typename TRNG>
void shuffle(TContainer & container, TRNG & rng)
{
SEQAN_CHECKPOINT;
typedef typename Position<TContainer>::Type TPosition;
typedef typename Value<TContainer>::Type TValue;
TValue tmp;
for (TPosition i = 0, iend = length(container); i < iend; ++i) {
Pdf<Uniform<TPosition> > uniformDist(i, iend - 1);
TPosition j = pickRandomNumber(rng, uniformDist);
// swap
move(tmp, container[i]);
move(container[i], container[j]);
move(container[j], tmp);
}
}
} // namespace seqan
#endif // <API key>
|
<?php
/**
* @author Mark van der Velden <mark@dynom.nl>
*/
namespace Faker\Test\Provider;
use Faker;
/**
* Class <API key>
*
* @package Faker\Test\Provider
*
* This class tests a large portion of all locale specific providers. It does not test the entire stack, because each
* locale specific provider (can) has specific implementations. The goal of this test is to test the common denominator
* and to try to catch possible invalid multi-byte sequences.
*/
class <API key> extends \<API key>
{
/**
* Constants with regular expression patterns for testing the output.
*
* Regular expressions are sensitive for malformed strings (e.g.: strings with incorrect encodings) so by using
* PCRE for the tests, even though they seem fairly pointless, we test for incorrect encodings also.
*/
const TEST_STRING_REGEX = '/.+/u';
/**
* Slightly more specific for e-mail, the point isn't to properly validate e-mails.
*/
const TEST_EMAIL_REGEX = '/^(.+)@(.+)$/ui';
/**
* @dataProvider localeDataProvider
* @param string $locale
*/
public function testAddress($locale = null)
{
$faker = Faker\Factory::create($locale);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->city);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->postcode);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->address);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->country);
}
/**
* @dataProvider localeDataProvider
* @param string $locale
*/
public function testCompany($locale = null)
{
$faker = Faker\Factory::create($locale);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->company);
}
/**
* @dataProvider localeDataProvider
* @param string $locale
*/
public function testDateTime($locale = null)
{
$faker = Faker\Factory::create($locale);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->century);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->timezone);
}
/**
* @dataProvider localeDataProvider
* @param string $locale
*/
public function testInternet($locale = null)
{
$faker = Faker\Factory::create($locale);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->userName);
$this->assertRegExp(static::TEST_EMAIL_REGEX, $faker->email);
$this->assertRegExp(static::TEST_EMAIL_REGEX, $faker->safeEmail);
$this->assertRegExp(static::TEST_EMAIL_REGEX, $faker->freeEmail);
$this->assertRegExp(static::TEST_EMAIL_REGEX, $faker->companyEmail);
}
/**
* @dataProvider localeDataProvider
* @param string $locale
*/
public function testPerson($locale = null)
{
$faker = Faker\Factory::create($locale);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->name);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->title);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->firstName);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->lastName);
}
/**
* @dataProvider localeDataProvider
* @param string $locale
*/
public function testPhoneNumber($locale = null)
{
$faker = Faker\Factory::create($locale);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->phoneNumber);
}
/**
* @dataProvider localeDataProvider
* @param string $locale
*/
public function testUserAgent($locale = null)
{
$faker = Faker\Factory::create($locale);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->userAgent);
}
/**
* @dataProvider localeDataProvider
*
* @param null $locale
* @param string $locale
*/
public function testUuid($locale = null)
{
$faker = Faker\Factory::create($locale);
$this->assertRegExp(static::TEST_STRING_REGEX, $faker->uuid);
}
/**
* @return array
*/
public function localeDataProvider()
{
$locales = $this->getAllLocales();
$data = array();
foreach ($locales as $locale) {
$data[] = array(
$locale
);
}
return $data;
}
/**
* Returns all locales as array values
*
* @return array
*/
private function getAllLocales()
{
static $locales = array();
if ( ! empty($locales)) {
return $locales;
}
// Finding all PHP files in the xx_XX directories
$providerDir = __DIR__ .'/../../../src/Faker/Provider';
foreach (glob($providerDir .'*.php') as $file) {
$localisation = basename(dirname($file));
if (isset($locales[ $localisation ])) {
continue;
}
$locales[ $localisation ] = $localisation;
}
return $locales;
}
}
|
<HTML>
<HEAD>
<TITLE>
Changes in TIFF v3.6.0
</TITLE>
</HEAD>
<BODY BGCOLOR=white>
<FONT FACE="Helvetica, Arial, Sans">
<FONT FACE="Helvetica, Arial, Sans">
<BASEFONT SIZE=4>
<B><FONT SIZE=+3>T</FONT>IFF <FONT SIZE=+2>C</FONT>HANGE <FONT SIZE=+2>I</FONT>NFORMATION</B>
<BASEFONT SIZE=3>
<UL>
<HR SIZE=4 WIDTH=65% ALIGN=left>
<B>Current Version</B>: v3.6.0<BR>
<B>Previous Version</B>: <A HREF=v3.5.7.html>v3.5.7</a><BR>
<B>Master FTP Site</B>: <A HREF="ftp://download.osgeo.org/libtiff">
download.osgeo.org</a>, directory pub/libtiff</A><BR>
<B>Master HTTP Site</B>: <A HREF="http:
http:
<HR SIZE=4 WIDTH=65% ALIGN=left>
</UL>
<P>
This document describes the changes made to the software between the
<I>previous</I> and <I>current</I> versions (see above).
If you don't find something listed here, then it was not done in this
timeframe, or it was not considered important enough to be mentioned.
The following information is located here:
<UL>
<LI><A HREF="#hightlights">Major Changes</A>
<LI><A HREF="#configure">Changes in the software configuration</A>
<LI><A HREF="#libtiff">Changes in libtiff</A>
<LI><A HREF="#tools">Changes in the tools</A>
<LI><A HREF="#contrib">Changes in the contrib area</A>
<LI><A HREF="#lzwkit">Changes in the LZW compression kit</A>
</UL>
<p>
<P><HR WIDTH=65% ALIGN=left>
<A NAME="highlights"><B><FONT SIZE=+3>M</FONT>AJOR CHANGES:</B></A>
<ul>
<li> New utility <a href=./man/raw2tiff.1.html>raw2tiff</a>
for converting raw rasters into TIFF files.
<li> Lots of new <a href=./man/tiff2ps.1.html>tiff2ps</a> options.
<li> Lots of new <a href=./man/fax2tiff.1.html>fax2tiff</a> options.
<li> Lots of bug fixes for LZW, JPEG and OJPEG compression.
</ul>
<h3>Custom Tag Support</h3>
The approach to extending libtiff with custom tags has changed radically.
Previously, all internally supported TIFF tags had a place in the
private TIFFDirectory structure within libtiff to hold the values (if read),
and a "field number" (ie. FIELD_SUBFILETYPE) used to identify that tag.
However, every time a new tag was added to the core, the size of the
TIFFDirectory structure would changing, breaking any dynamically linked
software that used the private data structures.<p>
Also, any tag not recognised
by libtiff would not be read and accessable to applications without some
fairly complicated work on the applications part to pre-register the tags
as exemplified by the support for "Geo"TIFF tags by libgeotiff layered on
libtiff. <p>
Amoung other things this approach required the extension code
to access the private libtiff structures ... which made the higher level
non-libtiff code be locked into a specific version of libtiff at compile time.
This caused no end of bug reports!<p>
The new approach is for libtiff to read all tags from TIFF files. Those that
aren't recognised as "core tags" (those having an associated FIELD_ value,
and place for storage in the TIFFDirectory structure) are now read into a
dynamic list of extra tags (td_customValues in TIFFDirectory). When a new
tag code is encountered for the first time in a given TIFF file, a new
anonymous tag definition is created for the tag in the tag definition list.
The type, and some other metadata is worked out from the instance encountered.
These fields are known as "custom tags". <p>
Custom tags can be set and fetched normally using TIFFSetField() and
TIFFGetField(), and appear pretty much like normal tags to application code.
However, they have no impact on internal libtiff processing (such as
compression). Some utilities, such as tiffcp will now copy these custom
tags to the new output files. <p>
As well as the internal work with custom tags, new C API entry points
were added so that extension libraries, such as libgeotiff, could
define new tags more easily without accessing internal data structures.
Because tag handling of extension tags is done via the "custom fields"
mechanism as well, the definition provided externally mostly serves to provide
a meaningful name for the tag.
The addition of "custom tags" and the altered approach to extending libtiff
with externally defined tags is the primary reason for the shift to the
3.6.x version number from 3.5.x.<p>
<P><HR WIDTH=65% ALIGN=left>
<A NAME="configure"><B><FONT SIZE=+3>C</FONT>HANGES IN THE SOFTWARE CONFIGURATION:</B></A>
<UL>
<li> configure, config.site: Fix for large files (>2GiB) support. New
option in the config.site: LARGEFILE="yes". Should be enougth for the large
files I/O.
<li> configure: Set -DPIXARLOG_SUPPORT option along with -DZIP_SUPPORT.
<li> html/Makefile.in: Updated to use groffhtml for generating html pages
from man pages.
<li> configure, libtiff/Makefile.in: Added SCO OpenServer 5.0.6 support
from John H. DuBois III.
<li> libtiff/{Makefile.vc, libtiff.def}: Missed declarations added.
<li> libtiff/Makefile.in, tools/Makefile.in: Shared library will not be
stripped when installing, utility binaries will do be stripped. As per bug 93.
<li> man/Makefile.in: Patch DESTDIR handling as per bug 95.
<li> configure: OpenBSD changes for Sparc64 and DSO version as per bug 96.
<li> config.site/configure: added support for OJPEG=yes option to enable
OJPEG support from config.site.
<li> config.guess, config.sub: Updated from ftp.gnu.org/pub/config.
<li> configure: Modify CheckForBigEndian so it can work in a cross
compiled situation.
<li> configure, libtiff/Makefile.in: Changes for building on MacOS 10.1
as per bug 94.
<li> html/Makefile.in: added missing images per bug 92.
<li> port/Makefile.in: fixed clean target per bug 92.
</UL>
<P><HR WIDTH=65% ALIGN=left>
<A NAME="libtiff"><B><FONT SIZE=+3>C</FONT>HANGES IN LIBTIFF:</B></A>
<UL>
<li> libtiff/tif_getimage.c: New function <A
HREF="./man/TIFFReadRGBAImage.3t.html"><API key>()</A>
implemented to retrieve raster array with user-specified origin position.
<li> libtiff/tif_fax3.c: Fix wrong line numbering.
<li> libtiff/tif_dirread.c: Check field counter against number of fields.
<li> Store a list of opened IFD to prevent directory looping.
<li> libtiff/tif_jpeg.c: modified segment_height calculation to always
be a full height tile for tiled images. Also changed error to just
be a warning.
<li> libtiff/tif_lzw.c: fixed so that decoder state isn't allocated till
LZWSetupDecode(). Needed to read LZW files in "r+" mode.
<li> libtiff/tif_dir.c: fixed up the tif_postdecode settings responsible
for byte swapping complex image data.
<li> libtiff/tif_open.c: Removed error if opening a compressed file
in update mode bug (198).
<li> libtiff/tif_write.c: TIFFWriteCheck() now fails if the image is
a pre-existing compressed image. That is, image writing to pre-existing
compressed images is not allowed.
|
<?php
/**
* sfGeneratorManager helps generate classes, views and templates for scaffolding, admin interface, ...
*
* @package symfony
* @subpackage generator
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfGeneratorManager.class.php 17858 2009-05-01 21:22:50Z FabianLange $
*/
class sfGeneratorManager
{
protected
$configuration = null,
$basePath = null;
/**
* Class constructor.
*
* @param <API key> $configuration A <API key> instance
* @param string $basePath The base path for file generation
*
* @see initialize()
*/
public function __construct(<API key> $configuration, $basePath = null)
{
$this->configuration = $configuration;
$this->basePath = $basePath;
}
/**
* Initializes the sfGeneratorManager instance.
*
* @param <API key> $configuration A <API key> instance
* @deprecated
*/
public function initialize(<API key> $configuration)
{
// DEPRECATED
}
/**
* Returns the current configuration instance.
*
* @return <API key> A <API key> instance
*/
public function getConfiguration()
{
return $this->configuration;
}
/**
* Gets the base path to use when generating files.
*
* @return string The base path
*/
public function getBasePath()
{
if (is_null($this->basePath))
{
// for BC
$this->basePath = sfConfig::get('sf_module_cache_dir');
}
return $this->basePath;
}
/**
* Sets the base path to use when generating files.
*
* @param string $basePath The base path
*/
public function setBasePath($basePath)
{
$this->basePath = $basePath;
}
/**
* Saves some content.
*
* @param string $path The relative path
* @param string $content The content
*/
public function save($path, $content)
{
$path = $this->getBasePath().DIRECTORY_SEPARATOR.$path;
if (!is_dir(dirname($path)))
{
$current_umask = umask(0000);
if (false === @mkdir(dirname($path), 0777, true))
{
throw new sfCacheException(sprintf('Failed to make cache directory "%s".', dirname($path)));
}
umask($current_umask);
}
if (false === $ret = @file_put_contents($path, $content))
{
throw new sfCacheException(sprintf('Failed to write cache file "%s".', $path));
}
return $ret;
}
/**
* Generates classes and templates for a given generator class.
*
* @param string $generatorClass The generator class name
* @param array $param An array of parameters
*
* @return string The cache for the configuration file
*/
public function generate($generatorClass, $param)
{
$generator = new $generatorClass($this);
return $generator->generate($param);
}
}
|
.noscript-two {
color: blue;
}
|
require 'rails_helper'
RSpec.describe "Stylesheets", type: :request do
require "sprockets"
let(:css) do
assets = Rails.application.assets
assets.find_asset("active_admin.css")
end
it "should successfully render the scss stylesheets using sprockets" do
expect(css).to_not eq nil
end
it "should not have any syntax errors" do
expect(css.to_s).to_not include("Syntax error:")
end
end
|
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
#ifndef <API key>
#define <API key>
#include <algorithm>
#include <cstddef>
#include <functional>
#include <boost/mpl/assert.hpp>
#include <boost/range.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>
#include <boost/variant/variant_fwd.hpp>
#include <boost/geometry/algorithms/detail/interior_iterator.hpp>
#include <boost/geometry/core/closure.hpp>
#include <boost/geometry/core/cs.hpp>
#include <boost/geometry/core/exterior_ring.hpp>
#include <boost/geometry/core/interior_rings.hpp>
#include <boost/geometry/core/mutable_range.hpp>
#include <boost/geometry/core/ring_type.hpp>
#include <boost/geometry/core/tags.hpp>
#include <boost/geometry/geometries/concepts/check.hpp>
#include <boost/geometry/algorithms/area.hpp>
#include <boost/geometry/algorithms/disjoint.hpp>
#include <boost/geometry/algorithms/detail/multi_modify.hpp>
#include <boost/geometry/util/order_as_direction.hpp>
namespace boost { namespace geometry
{
// Silence warning C4127: conditional expression is constant
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4127)
#endif
#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace correct
{
template <typename Geometry>
struct correct_nop
{
static inline void apply(Geometry& )
{}
};
template <typename Box, std::size_t Dimension, std::size_t DimensionCount>
struct correct_box_loop
{
typedef typename coordinate_type<Box>::type coordinate_type;
static inline void apply(Box& box)
{
if (get<min_corner, Dimension>(box) > get<max_corner, Dimension>(box))
{
// Swap the coordinates
coordinate_type max_value = get<min_corner, Dimension>(box);
coordinate_type min_value = get<max_corner, Dimension>(box);
set<min_corner, Dimension>(box, min_value);
set<max_corner, Dimension>(box, max_value);
}
correct_box_loop
<
Box, Dimension + 1, DimensionCount
>::apply(box);
}
};
template <typename Box, std::size_t DimensionCount>
struct correct_box_loop<Box, DimensionCount, DimensionCount>
{
static inline void apply(Box& )
{}
};
// Correct a box: make min/max correct
template <typename Box>
struct correct_box
{
static inline void apply(Box& box)
{
// Currently only for Cartesian coordinates
// (or spherical without crossing dateline)
correct_box_loop
<
Box, 0, dimension<Box>::type::value
>::apply(box);
}
};
// Close a ring, if not closed
template <typename Ring, typename Predicate>
struct correct_ring
{
typedef typename point_type<Ring>::type point_type;
typedef typename coordinate_type<Ring>::type coordinate_type;
typedef typename strategy::area::services::default_strategy
<
typename cs_tag<point_type>::type,
point_type
>::type strategy_type;
typedef detail::area::ring_area
<
order_as_direction<geometry::point_order<Ring>::value>::value,
geometry::closure<Ring>::value
> ring_area_type;
static inline void apply(Ring& r)
{
// Check close-ness
if (boost::size(r) > 2)
{
// check if closed, if not, close it
bool const disjoint = geometry::disjoint(*boost::begin(r), *(boost::end(r) - 1));
closure_selector const s = geometry::closure<Ring>::value;
if (disjoint && (s == closed))
{
geometry::append(r, *boost::begin(r));
}
if (! disjoint && s != closed)
{
// Open it by removing last point
geometry::traits::resize<Ring>::apply(r, boost::size(r) - 1);
}
}
// Check area
Predicate predicate;
typedef typename default_area_result<Ring>::type area_result_type;
area_result_type const zero = area_result_type();
if (predicate(ring_area_type::apply(r, strategy_type()), zero))
{
std::reverse(boost::begin(r), boost::end(r));
}
}
};
// Correct a polygon: normalizes all rings, sets outer ring clockwise, sets all
// inner rings counter clockwise (or vice versa depending on orientation)
template <typename Polygon>
struct correct_polygon
{
typedef typename ring_type<Polygon>::type ring_type;
typedef typename default_area_result<Polygon>::type area_result_type;
static inline void apply(Polygon& poly)
{
correct_ring
<
ring_type,
std::less<area_result_type>
>::apply(exterior_ring(poly));
typename <API key><Polygon>::type
rings = interior_rings(poly);
for (typename detail::interior_iterator<Polygon>::type
it = boost::begin(rings); it != boost::end(rings); ++it)
{
correct_ring
<
ring_type,
std::greater<area_result_type>
>::apply(*it);
}
}
};
}} // namespace detail::correct
#endif // DOXYGEN_NO_DETAIL
#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{
template <typename Geometry, typename Tag = typename tag<Geometry>::type>
struct correct: not_implemented<Tag>
{};
template <typename Point>
struct correct<Point, point_tag>
: detail::correct::correct_nop<Point>
{};
template <typename LineString>
struct correct<LineString, linestring_tag>
: detail::correct::correct_nop<LineString>
{};
template <typename Segment>
struct correct<Segment, segment_tag>
: detail::correct::correct_nop<Segment>
{};
template <typename Box>
struct correct<Box, box_tag>
: detail::correct::correct_box<Box>
{};
template <typename Ring>
struct correct<Ring, ring_tag>
: detail::correct::correct_ring
<
Ring,
std::less<typename default_area_result<Ring>::type>
>
{};
template <typename Polygon>
struct correct<Polygon, polygon_tag>
: detail::correct::correct_polygon<Polygon>
{};
template <typename MultiPoint>
struct correct<MultiPoint, multi_point_tag>
: detail::correct::correct_nop<MultiPoint>
{};
template <typename MultiLineString>
struct correct<MultiLineString, <API key>>
: detail::correct::correct_nop<MultiLineString>
{};
template <typename Geometry>
struct correct<Geometry, multi_polygon_tag>
: detail::multi_modify
<
Geometry,
detail::correct::correct_polygon
<
typename boost::range_value<Geometry>::type
>
>
{};
} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH
namespace resolve_variant {
template <typename Geometry>
struct correct
{
static inline void apply(Geometry& geometry)
{
concepts::check<Geometry const>();
dispatch::correct<Geometry>::apply(geometry);
}
};
template <<API key>(typename T)>
struct correct<boost::variant<<API key>(T)> >
{
struct visitor: boost::static_visitor<void>
{
template <typename Geometry>
void operator()(Geometry& geometry) const
{
correct<Geometry>::apply(geometry);
}
};
static inline void
apply(boost::variant<<API key>(T)>& geometry)
{
boost::apply_visitor(visitor(), geometry);
}
};
} // namespace resolve_variant
/*!
\brief Corrects a geometry
\details Corrects a geometry: all rings which are wrongly oriented with respect
to their expected orientation are reversed. To all rings which do not have a
closing point and are typed as they should have one, the first point is
appended. Also boxes can be corrected.
\ingroup correct
\tparam Geometry \tparam_geometry
\param geometry \param_geometry which will be corrected if necessary
\qbk{[include reference/algorithms/correct.qbk]}
*/
template <typename Geometry>
inline void correct(Geometry& geometry)
{
resolve_variant::correct<Geometry>::apply(geometry);
}
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
}} // namespace boost::geometry
#endif // <API key>
|
package org.jboss.windup.config.phase;
import org.jboss.windup.config.<API key>;
import org.ocpsoft.rewrite.config.Rule;
/**
* Previous: {@link <API key>}<br/>
* Next: {@link PostFinalizePhase}
*
* <p>
* This occurs at the end of execution. {@link Rule}s in this phase are responsible for any cleanup of resources that
* may have been opened during {@link Rule}s from earlier {@link <API key>}s.
* </p>
*
* @author <a href="mailto:jesse.sightler@gmail.com">Jesse Sightler</a>
*
*/
public class FinalizePhase extends RulePhase
{
public FinalizePhase()
{
super(FinalizePhase.class);
}
@Override
public Class<? extends RulePhase> getExecuteAfter()
{
return <API key>.class;
}
@Override
public Class<? extends RulePhase> getExecuteBefore()
{
return null;
}
}
|
#if !defined <API key> && !defined <API key>
# error "Never use <bmiintrin.h> directly; include <x86intrin.h> instead."
#endif
#ifndef <API key>
#define <API key>
#ifndef __BMI__
#pragma GCC push_options
#pragma GCC target("bmi")
#define __DISABLE_BMI__
#endif /* __BMI__ */
extern __inline unsigned short __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__tzcnt_u16 (unsigned short __X)
{
return <API key> (__X);
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__andn_u32 (unsigned int __X, unsigned int __Y)
{
return ~__X & __Y;
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__bextr_u32 (unsigned int __X, unsigned int __Y)
{
return <API key> (__X, __Y);
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
_bextr_u32 (unsigned int __X, unsigned int __Y, unsigned __Z)
{
return <API key> (__X, ((__Y & 0xff) | ((__Z & 0xff) << 8)));
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__blsi_u32 (unsigned int __X)
{
return __X & -__X;
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
_blsi_u32 (unsigned int __X)
{
return __blsi_u32 (__X);
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__blsmsk_u32 (unsigned int __X)
{
return __X ^ (__X - 1);
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
_blsmsk_u32 (unsigned int __X)
{
return __blsmsk_u32 (__X);
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__blsr_u32 (unsigned int __X)
{
return __X & (__X - 1);
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
_blsr_u32 (unsigned int __X)
{
return __blsr_u32 (__X);
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__tzcnt_u32 (unsigned int __X)
{
return <API key> (__X);
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
_tzcnt_u32 (unsigned int __X)
{
return <API key> (__X);
}
#ifdef __x86_64__
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__andn_u64 (unsigned long long __X, unsigned long long __Y)
{
return ~__X & __Y;
}
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__bextr_u64 (unsigned long long __X, unsigned long long __Y)
{
return <API key> (__X, __Y);
}
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
_bextr_u64 (unsigned long long __X, unsigned int __Y, unsigned int __Z)
{
return <API key> (__X, ((__Y & 0xff) | ((__Z & 0xff) << 8)));
}
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__blsi_u64 (unsigned long long __X)
{
return __X & -__X;
}
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
_blsi_u64 (unsigned long long __X)
{
return __blsi_u64 (__X);
}
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__blsmsk_u64 (unsigned long long __X)
{
return __X ^ (__X - 1);
}
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
_blsmsk_u64 (unsigned long long __X)
{
return __blsmsk_u64 (__X);
}
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__blsr_u64 (unsigned long long __X)
{
return __X & (__X - 1);
}
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
_blsr_u64 (unsigned long long __X)
{
return __blsr_u64 (__X);
}
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__tzcnt_u64 (unsigned long long __X)
{
return <API key> (__X);
}
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
_tzcnt_u64 (unsigned long long __X)
{
return <API key> (__X);
}
#endif /* __x86_64__ */
#ifdef __DISABLE_BMI__
#undef __DISABLE_BMI__
#pragma GCC pop_options
#endif /* __DISABLE_BMI__ */
#endif /* <API key> */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.