bytes32 to string in javascript - javascript

currently i'm working on a ethereum dapp(voting), in my smart contract i have a function to fetch candidate list of type bytes32[] , on the java script side i'm not getting the values instead 0x only
How to parse the value , below is the code
pragma solidity ^0.4.0;
contract Voting {
mapping (bytes32 => uint8) public votesReceived;
bytes32[] public candidateList;
string myString = "someString";
function Voting(bytes32[] candidateNames) public {
candidateList = candidateNames ;
}
function totalVotesFor(bytes32 candidate) view public returns (uint8) {
return votesReceived[candidate];
}
function addCandidate(bytes32 candidate) public returns (bool){
require(isNewEntry(candidate));
candidateList.push(candidate);
return isNewEntry(candidate);
}
function voteForCandidate(bytes32 candidate) public {
require(validCandidate(candidate));
votesReceived[candidate] += 1;
}
function getCandidateList() view public returns (bytes32[]) {
return candidateList;
}
function isNewEntry(bytes32 candidate) view public returns (bool) {
for(uint i = 0; i < candidateList.length; i++) {
if (candidateList[i] == candidate) {
return false;
}
}
return true;
}
function validCandidate(bytes32 candidate) view public returns (bool) {
for(uint i = 0; i < candidateList.length; i++) {
if (candidateList[i] == candidate) {
return true;
}
}
return false;
}
}
below is the code to access the contract function
Voting.deployed().then(function(contractInstance) {
contractInstance.getCandidateList.call().then(function(v) {
console.log(v)
});
})
someone please help me

Assuming you're using web3 on the JS side, it's web3.toAscii.
Example from the docs:
var str = web3.toAscii("0x657468657265756d000000000000000000000000000000000000000000000000");
console.log(str); // "ethereum"

Related

How to stop running process in c#

I am calling a same function in parallel using Task.WhenAll(); and I was wondering if there is any way we can stop all threads /process if stop button is clicked? Also I do not want browser to be closed. can anyone suggest me what approach I should use?
[HttpPost]
public async Task<IActionResult> Runcase(List<string> products,string runnumber,string button)
{
try
{
if (ModelState.IsValid)
{
var productinfo = products;
List<string> productids = new List<string>(productinfo);
var runnum = runnumber;
string runid = "";
int count = productids.Count();
List<Task> tasks = new List<Task>();
int rawid = 0;
for (int i = 0; i < count; i++)
{
tasks.Add(RunServiceAsync(productids[i], runnum,rawid));
}
await Task.WhenAll(tasks);
ViewBag.completed = "Success";
return View();
}
else
{
ViewBag.productinfo = new MultiSelectList(_context.inputValuesConfigurations, "ProductID", "ProductName");
ModelState.AddModelError(string.Empty, "Please enter a valid data...");
return View();
}
}
catch(Exception ex)
{
return View();
}
}

reset the form data after submission in struts

