A list of puns related to "Wrapper Function"
The fact that it doesn't work is completely irrelevant since it's never going to be used anyway.
Why does this wrapper function give different results compared to not using it.
Wrapper function:
coxph_hapfit <- function(y_vars, dataset, haplotypes, wt){
paste(y_vars, "~", paste(haplotypes, collapse = "+"),
"+pc1", "+pc2", "+pc3", "+age", "+gender") %>%
as.formula(.) %>%
coxph(., data = dataset, id = id_row, weights = wt)
}
Using the wrapper function
map2(x, y,
~coxph_hapfit(y_vars = "Surv(chftt, chf)",
haplotypes = .y, dataset = .x, wt = .x$post))
Without using the wrapper
map2(x, y,
~paste("Surv(chftt, chf)", "~", .y,
"+pc1", "+pc2", "+pc3", "+age", "+gender") %>%
as.formula(.) %>%
coxph(., data = .x, weights = .x$post, id = .x$id_row))
What am I missing here that these two lines of code produce different results yet use the same data?
So I have a function letβs say getAllFruits() that calls an api listAllfruits. What I want to do once getAllFruits() is complete I want to set some flag. But how can I do that without using then or arrow function? Basically I guess I will have to a callback but I am not able to figure out the syntax.
Hereβs a snippet:
getAllFruits() { . . . api.listAllfruits(error, data, response){ . . . If(error){ β¦ } elseif(response){ β¦ } } β¦ } Now I have this function:
doThisOnClick() { Flag = 0; //once the api call completes getAllFruits (){ //this is not correct Flag = 1; } }
Ps- I am new pls help
I want to pass a predefined function along with its arguments through another function that does something on top of it. In the example below, I want to pass the math functions to my custom one and have it actually execute within the Try, Except block. When I run this code, the math functions actually execute in the print statements and it throws the errors written in the math module. Not sure if a wrapper / helper function is the answer but experience in the two concepts is little-to-none.
import math
def custom_error(func):
try:
return func
except ValueError:
return "YOU CANT DO THAT!"
# THIS WILL RUN WITHOUT ISSUES
print(custom_error(math.sqrt(1)))
# I WANT TO PRINT MY OWN ERROR FOR THIS
print(custom_error(math.sqrt(-1)))
# THIS IS ANOTHER FUNCTION THAT I WANT TO USE THAT WILL BREAK
print(custom_error(math.factorial(-1)))
NOTE : This code is dumbed down version of what I am actually trying to accomplish but the concept is the same.
I'm pretty stumped here as I don't have a ton of Typescript experience. I'm writing an express app and would like to write an wrapper function that executes an express route handler and catches any errors (and forwards then to the express error handler).
Here's what I have:
import { someRouteHandler } from '../email/handlers';
type ArgsArray = any[];
type HandlerFunc = (...a: ArgsArray) => Promise<any>;
const wrapErrors =
(fn: HandlerFunc) =>
(...args: ArgsArray): Promise<any> =>
fn(...args).catch(args[2]);
const stronglyTyped = wrapErrors(someRouteHandler);
export default wrapErrors;
What I'd like to know is whether or not it is possible to write wrapErrors
generically so that it is able to infer the types of someRouteHandler
which is going to be an async function.
I have a function that makes calls to an API endpoint. As an example below let's say I have 3 object types that use the same format when making calls to the API. I would like to abstract out the logic into an intermediary function with $ObjectType being the only thing that changes.
However, I think this causes an issue with readability/usability. ```Get-SingleObjectDetails``` isn't as easy to understand as 3 separate functions: ```Get-DeviceDetails```, ```Get-PolicyDetails```, and ```Get-ConfigurationDetails```, etc...
What is the best/easiest to maintain/most elegant way to go about creating aliases like this?
function Get-SingleObjectDetails {
[Cmdletbinding()]
param(
#DeviceId or PolicyId
[Parameter(Mandatory)]$Id,
[Parameter()]
[ValidateSet('device', 'policy', 'configuration')]
$ObjectType,
[Parameter()]$InstanceUrl = $([myClass]::instanceUrl),
[Parameter()]$Username = $([myClass]::username),
[Parameter()]$Password = $([myClass]::password)
)
$restParams = @{
Method = 'GET'
Uri = "$([myClass]::instanceUrl)/api/v1/$ObjectType/$Id"
Headers = @{
Authorization = "Basic " + $(
[System.Convert]::ToBase64String(
[System.Text.Encoding]::UTF8.GetBytes(
"$Username`:$Password"
)
)
)
}
}
return $(Invoke-RestMethod @restParams).result
}
# A simpler way to do it besides this? Is there a way to do it without having to specify the parameters again? A way to define the parameters in advance and reuse them in the function definitions maybe?
function Get-ConfigurationDetails {
[Cmdletbinding()]
param(
#DeviceId or PolicyId
[Parameter(Mandatory)]$Id,
[Parameter()]$InstanceUrl = $([myClass]::instanceUrl),
[Parameter()]$Username = $([myClass]::username),
[Parameter()]$Password = $([myClass]::password)
)
Get-SingleObjectDetails @PSBoundParameters -ObjectType 'configuration'
}
I'm new to R, but not to programming. I encountered a surprise where a model created with a wrapper function isn't treated the same as an identical model defined without the wrapper. It's not going to stop me from working or anything, but there is something happening here in the R language that I'd like to understand if anyone here can help.
I have small function that wraps lme4::glmer
. it just adds some default arguments for a logistic regression:
bin_lme <- function(formula, data) {
lme4::glmer(
formula = formula,
data = data,
family = binomial,
control = lme4::glmerControl(optimizer = "bobyqa")
)
}
I then use that function to build a model. For comparison, I build an identical model without using the wrapper as well:
model_a <- bin_lme(correct ~ training + (training | pid), df)
model_b <- lme4::glmer(
formula = correct ~ training + (training | pid),
data = df,
family = binomial,
control = lme4::glmerControl(optimizer = "bobyqa")
)
These should be identical, right? Passing them to the summary
function returns identical output. So does typeof
and class
. They seem identical, but ggeffects::ggeffect
produces an error for the one that was created via the wrapper, but not for the other:
r$> ggeffects::ggeffect(model_a)
Can't compute marginal effects, 'effects::Effect()' returned an error.
Reason: 'data' must be a data.frame, environment, or list
You may try 'ggpredict()' or 'ggemmeans()'.
NULL
Versus:
r$> ggeffects::ggeffect(model_b)
$training
# Predicted probabilities of correct
# x = training
x | Predicted | 95% CI
--------------------------------
0.00 | 0.06 | [0.05, 0.07]
10.20 | 0.20 | [0.17, 0.24]
12.40 | 0.26 | [0.21, 0.31]
13.80 | 0.30 | [0.24, 0.36]
14.10 | 0.31 | [0.25, 0.37]
16.70 | 0.39 | [0.31, 0.48]
17.10 | 0.40 | [0.32, 0.49]
attr(,"class")
[1] "ggalleffects" "list"
attr(,"model.name")
[1] "model_b"
So far, this seems to just be with ggeffect
, as ggpredict
and emmeans
(all from the ggeffects
package) do not error on either one.
Wha
... keep reading on reddit β‘You can check out the source code at the following GitHub link:
* Note: it requires curl (because I'm too lazy to convert the commands to wget)
I want to wrap generic functions having one common parameters with an effect to return an new function.
function withEffect(fn) {
return function(...fargs) {
return fn(effect, ...fargs);
}
}
// to use:
function doStuff(effect: TEffect, a1: number, a2: string) {
...
return result: TResult;
}
export const perform = withEffect(doStuff) // should have type (a1: number, a2: string) => TResult
The question is now, how to type TEffect correctly, using TS 4.0.x
I tried
function withEffect<Fn extends (eff: TEffect, ...args: any[]) => any, [_, ...Fargs] = Paremeters<Fn>>(fn): (...args: FArgs) => ReturnType<Fn> {
...
}
But that complains that instead of the comma inside the function definition it would rather want it to be a ternary expression.
function withEffect<Fn extends (eff: TEffect, ...args: any[]) => any>(fn){
return function<[_, ...FArgs] = Parameters<Fn>>(...fargs: FArgs) {
...
}
}
would not work either.
I can pass any plain function to a function<> callback by simply using its name - as long as it matches the signature.
But a non-static member function with the same signature cannot be simply passed as "instance.memberfunction". It first needs to be wrapped in a lambda that will also capture "this". Forwarding the arguments generically regardless of number, type and other properties is a bit verbose:
[&](auto &&... args) -> decltype(auto) {return instance.function(std::forward<decltype(args)>(args)...);}
I want a convenience wrapper that does this cleanly but my template-fu is insufficient.
I can do this with a macro, of course, but...
#define CALLBACK(callable) ([&](auto &&... args) -> decltype(auto) { \
return (callable)(std::forward<decltype(args)>(args)...);})
Hi Flask newbie here.
I have some decorators that I want to apply to my endpoints, but I am not sure where to put those decorators code.
For example, I have this customized error handler wrapper function called @ERROR
, which checks errors for input parameter param
. This function resides in a helper file called Error.py:
def ERROR (function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
param=request.args.get('param')
#checks param
return function(param, *args, **kwargs)
return wrapper
And then param gets passed to a flask app file where all the endpoints are.
It bothers me that I am requesting parameters outside of the app file. Any good ideas (or standard practices) on where I can put my wrapper functions? I thought about moving them to the app file as well but it's gonna make the file "uglier"...
Any suggestions help! Thank you :)
It is super easy to use (literally one line above any already-written function) and automatically generates an OpenAPI schema and interactive documentation using ReDoc and SwaggerUI. It supports async functions and has the option to return a HTTP code immediately, continue processing the request and query another API with the response. Go check it out! I would love feedback on the project, as I already had a wrapper for Flask and the feedback was awesome! β€οΈ
https://github.com/daleal/asymmetric
Looking for a quick way to create questionnaires on console? I created this library so that you can just do that! Main features include validators, commands and traversal through questions (all of which can be customized).
I also included an example (beck depression inventory) implementation in GitHub. Looking forward for your criticism.
GitHub link:
https://github.com/realsuayip/quizz
PyPI:
I am trying to use librealsense with the D435 camera and an Android device. My goal is to retrieve a point-cloud to do mapping with the D435 for a robotics project.
If I am correct, there are 2 ways to implement librealsense for Android, the java and native version:
java librealsense: https://github.com/IntelRealSense/librealsense/tree/development/wrappers/android/examples/java_example
native librealsense for Android: https://github.com/IntelRealSense/librealsense/tree/development/wrappers/android/examples/native_example
However, looking through all the files in the library, neither seems to have functions to create a point cloud. With the typical C++ code, like in the example below, there are functions like re2::context().create_pointcloud(). But I can't find the equivalent with the Android wrappers.
https://dev.intelrealsense.com/docs/rs-pointcloud
Anyone know why, or how I can get a point-cloud?
With ethereum becoming to #1 second layer for BTC itβs clear speed matters. It nano could wrap other crypto in a non custodian way the wrapped crypto could be transferred between exchanges and wallets at the speed nano transacts.
nBTC nETH etc.
I have a third-party library, in which there's a function that returns `void` directly, but has a block that's used as a callback:
def my_get_data1(arg1)
Thread.new do
ExternalLib.get_data_by_block("arg1") do |a, b, c|
# [ result of computation and some other data comes here ]
end
end
end
And there's the same kind of function that accepts a `proc` instead, and they both work identically:
MyProc = Proc.new do |a, b, c|
# [ result of computation and some other data comes here ]
end
def my_get_data2(arg1)
Thread.new do
ExternalLib.get_data_by_proc(arg1, MyProc)
end
end
my_get_data1() and my_get_data2() serve the purpose of an interface or wrapper of `ExternalLib.get_data()` for the end user, this is what I need.
Q: How can I actually allow a user to get access to the result of the computation -- to what's inside of the `block` or `proc`?
I want it to be something like this:
p1 = Proc.new do |a|
# [ user will access result here, via a]
end
my_get_data1(arg1, p1)
my_get_data2(arg1) do do |a|
# [ user will access result here, via a]
end
P.S.
I've found out that that I have to use Thread.new because otherwise, it'll hang when I run it as "ruby my_script1.rb", probably due to GIL. In `irb` it won't, though.
I built a simple open source library to help transform any written module into an API in a matter of seconds. Visit my repo and try it out!
https://github.com/daleal/symmetric
https://i.imgur.com/F2HfHwF.png
import pambda from 'pambdajs';
const p = await pambda.init(5);
data = [1,2,3];
const heavyWork = (x) => {
return x+x;
}
// original single process way
const singleProcess = () => {
data.map(heavyWork);
}
// PambdaJS multi process way
const pambdaProcess = async () => {
await p.map(heavyWork, data);
}
// javascript example
const func = (arg1, arg2) => { // operations }
const wrapper = callback => (arg1, arg2) => { callback(arg1, arg2); }
wrapper(func);
I think the syntax above is correct. When do you guys actually use it? I am at the phase where I kinda of barely understand what's going on but am not comfortable using this pattern. I want to use it a couple times to build that comfort and could probably find a good use case if advised on it. I typically work with React, Express, and Firebase.
I've been bit in the butt by not checking the return values of some important functions, so I'm trying to be better about it, but find that it really clutters up the code with a lot of redundant blocks of similar code. I had the idea to make a wrapper function that will do all the error checking, but I don't know if this is really a good idea to use or to get accustomed to doing.
Here is an example of what I've wrote for fread/fwrite...
int freadWErrCheck(void *ptr, size_t size, size_t nmemb, FILE *stream, char *errMessage)
{
if (fread(ptr, size, nmemb, stream) != nmemb / size) {
if (ferror(stream)) {
perror(errMessage);
returnVal = errno;
return errno;
}
}
return 0;
}
So I'd use it like this...
if (freadWErrCheck(fileBuffer,sizeof(unsigned char),returnFileSize(dbFileName),dbFile, "writeDatabase fread fileBuffer") != 0)
return returnVal;
returnVal would be a global int so it can pass the return value back from the calling function.
It's cut down on redundant code a lot, but I feel like it could be better. For one thing, I could think of some better/more-informative error messages, but for now I'm just following a format of "calling-function fread/fwrite ptr". It would be great if I could figure out how to throw the line-number in there, but since the source is always changing, the line-numbers won't really reflect accurately.
Criticisms? Advice?
Originally when I was envisioning writing my own utility method with a callback parameter, I imagined passing the arguments as a separate parameter:
function loopTheCallbackUntil(callback, args) {...}
But then I saw someone recommend passing the arguments into the callback itself. To fix the issue of immediate invokation with that syntax, a wrapper function was used:
function loopTheCallbackUntil(callback) {...}
loopTheCallbackUntil(() => handleEachstep(p1, p2));
Is this how it's normally done when designind functions that take function arguments? It does seem cleaner this way.
If it depends, when would you opt to pass arguments as a seprate parameter?
You can check out the source code at the following GitHub link:
* Note: it requires curl (because I'm too lazy to convert the commands to wget)
You can check out the source code for each at the following GitHub links:
* Note: they both require curl (because I'm too lazy to convert the commands to wget)
Please note that this site uses cookies to personalise content and adverts, to provide social media features, and to analyse web traffic. Click here for more information.