Is there a method typically used to check if a flag is present in an int/other data type? I figured out something like this:
if ((host&flagtocheckfor)==flagtocheckfor)
Which works fine- however it's such a common method of setting flags is this the way flags are usually checked? Or is there a more concise method?
That's pretty well exactly the way bit flags are checked in most languages that support them.
For example:
#define BIT_7 0x80
#define BITS_0_AND_1 0x03
if ((flag & BIT_7) == BIT_7) ...
if ((flag & BITS_0_AND_1) == BITS_0_AND_1) ...
While you can check something like the first with:
if ((flag & BIT_7) != 0) ...
that won't actually work for the second since it will return true if either of the bits are set, not both.
For completeness, C allows you to set the bit masks with:
flag = flag | BIT_7; // or you can also use 'flag |= BIT_7'
You can clear them with:
flag = flag & (~BIT_7);
And toggle them with:
flag = flag ^ BIT_7;
Related
It says that 'x' is not defined and I don't know what to do about it since 'x' is supposed to be an user-defined variable.
I'm new to coding and even newer to Octave and I'm aware that it's an extremely simple, basic question - foolish, even. But even so, if someone could please tell me how to code this, I'd be glad.
function value = sqrmat (x)
% returns true if x is a square matrix and false otherwise
if rows(x)==columns(x)
value=true;
else
value=false;
endif
end
Octave has "script files" and "function files". To create a "script file", use a command (or statement) that has no effect.
Put this command at the top of the file, before all defined functions. Examples:
Declare any number...
In this case, the program assigns this number to the variable "ans".
% script
1;
function value = sqrmat (x)
% returns true if x is a square matrix and false otherwise
if rows(x)==columns(x)
value=true;
else
value=false;
endif
end
A simple message...
It could be a notification, a greeting, and so on.
% script
printf("File accessed\n")
I have the following command:
kubectl get pod -A -o=json | jq -r '.items[]|select(any( .status.containerStatuses[]; .state.waiting or .state.terminated))|[.metadata.namespace, .metadata.name]|#csv'
This command works great. It outputs both the namespace and name of my failing pods.
But now I want to add one more column to the results. The column I want is located in one (and only one) of two places:
.status.containerStatuses[].state.waiting.reason
.status.containerStatuses[].state.terminated.reason
I first tried adding .status.containerStatuses[].state.*.reason to the results fields array. But that gave me an unexpected '*' compile error.
I then got to thinking about how I would do this with SQL or another programming language. They frequently have a function that will return the first non-null value of its parameters. (This is usually called coalesce). However I could not find any such command for jq.
How can I return the reason as a result of my query?
jq has a counterpart to "coalesce" in the form of //.
For example, null // 0 evaluates to 0, and chances are that it will suffice in your case, perhaps:
.status.containerStatuses[].state | (.waiting // .terminated) | .reason
or
.status.containerStatuses[].state | (.waiting.reason // .terminated.reason )
or similar.
However, // should only be used with some understanding of what it does, as explained in detail on the jq FAQ at https://github.com/stedolan/jq/wiki/FAQ#or-versus-
If // is inapplicable for some reason, then the obvious alternative would be an if ... then ... else ... end statement, which is quite like C's _ ? _ : _ in that it can be used to produce a value, e.g. something along the lines of:
.status.containerStatuses[].state
| if has("waiting") then .waiting.reason
else .terminated.reason
end
However, if containerStatuses is an array, then some care may be required.
In case you want to go with coalesce:
# Stream-oriented version
def coalesce(s):
first(s | select(. != null)) // null;
or if you prefer to work with arrays:
# Input: an array
# Output: the first non-null element if any, else null
def coalesce: coalesce(.[]);
Using the stream-oriented version, you could write something along the lines you had in mind with the wildcard, e.g.
coalesce(.status.containerStatuses[].state[].reason?)
Say I want to ask the user to confirm an action. The action consists of three parts. Each of the three parts can be formatted in one of two ways. In a human-language-specific way, I might do something like this (pseudocode):
res = ""
res = "Do you want to %1 at %2, %3 at time %4%5?" % (
"foo" if fooing else "bar", foobar_data,
"expiring" if expiring else "starting", the_time,
", without foobing" if no_foob else (", foobing at %1" % when_foob))
Even if I wrap all translatable strings with the translation function (e.g. tr("Do you want to %1 at %2 ...")), this would probably only work for english since other languages are unlikely to have the same syntactic structure.
But if I write out the whole sentences then I get a combinatorial explosion:
if fooing and expiring and no_foob:
res = "Do you want to foo at %1, expiring at time %2, without foobing?"
elif fooing and expiring and not no_foob:
res = "Do you want to foo at %1, expiring at time %2, foobing at %3?"
elif fooing and not expiring and no_foob:
res = "Do you want to foo at %1, starting at time %2, without foobing?"
# etc ...
res = res % (foobar_data, the_time, when_foob) # account for sometimes not having when_foob somehow
What's the standard way to deal with this situation?
I think it's best to avoid such complex sentences altogether. Instead, provide one simple sentence and add further details in a table-like way (tables are easier to translate).
This has the added bonus that you can hide the details per default (progressive disclosure) and keep the main message short. This increases the chance that your users read the confirmation dialog at all.
Mock-up:
Do you really want to <Foo/Bar>?
[ Cancel ] [ <Foo/Bar> ] [ Details... ]
---------------------------------------------
Time: <Expring at %1 / Starting at %1>
Foobing: <Yes/No>
Even if I wrap all translatable strings with the translation function, this would probably only work for english since other languages are unlikely to have the same syntactic structure.
Yes and no. You can obviously switch the sentence and parameters around to fit the target language:
Wollen Sie am %2 %1, %3 %4%5?
The tricky part obviously is to get the declinations and such right; while the words themselves might not change at all in English when swapping them, they may have to be altered heavily in other languages.
For this it's important to translate all the necessary variations, and be able to annotate them with context in your translation system:
tr('foo', context='infinitive') if fooing else tr('bar', context='infinitive')
tr('expiring', context='verb before date') if expiring else tr('starting', context='verb before date')
The PO file format for instance has this notion built in:
msgctxt "verb before date"
msgid "expiring"
msgstr "wird auslaufen am"
It does take some linguistic knowledge to break up sentences correctly, be able to classify and annotate each term correctly so it can be correctly translated into all languages as necessary, and it takes a lot of Q&A to ensure it's being done correctly. You want to find the right balance between small enough snippets that translations can be reused, and breaking it down enough so it can be translated correctly.
You can also use message ids, if that becomes too complex:
res = "question.confirmActivty" % (..)
msgid "question.confirmActivty"
msgstr "Do you want to %1 at %2, %3 at time %4%5?"
I want to give different output in different invocation of "mycommand". Detailed output (name and age) if "mycommand" is invoked directly or smaller output (only first col) if used in set command. Is this possible in TCL ?
> set output [mycommand]
> puts "$output"
name1
name2
name3
> mycommand
name1 age29
name2 age30
name2 age31
>
There is nothing built-in to allow that, and doing so would probably cause more problems that it would solve. If you need it to produce different results in different contexts, the best thing is to implement an option to control the output (eg: [mycommand -verbose]`)
You could check to see if the global tcl_interactive variable is set and true, and use info level to see (OK, to guess) if you're being called directly, but it would be a total hack.
if {$::tcl_interactive && [info level]==1} {
# do a verbose thing
} else {
# do a not-so-verbose thing
}
But I advise you not do this. Let the caller ask for one or the other mode explicitly, and pick a sensible default. (Which one? When are you laziest?)
For the following code:
set str "a bb ccc"
if {[string first bb "$str"] >= 0} {
puts "yes"
}
My college said I should not double-quote $str because there is performance difference, something like TCL makes a new object internally using $str.
I cannot find a convincing document on this. Do you know if the claim is accurate?
Your colleague is actually wrong, as Tcl's parser is smart enough to know that "$str" is identical to $str. Let's look at the bytecode generated (this is with Tcl 8.6.0, but the part that we're going to look at in detail is actually the same in older versions all the way back to 8.0a1):
% tcl::unsupported::disassemble script {
set str "a bb ccc"
if {[string first bb "$str"] >= 0} {
puts "yes"
}
}
ByteCode 0x0x78710, refCt 1, epoch 15, interp 0x0x2dc10 (epoch 15)
Source "\nset str \"a bb ccc\"\nif {[string first bb \"$str\"] >= 0} "
Cmds 4, src 74, inst 37, litObjs 7, aux 0, stkDepth 2, code/src 0.00
Commands 4:
1: pc 0-5, src 1-18 2: pc 6-35, src 20-72
3: pc 15-20, src 25-46 4: pc 26-31, src 61-70
Command 1: "set str \"a bb ccc\""
(0) push1 0 # "str"
(2) push1 1 # "a bb ccc"
(4) storeScalarStk
(5) pop
Command 2: "if {[string first bb \"$str\"] >= 0} {\n puts \"yes\"\n}"
(6) startCommand +30 2 # next cmd at pc 36, 2 cmds start here
Command 3: "string first bb \"$str\""
(15) push1 2 # "bb"
(17) push1 0 # "str"
(19) loadScalarStk
(20) strfind
(21) push1 3 # "0"
(23) ge
(24) jumpFalse1 +10 # pc 34
Command 4: "puts \"yes\""
(26) push1 4 # "puts"
(28) push1 5 # "yes"
(30) invokeStk1 2
(32) jump1 +4 # pc 36
(34) push1 6 # ""
(36) done
As you can see (look at (17)–(19)), the "$str" is compiled to a push of the name of the variable and a dereference (loadScalarStk). That's the most optimal sequence given that there's no local variable table (i.e., we're not in a procedure). The compiler doesn't do non-local optimizations.
I think your colleague is correct: if Tcl sees plain $str where a word is expected, it parses out that "str" as the name of a variable, looks it up in the approptiate scope, then extracts an internal object representing its value from that variable and then asks that object to produce the string representation of that value. At this point that string representation will be either already available and cached (in the object) — and it will, in your case, — or it will be transparently generated by the object, and cached.
If you put dereferencing of a variable ($str) in a double quoted string, then Tcl goes like this: when it sees the first " in a place where a word is expected, it enters a mode where it would parse the following characters, performing variable- and command substitutions as it goes until it sees the next unescaped ", at which point the substituted text accumulated since the opening " is considered to be one word and it ends up being in a (newly created) internal object representing that word's value.
As you can see, in the second (your) case the original object holding the value of a variable named "str" will be asked for its value, and it then will be used to construct another value while in the first case the first value would be used right away.
Now there's a more subtle matter. For the scripts it evaluates, Tcl only guarantees that its interpreter obeys certain evaluation rules, and nothing more; everything else is implementation details. These details might change from version to version; for instance, in Tcl 8.6, the engine has been reimplemented using non-recursive evaluation (NRE), and while those were rather radical changes to the Tcl internals, your existing scripts did not notice.
What I'm leading you to, is that discussing of implicit performance "hacks" such as the one we're at now only have sense when applied to a particular version of the runtime. I very much doubt Tcl currently optimizes away "$str" to just re-use the object from $str but it could eventually start, in theory.
The real "problem" with your approach is not performance degradation but rather an apparent self-delusion you seem to apply to yourself which leads to Tcl code of dubious style. Let me explain. Contrary to "more conventional" languages (usually influenced by C and the like), Tcl does not have special syntax for strings. This is because it does not have string literals: every value starting its life in a script from a literal is initially a string. The actual type of any value is defined at runtime by commands operating on those values. To demonstrate, set x 10; incr x will put a string "10" to a variable named "x", and then the incr command will force the value in that variable "x" to convert the string "10" it holds to an integer (of value 10); then this integer will be incremented by 1 (producing 11) invalidating the string representation as a side effect. If you later will do puts $x, the string representation will be regenerated from the integer (producing "11"), cached in the value and then printed.
Hence the code style you adopted actually tries to make Tcl code look more like Python (or Perl or whatever was your previous language) for no real value, and also look alien to seasoned Tcl developers. Both double quotes and curly braces are used in Tcl for grouping, not for producing string values and code blocks, respectively — these are just particular use cases for different ways of grouping. Consider reading this thread for more background.
Update: various types of grouping are very well explained in the tutorial which is worth reading as a whole.