Coffescript not compiling valid source - coffeescript

I'm calling this function and get error in this place: data: { key: node.parent.data.key } saing "Unexpected {". Is there something wrong. because I can't find the error.
$("#discipline-list", #el).dynatree({
fx: { height: "toggle",
duration: 100 },
initAjax: {
url: "/disciplines",
data: { mode: "funnyMode" }
},
onLazyRead: (node) ->
console.log(node);
node.appendAjax({url: "/disciplines_details",
data: { key: node.parent.data.key }
});
});

Coffee script is not appreciating having the anonymous object properties on the same line. Adding a single newline fixes this...
$("#discipline-list", #el).dynatree({
fx: { height: "toggle",
duration: 100 },
initAjax: {
url: "/disciplines",
data: { mode: "funnyMode" }
},
onLazyRead: (node) ->
console.log(node);
node.appendAjax({
url: "/disciplines_details",
data: { key: node.parent.data.key }
});
});
EDIT: How to convert js to coffee script...
go to http://js2coffee.org/ and paste the js (corrected from your version)
$("#discipline-list", this.el).dynatree({
fx: { height: "toggle",
duration: 100 },
initAjax: {
url: "/disciplines",
data: { mode: "funnyMode" }
},
onLazyRead: function(node){
console.log(node);
node.appendAjax({ url: "/disciplines_details",
data: { key: node.parent.data.key }
});
}
});
You will end up with well formed coffee script...
$("#discipline-list", #el).dynatree
fx:
height: "toggle"
duration: 100
initAjax:
url: "/disciplines"
data:
mode: "funnyMode"
onLazyRead: (node) ->
console.log node
node.appendAjax
url: "/disciplines_details"
data:
key: node.parent.data.key

I don't know exactly what is wrong, but the more canonical way to write it would be
node.appendAjax
url: "/disciplines_details"
data:
key: node.parent.data.key
With compile errors like that, always first go to Try Coffeescript and see how it gets parsed. That makes it very easy and quick to fix in most cases.

The object properties on the same line are confusing the parser:
node.appendAjax({url: "/disciplines_details",
Just move url to the next line and it should work:
node.appendAjax({
url: "/disciplines_details",
That said, you're still writing javascript.
Whitespace is significant in coffeescript (i.e. you can't minify it). Correct indentation is essential, and this code is all wrong. Fix indentation, get rid of commas and semi-colons:
$("#discipline-list", #el).dynatree({
fx: {
height: "toggle"
duration: 100
}
initAjax: {
url: "/disciplines",
data: { mode: "funnyMode" }
}
onLazyRead: (node) ->
console.log(node)
node.appendAjax({
url: "/disciplines_details"
data: { key: node.parent.data.key }
})
})
Then proceed to get rid of brackets and parenthesis as in #Billy's last sample. If you're not comfortable you should try sticking to plain javascript for some time.

Related

Why does my redirects() in NextJS not work?

what am I doing wrong? I'm building an accessible website with NextJS and want to redirect to fitting pages to the plain-language-counterpart. But since they are a different kind of language, their URLs are different, too.
My routes are built like this:
Standard language = my-website.com/about
Plain language = my-website.com/plain-language/about
And I have a switch where I can just change the /plain-language/ part
Now I have these routes:
my-website.com/accessible-webdesign
my-website.com/plain-language/for-disabled-persons
And if I click the switch on the first one, it will link me to my-website.com/plain-language/accessible-webdesign, which doesn't exist! So I used redirects() and also restarted my server to fix this, but it doesn't work. It doesn't redirect and I get a 404 just as before.
Can you check my code and tell me, what I should change to make it work?
Thank you!
This is my next.config.js:
const withBundleAnalyzer = require('#next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
/** #type {import('next').NextConfig} */
const path = require('path');
const withPWA = require('next-pwa')({
dest: 'public',
disable: process.env.NODE_ENV === 'development',
sw: 'sw.js'
})
const nextConfig = {
async redirects(){
return[
{
source: '/plain-language/accessible-webdesign',
destination: '/plain-language/for-disabled-persons',
permanent: 'true'
}
]
},
reactStrictMode: true,
swcMinify: true,
trailingSlash: false,
webpackDevMiddleware: config => {
config.watchOptions = {
poll: 1000,
aggregateTimeout: 300
}
return config
},
sassOptions: {
includePaths: [path.join(__dirname, 'styles')]
},
experimental: {
images: {
layoutRaw: true
}
},
images: {
/*unoptimized: true - for static export!*/
/*deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
formats: ['image/webp']*/
}
}
module.exports = withBundleAnalyzer(withPWA({nextConfig}));
My working solution was from here: https://stackoverflow.com/a/58182678/
I put a middleware.ts in the root-folder (right next to package.json, next.config.js etc).
And I wrote this inside:
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export async function middleware(request: NextRequest) {
/* /accessible-webdesign --> /for-disabled-persons */
if (request.nextUrl.pathname.startsWith('/plain-language/accessible-webdesign')) {
return NextResponse.redirect(new URL('/plain-language/for-disabled-persons', request.url));
}
/* /another-url --> /another-redirect */
if (request.nextUrl.pathname.startsWith('/plain-language/another-url')) {
return NextResponse.redirect(new URL('/plain-language/another-redirect', request.url));
}
}
Not as beautiful, but working.

Getting an ' instance.requestPaymentMethod is not a function' in Braintree's sample

I'm getting an instance.requestpaymentmethod is not a function when I was just following along the tutorial for custom-field integration found here:
https://developers.braintreepayments.com/start/tutorial-hosted-fields-node
The error happens when I click on the "Pay" button.
Did anyone solve this problem? My assumption is that the code isn't updated or the script sources changed somewhat. If anyone from Braintree can actually help, that'll be great.
Thanks!
Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.
I took a look at the example code snippet in the guide you shared and I was able to find the culprit. First off, the error you're getting is expected as the requestPaymentMethod method actually belongs to our Drop-In UI solution and the Hosted Fields JS library doesn't have such module. I informed our Documentation team to get that code example updated.
That being said, you can find a working example in our Hosted Fields guide. If you check the function (hostedFieldsErr, hostedFieldsInstance) callback function, you'll see that the payment nonce is created by the tokenize function of the hostedFieldsInstance.
I also ran into this issue today. Use the following code in <script> tag. It will work for you.
var form = document.querySelector('#hosted-fields-form');
var submit = document.querySelector('input[type="submit"]');
braintree.client.create({
authorization: '<YOUR_TOKENIZATION_KEY>'
}, function (clientErr, clientInstance) {
if (clientErr) {
console.error(clientErr);
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '14px'
},
'input.invalid': {
'color': 'red'
},
'input.valid': {
'color': 'green'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: '4111 1111 1111 1111'
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationDate: {
selector: '#expiration-date',
placeholder: '10/2019'
}
}
}, function (hostedFieldsErr, hostedFieldsInstance) {
if (hostedFieldsErr) {
console.error(hostedFieldsErr);
return;
}
form.addEventListener('submit', function (event) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
if (tokenizeErr) {
console.error(tokenizeErr);
return;
}
console.log('Got a nonce: ' + payload.nonce);
$.ajax({
type: 'POST',
url: '<YOUR_API_URL>',
data: { 'paymentMethodNonce': payload.nonce }
}).done(function (result) {
hostedFieldsInstance.teardown(function (teardownErr) {
if (teardownErr) {
console.error('Could not tear down Drop-in UI!');
} else {
console.info('Drop-in UI has been torn down!');
$('#submit-button').remove();
}
});
if (result.success) {
$('#checkout-message').html('<h1>Success</h1><p>Your Drop-in UI is working! Check your sandbox Control Panel for your test transactions.</p><p>Refresh to try another transaction.</p>');
} else {
console.log(result);
$('#checkout-message').html('<h1>Error</h1><p>Check your console.</p>');
}
});
});
}, false);
});
});

codemirror inner mode auto indentation problems

I'm having some trouble getting codemirror to apply the correct autoindentation to inner modes in a mixed mode.
You can see a live version of the mode (and how it's not working) here:
https://extremely-alpha.iodide.io/notebooks/216/ but in short the idea is to be able to use matlab style block delimiters to switch between languages like this:
%% js
[1,2,3].forEach(i => {
console.log(i)
})
%% py
for i in range(5):
for j in range(10):
print i+j
%% css
div#foo {
border: 1px solid pink
}
As you can see from my example link, the syntax highlighting works ok, but you'll also notice that the indentation is not working as desired.
The code for this codemirror mode is here on github. It is very much based on codemirror's html mixed mode.
I tried adding copyState to my code, again following the html mixed mode --
copyState: state => {
let local;
if (state.localState) {
console.log("state.localState copied");
local = CodeMirror.copyState(state.localMode, state.localState);
}
return {
token: state.token,
localMode: state.localMode,
localState: local
};
},
-- but this results in a different kind of weird indentation behavior, and doesn't end up working.
I've been banging my head against this for quite some time, and I haven't been able to piece it together via google, api docs and forums, so any help would be greatly appreciated! Thank you!
in case anyone comes across this problem in the future: it turns out codemirror modes do not typically come with sensible defaults built in, or at least they are not loaded by default when you use CodeMirror.getMode(...). In my case, I had to change from
const innerModes = {
js: CodeMirror.getMode({}, { name: "javascript" }),
py: CodeMirror.getMode({}, { name: "python" }),
md: CodeMirror.getMode({}, { name: "markdown" }),
css: CodeMirror.getMode({}, { name: "css" }),
raw: CodeMirror.getMode({}, { name: "text/plain" }),
fetch: CodeMirror.getMode({}, { name: "fetch" })
};
to:
const innerModes = {
js: CodeMirror.getMode(
{ indentUnit: 2, statementIndent: 2 },
{ name: "javascript" }
),
py: CodeMirror.getMode(
{ indentUnit: 4, hangingIndent: 4 },
{ name: "python" }
),
md: CodeMirror.getMode({}, { name: "markdown" }),
css: CodeMirror.getMode({ indentUnit: 2 }, { name: "css" }),
raw: CodeMirror.getMode({}, { name: "text/plain" }),
fetch: CodeMirror.getMode({}, { name: "fetch" })
};
This prevented NaNs from getting passed out of the indent function of the sub-modes.

Angularjs ngResource needs to have file as one of the fields

I have resource that has following fields:
description, picture
Is it possible to send that resource to URL as multipart/form, and if so, how?
I've tried putting:
app.factory('resource_name', ['$resource', function($resource) {
return $resource('<url> ',
{
<params_for_url>
},
save: {
method: "POST",
headers: {
"Content-Type": "multipart/form-data;"
}
},
but this doesn't get to the server as form-data. It goes like JSON with header just set:
{
description: "gtrdgf",
picture: {
lastModifiedDate:2013-11-26T20:42:13.000Z,
name: "suggested_pokes.png"
size: 32995
type: "image/png"
webkitRelativePath: ""
}
Did anyone met this requirement before? If this is possible at all...
Thanks!
I found solution for this one. You have to use FormData to submit it. You can use it as interceptor. I used it like this (this is my save method of ngResource)
save: {
method: 'POST',
transformRequest: formDataObject,
headers: {'Content-Type':undefined, enctype:'multipart/form-data'}
},
and here is transformer:
function formDataObject (data) {
var fd = new FormData();
angular.forEach(data, function(value, key) {
fd.append(key, value);
});
return fd;
}

RESTful Model, get rid of the id query param in the GET request

I'm a little bit stuck here. My model code is
Ext.define('MyFancyModel', {
extend: 'Ext.data.Model',
fields: [
{ name: 'id', type: 'string' },
{ name: 'name', type: 'string' }
],
proxy: {
type: 'rest',
url: '/fancymodel',
noCache: false
}
});
When I try to load data by id using
Ext.ModelManager.getModel('MyFancyModel').load('some-id', {});
the request url is /fancymodel/some-id?id=some-id which is obviously not correct. So how can I achieve the right request url: /fancymodel/some-id without any patches or overrides?
EDIT:
jsfiddle
In the developer console you can see failed GET request
http://fiddle.jshell.net/fancymodel/some-id?id=some-id
EDIT:
Thread on the Sencha forum
I haven't found any ExtJS solution, so I have written a small patch (not sure it works in every situations) :
Ext.override(Ext.data.proxy.Rest, {
buildUrl: function (request) {
delete request.params.id;
return this.callParent(arguments);
}
});
The standard way :
Ext.define('MyPatches.data.proxy.Rest', {
override: 'Ext.data.proxy.Rest',
buildUrl: function (request) {
delete request.params.id;
return this.callParent(arguments);
}
});