Structs duplication in Julia - struct

I have package called sandwich, it then has:
A file flavours.jl which defines a struct HamCheeseSandwich.
The file factory.jl is a module which first first runs include("flavours.jl") and has a method make_sandwich which creates a HamCheeseSandwich, except rather than producing a HamCheeseSandwich it returns sandwich.factory.HamCheeseSandwich
The last file is printer.jl , here the sandwich made in factory.jl fails with MethodError: no method matching print_sandwich(::sandwich.factory.HamCheeseSandwich)
# printer.jl
function print_sandwich(sandwich::HamCheeseSandwich)
println("Enjoy your sandwich")
println(sandwich)
end
When I check the types
Julia> sandwich.factory.HamCheeseSandwich == HamCheeseSandwich
false
Which suggests the problem is my use of include has created two versions of HamCheeseSandwich.
To reproduce
A working example can be seen at this repo:https://github.com/this-josh/Julia-structs-question
This behaviour can be reproduced with
using sandwich
s = factory.make_sandwich(true,false)
print_sandwich(s)
My question is how should I use includes within my package to prevent the duplication of HamCheeseSandwich and to make sure I can still type hint as in printer.jl

You are defining the type HamSandwich several times and you should do it once and then reference the definition.
Hence your code should be:
module Sandwich
module Flavours
struct HamSandwich end
end
module Factory
import ..Flavours
makeSandwich() = Flavours.HamSandwich()
end
end
Testing:
julia> using Main.Sandwich
julia> Sandwich.Factory.makeSandwich()
Main.Sandwich.Flavours.HamSandwich()

Related

target_transform in torchvision.datasets.ImageFolder seems not to work

I am using PuyTorch 1.13 with Python 3.10.
I have a problem where I import pictures from a folder structure using
data = ImageFolder(root='./faces/', loader=img_loader, transform=transform,
is_valid_file=is_valid_file)
In this command labels are assigned automatically according to which subdirectory belongs an image.
I wanted to assign different labels and use target_transform for this purpose (e.g. I wanted to use a word from the file name to assign an appropriate label).
I have used
def target_transform(id):
print(2)
return id * 2
data = ImageFolder(root='./faces/', loader=img_loader, transform=transform, target_transform=target_transform, is_valid_file=is_valid_file)
Next,
data = ImageFolder(root='./faces/', loader=img_loader, transform=transform, target_transform=lambda id:2*id, is_valid_file=is_valid_file)
or
data = ImageFolder(root='./faces/', loader=img_loader, transform=transform, target_transform=
torchvision.transforms.Lambda(lambda id:2*id), is_valid_file=is_valid_file)
But none of these affect the labels. In addition, in the first example I included the print statemet to see whether the function is called but it is not. I have serached the use of this funciton but the exmaples I have found do not work and the documentation is scarce in this respect. Any idea what is wrogn with the code?

How can i create a "run-loop" function that detects key-presses using Python?

