getting error non void function does not return a value in all control paths - function

bool vote(string name){
// TODO
for(int i = 0 ; i < candidate_count ; i++){
if(strcmp(name,candidates[i].name) == 0){
candidates[i].votes = candidates[i].votes + 1;
return true;
}
}
else{
return false;
}
}
It is a voter function that when a user inputs candidates name,
it's going to check if it is in the candidates array.
But when I compile the code I'm getting the error non void function does not return a value.

Related

For/If Loop has no errors but does not push the value to the array

I am trying to create a whitelist. I've used a for and if loop to check if the msg.sender already exists in the array. When the whitelist() function is run, no errors are returned, but when I run check(), it tells me the address doesn't exist in the array, same thing with directing fetching the array.
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SelfWhitelist {
address[] public addressWhitelist;
function whitelist() public returns(string memory) {
for(uint i = 0; i < addressWhitelist.length; i++) {
if(addressWhitelist[i] != msg.sender) {
addressWhitelist.push(msg.sender);
return "Whitelisted!";
}
}
return "Already whitelisted!";
}
function check() public view returns (bool){
for(uint i = 0; i < addressWhitelist.length; i++){
if(addressWhitelist[i] == msg.sender)
return true;
}
return false;
}
}
I added this block of code to check for duplicate entries in the array.
for(uint i = 0; i < addressWhitelist.length; i++) {
if(addressWhitelist[i] != msg.sender) {
addressWhitelist.push(msg.sender);
return "Whitelisted!";
}
Expected for no errors and my address being pushed to the array.
The code ran without errors, but nothing was added to the array.
I would use mapping type to hold the whitelisted addresses, then you don't have to loop over the array
contract SelfWhitelist {
mapping(address => bool) public addressWhitelist;
function whitelist() public returns(string memory) {
if (check()) {
return "Already whitelisted!";
}
addressWhitelist[msg.sender] = true;
return "Whitelisted!";
}
function check() public view returns (bool) {
return addressWhitelist[msg.sender];
}
}
And in your code, seems you have logical issues:
for(uint i = 0; i < addressWhitelist.length; i++) {
if(addressWhitelist[i] != msg.sender) {
addressWhitelist.push(msg.sender);
return "Whitelisted!";
}
}
if the array is empty, the loop never executes, so nothing will be added
if the first item is not msg.sender, msg.sender will be whitelisted, even though it might be already whitelisted.

Gas Estimate of function: Infinite

Here's my first ever smart contract. What exactly causes such a warning and how should I improve my code?
This is just one of many similar warnings
Warning:
Gas requirement of function Consensus.deployPmu(string) high: infinite. If the gas requirement of a function is higher than the block gas limit, it cannot be executed. Please avoid loops in your functions or actions that modify large areas of storage (this includes clearing or copying arrays in storage)
pragma solidity ^0.5.7;
contract Consensus {
struct PMU{
string name;
address pmu;
uint256[] data;
bool errorFlag;
uint256 errorCount;
}
mapping (address => PMU) PMUS;
address[] accounts;
uint256[] empty;
function deployPmu(string memory _name) public{
PMUS[msg.sender] = PMU(_name,msg.sender,empty,false,0);
accounts.push(msg.sender);
}
function print() public view returns(string memory name, uint256[] memory data,bool errorFlag,uint256 errorCount){
PMU memory instancePMU = PMUS[msg.sender];
return (instancePMU.name,instancePMU.data,instancePMU.errorFlag,instancePMU.errorCount);
}
function log(uint256[] memory roc) public{
for (uint i=0; i<roc.length;i++){
PMUS[msg.sender].data.push(roc[i]);
if(roc[i]<12){
PMUS[msg.sender].errorFlag = false;
errorFlags[msg.sender] = false;
PMUS[msg.sender].errorCount=0;
}
if(roc[i]>12){
PMUS[msg.sender].errorCount= PMUS[msg.sender].errorCount+1;
}
if( PMUS[msg.sender].errorCount >= 5){
PMUS[msg.sender].errorFlag = true;
errorFlags[msg.sender] = true;
PMUS[msg.sender].errorCount = 0;
}
}
}
mapping (address => bool) errorFlags;
bool GridFault=false;
bool PMUfault=false;
address[] tru;
address[] falz;
function faultStatus () public returns (address[] memory)
{
address[] memory empty;
tru = empty;
falz =empty;
GridFault = false;
PMUfault = false;
uint256 count =0;
for(uint256 i =0; i<accounts.length; i++){
if(errorFlags[accounts[i]] == true){
count = count + 1;
tru.push(accounts[i]);
}
else{
falz.push(accounts[i]);
}
}
if(count > (accounts.length-1)/2){
GridFault = true;
if(falz.length != 0){
PMUfault = true;
}
}
else if(count == 0){
GridFault = false;
PMUfault = false;
}
else{
PMUfault = true;
return tru;
}
}
function gridstatus() public view returns(address[] memory, bool, bool){
if(GridFault == true){
return (falz,GridFault, PMUfault);
}
else{
return(tru,GridFault, PMUfault);
}
}
}

How the performance of a JavaFx-MySQL application can be enhanced

In my JavaFx application, i'm loading an ObservableList when a button is clicked and then display the list in a table.
the controller code:
#FXML
private void initialize() throws SQLException, ParseException, ClassNotFoundException {
searchChoice.setItems(criteriaList);
searchChoice.getSelectionModel().selectFirst();
productIdColumn.setCellValueFactory(cellData -> cellData.getValue().productIdProperty());
unitColumn.setCellValueFactory(cellData -> cellData.getValue().unitProperty());
productTitleColumn.setCellValueFactory(cellData -> cellData.getValue().titleProperty());
productTypeColumn.setCellValueFactory(cellData -> cellData.getValue().typeProperty());
productUnitPriceColumn.setCellValueFactory(cellData -> Bindings.format("%.2f", cellData.getValue().unitPriceProperty().asObject()));
productQuantityColumn.setCellValueFactory(cellData -> cellData.getValue().quantityProperty().asObject());
productStatusColumn.setCellValueFactory(cellData -> cellData.getValue().productStatusProperty());
descriptionColumn.setCellValueFactory(cellData -> cellData.getValue().descriptionProperty());
reorderPointColumn.setCellValueFactory(cellData -> cellData.getValue().reOrderPointProperty().asObject());
surplusPointColumn.setCellValueFactory(cellData -> cellData.getValue().surplusPointProperty().asObject());
productIdColumn.setSortType(TableColumn.SortType.DESCENDING);
productTable.getSortOrder().add(productIdColumn);
productTable.setRowFactory(tv -> new TableRow<Product>() {
#Override
public void updateItem(Product item, boolean empty) {
super.updateItem(item, empty);
if (item == null) {
setStyle("");
} else if (item.getQuantity() < item.getReOrderPoint()) {
setStyle("-fx-background-color: tomato;");
} else if (item.getQuantity() > item.getSurplusPoint()) {
setStyle("-fx-background-color: darkorange;");
} else {
setStyle("-fx-background-color: skyblue;");
}
}
});
try {
ObservableList<Product> productData = ProductDAO.searchProducts();
populateProducts(productData);
String[] expireDate = new String[productData.size()];
String[] id = new String[productData.size()];
String[] existingStatus = new String[productData.size()];
for (int i = 0; i < productData.size(); i++) {
expireDate[i] = productData.get(i).getExpireDate();
id[i] = productData.get(i).getProductId();
existingStatus[i] = productData.get(i).getProductStatus();
DateFormat format = new SimpleDateFormat(app.values.getProperty("DATE_FORMAT_PATTERN"), Locale.ENGLISH);
Date expireDateString = format.parse(expireDate[i]);
Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date today = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
if (expireDateString.before(today) && !existingStatus[i].equals(app.values.getProperty("STATUS_TYPE2"))) {
ProductDAO.updateProductStatus(id[i], app.values.getProperty("STATUS_TYPE3"));
}
if (expireDateString.after(today) && !existingStatus[i].equals(app.values.getProperty("STATUS_TYPE2"))) {
ProductDAO.updateProductStatus(id[i], app.values.getProperty("STATUS_TYPE1"));
}
}
ObservableList<Product> productDataRefreshed = ProductDAO.searchProducts();
populateProducts(productDataRefreshed);
ObservableList<Product> productCodesData = ProductDAO.getProductCodes();
ObservableList<Product> productTitlesData = ProductDAO.getProductTitles();
ObservableList<Product> productTypesData = ProductDAO.getProductTypes();
ObservableList<Product> productStatusData = ProductDAO.getProductStatus();
String possibleProducts1[] = new String[productCodesData.size()];
for (int k = 0; k < productCodesData.size(); k++) {
possibleProducts1[k] = productCodesData.get(k).getProductId();
}
String possibleProducts2[] = new String[productTitlesData.size()];
for (int k = 0; k < productTitlesData.size(); k++) {
possibleProducts2[k] = productTitlesData.get(k).getTitle();
}
String possibleProducts3[] = new String[productTypesData.size()];
for (int k = 0; k < productTypesData.size(); k++) {
possibleProducts3[k] = productTypesData.get(k).getType();
}
String possibleProducts4[] = new String[productStatusData.size()];
for (int k = 0; k < productStatusData.size(); k++) {
possibleProducts4[k] = productStatusData.get(k).getProductStatus();
}
TextFields.bindAutoCompletion(searchField, possibleProducts1);
TextFields.bindAutoCompletion(searchField, possibleProducts2);
TextFields.bindAutoCompletion(searchField, possibleProducts3);
TextFields.bindAutoCompletion(searchField, possibleProducts4);
} catch (SQLException e) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle(app.values.getProperty("ERROR_TITLE"));
alert.setHeaderText(app.values.getProperty("FAILURE_MESSAGE"));
alert.setHeaderText(app.values.getProperty("ERROR_GETTING_INFORMATION_FROM_DATABASE_MESSAGE"));
alert.showAndWait();
throw e;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
the service mysql query :
public static ObservableList<Product> searchProducts() throws SQLException, ClassNotFoundException {
String selectStmt = "SELECT * FROM product";
ResultSet rsPrdcts = DbUtil.dbExecuteQuery(selectStmt);
ObservableList<Product> productList = getProductList(rsPrdcts);
return productList;
}
The issue here is, when there are more than 200-300 items in the list the scene gets really slow to load. What countermeasures can I take regarding this matter? Any idea will be very much appreciated.
Thanks in advance.
You need to implement an ObservableList which only retrieves the data which is rqeusted by the TableView. Currently you retrive all elements in the table and cast the retrieved list to an ObservableList.
The TableView uses the .get(int idx) method of the OL to retrieve all items which should be displayed and the .size() method for determining the size of the scrollbar. When you scroll the TableView will discard all items which are not displayed and call the get method again.
To solve your problem need to create a class which implements ObservableList<E>. First you need to implement the .get(int idx) and the .size() method, for all other methods I would throw new UnsupportedOperationException() and later on see which other method is needed. So the .size() method needs to execute the following query
SELECT count(*) FROM product
and the get(int idx) something like this
int numItems = 30;
int offset = idx - (idx % numItems)
SELECT * FROM product LIMIT offset, numItems
you can create an internal list which only holds e.g. 30 items from your db and whenever the requested idx < offset || idx > offset + numItems you issue a new db request.
I used this this approach with database tables with millions of rows and had a very performant GUI. You can also add paging to the TableView because with to many rows the scrollbar gets useless, but this is a different discussion.
edit:
I forgot to mention that this is called Lazy Loading

Object Reference not set to an instance of an object at ScriptMain.CreateNewOutputRows()

I have this dataset:
001abcdefghijklmnopqrstuvwxyz
003jfaoijfpoisajeoaijefoaijofija
005;lksajdf;lkjsafd;lkjdf
006;ldsjfa;ojfda;okjdfa;lkjfda
009;akjfd;lakjfd;lajfd;lakjfd;la
013jjsjfkdjf;ldsajfljkd;fjkdfjdfj
001kfjfdjfkdjfosjisjfojesfljsijfesli <-- New Record
I am using a Script Transformation to transform these rows into columns:
private StreamReader SR;
private string File1;
public override void AcquireConnections(object Transaction)
{
// Get the connection for File1
IDTSConnectionManager100 CM = this.Connections.OILFILEMGR;
File1 = (string)CM.AcquireConnection(null);
}
public override void PreExecute()
{
// Create a reader for File1
base.PreExecute();
SR = new StreamReader(File1);
}
public override void PostExecute()
{
// Close the reader
base.PostExecute();
SR.Close();
}
public override void CreateNewOutputRows()
{
// Declare variables
string nextLine;
int LineNumber;
nextLine = SR.ReadLine();
LineNumber = 1;
while (nextLine != null)
{
//MessageBox.Show(nextLine);
// Add a row
Output0Buffer.AddRow();
Output0Buffer.APINumber = nextLine.Substring(5, 6);
Output0Buffer.County = nextLine.Substring(2, 3);
Output0Buffer.District = nextLine.Substring(14, 2);
nextLine = SR.ReadLine();
LineNumber = LineNumber + 1;
while (nextLine.Substring(0, 2) != "01")
{
if (nextLine.Substring(0, 2) == "02")
{
Output0Buffer.LeaseNumber = nextLine.Substring(5, 5);
}
if (nextLine.Substring(0, 2) == "09")
{
Output0Buffer.FormationName = nextLine.Substring(5, 32);
}
if (nextLine.Substring(0, 2) == "13")
{
Output0Buffer.Latitude = nextLine.Substring(132, 10);
Output0Buffer.Longitude = nextLine.Substring(142, 10);
}
nextLine = SR.ReadLine();
LineNumber = LineNumber + 1;
}
}
}
}
I tried to split the datasets in half, and I noticed that the number of rows being processed went down with each split by half as well. This leads me to believe the code works, but is not closing out correctly. I believe when the last record is recorded, somehow the script errors out.
What am I missing here?
Thanks.
After much tinkering, I ran into this C#.net staple.
If you have a null line, don't try to Subset it.
I changed:
while (nextLine.Substring(0, 2) != "01")
to:
while(nextLine != null && nextLine.Substring(0, 2) != "01")
Since the nextLine = SR.ReadLine(); is prior to the substring, you have to check against null.
Enjoy.

Calling parents by name

Is there a way/plugin to call $parents["ExamViewModel"] instead of $parents[2]?
That would be very helpful for shared views that may show in different parent views.
No there is no such thing.
You could create your own method using instanceof as a cleaner way.
Something like:
function findParentOfType(parents, targetType) {
for (var i = 0; i < parents.length; i++) {
if (parents[i] instanceof targetType) return parents[i];
}
return null;
}
Usage:
findParentOfType($parents, ExamViewModel)
Example:
function Class1() {
this.name = 'MyClass1';
}
function Class2() {
this.name = 'MyClass2';
}
var parents = [new Class1(), new Class2()];
function findParentOfType(parents, targetType) {
for (var i = 0; i < parents.length; i++) {
if (parents[i] instanceof targetType) return parents[i];
}
return null;
}
console.log(findParentOfType(parents, Class2).name);