Spring supports @Value
methods on:
static String someVariable
@Value("{someVar}")
public void setSomeVariable(String someVar){
someVariable = someVar;
}
Useful for "living off the land" techniques or in scripts:
timeout 1 bash -c "cat /dev/null > /dev/tcp/google.com/80"
echo $? # 0 = OK
TLDR: run the command "cat /dev/null > /dev/tcp/google.com/80" which uses linux's TCP device files and wait for 1 second. If the TCP connection is successful, exit code will be 0
Uwrapping the above command from the end:
/dev/tcp/google.com/80
: we're using linux's inbuilt TCP/IP dev filescat /dev/null > /dev/tcp/google.com/80
: sending "null" to this endpoint (google.com, port 80)cat
command to completetimeout
, it's easier to wrap the command with inverted commas (to avoid redirecting the output of "timeout" itself by mistake), and feed it into bash -c
which accepts string commands and feeds them to bashecho $?
outputs the previous command's exit code. In this case, 0 will mean TCP connection was successful, and otherwise a non-zero exit code is returnedAsyncio contains the event_loop.run_in_executor
function which allows you to run co-routines in a separate executor - this being a Thread or Processor pool (via the concurrent.futures module):
def blocking_task(i):
print(i) #or some other useful task...
async def run_blocking_tasks(executor):
loop = asyncio.get_event_loop()
blocking_tasks = [
loop.run_in_executor(executor, blocking_task, i)
for i in range(6)
]
completed, pending = await asyncio.wait(blocking_tasks)
results = [t.result() for t in completed]
return results
event_loop = asyncio.get_event_loop()
try:
event_loop.run_until_complete(
run_blocking_tasks(executor)
)
finally:
event_loop.close()
Important: note that the last argument to run_in_executor is *args, i.e. the arguments to pass to the blocking task. Passing the argument directly (blocking_task(i)
) will not work as expected
Python3 allows us to sort iterables using the sorted function. It also allows us to define a "key function". The key function accepts a single parameter - an item from the iterable. It returns an integer, the lower the integer, the higher up in the sorted list (i.e. an item which returns 1 will appear before an item which returns 2)
Let's define an iterable of dicts:
listOfDicts = [{
'level': 'high',
'id' : 3
},
{
'level': 'low',
'id' : 2
},
{
'level': 'low',
'id' : 1
},
{
'level': 'medium',
'id' : 4
}]
We'd like to have dicts whose level attribute is high to appear first in the list, followed by medium, and last by low. Let's define a suitable key function to do this:
def custom_sort_function(obj):
if (obj['level'] == 'high'):
return 1
if (obj['level'] == 'medium'):
return 2
if (obj['level'] == 'low'):
return 3
return 4
Last, we apply the above function to our iterable using sorted. P.S. note how we use a lambda to feed each entry into the custom_sort_function - this is not necessary - you can just provide the function name
sorted(listOfDicts, key=lambda x : custom_sort_function(x))
# - OR -
sorted(listOfDicts, key=custom_sort_function)
Which returns the sorted list as expected:
[{'level': 'high', 'id': 3}, {'level': 'medium', 'id': 4}, {'level': 'low', 'id': 2}, {'level': 'low', 'id': 1}]
The elvis operator (?:) allows you to assign a "default" value if the variable to the left of the elvis operator is null
The notation someVariable?.let{ } allows you to take an action (which is defined within "let") only if someVariable is non-null
fun main() {
// the elvis operator
val test = null
val test2 = test ?: "it was null"
println(test2)
// taking action only if variable is non-null
// using ?.let
val isNull = null
isNull?.let{
println("Inside let with null - will not be printed")
}
val isNotNull = 1
isNotNull?.let{
println("Inside let with non-null value of '$it' - will be printed")
}
}
Output:
it was null
Inside let with non-null value of '1' - will be printed
It's possible to generate a dictionary using comprehensions:
t = ["1", "234", "45"]
a = { keyName: len(keyName) for keyName in t }
print(a)
# prints: {'1': 1, '234': 3, '45': 2}
Using only functional-style array methods to get the unique values in an array:
const sampleArray = [1, 2, 1, 3, 4]; // note "1" is repeated
const uniqueArray = sampleArray.filter( (value, idx, arr) => arr.indexOf(value) === idx );
console.log(uniqueArray);
// expected output is [1, 2, 3, 4]
This JS snippet takes advantage of two things:
Executor (plain threading): allows you to define multiple threads (a pool of threads) which run atomic units of work in parallel. Depending on resources, max number of threads is limited. If on thread is blocked, it will wait until it can continue. (i.e. we have parallelism but no asynchronicity)
CompleteableFuture: allows the same as above, however now if a thread is blocked it can switch to another task while waiting for the original work to become unblocked. (i.e. now we have parallelism and asynchronicity)
Webflux: allows the same as the above, but where CompleteableFuture is eagerly executed, webflux is designed to be lazily executed (i.e. executed only when required - on subsciption). This allows the design to implement backpressure and control upstream workloads
old_list = [{
'fieldToUpdate': 'oldValue'
}]
new_list = list( map( lambda entry: entry.update({'fieldToUpdate': 'newValue'}) or entry, old_list) )
# new_list is now: [{'fieldToUpdate': 'newValue'}]
The above code snippet makes use of the fact that the "update" method of a standard python dict returns "None" - hence you can see the "or" being used to returned the newly updated entry
JSON.stringify() accepts a second parameter called "the replacer parameter". This parameter can be:
An array: the values in the function represent which keys of the object should be stringifyed into JSON. Anything not in the array is left out of the JSON string.
A function: the function accepts 2 parameters - key and value. The return value of this function is what will be inserted into the JSON object for the given key. Returning undefined omits the key from the JSON object. This allows you to provide custom logic when stringifying objects to JSON
A typical java-like singleton would look like this in Kotlin:
class Singleton private constructor() {
private object SingletonHolder {
val INSTANCE = Singleton()
}
companion object {
val instance : Singleton by lazy {
SingletonHolder.INSTANCE
}
}
}
The above code:
The important note here is the "by lazy" delegate property. by lazy is thread safe and hence avoids the double check code we normally use in Java to create a singleton. In addition, the companion object is itself a singleton, so we can shorten the above to:
class Singleton private constructor() {
companion object {
val instance : Singleton by lazy {
Singleton()
}
}
}
We simply got rid of the private SingletonHolder object, Furthermore, Kotlin shorthands all this to a single line:
object Singleton
Javascript functions can return other functions, and the inner function has access to the scope of the outer function, making it useful to store variables persistently between function calls, for example:
var checkCookie = function() {
var lastCookie = document.cookie; // 'static' memory between function calls
return function() {
var currentCookie = document.cookie;
if (currentCookie != lastCookie) {
// something useful like parse cookie, run a callback fn, etc.
lastCookie = currentCookie; // store latest cookie
}
};
}();
window.setInterval(checkCookie, 100); // run every 100 ms
// example object:
let demo = {one: 1, two: 2}
// pick subset of keys
let {one} = demo
// rename variables
let {one: anotherOne} = demo
// "one" renamed to "anotherOne"
// provide default values
let {three = 3, one} = demo
// since "three" doesn't exist in demo, it's given the default value of "3"
// gather the rest
let {one, ...rest} = demo
//"rest" will contain anything from "demo" which is not "one"