bitcoinj Connect P2SH input transaction to the output transaction - bitcoin

I have created P2SH address and send coins to the address
https://www.blocktrail.com/tBTC/address/2N8Xu6rNAwssXtP2XPjSTuT2ViWQoPeHr3r
Next I want to send coins from 2N8Xu6rNAwssXtP2XPjSTuT2ViWQoPeHr3r address.
How to prepare P2SH transaction and connect it to the output script?
public static void sendFromP2SH(WalletAppKit kit, Address destAdd, Coin coin) throws AddressFormatException, InsufficientMoneyException, ExecutionException, InterruptedException {
Transaction tx = new Transaction(TestNet3Params.get());
tx.addOutput(coin, destAdd); //prepare destination output
Wallet.SendRequest req = Wallet.SendRequest.forTx(tx);
//TODO prepare P2SH input for output //https://www.blocktrail.com/tBTC/address/2N8Xu6rNAwssXtP2XPjSTuT2ViWQoPeHr3r
Script script = P2SHScript(kit); //2N8Xu6rNAwssXtP2XPjSTuT2ViWQoPeHr3r
TransactionOutput t = null;//... HOW TO CONNECT P2SH input transaction to the output ?
tx.addInput(t);
kit.wallet().completeTx(req);
kit.wallet().commitTx(req.tx);
kit.peerGroup().broadcastTransaction(req.tx).get();
}
prepare script for the P2SH address 2N8Xu6rNAwssXtP2XPjSTuT2ViWQoPeHr3r
public static Script P2SHScript(WalletAppKit kit) {
ECKey pubClientKey = kit.wallet().getImportedKeys().get(0);
ECKey pubServerKey = kit.wallet().getImportedKeys().get(1);
return ScriptBuilder.createP2SHOutputScript(1, ImmutableList.of(pubClientKey, pubServerKey));
}
Thank you.

What about the following constructor?
public TransactionOutput(NetworkParameters params, Transaction parent, BigInteger value, Address to)
Inside the code it speculates over the 'to' address to check if it is multisig and creates the output script appropriately.

Related

How to send extent report in email to stackholders after running all the test cases in cucumber?

