entr | Run arbitrary commands when files | Command Line Interface library
kandi X-RAY | entr Summary
Support
Quality
Security
License
Reuse
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here
entr Key Features
entr Examples and Code Snippets
Trending Discussions on entr
Trending Discussions on entr
QUESTION
i'm trying to check if a data is already present in my database and comparing it with user input from my java application. But when i use equals
method, i have always a false return... And i would like a "true" return. I don't understand why it doesn't match... Here is my code :
public boolean getTicketWithRegVehicleNumber(String vehicleRegNumber) {
Connection con = null;
boolean valueReturn = false;
try {
con = dataBaseConfig.getConnection();
PreparedStatement ps = con.prepareStatement(DBConstants.GET_VEHICLE_REG_NUMBER);
ps.setString(1, vehicleRegNumber);
ResultSet rs = ps.executeQuery();
//TODO trouver comment tester l'egalité entre la db et la saisie user
String sqlRequestResult = DBConstants.GET_VEHICLE_REG_NUMBER;
if (sqlRequestResult.equals(vehicleRegNumber)){
valueReturn = true;
}
dataBaseConfig.closeResultSet(rs);
dataBaseConfig.closePreparedStatement(ps);
} catch (Exception ex) {
logger.error("Error fetching next available slot", ex);
} finally {
dataBaseConfig.closeConnection(con);
}
return valueReturn;
}
here is my SQL request :
public static final String GET_VEHICLE_REG_NUMBER = "select t.VEHICLE_REG_NUMBER from ticket t where t.VEHICLE_REG_NUMBER = ? ";
To sum up, i have a boolean variable : returnValue, and i want that when i use equals method on my SQL selected data (a VARCHAR type that i put in a String variable) and user's input which is a String , my boolean return true.
Thanks for helping :-)
ANSWER
Answered 2021-Jun-14 at 20:48You're comparing your plain sql query string (DBConstants.GET_VEHICLE_REG_NUMBER) to the vehicleRegNumber parameter and no wonder they don't match.
What you need to compare is the result from your ps.executeQuery();
which is assigned to ResultSet rs
.
Read the ResultSet javadoc to understand how you can extract data from it - https://docs.oracle.com/javase/8/docs/api/java/sql/ResultSet.html.
QUESTION
after search on csv
im try calculating operation in row :
import csv
import sys
import numpy as np
import pandas as pd
import operator
import matplotlib.pyplot as plt
df = pd.read_csv('data-02.csv')
Space1 = "********************"
with open('data-02.csv', 'r+') as data:
base = csv.reader(data)
ticker = input('Entre a Ticker: ')
for row in base:
if row[2] == ticker:
print(row)
if df["price"] > df["lowPrice"] and df["price"] < df["highPrice"]:
print("Wait More Range ")
elif df["price"] < df["lowPrice"]:
print("TREND DOWN Now ")
print(Space1)
else:
print("TREND UP Now ")
print(Space1)
from fist line to 15 everything is ok , but after that i want calculating inside this
row
im get this error :
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
ANSWER
Answered 2021-Jun-13 at 13:35Are you trying to iterate both on "df" and "base" rows? If so, you have to slice the "df" to get the value for the columns at the row (using iloc - https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.iloc.html - or loc - https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html). The comparissons on the if and elif conditions returns Series, not a single boolean. If you absolutely have to take this approach on having both "df" and "base", I'd sugest:
for idx,row in enumerate(base):
if row[2] == ticker:
print(row)
if df.loc[idx,"price"] > df.loc[idx,"lowPrice"] and df.loc[idx,"price"] < df.loc[idx,"highPrice"]:
print("Wait More Range ")
elif df.loc[idx,"price"] < df.loc[idx,"lowPrice"]:
print("TREND DOWN Now ")
print(Space1)
else:
print("TREND UP Now ")
print(Space1)
QUESTION
I am attempting to use the 'entr' command to automatically compile Groff documents.
I wish to run the following line:
refer references.bib $1 | groff -ms $1 -T pdf > $2
Sadly it will only compile once if I try this:
echo $1 | entr refer references.bib $1 | groff -ms $1 -T pdf > $2
I have also tried the following, but it creates an infinite loop that cant be exited with Ctrl+C:
compile(){
refer references.bib $1 | groff -ms $1 -T pdf > $2
}
while true; do
compile $1 $2
echo $1 | entr -pd -s 'kill $PPID'
done
What is the correct way of doing this?
ANSWER
Answered 2021-Jun-02 at 17:31I didn't try this because I didn't want to install entr
. But I think the following should work:
echo "$1" | entr sh -c "refer references.bib $1 | groff -ms $1 -T pdf > $2"
Note that we run the pipe refer | groff
in a shell to group it together. The command from your question without the shell runs refer
upon file change, but groff
only once. In entr ... | groff
the groff
part isn't executed by entr
, but by bash
in parallel.
This command works only if $1
and $2
do not contain special symbols like spaces, *
, or $
. The correct way to handle these arguments would be ...
echo "$1" | entr sh -c 'refer references.bib "$1" | groff -ms "$1" -T pdf > "$2"' . "$1" "$2"
QUESTION
I use the following example code to initialize vector of shared_ptr:
#include
#include
#include
#include
struct Song
{
std::wstring artist;
std::wstring title;
Song(const std::wstring& artist_, const std::wstring& title_) :
artist{ artist_ }, title{ title_ } {}
};
using namespace std;
int main()
{
vector> v {
make_shared(L"Bob Dylan", L"The Times They Are A Changing"),
make_shared(L"Aretha Franklin", L"Bridge Over Troubled Water"),
make_shared(L"Thalía", L"Entre El Mar y Una Estrella")
};
// how to initialize these following shared_ptr chains?
vector>> long_Song;
shared_ptr>>>> ptr_long_Song;
return 0;
}
But for chained shared_ptr (is this right name?), how to initialize them, like the last two declarations?
ANSWER
Answered 2021-Jun-02 at 16:36You can use a nested type to initalize a type which is nested one level deeper like that
vector> v {
make_shared(L"Bob Dylan", L"The Times They Are A Changing"),
make_shared(L"Aretha Franklin", L"Bridge Over Troubled Water"),
make_shared(L"Thalía", L"Entre El Mar y Una Estrella")};
using songs = decltype(v);
vector>>> long_Song {std::make_shared(v)};
using long_songs = decltype(long_Song);
shared_ptr>>>> ptr_long_Song { std::make_shared(long_Song)};
QUESTION
I have to make a program that will allow the user to save people's personal information like their last names, first names, genders, heights and so on... I am not allowed to use dictionaries so no use in recommending it.
I don't know how to add the suffix "cm" when I print the person's height. Here is my code that request height input:
starting line 68
taille = input("Entrez la taille de la personne en cm (0 à 250) :\n").strip()
isTailleValid = validation_taille(taille)
while not isTailleValid:
taille = input("Taille invalide, entrez bien une valeur entre 0 et 250 :\n").strip()
isTailleValid = validation_taille(taille)
taille = float(taille)
personInf[Personne_taille] = taille
This is where the program request information about the height (french: taille) after that it adds that input to a list called Liste_info under the Personne_taille index by doing:
Liste_info.append(personInf)
now when I call the function to print out the result it shows up like this:
Is there any way to add " cm" at the end of 175?
ANSWER
Answered 2021-May-29 at 08:57while not isTailleValid:
taille = input("Taille invalide, entrez bien une valeur entre 0 et 250 :\n").strip()
isTailleValid = validation_taille(taille)
personInf[Personne_taille] = taille + "cm"
QUESTION
@bot.command()
@commands.has_permissions(manage_messages=True)
async def clear(ctx,member : discord.Member,amount=200):
await ctx.channel.purge(limit=amount)
if amount > 200:
await ctx.send(f"{member.mention}merci de clear entre 0-200 message(s)")
else:
await ctx.send(f"j'ai clear {amount} message(s)",delete_after=5)```
error:
File "C:\Users\dzzdz\PycharmProjects\pythonProject12\venv\lib\site-packages\discord\ext\commands\core.py", line 451, in _actual_conversion
ret = await instance.convert(ctx, argument)
File "C:\Users\dzdz\PycharmProjects\pythonProject12\venv\lib\site-packages\discord\ext\commands\converter.py", line 195, in convert
raise MemberNotFound(argument) discord.ext.commands.errors.MemberNotFound: Member "300" not found.
In this error, we can see that the command works only if I do !clear @ (amount).
If I remove the discord.member it's working. I can't remove the discord.member because one can't have an optional argument that comes before a default argument.
So what can I do?
ANSWER
Answered 2021-May-26 at 20:16Here are some errors that I noticed:
First) Since you are looking for the author of the message, member
is not relevant here at all. We can simply use ctx.author
for this and then display it as desired.
Second) You have a logic error in your code. Your if amount >200
statement is not considered the way your code is and then more than 200 messages can be deleted without the error message showing up.
One possible code would be:
@client.command() / @bot.command() / @commands.command() # Depends on what you use
@commands.has_permissions(manage_messages=True)
async def clear(ctx, amount=200):
if amount > 200:
await ctx.send(f"{ctx.author.mention} merci de clear entre 0-200 message(s)")
return # Do not proceed
else:
await ctx.send(f"j'ai clear {amount} message(s)", delete_after=5)
await ctx.channel.purge(limit=amount) # Clear messages if lower than 200
QUESTION
guys. Help me, please. I've got a problem with calculator in tkinter.
Error: AttributeError: '_tkinter.tkapp' object has no attribute 'insert'.
from tkinter import *
root = Tk()
root.title("Calculator")
root.geometry("400x480")
root.configure(bg = 'gray')
#commands for buttons
def add_digit(digit):
root.insert(0, digit)
#buttons
b7 = Button(root, text = '7', bd = 5, command = lambda : add_digit(7)).grid(row = 1, column = 0, stick = 'wens', padx = 5, pady = 5)
b8 = Button(root, text = '8', bd = 5, command = lambda : add_digit(8)).grid(row = 1, column = 1, stick = 'wens', padx = 5, pady = 5)
b9 = Button(root, text = '9', bd = 5, command = lambda : add_digit(9)).grid(row = 1, column = 2, stick = 'wens', padx = 5, pady = 5)
b4 = Button(root, text = '4', bd = 5, command = lambda : add_digit(4)).grid(row = 2, column = 0, stick = 'wens', padx = 5, pady = 5)
b5 = Button(root, text = '5', bd = 5, command = lambda : add_digit(5)).grid(row = 2, column = 1, stick = 'wens', padx = 5, pady = 5)
b6 = Button(root, text = '6', bd = 5, command = lambda : add_digit(6)).grid(row = 2, column = 2, stick = 'wens', padx = 5, pady = 5)
b1 = Button(root, text = '1', bd = 5, command = lambda : add_digit(1)).grid(row = 3, column = 0, stick = 'wens', padx = 5, pady = 5)
b2 = Button(root, text = '2', bd = 5, command = lambda : add_digit(2)).grid(row = 3, column = 1, stick = 'wens', padx = 5, pady = 5)
b3 = Button(root, text = '3', bd = 5, command = lambda : add_digit(3)).grid(row = 3, column = 2, stick = 'wens', padx = 5, pady = 5)
b0 = Button(root, text = '0', bd = 5, command = lambda : add_digit(0)).grid(row = 4, column = 1, stick = 'wens', padx = 5, pady = 5)
#entry
entr = Entry(root, bd = 4).grid(row = 0, column = 0, columnspan = 3)
root.mainloop()
ANSWER
Answered 2021-May-26 at 16:23You cannot 'insert' text into a Window. A Label is used for text on a window. Why do you want to add numbers to the root window when you have a text widget? Also, update your function:
def add_digit(digit):
entr.insert(END, digit) #=== Insert into text widget
Also, the code which has your entry should be:
entr = Entry(root, bd = 4)
entr.grid(row = 0, column = 0, columnspan = 3)
QUESTION
I am new to coding. Is it possible to use wildcard for renaming a file in a directory?
example there are two files in a folder:
asdxyd01.pdf
cdc1pxych001.pdf
want to rename the file by removing the all characters before "xy".
i am using the following code which is working great for removing the specific words only.
# Function to replace words in files names in a folder
import os
def main():
i = 0
# Ask user where the PDFs are
path = input('Folder path to PDFs: ')
# Sets the scripts working directory to the location of the PDFs
os.chdir(path)
filetype = input('entre file extention here: ')
rep = input('entre word to remove from file name: ')
for filename in os.listdir(path):
my_dest = filename.replace(rep, "") +"."+filetype
my_source = filename
my_dest = my_dest
# rename() function will
# rename all the files
os.rename(my_source, my_dest)
i += 1
# Driver Code
if __name__ == '__main__':
# Calling main() function
main()
ANSWER
Answered 2021-May-26 at 12:30Judging by your question, I assume that you want your files to be renamed as: xyd01.pdf, ch001.pdf. Firstly, let's look at your mistake:
my_dest = filename.replace(rep, "") +"."+filetype
Here by replacing 'rep' with '' you are basically deleting the pattern from name, not the characters before it. So, to achieve your goal you need to find the occurrence of your matching pattern and replace the substring before it. You can do this by:
index=filename.find(rep)
prefix=filename[:index]
my_dest = filename.replace(prefix, "")
Look, that I haven't added "."+filetype
at the end of destination either, cause it will make the replace file look like this: xyd01.pdf.pdf.
Now you should keep some more things in consideration while running this code. If you do not put any checking at the very beginning of for loop, your program will rename any file name having the same pattern, so add this below condition also:
if filetype not in filename:
continue
Finally another checking is important to prevent invalid array index while slicing the file name:
index=filename.find(rep)
if index<=0:
continue
Overall looks like this:
for filename in os.listdir(path):
if filetype not in filename:
continue
index=filename.find(rep)
if index<=0:
continue
prefix=filename[:index]
my_dest = filename.replace(prefix, "")
my_source = filename
os.rename(my_source, my_dest)
i += 1 # this increment isn't necessary
QUESTION
I am trying to execute a code using the gfortran compiler. In order to compile, I use :
gfortran -O3 hecese_seq.f90
In order to execute, I use :
./a.out
The code is below:
compteur_tempo=0
do while (.not.fin)
compteur_tempo=compteur_tempo+1
duree = duree+dt
do pas=1,2
tab0(:,:) =tab(:,:)
!----------- CE/SE
if(pas.eq.1)then
do i=1,cpt,2
flux(i)= tab0(i,3)*grad_x_u(i)
sm(i)= dt/(dx)*flux(i) + dt**2/(4.0d0*dx)*grad_t_f(i) + dx/4.0*grad_x_u(i)
enddo
do i=2,cpt-1,2
tab(i,2)= 0.5d0*( tab0(i+1,2)+tab0(i-1,2)+sm(i-1)-sm(i+1)) !-------Coord paires
enddo
else
do i=2,cpt,2
flux(i)= tab0(i,3)*grad_x_u(i)
sm(i)= dt/(dx)*flux(i) + dt**2/(4.0d0*dx)*grad_t_f(i) + dx/4.0*grad_x_u(i)
enddo
do i=3,cpt-1,2
tab(i,2)= 0.5d0*( tab0(i+1,2)+tab0(i-1,2)+sm(i-1)-sm(i+1)) !-------Coord impaires
enddo
endif
!-------------- Traitement des interfaces - continuité du flux par la conductivité thermique
do j=2,nb_element
i = p_element(j)
tab(i,2)=(tab(i-1,7)*tab(i-1,2)+tab(i+1,7)*tab(i+1,2))/(tab(i-1,7)+tab(i+1,7))
enddo
!-------------- Conditions cyclique sur la température
tab(1,2)= 0.5d0*( tab0(2,2)+tab0(cpt-1,2)+sm(cpt-1)-sm(2))!2*dt/dx*(flux(1))-sm(2)-sm(1)+tab(2,2)!tab(2,2)!2000/T_ref!
tab(cpt,2)=tab(1,2)!(-2*dt/dx)*flux(cpt)+sm(cpt-1)+sm(cpt)+tabi(cpt-1,2)!2000/T_ref!
goto 113
!---------------Resolution par Newton raphson - Actuellement inutilisé, je le laisse au cas où
error=0.0d0
test1=.true.
itermax =10
rhs(:)=tab(:,2)
iter =0
eps=1.0d-10
DeltaT=1.0d-10
sh(:)=0
f1(:)=0
f2(:)=0
delt(:)=0
do while((test1).and.(iter.le.itermax))
iter = iter+1
Call GRAD
do j=pas+1,cpt-1,2
sh(j)=tab(j,7)*tab(j,8)*grad_x_u(j)
fluxnr(j) = -(tab(j,2)+(dt/2)*sh(j)-rhs(j))
Delt(j)=fluxnr(j)
tab(j,2) =tab(j,2)+delt(j)
enddo
error=0.0d0
do j=2,cpt-1!,2!1,nb_element!
error = max(error, abs(delt(j)))
enddo
if(iter.eq.itermax)then
write(6,*)'itermax'
endif
test1=abs(error).ge.eps!.or.dabs(error).eq.0.0d0
enddo
!---------------Resolution des gradients
113 continue
CALL GRAD
do i=pas+1,cpt-1,2
grad_x_f(i)= tab(i,3)*(tab(i+1,2)-2.0*tab(i,2)+tab(i-1,2))/(dx**2)!(Différence centrée deuxième ordre (dérivée seconde de la Temp)
grad_t_u(i) = -grad_x_f(i)+tab(i,7)*grad_x_u(i)*tab(i,8)/2!(Terme source ajouté ici seulement - Légère influence sur les interfaces)
grad_t_f(i) = grad_x_f(i)*tab(i,3)/(cfl*dx)!(Terme en dx/dt remplacé par tab(i,3)/(cfl*dx))
enddo
!------ Conditions cyclique - Gradients
grad_x_f(cpt)=grad_x_f(cpt-1)
grad_x_f(1)=grad_x_f(cpt)
grad_t_u(cpt)=grad_t_u(cpt-1)
grad_t_u(1)=grad_t_u(cpt)
grad_t_f(cpt)=grad_t_f(cpt-1)
grad_t_f(1)=grad_t_f(cpt)
!------ Gradients moyennés sur l'interface (histoire de limiter les discontinuités)
do j=2,nb_element
i = p_element(j)
grad_x_f(i)=(grad_x_f(i+1)+grad_x_f(i-1))/2
grad_t_u(i)=(grad_t_u(i+1)+grad_t_u(i-1))/2
grad_t_f(i)=(grad_t_f(i+1)+grad_t_f(i-1))/2
enddo
enddo
!-------------- Test de la fonte de l'electrolite
test = .false.
i_ca_el = p_element(num)
i_el_an = p_element(num+1)
i=i_ca_el
do while(((i.lt.i_el_an-1).and.(.not.test)))
test=tab(i,2).le.(T_fonte)!20000)! Choix entre température d'équilibre ou température de fonte
i = i+1
enddo
if(i.ge.i_el_an-1)convergence =.true.
if(convergence) then
write(6,*)'Convergence',i, i_ca_el,i_el_an-1, duree*time_ref
else
write(6,'(''Non Convergence'', 3i5,3f18.12)'),i, i_ca_el,i_el_an-1,tab(i,2)*t_ref,duree*time_ref
endif
if(.not.stock)then
if( convergence.and.(duree.lt.duree_totale))then
open(10,file='test'//char(ww+48)//'.dat', status='unknown')
do i=1,cpt
write(10,*)tab(i,1)*l_ref,tab(i,2)*t_ref
enddo
close(10)
stock=.true.
stop
endif
endif
fin=duree.ge.duree_totale
pas_stockage = pas_stockage+dt
if(pas_stockage.ge.intervalle_stockage)then
do i=1,nb_probe
write(w_output(i),*)duree*time_ref, tab(probe_indice(i),2)*t_ref
enddo
pas_stockage =0.0d0
endif
enddo
!execution time
CALL CPU_TIME(TIME_END)
call system_clock(count=t2, count_rate=ir)
write(*,*)" duree = ",duree,duree*time_ref
write(*,*)"compteur temporel ",compteur_tempo
write(*,*)"cpt ",cpt
write(*,*)" temps d’excecution du programme",TIME_END-TIME_START
temps=real(t2 - t1 ,kind =8)/real(ir,kind =8)
write (*,*) "temps d’exe du programme:",temps
do i=1,nb_probe
close(w_output(i))
enddo
For the part testing the convergence, it's okay but I don't get the execution time as I wanted to display it. I feel that the last part doesn't get executed. (maybe due to the "Stop" used for testing the convergence).
For the execution, I get:
Non Convergence 222 184 303 699.993372185986 0.340103428568
Non Convergence 222 184 303 699.993948217854 0.340103999997
Non Convergence 222 184 303 699.994524248306 0.340104571426
Non Convergence 222 184 303 699.995100277341 0.340105142854
Non Convergence 222 184 303 699.995676304960 0.340105714283
Non Convergence 222 184 303 699.996252331162 0.340106285711
Non Convergence 222 184 303 699.996828355948 0.340106857140
Non Convergence 222 184 303 699.997404379318 0.340107428568
Non Convergence 222 184 303 699.997980401271 0.340107999997
Non Convergence 222 184 303 699.998556421807 0.340108571426
Non Convergence 222 184 303 699.999132440928 0.340109142854
Non Convergence 222 184 303 699.999708458632 0.340109714283
Non Convergence 222 184 303 700.000284474919 0.340110285711
Non Convergence 222 184 303 700.000860489791 0.340110857140
Non Convergence 222 184 303 700.001436503245 0.340111428568
Non Convergence 222 184 303 700.002012515283 0.340111999997
Non Convergence 222 184 303 700.002588525905 0.340112571426
Non Convergence 222 184 303 700.003164535111 0.340113142854
Non Convergence 222 184 303 700.003740542900 0.340113714283
Non Convergence 222 184 303 700.004316549273 0.340114285711
Non Convergence 222 184 303 700.004892554230 0.340114857140
Non Convergence 222 184 303 700.005468557770 0.340115428568
Non Convergence 222 184 303 700.006044559894 0.340115999997
Non Convergence 222 184 303 700.006620560601 0.340116571426
Non Convergence 222 184 303 700.007196559892 0.340117142854
Convergence 303 184 303 0.34011771428275706
Note: The following floating-point exceptions are signalling: IEEE_UNDERFLOW_FLAG IEEE_DENORMAL
I showed you a small part of the execution (there are a lot of values so no need to show them all).
My problem is that I can't display the execution time while it has been already implemented. I'm new on this website so I hope you can help me.
ANSWER
Answered 2021-May-26 at 09:50Your structure basically is
do
!do something
if (convergence) STOP
end do
That means that at convergence the program stops completely and you never get past the loop.
To be able to continue execution after the loop you want to just exit the loop.
do
!do something
if (convergence) EXIT
end do
!further statements
QUESTION
i'm new at dart. I don't know what kind of mistake i have made, but this code didn't work. Is a simple code, just read the age in terminal and say it's underage or over 18.
import 'dart:io';
main(){
print("Entre com a sua idade: ");
var input = stdin.readLineSync();
var idade = int.parse(input);
if(idade >= 18){
print("É maior de idade");
}else{
print("É menor de idade");
}
}
And i get this error:
algoritmo01.dart:15:25: Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't. var idade = int.parse(input);
ANSWER
Answered 2021-Mar-18 at 18:23Welcome to Dart. What you are experience is the new null-safety feature (introduced with Dart 2.12.0) where variables by default cannot contain the value null. This is statically checked so you will get an error even before your program are executed.
In your example the problem is the following line:
var input = stdin.readLineSync();
If we check the manual we can see this method have the following signature:
String? readLineSync (
{Encoding encoding = systemEncoding,
bool retainNewlines = false}
)
https://api.dart.dev/stable/2.12.2/dart-io/Stdin/readLineSync.html
String?
means it is a nullable type and is therefore allowed to contain any String or null. If the type instead was String
it would mean the result can only be a String
and never null
.
This means that your variable input
now has the type String?
. This i(introduced with 2.12.0)s a problem if you take a look at the second line of your example:
var idade = int.parse(input);
Since the signature of int.parse
is:
int parse (
String source,
{int? radix,
@deprecated int onError(
String source
)}
)
https://api.dart.dev/stable/2.12.2/dart-core/int/parse.html
Which takes a String
(which can therefore never be null
). You are therefore not allowed to give your String?
as parameter to a method which only handles String
. The opposite would have been allowed (if method takes String?
and you give it a String
).
So what can we do about this situation? Well, you need to handle the case of null
or tell Dart that it should just crash your program if input
are null
.
So you could handle it like:
import 'dart:io';
void main() {
print("Entre com a sua idade: ");
var input = stdin.readLineSync();
if (input != null) {
var idade = int.parse(input);
if (idade >= 18) {
print("É maior de idade");
} else {
print("É menor de idade");
}
} else {
print('Input was null!');
}
}
As you can see, this is allowed even if input
are technically still of the type String?
. But Dart can see that your if
statement will prevent input
to have the value null
so it will be "promoted" to String
as long as you are inside this if-statement.
Another solution is to tell Dart that it should stop complain about statically errors about input
and just assume input
is String
when compiling the code:
import 'dart:io';
void main() {
print("Entre com a sua idade: ");
var input = stdin.readLineSync()!;
var idade = int.parse(input);
if (idade >= 18) {
print("É maior de idade");
} else {
print("É menor de idade");
}
}
(The change is the !
added after readLineSync()
)
Dart will in this case instead add its own null
-check and crash the program if stdin.readLineSync
does give a null
value. This is to ensure that we are still never going to give int.parse
a null value which could make your code crash somewhere else. By adding the null
-check where we get the questionable value, we can ensure we fails fast and at the place where things was not as we expected it to be.
You can read a lot more about null-safety in Dart here (also linked to by Stephen): https://dart.dev/null-safety/understanding-null-safety
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install entr
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page