Can't get CoffeeScript to recognize a function in a js file - coffeescript

I am writing a simple app in Coffeescript to control a Philips Hue light. I have included this module into my project. The below code seems to work fine up until I try to set the color of the lights using setLightState. The compiler says the function isn't a function. I don't quite understand why it doesn't recognize the function.
# Connect with Philips Hue bridge
jsHue = require 'jshue'
hue = jsHue()
# Get the IP address of any bridges on the network
hueBridgeIPAddress = hue.discover().then((bridges) =>
if bridges.length is 0
console.log 'No bridges found. :('
else
(b.internalipaddress for b in bridges)
).catch((e) => console.log 'Error finding bridges', e)
if hueBridgeIPAddress.length isnt 0 # if there is at least 1 bridge
bridge = hue.bridge(hueBridgeIPAddress[0]) #get the first bridge in the list
# Create a user on that bridge (may need to press the reset button on the bridge before starting the tech buck)
user = bridge.createUser('myApp#testdevice').then((data) =>
username = data[0].success.username
console.log 'New username:', username
bridge.user(username)
)
if user?
#assuming a user was sucessfully created set the lighting to white
user.setLightState(1, {on:true, sat:0, bri:100, hue:65280}).then((data) =>
# process response data, do other things
)

As you can see on the github page of the jshue lib, bridge.createUser does not directly return a user object.
Instead the example code sets the user variable inside the then function of the returned promise:
bridge.createUser('myApp#testdevice').then(data => {
// extract bridge-generated username from returned data
var username = data[0].success.username;
// instantiate user object with username
var user = bridge.user(username);
user.setLightState( .... )
});
It can be expected that - using this approach - the user variable will be set correctly and user.setLightState will be defined.
A self-contained example:
Take this Codepen for example:
url = "https://api.ipify.org?format=json"
outside = axios.get(url).then (response) =>
inside = response.data.ip
console.log "inside: #{inside}"
inside
console.log "outside: #{outside}"
The console output is
outside: [object Promise]
inside: 178.19.212.102
You can see that:
the outside log is first and is a Promise object
the inside log comes last and contains the actual object from the Ajax call (in this case your IP)
the then function implicitly returning inside does not change anything

Related

Form Gathering Info from Two Other Forms