I am very new to struts and the application is using struts , and every time I submit the form the old values are submitted until and unless I change the values by selecting different options from drop down or I go to other tab and come back again to the same tab then in this case the values are resetting..
In my scenario what I want to achieve is to reset some of the values after they executed once.on the basis of those values I have to search some data and show it on the form, if I don't remove this value then it .
This is my execute method :
public class ListTerminalDevicesAction extends BaseQueryAction {
private RetailerService retailerService;
private DataBinder<OmposTerminalQuery> dataBinder;
private TerminalDeviceService terminalDeviceService;
private ImportCSVService importCSVService;
#Inject
public void setImportCSVService(ImportCSVService importCSVService) {
this.importCSVService = importCSVService;
}
#Inject
public void setRetailerService(final RetailerService retailerService) {
this.retailerService = retailerService;
}
#Inject
public void setTerminalDeviceService(final TerminalDeviceService terminalDeviceService) {
this.terminalDeviceService = terminalDeviceService;
}
#Inject
private DataBinder<OmposTerminalQuery> getDataBinder() {
if (dataBinder == null) {
final BeanBinder<OmposTerminalQuery> binder = BeanBinder.instance(OmposTerminalQuery.class);
binder.registerBinder("pageParameters", DataBinderHelper.pageBinder());
binder.registerBinder("retailer", PropertyBinder.instance(OmposRetailer.class, "retailer"));
binder.registerBinder("branch", PropertyBinder.instance(OmposBranch.class, "branch"));
binder.registerBinder("store", PropertyBinder.instance(OmposStore.class, "store"));
binder.registerBinder("terminalId", PropertyBinder.instance(String.class, "terminalId"));
binder.registerBinder("terminalSearchByTid",
PropertyBinder.instance(String.class, "terminalSearchByTid"));
dataBinder = binder;
}
return dataBinder;
}
#Override
protected void executeQuery(ActionContext context, QueryParameters queryParameters) {
final OmposTerminalQuery query = (OmposTerminalQuery) queryParameters;
query.setResultType(ResultType.PAGE);
// List<OmposRetailer> retailerList = retailerService.searchRetailers();
// context.getRequest().setAttribute("retailers", retailerList);
// if (query.getRetailer() != null) {
// OmposBranchQuery branchQuery = new OmposBranchQuery();
// branchQuery.setOmposRetailer(query.getRetailer());
// List<OmposBranch> branchList = retailerService.searchBranchByRetailer(branchQuery);
// context.getRequest().setAttribute("branches", branchList);
// if (query.getBranch() != null) {
// OmposStoreQuery storeQuery = new OmposStoreQuery();
// storeQuery.setOmposBranch(query.getBranch());
// List<OmposStore> storeList = retailerService.searchStore(storeQuery);
List<OmposStore> storeList = retailerService.searchStores();
context.getRequest().setAttribute("stores", storeList);
if (query.getStore() != null) {
ListTerminalDevicesForm form = context.getForm();
final FormFile uploadTerminal = form.getUploadTerminal();
if (uploadTerminal != null && uploadTerminal.getFileSize() != 0) {
try {
ImportCSVDTO uploadDtoForTerminal = new ImportCSVDTO();
// uploadDtoForTerminal.setRetailer(query.getRetailer());
// uploadDtoForTerminal.setBranch(query.getBranch());
uploadDtoForTerminal.setStore(query.getStore());
int records = importCSVService.importCSV(TMSEntity.TERMINAL, uploadDtoForTerminal,
uploadTerminal.getInputStream());
if (records > 0) {
context.getRequest().setAttribute("uploadMsgTerminal", records);
}
} catch (final UnknownColumnException | IOException e) {
// context.sendError("general.error.csv.unknownColumn",
// e.getColumn());
} finally {
uploadTerminal.destroy();
}
}
OmposTerminalQuery terminalQuery = new OmposTerminalQuery();
List<OmposTerminal> terminalList = null;
if (query.getStore() != null && query.getTerminalSearchByTid() != null) {
terminalQuery.setTerminalSearchByTid(query.getTerminalSearchByTid());
terminalQuery.setStore(query.getStore());
terminalList = terminalDeviceService.searchTerminalByTidAndStoreId(terminalQuery);
} else {
terminalQuery.setStore(query.getStore());
terminalList = terminalDeviceService.searchByStore(terminalQuery);
}
context.getRequest().setAttribute("terminals", terminalList);
if (query.getTerminalId() != null) {
OmposTerminal omposTerminal = new OmposTerminal();
omposTerminal.setTerminalId(query.getTerminalId());
OmposDeviceQuery deviceQuery = new OmposDeviceQuery();
deviceQuery.setOmposTerminal(omposTerminal);
final FormFile uploadDevice = form.getUploadDevice();
if (uploadDevice != null && uploadDevice.getFileSize() != 0) {
try {
ImportCSVDTO uploadDtoForDevice = new ImportCSVDTO();
uploadDtoForDevice.setRetailer(query.getRetailer());
uploadDtoForDevice.setBranch(query.getBranch());
uploadDtoForDevice.setStore(query.getStore());
uploadDtoForDevice.setTerminal(new OmposTerminal(null, query.getTerminalId(), null));
int records = importCSVService.importCSV(TMSEntity.DEVICE, uploadDtoForDevice,
uploadDevice.getInputStream());
if (records > 0) {
context.getRequest().setAttribute("uploadMsgDevice", records);
}
} catch (final UnknownColumnException | IOException e) {
// context.sendError("general.error.csv.unknownColumn",
// e.getColumn());
} finally {
uploadDevice.destroy();
}
}
context.getRequest().setAttribute("terminalId", query.getTerminalId());
List<OmposDevice> deviceList = terminalDeviceService.searchByTerminal(deviceQuery);
context.getRequest().setAttribute("devices", deviceList);
}
}
// }
// }
}
#Override
protected QueryParameters prepareForm(ActionContext context) {
final ListTerminalDevicesForm form = context.getForm();
final OmposTerminalQuery query = getDataBinder().readFromString(form.getQuery());
return query;
}
#Override
protected boolean willExecuteQuery(final ActionContext context,
final QueryParameters queryParameters) throws Exception {
return true;
}
}
I have to reset "terminalSearchByTid" field after the execution.
override Struts' Action reset() method

