I'm trying to interface to a Huawei device (MA5608T) via Python through SNMP.I learned that there is a correspondence between the index value and the port.
But I still don't understand how it translates
for example:
4194445056.0(index) = 0/17/7(port)
does anyone know what are the steps to do?
try this way:
4194304000 + (slot * (256 * 32)) + pon * 256) + '.' + onu_id
This Javascript code is taken from production. The binary operations will give you a clue on how to extract the data from the packet.
function convert_snmp_packet( packet ){
let regex = /[^\.]*/g;
let found = packet.match( regex );
if( found.length < 2 ) {
throw new Error( "wrong packet ? " + packet );
}
let left_part = parseInt( found[0] );
// found[1] is just the dot
let ont_index = parseInt( found[ 2 ] );
let slot_num;
let port_num;
slot_num = ( left_part & ( 15 << 13 ) ) >> 13;
port_num = ( left_part & ( 15 << 8 ) ) >> 8;
let json = {
slot_num: slot_num,
port_num: port_num,
ont_index: ont_index
};
return json;
}
test code:
class packet_Test extends Test {
test_packet( ){
// packet must be a String for this to work
let p = "4194445056.0";
let actual = convert_snmp_packet( p );
let expected = { slot_num: 1, port_num: 7, ont_index: 0 };
this.assertEquals( expected, actual );
this.done()
}
}
Sorry for the necromancy. Ran into this while looking for information about SNMP over a Huawei olt.
Is there any way to align the text (justify/left/right alignment)shown below token field in login page of custom credential provider
If you have a look at credentialprovider.h
typedef /* [v1_enum] */
enum _CREDENTIAL_PROVIDER_FIELD_STATE
{
CPFS_HIDDEN = 0,
CPFS_DISPLAY_IN_SELECTED_TILE = ( CPFS_HIDDEN + 1 ) ,
CPFS_DISPLAY_IN_DESELECTED_TILE = ( CPFS_DISPLAY_IN_SELECTED_TILE + 1 ) ,
CPFS_DISPLAY_IN_BOTH = ( CPFS_DISPLAY_IN_DESELECTED_TILE + 1 )
} CREDENTIAL_PROVIDER_FIELD_STATE;
typedef /* [v1_enum] */
enum _CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE
{
CPFIS_NONE = 0,
CPFIS_READONLY = ( CPFIS_NONE + 1 ) ,
CPFIS_DISABLED = ( CPFIS_READONLY + 1 ) ,
CPFIS_FOCUSED = ( CPFIS_DISABLED + 1 )
} CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE;
There is no provision for alignment for a field in CREDENTIAL_PROVIDER_FIELD_STATE. There is no API/constant to declare the aligment of a specific field. The only alignment Credential Provider does is "Center alignment".
I'm trying to ADD a stop loss to my open market orders in MetaTrader 4 when a position gets 100 pips "to the good" which is to be equal to the Order Open Price;
OrderStopLoss() == OrderOpenPrice()
But this isn't happening.
I've added Print() & GetLastError() functions and nothing is coming up in the journal, so it must be something in my coding - but cannot see what would be wrong.
OK this is what I have so far, one for loop for the buy, one for the sell. I've also Normalized the "doubles" as I have been advised to do & have also declared the BuyMod & SellMod to "true" at the very top. This should ensure that the default won't resort to false. I also thought it might be helpful if I told you I have the MetaEditor version 5 build 1241:)
The following code I have is the following;
/*Breakeven Order Modification*/
bool BuyMod = true;
bool SellMod = true;
for(int b = OrdersTotal()-1;b>=0;b--)
{
if(OrderSelect(b,SELECT_BY_POS,MODE_TRADES))
{
double aBidPrice = MarketInfo(Symbol(),MODE_BID);
double anOpenPrice = OrderOpenPrice();
double aNewTpPrice = OrderTakeProfit();
double aCurrentSL = OrderStopLoss();
double aNewSLPrice = anOpenPrice;
double pnlPoints = (aBidPrice - anOpenPrice)/_Point;
double stopPoints = (aBidPrice - aNewSLPrice)/_Point;
int stopLevel = int(MarketInfo(Symbol(),MODE_STOPLEVEL));
int aTicket = OrderTicket();
if(OrderType() == OP_BUY)
if(stopPoints >= stopLevel)
if(aTicket > 0)
if(pnlPoints >= breakeven)
if(aNewSLPrice != aCurrentSL)
{
BuyMod = OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(aNewSLPrice,Digits),NormalizeDouble(aNewTpPrice,Digits),0,buycolor);
SendMail("Notification of Order Modification for Ticket#"+IntegerToString(OrderTicket(),10),"Good news! Order Ticket#"+IntegerToString(OrderTicket(),10)+"has been changed to breakeven");
}
}
}
for(int s = OrdersTotal()-1; s>=0; s--)
{
if(OrderSelect(s,SELECT_BY_POS,MODE_TRADES))
{
double anAskPrice = MarketInfo(Symbol(),MODE_ASK);
double anOpenPrice = OrderOpenPrice();
double aNewTpPrice = OrderTakeProfit();
double aCurrentSL = OrderStopLoss();
double aNewSLPrice = anOpenPrice;
double pnlPoints = (anOpenPrice - anAskPrice)/_Point;
double stopPoints = (aNewSLPrice - anAskPrice)/_Point;
int stopLevel = int(MarketInfo(Symbol(),MODE_STOPLEVEL));
int aTicket = OrderTicket();
if(OrderType()== OP_SELL)
if(stopPoints >= stopLevel)
if(pnlPoints >= breakeven)
if(aNewSLPrice != aCurrentSL)
if(aTicket > 0)
{
SellMod = OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(aNewSLPrice,Digits),NormalizeDouble(aNewTpPrice,Digits),0,sellcolor);
SendMail("Notification of Order Modification for Ticket#"+IntegerToString(OrderTicket(),10),"Good news! Order Ticket#"+IntegerToString(OrderTicket(),10)+"has been changed to breakeven");
}
}
}
trading algorithmic-trading mql4 metatrader4
shareeditdeleteflag
edited just now
asked 2 days ago
Todd Gilbey
264
You might want to know, StackOverflow does not promote duplicate questions. ( see the
Besides meeting an MQL4 syntax-rules,there are more conditions:
A first hidden trouble is in number rounding issues.
MetaQuotes, Inc., recommends wherever possible, to normalise float values into a proper price-representation.
Thus,wherever a price goes into a server-side instruction { OrderSend(), OrderModify(), ... } one shall always prepare such aPriceDOMAIN valueby a call to NormalizeDouble( ... , _Digits ), before a normalised price hits any server-side instruction call.
May sound rather naive, but this saves you issues with server-side rejections.
Add NormalizeDouble() calls into your code on a regular base as your life-saving vest.
A second, even a better hidden trouble is in STOP_ZONE-s and FREEZE_ZONE-s
While not visible directly, any Broker set's in their respective Terms & Conditions these parameters.
In practice,this means, if you instruct { OrderSend() | OrderModify() } to set / move aPriceDOMAIN level to be setup too close to current actual Ask/Bid ( violating a Broker-forbidden STOP_ZONE )orto delete / modify aPriceDOMAIN level of TP or SL, that are already set and is right now, within a Broker-forbidden FREEZE_ZONE distance from actual Ask/Bid,such instruction will not be successfully accepted and executed.
So besides calls to the NormalizeDouble(), always wait a bit longer as the price moves "far" enough and regularly check for not violating forbidden STOP_ + FREEZE_ zones before ordering any modifications in your order-management part of your algotrading projects.
Anyway, Welcome to Wild Worlds of MQL4
Update: while StackOverflow is not a Do-a-Homework site, let me propose a few directions for the solution:
for ( int b = OrdersTotal() - 1; b >= 0; b-- ) // ________________________ // I AM NOT A FAN OF db.Pool-looping, but will keep original approach for context purposes
{ if ( ( OrderSelect( b, SELECT_BY_POS, MODE_TRADES ) ) == true )
{ // YES, HAVE TO OPEN A CODE-BLOCK FOR if()-POSITIVE CASE:
// ------------------------------------------------------
double aBidPRICE = MarketInfo( Symbol(), MODE_BID ); // .UPD
double anOpenPRICE = OrderOpenPrice(); // .SET FROM a db.Pool Current Record
double aNewTpPRICE = OrderTakeProfit(); // .SET FROM a db.Pool Current Record
double aCurrentSlPRICE = OrderStopLoss(); // .SET FROM a db.Pool Current Record
double aNewSlPRICE = anOpenPRICE; // .SET
double pnlPOINTs = ( aBidPRICE - anOpenPRICE )/_Point; // .SET
double stopPOINTs = ( aBidPRICE - aNewSlPRICE )/_Point; // .SET
// ------------------------------------------------------------ // .TEST
if ( OP_BUY == OrderType() )
if ( Period() == OrderMagicNumber() )
if ( stopPOINTa > stopLevel )
if ( pnlPOINTs >= breakeven )
if ( aNewSlPRICE != aCurrentSlPRICE )
{ // YES, HAVE TO OPEN A BLOCK {...}-CODE-BLOCK FOR THE if()if()if()if()-chain's-POSITIVE CASE:
// -------------------------------------------------------------------------------------------
int aBuyMOD = OrderModify( OrderTicket(),
OrderOpenPrice(),
NormalizeDouble( aNewSlPRICE, Digits ),
NormalizeDouble( aNewTpPRICE, Digits ),
0,
buycolor
);
switch( aBuyMOD )
{ case ( NULL ): { ...; break; } // FAIL ( ANALYSE ERROR )
default: { ...; break; } // PASS OrderModify()
}
}
}
The problem is in your call to a built-in OrderModify() function.
OrderStopLoss() == OrderModify() will evaluate as false which in turn will evaluate as 0 since == is a comparison operator.
An OrderStopLoss() is a call to another built-in function (not a variable), you can't save anything to it so OrderStopLoss() = 4 wouldn't work either.
From the MQL4 documentation:
bool OrderModify( int ticket, // ticket
double price, // price
double stoploss, // stop loss
double takeprofit, // take profit
datetime expiration, // expiration
color arrow_color // color
);
In your case that would be the following, assuming ModBuy is already defined somewhere in the code:
ModBuy = OrderModify( OrderTicket(), // <-ticket from record OrderSelect()'d
OrderOpenPrice(), // <-price from current record
OrderOpenPrice(), // <-price from current record
OrderTakeProfit(), // <-TP from current record
0, // ( cannot set P/O expiration for M/O )
buycolor // ( set a color for a GUI marker )
);
Or you could just use any other valid value instead of the second OrderOpenPrice() to set a new stoploss.
I'm really sorry, I'm new to Stackoverflow, this is the revised code I now have based on everyone's comments & recommendation's below
**Local Declarations**
pnlPoints = 0;
point = MarketInfo(Symbol(),MODE_POINT);
stopLevel = int(MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo (Symbol(),MODE_SPREAD));
sl = NormalizeDouble(OrderStopLoss(),Digits);
tp = OrderTakeProfit();
cmd = OrderType();
breakeven = 100;
**Global Variables**
double pnlPoints;
double price,sl,tp;
double point;
int stopLevel;
int cmd;
int breakeven;
double newSL;
for(int b = OrdersTotal()-1; b>=0; b--)
{
if((OrderSelect(b,SELECT_BY_POS,MODE_TRADES))==true)
price = MarketInfo(Symbol(),MODE_BID);
newSL = NormalizeDouble(OrderOpenPrice(),Digits);
pnlPoints = (price - OrderOpenPrice())/point;
{
if(OrderType()==OP_BUY)
if(OrderMagicNumber() == Period())
if((price-newSL)/point>=stopLevel)
if(pnlPoints>=breakeven)
if(sl!=newSL)
ModBuy = OrderModify(OrderTicket(),OrderOpenPrice(),newSL,tp,buycolor);
else if(ModBuy == false)
{
Print("OrderModify failed with error #",GetLastError());
}
}
}
Apple's documentation :
AudioToolbox Framework Reference > Audio File Services Reference > Reading and Writing Audio Files > AudioFileWriteBytes
Declaration Swift func AudioFileWriteBytes(_ inAudioFile: AudioFileID,
_ inUseCache: Boolean,
_ inStartingByte: Int64,
_ ioNumBytes: UnsafeMutablePointer<UInt32>,
_ inBuffer: UnsafePointer<Void>) -> OSStatus
Code in XCode Version 7.0 beta 4 (7A165t)
audioErr = AudioFileWriteBytes(audioFile, false, Int64(sampleCount * 2), bytesToWriteMem, sampleMem as! UnsafePointer<Void>)
XCode's reponse :
Cannot invoke 'AudioFileWriteBytes' with an argument list of type '(AudioFileID, Bool, Int64, UnsafeMutablePointer<UInt32>, UnsafePointer<Void>)'
Any idea ?
EDIT :
Thanks Martin R for your response, here is my full code and i don't understand why the AudioFileWriteBytes call returns an error ... :
import Foundation
import AudioToolbox
import Darwin
import AudioUnit
import CoreFoundation
extension Int {
func format (f:String) -> String {
return NSString(format:"%\(f)d", self) as String
}
}
let SAMPLE_RATE:Float64 = 44100 // 1
let DURATION = 0.1 // 2
// #define FILENAME_FORMAT #"%0.3f-square.aif" 3 skipped
if (Process.arguments.count < 2) {
print("Usage: CAToneFileGenerator n\n(where n is tone in Hz)")
exit(0)
}
var hz:Double = atof(Process.arguments[1]) // 4 (atof convert ASCII string to double)
assert(hz > 0)
print("generating \(hz) tone")
var fileName:String = String(format:"%d-square.aif", hz) // 5
var filePath:String = NSFileManager.defaultManager().currentDirectoryPath.stringByAppendingPathComponent(fileName)
var fileURL:NSURL = NSURL.fileURLWithPath(filePath) // the Audio File Services functions take URLs, not file paths
// Prepare the format
var asbd = AudioStreamBasicDescription() // 6
memset(&asbd, 0, sizeof(AudioStreamBasicDescription)) // 7
asbd.mSampleRate = SAMPLE_RATE // 8
asbd.mFormatID = AudioFormatID(kAudioFormatLinearPCM)
asbd.mFormatFlags = AudioFormatFlags(kAudioFormatFlagIsBigEndian | kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked)
asbd.mBitsPerChannel = 16
asbd.mChannelsPerFrame = 1
asbd.mFramesPerPacket = 1
asbd.mBytesPerFrame = 2
asbd.mBytesPerPacket = 2
// Set up the file
var audioFile:AudioFileID = AudioFileID()
var audioErr:OSStatus = noErr
audioErr = AudioFileCreateWithURL(fileURL, // 9
AudioFileTypeID(kAudioFileAIFFType),
&asbd,
.EraseFile,
&audioFile)
// 1 -> AudioFileFlags(kAudioFileFlags_EraseFile)
assert(audioErr == noErr)
// Start writing samples
var maxSampleCount:CLong = CLong(SAMPLE_RATE * DURATION) // 10
var sampleCount:CLong = 0
var bytesToWrite:UInt32 = 2
/*
var bytesToWriteMem = UnsafeMutablePointer<UInt32>.alloc(1)
bytesToWriteMem.initialize(bytesToWrite)
*/
var wavelengthInSamples:Double = SAMPLE_RATE / hz // 11
var sample:UInt16
//var sampleMem = UnsafeMutablePointer<UInt16>.alloc(1)
//sampleMem.initialize(sample)
while sampleCount < maxSampleCount {
for i in 0..<Int(wavelengthInSamples) {
// Square wave
if ( i < Int(wavelengthInSamples/2)) { // 12
sample = UInt16.max // 13
} else {
sample = UInt16.min
}
//let bytesToWrite2 = bytesToWrite
audioErr = AudioFileWriteBytes(audioFile, // 14
false,
Int64(sampleCount * 2),
&bytesToWrite, //UnsafeMutablePointer<UInt32>
&sample) //UnsafePointer<Void>
assert(audioErr == noErr)
sampleCount++ // 15
}
}
/*
bytesToWriteMem.destroy()
bytesToWriteMem.dealloc(1)
sampleMem.destroy()
sampleMem.dealloc(1)
*/
audioErr = AudioFileClose(audioFile) // 16
assert(audioErr == noErr)
print("wrote \(sampleCount) samples")
That was tricky to find, because the error message does not help at all.
The problem is that the type of the second parameter of AudioFileWriteBytes() is Boolean, not Bool:
audioErr = AudioFileWriteBytes(audioFile,
Boolean(0), // <--- HERE
Int64(sampleCount * 2),
&bytesToWrite,
&sample)
For more information about the difference between Boolean and Bool
see for example Type 'Boolean' does not conform to protocol 'BooleanType'.
Update: As of Swift 2/Xcode 7, the Mac type Boolean is mapped
to the Swift Bool, so you have to pass false or true now:
audioErr = AudioFileWriteBytes(audioFile,
false, // <--- HERE
Int64(sampleCount * 2),
&bytesToWrite,
&sample)
I use QGraphicsView and QGraphicsScene to display a map - a lot of object (lines, images, polygons, etc). I implemented zooming the view this way:
...
void MapView::wheelEvent( QWheelEvent *pEvent )
{
if ( pEvent->modifiers() & Qt::ControlModifier )
{
if ( pEvent->delta() > 0 )
zoomIn();
else
zoomOut();
pEvent->accept();
}
else
{
QGraphicsView::wheelEvent( pEvent );
}
}
...
void MapView::zoomIn( int nValue )
{
m_dZoom = ( nValue == -1 ) ? qMin( ( m_dZoom + m_dZoomStep ), m_dZoomMax ) : qMin( ( m_dZoom + qreal( nValue ) ), m_dZoomMax );
setupTransform();
}
void MapView::zoomOut( int nValue )
{
m_dZoom = ( nValue == -1 ) ? qMax( ( m_dZoom - m_dZoomStep ), m_dZoomMin ) : qMax( ( m_dZoom - qreal( nValue ) ), m_dZoomMin );
setupTransform();
}
...
void MapView::setupTransform()
{
QTransform t = transform();
t.reset();
qreal dScale = qPow( qreal( 2 ), ( m_dZoom - ( m_dZoomMax / 4 ) ) / qreal( 50 ) );
t.scale( dScale, dScale );
setTransform( t );
emit onZoomChanged( m_dZoom );
}
...
When I run application on Linux (CentOS 6.3, Qt 4.8) - zooming the view runs very good (smoothly). But when I run it on Windows (Windows 7 32bit, Qt 5.4) zoomig the view freezes - I constanly rotate the mouse wheel with no effect (no zooming, the view is not responding), and after a second or two later the view starts responding again. When this happens current zoom position turned out to be correctly set - it seems like the view were zooming but not updating the picture. The problem occurs with different zoom values and scroll positions, but always when the view is going to crop map objects (paths).
Do you have any ideas how to fix that problem, or am I doing something wrong?
Thank you very much in advance.