I'm new to python3 and I've been practicing by doing some basic programs but now I'm stuck with a little snake type game I wrote. The code I wrote so far have the following parts in order:
Imported modules
Classes to get a key from the user without the need to press "enter"
A function that is called by the module threading (named move_alt()).
t = threading.Thread(target=move_alt) # this is immediately after the portion of code
described in point 3)
4)A move_forward() function to create the map using a list of characters and to move a "position character" starting at the center of the map to the right till it crashes into a "wall caracter". This function is named move_forward().
t.setDaemon(True)
t.start()
move_forward()
The idea is to start a thread to run simultaneously with move_forward function, which targets the function described in 2) to take a key from the user and depending on what key was pressed make some action over move_forward function, for example (and to be more specific) move_up or move_down, etc.
I don't know how to use the threading module correctly so I'm not getting my code to work as expected. Instead what is happening is the program would run the thread without running simultaneously the move_forward function and until I don't press a key (which is what it's done inside the thread) it doesn't do anything. Actually, at the beginning when i just run the program it tries to draw the map (list of characters) but only draws some characters and then gets stuck.
Sorry if my explanation wasn't efficient but English is not my first language and I tend to write too much.
P.S= I didn't put the code above because it is too long due to comments and stuff I made to learn (and not forget)
After a lot of thinking I was finally able to make the program work as expected. First of all, the threading module wasn't the best option but for some reason I was confusing threading (which is used for concurrency purposes) with whatever I was trying to do. So after a little while I stopped using this idea.
The way I managed to make it work was actually using another module called "keyboard" (for linux users you have to use the module as root for some reason). Here is a little bit of a code to use that module:
def onkeypressw(event): this function is used as a condition in the "while loop" for the move_up condition
global stopw
if event.name == 's' or event.name == "a" or event.name == "d":
stopw = True
keyboard.on_press(onkeypressw)
def onkeypressw1(event): # this function is used as condition in the if sentence in the main function to call move_up() function
global runw1
if event.name == "w":
runw1 = True
else:
runw1 = False
keyboard.on_press(onkeypressw1)
Then in the main function i have a while True loop running, where i have some if sentences that run one of four possibles move function: move_up, move_down, move_left, move_right depending of which key i pressed (w-s-d-a). Inside these "move functions" there are while loops to draw the map and move the character position(let's say the snake head) using a list of characters, until I press another button. So for example if in the main function I pressed "w" the program is going to run move_up function and move the character position until either it crashes against "the wall character" or I press "s, d or a". The conditions I put for the "while loop" are: 1)one for the wall character and 2)"not stopw" so it draws the list until I crash against the wall or stopw = True.
I know you can make this code using others modules and get the same result with less work but i wanted to use as much basic code as possible to learn python3 faster because I had previous experience programming with C.
P.S: Here is one of the moves function, just in case someone is curious:
def move_up():
global c, f
global map1
global stopw
while f> 0 and not stopw:
map1[f, c] = " o " # f represents the rows and c the columns, I replaced the initial position character "_" for "o"
f = f - 1 # up one row
map1[f, c] = " _ " # I put the position character "_" at the new position
cls() # clear the screen
time.sleep(0.4) # add a little delay just to modify the snake speed
stopw = False # reset the boolean

How to use extract the hidden layer features in H2ODeepLearningEstimator?

I found H2O has the function h2o.deepfeatures in R to pull the hidden layer features
https://www.rdocumentation.org/packages/h2o/versions/3.20.0.8/topics/h2o.deepfeatures
train_features <- h2o.deepfeatures(model_nn, train, layer=3)
But I didn't find any example in Python? Can anyone provide some sample code?
Most Python/R API functions are wrappers around REST calls. See http://docs.h2o.ai/h2o/latest-stable/h2o-py/docs/_modules/h2o/model/model_base.html#ModelBase.deepfeatures
So, to convert an R example to a Python one, move the model to be the this, and all other args should shuffle along. I.e. the example from the manual becomes (with dots in variable names changed to underlines):
prostate_hex = ...
prostate_dl = ...
prostate_deepfeatures_layer1 = prostate_dl.deepfeatures(prostate_hex, 1)
prostate_deepfeatures_layer2 = prostate_dl.deepfeatures(prostate_hex, 2)
Sometimes the function name will change slightly (e.g. h2o.importFile() vs. h2o.import_file() so you need to hunt for it at http://docs.h2o.ai/h2o/latest-stable/h2o-py/docs/index.html

Python GDAL, SetAttributeFilter not working

I am trying to use GDAL's SetAttributeFilter() to filter the features in a layer of my shapefile, but the filter seems to have no effect.
My current data is a shapefile from the US Census Bureau, but I have tried with other shapefiles and get a similar result.
For example
from osgeo import ogr
shapefile_path = '../input/processed/shapefile/'
shapefile_ds = ogr.Open(shapefile_path)
cbsa = shapefile_ds.GetLayer('cb_2016_us_cbsa_500k')
print(cbsa.GetFeatureCount())
cbsa.SetAttributeFilter('NAME = "Chicago-Naperville-Elgin, IL-IN-WI"')
feat = cbsa.GetNextFeature()
print(feat.GetField('NAME'))
print(cbsa.GetFeatureCount())
Yields
945
Platteville, WI
945
I'm using Python 3.6 and GDAL 2.2.1
You can capture the return value of the SetAttributeFilter statement and make sure its 0, otherwise something went wrong.
In this particular case, its probably due to the quoting. Single quotes refer to string literals (a value), and double quotes refer to a column/table name.
Depending on how you run this Python code, somewhere in the stdout/stderr GDAL prints something like:
ERROR 1: "Chicago-Naperville-Elgin, IL-IN-WI" not recognised as an available field.
More details can be found at:
https://trac.osgeo.org/gdal/wiki/rfc52_strict_sql_quoting
To get it working, simply swap the single/double quoting, so:
cbsa.SetAttributeFilter("NAME='Chicago-Naperville-Elgin, IL-IN-WI'")
While this was a while ago, when I learn something I like to say what worked in my case in case I search this again.
For me, I had to have the syntax like:
cbsa.SetAttributeFilter('"NAME" = \'Chicago-Naperville-Elgin\'') # I didn't test multiple values
where the referenced page of the accepted answer says:
<delimited identifier> ::= <double quote> <delimited identifier body> <double quote>
<character string literal> ::= <quote> [ <character representation> ... ] <quote>
It may be that there has been an update to ogr changing this since '17.

what is the workaround for QString.contains() method for pyqt4+python3?

I have been converting a Qt/C++ widget code into PyQt4+Python3. I have a QFileSystemModel defined and the items it returns have "data" with the filename as type "str". (This is of type QString in Qt/C++ or Python2x).
I have to search for a filter based on QRegEx. In Qt/C++ and Python2x this is achieved by QString.contains(QRegEx).
I found that QString has been removed in Python3. Since now in Python3 everything is now of type "str", how can i implement the old method QString.contains(QRegEx)?
Thanks,
Kodanda
For string mainipulation, Python is generally superior to anything Qt has to offer (particularly when it comes to regular expressions).
But if you must use QRegExp:
# test whether string contains pattern
if QRegExp(pattern).indexIn(string) != -1:
print('found')
Python:
if re.search(pattern, string):
print('found')

Resources