values modified in javascript not getting updated in JSF PhaseListener

Initially hold_mode value is set to 0, after commandButton click, it changed to 1 through JavaScript onclick event...but in PhaseListener beforePhase() method, the value is 0. I did not understand why the value is still 0.
Can anyone please explain me on this.?
info.xhtml
<h:form id="userForm">
<h:inputHidden id="hold_mode" value="0" />
<h:commandButton id="hold" style="width: 60px;" value="#{myForm.holdbtntitle}" disabled="#{myForm.holdbtn}" action="#{myForm.hold}" actionListener="#{convo.holdListener}" onclick="return send(true,'3');" rendered="#{myForm.holdpanelflg}"/>
JavaScript
function send(confirmFlg,msgFlg) {
isClicked = true;
if(confirmFlg) {
msg = 'From Hold';
if(confirm(msg) == false) {
isClicked = false;
event.returnValue = false;
return false;
}
}
if(isClicked) {
if(msgFlg == '3') {
document.all.item('myForm:hold_mode').value='1';
}
pep_OpenWaitDirect('../../../html/common/printwait.xhtml');
return true;
} else {
return false;
}
}
PhaseListener
public class RemoveValidateListener implements PhaseListener {
private static final long serialVersionUID = 3556867423746720962L;
private FacesContext old = null;
public void beforePhase(PhaseEvent e) {
System.out.println("Before "+e.getPhaseId());
if(e.getPhaseId().equals(PhaseId.PROCESS_VALIDATIONS)) {
UIComponent comp = FacesContext.getCurrentInstance().getViewRoot();
if(findHoldMode(comp)){
old = FacesContext.getCurrentInstance();
removeValidatorsForComponentTree(comp);
}
}
}
public void afterPhase(PhaseEvent e) {
System.out.println("After "+e.getPhaseId());
if(e.getPhaseId().equals(PhaseId.PROCESS_VALIDATIONS)) {
FacesContext context = FacesContext.getCurrentInstance();
UIComponent comp = FacesContext.getCurrentInstance().getViewRoot();
if(findHoldMode(comp)){
StateManager stateManager = (StateManager)context.getApplication().getStateManager();
stateManager.restoreView(old,old.getViewRoot().getViewId(),old.getViewRoot().getRenderKitId());
}
}
}
private boolean findHoldMode(UIComponent comp){
boolean rtnFlg = false;
List list = comp.getChildren();
for (int i = 0; i < list.size(); i++) {
UIComponent temp = (UIComponent) list.get(i);
if (!(temp instanceof HtmlBody)) {
continue;
} else {
List<UIComponent> childList = temp.getChildren();
for (int j = 0; j < childList.size(); j++) {
UIComponent childTemp = (UIComponent) childList.get(j);
if (!(childTemp instanceof HtmlPanelGrid)) {
continue;
} else {
List<UIComponent> child2List = childTemp.getChildren();
for (int k = 0; k < child2List.size(); k++) {
UIComponent child2Temp = (UIComponent) child2List.get(k);
if (!(child2Temp instanceof HtmlForm)) {
continue;
}
UIComponent hold = child2Temp.findComponent(JsfBase.HOLD_MODE_COMPNAME);
if (hold == null) {
continue;
}
if (!(hold instanceof UIInput)) {
continue;
}
Object mode = ((UIInput) hold).getValue();
if (mode == null || !(mode.toString().equals(JsfBase.HOLD_MODE_ON))) {
continue;
} else {
rtnFlg = true;
((UIInput) hold).setValue("0");
break;
}
}
}
}
}
}
return rtnFlg;
}
private void removeValidatorsForComponentTree(UIComponent comp){
removeValidators(comp);
List complist = comp.getChildren();
if (complist.size()>0){
for(int i = 0; i < complist.size(); i++) {
UIComponent uicom = (UIComponent) complist.get(i);
removeValidatorsForComponentTree(uicom);
}
}
}
private void removeValidators(UIComponent comp){
if(comp instanceof UIInput){
removeValidator((UIInput)comp);
}
}
public void removeValidator(UIInput comp){
Validator[] validator = comp.getValidators();
for(int i=0;i < validator.length;i++){
comp.removeValidator(validator[i]);
}
if(comp.isRequired()){
comp.setRequired(false);
}
}
}
I tried this <h:inputHidden id="hold_mode" value="0" immediate="true" /> and it works for the current screen but the problem is when I click the commandButton in other screens, the following exception occured
java.lang.IllegalStateException: FacesContext already released
Issue got fixed after modified PhaseListener
Why I got IllegalStateException is as I have declared FacesContext object old globally. In that case, I had declared it inside befoerPhase method as we don't declare FacesContext globally..
Before code modification, what we did is we removed validators in beforePhase and we are restoring the view state in afterPhase, but it did not worked properly. So now I am saving the view state before validators removal in beforePhase instead of restoring it in afterPhase..
public class RemoveValidateListener implements PhaseListener {
private static final long serialVersionUID = 3556867423746720962L;
public void beforePhase(PhaseEvent e) {
if (e.getPhaseId().equals(PhaseId.PROCESS_VALIDATIONS)) {
FacesContext context = FacesContext.getCurrentInstance();
UIComponent comp = context.getViewRoot();
StateManager stateManager = (StateManager) context.getApplication().getStateManager();
stateManager.saveView(context);
if (findHoryuMode(comp)) {
removeValidatorsForComponentTree(comp);
}
}
}
public void afterPhase(PhaseEvent e) {
}
}

