I am new to blockchain technology. I am trying to deploy smart contract. But I am always getting below error while compiling sol file. It was working, but suddenly stopped working. I have not made any changes.
This is the error I am getting
Traceback (most recent call last):
File ".\main.py", line 68, in <module>
main()
File ".\main.py", line 57, in main
compiled_sol = compile_source_file('contract.sol')
File ".\main.py", line 20, in compile_source_file
return solcx.compile_source(source)
File "C:\Program Files (x86)\Python37-32\lib\site-packages\solcx\main.py", line 130, in compile_source
allow_empty=allow_empty,
File "C:\Program Files (x86)\Python37-32\lib\site-packages\solcx\main.py", line 277, in _compile_combined_json
combined_json = _get_combined_json_outputs(solc_binary)
File "C:\Program Files (x86)\Python37-32\lib\site-packages\solcx\main.py", line 242, in _get_combined_json_outputs
help_str = wrapper.solc_wrapper(solc_binary=solc_binary, help=True)[0].split("\n")
File "C:\Program Files (x86)\Python37-32\lib\site-packages\solcx\wrapper.py", line 163, in solc_wrapper
stderr_data=stderrdata,
solcx.exceptions.SolcError: An error occurred during execution
> command: `C:\Users\Nikesh\.solcx\solc-v0.8.11\solc.exe --help -`
> return code: `0`
> stdout:
solc, the Solidity commandline compiler.
This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you
are welcome to redistribute it under certain conditions. See 'solc --license'
for details.
Usage: solc [options] [input_file...]
Compiles the given Solidity input files (or the standard input if none given or
"-" is used as a file name) and outputs the components specified in the options
at standard output or in files in the output directory, if specified.
Imports are automatically read from the filesystem, but it is also possible to
remap paths using the context:prefix=path syntax.
Example:
solc --bin -o /tmp/solcoutput dapp-bin=/usr/local/lib/dapp-bin contract.sol
General Information:
--help Show help message and exit.
--version Show version and exit.
--license Show licensing information and exit.
--input-file arg input file
Input Options:
--base-path path Use the given path as the root of the source tree
instead of the root of the filesystem.
--include-path path Make an additional source directory available to the
default import callback. Use this option if you want to
import contracts whose location is not fixed in relation
to your main source tree, e.g. third-party libraries
installed using a package manager. Can be used multiple
times. Can only be used if base path has a non-empty
value.
--allow-paths path(s)
Allow a given path for imports. A list of paths can be
supplied by separating them with a comma.
--ignore-missing Ignore missing files.
--error-recovery Enables additional parser error recovery.
I am using web3 and solcx
This is the contract.sol file
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
contract StoreVar {
uint8 public _myVar;
event MyEvent(uint indexed _var);
function setVar(uint8 _var) public {
_myVar = _var;
emit MyEvent(_var);
}
function getVar() public view returns (uint8) {
return _myVar;
}
}
And this is the main file
from web3 import Web3
from web3.middleware import geth_poa_middleware
# from solcx import compile_source, install_solc
import solcx
"""
pip install py-solc-x
pip install web3
"""
def compile_source_file(file_path):
solcx.install_solc(version='latest')
# install_solc(version='latest')
# install_solc("0.6.0")
# print(solcx.get_compilable_solc_versions())
with open(file_path, 'r') as f:
source = f.read()
print(source)
return solcx.compile_source(source)
def deploy_contract(w3, contract_interface):
# unicorns = w3.eth.contract(address="0x589a1532Aasfgs4e38345b58C11CF4697Ea89A866", abi=contract_interface['abi'])
# nonce = w3.eth.get_transaction_count('0x589a1532AAaE84e38345b58C11CF4697Eaasasd')
# unicorn_txn = unicorns.functions.transfer(
# '0x589a1532AAaE84e38345b58C11CF4697asdfasd',
# 1,
# ).buildTransaction({
# 'chainId': 1,
# 'gas': 70000,
# 'maxFeePerGas': w3.toWei('2', 'gwei'),
# 'maxPriorityFeePerGas': w3.toWei('1', 'gwei'),
# 'nonce': nonce,
# })
# print(unicorn_txn)
tx_hash = w3.eth.contract(
abi=contract_interface['abi'],
bytecode=contract_interface['bin']).constructor().transact()
address = w3.eth.get_transaction_receipt(tx_hash)['contractAddress']
return address
def main():
w3 = Web3(Web3.HTTPProvider("https://rinkeby.infura.io/v3/c0easgasgas2666cd56ef4e3"))
w3.middleware_onion.inject(geth_poa_middleware, layer=0)
# print(w3.eth.get_block('latest'))
# print(w3.eth.get_balance('0x589a15asdfasdfab58C11CF4697Ea89A866'))
address = '0x589a1532AAaE8asdfasdf8C11CF4697Ea89A866'
abi = '[{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"address","name":"minter_","type":"address"}'
compiled_sol = compile_source_file('contract.sol')
contract_id, contract_interface = compiled_sol.popitem()
# print(contract_id)
# print(contract_interface)
address = deploy_contract(w3, contract_interface)
print(f'Deployed {contract_id} to: {address}\n')
main()
Please help me out resolving this.
Update:
solcx.compile_source has an optional output_values argument. If you don't provide it, py-solc-x will parse the solc --help output for it. In solc v0.8.9 and earlier, the return value for solc --help was 1, but that changed to 0 with v0.8.10, which breaks what py-solc-x is expecting.
I have a pull request in with py-solc-x to fix it. In the meantime, you can either use solc <=v0.8.9 or specify your own output_values.
Original:
I'm not sure what the root of the problem is, but specifying an solc version <=0.8.9 worked for me. In your example:
def compile_source_file(file_path):
solcx.install_solc(version='0.8.9')
solcx.set_solc_version('0.8.9')
with open(file_path, 'r') as f:
source = f.read()
print(source)
return solcx.compile_source(source)
Related
Im new to pyflink. Im tryig to write a python program to read data from kafka topic and prints data to stdout. I followed the link Flink Python Datastream API Kafka Producer Sink Serializaion. But i keep seeing NoSuchMethodError due to version mismatch. I have added the flink-sql-kafka-connector available at https://repo.maven.apache.org/maven2/org/apache/flink/flink-sql-connector-kafka_2.11/1.13.0/flink-sql-connector-kafka_2.11-1.13.0.jar. Can someone help me in with a proper example to do this? Following is my code
import json
import os
from pyflink.common import SimpleStringSchema
from pyflink.datastream import StreamExecutionEnvironment
from pyflink.datastream.connectors import FlinkKafkaConsumer
from pyflink.common.typeinfo import Types
def my_map(obj):
json_obj = json.loads(json.loads(obj))
return json.dumps(json_obj["name"])
def kafkaread():
env = StreamExecutionEnvironment.get_execution_environment()
env.add_jars("file:///automation/flink/flink-sql-connector-kafka_2.11-1.10.1.jar")
deserialization_schema = SimpleStringSchema()
kafkaSource = FlinkKafkaConsumer(
topics='test',
deserialization_schema=deserialization_schema,
properties={'bootstrap.servers': '10.234.175.22:9092', 'group.id': 'test'}
)
ds = env.add_source(kafkaSource).print()
env.execute('kafkaread')
if __name__ == '__main__':
kafkaread()
But python doesnt recognise the jar file and throws the following error.
Traceback (most recent call last):
File "flinkKafka.py", line 31, in <module>
kafkaread()
File "flinkKafka.py", line 20, in kafkaread
kafkaSource = FlinkKafkaConsumer(
File "/automation/flink/venv/lib/python3.8/site-packages/pyflink/datastream/connectors.py", line 186, in __init__
j_flink_kafka_consumer = _get_kafka_consumer(topics, properties, deserialization_schema,
File "/automation/flink/venv/lib/python3.8/site-packages/pyflink/datastream/connectors.py", line 336, in _get_kafka_consumer
j_flink_kafka_consumer = j_consumer_clz(topics,
File "/automation/flink/venv/lib/python3.8/site-packages/pyflink/util/exceptions.py", line 185, in wrapped_call
raise TypeError(
TypeError: Could not found the Java class 'org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer'. The Java dependencies could be specified via command line argument '--jarfile' or the config option 'pipeline.jars'
What is the correct location to add the jar file?
I see that you downloaded flink-sql-connector-kafka_2.11-1.13.0.jar, but the code loades flink-sql-connector-kafka_2.11-1.10.1.jar.
May be you can have a check
just need to check the path to flink-sql-connector jar
You should add jar file of flink-sql-connector-kafka, it depends on your pyflink and scala version. If versions are true, check your path in add_jars function if the jar package is here.
I'm currently struggling with the following problem:
My folder structer looks like:
master
- resources
customFile.fmu
fileCallingFMU.py
While executing the fileCallingFMU.py I pass a path string like
path = "./resources/customFile.fmu"
My script contains a super function where I pass the path variable. But everytime I execute the script it trips with an exception:
Exception has occurred: FileNotFoundError
[Errno 2] No such file or directory: b'2021-11-16_./resources/customFile.fmu.txt'
File "[projectFolder]\fileCallingFMU.py", line 219, in __init__
super().__init__(path, config, log_level)
File "[projectFolder]\fileCallingFMU.py", line 86, in <module>
env = gym.make(env_name)
My urging question now is the following:
Why and how does python manipulate the path variable with a date-prefix and .txt as file extension?!
Hope anyone can enlighten me on this one...
EDIT
I'm trying to get the example of ModelicaGym running.
My fileCallingFMU.py contains the following code:
path = "./resources/customFile.fmu"
env_entry_point = 'cart_pole_env:JModelicaCSCartPoleEnv'
config = {
'path': path,
'm_cart': m_cart,
'm_pole': m_pole,
'theta_0': theta_0,
'theta_dot_0': theta_dot_0,
'time_step': time_step,
'positive_reward': positive_reward,
'negative_reward': negative_reward,
'force': force,
'log_level': log_level
}
from gym.envs.registration import register
env_name = env_name
register(
id=env_name,
entry_point=env_entry_point,
kwargs=config
)
env = gym.make(env_name)
The full code for the entryPoint can be found here.
As jjramsey pointed out the problem was burried within the ModelicaGym library.
The logger could not create a propper log file, because the model name was not properly stored in the self.model variable.
Source of this error lied in the line
self.model_name = model_path.split(os.path.sep)[-1]
due to the fact that the os library was not able to separate my path string
"./resources/customFile.fmu"
After changing it to
".\\resources\\customFile.fmu"
everythig works as expected.
Thanks again!
Well, I am making a personal project, for this project, I need to run a python script every time on the computer, and this script needs to start when the computer is turned on, for this, I used PyInstaller to turn the script in a ".exe" file, but an error is shown.
Python Code, filename; "teste.py":
import pynotifier
pynotifier.Notification(
"TESTE", # Translate: Test
"ISSO É APENAS UM TESTE", # Translate: This is just a test
6
).send()
this code just show me a notification, I turned it into a ".exe" file with this code:
pyinstaller --onefile --nowindowed teste.py
when I execute it, turns the python file into a exe file normally, but when I execute it, it shows me this message:
Exception in thread Thread-1:
Traceback (most recent call last):
File "threading.py", line 917, in _bootstrap_inner
File "threading.py", line 865, in run
File "win10toast\__init__.py", line 93, in _show_toast
File "pkg_resources\__init__.py", line 1144, in resource_filename
File "pkg_resources\__init__.py", line 357, in get_provider
File "pkg_resources\__init__.py", line 900, in require
File "pkg_resources\__init__.py", line 786, in resolve
pkg_resources.DistributionNotFound: The 'win10toast' distribution was not found and is required by the application
for more information, this is the code inside the PyNotifier module, since it has no documentation on the web:
init.py file:
from .pynotifier import Notification
version.py file:
VERSION = (0, 1, 1)
__version__ = '.'.join(map(str, VERSION))
pynotifier.py file:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# PyNotifier
# Copyright (c) 2018 Yuriy Lisovskiy
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
__all__ = ['Notification']
# standard library
import platform
# class to run notification
class Notification:
# urgency level
URGENCY_LOW = 'low'
URGENCY_NORMAL = 'normal'
URGENCY_CRITICAL = 'critical'
# 'title' - a title of notification
# 'description' - more info about the notification
# 'duration' - notification timeout in seconds
# 'urgency' - notification urgency level
# 'icon_path' - path to notification icon file
def __init__(self, title, description, duration=5, urgency=URGENCY_LOW, icon_path=None):
if urgency not in [self.URGENCY_LOW, self.URGENCY_NORMAL, self.URGENCY_CRITICAL]:
raise ValueError('invalid urgency was given: {}'.format(urgency))
self.__WINDOWS = 'Windows'
self.__LINUX = 'Linux'
self.__title = title
self.__description = description
self.__duration = duration
self.__urgency = urgency
self.__icon_path = icon_path
self.__is_windows = False
# 'send' - sends notification depending on system
def send(self):
system = platform.system()
if self.__LINUX in system:
self.__send_linux()
elif self.__WINDOWS in system:
self.__send_windows()
else:
raise SystemError('notifications are not supported for {} system'.format(system))
# '__send_linux' - sends notification if running on Linux system
def __send_linux(self):
import subprocess
command = [
'notify-send', '{}'.format(self.__title),
'{}'.format(self.__description),
'-u', self.__urgency,
'-t', '{}'.format(self.__duration * 1000)
]
if self.__icon_path is not None:
command += ['-i', self.__icon_path]
subprocess.call(command)
# '__send_windows' - sends notification if running on Windows system
def __send_windows(self):
try:
import win10toast
win10toast.ToastNotifier().show_toast(
threaded=True,
title=self.__title,
msg=self.__description,
duration=self.__duration,
icon_path=self.__icon_path
)
except ImportError:
raise ImportError('notifications are not supported, can\'t import necessary library')
Please help me guys :|
Try this library's
import plyer.platforms.win.notification
from plyer import notification
I wrote the following code, which results in an error and I don't know how to fix it to work.
The code is:
# Name: ClipGDBtoNewGDB.py
# Description: Take an input GDB, create a list, iterate through each
feature class, clipping it and writing it to a new GDB.
# Author: tuilbox
# Import system modules
import arcpy, os
from arcpy import env
# Set workspace
env.workspace = arcpy.GetParameterAsText(0)
arcpy.env.overwriteOutput=True
# Set local variables
fclist = arcpy.ListFeatureClasses()
clip_features = arcpy.GetParameterAsText(1)
output_directory=arcpy.GetParameterAsText(2)
xy_tolerance = ""
outgdb=os.path.join(output_directory, arcpy.GetParameterAsText(3))
if not arcpy.Exists(outgdb):
arcpy.CreateFileGDB_management(output_directory,
arcpy.GetParameterAsText(3))
# Execute Clip within for loop
for fc in fclist:
arcpy.Clip_analysis(fc, clip_features, os.path.join(outgdb, fc))
The error is: Traceback (most recent call last):
File "F:/GIS_Joseph/Lab10_Joseph/ClipGDBtoNewGDB.py", line 17, in <module>
arcpy.CreateFileGDB_management(output_directory, arcpy.GetParameterAsText(3))
File "C:\Program Files (x86)\ArcGIS\Desktop10.5\ArcPy\arcpy\management.py", line 18878, in CreateFileGDB
raise e
ExecuteError: Failed to execute. Parameters are not valid.
ERROR 000735: File GDB Location: Value is required
ERROR 000735: File GDB Name: Value is required
Failed to execute (CreateFileGDB).
Any help would be appreciated. Thank you.
With this type of question it would be helpful to let us know what parameters you are passing into your script. Have you passed a valid parameter in position 3? Use arcpy.AddMessage to double check what value you are attempting to pass to arcpy.CreateFileGDB_management.
I tried to make a Twitter bot from https://github.com/joaquinlpereyra/twitterImgBot
The installations went well and successfully but the problem came when I tried to execute it.
Below is the code for my config in the config.py.
Keys and Tokens removed with the API key replaced with random numbers because that's the problem I'm trying to address.
import os
import configparser
import tweepy
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
# read configs from file
config = configparser.ConfigParser()
config.read(dname + '/settings')
twitter_config = config['Twitter']
api_key = twitter_config['2931928391273123']
secret_key = twitter_config['REMOVED']
token = twitter_config['REMOVED']
secret_token = twitter_config['REMOVED']
The error I'm getting when executing it in cmd is:
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\Documents and Settings\Administrator>cd C:\Documents and Settings\Administrat
or\Desktop\twitterImgBot-master
C:\Documents and Settings\Administrator\Desktop\twitterImgBot- master>python twitterbot.py
Traceback (most recent call last):
File "twitterbot.py", line 3, in <module>
from settings import config
File "C:\Documents and Settings\Administrator\Desktop\twitterImgBot-master\settings\config.py", line 13, in <module>
api_key = twitter_config['2931928391273123']
File "C:\Python34\lib\configparser.py", line 1203, in __getitem__
raise KeyError(key)
KeyError: '2931928391273123'
C:\Documents and Settings\Administrator\Desktop\twitterImgBot-master>
I looked up all the questions here that has something to do with KeyError but none of them have something to do with the Twitter's API key
Again, the API key which is 2931928391273123 is just a random number to substitute the original one for obvious reasons. I did double check it to make sure I had the correct keys/tokens before resorting to here.
This is also a first for me, so I'm hoping someone can lend me a helping hand! I would have posted the 2 screenshots of the Python file and the cmd but I'm only limited to one link.
Thanks in advance!