_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q27300
Api
train
function Api(options, t, u, j) { this.options = options; this.transport = t; this.url = u; this.jsonBackup = j; this.accessToken = options.accessToken; this.transportOptions = _getTransport(options, u); }
javascript
{ "resource": "" }
q27301
ErrorStackParser$$parse
train
function ErrorStackParser$$parse(error) { if (typeof error.stacktrace !== 'undefined' || typeof error['opera#sourceloc'] !== 'undefined') { return this.parseOpera(error); } else if (error.stack && error.stack.match(CHROME_IE_STACK_REGEXP)) { return this.parseV8OrIE(error); } else if (error.stack) { return this.parseFFOrSafari(error); } else { throw new Error('Cannot parse given Error object'); } }
javascript
{ "resource": "" }
q27302
_rollbarWindowOnError
train
function _rollbarWindowOnError(client, old, args) { if (!args[4] && window._rollbarWrappedError) { args[4] = window._rollbarWrappedError; window._rollbarWrappedError = null; } globalNotifier.uncaughtError.apply(globalNotifier, args); if (old) { old.apply(window, args); } }
javascript
{ "resource": "" }
q27303
firstFourLines
train
function firstFourLines(file, options) { file.excerpt = file.content.split('\n').slice(0, 4).join(' '); }
javascript
{ "resource": "" }
q27304
parser
train
function parser(lang, opts) { lang = lang || opts.lang; if (engines.hasOwnProperty(lang)) { return engines[lang]; } return engines.yaml; }
javascript
{ "resource": "" }
q27305
parseMatter
train
function parseMatter(file, options) { const opts = defaults(options); const open = opts.delimiters[0]; const close = '\n' + opts.delimiters[1]; let str = file.content; if (opts.language) { file.language = opts.language; } // get the length of the opening delimiter const openLen = open.length; if (!utils.startsWith(str, open, openLen)) { excerpt(file, opts); return file; } // if the next character after the opening delimiter is // a character from the delimiter, then it's not a front- // matter delimiter if (str.charAt(openLen) === open.slice(-1)) { return file; } // strip the opening delimiter str = str.slice(openLen); const len = str.length; // use the language defined after first delimiter, if it exists const language = matter.language(str, opts); if (language.name) { file.language = language.name; str = str.slice(language.raw.length); } // get the index of the closing delimiter let closeIndex = str.indexOf(close); if (closeIndex === -1) { closeIndex = len; } // get the raw front-matter block file.matter = str.slice(0, closeIndex); const block = file.matter.replace(/^\s*#[^\n]+/gm, '').trim(); if (block === '') { file.isEmpty = true; file.empty = file.content; file.data = {}; } else { // create file.data by parsing the raw file.matter block file.data = parse(file.language, file.matter, opts); } // update file.content if (closeIndex === len) { file.content = ''; } else { file.content = str.slice(closeIndex + close.length); if (file.content[0] === '\r') { file.content = file.content.slice(1); } if (file.content[0] === '\n') { file.content = file.content.slice(1); } } excerpt(file, opts); if (opts.sections === true || typeof opts.section === 'function') { sections(file, opts.section); } return file; }
javascript
{ "resource": "" }
q27306
Socket
train
function Socket(sio, options) { if (!(this instanceof Socket)) { return new Socket(sio, options); } EventEmitter.call(this); options = options || {}; this.sio = sio; this.forceBase64 = !!options.forceBase64; this.streams = {}; this.encoder = new parser.Encoder(); this.decoder = new parser.Decoder(); var eventName = exports.event; sio.on(eventName, bind(this, emit)); sio.on(eventName + '-read', bind(this, '_onread')); sio.on(eventName + '-write', bind(this, '_onwrite')); sio.on(eventName + '-end', bind(this, '_onend')); sio.on(eventName + '-error', bind(this, '_onerror')); sio.on('error', bind(this, emit, 'error')); sio.on('disconnect', bind(this, '_ondisconnect')); this.encoder.on('stream', bind(this, '_onencode')); this.decoder.on('stream', bind(this, '_ondecode')); }
javascript
{ "resource": "" }
q27307
lookup
train
function lookup(sio, options) { options = options || {}; if (null == options.forceBase64) { options.forceBase64 = exports.forceBase64; } if (!sio._streamSocket) { sio._streamSocket = new Socket(sio, options); } return sio._streamSocket; }
javascript
{ "resource": "" }
q27308
BlobReadStream
train
function BlobReadStream(blob, options) { if (!(this instanceof BlobReadStream)) { return new BlobReadStream(blob, options); } Readable.call(this, options); options = options || {}; this.blob = blob; this.slice = blob.slice || blob.webkitSlice || blob.mozSlice; this.start = 0; this.sync = options.synchronous || false; var fileReader; if (options.synchronous) { fileReader = this.fileReader = new FileReaderSync(); } else { fileReader = this.fileReader = new FileReader(); } fileReader.onload = bind(this, '_onload'); fileReader.onerror = bind(this, '_onerror'); }
javascript
{ "resource": "" }
q27309
dig
train
function dig(o, namerg) { var os = [], out; function digger(o, namerg, res) { o = o || this; res = res || []; for(var i = 0; i < res.length; i++) { if(o === res[i]) { return res; } } os.push(o); try{ for(var name in o); } catch(e) { return []; } var inside, clean = true; for(name in o) { if(clean && o.hasOwnProperty(name) && name.match(namerg)) { res.push(o); clean = false; } var isObject = false; try{ isObject = o[name] === Object(o[name]) && typeof o[name] != "function"; } catch(e) {} if(isObject) { inside = false; for (i = 0, ii = os.length; i < ii; i++) { if (os[i] == o[name]) { inside = true; break; } } if (!inside) { digger(o[name], namerg, res); } } } return res; } out = digger(o, namerg); os = null; return out; }
javascript
{ "resource": "" }
q27310
calculateCollatzConjecture
train
function calculateCollatzConjecture(number) { if (!(number in cache)) { if (number % 2 === 0) cache[number] = number >> 1; else cache[number] = number * 3 + 1; } return cache[number]; }
javascript
{ "resource": "" }
q27311
generateCollatzConjecture
train
function generateCollatzConjecture(number) { const collatzConjecture = []; do { number = calculateCollatzConjecture(number); collatzConjecture.push(number); } while (number !== 1); return collatzConjecture; }
javascript
{ "resource": "" }
q27312
dijkstra
train
function dijkstra(graph, s) { const distance = {}; const previous = {}; const q = new PriorityQueue(); // Initialize distance[s] = 0; graph.vertices.forEach(v => { if (v !== s) { distance[v] = Infinity; } q.insert(v, distance[v]); }); let currNode; const relax = v => { const newDistance = distance[currNode] + graph.edge(currNode, v); if (newDistance < distance[v]) { distance[v] = newDistance; previous[v] = currNode; q.changePriority(v, distance[v]); } }; while (!q.isEmpty()) { currNode = q.extract(); graph.neighbors(currNode).forEach(relax); } return { distance, previous }; }
javascript
{ "resource": "" }
q27313
train
function(suppliedConfig) { var targetElement = suppliedConfig.el || getConfig().el; rootTarget = $(targetElement); if (rootTarget.length === 0) { throw triggerError('No target DOM element was found (' + targetElement + ')'); } rootTarget.addClass('bookingjs'); rootTarget.children(':not(script)').remove(); }
javascript
{ "resource": "" }
q27314
train
function() { showLoadingScreen(); calendarTarget.fullCalendar('removeEventSources'); if (getConfig().booking.graph === 'group_customer' || getConfig().booking.graph === 'group_customer_payment') { // If in group bookings mode, fetch slots timekitGetBookingSlots(); } else { // If in normal single-participant mode, call findtime timekitFetchAvailability(); } }
javascript
{ "resource": "" }
q27315
train
function(firstEventStart) { calendarTarget.fullCalendar('gotoDate', firstEventStart); var firstEventStartHour = moment(firstEventStart).format('H'); scrollToTime(firstEventStartHour); }
javascript
{ "resource": "" }
q27316
train
function(time) { // Only proceed for agendaWeek view if (calendarTarget.fullCalendar('getView').name !== 'agendaWeek'){ return; } // Get height of each hour row var slotDuration = calendarTarget.fullCalendar('option', 'slotDuration'); var slotDurationMinutes = 30; if (slotDuration) slotDurationMinutes = slotDuration.slice(3, 5); var hours = calendarTarget.find('.fc-slats .fc-minor'); var hourHeight = $(hours[0]).height() * (60 / slotDurationMinutes); // If minTime is set in fullCalendar config, subtract that from the scollTo calculationn var minTimeHeight = 0; if (getConfig().fullcalendar.minTime) { var minTime = moment(getConfig().fullcalendar.minTime, 'HH:mm:ss').format('H'); minTimeHeight = hourHeight * minTime; } // Calculate scrolling location and container sizes var scrollTo = (hourHeight * time) - minTimeHeight; var scrollable = calendarTarget.find('.fc-scroller'); var scrollableHeight = scrollable.height(); var scrollableScrollTop = scrollable.scrollTop(); var maximumHeight = scrollable.find('.fc-time-grid').height(); // Only perform the scroll if the scrollTo is outside the current visible boundary if (scrollTo > scrollableScrollTop && scrollTo < scrollableScrollTop + scrollableHeight) { return; } // If scrollTo point is past the maximum height, then scroll to maximum possible while still animating if (scrollTo > maximumHeight - scrollableHeight) { scrollTo = maximumHeight - scrollableHeight; } // Perform the scrollTo animation scrollable.animate({scrollTop: scrollTo}); }
javascript
{ "resource": "" }
q27317
train
function() { var showTimezoneHelper = getConfig().ui.show_timezone_helper; var showCredits = getConfig().ui.show_credits; // If neither TZ helper or credits is shown, dont render the footer if (!showTimezoneHelper && !showCredits) return var campaignName = 'widget'; var campaignSource = window.location.hostname.replace(/\./g, '-'); if (getConfig().project_id) { campaignName = 'embedded-widget'; } if (getConfig().project_slug) { campaignName = 'hosted-widget'; } var timezoneIcon = require('!svg-inline!./assets/timezone-icon.svg'); var arrowDownIcon = require('!svg-inline!./assets/arrow-down-icon.svg'); var timekitLogo = require('!svg-inline!./assets/timekit-logo.svg'); var template = require('./templates/footer.html'); var footerTarget = $(template.render({ timezoneIcon: timezoneIcon, arrowDownIcon: arrowDownIcon, listTimezones: timezones, timekitLogo: timekitLogo, campaignName: campaignName, campaignSource: campaignSource, showCredits: showCredits, showTimezoneHelper: showTimezoneHelper })); rootTarget.append(footerTarget); // Set initial customer timezone var pickerSelect = $('.bookingjs-footer-tz-picker-select'); pickerSelect.val(customerTimezone); // Listen to changes by the user pickerSelect.change(function() { setCustomerTimezone(pickerSelect.val()); $(rootTarget).trigger('customer-timezone-changed'); }) }
javascript
{ "resource": "" }
q27318
train
function () { var tzGuess = moment.tz.guess() || 'UTC'; setCustomerTimezone(tzGuess); // Add the guessed customer timezone to list if its unknwon var knownTimezone = $.grep(timezones, function (tz) { return tz.key === customerTimezone }).length > 0 if (!knownTimezone) { var name = '(' + moment().tz(customerTimezone).format('Z') + ') ' + customerTimezone timezones.unshift({ key: customerTimezone, name: name }); } }
javascript
{ "resource": "" }
q27319
train
function() { var sizing = decideCalendarSize(getConfig().fullcalendar.defaultView); var args = { height: sizing.height, eventClick: clickTimeslot, windowResize: function() { var sizing = decideCalendarSize(); calendarTarget.fullCalendar('changeView', sizing.view); calendarTarget.fullCalendar('option', 'height', sizing.height); } }; $.extend(true, args, getConfig().fullcalendar); args.defaultView = sizing.view; calendarTarget = $('<div class="bookingjs-calendar empty-calendar">'); rootTarget.append(calendarTarget); calendarTarget.fullCalendar(args); $(rootTarget).on('customer-timezone-changed', function () { if (!calendarTarget) return getAvailability(); calendarTarget.fullCalendar('option', 'now', moment().tz(customerTimezone).format()); }) utils.doCallback('fullCalendarInitialized'); }
javascript
{ "resource": "" }
q27320
train
function(eventData) { if (!getConfig().disable_confirm_page) { showBookingPage(eventData) } else { $('.fc-event-clicked').removeClass('fc-event-clicked'); $(this).addClass('fc-event-clicked'); utils.doCallback('clickTimeslot', eventData); } }
javascript
{ "resource": "" }
q27321
train
function(currentView) { currentView = currentView || calendarTarget.fullCalendar('getView').name var view = getConfig().fullcalendar.defaultView var height = 385; if (rootTarget.width() < 480) { rootTarget.addClass('is-small'); if (getConfig().ui.avatar) height -= 15; if (currentView === 'agendaWeek' || currentView === 'basicDay') { view = 'basicDay'; } } else { rootTarget.removeClass('is-small'); } $.each(getConfig().customer_fields, function(key, field) { if (field.format === 'textarea') height += 98; else if (field.format === 'checkbox') height += 51; else height += 66; }) return { height: height, view: view }; }
javascript
{ "resource": "" }
q27322
train
function(eventData) { var firstEventStart = moment(eventData[0].start) var firstEventEnd = moment(eventData[0].end) var firstEventDuration = firstEventEnd.diff(firstEventStart, 'minutes') if (firstEventDuration <= 90) { calendarTarget.fullCalendar('option', 'slotDuration', '00:15:00') } calendarTarget.fullCalendar('addEventSource', { events: eventData }); calendarTarget.removeClass('empty-calendar'); // Go to first event if enabled goToFirstEvent(eventData[0].start); }
javascript
{ "resource": "" }
q27323
train
function() { utils.doCallback('showLoadingScreen'); var template = require('./templates/loading.html'); loadingTarget = $(template.render({ loadingIcon: require('!svg-inline!./assets/loading-spinner.svg') })); rootTarget.append(loadingTarget); }
javascript
{ "resource": "" }
q27324
train
function(message) { // If an error already has been thrown, exit if (errorTarget) return message utils.doCallback('errorTriggered', message); utils.logError(message) // If no target DOM element exists, only do the logging if (!rootTarget) return message var messageProcessed = message var contextProcessed = null if (utils.isArray(message)) { messageProcessed = message[0] if (message[1].data) { contextProcessed = stringify(message[1].data.errors || message[1].data.error || message[1].data) } else { contextProcessed = stringify(message[1]) } } var template = require('./templates/error.html'); errorTarget = $(template.render({ errorWarningIcon: require('!svg-inline!./assets/error-warning-icon.svg'), message: messageProcessed, context: contextProcessed })); rootTarget.append(errorTarget); return message }
javascript
{ "resource": "" }
q27325
train
function () { var textTemplate = require('./templates/fields/text.html'); var textareaTemplate = require('./templates/fields/textarea.html'); var selectTemplate = require('./templates/fields/select.html'); var checkboxTemplate = require('./templates/fields/checkbox.html'); var fieldsTarget = [] $.each(getConfig().customer_fields, function(key, field) { var tmpl = textTemplate if (field.format === 'textarea') tmpl = textareaTemplate if (field.format === 'select') tmpl = selectTemplate if (field.format === 'checkbox') tmpl = checkboxTemplate if (!field.format) field.format = 'text' if (key === 'email') field.format = 'email' var data = $.extend({ key: key, arrowDownIcon: require('!svg-inline!./assets/arrow-down-icon.svg') }, field) var fieldTarget = $(tmpl.render(data)) fieldsTarget.push(fieldTarget) }) return fieldsTarget }
javascript
{ "resource": "" }
q27326
train
function(eventData) { utils.doCallback('showBookingPage', eventData); var template = require('./templates/booking-page.html'); var dateFormat = getConfig().ui.booking_date_format || moment.localeData().longDateFormat('LL'); var timeFormat = getConfig().ui.booking_time_format || moment.localeData().longDateFormat('LT'); var allocatedResource = eventData.resources ? eventData.resources[0].name : false; bookingPageTarget = $(template.render({ chosenDate: formatTimestamp(eventData.start, dateFormat), chosenTime: formatTimestamp(eventData.start, timeFormat) + ' - ' + formatTimestamp(eventData.end, timeFormat), allocatedResourcePrefix: getConfig().ui.localization.allocated_resource_prefix, allocatedResource: allocatedResource, closeIcon: require('!svg-inline!./assets/close-icon.svg'), checkmarkIcon: require('!svg-inline!./assets/checkmark-icon.svg'), loadingIcon: require('!svg-inline!./assets/loading-spinner.svg'), errorIcon: require('!svg-inline!./assets/error-icon.svg'), submitText: getConfig().ui.localization.submit_button, successMessage: interpolate.sprintf(getConfig().ui.localization.success_message, '<span class="booked-email"></span>') })); var formFields = bookingPageTarget.find('.bookingjs-form-fields'); $(formFields).append(renderCustomerFields()); var form = bookingPageTarget.children('.bookingjs-form'); bookingPageTarget.children('.bookingjs-bookpage-close').click(function(e) { e.preventDefault(); var bookingHasBeenCreated = $(form).hasClass('success'); if (bookingHasBeenCreated) getAvailability(); hideBookingPage(); }); if (eventData.resources) { utils.logDebug(['Available resources for chosen timeslot:', eventData.resources]); } form.find('.bookingjs-form-input').on('input', function() { var field = $(this).closest('.bookingjs-form-field'); if (this.value) field.addClass('bookingjs-form-field--dirty'); else field.removeClass('bookingjs-form-field--dirty'); }); form.submit(function(e) { submitBookingForm(this, e, eventData); }); $(rootTarget).on('customer-timezone-changed', function () { if (!bookingPageTarget) return $('.bookingjs-bookpage-date').text(formatTimestamp(eventData.start, dateFormat)); $('.bookingjs-bookpage-time').text(formatTimestamp(eventData.start, timeFormat) + ' - ' + formatTimestamp(eventData.end, timeFormat)); }); $(document).on('keyup', function(e) { // escape key maps to keycode `27` if (e.keyCode === 27) { hideBookingPage(); } }); rootTarget.append(bookingPageTarget); setTimeout(function(){ bookingPageTarget.addClass('show'); }, 100); }
javascript
{ "resource": "" }
q27327
train
function(form, e, eventData) { e.preventDefault(); var formElement = $(form); if(formElement.hasClass('success')) { getAvailability(); hideBookingPage(); return; } // Abort if form is submitting, have submitted or does not validate if(formElement.hasClass('loading') || formElement.hasClass('error') || !e.target.checkValidity()) { var submitButton = formElement.find('.bookingjs-form-button'); submitButton.addClass('button-shake'); setTimeout(function() { submitButton.removeClass('button-shake'); }, 500); return; } var formData = {}; $.each(formElement.serializeArray(), function(i, field) { formData[field.name] = field.value; }); formElement.addClass('loading'); utils.doCallback('submitBookingForm', formData); // Call create event endpoint timekitCreateBooking(formData, eventData).then(function(response){ formElement.find('.booked-email').html(formData.email); formElement.removeClass('loading').addClass('success'); }).catch(function(response){ showBookingFailed(formElement) }); }
javascript
{ "resource": "" }
q27328
train
function(formData, eventData) { var nativeFields = ['name', 'email', 'location', 'comment', 'phone', 'voip'] var args = { start: eventData.start.format(), end: eventData.end.format(), description: '', customer: { name: formData.name, email: formData.email, timezone: customerTimezone } }; if (getConfig().project_id) { args.project_id = getConfig().project_id } else { $.extend(true, args, { what: 'Meeting with ' + formData.name, where: 'TBD' }); } args.description += (getConfig().customer_fields.name.title || 'Name') + ': ' + formData.name + '\n'; args.description += (getConfig().customer_fields.name.email || 'Email') + ': ' + formData.email + '\n'; if (getConfig().customer_fields.location) { args.customer.where = formData.location; args.where = formData.location; } if (getConfig().customer_fields.comment) { args.customer.comment = formData.comment; args.description += (getConfig().customer_fields.comment.title || 'Comment') + ': ' + formData.comment + '\n'; } if (getConfig().customer_fields.phone) { args.customer.phone = formData.phone; args.description += (getConfig().customer_fields.phone.title || 'Phone') + ': ' + formData.phone + '\n'; } if (getConfig().customer_fields.voip) { args.customer.voip = formData.voip; args.description += (getConfig().customer_fields.voip.title || 'Voip') + ': ' + formData.voip + '\n'; } // Save custom fields in meta object $.each(getConfig().customer_fields, function(key, field) { if ($.inArray(key, nativeFields) >= 0) return if (field.format === 'checkbox') formData[key] = !!formData[key] args.customer[key] = formData[key] args.description += (getConfig().customer_fields[key].title || key) + ': ' + formData[key] + '\n'; }) if (getConfig().booking.graph === 'group_customer' || getConfig().booking.graph === 'group_customer_payment') { args.related = { owner_booking_id: eventData.booking.id } args.resource_id = eventData.booking.resource.id } else if (typeof eventData.resources === 'undefined' || eventData.resources.length === 0) { throw triggerError(['No resources to pick from when creating booking']); } else { args.resource_id = eventData.resources[0].id } $.extend(true, args, getConfig().booking); utils.doCallback('createBookingStarted', args); var request = sdk .include(getConfig().create_booking_response_include) .createBooking(args); request .then(function(response){ utils.doCallback('createBookingSuccessful', response); }).catch(function(response){ utils.doCallback('createBookingFailed', response); triggerError(['An error with Timekit Create Booking occured', response]); }); return request; }
javascript
{ "resource": "" }
q27329
train
function (response, suppliedConfig) { var remoteConfig = response.data // streamline naming of object keys if (remoteConfig.id) { remoteConfig.project_id = remoteConfig.id delete remoteConfig.id } if (remoteConfig.slug) { remoteConfig.project_slug = remoteConfig.slug delete remoteConfig.slug } // merge with supplied config for overwriting settings var mergedConfig = $.extend(true, {}, remoteConfig, suppliedConfig); utils.logDebug(['Remote config:', remoteConfig]); startWithConfig(mergedConfig) }
javascript
{ "resource": "" }
q27330
train
function(suppliedConfig) { // Handle config and defaults try { config.parseAndUpdate(suppliedConfig); } catch (e) { render.triggerError(e); return this } utils.logDebug(['Final config:', getConfig()]); try { return startRender(); } catch (e) { render.triggerError(e); return this } }
javascript
{ "resource": "" }
q27331
train
function(suppliedConfig) { if (typeof suppliedConfig.sdk === 'undefined') suppliedConfig.sdk = {} if (suppliedConfig.app_key) suppliedConfig.sdk.appKey = suppliedConfig.app_key return $.extend(true, {}, defaultConfig.primary.sdk, suppliedConfig.sdk); }
javascript
{ "resource": "" }
q27332
train
function(suppliedConfig) { suppliedConfig.sdk = prepareSdkConfig(suppliedConfig) return $.extend(true, {}, defaultConfig.primary, suppliedConfig); }
javascript
{ "resource": "" }
q27333
train
function(config) { $.each(config.customer_fields, function (key, field) { if (!defaultConfig.customerFieldsNativeFormats[key]) return config.customer_fields[key] = $.extend({}, defaultConfig.customerFieldsNativeFormats[key], field); }) return config }
javascript
{ "resource": "" }
q27334
train
function (localConfig, propertyName, propertyObject) { var presetCheck = defaultConfig.presets[propertyName][propertyObject]; if (presetCheck) return $.extend(true, {}, presetCheck, localConfig); return localConfig }
javascript
{ "resource": "" }
q27335
train
function (suppliedConfig, urlParams) { $.each(suppliedConfig.customer_fields, function (key) { if (!urlParams['customer.' + key]) return suppliedConfig.customer_fields[key].prefilled = urlParams['customer.' + key]; }); return suppliedConfig }
javascript
{ "resource": "" }
q27336
train
function (evt, data) { // Identify the event type with the nipple's id. type = evt.type + ' ' + data.id + ':' + evt.type; self.trigger(type, data); }
javascript
{ "resource": "" }
q27337
splitLongWord
train
function splitLongWord(word, options) { var wrapCharacters = options.longWordSplit.wrapCharacters || []; var forceWrapOnLimit = options.longWordSplit.forceWrapOnLimit || false; var max = options.wordwrap; var fuseWord = []; var idx = 0; while (word.length > max) { var firstLine = word.substr(0, max); var remainingChars = word.substr(max); var splitIndex = firstLine.lastIndexOf(wrapCharacters[idx]); if (splitIndex > -1) { // We've found a character to split on, store before the split then check if we // need to split again word = firstLine.substr(splitIndex + 1) + remainingChars; fuseWord.push(firstLine.substr(0, splitIndex + 1)); } else { idx++; if (idx >= wrapCharacters.length) { // Cannot split on character, so either split at 'max' or preserve length if (forceWrapOnLimit) { fuseWord.push(firstLine); word = remainingChars; if (word.length > max) { continue; } } else { word = firstLine + remainingChars; if (!options.preserveNewlines) { word += '\n'; } } break; } else { word = firstLine + remainingChars; } } } fuseWord.push(word); return fuseWord.join('\n'); }
javascript
{ "resource": "" }
q27338
ruleSync
train
function ruleSync(filePath) { var ruleId = path.basename(filePath) var result = {} var tests = {} var description var code var tags var name ruleId = ruleId.slice('remark-lint-'.length) code = fs.readFileSync(path.join(filePath, 'index.js'), 'utf-8') tags = dox.parseComments(code)[0].tags description = find(tags, 'fileoverview') name = find(tags, 'module') /* istanbul ignore if */ if (name !== ruleId) { throw new Error(ruleId + ' has an invalid `@module`: ' + name) } /* istanbul ignore if */ if (!description) { throw new Error(ruleId + ' is missing a `@fileoverview`') } description = strip(description) result.ruleId = ruleId result.description = trim(description) result.tests = tests result.filePath = filePath find .all(tags, 'example') .map(strip) .forEach(check) return result function check(example) { var lines = example.split('\n') var value = strip(lines.slice(1).join('\n')) var info var setting var context var name try { info = JSON.parse(lines[0]) } catch (error) { /* istanbul ignore next */ throw new Error( 'Could not parse example in ' + ruleId + ':\n' + error.stack ) } setting = JSON.stringify(info.setting || true) context = tests[setting] name = info.name if (!context) { context = [] tests[setting] = context } if (!info.label) { context[name] = { config: info.config || {}, setting: setting, input: value, output: [] } return } /* istanbul ignore if */ if (info.label !== 'input' && info.label !== 'output') { throw new Error( 'Expected `input` or `ouput` for `label` in ' + ruleId + ', not `' + info.label + '`' ) } if (!context[name]) { context[name] = {config: info.config || {}} } context[name].setting = setting if (info.label === 'output') { value = value.split('\n') } context[name][info.label] = value } }
javascript
{ "resource": "" }
q27339
check
train
function check(node) { var url = node.url var reason if (identifiers.indexOf(url.toLowerCase()) !== -1) { reason = 'Did you mean to use `[' + url + ']` instead of ' + '`(' + url + ')`, a reference?' file.message(reason, node) } }
javascript
{ "resource": "" }
q27340
compare
train
function compare(start, end, max) { var diff = end.line - start.line var lines = Math.abs(diff) - max var reason if (lines > 0) { reason = 'Remove ' + lines + ' ' + plural('line', lines) + ' ' + (diff > 0 ? 'before' : 'after') + ' node' file.message(reason, end) } }
javascript
{ "resource": "" }
q27341
check
train
function check(node) { var initial = start(node).offset var final = end(node).offset if (generated(node)) { return null } return node.lang || /^\s*([~`])\1{2,}/.test(contents.slice(initial, final)) ? 'fenced' : 'indented' }
javascript
{ "resource": "" }
q27342
unDashHyphen
train
function unDashHyphen (str) { return str .trim() .toLowerCase() .replace(/[-_\s]+(.)?/g, function (match, c) { return c ? c.toUpperCase() : ""; }); }
javascript
{ "resource": "" }
q27343
isAllUpperCase
train
function isAllUpperCase (str) { return str .split("") .map(ch => ch.charCodeAt(0)) .every(n => n >= 65 && n <= 90); }
javascript
{ "resource": "" }
q27344
players
train
function players (resp) { return base(resp).map(function (player) { var names = player.displayLastCommaFirst.split(", ").reverse(); return { firstName: names[0].trim(), lastName: (names[1] ? names[1] : "").trim(), playerId: player.personId, teamId: player.teamId, }; }); }
javascript
{ "resource": "" }
q27345
Git
train
function Git (baseDir, ChildProcess, Buffer) { this._baseDir = baseDir; this._runCache = []; this.ChildProcess = ChildProcess; this.Buffer = Buffer; }
javascript
{ "resource": "" }
q27346
train
function (callback) { var plugins = this.internals.plugins; var self = this; return Promise.resolve(Object.keys(APIHooks)) .each(function (hook) { var plugin = plugins.hook(hook); if (!plugin) return; var APIHook = APIHooks[hook].bind(self); return Promise.resolve(plugin) .map(function (plugin) { return plugin[hook](); }) .each(function (args) { return APIHook.apply(self, args); }); }) .asCallback(callback); }
javascript
{ "resource": "" }
q27347
train
function (description, args, type) { var name = args.shift(); this.internals.argv.describe(name, description); for (var i = 0; i < args.length; ++i) { this.internals.argv.alias(args[i], name); } switch (type) { case 'string': this.internals.argv.string(name); break; case 'boolean': this.internals.argv.boolean(name); break; default: return false; } return true; }
javascript
{ "resource": "" }
q27348
train
function (specification, opts, callback) { var executeSync = load('sync'); if (arguments.length > 0) { if (typeof specification === 'string') { this.internals.argv.destination = specification; } if (typeof opts === 'string') { this.internals.migrationMode = opts; this.internals.matching = opts; } else if (typeof opts === 'function') { callback = opts; } } return Promise.fromCallback( function (callback) { executeSync(this.internals, this.config, callback); }.bind(this) ).asCallback(callback); }
javascript
{ "resource": "" }
q27349
train
function (scope, callback) { var executeDown = load('down'); if (typeof scope === 'string') { this.internals.migrationMode = scope; this.internals.matching = scope; } else if (typeof scope === 'function') { callback = scope; } this.internals.argv.count = Number.MAX_VALUE; return Promise.fromCallback( function (callback) { executeDown(this.internals, this.config, callback); }.bind(this) ).asCallback(callback); }
javascript
{ "resource": "" }
q27350
train
function (migrationName, scope, callback) { var executeCreateMigration = load('create-migration'); if (typeof scope === 'function') { callback = scope; } else if (scope) { this.internals.migrationMode = scope; this.internals.matching = scope; } this.internals.argv._.push(migrationName); return Promise.fromCallback( function (callback) { executeCreateMigration(this.internals, this.config, callback); }.bind(this) ).asCallback(callback); }
javascript
{ "resource": "" }
q27351
train
function (dbname, callback) { var executeDB = load('db'); this.internals.argv._.push(dbname); this.internals.mode = 'create'; return Promise.fromCallback( function (callback) { executeDB(this.internals, this.config, callback); }.bind(this) ).asCallback(callback); }
javascript
{ "resource": "" }
q27352
train
function (mode, scope, callback) { var executeSeed = load('seed'); if (scope) { this.internals.migrationMode = scope; this.internals.matching = scope; } this.internals.mode = mode || 'vc'; return Promise.fromCallback( function (callback) { executeSeed(this.internals, this.config, callback); }.bind(this) ).asCallback(callback); }
javascript
{ "resource": "" }
q27353
train
function (specification, scope, callback) { var executeUndoSeed = load('undo-seed'); if (arguments.length > 0) { if (typeof specification === 'number') { this.internals.argv.count = specification; if (scope) { this.internals.migrationMode = scope; this.internals.matching = scope; } } else if (typeof specification === 'string') { this.internals.migrationMode = scope; this.internals.matching = scope; } } return Promise.fromCallback( function (callback) { executeUndoSeed(this.internals, this.config, callback); }.bind(this) ).asCallback(callback); }
javascript
{ "resource": "" }
q27354
SeedLink
train
function SeedLink (driver, internals) { this.seeder = require('./seeder.js')( driver, internals.argv['vcseeder-dir'], true, internals ); this.internals = internals; this.links = []; }
javascript
{ "resource": "" }
q27355
exportToJDL
train
function exportToJDL(jdl, path) { if (!jdl) { throw new Error('A JDLObject has to be passed to be exported.'); } if (!path) { path = './jhipster-jdl.jh'; } fs.writeFileSync(path, jdl.toString()); }
javascript
{ "resource": "" }
q27356
convertEntitiesToJDL
train
function convertEntitiesToJDL(entities, jdl) { if (!entities) { throw new Error('Entities have to be passed to be converted.'); } init(entities, jdl); addEntities(); addRelationshipsToJDL(); return configuration.jdl; }
javascript
{ "resource": "" }
q27357
exportEntitiesInApplications
train
function exportEntitiesInApplications(passedConfiguration) { if (!passedConfiguration || !passedConfiguration.entities) { throw new Error('Entities have to be passed to be exported.'); } let exportedEntities = []; Object.keys(passedConfiguration.applications).forEach(applicationName => { const application = passedConfiguration.applications[applicationName]; const entitiesToExport = getEntitiesToExport(application.entityNames, passedConfiguration.entities); exportedEntities = exportedEntities.concat( exportEntities({ entities: entitiesToExport, forceNoFiltering: passedConfiguration.forceNoFiltering, application: { forSeveralApplications: Object.keys(passedConfiguration.applications).length !== 1, name: application.config.baseName, type: application.config.applicationType } }) ); }); return exportedEntities; }
javascript
{ "resource": "" }
q27358
exportEntities
train
function exportEntities(passedConfiguration) { init(passedConfiguration); createJHipsterJSONFolder( passedConfiguration.application.forSeveralApplications ? configuration.application.name : '' ); if (!configuration.forceNoFiltering) { filterOutUnchangedEntities(); } if (shouldFilterOutEntitiesBasedOnMicroservice()) { filterOutEntitiesByMicroservice(); } writeEntities(passedConfiguration.application.forSeveralApplications ? configuration.application.name : ''); return Object.values(configuration.entities); }
javascript
{ "resource": "" }
q27359
writeEntities
train
function writeEntities(subFolder) { for (let i = 0, entityNames = Object.keys(configuration.entities); i < entityNames.length; i++) { const filePath = path.join(subFolder, toFilePath(entityNames[i])); const entity = updateChangelogDate(filePath, configuration.entities[entityNames[i]]); fs.writeFileSync(filePath, JSON.stringify(entity, null, 4)); } }
javascript
{ "resource": "" }
q27360
writeConfigFile
train
function writeConfigFile(config, yoRcPath = '.yo-rc.json') { let newYoRc = { ...config }; if (FileUtils.doesFileExist(yoRcPath)) { const yoRc = JSON.parse(fs.readFileSync(yoRcPath, { encoding: 'utf-8' })); newYoRc = { ...yoRc, ...config, [GENERATOR_NAME]: { ...yoRc[GENERATOR_NAME], ...config[GENERATOR_NAME] } }; } fs.writeFileSync(yoRcPath, JSON.stringify(newYoRc, null, 2)); }
javascript
{ "resource": "" }
q27361
readFile
train
function readFile(path) { if (!path) { throw new Error('The passed file must not be nil to be read.'); } if (!FileUtils.doesFileExist(path)) { throw new Error(`The passed file '${path}' must exist and must not be a directory to be read.`); } return fs.readFileSync(path, 'utf-8').toString(); }
javascript
{ "resource": "" }
q27362
parse
train
function parse(args) { const merged = merge(defaults(), args); if (!args || !merged.jdlObject || !args.databaseType) { throw new Error('The JDL object and the database type are both mandatory.'); } if (merged.applicationType !== GATEWAY) { checkNoSQLModeling(merged.jdlObject, args.databaseType); } init(merged); initializeEntities(); setOptions(); fillEntities(); setApplicationToEntities(); return entities; }
javascript
{ "resource": "" }
q27363
checkApplication
train
function checkApplication(jdlApplication) { if (!jdlApplication || !jdlApplication.config) { throw new Error('An application must be passed to be validated.'); } applicationConfig = jdlApplication.config; checkForValidValues(); checkForNoDatabaseType(); checkForInvalidDatabaseCombinations(); }
javascript
{ "resource": "" }
q27364
exportApplication
train
function exportApplication(application) { checkForErrors(application); const formattedApplication = setUpApplicationStructure(application); writeConfigFile(formattedApplication); return formattedApplication; }
javascript
{ "resource": "" }
q27365
writeApplicationFileForMultipleApplications
train
function writeApplicationFileForMultipleApplications(application) { const applicationBaseName = application[GENERATOR_NAME].baseName; checkPath(applicationBaseName); createFolderIfNeeded(applicationBaseName); writeConfigFile(application, path.join(applicationBaseName, '.yo-rc.json')); }
javascript
{ "resource": "" }
q27366
convertServerOptionsToJDL
train
function convertServerOptionsToJDL(config, jdl) { const jdlObject = jdl || new JDLObject(); const jhipsterConfig = config || {}; [SKIP_CLIENT, SKIP_SERVER, SKIP_USER_MANAGEMENT].forEach(option => { if (jhipsterConfig[option] === true) { jdlObject.addOption( new JDLUnaryOption({ name: option, value: jhipsterConfig[option] }) ); } }); return jdlObject; }
javascript
{ "resource": "" }
q27367
parseFromConfigurationObject
train
function parseFromConfigurationObject(configuration) { if (!configuration.document) { throw new Error('The parsed JDL content must be passed.'); } init(configuration); fillApplications(); fillDeployments(); fillEnums(); fillClassesAndFields(); fillAssociations(); fillOptions(); return jdlObject; }
javascript
{ "resource": "" }
q27368
checkOptions
train
function checkOptions( { jdlObject, applicationSettings, applicationsPerEntityName } = { applicationSettings: {}, applicationsPerEntityName: {} } ) { if (!jdlObject) { throw new Error('A JDL object has to be passed to check its options.'); } configuration = { jdlObject, applicationSettings, applicationsPerEntityName }; jdlObject.getOptions().forEach(option => { checkOption(option); }); }
javascript
{ "resource": "" }
q27369
formatComment
train
function formatComment(comment) { if (!comment) { return undefined; } const parts = comment.trim().split('\n'); if (parts.length === 1 && parts[0].indexOf('*') !== 0) { return parts[0]; } return parts.reduce((previousValue, currentValue) => { // newlines in the middle of the comment should stay to achieve: // multiline comments entered by user drive unchanged from JDL // studio to generated domain class let delimiter = ''; if (previousValue !== '') { delimiter = '\n'; } return previousValue.concat(delimiter, currentValue.trim().replace(/[*]*\s*/, '')); }, ''); }
javascript
{ "resource": "" }
q27370
createDirectory
train
function createDirectory(directory) { if (!directory) { throw new Error('A directory must be passed to be created.'); } const statObject = getStatObject(directory); if (statObject && statObject.isFile()) { throw new Error(`The directory to create '${directory}' is a file.`); } fse.ensureDirSync(directory); }
javascript
{ "resource": "" }
q27371
writeDeploymentConfigs
train
function writeDeploymentConfigs(deployment) { const folderName = deployment[GENERATOR_NAME].deploymentType; checkPath(folderName); createFolderIfNeeded(folderName); writeConfigFile(deployment, path.join(folderName, '.yo-rc.json')); }
javascript
{ "resource": "" }
q27372
train
function(target) { if(target.length > 999) return fuzzysort.prepare(target) // don't cache huge targets var targetPrepared = preparedCache.get(target) if(targetPrepared !== undefined) return targetPrepared targetPrepared = fuzzysort.prepare(target) preparedCache.set(target, targetPrepared) return targetPrepared }
javascript
{ "resource": "" }
q27373
negotiation
train
function negotiation(opt) { var self = { type : new type.UInt8(), flag : new type.UInt8(), length : new type.UInt16Le(0x0008, { constant : true }), result : new type.UInt32Le() }; return new type.Component(self, opt); }
javascript
{ "resource": "" }
q27374
clientConnectionRequestPDU
train
function clientConnectionRequestPDU(opt, cookie) { var self = { len : new type.UInt8(function() { return new type.Component(self).size() - 1; }), code : new type.UInt8(MessageType.X224_TPDU_CONNECTION_REQUEST, { constant : true }), padding : new type.Component([new type.UInt16Le(), new type.UInt16Le(), new type.UInt8()]), cookie : cookie || new type.Factory( function (s) { var offset = 0; while (true) { var token = s.buffer.readUInt16LE(s.offset + offset); if (token === 0x0a0d) { self.cookie = new type.BinaryString(null, { readLength : new type.CallableValue(offset + 2) }).read(s); return; } else { offset += 1; } } }, { conditional : function () { return self.len.value > 14; }}), protocolNeg : negotiation({ optional : true }) }; return new type.Component(self, opt); }
javascript
{ "resource": "" }
q27375
serverConnectionConfirm
train
function serverConnectionConfirm(opt) { var self = { len : new type.UInt8(function() { return new type.Component(self).size() - 1; }), code : new type.UInt8(MessageType.X224_TPDU_CONNECTION_CONFIRM, { constant : true }), padding : new type.Component([new type.UInt16Le(), new type.UInt16Le(), new type.UInt8()]), protocolNeg : negotiation({ optional : true }) }; return new type.Component(self, opt); }
javascript
{ "resource": "" }
q27376
x224DataHeader
train
function x224DataHeader() { var self = { header : new type.UInt8(2), messageType : new type.UInt8(MessageType.X224_TPDU_DATA, { constant : true }), separator : new type.UInt8(0x80, { constant : true }) }; return new type.Component(self); }
javascript
{ "resource": "" }
q27377
X224
train
function X224(transport) { this.transport = transport; this.requestedProtocol = Protocols.PROTOCOL_SSL; this.selectedProtocol = Protocols.PROTOCOL_SSL; var self = this; this.transport.on('close', function() { self.emit('close'); }).on('error', function (err) { self.emit('error', err); }); }
javascript
{ "resource": "" }
q27378
Server
train
function Server(transport, keyFilePath, crtFilePath) { X224.call(this, transport); this.keyFilePath = keyFilePath; this.crtFilePath = crtFilePath; var self = this; this.transport.once('data', function (s) { self.recvConnectionRequest(s); }); }
javascript
{ "resource": "" }
q27379
BufferLayer
train
function BufferLayer(socket) { //for ssl connection this.securePair = null; this.socket = socket; var self = this; // bind event this.socket.on('data', function(data) { try { self.recv(data); } catch(e) { self.socket.destroy(); self.emit('error', e); } }).on('close', function() { self.emit('close'); }).on('error', function (err) { self.emit('error', err); }); //buffer data this.buffers = []; this.bufferLength = 0; //expected size this.expectedSize = 0; }
javascript
{ "resource": "" }
q27380
readObjectIdentifier
train
function readObjectIdentifier(s, oid) { var size = readLength(s); if(size !== 5) { return false; } var a_oid = [0, 0, 0, 0, 0, 0]; var t12 = new type.UInt8().read(s).value; a_oid[0] = t12 >> 4; a_oid[1] = t12 & 0x0f; a_oid[2] = new type.UInt8().read(s).value; a_oid[3] = new type.UInt8().read(s).value; a_oid[4] = new type.UInt8().read(s).value; a_oid[5] = new type.UInt8().read(s).value; for(var i in oid) { if(oid[i] !== a_oid[i]) return false; } return true; }
javascript
{ "resource": "" }
q27381
readNumericString
train
function readNumericString(s, minValue) { var length = readLength(s); length = (length + minValue + 1) / 2; s.readPadding(length); }
javascript
{ "resource": "" }
q27382
bnToBuffer
train
function bnToBuffer(trimOrSize) { var res = new Buffer(this.toByteArray()); if (trimOrSize === true && res[0] === 0) { res = res.slice(1); } else if (_.isNumber(trimOrSize)) { if (res.length > trimOrSize) { for (var i = 0; i < res.length - trimOrSize; i++) { if (res[i] !== 0) { return null; } } return res.slice(res.length - trimOrSize); } else if (res.length < trimOrSize) { var padded = new Buffer(trimOrSize); padded.fill(0, 0, trimOrSize - res.length); res.copy(padded, trimOrSize - res.length); return padded; } } return res; }
javascript
{ "resource": "" }
q27383
Global
train
function Global(transport, fastPathTransport) { this.transport = transport; this.fastPathTransport = fastPathTransport; // must be init via connect event this.userId = 0; this.serverCapabilities = []; this.clientCapabilities = []; }
javascript
{ "resource": "" }
q27384
decompress
train
function decompress (bitmap) { var fName = null; switch (bitmap.bitsPerPixel.value) { case 15: fName = 'bitmap_decompress_15'; break; case 16: fName = 'bitmap_decompress_16'; break; case 24: fName = 'bitmap_decompress_24'; break; case 32: fName = 'bitmap_decompress_32'; break; default: throw 'invalid bitmap data format'; } var input = new Uint8Array(bitmap.bitmapDataStream.value); var inputPtr = rle._malloc(input.length); var inputHeap = new Uint8Array(rle.HEAPU8.buffer, inputPtr, input.length); inputHeap.set(input); var ouputSize = bitmap.width.value * bitmap.height.value * 4; var outputPtr = rle._malloc(ouputSize); var outputHeap = new Uint8Array(rle.HEAPU8.buffer, outputPtr, ouputSize); var res = rle.ccall(fName, 'number', ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number'], [outputHeap.byteOffset, bitmap.width.value, bitmap.height.value, bitmap.width.value, bitmap.height.value, inputHeap.byteOffset, input.length] ); var output = new Uint8ClampedArray(outputHeap.buffer, outputHeap.byteOffset, ouputSize); rle._free(inputPtr); rle._free(outputPtr); return output; }
javascript
{ "resource": "" }
q27385
RdpClient
train
function RdpClient(config) { config = config || {}; this.connected = false; this.bufferLayer = new layer.BufferLayer(new net.Socket()); this.tpkt = new TPKT(this.bufferLayer); this.x224 = new x224.Client(this.tpkt); this.mcs = new t125.mcs.Client(this.x224); this.sec = new pdu.sec.Client(this.mcs, this.tpkt); this.global = new pdu.global.Client(this.sec, this.sec); // config log level log.level = log.Levels[config.logLevel || 'INFO'] || log.Levels.INFO; // credentials if (config.domain) { this.sec.infos.obj.domain.value = new Buffer(config.domain + '\x00', 'ucs2'); } if (config.userName) { this.sec.infos.obj.userName.value = new Buffer(config.userName + '\x00', 'ucs2'); } if (config.password) { this.sec.infos.obj.password.value = new Buffer(config.password + '\x00', 'ucs2'); } if (config.enablePerf) { this.sec.infos.obj.extendedInfo.obj.performanceFlags.value = pdu.sec.PerfFlag.PERF_DISABLE_WALLPAPER | pdu.sec.PerfFlag.PERF_DISABLE_MENUANIMATIONS | pdu.sec.PerfFlag.PERF_DISABLE_CURSOR_SHADOW | pdu.sec.PerfFlag.PERF_DISABLE_THEMING | pdu.sec.PerfFlag.PERF_DISABLE_FULLWINDOWDRAG; } if (config.autoLogin) { this.sec.infos.obj.flag.value |= pdu.sec.InfoFlag.INFO_AUTOLOGON; } if (config.screen && config.screen.width && config.screen.height) { this.mcs.clientCoreData.obj.desktopWidth.value = config.screen.width; this.mcs.clientCoreData.obj.desktopHeight.value = config.screen.height; } log.info('screen ' + this.mcs.clientCoreData.obj.desktopWidth.value + 'x' + this.mcs.clientCoreData.obj.desktopHeight.value); // config keyboard layout switch (config.locale) { case 'fr': log.info('french keyboard layout'); this.mcs.clientCoreData.obj.kbdLayout.value = t125.gcc.KeyboardLayout.FRENCH; break; case 'en': default: log.info('english keyboard layout'); this.mcs.clientCoreData.obj.kbdLayout.value = t125.gcc.KeyboardLayout.US; } //bind all events var self = this; this.global.on('connect', function () { self.connected = true; self.emit('connect'); }).on('session', function () { self.emit('session'); }).on('close', function () { self.connected = false; self.emit('close'); }).on('bitmap', function (bitmaps) { for(var bitmap in bitmaps) { var bitmapData = bitmaps[bitmap].obj.bitmapDataStream.value; var isCompress = bitmaps[bitmap].obj.flags.value & pdu.data.BitmapFlag.BITMAP_COMPRESSION; if (isCompress && config.decompress) { bitmapData = decompress(bitmaps[bitmap].obj); isCompress = false; } self.emit('bitmap', { destTop : bitmaps[bitmap].obj.destTop.value, destLeft : bitmaps[bitmap].obj.destLeft.value, destBottom : bitmaps[bitmap].obj.destBottom.value, destRight : bitmaps[bitmap].obj.destRight.value, width : bitmaps[bitmap].obj.width.value, height : bitmaps[bitmap].obj.height.value, bitsPerPixel : bitmaps[bitmap].obj.bitsPerPixel.value, isCompress : isCompress, data : bitmapData }); } }).on('error', function (err) { log.error(err.code + '(' + err.message + ')\n' + err.stack); if (err instanceof error.FatalError) { throw err; } else { self.emit('error', err); } }); }
javascript
{ "resource": "" }
q27386
RdpServer
train
function RdpServer(config, socket) { if (!(config.key && config.cert)) { throw new error.FatalError('NODE_RDP_PROTOCOL_RDP_SERVER_CONFIG_MISSING', 'missing cryptographic tools') } this.connected = false; this.bufferLayer = new layer.BufferLayer(socket); this.tpkt = new TPKT(this.bufferLayer); this.x224 = new x224.Server(this.tpkt, config.key, config.cert); this.mcs = new t125.mcs.Server(this.x224); }
javascript
{ "resource": "" }
q27387
rdpInfos
train
function rdpInfos(extendedInfoConditional) { var self = { codePage : new type.UInt32Le(), flag : new type.UInt32Le(InfoFlag.INFO_MOUSE | InfoFlag.INFO_UNICODE | InfoFlag.INFO_LOGONNOTIFY | InfoFlag.INFO_LOGONERRORS | InfoFlag.INFO_DISABLECTRLALTDEL | InfoFlag.INFO_ENABLEWINDOWSKEY), cbDomain : new type.UInt16Le(function() { return self.domain.size() - 2; }), cbUserName : new type.UInt16Le(function() { return self.userName.size() - 2; }), cbPassword : new type.UInt16Le(function() { return self.password.size() - 2; }), cbAlternateShell : new type.UInt16Le(function() { return self.alternateShell.size() - 2; }), cbWorkingDir : new type.UInt16Le(function() { return self.workingDir.size() - 2; }), domain : new type.BinaryString(new Buffer('\x00', 'ucs2'),{ readLength : new type.CallableValue(function() { return self.cbDomain.value + 2; })}), userName : new type.BinaryString(new Buffer('\x00', 'ucs2'), { readLength : new type.CallableValue(function() { return self.cbUserName.value + 2; })}), password : new type.BinaryString(new Buffer('\x00', 'ucs2'), { readLength : new type.CallableValue(function () { return self.cbPassword.value + 2; })}), alternateShell : new type.BinaryString(new Buffer('\x00', 'ucs2'), { readLength : new type.CallableValue(function() { return self.cbAlternateShell.value + 2; })}), workingDir : new type.BinaryString(new Buffer('\x00', 'ucs2'), { readLength : new type.CallableValue(function() { return self.cbWorkingDir.value + 2; })}), extendedInfo : rdpExtendedInfos({ conditional : extendedInfoConditional }) }; return new type.Component(self); }
javascript
{ "resource": "" }
q27388
rdpExtendedInfos
train
function rdpExtendedInfos(opt) { var self = { clientAddressFamily : new type.UInt16Le(AfInet.AfInet), cbClientAddress : new type.UInt16Le(function() { return self.clientAddress.size(); }), clientAddress : new type.BinaryString(new Buffer('\x00', 'ucs2'),{ readLength : new type.CallableValue(function() { return self.cbClientAddress; }) }), cbClientDir : new type.UInt16Le(function() { return self.clientDir.size(); }), clientDir : new type.BinaryString(new Buffer('\x00', 'ucs2'), { readLength : new type.CallableValue(function() { return self.cbClientDir; }) }), clientTimeZone : new type.BinaryString(new Buffer(Array(172 + 1).join("\x00"))), clientSessionId : new type.UInt32Le(), performanceFlags : new type.UInt32Le() }; return new type.Component(self, opt); }
javascript
{ "resource": "" }
q27389
securityHeader
train
function securityHeader() { var self = { securityFlag : new type.UInt16Le(), securityFlagHi : new type.UInt16Le() }; return new type.Component(self); }
javascript
{ "resource": "" }
q27390
Client
train
function Client(transport, fastPathTransport) { Sec.call(this, transport, fastPathTransport); // for basic RDP layer (in futur) this.enableSecureCheckSum = false; var self = this; this.transport.on('connect', function(gccClient, gccServer, userId, channels) { self.connect(gccClient, gccServer, userId, channels); }).on('close', function() { self.emit('close'); }).on('error', function (err) { self.emit('error', err); }); }
javascript
{ "resource": "" }
q27391
Asn1Tag
train
function Asn1Tag(tagClass, tagFormat, tagNumber) { this.tagClass = tagClass; this.tagFormat = tagFormat; this.tagNumber = tagNumber; }
javascript
{ "resource": "" }
q27392
Stream
train
function Stream(i) { this.offset = 0; if (i instanceof Buffer) { this.buffer = i; } else { this.buffer = new Buffer(i || 8192); } }
javascript
{ "resource": "" }
q27393
Type
train
function Type(opt) { CallableValue.call(this); this.opt = opt || {}; this.isReaded = false; this.isWritten = false; }
javascript
{ "resource": "" }
q27394
SingleType
train
function SingleType(value, nbBytes, readBufferCallback, writeBufferCallback, opt){ Type.call(this, opt); this.value = value || 0; this.nbBytes = nbBytes; this.readBufferCallback = readBufferCallback; this.writeBufferCallback = writeBufferCallback; }
javascript
{ "resource": "" }
q27395
UInt8
train
function UInt8(value, opt) { SingleType.call(this, value, 1, Buffer.prototype.readUInt8, Buffer.prototype.writeUInt8, opt); }
javascript
{ "resource": "" }
q27396
UInt16Le
train
function UInt16Le(value, opt) { SingleType.call(this, value, 2, Buffer.prototype.readUInt16LE, Buffer.prototype.writeUInt16LE, opt); }
javascript
{ "resource": "" }
q27397
UInt16Be
train
function UInt16Be(value, opt) { SingleType.call(this, value, 2, Buffer.prototype.readUInt16BE, Buffer.prototype.writeUInt16BE, opt); }
javascript
{ "resource": "" }
q27398
UInt32Le
train
function UInt32Le(value, opt) { SingleType.call(this, value, 4, Buffer.prototype.readUInt32LE, Buffer.prototype.writeUInt32LE, opt); }
javascript
{ "resource": "" }
q27399
UInt32Be
train
function UInt32Be(value, opt) { SingleType.call(this, value, 4, Buffer.prototype.readUInt32BE, Buffer.prototype.writeUInt32BE, opt); }
javascript
{ "resource": "" }