Java Error: Can not find Symbol [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 5 years ago.
I've been working on this program for sometime now and I've been struggling with it. I'm new to programming so I don't understand how to fix it. So far I've managed to get rid of most of the errors but this one is the one I, for some reason, cannot fix. Can someone help me? I would really appreciate it.
import java.util.Scanner;
import java.util.ArrayList;
public class PetSorter
{
public static void main (String [] args)
{
ArrayList<Pet> strList = new ArrayList<Pet>();
Boolean another = true;
Scanner keyboard = new Scanner(System.in);
while(another)
{
System.out.println("Enter the pet's name: ");
String nam = keyboard.nextLine();
Pet p = new Pet(nam); //here is where the Error occurs
strList.add(p);
System.out.println("Would you like to enter another pet's name? (y/n)");
String answer = keyboard.nextLine();
another = answer.equalsIgnoreCase("y");
}
PetSorter.nameSort(strList);
for (int x = 0; x < strList.size(); x++)
{
System.out.println(strList.get(x).getName());
}
}
public static void nameSort (ArrayList<Pet> array)
{
for (int i = 1; i < array.size(); i++)
{
int j = i;
Pet tp = array.get(i);
String B = array.get(i).getName();
while ((j > 0) && (array.get(j-1).getName().compareTo(B) > 0 ))
{
array.set(j, array.get(j-1));
j--;
}
array.set(j,tp);
}
}
}
Here is the pet class below
import java.util.ArrayList;
import java.util.Scanner;
public class Pet
{
private String name;
private int age; //in years
private double weight; //in pounds
/**
This main is just a demonstration program.
*/
public static void main(String[] args)
{
Pet myDog = new Pet( );
myDog.set("Fido", 2, 5.5);
myDog.writeOutput( );
System.out.println("Changing name.");
myDog.set("Rex");
myDog.writeOutput( );
System.out.println("Changing weight.");
myDog.set(6.5);
myDog.writeOutput( );
System.out.println("Changing age.");
myDog.set(3);
myDog.writeOutput( );
}
public void writeOutput( )
{
System.out.println("Name: " + name);
System.out.println("Age: " + age + " years");
System.out.println("Weight: " + weight + " pounds");
}
public void set(String newName)
{
name = newName;
//age and weight are unchanged.
}
public void set(int newAge)
{
if (newAge <= 0)
{
System.out.println("Error: illegal age.");
System.exit(0);
}
else
age = newAge;
//name and weight are unchanged.
}
public void set(double newWeight)
{
if (newWeight <= 0)
{
System.out.println("Error: illegal weight.");
System.exit(0);
}
else
weight = newWeight;
//name and age are unchanged.
}
public void set(String newName, int newAge, double newWeight)
{
name = newName;
if ((newAge <= 0) || (newWeight <= 0))
{
System.out.println("Error: illegal age or weight.");
System.exit(0);
}
else
{
age = newAge;
weight = newWeight;
}
}
public String getName( )
{
return name;
}
public int getAge( )
{
return age;
}
public double getWeight( )
{
return weight;
}
}
Add to your Pet class the required constrcutor :
public class Pet {
String name;
...
public Pet (String name) {
this.name = name;
}
...
}
replace with
Pet p = new PetSorter().new Pet(nam); //here is where the Error occurs
and add class Pet
new code:
import java.util.Scanner;
import java.util.ArrayList;
public class PetSorter
{
public class Pet
{
String name;
public Pet(String _name)
{
name=_name;
}
public String getName()
{
return name;
}
}
public static void main (String [] args)
{
ArrayList<Pet> strList = new ArrayList<Pet>();
Boolean another = true;
Scanner keyboard = new Scanner(System.in);
while(another)
{
System.out.println("Enter the pet's name: ");
String nam = keyboard.nextLine();
Pet p = new PetSorter().new Pet(nam); //here is where the Error occurs
strList.add(p);
System.out.println("Would you like to enter another pet's name? (y/n)");
String answer = keyboard.nextLine();
another = answer.equalsIgnoreCase("y");
}
PetSorter.nameSort(strList);
for (int x = 0; x < strList.size(); x++)
{
System.out.println(strList.get(x).getName());
}
}
public static void nameSort (ArrayList<Pet> array)
{
for (int i = 1; i < array.size(); i++)
{
int j = i;
Pet tp = array.get(i);
String B = array.get(i).getName();
while ((j > 0) && (array.get(j-1).getName().compareTo(B) > 0 ))
{
array.set(j, array.get(j-1));
j--;
}
array.set(j,tp);
}
}
}
Pet p = new Pet(nam); , Pet class doesn't have a constructor that takes any arguments.

Validating ReCaptcha (Javascript API) User Answer on Localhost with ASP.NET

I am using ReCaptcha with the javascript API on my aspx page on localhost. I read somewhere that I don't need a key as long as I use it on localhost. So, I use some random key that I found somewhere. I could render the recaptcha challenge successfully. The following is my javascript code.
Recaptcha.create("6Ld4iQsAAAAAAM3nfX_K0vXaUudl2Gk0lpTF3REf", 'captchadiv',
{
tabindex: 1,
theme: "clean",
callback: Recaptcha.focus_response_field
});
//To Validate user response
function Recaptcha_IsCorrect()
{
var xmlHttpRequest;
var PageURL = document.URL;
var xmlDoc;
if (window.XMLHttpRequest)
{
xmlHttpRequest = new XMLHttpRequest();
}
else
{
xmlHttpRequest = new ActiveXObject("Microsoft.xmlHttpRequest");
}
var challenge = Recaptcha.get_challenge();
var userResponse = Recaptcha.get_response();
var url = "../Ajax/PIAsyncAjax.asmx/ValidateReCaptcha?clientIP=127.0.0.1&privateKey=6Ld4iQsAAAAAAM3nfX_K0vXaUudl2Gk0lpTF3REf&challenge=" + challenge + "&response=" + userResponse;
xmlHttpRequest.open("GET", url);
xmlHttpRequest.onreadystatechange = function ()
{
if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
{
alert(xmlHttpRequest.responseText);
}
};
xmlHttpRequest.send();
}
The following is my code for the webservice which exposed the webmethod to validate ReCaptcha user input. I get the error "invalid-site-private-key".
namespace YADA.YADAYADA{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class PIAsyncAjax : System.Web.Services.WebService
{
[WebMethod]
public string ValidateReCaptcha(string clientIP, string privateKey, string challenge, string response)
{
bool isValid = false;
string validationResponse = "";
reCaptchaValidation validator =
new reCaptchaValidation(null,
clientIP,
privateKey,
challenge,
response);
isValid = validator.Validate();
if (isValid)
{
validationResponse = "true";
}
else
{
if (!validator.IsErrored)
{
validationResponse = "false";
}
else
{
// oh dear, something not right
if (validator.Exception != null) // an exception occurred while
// trying to validate
validationResponse = validator.Exception.ToString();
else if (validator.ValidationResult != null) // the validation web service
// returned an error code
// (other than an invalid captcha solution)
validationResponse = "web service error: " + validator.ValidationResult;
}
}
return validationResponse;
}
}
public class reCaptchaValidation
{
private string challenge, response, privateKey, ip;
private IWebProxy proxy;
public reCaptchaValidation(string clientIP, string privateKey,
string challenge, string response) : this(null, clientIP, privateKey,
challenge, response) { }
public reCaptchaValidation(IWebProxy proxy, string clientIP,
string privateKey, string challenge, string response)
{
this.proxy = proxy;
this.ip = clientIP;
this.privateKey = privateKey;
this.challenge = challenge;
this.response = response;
}
private bool _errored;
public bool IsErrored
{
get
{
return _errored;
}
}
private Exception _ex;
public Exception Exception
{
get
{
return _ex;
}
}
private string _vr;
public string ValidationResult
{
get
{
return _vr;
}
}
public bool Validate()
{
try
{
string post = "privatekey=" + HttpUtility.UrlEncode(privateKey) +
"&remoteip=" + HttpUtility.UrlEncode(ip) + "&challenge=" +
HttpUtility.UrlEncode(challenge) + "&response=" +
HttpUtility.UrlEncode(response);
WebRequest wr = HttpWebRequest.Create
("http://www.google.com/recaptcha/api/verify");
wr.Method = "POST";
if (proxy != null)
wr.Proxy = proxy;
wr.ContentLength = post.Length;
wr.ContentType = "application/x-www-form-urlencoded";
using (StreamWriter sw = new StreamWriter(wr.GetRequestStream()))
{
sw.Write(post);
sw.Close();
}
HttpWebResponse resp = (HttpWebResponse)wr.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
string valid = sr.ReadLine();
if (valid != null)
{
if (valid.ToLower().Trim() == "false")
{
string errorcode = sr.ReadLine();
if (errorcode != null)
{
if (errorcode.ToLower().Trim() != "incorrect-captcha-sol")
{
_vr = errorcode;
_errored = true;
return false;
}
}
}
return (valid.ToLower().Trim() == "true");
}
else _vr = "empty web service response";
sr.Close();
return false;
}
}
catch (Exception caught)
{
_errored = true;
_ex = caught;
}
return false;
}
}}
What am I doing wrong? Should I have to get a private key? Any help would be great.
Thanks in advance,
Venkat.
It works with the public and private keys that I just created. Damn, I just assumed, "localhost" would not be accepted as a legal domain-name while signing up.

Categories