_repr_latex_ method not working anymore in Jupyter / IPython notebook - latex

I have an Expr class to represent mathematical expressions in which I defined
def _latex(self):
""":return: string LaTex formula"""
(...)
return res
def _repr_latex_(self):
return r'$%s$'%self._latex() #tried several variations of this...
#property
def latex(self):
from IPython.display import Math
return Math(self._latex())
as you can see on http://nbviewer.ipython.org/github/Goulu/Goulib/blob/master/notebook.ipynb at cell [42], latex is correctly rendered when explicitly specified by the property
but fails next cell when called though _repr_latex_ with a UnicodeDecodeError.
e2(e1)._latex() returns '\sin(3x+2)' with no unicode, so what's wrong here ?
Thanks !

well... it was partly my mistake : my Expr class inherits from my Plot class which has a _repr_svg_ method and Jupyter called this one by default instead of _repr_latex_ ...
Ok But:
the error message in Jupyter/IPython doesn't mention this
I still don't know how to select the default _repr_xxx_ method of a class

Related

Functions in Micro-python

i have a question about micro-python that how to make and call functions in micro-python or any other idea related to functions
my code throwing an error that NameError: name 'my_func' isn't defined
import time
from machine import Pin
led = Pin(2, Pin.OUT)
btn = Pin(4, Pin.IN, Pin.PULL_UP)
while True:
if not btn.value():
my_func()
while not btn():
pass
def my_func():
led(not led())
time.sleep_ms(300)
Generaly, what I do following: Imports then Functions and after that- rest of the flow
Slightly modified your code to pass LED object for function
import time
from machine import Pin
def my_func(myLed):
myLed.value(not myLed.value()) # invert boolean value
time.sleep_ms(300)
led = Pin(2, Pin.OUT)
btn = Pin(4, Pin.IN, Pin.PULL_UP)
while True:
if not btn.value():
my_func(led)
while not btn():
pass
you need to import a function before it can be called.

Auto alignment of data in Xtext

I had one custom parser rule in which I had defined all my keywords such as _self, _for, _loop etc. Because of this, if I type _s and click Ctrl+ space bar, it shows _self.But what I required is even though I type self or SE, it should auto assign as _self.Is it possible? If so, could anyone please suggest a solution for this. Thanks in advance
There are multiple things to be payed attention to
There needs to be a proposal and only one proposal. Otherwise the user has to select the prosal to be applied and no auto insert takes places
Proposals are created based on the error recovery and so you might not get the proposal you are looking for at all
so lets assume you have a grammar like
Model:
greetings+=Greeting*;
Greeting:
'_self' name=ID '!';
and a model file like
SE
Then the error recovery will work fine an a proposal of "_self" will be added to the list of proposals
Proposals are Filtered based on the current prefix in the model. that would be the place you could start customizing.
e.g. this very naive impl
import org.eclipse.xtext.ui.editor.contentassist.FQNPrefixMatcher;
public class MyPrefixMatcher extends FQNPrefixMatcher {
#Override
public boolean isCandidateMatchingPrefix(String name, String prefix) {
return super.isCandidateMatchingPrefix(name, prefix) || super.isCandidateMatchingPrefix(name, "_" + prefix);
}
}
and dont forget to bind
import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor
import org.eclipse.xtext.ui.editor.contentassist.PrefixMatcher
import org.xtext.example.mydsl4.ui.contentassist.MyPrefixMatcher
#FinalFieldsConstructor
class MyDslUiModule extends AbstractMyDslUiModule {
override Class<? extends PrefixMatcher> bindPrefixMatcher() {
return MyPrefixMatcher;
}
}
There is another feature that does not use proposals at all but the text that is actually typed and if it recognizes something then can replace it with something else. this feature is called "Auto Edit". The extension point in xtext for this is IAutoEditStrategy / AbstractEditStrategyProvider

Creating one parameter for multiple DB columns in ActiveRecord Rails [duplicate]