I want to send an email with extent report attachment that I have generated. I am using cucumber. Currently report is generated using latest timestamp with below name
D:\DAAutomation1\NewFeature1\output\10062021_071218798\Report_10062021_071218798.html
Now I want to send this dynamically generated report in email. I am trying to send using the below code in SequentialRunnerTestbut it is not working.
How can I attach a dynamically generated report which stored in a dynamically generated folder?
From which location I need to call this code?
#BeforeClass
public static void Setup() {
if (CustomFormatter.getReportInstance() == null) {
Date d = new Date();
String today = new SimpleDateFormat(Constants.SCREENSHOT_SDF).format(d);
String reportName = String.format("Report_%s%s", today, Constants.HTML_EXTENSION);
File dir = new File(today);
dir = new File(Constants.REPORT_PATH + dir);
if (!dir.exists()) {
dir.mkdir();
Variables.reportFolderName = dir;
}
reportPath = new File(dir + "/" + reportName);
File folderPath = new File(dir + "/");
CustomFormatter.initiateCustomFormatter(reportPath, folderPath);
File extentConfig = new File(Constants.CONFIG_FILES_URI + Constants.EXTENT_FILE);
CustomFormatter.loadConfig(extentConfig);
CustomFormatter.addSystemInfo("user", System.getProperty("user.name"));
CustomFormatter.addSystemInfo("os", System.getProperty("os.name"));
CustomFormatter.addSystemInfo("browser", CONFIG.getProperty("browser"));
CustomFormatter.addSystemInfo("Tenant", CONFIG.getProperty("application.url"));
} else {
CustomFormatter.initiateCustomFormatter();
}
#AfterClass
public static void SendEmail() throws EmailException {
// Create the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setPath(System.getProperty("user.dir")+"output/folderPath/"+reportPath);
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription(" Test Execution Report");
attachment.setName("Automation Test Execution Report");
// Create the email message
MultiPartEmail email = new MultiPartEmail();
email.setHostName("smtp.gmail.com");
email.setSSLOnConnect(true);
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator("xyz#gmail.com", "xyz#123"));
email.addTo("xyz#gmail.com", "Test");
email.setFrom("xyz#gmail.com", "Me");
email.setSubject("Automation Test Execution Report");
email.setMsg("Automation Test Execution Report");
// add the attachment
email.attach(attachment);
// send the email
email.send();
}
please write seperate simple java program that should be executed after your cucumber run.
After the complete execution only, you will see the latest report in your target folder. your secondary program should pick the report from the target folder and mail to them.
In My case,
I have written separate java program and JAR packed that will do following actions,
Zip screenshot, css and html report from target folder,
Move them to separate folder with current date and time to identify
Then mail the zip folder
My Execution like,
Created a .bat/sh file
added my cucumber execution
added secondary program execution as JAR execution
mvn test -DCucumber.Options="--tags #temp"
java -jar ZippingAndEmailing.jar [reportLocation] [targetlocation] [emailReciptents]
java -jar ZippingAndEmailing.jar target/cucumber Results jayanthbala1993#gmail.com
From which location I need to call this code?
You have to call that under #AfterClass as you want to send report after executing all tests.
#AfterClass
public static void sendReport() {
SendReport sendReport = new SendReport();
sendReport.triggerMail("Report", "\\NewFeature1\\output\\10062021_071218798\\Report_10062021_071218798.html);
}
How can I attach a dynamically generated report which stored in a
dynamically generated folder
public class SendReport{
public String[] ToAdresses = { "nandan#gmail.com"
,"nandan2#gmail.com"
public void triggerMail(String reportName, String reportPath)
throws IOException, AddressException, MessagingException {
Properties sysmProp = System.getProperties();
sysmProp.put("mail.smtp.starttls.enable", "true");
sysmProp.put("mail.smtp.host", host);
sysmProp.put("mail.smtp.user", from);
sysmProp.put("mail.smtp.password", password);
sysmProp.put("mail.smtp.port", "587");
sysmProp.put("mail.smtp.auth", "true");
/*Create session object*/
Session session = Session.getInstance(sysmProp, null);
/*Create MimeMessage object and add recipients */
MimeMessage message = new MimeMessage(session);
/* Setting the string value type as address */
InternetAddress[] recipients = new InternetAddress[ToAdresses.length];
for (int i = 0; i < ToAdresses.length; i++) {
recipients[i] = new InternetAddress(ToAdresses[i]);
}
/* Adding the recipients to the message object. */
for (int j = 0; j < ToAdresses.length; j++) {
message.addRecipient(Message.RecipientType.TO, recipients[j]);
}
message.setSubject("Test report");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Body of email.")
/* Adding the attachment to the mail. */
File file = new File(System.getProperty("user.dir") + reportPath);
BodyPart messageBodyPart_2 = new MimeBodyPart();
DataSource source = new FileDataSource(file.getAbsolutePath());
messageBodyPart_2.setDataHandler(new DataHandler(source));
messageBodyPart_2.setFileName("Test_" + reportName + ".html");
/* Clubbing the subject of mail. */
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(messageBodyPart_2);
message.setContent(multipart);
/* Triggers mail. */
Transport.send(message);
}
}

How to pass list/array of request objects to tensorflow serving in one server call?

After loading the wide and deep model, i was able to make prediction for one request object using the map of features and then serializing it to string for predictions as shown below-
is there a way we can create a batch of requests objects and send them for prediction to tensorflow server?
Code for single prediction looks like this-
for (each feature in feature list) {
Feature feature = null;
feature = Feature.newBuilder().setBytesList(BytesList.newBuilder().addValue(ByteString.copyFromUtf8("dummy string"))).build();
if (feature != null) {
inputFeatureMap.put(name, feature);
}
}
//Converting features(in inputFeatureMap) corresponding to one request into 'Features' Proto object
Features features = Features.newBuilder().putAllFeature(inputFeatureMap).build();
inputStr = Example.newBuilder().setFeatures(features).build().toByteString();
}
TensorProto proto = TensorProto.newBuilder()
.addStringVal(inputStr)
.setTensorShape(TensorShapeProto.newBuilder().addDim(TensorShapeProto.Dim.newBuilder().setSize(1).build()).build())
.setDtype(DataType.DT_STRING)
.build();
PredictRequest req = PredictRequest.newBuilder()
.setModelSpec(ModelSpec.newBuilder()
.setName("your serving model name")
.setSignatureName("serving_default")
.setVersion(Int64Value.newBuilder().setValue(modelVer)))
.putAllInputs(ImmutableMap.of("inputs", proto))
.build();
PredictResponse response = stub.predict(req);
System.out.println(response.getOutputsMap());
Is there a way we can send the list of Features Object for predictions, something similar to this-
List<Features> = {someway to create array/list of inputFeatureMap's which can be converted to serialized string.}
For anyone stumbling here, I found a simple workaround with Example proto to do batch request. I will borrow code from this question and modify it for the batch.
Features features =
Features.newBuilder()
.putFeature("Attribute1", feature("A12"))
.putFeature("Attribute2", feature(12))
.putFeature("Attribute3", feature("A32"))
.putFeature("Attribute4", feature("A40"))
.putFeature("Attribute5", feature(7472))
.putFeature("Attribute6", feature("A65"))
.putFeature("Attribute7", feature("A71"))
.putFeature("Attribute8", feature(1))
.putFeature("Attribute9", feature("A92"))
.putFeature("Attribute10", feature("A101"))
.putFeature("Attribute11", feature(2))
.putFeature("Attribute12", feature("A121"))
.putFeature("Attribute13", feature(24))
.putFeature("Attribute14", feature("A143"))
.putFeature("Attribute15", feature("A151"))
.putFeature("Attribute16", feature(1))
.putFeature("Attribute17", feature("A171"))
.putFeature("Attribute18", feature(1))
.putFeature("Attribute19", feature("A191"))
.putFeature("Attribute20", feature("A201"))
.build();
Example example = Example.newBuilder().setFeatures(features).build();
String pfad = System.getProperty("user.dir") + "\\1511523781";
try (SavedModelBundle model = SavedModelBundle.load(pfad, "serve")) {
Session session = model.session();
final String xName = "input_example_tensor";
final String scoresName = "dnn/head/predictions/probabilities:0";
try (Tensor<String> inputBatch = Tensors.create(new byte[][] {example.toByteArray(), example.toByteArray(), example.toByteArray(), example.toByteArray()});
Tensor<Float> output =
session
.runner()
.feed(xName, inputBatch)
.fetch(scoresName)
.run()
.get(0)
.expect(Float.class)) {
System.out.println(Arrays.deepToString(output.copyTo(new float[4][2])));
}
}
Essentially you can pass each example as an object in byte[4][] and you will receive the result in the same shape float[4][2]

How to get delivery report from SMSC using Jamaa-Smpp and C#?

How to get delivery report from SMSC using Jamaa-Smpp and C#?
Thanks in advance,
We can get delivery report in Jamaa-Smpp by using client_MessageDelivered event
First ,we need to use this code:
SmppClient(); client = new SmppClient();
client.MessageDelivered += new EventHandler<MessageEventArgs>(client_MessageDelivered);
Second , we need to use this code:
void client_MessageDelivered(object sender, MessageEventArgs e)
{
TextMessage msg = e.ShortMessage as TextMessage;
string msgtext=msg.text;
}
and do not forget to set value to SubmitSm.RegisteredDelivery as your work requirements:
//SMSC delivery receipt requested where final delivery outcome is deliver success or failure
SubmitSm.RegisteredDelivery = RegisteredDelivery.DeliveryReceipt;
or
//SMSC delivery receipt requested where the final delivery outcome is delivery failure
SubmitSm.RegisteredDelivery = RegisteredDelivery.DeliveryReceiptFailure;

transform mule message payload to snmp trap or pdu object

I've applied a sample of using snmp4j for sending and receiving traps and everything is ok.
but the issue is :
when using mule esb for receiving snmp traps, I can't convert the incoming message payload to PDU (or any snmp4j suitable object) to extract data from, I've done a lot of search but in vain.
can anyone assist me to :
convert mule esb message payload that I've received from udp endpoint to org.snmp4j.PDU object to extract trap data from?
here is my code :
public synchronized MuleEvent process(MuleEvent event) throws MuleException {
byte[] encodedMessage = event.getMessage().getPayload(byte[].class);
//next line is not working but its only sample of what I Am looking for
PDU pdu = new PDU(encodedMessage );
.....
any assistance is highly appreciated
public class SNMP4JParser implements Callable {
/**
* The following objects are all necessary in order to use SNMP4j as a parser for raw messages.
* This was all inspired by SNMP4j source code, in particular MessageDispatcherImpl.java
*/
private MessageProcessingModel model = null;
private MessageDispatcher dispatcher = null;
private Address listenAddress = null;
private Integer32 messageProcessingModel = null;
private Integer32 securityModel = null;
private OctetString securityName = null;
private Integer32 securityLevel = null;
private PduHandle handle = null;
private StatusInformation statusInfo = null;
private MutableStateReference mutableStateReference = null;
/**
* Taken from org.snmp4j.transport.AbstractTransportMapping class
*/
protected Integer32 maxInboundMessageSize = new Integer32 ( (1 << 16) - 1 );
/**
* Taken from org.snmp4j.MessageDispatcherImpl class
*/
private int transactionID = new Random().nextInt(Integer.MAX_VALUE - 2) + 1;
/**
* Create all objects that SNMP4j needs to parse a raw SNMP message
*/
public SNMP4JParser()
{
model = new MPv1();
dispatcher = new MessageDispatcherImpl();
listenAddress = GenericAddress.parse("udp:0.0.0.0/2001");
messageProcessingModel = new Integer32();
securityModel = new Integer32();
securityName = new OctetString();
securityLevel = new Integer32();
handle = new PduHandle(transactionID);
statusInfo = new StatusInformation();
mutableStateReference = new MutableStateReference();
}
/**
* #see org.mule.api.lifecycle.Callable#onCall(org.mule.api.MuleEventContext)
*/
#Override
public Object onCall(MuleEventContext eventContext) throws Exception
{
byte[] payloadBytes = eventContext.getMessage().getPayloadAsBytes();
ByteBuffer buffer = ByteBuffer.wrap(payloadBytes);
BERInputStream wholeMessage = new BERInputStream(buffer);
MutablePDU mutablePdu = new MutablePDU();
int status = model.prepareDataElements(
dispatcher,
listenAddress,
wholeMessage,
messageProcessingModel,
securityModel,
securityName,
securityLevel,
mutablePdu,
handle,
maxInboundMessageSize,
statusInfo,
mutableStateReference);
if ( status != SnmpConstants.SNMP_MP_OK )
throw new RuntimeException(
"Couldn't parse SNMP message. model.prepareDataElements() returned " + status);
return mutablePdu.getPdu();
}
}
I've tested it with a flow like this ( I used snmp4j-1.11.5 and mule-standalone-3.4.0 )
<udp:connector name="connector" doc:name="UDP"/>
<flow name="snmp-demo-trapHandlingFlow" doc:name="snmp-demo-trapHandlingFlow">
<udp:inbound-endpoint host="0.0.0.0" port="2001" responseTimeout="10000" doc:name="UDP"/>
<logger message="TRAP RECEIVED - #[System.currentTimeMillis()]" level="DEBUG" doc:name="Inbound timestamp"/>
<component class="com.netboss.flow.demo.SNMP4JParser" doc:name="SNMP4JParser"/>
[...]
And it works.
Now, I realize there are still some open questions:
Is there a better/more efficient way of doing it?
This works only for SNMP v1, how do I modify the above code to make it work with v2 and v3 as well?
You can convert a BER stream to a SNMP4J PDU much easier when you implement your own TransportMapping and associate that with the SNMP4J MessageDispatcherImpl. Then add all the necessary MessageProcessingModels and SecurityProtocols to the message dispatcher.
Finally, add your implementation of the CommandResponder interface to the message dispatcher and you are done.
You need to create a custom transformer that transforms the message payload in the relevant SNMP4J object. Alternatively this can be done with an expression transformer if the SNMP4J API is simple enough.

In Bloomberg API how do you specify to get FX forwards as a spread rather than absolute values?

How do you explicitly request fx forwards as outrights using the bloomberg API?
In the Bloomberg terminal you can choose whether to get FX Forwards as absolute rates (outrights) or as offsets from Spots (Points) by doing XDF, hitting 7, then the option is about half way down. 0 means outrights, and 1 means offfsets.
With most defaults you can explicitly set them in the API, so your code gives the same result whichever computer you run on. How do you set this one in a V3 API query?
Having had a colleague told by the help desk this is impossible, it turns out they are wrong and it is possible. You override the FWD_CURVE_QUOTE_FORMAT to be RATES for absolute and POINTS as offsets.
Example code (Java):
public static void main(String [] args) throws Exception{
Session session = BlpUtil.connectToReferenceData();
Service refDataService = session.getService("//blp/refdata");
Request request = refDataService.createRequest("HistoricalDataRequest");
Element securities = request.getElement("securities");
securities.appendValue("JPY10Y CMPL Curncy");
Element fields = request.getElement("fields");
fields.appendValue("PX_LAST");
request.set("startDate", "20100527");
request.set("endDate", "20100527");
Element overrides = request.getElement("overrides");
Element override1 = overrides.appendElement();
override1.setElement("fieldId", "FWD_CURVE_QUOTE_FORMAT");
override1.setElement("value", "POINTS");
CorrelationID cid = session.sendRequest(request, null);
while (true) {
Event event = session.nextEvent();
MessageIterator msgIter = event.messageIterator();
while (msgIter.hasNext()) {
Message msg = msgIter.next();
if (msg.correlationID() == cid) {
System.out.println("msg = " + msg);
}
}
}
}