I have a form that creates a New Work Order. I want to be able to pull the ClientID from the New Client Form or the Main Menu, whichever is open. However I am not getting the desired results:
I have used =IIf(IsNull(Forms![New Client]![txtClientID]), Forms![Main Menu]![txtClientID], Forms![New Client]![txtClientID]) in the Default Value of the Control on the New Work Order Form. I get the correct ID when I go to the form from New Client, but a #Name error when I try to access it from the Main Menu.
What can I do to make it work?
You need to check if the form is loaded, for example (you need to add your own error traps):
Function IsLoaded(ByVal strFormName As String) As Boolean
Const conObjStateClosed = 0
Const conDesignView = 0
If SysCmd(acSysCmdGetObjectState, acForm, strFormName) <> conObjStateClosed Then
If Forms(strFormName).CurrentView <> conDesignView Then
IsLoaded = True
End If
End If
However, it may be easier to use OpenArgs ( http://msdn.microsoft.com/en-us/library/office/ff820845(v=office.15).aspx )
In which case you could say something like:
If IsNull(Me.OpenArgs) Then
MsgBox "No openargs"
Else
Me.txtClientID = Me.Openargs
End If
Or even use Openargs to set the default value.

Flask-MongoKit find_one()

I'm trying to use Flask-MongoKit as follows (with both attempts to find_one failing):
app = Flask('app-name')
db = MongoKit(app)
db.register([database.Users])
with app.app_context():
print db['users'].find_one()
print db.Users.find_one()
When I used plain MongoKit (non-Flask version), and this worked (as follows)
db = Connection()
db.register([database.Users])
print db.Users.find_one()
Thanks!
EDIT:
The database and collection are defined as follows.
class Users(Document):
__collection__ = 'users'
__database__ = 'database'
Flask-MongoKit doesn't use MongoKit's __database__ value. Instead, it uses an application config setting named MONGODB_DATABASE. If that isn't set, it defaults to a database named flask. If you change your code to
app = Flask('app-name')
app.config['MONGODB_DATABASE'] = 'database'
db = MongoKit(app)
your calls to find_one() should work.
The relative bits can be found here and here.

OneNote create Page with UpdateHierarchy - how to find new page?

I managed to create sections at very specific places within my OneNote Notebooks. Now I want to achieve the same with pages. So instead of using the unpredicteable-placing "CreateNewPage" method, I use UpdateHierarchy which works perfectly fine (for testing purpose I'm using AppendChild below).
The only issue I'm having is, that after creating the new page using UpdateHierarchy I'm completely loosing any links to the newly created page. OneNote assigns an ID and ignores all further Tags/Names I give. Also setting the One:T member used for setting the title is getting ignored - it always creates an "Untitled Page".
Am I doing anything wrong or do I need to first CreateNewPage and, using the assigned page-ID, re-place it using UpdateHierarchy?
Regards
Joel
function createPage {
param([string]$title, [string]$sectionnode)
[string]$pageref=$null
# Gather the pages within the notebook
[xml]$ref = $null
$_globalOneNote["COM"].GetHierarchy($sectionnode, [Microsoft.Office.InterOp.OneNote.HierarchyScope]::hsPages, [ref]$ref)
[System.Xml.XmlNamespaceManager] $nsmgr = $ref.NameTable
$nsmgr.AddNamespace('one', "http://schemas.microsoft.com/office/onenote/2010/onenote")
# Creation of a new page
$newPage = $ref.CreateElement('one', 'Page', 'http://schemas.microsoft.com/office/onenote/2010/onenote')
$newTitle = $ref.CreateElement('one', 'Title', 'http://schemas.microsoft.com/office/onenote/2010/onenote')
$newOE = $ref.CreateElement('one', 'OE', 'http://schemas.microsoft.com/office/onenote/2010/onenote')
$newT = $ref.CreateElement('one', 'T', 'http://schemas.microsoft.com/office/onenote/2010/onenote')
$newPage.SetAttribute('name', "Olololo")
$newT.InnerText = '<![CDATA[Testtitle]]>'
$newOE.AppendChild($newT)
$newTitle.AppendChild($newOE)
$newPage.AppendChild($newTitle)
$ref.Section.AppendChild($newPage)
$_globalBJBOneNote["COM"].UpdateHierarchy($ref.OuterXML)
}
This does the trick. Setting of title etc. must still be done using UpdatePageContent however the new page is placed properly. For putting metadata (title, indention etc.) a separate function may be used that works using the returned GUID of the createPage function.
function createPage {
param([string]$sectionnode, [string]$pagenode = $sectionnode)
# Gather the sections within the notebook
[xml]$ref = $null
$_globalBJBOneNote["COM"].GetHierarchy($sectionnode, [Microsoft.Office.InterOp.OneNote.HierarchyScope]::hsPages, [ref]$ref)
[System.Xml.XmlNamespaceManager] $nsmgr = $ref.NameTable
$nsmgr.AddNamespace('one', "http://schemas.microsoft.com/office/onenote/2010/onenote")
# Create new page
[string]$pageID = $null
$_globalBJBOneNote["COM"].createNewPage($ref.Section.ID, [ref]$pageID)
# Reload the hierarchy, now we can get the node of the new notebook
$_globalBJBOneNote["COM"].GetHierarchy($sectionnode, [Microsoft.Office.InterOp.OneNote.HierarchyScope]::hsPages, [ref]$ref)
$newPageNode = $ref.SelectSingleNode('//one:Page[#ID="' + $pageID + '"]', $nsmgr)
$referencePageNode = $ref.SelectSingleNode('//one:Page[#ID="' + $pagenode + '"]', $nsmgr)
# Reposition
[void]$ref.Section.removeChild($newPageNode)
[void]$ref.Section.InsertAfter($newPageNode, $referencePageNode)
$_globalBJBOneNote["COM"].UpdateHierarchy($ref.OuterXML)
$pageID
}

Coffeescript running a second function before the first has finished executing

My code is as follows. I would expect the code inside configureMission() to finish running before running mapSurface. This does not appear to be happening.
missionCommands = "" # you don't have a mission yet
$('#startExploration').click -> # Set #missionControl as input for game configuration
configureMission()
mapSurface()
configureMission =->
$('#MissionControl').on "submit", ->
# cool helper function shamelessly pinched from http://jsfiddle.net/sxGtM/3/
$.fn.serializeObject = function() # not shown
missionCommands = JSON.stringify($('form').serializeObject())
return false #stops click event from firing
mapSurface =->
console.log('map')
console.log(missionCommands)
I have noticed that if I submit the form a second time, the missionCommands variable has been updated with the json data, so it appears that the form data has been processed, but that this is happening after the second function has run.
map login.js:60
login.js:61
map login.js:60
{"xMaximum":"","yMaximum":"","xCoord":["iuoiuyi",""],"yCoord":["",""],"orientaiton":["",""]} login.js:61
I can make it work by moving the mapSurface function inside the configureMission function, but this seems like bad form. I wonder, is there a more correct pattern I could use to achieve my desired result of processing the form data into json, setting this into a variable and passing the variable to a second function.
You're treating asynchronous commands as synchronous commands. JavaScript (and thereby CoffeeScript) works asynchronously, meaning that functions will be run in parallel.
You can solve this problem by specifying mapSurface() as the callback for configureMission() as follows:
missionCommands = ""
$('#startExploration').click ->
configureMission(mapSurface)
configureMission = (cb) ->
console.log "now running configureMission()"
$('#MissionControl').on "submit", ->
$.fn.serializeObject = function() # not shown
missionCommands = JSON.stringify($('form').serializeObject())
console.log "completed configureMission()"
return cb()
mapSurface = ->
console.log "now running mapSurface()"
console.log missionCommands
console.log "completed mapSurface()"
Learn about JavaScript callbacks here: http://recurial.com/programming/understanding-callback-functions-in-javascript/.

AMFPHP overiding default function arguments?

I've got this odd problem.
If I make a call on that function through amfphp service browser and give it a valid ID and leave the $num_images field blank amfphp will actually pass a blank string as the argument.
// if i call this function width just an ID
function getWorkers($id, $num_images = 100) {
...
// num_images will be set as ''
}
I can easily override using a check:
function getWorkers($id, $num_images = 100) {
if($num_images=='') $num_images = 100;
...
// num_images will now be really set as 100
}
Anyone experiencing the same with amfphp?
That's odd, I never got that from AMFPHP. If you don't have the latest version try updating your installation of AMFPHP. Also make sure Flash doesn't somehow pass an empty variable as the second variable.
(Copied from the comment.)