Ruby setters—whether created by (c)attr_accessor or manually—seem to be the only methods that need self. qualification when accessed within the class itself. This seems to put Ruby alone the world of languages:
All methods need self/this (like Perl, and I think Javascript)
No methods require self/this is (C#, Java)
Only setters need self/this (Ruby?)
The best comparison is C# vs Ruby, because both languages support accessor methods which work syntactically just like class instance variables: foo.x = y, y = foo.x . C# calls them properties.
Here's a simple example; the same program in Ruby then C#:
class A
def qwerty; #q; end # manual getter
def qwerty=(value); #q = value; end # manual setter, but attr_accessor is same
def asdf; self.qwerty = 4; end # "self." is necessary in ruby?
def xxx; asdf; end # we can invoke nonsetters w/o "self."
def dump; puts "qwerty = #{qwerty}"; end
end
a = A.new
a.xxx
a.dump
take away the self.qwerty =() and it fails (Ruby 1.8.6 on Linux & OS X). Now C#:
using System;
public class A {
public A() {}
int q;
public int qwerty {
get { return q; }
set { q = value; }
}
public void asdf() { qwerty = 4; } // C# setters work w/o "this."
public void xxx() { asdf(); } // are just like other methods
public void dump() { Console.WriteLine("qwerty = {0}", qwerty); }
}
public class Test {
public static void Main() {
A a = new A();
a.xxx();
a.dump();
}
}
Question: Is this true? Are there other occasions besides setters where self is necessary? I.e., are there other occasions where a Ruby method cannot be invoked without self?
There are certainly lots of cases where self becomes necessary. This is not unique to Ruby, just to be clear:
using System;
public class A {
public A() {}
public int test { get { return 4; }}
public int useVariable() {
int test = 5;
return test;
}
public int useMethod() {
int test = 5;
return this.test;
}
}
public class Test {
public static void Main() {
A a = new A();
Console.WriteLine("{0}", a.useVariable()); // prints 5
Console.WriteLine("{0}", a.useMethod()); // prints 4
}
}
Same ambiguity is resolved in same way. But while subtle I'm asking about the case where
A method has been defined, and
No local variable has been defined, and
we encounter
qwerty = 4
which is ambiguous—is this a method invocation or an new local variable assignment?
#Mike Stone
Hi! I understand and appreciate the points you've made and your
example was great. Believe me when I say, if I had enough reputation,
I'd vote up your response. Yet we still disagree:
on a matter of semantics, and
on a central point of fact
First I claim, not without irony, we're having a semantic debate about the
meaning of 'ambiguity'.
When it comes to parsing and programming language semantics (the subject
of this question), surely you would admit a broad spectrum of the notion
'ambiguity'. Let's just adopt some random notation:
ambiguous: lexical ambiguity (lex must 'look ahead')
Ambiguous: grammatical ambiguity (yacc must defer to parse-tree analysis)
AMBIGUOUS: ambiguity knowing everything at the moment of execution
(and there's junk between 2-3 too). All these categories are resolved by
gathering more contextual info, looking more and more globally. So when you
say,
"qwerty = 4" is UNAMBIGUOUS in C#
when there is no variable defined...
I couldn't agree more. But by the same token, I'm saying
"qwerty = 4" is un-Ambiguous in ruby
(as it now exists)
"qwerty = 4" is Ambiguous in C#
And we're not yet contradicting each other. Finally, here's where we really
disagree: Either ruby could or could not be implemented without any further
language constructs such that,
For "qwerty = 4," ruby UNAMBIGUOUSLY
invokes an existing setter if there
is no local variable defined
You say no. I say yes; another ruby could exist which behaves exactly like
the current in every respect, except "qwerty = 4" defines a new
variable when no setter and no local exists, it invokes the setter if one
exists, and it assigns to the local if one exists. I fully accept that I
could be wrong. In fact, a reason why I might be wrong would be interesting.
Let me explain.
Imagine you are writing a new OO language with accessor methods looking
like instances vars (like ruby & C#). You'd probably start with
conceptual grammars something like:
var = expr // assignment
method = expr // setter method invocation
But the parser-compiler (not even the runtime) will puke, because even after
all the input is grokked there's no way to know which grammar is pertinent.
You're faced which a classic choice. I can't be sure of the details, but
basically ruby does this:
var = expr // assignment (new or existing)
// method = expr, disallow setter method invocation without .
that is why it's un-Ambiguous, while and C# does this:
symbol = expr // push 'symbol=' onto parse tree and decide later
// if local variable is def'd somewhere in scope: assignment
// else if a setter is def'd in scope: invocation
For C#, 'later' is still at compile time.
I'm sure ruby could do the same, but 'later' would have to be at runtime, because
as ben points out you don't know until the statement is executed which case
applies.
My question was never intended to mean "do I really need the 'self.'?" or "what
potential ambiguity is being avoided?" Rather I wanted to know why was this
particular choice made? Maybe it's not performance. Maybe it just got the job
done, or it was considered best to always allow a 1-liner local to override a
method (a pretty rare case requirement) ...
But I'm sort of suggesting that the most dynamical language might be the one which
postpones this decision the longest, and chooses semantics based on the most contextual
info: so if you have no local and you defined a setter, it would use the setter. Isn't
this why we like ruby, smalltalk, objc, because method invocation is decided at runtime,
offering maximum expressiveness?
Well, I think the reason this is the case is because qwerty = 4 is ambiguous—are you defining a new variable called qwerty or calling the setter? Ruby resolves this ambiguity by saying it will create a new variable, thus the self. is required.
Here is another case where you need self.:
class A
def test
4
end
def use_variable
test = 5
test
end
def use_method
test = 5
self.test
end
end
a = A.new
a.use_variable # returns 5
a.use_method # returns 4
As you can see, the access to test is ambiguous, so the self. is required.
Also, this is why the C# example is actually not a good comparison, because you define variables in a way that is unambiguous from using the setter. If you had defined a variable in C# that was the same name as the accessor, you would need to qualify calls to the accessor with this., just like the Ruby case.
The important thing to remember here is that Ruby methods can be (un)defined at any point, so to intelligently resolve the ambiguity, every assignment would need to run code to check whether there is a method with the assigned-to name at the time of assignment.
Because otherwise it would be impossible to set local variables at all inside of methods. variable = some_value is ambiguous. For example:
class ExampleClass
attr_reader :last_set
def method_missing(name, *args)
if name.to_s =~ /=$/
#last_set = args.first
else
super
end
end
def some_method
some_variable = 5 # Set a local variable? Or call method_missing?
puts some_variable
end
end
If self wasn't required for setters, some_method would raise NameError: undefined local variable or method 'some_variable'. As-is though, the method works as intended:
example = ExampleClass.new
example.blah = 'Some text'
example.last_set #=> "Some text"
example.some_method # prints "5"
example.last_set #=> "Some text"

Creating a capitalize Method in Dart

I am trying to create a method in dart but have run into a wall. I was looking at how .toUpperCase(); and .toLowerCase(); were done. The method that I am trying to create is .capitalize();
I would like to call this method like this
String hello = "WORLD".capitalize(); //World
Here is the code I have so far
String capitalize() {
return this.codeUnitAt(0).toUpperCase() + this.substring(1).toLowerCase();
}
When running String hello = "WORLD".capitalize(); I get the following error
[38;5;124m[2015-6-4 11:37:13.011] Class 'String' has no instance method 'capitalize'.
NoSuchMethodError: method not found: 'capitalize'
Receiver: "WORLD"
Arguments: [][0m
I know i can call a function like String capitalize(String s) => s[0].toUpperCase() + s.substring(1);
But would much rather keep string Manipulation calls the same.
Thanks and I appreciate any help:)
You cannot extend the String class like you want. Just use it like this:
capitalize("WORLD");
Yes, not like JS, you can't just change any class in Dart. You can extend it only. E.g. you can create MyString class with capitalize method. But I don't think you want it. Just make some StringUtils.dart library with method capitalize
Since dart is more common now, there are a lot more packages available at pub.dartlang.org.
I found a nice dart package for different operation on strings. It also contains a capitalize method.
https://pub.dartlang.org/packages/basic_utils
Simply add the dependency :
dependencies:
basic_utils: ^1.0.3
Usage :
StringUtils.capitalize("helloworld"); // helloworld => Helloworld
It also contains other usefull methods :
camelCaseToUpperUnderscore
camelCaseToLowerUnderscore
isAscii
isNullOrEmpty ...
if this is still a problem, you can simple use this dependecy:
dependencies:
text_tools: ^0.0.2
Is simple to use, here is an example:
//This will put the first letter in UpperCase, will print 'Name'
print(TextTools.toUppercaseFirstLetter(text: 'name'));

Getting value of a Numeric Property in kivy

I am trying to use a NumericProperty but getting Type errors when trying to use it as a value
My code looks like this
from kivy.properties import NumericProperty
from kivy.uix.widget import Widget
class Segment(Widget):
def __init__(self, segments):
super(Segment, self).__init__()
self.segments = NumericPropery(segments)
def build(self):
for i in range(0, self.segments):
# Do something
I get an error :
for i in range(0, self.segments):
TypeError: range() integer end argument expected, got kivy.properties.NumericProperty.
so I tried using self.segments.get() instead, but then I got this error
TypeError: get() takes exactly one argument (0 given)
apperently the get function expects <kivy._event.EventDispatcher> object argument
Any idea how to get around this?
I had a similar problem with this code ...
class GameModel(object):
some_number = NumericProperty(1)
def __init__(self):
self.some_number = 2
... which raised the error:
TypeError: Argument 'obj' has incorrect type (expected kivy._event.EventDispatcher, got GameModel)
I did declare the property at class level though. In my case the problem was that the class itself was not derived from a Kivy Widget class or - as stated in the error message - from an EventDispatcher Object
Deriving from EventDispatcher fixed my problem:
class GameModel(EventDispatcher):
Hope this is helpful for someone else some day ;-)
You have to declare properties at class level.
class Segment(Widget):
segments = NumericProperty()
This will give the correct behaviour. The problem is that properties do their own management of per-instance values and interacting with the eventloop etc.. If you don't declare them at class level, they don't get to do this, so your functions only see the NumericProperty itself (which is your problem).

Resources