Unexported function aliases in module - package

Decades of research & software lead to many synonyms for functions that users could expect to "just work" in my module. There are roughly 80 aliases I want to support, yet not export. For example, imagine :bar, :qux, "bar", "qux" to be aliases for Base.sqrt as an input to struct Bar.
Question: What is the recommended way to create unexported aliases for functions in a module?
I have read the module documentation and this SO question question and searched codebases on GitHub. Below are my attemps, Bar2 is faster, but goes against "avoid globals in the namespace".
# approach 1: add to namespace, but don't export
module Foo1
struct Bar1 fun::Function end
Bar1(fun::Union{Symbol, String}) = Bar1(getfield(#__MODULE__, Symbol(fun)))
const baz = const qux = √ # ...
export Bar1
end
# approach 2: package internal dictionary, not in namespace
module Foo2
struct Bar2 fun::Function end
Bar2(fun::Union{Symbol, String}) = Bar2(alias[Symbol(fun)])
const alias = Base.ImmutableDict(:baz => √, :qux => √) #...
export Bar2
end
using .Foo1, .Foo2
Bar1(:baz).fun == Bar1("qux").fun == Bar2(:baz).fun == Bar2("qux").fun # true

Related

Using enums in react const

I need to map enum values to 1 variable and then call the variable and check if that enum was present or not.
render() {
const {
id,
name,
features} = this.props;
}
Features would be the variable that needs to be mapped according to which enums are coming in. I would get something similar from the API:
{"id":"111", "name":"jack", "features":["MOUNTAIN", "HILL"]}
So there would be a total of 4 different features : MOUNTAIN, HILL, LAKE, FISH.
Then when needed I can check:
if(features.mountain)
//do stuff
If you like to check if a given property from your enum (for example "MOUNTAIN") is included in the features array returned from the api you can use the Array.prototype.includes() method:
if(featuresArrayfromApi.includes('MOUNTAIN'){
//do stuff
}
If you would like to check if the features returned from the api include one or more of the properties in your features enum you can combine includes with Array.prototype.some().
For example, in Typescript you would write it like this:
enum Features { MOUNTAIN, HILL, LAKE, FISH }
if(Object.keys(Features)
.some(feature => featuresFromApi.includes(feature))){
// do stuff
}
Edit
The features key from the api data should be mapped like any other key(id, name) - just instead of holding 1 value it holds an array. Then you can use the validations suggested above in an if clause. For example:
const data = [
{"id":"111", "name":"jack", "features":["MOUNTAIN", "HILL"]},
{"id":"222", "name":"john", "features":["FISH", "HILL", "LAKE"]}
{"id":"333", "name":"joe", "features":["LAKE", "HILL", "FISH"]}
]
data.map(record =>{
console.log(record.id);
console.log(record.name);
if (record.features.includes('MOUNTAIN'){
// do stuff
}
})
Also, bear in mind that enum is a Typescript symbol which isn't available in Javascript, so in case you are not using Typescript you can just declare it like this and it would work the same:
const Features = {
MOUNTAIN: "MOUNTAIN",
HILL: "HILL",
LAKE, "LAKE",
FISH: "FISH"
}

How to manipulate 3 DataStream in on Flink job?

We have 3 java pojos,
class Foo{
int id;
String name;
List<Bar1> list1;
List<Bar2> list2;
}
class Bar1{
int id;
String field_x;
String field_y;
}
class Bar2{
int id;
String field_a;
String field_b;
}
And we have 3 DataStreams in our Flink job,
class Test{
public static void main(...){
DataStream<Foo> ds1 = ...;
DataStream<Bar1> ds2 = ...;
DataStream<Bar2> ds3 = ...;
}
}
For each id, there will be only one Foo object, while Bar1 and Bar2 object could be multiple.
What we want to do is, for each Foo in ds1, find all Bar1 with the same id in ds2 and put them into list1, find all Bar2 with the same id in ds3 and put them into list2.
What is the best way to go?
Flink's DataStream operators support up to two input streams.
There are two common ways to implement operations on three streams:
with two binary operations. This is very simple in your case since Bar1 and Bar2 are not related to each other. This would look roughly as follows:
DataStream<Foo> withList1 = ds1
.connect(ds2).keyBy("id", "id")
.process(
// your processing logic
new CoProcessFunction<Foo, Bar1, Foo>(){...});
DataStream<Foo> withList1AndList2 = withList1
.connect(ds3).keyBy("id", "id")
.process(
// your processing logic
new CoProcessFunction<Foo, Bar2, Foo>(){...});
by unioning all three streams into a single stream with a common data type (for example a POJO with three fields foo, bar1, and bar2 of which only one field is used and using an operator with a single input to process the unioned stream.
// map Foo to CommonType
DataStream<CommonType> common1 = ds1.map(new MapFunction<Foo, CommonType>(){...});
// map Bar1 to CommonType
DataStream<CommonType> common2 = ds2.map(new MapFunction<Bar1, CommonType>(){...});
// map Bar2 to CommonType
DataStream<CommonType> common3 = ds3.map(new MapFunction<Bar2, CommonType>(){...});
DataStream<Foo> withList1AndList2 = ds1.union(ds2, ds3)
.keyBy("id")
.process(
// your processing logic
new KeyedProcessFunction<CommonType, Foo>(){...});
You can also just union ds2 and ds3 and use a binary operator.
The bigger problem might be to identify when all Bar1 and Bar2 events were received such that you can emit a result. Again, there a few options (depending on your use case).
if Foo knows for how many Bar1 and Bar2 it needs to wait, the solution is obvious.
if Foo does not know for how many events to wait, you can try to send a notification that signals that the last Bar1 or Bar2 was sent.
you can also work with a time out if you know that all Bar1 or Bar2 should arrive within x seconds/minutes/etc.

Maya Python static class function scope

I have some trouble getting my static class to work. There is something I am missing about the scope of functions within a class. If called the script gives me following error:
NameError: global name 'disableCostumFrames' is not defined #
import maya.cmds as cmds
from functools import partial
class Blast:
def createWindow():
# Todo:
# hanldes the gui for the user
windowID = 'window'
if cmds.window(windowID, exists = True):
cmds.deleteUI('window')
window = cmds.window(windowID, title="Blast", iconName='Blast', widthHeight=(400, 200) )
cmds.frameLayout( label='')
cmds.rowColumnLayout( numberOfColumns=4, columnWidth=[(1, 100),(3, 100)] )
cmds.text( label='Start: ' )
global Blast_startFrame
Blast_startFrame = cmds.textField( enable = False)
cmds.text( label=' End: ' )
global Blast_endFrame
Blast_endFrame = cmds.textField( enable = False)
cmds.setParent('..')
cmds.rowColumnLayout( numberOfColumns=2, columnWidth=[(1, 100), (2, 100)] )
cmds.radioCollection()
#cmds.radioButton( label='Full', select = True, onCommand= partial(disableCostumFrames, Blast_startFrame, Blast_endFrame ) )
#cmds.radioButton( label='Costum', onCommand= partial(enableCostumFrames, Blast_startFrame, Blast_endFrame ) )
cmds.setParent('..')
cmds.rowColumnLayout( numberOfColumns=1, columnWidth=[(1, 400), (2, 100)] )
cmds.button( label='Playblast' ,command= 'createPlayblast')
cmds.setParent('..')
cmds.showWindow( window )
return Blast_startFrame, Blast_endFrame
def main():
createWindow()
def enableCostumFrames(Blast_startFrame, Blast_endFrame, *args):
cmds.textField(Blast_startFrame, edit=True, enable=True)
cmds.textField(Blast_endFrame, edit=True, enable=True)
def disableCostumFrames(Blast_startFrame, Blast_endFrame, *args):
cmds.textField(Blast_startFrame, edit=True, text="", enable=False)
cmds.textField(Blast_endFrame, edit=True, text="", enable=False)
How do I need to define these functions within the class? I am calling the module like that:
import sys
Dir = 'c:/Blast'
if Dir not in sys.path:
sys.path.append(Dir)
try: reload(Blast_v011)
except: import Blast_v011
Blast_v011.Blast()
maybe iam doing something wrong on this side? Appreciated any help.
In this case you need to add a self reference to all of the methods in your class. The usual python class looks like this:
class MyClass(object):
def __init__(self):
self.variable = 123
def some_method(self):
print "my variable = ", self.variable
def some_other_method(self):
if self.variable > 1:
self.some_method()
The self reference in the member functions is how you get at class member variables and other functions -- it's python's way of referring to what other languages call this.
Instance methods can only be called on an instance (it's the instance that gets passed in as self). You can make a method that is called on the class itself -- rather than any particular instance of the class -- using the #classmethod decorator. Classmethods also take an argument, but instead of self it's a reference to the class. You use it the same way to get variables defined at the class level, which are shared by all copies of the class:
class HasShared(object):
shared = 99
#classmethod
def a_class_method(cls):
print cls.shared
(You can mix and match class and instance methods in the same class).
You can also make static methods using the #staticmethod decorator. These don't get a default argument at all:
class NotPythonic(object):
#staticmethod
def needs_no_args():
print "call me as NotPythonic.needs_no_args()"
In Python we tend to avoid this formula, since you can get a static method by just creating a function in a module without making a class to hold them. For the example code you posted, I'd probably just make a conventional class using instance methods, since your functions need the names of the gui widgets to be able to actually ask them questions.

Julia: How can I explore all the variables of file A into file B?

I have a couple of questions regarding Julia. I did some online digging but couldn't find any answer. If I have a file nameA.jl which has a whole lot of variables (for example, physical constants such as a mass of the proton), how can I easily export/call all those variables when I need to use in another file (i.e., nameB.jl).
Second, what is the best way to create some sort of "global" variable through "class" (I know Julia does not have the class concept similar to Python) or another mean, so I can access easily to any other file in the project and modify as I need.
I did try to get these answers from google but couldn't find any help.
Thank you
To your first question:
PhysicalConstants.jl
module PhysicalConstants
export fine_structure_constant, proton_electron_massratio
const fine_structure_constant = 7.2973525664e-3
const proton_electron_massratio = 1836.15267247
end # module
UsePhysicalConstants.jl
importall PhysicalConstants
this = fine_structure_constant * proton_electron_massratio
# 13.399053416751173
As I understand your second question:
ChangeableValues.jl
module ChangeableValues
export changeable_value, change_value, value
type Changeable{T}
value::T
end
typeof_value{T}(x::Changeable{T}) = T
value{T}(x::Changeable{T}) = x.value
# changeable_value is const for speed
# changeable_value.value is not const
const changeable_value = Changeable(0)
function change_value{T}(new_value::T)
if T == typeof_value(changeable_value)
changeable_value.value = new_value
else
throw(TypeError())
end
return nothing
end
end # module
UseChangeableValue.jl
import ChangeableValues: changeable_value, change_value, value
println("value = ", value(changeable_value)) # 0
change_value(1)
println("value = ", value(changeable_value)) # 1
change_value(2)
println("value = ", value(changeable_value)) # 2
# it remains 2 when imported elsewhere until it is changed again

How to use Slick's mapped tables with foreign keys?

I'm struggling with Slick's lifted embedding and mapped tables. The API feels strange to me, maybe just because it is structured in a way that's unfamiliar to me.
I want to build a Task/Todo-List. There are two entities:
Task: Each task has a an optional reference to the next task. That way a linked list is build. The intention is that the user can order the tasks by his priority. This order is represented by the references from task to task.
TaskList: Represents a TaskList with a label and a reference to the first Task of the list.
case class Task(id: Option[Long], title: String, nextTask: Option[Task])
case class TaskList(label: String, firstTask: Option[Task])
Now I tried to write a data access object (DAO) for these two entities.
import scala.slick.driver.H2Driver.simple._
import slick.lifted.MappedTypeMapper
implicit val session: Session = Database.threadLocalSession
val queryById = Tasks.createFinderBy( t => t.id )
def task(id: Long): Option[Task] = queryById(id).firstOption
private object Tasks extends Table[Task]("TASKS") {
def id = column[Long]("ID", O.PrimaryKey, O.AutoInc)
def title = column[String]("TITLE")
def nextTaskId = column[Option[Long]]("NEXT_TASK_ID")
def nextTask = foreignKey("NEXT_TASK_FK", nextTaskId, Tasks)(_.id)
def * = id ~ title ~ nextTask <> (Task, Task.unapply _)
}
private object TaskLists extends Table[TaskList]("TASKLISTS") {
def label = column[String]("LABEL", O.PrimaryKey)
def firstTaskId = column[Option[Long]]("FIRST_TASK_ID")
def firstTask = foreignKey("FIRST_TASK_FK", firstTaskId, Tasks)(_.id)
def * = label ~ firstTask <> (Task, Task.unapply _)
}
Unfortunately it does not compile. The problems are in the * projection of both tables at nextTask respective firstTask.
could not find implicit value for evidence parameter of type
scala.slick.lifted.TypeMapper[scala.slick.lifted.ForeignKeyQuery[SlickTaskRepository.this.Tasks.type,justf0rfun.bookmark.model.Task]]
could not find implicit value for evidence parameter of type scala.slick.lifted.TypeMapper[scala.slick.lifted.ForeignKeyQuery[SlickTaskRepository.this.Tasks.type,justf0rfun.bookmark.model.Task]]
I tried to solve that with the following TypeMapper but that does not compile, too.
implicit val taskMapper = MappedTypeMapper.base[Option[Long], Option[Task]](
option => option match {
case Some(id) => task(id)
case _ => None
},
option => option match {
case Some(task) => task.id
case _ => None
})
could not find implicit value for parameter tm: scala.slick.lifted.TypeMapper[Option[justf0rfun.bookmark.model.Task]]
not enough arguments for method base: (implicit tm: scala.slick.lifted.TypeMapper[Option[justf0rfun.bookmark.model.Task]])scala.slick.lifted.BaseTypeMapper[Option[Long]]. Unspecified value parameter tm.
Main question: How to use Slick's lifted embedding and mapped tables the right way? How to I get this to work?
Thanks in advance.
The short answer is: Use ids instead of object references and use Slick queries to dereference ids. You can put the queries into methods for re-use.
That would make your case classes look like this:
case class Task(id: Option[Long], title: String, nextTaskId: Option[Long])
case class TaskList(label: String, firstTaskId: Option[Long])
I'll publish an article about this topic at some point and link it here.

Resources