I have a query where user can have 3 option value where they can either just choose one on each option or 2 of either option of even 3 of the option. However, when creating the if else statement in the controller, the if else comes up until 7 statements. Any ideas how to reduce the if else statement.
each if else statement gives different input inside,
as an example
if (1 !="" && 2 =="" && 3==""){
}elseif(1 =="" && 2 !="" && 3==""){
}elseif(1 =="" && 2 =="" && 3!=""){
}elseif(1 !="" && 2 !="" && 3 ==""){
}elseif(1 !="" && 2 =="" && 3 !=""){
}elseif(1 =="" && 2 !="" && 3 !=""){
}elseif(1 !="" && 2 !="" && 3 !=""){
}else{}
You can use nested if statements instead of this , I think it may help you on this scenario
if(1 !=""){
if(2 != ""){
if(3 != ""){
// all statements are true
}else {
// 1 & 2 statements are true
}
}else {
// only 1 is true
}
}else {
// all statements is false
}
OR you can do also
if (1 != "") {
if (2 != "") {
if (3 != "") {
// all statements are true
}
}
} else {
// all statements is false
}
you can use this. This is not small but it is easy to understand
if (!empty(1) && empty(2) && empty(3)){
return '1';
}
if(empty(1) && !empty(2) && empty(3)){
return '2';
}
if(empty(1) && empty(2) && !empty(3)){
return '3';
}
if(!empty(1) && !empty(2) && empty(3)){
return '1 & 2';
}
if(!empty(1) && empty(2) && !empty(3)){
return '1 & 3';
}
if(empty(1) && !empty(2) && !empty(3)){
return '2 & 3';
}
if(!empty(1) && !empty(2) && !empty(3)){
return 'all empty';
}
here i used return early patten to simplify
Related
i am using tput sc/rc/ed and printf '\E[n<A|B|C|D>'|printf '\E[y;xH',here two ex:
tty_esc(){ printf "\e[%s" "$1"; }
tty_cursor_locate(){ tty_esc "${2};${1}H"; }
tty_cursor_right(){ tty_esc ${1}C; }
print_center()
{
local _width=$(tput cols)
local _str=$1
local _row=$2
local _cols=$((((${_width} - ${#_str})) / 2))
tty_cursor_locate ${_cols:-100} ${_row:-1}
printf "%s\n" " ${_str} "
}
show_net_adapter()
{
local _addr _iface _count
local _origin=$1
iface_line_count=
tty_cursor_locate ${_origin:-0} 4
printf "%s\n" "Current connected adapter(s):"
for _iface in $(get_net_adapter);do
if [[ "${_iface}" != "lo" ]];then
_addr=$(get_net_addr ${_iface})
test -z "${_addr}" && continue
let _count+=1
let iface_line_count+=1
if [[ ${_count} != 1 ]];then
unset _count
printf '%s' "${tty_rever}"
fi
tty_cursor_right ${_origin:-0}
print_fill 50 ${_iface} ${_addr:--}
printf "${tty_reset}"
fi
done
print_line -s "=" ${line_origin}
}
as above, I should locate the cursor before I print something.
BTW
I use trap "myfunc" WINCH, it only works once. when I try again to change my crt. size, it doesn't work.
Not really sure what you mean by in default position always, either intentations or overwrite the text but the following function can do both.
#!/bin/sh
preent () { # $1=indent start line, $2=spaces, $3=reset cursor, $4=update (1=itself, 2=delete previous lines, 0=newline), $5=save cursor, $6=text
if text="$6""$7""$8""$9""${10}" awk -v col="$COLUMNS" -v cp="$_CURSOR_POS" -v id="$1" -v spc="$2" -v rc="$3" -v u="$4" -v sc="$5" '
BEGIN { t=ENVIRON["text"]; lt=sprintf("%d",col/4); idx=1; len=length(t); y=0; sp=sprintf("% " spc "s",""); delete A;
for(ln=1;idx<len;ln++) { if(ln==id) { col=col-spc; y=1 } bd=col-lt; f=0
for(i=idx+col-1;i>bd;i--) { c=substr(t,i,1);
if(c==" ") {
if(y) { A[ln]=sprintf("%s%s",sp,substr(t,idx,i-idx)); idx=i+1; f=1; break
} else { A[ln]=substr(t,idx,i-idx); idx=i+1; f=1; break }
} else if(c=="") {
if(y) { A[ln]=sprintf("%s%s",sp,substr(t,idx,i-idx)); idx=i; f=1; break
} else { A[ln]=substr(t,idx,i-idx); idx=i; f=1; break; }
}
}
if(!f) {
if(y) { A[ln]=sprintf("%s%s",sp,substr(t,idx,col)); idx=idx+col
} else { A[ln]=substr(t,idx,col); idx=idx+col }
}
} if(rc=="true") cp=0;
if(u=="1") { for(i=1;i<ln;i++) printf("\x1B[1A\x1B[K"); cp=cp+1-i
} else if(u=="2") { for(i=0;i<cp;i++) printf("\x1B[1A\x1B[K"); cp=0 }
for(i=1;i<ln;i++) printf("%s\n",A[i]);
if(sc=="true") { exit ln-1+cp } else { exit 0 }
}'; then _CURSOR_POS="$?"; else _CURSOR_POS="$?"; fi
}
Example 1 (Long text, 5 spaces indent, indent starts from 2nd line)
preent 2 5 'false' 0 'false' 'You never say good-bye Handong-an monghani udukoni anja Dashi saenggakhatjiman ' \
'Momchul sun optkesso Ontong kudae saenggak hal subakke omnun ' \
"Nae jashini miwo Don't you let me go Baby don't you let me down"
Output
You never say good-bye Handong-an monghani
udukoni anja Dashi saenggakhatjiman Momchul
sun optkesso Ontong kudae saenggak hal
subakke omnun Nae jashini miwo Don't you
let me go Baby don't you let me down
Example 2 (Long text with no spaces)
preent 2 5 'false' 0 'false' 'Youneversaygood-byeHandong-anmonghaniudukonianjaDashisaenggakhatjiman' \
'MomchulsunoptkessoOntongkudaesaenggakhalsubakkeomnun' \
"NaejashinimiwoDon'tyouletmegoBabydon'tyouletmedown"
Output
Youneversaygood-byeHandong-anmonghaniudukonianjaD
ashisaenggakhatjimanMomchulsunoptkessoOntong
kudaesaenggakhalsubakkeomnunNaejashinimiwoDo
n'tyouletmegoBabydon'tyouletmedown
In bash, I often did things like:
[ -z "${someEnvVar}" ] && someEnvVar="default value"
Instead of creating a full-fledge if statement:
if [ -z "${someEnvVar}" ]; then someEnvVar="default value"; fi
Is there a similar shorthand in PowerShell without creating a function or alias?
I'd rather not write the following in PowerShell:
if ("${someVar}" -eq "") {
$someVar = "default value"
}
If seems more readable to me, but you can use short circuit of OR (similar to BASH version):
$someVar = ""
[void]($someVar -ne "" -or ($someVar = "Default"))
$someVar #yields "Default"
$someVar = "Custom"
[void]($someVar -ne "" -or ($someVar = "Default"))
$someVar #yields "Custom"
I am afraid Powershell doesnt have such an elegant solution as C# have:
Exp1 ? Exp2: Exp3
msg = (age >= 18) ? "Welcome" : "Sorry";
But you could do something like this:
$someVar = if ("${someVar}" -eq "") { "default value" }
Here are some options:
$emptystring = ""
if ($emptystring -eq "") {
"The string was empty"
}
if (!$emptystring) {
"The string was null or empty"
}
if (!$someVar) {
"The value was null or unassigned"
}
if ([string]::IsNullOrEmpty($emptystring)) {
"The value was null or empty"
}
This produces the following output:
The string was empty
The string was null or empty
The value was null or unassigned
The value was null or empty
Since PowerShell 7, you can use C#-like If ? Then : Else syntax:
$Variable = -not $Variable ? $Default : $Variable
For pipes, you can now use bash-like || and &&:
(Get-Value && Use-Value) || Set-Value $Default
or
(Get-Value && Use-Value) || (& {Set-Value $Default; Get-Value} | Use-Value)
where & executes a script block (I don't know of a way to chain two commands in a pipe without passing values between them)
My code seems to not be working because I'm mishandling a hash...
There's two sections in my code where I reference the hash, and two distinct syntax errors that I haven't resolved through googling.
First Section Syntax Error & Code:
"syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('"
def showBoard
puts " 1 2 3"
puts " A #{#spaces["A1"]} | #{#spaces["A2"]} | #{#spaces["A3"]}"
puts ---------------------------
puts " B #{#spaces["B1"]} | #{#spaces["B2"]} | #{#spaces["B3"]}"
puts ---------------------------
puts " C #{#spaces["C1"]} | #{#spaces["C2"]} | #{#spaces["C3"]}"
puts ---------------------------
end
Second Section Syntax Error & Code:
"syntax error, unexpected =>, expecting keyword_end"
def checkGame?
if
"A1"=>"X" && "A2"=>"X" && "A3"=>"X" ||
"B1"=>"X" && "B2"=>"X" && "B3"=>"X" ||
"C1"=>"X" && "C2"=>"X" && "C3"=>"X" ||
"A1"=>"X" && "B1"=>"X" && "C1"=>"X" ||
"A2"=>"X" && "B2"=>"X" && "C2"=>"X" ||
"A3"=>"X" && "B3"=>"X" && "C3"=>"X" ||
"A1"=>"X" && "B2"=>"X" && "C3"=>"X" ||
"A3"=>"X" && "B2"=>"X" && "C1"=>"X"
puts player1 + " wins!"
checkGame == true
elsif
"A1"=>"O" && "A2"=>"O" && "A3"=>"O" ||
"B1"=>"O" && "B2"=>"O" && "B3"=>"O" ||
"C1"=>"O" && "C2"=>"O" && "C3"=>"O" ||
"A1"=>"O" && "B1"=>"O" && "C1"=>"O" ||
"A2"=>"O" && "B2"=>"O" && "C2"=>"O" ||
"A3"=>"O" && "B3"=>"O" && "C3"=>"O" ||
"A1"=>"O" && "B2"=>"O" && "C3"=>"O" ||
"A3"=>"O" && "B2"=>"O" && "C1"=>"O"
puts player2 + " wins!"
return true
checkGame == true
elsif
"A1"!=" " && "A2"!=" " && "A3"!= " " &&
"B1"!=" " && "B2"!=" " && "B3"!= " " &&
"C1"!=" " && "C2"!=" " && "C3"!= " "
puts "It's a draw. :/ "
checkGame == true
end
return false
end
What's going wrong?
The problem with the first section is
puts -------
You probably meant to enclose the dashes in quotes, to make it a string.
The => (hashrocket) operator is only used when declaring a new hash (for example {"a" => 1}) but your second bit of code is using it outside of that context ( I'm not sure what you were trying to do so can't really suggest anything). There's a few other things that don't make sense too - you're comparing string literals at the bottom , and I suspect that the precedent of || and && won't do what you want, whatever that is
I am writing a simple java and bash program, but it is not working. Let me know where is wrong.
Bash:
for i in [1..100]; do
echo $i
java prob2 $i
done
Java:
import java.io.*;
public class prob2
{
public static void main( String[] args )
{
int l = args.length;
if ( l == 1 )
{
int num = Integer.parseInt(args[0]);
while ( num != 0 && num != 1)
num = num - 2;
if ( num == 0 )
System.out.println("Even");
else if ( num == 1 )
System.out.println("Odd");
}
}
}
The error I'm getting is:
Exception in thread "main" java.lang.NumberFormatException: For input string: "[1..100]" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:492) at java.lang.Integer.parseInt(Integer.java:527) at prob2.main(prob2.java:10)
That's not how you would do a bash loop. Try this:
for i in `seq 1 100`; do
echo $i
java prob2 $i
done
As an aside, a faster algorithm for determining if a number is odd or even is to take it modulo 2:
if (num % 2 == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
You have to use curly braces, not array brackets:
for i in {1..100}; do
echo $i
java prob2 $i
done
I've just installed DEBIAN today and installed XXXXX application.
This application create ~/.XXXXX/ folder configuration.
I find that the ~/.XXXXX folder is owned by root. Applying any change for instance, then closing and reopening XXXXX, should reflect the applied change.
However, any channel or setting change is forgotten immediately.
A simple chown command solves all.
I was a little confused to start with when I couldn't save my settings... but a little digging shows the problem. It's a little annoying, and the only additional application I've installed so far which behaves this way, which kinda singles it out.
Because this application not have maintainer, I want to resolve this problem for another users.
I beleve that the proble is in debian/postinst file:
set -e
setuid () {
db_get XXXXX/setuid
if [ -x /usr/bin/XXXXX ] && [ "$RET" = "false" ] ; then
if [ ! -x /usr/sbin/dpkg-statoverride ] ||\
! /usr/sbin/dpkg-statoverride --list /usr/bin/XXXXX >/dev/null; then
chown root:root /usr/bin/XXXXX
chmod u=rwx,go=rx /usr/bin/XXXXX
fi
else
if [ ! -x /usr/sbin/dpkg-statoverride ] || \
! /usr/sbin/dpkg-statoverride --list /usr/bin/XXXXX >/dev/null; then
chown root:root /usr/bin/XXXXX
chmod u=rwxs,go=rx /usr/bin/XXXXX
fi
fi
}
# Parse the option requested from XXXXX-configure
get_option () {
OPTION=`XXXXX-configure --$1 2>/dev/null | awk -F: '{ print \$2 }'`
}
suck_XXXXX_xml () {
# If XXXXX-configure was not there at Debconf, but
# /etc/XXXXX/XXXXX.xml was, then we presume that the
# administrator knew what he was doing. We will therefore suck
# this information into the Debconf database now that
# XXXXX-configure is installed.
if [ -f /etc/XXXXX/debconf.XXXXX.xml ]; then
get_option norm
db_set XXXXX/norm "$OPTION"
get_option frequencies
db_set XXXXX/frequencies-ntsc "$OPTION"
db_set XXXXX/frequencies-jp "$OPTION"
db_set XXXXX/frequencies-pal "$OPTION"
get_option device
db_set XXXXX/v4ldevice "$OPTION"
get_option vbidevice
db_set XXXXX/vbidevice "$OPTION"
get_option priority
db_set XXXXX/processpriority "$OPTION"
fi
}
### MAIN POSTINST ###
case "$1" in
configure)
# Load Debconf library
. /usr/share/debconf/confmodule
# Handle the setuid bit.
setuid
# Load /etc/XXXXX/XXXXX.xml into Debconf, if necessary
suck_XXXXX_xml
# Try to set the /var/run/XXXXX directory to video group
if [ -d /var/run/XXXXX ] ; then
if [ ! -x /usr/sbin/dpkg-statoverride ] || \
! /usr/sbin/dpkg-statoverride --list /var/run/XXXXX >/dev/null; then
chmod ug=rwx,o=rxt /var/run/XXXXX
chown root:video /var/run/XXXXX
fi
fi
CONFIGFILE=/etc/XXXXX/XXXXX.xml
db_get XXXXX/norm
NORM=$RET
case "$NORM" in
NTSC|PAL-M|PAL-Nc)
db_get XXXXX/frequencies-ntsc
case "$RET" in
Cable) FREQTABLE=us-cable ;;
Broadcast) FREQTABLE=us-broadcast ;;
*) FREQTABLE=us-cable100 ;;
esac
;;
NTSC-JP)
db_get XXXXX/frequencies-jp
case "$RET" in
Cable) FREQTABLE=japan-cable ;;
*) FREQTABLE=japan-broadcast ;;
esac
;;
PAL|PAL-60|PAL-N|SECAM)
db_get XXXXX/frequencies-pal
case "$RET" in
Europe) FREQTABLE=europe ;;
France) FREQTABLE=france ;;
Russia) FREQTABLE=russia ;;
Australia) FREQTABLE=australia ;;
"New Zealand") FREQTABLE=newzealand ;;
"China Broadcast") FREQTABLE=china-broadcast ;;
"Australia Optus cable") FREQTABLE=australia-optus ;;
*) FREQTABLE=custom ;;
esac
;;
*)
FREQTABLE=custom
;;
esac
db_get XXXXX/v4ldevice
V4LDEV=$RET
db_get XXXXX/vbidevice
VBIDEV=$RET
db_get XXXXX/processpriority
PRI=$RET
db_stop
# Create the configuration file if it doesn't exist
if [ ! -f $CONFIGFILE ]; then
cp /usr/share/doc/XXXXX/examples/default.XXXXX.xml $CONFIGFILE
fi
# Configure XXXXX.
XXXXX-configure --configfile="$CONFIGFILE" --norm="$NORM" \
--frequencies="$FREQTABLE" --device="$V4LDEV" \
--vbidevice="$VBIDEV" --priority="$PRI" 2>/dev/null
;;
abort-upgrade|abort-remove|abort-deconfigure)
;;
*)
echo "postinst called with unknown argument \`$1'" >&2
exit 1
;;
esac
Any help is welcome,
Regards.
From app code
int mkdir_and_force_owner( const char *path, uid_t uid, gid_t gid )
{
if( mkdir( path, S_IRWXU ) < 0 ) {
if( errno != EEXIST ) {
lfprintf( stderr, _("Cannot create %s: %s\n"),
path, strerror( errno ) );
} else {
/* It exists, make sure it's a directory. */
DIR *temp_dir = opendir( path );
if( !path ) {
lfprintf( stderr, _("Cannot open %s: %s\n"),
path, strerror( errno ) );
} else {
closedir( temp_dir );
return 1;
}
}
} else {
/* We created the directory, now force it to be owned by the user. */
if( chown( path, uid, gid ) < 0 ) {
lfprintf( stderr, _("Cannot change owner of %s: %s.\n"),
path, strerror( errno ) );
} else {
return 1;
}
}
return 0;
}
ct->uid = getuid();
/* Make the ~/.XXXXX directory every time on startup, to be safe. */
if( asprintf( &temp_dirname, "%s/.XXXXX", getenv( "HOME" ) ) < 0 ) {
/* FIXME: Clean up ?? */
return 0;
}
mkdir_and_force_owner( temp_dirname, ct->uid, getgid() );
free( temp_dirname );
This is main app with create initial directory in home. Drop root privileges as early as possible. Only re-enable them to get access to the real-time scheduler. This not work in debian.
int main( int argc, char **argv )
{
rtctimer_t *rtctimer = 0;
int read_stdin = 1;
int result = 0;
int realtime = 0;
uid_t priv_uid = geteuid();
uid_t user_uid = getuid();
/*
* Temporarily drop down to user-level access, so that files aren't
* created setuid root.
*/
if( seteuid( user_uid ) == -1 ) {
lfprintf( stderr, _("\n"
" Failed to drop root privileges: %s.\n"
" motv will now exit to avoid security problems.\n\n"),
strerror( errno ) );
return 1;
}
setup_i18n();
setup_utf8();
lfprintf( stderr, _("Running %s.\n"), PACKAGE_STRING );
/* Steal system resources in the name of performance. */
/* Get maximum priority before dropping root privileges. We'll drop back */
/* to the value specified in the config file (or the default) later. */
seteuid( priv_uid );
setpriority( PRIO_PROCESS, 0, -19 );
if( set_realtime_priority( 0 ) ) {
realtime = 1;
}
rtctimer = rtctimer_new( 0 );
if( rtctimer ) {
if( !rtctimer_set_interval( rtctimer, 1024 ) &&
!rtctimer_set_interval( rtctimer, 64 ) ) {
rtctimer_delete( rtctimer );
rtctimer = 0;
} else {
rtctimer_start_clock( rtctimer );
if( rtctimer_get_resolution( rtctimer ) < 1024 ) {
rtctimer_delete( rtctimer );
rtctimer = 0;
}
}
}
/* We've now stolen all our root-requiring resources, drop to a user. */
if( setuid( user_uid ) == -1 ) {
/*
* This used to say "Unknown problems", but we're printing an
* error string, so that didn't really make sense, did it?
*/
lfprintf( stderr, _("\n"
" Failed to drop root privileges: %s.\n"
" motv will now exit to avoid security problems.\n\n"),
strerror( errno ) );
return 1;
}
/* Ditch stdin early. */
if( isatty( STDIN_FILENO ) ) {
read_stdin = 0;
close( STDIN_FILENO );
}
/* Run motv. */
for(;;) {
if( result == 2 ) {
char *new_argv[ 2 ];
new_argv[ 0 ] = "motv";
new_argv[ 1 ] = 0;
result = motv_main( rtctimer, read_stdin, realtime, 0, new_argv );
} else {
result = motv_main( rtctimer, read_stdin, realtime, argc, argv );
}
if( result != 2 ) break;
}
if( rtctimer ) {
rtctimer_delete( rtctimer );
}
return result;
}
The problem is not created by the debian package postinst script because it never creates the ~/.XXXXX directory.
Check the values of ct->uid and getgid() when you call mkdir_and_force_owner(): that function is not called on your main() so I cannot read how you are calling it.
You have to be sure that they are not 0 and 0: print the values for debug. In this case the function will create and chown() the dir root:root; BTW you are running the software as root due to the setuid bit, otherwise you couldn't chown() your configuration dir.