id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
|---|---|---|---|---|---|---|---|---|---|---|---|
12,800
|
elix/elix
|
tasks/buildWeekData.js
|
formatWeekDataAsModule
|
function formatWeekDataAsModule(weekData) {
const date = new Date();
const { firstDay, weekendEnd, weekendStart } = weekData;
const transformed = {
firstDay: transformWeekDays(firstDay),
weekendEnd: transformWeekDays(weekendEnd),
weekendStart: transformWeekDays(weekendStart)
};
const formatted = JSON.stringify(transformed, null, 2);
const js =
`// Generated at ${date}
// from https://github.com/unicode-cldr/cldr-core/blob/master/supplemental/weekData.json
const weekData = ${formatted};
export default weekData;
`;
return js;
}
|
javascript
|
function formatWeekDataAsModule(weekData) {
const date = new Date();
const { firstDay, weekendEnd, weekendStart } = weekData;
const transformed = {
firstDay: transformWeekDays(firstDay),
weekendEnd: transformWeekDays(weekendEnd),
weekendStart: transformWeekDays(weekendStart)
};
const formatted = JSON.stringify(transformed, null, 2);
const js =
`// Generated at ${date}
// from https://github.com/unicode-cldr/cldr-core/blob/master/supplemental/weekData.json
const weekData = ${formatted};
export default weekData;
`;
return js;
}
|
[
"function",
"formatWeekDataAsModule",
"(",
"weekData",
")",
"{",
"const",
"date",
"=",
"new",
"Date",
"(",
")",
";",
"const",
"{",
"firstDay",
",",
"weekendEnd",
",",
"weekendStart",
"}",
"=",
"weekData",
";",
"const",
"transformed",
"=",
"{",
"firstDay",
":",
"transformWeekDays",
"(",
"firstDay",
")",
",",
"weekendEnd",
":",
"transformWeekDays",
"(",
"weekendEnd",
")",
",",
"weekendStart",
":",
"transformWeekDays",
"(",
"weekendStart",
")",
"}",
";",
"const",
"formatted",
"=",
"JSON",
".",
"stringify",
"(",
"transformed",
",",
"null",
",",
"2",
")",
";",
"const",
"js",
"=",
"`",
"${",
"date",
"}",
"${",
"formatted",
"}",
"`",
";",
"return",
"js",
";",
"}"
] |
Extract the week data we care about and format it as an ES6 module.
|
[
"Extract",
"the",
"week",
"data",
"we",
"care",
"about",
"and",
"format",
"it",
"as",
"an",
"ES6",
"module",
"."
] |
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
|
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/tasks/buildWeekData.js#L33-L49
|
12,801
|
elix/elix
|
src/AutoSizeTextarea.js
|
getTextFromContent
|
function getTextFromContent(contentNodes) {
if (contentNodes === null) {
return '';
}
const texts = [...contentNodes].map(node => node.textContent);
const text = texts.join('').trim();
return unescapeHtml(text);
}
|
javascript
|
function getTextFromContent(contentNodes) {
if (contentNodes === null) {
return '';
}
const texts = [...contentNodes].map(node => node.textContent);
const text = texts.join('').trim();
return unescapeHtml(text);
}
|
[
"function",
"getTextFromContent",
"(",
"contentNodes",
")",
"{",
"if",
"(",
"contentNodes",
"===",
"null",
")",
"{",
"return",
"''",
";",
"}",
"const",
"texts",
"=",
"[",
"...",
"contentNodes",
"]",
".",
"map",
"(",
"node",
"=>",
"node",
".",
"textContent",
")",
";",
"const",
"text",
"=",
"texts",
".",
"join",
"(",
"''",
")",
".",
"trim",
"(",
")",
";",
"return",
"unescapeHtml",
"(",
"text",
")",
";",
"}"
] |
Return the text represented by the given content nodes.
|
[
"Return",
"the",
"text",
"represented",
"by",
"the",
"given",
"content",
"nodes",
"."
] |
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
|
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/AutoSizeTextarea.js#L255-L262
|
12,802
|
elix/elix
|
src/State.js
|
isEmpty
|
function isEmpty(o) {
for (var key in o) {
if (o.hasOwnProperty(key)) {
return false;
}
}
return Object.getOwnPropertySymbols(o).length === 0;
}
|
javascript
|
function isEmpty(o) {
for (var key in o) {
if (o.hasOwnProperty(key)) {
return false;
}
}
return Object.getOwnPropertySymbols(o).length === 0;
}
|
[
"function",
"isEmpty",
"(",
"o",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"o",
")",
"{",
"if",
"(",
"o",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"Object",
".",
"getOwnPropertySymbols",
"(",
"o",
")",
".",
"length",
"===",
"0",
";",
"}"
] |
Return true if o is an empty object.
|
[
"Return",
"true",
"if",
"o",
"is",
"an",
"empty",
"object",
"."
] |
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
|
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/State.js#L93-L100
|
12,803
|
elix/elix
|
src/PageNumbersMixin.js
|
PageNumbersMixin
|
function PageNumbersMixin(Base) {
class PageNumbers extends Base {
/**
* Destructively wrap a node with elements to show page numbers.
*
* @param {Node} original - the element that should be wrapped by page numbers
*/
[wrap](original) {
const pageNumbersTemplate = template.html`
<div id="pageNumbers" role="none" style="display: flex; flex: 1; overflow: hidden;">
<style>
#pageNumber {
bottom: 0;
color: white;
padding: 0.5em;
position: absolute;
right: 0;
}
</style>
<div id="pageNumbersContainer" role="none" style="display: flex; flex: 1; overflow: hidden; position: relative;"></div>
<div id="pageNumber"></div>
</div>
`;
template.wrap(original, pageNumbersTemplate.content, '#pageNumbersContainer');
}
get updates() {
const selectedIndex = this.selectedIndex || this.state.selectedIndex;
const textContent = selectedIndex >= 0 && this.items ?
`${selectedIndex + 1} / ${this.items.length}` :
'';
return merge(super.updates, {
$: {
pageNumber: {
textContent
}
}
});
}
}
return PageNumbers;
}
|
javascript
|
function PageNumbersMixin(Base) {
class PageNumbers extends Base {
/**
* Destructively wrap a node with elements to show page numbers.
*
* @param {Node} original - the element that should be wrapped by page numbers
*/
[wrap](original) {
const pageNumbersTemplate = template.html`
<div id="pageNumbers" role="none" style="display: flex; flex: 1; overflow: hidden;">
<style>
#pageNumber {
bottom: 0;
color: white;
padding: 0.5em;
position: absolute;
right: 0;
}
</style>
<div id="pageNumbersContainer" role="none" style="display: flex; flex: 1; overflow: hidden; position: relative;"></div>
<div id="pageNumber"></div>
</div>
`;
template.wrap(original, pageNumbersTemplate.content, '#pageNumbersContainer');
}
get updates() {
const selectedIndex = this.selectedIndex || this.state.selectedIndex;
const textContent = selectedIndex >= 0 && this.items ?
`${selectedIndex + 1} / ${this.items.length}` :
'';
return merge(super.updates, {
$: {
pageNumber: {
textContent
}
}
});
}
}
return PageNumbers;
}
|
[
"function",
"PageNumbersMixin",
"(",
"Base",
")",
"{",
"class",
"PageNumbers",
"extends",
"Base",
"{",
"/**\n * Destructively wrap a node with elements to show page numbers.\n * \n * @param {Node} original - the element that should be wrapped by page numbers\n */",
"[",
"wrap",
"]",
"(",
"original",
")",
"{",
"const",
"pageNumbersTemplate",
"=",
"template",
".",
"html",
"`",
"`",
";",
"template",
".",
"wrap",
"(",
"original",
",",
"pageNumbersTemplate",
".",
"content",
",",
"'#pageNumbersContainer'",
")",
";",
"}",
"get",
"updates",
"(",
")",
"{",
"const",
"selectedIndex",
"=",
"this",
".",
"selectedIndex",
"||",
"this",
".",
"state",
".",
"selectedIndex",
";",
"const",
"textContent",
"=",
"selectedIndex",
">=",
"0",
"&&",
"this",
".",
"items",
"?",
"`",
"${",
"selectedIndex",
"+",
"1",
"}",
"${",
"this",
".",
"items",
".",
"length",
"}",
"`",
":",
"''",
";",
"return",
"merge",
"(",
"super",
".",
"updates",
",",
"{",
"$",
":",
"{",
"pageNumber",
":",
"{",
"textContent",
"}",
"}",
"}",
")",
";",
"}",
"}",
"return",
"PageNumbers",
";",
"}"
] |
Adds a page number and total page count to a carousel-like element.
This can be applied to components like [Carousel](Carousel) that renders
their content as pages.
@module PageNumbersMixin
|
[
"Adds",
"a",
"page",
"number",
"and",
"total",
"page",
"count",
"to",
"a",
"carousel",
"-",
"like",
"element",
"."
] |
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
|
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/PageNumbersMixin.js#L16-L61
|
12,804
|
elix/elix
|
src/AttributeMarshallingMixin.js
|
attributeToPropertyName
|
function attributeToPropertyName(attributeName) {
let propertyName = attributeToPropertyNames[attributeName];
if (!propertyName) {
// Convert and memoize.
const hyphenRegEx = /-([a-z])/g;
propertyName = attributeName.replace(hyphenRegEx,
match => match[1].toUpperCase());
attributeToPropertyNames[attributeName] = propertyName;
}
return propertyName;
}
|
javascript
|
function attributeToPropertyName(attributeName) {
let propertyName = attributeToPropertyNames[attributeName];
if (!propertyName) {
// Convert and memoize.
const hyphenRegEx = /-([a-z])/g;
propertyName = attributeName.replace(hyphenRegEx,
match => match[1].toUpperCase());
attributeToPropertyNames[attributeName] = propertyName;
}
return propertyName;
}
|
[
"function",
"attributeToPropertyName",
"(",
"attributeName",
")",
"{",
"let",
"propertyName",
"=",
"attributeToPropertyNames",
"[",
"attributeName",
"]",
";",
"if",
"(",
"!",
"propertyName",
")",
"{",
"// Convert and memoize.",
"const",
"hyphenRegEx",
"=",
"/",
"-([a-z])",
"/",
"g",
";",
"propertyName",
"=",
"attributeName",
".",
"replace",
"(",
"hyphenRegEx",
",",
"match",
"=>",
"match",
"[",
"1",
"]",
".",
"toUpperCase",
"(",
")",
")",
";",
"attributeToPropertyNames",
"[",
"attributeName",
"]",
"=",
"propertyName",
";",
"}",
"return",
"propertyName",
";",
"}"
] |
Convert hyphenated foo-bar attribute name to camel case fooBar property name.
|
[
"Convert",
"hyphenated",
"foo",
"-",
"bar",
"attribute",
"name",
"to",
"camel",
"case",
"fooBar",
"property",
"name",
"."
] |
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
|
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/AttributeMarshallingMixin.js#L126-L136
|
12,805
|
elix/elix
|
src/AttributeMarshallingMixin.js
|
propertyNameToAttribute
|
function propertyNameToAttribute(propertyName) {
let attribute = propertyNamesToAttributes[propertyName];
if (!attribute) {
// Convert and memoize.
const uppercaseRegEx = /([A-Z])/g;
attribute = propertyName.replace(uppercaseRegEx, '-$1').toLowerCase();
}
return attribute;
}
|
javascript
|
function propertyNameToAttribute(propertyName) {
let attribute = propertyNamesToAttributes[propertyName];
if (!attribute) {
// Convert and memoize.
const uppercaseRegEx = /([A-Z])/g;
attribute = propertyName.replace(uppercaseRegEx, '-$1').toLowerCase();
}
return attribute;
}
|
[
"function",
"propertyNameToAttribute",
"(",
"propertyName",
")",
"{",
"let",
"attribute",
"=",
"propertyNamesToAttributes",
"[",
"propertyName",
"]",
";",
"if",
"(",
"!",
"attribute",
")",
"{",
"// Convert and memoize.",
"const",
"uppercaseRegEx",
"=",
"/",
"([A-Z])",
"/",
"g",
";",
"attribute",
"=",
"propertyName",
".",
"replace",
"(",
"uppercaseRegEx",
",",
"'-$1'",
")",
".",
"toLowerCase",
"(",
")",
";",
"}",
"return",
"attribute",
";",
"}"
] |
Convert a camel case fooBar property name to a hyphenated foo-bar attribute.
|
[
"Convert",
"a",
"camel",
"case",
"fooBar",
"property",
"name",
"to",
"a",
"hyphenated",
"foo",
"-",
"bar",
"attribute",
"."
] |
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
|
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/AttributeMarshallingMixin.js#L154-L162
|
12,806
|
elix/elix
|
src/SlotContentMixin.js
|
assignedNodesChanged
|
function assignedNodesChanged(component) {
const slot = component[symbols.contentSlot];
const content = slot ?
slot.assignedNodes({ flatten: true }) :
null;
// Make immutable.
Object.freeze(content);
component.setState({ content });
}
|
javascript
|
function assignedNodesChanged(component) {
const slot = component[symbols.contentSlot];
const content = slot ?
slot.assignedNodes({ flatten: true }) :
null;
// Make immutable.
Object.freeze(content);
component.setState({ content });
}
|
[
"function",
"assignedNodesChanged",
"(",
"component",
")",
"{",
"const",
"slot",
"=",
"component",
"[",
"symbols",
".",
"contentSlot",
"]",
";",
"const",
"content",
"=",
"slot",
"?",
"slot",
".",
"assignedNodes",
"(",
"{",
"flatten",
":",
"true",
"}",
")",
":",
"null",
";",
"// Make immutable.",
"Object",
".",
"freeze",
"(",
"content",
")",
";",
"component",
".",
"setState",
"(",
"{",
"content",
"}",
")",
";",
"}"
] |
The nodes assigned to the given component have changed. Update the component's state to reflect the new content.
|
[
"The",
"nodes",
"assigned",
"to",
"the",
"given",
"component",
"have",
"changed",
".",
"Update",
"the",
"component",
"s",
"state",
"to",
"reflect",
"the",
"new",
"content",
"."
] |
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
|
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/SlotContentMixin.js#L147-L158
|
12,807
|
elix/elix
|
src/FocusCaptureMixin.js
|
FocusCaptureMixin
|
function FocusCaptureMixin(base) {
class FocusCapture extends base {
componentDidMount() {
if (super.componentDidMount) { super.componentDidMount(); }
this.$.focusCatcher.addEventListener('focus', () => {
if (!this[wrappingFocusKey]) {
// Wrap focus back to the first focusable element.
const focusElement = firstFocusableElement(this.shadowRoot);
if (focusElement) {
focusElement.focus();
}
}
});
}
[symbols.keydown](event) {
const firstElement = firstFocusableElement(this.shadowRoot);
const onFirstElement = document.activeElement === firstElement ||
this.shadowRoot.activeElement === firstElement;
if (onFirstElement && event.key === 'Tab' && event.shiftKey) {
// Set focus to focus catcher.
// The Shift+Tab keydown event should continue bubbling, and the default
// behavior should cause it to end up on the last focusable element.
this[wrappingFocusKey] = true;
this.$.focusCatcher.focus();
this[wrappingFocusKey] = false;
// Don't mark the event as handled, since we want it to keep bubbling up.
}
// Prefer mixin result if it's defined, otherwise use base result.
return (super[symbols.keydown] && super[symbols.keydown](event)) || false;
}
/**
* Destructively wrap a node with elements necessary to capture focus.
*
* Call this method in a components `symbols.template` property.
* Invoke this method as `this[FocusCaptureMixin.wrap](element)`.
*
* @param {Node} original - the element within which focus should wrap
*/
[wrap](original) {
const focusCaptureTemplate = template.html`
<div style="display: flex;">
<div id="focusCaptureContainer" style="display: flex;"></div>
<div id="focusCatcher" tabindex="0"></div>
</div>
`;
template.wrap(original, focusCaptureTemplate.content, '#focusCaptureContainer');
}
}
return FocusCapture;
}
|
javascript
|
function FocusCaptureMixin(base) {
class FocusCapture extends base {
componentDidMount() {
if (super.componentDidMount) { super.componentDidMount(); }
this.$.focusCatcher.addEventListener('focus', () => {
if (!this[wrappingFocusKey]) {
// Wrap focus back to the first focusable element.
const focusElement = firstFocusableElement(this.shadowRoot);
if (focusElement) {
focusElement.focus();
}
}
});
}
[symbols.keydown](event) {
const firstElement = firstFocusableElement(this.shadowRoot);
const onFirstElement = document.activeElement === firstElement ||
this.shadowRoot.activeElement === firstElement;
if (onFirstElement && event.key === 'Tab' && event.shiftKey) {
// Set focus to focus catcher.
// The Shift+Tab keydown event should continue bubbling, and the default
// behavior should cause it to end up on the last focusable element.
this[wrappingFocusKey] = true;
this.$.focusCatcher.focus();
this[wrappingFocusKey] = false;
// Don't mark the event as handled, since we want it to keep bubbling up.
}
// Prefer mixin result if it's defined, otherwise use base result.
return (super[symbols.keydown] && super[symbols.keydown](event)) || false;
}
/**
* Destructively wrap a node with elements necessary to capture focus.
*
* Call this method in a components `symbols.template` property.
* Invoke this method as `this[FocusCaptureMixin.wrap](element)`.
*
* @param {Node} original - the element within which focus should wrap
*/
[wrap](original) {
const focusCaptureTemplate = template.html`
<div style="display: flex;">
<div id="focusCaptureContainer" style="display: flex;"></div>
<div id="focusCatcher" tabindex="0"></div>
</div>
`;
template.wrap(original, focusCaptureTemplate.content, '#focusCaptureContainer');
}
}
return FocusCapture;
}
|
[
"function",
"FocusCaptureMixin",
"(",
"base",
")",
"{",
"class",
"FocusCapture",
"extends",
"base",
"{",
"componentDidMount",
"(",
")",
"{",
"if",
"(",
"super",
".",
"componentDidMount",
")",
"{",
"super",
".",
"componentDidMount",
"(",
")",
";",
"}",
"this",
".",
"$",
".",
"focusCatcher",
".",
"addEventListener",
"(",
"'focus'",
",",
"(",
")",
"=>",
"{",
"if",
"(",
"!",
"this",
"[",
"wrappingFocusKey",
"]",
")",
"{",
"// Wrap focus back to the first focusable element.",
"const",
"focusElement",
"=",
"firstFocusableElement",
"(",
"this",
".",
"shadowRoot",
")",
";",
"if",
"(",
"focusElement",
")",
"{",
"focusElement",
".",
"focus",
"(",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"[",
"symbols",
".",
"keydown",
"]",
"(",
"event",
")",
"{",
"const",
"firstElement",
"=",
"firstFocusableElement",
"(",
"this",
".",
"shadowRoot",
")",
";",
"const",
"onFirstElement",
"=",
"document",
".",
"activeElement",
"===",
"firstElement",
"||",
"this",
".",
"shadowRoot",
".",
"activeElement",
"===",
"firstElement",
";",
"if",
"(",
"onFirstElement",
"&&",
"event",
".",
"key",
"===",
"'Tab'",
"&&",
"event",
".",
"shiftKey",
")",
"{",
"// Set focus to focus catcher.",
"// The Shift+Tab keydown event should continue bubbling, and the default",
"// behavior should cause it to end up on the last focusable element.",
"this",
"[",
"wrappingFocusKey",
"]",
"=",
"true",
";",
"this",
".",
"$",
".",
"focusCatcher",
".",
"focus",
"(",
")",
";",
"this",
"[",
"wrappingFocusKey",
"]",
"=",
"false",
";",
"// Don't mark the event as handled, since we want it to keep bubbling up.",
"}",
"// Prefer mixin result if it's defined, otherwise use base result.",
"return",
"(",
"super",
"[",
"symbols",
".",
"keydown",
"]",
"&&",
"super",
"[",
"symbols",
".",
"keydown",
"]",
"(",
"event",
")",
")",
"||",
"false",
";",
"}",
"/**\n * Destructively wrap a node with elements necessary to capture focus.\n * \n * Call this method in a components `symbols.template` property.\n * Invoke this method as `this[FocusCaptureMixin.wrap](element)`.\n * \n * @param {Node} original - the element within which focus should wrap\n */",
"[",
"wrap",
"]",
"(",
"original",
")",
"{",
"const",
"focusCaptureTemplate",
"=",
"template",
".",
"html",
"`",
"`",
";",
"template",
".",
"wrap",
"(",
"original",
",",
"focusCaptureTemplate",
".",
"content",
",",
"'#focusCaptureContainer'",
")",
";",
"}",
"}",
"return",
"FocusCapture",
";",
"}"
] |
Allows Tab and Shift+Tab operations to cycle the focus within the component.
This mixin expects the component to provide:
* A template-stamping mechanism compatible with `ShadowTemplateMixin`.
The mixin provides these features to the component:
* Template elements and event handlers that will cause the keyboard focus to wrap.
This mixin [contributes to a component's template](mixins#mixins-that-contribute-to-a-component-s-template).
See that discussion for details on how to use such a mixin.
@module FocusCaptureMixin
|
[
"Allows",
"Tab",
"and",
"Shift",
"+",
"Tab",
"operations",
"to",
"cycle",
"the",
"focus",
"within",
"the",
"component",
"."
] |
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
|
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/FocusCaptureMixin.js#L28-L84
|
12,808
|
elix/elix
|
src/PullToRefresh.js
|
handleScrollPull
|
async function handleScrollPull(element, scrollTarget) {
const scrollTop = scrollTarget === window ?
document.body.scrollTop :
scrollTarget.scrollTop;
if (scrollTop < 0) {
// Negative scroll top means we're probably in WebKit.
// Start a scroll pull operation.
let scrollPullDistance = -scrollTop;
if (element.state.scrollPullDistance &&
!element.state.scrollPullMaxReached &&
scrollPullDistance < element.state.scrollPullDistance) {
// The negative scroll events have started to head back to zero (most
// likely because the user let go and stopped scrolling), so we've reached
// the maximum extent of the scroll pull. From this point on, we want to
// stop our own translation effect and let the browser smoothly snap the
// page back to the top (zero) scroll position. If we don't do that, we'll
// be fighting with the browser effect, and the result will not be smooth.
element.setState({ scrollPullMaxReached: true });
}
await element.setState({ scrollPullDistance });
} else if (element.state.scrollPullDistance !== null) {
// We've scrolled back into zero/positive territory, i.e., at or below the
// top of the page, so the scroll pull has finished.
await element.setState({
scrollPullDistance: null,
scrollPullMaxReached: false,
});
}
}
|
javascript
|
async function handleScrollPull(element, scrollTarget) {
const scrollTop = scrollTarget === window ?
document.body.scrollTop :
scrollTarget.scrollTop;
if (scrollTop < 0) {
// Negative scroll top means we're probably in WebKit.
// Start a scroll pull operation.
let scrollPullDistance = -scrollTop;
if (element.state.scrollPullDistance &&
!element.state.scrollPullMaxReached &&
scrollPullDistance < element.state.scrollPullDistance) {
// The negative scroll events have started to head back to zero (most
// likely because the user let go and stopped scrolling), so we've reached
// the maximum extent of the scroll pull. From this point on, we want to
// stop our own translation effect and let the browser smoothly snap the
// page back to the top (zero) scroll position. If we don't do that, we'll
// be fighting with the browser effect, and the result will not be smooth.
element.setState({ scrollPullMaxReached: true });
}
await element.setState({ scrollPullDistance });
} else if (element.state.scrollPullDistance !== null) {
// We've scrolled back into zero/positive territory, i.e., at or below the
// top of the page, so the scroll pull has finished.
await element.setState({
scrollPullDistance: null,
scrollPullMaxReached: false,
});
}
}
|
[
"async",
"function",
"handleScrollPull",
"(",
"element",
",",
"scrollTarget",
")",
"{",
"const",
"scrollTop",
"=",
"scrollTarget",
"===",
"window",
"?",
"document",
".",
"body",
".",
"scrollTop",
":",
"scrollTarget",
".",
"scrollTop",
";",
"if",
"(",
"scrollTop",
"<",
"0",
")",
"{",
"// Negative scroll top means we're probably in WebKit.",
"// Start a scroll pull operation.",
"let",
"scrollPullDistance",
"=",
"-",
"scrollTop",
";",
"if",
"(",
"element",
".",
"state",
".",
"scrollPullDistance",
"&&",
"!",
"element",
".",
"state",
".",
"scrollPullMaxReached",
"&&",
"scrollPullDistance",
"<",
"element",
".",
"state",
".",
"scrollPullDistance",
")",
"{",
"// The negative scroll events have started to head back to zero (most",
"// likely because the user let go and stopped scrolling), so we've reached",
"// the maximum extent of the scroll pull. From this point on, we want to",
"// stop our own translation effect and let the browser smoothly snap the",
"// page back to the top (zero) scroll position. If we don't do that, we'll",
"// be fighting with the browser effect, and the result will not be smooth.",
"element",
".",
"setState",
"(",
"{",
"scrollPullMaxReached",
":",
"true",
"}",
")",
";",
"}",
"await",
"element",
".",
"setState",
"(",
"{",
"scrollPullDistance",
"}",
")",
";",
"}",
"else",
"if",
"(",
"element",
".",
"state",
".",
"scrollPullDistance",
"!==",
"null",
")",
"{",
"// We've scrolled back into zero/positive territory, i.e., at or below the",
"// top of the page, so the scroll pull has finished.",
"await",
"element",
".",
"setState",
"(",
"{",
"scrollPullDistance",
":",
"null",
",",
"scrollPullMaxReached",
":",
"false",
",",
"}",
")",
";",
"}",
"}"
] |
If a user flicks down to quickly scroll up, and scrolls past the top of the page, the area above the page may be shown briefly. We use that opportunity to show the user the refresh header so they'll realize they can pull to refresh. We call this operation a "scroll pull". It works a little like a real touch drag, but cannot trigger a refresh. We can only handle a scroll pull in a browser like Mobile Safari that gives us scroll events past the top of the page.
|
[
"If",
"a",
"user",
"flicks",
"down",
"to",
"quickly",
"scroll",
"up",
"and",
"scrolls",
"past",
"the",
"top",
"of",
"the",
"page",
"the",
"area",
"above",
"the",
"page",
"may",
"be",
"shown",
"briefly",
".",
"We",
"use",
"that",
"opportunity",
"to",
"show",
"the",
"user",
"the",
"refresh",
"header",
"so",
"they",
"ll",
"realize",
"they",
"can",
"pull",
"to",
"refresh",
".",
"We",
"call",
"this",
"operation",
"a",
"scroll",
"pull",
".",
"It",
"works",
"a",
"little",
"like",
"a",
"real",
"touch",
"drag",
"but",
"cannot",
"trigger",
"a",
"refresh",
".",
"We",
"can",
"only",
"handle",
"a",
"scroll",
"pull",
"in",
"a",
"browser",
"like",
"Mobile",
"Safari",
"that",
"gives",
"us",
"scroll",
"events",
"past",
"the",
"top",
"of",
"the",
"page",
"."
] |
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
|
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/PullToRefresh.js#L303-L331
|
12,809
|
elix/elix
|
src/TimerSelectionMixin.js
|
updateTimer
|
function updateTimer(element) {
// If the element is playing and we haven't started a timer yet, do so now.
// Also, if the element's selectedIndex changed for any reason, restart the
// timer. This ensures that the timer restarts no matter why the selection
// changes: it could have been us moving to the next slide because the timer
// elapsed, or the user might have directly manipulated the selection, etc.
if (element.state.playing &&
(!element.state.timerTimeout || element.state.selectedIndex !== element.state.selectedIndexForTimer)) {
restartTimer(element);
} else if (!element.state.playing && element.state.timerTimeout) {
clearTimer(element);
}
}
|
javascript
|
function updateTimer(element) {
// If the element is playing and we haven't started a timer yet, do so now.
// Also, if the element's selectedIndex changed for any reason, restart the
// timer. This ensures that the timer restarts no matter why the selection
// changes: it could have been us moving to the next slide because the timer
// elapsed, or the user might have directly manipulated the selection, etc.
if (element.state.playing &&
(!element.state.timerTimeout || element.state.selectedIndex !== element.state.selectedIndexForTimer)) {
restartTimer(element);
} else if (!element.state.playing && element.state.timerTimeout) {
clearTimer(element);
}
}
|
[
"function",
"updateTimer",
"(",
"element",
")",
"{",
"// If the element is playing and we haven't started a timer yet, do so now.",
"// Also, if the element's selectedIndex changed for any reason, restart the",
"// timer. This ensures that the timer restarts no matter why the selection",
"// changes: it could have been us moving to the next slide because the timer",
"// elapsed, or the user might have directly manipulated the selection, etc.",
"if",
"(",
"element",
".",
"state",
".",
"playing",
"&&",
"(",
"!",
"element",
".",
"state",
".",
"timerTimeout",
"||",
"element",
".",
"state",
".",
"selectedIndex",
"!==",
"element",
".",
"state",
".",
"selectedIndexForTimer",
")",
")",
"{",
"restartTimer",
"(",
"element",
")",
";",
"}",
"else",
"if",
"(",
"!",
"element",
".",
"state",
".",
"playing",
"&&",
"element",
".",
"state",
".",
"timerTimeout",
")",
"{",
"clearTimer",
"(",
"element",
")",
";",
"}",
"}"
] |
Update the timer to match the element's `playing` state.
|
[
"Update",
"the",
"timer",
"to",
"match",
"the",
"element",
"s",
"playing",
"state",
"."
] |
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
|
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/TimerSelectionMixin.js#L134-L146
|
12,810
|
elix/elix
|
src/TrackpadSwipeMixin.js
|
resetWheelTracking
|
function resetWheelTracking(element) {
element[wheelDistanceSymbol] = 0;
element[lastDeltaXSymbol] = 0;
element[absorbDecelerationSymbol] = false;
element[postNavigateDelayCompleteSymbol] = false;
if (element[lastWheelTimeoutSymbol]) {
clearTimeout(element[lastWheelTimeoutSymbol]);
element[lastWheelTimeoutSymbol] = null;
}
}
|
javascript
|
function resetWheelTracking(element) {
element[wheelDistanceSymbol] = 0;
element[lastDeltaXSymbol] = 0;
element[absorbDecelerationSymbol] = false;
element[postNavigateDelayCompleteSymbol] = false;
if (element[lastWheelTimeoutSymbol]) {
clearTimeout(element[lastWheelTimeoutSymbol]);
element[lastWheelTimeoutSymbol] = null;
}
}
|
[
"function",
"resetWheelTracking",
"(",
"element",
")",
"{",
"element",
"[",
"wheelDistanceSymbol",
"]",
"=",
"0",
";",
"element",
"[",
"lastDeltaXSymbol",
"]",
"=",
"0",
";",
"element",
"[",
"absorbDecelerationSymbol",
"]",
"=",
"false",
";",
"element",
"[",
"postNavigateDelayCompleteSymbol",
"]",
"=",
"false",
";",
"if",
"(",
"element",
"[",
"lastWheelTimeoutSymbol",
"]",
")",
"{",
"clearTimeout",
"(",
"element",
"[",
"lastWheelTimeoutSymbol",
"]",
")",
";",
"element",
"[",
"lastWheelTimeoutSymbol",
"]",
"=",
"null",
";",
"}",
"}"
] |
Reset all state related to the tracking of the wheel.
|
[
"Reset",
"all",
"state",
"related",
"to",
"the",
"tracking",
"of",
"the",
"wheel",
"."
] |
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
|
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/TrackpadSwipeMixin.js#L171-L180
|
12,811
|
elix/elix
|
src/KeyboardPrefixSelectionMixin.js
|
handlePlainCharacter
|
function handlePlainCharacter(element, char) {
const prefix = element[typedPrefixKey] || '';
element[typedPrefixKey] = prefix + char;
element.selectItemWithTextPrefix(element[typedPrefixKey]);
setPrefixTimeout(element);
}
|
javascript
|
function handlePlainCharacter(element, char) {
const prefix = element[typedPrefixKey] || '';
element[typedPrefixKey] = prefix + char;
element.selectItemWithTextPrefix(element[typedPrefixKey]);
setPrefixTimeout(element);
}
|
[
"function",
"handlePlainCharacter",
"(",
"element",
",",
"char",
")",
"{",
"const",
"prefix",
"=",
"element",
"[",
"typedPrefixKey",
"]",
"||",
"''",
";",
"element",
"[",
"typedPrefixKey",
"]",
"=",
"prefix",
"+",
"char",
";",
"element",
".",
"selectItemWithTextPrefix",
"(",
"element",
"[",
"typedPrefixKey",
"]",
")",
";",
"setPrefixTimeout",
"(",
"element",
")",
";",
"}"
] |
Add a plain character to the prefix.
|
[
"Add",
"a",
"plain",
"character",
"to",
"the",
"prefix",
"."
] |
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
|
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/KeyboardPrefixSelectionMixin.js#L122-L127
|
12,812
|
elix/elix
|
src/KeyboardPrefixSelectionMixin.js
|
resetPrefixTimeout
|
function resetPrefixTimeout(element) {
if (element[prefixTimeoutKey]) {
clearTimeout(element[prefixTimeoutKey]);
element[prefixTimeoutKey] = false;
}
}
|
javascript
|
function resetPrefixTimeout(element) {
if (element[prefixTimeoutKey]) {
clearTimeout(element[prefixTimeoutKey]);
element[prefixTimeoutKey] = false;
}
}
|
[
"function",
"resetPrefixTimeout",
"(",
"element",
")",
"{",
"if",
"(",
"element",
"[",
"prefixTimeoutKey",
"]",
")",
"{",
"clearTimeout",
"(",
"element",
"[",
"prefixTimeoutKey",
"]",
")",
";",
"element",
"[",
"prefixTimeoutKey",
"]",
"=",
"false",
";",
"}",
"}"
] |
Stop listening for typing.
|
[
"Stop",
"listening",
"for",
"typing",
"."
] |
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
|
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/KeyboardPrefixSelectionMixin.js#L130-L135
|
12,813
|
elix/elix
|
src/KeyboardPrefixSelectionMixin.js
|
setPrefixTimeout
|
function setPrefixTimeout(element) {
resetPrefixTimeout(element);
element[prefixTimeoutKey] = setTimeout(() => {
resetTypedPrefix(element);
}, TYPING_TIMEOUT_DURATION);
}
|
javascript
|
function setPrefixTimeout(element) {
resetPrefixTimeout(element);
element[prefixTimeoutKey] = setTimeout(() => {
resetTypedPrefix(element);
}, TYPING_TIMEOUT_DURATION);
}
|
[
"function",
"setPrefixTimeout",
"(",
"element",
")",
"{",
"resetPrefixTimeout",
"(",
"element",
")",
";",
"element",
"[",
"prefixTimeoutKey",
"]",
"=",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"resetTypedPrefix",
"(",
"element",
")",
";",
"}",
",",
"TYPING_TIMEOUT_DURATION",
")",
";",
"}"
] |
Wait for the user to stop typing.
|
[
"Wait",
"for",
"the",
"user",
"to",
"stop",
"typing",
"."
] |
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
|
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/KeyboardPrefixSelectionMixin.js#L144-L149
|
12,814
|
elix/elix
|
demos/src/CalendarDayMoonPhase.js
|
jd0
|
function jd0(year, month, day) {
let y = year;
let m = month;
if (m < 3) {
m += 12;
y -= 1
};
const a = Math.floor(y/100);
const b = 2-a+Math.floor(a/4);
const j = Math.floor(365.25*(y+4716))+Math.floor(30.6001*(m+1))+day+b-1524.5;
return j;
}
|
javascript
|
function jd0(year, month, day) {
let y = year;
let m = month;
if (m < 3) {
m += 12;
y -= 1
};
const a = Math.floor(y/100);
const b = 2-a+Math.floor(a/4);
const j = Math.floor(365.25*(y+4716))+Math.floor(30.6001*(m+1))+day+b-1524.5;
return j;
}
|
[
"function",
"jd0",
"(",
"year",
",",
"month",
",",
"day",
")",
"{",
"let",
"y",
"=",
"year",
";",
"let",
"m",
"=",
"month",
";",
"if",
"(",
"m",
"<",
"3",
")",
"{",
"m",
"+=",
"12",
";",
"y",
"-=",
"1",
"}",
";",
"const",
"a",
"=",
"Math",
".",
"floor",
"(",
"y",
"/",
"100",
")",
";",
"const",
"b",
"=",
"2",
"-",
"a",
"+",
"Math",
".",
"floor",
"(",
"a",
"/",
"4",
")",
";",
"const",
"j",
"=",
"Math",
".",
"floor",
"(",
"365.25",
"*",
"(",
"y",
"+",
"4716",
")",
")",
"+",
"Math",
".",
"floor",
"(",
"30.6001",
"*",
"(",
"m",
"+",
"1",
")",
")",
"+",
"day",
"+",
"b",
"-",
"1524.5",
";",
"return",
"j",
";",
"}"
] |
The Julian date at 0 hours UT at Greenwich
|
[
"The",
"Julian",
"date",
"at",
"0",
"hours",
"UT",
"at",
"Greenwich"
] |
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
|
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/demos/src/CalendarDayMoonPhase.js#L102-L113
|
12,815
|
elix/elix
|
src/Explorer.js
|
createDefaultProxies
|
function createDefaultProxies(items, proxyRole) {
const proxies = items ?
items.map(() => template.createElement(proxyRole)) :
[];
// Make the array immutable to help update performance.
Object.freeze(proxies);
return proxies;
}
|
javascript
|
function createDefaultProxies(items, proxyRole) {
const proxies = items ?
items.map(() => template.createElement(proxyRole)) :
[];
// Make the array immutable to help update performance.
Object.freeze(proxies);
return proxies;
}
|
[
"function",
"createDefaultProxies",
"(",
"items",
",",
"proxyRole",
")",
"{",
"const",
"proxies",
"=",
"items",
"?",
"items",
".",
"map",
"(",
"(",
")",
"=>",
"template",
".",
"createElement",
"(",
"proxyRole",
")",
")",
":",
"[",
"]",
";",
"// Make the array immutable to help update performance.",
"Object",
".",
"freeze",
"(",
"proxies",
")",
";",
"return",
"proxies",
";",
"}"
] |
Return the default list generated for the given items.
|
[
"Return",
"the",
"default",
"list",
"generated",
"for",
"the",
"given",
"items",
"."
] |
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
|
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/Explorer.js#L393-L400
|
12,816
|
elix/elix
|
src/Explorer.js
|
findChildContainingNode
|
function findChildContainingNode(root, node) {
const parentNode = node.parentNode;
return parentNode === root ?
node :
findChildContainingNode(root, parentNode);
}
|
javascript
|
function findChildContainingNode(root, node) {
const parentNode = node.parentNode;
return parentNode === root ?
node :
findChildContainingNode(root, parentNode);
}
|
[
"function",
"findChildContainingNode",
"(",
"root",
",",
"node",
")",
"{",
"const",
"parentNode",
"=",
"node",
".",
"parentNode",
";",
"return",
"parentNode",
"===",
"root",
"?",
"node",
":",
"findChildContainingNode",
"(",
"root",
",",
"parentNode",
")",
";",
"}"
] |
Find the child of root that is or contains the given node.
|
[
"Find",
"the",
"child",
"of",
"root",
"that",
"is",
"or",
"contains",
"the",
"given",
"node",
"."
] |
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
|
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/Explorer.js#L404-L409
|
12,817
|
elix/elix
|
src/Explorer.js
|
setListAndStageOrder
|
function setListAndStageOrder(element) {
const proxyListPosition = element.state.proxyListPosition;
const rightToLeft = element[symbols.rightToLeft];
const listInInitialPosition =
proxyListPosition === 'top' ||
proxyListPosition === 'start' ||
proxyListPosition === 'left' && !rightToLeft ||
proxyListPosition === 'right' && rightToLeft;
const container = element.$.explorerContainer;
const stage = findChildContainingNode(container, element.$.stage);
const list = findChildContainingNode(container, element.$.proxyList);
const firstElement = listInInitialPosition ? list : stage;
const lastElement = listInInitialPosition ? stage : list;
if (firstElement.nextElementSibling !== lastElement) {
element.$.explorerContainer.insertBefore(firstElement, lastElement);
}
}
|
javascript
|
function setListAndStageOrder(element) {
const proxyListPosition = element.state.proxyListPosition;
const rightToLeft = element[symbols.rightToLeft];
const listInInitialPosition =
proxyListPosition === 'top' ||
proxyListPosition === 'start' ||
proxyListPosition === 'left' && !rightToLeft ||
proxyListPosition === 'right' && rightToLeft;
const container = element.$.explorerContainer;
const stage = findChildContainingNode(container, element.$.stage);
const list = findChildContainingNode(container, element.$.proxyList);
const firstElement = listInInitialPosition ? list : stage;
const lastElement = listInInitialPosition ? stage : list;
if (firstElement.nextElementSibling !== lastElement) {
element.$.explorerContainer.insertBefore(firstElement, lastElement);
}
}
|
[
"function",
"setListAndStageOrder",
"(",
"element",
")",
"{",
"const",
"proxyListPosition",
"=",
"element",
".",
"state",
".",
"proxyListPosition",
";",
"const",
"rightToLeft",
"=",
"element",
"[",
"symbols",
".",
"rightToLeft",
"]",
";",
"const",
"listInInitialPosition",
"=",
"proxyListPosition",
"===",
"'top'",
"||",
"proxyListPosition",
"===",
"'start'",
"||",
"proxyListPosition",
"===",
"'left'",
"&&",
"!",
"rightToLeft",
"||",
"proxyListPosition",
"===",
"'right'",
"&&",
"rightToLeft",
";",
"const",
"container",
"=",
"element",
".",
"$",
".",
"explorerContainer",
";",
"const",
"stage",
"=",
"findChildContainingNode",
"(",
"container",
",",
"element",
".",
"$",
".",
"stage",
")",
";",
"const",
"list",
"=",
"findChildContainingNode",
"(",
"container",
",",
"element",
".",
"$",
".",
"proxyList",
")",
";",
"const",
"firstElement",
"=",
"listInInitialPosition",
"?",
"list",
":",
"stage",
";",
"const",
"lastElement",
"=",
"listInInitialPosition",
"?",
"stage",
":",
"list",
";",
"if",
"(",
"firstElement",
".",
"nextElementSibling",
"!==",
"lastElement",
")",
"{",
"element",
".",
"$",
".",
"explorerContainer",
".",
"insertBefore",
"(",
"firstElement",
",",
"lastElement",
")",
";",
"}",
"}"
] |
Physically reorder the list and stage to reflect the desired arrangement. We could change the visual appearance by reversing the order of the flex box, but then the visual order wouldn't reflect the document order, which determines focus order. That would surprise a user trying to tab through the controls.
|
[
"Physically",
"reorder",
"the",
"list",
"and",
"stage",
"to",
"reflect",
"the",
"desired",
"arrangement",
".",
"We",
"could",
"change",
"the",
"visual",
"appearance",
"by",
"reversing",
"the",
"order",
"of",
"the",
"flex",
"box",
"but",
"then",
"the",
"visual",
"order",
"wouldn",
"t",
"reflect",
"the",
"document",
"order",
"which",
"determines",
"focus",
"order",
".",
"That",
"would",
"surprise",
"a",
"user",
"trying",
"to",
"tab",
"through",
"the",
"controls",
"."
] |
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
|
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/Explorer.js#L417-L433
|
12,818
|
adonisjs/adonis-lucid
|
src/Database/MonkeyPatch.js
|
generateAggregate
|
function generateAggregate (aggregateOp, defaultColumnName = undefined) {
let funcName = `get${_.upperFirst(aggregateOp)}`
/**
* Do not re-add the method if exists
*/
if (KnexQueryBuilder.prototype[funcName]) {
return
}
KnexQueryBuilder.prototype[funcName] = async function (columnName = defaultColumnName) {
if (!columnName) {
throw new Error(`'${funcName}' requires a column name.`)
}
const wrapper = new this.constructor(this.client)
const query = wrapper.from(this.as('__lucid'))
/**
* Copy events from the original query
*/
query._events = this._events
/**
* Executing query chain
*/
const results = await query[aggregateOp](`${columnName} as __lucid_aggregate`)
return results[0].__lucid_aggregate
}
}
|
javascript
|
function generateAggregate (aggregateOp, defaultColumnName = undefined) {
let funcName = `get${_.upperFirst(aggregateOp)}`
/**
* Do not re-add the method if exists
*/
if (KnexQueryBuilder.prototype[funcName]) {
return
}
KnexQueryBuilder.prototype[funcName] = async function (columnName = defaultColumnName) {
if (!columnName) {
throw new Error(`'${funcName}' requires a column name.`)
}
const wrapper = new this.constructor(this.client)
const query = wrapper.from(this.as('__lucid'))
/**
* Copy events from the original query
*/
query._events = this._events
/**
* Executing query chain
*/
const results = await query[aggregateOp](`${columnName} as __lucid_aggregate`)
return results[0].__lucid_aggregate
}
}
|
[
"function",
"generateAggregate",
"(",
"aggregateOp",
",",
"defaultColumnName",
"=",
"undefined",
")",
"{",
"let",
"funcName",
"=",
"`",
"${",
"_",
".",
"upperFirst",
"(",
"aggregateOp",
")",
"}",
"`",
"/**\n * Do not re-add the method if exists\n */",
"if",
"(",
"KnexQueryBuilder",
".",
"prototype",
"[",
"funcName",
"]",
")",
"{",
"return",
"}",
"KnexQueryBuilder",
".",
"prototype",
"[",
"funcName",
"]",
"=",
"async",
"function",
"(",
"columnName",
"=",
"defaultColumnName",
")",
"{",
"if",
"(",
"!",
"columnName",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"funcName",
"}",
"`",
")",
"}",
"const",
"wrapper",
"=",
"new",
"this",
".",
"constructor",
"(",
"this",
".",
"client",
")",
"const",
"query",
"=",
"wrapper",
".",
"from",
"(",
"this",
".",
"as",
"(",
"'__lucid'",
")",
")",
"/**\n * Copy events from the original query\n */",
"query",
".",
"_events",
"=",
"this",
".",
"_events",
"/**\n * Executing query chain\n */",
"const",
"results",
"=",
"await",
"query",
"[",
"aggregateOp",
"]",
"(",
"`",
"${",
"columnName",
"}",
"`",
")",
"return",
"results",
"[",
"0",
"]",
".",
"__lucid_aggregate",
"}",
"}"
] |
Generates an aggregate function, that returns the aggregated result
as a number.
@method generateAggregate
@param {String} aggregateOp
@param {String} defaultColumnName
@return {Number}
@example
```js
generateAggregate('count')
```
|
[
"Generates",
"an",
"aggregate",
"function",
"that",
"returns",
"the",
"aggregated",
"result",
"as",
"a",
"number",
"."
] |
6cd666df9534a981f4bd99ac0812a44d1685728a
|
https://github.com/adonisjs/adonis-lucid/blob/6cd666df9534a981f4bd99ac0812a44d1685728a/src/Database/MonkeyPatch.js#L182-L212
|
12,819
|
tscanlin/tocbot
|
src/js/parse-content.js
|
getHeadingObject
|
function getHeadingObject (heading) {
var obj = {
id: heading.id,
children: [],
nodeName: heading.nodeName,
headingLevel: getHeadingLevel(heading),
textContent: heading.textContent.trim()
}
if (options.includeHtml) {
obj.childNodes = heading.childNodes
}
return obj
}
|
javascript
|
function getHeadingObject (heading) {
var obj = {
id: heading.id,
children: [],
nodeName: heading.nodeName,
headingLevel: getHeadingLevel(heading),
textContent: heading.textContent.trim()
}
if (options.includeHtml) {
obj.childNodes = heading.childNodes
}
return obj
}
|
[
"function",
"getHeadingObject",
"(",
"heading",
")",
"{",
"var",
"obj",
"=",
"{",
"id",
":",
"heading",
".",
"id",
",",
"children",
":",
"[",
"]",
",",
"nodeName",
":",
"heading",
".",
"nodeName",
",",
"headingLevel",
":",
"getHeadingLevel",
"(",
"heading",
")",
",",
"textContent",
":",
"heading",
".",
"textContent",
".",
"trim",
"(",
")",
"}",
"if",
"(",
"options",
".",
"includeHtml",
")",
"{",
"obj",
".",
"childNodes",
"=",
"heading",
".",
"childNodes",
"}",
"return",
"obj",
"}"
] |
Get important properties from a heading element and store in a plain object.
@param {HTMLElement} heading
@return {Object}
|
[
"Get",
"important",
"properties",
"from",
"a",
"heading",
"element",
"and",
"store",
"in",
"a",
"plain",
"object",
"."
] |
b1437aea1efbb2cccc82180be7465ed2d54508be
|
https://github.com/tscanlin/tocbot/blob/b1437aea1efbb2cccc82180be7465ed2d54508be/src/js/parse-content.js#L34-L48
|
12,820
|
tscanlin/tocbot
|
src/js/parse-content.js
|
addNode
|
function addNode (node, nest) {
var obj = getHeadingObject(node)
var level = getHeadingLevel(node)
var array = nest
var lastItem = getLastItem(array)
var lastItemLevel = lastItem
? lastItem.headingLevel
: 0
var counter = level - lastItemLevel
while (counter > 0) {
lastItem = getLastItem(array)
if (lastItem && lastItem.children !== undefined) {
array = lastItem.children
}
counter--
}
if (level >= options.collapseDepth) {
obj.isCollapsed = true
}
array.push(obj)
return array
}
|
javascript
|
function addNode (node, nest) {
var obj = getHeadingObject(node)
var level = getHeadingLevel(node)
var array = nest
var lastItem = getLastItem(array)
var lastItemLevel = lastItem
? lastItem.headingLevel
: 0
var counter = level - lastItemLevel
while (counter > 0) {
lastItem = getLastItem(array)
if (lastItem && lastItem.children !== undefined) {
array = lastItem.children
}
counter--
}
if (level >= options.collapseDepth) {
obj.isCollapsed = true
}
array.push(obj)
return array
}
|
[
"function",
"addNode",
"(",
"node",
",",
"nest",
")",
"{",
"var",
"obj",
"=",
"getHeadingObject",
"(",
"node",
")",
"var",
"level",
"=",
"getHeadingLevel",
"(",
"node",
")",
"var",
"array",
"=",
"nest",
"var",
"lastItem",
"=",
"getLastItem",
"(",
"array",
")",
"var",
"lastItemLevel",
"=",
"lastItem",
"?",
"lastItem",
".",
"headingLevel",
":",
"0",
"var",
"counter",
"=",
"level",
"-",
"lastItemLevel",
"while",
"(",
"counter",
">",
"0",
")",
"{",
"lastItem",
"=",
"getLastItem",
"(",
"array",
")",
"if",
"(",
"lastItem",
"&&",
"lastItem",
".",
"children",
"!==",
"undefined",
")",
"{",
"array",
"=",
"lastItem",
".",
"children",
"}",
"counter",
"--",
"}",
"if",
"(",
"level",
">=",
"options",
".",
"collapseDepth",
")",
"{",
"obj",
".",
"isCollapsed",
"=",
"true",
"}",
"array",
".",
"push",
"(",
"obj",
")",
"return",
"array",
"}"
] |
Add a node to the nested array.
@param {Object} node
@param {Array} nest
@return {Array}
|
[
"Add",
"a",
"node",
"to",
"the",
"nested",
"array",
"."
] |
b1437aea1efbb2cccc82180be7465ed2d54508be
|
https://github.com/tscanlin/tocbot/blob/b1437aea1efbb2cccc82180be7465ed2d54508be/src/js/parse-content.js#L56-L80
|
12,821
|
tscanlin/tocbot
|
src/js/parse-content.js
|
selectHeadings
|
function selectHeadings (contentSelector, headingSelector) {
var selectors = headingSelector
if (options.ignoreSelector) {
selectors = headingSelector.split(',')
.map(function mapSelectors (selector) {
return selector.trim() + ':not(' + options.ignoreSelector + ')'
})
}
try {
return document.querySelector(contentSelector)
.querySelectorAll(selectors)
} catch (e) {
console.warn('Element not found: ' + contentSelector); // eslint-disable-line
return null
}
}
|
javascript
|
function selectHeadings (contentSelector, headingSelector) {
var selectors = headingSelector
if (options.ignoreSelector) {
selectors = headingSelector.split(',')
.map(function mapSelectors (selector) {
return selector.trim() + ':not(' + options.ignoreSelector + ')'
})
}
try {
return document.querySelector(contentSelector)
.querySelectorAll(selectors)
} catch (e) {
console.warn('Element not found: ' + contentSelector); // eslint-disable-line
return null
}
}
|
[
"function",
"selectHeadings",
"(",
"contentSelector",
",",
"headingSelector",
")",
"{",
"var",
"selectors",
"=",
"headingSelector",
"if",
"(",
"options",
".",
"ignoreSelector",
")",
"{",
"selectors",
"=",
"headingSelector",
".",
"split",
"(",
"','",
")",
".",
"map",
"(",
"function",
"mapSelectors",
"(",
"selector",
")",
"{",
"return",
"selector",
".",
"trim",
"(",
")",
"+",
"':not('",
"+",
"options",
".",
"ignoreSelector",
"+",
"')'",
"}",
")",
"}",
"try",
"{",
"return",
"document",
".",
"querySelector",
"(",
"contentSelector",
")",
".",
"querySelectorAll",
"(",
"selectors",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"warn",
"(",
"'Element not found: '",
"+",
"contentSelector",
")",
";",
"// eslint-disable-line",
"return",
"null",
"}",
"}"
] |
Select headings in content area, exclude any selector in options.ignoreSelector
@param {String} contentSelector
@param {Array} headingSelector
@return {Array}
|
[
"Select",
"headings",
"in",
"content",
"area",
"exclude",
"any",
"selector",
"in",
"options",
".",
"ignoreSelector"
] |
b1437aea1efbb2cccc82180be7465ed2d54508be
|
https://github.com/tscanlin/tocbot/blob/b1437aea1efbb2cccc82180be7465ed2d54508be/src/js/parse-content.js#L88-L103
|
12,822
|
tscanlin/tocbot
|
src/js/parse-content.js
|
nestHeadingsArray
|
function nestHeadingsArray (headingsArray) {
return reduce.call(headingsArray, function reducer (prev, curr) {
var currentHeading = getHeadingObject(curr)
addNode(currentHeading, prev.nest)
return prev
}, {
nest: []
})
}
|
javascript
|
function nestHeadingsArray (headingsArray) {
return reduce.call(headingsArray, function reducer (prev, curr) {
var currentHeading = getHeadingObject(curr)
addNode(currentHeading, prev.nest)
return prev
}, {
nest: []
})
}
|
[
"function",
"nestHeadingsArray",
"(",
"headingsArray",
")",
"{",
"return",
"reduce",
".",
"call",
"(",
"headingsArray",
",",
"function",
"reducer",
"(",
"prev",
",",
"curr",
")",
"{",
"var",
"currentHeading",
"=",
"getHeadingObject",
"(",
"curr",
")",
"addNode",
"(",
"currentHeading",
",",
"prev",
".",
"nest",
")",
"return",
"prev",
"}",
",",
"{",
"nest",
":",
"[",
"]",
"}",
")",
"}"
] |
Nest headings array into nested arrays with 'children' property.
@param {Array} headingsArray
@return {Object}
|
[
"Nest",
"headings",
"array",
"into",
"nested",
"arrays",
"with",
"children",
"property",
"."
] |
b1437aea1efbb2cccc82180be7465ed2d54508be
|
https://github.com/tscanlin/tocbot/blob/b1437aea1efbb2cccc82180be7465ed2d54508be/src/js/parse-content.js#L110-L119
|
12,823
|
tscanlin/tocbot
|
src/js/build-html.js
|
createEl
|
function createEl (d, container) {
var link = container.appendChild(createLink(d))
if (d.children.length) {
var list = createList(d.isCollapsed)
d.children.forEach(function (child) {
createEl(child, list)
})
link.appendChild(list)
}
}
|
javascript
|
function createEl (d, container) {
var link = container.appendChild(createLink(d))
if (d.children.length) {
var list = createList(d.isCollapsed)
d.children.forEach(function (child) {
createEl(child, list)
})
link.appendChild(list)
}
}
|
[
"function",
"createEl",
"(",
"d",
",",
"container",
")",
"{",
"var",
"link",
"=",
"container",
".",
"appendChild",
"(",
"createLink",
"(",
"d",
")",
")",
"if",
"(",
"d",
".",
"children",
".",
"length",
")",
"{",
"var",
"list",
"=",
"createList",
"(",
"d",
".",
"isCollapsed",
")",
"d",
".",
"children",
".",
"forEach",
"(",
"function",
"(",
"child",
")",
"{",
"createEl",
"(",
"child",
",",
"list",
")",
"}",
")",
"link",
".",
"appendChild",
"(",
"list",
")",
"}",
"}"
] |
Create link and list elements.
@param {Object} d
@param {HTMLElement} container
@return {HTMLElement}
|
[
"Create",
"link",
"and",
"list",
"elements",
"."
] |
b1437aea1efbb2cccc82180be7465ed2d54508be
|
https://github.com/tscanlin/tocbot/blob/b1437aea1efbb2cccc82180be7465ed2d54508be/src/js/build-html.js#L20-L29
|
12,824
|
tscanlin/tocbot
|
src/js/build-html.js
|
render
|
function render (selector, data) {
var collapsed = false
var container = createList(collapsed)
data.forEach(function (d) {
createEl(d, container)
})
var parent = document.querySelector(selector)
// Return if no parent is found.
if (parent === null) {
return
}
// Remove existing child if it exists.
if (parent.firstChild) {
parent.removeChild(parent.firstChild)
}
// Just return the parent and don't append the list if no links are found.
if (data.length === 0) {
return parent
}
// Append the Elements that have been created
return parent.appendChild(container)
}
|
javascript
|
function render (selector, data) {
var collapsed = false
var container = createList(collapsed)
data.forEach(function (d) {
createEl(d, container)
})
var parent = document.querySelector(selector)
// Return if no parent is found.
if (parent === null) {
return
}
// Remove existing child if it exists.
if (parent.firstChild) {
parent.removeChild(parent.firstChild)
}
// Just return the parent and don't append the list if no links are found.
if (data.length === 0) {
return parent
}
// Append the Elements that have been created
return parent.appendChild(container)
}
|
[
"function",
"render",
"(",
"selector",
",",
"data",
")",
"{",
"var",
"collapsed",
"=",
"false",
"var",
"container",
"=",
"createList",
"(",
"collapsed",
")",
"data",
".",
"forEach",
"(",
"function",
"(",
"d",
")",
"{",
"createEl",
"(",
"d",
",",
"container",
")",
"}",
")",
"var",
"parent",
"=",
"document",
".",
"querySelector",
"(",
"selector",
")",
"// Return if no parent is found.",
"if",
"(",
"parent",
"===",
"null",
")",
"{",
"return",
"}",
"// Remove existing child if it exists.",
"if",
"(",
"parent",
".",
"firstChild",
")",
"{",
"parent",
".",
"removeChild",
"(",
"parent",
".",
"firstChild",
")",
"}",
"// Just return the parent and don't append the list if no links are found.",
"if",
"(",
"data",
".",
"length",
"===",
"0",
")",
"{",
"return",
"parent",
"}",
"// Append the Elements that have been created",
"return",
"parent",
".",
"appendChild",
"(",
"container",
")",
"}"
] |
Render nested heading array data into a given selector.
@param {String} selector
@param {Array} data
@return {HTMLElement}
|
[
"Render",
"nested",
"heading",
"array",
"data",
"into",
"a",
"given",
"selector",
"."
] |
b1437aea1efbb2cccc82180be7465ed2d54508be
|
https://github.com/tscanlin/tocbot/blob/b1437aea1efbb2cccc82180be7465ed2d54508be/src/js/build-html.js#L37-L64
|
12,825
|
tscanlin/tocbot
|
src/js/build-html.js
|
createLink
|
function createLink (data) {
var item = document.createElement('li')
var a = document.createElement('a')
if (options.listItemClass) {
item.setAttribute('class', options.listItemClass)
}
if (options.onClick) {
a.onclick = options.onClick
}
if (options.includeHtml && data.childNodes.length) {
forEach.call(data.childNodes, function (node) {
a.appendChild(node.cloneNode(true))
})
} else {
// Default behavior.
a.textContent = data.textContent
}
a.setAttribute('href', '#' + data.id)
a.setAttribute('class', options.linkClass +
SPACE_CHAR + 'node-name--' + data.nodeName +
SPACE_CHAR + options.extraLinkClasses)
item.appendChild(a)
return item
}
|
javascript
|
function createLink (data) {
var item = document.createElement('li')
var a = document.createElement('a')
if (options.listItemClass) {
item.setAttribute('class', options.listItemClass)
}
if (options.onClick) {
a.onclick = options.onClick
}
if (options.includeHtml && data.childNodes.length) {
forEach.call(data.childNodes, function (node) {
a.appendChild(node.cloneNode(true))
})
} else {
// Default behavior.
a.textContent = data.textContent
}
a.setAttribute('href', '#' + data.id)
a.setAttribute('class', options.linkClass +
SPACE_CHAR + 'node-name--' + data.nodeName +
SPACE_CHAR + options.extraLinkClasses)
item.appendChild(a)
return item
}
|
[
"function",
"createLink",
"(",
"data",
")",
"{",
"var",
"item",
"=",
"document",
".",
"createElement",
"(",
"'li'",
")",
"var",
"a",
"=",
"document",
".",
"createElement",
"(",
"'a'",
")",
"if",
"(",
"options",
".",
"listItemClass",
")",
"{",
"item",
".",
"setAttribute",
"(",
"'class'",
",",
"options",
".",
"listItemClass",
")",
"}",
"if",
"(",
"options",
".",
"onClick",
")",
"{",
"a",
".",
"onclick",
"=",
"options",
".",
"onClick",
"}",
"if",
"(",
"options",
".",
"includeHtml",
"&&",
"data",
".",
"childNodes",
".",
"length",
")",
"{",
"forEach",
".",
"call",
"(",
"data",
".",
"childNodes",
",",
"function",
"(",
"node",
")",
"{",
"a",
".",
"appendChild",
"(",
"node",
".",
"cloneNode",
"(",
"true",
")",
")",
"}",
")",
"}",
"else",
"{",
"// Default behavior.",
"a",
".",
"textContent",
"=",
"data",
".",
"textContent",
"}",
"a",
".",
"setAttribute",
"(",
"'href'",
",",
"'#'",
"+",
"data",
".",
"id",
")",
"a",
".",
"setAttribute",
"(",
"'class'",
",",
"options",
".",
"linkClass",
"+",
"SPACE_CHAR",
"+",
"'node-name--'",
"+",
"data",
".",
"nodeName",
"+",
"SPACE_CHAR",
"+",
"options",
".",
"extraLinkClasses",
")",
"item",
".",
"appendChild",
"(",
"a",
")",
"return",
"item",
"}"
] |
Create link element.
@param {Object} data
@return {HTMLElement}
|
[
"Create",
"link",
"element",
"."
] |
b1437aea1efbb2cccc82180be7465ed2d54508be
|
https://github.com/tscanlin/tocbot/blob/b1437aea1efbb2cccc82180be7465ed2d54508be/src/js/build-html.js#L71-L96
|
12,826
|
tscanlin/tocbot
|
src/js/build-html.js
|
createList
|
function createList (isCollapsed) {
var listElement = (options.orderedList) ? 'ol' : 'ul'
var list = document.createElement(listElement)
var classes = options.listClass +
SPACE_CHAR + options.extraListClasses
if (isCollapsed) {
classes += SPACE_CHAR + options.collapsibleClass
classes += SPACE_CHAR + options.isCollapsedClass
}
list.setAttribute('class', classes)
return list
}
|
javascript
|
function createList (isCollapsed) {
var listElement = (options.orderedList) ? 'ol' : 'ul'
var list = document.createElement(listElement)
var classes = options.listClass +
SPACE_CHAR + options.extraListClasses
if (isCollapsed) {
classes += SPACE_CHAR + options.collapsibleClass
classes += SPACE_CHAR + options.isCollapsedClass
}
list.setAttribute('class', classes)
return list
}
|
[
"function",
"createList",
"(",
"isCollapsed",
")",
"{",
"var",
"listElement",
"=",
"(",
"options",
".",
"orderedList",
")",
"?",
"'ol'",
":",
"'ul'",
"var",
"list",
"=",
"document",
".",
"createElement",
"(",
"listElement",
")",
"var",
"classes",
"=",
"options",
".",
"listClass",
"+",
"SPACE_CHAR",
"+",
"options",
".",
"extraListClasses",
"if",
"(",
"isCollapsed",
")",
"{",
"classes",
"+=",
"SPACE_CHAR",
"+",
"options",
".",
"collapsibleClass",
"classes",
"+=",
"SPACE_CHAR",
"+",
"options",
".",
"isCollapsedClass",
"}",
"list",
".",
"setAttribute",
"(",
"'class'",
",",
"classes",
")",
"return",
"list",
"}"
] |
Create list element.
@param {Boolean} isCollapsed
@return {HTMLElement}
|
[
"Create",
"list",
"element",
"."
] |
b1437aea1efbb2cccc82180be7465ed2d54508be
|
https://github.com/tscanlin/tocbot/blob/b1437aea1efbb2cccc82180be7465ed2d54508be/src/js/build-html.js#L103-L114
|
12,827
|
tscanlin/tocbot
|
src/js/build-html.js
|
updateFixedSidebarClass
|
function updateFixedSidebarClass () {
if (options.scrollContainer && document.querySelector(options.scrollContainer)) {
var top = document.querySelector(options.scrollContainer).scrollTop
} else {
var top = document.documentElement.scrollTop || body.scrollTop
}
var posFixedEl = document.querySelector(options.positionFixedSelector)
if (options.fixedSidebarOffset === 'auto') {
options.fixedSidebarOffset = document.querySelector(options.tocSelector).offsetTop
}
if (top > options.fixedSidebarOffset) {
if (posFixedEl.className.indexOf(options.positionFixedClass) === -1) {
posFixedEl.className += SPACE_CHAR + options.positionFixedClass
}
} else {
posFixedEl.className = posFixedEl.className.split(SPACE_CHAR + options.positionFixedClass).join('')
}
}
|
javascript
|
function updateFixedSidebarClass () {
if (options.scrollContainer && document.querySelector(options.scrollContainer)) {
var top = document.querySelector(options.scrollContainer).scrollTop
} else {
var top = document.documentElement.scrollTop || body.scrollTop
}
var posFixedEl = document.querySelector(options.positionFixedSelector)
if (options.fixedSidebarOffset === 'auto') {
options.fixedSidebarOffset = document.querySelector(options.tocSelector).offsetTop
}
if (top > options.fixedSidebarOffset) {
if (posFixedEl.className.indexOf(options.positionFixedClass) === -1) {
posFixedEl.className += SPACE_CHAR + options.positionFixedClass
}
} else {
posFixedEl.className = posFixedEl.className.split(SPACE_CHAR + options.positionFixedClass).join('')
}
}
|
[
"function",
"updateFixedSidebarClass",
"(",
")",
"{",
"if",
"(",
"options",
".",
"scrollContainer",
"&&",
"document",
".",
"querySelector",
"(",
"options",
".",
"scrollContainer",
")",
")",
"{",
"var",
"top",
"=",
"document",
".",
"querySelector",
"(",
"options",
".",
"scrollContainer",
")",
".",
"scrollTop",
"}",
"else",
"{",
"var",
"top",
"=",
"document",
".",
"documentElement",
".",
"scrollTop",
"||",
"body",
".",
"scrollTop",
"}",
"var",
"posFixedEl",
"=",
"document",
".",
"querySelector",
"(",
"options",
".",
"positionFixedSelector",
")",
"if",
"(",
"options",
".",
"fixedSidebarOffset",
"===",
"'auto'",
")",
"{",
"options",
".",
"fixedSidebarOffset",
"=",
"document",
".",
"querySelector",
"(",
"options",
".",
"tocSelector",
")",
".",
"offsetTop",
"}",
"if",
"(",
"top",
">",
"options",
".",
"fixedSidebarOffset",
")",
"{",
"if",
"(",
"posFixedEl",
".",
"className",
".",
"indexOf",
"(",
"options",
".",
"positionFixedClass",
")",
"===",
"-",
"1",
")",
"{",
"posFixedEl",
".",
"className",
"+=",
"SPACE_CHAR",
"+",
"options",
".",
"positionFixedClass",
"}",
"}",
"else",
"{",
"posFixedEl",
".",
"className",
"=",
"posFixedEl",
".",
"className",
".",
"split",
"(",
"SPACE_CHAR",
"+",
"options",
".",
"positionFixedClass",
")",
".",
"join",
"(",
"''",
")",
"}",
"}"
] |
Update fixed sidebar class.
@return {HTMLElement}
|
[
"Update",
"fixed",
"sidebar",
"class",
"."
] |
b1437aea1efbb2cccc82180be7465ed2d54508be
|
https://github.com/tscanlin/tocbot/blob/b1437aea1efbb2cccc82180be7465ed2d54508be/src/js/build-html.js#L120-L139
|
12,828
|
tscanlin/tocbot
|
src/js/build-html.js
|
getHeadingTopPos
|
function getHeadingTopPos (obj) {
var position = 0
if (obj != document.querySelector(options.contentSelector && obj != null)) {
position = obj.offsetTop
if (options.hasInnerContainers)
position += getHeadingTopPos(obj.offsetParent)
}
return position
}
|
javascript
|
function getHeadingTopPos (obj) {
var position = 0
if (obj != document.querySelector(options.contentSelector && obj != null)) {
position = obj.offsetTop
if (options.hasInnerContainers)
position += getHeadingTopPos(obj.offsetParent)
}
return position
}
|
[
"function",
"getHeadingTopPos",
"(",
"obj",
")",
"{",
"var",
"position",
"=",
"0",
"if",
"(",
"obj",
"!=",
"document",
".",
"querySelector",
"(",
"options",
".",
"contentSelector",
"&&",
"obj",
"!=",
"null",
")",
")",
"{",
"position",
"=",
"obj",
".",
"offsetTop",
"if",
"(",
"options",
".",
"hasInnerContainers",
")",
"position",
"+=",
"getHeadingTopPos",
"(",
"obj",
".",
"offsetParent",
")",
"}",
"return",
"position",
"}"
] |
Get top position of heading
@param {HTMLElement}
@return {integer} position
|
[
"Get",
"top",
"position",
"of",
"heading"
] |
b1437aea1efbb2cccc82180be7465ed2d54508be
|
https://github.com/tscanlin/tocbot/blob/b1437aea1efbb2cccc82180be7465ed2d54508be/src/js/build-html.js#L146-L154
|
12,829
|
tscanlin/tocbot
|
src/js/build-html.js
|
updateToc
|
function updateToc (headingsArray) {
// If a fixed content container was set
if (options.scrollContainer && document.querySelector(options.scrollContainer)) {
var top = document.querySelector(options.scrollContainer).scrollTop
} else {
var top = document.documentElement.scrollTop || body.scrollTop
}
// Add fixed class at offset
if (options.positionFixedSelector) {
updateFixedSidebarClass()
}
// Get the top most heading currently visible on the page so we know what to highlight.
var headings = headingsArray
var topHeader
// Using some instead of each so that we can escape early.
if (currentlyHighlighting &&
document.querySelector(options.tocSelector) !== null &&
headings.length > 0) {
some.call(headings, function (heading, i) {
if (getHeadingTopPos(heading) > top + options.headingsOffset + 10) {
// Don't allow negative index value.
var index = (i === 0) ? i : i - 1
topHeader = headings[index]
return true
} else if (i === headings.length - 1) {
// This allows scrolling for the last heading on the page.
topHeader = headings[headings.length - 1]
return true
}
})
// Remove the active class from the other tocLinks.
var tocLinks = document.querySelector(options.tocSelector)
.querySelectorAll('.' + options.linkClass)
forEach.call(tocLinks, function (tocLink) {
tocLink.className = tocLink.className.split(SPACE_CHAR + options.activeLinkClass).join('')
})
var tocLis = document.querySelector(options.tocSelector)
.querySelectorAll('.' + options.listItemClass)
forEach.call(tocLis, function (tocLi) {
tocLi.className = tocLi.className.split(SPACE_CHAR + options.activeListItemClass).join('')
})
// Add the active class to the active tocLink.
var activeTocLink = document.querySelector(options.tocSelector)
.querySelector('.' + options.linkClass +
'.node-name--' + topHeader.nodeName +
'[href="#' + topHeader.id + '"]')
if (activeTocLink.className.indexOf(options.activeLinkClass) === -1) {
activeTocLink.className += SPACE_CHAR + options.activeLinkClass
}
var li = activeTocLink.parentNode
if (li && li.className.indexOf(options.activeListItemClass) === -1) {
li.className += SPACE_CHAR + options.activeListItemClass
}
var tocLists = document.querySelector(options.tocSelector)
.querySelectorAll('.' + options.listClass + '.' + options.collapsibleClass)
// Collapse the other collapsible lists.
forEach.call(tocLists, function (list) {
if (list.className.indexOf(options.isCollapsedClass) === -1) {
list.className += SPACE_CHAR + options.isCollapsedClass
}
})
// Expand the active link's collapsible list and its sibling if applicable.
if (activeTocLink.nextSibling && activeTocLink.nextSibling.className.indexOf(options.isCollapsedClass) !== -1) {
activeTocLink.nextSibling.className = activeTocLink.nextSibling.className.split(SPACE_CHAR + options.isCollapsedClass).join('')
}
removeCollapsedFromParents(activeTocLink.parentNode.parentNode)
}
}
|
javascript
|
function updateToc (headingsArray) {
// If a fixed content container was set
if (options.scrollContainer && document.querySelector(options.scrollContainer)) {
var top = document.querySelector(options.scrollContainer).scrollTop
} else {
var top = document.documentElement.scrollTop || body.scrollTop
}
// Add fixed class at offset
if (options.positionFixedSelector) {
updateFixedSidebarClass()
}
// Get the top most heading currently visible on the page so we know what to highlight.
var headings = headingsArray
var topHeader
// Using some instead of each so that we can escape early.
if (currentlyHighlighting &&
document.querySelector(options.tocSelector) !== null &&
headings.length > 0) {
some.call(headings, function (heading, i) {
if (getHeadingTopPos(heading) > top + options.headingsOffset + 10) {
// Don't allow negative index value.
var index = (i === 0) ? i : i - 1
topHeader = headings[index]
return true
} else if (i === headings.length - 1) {
// This allows scrolling for the last heading on the page.
topHeader = headings[headings.length - 1]
return true
}
})
// Remove the active class from the other tocLinks.
var tocLinks = document.querySelector(options.tocSelector)
.querySelectorAll('.' + options.linkClass)
forEach.call(tocLinks, function (tocLink) {
tocLink.className = tocLink.className.split(SPACE_CHAR + options.activeLinkClass).join('')
})
var tocLis = document.querySelector(options.tocSelector)
.querySelectorAll('.' + options.listItemClass)
forEach.call(tocLis, function (tocLi) {
tocLi.className = tocLi.className.split(SPACE_CHAR + options.activeListItemClass).join('')
})
// Add the active class to the active tocLink.
var activeTocLink = document.querySelector(options.tocSelector)
.querySelector('.' + options.linkClass +
'.node-name--' + topHeader.nodeName +
'[href="#' + topHeader.id + '"]')
if (activeTocLink.className.indexOf(options.activeLinkClass) === -1) {
activeTocLink.className += SPACE_CHAR + options.activeLinkClass
}
var li = activeTocLink.parentNode
if (li && li.className.indexOf(options.activeListItemClass) === -1) {
li.className += SPACE_CHAR + options.activeListItemClass
}
var tocLists = document.querySelector(options.tocSelector)
.querySelectorAll('.' + options.listClass + '.' + options.collapsibleClass)
// Collapse the other collapsible lists.
forEach.call(tocLists, function (list) {
if (list.className.indexOf(options.isCollapsedClass) === -1) {
list.className += SPACE_CHAR + options.isCollapsedClass
}
})
// Expand the active link's collapsible list and its sibling if applicable.
if (activeTocLink.nextSibling && activeTocLink.nextSibling.className.indexOf(options.isCollapsedClass) !== -1) {
activeTocLink.nextSibling.className = activeTocLink.nextSibling.className.split(SPACE_CHAR + options.isCollapsedClass).join('')
}
removeCollapsedFromParents(activeTocLink.parentNode.parentNode)
}
}
|
[
"function",
"updateToc",
"(",
"headingsArray",
")",
"{",
"// If a fixed content container was set",
"if",
"(",
"options",
".",
"scrollContainer",
"&&",
"document",
".",
"querySelector",
"(",
"options",
".",
"scrollContainer",
")",
")",
"{",
"var",
"top",
"=",
"document",
".",
"querySelector",
"(",
"options",
".",
"scrollContainer",
")",
".",
"scrollTop",
"}",
"else",
"{",
"var",
"top",
"=",
"document",
".",
"documentElement",
".",
"scrollTop",
"||",
"body",
".",
"scrollTop",
"}",
"// Add fixed class at offset",
"if",
"(",
"options",
".",
"positionFixedSelector",
")",
"{",
"updateFixedSidebarClass",
"(",
")",
"}",
"// Get the top most heading currently visible on the page so we know what to highlight.",
"var",
"headings",
"=",
"headingsArray",
"var",
"topHeader",
"// Using some instead of each so that we can escape early.",
"if",
"(",
"currentlyHighlighting",
"&&",
"document",
".",
"querySelector",
"(",
"options",
".",
"tocSelector",
")",
"!==",
"null",
"&&",
"headings",
".",
"length",
">",
"0",
")",
"{",
"some",
".",
"call",
"(",
"headings",
",",
"function",
"(",
"heading",
",",
"i",
")",
"{",
"if",
"(",
"getHeadingTopPos",
"(",
"heading",
")",
">",
"top",
"+",
"options",
".",
"headingsOffset",
"+",
"10",
")",
"{",
"// Don't allow negative index value.",
"var",
"index",
"=",
"(",
"i",
"===",
"0",
")",
"?",
"i",
":",
"i",
"-",
"1",
"topHeader",
"=",
"headings",
"[",
"index",
"]",
"return",
"true",
"}",
"else",
"if",
"(",
"i",
"===",
"headings",
".",
"length",
"-",
"1",
")",
"{",
"// This allows scrolling for the last heading on the page.",
"topHeader",
"=",
"headings",
"[",
"headings",
".",
"length",
"-",
"1",
"]",
"return",
"true",
"}",
"}",
")",
"// Remove the active class from the other tocLinks.",
"var",
"tocLinks",
"=",
"document",
".",
"querySelector",
"(",
"options",
".",
"tocSelector",
")",
".",
"querySelectorAll",
"(",
"'.'",
"+",
"options",
".",
"linkClass",
")",
"forEach",
".",
"call",
"(",
"tocLinks",
",",
"function",
"(",
"tocLink",
")",
"{",
"tocLink",
".",
"className",
"=",
"tocLink",
".",
"className",
".",
"split",
"(",
"SPACE_CHAR",
"+",
"options",
".",
"activeLinkClass",
")",
".",
"join",
"(",
"''",
")",
"}",
")",
"var",
"tocLis",
"=",
"document",
".",
"querySelector",
"(",
"options",
".",
"tocSelector",
")",
".",
"querySelectorAll",
"(",
"'.'",
"+",
"options",
".",
"listItemClass",
")",
"forEach",
".",
"call",
"(",
"tocLis",
",",
"function",
"(",
"tocLi",
")",
"{",
"tocLi",
".",
"className",
"=",
"tocLi",
".",
"className",
".",
"split",
"(",
"SPACE_CHAR",
"+",
"options",
".",
"activeListItemClass",
")",
".",
"join",
"(",
"''",
")",
"}",
")",
"// Add the active class to the active tocLink.",
"var",
"activeTocLink",
"=",
"document",
".",
"querySelector",
"(",
"options",
".",
"tocSelector",
")",
".",
"querySelector",
"(",
"'.'",
"+",
"options",
".",
"linkClass",
"+",
"'.node-name--'",
"+",
"topHeader",
".",
"nodeName",
"+",
"'[href=\"#'",
"+",
"topHeader",
".",
"id",
"+",
"'\"]'",
")",
"if",
"(",
"activeTocLink",
".",
"className",
".",
"indexOf",
"(",
"options",
".",
"activeLinkClass",
")",
"===",
"-",
"1",
")",
"{",
"activeTocLink",
".",
"className",
"+=",
"SPACE_CHAR",
"+",
"options",
".",
"activeLinkClass",
"}",
"var",
"li",
"=",
"activeTocLink",
".",
"parentNode",
"if",
"(",
"li",
"&&",
"li",
".",
"className",
".",
"indexOf",
"(",
"options",
".",
"activeListItemClass",
")",
"===",
"-",
"1",
")",
"{",
"li",
".",
"className",
"+=",
"SPACE_CHAR",
"+",
"options",
".",
"activeListItemClass",
"}",
"var",
"tocLists",
"=",
"document",
".",
"querySelector",
"(",
"options",
".",
"tocSelector",
")",
".",
"querySelectorAll",
"(",
"'.'",
"+",
"options",
".",
"listClass",
"+",
"'.'",
"+",
"options",
".",
"collapsibleClass",
")",
"// Collapse the other collapsible lists.",
"forEach",
".",
"call",
"(",
"tocLists",
",",
"function",
"(",
"list",
")",
"{",
"if",
"(",
"list",
".",
"className",
".",
"indexOf",
"(",
"options",
".",
"isCollapsedClass",
")",
"===",
"-",
"1",
")",
"{",
"list",
".",
"className",
"+=",
"SPACE_CHAR",
"+",
"options",
".",
"isCollapsedClass",
"}",
"}",
")",
"// Expand the active link's collapsible list and its sibling if applicable.",
"if",
"(",
"activeTocLink",
".",
"nextSibling",
"&&",
"activeTocLink",
".",
"nextSibling",
".",
"className",
".",
"indexOf",
"(",
"options",
".",
"isCollapsedClass",
")",
"!==",
"-",
"1",
")",
"{",
"activeTocLink",
".",
"nextSibling",
".",
"className",
"=",
"activeTocLink",
".",
"nextSibling",
".",
"className",
".",
"split",
"(",
"SPACE_CHAR",
"+",
"options",
".",
"isCollapsedClass",
")",
".",
"join",
"(",
"''",
")",
"}",
"removeCollapsedFromParents",
"(",
"activeTocLink",
".",
"parentNode",
".",
"parentNode",
")",
"}",
"}"
] |
Update TOC highlighting and collpased groupings.
|
[
"Update",
"TOC",
"highlighting",
"and",
"collpased",
"groupings",
"."
] |
b1437aea1efbb2cccc82180be7465ed2d54508be
|
https://github.com/tscanlin/tocbot/blob/b1437aea1efbb2cccc82180be7465ed2d54508be/src/js/build-html.js#L159-L233
|
12,830
|
tscanlin/tocbot
|
src/js/build-html.js
|
removeCollapsedFromParents
|
function removeCollapsedFromParents (element) {
if (element.className.indexOf(options.collapsibleClass) !== -1 && element.className.indexOf(options.isCollapsedClass) !== -1) {
element.className = element.className.split(SPACE_CHAR + options.isCollapsedClass).join('')
return removeCollapsedFromParents(element.parentNode.parentNode)
}
return element
}
|
javascript
|
function removeCollapsedFromParents (element) {
if (element.className.indexOf(options.collapsibleClass) !== -1 && element.className.indexOf(options.isCollapsedClass) !== -1) {
element.className = element.className.split(SPACE_CHAR + options.isCollapsedClass).join('')
return removeCollapsedFromParents(element.parentNode.parentNode)
}
return element
}
|
[
"function",
"removeCollapsedFromParents",
"(",
"element",
")",
"{",
"if",
"(",
"element",
".",
"className",
".",
"indexOf",
"(",
"options",
".",
"collapsibleClass",
")",
"!==",
"-",
"1",
"&&",
"element",
".",
"className",
".",
"indexOf",
"(",
"options",
".",
"isCollapsedClass",
")",
"!==",
"-",
"1",
")",
"{",
"element",
".",
"className",
"=",
"element",
".",
"className",
".",
"split",
"(",
"SPACE_CHAR",
"+",
"options",
".",
"isCollapsedClass",
")",
".",
"join",
"(",
"''",
")",
"return",
"removeCollapsedFromParents",
"(",
"element",
".",
"parentNode",
".",
"parentNode",
")",
"}",
"return",
"element",
"}"
] |
Remove collpased class from parent elements.
@param {HTMLElement} element
@return {HTMLElement}
|
[
"Remove",
"collpased",
"class",
"from",
"parent",
"elements",
"."
] |
b1437aea1efbb2cccc82180be7465ed2d54508be
|
https://github.com/tscanlin/tocbot/blob/b1437aea1efbb2cccc82180be7465ed2d54508be/src/js/build-html.js#L240-L246
|
12,831
|
tscanlin/tocbot
|
src/js/build-html.js
|
disableTocAnimation
|
function disableTocAnimation (event) {
var target = event.target || event.srcElement
if (typeof target.className !== 'string' || target.className.indexOf(options.linkClass) === -1) {
return
}
// Bind to tocLink clicks to temporarily disable highlighting
// while smoothScroll is animating.
currentlyHighlighting = false
}
|
javascript
|
function disableTocAnimation (event) {
var target = event.target || event.srcElement
if (typeof target.className !== 'string' || target.className.indexOf(options.linkClass) === -1) {
return
}
// Bind to tocLink clicks to temporarily disable highlighting
// while smoothScroll is animating.
currentlyHighlighting = false
}
|
[
"function",
"disableTocAnimation",
"(",
"event",
")",
"{",
"var",
"target",
"=",
"event",
".",
"target",
"||",
"event",
".",
"srcElement",
"if",
"(",
"typeof",
"target",
".",
"className",
"!==",
"'string'",
"||",
"target",
".",
"className",
".",
"indexOf",
"(",
"options",
".",
"linkClass",
")",
"===",
"-",
"1",
")",
"{",
"return",
"}",
"// Bind to tocLink clicks to temporarily disable highlighting",
"// while smoothScroll is animating.",
"currentlyHighlighting",
"=",
"false",
"}"
] |
Disable TOC Animation when a link is clicked.
@param {Event} event
|
[
"Disable",
"TOC",
"Animation",
"when",
"a",
"link",
"is",
"clicked",
"."
] |
b1437aea1efbb2cccc82180be7465ed2d54508be
|
https://github.com/tscanlin/tocbot/blob/b1437aea1efbb2cccc82180be7465ed2d54508be/src/js/build-html.js#L252-L260
|
12,832
|
paulkr/overhang.js
|
lib/overhang.js
|
raise
|
function raise (runCallback, identifier) {
$overlay.fadeOut(100);
$overhang.slideUp(attributes.speed, function () {
if (runCallback) {
attributes.callback(identifier !== null ? $element.data(identifier) : "");
}
});
}
|
javascript
|
function raise (runCallback, identifier) {
$overlay.fadeOut(100);
$overhang.slideUp(attributes.speed, function () {
if (runCallback) {
attributes.callback(identifier !== null ? $element.data(identifier) : "");
}
});
}
|
[
"function",
"raise",
"(",
"runCallback",
",",
"identifier",
")",
"{",
"$overlay",
".",
"fadeOut",
"(",
"100",
")",
";",
"$overhang",
".",
"slideUp",
"(",
"attributes",
".",
"speed",
",",
"function",
"(",
")",
"{",
"if",
"(",
"runCallback",
")",
"{",
"attributes",
".",
"callback",
"(",
"identifier",
"!==",
"null",
"?",
"$element",
".",
"data",
"(",
"identifier",
")",
":",
"\"\"",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Raise the overhang alert
|
[
"Raise",
"the",
"overhang",
"alert"
] |
97ad104aca7ce24b5de3239df0c00cd946ffe06e
|
https://github.com/paulkr/overhang.js/blob/97ad104aca7ce24b5de3239df0c00cd946ffe06e/lib/overhang.js#L53-L60
|
12,833
|
gregjacobs/Autolinker.js
|
gulpfile.js
|
buildSrcCheckMinifiedSizeTask
|
async function buildSrcCheckMinifiedSizeTask() {
const stats = await fs.stat( './dist/Autolinker.min.js' );
const sizeInKb = stats.size / 1000;
const maxExpectedSizeInKb = 46;
if( sizeInKb > maxExpectedSizeInKb ) {
throw new Error( `
Minified file size of ${sizeInKb.toFixed( 2 )}kb is greater than max
expected minified size of ${maxExpectedSizeInKb}kb
This check is to make sure that a dependency is not accidentally
added which significantly inflates the size of Autolinker. If
additions to the codebase have been made though and a higher size
is expected, bump the 'maxExpectedSizeInKb' number in gulpfile.js
`.trim().replace( /^\t*/gm, '' ) );
}
}
|
javascript
|
async function buildSrcCheckMinifiedSizeTask() {
const stats = await fs.stat( './dist/Autolinker.min.js' );
const sizeInKb = stats.size / 1000;
const maxExpectedSizeInKb = 46;
if( sizeInKb > maxExpectedSizeInKb ) {
throw new Error( `
Minified file size of ${sizeInKb.toFixed( 2 )}kb is greater than max
expected minified size of ${maxExpectedSizeInKb}kb
This check is to make sure that a dependency is not accidentally
added which significantly inflates the size of Autolinker. If
additions to the codebase have been made though and a higher size
is expected, bump the 'maxExpectedSizeInKb' number in gulpfile.js
`.trim().replace( /^\t*/gm, '' ) );
}
}
|
[
"async",
"function",
"buildSrcCheckMinifiedSizeTask",
"(",
")",
"{",
"const",
"stats",
"=",
"await",
"fs",
".",
"stat",
"(",
"'./dist/Autolinker.min.js'",
")",
";",
"const",
"sizeInKb",
"=",
"stats",
".",
"size",
"/",
"1000",
";",
"const",
"maxExpectedSizeInKb",
"=",
"46",
";",
"if",
"(",
"sizeInKb",
">",
"maxExpectedSizeInKb",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"sizeInKb",
".",
"toFixed",
"(",
"2",
")",
"}",
"${",
"maxExpectedSizeInKb",
"}",
"`",
".",
"trim",
"(",
")",
".",
"replace",
"(",
"/",
"^\\t*",
"/",
"gm",
",",
"''",
")",
")",
";",
"}",
"}"
] |
Checks that we don't accidentally add an extra dependency that bloats the
minified size of Autolinker
|
[
"Checks",
"that",
"we",
"don",
"t",
"accidentally",
"add",
"an",
"extra",
"dependency",
"that",
"bloats",
"the",
"minified",
"size",
"of",
"Autolinker"
] |
acdf9a5dd9208f27c144efaa068ae4b5d924b38c
|
https://github.com/gregjacobs/Autolinker.js/blob/acdf9a5dd9208f27c144efaa068ae4b5d924b38c/gulpfile.js#L295-L311
|
12,834
|
chariotsolutions/phonegap-nfc
|
www/phonegap-nfc-blackberry.js
|
function(ndefMessageAsString) {
"use strict";
var ndefMessage = JSON.parse(ndefMessageAsString);
cordova.fireDocumentEvent("ndef", {
type: "ndef",
tag: {
ndefMessage: ndefMessage
}
});
}
|
javascript
|
function(ndefMessageAsString) {
"use strict";
var ndefMessage = JSON.parse(ndefMessageAsString);
cordova.fireDocumentEvent("ndef", {
type: "ndef",
tag: {
ndefMessage: ndefMessage
}
});
}
|
[
"function",
"(",
"ndefMessageAsString",
")",
"{",
"\"use strict\"",
";",
"var",
"ndefMessage",
"=",
"JSON",
".",
"parse",
"(",
"ndefMessageAsString",
")",
";",
"cordova",
".",
"fireDocumentEvent",
"(",
"\"ndef\"",
",",
"{",
"type",
":",
"\"ndef\"",
",",
"tag",
":",
"{",
"ndefMessage",
":",
"ndefMessage",
"}",
"}",
")",
";",
"}"
] |
takes an ndefMessage from the success callback and fires a javascript event
|
[
"takes",
"an",
"ndefMessage",
"from",
"the",
"success",
"callback",
"and",
"fires",
"a",
"javascript",
"event"
] |
aa92afca3686dff038d71d2ecb270c62e07c4bcb
|
https://github.com/chariotsolutions/phonegap-nfc/blob/aa92afca3686dff038d71d2ecb270c62e07c4bcb/www/phonegap-nfc-blackberry.js#L59-L68
|
|
12,835
|
chariotsolutions/phonegap-nfc
|
src/blackberry10/index.js
|
function(pluginResult, payloadString) {
var payload = JSON.parse(payloadString),
ndefObjectAsString = JSON.stringify(decode(b64toArray(payload.data)));
pluginResult.callbackOk(ndefObjectAsString, true);
}
|
javascript
|
function(pluginResult, payloadString) {
var payload = JSON.parse(payloadString),
ndefObjectAsString = JSON.stringify(decode(b64toArray(payload.data)));
pluginResult.callbackOk(ndefObjectAsString, true);
}
|
[
"function",
"(",
"pluginResult",
",",
"payloadString",
")",
"{",
"var",
"payload",
"=",
"JSON",
".",
"parse",
"(",
"payloadString",
")",
",",
"ndefObjectAsString",
"=",
"JSON",
".",
"stringify",
"(",
"decode",
"(",
"b64toArray",
"(",
"payload",
".",
"data",
")",
")",
")",
";",
"pluginResult",
".",
"callbackOk",
"(",
"ndefObjectAsString",
",",
"true",
")",
";",
"}"
] |
called by invoke, when NFC tag is scanned
|
[
"called",
"by",
"invoke",
"when",
"NFC",
"tag",
"is",
"scanned"
] |
aa92afca3686dff038d71d2ecb270c62e07c4bcb
|
https://github.com/chariotsolutions/phonegap-nfc/blob/aa92afca3686dff038d71d2ecb270c62e07c4bcb/src/blackberry10/index.js#L127-L131
|
|
12,836
|
FaridSafi/react-native-gifted-form
|
GiftedFormManager.js
|
formatValues
|
function formatValues(values) {
var formatted = {};
for (var key in values) {
if (values.hasOwnProperty(key)) {
if (typeof values[key] === 'boolean') {
var position = key.indexOf('{');
if (position !== -1) {
if (values[key] === true) {
// Each options of SelectWidget are stored as boolean and grouped using '{' and '}'
// eg:
// gender{male} = true
// gender{female} = false
var newKey = key.substr(0, position);
var newValue = key.substr(position);
newValue = newValue.replace('{', '');
newValue = newValue.replace('}', '');
if (!Array.isArray(formatted[newKey])) {
formatted[newKey] = [];
}
formatted[newKey].push(newValue);
}
} else {
formatted[key] = values[key];
}
} else {
if (typeof values[key] === 'string') {
formatted[key] = values[key].trim();
} else {
formatted[key] = values[key];
}
}
}
}
return formatted;
}
|
javascript
|
function formatValues(values) {
var formatted = {};
for (var key in values) {
if (values.hasOwnProperty(key)) {
if (typeof values[key] === 'boolean') {
var position = key.indexOf('{');
if (position !== -1) {
if (values[key] === true) {
// Each options of SelectWidget are stored as boolean and grouped using '{' and '}'
// eg:
// gender{male} = true
// gender{female} = false
var newKey = key.substr(0, position);
var newValue = key.substr(position);
newValue = newValue.replace('{', '');
newValue = newValue.replace('}', '');
if (!Array.isArray(formatted[newKey])) {
formatted[newKey] = [];
}
formatted[newKey].push(newValue);
}
} else {
formatted[key] = values[key];
}
} else {
if (typeof values[key] === 'string') {
formatted[key] = values[key].trim();
} else {
formatted[key] = values[key];
}
}
}
}
return formatted;
}
|
[
"function",
"formatValues",
"(",
"values",
")",
"{",
"var",
"formatted",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"key",
"in",
"values",
")",
"{",
"if",
"(",
"values",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"if",
"(",
"typeof",
"values",
"[",
"key",
"]",
"===",
"'boolean'",
")",
"{",
"var",
"position",
"=",
"key",
".",
"indexOf",
"(",
"'{'",
")",
";",
"if",
"(",
"position",
"!==",
"-",
"1",
")",
"{",
"if",
"(",
"values",
"[",
"key",
"]",
"===",
"true",
")",
"{",
"// Each options of SelectWidget are stored as boolean and grouped using '{' and '}'",
"// eg:",
"// gender{male} = true",
"// gender{female} = false",
"var",
"newKey",
"=",
"key",
".",
"substr",
"(",
"0",
",",
"position",
")",
";",
"var",
"newValue",
"=",
"key",
".",
"substr",
"(",
"position",
")",
";",
"newValue",
"=",
"newValue",
".",
"replace",
"(",
"'{'",
",",
"''",
")",
";",
"newValue",
"=",
"newValue",
".",
"replace",
"(",
"'}'",
",",
"''",
")",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"formatted",
"[",
"newKey",
"]",
")",
")",
"{",
"formatted",
"[",
"newKey",
"]",
"=",
"[",
"]",
";",
"}",
"formatted",
"[",
"newKey",
"]",
".",
"push",
"(",
"newValue",
")",
";",
"}",
"}",
"else",
"{",
"formatted",
"[",
"key",
"]",
"=",
"values",
"[",
"key",
"]",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"typeof",
"values",
"[",
"key",
"]",
"===",
"'string'",
")",
"{",
"formatted",
"[",
"key",
"]",
"=",
"values",
"[",
"key",
"]",
".",
"trim",
"(",
")",
";",
"}",
"else",
"{",
"formatted",
"[",
"key",
"]",
"=",
"values",
"[",
"key",
"]",
";",
"}",
"}",
"}",
"}",
"return",
"formatted",
";",
"}"
] |
the select widgets values need to be formated because even when the values are 'False' they are stored formatValues return only selected values of select widgets
|
[
"the",
"select",
"widgets",
"values",
"need",
"to",
"be",
"formated",
"because",
"even",
"when",
"the",
"values",
"are",
"False",
"they",
"are",
"stored",
"formatValues",
"return",
"only",
"selected",
"values",
"of",
"select",
"widgets"
] |
7910cb47157b35841f93d72febb39317dc0002c0
|
https://github.com/FaridSafi/react-native-gifted-form/blob/7910cb47157b35841f93d72febb39317dc0002c0/GiftedFormManager.js#L94-L128
|
12,837
|
mhart/aws4
|
aws4.js
|
encodeRfc3986
|
function encodeRfc3986(urlEncodedString) {
return urlEncodedString.replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
}
|
javascript
|
function encodeRfc3986(urlEncodedString) {
return urlEncodedString.replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
}
|
[
"function",
"encodeRfc3986",
"(",
"urlEncodedString",
")",
"{",
"return",
"urlEncodedString",
".",
"replace",
"(",
"/",
"[!'()*]",
"/",
"g",
",",
"function",
"(",
"c",
")",
"{",
"return",
"'%'",
"+",
"c",
".",
"charCodeAt",
"(",
"0",
")",
".",
"toString",
"(",
"16",
")",
".",
"toUpperCase",
"(",
")",
"}",
")",
"}"
] |
This function assumes the string has already been percent encoded
|
[
"This",
"function",
"assumes",
"the",
"string",
"has",
"already",
"been",
"percent",
"encoded"
] |
e2052432f836af766b33ce5782a3bfa21f40db99
|
https://github.com/mhart/aws4/blob/e2052432f836af766b33ce5782a3bfa21f40db99/aws4.js#L19-L23
|
12,838
|
alexeyten/qr-image
|
lib/qr-base.js
|
getTemplate
|
function getTemplate(message, ec_level) {
var i = 1;
var len;
if (message.data1) {
len = Math.ceil(message.data1.length / 8);
} else {
i = 10;
}
for (/* i */; i < 10; i++) {
var version = versions[i][ec_level];
if (version.data_len >= len) {
return _deepCopy(version);
}
}
if (message.data10) {
len = Math.ceil(message.data10.length / 8);
} else {
i = 27;
}
for (/* i */; i < 27; i++) {
var version = versions[i][ec_level];
if (version.data_len >= len) {
return _deepCopy(version);
}
}
len = Math.ceil(message.data27.length / 8);
for (/* i */; i < 41; i++) {
var version = versions[i][ec_level];
if (version.data_len >= len) {
return _deepCopy(version);
}
}
throw new Error("Too much data");
}
|
javascript
|
function getTemplate(message, ec_level) {
var i = 1;
var len;
if (message.data1) {
len = Math.ceil(message.data1.length / 8);
} else {
i = 10;
}
for (/* i */; i < 10; i++) {
var version = versions[i][ec_level];
if (version.data_len >= len) {
return _deepCopy(version);
}
}
if (message.data10) {
len = Math.ceil(message.data10.length / 8);
} else {
i = 27;
}
for (/* i */; i < 27; i++) {
var version = versions[i][ec_level];
if (version.data_len >= len) {
return _deepCopy(version);
}
}
len = Math.ceil(message.data27.length / 8);
for (/* i */; i < 41; i++) {
var version = versions[i][ec_level];
if (version.data_len >= len) {
return _deepCopy(version);
}
}
throw new Error("Too much data");
}
|
[
"function",
"getTemplate",
"(",
"message",
",",
"ec_level",
")",
"{",
"var",
"i",
"=",
"1",
";",
"var",
"len",
";",
"if",
"(",
"message",
".",
"data1",
")",
"{",
"len",
"=",
"Math",
".",
"ceil",
"(",
"message",
".",
"data1",
".",
"length",
"/",
"8",
")",
";",
"}",
"else",
"{",
"i",
"=",
"10",
";",
"}",
"for",
"(",
"/* i */",
";",
"i",
"<",
"10",
";",
"i",
"++",
")",
"{",
"var",
"version",
"=",
"versions",
"[",
"i",
"]",
"[",
"ec_level",
"]",
";",
"if",
"(",
"version",
".",
"data_len",
">=",
"len",
")",
"{",
"return",
"_deepCopy",
"(",
"version",
")",
";",
"}",
"}",
"if",
"(",
"message",
".",
"data10",
")",
"{",
"len",
"=",
"Math",
".",
"ceil",
"(",
"message",
".",
"data10",
".",
"length",
"/",
"8",
")",
";",
"}",
"else",
"{",
"i",
"=",
"27",
";",
"}",
"for",
"(",
"/* i */",
";",
"i",
"<",
"27",
";",
"i",
"++",
")",
"{",
"var",
"version",
"=",
"versions",
"[",
"i",
"]",
"[",
"ec_level",
"]",
";",
"if",
"(",
"version",
".",
"data_len",
">=",
"len",
")",
"{",
"return",
"_deepCopy",
"(",
"version",
")",
";",
"}",
"}",
"len",
"=",
"Math",
".",
"ceil",
"(",
"message",
".",
"data27",
".",
"length",
"/",
"8",
")",
";",
"for",
"(",
"/* i */",
";",
"i",
"<",
"41",
";",
"i",
"++",
")",
"{",
"var",
"version",
"=",
"versions",
"[",
"i",
"]",
"[",
"ec_level",
"]",
";",
"if",
"(",
"version",
".",
"data_len",
">=",
"len",
")",
"{",
"return",
"_deepCopy",
"(",
"version",
")",
";",
"}",
"}",
"throw",
"new",
"Error",
"(",
"\"Too much data\"",
")",
";",
"}"
] |
{{{1 Get version template
|
[
"{{{",
"1",
"Get",
"version",
"template"
] |
9b5ee0e8f38152f29cfd59eedaf037fafb47e740
|
https://github.com/alexeyten/qr-image/blob/9b5ee0e8f38152f29cfd59eedaf037fafb47e740/lib/qr-base.js#L89-L125
|
12,839
|
alexeyten/qr-image
|
lib/qr-base.js
|
fillTemplate
|
function fillTemplate(message, template) {
var blocks = new Buffer(template.data_len);
blocks.fill(0);
if (template.version < 10) {
message = message.data1;
} else if (template.version < 27) {
message = message.data10;
} else {
message = message.data27;
}
var len = message.length;
for (var i = 0; i < len; i += 8) {
var b = 0;
for (var j = 0; j < 8; j++) {
b = (b << 1) | (message[i + j] ? 1 : 0);
}
blocks[i / 8] = b;
}
var pad = 236;
for (var i = Math.ceil((len + 4) / 8); i < blocks.length; i++) {
blocks[i] = pad;
pad = (pad == 236) ? 17 : 236;
}
var offset = 0;
template.blocks = template.blocks.map(function(n) {
var b = blocks.slice(offset, offset + n);
offset += n;
template.ec.push(calculateEC(b, template.ec_len));
return b;
});
return template;
}
|
javascript
|
function fillTemplate(message, template) {
var blocks = new Buffer(template.data_len);
blocks.fill(0);
if (template.version < 10) {
message = message.data1;
} else if (template.version < 27) {
message = message.data10;
} else {
message = message.data27;
}
var len = message.length;
for (var i = 0; i < len; i += 8) {
var b = 0;
for (var j = 0; j < 8; j++) {
b = (b << 1) | (message[i + j] ? 1 : 0);
}
blocks[i / 8] = b;
}
var pad = 236;
for (var i = Math.ceil((len + 4) / 8); i < blocks.length; i++) {
blocks[i] = pad;
pad = (pad == 236) ? 17 : 236;
}
var offset = 0;
template.blocks = template.blocks.map(function(n) {
var b = blocks.slice(offset, offset + n);
offset += n;
template.ec.push(calculateEC(b, template.ec_len));
return b;
});
return template;
}
|
[
"function",
"fillTemplate",
"(",
"message",
",",
"template",
")",
"{",
"var",
"blocks",
"=",
"new",
"Buffer",
"(",
"template",
".",
"data_len",
")",
";",
"blocks",
".",
"fill",
"(",
"0",
")",
";",
"if",
"(",
"template",
".",
"version",
"<",
"10",
")",
"{",
"message",
"=",
"message",
".",
"data1",
";",
"}",
"else",
"if",
"(",
"template",
".",
"version",
"<",
"27",
")",
"{",
"message",
"=",
"message",
".",
"data10",
";",
"}",
"else",
"{",
"message",
"=",
"message",
".",
"data27",
";",
"}",
"var",
"len",
"=",
"message",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"8",
")",
"{",
"var",
"b",
"=",
"0",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"8",
";",
"j",
"++",
")",
"{",
"b",
"=",
"(",
"b",
"<<",
"1",
")",
"|",
"(",
"message",
"[",
"i",
"+",
"j",
"]",
"?",
"1",
":",
"0",
")",
";",
"}",
"blocks",
"[",
"i",
"/",
"8",
"]",
"=",
"b",
";",
"}",
"var",
"pad",
"=",
"236",
";",
"for",
"(",
"var",
"i",
"=",
"Math",
".",
"ceil",
"(",
"(",
"len",
"+",
"4",
")",
"/",
"8",
")",
";",
"i",
"<",
"blocks",
".",
"length",
";",
"i",
"++",
")",
"{",
"blocks",
"[",
"i",
"]",
"=",
"pad",
";",
"pad",
"=",
"(",
"pad",
"==",
"236",
")",
"?",
"17",
":",
"236",
";",
"}",
"var",
"offset",
"=",
"0",
";",
"template",
".",
"blocks",
"=",
"template",
".",
"blocks",
".",
"map",
"(",
"function",
"(",
"n",
")",
"{",
"var",
"b",
"=",
"blocks",
".",
"slice",
"(",
"offset",
",",
"offset",
"+",
"n",
")",
";",
"offset",
"+=",
"n",
";",
"template",
".",
"ec",
".",
"push",
"(",
"calculateEC",
"(",
"b",
",",
"template",
".",
"ec_len",
")",
")",
";",
"return",
"b",
";",
"}",
")",
";",
"return",
"template",
";",
"}"
] |
{{{1 Fill template
|
[
"{{{",
"1",
"Fill",
"template"
] |
9b5ee0e8f38152f29cfd59eedaf037fafb47e740
|
https://github.com/alexeyten/qr-image/blob/9b5ee0e8f38152f29cfd59eedaf037fafb47e740/lib/qr-base.js#L128-L165
|
12,840
|
alexeyten/qr-image
|
lib/qr-base.js
|
QR
|
function QR(text, ec_level, parse_url) {
ec_level = EC_LEVELS.indexOf(ec_level) > -1 ? ec_level : 'M';
var message = encode(text, parse_url);
var data = fillTemplate(message, getTemplate(message, ec_level));
return matrix.getMatrix(data);
}
|
javascript
|
function QR(text, ec_level, parse_url) {
ec_level = EC_LEVELS.indexOf(ec_level) > -1 ? ec_level : 'M';
var message = encode(text, parse_url);
var data = fillTemplate(message, getTemplate(message, ec_level));
return matrix.getMatrix(data);
}
|
[
"function",
"QR",
"(",
"text",
",",
"ec_level",
",",
"parse_url",
")",
"{",
"ec_level",
"=",
"EC_LEVELS",
".",
"indexOf",
"(",
"ec_level",
")",
">",
"-",
"1",
"?",
"ec_level",
":",
"'M'",
";",
"var",
"message",
"=",
"encode",
"(",
"text",
",",
"parse_url",
")",
";",
"var",
"data",
"=",
"fillTemplate",
"(",
"message",
",",
"getTemplate",
"(",
"message",
",",
"ec_level",
")",
")",
";",
"return",
"matrix",
".",
"getMatrix",
"(",
"data",
")",
";",
"}"
] |
{{{1 All-in-one
|
[
"{{{",
"1",
"All",
"-",
"in",
"-",
"one"
] |
9b5ee0e8f38152f29cfd59eedaf037fafb47e740
|
https://github.com/alexeyten/qr-image/blob/9b5ee0e8f38152f29cfd59eedaf037fafb47e740/lib/qr-base.js#L168-L173
|
12,841
|
alexeyten/qr-image
|
lib/encode.js
|
encode_8bit
|
function encode_8bit(data) {
var len = data.length;
var bits = [];
for (var i = 0; i < len; i++) {
pushBits(bits, 8, data[i]);
}
var res = {};
var d = [0, 1, 0, 0];
pushBits(d, 16, len);
res.data10 = res.data27 = d.concat(bits);
if (len < 256) {
var d = [0, 1, 0, 0];
pushBits(d, 8, len);
res.data1 = d.concat(bits);
}
return res;
}
|
javascript
|
function encode_8bit(data) {
var len = data.length;
var bits = [];
for (var i = 0; i < len; i++) {
pushBits(bits, 8, data[i]);
}
var res = {};
var d = [0, 1, 0, 0];
pushBits(d, 16, len);
res.data10 = res.data27 = d.concat(bits);
if (len < 256) {
var d = [0, 1, 0, 0];
pushBits(d, 8, len);
res.data1 = d.concat(bits);
}
return res;
}
|
[
"function",
"encode_8bit",
"(",
"data",
")",
"{",
"var",
"len",
"=",
"data",
".",
"length",
";",
"var",
"bits",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"pushBits",
"(",
"bits",
",",
"8",
",",
"data",
"[",
"i",
"]",
")",
";",
"}",
"var",
"res",
"=",
"{",
"}",
";",
"var",
"d",
"=",
"[",
"0",
",",
"1",
",",
"0",
",",
"0",
"]",
";",
"pushBits",
"(",
"d",
",",
"16",
",",
"len",
")",
";",
"res",
".",
"data10",
"=",
"res",
".",
"data27",
"=",
"d",
".",
"concat",
"(",
"bits",
")",
";",
"if",
"(",
"len",
"<",
"256",
")",
"{",
"var",
"d",
"=",
"[",
"0",
",",
"1",
",",
"0",
",",
"0",
"]",
";",
"pushBits",
"(",
"d",
",",
"8",
",",
"len",
")",
";",
"res",
".",
"data1",
"=",
"d",
".",
"concat",
"(",
"bits",
")",
";",
"}",
"return",
"res",
";",
"}"
] |
{{{1 8bit encode
|
[
"{{{",
"1",
"8bit",
"encode"
] |
9b5ee0e8f38152f29cfd59eedaf037fafb47e740
|
https://github.com/alexeyten/qr-image/blob/9b5ee0e8f38152f29cfd59eedaf037fafb47e740/lib/encode.js#L10-L31
|
12,842
|
alexeyten/qr-image
|
lib/encode.js
|
encode_numeric
|
function encode_numeric(str) {
var len = str.length;
var bits = [];
for (var i = 0; i < len; i += 3) {
var s = str.substr(i, 3);
var b = Math.ceil(s.length * 10 / 3);
pushBits(bits, b, parseInt(s, 10));
}
var res = {};
var d = [0, 0, 0, 1];
pushBits(d, 14, len);
res.data27 = d.concat(bits);
if (len < 4096) {
var d = [0, 0, 0, 1];
pushBits(d, 12, len);
res.data10 = d.concat(bits);
}
if (len < 1024) {
var d = [0, 0, 0, 1];
pushBits(d, 10, len);
res.data1 = d.concat(bits);
}
return res;
}
|
javascript
|
function encode_numeric(str) {
var len = str.length;
var bits = [];
for (var i = 0; i < len; i += 3) {
var s = str.substr(i, 3);
var b = Math.ceil(s.length * 10 / 3);
pushBits(bits, b, parseInt(s, 10));
}
var res = {};
var d = [0, 0, 0, 1];
pushBits(d, 14, len);
res.data27 = d.concat(bits);
if (len < 4096) {
var d = [0, 0, 0, 1];
pushBits(d, 12, len);
res.data10 = d.concat(bits);
}
if (len < 1024) {
var d = [0, 0, 0, 1];
pushBits(d, 10, len);
res.data1 = d.concat(bits);
}
return res;
}
|
[
"function",
"encode_numeric",
"(",
"str",
")",
"{",
"var",
"len",
"=",
"str",
".",
"length",
";",
"var",
"bits",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"3",
")",
"{",
"var",
"s",
"=",
"str",
".",
"substr",
"(",
"i",
",",
"3",
")",
";",
"var",
"b",
"=",
"Math",
".",
"ceil",
"(",
"s",
".",
"length",
"*",
"10",
"/",
"3",
")",
";",
"pushBits",
"(",
"bits",
",",
"b",
",",
"parseInt",
"(",
"s",
",",
"10",
")",
")",
";",
"}",
"var",
"res",
"=",
"{",
"}",
";",
"var",
"d",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"1",
"]",
";",
"pushBits",
"(",
"d",
",",
"14",
",",
"len",
")",
";",
"res",
".",
"data27",
"=",
"d",
".",
"concat",
"(",
"bits",
")",
";",
"if",
"(",
"len",
"<",
"4096",
")",
"{",
"var",
"d",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"1",
"]",
";",
"pushBits",
"(",
"d",
",",
"12",
",",
"len",
")",
";",
"res",
".",
"data10",
"=",
"d",
".",
"concat",
"(",
"bits",
")",
";",
"}",
"if",
"(",
"len",
"<",
"1024",
")",
"{",
"var",
"d",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"1",
"]",
";",
"pushBits",
"(",
"d",
",",
"10",
",",
"len",
")",
";",
"res",
".",
"data1",
"=",
"d",
".",
"concat",
"(",
"bits",
")",
";",
"}",
"return",
"res",
";",
"}"
] |
{{{1 numeric encode
|
[
"{{{",
"1",
"numeric",
"encode"
] |
9b5ee0e8f38152f29cfd59eedaf037fafb47e740
|
https://github.com/alexeyten/qr-image/blob/9b5ee0e8f38152f29cfd59eedaf037fafb47e740/lib/encode.js#L78-L107
|
12,843
|
alexeyten/qr-image
|
lib/encode.js
|
encode_url
|
function encode_url(str) {
var slash = str.indexOf('/', 8) + 1 || str.length;
var res = encode(str.slice(0, slash).toUpperCase(), false);
if (slash >= str.length) {
return res;
}
var path_res = encode(str.slice(slash), false);
res.data27 = res.data27.concat(path_res.data27);
if (res.data10 && path_res.data10) {
res.data10 = res.data10.concat(path_res.data10);
}
if (res.data1 && path_res.data1) {
res.data1 = res.data1.concat(path_res.data1);
}
return res;
}
|
javascript
|
function encode_url(str) {
var slash = str.indexOf('/', 8) + 1 || str.length;
var res = encode(str.slice(0, slash).toUpperCase(), false);
if (slash >= str.length) {
return res;
}
var path_res = encode(str.slice(slash), false);
res.data27 = res.data27.concat(path_res.data27);
if (res.data10 && path_res.data10) {
res.data10 = res.data10.concat(path_res.data10);
}
if (res.data1 && path_res.data1) {
res.data1 = res.data1.concat(path_res.data1);
}
return res;
}
|
[
"function",
"encode_url",
"(",
"str",
")",
"{",
"var",
"slash",
"=",
"str",
".",
"indexOf",
"(",
"'/'",
",",
"8",
")",
"+",
"1",
"||",
"str",
".",
"length",
";",
"var",
"res",
"=",
"encode",
"(",
"str",
".",
"slice",
"(",
"0",
",",
"slash",
")",
".",
"toUpperCase",
"(",
")",
",",
"false",
")",
";",
"if",
"(",
"slash",
">=",
"str",
".",
"length",
")",
"{",
"return",
"res",
";",
"}",
"var",
"path_res",
"=",
"encode",
"(",
"str",
".",
"slice",
"(",
"slash",
")",
",",
"false",
")",
";",
"res",
".",
"data27",
"=",
"res",
".",
"data27",
".",
"concat",
"(",
"path_res",
".",
"data27",
")",
";",
"if",
"(",
"res",
".",
"data10",
"&&",
"path_res",
".",
"data10",
")",
"{",
"res",
".",
"data10",
"=",
"res",
".",
"data10",
".",
"concat",
"(",
"path_res",
".",
"data10",
")",
";",
"}",
"if",
"(",
"res",
".",
"data1",
"&&",
"path_res",
".",
"data1",
")",
"{",
"res",
".",
"data1",
"=",
"res",
".",
"data1",
".",
"concat",
"(",
"path_res",
".",
"data1",
")",
";",
"}",
"return",
"res",
";",
"}"
] |
{{{1 url encode
|
[
"{{{",
"1",
"url",
"encode"
] |
9b5ee0e8f38152f29cfd59eedaf037fafb47e740
|
https://github.com/alexeyten/qr-image/blob/9b5ee0e8f38152f29cfd59eedaf037fafb47e740/lib/encode.js#L110-L131
|
12,844
|
alexeyten/qr-image
|
lib/encode.js
|
encode
|
function encode(data, parse_url) {
var str;
var t = typeof data;
if (t == 'string' || t == 'number') {
str = '' + data;
data = new Buffer(str);
} else if (Buffer.isBuffer(data)) {
str = data.toString();
} else if (Array.isArray(data)) {
data = new Buffer(data);
str = data.toString();
} else {
throw new Error("Bad data");
}
if (/^[0-9]+$/.test(str)) {
if (data.length > 7089) {
throw new Error("Too much data");
}
return encode_numeric(str);
}
if (/^[0-9A-Z \$%\*\+\.\/\:\-]+$/.test(str)) {
if (data.length > 4296) {
throw new Error("Too much data");
}
return encode_alphanum(str);
}
if (parse_url && /^https?:/i.test(str)) {
return encode_url(str);
}
if (data.length > 2953) {
throw new Error("Too much data");
}
return encode_8bit(data);
}
|
javascript
|
function encode(data, parse_url) {
var str;
var t = typeof data;
if (t == 'string' || t == 'number') {
str = '' + data;
data = new Buffer(str);
} else if (Buffer.isBuffer(data)) {
str = data.toString();
} else if (Array.isArray(data)) {
data = new Buffer(data);
str = data.toString();
} else {
throw new Error("Bad data");
}
if (/^[0-9]+$/.test(str)) {
if (data.length > 7089) {
throw new Error("Too much data");
}
return encode_numeric(str);
}
if (/^[0-9A-Z \$%\*\+\.\/\:\-]+$/.test(str)) {
if (data.length > 4296) {
throw new Error("Too much data");
}
return encode_alphanum(str);
}
if (parse_url && /^https?:/i.test(str)) {
return encode_url(str);
}
if (data.length > 2953) {
throw new Error("Too much data");
}
return encode_8bit(data);
}
|
[
"function",
"encode",
"(",
"data",
",",
"parse_url",
")",
"{",
"var",
"str",
";",
"var",
"t",
"=",
"typeof",
"data",
";",
"if",
"(",
"t",
"==",
"'string'",
"||",
"t",
"==",
"'number'",
")",
"{",
"str",
"=",
"''",
"+",
"data",
";",
"data",
"=",
"new",
"Buffer",
"(",
"str",
")",
";",
"}",
"else",
"if",
"(",
"Buffer",
".",
"isBuffer",
"(",
"data",
")",
")",
"{",
"str",
"=",
"data",
".",
"toString",
"(",
")",
";",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"data",
")",
")",
"{",
"data",
"=",
"new",
"Buffer",
"(",
"data",
")",
";",
"str",
"=",
"data",
".",
"toString",
"(",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"\"Bad data\"",
")",
";",
"}",
"if",
"(",
"/",
"^[0-9]+$",
"/",
".",
"test",
"(",
"str",
")",
")",
"{",
"if",
"(",
"data",
".",
"length",
">",
"7089",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Too much data\"",
")",
";",
"}",
"return",
"encode_numeric",
"(",
"str",
")",
";",
"}",
"if",
"(",
"/",
"^[0-9A-Z \\$%\\*\\+\\.\\/\\:\\-]+$",
"/",
".",
"test",
"(",
"str",
")",
")",
"{",
"if",
"(",
"data",
".",
"length",
">",
"4296",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Too much data\"",
")",
";",
"}",
"return",
"encode_alphanum",
"(",
"str",
")",
";",
"}",
"if",
"(",
"parse_url",
"&&",
"/",
"^https?:",
"/",
"i",
".",
"test",
"(",
"str",
")",
")",
"{",
"return",
"encode_url",
"(",
"str",
")",
";",
"}",
"if",
"(",
"data",
".",
"length",
">",
"2953",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Too much data\"",
")",
";",
"}",
"return",
"encode_8bit",
"(",
"data",
")",
";",
"}"
] |
{{{1 Choose encode mode and generates struct with data for different version
|
[
"{{{",
"1",
"Choose",
"encode",
"mode",
"and",
"generates",
"struct",
"with",
"data",
"for",
"different",
"version"
] |
9b5ee0e8f38152f29cfd59eedaf037fafb47e740
|
https://github.com/alexeyten/qr-image/blob/9b5ee0e8f38152f29cfd59eedaf037fafb47e740/lib/encode.js#L134-L172
|
12,845
|
alexeyten/qr-image
|
lib/matrix.js
|
init
|
function init(version) {
var N = version * 4 + 17;
var matrix = [];
var zeros = new Buffer(N);
zeros.fill(0);
zeros = [].slice.call(zeros);
for (var i = 0; i < N; i++) {
matrix[i] = zeros.slice();
}
return matrix;
}
|
javascript
|
function init(version) {
var N = version * 4 + 17;
var matrix = [];
var zeros = new Buffer(N);
zeros.fill(0);
zeros = [].slice.call(zeros);
for (var i = 0; i < N; i++) {
matrix[i] = zeros.slice();
}
return matrix;
}
|
[
"function",
"init",
"(",
"version",
")",
"{",
"var",
"N",
"=",
"version",
"*",
"4",
"+",
"17",
";",
"var",
"matrix",
"=",
"[",
"]",
";",
"var",
"zeros",
"=",
"new",
"Buffer",
"(",
"N",
")",
";",
"zeros",
".",
"fill",
"(",
"0",
")",
";",
"zeros",
"=",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"zeros",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"N",
";",
"i",
"++",
")",
"{",
"matrix",
"[",
"i",
"]",
"=",
"zeros",
".",
"slice",
"(",
")",
";",
"}",
"return",
"matrix",
";",
"}"
] |
{{{1 Initialize matrix with zeros
|
[
"{{{",
"1",
"Initialize",
"matrix",
"with",
"zeros"
] |
9b5ee0e8f38152f29cfd59eedaf037fafb47e740
|
https://github.com/alexeyten/qr-image/blob/9b5ee0e8f38152f29cfd59eedaf037fafb47e740/lib/matrix.js#L4-L14
|
12,846
|
alexeyten/qr-image
|
lib/matrix.js
|
fillFinders
|
function fillFinders(matrix) {
var N = matrix.length;
for (var i = -3; i <= 3; i++) {
for (var j = -3; j <= 3; j++) {
var max = Math.max(i, j);
var min = Math.min(i, j);
var pixel = (max == 2 && min >= -2) || (min == -2 && max <= 2) ? 0x80 : 0x81;
matrix[3 + i][3 + j] = pixel;
matrix[3 + i][N - 4 + j] = pixel;
matrix[N - 4 + i][3 + j] = pixel;
}
}
for (var i = 0; i < 8; i++) {
matrix[7][i] = matrix[i][7] =
matrix[7][N - i - 1] = matrix[i][N - 8] =
matrix[N - 8][i] = matrix[N - 1 - i][7] = 0x80;
}
}
|
javascript
|
function fillFinders(matrix) {
var N = matrix.length;
for (var i = -3; i <= 3; i++) {
for (var j = -3; j <= 3; j++) {
var max = Math.max(i, j);
var min = Math.min(i, j);
var pixel = (max == 2 && min >= -2) || (min == -2 && max <= 2) ? 0x80 : 0x81;
matrix[3 + i][3 + j] = pixel;
matrix[3 + i][N - 4 + j] = pixel;
matrix[N - 4 + i][3 + j] = pixel;
}
}
for (var i = 0; i < 8; i++) {
matrix[7][i] = matrix[i][7] =
matrix[7][N - i - 1] = matrix[i][N - 8] =
matrix[N - 8][i] = matrix[N - 1 - i][7] = 0x80;
}
}
|
[
"function",
"fillFinders",
"(",
"matrix",
")",
"{",
"var",
"N",
"=",
"matrix",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"-",
"3",
";",
"i",
"<=",
"3",
";",
"i",
"++",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"-",
"3",
";",
"j",
"<=",
"3",
";",
"j",
"++",
")",
"{",
"var",
"max",
"=",
"Math",
".",
"max",
"(",
"i",
",",
"j",
")",
";",
"var",
"min",
"=",
"Math",
".",
"min",
"(",
"i",
",",
"j",
")",
";",
"var",
"pixel",
"=",
"(",
"max",
"==",
"2",
"&&",
"min",
">=",
"-",
"2",
")",
"||",
"(",
"min",
"==",
"-",
"2",
"&&",
"max",
"<=",
"2",
")",
"?",
"0x80",
":",
"0x81",
";",
"matrix",
"[",
"3",
"+",
"i",
"]",
"[",
"3",
"+",
"j",
"]",
"=",
"pixel",
";",
"matrix",
"[",
"3",
"+",
"i",
"]",
"[",
"N",
"-",
"4",
"+",
"j",
"]",
"=",
"pixel",
";",
"matrix",
"[",
"N",
"-",
"4",
"+",
"i",
"]",
"[",
"3",
"+",
"j",
"]",
"=",
"pixel",
";",
"}",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"8",
";",
"i",
"++",
")",
"{",
"matrix",
"[",
"7",
"]",
"[",
"i",
"]",
"=",
"matrix",
"[",
"i",
"]",
"[",
"7",
"]",
"=",
"matrix",
"[",
"7",
"]",
"[",
"N",
"-",
"i",
"-",
"1",
"]",
"=",
"matrix",
"[",
"i",
"]",
"[",
"N",
"-",
"8",
"]",
"=",
"matrix",
"[",
"N",
"-",
"8",
"]",
"[",
"i",
"]",
"=",
"matrix",
"[",
"N",
"-",
"1",
"-",
"i",
"]",
"[",
"7",
"]",
"=",
"0x80",
";",
"}",
"}"
] |
{{{1 Put finders into matrix
|
[
"{{{",
"1",
"Put",
"finders",
"into",
"matrix"
] |
9b5ee0e8f38152f29cfd59eedaf037fafb47e740
|
https://github.com/alexeyten/qr-image/blob/9b5ee0e8f38152f29cfd59eedaf037fafb47e740/lib/matrix.js#L17-L34
|
12,847
|
alexeyten/qr-image
|
lib/matrix.js
|
fillAlignAndTiming
|
function fillAlignAndTiming(matrix) {
var N = matrix.length;
if (N > 21) {
var len = N - 13;
var delta = Math.round(len / Math.ceil(len / 28));
if (delta % 2) delta++;
var res = [];
for (var p = len + 6; p > 10; p -= delta) {
res.unshift(p);
}
res.unshift(6);
for (var i = 0; i < res.length; i++) {
for (var j = 0; j < res.length; j++) {
var x = res[i], y = res[j];
if (matrix[x][y]) continue;
for (var r = -2; r <=2 ; r++) {
for (var c = -2; c <=2 ; c++) {
var max = Math.max(r, c);
var min = Math.min(r, c);
var pixel = (max == 1 && min >= -1) || (min == -1 && max <= 1) ? 0x80 : 0x81;
matrix[x + r][y + c] = pixel;
}
}
}
}
}
for (var i = 8; i < N - 8; i++) {
matrix[6][i] = matrix[i][6] = i % 2 ? 0x80 : 0x81;
}
}
|
javascript
|
function fillAlignAndTiming(matrix) {
var N = matrix.length;
if (N > 21) {
var len = N - 13;
var delta = Math.round(len / Math.ceil(len / 28));
if (delta % 2) delta++;
var res = [];
for (var p = len + 6; p > 10; p -= delta) {
res.unshift(p);
}
res.unshift(6);
for (var i = 0; i < res.length; i++) {
for (var j = 0; j < res.length; j++) {
var x = res[i], y = res[j];
if (matrix[x][y]) continue;
for (var r = -2; r <=2 ; r++) {
for (var c = -2; c <=2 ; c++) {
var max = Math.max(r, c);
var min = Math.min(r, c);
var pixel = (max == 1 && min >= -1) || (min == -1 && max <= 1) ? 0x80 : 0x81;
matrix[x + r][y + c] = pixel;
}
}
}
}
}
for (var i = 8; i < N - 8; i++) {
matrix[6][i] = matrix[i][6] = i % 2 ? 0x80 : 0x81;
}
}
|
[
"function",
"fillAlignAndTiming",
"(",
"matrix",
")",
"{",
"var",
"N",
"=",
"matrix",
".",
"length",
";",
"if",
"(",
"N",
">",
"21",
")",
"{",
"var",
"len",
"=",
"N",
"-",
"13",
";",
"var",
"delta",
"=",
"Math",
".",
"round",
"(",
"len",
"/",
"Math",
".",
"ceil",
"(",
"len",
"/",
"28",
")",
")",
";",
"if",
"(",
"delta",
"%",
"2",
")",
"delta",
"++",
";",
"var",
"res",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"p",
"=",
"len",
"+",
"6",
";",
"p",
">",
"10",
";",
"p",
"-=",
"delta",
")",
"{",
"res",
".",
"unshift",
"(",
"p",
")",
";",
"}",
"res",
".",
"unshift",
"(",
"6",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"res",
".",
"length",
";",
"i",
"++",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"res",
".",
"length",
";",
"j",
"++",
")",
"{",
"var",
"x",
"=",
"res",
"[",
"i",
"]",
",",
"y",
"=",
"res",
"[",
"j",
"]",
";",
"if",
"(",
"matrix",
"[",
"x",
"]",
"[",
"y",
"]",
")",
"continue",
";",
"for",
"(",
"var",
"r",
"=",
"-",
"2",
";",
"r",
"<=",
"2",
";",
"r",
"++",
")",
"{",
"for",
"(",
"var",
"c",
"=",
"-",
"2",
";",
"c",
"<=",
"2",
";",
"c",
"++",
")",
"{",
"var",
"max",
"=",
"Math",
".",
"max",
"(",
"r",
",",
"c",
")",
";",
"var",
"min",
"=",
"Math",
".",
"min",
"(",
"r",
",",
"c",
")",
";",
"var",
"pixel",
"=",
"(",
"max",
"==",
"1",
"&&",
"min",
">=",
"-",
"1",
")",
"||",
"(",
"min",
"==",
"-",
"1",
"&&",
"max",
"<=",
"1",
")",
"?",
"0x80",
":",
"0x81",
";",
"matrix",
"[",
"x",
"+",
"r",
"]",
"[",
"y",
"+",
"c",
"]",
"=",
"pixel",
";",
"}",
"}",
"}",
"}",
"}",
"for",
"(",
"var",
"i",
"=",
"8",
";",
"i",
"<",
"N",
"-",
"8",
";",
"i",
"++",
")",
"{",
"matrix",
"[",
"6",
"]",
"[",
"i",
"]",
"=",
"matrix",
"[",
"i",
"]",
"[",
"6",
"]",
"=",
"i",
"%",
"2",
"?",
"0x80",
":",
"0x81",
";",
"}",
"}"
] |
{{{1 Put align and timinig
|
[
"{{{",
"1",
"Put",
"align",
"and",
"timinig"
] |
9b5ee0e8f38152f29cfd59eedaf037fafb47e740
|
https://github.com/alexeyten/qr-image/blob/9b5ee0e8f38152f29cfd59eedaf037fafb47e740/lib/matrix.js#L37-L66
|
12,848
|
alexeyten/qr-image
|
lib/matrix.js
|
fillStub
|
function fillStub(matrix) {
var N = matrix.length;
for (var i = 0; i < 8; i++) {
if (i != 6) {
matrix[8][i] = matrix[i][8] = 0x80;
}
matrix[8][N - 1 - i] = 0x80;
matrix[N - 1 - i][8] = 0x80;
}
matrix[8][8] = 0x80;
matrix[N - 8][8] = 0x81;
if (N < 45) return;
for (var i = N - 11; i < N - 8; i++) {
for (var j = 0; j < 6; j++) {
matrix[i][j] = matrix[j][i] = 0x80;
}
}
}
|
javascript
|
function fillStub(matrix) {
var N = matrix.length;
for (var i = 0; i < 8; i++) {
if (i != 6) {
matrix[8][i] = matrix[i][8] = 0x80;
}
matrix[8][N - 1 - i] = 0x80;
matrix[N - 1 - i][8] = 0x80;
}
matrix[8][8] = 0x80;
matrix[N - 8][8] = 0x81;
if (N < 45) return;
for (var i = N - 11; i < N - 8; i++) {
for (var j = 0; j < 6; j++) {
matrix[i][j] = matrix[j][i] = 0x80;
}
}
}
|
[
"function",
"fillStub",
"(",
"matrix",
")",
"{",
"var",
"N",
"=",
"matrix",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"8",
";",
"i",
"++",
")",
"{",
"if",
"(",
"i",
"!=",
"6",
")",
"{",
"matrix",
"[",
"8",
"]",
"[",
"i",
"]",
"=",
"matrix",
"[",
"i",
"]",
"[",
"8",
"]",
"=",
"0x80",
";",
"}",
"matrix",
"[",
"8",
"]",
"[",
"N",
"-",
"1",
"-",
"i",
"]",
"=",
"0x80",
";",
"matrix",
"[",
"N",
"-",
"1",
"-",
"i",
"]",
"[",
"8",
"]",
"=",
"0x80",
";",
"}",
"matrix",
"[",
"8",
"]",
"[",
"8",
"]",
"=",
"0x80",
";",
"matrix",
"[",
"N",
"-",
"8",
"]",
"[",
"8",
"]",
"=",
"0x81",
";",
"if",
"(",
"N",
"<",
"45",
")",
"return",
";",
"for",
"(",
"var",
"i",
"=",
"N",
"-",
"11",
";",
"i",
"<",
"N",
"-",
"8",
";",
"i",
"++",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"6",
";",
"j",
"++",
")",
"{",
"matrix",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"matrix",
"[",
"j",
"]",
"[",
"i",
"]",
"=",
"0x80",
";",
"}",
"}",
"}"
] |
{{{1 Fill reserved areas with zeroes
|
[
"{{{",
"1",
"Fill",
"reserved",
"areas",
"with",
"zeroes"
] |
9b5ee0e8f38152f29cfd59eedaf037fafb47e740
|
https://github.com/alexeyten/qr-image/blob/9b5ee0e8f38152f29cfd59eedaf037fafb47e740/lib/matrix.js#L69-L88
|
12,849
|
alexeyten/qr-image
|
lib/matrix.js
|
getMatrix
|
function getMatrix(data) {
var matrix = init(data.version);
fillFinders(matrix);
fillAlignAndTiming(matrix);
fillStub(matrix);
var penalty = Infinity;
var bestMask = 0;
for (var mask = 0; mask < 8; mask++) {
fillData(matrix, data, mask);
fillReserved(matrix, data.ec_level, mask);
var p = calculatePenalty(matrix);
if (p < penalty) {
penalty = p;
bestMask = mask;
}
}
fillData(matrix, data, bestMask);
fillReserved(matrix, data.ec_level, bestMask);
return matrix.map(function(row) {
return row.map(function(cell) {
return cell & 1;
});
});
}
|
javascript
|
function getMatrix(data) {
var matrix = init(data.version);
fillFinders(matrix);
fillAlignAndTiming(matrix);
fillStub(matrix);
var penalty = Infinity;
var bestMask = 0;
for (var mask = 0; mask < 8; mask++) {
fillData(matrix, data, mask);
fillReserved(matrix, data.ec_level, mask);
var p = calculatePenalty(matrix);
if (p < penalty) {
penalty = p;
bestMask = mask;
}
}
fillData(matrix, data, bestMask);
fillReserved(matrix, data.ec_level, bestMask);
return matrix.map(function(row) {
return row.map(function(cell) {
return cell & 1;
});
});
}
|
[
"function",
"getMatrix",
"(",
"data",
")",
"{",
"var",
"matrix",
"=",
"init",
"(",
"data",
".",
"version",
")",
";",
"fillFinders",
"(",
"matrix",
")",
";",
"fillAlignAndTiming",
"(",
"matrix",
")",
";",
"fillStub",
"(",
"matrix",
")",
";",
"var",
"penalty",
"=",
"Infinity",
";",
"var",
"bestMask",
"=",
"0",
";",
"for",
"(",
"var",
"mask",
"=",
"0",
";",
"mask",
"<",
"8",
";",
"mask",
"++",
")",
"{",
"fillData",
"(",
"matrix",
",",
"data",
",",
"mask",
")",
";",
"fillReserved",
"(",
"matrix",
",",
"data",
".",
"ec_level",
",",
"mask",
")",
";",
"var",
"p",
"=",
"calculatePenalty",
"(",
"matrix",
")",
";",
"if",
"(",
"p",
"<",
"penalty",
")",
"{",
"penalty",
"=",
"p",
";",
"bestMask",
"=",
"mask",
";",
"}",
"}",
"fillData",
"(",
"matrix",
",",
"data",
",",
"bestMask",
")",
";",
"fillReserved",
"(",
"matrix",
",",
"data",
".",
"ec_level",
",",
"bestMask",
")",
";",
"return",
"matrix",
".",
"map",
"(",
"function",
"(",
"row",
")",
"{",
"return",
"row",
".",
"map",
"(",
"function",
"(",
"cell",
")",
"{",
"return",
"cell",
"&",
"1",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
{{{1 All-in-one function
|
[
"{{{",
"1",
"All",
"-",
"in",
"-",
"one",
"function"
] |
9b5ee0e8f38152f29cfd59eedaf037fafb47e740
|
https://github.com/alexeyten/qr-image/blob/9b5ee0e8f38152f29cfd59eedaf037fafb47e740/lib/matrix.js#L314-L340
|
12,850
|
Autodesk/hig
|
packages/components/scripts/build.js
|
getPackageExportNames
|
function getPackageExportNames(packagePath) {
const packageMeta = getPackageMeta(packagePath);
const packageModulePath = path.join(packagePath, packageMeta.module);
const moduleFileSource = fs.readFileSync(packageModulePath, "utf8");
const { body } = esprima.parseModule(moduleFileSource);
return body.reduce((result, statement) => {
if (statement.type === "ExportDefaultDeclaration") {
return result.concat(["default"]);
}
if (statement.type === "ExportNamedDeclaration") {
return result.concat(getNamesFromDeclaration(statement));
}
return result;
}, []);
}
|
javascript
|
function getPackageExportNames(packagePath) {
const packageMeta = getPackageMeta(packagePath);
const packageModulePath = path.join(packagePath, packageMeta.module);
const moduleFileSource = fs.readFileSync(packageModulePath, "utf8");
const { body } = esprima.parseModule(moduleFileSource);
return body.reduce((result, statement) => {
if (statement.type === "ExportDefaultDeclaration") {
return result.concat(["default"]);
}
if (statement.type === "ExportNamedDeclaration") {
return result.concat(getNamesFromDeclaration(statement));
}
return result;
}, []);
}
|
[
"function",
"getPackageExportNames",
"(",
"packagePath",
")",
"{",
"const",
"packageMeta",
"=",
"getPackageMeta",
"(",
"packagePath",
")",
";",
"const",
"packageModulePath",
"=",
"path",
".",
"join",
"(",
"packagePath",
",",
"packageMeta",
".",
"module",
")",
";",
"const",
"moduleFileSource",
"=",
"fs",
".",
"readFileSync",
"(",
"packageModulePath",
",",
"\"utf8\"",
")",
";",
"const",
"{",
"body",
"}",
"=",
"esprima",
".",
"parseModule",
"(",
"moduleFileSource",
")",
";",
"return",
"body",
".",
"reduce",
"(",
"(",
"result",
",",
"statement",
")",
"=>",
"{",
"if",
"(",
"statement",
".",
"type",
"===",
"\"ExportDefaultDeclaration\"",
")",
"{",
"return",
"result",
".",
"concat",
"(",
"[",
"\"default\"",
"]",
")",
";",
"}",
"if",
"(",
"statement",
".",
"type",
"===",
"\"ExportNamedDeclaration\"",
")",
"{",
"return",
"result",
".",
"concat",
"(",
"getNamesFromDeclaration",
"(",
"statement",
")",
")",
";",
"}",
"return",
"result",
";",
"}",
",",
"[",
"]",
")",
";",
"}"
] |
Parsed the package's main module and returns all of the export names
@param {string} packageName
@returns {string[]}
|
[
"Parsed",
"the",
"package",
"s",
"main",
"module",
"and",
"returns",
"all",
"of",
"the",
"export",
"names"
] |
b51406a358ec536d70dc404199c62dafe7e4f75e
|
https://github.com/Autodesk/hig/blob/b51406a358ec536d70dc404199c62dafe7e4f75e/packages/components/scripts/build.js#L60-L77
|
12,851
|
Autodesk/hig
|
packages/flyout/src/coordinateHelpers.js
|
offsetContainerProperty
|
function offsetContainerProperty(offsetProperty, coordinates, diff) {
return {
...coordinates,
containerPosition: {
...coordinates.containerPosition,
[offsetProperty]: coordinates.containerPosition[offsetProperty] + diff
}
};
}
|
javascript
|
function offsetContainerProperty(offsetProperty, coordinates, diff) {
return {
...coordinates,
containerPosition: {
...coordinates.containerPosition,
[offsetProperty]: coordinates.containerPosition[offsetProperty] + diff
}
};
}
|
[
"function",
"offsetContainerProperty",
"(",
"offsetProperty",
",",
"coordinates",
",",
"diff",
")",
"{",
"return",
"{",
"...",
"coordinates",
",",
"containerPosition",
":",
"{",
"...",
"coordinates",
".",
"containerPosition",
",",
"[",
"offsetProperty",
"]",
":",
"coordinates",
".",
"containerPosition",
"[",
"offsetProperty",
"]",
"+",
"diff",
"}",
"}",
";",
"}"
] |
Offsets the container
@param {string} offsetProperty
@param {Coordinates} coordinates
@param {number} diff
@returns {Coordinates}
|
[
"Offsets",
"the",
"container"
] |
b51406a358ec536d70dc404199c62dafe7e4f75e
|
https://github.com/Autodesk/hig/blob/b51406a358ec536d70dc404199c62dafe7e4f75e/packages/flyout/src/coordinateHelpers.js#L17-L25
|
12,852
|
Autodesk/hig
|
packages/flyout/src/getCoordinates.js
|
createViewportDeterminer
|
function createViewportDeterminer(props) {
const { viewportRect, panelRect, actionRect } = props;
return function isInViewport({ containerPosition }) {
const containerTop = actionRect.top + containerPosition.top;
const containerLeft = actionRect.left + containerPosition.left;
const containerRight = containerLeft + panelRect.width;
const containerBottom = containerTop + panelRect.height;
const result =
containerLeft >= viewportRect.left &&
containerTop >= viewportRect.top &&
containerRight <= viewportRect.right &&
containerBottom <= viewportRect.bottom;
return result;
};
}
|
javascript
|
function createViewportDeterminer(props) {
const { viewportRect, panelRect, actionRect } = props;
return function isInViewport({ containerPosition }) {
const containerTop = actionRect.top + containerPosition.top;
const containerLeft = actionRect.left + containerPosition.left;
const containerRight = containerLeft + panelRect.width;
const containerBottom = containerTop + panelRect.height;
const result =
containerLeft >= viewportRect.left &&
containerTop >= viewportRect.top &&
containerRight <= viewportRect.right &&
containerBottom <= viewportRect.bottom;
return result;
};
}
|
[
"function",
"createViewportDeterminer",
"(",
"props",
")",
"{",
"const",
"{",
"viewportRect",
",",
"panelRect",
",",
"actionRect",
"}",
"=",
"props",
";",
"return",
"function",
"isInViewport",
"(",
"{",
"containerPosition",
"}",
")",
"{",
"const",
"containerTop",
"=",
"actionRect",
".",
"top",
"+",
"containerPosition",
".",
"top",
";",
"const",
"containerLeft",
"=",
"actionRect",
".",
"left",
"+",
"containerPosition",
".",
"left",
";",
"const",
"containerRight",
"=",
"containerLeft",
"+",
"panelRect",
".",
"width",
";",
"const",
"containerBottom",
"=",
"containerTop",
"+",
"panelRect",
".",
"height",
";",
"const",
"result",
"=",
"containerLeft",
">=",
"viewportRect",
".",
"left",
"&&",
"containerTop",
">=",
"viewportRect",
".",
"top",
"&&",
"containerRight",
"<=",
"viewportRect",
".",
"right",
"&&",
"containerBottom",
"<=",
"viewportRect",
".",
"bottom",
";",
"return",
"result",
";",
"}",
";",
"}"
] |
Determines whether the given position is entirely within the viewport
@param {Payload} payload
@returns {function(Coordinates): boolean}
|
[
"Determines",
"whether",
"the",
"given",
"position",
"is",
"entirely",
"within",
"the",
"viewport"
] |
b51406a358ec536d70dc404199c62dafe7e4f75e
|
https://github.com/Autodesk/hig/blob/b51406a358ec536d70dc404199c62dafe7e4f75e/packages/flyout/src/getCoordinates.js#L234-L250
|
12,853
|
canonical-web-and-design/vanilla-framework
|
gulp/styles.js
|
throwSassError
|
function throwSassError(sassError) {
throw new gutil.PluginError({
plugin: 'sass',
message: util.format("Sass error: '%s' on line %s of %s", sassError.message, sassError.line, sassError.file)
});
}
|
javascript
|
function throwSassError(sassError) {
throw new gutil.PluginError({
plugin: 'sass',
message: util.format("Sass error: '%s' on line %s of %s", sassError.message, sassError.line, sassError.file)
});
}
|
[
"function",
"throwSassError",
"(",
"sassError",
")",
"{",
"throw",
"new",
"gutil",
".",
"PluginError",
"(",
"{",
"plugin",
":",
"'sass'",
",",
"message",
":",
"util",
".",
"format",
"(",
"\"Sass error: '%s' on line %s of %s\"",
",",
"sassError",
".",
"message",
",",
"sassError",
".",
"line",
",",
"sassError",
".",
"file",
")",
"}",
")",
";",
"}"
] |
Provide details of Sass errors
|
[
"Provide",
"details",
"of",
"Sass",
"errors"
] |
720e10be29350c847e64b928ebf604f5cf64adcd
|
https://github.com/canonical-web-and-design/vanilla-framework/blob/720e10be29350c847e64b928ebf604f5cf64adcd/gulp/styles.js#L10-L15
|
12,854
|
Operational-Transformation/ot.js
|
lib/simple-text-operation.js
|
Insert
|
function Insert (str, position) {
if (!this || this.constructor !== SimpleTextOperation) {
// => function was called without 'new'
return new Insert(str, position);
}
this.str = str;
this.position = position;
}
|
javascript
|
function Insert (str, position) {
if (!this || this.constructor !== SimpleTextOperation) {
// => function was called without 'new'
return new Insert(str, position);
}
this.str = str;
this.position = position;
}
|
[
"function",
"Insert",
"(",
"str",
",",
"position",
")",
"{",
"if",
"(",
"!",
"this",
"||",
"this",
".",
"constructor",
"!==",
"SimpleTextOperation",
")",
"{",
"// => function was called without 'new'",
"return",
"new",
"Insert",
"(",
"str",
",",
"position",
")",
";",
"}",
"this",
".",
"str",
"=",
"str",
";",
"this",
".",
"position",
"=",
"position",
";",
"}"
] |
Insert the string `str` at the zero-based `position` in the document.
|
[
"Insert",
"the",
"string",
"str",
"at",
"the",
"zero",
"-",
"based",
"position",
"in",
"the",
"document",
"."
] |
8873b7e28e83f9adbf6c3a28ec639c9151a838ae
|
https://github.com/Operational-Transformation/ot.js/blob/8873b7e28e83f9adbf6c3a28ec639c9151a838ae/lib/simple-text-operation.js#L14-L21
|
12,855
|
Operational-Transformation/ot.js
|
lib/simple-text-operation.js
|
Delete
|
function Delete (count, position) {
if (!this || this.constructor !== SimpleTextOperation) {
return new Delete(count, position);
}
this.count = count;
this.position = position;
}
|
javascript
|
function Delete (count, position) {
if (!this || this.constructor !== SimpleTextOperation) {
return new Delete(count, position);
}
this.count = count;
this.position = position;
}
|
[
"function",
"Delete",
"(",
"count",
",",
"position",
")",
"{",
"if",
"(",
"!",
"this",
"||",
"this",
".",
"constructor",
"!==",
"SimpleTextOperation",
")",
"{",
"return",
"new",
"Delete",
"(",
"count",
",",
"position",
")",
";",
"}",
"this",
".",
"count",
"=",
"count",
";",
"this",
".",
"position",
"=",
"position",
";",
"}"
] |
Delete `count` many characters at the zero-based `position` in the document.
|
[
"Delete",
"count",
"many",
"characters",
"at",
"the",
"zero",
"-",
"based",
"position",
"in",
"the",
"document",
"."
] |
8873b7e28e83f9adbf6c3a28ec639c9151a838ae
|
https://github.com/Operational-Transformation/ot.js/blob/8873b7e28e83f9adbf6c3a28ec639c9151a838ae/lib/simple-text-operation.js#L42-L48
|
12,856
|
Operational-Transformation/ot.js
|
lib/undo-manager.js
|
UndoManager
|
function UndoManager (maxItems) {
this.maxItems = maxItems || 50;
this.state = NORMAL_STATE;
this.dontCompose = false;
this.undoStack = [];
this.redoStack = [];
}
|
javascript
|
function UndoManager (maxItems) {
this.maxItems = maxItems || 50;
this.state = NORMAL_STATE;
this.dontCompose = false;
this.undoStack = [];
this.redoStack = [];
}
|
[
"function",
"UndoManager",
"(",
"maxItems",
")",
"{",
"this",
".",
"maxItems",
"=",
"maxItems",
"||",
"50",
";",
"this",
".",
"state",
"=",
"NORMAL_STATE",
";",
"this",
".",
"dontCompose",
"=",
"false",
";",
"this",
".",
"undoStack",
"=",
"[",
"]",
";",
"this",
".",
"redoStack",
"=",
"[",
"]",
";",
"}"
] |
Create a new UndoManager with an optional maximum history size.
|
[
"Create",
"a",
"new",
"UndoManager",
"with",
"an",
"optional",
"maximum",
"history",
"size",
"."
] |
8873b7e28e83f9adbf6c3a28ec639c9151a838ae
|
https://github.com/Operational-Transformation/ot.js/blob/8873b7e28e83f9adbf6c3a28ec639c9151a838ae/lib/undo-manager.js#L14-L20
|
12,857
|
notwaldorf/emoji-translate
|
emoji-translate.js
|
getEmojiForWord
|
function getEmojiForWord(word) {
let translations = getAllEmojiForWord(word);
return translations[Math.floor(Math.random() * translations.length)];
}
|
javascript
|
function getEmojiForWord(word) {
let translations = getAllEmojiForWord(word);
return translations[Math.floor(Math.random() * translations.length)];
}
|
[
"function",
"getEmojiForWord",
"(",
"word",
")",
"{",
"let",
"translations",
"=",
"getAllEmojiForWord",
"(",
"word",
")",
";",
"return",
"translations",
"[",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"translations",
".",
"length",
")",
"]",
";",
"}"
] |
Returns a random emoji translation of an english word.
@param {String} word The word to be translated.
@returns {String} A random emoji translation or '' if none exists.
|
[
"Returns",
"a",
"random",
"emoji",
"translation",
"of",
"an",
"english",
"word",
"."
] |
ed74d89410dc4aa3c67e19c5a9171b7267aba362
|
https://github.com/notwaldorf/emoji-translate/blob/ed74d89410dc4aa3c67e19c5a9171b7267aba362/emoji-translate.js#L108-L111
|
12,858
|
notwaldorf/emoji-translate
|
emoji-translate.js
|
translate
|
function translate(sentence, onlyEmoji) {
let translation = '';
let words = sentence.split(' ');
for (let i = 0; i < words.length; i++ ) {
// Punctuation blows. Get all the punctuation at the start and end of the word.
// TODO: stop copy pasting this.
let firstSymbol = '';
let lastSymbol = '';
var word = words[i];
while (SYMBOLS.indexOf(word[0]) != -1) {
firstSymbol += word[0];
word = word.slice(1, word.length);
}
while (SYMBOLS.indexOf(word[word.length - 1]) != -1) {
lastSymbol += word[word.length - 1];
word = word.slice(0, word.length - 1);
}
if (onlyEmoji) {
firstSymbol = lastSymbol = ''
}
let translated = getEmojiForWord(word);
if (translated) {
translation += firstSymbol + translated + lastSymbol + ' ';
} else if (!onlyEmoji){
translation += firstSymbol + word + lastSymbol + ' '
}
}
return translation;
}
|
javascript
|
function translate(sentence, onlyEmoji) {
let translation = '';
let words = sentence.split(' ');
for (let i = 0; i < words.length; i++ ) {
// Punctuation blows. Get all the punctuation at the start and end of the word.
// TODO: stop copy pasting this.
let firstSymbol = '';
let lastSymbol = '';
var word = words[i];
while (SYMBOLS.indexOf(word[0]) != -1) {
firstSymbol += word[0];
word = word.slice(1, word.length);
}
while (SYMBOLS.indexOf(word[word.length - 1]) != -1) {
lastSymbol += word[word.length - 1];
word = word.slice(0, word.length - 1);
}
if (onlyEmoji) {
firstSymbol = lastSymbol = ''
}
let translated = getEmojiForWord(word);
if (translated) {
translation += firstSymbol + translated + lastSymbol + ' ';
} else if (!onlyEmoji){
translation += firstSymbol + word + lastSymbol + ' '
}
}
return translation;
}
|
[
"function",
"translate",
"(",
"sentence",
",",
"onlyEmoji",
")",
"{",
"let",
"translation",
"=",
"''",
";",
"let",
"words",
"=",
"sentence",
".",
"split",
"(",
"' '",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"words",
".",
"length",
";",
"i",
"++",
")",
"{",
"// Punctuation blows. Get all the punctuation at the start and end of the word.",
"// TODO: stop copy pasting this.",
"let",
"firstSymbol",
"=",
"''",
";",
"let",
"lastSymbol",
"=",
"''",
";",
"var",
"word",
"=",
"words",
"[",
"i",
"]",
";",
"while",
"(",
"SYMBOLS",
".",
"indexOf",
"(",
"word",
"[",
"0",
"]",
")",
"!=",
"-",
"1",
")",
"{",
"firstSymbol",
"+=",
"word",
"[",
"0",
"]",
";",
"word",
"=",
"word",
".",
"slice",
"(",
"1",
",",
"word",
".",
"length",
")",
";",
"}",
"while",
"(",
"SYMBOLS",
".",
"indexOf",
"(",
"word",
"[",
"word",
".",
"length",
"-",
"1",
"]",
")",
"!=",
"-",
"1",
")",
"{",
"lastSymbol",
"+=",
"word",
"[",
"word",
".",
"length",
"-",
"1",
"]",
";",
"word",
"=",
"word",
".",
"slice",
"(",
"0",
",",
"word",
".",
"length",
"-",
"1",
")",
";",
"}",
"if",
"(",
"onlyEmoji",
")",
"{",
"firstSymbol",
"=",
"lastSymbol",
"=",
"''",
"}",
"let",
"translated",
"=",
"getEmojiForWord",
"(",
"word",
")",
";",
"if",
"(",
"translated",
")",
"{",
"translation",
"+=",
"firstSymbol",
"+",
"translated",
"+",
"lastSymbol",
"+",
"' '",
";",
"}",
"else",
"if",
"(",
"!",
"onlyEmoji",
")",
"{",
"translation",
"+=",
"firstSymbol",
"+",
"word",
"+",
"lastSymbol",
"+",
"' '",
"}",
"}",
"return",
"translation",
";",
"}"
] |
Translates an entire sentence to emoji. If multiple translations exist
for a particular word, a random emoji is picked.
@param {String} sentence The sentence to be translated
@param {Bool} onlyEmoji True if the translation should omit all untranslatable words
@returns {String} An emoji translation!
|
[
"Translates",
"an",
"entire",
"sentence",
"to",
"emoji",
".",
"If",
"multiple",
"translations",
"exist",
"for",
"a",
"particular",
"word",
"a",
"random",
"emoji",
"is",
"picked",
"."
] |
ed74d89410dc4aa3c67e19c5a9171b7267aba362
|
https://github.com/notwaldorf/emoji-translate/blob/ed74d89410dc4aa3c67e19c5a9171b7267aba362/emoji-translate.js#L165-L196
|
12,859
|
fzaninotto/uptime
|
lib/pollers/udp/udpPoller.js
|
function() {
var udpServer = dgram.createSocket('udp4');
// binding required for getting responses
udpServer.bind();
udpServer.on('error', function () {});
getUdpServer = function() {
return udpServer;
};
return getUdpServer();
}
|
javascript
|
function() {
var udpServer = dgram.createSocket('udp4');
// binding required for getting responses
udpServer.bind();
udpServer.on('error', function () {});
getUdpServer = function() {
return udpServer;
};
return getUdpServer();
}
|
[
"function",
"(",
")",
"{",
"var",
"udpServer",
"=",
"dgram",
".",
"createSocket",
"(",
"'udp4'",
")",
";",
"// binding required for getting responses",
"udpServer",
".",
"bind",
"(",
")",
";",
"udpServer",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
")",
"{",
"}",
")",
";",
"getUdpServer",
"=",
"function",
"(",
")",
"{",
"return",
"udpServer",
";",
"}",
";",
"return",
"getUdpServer",
"(",
")",
";",
"}"
] |
UdpServer Singleton, using self-redefining function
|
[
"UdpServer",
"Singleton",
"using",
"self",
"-",
"redefining",
"function"
] |
e2f6bfe42da7b9e8e1416cf9e0668fd9fb5e4294
|
https://github.com/fzaninotto/uptime/blob/e2f6bfe42da7b9e8e1416cf9e0668fd9fb5e4294/lib/pollers/udp/udpPoller.js#L12-L21
|
|
12,860
|
fzaninotto/uptime
|
lib/pollers/udp/udpPoller.js
|
UdpPoller
|
function UdpPoller(target, timeout, callback) {
UdpPoller.super_.call(this, target, timeout, callback);
}
|
javascript
|
function UdpPoller(target, timeout, callback) {
UdpPoller.super_.call(this, target, timeout, callback);
}
|
[
"function",
"UdpPoller",
"(",
"target",
",",
"timeout",
",",
"callback",
")",
"{",
"UdpPoller",
".",
"super_",
".",
"call",
"(",
"this",
",",
"target",
",",
"timeout",
",",
"callback",
")",
";",
"}"
] |
UDP Poller, to check UDP services
@param {Mixed} Poller Target (e.g. URL)
@param {Number} Poller timeout in milliseconds. Without response before this duration, the poller stops and executes the error callback.
@param {Function} Error/success callback
@api public
|
[
"UDP",
"Poller",
"to",
"check",
"UDP",
"services"
] |
e2f6bfe42da7b9e8e1416cf9e0668fd9fb5e4294
|
https://github.com/fzaninotto/uptime/blob/e2f6bfe42da7b9e8e1416cf9e0668fd9fb5e4294/lib/pollers/udp/udpPoller.js#L31-L33
|
12,861
|
fzaninotto/uptime
|
fixtures/populate.js
|
function(callback) {
console.log('Removing Checks');
async.series([
function(cb) { CheckEvent.collection.remove(cb); },
function(cb) { Check.collection.remove(cb); }
], callback);
}
|
javascript
|
function(callback) {
console.log('Removing Checks');
async.series([
function(cb) { CheckEvent.collection.remove(cb); },
function(cb) { Check.collection.remove(cb); }
], callback);
}
|
[
"function",
"(",
"callback",
")",
"{",
"console",
".",
"log",
"(",
"'Removing Checks'",
")",
";",
"async",
".",
"series",
"(",
"[",
"function",
"(",
"cb",
")",
"{",
"CheckEvent",
".",
"collection",
".",
"remove",
"(",
"cb",
")",
";",
"}",
",",
"function",
"(",
"cb",
")",
"{",
"Check",
".",
"collection",
".",
"remove",
"(",
"cb",
")",
";",
"}",
"]",
",",
"callback",
")",
";",
"}"
] |
defaults to 3 months ago
|
[
"defaults",
"to",
"3",
"months",
"ago"
] |
e2f6bfe42da7b9e8e1416cf9e0668fd9fb5e4294
|
https://github.com/fzaninotto/uptime/blob/e2f6bfe42da7b9e8e1416cf9e0668fd9fb5e4294/fixtures/populate.js#L9-L15
|
|
12,862
|
fzaninotto/uptime
|
lib/pollers/https/httpsPoller.js
|
HttpsPoller
|
function HttpsPoller(target, timeout, callback) {
HttpsPoller.super_.call(this, target, timeout, callback);
}
|
javascript
|
function HttpsPoller(target, timeout, callback) {
HttpsPoller.super_.call(this, target, timeout, callback);
}
|
[
"function",
"HttpsPoller",
"(",
"target",
",",
"timeout",
",",
"callback",
")",
"{",
"HttpsPoller",
".",
"super_",
".",
"call",
"(",
"this",
",",
"target",
",",
"timeout",
",",
"callback",
")",
";",
"}"
] |
HTTPS Poller, to check web pages served via SSL
@param {Mixed} Poller Target (e.g. URL)
@param {Number} Poller timeout in milliseconds. Without response before this duration, the poller stops and executes the error callback.
@param {Function} Error/success callback
@api public
|
[
"HTTPS",
"Poller",
"to",
"check",
"web",
"pages",
"served",
"via",
"SSL"
] |
e2f6bfe42da7b9e8e1416cf9e0668fd9fb5e4294
|
https://github.com/fzaninotto/uptime/blob/e2f6bfe42da7b9e8e1416cf9e0668fd9fb5e4294/lib/pollers/https/httpsPoller.js#L24-L26
|
12,863
|
fzaninotto/uptime
|
lib/pollers/http/httpPoller.js
|
HttpPoller
|
function HttpPoller(target, timeout, callback) {
HttpPoller.super_.call(this, target, timeout, callback);
}
|
javascript
|
function HttpPoller(target, timeout, callback) {
HttpPoller.super_.call(this, target, timeout, callback);
}
|
[
"function",
"HttpPoller",
"(",
"target",
",",
"timeout",
",",
"callback",
")",
"{",
"HttpPoller",
".",
"super_",
".",
"call",
"(",
"this",
",",
"target",
",",
"timeout",
",",
"callback",
")",
";",
"}"
] |
HTTP Poller, to check web pages
@param {Mixed} Poller Target (e.g. URL)
@param {Number} Poller timeout in milliseconds. Without response before this duration, the poller stops and executes the error callback.
@param {Function} Error/success callback
@api public
|
[
"HTTP",
"Poller",
"to",
"check",
"web",
"pages"
] |
e2f6bfe42da7b9e8e1416cf9e0668fd9fb5e4294
|
https://github.com/fzaninotto/uptime/blob/e2f6bfe42da7b9e8e1416cf9e0668fd9fb5e4294/lib/pollers/http/httpPoller.js#L24-L26
|
12,864
|
fzaninotto/uptime
|
lib/pollers/basePoller.js
|
BasePoller
|
function BasePoller(target, timeout, callback) {
this.target = target;
this.timeout = timeout || 5000;
this.callback = callback;
this.isDebugEnabled = false;
this.initialize();
}
|
javascript
|
function BasePoller(target, timeout, callback) {
this.target = target;
this.timeout = timeout || 5000;
this.callback = callback;
this.isDebugEnabled = false;
this.initialize();
}
|
[
"function",
"BasePoller",
"(",
"target",
",",
"timeout",
",",
"callback",
")",
"{",
"this",
".",
"target",
"=",
"target",
";",
"this",
".",
"timeout",
"=",
"timeout",
"||",
"5000",
";",
"this",
".",
"callback",
"=",
"callback",
";",
"this",
".",
"isDebugEnabled",
"=",
"false",
";",
"this",
".",
"initialize",
"(",
")",
";",
"}"
] |
Base Poller constructor
@param {Mixed} Poller Target (e.g. URL)
@param {Number} Poller timeout in milliseconds. Without response before this duration, the poller stops and executes the error callback.
@param {Function} Error/success callback
@api public
|
[
"Base",
"Poller",
"constructor"
] |
e2f6bfe42da7b9e8e1416cf9e0668fd9fb5e4294
|
https://github.com/fzaninotto/uptime/blob/e2f6bfe42da7b9e8e1416cf9e0668fd9fb5e4294/lib/pollers/basePoller.js#L14-L20
|
12,865
|
fzaninotto/uptime
|
app/api/routes/check.js
|
function(req, res, next) {
Check
.find({ _id: req.params.id })
.select({qos: 0})
.findOne(function(err, check) {
if (err) return next(err);
if (!check) return res.json(404, { error: 'failed to load check ' + req.params.id });
req.check = check;
next();
});
}
|
javascript
|
function(req, res, next) {
Check
.find({ _id: req.params.id })
.select({qos: 0})
.findOne(function(err, check) {
if (err) return next(err);
if (!check) return res.json(404, { error: 'failed to load check ' + req.params.id });
req.check = check;
next();
});
}
|
[
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"Check",
".",
"find",
"(",
"{",
"_id",
":",
"req",
".",
"params",
".",
"id",
"}",
")",
".",
"select",
"(",
"{",
"qos",
":",
"0",
"}",
")",
".",
"findOne",
"(",
"function",
"(",
"err",
",",
"check",
")",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"err",
")",
";",
"if",
"(",
"!",
"check",
")",
"return",
"res",
".",
"json",
"(",
"404",
",",
"{",
"error",
":",
"'failed to load check '",
"+",
"req",
".",
"params",
".",
"id",
"}",
")",
";",
"req",
".",
"check",
"=",
"check",
";",
"next",
"(",
")",
";",
"}",
")",
";",
"}"
] |
check route middleware
|
[
"check",
"route",
"middleware"
] |
e2f6bfe42da7b9e8e1416cf9e0668fd9fb5e4294
|
https://github.com/fzaninotto/uptime/blob/e2f6bfe42da7b9e8e1416cf9e0668fd9fb5e4294/app/api/routes/check.js#L41-L51
|
|
12,866
|
fzaninotto/uptime
|
app/api/routes/tag.js
|
function(req, res, next) {
Tag.findOne({ name: req.params.name }, function(err, tag) {
if (err) return next(err);
if (!tag) return res.json(404, { error: 'failed to load tag ' + req.params.name });
req.tag = tag;
next();
});
}
|
javascript
|
function(req, res, next) {
Tag.findOne({ name: req.params.name }, function(err, tag) {
if (err) return next(err);
if (!tag) return res.json(404, { error: 'failed to load tag ' + req.params.name });
req.tag = tag;
next();
});
}
|
[
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"Tag",
".",
"findOne",
"(",
"{",
"name",
":",
"req",
".",
"params",
".",
"name",
"}",
",",
"function",
"(",
"err",
",",
"tag",
")",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"err",
")",
";",
"if",
"(",
"!",
"tag",
")",
"return",
"res",
".",
"json",
"(",
"404",
",",
"{",
"error",
":",
"'failed to load tag '",
"+",
"req",
".",
"params",
".",
"name",
"}",
")",
";",
"req",
".",
"tag",
"=",
"tag",
";",
"next",
"(",
")",
";",
"}",
")",
";",
"}"
] |
tag route middleware
|
[
"tag",
"route",
"middleware"
] |
e2f6bfe42da7b9e8e1416cf9e0668fd9fb5e4294
|
https://github.com/fzaninotto/uptime/blob/e2f6bfe42da7b9e8e1416cf9e0668fd9fb5e4294/app/api/routes/tag.js#L26-L33
|
|
12,867
|
fzaninotto/uptime
|
lib/pollers/http/baseHttpPoller.js
|
BaseHttpPoller
|
function BaseHttpPoller(target, timeout, callback) {
BaseHttpPoller.super_.call(this, target, timeout, callback);
}
|
javascript
|
function BaseHttpPoller(target, timeout, callback) {
BaseHttpPoller.super_.call(this, target, timeout, callback);
}
|
[
"function",
"BaseHttpPoller",
"(",
"target",
",",
"timeout",
",",
"callback",
")",
"{",
"BaseHttpPoller",
".",
"super_",
".",
"call",
"(",
"this",
",",
"target",
",",
"timeout",
",",
"callback",
")",
";",
"}"
] |
Abstract class for HTTP and HTTPS Pollers, to check web pages
@param {Mixed} Poller Target (e.g. URL)
@param {Number} Poller timeout in milliseconds. Without response before this duration, the poller stops and executes the error callback.
@param {Function} Error/success callback
@api public
|
[
"Abstract",
"class",
"for",
"HTTP",
"and",
"HTTPS",
"Pollers",
"to",
"check",
"web",
"pages"
] |
e2f6bfe42da7b9e8e1416cf9e0668fd9fb5e4294
|
https://github.com/fzaninotto/uptime/blob/e2f6bfe42da7b9e8e1416cf9e0668fd9fb5e4294/lib/pollers/http/baseHttpPoller.js#L20-L22
|
12,868
|
Lucifier129/react-lite
|
addons/shallowCompare.js
|
shallowCompare
|
function shallowCompare(instance, nextProps, nextState) {
return (
!shallowEqual(instance.props, nextProps) ||
!shallowEqual(instance.state, nextState)
);
}
|
javascript
|
function shallowCompare(instance, nextProps, nextState) {
return (
!shallowEqual(instance.props, nextProps) ||
!shallowEqual(instance.state, nextState)
);
}
|
[
"function",
"shallowCompare",
"(",
"instance",
",",
"nextProps",
",",
"nextState",
")",
"{",
"return",
"(",
"!",
"shallowEqual",
"(",
"instance",
".",
"props",
",",
"nextProps",
")",
"||",
"!",
"shallowEqual",
"(",
"instance",
".",
"state",
",",
"nextState",
")",
")",
";",
"}"
] |
Does a shallow comparison for props and state.
See ReactComponentWithPureRenderMixin
|
[
"Does",
"a",
"shallow",
"comparison",
"for",
"props",
"and",
"state",
".",
"See",
"ReactComponentWithPureRenderMixin"
] |
b7586ae247615f2d4c4373f206e6c284d7931f81
|
https://github.com/Lucifier129/react-lite/blob/b7586ae247615f2d4c4373f206e6c284d7931f81/addons/shallowCompare.js#L17-L22
|
12,869
|
Lucifier129/react-lite
|
addons/utils/getIteratorFn.js
|
getIteratorFn
|
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (
(ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL]) ||
maybeIterable[FAUX_ITERATOR_SYMBOL]
);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
|
javascript
|
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (
(ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL]) ||
maybeIterable[FAUX_ITERATOR_SYMBOL]
);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
|
[
"function",
"getIteratorFn",
"(",
"maybeIterable",
")",
"{",
"var",
"iteratorFn",
"=",
"maybeIterable",
"&&",
"(",
"(",
"ITERATOR_SYMBOL",
"&&",
"maybeIterable",
"[",
"ITERATOR_SYMBOL",
"]",
")",
"||",
"maybeIterable",
"[",
"FAUX_ITERATOR_SYMBOL",
"]",
")",
";",
"if",
"(",
"typeof",
"iteratorFn",
"===",
"'function'",
")",
"{",
"return",
"iteratorFn",
";",
"}",
"}"
] |
Before Symbol spec.
Returns the iterator method function contained on the iterable object.
Be sure to invoke the function with the iterable as context:
var iteratorFn = getIteratorFn(myIterable);
if (iteratorFn) {
var iterator = iteratorFn.call(myIterable);
...
}
@param {?object} maybeIterable
@return {?function}
|
[
"Before",
"Symbol",
"spec",
".",
"Returns",
"the",
"iterator",
"method",
"function",
"contained",
"on",
"the",
"iterable",
"object",
"."
] |
b7586ae247615f2d4c4373f206e6c284d7931f81
|
https://github.com/Lucifier129/react-lite/blob/b7586ae247615f2d4c4373f206e6c284d7931f81/addons/utils/getIteratorFn.js#L33-L41
|
12,870
|
Lucifier129/react-lite
|
addons/ReactStateSetters.js
|
function(component, funcReturningState) {
return function(a, b, c, d, e, f) {
var partialState = funcReturningState.call(component, a, b, c, d, e, f);
if (partialState) {
component.setState(partialState);
}
};
}
|
javascript
|
function(component, funcReturningState) {
return function(a, b, c, d, e, f) {
var partialState = funcReturningState.call(component, a, b, c, d, e, f);
if (partialState) {
component.setState(partialState);
}
};
}
|
[
"function",
"(",
"component",
",",
"funcReturningState",
")",
"{",
"return",
"function",
"(",
"a",
",",
"b",
",",
"c",
",",
"d",
",",
"e",
",",
"f",
")",
"{",
"var",
"partialState",
"=",
"funcReturningState",
".",
"call",
"(",
"component",
",",
"a",
",",
"b",
",",
"c",
",",
"d",
",",
"e",
",",
"f",
")",
";",
"if",
"(",
"partialState",
")",
"{",
"component",
".",
"setState",
"(",
"partialState",
")",
";",
"}",
"}",
";",
"}"
] |
Returns a function that calls the provided function, and uses the result
of that to set the component's state.
@param {ReactCompositeComponent} component
@param {function} funcReturningState Returned callback uses this to
determine how to update state.
@return {function} callback that when invoked uses funcReturningState to
determined the object literal to setState.
|
[
"Returns",
"a",
"function",
"that",
"calls",
"the",
"provided",
"function",
"and",
"uses",
"the",
"result",
"of",
"that",
"to",
"set",
"the",
"component",
"s",
"state",
"."
] |
b7586ae247615f2d4c4373f206e6c284d7931f81
|
https://github.com/Lucifier129/react-lite/blob/b7586ae247615f2d4c4373f206e6c284d7931f81/addons/ReactStateSetters.js#L25-L32
|
|
12,871
|
Lucifier129/react-lite
|
addons/ReactStateSetters.js
|
function(component, key) {
// Memoize the setters.
var cache = component.__keySetters || (component.__keySetters = {});
return cache[key] || (cache[key] = createStateKeySetter(component, key));
}
|
javascript
|
function(component, key) {
// Memoize the setters.
var cache = component.__keySetters || (component.__keySetters = {});
return cache[key] || (cache[key] = createStateKeySetter(component, key));
}
|
[
"function",
"(",
"component",
",",
"key",
")",
"{",
"// Memoize the setters.",
"var",
"cache",
"=",
"component",
".",
"__keySetters",
"||",
"(",
"component",
".",
"__keySetters",
"=",
"{",
"}",
")",
";",
"return",
"cache",
"[",
"key",
"]",
"||",
"(",
"cache",
"[",
"key",
"]",
"=",
"createStateKeySetter",
"(",
"component",
",",
"key",
")",
")",
";",
"}"
] |
Returns a single-argument callback that can be used to update a single
key in the component's state.
Note: this is memoized function, which makes it inexpensive to call.
@param {ReactCompositeComponent} component
@param {string} key The key in the state that you should update.
@return {function} callback of 1 argument which calls setState() with
the provided keyName and callback argument.
|
[
"Returns",
"a",
"single",
"-",
"argument",
"callback",
"that",
"can",
"be",
"used",
"to",
"update",
"a",
"single",
"key",
"in",
"the",
"component",
"s",
"state",
"."
] |
b7586ae247615f2d4c4373f206e6c284d7931f81
|
https://github.com/Lucifier129/react-lite/blob/b7586ae247615f2d4c4373f206e6c284d7931f81/addons/ReactStateSetters.js#L45-L49
|
|
12,872
|
xmppjs/xmpp.js
|
server/index.js
|
kill
|
async function kill(pid) {
try {
process.kill(pid, 'SIGTERM')
} catch (err) {
if (err.code !== 'ESRCH') throw err
}
}
|
javascript
|
async function kill(pid) {
try {
process.kill(pid, 'SIGTERM')
} catch (err) {
if (err.code !== 'ESRCH') throw err
}
}
|
[
"async",
"function",
"kill",
"(",
"pid",
")",
"{",
"try",
"{",
"process",
".",
"kill",
"(",
"pid",
",",
"'SIGTERM'",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"code",
"!==",
"'ESRCH'",
")",
"throw",
"err",
"}",
"}"
] |
eslint-disable-next-line require-await
|
[
"eslint",
"-",
"disable",
"-",
"next",
"-",
"line",
"require",
"-",
"await"
] |
78f7a8fc220ce3dd013c60afacbf011400d23317
|
https://github.com/xmppjs/xmpp.js/blob/78f7a8fc220ce3dd013c60afacbf011400d23317/server/index.js#L54-L60
|
12,873
|
PatrickJS/angular-websocket
|
src/angular-websocket.js
|
cancelableify
|
function cancelableify(promise) {
promise.cancel = cancel;
var then = promise.then;
promise.then = function() {
var newPromise = then.apply(this, arguments);
return cancelableify(newPromise);
};
return promise;
}
|
javascript
|
function cancelableify(promise) {
promise.cancel = cancel;
var then = promise.then;
promise.then = function() {
var newPromise = then.apply(this, arguments);
return cancelableify(newPromise);
};
return promise;
}
|
[
"function",
"cancelableify",
"(",
"promise",
")",
"{",
"promise",
".",
"cancel",
"=",
"cancel",
";",
"var",
"then",
"=",
"promise",
".",
"then",
";",
"promise",
".",
"then",
"=",
"function",
"(",
")",
"{",
"var",
"newPromise",
"=",
"then",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"return",
"cancelableify",
"(",
"newPromise",
")",
";",
"}",
";",
"return",
"promise",
";",
"}"
] |
Credit goes to @btford
|
[
"Credit",
"goes",
"to"
] |
1d3101e00cf396e1de436a26c6834f9b48529804
|
https://github.com/PatrickJS/angular-websocket/blob/1d3101e00cf396e1de436a26c6834f9b48529804/src/angular-websocket.js#L286-L294
|
12,874
|
QuantumMechanics/NEM-sdk
|
src/crypto/cryptoHelpers.js
|
function(common, walletAccount, algo) {
// Errors
if(!common || !walletAccount || !algo) throw new Error('Missing argument !');
let r = undefined;
if (algo === "trezor") { // HW wallet
r = { 'priv': '' };
common.isHW = true;
} else if (!common.password) {
throw new Error('Missing argument !');
}
// Processing
if (algo === "pass:6k") { // Brain wallets
if (!walletAccount.encrypted && !walletAccount.iv) {
// Account private key is generated simply using a passphrase so it has no encrypted and iv
r = derivePassSha(common.password, 6000);
} else if (!walletAccount.encrypted || !walletAccount.iv) {
// Else if one is missing there is a problem
//console.log("Account might be compromised, missing encrypted or iv");
return false;
} else {
// Else child accounts have encrypted and iv so we decrypt
let pass = derivePassSha(common.password, 20);
let obj = {
ciphertext: CryptoJS.enc.Hex.parse(walletAccount.encrypted),
iv: convert.hex2ua(walletAccount.iv),
key: convert.hex2ua(pass.priv)
};
let d = decrypt(obj);
r = { 'priv': d };
}
} else if (algo === "pass:bip32") { // Wallets from PRNG
let pass = derivePassSha(common.password, 20);
let obj = {
ciphertext: CryptoJS.enc.Hex.parse(walletAccount.encrypted),
iv: convert.hex2ua(walletAccount.iv),
key: convert.hex2ua(pass.priv)
};
let d = decrypt(obj);
r = { 'priv': d };
} else if (algo === "pass:enc") { // Private Key wallets
let pass = derivePassSha(common.password, 20);
let obj = {
ciphertext: CryptoJS.enc.Hex.parse(walletAccount.encrypted),
iv: convert.hex2ua(walletAccount.iv),
key: convert.hex2ua(pass.priv)
};
let d = decrypt(obj);
r = { 'priv': d };
} else if (!r) {
//console.log("Unknown wallet encryption method");
return false;
}
// Result
common.privateKey = r.priv;
return true;
}
|
javascript
|
function(common, walletAccount, algo) {
// Errors
if(!common || !walletAccount || !algo) throw new Error('Missing argument !');
let r = undefined;
if (algo === "trezor") { // HW wallet
r = { 'priv': '' };
common.isHW = true;
} else if (!common.password) {
throw new Error('Missing argument !');
}
// Processing
if (algo === "pass:6k") { // Brain wallets
if (!walletAccount.encrypted && !walletAccount.iv) {
// Account private key is generated simply using a passphrase so it has no encrypted and iv
r = derivePassSha(common.password, 6000);
} else if (!walletAccount.encrypted || !walletAccount.iv) {
// Else if one is missing there is a problem
//console.log("Account might be compromised, missing encrypted or iv");
return false;
} else {
// Else child accounts have encrypted and iv so we decrypt
let pass = derivePassSha(common.password, 20);
let obj = {
ciphertext: CryptoJS.enc.Hex.parse(walletAccount.encrypted),
iv: convert.hex2ua(walletAccount.iv),
key: convert.hex2ua(pass.priv)
};
let d = decrypt(obj);
r = { 'priv': d };
}
} else if (algo === "pass:bip32") { // Wallets from PRNG
let pass = derivePassSha(common.password, 20);
let obj = {
ciphertext: CryptoJS.enc.Hex.parse(walletAccount.encrypted),
iv: convert.hex2ua(walletAccount.iv),
key: convert.hex2ua(pass.priv)
};
let d = decrypt(obj);
r = { 'priv': d };
} else if (algo === "pass:enc") { // Private Key wallets
let pass = derivePassSha(common.password, 20);
let obj = {
ciphertext: CryptoJS.enc.Hex.parse(walletAccount.encrypted),
iv: convert.hex2ua(walletAccount.iv),
key: convert.hex2ua(pass.priv)
};
let d = decrypt(obj);
r = { 'priv': d };
} else if (!r) {
//console.log("Unknown wallet encryption method");
return false;
}
// Result
common.privateKey = r.priv;
return true;
}
|
[
"function",
"(",
"common",
",",
"walletAccount",
",",
"algo",
")",
"{",
"// Errors",
"if",
"(",
"!",
"common",
"||",
"!",
"walletAccount",
"||",
"!",
"algo",
")",
"throw",
"new",
"Error",
"(",
"'Missing argument !'",
")",
";",
"let",
"r",
"=",
"undefined",
";",
"if",
"(",
"algo",
"===",
"\"trezor\"",
")",
"{",
"// HW wallet",
"r",
"=",
"{",
"'priv'",
":",
"''",
"}",
";",
"common",
".",
"isHW",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"!",
"common",
".",
"password",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing argument !'",
")",
";",
"}",
"// Processing",
"if",
"(",
"algo",
"===",
"\"pass:6k\"",
")",
"{",
"// Brain wallets",
"if",
"(",
"!",
"walletAccount",
".",
"encrypted",
"&&",
"!",
"walletAccount",
".",
"iv",
")",
"{",
"// Account private key is generated simply using a passphrase so it has no encrypted and iv",
"r",
"=",
"derivePassSha",
"(",
"common",
".",
"password",
",",
"6000",
")",
";",
"}",
"else",
"if",
"(",
"!",
"walletAccount",
".",
"encrypted",
"||",
"!",
"walletAccount",
".",
"iv",
")",
"{",
"// Else if one is missing there is a problem",
"//console.log(\"Account might be compromised, missing encrypted or iv\");",
"return",
"false",
";",
"}",
"else",
"{",
"// Else child accounts have encrypted and iv so we decrypt",
"let",
"pass",
"=",
"derivePassSha",
"(",
"common",
".",
"password",
",",
"20",
")",
";",
"let",
"obj",
"=",
"{",
"ciphertext",
":",
"CryptoJS",
".",
"enc",
".",
"Hex",
".",
"parse",
"(",
"walletAccount",
".",
"encrypted",
")",
",",
"iv",
":",
"convert",
".",
"hex2ua",
"(",
"walletAccount",
".",
"iv",
")",
",",
"key",
":",
"convert",
".",
"hex2ua",
"(",
"pass",
".",
"priv",
")",
"}",
";",
"let",
"d",
"=",
"decrypt",
"(",
"obj",
")",
";",
"r",
"=",
"{",
"'priv'",
":",
"d",
"}",
";",
"}",
"}",
"else",
"if",
"(",
"algo",
"===",
"\"pass:bip32\"",
")",
"{",
"// Wallets from PRNG",
"let",
"pass",
"=",
"derivePassSha",
"(",
"common",
".",
"password",
",",
"20",
")",
";",
"let",
"obj",
"=",
"{",
"ciphertext",
":",
"CryptoJS",
".",
"enc",
".",
"Hex",
".",
"parse",
"(",
"walletAccount",
".",
"encrypted",
")",
",",
"iv",
":",
"convert",
".",
"hex2ua",
"(",
"walletAccount",
".",
"iv",
")",
",",
"key",
":",
"convert",
".",
"hex2ua",
"(",
"pass",
".",
"priv",
")",
"}",
";",
"let",
"d",
"=",
"decrypt",
"(",
"obj",
")",
";",
"r",
"=",
"{",
"'priv'",
":",
"d",
"}",
";",
"}",
"else",
"if",
"(",
"algo",
"===",
"\"pass:enc\"",
")",
"{",
"// Private Key wallets",
"let",
"pass",
"=",
"derivePassSha",
"(",
"common",
".",
"password",
",",
"20",
")",
";",
"let",
"obj",
"=",
"{",
"ciphertext",
":",
"CryptoJS",
".",
"enc",
".",
"Hex",
".",
"parse",
"(",
"walletAccount",
".",
"encrypted",
")",
",",
"iv",
":",
"convert",
".",
"hex2ua",
"(",
"walletAccount",
".",
"iv",
")",
",",
"key",
":",
"convert",
".",
"hex2ua",
"(",
"pass",
".",
"priv",
")",
"}",
";",
"let",
"d",
"=",
"decrypt",
"(",
"obj",
")",
";",
"r",
"=",
"{",
"'priv'",
":",
"d",
"}",
";",
"}",
"else",
"if",
"(",
"!",
"r",
")",
"{",
"//console.log(\"Unknown wallet encryption method\");",
"return",
"false",
";",
"}",
"// Result",
"common",
".",
"privateKey",
"=",
"r",
".",
"priv",
";",
"return",
"true",
";",
"}"
] |
Reveal the private key of an account or derive it from the wallet password
@param {object} common- An object containing password and privateKey field
@param {object} walletAccount - A wallet account object
@param {string} algo - A wallet algorithm
@return {object|boolean} - The account private key in and object or false
|
[
"Reveal",
"the",
"private",
"key",
"of",
"an",
"account",
"or",
"derive",
"it",
"from",
"the",
"wallet",
"password"
] |
4b0b60007c52ff4a89deeef84f9ca95b61c92fca
|
https://github.com/QuantumMechanics/NEM-sdk/blob/4b0b60007c52ff4a89deeef84f9ca95b61c92fca/src/crypto/cryptoHelpers.js#L75-L133
|
|
12,875
|
QuantumMechanics/NEM-sdk
|
src/crypto/cryptoHelpers.js
|
function(priv, network, _expectedAddress) {
// Errors
if (!priv || !network || !_expectedAddress) throw new Error('Missing argument !');
if (!Helpers.isPrivateKeyValid(priv)) throw new Error('Private key is not valid !');
//Processing
let expectedAddress = _expectedAddress.toUpperCase().replace(/-/g, '');
let kp = KeyPair.create(priv);
let address = Address.toAddress(kp.publicKey.toString(), network);
// Result
return address === expectedAddress;
}
|
javascript
|
function(priv, network, _expectedAddress) {
// Errors
if (!priv || !network || !_expectedAddress) throw new Error('Missing argument !');
if (!Helpers.isPrivateKeyValid(priv)) throw new Error('Private key is not valid !');
//Processing
let expectedAddress = _expectedAddress.toUpperCase().replace(/-/g, '');
let kp = KeyPair.create(priv);
let address = Address.toAddress(kp.publicKey.toString(), network);
// Result
return address === expectedAddress;
}
|
[
"function",
"(",
"priv",
",",
"network",
",",
"_expectedAddress",
")",
"{",
"// Errors",
"if",
"(",
"!",
"priv",
"||",
"!",
"network",
"||",
"!",
"_expectedAddress",
")",
"throw",
"new",
"Error",
"(",
"'Missing argument !'",
")",
";",
"if",
"(",
"!",
"Helpers",
".",
"isPrivateKeyValid",
"(",
"priv",
")",
")",
"throw",
"new",
"Error",
"(",
"'Private key is not valid !'",
")",
";",
"//Processing",
"let",
"expectedAddress",
"=",
"_expectedAddress",
".",
"toUpperCase",
"(",
")",
".",
"replace",
"(",
"/",
"-",
"/",
"g",
",",
"''",
")",
";",
"let",
"kp",
"=",
"KeyPair",
".",
"create",
"(",
"priv",
")",
";",
"let",
"address",
"=",
"Address",
".",
"toAddress",
"(",
"kp",
".",
"publicKey",
".",
"toString",
"(",
")",
",",
"network",
")",
";",
"// Result",
"return",
"address",
"===",
"expectedAddress",
";",
"}"
] |
Check if a private key correspond to an account address
@param {string} priv - An account private key
@param {number} network - A network id
@param {string} _expectedAddress - The expected NEM address
@return {boolean} - True if valid, false otherwise
|
[
"Check",
"if",
"a",
"private",
"key",
"correspond",
"to",
"an",
"account",
"address"
] |
4b0b60007c52ff4a89deeef84f9ca95b61c92fca
|
https://github.com/QuantumMechanics/NEM-sdk/blob/4b0b60007c52ff4a89deeef84f9ca95b61c92fca/src/crypto/cryptoHelpers.js#L144-L154
|
|
12,876
|
QuantumMechanics/NEM-sdk
|
src/crypto/cryptoHelpers.js
|
function(data, key) {
// Errors
if (!data || !key) throw new Error('Missing argument !');
// Processing
let iv = nacl.randomBytes(16)
let encKey = convert.ua2words(key, 32);
let encIv = {
iv: convert.ua2words(iv, 16)
};
let encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Hex.parse(data), encKey, encIv);
// Result
return {
ciphertext: encrypted.ciphertext,
iv: iv,
key: key
};
}
|
javascript
|
function(data, key) {
// Errors
if (!data || !key) throw new Error('Missing argument !');
// Processing
let iv = nacl.randomBytes(16)
let encKey = convert.ua2words(key, 32);
let encIv = {
iv: convert.ua2words(iv, 16)
};
let encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Hex.parse(data), encKey, encIv);
// Result
return {
ciphertext: encrypted.ciphertext,
iv: iv,
key: key
};
}
|
[
"function",
"(",
"data",
",",
"key",
")",
"{",
"// Errors",
"if",
"(",
"!",
"data",
"||",
"!",
"key",
")",
"throw",
"new",
"Error",
"(",
"'Missing argument !'",
")",
";",
"// Processing",
"let",
"iv",
"=",
"nacl",
".",
"randomBytes",
"(",
"16",
")",
"let",
"encKey",
"=",
"convert",
".",
"ua2words",
"(",
"key",
",",
"32",
")",
";",
"let",
"encIv",
"=",
"{",
"iv",
":",
"convert",
".",
"ua2words",
"(",
"iv",
",",
"16",
")",
"}",
";",
"let",
"encrypted",
"=",
"CryptoJS",
".",
"AES",
".",
"encrypt",
"(",
"CryptoJS",
".",
"enc",
".",
"Hex",
".",
"parse",
"(",
"data",
")",
",",
"encKey",
",",
"encIv",
")",
";",
"// Result",
"return",
"{",
"ciphertext",
":",
"encrypted",
".",
"ciphertext",
",",
"iv",
":",
"iv",
",",
"key",
":",
"key",
"}",
";",
"}"
] |
Encrypt hex data using a key
@param {string} data - An hex string
@param {Uint8Array} key - An Uint8Array key
@return {object} - The encrypted data
|
[
"Encrypt",
"hex",
"data",
"using",
"a",
"key"
] |
4b0b60007c52ff4a89deeef84f9ca95b61c92fca
|
https://github.com/QuantumMechanics/NEM-sdk/blob/4b0b60007c52ff4a89deeef84f9ca95b61c92fca/src/crypto/cryptoHelpers.js#L193-L209
|
|
12,877
|
QuantumMechanics/NEM-sdk
|
src/crypto/cryptoHelpers.js
|
function(privateKey, password) {
// Errors
if (!privateKey || !password) throw new Error('Missing argument !');
if (!Helpers.isPrivateKeyValid(privateKey)) throw new Error('Private key is not valid !');
// Processing
let pass = derivePassSha(password, 20);
let r = encrypt(privateKey, convert.hex2ua(pass.priv));
// Result
return {
ciphertext: CryptoJS.enc.Hex.stringify(r.ciphertext),
iv: convert.ua2hex(r.iv)
};
}
|
javascript
|
function(privateKey, password) {
// Errors
if (!privateKey || !password) throw new Error('Missing argument !');
if (!Helpers.isPrivateKeyValid(privateKey)) throw new Error('Private key is not valid !');
// Processing
let pass = derivePassSha(password, 20);
let r = encrypt(privateKey, convert.hex2ua(pass.priv));
// Result
return {
ciphertext: CryptoJS.enc.Hex.stringify(r.ciphertext),
iv: convert.ua2hex(r.iv)
};
}
|
[
"function",
"(",
"privateKey",
",",
"password",
")",
"{",
"// Errors",
"if",
"(",
"!",
"privateKey",
"||",
"!",
"password",
")",
"throw",
"new",
"Error",
"(",
"'Missing argument !'",
")",
";",
"if",
"(",
"!",
"Helpers",
".",
"isPrivateKeyValid",
"(",
"privateKey",
")",
")",
"throw",
"new",
"Error",
"(",
"'Private key is not valid !'",
")",
";",
"// Processing",
"let",
"pass",
"=",
"derivePassSha",
"(",
"password",
",",
"20",
")",
";",
"let",
"r",
"=",
"encrypt",
"(",
"privateKey",
",",
"convert",
".",
"hex2ua",
"(",
"pass",
".",
"priv",
")",
")",
";",
"// Result",
"return",
"{",
"ciphertext",
":",
"CryptoJS",
".",
"enc",
".",
"Hex",
".",
"stringify",
"(",
"r",
".",
"ciphertext",
")",
",",
"iv",
":",
"convert",
".",
"ua2hex",
"(",
"r",
".",
"iv",
")",
"}",
";",
"}"
] |
Encode a private key using a password
@param {string} privateKey - An hex private key
@param {string} password - A password
@return {object} - The encoded data
|
[
"Encode",
"a",
"private",
"key",
"using",
"a",
"password"
] |
4b0b60007c52ff4a89deeef84f9ca95b61c92fca
|
https://github.com/QuantumMechanics/NEM-sdk/blob/4b0b60007c52ff4a89deeef84f9ca95b61c92fca/src/crypto/cryptoHelpers.js#L238-L250
|
|
12,878
|
QuantumMechanics/NEM-sdk
|
src/crypto/cryptoHelpers.js
|
function(senderPriv, recipientPub, msg) {
// Errors
if (!senderPriv || !recipientPub || !msg) throw new Error('Missing argument !');
if (!Helpers.isPrivateKeyValid(senderPriv)) throw new Error('Private key is not valid !');
if (!Helpers.isPublicKeyValid(recipientPub)) throw new Error('Public key is not valid !');
// Processing
let iv = nacl.randomBytes(16)
//console.log("IV:", convert.ua2hex(iv));
let salt = nacl.randomBytes(32)
let encoded = _encode(senderPriv, recipientPub, msg, iv, salt);
// Result
return encoded;
}
|
javascript
|
function(senderPriv, recipientPub, msg) {
// Errors
if (!senderPriv || !recipientPub || !msg) throw new Error('Missing argument !');
if (!Helpers.isPrivateKeyValid(senderPriv)) throw new Error('Private key is not valid !');
if (!Helpers.isPublicKeyValid(recipientPub)) throw new Error('Public key is not valid !');
// Processing
let iv = nacl.randomBytes(16)
//console.log("IV:", convert.ua2hex(iv));
let salt = nacl.randomBytes(32)
let encoded = _encode(senderPriv, recipientPub, msg, iv, salt);
// Result
return encoded;
}
|
[
"function",
"(",
"senderPriv",
",",
"recipientPub",
",",
"msg",
")",
"{",
"// Errors",
"if",
"(",
"!",
"senderPriv",
"||",
"!",
"recipientPub",
"||",
"!",
"msg",
")",
"throw",
"new",
"Error",
"(",
"'Missing argument !'",
")",
";",
"if",
"(",
"!",
"Helpers",
".",
"isPrivateKeyValid",
"(",
"senderPriv",
")",
")",
"throw",
"new",
"Error",
"(",
"'Private key is not valid !'",
")",
";",
"if",
"(",
"!",
"Helpers",
".",
"isPublicKeyValid",
"(",
"recipientPub",
")",
")",
"throw",
"new",
"Error",
"(",
"'Public key is not valid !'",
")",
";",
"// Processing",
"let",
"iv",
"=",
"nacl",
".",
"randomBytes",
"(",
"16",
")",
"//console.log(\"IV:\", convert.ua2hex(iv));",
"let",
"salt",
"=",
"nacl",
".",
"randomBytes",
"(",
"32",
")",
"let",
"encoded",
"=",
"_encode",
"(",
"senderPriv",
",",
"recipientPub",
",",
"msg",
",",
"iv",
",",
"salt",
")",
";",
"// Result",
"return",
"encoded",
";",
"}"
] |
Encode a message
@param {string} senderPriv - A sender private key
@param {string} recipientPub - A recipient public key
@param {string} msg - A text message
@return {string} - The encoded message
|
[
"Encode",
"a",
"message"
] |
4b0b60007c52ff4a89deeef84f9ca95b61c92fca
|
https://github.com/QuantumMechanics/NEM-sdk/blob/4b0b60007c52ff4a89deeef84f9ca95b61c92fca/src/crypto/cryptoHelpers.js#L292-L304
|
|
12,879
|
QuantumMechanics/NEM-sdk
|
src/crypto/cryptoHelpers.js
|
function(recipientPrivate, senderPublic, _payload) {
// Errors
if(!recipientPrivate || !senderPublic || !_payload) throw new Error('Missing argument !');
if (!Helpers.isPrivateKeyValid(recipientPrivate)) throw new Error('Private key is not valid !');
if (!Helpers.isPublicKeyValid(senderPublic)) throw new Error('Public key is not valid !');
// Processing
let binPayload = convert.hex2ua(_payload);
let salt = new Uint8Array(binPayload.buffer, 0, 32);
let iv = new Uint8Array(binPayload.buffer, 32, 16);
let payload = new Uint8Array(binPayload.buffer, 48);
let sk = convert.hex2ua_reversed(recipientPrivate);
let pk = convert.hex2ua(senderPublic);
let shared = new Uint8Array(32);
let r = key_derive(shared, salt, sk, pk);
let encKey = r;
let encIv = {
iv: convert.ua2words(iv, 16)
};
let encrypted = {
'ciphertext': convert.ua2words(payload, payload.length)
};
let plain = CryptoJS.AES.decrypt(encrypted, encKey, encIv);
// Result
let hexplain = CryptoJS.enc.Hex.stringify(plain);
return hexplain;
}
|
javascript
|
function(recipientPrivate, senderPublic, _payload) {
// Errors
if(!recipientPrivate || !senderPublic || !_payload) throw new Error('Missing argument !');
if (!Helpers.isPrivateKeyValid(recipientPrivate)) throw new Error('Private key is not valid !');
if (!Helpers.isPublicKeyValid(senderPublic)) throw new Error('Public key is not valid !');
// Processing
let binPayload = convert.hex2ua(_payload);
let salt = new Uint8Array(binPayload.buffer, 0, 32);
let iv = new Uint8Array(binPayload.buffer, 32, 16);
let payload = new Uint8Array(binPayload.buffer, 48);
let sk = convert.hex2ua_reversed(recipientPrivate);
let pk = convert.hex2ua(senderPublic);
let shared = new Uint8Array(32);
let r = key_derive(shared, salt, sk, pk);
let encKey = r;
let encIv = {
iv: convert.ua2words(iv, 16)
};
let encrypted = {
'ciphertext': convert.ua2words(payload, payload.length)
};
let plain = CryptoJS.AES.decrypt(encrypted, encKey, encIv);
// Result
let hexplain = CryptoJS.enc.Hex.stringify(plain);
return hexplain;
}
|
[
"function",
"(",
"recipientPrivate",
",",
"senderPublic",
",",
"_payload",
")",
"{",
"// Errors",
"if",
"(",
"!",
"recipientPrivate",
"||",
"!",
"senderPublic",
"||",
"!",
"_payload",
")",
"throw",
"new",
"Error",
"(",
"'Missing argument !'",
")",
";",
"if",
"(",
"!",
"Helpers",
".",
"isPrivateKeyValid",
"(",
"recipientPrivate",
")",
")",
"throw",
"new",
"Error",
"(",
"'Private key is not valid !'",
")",
";",
"if",
"(",
"!",
"Helpers",
".",
"isPublicKeyValid",
"(",
"senderPublic",
")",
")",
"throw",
"new",
"Error",
"(",
"'Public key is not valid !'",
")",
";",
"// Processing",
"let",
"binPayload",
"=",
"convert",
".",
"hex2ua",
"(",
"_payload",
")",
";",
"let",
"salt",
"=",
"new",
"Uint8Array",
"(",
"binPayload",
".",
"buffer",
",",
"0",
",",
"32",
")",
";",
"let",
"iv",
"=",
"new",
"Uint8Array",
"(",
"binPayload",
".",
"buffer",
",",
"32",
",",
"16",
")",
";",
"let",
"payload",
"=",
"new",
"Uint8Array",
"(",
"binPayload",
".",
"buffer",
",",
"48",
")",
";",
"let",
"sk",
"=",
"convert",
".",
"hex2ua_reversed",
"(",
"recipientPrivate",
")",
";",
"let",
"pk",
"=",
"convert",
".",
"hex2ua",
"(",
"senderPublic",
")",
";",
"let",
"shared",
"=",
"new",
"Uint8Array",
"(",
"32",
")",
";",
"let",
"r",
"=",
"key_derive",
"(",
"shared",
",",
"salt",
",",
"sk",
",",
"pk",
")",
";",
"let",
"encKey",
"=",
"r",
";",
"let",
"encIv",
"=",
"{",
"iv",
":",
"convert",
".",
"ua2words",
"(",
"iv",
",",
"16",
")",
"}",
";",
"let",
"encrypted",
"=",
"{",
"'ciphertext'",
":",
"convert",
".",
"ua2words",
"(",
"payload",
",",
"payload",
".",
"length",
")",
"}",
";",
"let",
"plain",
"=",
"CryptoJS",
".",
"AES",
".",
"decrypt",
"(",
"encrypted",
",",
"encKey",
",",
"encIv",
")",
";",
"// Result",
"let",
"hexplain",
"=",
"CryptoJS",
".",
"enc",
".",
"Hex",
".",
"stringify",
"(",
"plain",
")",
";",
"return",
"hexplain",
";",
"}"
] |
Decode an encrypted message payload
@param {string} recipientPrivate - A recipient private key
@param {string} senderPublic - A sender public key
@param {string} _payload - An encrypted message payload
@return {string} - The decoded payload as hex
|
[
"Decode",
"an",
"encrypted",
"message",
"payload"
] |
4b0b60007c52ff4a89deeef84f9ca95b61c92fca
|
https://github.com/QuantumMechanics/NEM-sdk/blob/4b0b60007c52ff4a89deeef84f9ca95b61c92fca/src/crypto/cryptoHelpers.js#L315-L340
|
|
12,880
|
QuantumMechanics/NEM-sdk
|
examples/browser/transfer/script.js
|
updateFee
|
function updateFee() {
// Check for amount errors
if(undefined === $("#amount").val() || !nem.utils.helpers.isTextAmountValid($("#amount").val())) return alert('Invalid amount !');
// Set the cleaned amount into transfer transaction object
transferTransaction.amount = nem.utils.helpers.cleanTextAmount($("#amount").val());
// Set the message into transfer transaction object
transferTransaction.message = $("#message").val();
// Prepare the updated transfer transaction object
var transactionEntity = nem.model.transactions.prepare("transferTransaction")(common, transferTransaction, nem.model.network.data.testnet.id);
// Format fee returned in prepared object
var feeString = nem.utils.format.nemValue(transactionEntity.fee)[0] + "." + nem.utils.format.nemValue(transactionEntity.fee)[1];
//Set fee in view
$("#fee").html(feeString);
}
|
javascript
|
function updateFee() {
// Check for amount errors
if(undefined === $("#amount").val() || !nem.utils.helpers.isTextAmountValid($("#amount").val())) return alert('Invalid amount !');
// Set the cleaned amount into transfer transaction object
transferTransaction.amount = nem.utils.helpers.cleanTextAmount($("#amount").val());
// Set the message into transfer transaction object
transferTransaction.message = $("#message").val();
// Prepare the updated transfer transaction object
var transactionEntity = nem.model.transactions.prepare("transferTransaction")(common, transferTransaction, nem.model.network.data.testnet.id);
// Format fee returned in prepared object
var feeString = nem.utils.format.nemValue(transactionEntity.fee)[0] + "." + nem.utils.format.nemValue(transactionEntity.fee)[1];
//Set fee in view
$("#fee").html(feeString);
}
|
[
"function",
"updateFee",
"(",
")",
"{",
"// Check for amount errors",
"if",
"(",
"undefined",
"===",
"$",
"(",
"\"#amount\"",
")",
".",
"val",
"(",
")",
"||",
"!",
"nem",
".",
"utils",
".",
"helpers",
".",
"isTextAmountValid",
"(",
"$",
"(",
"\"#amount\"",
")",
".",
"val",
"(",
")",
")",
")",
"return",
"alert",
"(",
"'Invalid amount !'",
")",
";",
"// Set the cleaned amount into transfer transaction object",
"transferTransaction",
".",
"amount",
"=",
"nem",
".",
"utils",
".",
"helpers",
".",
"cleanTextAmount",
"(",
"$",
"(",
"\"#amount\"",
")",
".",
"val",
"(",
")",
")",
";",
"// Set the message into transfer transaction object",
"transferTransaction",
".",
"message",
"=",
"$",
"(",
"\"#message\"",
")",
".",
"val",
"(",
")",
";",
"// Prepare the updated transfer transaction object",
"var",
"transactionEntity",
"=",
"nem",
".",
"model",
".",
"transactions",
".",
"prepare",
"(",
"\"transferTransaction\"",
")",
"(",
"common",
",",
"transferTransaction",
",",
"nem",
".",
"model",
".",
"network",
".",
"data",
".",
"testnet",
".",
"id",
")",
";",
"// Format fee returned in prepared object",
"var",
"feeString",
"=",
"nem",
".",
"utils",
".",
"format",
".",
"nemValue",
"(",
"transactionEntity",
".",
"fee",
")",
"[",
"0",
"]",
"+",
"\".\"",
"+",
"nem",
".",
"utils",
".",
"format",
".",
"nemValue",
"(",
"transactionEntity",
".",
"fee",
")",
"[",
"1",
"]",
";",
"//Set fee in view",
"$",
"(",
"\"#fee\"",
")",
".",
"html",
"(",
"feeString",
")",
";",
"}"
] |
Function to update our fee in the view
|
[
"Function",
"to",
"update",
"our",
"fee",
"in",
"the",
"view"
] |
4b0b60007c52ff4a89deeef84f9ca95b61c92fca
|
https://github.com/QuantumMechanics/NEM-sdk/blob/4b0b60007c52ff4a89deeef84f9ca95b61c92fca/examples/browser/transfer/script.js#L21-L39
|
12,881
|
QuantumMechanics/NEM-sdk
|
examples/browser/transfer/script.js
|
send
|
function send() {
// Check form for errors
if(!$("#privateKey").val() || !$("#recipient").val()) return alert('Missing parameter !');
if(undefined === $("#amount").val() || !nem.utils.helpers.isTextAmountValid($("#amount").val())) return alert('Invalid amount !');
if (!nem.model.address.isValid(nem.model.address.clean($("#recipient").val()))) return alert('Invalid recipent address !');
// Set the private key in common object
common.privateKey = $("#privateKey").val();
// Check private key for errors
if (common.privateKey.length !== 64 && common.privateKey.length !== 66) return alert('Invalid private key, length must be 64 or 66 characters !');
if (!nem.utils.helpers.isHexadecimal(common.privateKey)) return alert('Private key must be hexadecimal only !');
// Set the cleaned amount into transfer transaction object
transferTransaction.amount = nem.utils.helpers.cleanTextAmount($("#amount").val());
// Recipient address must be clean (no hypens: "-")
transferTransaction.recipient = nem.model.address.clean($("#recipient").val());
// Set message
transferTransaction.message = $("#message").val();
// Prepare the updated transfer transaction object
var transactionEntity = nem.model.transactions.prepare("transferTransaction")(common, transferTransaction, nem.model.network.data.testnet.id);
// Serialize transfer transaction and announce
nem.model.transactions.send(common, transactionEntity, endpoint).then(function(res){
// If code >= 2, it's an error
if (res.code >= 2) {
alert(res.message);
} else {
alert(res.message);
}
}, function(err) {
alert(err);
});
}
|
javascript
|
function send() {
// Check form for errors
if(!$("#privateKey").val() || !$("#recipient").val()) return alert('Missing parameter !');
if(undefined === $("#amount").val() || !nem.utils.helpers.isTextAmountValid($("#amount").val())) return alert('Invalid amount !');
if (!nem.model.address.isValid(nem.model.address.clean($("#recipient").val()))) return alert('Invalid recipent address !');
// Set the private key in common object
common.privateKey = $("#privateKey").val();
// Check private key for errors
if (common.privateKey.length !== 64 && common.privateKey.length !== 66) return alert('Invalid private key, length must be 64 or 66 characters !');
if (!nem.utils.helpers.isHexadecimal(common.privateKey)) return alert('Private key must be hexadecimal only !');
// Set the cleaned amount into transfer transaction object
transferTransaction.amount = nem.utils.helpers.cleanTextAmount($("#amount").val());
// Recipient address must be clean (no hypens: "-")
transferTransaction.recipient = nem.model.address.clean($("#recipient").val());
// Set message
transferTransaction.message = $("#message").val();
// Prepare the updated transfer transaction object
var transactionEntity = nem.model.transactions.prepare("transferTransaction")(common, transferTransaction, nem.model.network.data.testnet.id);
// Serialize transfer transaction and announce
nem.model.transactions.send(common, transactionEntity, endpoint).then(function(res){
// If code >= 2, it's an error
if (res.code >= 2) {
alert(res.message);
} else {
alert(res.message);
}
}, function(err) {
alert(err);
});
}
|
[
"function",
"send",
"(",
")",
"{",
"// Check form for errors",
"if",
"(",
"!",
"$",
"(",
"\"#privateKey\"",
")",
".",
"val",
"(",
")",
"||",
"!",
"$",
"(",
"\"#recipient\"",
")",
".",
"val",
"(",
")",
")",
"return",
"alert",
"(",
"'Missing parameter !'",
")",
";",
"if",
"(",
"undefined",
"===",
"$",
"(",
"\"#amount\"",
")",
".",
"val",
"(",
")",
"||",
"!",
"nem",
".",
"utils",
".",
"helpers",
".",
"isTextAmountValid",
"(",
"$",
"(",
"\"#amount\"",
")",
".",
"val",
"(",
")",
")",
")",
"return",
"alert",
"(",
"'Invalid amount !'",
")",
";",
"if",
"(",
"!",
"nem",
".",
"model",
".",
"address",
".",
"isValid",
"(",
"nem",
".",
"model",
".",
"address",
".",
"clean",
"(",
"$",
"(",
"\"#recipient\"",
")",
".",
"val",
"(",
")",
")",
")",
")",
"return",
"alert",
"(",
"'Invalid recipent address !'",
")",
";",
"// Set the private key in common object",
"common",
".",
"privateKey",
"=",
"$",
"(",
"\"#privateKey\"",
")",
".",
"val",
"(",
")",
";",
"// Check private key for errors",
"if",
"(",
"common",
".",
"privateKey",
".",
"length",
"!==",
"64",
"&&",
"common",
".",
"privateKey",
".",
"length",
"!==",
"66",
")",
"return",
"alert",
"(",
"'Invalid private key, length must be 64 or 66 characters !'",
")",
";",
"if",
"(",
"!",
"nem",
".",
"utils",
".",
"helpers",
".",
"isHexadecimal",
"(",
"common",
".",
"privateKey",
")",
")",
"return",
"alert",
"(",
"'Private key must be hexadecimal only !'",
")",
";",
"// Set the cleaned amount into transfer transaction object",
"transferTransaction",
".",
"amount",
"=",
"nem",
".",
"utils",
".",
"helpers",
".",
"cleanTextAmount",
"(",
"$",
"(",
"\"#amount\"",
")",
".",
"val",
"(",
")",
")",
";",
"// Recipient address must be clean (no hypens: \"-\")",
"transferTransaction",
".",
"recipient",
"=",
"nem",
".",
"model",
".",
"address",
".",
"clean",
"(",
"$",
"(",
"\"#recipient\"",
")",
".",
"val",
"(",
")",
")",
";",
"// Set message",
"transferTransaction",
".",
"message",
"=",
"$",
"(",
"\"#message\"",
")",
".",
"val",
"(",
")",
";",
"// Prepare the updated transfer transaction object",
"var",
"transactionEntity",
"=",
"nem",
".",
"model",
".",
"transactions",
".",
"prepare",
"(",
"\"transferTransaction\"",
")",
"(",
"common",
",",
"transferTransaction",
",",
"nem",
".",
"model",
".",
"network",
".",
"data",
".",
"testnet",
".",
"id",
")",
";",
"// Serialize transfer transaction and announce",
"nem",
".",
"model",
".",
"transactions",
".",
"send",
"(",
"common",
",",
"transactionEntity",
",",
"endpoint",
")",
".",
"then",
"(",
"function",
"(",
"res",
")",
"{",
"// If code >= 2, it's an error",
"if",
"(",
"res",
".",
"code",
">=",
"2",
")",
"{",
"alert",
"(",
"res",
".",
"message",
")",
";",
"}",
"else",
"{",
"alert",
"(",
"res",
".",
"message",
")",
";",
"}",
"}",
",",
"function",
"(",
"err",
")",
"{",
"alert",
"(",
"err",
")",
";",
"}",
")",
";",
"}"
] |
Build transaction from form data and send
|
[
"Build",
"transaction",
"from",
"form",
"data",
"and",
"send"
] |
4b0b60007c52ff4a89deeef84f9ca95b61c92fca
|
https://github.com/QuantumMechanics/NEM-sdk/blob/4b0b60007c52ff4a89deeef84f9ca95b61c92fca/examples/browser/transfer/script.js#L44-L80
|
12,882
|
QuantumMechanics/NEM-sdk
|
examples/browser/offlineTransaction/create/script.js
|
create
|
function create() {
// Check form for errors
if(!$("#privateKey").val() || !$("#recipient").val()) return alert('Missing parameter !');
if(undefined === $("#amount").val() || !nem.utils.helpers.isTextAmountValid($("#amount").val())) return alert('Invalid amount !');
if (!nem.model.address.isValid(nem.model.address.clean($("#recipient").val()))) return alert('Invalid recipent address !');
// Set the private key in common object
common.privateKey = $("#privateKey").val();
// Check private key for errors
if (common.privateKey.length !== 64 && common.privateKey.length !== 66) return alert('Invalid private key, length must be 64 or 66 characters !');
if (!nem.utils.helpers.isHexadecimal(common.privateKey)) return alert('Private key must be hexadecimal only !');
// Set the cleaned amount into transfer transaction object
transferTransaction.amount = nem.utils.helpers.cleanTextAmount($("#amount").val());
// Recipient address must be clean (no hypens: "-")
transferTransaction.recipient = nem.model.address.clean($("#recipient").val());
// Set message
transferTransaction.message = $("#message").val();
// Prepare the updated transfer transaction object
var transactionEntity = nem.model.transactions.prepare("transferTransaction")(common, transferTransaction, nem.model.network.data.testnet.id);
// Create a key pair object from private key
var kp = nem.crypto.keyPair.create(nem.utils.helpers.fixPrivateKey(common.privateKey));
// Serialize the transaction
var serialized = nem.utils.serialization.serializeTransaction(transactionEntity);
// Sign the serialized transaction with keypair object
var signature = kp.sign(serialized);
// Build the object to send
var result = {
'data': nem.utils.convert.ua2hex(serialized),
'signature': signature.toString()
};
// Show the object to send in view
$("#result").val(JSON.stringify(result));
}
|
javascript
|
function create() {
// Check form for errors
if(!$("#privateKey").val() || !$("#recipient").val()) return alert('Missing parameter !');
if(undefined === $("#amount").val() || !nem.utils.helpers.isTextAmountValid($("#amount").val())) return alert('Invalid amount !');
if (!nem.model.address.isValid(nem.model.address.clean($("#recipient").val()))) return alert('Invalid recipent address !');
// Set the private key in common object
common.privateKey = $("#privateKey").val();
// Check private key for errors
if (common.privateKey.length !== 64 && common.privateKey.length !== 66) return alert('Invalid private key, length must be 64 or 66 characters !');
if (!nem.utils.helpers.isHexadecimal(common.privateKey)) return alert('Private key must be hexadecimal only !');
// Set the cleaned amount into transfer transaction object
transferTransaction.amount = nem.utils.helpers.cleanTextAmount($("#amount").val());
// Recipient address must be clean (no hypens: "-")
transferTransaction.recipient = nem.model.address.clean($("#recipient").val());
// Set message
transferTransaction.message = $("#message").val();
// Prepare the updated transfer transaction object
var transactionEntity = nem.model.transactions.prepare("transferTransaction")(common, transferTransaction, nem.model.network.data.testnet.id);
// Create a key pair object from private key
var kp = nem.crypto.keyPair.create(nem.utils.helpers.fixPrivateKey(common.privateKey));
// Serialize the transaction
var serialized = nem.utils.serialization.serializeTransaction(transactionEntity);
// Sign the serialized transaction with keypair object
var signature = kp.sign(serialized);
// Build the object to send
var result = {
'data': nem.utils.convert.ua2hex(serialized),
'signature': signature.toString()
};
// Show the object to send in view
$("#result").val(JSON.stringify(result));
}
|
[
"function",
"create",
"(",
")",
"{",
"// Check form for errors",
"if",
"(",
"!",
"$",
"(",
"\"#privateKey\"",
")",
".",
"val",
"(",
")",
"||",
"!",
"$",
"(",
"\"#recipient\"",
")",
".",
"val",
"(",
")",
")",
"return",
"alert",
"(",
"'Missing parameter !'",
")",
";",
"if",
"(",
"undefined",
"===",
"$",
"(",
"\"#amount\"",
")",
".",
"val",
"(",
")",
"||",
"!",
"nem",
".",
"utils",
".",
"helpers",
".",
"isTextAmountValid",
"(",
"$",
"(",
"\"#amount\"",
")",
".",
"val",
"(",
")",
")",
")",
"return",
"alert",
"(",
"'Invalid amount !'",
")",
";",
"if",
"(",
"!",
"nem",
".",
"model",
".",
"address",
".",
"isValid",
"(",
"nem",
".",
"model",
".",
"address",
".",
"clean",
"(",
"$",
"(",
"\"#recipient\"",
")",
".",
"val",
"(",
")",
")",
")",
")",
"return",
"alert",
"(",
"'Invalid recipent address !'",
")",
";",
"// Set the private key in common object",
"common",
".",
"privateKey",
"=",
"$",
"(",
"\"#privateKey\"",
")",
".",
"val",
"(",
")",
";",
"// Check private key for errors",
"if",
"(",
"common",
".",
"privateKey",
".",
"length",
"!==",
"64",
"&&",
"common",
".",
"privateKey",
".",
"length",
"!==",
"66",
")",
"return",
"alert",
"(",
"'Invalid private key, length must be 64 or 66 characters !'",
")",
";",
"if",
"(",
"!",
"nem",
".",
"utils",
".",
"helpers",
".",
"isHexadecimal",
"(",
"common",
".",
"privateKey",
")",
")",
"return",
"alert",
"(",
"'Private key must be hexadecimal only !'",
")",
";",
"// Set the cleaned amount into transfer transaction object",
"transferTransaction",
".",
"amount",
"=",
"nem",
".",
"utils",
".",
"helpers",
".",
"cleanTextAmount",
"(",
"$",
"(",
"\"#amount\"",
")",
".",
"val",
"(",
")",
")",
";",
"// Recipient address must be clean (no hypens: \"-\")",
"transferTransaction",
".",
"recipient",
"=",
"nem",
".",
"model",
".",
"address",
".",
"clean",
"(",
"$",
"(",
"\"#recipient\"",
")",
".",
"val",
"(",
")",
")",
";",
"// Set message",
"transferTransaction",
".",
"message",
"=",
"$",
"(",
"\"#message\"",
")",
".",
"val",
"(",
")",
";",
"// Prepare the updated transfer transaction object",
"var",
"transactionEntity",
"=",
"nem",
".",
"model",
".",
"transactions",
".",
"prepare",
"(",
"\"transferTransaction\"",
")",
"(",
"common",
",",
"transferTransaction",
",",
"nem",
".",
"model",
".",
"network",
".",
"data",
".",
"testnet",
".",
"id",
")",
";",
"// Create a key pair object from private key",
"var",
"kp",
"=",
"nem",
".",
"crypto",
".",
"keyPair",
".",
"create",
"(",
"nem",
".",
"utils",
".",
"helpers",
".",
"fixPrivateKey",
"(",
"common",
".",
"privateKey",
")",
")",
";",
"// Serialize the transaction",
"var",
"serialized",
"=",
"nem",
".",
"utils",
".",
"serialization",
".",
"serializeTransaction",
"(",
"transactionEntity",
")",
";",
"// Sign the serialized transaction with keypair object",
"var",
"signature",
"=",
"kp",
".",
"sign",
"(",
"serialized",
")",
";",
"// Build the object to send",
"var",
"result",
"=",
"{",
"'data'",
":",
"nem",
".",
"utils",
".",
"convert",
".",
"ua2hex",
"(",
"serialized",
")",
",",
"'signature'",
":",
"signature",
".",
"toString",
"(",
")",
"}",
";",
"// Show the object to send in view",
"$",
"(",
"\"#result\"",
")",
".",
"val",
"(",
"JSON",
".",
"stringify",
"(",
"result",
")",
")",
";",
"}"
] |
Build transaction from form data
|
[
"Build",
"transaction",
"from",
"form",
"data"
] |
4b0b60007c52ff4a89deeef84f9ca95b61c92fca
|
https://github.com/QuantumMechanics/NEM-sdk/blob/4b0b60007c52ff4a89deeef84f9ca95b61c92fca/examples/browser/offlineTransaction/create/script.js#L41-L83
|
12,883
|
QuantumMechanics/NEM-sdk
|
examples/browser/monitor/script.js
|
showTransactions
|
function showTransactions(height) {
// Set the block height in modal title
$('#txsHeight').html(height);
// Get the transactions for that block
var txs = transactions[height];
// Reset the modal body
$('#txs').html('');
// Loop transactions
for(var i = 0; i < txs.length; i++) {
// Add stringified transaction object to the modal body
$('#txs').append('<pre>'+JSON.stringify(txs[i])+'</pre>');
}
// Open modal
$('#myModal').modal('show');
}
|
javascript
|
function showTransactions(height) {
// Set the block height in modal title
$('#txsHeight').html(height);
// Get the transactions for that block
var txs = transactions[height];
// Reset the modal body
$('#txs').html('');
// Loop transactions
for(var i = 0; i < txs.length; i++) {
// Add stringified transaction object to the modal body
$('#txs').append('<pre>'+JSON.stringify(txs[i])+'</pre>');
}
// Open modal
$('#myModal').modal('show');
}
|
[
"function",
"showTransactions",
"(",
"height",
")",
"{",
"// Set the block height in modal title",
"$",
"(",
"'#txsHeight'",
")",
".",
"html",
"(",
"height",
")",
";",
"// Get the transactions for that block",
"var",
"txs",
"=",
"transactions",
"[",
"height",
"]",
";",
"// Reset the modal body",
"$",
"(",
"'#txs'",
")",
".",
"html",
"(",
"''",
")",
";",
"// Loop transactions",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"txs",
".",
"length",
";",
"i",
"++",
")",
"{",
"// Add stringified transaction object to the modal body",
"$",
"(",
"'#txs'",
")",
".",
"append",
"(",
"'<pre>'",
"+",
"JSON",
".",
"stringify",
"(",
"txs",
"[",
"i",
"]",
")",
"+",
"'</pre>'",
")",
";",
"}",
"// Open modal",
"$",
"(",
"'#myModal'",
")",
".",
"modal",
"(",
"'show'",
")",
";",
"}"
] |
Function to open modal and set transaction data into it
|
[
"Function",
"to",
"open",
"modal",
"and",
"set",
"transaction",
"data",
"into",
"it"
] |
4b0b60007c52ff4a89deeef84f9ca95b61c92fca
|
https://github.com/QuantumMechanics/NEM-sdk/blob/4b0b60007c52ff4a89deeef84f9ca95b61c92fca/examples/browser/monitor/script.js#L59-L73
|
12,884
|
angular-ui/ui-sortable
|
src/sortable.js
|
isFloating
|
function isFloating(item) {
return (
/left|right/.test(item.css('float')) ||
/inline|table-cell/.test(item.css('display'))
);
}
|
javascript
|
function isFloating(item) {
return (
/left|right/.test(item.css('float')) ||
/inline|table-cell/.test(item.css('display'))
);
}
|
[
"function",
"isFloating",
"(",
"item",
")",
"{",
"return",
"(",
"/",
"left|right",
"/",
".",
"test",
"(",
"item",
".",
"css",
"(",
"'float'",
")",
")",
"||",
"/",
"inline|table-cell",
"/",
".",
"test",
"(",
"item",
".",
"css",
"(",
"'display'",
")",
")",
")",
";",
"}"
] |
thanks jquery-ui
|
[
"thanks",
"jquery",
"-",
"ui"
] |
e763b5765eea87743c8463ddf045a53015193c20
|
https://github.com/angular-ui/ui-sortable/blob/e763b5765eea87743c8463ddf045a53015193c20/src/sortable.js#L268-L273
|
12,885
|
angular-ui/ui-sortable
|
demo/demo.js
|
function(e, ui) {
var logEntry = {
ID: $scope.sortingLog.length + 1,
Text: 'Moved element: ' + ui.item.scope().item.text
};
$scope.sortingLog.push(logEntry);
}
|
javascript
|
function(e, ui) {
var logEntry = {
ID: $scope.sortingLog.length + 1,
Text: 'Moved element: ' + ui.item.scope().item.text
};
$scope.sortingLog.push(logEntry);
}
|
[
"function",
"(",
"e",
",",
"ui",
")",
"{",
"var",
"logEntry",
"=",
"{",
"ID",
":",
"$scope",
".",
"sortingLog",
".",
"length",
"+",
"1",
",",
"Text",
":",
"'Moved element: '",
"+",
"ui",
".",
"item",
".",
"scope",
"(",
")",
".",
"item",
".",
"text",
"}",
";",
"$scope",
".",
"sortingLog",
".",
"push",
"(",
"logEntry",
")",
";",
"}"
] |
called after a node is dropped
|
[
"called",
"after",
"a",
"node",
"is",
"dropped"
] |
e763b5765eea87743c8463ddf045a53015193c20
|
https://github.com/angular-ui/ui-sortable/blob/e763b5765eea87743c8463ddf045a53015193c20/demo/demo.js#L25-L31
|
|
12,886
|
angular-ui/ui-sortable
|
gruntFile.js
|
fakeTargetTask
|
function fakeTargetTask(prefix){
return function(){
if (this.args.length !== 1) {
return grunt.log.fail('Just give the name of the ' + prefix + ' you want like :\ngrunt ' + prefix + ':bower');
}
var done = this.async();
var spawn = require('child_process').spawn;
spawn('./node_modules/.bin/gulp', [ prefix, '--branch='+this.args[0] ].concat(grunt.option.flags()), {
cwd : './node_modules/angular-ui-publisher',
stdio: 'inherit'
}).on('close', done);
};
}
|
javascript
|
function fakeTargetTask(prefix){
return function(){
if (this.args.length !== 1) {
return grunt.log.fail('Just give the name of the ' + prefix + ' you want like :\ngrunt ' + prefix + ':bower');
}
var done = this.async();
var spawn = require('child_process').spawn;
spawn('./node_modules/.bin/gulp', [ prefix, '--branch='+this.args[0] ].concat(grunt.option.flags()), {
cwd : './node_modules/angular-ui-publisher',
stdio: 'inherit'
}).on('close', done);
};
}
|
[
"function",
"fakeTargetTask",
"(",
"prefix",
")",
"{",
"return",
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"args",
".",
"length",
"!==",
"1",
")",
"{",
"return",
"grunt",
".",
"log",
".",
"fail",
"(",
"'Just give the name of the '",
"+",
"prefix",
"+",
"' you want like :\\ngrunt '",
"+",
"prefix",
"+",
"':bower'",
")",
";",
"}",
"var",
"done",
"=",
"this",
".",
"async",
"(",
")",
";",
"var",
"spawn",
"=",
"require",
"(",
"'child_process'",
")",
".",
"spawn",
";",
"spawn",
"(",
"'./node_modules/.bin/gulp'",
",",
"[",
"prefix",
",",
"'--branch='",
"+",
"this",
".",
"args",
"[",
"0",
"]",
"]",
".",
"concat",
"(",
"grunt",
".",
"option",
".",
"flags",
"(",
")",
")",
",",
"{",
"cwd",
":",
"'./node_modules/angular-ui-publisher'",
",",
"stdio",
":",
"'inherit'",
"}",
")",
".",
"on",
"(",
"'close'",
",",
"done",
")",
";",
"}",
";",
"}"
] |
HACK TO ACCESS TO THE COMPONENT PUBLISHER
|
[
"HACK",
"TO",
"ACCESS",
"TO",
"THE",
"COMPONENT",
"PUBLISHER"
] |
e763b5765eea87743c8463ddf045a53015193c20
|
https://github.com/angular-ui/ui-sortable/blob/e763b5765eea87743c8463ddf045a53015193c20/gruntFile.js#L19-L33
|
12,887
|
angular-ui/ui-sortable
|
gruntFile.js
|
function(configFile, customOptions) {
var options = { configFile: configFile, singleRun: true };
var travisOptions = process.env.TRAVIS && {
browsers: ['Chrome', 'Firefox'],
reporters: ['dots', 'coverage', 'coveralls'],
preprocessors: { 'src/*.js': ['coverage'] },
coverageReporter: {
reporters: [{
type: 'text'
}, {
type: 'lcov',
dir: 'coverage/'
}]
},
};
return grunt.util._.extend(options, customOptions, travisOptions);
}
|
javascript
|
function(configFile, customOptions) {
var options = { configFile: configFile, singleRun: true };
var travisOptions = process.env.TRAVIS && {
browsers: ['Chrome', 'Firefox'],
reporters: ['dots', 'coverage', 'coveralls'],
preprocessors: { 'src/*.js': ['coverage'] },
coverageReporter: {
reporters: [{
type: 'text'
}, {
type: 'lcov',
dir: 'coverage/'
}]
},
};
return grunt.util._.extend(options, customOptions, travisOptions);
}
|
[
"function",
"(",
"configFile",
",",
"customOptions",
")",
"{",
"var",
"options",
"=",
"{",
"configFile",
":",
"configFile",
",",
"singleRun",
":",
"true",
"}",
";",
"var",
"travisOptions",
"=",
"process",
".",
"env",
".",
"TRAVIS",
"&&",
"{",
"browsers",
":",
"[",
"'Chrome'",
",",
"'Firefox'",
"]",
",",
"reporters",
":",
"[",
"'dots'",
",",
"'coverage'",
",",
"'coveralls'",
"]",
",",
"preprocessors",
":",
"{",
"'src/*.js'",
":",
"[",
"'coverage'",
"]",
"}",
",",
"coverageReporter",
":",
"{",
"reporters",
":",
"[",
"{",
"type",
":",
"'text'",
"}",
",",
"{",
"type",
":",
"'lcov'",
",",
"dir",
":",
"'coverage/'",
"}",
"]",
"}",
",",
"}",
";",
"return",
"grunt",
".",
"util",
".",
"_",
".",
"extend",
"(",
"options",
",",
"customOptions",
",",
"travisOptions",
")",
";",
"}"
] |
HACK TO MAKE TRAVIS WORK
|
[
"HACK",
"TO",
"MAKE",
"TRAVIS",
"WORK"
] |
e763b5765eea87743c8463ddf045a53015193c20
|
https://github.com/angular-ui/ui-sortable/blob/e763b5765eea87743c8463ddf045a53015193c20/gruntFile.js#L41-L57
|
|
12,888
|
jeremyfa/yaml.js
|
dist/yaml.legacy.js
|
function(message, parsedLine, snippet, parsedFile){
this.rawMessage = message;
this.parsedLine = (parsedLine !== undefined) ? parsedLine : -1;
this.snippet = (snippet !== undefined) ? snippet : null;
this.parsedFile = (parsedFile !== undefined) ? parsedFile : null;
this.updateRepr();
this.message = message;
}
|
javascript
|
function(message, parsedLine, snippet, parsedFile){
this.rawMessage = message;
this.parsedLine = (parsedLine !== undefined) ? parsedLine : -1;
this.snippet = (snippet !== undefined) ? snippet : null;
this.parsedFile = (parsedFile !== undefined) ? parsedFile : null;
this.updateRepr();
this.message = message;
}
|
[
"function",
"(",
"message",
",",
"parsedLine",
",",
"snippet",
",",
"parsedFile",
")",
"{",
"this",
".",
"rawMessage",
"=",
"message",
";",
"this",
".",
"parsedLine",
"=",
"(",
"parsedLine",
"!==",
"undefined",
")",
"?",
"parsedLine",
":",
"-",
"1",
";",
"this",
".",
"snippet",
"=",
"(",
"snippet",
"!==",
"undefined",
")",
"?",
"snippet",
":",
"null",
";",
"this",
".",
"parsedFile",
"=",
"(",
"parsedFile",
"!==",
"undefined",
")",
"?",
"parsedFile",
":",
"null",
";",
"this",
".",
"updateRepr",
"(",
")",
";",
"this",
".",
"message",
"=",
"message",
";",
"}"
] |
Exception class thrown when an error occurs during parsing.
@author Fabien Potencier <fabien@symfony.com>
@api
Constructor.
@param string message The error message
@param integer parsedLine The line where the error occurred
@param integer snippet The snippet of code near the problem
@param string parsedFile The file name where the error occurred
|
[
"Exception",
"class",
"thrown",
"when",
"an",
"error",
"occurs",
"during",
"parsing",
"."
] |
0b53177b26dfe0c2081465e3a496c9b4cb5b1c63
|
https://github.com/jeremyfa/yaml.js/blob/0b53177b26dfe0c2081465e3a496c9b4cb5b1c63/dist/yaml.legacy.js#L40-L51
|
|
12,889
|
jeremyfa/yaml.js
|
dist/yaml.legacy.js
|
function(file /* String */, callback /* Function */)
{
if ( callback == null )
{
var input = this.getFileContents(file);
var ret = null;
try
{
ret = this.parse(input);
}
catch ( e )
{
if ( e instanceof YamlParseException ) {
e.setParsedFile(file);
}
throw e;
}
return ret;
}
this.getFileContents(file, function(data)
{
callback(new Yaml().parse(data));
});
}
|
javascript
|
function(file /* String */, callback /* Function */)
{
if ( callback == null )
{
var input = this.getFileContents(file);
var ret = null;
try
{
ret = this.parse(input);
}
catch ( e )
{
if ( e instanceof YamlParseException ) {
e.setParsedFile(file);
}
throw e;
}
return ret;
}
this.getFileContents(file, function(data)
{
callback(new Yaml().parse(data));
});
}
|
[
"function",
"(",
"file",
"/* String */",
",",
"callback",
"/* Function */",
")",
"{",
"if",
"(",
"callback",
"==",
"null",
")",
"{",
"var",
"input",
"=",
"this",
".",
"getFileContents",
"(",
"file",
")",
";",
"var",
"ret",
"=",
"null",
";",
"try",
"{",
"ret",
"=",
"this",
".",
"parse",
"(",
"input",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"e",
"instanceof",
"YamlParseException",
")",
"{",
"e",
".",
"setParsedFile",
"(",
"file",
")",
";",
"}",
"throw",
"e",
";",
"}",
"return",
"ret",
";",
"}",
"this",
".",
"getFileContents",
"(",
"file",
",",
"function",
"(",
"data",
")",
"{",
"callback",
"(",
"new",
"Yaml",
"(",
")",
".",
"parse",
"(",
"data",
")",
")",
";",
"}",
")",
";",
"}"
] |
Parses YAML into a JS representation.
The parse method, when supplied with a YAML stream (file),
will do its best to convert YAML in a file into a JS representation.
Usage:
<code>
obj = yaml.parseFile('config.yml');
</code>
@param string input Path of YAML file
@return array The YAML converted to a JS representation
@throws YamlParseException If the YAML is not valid
|
[
"Parses",
"YAML",
"into",
"a",
"JS",
"representation",
"."
] |
0b53177b26dfe0c2081465e3a496c9b4cb5b1c63
|
https://github.com/jeremyfa/yaml.js/blob/0b53177b26dfe0c2081465e3a496c9b4cb5b1c63/dist/yaml.legacy.js#L193-L217
|
|
12,890
|
jeremyfa/yaml.js
|
dist/yaml.legacy.js
|
function(array, inline, spaces)
{
if ( inline == null ) inline = 2;
var yaml = new YamlDumper();
if (spaces) {
yaml.numSpacesForIndentation = spaces;
}
return yaml.dump(array, inline);
}
|
javascript
|
function(array, inline, spaces)
{
if ( inline == null ) inline = 2;
var yaml = new YamlDumper();
if (spaces) {
yaml.numSpacesForIndentation = spaces;
}
return yaml.dump(array, inline);
}
|
[
"function",
"(",
"array",
",",
"inline",
",",
"spaces",
")",
"{",
"if",
"(",
"inline",
"==",
"null",
")",
"inline",
"=",
"2",
";",
"var",
"yaml",
"=",
"new",
"YamlDumper",
"(",
")",
";",
"if",
"(",
"spaces",
")",
"{",
"yaml",
".",
"numSpacesForIndentation",
"=",
"spaces",
";",
"}",
"return",
"yaml",
".",
"dump",
"(",
"array",
",",
"inline",
")",
";",
"}"
] |
Dumps a JS representation to a YAML string.
The dump method, when supplied with an array, will do its best
to convert the array into friendly YAML.
@param array array JS representation
@param integer inline The level where you switch to inline YAML
@return string A YAML string representing the original JS representation
@api
|
[
"Dumps",
"a",
"JS",
"representation",
"to",
"a",
"YAML",
"string",
"."
] |
0b53177b26dfe0c2081465e3a496c9b4cb5b1c63
|
https://github.com/jeremyfa/yaml.js/blob/0b53177b26dfe0c2081465e3a496c9b4cb5b1c63/dist/yaml.legacy.js#L256-L266
|
|
12,891
|
jeremyfa/yaml.js
|
dist/yaml.legacy.js
|
function(value)
{
var result = null;
value = this.trim(value);
if ( 0 == value.length )
{
return '';
}
switch ( value.charAt(0) )
{
case '[':
result = this.parseSequence(value);
break;
case '{':
result = this.parseMapping(value);
break;
default:
result = this.parseScalar(value);
}
// some comment can end the scalar
if ( value.substr(this.i+1).replace(/^\s*#.*$/, '') != '' ) {
console.log("oups "+value.substr(this.i+1));
throw new YamlParseException('Unexpected characters near "'+value.substr(this.i)+'".');
}
return result;
}
|
javascript
|
function(value)
{
var result = null;
value = this.trim(value);
if ( 0 == value.length )
{
return '';
}
switch ( value.charAt(0) )
{
case '[':
result = this.parseSequence(value);
break;
case '{':
result = this.parseMapping(value);
break;
default:
result = this.parseScalar(value);
}
// some comment can end the scalar
if ( value.substr(this.i+1).replace(/^\s*#.*$/, '') != '' ) {
console.log("oups "+value.substr(this.i+1));
throw new YamlParseException('Unexpected characters near "'+value.substr(this.i)+'".');
}
return result;
}
|
[
"function",
"(",
"value",
")",
"{",
"var",
"result",
"=",
"null",
";",
"value",
"=",
"this",
".",
"trim",
"(",
"value",
")",
";",
"if",
"(",
"0",
"==",
"value",
".",
"length",
")",
"{",
"return",
"''",
";",
"}",
"switch",
"(",
"value",
".",
"charAt",
"(",
"0",
")",
")",
"{",
"case",
"'['",
":",
"result",
"=",
"this",
".",
"parseSequence",
"(",
"value",
")",
";",
"break",
";",
"case",
"'{'",
":",
"result",
"=",
"this",
".",
"parseMapping",
"(",
"value",
")",
";",
"break",
";",
"default",
":",
"result",
"=",
"this",
".",
"parseScalar",
"(",
"value",
")",
";",
"}",
"// some comment can end the scalar",
"if",
"(",
"value",
".",
"substr",
"(",
"this",
".",
"i",
"+",
"1",
")",
".",
"replace",
"(",
"/",
"^\\s*#.*$",
"/",
",",
"''",
")",
"!=",
"''",
")",
"{",
"console",
".",
"log",
"(",
"\"oups \"",
"+",
"value",
".",
"substr",
"(",
"this",
".",
"i",
"+",
"1",
")",
")",
";",
"throw",
"new",
"YamlParseException",
"(",
"'Unexpected characters near \"'",
"+",
"value",
".",
"substr",
"(",
"this",
".",
"i",
")",
"+",
"'\".'",
")",
";",
"}",
"return",
"result",
";",
"}"
] |
Convert a YAML string to a JS object.
@param string value A YAML string
@return object A JS object representing the YAML string
|
[
"Convert",
"a",
"YAML",
"string",
"to",
"a",
"JS",
"object",
"."
] |
0b53177b26dfe0c2081465e3a496c9b4cb5b1c63
|
https://github.com/jeremyfa/yaml.js/blob/0b53177b26dfe0c2081465e3a496c9b4cb5b1c63/dist/yaml.legacy.js#L410-L439
|
|
12,892
|
jeremyfa/yaml.js
|
dist/yaml.legacy.js
|
function(value)
{
if ( undefined == value || null == value )
return 'null';
if ( value instanceof Date)
return value.toISOString();
if ( typeof(value) == 'object')
return this.dumpObject(value);
if ( typeof(value) == 'boolean' )
return value ? 'true' : 'false';
if ( /^\d+$/.test(value) )
return typeof(value) == 'string' ? "'"+value+"'" : parseInt(value);
if ( this.isNumeric(value) )
return typeof(value) == 'string' ? "'"+value+"'" : parseFloat(value);
if ( typeof(value) == 'number' )
return value == Infinity ? '.Inf' : ( value == -Infinity ? '-.Inf' : ( isNaN(value) ? '.NAN' : value ) );
var yaml = new YamlEscaper();
if ( yaml.requiresDoubleQuoting(value) )
return yaml.escapeWithDoubleQuotes(value);
if ( yaml.requiresSingleQuoting(value) )
return yaml.escapeWithSingleQuotes(value);
if ( '' == value )
return '""';
if ( this.getTimestampRegex().test(value) )
return "'"+value+"'";
if ( this.inArray(value.toLowerCase(), ['null','~','true','false']) )
return "'"+value+"'";
// default
return value;
}
|
javascript
|
function(value)
{
if ( undefined == value || null == value )
return 'null';
if ( value instanceof Date)
return value.toISOString();
if ( typeof(value) == 'object')
return this.dumpObject(value);
if ( typeof(value) == 'boolean' )
return value ? 'true' : 'false';
if ( /^\d+$/.test(value) )
return typeof(value) == 'string' ? "'"+value+"'" : parseInt(value);
if ( this.isNumeric(value) )
return typeof(value) == 'string' ? "'"+value+"'" : parseFloat(value);
if ( typeof(value) == 'number' )
return value == Infinity ? '.Inf' : ( value == -Infinity ? '-.Inf' : ( isNaN(value) ? '.NAN' : value ) );
var yaml = new YamlEscaper();
if ( yaml.requiresDoubleQuoting(value) )
return yaml.escapeWithDoubleQuotes(value);
if ( yaml.requiresSingleQuoting(value) )
return yaml.escapeWithSingleQuotes(value);
if ( '' == value )
return '""';
if ( this.getTimestampRegex().test(value) )
return "'"+value+"'";
if ( this.inArray(value.toLowerCase(), ['null','~','true','false']) )
return "'"+value+"'";
// default
return value;
}
|
[
"function",
"(",
"value",
")",
"{",
"if",
"(",
"undefined",
"==",
"value",
"||",
"null",
"==",
"value",
")",
"return",
"'null'",
";",
"if",
"(",
"value",
"instanceof",
"Date",
")",
"return",
"value",
".",
"toISOString",
"(",
")",
";",
"if",
"(",
"typeof",
"(",
"value",
")",
"==",
"'object'",
")",
"return",
"this",
".",
"dumpObject",
"(",
"value",
")",
";",
"if",
"(",
"typeof",
"(",
"value",
")",
"==",
"'boolean'",
")",
"return",
"value",
"?",
"'true'",
":",
"'false'",
";",
"if",
"(",
"/",
"^\\d+$",
"/",
".",
"test",
"(",
"value",
")",
")",
"return",
"typeof",
"(",
"value",
")",
"==",
"'string'",
"?",
"\"'\"",
"+",
"value",
"+",
"\"'\"",
":",
"parseInt",
"(",
"value",
")",
";",
"if",
"(",
"this",
".",
"isNumeric",
"(",
"value",
")",
")",
"return",
"typeof",
"(",
"value",
")",
"==",
"'string'",
"?",
"\"'\"",
"+",
"value",
"+",
"\"'\"",
":",
"parseFloat",
"(",
"value",
")",
";",
"if",
"(",
"typeof",
"(",
"value",
")",
"==",
"'number'",
")",
"return",
"value",
"==",
"Infinity",
"?",
"'.Inf'",
":",
"(",
"value",
"==",
"-",
"Infinity",
"?",
"'-.Inf'",
":",
"(",
"isNaN",
"(",
"value",
")",
"?",
"'.NAN'",
":",
"value",
")",
")",
";",
"var",
"yaml",
"=",
"new",
"YamlEscaper",
"(",
")",
";",
"if",
"(",
"yaml",
".",
"requiresDoubleQuoting",
"(",
"value",
")",
")",
"return",
"yaml",
".",
"escapeWithDoubleQuotes",
"(",
"value",
")",
";",
"if",
"(",
"yaml",
".",
"requiresSingleQuoting",
"(",
"value",
")",
")",
"return",
"yaml",
".",
"escapeWithSingleQuotes",
"(",
"value",
")",
";",
"if",
"(",
"''",
"==",
"value",
")",
"return",
"'\"\"'",
";",
"if",
"(",
"this",
".",
"getTimestampRegex",
"(",
")",
".",
"test",
"(",
"value",
")",
")",
"return",
"\"'\"",
"+",
"value",
"+",
"\"'\"",
";",
"if",
"(",
"this",
".",
"inArray",
"(",
"value",
".",
"toLowerCase",
"(",
")",
",",
"[",
"'null'",
",",
"'~'",
",",
"'true'",
",",
"'false'",
"]",
")",
")",
"return",
"\"'\"",
"+",
"value",
"+",
"\"'\"",
";",
"// default",
"return",
"value",
";",
"}"
] |
Dumps a given JS variable to a YAML string.
@param mixed value The JS variable to convert
@return string The YAML string representing the JS object
|
[
"Dumps",
"a",
"given",
"JS",
"variable",
"to",
"a",
"YAML",
"string",
"."
] |
0b53177b26dfe0c2081465e3a496c9b4cb5b1c63
|
https://github.com/jeremyfa/yaml.js/blob/0b53177b26dfe0c2081465e3a496c9b4cb5b1c63/dist/yaml.legacy.js#L448-L477
|
|
12,893
|
jeremyfa/yaml.js
|
dist/yaml.legacy.js
|
function(value)
{
var keys = this.getKeys(value);
var output = null;
var i;
var len = keys.length;
// array
if ( value instanceof Array )
/*( 1 == len && '0' == keys[0] )
||
( len > 1 && this.reduceArray(keys, function(v,w){return Math.floor(v+w);}, 0) == len * (len - 1) / 2) )*/
{
output = [];
for ( i = 0; i < len; i++ )
{
output.push(this.dump(value[keys[i]]));
}
return '['+output.join(', ')+']';
}
// mapping
output = [];
for ( i = 0; i < len; i++ )
{
output.push(this.dump(keys[i])+': '+this.dump(value[keys[i]]));
}
return '{ '+output.join(', ')+' }';
}
|
javascript
|
function(value)
{
var keys = this.getKeys(value);
var output = null;
var i;
var len = keys.length;
// array
if ( value instanceof Array )
/*( 1 == len && '0' == keys[0] )
||
( len > 1 && this.reduceArray(keys, function(v,w){return Math.floor(v+w);}, 0) == len * (len - 1) / 2) )*/
{
output = [];
for ( i = 0; i < len; i++ )
{
output.push(this.dump(value[keys[i]]));
}
return '['+output.join(', ')+']';
}
// mapping
output = [];
for ( i = 0; i < len; i++ )
{
output.push(this.dump(keys[i])+': '+this.dump(value[keys[i]]));
}
return '{ '+output.join(', ')+' }';
}
|
[
"function",
"(",
"value",
")",
"{",
"var",
"keys",
"=",
"this",
".",
"getKeys",
"(",
"value",
")",
";",
"var",
"output",
"=",
"null",
";",
"var",
"i",
";",
"var",
"len",
"=",
"keys",
".",
"length",
";",
"// array",
"if",
"(",
"value",
"instanceof",
"Array",
")",
"/*( 1 == len && '0' == keys[0] )\n\t\t\t||\n\t\t\t( len > 1 && this.reduceArray(keys, function(v,w){return Math.floor(v+w);}, 0) == len * (len - 1) / 2) )*/",
"{",
"output",
"=",
"[",
"]",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"output",
".",
"push",
"(",
"this",
".",
"dump",
"(",
"value",
"[",
"keys",
"[",
"i",
"]",
"]",
")",
")",
";",
"}",
"return",
"'['",
"+",
"output",
".",
"join",
"(",
"', '",
")",
"+",
"']'",
";",
"}",
"// mapping",
"output",
"=",
"[",
"]",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"output",
".",
"push",
"(",
"this",
".",
"dump",
"(",
"keys",
"[",
"i",
"]",
")",
"+",
"': '",
"+",
"this",
".",
"dump",
"(",
"value",
"[",
"keys",
"[",
"i",
"]",
"]",
")",
")",
";",
"}",
"return",
"'{ '",
"+",
"output",
".",
"join",
"(",
"', '",
")",
"+",
"' }'",
";",
"}"
] |
Dumps a JS object to a YAML string.
@param object value The JS array to dump
@return string The YAML string representing the JS object
|
[
"Dumps",
"a",
"JS",
"object",
"to",
"a",
"YAML",
"string",
"."
] |
0b53177b26dfe0c2081465e3a496c9b4cb5b1c63
|
https://github.com/jeremyfa/yaml.js/blob/0b53177b26dfe0c2081465e3a496c9b4cb5b1c63/dist/yaml.legacy.js#L486-L516
|
|
12,894
|
jeremyfa/yaml.js
|
dist/yaml.legacy.js
|
function(scalar, delimiters, stringDelimiters, i, evaluate)
{
if ( delimiters == undefined ) delimiters = null;
if ( stringDelimiters == undefined ) stringDelimiters = ['"', "'"];
if ( i == undefined ) i = 0;
if ( evaluate == undefined ) evaluate = true;
var output = null;
var pos = null;
var matches = null;
if ( this.inArray(scalar[i], stringDelimiters) )
{
// quoted scalar
output = this.parseQuotedScalar(scalar, i);
i = this.i;
if (null !== delimiters) {
var tmp = scalar.substr(i).replace(/^\s+/, '');
if (!this.inArray(tmp.charAt(0), delimiters)) {
throw new YamlParseException('Unexpected characters ('+scalar.substr(i)+').');
}
}
}
else
{
// "normal" string
if ( !delimiters )
{
output = (scalar+'').substring(i);
i += output.length;
// remove comments
pos = output.indexOf(' #');
if ( pos != -1 )
{
output = output.substr(0, pos).replace(/\s+$/g,'');
}
}
else if ( matches = new RegExp('^(.+?)('+delimiters.join('|')+')').exec((scalar+'').substring(i)) )
{
output = matches[1];
i += output.length;
}
else
{
throw new YamlParseException('Malformed inline YAML string ('+scalar+').');
}
output = evaluate ? this.evaluateScalar(output) : output;
}
this.i = i;
return output;
}
|
javascript
|
function(scalar, delimiters, stringDelimiters, i, evaluate)
{
if ( delimiters == undefined ) delimiters = null;
if ( stringDelimiters == undefined ) stringDelimiters = ['"', "'"];
if ( i == undefined ) i = 0;
if ( evaluate == undefined ) evaluate = true;
var output = null;
var pos = null;
var matches = null;
if ( this.inArray(scalar[i], stringDelimiters) )
{
// quoted scalar
output = this.parseQuotedScalar(scalar, i);
i = this.i;
if (null !== delimiters) {
var tmp = scalar.substr(i).replace(/^\s+/, '');
if (!this.inArray(tmp.charAt(0), delimiters)) {
throw new YamlParseException('Unexpected characters ('+scalar.substr(i)+').');
}
}
}
else
{
// "normal" string
if ( !delimiters )
{
output = (scalar+'').substring(i);
i += output.length;
// remove comments
pos = output.indexOf(' #');
if ( pos != -1 )
{
output = output.substr(0, pos).replace(/\s+$/g,'');
}
}
else if ( matches = new RegExp('^(.+?)('+delimiters.join('|')+')').exec((scalar+'').substring(i)) )
{
output = matches[1];
i += output.length;
}
else
{
throw new YamlParseException('Malformed inline YAML string ('+scalar+').');
}
output = evaluate ? this.evaluateScalar(output) : output;
}
this.i = i;
return output;
}
|
[
"function",
"(",
"scalar",
",",
"delimiters",
",",
"stringDelimiters",
",",
"i",
",",
"evaluate",
")",
"{",
"if",
"(",
"delimiters",
"==",
"undefined",
")",
"delimiters",
"=",
"null",
";",
"if",
"(",
"stringDelimiters",
"==",
"undefined",
")",
"stringDelimiters",
"=",
"[",
"'\"'",
",",
"\"'\"",
"]",
";",
"if",
"(",
"i",
"==",
"undefined",
")",
"i",
"=",
"0",
";",
"if",
"(",
"evaluate",
"==",
"undefined",
")",
"evaluate",
"=",
"true",
";",
"var",
"output",
"=",
"null",
";",
"var",
"pos",
"=",
"null",
";",
"var",
"matches",
"=",
"null",
";",
"if",
"(",
"this",
".",
"inArray",
"(",
"scalar",
"[",
"i",
"]",
",",
"stringDelimiters",
")",
")",
"{",
"// quoted scalar",
"output",
"=",
"this",
".",
"parseQuotedScalar",
"(",
"scalar",
",",
"i",
")",
";",
"i",
"=",
"this",
".",
"i",
";",
"if",
"(",
"null",
"!==",
"delimiters",
")",
"{",
"var",
"tmp",
"=",
"scalar",
".",
"substr",
"(",
"i",
")",
".",
"replace",
"(",
"/",
"^\\s+",
"/",
",",
"''",
")",
";",
"if",
"(",
"!",
"this",
".",
"inArray",
"(",
"tmp",
".",
"charAt",
"(",
"0",
")",
",",
"delimiters",
")",
")",
"{",
"throw",
"new",
"YamlParseException",
"(",
"'Unexpected characters ('",
"+",
"scalar",
".",
"substr",
"(",
"i",
")",
"+",
"').'",
")",
";",
"}",
"}",
"}",
"else",
"{",
"// \"normal\" string",
"if",
"(",
"!",
"delimiters",
")",
"{",
"output",
"=",
"(",
"scalar",
"+",
"''",
")",
".",
"substring",
"(",
"i",
")",
";",
"i",
"+=",
"output",
".",
"length",
";",
"// remove comments",
"pos",
"=",
"output",
".",
"indexOf",
"(",
"' #'",
")",
";",
"if",
"(",
"pos",
"!=",
"-",
"1",
")",
"{",
"output",
"=",
"output",
".",
"substr",
"(",
"0",
",",
"pos",
")",
".",
"replace",
"(",
"/",
"\\s+$",
"/",
"g",
",",
"''",
")",
";",
"}",
"}",
"else",
"if",
"(",
"matches",
"=",
"new",
"RegExp",
"(",
"'^(.+?)('",
"+",
"delimiters",
".",
"join",
"(",
"'|'",
")",
"+",
"')'",
")",
".",
"exec",
"(",
"(",
"scalar",
"+",
"''",
")",
".",
"substring",
"(",
"i",
")",
")",
")",
"{",
"output",
"=",
"matches",
"[",
"1",
"]",
";",
"i",
"+=",
"output",
".",
"length",
";",
"}",
"else",
"{",
"throw",
"new",
"YamlParseException",
"(",
"'Malformed inline YAML string ('",
"+",
"scalar",
"+",
"').'",
")",
";",
"}",
"output",
"=",
"evaluate",
"?",
"this",
".",
"evaluateScalar",
"(",
"output",
")",
":",
"output",
";",
"}",
"this",
".",
"i",
"=",
"i",
";",
"return",
"output",
";",
"}"
] |
Parses a scalar to a YAML string.
@param scalar scalar
@param string delimiters
@param object stringDelimiters
@param integer i
@param boolean evaluate
@return string A YAML string
@throws YamlParseException When malformed inline YAML string is parsed
|
[
"Parses",
"a",
"scalar",
"to",
"a",
"YAML",
"string",
"."
] |
0b53177b26dfe0c2081465e3a496c9b4cb5b1c63
|
https://github.com/jeremyfa/yaml.js/blob/0b53177b26dfe0c2081465e3a496c9b4cb5b1c63/dist/yaml.legacy.js#L531-L585
|
|
12,895
|
jeremyfa/yaml.js
|
dist/yaml.legacy.js
|
function(scalar, i)
{
var matches = null;
//var item = /^(.*?)['"]\s*(?:[,:]|[}\]]\s*,)/.exec((scalar+'').substring(i))[1];
if ( !(matches = new RegExp('^'+YamlInline.REGEX_QUOTED_STRING).exec((scalar+'').substring(i))) )
{
throw new YamlParseException('Malformed inline YAML string ('+(scalar+'').substring(i)+').');
}
var output = matches[0].substr(1, matches[0].length - 2);
var unescaper = new YamlUnescaper();
if ( '"' == (scalar+'').charAt(i) )
{
output = unescaper.unescapeDoubleQuotedString(output);
}
else
{
output = unescaper.unescapeSingleQuotedString(output);
}
i += matches[0].length;
this.i = i;
return output;
}
|
javascript
|
function(scalar, i)
{
var matches = null;
//var item = /^(.*?)['"]\s*(?:[,:]|[}\]]\s*,)/.exec((scalar+'').substring(i))[1];
if ( !(matches = new RegExp('^'+YamlInline.REGEX_QUOTED_STRING).exec((scalar+'').substring(i))) )
{
throw new YamlParseException('Malformed inline YAML string ('+(scalar+'').substring(i)+').');
}
var output = matches[0].substr(1, matches[0].length - 2);
var unescaper = new YamlUnescaper();
if ( '"' == (scalar+'').charAt(i) )
{
output = unescaper.unescapeDoubleQuotedString(output);
}
else
{
output = unescaper.unescapeSingleQuotedString(output);
}
i += matches[0].length;
this.i = i;
return output;
}
|
[
"function",
"(",
"scalar",
",",
"i",
")",
"{",
"var",
"matches",
"=",
"null",
";",
"//var item = /^(.*?)['\"]\\s*(?:[,:]|[}\\]]\\s*,)/.exec((scalar+'').substring(i))[1];",
"if",
"(",
"!",
"(",
"matches",
"=",
"new",
"RegExp",
"(",
"'^'",
"+",
"YamlInline",
".",
"REGEX_QUOTED_STRING",
")",
".",
"exec",
"(",
"(",
"scalar",
"+",
"''",
")",
".",
"substring",
"(",
"i",
")",
")",
")",
")",
"{",
"throw",
"new",
"YamlParseException",
"(",
"'Malformed inline YAML string ('",
"+",
"(",
"scalar",
"+",
"''",
")",
".",
"substring",
"(",
"i",
")",
"+",
"').'",
")",
";",
"}",
"var",
"output",
"=",
"matches",
"[",
"0",
"]",
".",
"substr",
"(",
"1",
",",
"matches",
"[",
"0",
"]",
".",
"length",
"-",
"2",
")",
";",
"var",
"unescaper",
"=",
"new",
"YamlUnescaper",
"(",
")",
";",
"if",
"(",
"'\"'",
"==",
"(",
"scalar",
"+",
"''",
")",
".",
"charAt",
"(",
"i",
")",
")",
"{",
"output",
"=",
"unescaper",
".",
"unescapeDoubleQuotedString",
"(",
"output",
")",
";",
"}",
"else",
"{",
"output",
"=",
"unescaper",
".",
"unescapeSingleQuotedString",
"(",
"output",
")",
";",
"}",
"i",
"+=",
"matches",
"[",
"0",
"]",
".",
"length",
";",
"this",
".",
"i",
"=",
"i",
";",
"return",
"output",
";",
"}"
] |
Parses a quoted scalar to YAML.
@param string scalar
@param integer i
@return string A YAML string
@throws YamlParseException When malformed inline YAML string is parsed
|
[
"Parses",
"a",
"quoted",
"scalar",
"to",
"YAML",
"."
] |
0b53177b26dfe0c2081465e3a496c9b4cb5b1c63
|
https://github.com/jeremyfa/yaml.js/blob/0b53177b26dfe0c2081465e3a496c9b4cb5b1c63/dist/yaml.legacy.js#L597-L624
|
|
12,896
|
jeremyfa/yaml.js
|
dist/yaml.legacy.js
|
function(sequence, i)
{
if ( i == undefined ) i = 0;
var output = [];
var len = sequence.length;
i += 1;
// [foo, bar, ...]
while ( i < len )
{
switch ( sequence.charAt(i) )
{
case '[':
// nested sequence
output.push(this.parseSequence(sequence, i));
i = this.i;
break;
case '{':
// nested mapping
output.push(this.parseMapping(sequence, i));
i = this.i;
break;
case ']':
this.i = i;
return output;
case ',':
case ' ':
break;
default:
var isQuoted = this.inArray(sequence.charAt(i), ['"', "'"]);
var value = this.parseScalar(sequence, [',', ']'], ['"', "'"], i);
i = this.i;
if ( !isQuoted && (value+'').indexOf(': ') != -1 )
{
// embedded mapping?
try
{
value = this.parseMapping('{'+value+'}');
}
catch ( e )
{
if ( !(e instanceof YamlParseException ) ) throw e;
// no, it's not
}
}
output.push(value);
i--;
}
i++;
}
throw new YamlParseException('Malformed inline YAML string "'+sequence+'"');
}
|
javascript
|
function(sequence, i)
{
if ( i == undefined ) i = 0;
var output = [];
var len = sequence.length;
i += 1;
// [foo, bar, ...]
while ( i < len )
{
switch ( sequence.charAt(i) )
{
case '[':
// nested sequence
output.push(this.parseSequence(sequence, i));
i = this.i;
break;
case '{':
// nested mapping
output.push(this.parseMapping(sequence, i));
i = this.i;
break;
case ']':
this.i = i;
return output;
case ',':
case ' ':
break;
default:
var isQuoted = this.inArray(sequence.charAt(i), ['"', "'"]);
var value = this.parseScalar(sequence, [',', ']'], ['"', "'"], i);
i = this.i;
if ( !isQuoted && (value+'').indexOf(': ') != -1 )
{
// embedded mapping?
try
{
value = this.parseMapping('{'+value+'}');
}
catch ( e )
{
if ( !(e instanceof YamlParseException ) ) throw e;
// no, it's not
}
}
output.push(value);
i--;
}
i++;
}
throw new YamlParseException('Malformed inline YAML string "'+sequence+'"');
}
|
[
"function",
"(",
"sequence",
",",
"i",
")",
"{",
"if",
"(",
"i",
"==",
"undefined",
")",
"i",
"=",
"0",
";",
"var",
"output",
"=",
"[",
"]",
";",
"var",
"len",
"=",
"sequence",
".",
"length",
";",
"i",
"+=",
"1",
";",
"// [foo, bar, ...]",
"while",
"(",
"i",
"<",
"len",
")",
"{",
"switch",
"(",
"sequence",
".",
"charAt",
"(",
"i",
")",
")",
"{",
"case",
"'['",
":",
"// nested sequence",
"output",
".",
"push",
"(",
"this",
".",
"parseSequence",
"(",
"sequence",
",",
"i",
")",
")",
";",
"i",
"=",
"this",
".",
"i",
";",
"break",
";",
"case",
"'{'",
":",
"// nested mapping",
"output",
".",
"push",
"(",
"this",
".",
"parseMapping",
"(",
"sequence",
",",
"i",
")",
")",
";",
"i",
"=",
"this",
".",
"i",
";",
"break",
";",
"case",
"']'",
":",
"this",
".",
"i",
"=",
"i",
";",
"return",
"output",
";",
"case",
"','",
":",
"case",
"' '",
":",
"break",
";",
"default",
":",
"var",
"isQuoted",
"=",
"this",
".",
"inArray",
"(",
"sequence",
".",
"charAt",
"(",
"i",
")",
",",
"[",
"'\"'",
",",
"\"'\"",
"]",
")",
";",
"var",
"value",
"=",
"this",
".",
"parseScalar",
"(",
"sequence",
",",
"[",
"','",
",",
"']'",
"]",
",",
"[",
"'\"'",
",",
"\"'\"",
"]",
",",
"i",
")",
";",
"i",
"=",
"this",
".",
"i",
";",
"if",
"(",
"!",
"isQuoted",
"&&",
"(",
"value",
"+",
"''",
")",
".",
"indexOf",
"(",
"': '",
")",
"!=",
"-",
"1",
")",
"{",
"// embedded mapping?",
"try",
"{",
"value",
"=",
"this",
".",
"parseMapping",
"(",
"'{'",
"+",
"value",
"+",
"'}'",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"!",
"(",
"e",
"instanceof",
"YamlParseException",
")",
")",
"throw",
"e",
";",
"// no, it's not",
"}",
"}",
"output",
".",
"push",
"(",
"value",
")",
";",
"i",
"--",
";",
"}",
"i",
"++",
";",
"}",
"throw",
"new",
"YamlParseException",
"(",
"'Malformed inline YAML string \"'",
"+",
"sequence",
"+",
"'\"'",
")",
";",
"}"
] |
Parses a sequence to a YAML string.
@param string sequence
@param integer i
@return string A YAML string
@throws YamlParseException When malformed inline YAML string is parsed
|
[
"Parses",
"a",
"sequence",
"to",
"a",
"YAML",
"string",
"."
] |
0b53177b26dfe0c2081465e3a496c9b4cb5b1c63
|
https://github.com/jeremyfa/yaml.js/blob/0b53177b26dfe0c2081465e3a496c9b4cb5b1c63/dist/yaml.legacy.js#L636-L693
|
|
12,897
|
jeremyfa/yaml.js
|
dist/yaml.legacy.js
|
function(mapping, i)
{
if ( i == undefined ) i = 0;
var output = {};
var len = mapping.length;
i += 1;
var done = false;
var doContinue = false;
// {foo: bar, bar:foo, ...}
while ( i < len )
{
doContinue = false;
switch ( mapping.charAt(i) )
{
case ' ':
case ',':
i++;
doContinue = true;
break;
case '}':
this.i = i;
return output;
}
if ( doContinue ) continue;
// key
var key = this.parseScalar(mapping, [':', ' '], ['"', "'"], i, false);
i = this.i;
// value
done = false;
while ( i < len )
{
switch ( mapping.charAt(i) )
{
case '[':
// nested sequence
output[key] = this.parseSequence(mapping, i);
i = this.i;
done = true;
break;
case '{':
// nested mapping
output[key] = this.parseMapping(mapping, i);
i = this.i;
done = true;
break;
case ':':
case ' ':
break;
default:
output[key] = this.parseScalar(mapping, [',', '}'], ['"', "'"], i);
i = this.i;
done = true;
i--;
}
++i;
if ( done )
{
doContinue = true;
break;
}
}
if ( doContinue ) continue;
}
throw new YamlParseException('Malformed inline YAML string "'+mapping+'"');
}
|
javascript
|
function(mapping, i)
{
if ( i == undefined ) i = 0;
var output = {};
var len = mapping.length;
i += 1;
var done = false;
var doContinue = false;
// {foo: bar, bar:foo, ...}
while ( i < len )
{
doContinue = false;
switch ( mapping.charAt(i) )
{
case ' ':
case ',':
i++;
doContinue = true;
break;
case '}':
this.i = i;
return output;
}
if ( doContinue ) continue;
// key
var key = this.parseScalar(mapping, [':', ' '], ['"', "'"], i, false);
i = this.i;
// value
done = false;
while ( i < len )
{
switch ( mapping.charAt(i) )
{
case '[':
// nested sequence
output[key] = this.parseSequence(mapping, i);
i = this.i;
done = true;
break;
case '{':
// nested mapping
output[key] = this.parseMapping(mapping, i);
i = this.i;
done = true;
break;
case ':':
case ' ':
break;
default:
output[key] = this.parseScalar(mapping, [',', '}'], ['"', "'"], i);
i = this.i;
done = true;
i--;
}
++i;
if ( done )
{
doContinue = true;
break;
}
}
if ( doContinue ) continue;
}
throw new YamlParseException('Malformed inline YAML string "'+mapping+'"');
}
|
[
"function",
"(",
"mapping",
",",
"i",
")",
"{",
"if",
"(",
"i",
"==",
"undefined",
")",
"i",
"=",
"0",
";",
"var",
"output",
"=",
"{",
"}",
";",
"var",
"len",
"=",
"mapping",
".",
"length",
";",
"i",
"+=",
"1",
";",
"var",
"done",
"=",
"false",
";",
"var",
"doContinue",
"=",
"false",
";",
"// {foo: bar, bar:foo, ...}",
"while",
"(",
"i",
"<",
"len",
")",
"{",
"doContinue",
"=",
"false",
";",
"switch",
"(",
"mapping",
".",
"charAt",
"(",
"i",
")",
")",
"{",
"case",
"' '",
":",
"case",
"','",
":",
"i",
"++",
";",
"doContinue",
"=",
"true",
";",
"break",
";",
"case",
"'}'",
":",
"this",
".",
"i",
"=",
"i",
";",
"return",
"output",
";",
"}",
"if",
"(",
"doContinue",
")",
"continue",
";",
"// key",
"var",
"key",
"=",
"this",
".",
"parseScalar",
"(",
"mapping",
",",
"[",
"':'",
",",
"' '",
"]",
",",
"[",
"'\"'",
",",
"\"'\"",
"]",
",",
"i",
",",
"false",
")",
";",
"i",
"=",
"this",
".",
"i",
";",
"// value",
"done",
"=",
"false",
";",
"while",
"(",
"i",
"<",
"len",
")",
"{",
"switch",
"(",
"mapping",
".",
"charAt",
"(",
"i",
")",
")",
"{",
"case",
"'['",
":",
"// nested sequence",
"output",
"[",
"key",
"]",
"=",
"this",
".",
"parseSequence",
"(",
"mapping",
",",
"i",
")",
";",
"i",
"=",
"this",
".",
"i",
";",
"done",
"=",
"true",
";",
"break",
";",
"case",
"'{'",
":",
"// nested mapping",
"output",
"[",
"key",
"]",
"=",
"this",
".",
"parseMapping",
"(",
"mapping",
",",
"i",
")",
";",
"i",
"=",
"this",
".",
"i",
";",
"done",
"=",
"true",
";",
"break",
";",
"case",
"':'",
":",
"case",
"' '",
":",
"break",
";",
"default",
":",
"output",
"[",
"key",
"]",
"=",
"this",
".",
"parseScalar",
"(",
"mapping",
",",
"[",
"','",
",",
"'}'",
"]",
",",
"[",
"'\"'",
",",
"\"'\"",
"]",
",",
"i",
")",
";",
"i",
"=",
"this",
".",
"i",
";",
"done",
"=",
"true",
";",
"i",
"--",
";",
"}",
"++",
"i",
";",
"if",
"(",
"done",
")",
"{",
"doContinue",
"=",
"true",
";",
"break",
";",
"}",
"}",
"if",
"(",
"doContinue",
")",
"continue",
";",
"}",
"throw",
"new",
"YamlParseException",
"(",
"'Malformed inline YAML string \"'",
"+",
"mapping",
"+",
"'\"'",
")",
";",
"}"
] |
Parses a mapping to a YAML string.
@param string mapping
@param integer i
@return string A YAML string
@throws YamlParseException When malformed inline YAML string is parsed
|
[
"Parses",
"a",
"mapping",
"to",
"a",
"YAML",
"string",
"."
] |
0b53177b26dfe0c2081465e3a496c9b4cb5b1c63
|
https://github.com/jeremyfa/yaml.js/blob/0b53177b26dfe0c2081465e3a496c9b4cb5b1c63/dist/yaml.legacy.js#L705-L778
|
|
12,898
|
jeremyfa/yaml.js
|
dist/yaml.legacy.js
|
function(scalar)
{
scalar = this.trim(scalar);
var raw = null;
var cast = null;
if ( ( 'null' == scalar.toLowerCase() ) ||
( '' == scalar ) ||
( '~' == scalar ) )
return null;
if ( (scalar+'').indexOf('!str ') == 0 )
return (''+scalar).substring(5);
if ( (scalar+'').indexOf('! ') == 0 )
return parseInt(this.parseScalar((scalar+'').substr(2)));
if ( /^\d+$/.test(scalar) )
{
raw = scalar;
cast = parseInt(scalar);
return '0' == scalar.charAt(0) ? this.octdec(scalar) : (( ''+raw == ''+cast ) ? cast : raw);
}
if ( 'true' == (scalar+'').toLowerCase() )
return true;
if ( 'false' == (scalar+'').toLowerCase() )
return false;
if ( this.isNumeric(scalar) )
return '0x' == (scalar+'').substr(0, 2) ? this.hexdec(scalar) : parseFloat(scalar);
if ( scalar.toLowerCase() == '.inf' )
return Infinity;
if ( scalar.toLowerCase() == '.nan' )
return NaN;
if ( scalar.toLowerCase() == '-.inf' )
return -Infinity;
if ( /^(-|\+)?[0-9,]+(\.[0-9]+)?$/.test(scalar) )
return parseFloat(scalar.split(',').join(''));
if ( this.getTimestampRegex().test(scalar) )
return new Date(this.strtotime(scalar));
//else
return ''+scalar;
}
|
javascript
|
function(scalar)
{
scalar = this.trim(scalar);
var raw = null;
var cast = null;
if ( ( 'null' == scalar.toLowerCase() ) ||
( '' == scalar ) ||
( '~' == scalar ) )
return null;
if ( (scalar+'').indexOf('!str ') == 0 )
return (''+scalar).substring(5);
if ( (scalar+'').indexOf('! ') == 0 )
return parseInt(this.parseScalar((scalar+'').substr(2)));
if ( /^\d+$/.test(scalar) )
{
raw = scalar;
cast = parseInt(scalar);
return '0' == scalar.charAt(0) ? this.octdec(scalar) : (( ''+raw == ''+cast ) ? cast : raw);
}
if ( 'true' == (scalar+'').toLowerCase() )
return true;
if ( 'false' == (scalar+'').toLowerCase() )
return false;
if ( this.isNumeric(scalar) )
return '0x' == (scalar+'').substr(0, 2) ? this.hexdec(scalar) : parseFloat(scalar);
if ( scalar.toLowerCase() == '.inf' )
return Infinity;
if ( scalar.toLowerCase() == '.nan' )
return NaN;
if ( scalar.toLowerCase() == '-.inf' )
return -Infinity;
if ( /^(-|\+)?[0-9,]+(\.[0-9]+)?$/.test(scalar) )
return parseFloat(scalar.split(',').join(''));
if ( this.getTimestampRegex().test(scalar) )
return new Date(this.strtotime(scalar));
//else
return ''+scalar;
}
|
[
"function",
"(",
"scalar",
")",
"{",
"scalar",
"=",
"this",
".",
"trim",
"(",
"scalar",
")",
";",
"var",
"raw",
"=",
"null",
";",
"var",
"cast",
"=",
"null",
";",
"if",
"(",
"(",
"'null'",
"==",
"scalar",
".",
"toLowerCase",
"(",
")",
")",
"||",
"(",
"''",
"==",
"scalar",
")",
"||",
"(",
"'~'",
"==",
"scalar",
")",
")",
"return",
"null",
";",
"if",
"(",
"(",
"scalar",
"+",
"''",
")",
".",
"indexOf",
"(",
"'!str '",
")",
"==",
"0",
")",
"return",
"(",
"''",
"+",
"scalar",
")",
".",
"substring",
"(",
"5",
")",
";",
"if",
"(",
"(",
"scalar",
"+",
"''",
")",
".",
"indexOf",
"(",
"'! '",
")",
"==",
"0",
")",
"return",
"parseInt",
"(",
"this",
".",
"parseScalar",
"(",
"(",
"scalar",
"+",
"''",
")",
".",
"substr",
"(",
"2",
")",
")",
")",
";",
"if",
"(",
"/",
"^\\d+$",
"/",
".",
"test",
"(",
"scalar",
")",
")",
"{",
"raw",
"=",
"scalar",
";",
"cast",
"=",
"parseInt",
"(",
"scalar",
")",
";",
"return",
"'0'",
"==",
"scalar",
".",
"charAt",
"(",
"0",
")",
"?",
"this",
".",
"octdec",
"(",
"scalar",
")",
":",
"(",
"(",
"''",
"+",
"raw",
"==",
"''",
"+",
"cast",
")",
"?",
"cast",
":",
"raw",
")",
";",
"}",
"if",
"(",
"'true'",
"==",
"(",
"scalar",
"+",
"''",
")",
".",
"toLowerCase",
"(",
")",
")",
"return",
"true",
";",
"if",
"(",
"'false'",
"==",
"(",
"scalar",
"+",
"''",
")",
".",
"toLowerCase",
"(",
")",
")",
"return",
"false",
";",
"if",
"(",
"this",
".",
"isNumeric",
"(",
"scalar",
")",
")",
"return",
"'0x'",
"==",
"(",
"scalar",
"+",
"''",
")",
".",
"substr",
"(",
"0",
",",
"2",
")",
"?",
"this",
".",
"hexdec",
"(",
"scalar",
")",
":",
"parseFloat",
"(",
"scalar",
")",
";",
"if",
"(",
"scalar",
".",
"toLowerCase",
"(",
")",
"==",
"'.inf'",
")",
"return",
"Infinity",
";",
"if",
"(",
"scalar",
".",
"toLowerCase",
"(",
")",
"==",
"'.nan'",
")",
"return",
"NaN",
";",
"if",
"(",
"scalar",
".",
"toLowerCase",
"(",
")",
"==",
"'-.inf'",
")",
"return",
"-",
"Infinity",
";",
"if",
"(",
"/",
"^(-|\\+)?[0-9,]+(\\.[0-9]+)?$",
"/",
".",
"test",
"(",
"scalar",
")",
")",
"return",
"parseFloat",
"(",
"scalar",
".",
"split",
"(",
"','",
")",
".",
"join",
"(",
"''",
")",
")",
";",
"if",
"(",
"this",
".",
"getTimestampRegex",
"(",
")",
".",
"test",
"(",
"scalar",
")",
")",
"return",
"new",
"Date",
"(",
"this",
".",
"strtotime",
"(",
"scalar",
")",
")",
";",
"//else",
"return",
"''",
"+",
"scalar",
";",
"}"
] |
Evaluates scalars and replaces magic values.
@param string scalar
@return string A YAML string
|
[
"Evaluates",
"scalars",
"and",
"replaces",
"magic",
"values",
"."
] |
0b53177b26dfe0c2081465e3a496c9b4cb5b1c63
|
https://github.com/jeremyfa/yaml.js/blob/0b53177b26dfe0c2081465e3a496c9b4cb5b1c63/dist/yaml.legacy.js#L787-L826
|
|
12,899
|
jeremyfa/yaml.js
|
dist/yaml.legacy.js
|
function(value /* String */)
{
this.currentLineNb = -1;
this.currentLine = '';
this.lines = this.cleanup(value).split("\n");
var data = null;
var context = null;
while ( this.moveToNextLine() )
{
if ( this.isCurrentLineEmpty() )
{
continue;
}
// tab?
if ( this.currentLine.charAt(0) == '\t' )
{
throw new YamlParseException('A YAML file cannot contain tabs as indentation.', this.getRealCurrentLineNb() + 1, this.currentLine);
}
var isRef = false;
var isInPlace = false;
var isProcessed = false;
var values = null;
var matches = null;
var c = null;
var parser = null;
var block = null;
var key = null;
var parsed = null;
var len = null;
var reverse = null;
if ( values = /^\-((\s+)(.+?))?\s*$/.exec(this.currentLine) )
{
if (context && 'mapping' == context) {
throw new YamlParseException('You cannot define a sequence item when in a mapping', this.getRealCurrentLineNb() + 1, this.currentLine);
}
context = 'sequence';
if ( !this.isDefined(data) ) data = [];
//if ( !(data instanceof Array) ) throw new YamlParseException("Non array entry", this.getRealCurrentLineNb() + 1, this.currentLine);
values = {leadspaces: values[2], value: values[3]};
if ( this.isDefined(values.value) && ( matches = /^&([^ ]+) *(.*)/.exec(values.value) ) )
{
matches = {ref: matches[1], value: matches[2]};
isRef = matches.ref;
values.value = matches.value;
}
// array
if ( !this.isDefined(values.value) || '' == this.trim(values.value) || values.value.replace(/^ +/,'').charAt(0) == '#' )
{
c = this.getRealCurrentLineNb() + 1;
parser = new YamlParser(c);
parser.refs = this.refs;
data.push(parser.parse(this.getNextEmbedBlock()));
this.refs = parser.refs;
}
else
{
if ( this.isDefined(values.leadspaces) &&
' ' == values.leadspaces &&
( matches = new RegExp('^('+YamlInline.REGEX_QUOTED_STRING+'|[^ \'"\{\[].*?) *\:(\\s+(.+?))?\\s*$').exec(values.value) )
) {
matches = {key: matches[1], value: matches[3]};
// this is a compact notation element, add to next block and parse
c = this.getRealCurrentLineNb();
parser = new YamlParser(c);
parser.refs = this.refs;
block = values.value;
if ( !this.isNextLineIndented() )
{
block += "\n"+this.getNextEmbedBlock(this.getCurrentLineIndentation() + 2);
}
data.push(parser.parse(block));
this.refs = parser.refs;
}
else
{
data.push(this.parseValue(values.value));
}
}
}
else if ( values = new RegExp('^('+YamlInline.REGEX_QUOTED_STRING+'|[^ \'"\[\{].*?) *\:(\\s+(.+?))?\\s*$').exec(this.currentLine) )
{
if ( !this.isDefined(data) ) data = {};
if (context && 'sequence' == context) {
throw new YamlParseException('You cannot define a mapping item when in a sequence', this.getRealCurrentLineNb() + 1, this.currentLine);
}
context = 'mapping';
//if ( data instanceof Array ) throw new YamlParseException("Non mapped entry", this.getRealCurrentLineNb() + 1, this.currentLine);
values = {key: values[1], value: values[3]};
try {
key = new YamlInline().parseScalar(values.key);
} catch (e) {
if ( e instanceof YamlParseException ) {
e.setParsedLine(this.getRealCurrentLineNb() + 1);
e.setSnippet(this.currentLine);
}
throw e;
}
if ( '<<' == key )
{
if ( this.isDefined(values.value) && '*' == (values.value+'').charAt(0) )
{
isInPlace = values.value.substr(1);
if ( this.refs[isInPlace] == undefined )
{
throw new YamlParseException('Reference "'+value+'" does not exist', this.getRealCurrentLineNb() + 1, this.currentLine);
}
}
else
{
if ( this.isDefined(values.value) && values.value != '' )
{
value = values.value;
}
else
{
value = this.getNextEmbedBlock();
}
c = this.getRealCurrentLineNb() + 1;
parser = new YamlParser(c);
parser.refs = this.refs;
parsed = parser.parse(value);
this.refs = parser.refs;
var merged = [];
if ( !this.isObject(parsed) )
{
throw new YamlParseException("YAML merge keys used with a scalar value instead of an array", this.getRealCurrentLineNb() + 1, this.currentLine);
}
else if ( this.isDefined(parsed[0]) )
{
// Numeric array, merge individual elements
reverse = this.reverseArray(parsed);
len = reverse.length;
for ( var i = 0; i < len; i++ )
{
var parsedItem = reverse[i];
if ( !this.isObject(reverse[i]) )
{
throw new YamlParseException("Merge items must be arrays", this.getRealCurrentLineNb() + 1, this.currentLine);
}
merged = this.mergeObject(reverse[i], merged);
}
}
else
{
// Associative array, merge
merged = this.mergeObject(merged, parsed);
}
isProcessed = merged;
}
}
else if ( this.isDefined(values.value) && (matches = /^&([^ ]+) *(.*)/.exec(values.value) ) )
{
matches = {ref: matches[1], value: matches[2]};
isRef = matches.ref;
values.value = matches.value;
}
if ( isProcessed )
{
// Merge keys
data = isProcessed;
}
// hash
else if ( !this.isDefined(values.value) || '' == this.trim(values.value) || this.trim(values.value).charAt(0) == '#' )
{
// if next line is less indented or equal, then it means that the current value is null
if ( this.isNextLineIndented() && !this.isNextLineUnIndentedCollection() )
{
data[key] = null;
}
else
{
c = this.getRealCurrentLineNb() + 1;
parser = new YamlParser(c);
parser.refs = this.refs;
data[key] = parser.parse(this.getNextEmbedBlock());
this.refs = parser.refs;
}
}
else
{
if ( isInPlace )
{
data = this.refs[isInPlace];
}
else
{
data[key] = this.parseValue(values.value);
}
}
}
else
{
// 1-liner followed by newline
if ( 2 == this.lines.length && this.isEmpty(this.lines[1]) )
{
try {
value = new YamlInline().parse(this.lines[0]);
} catch (e) {
if ( e instanceof YamlParseException ) {
e.setParsedLine(this.getRealCurrentLineNb() + 1);
e.setSnippet(this.currentLine);
}
throw e;
}
if ( this.isObject(value) )
{
var first = value[0];
if ( typeof(value) == 'string' && '*' == first.charAt(0) )
{
data = [];
len = value.length;
for ( var i = 0; i < len; i++ )
{
data.push(this.refs[value[i].substr(1)]);
}
value = data;
}
}
return value;
}
throw new YamlParseException('Unable to parse.', this.getRealCurrentLineNb() + 1, this.currentLine);
}
if ( isRef )
{
if ( data instanceof Array )
this.refs[isRef] = data[data.length-1];
else
{
var lastKey = null;
for ( var k in data )
{
if ( data.hasOwnProperty(k) ) lastKey = k;
}
this.refs[isRef] = data[k];
}
}
}
return this.isEmpty(data) ? null : data;
}
|
javascript
|
function(value /* String */)
{
this.currentLineNb = -1;
this.currentLine = '';
this.lines = this.cleanup(value).split("\n");
var data = null;
var context = null;
while ( this.moveToNextLine() )
{
if ( this.isCurrentLineEmpty() )
{
continue;
}
// tab?
if ( this.currentLine.charAt(0) == '\t' )
{
throw new YamlParseException('A YAML file cannot contain tabs as indentation.', this.getRealCurrentLineNb() + 1, this.currentLine);
}
var isRef = false;
var isInPlace = false;
var isProcessed = false;
var values = null;
var matches = null;
var c = null;
var parser = null;
var block = null;
var key = null;
var parsed = null;
var len = null;
var reverse = null;
if ( values = /^\-((\s+)(.+?))?\s*$/.exec(this.currentLine) )
{
if (context && 'mapping' == context) {
throw new YamlParseException('You cannot define a sequence item when in a mapping', this.getRealCurrentLineNb() + 1, this.currentLine);
}
context = 'sequence';
if ( !this.isDefined(data) ) data = [];
//if ( !(data instanceof Array) ) throw new YamlParseException("Non array entry", this.getRealCurrentLineNb() + 1, this.currentLine);
values = {leadspaces: values[2], value: values[3]};
if ( this.isDefined(values.value) && ( matches = /^&([^ ]+) *(.*)/.exec(values.value) ) )
{
matches = {ref: matches[1], value: matches[2]};
isRef = matches.ref;
values.value = matches.value;
}
// array
if ( !this.isDefined(values.value) || '' == this.trim(values.value) || values.value.replace(/^ +/,'').charAt(0) == '#' )
{
c = this.getRealCurrentLineNb() + 1;
parser = new YamlParser(c);
parser.refs = this.refs;
data.push(parser.parse(this.getNextEmbedBlock()));
this.refs = parser.refs;
}
else
{
if ( this.isDefined(values.leadspaces) &&
' ' == values.leadspaces &&
( matches = new RegExp('^('+YamlInline.REGEX_QUOTED_STRING+'|[^ \'"\{\[].*?) *\:(\\s+(.+?))?\\s*$').exec(values.value) )
) {
matches = {key: matches[1], value: matches[3]};
// this is a compact notation element, add to next block and parse
c = this.getRealCurrentLineNb();
parser = new YamlParser(c);
parser.refs = this.refs;
block = values.value;
if ( !this.isNextLineIndented() )
{
block += "\n"+this.getNextEmbedBlock(this.getCurrentLineIndentation() + 2);
}
data.push(parser.parse(block));
this.refs = parser.refs;
}
else
{
data.push(this.parseValue(values.value));
}
}
}
else if ( values = new RegExp('^('+YamlInline.REGEX_QUOTED_STRING+'|[^ \'"\[\{].*?) *\:(\\s+(.+?))?\\s*$').exec(this.currentLine) )
{
if ( !this.isDefined(data) ) data = {};
if (context && 'sequence' == context) {
throw new YamlParseException('You cannot define a mapping item when in a sequence', this.getRealCurrentLineNb() + 1, this.currentLine);
}
context = 'mapping';
//if ( data instanceof Array ) throw new YamlParseException("Non mapped entry", this.getRealCurrentLineNb() + 1, this.currentLine);
values = {key: values[1], value: values[3]};
try {
key = new YamlInline().parseScalar(values.key);
} catch (e) {
if ( e instanceof YamlParseException ) {
e.setParsedLine(this.getRealCurrentLineNb() + 1);
e.setSnippet(this.currentLine);
}
throw e;
}
if ( '<<' == key )
{
if ( this.isDefined(values.value) && '*' == (values.value+'').charAt(0) )
{
isInPlace = values.value.substr(1);
if ( this.refs[isInPlace] == undefined )
{
throw new YamlParseException('Reference "'+value+'" does not exist', this.getRealCurrentLineNb() + 1, this.currentLine);
}
}
else
{
if ( this.isDefined(values.value) && values.value != '' )
{
value = values.value;
}
else
{
value = this.getNextEmbedBlock();
}
c = this.getRealCurrentLineNb() + 1;
parser = new YamlParser(c);
parser.refs = this.refs;
parsed = parser.parse(value);
this.refs = parser.refs;
var merged = [];
if ( !this.isObject(parsed) )
{
throw new YamlParseException("YAML merge keys used with a scalar value instead of an array", this.getRealCurrentLineNb() + 1, this.currentLine);
}
else if ( this.isDefined(parsed[0]) )
{
// Numeric array, merge individual elements
reverse = this.reverseArray(parsed);
len = reverse.length;
for ( var i = 0; i < len; i++ )
{
var parsedItem = reverse[i];
if ( !this.isObject(reverse[i]) )
{
throw new YamlParseException("Merge items must be arrays", this.getRealCurrentLineNb() + 1, this.currentLine);
}
merged = this.mergeObject(reverse[i], merged);
}
}
else
{
// Associative array, merge
merged = this.mergeObject(merged, parsed);
}
isProcessed = merged;
}
}
else if ( this.isDefined(values.value) && (matches = /^&([^ ]+) *(.*)/.exec(values.value) ) )
{
matches = {ref: matches[1], value: matches[2]};
isRef = matches.ref;
values.value = matches.value;
}
if ( isProcessed )
{
// Merge keys
data = isProcessed;
}
// hash
else if ( !this.isDefined(values.value) || '' == this.trim(values.value) || this.trim(values.value).charAt(0) == '#' )
{
// if next line is less indented or equal, then it means that the current value is null
if ( this.isNextLineIndented() && !this.isNextLineUnIndentedCollection() )
{
data[key] = null;
}
else
{
c = this.getRealCurrentLineNb() + 1;
parser = new YamlParser(c);
parser.refs = this.refs;
data[key] = parser.parse(this.getNextEmbedBlock());
this.refs = parser.refs;
}
}
else
{
if ( isInPlace )
{
data = this.refs[isInPlace];
}
else
{
data[key] = this.parseValue(values.value);
}
}
}
else
{
// 1-liner followed by newline
if ( 2 == this.lines.length && this.isEmpty(this.lines[1]) )
{
try {
value = new YamlInline().parse(this.lines[0]);
} catch (e) {
if ( e instanceof YamlParseException ) {
e.setParsedLine(this.getRealCurrentLineNb() + 1);
e.setSnippet(this.currentLine);
}
throw e;
}
if ( this.isObject(value) )
{
var first = value[0];
if ( typeof(value) == 'string' && '*' == first.charAt(0) )
{
data = [];
len = value.length;
for ( var i = 0; i < len; i++ )
{
data.push(this.refs[value[i].substr(1)]);
}
value = data;
}
}
return value;
}
throw new YamlParseException('Unable to parse.', this.getRealCurrentLineNb() + 1, this.currentLine);
}
if ( isRef )
{
if ( data instanceof Array )
this.refs[isRef] = data[data.length-1];
else
{
var lastKey = null;
for ( var k in data )
{
if ( data.hasOwnProperty(k) ) lastKey = k;
}
this.refs[isRef] = data[k];
}
}
}
return this.isEmpty(data) ? null : data;
}
|
[
"function",
"(",
"value",
"/* String */",
")",
"{",
"this",
".",
"currentLineNb",
"=",
"-",
"1",
";",
"this",
".",
"currentLine",
"=",
"''",
";",
"this",
".",
"lines",
"=",
"this",
".",
"cleanup",
"(",
"value",
")",
".",
"split",
"(",
"\"\\n\"",
")",
";",
"var",
"data",
"=",
"null",
";",
"var",
"context",
"=",
"null",
";",
"while",
"(",
"this",
".",
"moveToNextLine",
"(",
")",
")",
"{",
"if",
"(",
"this",
".",
"isCurrentLineEmpty",
"(",
")",
")",
"{",
"continue",
";",
"}",
"// tab?",
"if",
"(",
"this",
".",
"currentLine",
".",
"charAt",
"(",
"0",
")",
"==",
"'\\t'",
")",
"{",
"throw",
"new",
"YamlParseException",
"(",
"'A YAML file cannot contain tabs as indentation.'",
",",
"this",
".",
"getRealCurrentLineNb",
"(",
")",
"+",
"1",
",",
"this",
".",
"currentLine",
")",
";",
"}",
"var",
"isRef",
"=",
"false",
";",
"var",
"isInPlace",
"=",
"false",
";",
"var",
"isProcessed",
"=",
"false",
";",
"var",
"values",
"=",
"null",
";",
"var",
"matches",
"=",
"null",
";",
"var",
"c",
"=",
"null",
";",
"var",
"parser",
"=",
"null",
";",
"var",
"block",
"=",
"null",
";",
"var",
"key",
"=",
"null",
";",
"var",
"parsed",
"=",
"null",
";",
"var",
"len",
"=",
"null",
";",
"var",
"reverse",
"=",
"null",
";",
"if",
"(",
"values",
"=",
"/",
"^\\-((\\s+)(.+?))?\\s*$",
"/",
".",
"exec",
"(",
"this",
".",
"currentLine",
")",
")",
"{",
"if",
"(",
"context",
"&&",
"'mapping'",
"==",
"context",
")",
"{",
"throw",
"new",
"YamlParseException",
"(",
"'You cannot define a sequence item when in a mapping'",
",",
"this",
".",
"getRealCurrentLineNb",
"(",
")",
"+",
"1",
",",
"this",
".",
"currentLine",
")",
";",
"}",
"context",
"=",
"'sequence'",
";",
"if",
"(",
"!",
"this",
".",
"isDefined",
"(",
"data",
")",
")",
"data",
"=",
"[",
"]",
";",
"//if ( !(data instanceof Array) ) throw new YamlParseException(\"Non array entry\", this.getRealCurrentLineNb() + 1, this.currentLine);",
"values",
"=",
"{",
"leadspaces",
":",
"values",
"[",
"2",
"]",
",",
"value",
":",
"values",
"[",
"3",
"]",
"}",
";",
"if",
"(",
"this",
".",
"isDefined",
"(",
"values",
".",
"value",
")",
"&&",
"(",
"matches",
"=",
"/",
"^&([^ ]+) *(.*)",
"/",
".",
"exec",
"(",
"values",
".",
"value",
")",
")",
")",
"{",
"matches",
"=",
"{",
"ref",
":",
"matches",
"[",
"1",
"]",
",",
"value",
":",
"matches",
"[",
"2",
"]",
"}",
";",
"isRef",
"=",
"matches",
".",
"ref",
";",
"values",
".",
"value",
"=",
"matches",
".",
"value",
";",
"}",
"// array",
"if",
"(",
"!",
"this",
".",
"isDefined",
"(",
"values",
".",
"value",
")",
"||",
"''",
"==",
"this",
".",
"trim",
"(",
"values",
".",
"value",
")",
"||",
"values",
".",
"value",
".",
"replace",
"(",
"/",
"^ +",
"/",
",",
"''",
")",
".",
"charAt",
"(",
"0",
")",
"==",
"'#'",
")",
"{",
"c",
"=",
"this",
".",
"getRealCurrentLineNb",
"(",
")",
"+",
"1",
";",
"parser",
"=",
"new",
"YamlParser",
"(",
"c",
")",
";",
"parser",
".",
"refs",
"=",
"this",
".",
"refs",
";",
"data",
".",
"push",
"(",
"parser",
".",
"parse",
"(",
"this",
".",
"getNextEmbedBlock",
"(",
")",
")",
")",
";",
"this",
".",
"refs",
"=",
"parser",
".",
"refs",
";",
"}",
"else",
"{",
"if",
"(",
"this",
".",
"isDefined",
"(",
"values",
".",
"leadspaces",
")",
"&&",
"' '",
"==",
"values",
".",
"leadspaces",
"&&",
"(",
"matches",
"=",
"new",
"RegExp",
"(",
"'^('",
"+",
"YamlInline",
".",
"REGEX_QUOTED_STRING",
"+",
"'|[^ \\'\"\\{\\[].*?) *\\:(\\\\s+(.+?))?\\\\s*$'",
")",
".",
"exec",
"(",
"values",
".",
"value",
")",
")",
")",
"{",
"matches",
"=",
"{",
"key",
":",
"matches",
"[",
"1",
"]",
",",
"value",
":",
"matches",
"[",
"3",
"]",
"}",
";",
"// this is a compact notation element, add to next block and parse",
"c",
"=",
"this",
".",
"getRealCurrentLineNb",
"(",
")",
";",
"parser",
"=",
"new",
"YamlParser",
"(",
"c",
")",
";",
"parser",
".",
"refs",
"=",
"this",
".",
"refs",
";",
"block",
"=",
"values",
".",
"value",
";",
"if",
"(",
"!",
"this",
".",
"isNextLineIndented",
"(",
")",
")",
"{",
"block",
"+=",
"\"\\n\"",
"+",
"this",
".",
"getNextEmbedBlock",
"(",
"this",
".",
"getCurrentLineIndentation",
"(",
")",
"+",
"2",
")",
";",
"}",
"data",
".",
"push",
"(",
"parser",
".",
"parse",
"(",
"block",
")",
")",
";",
"this",
".",
"refs",
"=",
"parser",
".",
"refs",
";",
"}",
"else",
"{",
"data",
".",
"push",
"(",
"this",
".",
"parseValue",
"(",
"values",
".",
"value",
")",
")",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"values",
"=",
"new",
"RegExp",
"(",
"'^('",
"+",
"YamlInline",
".",
"REGEX_QUOTED_STRING",
"+",
"'|[^ \\'\"\\[\\{].*?) *\\:(\\\\s+(.+?))?\\\\s*$'",
")",
".",
"exec",
"(",
"this",
".",
"currentLine",
")",
")",
"{",
"if",
"(",
"!",
"this",
".",
"isDefined",
"(",
"data",
")",
")",
"data",
"=",
"{",
"}",
";",
"if",
"(",
"context",
"&&",
"'sequence'",
"==",
"context",
")",
"{",
"throw",
"new",
"YamlParseException",
"(",
"'You cannot define a mapping item when in a sequence'",
",",
"this",
".",
"getRealCurrentLineNb",
"(",
")",
"+",
"1",
",",
"this",
".",
"currentLine",
")",
";",
"}",
"context",
"=",
"'mapping'",
";",
"//if ( data instanceof Array ) throw new YamlParseException(\"Non mapped entry\", this.getRealCurrentLineNb() + 1, this.currentLine);",
"values",
"=",
"{",
"key",
":",
"values",
"[",
"1",
"]",
",",
"value",
":",
"values",
"[",
"3",
"]",
"}",
";",
"try",
"{",
"key",
"=",
"new",
"YamlInline",
"(",
")",
".",
"parseScalar",
"(",
"values",
".",
"key",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"e",
"instanceof",
"YamlParseException",
")",
"{",
"e",
".",
"setParsedLine",
"(",
"this",
".",
"getRealCurrentLineNb",
"(",
")",
"+",
"1",
")",
";",
"e",
".",
"setSnippet",
"(",
"this",
".",
"currentLine",
")",
";",
"}",
"throw",
"e",
";",
"}",
"if",
"(",
"'<<'",
"==",
"key",
")",
"{",
"if",
"(",
"this",
".",
"isDefined",
"(",
"values",
".",
"value",
")",
"&&",
"'*'",
"==",
"(",
"values",
".",
"value",
"+",
"''",
")",
".",
"charAt",
"(",
"0",
")",
")",
"{",
"isInPlace",
"=",
"values",
".",
"value",
".",
"substr",
"(",
"1",
")",
";",
"if",
"(",
"this",
".",
"refs",
"[",
"isInPlace",
"]",
"==",
"undefined",
")",
"{",
"throw",
"new",
"YamlParseException",
"(",
"'Reference \"'",
"+",
"value",
"+",
"'\" does not exist'",
",",
"this",
".",
"getRealCurrentLineNb",
"(",
")",
"+",
"1",
",",
"this",
".",
"currentLine",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"this",
".",
"isDefined",
"(",
"values",
".",
"value",
")",
"&&",
"values",
".",
"value",
"!=",
"''",
")",
"{",
"value",
"=",
"values",
".",
"value",
";",
"}",
"else",
"{",
"value",
"=",
"this",
".",
"getNextEmbedBlock",
"(",
")",
";",
"}",
"c",
"=",
"this",
".",
"getRealCurrentLineNb",
"(",
")",
"+",
"1",
";",
"parser",
"=",
"new",
"YamlParser",
"(",
"c",
")",
";",
"parser",
".",
"refs",
"=",
"this",
".",
"refs",
";",
"parsed",
"=",
"parser",
".",
"parse",
"(",
"value",
")",
";",
"this",
".",
"refs",
"=",
"parser",
".",
"refs",
";",
"var",
"merged",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"this",
".",
"isObject",
"(",
"parsed",
")",
")",
"{",
"throw",
"new",
"YamlParseException",
"(",
"\"YAML merge keys used with a scalar value instead of an array\"",
",",
"this",
".",
"getRealCurrentLineNb",
"(",
")",
"+",
"1",
",",
"this",
".",
"currentLine",
")",
";",
"}",
"else",
"if",
"(",
"this",
".",
"isDefined",
"(",
"parsed",
"[",
"0",
"]",
")",
")",
"{",
"// Numeric array, merge individual elements",
"reverse",
"=",
"this",
".",
"reverseArray",
"(",
"parsed",
")",
";",
"len",
"=",
"reverse",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"parsedItem",
"=",
"reverse",
"[",
"i",
"]",
";",
"if",
"(",
"!",
"this",
".",
"isObject",
"(",
"reverse",
"[",
"i",
"]",
")",
")",
"{",
"throw",
"new",
"YamlParseException",
"(",
"\"Merge items must be arrays\"",
",",
"this",
".",
"getRealCurrentLineNb",
"(",
")",
"+",
"1",
",",
"this",
".",
"currentLine",
")",
";",
"}",
"merged",
"=",
"this",
".",
"mergeObject",
"(",
"reverse",
"[",
"i",
"]",
",",
"merged",
")",
";",
"}",
"}",
"else",
"{",
"// Associative array, merge",
"merged",
"=",
"this",
".",
"mergeObject",
"(",
"merged",
",",
"parsed",
")",
";",
"}",
"isProcessed",
"=",
"merged",
";",
"}",
"}",
"else",
"if",
"(",
"this",
".",
"isDefined",
"(",
"values",
".",
"value",
")",
"&&",
"(",
"matches",
"=",
"/",
"^&([^ ]+) *(.*)",
"/",
".",
"exec",
"(",
"values",
".",
"value",
")",
")",
")",
"{",
"matches",
"=",
"{",
"ref",
":",
"matches",
"[",
"1",
"]",
",",
"value",
":",
"matches",
"[",
"2",
"]",
"}",
";",
"isRef",
"=",
"matches",
".",
"ref",
";",
"values",
".",
"value",
"=",
"matches",
".",
"value",
";",
"}",
"if",
"(",
"isProcessed",
")",
"{",
"// Merge keys",
"data",
"=",
"isProcessed",
";",
"}",
"// hash",
"else",
"if",
"(",
"!",
"this",
".",
"isDefined",
"(",
"values",
".",
"value",
")",
"||",
"''",
"==",
"this",
".",
"trim",
"(",
"values",
".",
"value",
")",
"||",
"this",
".",
"trim",
"(",
"values",
".",
"value",
")",
".",
"charAt",
"(",
"0",
")",
"==",
"'#'",
")",
"{",
"// if next line is less indented or equal, then it means that the current value is null",
"if",
"(",
"this",
".",
"isNextLineIndented",
"(",
")",
"&&",
"!",
"this",
".",
"isNextLineUnIndentedCollection",
"(",
")",
")",
"{",
"data",
"[",
"key",
"]",
"=",
"null",
";",
"}",
"else",
"{",
"c",
"=",
"this",
".",
"getRealCurrentLineNb",
"(",
")",
"+",
"1",
";",
"parser",
"=",
"new",
"YamlParser",
"(",
"c",
")",
";",
"parser",
".",
"refs",
"=",
"this",
".",
"refs",
";",
"data",
"[",
"key",
"]",
"=",
"parser",
".",
"parse",
"(",
"this",
".",
"getNextEmbedBlock",
"(",
")",
")",
";",
"this",
".",
"refs",
"=",
"parser",
".",
"refs",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"isInPlace",
")",
"{",
"data",
"=",
"this",
".",
"refs",
"[",
"isInPlace",
"]",
";",
"}",
"else",
"{",
"data",
"[",
"key",
"]",
"=",
"this",
".",
"parseValue",
"(",
"values",
".",
"value",
")",
";",
"}",
"}",
"}",
"else",
"{",
"// 1-liner followed by newline",
"if",
"(",
"2",
"==",
"this",
".",
"lines",
".",
"length",
"&&",
"this",
".",
"isEmpty",
"(",
"this",
".",
"lines",
"[",
"1",
"]",
")",
")",
"{",
"try",
"{",
"value",
"=",
"new",
"YamlInline",
"(",
")",
".",
"parse",
"(",
"this",
".",
"lines",
"[",
"0",
"]",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"e",
"instanceof",
"YamlParseException",
")",
"{",
"e",
".",
"setParsedLine",
"(",
"this",
".",
"getRealCurrentLineNb",
"(",
")",
"+",
"1",
")",
";",
"e",
".",
"setSnippet",
"(",
"this",
".",
"currentLine",
")",
";",
"}",
"throw",
"e",
";",
"}",
"if",
"(",
"this",
".",
"isObject",
"(",
"value",
")",
")",
"{",
"var",
"first",
"=",
"value",
"[",
"0",
"]",
";",
"if",
"(",
"typeof",
"(",
"value",
")",
"==",
"'string'",
"&&",
"'*'",
"==",
"first",
".",
"charAt",
"(",
"0",
")",
")",
"{",
"data",
"=",
"[",
"]",
";",
"len",
"=",
"value",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"data",
".",
"push",
"(",
"this",
".",
"refs",
"[",
"value",
"[",
"i",
"]",
".",
"substr",
"(",
"1",
")",
"]",
")",
";",
"}",
"value",
"=",
"data",
";",
"}",
"}",
"return",
"value",
";",
"}",
"throw",
"new",
"YamlParseException",
"(",
"'Unable to parse.'",
",",
"this",
".",
"getRealCurrentLineNb",
"(",
")",
"+",
"1",
",",
"this",
".",
"currentLine",
")",
";",
"}",
"if",
"(",
"isRef",
")",
"{",
"if",
"(",
"data",
"instanceof",
"Array",
")",
"this",
".",
"refs",
"[",
"isRef",
"]",
"=",
"data",
"[",
"data",
".",
"length",
"-",
"1",
"]",
";",
"else",
"{",
"var",
"lastKey",
"=",
"null",
";",
"for",
"(",
"var",
"k",
"in",
"data",
")",
"{",
"if",
"(",
"data",
".",
"hasOwnProperty",
"(",
"k",
")",
")",
"lastKey",
"=",
"k",
";",
"}",
"this",
".",
"refs",
"[",
"isRef",
"]",
"=",
"data",
"[",
"k",
"]",
";",
"}",
"}",
"}",
"return",
"this",
".",
"isEmpty",
"(",
"data",
")",
"?",
"null",
":",
"data",
";",
"}"
] |
Parses a YAML string to a JS value.
@param String value A YAML string
@return mixed A JS value
|
[
"Parses",
"a",
"YAML",
"string",
"to",
"a",
"JS",
"value",
"."
] |
0b53177b26dfe0c2081465e3a496c9b4cb5b1c63
|
https://github.com/jeremyfa/yaml.js/blob/0b53177b26dfe0c2081465e3a496c9b4cb5b1c63/dist/yaml.legacy.js#L976-L1239
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.