emacs smart-tab with yasnippets - ruby-on-rails

I'm trying to get tab complete within all open buffers and yasnippet to both work with the tab key. At the moment I can have one or the other. The following code is how I'm handling the yasnippet expand, but as I'm not a lisp programmer I cannot see the mistake here.
If it cannot expand the snippet I would like it to try and expand from the buffer.
;; Auto complete settings / tab settings
;; http://emacsblog.org/2007/03/12/tab-completion-everywhere/ <-- in the comments
(global-set-key [(tab)] 'smart-tab)
(defun smart-tab ()
"This smart tab is minibuffer compliant: it acts as usual in
the minibuffer. Else, if mark is active, indents region. Else if
point is at the end of a symbol, expands it. Else indents the
current line."
(interactive)
(if (minibufferp)
(unless (minibuffer-complete)
(dabbrev-expand nil))
(if mark-active
(indent-region (region-beginning)
(region-end))
(if (looking-at "\\_>")
(unless (yas/expand)
(dabbrev-expand nil))
(indent-for-tab-command)))))

First, I try to understand what the code does, and what you would like it does.
Your code
first checks if the point is in the minibuffer.
If so, then it tries to complete the minibuffer
if (in minibuffer) cannot complete it, it calls dabbrev-expand
else if the point is not in minibuffer
if some region is marked , it indents the region.
if no mark is active, it checks to see if the point is at the end of some word
if so, it checks is yasnippet can expand.
if yas cannot expand, it calls dabbrev-expand
if not, it tries to indent the current line
This is what your code does.
Your code fails due to yas/expand. This command does not return in case the expansion fails.
In case that this command fails, it checks the state of the variable yas/fallback-behavior. If this variable has the value call-other-command, as in your case, the failed yas expansion calls the command bound to the key kept in the variable yas/trigger-key.
In your case , this variable is TAB.
So: You are at the end of the word, You press TAB to complete it, this triggers the interactive smart-tab, which calls yas/expand which in case it fails to expand calls the bound function of TAB, and here is the infinite loop.
The Solution for your problem is to temporaily bound nil to yas/fallback-behavior in this smart-tab function.
Here is how to fix it:
(if (looking-at "\\_>")
(let ((yas/fallback-behavior nil))
(unless (yas/expand)
(dabbrev-expand nil)))
(indent-for-tab-command))

Related

Using zref-savepos within \newenvironment

I've defined
\usepackage{zref-savepos}
\newcommand*{\curypos}[1]{%
\zsaveposy{#1}%
\zposy{#1}sp = %
\the\dimexpr\zposy{#1}sp\relax%
}
and that seems to work fine. Saying \curypos{some_label} reports the y position on the page, just as expected.
Now do
\newenvironment{mytest}[2]
{\write\myfile{\curypos{#1} #2}%
}
{% Do nothing to close out the environment.
}
\begin{mytest}{first}{second}
pointless blather
\end{mytest}
The contents of \myfile do not show the y-position on the page. Instead they show
\zsaveposy {first}0sp = 0.0pt second
For some reason, first is not passing through as an argument to \curypos.
I'm guessing that this is some form of fragility, so I tried using \protect in various places and declaring \curypos with \DeclareRobustCommand, but none of them work.
This isn't a complete answer, but I think the problem is due to the fact that the call to \zsaveposy is made from within a \write. My guess is that these write operations are treated as though they take place at the top (or bottom?) of the page so that the position is always (0,0). Breaking up the definition of the environment command as follows works.
\newenvironment{intfig}[2]
{\zsaveposy{#1}%
\write\myfile{\the\dimexpr\zposy{#1} #2 }%
}
{% nothing
}

IsTradeAllowed not returning what I would expect

Please see the script below:
void OnStart()
{
Alert(IsTradeAllowed()); //alert 1
Alert(IsTradeAllowed(NULL, TimeGMT())); //alert 2
Alert(IsTradeAllowed(Symbol(), TimeGMT())); //alert 3
Alert(IsTradeAllowed("GBPUSD", TimeGMT())); //alert 4
}
This returns:
true //for alert 1
true //for alert 2
false //for alert 3
false //for alert 4
As alert 2 returns: true, then I would expect alert 3 and alert 4 to return true.
I have tried running the code at multiple times of the day on weekdays. The code returns the same result at weekends. I have also tried putting the code in a script and an EA. Every time I get the same result. Is there an explanation for this? I have tried what is suggested here: https://www.mql5.com/en/docs/runtime/tradepermission
Symbol() returns: "GBPUSD". Each alert should return true in my mind, however this does not appear to be the case here. Incidentally I have notices that Symbol() returns the symbol at the top of the demo account watchlist if the script is run inside MetaEditor, however it returns the symbol displayed on the chart if run inside the demo account.
The broker is Oanda.
Update 04/03/21 at 19:55
I have now discovered that if I right click on the Market Watch and select: show all, then more symbols appear. I can then see that some symbols are greyed out and some symbols are not. The symbols that are not greyed out e.g. USDGBP-g return what I would expect when running the program above i.e. alert 1-alert 4 =true. The symbols that are greyed out e.g. USDGBP returns true; true; false; false in the program above. I now have two questions:
Why does: IsTradeAllowed(NULL, TimeGMT()); //alert 2 return true for symbols that are greyed out?
What does -g mean in GBPUSD-g?
IsTradeAllowed checks if the Expert Advisor is allowed to trade and trading context is not busy.
The version of the function without any arguments will check if the EA has been applied with the correct permissions ("Allow live trading" ticked and "AutoTrading" enabled).
The second form of the function:
bool IsTradeAllowed(const string symbol, datetime tested_time);
checks if the EA would be allowed to trade according to the specifications for the chart selected (to view this, from the Market Watch window right click a symbol, from the menu that pops up select "Specification").
For example
IsTradeAllowed(Symbol(), D'2021.03.06 12:00');
would check if the current symbol can be traded this coming Saturday (which should be false).
If you are getting undesirable results you should check that your broker has set the "Specifications" correctly.
EDIT
I've tested the command in OANDA which is the broker you are using and the command functions as expected.
NULL is not valid for a Symbol and its use makes the command function in its first form (ie timedate is ignored).
I would suggest rather than use Alerts to examine output, try the following.
string cmnt;
cmnt=StringConcatenate("Alert 1: ",IsTradeAllowed());
cmnt=StringConcatenate(cmnt+"\r\n","Alert 2: ",IsTradeAllowed(NULL, TimeGMT()));
cmnt=StringConcatenate(cmnt+"\r\n","Alert 3: ",IsTradeAllowed(Symbol(), TimeGMT()));
cmnt=StringConcatenate(cmnt+"\r\n","Alert 4: ",IsTradeAllowed("GBPUSD", TimeGMT()));
Comment(cmnt);
I tried your script in my ICMarkets version of MetaTrader4. With disabled auto trading i get result:
When I set auto trading to enable using Ctrl+E shortcut, in all cases script return true.
I recommend you to try this script on another account or different broker. If this will help, you should communicate with your broker about this issue. The last option is a reinstall MetaTrader to make sure, that all config files are correct.

Lua - table won't insert from function

I have a Lua function where I build a table of value and attempt to add it to a global table with a named key.
The key name is pulled from the function arguments. Basically, it's a filename, and I'm pairing it up with data about the file.
Unfortunately, the global table always comes back nil. Here's my code: (let me know if you need to see more)
(Commented parts are other attempts, although many attempts have been deleted already)
Animator = Class{}
function Animator:init(atlasfile, stringatlasfriendlyname, totalanimationstates, numberofframesperstate, booleanstatictilesize)
-- Define the Animator's operation mode. Either static tile size or variable.
if booleanstatictilesize ~= false then
self.isTileSizeStatic = true
else
self.isTileSizeStatic = false
end
-- Define the total animation states (walking left, walking right, up down, etc.)
-- And then the total frames per state.
self.numAnimationStates = totalanimationstates or 1
self.numAnimationFrames = numberofframesperstate or 2
-- Assign the actual atlas file and give it a programmer-friendly name.
self.atlasname = stringatlasfriendlyname or removeFileExtension(atlasfile, 'animation')
generateAnimationQuads(atlasfile, self.atlasname, self.numAnimationStates, self.numAnimationFrames)
end
function generateAnimationQuads(atlasfile, atlasfriendlyname, states, frames)
spriteWidthDivider = atlasfile:getWidth() / frames
spriteHeightDivider = atlasfile:getHeight() / states
animationQuadArray = generateQuads(atlasfile, spriteWidthDivider, spriteHeightDivider)
animationSetValues = {atlasarray = animationQuadArray, width = spriteWidthDivider, height = spriteHeightDivider}
--gAnimationSets[#gAnimationSets+1] = atlasfriendlyname
gAnimationSets[atlasfriendlyname] = animationSetValues
--table.insert(gAnimationSets, atlasfriendlyname)
end
Note: when using print(atlasfriendlyname) and print(animationSetValues), neither are empty or nil. They both contain values.
For some reason, the line(s) that assign the key pair to gAnimationSets does not work.
gAnimationSets is defined a single time at the top of the program in main.lua, using
gAnimationSets = {}
Animator class is called during the init() function of a character class called Bug. And the Bug class is initialized in the init() function of StartState, which extends from BaseState, which simply defines dummy init(), enter(), update() etc. functions.
StartState is invoked in main.lua using the StateMachine class, where it is passed into StateMachine as a value of a global table declared in main.lua.
gAnimationSets is declared after the table of states and before invoking the state.
This is using the Love2D engine.
Sorry that I came here for help, I've been picking away at this for hours.
Edit: more testing.
Trying to print the animationQuadArray at the index gTextures['buganimation'] always returns nil. Huh?
Here's gTextures in Main.lua
gTextures = {
['background'] = love.graphics.newImage('graphics/background.png'),
['main'] = love.graphics.newImage('graphics/breakout.png'),
['arrows'] = love.graphics.newImage('graphics/arrows.png'),
['hearts'] = love.graphics.newImage('graphics/hearts.png'),
['particle'] = love.graphics.newImage('graphics/particle.png'),
['buganimation'] = love.graphics.newImage('graphics/buganimation.png')
}
Attempting to return gTextures['buganimation'] returns a file value as normal. It's not empty.
My brain is so fried right now I can't even remember why I came to edit this. I can't remember.
Global table in Main.lua, all other functions can't access it.
print(gTextures['buganimation']) works inside the function in question. So gTextures is absolutely accessible.
Table isn't empty. AnimationSetValues is not empty.
I'm adding second answer because both are correct in context.
I ended up switching IDE's to VS Code and now the original one works.
I was originally using Eclipse LDT with a Love2D interpreter and in that environment, my original answer is correct, but in VS Code, the original is also correct.
So Dimitry was right, they are equivalent, but something about my actual Eclipse setup was not allowing that syntax to work.
I switched to VS Code after I had another strange syntax problem with the interpreter where goto syntax was not recognized and gave a persistent error. The interpreter thought goto was the name of a variable.
So I switched, and now both things are fixed. I guess I just won't use LDT for now.
Solution: Lua syntax. Brain Fry Syndrome
I wrote:
animationSetValues = {atlasarray = animationQuadArray, width = spriteWidthDivider, height = spriteHeightDivider}
Should be:
animationSetValues = {['atlasfile']=atlasfile, ['atlasarray']=animationQuadArray, ['width']=spriteWidthDivider, ['height']=spriteHeightDivider}
Edit: I'm fully aware of how to use answers. This was posted here to reserve my spot for an answer so I could edit it later when I returned back home, which is exactly what I'm doing right now. I'll keep the old post for archival purposes.
Original:
I solved it. I apologize for not posting the solution right now. My brain is melted into gravy.
I will post it tomorrow. Just wanted to "answer" saying no need to help. Solved it.
Solution is basically, "oh it's just one of those Lua things". Wonderful. I'm having so much fun with this language - you can tell by my blank expression.
From the language without line endings or brackets, but forced print parentheses... ugh. I'm going back to C# when this class is done.

Control flow in Lua

I have a problem which i suppose must be very common and most of you would have faced it.
I have written a program in lua, say main.lua which on receiving key event should modify the coordinates and display the geometry figure.
This lua code calls reg.c, where it kind of registers.
Now in reg.c i have a function engine which receives the key pressed and passes it to the lua function responsible for key handling.
But by the time key event comes, lua code is done with the registration and exits, thus the call from engine() becomes illegal memory access leading to segmentation fault.
Also i suppose we can't have lua call hanging in reg function, and call engine function from somewhere else.
Then what should be the solution, please guide me through this.
#jacob: here is the prototype of what i am trying to achieve:
function key_handler() //this function will get the latest key pressed from some other function
{
draw.image();
draw.geometry();
...
...
while(1)
{
//draw Points until some condition goes wrong
}
}
Now, once entered into key_handler, while he is busy drawing the points unless and until the failing condition occurs, i am unable to receive key pressed till that time.
I hope this explanation is much simpler and have made my point, and will help others to understand the problem.
I am really sorry, but i am not good at expressing or making others understand.
One more thing, i ahve followed the C syntax to explain, however this is completely implemented in lua
Your code snippet is still largely non-informative (ideally one should be able to just run your code in a stock Lua interpreter and see your problem). If you're describing a Lua problem, use Lua code to describe it.
However I'm beginning to see where you want to go.
The thing you need to could do is have a coroutine that's called in your key handler, which passes an argument back to your handler:
function isContinue() --just to simulate whatever function you use getting keypresses.
-- in whatever framework you're using there will probably be a function key_pressed or the like.
print('Initialize checking function')
while true do
print('Continue looping?')
local ans = io.read():match('[yY]')
local action
if not ans then
print('Do what instead?')
action = io.read()
if action:match('kill') then -- abort keychecker.
break
end
end
coroutine.yield(ans,action)
end
print('finalizing isContinue')
return nil,'STOP' -- important to tell key_handler to quit too, else it'll be calling a dead coroutine.
end
function key_handler()
local coro = coroutine.create(isContinue)
local stat,cont,action
while true do
print'Draw point'
stat,cont,action = coroutine.resume(coro)
if not stat then
print('Coroutine errored:',cont)
elseif not cont then
print('isContinue interrupted keyhandler')
print("We'll "..action.." instead.")
break
end
end
print('finalizing key_handler')
end
key_handler()
-- type something containing y or Y to continue, all else aborts.
-- when aborting, you get asked what to do instead of continuing,
--- with "kill" being a special case.
This should be self explanatory. You should probably take a good look at Programming in Lua, chapter 9: Coroutines.
The big difficulty (well, if you're not accustomed to collaborative threading) is that a coroutine should yield itself: it's not the calling function that's in charge of returning control.
Hope this helps you.

How do you accept a string in Erlang?

I'm writing a program where the user must enter a 'yes' or 'no' value. The following is the code that will be executed when the message {createPatient,PatientName} is received.
{createPatient, PatientName} ->
Pid = spawn(patient,newPatient,[PatientName]),
register(PatientName,Pid),
io:format("*--- New Patient with name - ~w~n", [PatientName]),
Result = io:read("Yes/No> "),
{_,Input} = Result,
if(Input==yes) ->
io:format("OK")
end,
loop(PatientRecords, DoctorPatientLinks, DoctorsOnline, CurrentPatientRequests, WaitingOfflineDoctorRequests);
When executed ,the line "New Patient with name..." is displayed however the line Yes/No is not displayed and the program sort of crashes because if another message is sent, then the execution of that message will not occur. Is there a different way to solve this problem please?
There are a number of points I would like to make here:
The io:read/1 function reads a term, not just a line, so you have to terminate input with a '.' (like in the shell).
io:read/1 returns {ok,Term} or {error,Reason} or eof so you code should check for these values, for example with a case.
As #AlexeyRomanov mentioned, io:get_line/1 might be a better choice for input.
The if expression must handle all cases even the ones in which you don't want to do anything, otherwise you will get an error. This can be combined with the case testing the read value.
You spawn the function patient:newPatient/1 before you ask if the name is a new patient, this seems a little strange. What does the newpatient function do? Is it in anyway also doing io to the user which might be interfering with functions here?
The main problem seems to be work out what is being done where, and when.
This is very artificial problem. In erlang any communication is usually inter-process and exchanging strings wouldn't make any sense - you ask question in context of process A and you would like to post answer in context of process B (shell probably).
Anyways, consider asking question and waiting in receive block in order to get an answer.
When question pops out in shell, call a function which will send the answer to 'asking' process with your answer.
So:
io:format("*--- New Patient with name - ~w~n", [PatientName]),
receive
{answer, yes} -> do_something();
{answer, no} -> do_something()
end
The 'answering' function would look like that:
answer(PatientName, Answer) ->
PatientName ! {answer, Answer}.
And shell action:
$> *--- New Patient with name - User1036032
$> somemodule:answer('User1036032', yes).
It is possible to create some dialog with shell (even unix shell), but to be honest it is used so rare that I do not remember those I/O tricks with read and write. http://trapexit.com/ used to have cookbook with this stuff.
Use io:get_line("Yes/No> ") instead.

Resources