I'm new to Python and I am studying Pyramid to learn how to write good code. I wrote this root factory code:
class RootFactory(object):
def __acl__(self):
return [
(Allow, 'group:alfa', 'alfa'),
]
def __init__(self, request):
print(type(request))
pass
and the result shows that "request" is <class 'pyramid.util.Request'> but if I open the module pyramid.util.py, to see the source code, I do not found the class Request. I think that this class is in the module pyramid.request.py
Could someone explain how this is working?
It's an implementation detail of using config.add_request_method. When adding request methods, a new class object is created using the InstancePropertyHelper which is located in the pyramid.util module. This could probably be fixed, but at the end of the day the actual class we care about is pyramid.request.Request so you should look there for issues.
Related
I am developing a project based on the pytorch lightning + hydra template found here https://github.com/ashleve/lightning-hydra-template. I am trying to instantiate a Pytorch dataset object using hydra instantiate, overriding the default cfg value with the DictConfig object. Specifically, I have this config file:
...
training_dataset:
_target_: src.datamodules.components.baseline_datasets.FSD50K
cfg: omegaconf.dictconfig.DictConfig(content={})
mode: "training"
...
While the pytorch lightning datamodule does the following:
class AudioTagDataModule(LightningDataModule):
def __init__(self, cfg: DictConfig):
super().__init__()
self.cfg = cfg
self.save_hyperparameters(logger=False)
def setup(self, stage: Optional[str] = None):
self.trainset = instantiate(self.cfg.datamodule.training_dataset, cfg=self.cfg)
...
The rest of the code is pretty much unmodified from the template. However, when the pytorch dataset is instantiated, I get an error due to the config being empty. Checking in debug, I see that the config value is not being overridden, despite having the same name that was specified in the configs. Could someone provide some guidance on why the override is not working and how to correctly proceed? Thank!
Looking at the AudioTagDataModule, I see that the setup method passes a cfg=self.cfg keyword argument to the instantiate function. This is why the cfg setting from your training_dataset config is not showing up in your instantiated dataset; the keyword argument is taking precedence. Based on the code you posted, it would probably make sense to pass an empty DictConfig to AudioTagDataModule.__init__ instead of defining a cfg key/value in training_dataset.
Another thing: in your yaml file, you'd probably want cfg: {} instead of cfg: omegaconf.dictconfig.DictConfig(content={}), as the latter will result in the python string "omegaconf.dictconfig.DictConfig(content={})" and the former will result in an empty DictConfig.
I have some static methods written in util files. When I try to patch them and add a side_effect to return a specific value, they just execute the original method content. It is not getting mocked. Why is this happening? Is there any way to overcome this issue, rather than trying to mock the internal methods of that method?
I am trying to mock below method which is in date_utils.py file.
def get_sys_date_in_sap_format():
today = datetime.now()
date = today.strftime("%d.%m.%Y")
logger.info("Date: {}", date)
return date
It is patched using below approach;
#patch("src.util.date_utils.get_sys_date_in_sap_format", side_effect=mock_sap_date)
This method is invoked inside the method which I am trying to test. Some help is really appreciated, as I am confused as why it is happening. Is there a way to resolve this?
#MrBean Bremen, it worked when I changed the import to b.my_method instead of a.my_method. I have always been wondering about this issue. Thank you so much.
#patch("src.sap.file_upload_service.get_sys_date_in_sap_format", return_value="11.10.2019")
I'm writing a ts transformer that finds named class decorator then replace decorator's call and passes a map with names and types of all props of decorated class, e.g.:
source file:
import BigNumber from "bignumber.js";
#decorator()
class AClass {
aProp: BigNumber;
}
output:
import BigNumber from "bignumber.js";
#decorator({"aProp": BigNumber})
class AClass {
aProp: BigNumber;
}
I'm getting prop name and type from PropertyDeclaration:
const clazzProps = [];
for (const childNode of clazz.members) {
if (ts.isPropertyDeclaration(childNode)) {
const type = typeChecker.getTypeAtLocation(childNode);
if (type.isClass()) {
clazzProps.push(ts.createPropertyAssignment(
ts.createIdentifier(childNode.name.getText()),
childNode.type.typeName
);
}
}
}
So far so good, however after compilation import statement is removed from output js file, cause in the source file BigNumber was only referenced as a type, not as a value. My question is, how to properly check if BigNumber is not a type only and make sure that import will not be stripped ?
I know it's a bit late, but still.
Typescript compiler has four main phases—parsing, binding, type checking, and emitting. Binding is where the relationships between identifiers are resolved, but transformation happens during the "emitting" phase.
That means on a moment when transform happened typescript already know that BigNumber is used only as type in this context and following it's own rules all imports which point only to type is not emitted to js.
Unfortunately, there is no simple solution and you probably will be needed to add this imports by yourself during the transform.
The same use-case and problem was solved here https://github.com/nestjs/graphql/blob/master/lib/plugin/visitors/model-class.visitor.ts
It's resolving types of property using type checker and finding the file this type pointint to and store this paths in importsToAddPerFile, than in updateImports the are added to the source file.
I'm generally not recommending using a TypeChecker (it's slower, might not be available in some context and can produce weird results if you have few transform relying on it) in transforms and probably for simple cases you can just read what imports you already have and re-create them manually.
I just started to study Kotlin and JavaFX by following tutorial.
I could see blank JavaFX windows, and I proceed next step that using FXML.
import javafx.application.Application
import javafx.fxml.FXMLLoader
import javafx.scene.Scene
import javafx.stage.Stage
class AppMain : Application() {
override fun start(primaryStage: Stage) {
primaryStage.title = "Try JavaFX"
val fxml = javaClass.getResource("fxml/Main.fxml")
val root = FXMLLoader.load(fxml) // ERRORS here! `load`
val scene = Scene(root)
primaryStage.scene = scene
primaryStage.show()
}
}
However, I couldn't figure out that how to avoid the type inferencing error like:
Error:(12, 31) Kotlin: Type inference failed: Not enough information to infer parameter T in fun <T : Any!> load(p0: URL!): T! Please specify it explicitly.
From the message, I understand that I have to write the type of variable fxml explicitly.
But I have no idea that what type should be labeled to fxml.
I tried to read the document about JavaFX, but I couldn't figure it out.(I'm not familiar with Java and Kotlin)
I tried to type like URL but it does not make sense.
Many JavaFX & Kotlin example codes that I could find from google does not seems to have the problem like this. (Are the example codes written in previous version?)
What type should I put for the variable?
Or did I miss something other?
Environment and Codes
Environment
JDK 11
JavaFX 11
Kotlin 1.2.71
My complete trial code
https://github.com/QuietJoon/StudyKotlin-JavaFX/tree/fxml
The problem isn't the parameter to the FXMLLoader.load function (which is a java.net.URL object, as returned by javaClass.getResource). It's that this function returns a generic type:
public static <T> T load(URL location)
The Kotlin compiler needs to know what type your root variable will be (as you've not explicitly defined it), but it can't know that as there's nothing in the code that will allow it to infer this.
A quick Google returned this example which has this code in it (in Java):
Parent root = FXMLLoader.load(getClass().getResource("fxml_example.fxml"));
As you can see here, the root variable is of type Parent. So what you need to do is provide this type (i.e. what you expect the load function to return) in some way. Here are two different ways you could do this:
Specify the type explicitly when declaring the variable: val root: Parent = FXMLLoader.load(fxml)
Specify the generic type when calling the method: val root = FXMLLoader.load<Parent>(fxml)
Note also that in your build.gradle file in your github repo there's a mistake that means the code didn't immediately compile when I fetched it:
compile "org.openjfx.javafx.fxml:11:$platform" should be compile "org.openjfx:javafx-fxml:11:$platform" (one of the dots should be a colon).
I am trying to come up with my first middleware of my own in a Django 1.10 project. And currently running into the following error
TypeError: init() missing 1 required positional argument:
'get_response'
I have defined the middleware in a middleware.py like this:
from zeon.utils import RequestLogThread
class StartRestEndPointMiddleWare(object):
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
request.request_log_id = RequestLogThread('send_contact', request.data).start()
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
return response
I am lost trying to figure out what's wrong, since everything seems to be in accordance with the doc. I would really appreciate any hint.
UPDATE:
I place it into middle_classes:
MIDDLEWARE_CLASSES = [
'zeon.middleware.StartRestEndPointMiddleWare',
]
Django changed the way middleware classes worked in 1.10. New-style middleware classes belong in the MIDDLEWARE list, like this:
MIDDLEWARE = [
'zeon.middleware.StartRestEndPointMiddleWare',
]
When you put your middleware into MIDDLEWARE_CLASSES, it's being treated as an old-style middleware, which works differently. A better error message might have made this more clear.