{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n `\n\n res.send(output);\n})\n\napp.get( \"/posts/:id\", (req, res) => {\n const id = req.params.id;\n const post = posts.find(id);\n\n if (!post.id) {\n throw new Error('Not Found')\n }\n\n const output =`\n \n \n Wizard-News\n \n \n \n
Wizard News
\n
\n

\n \n ${post.title} \n
\n By: ${post.name} | ${post.date}\n
\n

\n
${post.content}
\n
\n \n `\n\n res.send(output);\n})\n\napp.use(function (err, req, res, next) {\n console.error(err.stack);\n res.status(404);\n const html = `\n \n \n Wizard News\n \n \n \n
Wizard News
\n
\n

404

\n

Accio Page! 🧙‍♀️ ... Page Not Found

\n
\n \n `\n res.send(html);\n})\n\napp.listen(PORT, () => {\n console.log(`App listening in port ${PORT}`);\n});\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252916,"cells":{"blob_id":{"kind":"string","value":"a6fd1d7d00df3d5f28630362bccdf10756c5319a"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"denniswong0106/lotide"},"path":{"kind":"string","value":"/test/countLettersTest.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1206,"string":"1,206"},"score":{"kind":"number","value":3.21875,"string":"3.21875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"const countLetters = require('../countLetters');\nconst assert = require('chai').assert;\n\ndescribe('#countLetters',() => {\n const sentence = 'hello darkness my old friend';\n console.log('const sentence = ', sentence);\n it('it should return 2 if given countLetters(sentence)[\"n\"]', () => {\n let actualOutput = countLetters(sentence)[\"n\"];\n let expectedOutput = 2;\n assert.equal(actualOutput, expectedOutput);\n })\n it('it should return undefined if given countLetters(sentence)[\"z\"]', ()=> {\n let actualOutput = countLetters(sentence)[\"z\"];\n let expectedOutput = undefined;\n assert.equal(actualOutput, expectedOutput);\n })\n console.log('#OutputObject', {\n h: 1,\n e: 3,\n l: 3,\n o: 2,\n ' ': 4,\n d: 3,\n a: 1,\n r: 2,\n k: 1,\n n: 2,\n s: 2,\n m: 1,\n y: 1,\n f: 1,\n i: 1\n }\n )\n it('it should return #OutputObject if given sentence', ()=> {\n let actualOutput = countLetters(sentence);\n let expectedOutput = {\n h: 1,\n e: 3,\n l: 3,\n o: 2,\n ' ': 4,\n d: 3,\n a: 1,\n r: 2,\n k: 1,\n n: 2,\n s: 2,\n m: 1,\n y: 1,\n f: 1,\n i: 1\n };\n assert.deepEqual(actualOutput, expectedOutput);\n })\n});"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252917,"cells":{"blob_id":{"kind":"string","value":"af2ad42a1cf37efdc8c7ea32fe9d3d201188ed96"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"Delpire/Delpire.github.io"},"path":{"kind":"string","value":"/projects/heliattack/background.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2698,"string":"2,698"},"score":{"kind":"number","value":3.015625,"string":"3.015625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\r\nvar LEVEL_LENGTH = [3000, 6000, 6000]\r\n\r\n// Background class\r\n//----------------------------------\r\nvar Background = function(game, x, y) {\r\n this.game = game;\r\n this.back_x = x;\r\n\tthis.mid_x = x;\r\n\tthis.front_x = x;\r\n};\r\n\r\nBackground.prototype = {\r\n\r\n\r\n render: function(context) {\r\n \r\n context.save();\r\n \r\n // Draw the background.\r\n context.drawImage(Resource.Image.levels[this.game.level], this.back_x, 0, 800, 480, 0, 0, 800, 480);\r\n \r\n // If mid_x is 3000, there is no longer a need to draw from the source twice.\r\n // Reset mid_x, allowing the render to draw from the beginning of the image again.\r\n if(this.mid_x >= LEVEL_LENGTH[this.game.level]){\r\n this.mid_x = 0;\r\n }\r\n \r\n // If out mid_x is past 2200, it will draw past the image.\r\n // Draw to the end of the image, and from there draw the beginning\r\n // of the image.\r\n if(this.mid_x > LEVEL_LENGTH[this.game.level] - 800){\r\n context.drawImage(Resource.Image.levels[this.game.level], this.mid_x, 480, LEVEL_LENGTH[this.game.level] - this.mid_x, 480, 0, 0, LEVEL_LENGTH[this.game.level] - this.mid_x, 480);\r\n context.drawImage(Resource.Image.levels[this.game.level], 0, 480, 800, 480, LEVEL_LENGTH[this.game.level] - this.mid_x, 0, 800, 480);\r\n }\r\n else{\r\n // Draw the mid ground.\r\n context.drawImage(Resource.Image.levels[this.game.level], this.mid_x, 480, 800, 480, 0, 0, 800, 480);\r\n }\r\n\r\n // If front_x is 3000, there is no longer a need to draw from the source twice.\r\n // Reset front_x, allowing the render to draw from the beginning of the image again.\r\n if(this.front_x >= LEVEL_LENGTH[this.game.level]){\r\n this.front_x = 0;\r\n }\r\n\r\n // If out front_x is past 2200, it will draw past the image.\r\n // Draw to the end of the image, and from there draw the beginning\r\n // of the image.\r\n if(this.front_x > LEVEL_LENGTH[this.game.level] - 800){\r\n context.drawImage(Resource.Image.levels[this.game.level], this.front_x, 960, LEVEL_LENGTH[this.game.level] - this.front_x, 480, 0, 0, LEVEL_LENGTH[this.game.level] - this.front_x, 480);\r\n context.drawImage(Resource.Image.levels[this.game.level], 0, 960, 800, 480, LEVEL_LENGTH[this.game.level] - this.front_x, 0, 800, 480);\r\n }\r\n else{\r\n // Draw the foreground.\r\n context.drawImage(Resource.Image.levels[this.game.level], this.front_x, 960, 800, 480, 0, 0, 800, 480);\r\n \r\n }\r\n \r\n context.restore();\r\n\t\r\n },\r\n \r\n update: function(){\r\n \r\n this.back_x += 5;\r\n this.mid_x += 8;\r\n this.front_x += 13;\r\n \r\n },\r\n \r\n nextLevel: function(){\r\n \r\n this.back_x = 0;\r\n\t this.mid_x = 0;\r\n\t this.front_x = 0;\r\n \r\n }\r\n};"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252918,"cells":{"blob_id":{"kind":"string","value":"215fa332fa71ce07b5257dfbebd0b47549a22b71"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"cadencegail/cadencegail.github.io"},"path":{"kind":"string","value":"/mashUp/mashup-gh-pages/mashup.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":6561,"string":"6,561"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"//FACEBOOK\n\n\n\n// This is called with the results from from FB.getLoginStatus().\nfunction statusChangeCallback(response) {\n console.log('statusChangeCallback');\n console.log(response);\n // The response object is returned with a status field that lets the\n // app know the current login status of the person.\n // Full docs on the response object can be found in the documentation\n // for FB.getLoginStatus().\n if (response.status === 'connected') {\n // Logged into your app and Facebook.\n testAPI();\n FB.api(\"/me/home\",\n {\n \"with\": \"location\"\n },\n\n function(response) {\n console.log(response);\n if (response && !response.error) {\n\n var waldo = {\n \tlat: Math.random() * 170 - 85,\n \tlng: Math.random() * 360 - 180,\n \tfriendname: \"Waldo\",\n \tfriendid:\"whereswaldo\",\n \tplacename:\"Waldo's place\",\n \tmessage: \"You found me!\"\n }\n \n markers = [waldo];\n\n for (var i in response['data']) {\n\n friendlocation = {\n lat: response.data[i].place.location.latitude,\n lng: response.data[i].place.location.longitude,\n friendname: response.data[i].from.name,\n friendid: response.data[i].from.id,\n placename: response.data[i].place.name\n }\n\n if (response.data[i].hasOwnProperty('story')) {\n friendlocation.message = '\"'+response.data[i].story+'\"';\n }\n else if (response.data[i].hasOwnProperty('message')) {\n friendlocation.message = '\"'+response.data[i].message+'\"';\n }\n else {\n friendlocation.message = \"\";\n }\n\n if (response.data[i].hasOwnProperty('picture')) {\n friendlocation.picture = response.data[i].picture;\n }\n markers.push(friendlocation);\n }\n loadMarkers(markers);\n }\n }\n );\n\n } else if (response.status === 'not_authorized') {\n // The person is logged into Facebook, but not your app.\n document.getElementById('status').innerHTML = 'Log in ' +\n 'to find your friends!';\n } else {\n // The person is not logged into Facebook, so we're not sure if\n // they are logged into this app or not.\n document.getElementById('status').innerHTML = 'Log in ' +\n 'to find your friends!';\n }\n}\n\n// This function is called when someone finishes with the Login\n// Button. See the onlogin handler attached to it in the sample\n// code below.\nfunction checkLoginState() {\n FB.getLoginStatus(function(response) {\n statusChangeCallback(response);\n });\n}\n\nwindow.fbAsyncInit = function() {\n FB.init({\n appId : '1396726507284343',\n cookie : true, // enable cookies to allow the server to access \n // the session\n xfbml : true, // parse social plugins on this page\n version : 'v2.1' // use version 2.1\n });\n\n // Now that we've initialized the JavaScript SDK, we call \n // FB.getLoginStatus(). This function gets the state of the\n // person visiting this page and can return one of three states to\n // the callback you provide. They can be:\n //\n // 1. Logged into your app ('connected')\n // 2. Logged into Facebook, but not your app ('not_authorized')\n // 3. Not logged into Facebook and can't tell if they are logged into\n // your app or not.\n //\n // These three cases are handled in the callback function.\n\n FB.getLoginStatus(function(response) {\n console.log(response);\n statusChangeCallback(response);\n });\n \n FB.Event.subscribe('auth.logout', logout_event);\n\n};\n\n\n\n// Load the SDK asynchronously\n(function(d, s, id) {\n var js, fjs = d.getElementsByTagName(s)[0];\n if (d.getElementById(id)) return;\n js = d.createElement(s); js.id = id;\n js.src = \"https://connect.facebook.net/en_US/sdk.js\";\n fjs.parentNode.insertBefore(js, fjs);\n}(document, 'script', 'facebook-jssdk'));\n\n// Here we run a very simple test of the Graph API after login is\n// successful. See statusChangeCallback() for when this call is made.\nfunction testAPI() {\n \n console.log('Welcome! Fetching your information.... ');\n FB.api('/me', function(response) {\n console.log('Successful login for: ' + response.name);\n document.getElementById('status').innerHTML =\n 'Where\\'s Waldo?';\n });\n}\n\nvar logout_event = function(response) {\n\tconsole.log(\"WE ARE HERE\");\n\tvar myMap = document.getElementById(\"map-canvas\");\n\tvar myBody = document.getElementById(\"map\");\n\tmyBody.removeChild(myMap);\n\tmyBody.innerHTML += \"
\";\n\tinitialize();\n}\n// GOOGLE MAPS\n\nfunction initialize() {\n var mapOptions = {\n center: { lat: 0, lng: 0},\n zoom: 0\n };\n map = new google.maps.Map(document.getElementById('map-canvas'),\n mapOptions);\n}\n\ngoogle.maps.event.addDomListener(window, 'load', initialize);\n\nfunction loadMarkers(markers) {\n\n var bounds = new google.maps.LatLngBounds();\n \n// Display multiple markers on a map\n var infoWindow = new google.maps.InfoWindow(), marker, i;\n var infoWindowContent = [];\n\n for (i = 0; i < markers.length; i++) {\n\n var str = '
' +\n ''+\n ''+\n '

'+markers[i].friendname+'

' +\n '
'+\n '

' + markers[i].message + '

'\n\n if (markers[i].hasOwnProperty('picture')) {\n str += ''\n }\n \n infoWindowContent.push(str);\n }\n\n// Loop through our array of markers & place each one on the map \nfor( i = 0; i < markers.length; i++ ) {\n\n var position = new google.maps.LatLng(markers[i].lat, markers[i].lng);\n bounds.extend(position);\n\n marker = new google.maps.Marker({\n position: position,\n map: map,\n title: markers[i].placename\n });\n \n // Allow each marker to have an info window \n\n google.maps.event.addListener(marker, 'click', (function(marker, i) {\n return function() {\n infoWindow.setContent(infoWindowContent[i]);\n infoWindow.open(map, marker);\n }\n })(marker, i));\n\n // Automatically center the map fitting all markers on the screen\n map.fitBounds(bounds);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252919,"cells":{"blob_id":{"kind":"string","value":"77fc8475742fc00c590cf0d0d6c4493ffb3d5aac"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"Indre101/Indre101.github.io"},"path":{"kind":"string","value":"/Door_game/js/script.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":12876,"string":"12,876"},"score":{"kind":"number","value":3.109375,"string":"3.109375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"const landingPageContainer = document.getElementById(\"landingPageContainer\");\nconst startGamePage = document.getElementById(\"startGamePage\");\nconst popUpInstructionsContainer = document.getElementById(\"popUpInstructionsContainer\");\nconst gameContainer = document.querySelector(\".body\");\nconst startButton = document.getElementById(\"startButton\");\nconst infoButtonContainer = document.getElementById(\"infoButtonContainer\");\nconst returnButtonContainer = document.getElementById(\"returnButtonContainer\");\n\n\nlet state = \"\";\nlet openDoorsCount = 0;\nlet lives = 3;\nlet score = 0;\n\n// AUDIO\nconst backgroundSound = new Audio(\"./audio/backgroundSound.mp3\");\n\n\n\n\nfunction randomNumberGenerator(l) {\n\n let n = Math.floor(Math.random() * l.length)\n\n return n\n\n}\n\n// chaning background image \nfunction changeBackground(x, u) {\n\n x.style.backgroundImage = u;\n\n}\n\n\n// function to toggle classes\n\nfunction toggleClasses(x, c) {\n x.classList.toggle(c)\n\n}\n\n\nfunction addClass(x, a) {\n\n x.classList.add(a)\n\n}\n\nfunction removeClass(x, a) {\n\n x.classList.remove(a);\n\n}\n\n// function to clear img src;\n\nfunction clearImgSrc(x) {\n x.src = \"\";\n\n}\n\n// class variables\n\nlet dBlock = \"d-block\";\nlet dNone = \"d-none\";\n\n\n// \nstartButton.onclick = function () {\n\n\n // start page changes to the game beginng\n let url1 = \"url('./images/images/bg_2.jpg')\"\n changeBackground(gameContainer, url1);\n toggleClasses(landingPageContainer, dNone);\n toggleClasses(startGamePage, dBlock);\n toggleClasses(startGamePage, dNone);\n\n // assigns first level img\n assignImage();\n // \n\n\n}\n\n// instruction button \n\ninfoButtonContainer.onclick = function () {\n toggleClasses(popUpInstructionsContainer, dNone);\n\n}\n\n\n// TRANSITION FUNCTION FOR BUTTONS ON HOVER\nfunction mouseOverAndOut(triggerElement, changingElement, className) {\n\n triggerElement.onmouseover = function () {\n\n addClass(changingElement, className)\n\n }\n\n\n\n triggerElement.onmouseout = function () {\n\n removeClass(changingElement, className)\n\n\n }\n}\n\n\n\nmouseOverAndOut(returnButtonContainer, document.querySelector(\".returnButton\"), \"returnButtonHover\")\nmouseOverAndOut(infoButtonContainer, document.getElementById(\"infoButtonBg\"), \"infoButtonHover\")\nmouseOverAndOut(document.getElementById(\"soundContainer\"), document.querySelector(\".soundBgMain\"), \"soundBgHover\")\nmouseOverAndOut(document.getElementById(\"gotIt\"), document.querySelector(\".gotItbg\"), \"gotItHover\")\n\n\n\n\n\n// MUSIC CONTROLS\nlet clickCount = 0\n\n\ndocument.getElementById(\"soundContainer\").onclick = function () {\n\n clickCount++;\n\n document.querySelector(\".soundIconMain\").src = \"./images/buttons_icons/sound_off.svg\";\n\n\n\n backgroundSound.addEventListener('ended', function () {\n this.currentTime = 0;\n this.play();\n }, false);\n backgroundSound.play();\n\n\n if (clickCount === 2) {\n clickCount = 0;\n document.querySelector(\".soundIconMain\").src = \"./images/buttons_icons/sound_on.svg\";\n backgroundSound.pause();\n\n }\n}\n\n\n// return button inside pup up instructions \n\nreturnButtonContainer.onclick = function () {\n toggleClasses(popUpInstructionsContainer, dNone);\n\n}\n\n\n//FUNCTION TO ADD THE DOORS \n\n\n// declared variables for function to add another column once level up\nconst htmlColumn = window.getComputedStyle(document.querySelector(\"html\"));\nconst doorContainer = document.getElementById(\"styleOftheDoorContainer\");\n\n\nconst colNum = parseInt(htmlColumn.getPropertyValue(\"--colNum\"));\nlet columnNumber = colNum\n\n\n\n// SELECT ALL \n\nfunction selectAllQuery(c) {\n let nodeArray = document.querySelectorAll(c);\n return nodeArray;\n\n}\n\n\n// function to add another grid and another column and frame-door element \nfunction winScenario() {\n\n\n\n columnNumber++\n document.documentElement.style.setProperty(\"--colNum\", columnNumber);\n\n\n let elmnt = document.querySelector(\".entrance\");\n let cln = elmnt.cloneNode(true);\n doorContainer.appendChild(cln);\n cln.querySelectorAll('img')[3].classList.remove(\"door-animation\");\n cln.querySelectorAll('img')[3].style.pointerEvents = \"auto\";\n\n\n\n let doorsOpeningNew = selectAllQuery(\".open\")\n let doorsOpeningArr = Array.prototype.slice.call(doorsOpeningNew);\n doorsOpeningFunction(doorsOpeningNew, doorsOpeningArr)\n\n\n}\n\n\n\nlet doorsOpening = selectAllQuery(\".open\");\n\nlet imgBehidDoors = selectAllQuery(\".imgBehidDoors\")\n\nlet doorsOpeningArr = Array.prototype.slice.call(doorsOpening);\n\n\n\n\n\n\n\n\n\n// function to assign images\n\nlet inf1 = \"./images/images/in_1.png\";\nlet inf2 = \"./images/images/in_2.png\";\n\n\nfunction selectAll(h) {\n\n let i = document.querySelectorAll(h);\n return i;\n}\n\nlet goodImg = [\"./images/images/bunny_1.png\", \"./images/images/bunny_2.png\", \"./images/images/puppy_1.png\"];\nlet messageSrcArr = [\"./images/images/message_1.png\", \"./images/images/message_2.png\", \"./images/images/message_3.png\", \"./images/images/message_4.png\"]\nlet looseImg = [inf1, inf2];\n\n\nfunction assignImage() {\n\n let i = selectAllQuery(\".imgBehidDoors\");\n\n i.forEach((e) => {\n\n // e.src === \"#\"\n e.removeAttribute('src')\n })\n\n i[randomNumberGenerator(i)].src = goodImg[randomNumberGenerator(goodImg)]\n\n let behidDoorsNumber_2 = randomNumberGenerator(imgBehidDoors);\n\n i.forEach((e) => {\n\n if (e.src === \"\") {\n\n e.src = looseImg[randomNumberGenerator(looseImg)]\n\n }\n\n\n })\n\n\n}\n\n// function for the imgBehindDoors when there is four doors\n\nfunction assignImageIfTwoCilckableImg() {\n let i = selectAllQuery(\".imgBehidDoors\");\n\n i.forEach((e) => {\n e.removeAttribute('src')\n })\n\n\n let behidDoorsNumber_2 = randomNumberGenerator(i)\n let behidDoorsNumber = randomNumberGenerator(i)\n\n\n do {\n behidDoorsNumber_2 = randomNumberGenerator(i);\n } while (behidDoorsNumber_2 === behidDoorsNumber)\n\n\n if (behidDoorsNumber_2 != behidDoorsNumber) {\n\n\n\n i[behidDoorsNumber].src = goodImg[randomNumberGenerator(goodImg)]\n i[behidDoorsNumber_2].src = goodImg[randomNumberGenerator(goodImg)]\n\n i.forEach((e) => {\n\n if (e.src === \"\") {\n\n e.src = looseImg[randomNumberGenerator(looseImg)]\n\n }\n\n\n })\n\n\n }\n\n\n\n\n\n\n\n}\n\n\n\n// FUNCTION FOR BOTH THREE OR LESS AND FOUR OR MORE DOOR GAME \nfunction doorsOpeningFunction(arrDoor, doorConvertedArray) {\n\n\n\n\n arrDoor.forEach((f) => {\n\n\n f.onclick = function () {\n\n let i = selectAllQuery(\".imgBehidDoors\");\n let messageInf = selectAllQuery(\".message\")\n\n\n\n addClass(this, \"door-animation\")\n\n\n let a = doorConvertedArray.indexOf(this)\n\n\n openDoorsCount++\n\n\n if (arrDoor.length >= 4 && openDoorsCount === 1) {\n\n assignImageIfTwoCilckableImg();\n\n\n if (looseImg.includes(i[a].getAttribute('src'))) {\n\n messageInf[a].src = messageSrcArr[randomNumberGenerator(messageSrcArr)];\n\n\n messageInf[a].classList.remove(\"d-none\");\n\n\n\n i[a].classList.add(\"inf\")\n\n\n state = \"loose\"\n\n arrDoor.forEach(d => {\n d.style.pointerEvents = \"none\";\n })\n\n\n startNewLevel(arrDoor, i)\n countLives()\n\n } else if (goodImg.includes(i[a].getAttribute('src'))) {\n\n\n state = \"win\"\n openDoorsCount++\n\n }\n\n\n }\n\n\n if (arrDoor.length >= 4 && openDoorsCount === 3) {\n\n\n\n if (looseImg.includes(i[a].getAttribute('src'))) {\n\n i[a].classList.add(\"inf\")\n\n messageInf[a].src = messageSrcArr[randomNumberGenerator(messageSrcArr)];\n\n messageInf[a].classList.remove(\"d-none\");\n\n\n arrDoor.forEach(d => {\n d.style.pointerEvents = \"none\";\n })\n\n\n startNewLevel(arrDoor, i)\n countLives()\n } else if (state === \"win\") {\n\n\n\n arrDoor.forEach(d => {\n d.style.pointerEvents = \"none\";\n })\n\n\n startNewLevel(arrDoor, i)\n calculateScore()\n }\n\n\n\n }\n\n // win or loose for less or equal to three doors\n\n\n if (arrDoor.length <= 3) {\n openDoorsCount++\n\n assignImage()\n arrDoor.forEach(d => {\n d.style.pointerEvents = \"none\";\n })\n\n\n if (goodImg.includes(i[a].getAttribute('src'))) {\n\n\n\n\n state = \"win\"\n startNewLevel(arrDoor, i)\n calculateScore()\n\n } else if (looseImg.includes(i[a].getAttribute('src'))) {\n\n\n\n\n i[a].classList.add(\"inf\")\n messageInf[a].src = messageSrcArr[randomNumberGenerator(messageSrcArr)];\n\n messageInf[a].classList.remove(\"d-none\");\n\n\n\n startNewLevel(arrDoor, i)\n state = \"loose\"\n countLives()\n\n }\n\n }\n\n\n }\n\n })\n}\n\n\n\n\n\n\n\n\n// FUNCTIONS FOR LIVES AND SCORE NUMBERS\nlet livesCount = document.getElementById(\"liveCount\");\nlet scoreCount = document.getElementById(\"scoreCount\");\nlet heartIcon = document.querySelector(\".img-icon-1\");\n\n\nlet highScore = [];\n\n\nlet looseColor = document.querySelector(\".looseColor\")\n\n\n\n\n\n\n// COUNT LIVES\nfunction countLives() {\n\n let elmnt = selectAllQuery(\".open\");\n\n\n lives--;\n\n if (lives === 1) {\n addClass(heartIcon, \"heartPulse\")\n\n } else if (lives === 0) {\n\n removeClass(heartIcon, \"heartPulse\");\n removeClass(looseColor, \"d-none\");\n\n highScore.push(score);\n\n document.querySelectorAll(\".playAgain\").forEach(playAgainBtn => {\n\n\n playAgainBtn.onclick = function () {\n gameOver()\n doorsOpeningFunction(doorsOpening, doorsOpeningArr);\n\n }\n\n })\n\n\n elmnt.forEach(entrances => {\n\n entrances.onclick = function () {\n this.style.pointerEvents = \"none\";\n\n }\n })\n\n\n\n\n\n\n\n\n\n }\n\n\n\n livesCount.textContent = lives;\n\n\n}\n\n\n\n// CALCULATE SCORE\n\nfunction calculateScore() {\n\n score++;\n let elmnt = selectAllQuery(\".open\");\n\n\n if (score === 4) {\n\n\n\n let b = document.querySelector(\".winColor\")\n\n\n setTimeout(() => {\n b.classList.remove(\"d-none\");\n elmnt.forEach(entrances => {\n\n entrances.onclick = function () {\n this.style.pointerEvents = \"none\";\n\n }\n })\n\n }, 1000);\n\n\n // \n highScore.push(score);\n\n document.querySelectorAll(\".playAgain\").forEach(playAgainBtn => {\n playAgainBtn.onclick = function () {\n\n gameOver()\n doorsOpeningFunction(doorsOpening, doorsOpeningArr);\n b.classList.add(\"d-none\");\n\n }\n\n })\n // \n } else if (score === 2) {\n\n let c = document.querySelector(\".third\")\n\n setTimeout(() => {\n elmnt.forEach(entrances => {\n\n\n entrances.onclick = function () {\n this.style.pointerEvents = \"none\";\n\n\n }\n })\n c.classList.remove(\"d-none\");\n\n\n }, 1000);\n\n\n document.getElementById(\"gotIt\").onclick = function () {\n\n c.classList.add(\"d-none\");\n winScenario()\n elmnt.forEach(entrances => {\n entrances.style.pointerEvents = \"auto\";\n })\n\n }\n\n\n\n\n } else if (score === 1) {\n\n let b = selectAllQuery(\".shout\")[randomNumberGenerator(selectAllQuery(\".shout\"))]\n\n setTimeout(() => {\n b.classList.remove(\"d-none\");\n // \n elmnt.forEach(entrances => {\n\n entrances.onclick = function () {\n this.style.pointerEvents = \"none\";\n\n }\n })\n // \n\n\n }, 1000);\n\n setTimeout(() => {\n winScenario()\n b.classList.add(\"d-none\");\n elmnt.forEach(entrances => {\n entrances.style.pointerEvents = \"auto\";\n })\n }, 3500);\n\n\n }\n\n scoreCount.textContent = score;\n\n\n}\n\n\n\n\nfunction startNewLevel(arr, imgBehinddor) {\n\n\n let messageInf = selectAllQuery(\".message\")\n\n\n let i = selectAllQuery(\".imgBehidDoors\");\n\n\n\n openDoorsCount = 0;\n\n arr.forEach((f) => {\n\n\n setTimeout(() => {\n removeClass(f, \"door-animation\");\n f.style.pointerEvents = \"auto\";\n\n\n messageInf.forEach(messageImg => {\n messageImg.classList.add(\"d-none\");\n\n })\n\n i.forEach(imgInf => {\n imgInf.classList.remove(\"inf\");\n })\n\n\n // missing animation to display for loose\n }, 2000);\n\n })\n\n\n\n\n\n}\n\nfunction gameOver() {\n\n addClass(looseColor, \"d-none\");\n\n\n // document.getElementById(\"highScore\").textContent = Math.max(highScore);\n document.getElementById(\"highScore\").textContent = Math.max.apply(null, highScore);\n\n\n\n\n openDoorsCount = 0;\n columnNumber = 2;\n document.documentElement.style.setProperty(\"--colNum\", columnNumber);\n score = 0;\n lives = 3;\n\n scoreCount.textContent = score;\n livesCount.textContent = lives;\n\n let i = selectAllQuery(\".imgBehidDoors\")\n\n i.forEach(imgBehind => {\n imgBehind.classList.remove(\"inf\");\n })\n\n let doorsOpening = selectAllQuery(\".open\");\n\n // let elmnt = selectAllQuery(\".entrance\");\n\n let select = document.querySelector('#styleOftheDoorContainer');\n let child = select.lastElementChild;\n\n\n\n if (doorsOpening.length === 4) {\n\n select.removeChild(child);\n child = select.lastElementChild;\n\n select.removeChild(child);\n\n\n } else if (doorsOpening.length === 3) {\n\n child = select.lastElementChild;\n\n select.removeChild(child);\n\n }\n\n\n}\n\n\ndoorsOpeningFunction(doorsOpening, doorsOpeningArr);"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252920,"cells":{"blob_id":{"kind":"string","value":"8cfc20340c187845ecdf0b6600ba025174a9e255"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"dylanmei/Whendle"},"path":{"kind":"string","value":"/whendle/api/observable.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":657,"string":"657"},"score":{"kind":"number","value":2.625,"string":"2.625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"\nWhendle.Observable = Class.create({\n\tinitialize: function() {\n\t\tthis._hash = new Hash();\n\t},\n\t\n\tobserve: function(name, handler) {\n\t\tvar handlers = this.handlers(name);\n\t\tif (handlers.length) {\n\t\t\thandlers.push(handler);\n\t\t}\n\t\telse {\n\t\t\tthis._hash.set(name, [handler]);\n\t\t}\n\t},\n\t\n\tignore: function(name, handler) {\n\t\tif (!name) return;\n\t\tif (!handler) this._hash.unset(name);\n\t\telse {\n\t\t\tvar handlers = this.handlers(name)\n\t\t\t\t.without(handler);\n\t\t\tthis._hash.set(name, handlers);\n\t\t}\n\t},\n\t\n\thandlers: function(name) {\n\t\treturn this._hash.get(name) || [];\n\t},\n\t\n\tfire: function(name, data) {\n\t\tthis.handlers(name)\n\t\t\t.each(function(f) { f(data); });\n\t}\n});"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252921,"cells":{"blob_id":{"kind":"string","value":"748e52fa30b15779d4a14c71ea19025cb00a5452"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"Albertosnp/weather-app-consola"},"path":{"kind":"string","value":"/app.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1593,"string":"1,593"},"score":{"kind":"number","value":2.921875,"string":"2.921875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"const { leerInput, inquirerMenu, pause, ciudadesAelegir } = require(\"./helpers/inquirer\");\nrequire(\"dotenv\").config()\nrequire('colors')\nconst Busquedas = require(\"./models/Busquedas\");\n\nconst main = async () => {\n let option = 0\n const busquedas = new Busquedas()\n do {\n option = await inquirerMenu()\n switch (option) {\n case 1:\n await buscarCiudad(busquedas)\n break;\n case 2:\n console.log('\\nHistorial de búsquedas\\n'.green);\n console.log(busquedas.historial.join('\\n'));\n break; \n }\n if (option !== 0) await pause()\n } while (option !== 0);\n};\n\nconst buscarCiudad = async (busquedas) => {\n const lugar = await leerInput('Introduce el nombre del lugar que quiere buscar:\\n');\n //Buscar los lugares en API\n const lugares = await busquedas.buscarCiudad(lugar)\n //Seleccionar un lugar\n const id_lugar = await ciudadesAelegir(lugares)\n //Cancelar la búsqueda\n if (id_lugar == 0) return\n const lugarSelecc = lugares.find(lugar => lugar.id === id_lugar)\n \n //Llamada api de tiempo por coordenadas\n const clima = await busquedas.buscarClimaPorLugar(lugarSelecc.lat, lugarSelecc.lng)\n\n //Mostrar los detalles del lugar clima\n console.clear();\n console.log('\\nInformación de la ciudad\\n'.green);\n console.log('Ciudad', lugarSelecc.nombre.green);\n console.log('Latitud', lugarSelecc.lat);\n console.log('Longitud', lugarSelecc.lng);\n console.log('Temperatura', clima.main);\n console.log('Descripción', clima.weather[0].description.green);\n //Guardar en db\n busquedas.agregarHistorial(lugarSelecc.nombre)\n};\n\n\nmain()"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252922,"cells":{"blob_id":{"kind":"string","value":"e2f66720d63b5cd15d80123171295aed28de3bb1"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"RadAtanasov/Clock"},"path":{"kind":"string","value":"/assets/js/script.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1219,"string":"1,219"},"score":{"kind":"number","value":3.296875,"string":"3.296875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"var hourHand = document.getElementsByClassName('hour_hand')[0];\nvar minuteHand = document.getElementsByClassName('minute_hand')[0];\nvar secondHand = document.getElementsByClassName('second_hand')[0];\n//var startDate = new Date();\n//var startRotateSecondHand = startDate.getSeconds();\n//var startRotateMinuteHand = startDate.getMinutes();\n//var startRotateHourHand = startDate.getHours();\n//secondHand.style.transform = 'rotate'+'('+(startRotateSecondHand)+')';\n//minuteHand.style.transform = 'rotate'+'('+(startRotateMinuteHand)+')';\n//hourHand.style.transform = 'rotate'+'('+(startRotateHourHand)+')';\nvar countTime = setInterval(function(){\n var date = new Date();\n var degRotateSecondHand = (360 * date.getSeconds()/60)+'deg';\n var degRotateMinuteHand = (360 * date.getMinutes()/60)+'deg';\n var degRotateHourHand = (360 * date.getHours()/12)+0.5*(360 * date.getMinutes()/360)+'deg';\n secondHand.style.transform = 'rotate'+'('+(degRotateSecondHand)+')';\n minuteHand.style.transform = 'rotate'+'('+(degRotateMinuteHand)+')';\n hourHand.style.transform = 'rotate'+'('+(degRotateHourHand)+')';\n secondHand.style.display = 'block';\n minuteHand.style.display = 'block';\n hourHand.style.display = 'block';\n}, 200);"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252923,"cells":{"blob_id":{"kind":"string","value":"7aef1ba58276fb495b2d18f86be9e7c1dcaa3be8"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"lolwuz/it"},"path":{"kind":"string","value":"/react-buggle/src/reducers/checkReducer.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1404,"string":"1,404"},"score":{"kind":"number","value":2.65625,"string":"2.65625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\n/*\nsrc/reducers/checkReducer.js\n*/\nexport default (state = { loading: false, guesses: [], solutions: [], points: 0, totalPoints: 0 }, action) => {\n switch (action.type) {\n case 'R_BOARD_CHECK':\n return { ...state, loading: true }\n case 'S_BOARD_CHECK':\n let guess = action.payload.data\n if (!guess.is_valid)\n guess.is_valid = 0\n else\n guess.is_valid = 1\n for (let i = 0; i < state.guesses.length; i++) {\n if (state.guesses[i].word === guess.word) {\n guess.is_valid = 2\n }\n }\n return { ...state, loading: false, guesses: [guess, ...state.guesses], points: state.points + guess.points }\n case 'F_BOARD_CHECK':\n return { ...state, loading: false, error: 'Error while fetching check' }\n\n case 'R_BOARD_SOLUTION':\n return { ...state, loading: true }\n case 'S_BOARD_SOLUTION':\n return { ...state, loading: false, solutions: action.payload.data.solved, totalPoints: action.payload.data.points }\n case 'F_BOARD_SOLUTION':\n return { ...state, loading: false, error: 'Error while fetching solution' }\n\n case 'DELETE_BOARD':\n return { ...state, loading: false, guesses: [], solutions: [], points: 0 }\n default:\n return state\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252924,"cells":{"blob_id":{"kind":"string","value":"56cb362bb6b95fc8beca3afcb0033066b9cadf88"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"PorcelainAddict/Tues_Painter_Decorator"},"path":{"kind":"string","value":"/specs/room_spec.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":711,"string":"711"},"score":{"kind":"number","value":2.828125,"string":"2.828125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"const assert = require('assert');\nconst Room = require('../room.js');\n\ndescribe('Room', function() {\n beforeEach(function() {\n //space reserved for room something soemthing\n room = new Room (10);\n });\n\n it('should have an area in square meters', function() {\n const actual = room.area;\n const expected = 10;\n assert.strictEqual(actual, expected);\n });\n\n it('should start not painted', function() {\n const actual = room.isItPainted();\n const expected = false;\n assert.strictEqual(actual, expected)\n });\n\n it('should be painted', function() {\n room.paintASquareMeter(3);\n room.paintASquareMeter(3);\n room.paintASquareMeter(3);\n assert.strictEqual(9, room.paintedArea);\n\n });\n\n\n\n\n\n});\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252925,"cells":{"blob_id":{"kind":"string","value":"b8664c996608c849314f40a70e0506a7494d8259"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"kauesedrez/CedrosDatabase"},"path":{"kind":"string","value":"/cedrosDb.jss"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":26424,"string":"26,424"},"score":{"kind":"number","value":2.59375,"string":"2.59375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT","Apache-2.0"],"string":"[\n \"MIT\",\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"\t/***\n\t[cdoc]\n\t#autor: Winetu Kaue Sedrez Bilhalva\n\t#name: Database Class\n\t#obs: https://msdn.microsoft.com/en-us/library/hww8txat(v=vs.84).aspx - documentação \n\t***/\n\n\t/*\n\t[init block]\n\t#desc: testa se a jquery está funcionando\n\t*/\n\tif(typeof $ == \"undefined\") {\n\t\tdocument.write(\"

Cedros Database

Hello Folks! It Works.

More? Cedros Development


\");\n\t\tdocument.write(\"

[!] Atenção [!] - Está faltando a jquery!


\");\n\t\t}\n\t/* [end block] */\n\t\n\t\n\t/*\n\t[init block]\n\t#name: teste de compatibilidade\n\t*/\n\t$(function(){\n\t\n\t\ttry{\n\t\t\n\t\t\tfso = new ActiveXObject(\"Scripting.FileSystemObject\");\n\t\t\n\t\t} catch(e) {\n\t\t\n\t\t\tdocument.write(\"O site não foi adicionado aos sites confiáveis
Vá em Ferramentas>Opções da Internet>Segurança>Sites Confiáveis>sites>Adicionar este site a zona>Adicionar

Nessa versão o sistema funciona apenas no Internet Explorer

Erro Original

\"+e.message);\n\t\t\n\t\t}\n\t\t\n\t\t\n\t\n\t});\n\t\n\t\n\t/***\n\t[init function]\n\t#name: Database()\n\t***/\n\tvar CedrosDatabase = function() {\n\t\n\t\tvar valor=[];\n\t\tthis.numLines=[];\n\t\tthis.numLins;\n\t\tthis.numCols=[];\n\t\t\n\t\t\n\t\tthis.table_;\n\t\tthis.database_;\n\t\t/** define com qual tabela o objeto irá trabalhar permanentemente **/\n\t\t\n\t\t// ------------------------------------------------------------------------------------------------\n\t\t\n\t\t/***\n\t\t[init function]\n\t\t#name:escreve();\n\t\t***/\n\t\t\n\t\t\tthis.escreve = function(x){\n\t\t\t$(\"#output\").append(x+\"

\");\n\t\t\t}\n\t\t\n\t\t/***\n\t\t[end function]\n\t\t***/\n\t\t\n\t\t// ------------------------------------------------------------------------------------------------\n\n\t\t/***\n\t\t[init block]\n\t\t#name: trims\n\t\t***/\n\t\t\tthis.trim = function(str) {\n\t\t\t\treturn str.replace(/^\\s+|\\s+$/g,\"\");\n\t\t\t\t\n\t\t\t}\n\t\t\t//left trim\n\t\t\tthis.ltrim=function(str) {\n\t\t\t\t\n\t\t\t\treturn str.replace(/^\\s+/,\"\");\n\t\t\t\t\n\t\t\t}\n\t\t\t//right trim\n\t\t\tthis.rtrim = function(str) {\n\t\t\t\t\n\t\t\t\treturn str.replace(/\\s+$/,\"\");\n\t\t\t}\n\t\t/***\n\t\t[end block]\n\t\t***/\n\t\t\n\t\t// ------------------------------------------------------------------------------------------------\t\n\t\t\t\n\t\t/* [init function]\n\t\t#name: itWorks();\n\t\t*/\n\t\t\tthis.itWorks = function() {\n\t\t\t\n\t\t\t\tdocument.write(\"

Cedros Database

Hello Folks! It Works.

More? Cedros Development


\");\n\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t//testa o path\n\t\t\t\tif(typeof PATH == 'undefined') {\n\t\t\t\t\n\t\t\t\t\t\tdocument.write(\"

[!] Atenção [!] - Está faltando o path.txt !


\");\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\telse {\n\t\t\t\t\n\t\t\t\t\t\tdocument.write(\"

Ótimo, tudo parece ter sido configurado corretamente. Não esqueça das barras no final do path.txt ;)


Leia a documentação do CBD em cedrosdev.com.br/cdb/docs\");\n\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t}\n\t\t/* [end function] */\t\t\t\n\t\t\t\n\t\t\t\n\t\t/***\n\t\t[init function]\n\t\t#name: getWhen();\n\t\t***/\n\t\n\t\tthis.getWhen = function (retorno_,coluna_,valor_){\n\t\t/** get nome(retorno_) when categoria(coluna_)=advogado(valor_) , retorna apenas uma ocorrencia**/\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\tvar fso = new ActiveXObject(\"Scripting.FileSystemObject\");\n\t\t\tvar file = fso.OpenTextFile(PATH+this.database_+\"\\\\\"+this.table_+\".cdb\",1);\n\t\t\tif (file.AtEndOfStream)\n\t\t\t arquivoOriginal=\"\";\n\t\t\telse\n\t\t\t arquivoOriginal=file.ReadAll();\n\t\t\tfile.Close();\n\t\t\t\n\t\t\t//arquivoOriginal retem todo o arquivo de banco de dados\n\t\t\tthis.numLines=arquivoOriginal.split(\"\\n\");\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\tfor(a=0;att)tt=hh;\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\treturn tt;\n\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\t//min\n\t\t\t\tif(valor_ == \"min\") {\n\t\t\t\t\n\t\t\t\t\tvar tt=0;\n\t\t\t\t\n\t\t\t\t\tfor(i=1;i\") {\n\t\t\t\t\t\t\n\t\t\t\t\t\tnumLin = [];\n\t\t\t\t\t\ta=0;\n\t\t\t\t\t\tfor(i=0;iparseInt(valor_)) {\n\t\t\t\t\t\ta++;\n\t\t\t\t\t\t\tnumLin[a]=i;\n\t\t\t\t\t\t\t/** numLin.length agora retem o total de matches **/\n\t\t\t\t\t\t\t//a++;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse if(modificador_==\">=\") {\n\t\t\t\t\t\t\n\t\t\t\t\t\tnumLin = [];\n\t\t\t\t\t\ta=0;\n\t\t\t\t\t\tfor(i=0;i=parseInt(valor_)) {\n\t\t\t\t\t\ta++;\n\t\t\t\t\t\t\tnumLin[a]=i;\n\t\t\t\t\t\t\t/** numLin.length agora retem o total de matches **/\n\t\t\t\t\t\t\t//a++;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse if(modificador_==\"<\") {\n\t\t\t\t\t\t\n\t\t\t\t\t\tnumLin = [];\n\t\t\t\t\t\ta=0;\n\t\t\t\t\t\tfor(i=0;i=\");\n\t\t\t\t\t\t\n\t\t\t}\n\t\t\treturn valor;\n\t\t\n\t\t}\n\t\t/* [end function] */\n\t\t\n\t\t// ------------------------------------------------------------------------------------------------\n\t\t\n\t\t/***\n\t\t[init function]\n\t\t#name: showTable();\n\t\t#desc: Mostra toda estrutura da tabela em uma div flutuante;\n\t\t***/\n\t\t\n\t\tvar showTableControle=true;\n\t\t\n\t\tthis.showTable = function() {\n\t\t\n\t\t\t\n\t\t\n\t\t\toutput_=\"

Show Table

Tabela: \"+this.table_+\"

\";\n\t\t\toutput_+=\"

\";\n\t\t\t\n\t\t\t\n\t\t\tresultado = this.getWhere(\"LINE\",\"0\",\">=\");\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\tfor(lpo=0;lpo\";\n\t\t\t\n\t\t\t\tfor(lpi=0;lpi\"+valor[lpo][lpi]+\"\";\n\t\t\t\t\telse output_+=\"\";\n\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\toutput_+=\"\";\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\toutput_+=\"
\"+valor[lpo][lpi]+\"
\";\n\n\t\t\t\n\t\t\tif(showTableControle) {\n\t\t\t\t//primeira vez\n\t\t\t\t$('body').append(\"
\");\n\t\t\t\t$('#divOutput').html(output_);\n\t\t\t\tshowTableControle=false;\n\t\t\t}\n\t\t\telse{\n\t\t\t\t//apenas atualiza a div\n\t\t\t\t$('#divOutput').html(output_).fadeIn('slow');\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t$(\"#divOutput\").css(\"position\",\"absolute\").css(\"backgroundColor\",\"#eee\").css(\"top\",20).css(\"left\",20).css(\"width\",\"900\").css(\"height\",\"400\").css(\"overflow\",\"auto\").css(\"padding\",10).css(\"margin\",10).css(\"borderColor\",\"red\").css(\"borderBottomWidth\",\"5\").css(\"fontFamily\",\"Calibri\");\n\t\t\t\n\t\t\t$(\"#tableOutput td\").css(\"fontFamily\",\"Courier New\").css(\"fontSize\",\"12px\").css(\"borderBottom\", \"1px solid #ddd\").css(\"borderLeft\", \"1px solid #ddd\").css(\"padding\",\"5px\");\n\t\t\t\n\t\t\t\n\t\t}\n\t\t\n\t\t\n\t\t/***\n\t\t[end function]\n\t\t***/\n\t\t\n\t\t// ------------------------------------------------------------------------------------------------\n\t\t\n\t\t/***\n\t\t[init function]\n\t\t#name: insert();\n\t\t#desc: insert into table values(\"..\",\"..\");\n\t\t***/\n\t\t\n\t\t\n\t\t\n\n\t\tthis.insert = function(params,html) {\n\t\t\n\t\t\tvar str=\"\";\n\t\t\n\t\t\tif(html==true) {\n\t\t\t\n\t\t\t\tfor (i=0; i\");\n\t\t\t\t\n\t\t\t\t}\n\t\t\t\n\t\t\t}\n\t\t\n\t\t\tfor (i=0; i=,<=,>,< ; se nao for definido será igual\n\t\to modificar serve apenas para colunas numericas\n\t\t***/\n\t\t\n\t\tthis.update = function(coluna1_,valor1_,coluna2_,valor2_,modificador) {\n\t\t\n\t\t\t// --> explode\n\t\t\t\tvar fso = new ActiveXObject(\"Scripting.FileSystemObject\");\n\t\t\t\tvar file = fso.OpenTextFile(PATH+this.database_+\"\\\\\"+this.table_+\".cdb\",1);\n\t\t\t\tif (file.AtEndOfStream)\n\t\t\t\t arquivoOriginal=\"\";\n\t\t\t\telse\n\t\t\t\t arquivoOriginal=file.ReadAll();\n\t\t\t\tfile.Close();\t\t\t\n\t\t\t\t//arquivoOriginal retem todo o arquivo de banco de dados\n\t\t\t\tthis.numLines=arquivoOriginal.split(\"\\n\");\t\t\t\n\t\t\t\tfor(a=0;a descobre a coluna nome\n\t\t\t\tfor(i=0;i remonta o arquivo\n\t\t\t\tvar resultadoUpdate=\"\";\n\t\t\t\tfor(g=0;g\") {\n\t\t\t\t\t\tfor(u=0;uparseInt(valor2_)) {\n\t\t\t\t\t\t\t\t\tvalor[g][numCol1]=valor1_;\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if(modificador==\"<\") {\n\t\t\t\t\t\tfor(u=0;u=\") {\n\t\t\t\t\t\tfor(u=0;u=parseInt(valor2_)) {\n\t\t\t\t\t\t\t\t\tvalor[g][numCol1]=valor1_;\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if(modificador==\"<=\") {\n\t\t\t\t\t\tfor(u=0;u grava o arquivo\n\t\t\t\tvar fso = new ActiveXObject(\"Scripting.FileSystemObject\");\n\t\t\t\tvar file = fso.OpenTextFile(PATH+this.database_+\"\\\\\"+this.table_+\".cdb\",2,-1,0);\n\t\t\t\tfile.Write(resultadoUpdate);\n\t\t\t\tfile.Close();\t\t\t\n\t\t\t// <-- grava o arquivo\n\t\t\t\n\t\t\n\t\t}\n\t\t/***\n\t\t[end function]\n\t\t***/\n\t\t \n\t\t// ------------------------------------------------------------------------------------------------\n\t\t\n\t\t/*** [init function]\n\t\t#name: erase();\n\t\t#desc: erase e-mail when id=002\n\t\t***/\n\t\t\n\t\tthis.erase = function(coluna1_,coluna2_,valor_,modificador) {\n\t\t\n\t\t\tif(modificador==undefined)\n\t\t\t\tthis.update(coluna1_,\"\",coluna2_,valor_);\n\t\t\telse\t\n\t\t\t\tthis.update(coluna1_,\"\",coluna2_,valor_,modificador);\n\t\t\n\t\t}\n\t\t\n\t\t\n\t\t/*** [end function] ***/\n\t\t\n\t\t// ------------------------------------------------------------------------------------------------\n\n\t\t/*** [init function]\n\t\t#name:\tdelete\n\t\t#desc: \tdeleta uma this.numLines inteira do banco de dados\n\t\t\t\tdelete when id=004\n\t\t***/\n\t\t\t\n\t\tthis.del = function(coluna_,valor_,modificador) {\n\t\t\n\t\t\t// --> explode\n\t\t\t\tvar fso = new ActiveXObject(\"Scripting.FileSystemObject\");\n\t\t\t\tvar file = fso.OpenTextFile(PATH+this.database_+\"\\\\\"+this.table_+\".cdb\",1);\n\t\t\t\tif (file.AtEndOfStream)\n\t\t\t\t arquivoOriginal=\"\";\n\t\t\t\telse\n\t\t\t\t arquivoOriginal=file.ReadAll();\n\t\t\t\tfile.Close();\t\t\t\n\t\t\t\t//arquivoOriginal retem todo o arquivo de banco de dados\n\t\t\t\tthis.numLines=arquivoOriginal.split(\"\\n\");\t\t\t\n\t\t\t\tfor(a=0;a0) {\n\t\t\t\n\t\t\t\t// --> descobre a coluna \n\t\t\t\t\tfor(i=0;i remonta o arquivo\n\t\t\t\tvar resDelete=\"\";\n\t\t\t\tfor(g=0;g\":\n\t\t\t\t\t\t\tif(g==0) {\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tresDelete+=this.numLines[g]+\"\\n\";\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif(parseInt(valor[g][numCol])<=parseInt(valor_)) {\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tresDelete+=this.numLines[g]+\"\\n\";\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\n\t\t\t\t\t\tcase \">=\":\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tif(g==0) {\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tresDelete+=this.numLines[g]+\"\\n\";\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif(parseInt(valor[g][numCol])=parseInt(valor_)) {\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tresDelete+=this.numLines[g]+\"\\n\";\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\n\t\t\t\t\t\tcase \"<=\":\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tif(g==0) {\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tresDelete+=this.numLines[g]+\"\\n\";\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif(parseInt(valor[g][numCol])>parseInt(valor_)) {\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tresDelete+=this.numLines[g]+\"\\n\";\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t// <-- remonta o arquivo\n\t\t\t\t\n\t\t\t\t// --> grava o arquivo\n\t\t\t\t\tif(resDelete.substring((resDelete.length-1),resDelete.length)==\"\\n\")resDelete=resDelete.substring(0,(resDelete.length - 1));\n\t\t\t\t\tvar fso = new ActiveXObject(\"Scripting.FileSystemObject\");\n\t\t\t\t\tvar file = fso.OpenTextFile(PATH+this.database_+\"\\\\\"+this.table_+\".cdb\",2,-1,0);\n\t\t\t\t\tfile.Write(resDelete);\n\t\t\t\t\tfile.Close();\t\t\t\n\t\t\t\t// <-- grava o arquivo\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t// --> corrige a coluna LINE\n\t\t\t\t\n\t\t\t\t\t// --> explode\n\t\t\t\t\t\tvar fso = new ActiveXObject(\"Scripting.FileSystemObject\");\n\t\t\t\t\t\tvar file = fso.OpenTextFile(PATH+this.database_+\"\\\\\"+this.table_+\".cdb\",1);\n\t\t\t\t\t\tif (file.AtEndOfStream)\n\t\t\t\t\t\t arquivoOriginal=\"\";\n\t\t\t\t\t\telse\n\t\t\t\t\t\t arquivoOriginal=file.ReadAll();\n\t\t\t\t\t\tfile.Close();\t\t\t\n\t\t\t\t\t\t//arquivoOriginal retem todo o arquivo de banco de dados\n\t\t\t\t\t\tthis.numLines=arquivoOriginal.split(\"\\n\");\t\t\t\n\t\t\t\t\t\tfor(a=0;a grava o arquivo\n\t\t\t\t\tvar fso = new ActiveXObject(\"Scripting.FileSystemObject\");\n\t\t\t\t\tvar file = fso.OpenTextFile(PATH+this.database_+\"\\\\\"+this.table_+\".cdb\",2,-1,0);\n\t\t\t\t\tfile.Write(resultadoUpdate);\n\t\t\t\t\tfile.Close();\t\t\t\n\t\t\t\t// <-- grava o arquivo\n\t\t\t}\n\t\t}\n\t\t\t\n\t\t\n\t\t/*** [end function] ***/\n\t\t\n\t\t\n\t\t// --------------------------------------------------------------------|\n\t\t// MODULO CDBMyAdmin --------------------------------------------------|\n\t\t// Neste modulo a formula muda, agora o banco deve ser passado por ----|\n\t\t// parâmetro, e não mais por variável estática ------------------------|\n\t\t// --------------------------------------------------------------------|\n\t\t\n\t\t/* [init function]\n\t\t#name: \t\tgetDatabases();\n\t\t#desc: \t\tusa a função GetFolder para listar todos os subfolders dentro do path PATH.\n\t\t\t\t\tusa a função Enumerator para listar todos \n\t\t\t\t\tusa o for (; !fc.atEnd(); fc.moveNext()) para varrer os subfolders\n\t\t\t\t\tfc.item() retem o caminho completo\n\t\t\t\t\tfc.item().name retem apenas o nome do folder\n\t\t#return:\tRetorno um array com o nome de todos os folders: bds[];\n\t\t*/\n\t\t\n\t\tthis.getDatabases = function() {\n\t\tvar dbs = [];\n\t\t\tvar fso = new ActiveXObject(\"Scripting.FileSystemObject\");\n\t\t\tf = fso.GetFolder(PATH);\t\t\t\n\t\t\t\n\t\t\t\tfc=new Enumerator(f.SubFolders);\n\t\t\t\ts = 0;\n\t\t\t\tfor (; !fc.atEnd(); fc.moveNext())\n\t\t\t\t{\n\t\t\t\t dbs[s]=fc.item().name;\n\t\t\t\t s++;\t\t\t\t \n\t\t\t\t}\n\t\t\treturn dbs;\n\t\t}\n\t\t\n\t\t/* [end function] */\n\t\t\n\t\t\n\t\t/* [init function]\n\t\t#name:\t\tgetTables()\n\t\t#desc:\t\tUsa GetBaseName em Enumerator(f.files) para listar o nome de cada arquivo .cdb dentro do banco de dados 'db'\n\t\t#pars:\t\tstring db -> O banco de dados (pasta) selecionado\n\t\t#return:\tarray tbs contendo o nome simples - sem extensão - de cada arquivo dentro da pasta db\n\t\t*/\n\t\tthis.getTables = function(db) {\n\t\tvar tbs = [];\n\t\t\tvar fso = new ActiveXObject(\"Scripting.FileSystemObject\");\n\t\t\tf = fso.GetFolder(PATH+\"\\\\\"+db+\"\\\\\");\n\t\t\tfc=new Enumerator(f.files);\n\t\t\t\ts = 0;\n\t\t\t\tfor (; !fc.atEnd(); fc.moveNext())\n\t\t\t\t{\n\t\t\t\t tbs[s]=fso.GetBaseName(fc.item());\n\t\t\t\t s++;\t\t\t\t \n\t\t\t\t}\n\t\t\treturn tbs;\n\t\t}\n\t\t/* [end function] */\n\t\t\n\t\t/* [init function]\n\t\t#name:\t\trenameTable();\n\t\t#desc:\t\trenomeia a tabela tb passado como parametro para newName\n\t\t#pars:\t\tstring db-->banco , string tb-->tabela, string newName-->novo nome da tabela\n\t\t#return :\ttrue;\n\t\t*/\n\t\tthis.renameTable = function(db,tb,newName) {\n\t\t\n\t\t\tvar fso = new ActiveXObject(\"Scripting.FileSystemObject\");\n\t\t\tf = fso.GetFile(PATH+\"\\\\\"+db+\"\\\\\"+tb+\".cdb\");\n\t\t\tf.name=newName+\".cdb\";\n\t\t\treturn true;\n\t\t\n\t\t}\n\t\t/* [end function] */\n\t\t\n\t\t/* [init function]\n\t\t#name:\t\trenameDatabase();\n\t\t#desc:\t\trenomeia o banco de dados (pasta) passada por parâmetro\n\t\t#pars:\t\tstring db-->banco, string newName-->novo nome do banco de dados\n\t\t#return :\ttrue;\n\t\t*/\n\t\tthis.renameDatabase = function(db,newName) {\n\t\t\n\t\t\tvar fso = new ActiveXObject(\"Scripting.FileSystemObject\");\n\t\t\tf = fso.GetFolder(PATH+\"\\\\\"+db+\"\\\\\");\n\t\t\t\n\t\t\tf.name=newName;\n\t\t\t\n\t\t\treturn true;\n\t\t\t\t\n\t\t}\n\t\t/* [end function] */\n\t\t\n\t\t/* [init function]\n\t\t#name: \t\tdeleteDatabase()\n\t\t*/\n\t\tthis.deleteDatabase = function(db) {\n\t\t\n\t\t\tvar fso = new ActiveXObject(\"Scripting.FileSystemObject\");\n\t\t\tf = fso.GetFolder(PATH+\"\\\\\"+db);\n\t\t\tfso.DeleteFolder(f);\n\t\t\treturn true;\n\t\t\n\t\t}\n\t\t/* [end function] */\n\t\t\n\t\t\n\t\t/* [init function]\n\t\t#name:\t\tdeleteTable();\n\t\t*/\n\t\tthis.deleteTable = function(db,tb){\n\t\t\n\t\t\tvar fso = new ActiveXObject(\"Scripting.FileSystemObject\");\n\t\t\tf = fso.GetFile(PATH+\"\\\\\"+db+\"\\\\\"+tb+\".cdb\");\n\t\t\tfso.deleteFile(f);\n\t\t\treturn true;\n\t\t\n\t\t}\n\t\t/* [end function] */\n\t\t\n\t\t\n\t\t/* [init function]\n\t\t#name: createTable();\n\t\t*/\n\t\tthis.createTable = function(tb,colunas) {\n\t\t\n\t\t\tvar fso = new ActiveXObject(\"Scripting.FileSystemObject\");\n\t\t\t\n\t\t\ttry{\n\t\t\t\tf=fso.CreateTextFile(PATH+conexao.database_+\"\\\\\"+tb+\".cdb\",false);\n\t\t\t\tf.Write(\"LINE|-$-|\"+colunas.replace(/,/g,\"|-$-|\"));\n\t\t\t\tf.Close();\n\t\t\t\treturn \"ok\";\n\t\t\t}\n\t\t\tcatch(e){\n\t\t\t\treturn \"
Erro: Não foi possivel criar a tabela. Ela já existe?
Erro original: \"+e.message+\"
\";\n\t\t\t}\t\n\t\t\n\t\t}\n\t\t/* [end function] */\n\t\t\t\n\t/***\n\t[init function]\n\t#name: createDatabase();\n\t***/\n\t\n\t\tthis.createDatabase = function(db) {\n\t\t\n\t\t\tvar fso = new ActiveXObject(\"Scripting.FileSystemObject\");\n\t\t\t\t\n\t\t\t\ttry{\n\t\t\t\t\tf=fso.CreateFolder(PATH+db)\n\t\t\t\t\treturn \"ok\";\n\t\t\t\t}\n\t\t\t\tcatch(e){\n\t\t\t\t\t\treturn \"
Erro: Não foi possivel criar o banco de dados. Ele já existe?
Erro original: \"+e.message+\"
\";\n\t\t\t\t}\n\t\t\n\t\t}\n\t\t\n\t}\n\t/***\n\t[end function]\n\t***/\n\t\n\n\t\n\t\n\t// valor[0][0] retem os valores do banco de dados\n\t//valor[0][1],[0][2],[0][3] retem os nomes das colunas\n\t//valor[1][0],[2][0],[3][0] retem o numero da this.numLines\n\t//this.numLines.length retem o total de this.numLiness do banco de dados\n\t//valor[0].length retem o total de colunas do banco de dados\n\t\n\t\n\t\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\n\t\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252926,"cells":{"blob_id":{"kind":"string","value":"2f3f1d6350a4c58d3838929ab3f57e33ea9cbde1"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"Stephaaan/ang_itat_reg_be_server"},"path":{"kind":"string","value":"/src/runners/tokenRemover.runner.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":386,"string":"386"},"score":{"kind":"number","value":2.8125,"string":"2.8125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"const state = require(\"../state/state\");\n\nmodule.exports = () => {\n const oldTokens = state(\"tokens\");\n const newTokens = []\n oldTokens.forEach(token => {\n console.log(\"kukame tokeny\");\n if(Date.now() < token.validUntil){\n console.log(\"ma to nevymazat\");\n \n newTokens.push(token)\n }\n })\n state(\"tokens\", newTokens);\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252927,"cells":{"blob_id":{"kind":"string","value":"367bd81d8c8030f13ab3c58460691880e1d7bdf4"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"vbuzato/tic-tac-toe"},"path":{"kind":"string","value":"/src/components/Board.jsx"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":847,"string":"847"},"score":{"kind":"number","value":2.65625,"string":"2.65625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"import React from 'react';\n\nclass Board extends React.Component {\n render() {\n const { board, play, resetGame } = this.props;\n return (\n
\n {board.map((_, index,) => {\n let option, choice, choose = '';\n if (board[index] !== 'E') {\n choice = board[index];\n option = 'inactive';\n choose = () => {console.log('not allowed')};\n } else {\n choose = (e, index) => play(e, index);\n }\n return (\n
choose(e, index)} key={`${index}`} id={`${index}`} className={`box pos${index} ${option}`}>\n {choice}\n
\n )}\n )}\n \n
\n );\n }\n}\n\nexport default Board;"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252928,"cells":{"blob_id":{"kind":"string","value":"430aa5b3f54e2ea358276ae2f5eca07e961c897a"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"jsera/gatest"},"path":{"kind":"string","value":"/public/js/resultview.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2379,"string":"2,379"},"score":{"kind":"number","value":2.84375,"string":"2.84375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"var ResultView = function(controller, resultModel) {\r\n this.controller = controller;\r\n this.model = resultModel;\r\n this.element = document.createElement(\"div\");\r\n this.favorited = false;\r\n this.details = null;\r\n \r\n this.init();\r\n};\r\n\r\n(function() {\r\n ResultView.prototype.init = function() {\r\n var scope = this;\r\n var favorites = this.controller.getFavorites();\r\n var templates = this.controller.getTemplates();\r\n var search = this.controller.getSearch();\r\n this.element = templates.getResult(this.model.Title, this.model.imdbID);\r\n \r\n var title = this.element.getElementsByClassName(\"movie_title\")[0];\r\n title.onclick = addPreventDefault(function() {\r\n if (scope.details == null) {\r\n // We want a spinner\r\n var spinner = templates.getSpinner();\r\n scope.element.appendChild(spinner);\r\n // Kick it off\r\n search.onSearchSuccess = function(searchObj) {\r\n scope.element.removeChild(spinner);\r\n scope.details = new DetailsView(scope.controller, searchObj.response);\r\n scope.element.appendChild(scope.details.element);\r\n };\r\n search.onSearchError = function(searchObj) {\r\n scope.element.removeChild(spinner);\r\n var error = templates.getError(\"Couldn't load details!\");\r\n scope.element.appendChild(error);\r\n };\r\n search.getDetails(scope.model);\r\n }\r\n }, scope);\r\n \r\n var like = this.element.getElementsByClassName(\"like\")[0];\r\n this.favorited = favorites.getFaveByID(this.model.imdbID);\r\n if (this.favorited) {\r\n // In a production app, you'd never hardcode things like this, instead,\r\n // you'd get it from a localization dictionary or something similar.\r\n like.innerHTML = \"Liked!\";\r\n }\r\n like.onclick = addPreventDefault(function() {\r\n if (!scope.favorited) {\r\n like.innerHTML = \"Liked!\";\r\n scope.favorited = true;\r\n favorites.favorite(this.model);\r\n }\r\n }, scope);\r\n };\r\n \r\n ResultView.prototype.getElement = function() {\r\n return this.element;\r\n };\r\n})();"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252929,"cells":{"blob_id":{"kind":"string","value":"9be4637f7a68581d09d505382c64ba93e9cb3cf1"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"LL0814/microCourseOnine"},"path":{"kind":"string","value":"/static/assets/javascripts/profile.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4463,"string":"4,463"},"score":{"kind":"number","value":2.578125,"string":"2.578125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"//upload header image\n$(\"#uploadHeadImg\").on('change', function(){\n var file = document.querySelector(\"#uploadHeadImg\").files[0];\n var min_width = 150;\n var min_height = 150;\n if (file && /\\.(jpe?g|png|gif)$/i.test(file.name) ) {\n //读取图片数据\n var reader = new FileReader();\n reader.readAsDataURL(file);\n reader.onload = function (e) {\n var data = e.target.result;\n //加载图片获取图片真实宽度和高度\n var image = new Image();\n image.onload=function(){\n var width = this.width;\n var height = this.height;\n ifPreview(width, min_width, height, min_height, data, file, \"headImg\",\"head\");\n };\n image.src= data;\n };\n }\n else{\n alert('格式不正确');\n }\n});\n\n$(\"#update-password\").on('click', function () {\n var password = $(\"#password\").val();\n var repassword = $(\"#password-confirmation\").val();\n var pwdpattern = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,21}$/;\n var step = 1;\n if (step == 1) {\n if (password == \"\" || password == null) {\n danger(\"errorTips\", \"密码不能为空\");\n }\n else {\n step = 2;\n }\n }\n if (step == 2) {\n if (pwdpattern.test(password) == false) {\n danger(\"errorTips\", \"密码由6-21字母和数字组成,不能是纯数字或纯英文\");\n }\n else {\n step = 3;\n }\n }\n if (step == 3) {\n if (password != repassword) {\n danger(\"errorTips\", \"两次密码不匹配\");\n }\n else {\n step = 4;\n }\n }\n if (step == 4) {\n $.ajax({\n type: \"POST\",\n url: \"/profile/\",\n data: { 'password': repassword, 'action':'resetpassword' },\n headers: {\n 'X-CSRFToken': $.cookie('csrftoken')\n },\n async: true,\n error: function (request) {\n danger(\"errorTips\", \"对不起, 修改密码失败, 请稍后再试\");\n },\n success: function (callback) {\n if(callback == 'success'){\n window.location.href = '/profile/';\n }else{\n danger(\"errorTips\", '对不起, 修改密码失败, 请稍后再试');\n }\n }\n });\n }\n});\n\n$('#profile-save').on('click', function() {\n let nickname = $('#nickname').val();\n let teacherId = $('#select-teacher').val();\n let gradeId = Number($('#select-grade').val());\n let classId = Number($('#select-class').val());\n $.ajax({\n type: \"POST\",\n url: \"/profile/\",\n data: { 'nickname': nickname,\n 'teacherId': teacherId,\n 'gradeId': gradeId,\n 'classId': classId,\n 'action':'editprofile' },\n headers: {\n 'X-CSRFToken': $.cookie('csrftoken')\n },\n async: true,\n error: function (request) {\n danger(\"errorTips\", \"对不起, 编辑失败, 请稍后再试\");\n },\n success: function (callback) {\n if(callback == 'success'){\n window.location.href = '/profile/';\n }else{\n danger(\"errorTips\", '对不起, 编辑失败, 请稍后再试');\n }\n }\n });\n});\n\nfunction danger(tid, tips) {\n $(\"#\" + tid).removeClass('hidden').text(tips);\n}\nfunction removeTips(tid) {\n $(\"#\" + tid).addClass(\"hidden\");\n}\n\nfunction ifPreview(width, min_width, height, min_height, data, file, id, prefix){\n if(width < min_width || height < min_height){\n alert(\"请上传宽度大于 \"+min_width+\"px,高度大于 \"+min_height+\"px 的封面图片。\");\n }\n else{\n //preview and update\n $(\"#\"+id).attr(\"src\", data);\n imgUpload(file, prefix);\n }\n}\n\nfunction imgUpload(file, prefix) {\n var formData = new FormData();\n formData.append(\"imgFile\", file);\n formData.append(\"prefix\", prefix);\n ajax(formData, \"/upload_imgs/\");\n}\n\nfunction ajax(formData, URL){\n $.ajax({\n type:'POST',\n url: URL,\n data: formData,\n headers: {\n 'X-CSRFToken': $.cookie('csrftoken')\n },\n processData: false,\n contentType: false,\n async: false,\n success: function(callback) {\n window.location.reload();\n }\n });\n}\n\n//proile update\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252930,"cells":{"blob_id":{"kind":"string","value":"fa1eb66e25522389883bb9e1d161f62636ff04d9"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"ItsJuice/quizzlr"},"path":{"kind":"string","value":"/app/assets/javascripts/quizzlr/quiz/quiz-functions.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":7398,"string":"7,398"},"score":{"kind":"number","value":2.96875,"string":"2.96875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"$(function()\n{\n\n //\n //\n // ***** Control progress bar *****\n //\n //\n function updateProgress(percentage)\n {\n\n // Set progress bar's width and update text to the correct percentage\n $('#msch-progress').css('width', '' + percentage + '%');\n $('#msch-progress_text').html('' + percentage + '% Complete');\n\n }\n\n //\n //\n // ***** Reset progress bar *****\n //\n //\n updateProgress(0);\n\n //\n //\n // ***** Scroll around the quiz *****\n //\n //\n function scrollQuiz(location)\n {\n\n // Variables for scrolling amounts and duration\n // Ideally Sharepoint should scroll to an element's position not by a set amount, in case the Sharepoint layout ever changes\n var duration = 600;\n var sharepointTop = 450;\n var sharepointBottom = 2000;\n\n // Top or bottom of quiz?\n switch (location) {\n\n // Top of questions, for new page\n case 'top' :\n\n // Target different elements based on whether you're inside Sharepoint or not\n if ($('#s4-workspace').length > 0) {\n\n // Sharepoint\n $('#s4-workspace').animate({scrollTop: sharepointTop}, duration);\n\n } else {\n\n // Local\n $('html, body').animate({scrollTop: $('#quiz-top').offset().top}, duration);\n\n }\n\n break;\n\n // Bottom of quiz, to see Next buttons\n case 'bottom' :\n\n // Target different elements based on whether you're inside Sharepoint or not\n if ($('#s4-workspace').length > 0) {\n\n // Sharepoint\n $('#s4-workspace').animate({scrollTop: sharepointBottom}, duration);\n\n } else {\n\n // Local\n $('html, body').animate({scrollTop: $('#quiz-bottom').offset().top}, duration);\n\n }\n\n break;\n\n }\n\n }\n\n\n // count how many steps there are\n var step_count = $('div[id*=\"step-\"]').size();\n\n\n $('input[id*=\"submit_\"]').click(function(e) {\n\n //prevent default link behaviour\n e.preventDefault();\n\n //console.log(\"button clicked \" + this.id);\n next_step(this.id.substring(7)) \n });\n\n // hide everything that needs hiding for the initial step\n $('div[id*=\"step-\"]').hide();\n $('#results').hide();\n $( \".progress-wrap\" ).css(\"display\", \"none\");\n $( \"#start-quiz\" ).click(function(e) {\n\n // Prevent the link executing\n e.preventDefault();\n first_step();\n });\n\n\n function first_step() {\n $('#intro').fadeOut('fast');\n\n\n window.setTimeout(function(){\n $('#step-1').fadeIn('slow');\n $( \".progress-wrap\" ).fadeIn('slow');\n }, 200);\n }\n\n function next_step(current_step) {\n var progress = Math.round(current_step * (100 / step_count));\n // Show your progress\n updateProgress(progress);\n\n $('#step-'+current_step).fadeOut('fast');\n \n if(current_step < step_count) {\n // Remove screen 1, show screen 2\n var t = window.setTimeout(function(){\n $('#step-'+(eval(current_step)+1)).fadeIn('slow');\n }, 200);\n } else {\n //console.log(\"Doing final step\");\n final_step();\n }\n }\n\n\n function final_step() {\n $(\"#quiz_form\").bind(\"ajax:success\",\n function(evt, data, status, xhr){\n //this assumes the action returns an HTML snippet\n handle_results(data.correct_answers);\n }).bind(\"ajax:error\", \n function(evt, data, status, xhr){\n //do something with the error here\n });\n\n $('#quiz_form').submit();\n\n }\n\n function handle_results(correctAnswers) {\n var totalAnswers = step_count;\n // You now know how many answer there are and how many you got right, so turn that into a percentage\n var percentageCorrect = Math.round((correctAnswers / totalAnswers) * 100);\n \n // Pass mark is 70% - show pass or fail message\n if (percentageCorrect >= 70) {\n\n // Set pass title and score message\n $('#quiz-results-message').html('Well done!');\n $('#quiz-results-text').html('You scored ' + percentageCorrect + '% - you obviously paid attention and have successfully passed the quiz!');\n\n // Submit score (pass)\n MySiteQuizSubmit(percentageCorrect, true);\n\n // You've passed, so no need to show the Try Again button\n $('#quiz-retry-button').hide();\n\n } else {\n\n // Set failure title and score message\n //$('#quiz-results-message').html('So close!');\n //$('#quiz-results-text').html(\"You scored \" + percentageCorrect + \"%\");\n $('#quiz-results-text').html(\"

You scored \" + percentageCorrect + \"% \" + \"(\" + correctAnswers + \"/\" + totalAnswers + \")

\");\n $('#quiz-attempts-text').html(\"

YOU HAVE 3 ATTEMPTS LEFT

\");\n //$('#quiz-results-text').html(\"

You scored \" + percentageCorrect + \"%

\");\n //$('#quiz-attempts-text').html(\"

You have 3 attempts remaining

\"); \n\n // Submit score (fail)\n MySiteQuizSubmit(percentageCorrect, false);\n\n // Make sure the Try Again button is visible\n $('#quiz-retry-button').show();\n\n }\n\n // Remove screen X, show screen X+1\n $('#results').slideDown();\n\n // Remove the progress bar\n $('#msch-progress_bar').hide();\n\n }\n\n //\n //\n // ***** Disable the quiz page submit buttons until you've answered enough questions on each page *****\n //\n //\n $('.msch-quiz-button').attr('disabled', 'disabled');\n $('.msch-quiz-button').addClass('msch-quiz-button-disabled');\n $('.msch-quiz-button').fadeTo(0, 0.5);\n\n // Reverse the above for the Try Again button at the end of the quiz\n $('#quiz-retry-button').removeAttr('disabled');\n $('#quiz-retry-button').removeClass('msch-quiz-button-disabled');\n $('#quiz-retry-button').fadeTo(0, 1);\n\n //\n //\n // ***** Watch for the user clicking an answer radio button to count answers on each page *****\n //\n //\n\n // Select all radio buttons the user could click to answer\n var answerCheckRadioButtons = $('#msch-container input[type=radio]');\n\n // Add a click action to them\n answerCheckRadioButtons.on('click', function() {\n var answerCounter = $('#msch-container input[type=radio]:checked').size();\n var numberOfQuestionsPerPage = 1;\n var targetQuizPage = answerCounter / numberOfQuestionsPerPage;\n var targetButton = $('#submit_' + targetQuizPage);\n\n // Turn that target into an addressable submit button, then remove the disabled class from that button\n // If you have the correct button, switch it back on and remove the disabled classes\n if (targetButton) {\n targetButton.removeAttr('disabled');\n targetButton.removeClass('msch-quiz-button-disabled');\n targetButton.fadeTo(0, 1);\n\n // Kill the reference to the target button, ready for the next click\n targetButton = null;\n }\n });\n});"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252931,"cells":{"blob_id":{"kind":"string","value":"0d19111d92250b607d509301fd4500e3298c30ea"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"CSA-DanielVillamizar/voteomatic"},"path":{"kind":"string","value":"/resources/js/mixins/meetingMixin.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1166,"string":"1,166"},"score":{"kind":"number","value":2.625,"string":"2.625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"/**\n * For any component that needs access to the\n * current meeting.\n *\n * @type {{computed: {}}}\n */\nmodule.exports = {\n data: function () {\n return {\n linkBase: \"https://voteomatic.com/lti-entry/\"\n }\n },\n\n computed: {\n\n /**\n * The current global meeting\n */\n meeting: {\n get : function(){\n return this.$store.getters.getActiveMeeting;\n },\n set : function(v){\n this.$store.commit('setMeeting', v);\n }\n },\n\n\n /**\n * The link that the user will enter into\n * canvas\n */\n meetingLink: {\n\n get: function () {\n return this.linkBase + this.meeting.id;\n },\n default: false\n },\n\n\n meetingName: function () {\n if (_.isUndefined(this.meeting) || _.isNull(this.meeting)) return '';\n\n return this.meeting.name;\n },\n\n meetingDate: function () {\n if (_.isUndefined(this.meeting) || _.isNull(this.meeting)) return '';\n\n return this.meeting.readableDate();\n },\n }\n};\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252932,"cells":{"blob_id":{"kind":"string","value":"4c84362c7bf6b37f9dfaa5a577f195af642adbec"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"alermar69/StairsGit"},"path":{"kind":"string","value":"/StairsGit/JavaScript/work/calculator/timber_stock/change_offer.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":20884,"string":"20,884"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"function changeOffer() {\n\nvar stairModel = params.stairModel;\nvar model = params.model;\n\n\n/*меняем главное описание*/\nif (model == \"тетивы\") {\n\tdocument.getElementById('description').innerHTML = \n\"

Изящная полностью деревянная лестница в классическом стиле.\" + \n\"Лестница изготавливается из клееного мебельного щита высочайшего качества.\" + \n\"Каркас лестницы - две клееные деревянные балки с пазами, в которые устанавливаются ступени.\"\n\"Пазы фрезеруются на специализированном фрезерном станке с программным управлением, что обеспечивает\" +\n\"идеальную точность размеров, аккуратность соединений и отсутствие скрипов во время эксплуатации.\" +\n\"Лестница отличается высочайшим качеством изготовления, использованием натуральных экологичных материалов\" + \n\"и великолепным современным дизайном. Предназначена для установки внутри помещения в частных домах и квартирах.\" +\n\"

\" +\n\"

Особенности модели

\" +\n\"
    \" +\n\t\"
  • Надежная конструкция выдерживает нагрузку до 400 кг;
  • \" +\n\t\"
  • Лестница красится в заводских условиях в выбранный Вами цвет;
  • \" +\n\t\"
  • Лестница идеально подойдет Вам, так как изготавливается на заказ под Ваш размер;
  • \" +\n\t\"
  • Лестница изготавливается на автоматическом оборудовании, что обеспечивает высочайшую точность и качество всех деталей;
  • \" +\n\t\"
  • Продуманная конструкция позволяет собрать и установить лестницу на объекте за 3-4 часа.;
  • \" +\n\"
\";\n\n\n}\nif (model == \"косоуры\") {\ndocument.getElementById('description').innerHTML = \n\"

Классическая полностью деревянная лестница на косоурах.\" + \n\"Лестница изготавливается из клееного мебельного щита высочайшего качества. \" + \n\"Каркас лестницы - две клееные деревянные балки с вырезами, в которые устанавливаются ступени. \" + \n\"Косоуры изготавливаюстя на специализированном фрезерном станке с программным управлением, что обеспечивает\" +\n\"идеальную точность размеров, аккуратность соединений и отсутствие скрипов во время эксплуатации.\" +\n\"Лестница отличается высочайшим качеством изготовления, использованием натуральных экологичных материалов\" + \n\"и строгим классическим дизайном. Предназначена для установки внутри помещения в частных домах и квартирах.\" +\n\"

\" +\n\"

\" +\n\"

Особенности модели

\" +\n\"
    \" +\n\t\"
  • Надежная конструкция выдерживает нагрузку до 400 кг;
  • \" +\n\t\"
  • Лестница красится в заводских условиях в выбранный Вами цвет;
  • \" +\n\t\"
  • Лестница идеально подойдет Вам, так как изготавливается на заказ под Ваш размер;
  • \" +\n\t\"
  • Лестница изготавливается на автоматическом оборудовании, что обеспечивает высочайшую точность и качество всех деталей;
  • \" +\n\t\"
  • Продуманная конструкция позволяет собрать и установить лестницу на объекте за 3-4 часа.;
  • \" +\n\"
\";\n\n}\n\nif (model == \"тетива+косоур\") {\ndocument.getElementById('description').innerHTML = \n\"

Классическая полностью деревянная лестница на косоурах.\" + \n\"Лестница изготавливается из клееного мебельного щита высочайшего качества.\" + \n\"Каркас лестницы - две клееные деревянные балки с вырезами, в которые устанавливаются ступени.\"\n\"Косоуры изготавливаюстя на специализированном фрезерном станке с программным управлением, что обеспечивает\" +\n\"идеальную точность размеров, аккуратность соединений и отсутствие скрипов во время эксплуатации.\" +\n\"Лестница отличается высочайшим качеством изготовления, использованием натуральных экологичных материалов\" + \n\"и строгим классическим дизайном. Предназначена для установки внутри помещения в частных домах и квартирах.\" +\n\"

\" +\n\"

\" +\n\"

Особенности модели

\" +\n\"
    \" +\n\t\"
  • Надежная конструкция выдерживает нагрузку до 400 кг;
  • \" +\n\t\"
  • Лестница красится в заводских условиях в выбранный Вами цвет;
  • \" +\n\t\"
  • Лестница идеально подойдет Вам, так как изготавливается на заказ под Ваш размер;
  • \" +\n\t\"
  • Лестница изготавливается на автоматическом оборудовании, что обеспечивает высочайшую точность и качество всех деталей;
  • \" +\n\t\"
  • Продуманная конструкция позволяет собрать и установить лестницу на объекте за 3-4 часа.;
  • \" +\n\"
\";\n\n}\n\n\n//complectDescription();\n}\n\nfunction complectDescription(){\n\n/*конструкция*/\nvar stairModel = params.stairModel;\nvar model = params.model;\nvar metalPaint = params.metalPaint;\n\nvar carcasText_3;\nvar carcasText_4;\nvar carcasImage;\nif (stairModel == \"Прямая\") carcasImage = \"001.jpg\";\nif (stairModel == \"Г-образная с площадкой\") carcasImage = \"002.jpg\";\nif (stairModel == \"Г-образная с забегом\") carcasImage = \"004.jpg\";\nif (stairModel == \"П-образная с площадкой\") carcasImage = \"003.jpg\";\nif (stairModel == \"П-образная с забегом\") carcasImage = \"005.jpg\";\nif (stairModel == \"П-образная трехмаршевая\") carcasImage = \"005.jpg\";\t\n//document.getElementById('carcasImage').innerHTML =\t\"\";\n\nif (model == \"лт\") carcasText_3 = \"Каркас остается видимым, подчеркивая оригинальность дизайна;\";\nif (model == \"ко\") carcasText_3 = \"Каркас можно легко и быстро обшить гипсокартоном, построить под лестницей стенку или оставить видимым;\";\n\nif (metalPaint == \"нет\") carcasText_4 = \"Детали каркаса поставляются зачищенными и подготовленными под покраску;\";\nif (metalPaint == \"грунт\") carcasText_4 = \"Детали каркаса поставляются покрытыми антикоррозийным гнутом;\";\nif (metalPaint == \"порошок\") carcasText_4 = \"Каркас покрываются красивой, прочной и долговечной порошковой краской;\";\nif (metalPaint == \"автоэмаль\") carcasText_4 = \"Для идеального внешнего вида, детали каркаса шпаклюются, шлифуются и покрываются высокоглянцевой автомобильной эмалью в 3 слоя;\";\n\ndocument.getElementById('carcasText_3').innerHTML =\tcarcasText_3; \ndocument.getElementById('carcasText_4').innerHTML =\tcarcasText_4; \n\n\n/*ступени*/\nsetTreadDescr();\n\n\n/*ограждения*/\n\n\nvar railingModel = document.getElementById('railingModel').options[document.getElementById('railingModel').selectedIndex].value;\nvar handrail = document.getElementById('handrail').options[document.getElementById('handrail').selectedIndex].value;\nvar rackType = null;//document.getElementById('banisterMaterial').options[document.getElementById('banisterMaterial').selectedIndex].value;\nvar rigelMaterial = null;//document.getElementById('rigelMaterial').options[document.getElementById('rigelMaterial').selectedIndex].value;\nvar rigelAmt = null;//document.getElementById('rigelAmt').options[document.getElementById('rigelAmt').selectedIndex].value;\n\nvar railingMetalPaint;\nvar railingTimberPaint;\nvar railingHeader;\nvar railingImage;\nvar railingText_1;\nvar railingText_2;\nvar railingText_3;\nvar railingText_4;\nvar railingText_5;\nvar railingText_6;\n\n/*поручень*/\n\nif (handrail == \"40х20 черн.\"){\n\trailingText_2 = \"Поручень из профильной трубы 40х20мм из конструкционной стали\";\n\trailingMetalPaint = \"сталь\";\n\t}\nif (handrail == \"40х40 черн.\"){\n\trailingText_2 = \"Поручень из профильной трубы 40х40мм из конструкционной стали\";\n\trailingMetalPaint = \"сталь\";\n\t}\nif (handrail == \"60х30 черн.\"){\n\trailingText_2 = \"Поручень из профильной трубы 60х30мм из конструкционной стали\";\n\trailingMetalPaint = \"сталь\";\n\t}\nif (handrail == \"кованый полукруглый\"){\n\trailingText_2 = \"Кованый полукруглый поручень подчеркивает оригинальность ограждений;\";\n\trailingMetalPaint = \"сталь\";\n\t}\nif (handrail == \"40х40 нерж.\"){\n\trailingText_2 = \"Поручень из квадратной нержавеющей трубы 40х40мм подчеркивает оригинальность ограждений;\";\n\t}\nif (handrail == \"Ф50 нерж.\"){\n\trailingText_2 = \"Поручень из круглой нержавеющей трубы подчеркивает оригинальность ограждений;\";\n\t}\nif (handrail == \"Ф50 сосна\"){\n\trailingText_2 = \"Круглый поручень из массива сосны теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;\";\n\trailingTimberPaint = \"дерево\";\n\t}\nif (handrail == \"омега-образный сосна\"){\n\trailingText_2 = \"Классический фигурный поручень из массива сосны теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;\";\n\trailingTimberPaint = \"дерево\";\n\t}\nif (handrail == \"50х50 сосна\"){\n\trailingText_2 = \"Квадратный поручень из массива сосны теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;\";\n\trailingTimberPaint = \"дерево\";\n\t}\nif (handrail == \"40х60 береза\"){\n\trailingText_2 = \"Прямоугольный поручень из массива березы теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;\";\n\trailingTimberPaint = \"дерево\";\n\t}\nif (handrail == \"омега-образный дуб\"){\n\trailingText_2 = \"Классический фигурный поручень из массива дуба теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;\";\n\trailingTimberPaint = \"дерево\";\n\t}\nif (handrail == \"40х60 дуб\"){\n\trailingText_2 = \"Прямоугольный поручень из массива дуба теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;\";\n\trailingTimberPaint = \"дерево\";\n\t}\nif (handrail == \"40х60 дуб с пазом\"){\n\trailingText_2 = \"Прямоугольный поручень из массива дуба теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;\";\n\trailingTimberPaint = \"дерево\";\n\t}\nif (handrail == \"Ф50 нерж. с пазом\"){\n\trailingText_2 = \"Круглый нержавеющий поручень подчеркивает оригинальность ограждений;\";\n\t}\nif (handrail == \"40х60 нерж. с пазом\"){\n\trailingText_2 = \"Прямоугольный нержавеющий поручень подчеркивает оригинальность ограждений;\";\n\t}\t\nif (handrail == \"нет\"){\n\trailingText_2 = \"Отсутствие поручня подчеркивает оригинальность ограждений;\";\n\t}\nif (handrail == \"сосна\"){\n\trailingText_2 = \"Прямоугольный поручень из массива сосны теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;\";\n\trailingTimberPaint = \"дерево\";\n\t}\nif (handrail == \"береза\"){\n\trailingText_2 = \"Прямоугольный поручень из массива березы теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;\";\n\trailingTimberPaint = \"дерево\";\n\t}\nif (handrail == \"лиственница\"){\n\trailingText_2 = \"Прямоугольный поручень из массива лиственницы теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;\";\n\trailingTimberPaint = \"дерево\";\n\t}\nif (handrail == \"дуб паркет.\"){\n\trailingText_2 = \"Прямоугольный поручень из массива дуба теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;\";\n\trailingTimberPaint = \"дерево\";\n\t}\nif (handrail == \"дуб ц/л\"){\n\trailingText_2 = \"Прямоугольный поручень из массива дуба теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;\";\n\trailingTimberPaint = \"дерево\";\n\t}\nif (handrail == \"ПВХ\"){\n\trailingText_2 = \"Круглый поручень из ПВХ, теплый и приятный на ощупь, подчеркивает оригинальный дизайн ограждений;\";\n\trailingTimberPaint = \"дерево\";\n\t}\n\nif (railingModel == \"Ригели\") {\n\trailingHeader = \"Ограждения с ригелями\";\n\trailingText_1 = \"Изящные минималистичные ограждения с горизонтальным заполнением (ригелями)\";\n\trailingImage = \"001.jpg\";\n\tif (rackType == \"40х40 черн.\") {\n\t\trailingText_3 = \"Стойки из квадратной профильной трубы 40х40мм из конструкционной стали\";\n\t\trailingMetalPaint = \"сталь\";\n\t\t}\n\tif (rackType == \"40х40 нерж+дуб\") {\n\t\trailingText_3 = \"Стойки квадратного сечения из нержавейки со вставками из массива дуба;\";\n\t\trailingTimberPaint = \"дерево\";\n\t\t}\n\tif (rackType == \"40х40 нерж.\") {\n\t\trailingText_3 = \"Стойки из профильной трубы 40х40мм из полированной нержавеющей стали;\";\n\t\t}\n\tif (rigelMaterial == \"20х20 черн.\") {\n\t\trailingText_4 = \"Ригеля из квадратной 20х20мм из конструкционной стали, \" + rigelAmt + \"шт.;\"\n\t\trailingMetalPaint = \"сталь\";\n\t\t}\n\tif (rigelMaterial == \"Ф12 нерж.\") {\n\t\trailingText_4 = \"Ригеля из круглой неравеющей трубки Ф12мм, \" + rigelAmt + \"шт.;\"\n\t\t}\n\tif (rigelMaterial == \"Ф16 нерж.\"){\n\trailingText_4 = \"Ригеля из круглой неравеющей трубки Ф16мм, \" + rigelAmt + \"шт.;\"\t\n\t}\n}\nif (railingModel == \"Стекло на стойках\") {\n\trailingHeader = \"Стеклянные ограждения на стойках\";\n\trailingText_1 = \"Ограждения в современном стиле со стеклом, установенным между стойкаи\";\n\trailingImage = \"003.jpg\";\n\tif (rackType == \"40х40 черн.\") {\n\t\trailingText_3 = \"Квадратные стойки из конструкционной стали сечением 40х40\";\n\t\trailingMetalPaint = \"сталь\";\n\t\t}\n\tif (rackType == \"40х40 нерж+дуб\") {\n\t\trailingText_3 = \"Стойки квадратного сечения из нержавейки со вставками из массива дуба;\";\n\t\trailingTimberPaint = \"дерево\";\n\t\t}\n\tif (rackType == \"40х40 нерж.\") {\n\t\trailingText_3 = \"Стойки квадратного сечения из полированной нержавеющей стали;\";\n\t\t}\n\trailingText_4 = \"Между стойками устанавливается закаленное стекло толщиной 8мм;\"\t\n\t}\nif (railingModel == \"Самонесущее стекло\") {\n\trailingHeader = \"Стеклянные ограждения без стоек\";\n\trailingText_1 = \"Стильные полностью стеклянные ограждения. Толстое закаленное стекло крепится прямо к торцу марша\";\n\trailingImage = \"004.jpg\";\n\trailingText_3 = \"Ограждение из толстого закаленного стекла толщиной 12мм;\"\n\trailingText_4 = \"\";\n\t}\n\nif (railingTimberPaint == \"дерево\"){\n\tif (timberPaint == \"нет\") railingText_6 = \"Деревянные детали ограждений поставляются отшлифованными и подготовленными к покраске\";\n\tif (timberPaint == \"лак\") railingText_6 = \"Деревянные детали ограждений покрываются прозрачным лаком\";\n\tif (timberPaint == \"морилка+лак\") railingText_6 = \"Деревянные детали ограждений тонируются в выбранный Вами цвет и покрываются лаком\";\n}\n\n\ndocument.getElementById('railingHeader').innerHTML = railingHeader;\ndocument.getElementById('railingImage').innerHTML =\t\"\";\ndocument.getElementById('railingText_1').innerHTML =railingText_1;\ndocument.getElementById('railingText_2').innerHTML =railingText_2;\ndocument.getElementById('railingText_3').innerHTML =railingText_3;\ndocument.getElementById('railingText_4').innerHTML =railingText_4;\ndocument.getElementById('railingText_5').innerHTML =railingText_5;\ndocument.getElementById('railingText_6').innerHTML =railingText_6;\nif (!railingText_4) document.getElementById('railingText_4').style.display = \"none\";\nelse document.getElementById('railingText_4').style.display = \"list-item\";\nif (!railingText_5) document.getElementById('railingText_5').style.display = \"none\";\nelse document.getElementById('railingText_5').style.display = \"list-item\";\nif (!railingText_6) document.getElementById('railingText_6').style.display = \"none\";\nelse document.getElementById('railingText_6').style.display = \"list-item\";\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252933,"cells":{"blob_id":{"kind":"string","value":"ee5b0b3da4f94fbff31cbaf05db6acea9485376f"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"LoriWinston/lab-04-pokemon-api"},"path":{"kind":"string","value":"/src/Components/Sort.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":738,"string":"738"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"// import React, { Component } from 'react'\n// import pokeData from '../Data'\n\n// export default class Sort extends Component {\n// render() {\n// return (\n// \n// {\n// // we are passed an array of options from the parent\n// this.props.options.sort(\n// // for each list item\n// (a, b) => a[this.props.pokemon].localeCompare(b[this.props.pokemon])\n// console.log(this.props.pokemon, 'HELP')\n// )\n// }\n\n// \n// )\n// }\n// }"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252934,"cells":{"blob_id":{"kind":"string","value":"71543857d7cc2a259e012b8f966e149b0bd37ecb"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"karanaso/node-cluster-phrases"},"path":{"kind":"string","value":"/specs/unit/source/phrasesAssessor.spec.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4406,"string":"4,406"},"score":{"kind":"number","value":2.796875,"string":"2.796875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"const should = require('should');\nconst rewire = require('rewire');\nconst os = require('os');\n\nconst phrasesAssessor = rewire('../../../source/phrasesAssessor');\n\ndescribe('phrasesAssessor.js', () => {\n let textData;\n\n beforeEach(() => {\n textData = 'hypertensive disorder' + os.EOL +\n 'acid reflosux' + os.EOL +\n 'gastritus';\n });\n\n describe('textDataToArray', () => {\n it('should be an empyt array if no data are present', () => {\n const textDataToArray = phrasesAssessor.__get__('textDataToArray');\n textDataToArray().should.have.length(0);\n });\n\n it('should return an array with three objects', () => {\n const textDataToArray = phrasesAssessor.__get__('textDataToArray');\n const expectedResult = ['hypertensive disorder', 'acid reflosux', 'gastritus'];\n textDataToArray(textData).should.have.length(3);\n });\n\n it('first item should be \"hypertensive disorder\"', () => {\n const textDataToArray = phrasesAssessor.__get__('textDataToArray');\n textDataToArray(textData)[0].should.equal('hypertensive disorder')\n });\n\n it('second item should be \"acid reflosux\"', () => {\n const textDataToArray = phrasesAssessor.__get__('textDataToArray');\n textDataToArray(textData)[1].should.equal('acid reflosux');\n });\n\n it('third item should be \"gastritus\"', () => {\n const textDataToArray = phrasesAssessor.__get__('textDataToArray');\n textDataToArray(textData)[2].should.equal('gastritus');\n });\n });\n\n describe('transformToObj', () => {\n let transformToObj;\n let obj;\n\n beforeEach(() => {\n transformToObj = phrasesAssessor.__get__('transformToObj');\n obj = phrasesAssessor.__get__('obj');\n });\n\n it('should create an internal object \"obj\" to hold keys and values', () => {\n transformToObj(['a b c']);\n obj.should.exist;\n Object.keys(obj).should.have.length(1);\n });\n\n it('should replace spaces with underscore', () => {\n transformToObj(['a b c']);\n obj['a_b_c'].should.exist;\n });\n\n it('should set the value to 0 to for a non existing key', () => {\n transformToObj(['a b c']);\n obj['a_b_c'].should.equal(0);\n });\n\n it('should not increase the value of a key if found twice', () => {\n transformToObj(['a b c']);\n transformToObj(['a b c']);\n obj['a_b_c'].should.equal(0);\n });\n });\n\n describe('prepareData', () => {\n it('should prepare the data for processing into obj', () => {\n const obj = phrasesAssessor.prepareData(textData);\n Object.keys(obj).should.have.length(4);\n obj['a_b_c'].should.equal(0);;\n obj['hypertensive_disorder'].should.equal(0);\n obj['acid_reflosux'].should.equal[0];\n obj['gastritus'].should.equal(0);\n });\n });\n\n describe('increaseCounterForKeys', () => {\n it('should increase counters for [\"gastritus\",\"hypertensive_disorder\"]', () => {\n const increaseCounterForKeys = phrasesAssessor.__get__('increaseCounterForKeys');\n const obj = phrasesAssessor.__get__('obj');\n increaseCounterForKeys([\"gastritus\", \"hypertensive_disorder\"]);\n obj['gastritus'].should.equal(1);\n obj['hypertensive_disorder'].should.equal(1);\n });\n });\n\n describe('underScoresToSpaces', () => {\n it('should return \"hypertensive disorder\" for key [\"hypertensive_disorder\"]', () => {\n const underScoresToSpaces = phrasesAssessor.__get__('underScoresToSpaces');\n const obj = phrasesAssessor.__get__('obj');\n underScoresToSpaces([\"hypertensive_disorder\"])[0].should.equal('hypertensive disorder')\n });\n });\n\n describe('assessPhrase', () => {\n it('should return only \"gastritus\" from phrase \"I have gastritus\"', () => {\n phrasesAssessor.assessPhrase('I have gastritus')[0].should.equal('gastritus');\n });\n\n it('should return only \"hypertensive_disorder\" phrase \"I have hypertensive disorder\"', () => {\n phrasesAssessor.assessPhrase('I have hypertensive disorder')[0].should.equal('hypertensive disorder');\n });\n\n it('should return [\"gastritus\",\"hypertensive disorder\" from phrase \"I think I gastritus and hypertensive disorder\"', () => {\n const phrase = \"I think I gastritus and hypertensive disorder\";\n const results = phrasesAssessor.assessPhrase(phrase);\n results.indexOf('hypertensive disorder').should.be.above(-1);\n results.indexOf('gastritus').should.be.above(-1);\n });\n });\n});"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252935,"cells":{"blob_id":{"kind":"string","value":"4c47f4ceb2979fec9d04472b7333a0f9203c26ae"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"captain-blue210/typescript-lesson"},"path":{"kind":"string","value":"/function-class/points.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":225,"string":"225"},"score":{"kind":"number","value":2.703125,"string":"2.703125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"var Point = /** @class */ (function () {\n function Point() {\n this.x = 0;\n this.y = 0;\n }\n return Point;\n}());\nvar pointA = new Point();\nvar pointB = { x: 2, y: 4 };\nvar pointC = { x: 5, y: 5, z: 10 };\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252936,"cells":{"blob_id":{"kind":"string","value":"146e2fe6a2fc5585f8bfb7d79208e9854401f7e1"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"derhuerst/vbb-rest"},"path":{"kind":"string","value":"/lib/to-ndjson-buf.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":310,"string":"310"},"score":{"kind":"number","value":2.578125,"string":"2.578125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["ISC"],"string":"[\n \"ISC\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"const toNdjsonBuf = (items) => {\n\tconst chunks = []\n\tlet i = 0, bytes = 0\n\tfor (const item of items) {\n\t\tconst sep = i++ === 0 ? '' : '\\n'\n\t\tconst buf = Buffer.from(sep + JSON.stringify(item), 'utf8')\n\t\tchunks.push(buf)\n\t\tbytes += buf.length\n\t}\n\treturn Buffer.concat(chunks, bytes)\n}\n\nexport {\n\ttoNdjsonBuf,\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252937,"cells":{"blob_id":{"kind":"string","value":"e733b0d37f8bd4e512fcaa59cec834941047c782"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"kscarrot/involution"},"path":{"kind":"string","value":"/src/leetcode/LC104.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":296,"string":"296"},"score":{"kind":"number","value":3.234375,"string":"3.234375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"/**\n * @param {TreeNode} root\n * @return {number}\n * @tag tree\n * @description\n[二叉树的最大深度](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/)\n */\nvar maxDepth = function (root) {\n if (!root) return 0\n return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252938,"cells":{"blob_id":{"kind":"string","value":"c763b453c9f07bfe633c47fe12dee7f5f2a6c89b"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"jike132/doc"},"path":{"kind":"string","value":"/js/func.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4473,"string":"4,473"},"score":{"kind":"number","value":4.03125,"string":"4.03125"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"//手写实现call\n/*\n\n思路:\n\ncontext容错处理\nSymbol实现唯一key值\ncontext对象新增唯一key属性,赋值:myCall的调用者\n此时this已指向context对象\n执行context对象里面的调用者函数\n\n删除添加的唯一key值属性\n\n\n */\n */\nFunction.prototype.call2 = function (context) {\n var context = context || window;\n context.fn = this;\n\n var args = [];\n for(var i = 1, len = arguments.length; i < len; i++) {\n args.push('arguments[' + i + ']');\n }\n\n var result = eval('context.fn(' + args +')');\n delete context.fn\n\n return result;\n}\nfunction test(y,z){\n return y+z\n}\nconsole.log(test.call2(this,1,2));\n\n\nwindow.name = 'global_name_ts'\n\nconst object = {\n name: 'Jake'\n}\n\nFunction.prototype.myCall = function (context, ...args) {\n /*\n       错误做法:直接 context = context || window\n       context值为null和undefined的,this会自动指向全局对象\n       值为数字0、空字符串、布尔值false的this也会指向该原始值的实例对象\n   */\n context = [null, undefined].includes(context) ? window : Object(context)\n\n // 给context对象新增一个独一无二的属性以免覆盖原有同名属性,并赋值为:调用者fun函数\n console.log('新增属性前:', context);\n const key = Symbol('call中独一无二的属性')\n context[key] = this\n console.log('新增属性后:', context);\n\n // 执行context对象里面的fun函数,此时fun函数里面的this指向调用者context\n const res = context[key](...args)\n\n    delete context[key]\n return res\n}\n\nconsole.log('-------------------------myCall------------------------------');\nfnA() // 直接指向window\nfnA.myCall(object, 1, 2)\n//手写实现 apply\n\n// (window)全局默认name值\nwindow.name = 'global_name_ts'\n​\nconst object = {\n name: 'Jake'\n}\n​\nFunction.prototype.myApply = function (context, args) {\n context = [null, undefined].includes(context) ? window : Object(context)\n​\n    const key = Symbol('apply中独一无二的属性')\n context[key] = this\n​\n    const res = context[key](...args)\n​\n    delete context[key]\n return res\n}\n​\nfunction fnA (...args) {\n console.log('结果👉', this.name, ...args)\n}\n​\nconsole.log('-------------------------myApply------------------------------');\nfnA() // 直接指向window\nfnA.myApply(object, [1, 2])\n\n//手写实现bind\n/*\n思路:\n\n拷贝调用源:通过变量储存源函数\n\n编写返回函数:\n源函数再调用call或者apply函数进行this改向\nnew判断:通过instanceof判断函数是否通过new调用,来决定绑定的context\n绑定this并且传递参数(参数 = myBind调用传参 + 内部返回函数调用传参)\n复制源函数的prototype给bindFn\n\n返回内部函数\n\n */\n// (window)全局默认name值\nwindow.name = 'global_name_ts'\n​\nconst object = {\n name: 'Jake'\n}\n​\nFunction.prototype.myBind = function (context) {\n context = [null, undefined].includes(context) ? window : Object(context)\n​\n    const that = this;\n // 指向类数组arguments对象,使用数组的slice方法得到新数组\n let args1 = [...arguments].slice(1)\n // let args1 = Array.prototype.slice.call(arguments, 1);\n​\n    let bindFn = function () {\n let args2 = [...arguments]\n // let args2 = Array.prototype.slice.call(arguments);\n ​\n /*\n         判断this instanceof bindFn是因为原生bind是可以new那个bind后返回的函数的\n       不是new的情况下this指向才会是context;\n       */\n return that.call(this instanceof bindFn ? this : context, ...args1.concat(args2));\n // return that.apply(this instanceof bindFn ? this : context, args1.concat(args2));\n }\n​\n // 复制源函数的prototype给bindFn,因为一些情况下函数没有prototype,比如箭头函数\n let Fn = function () { };\n Fn.prototype = that.prototype;\n bindFn.prototype = new Fn();\n​\n // 或者\n // bindFn.prototype = that.prototype // 但是有修改会被同时改动\n // bindFn.prototype = Object.create(that.prototype || Function.prototype)\n​\n    return bindFn;\n}\n​\nfunction fnB (...args) {\n console.log('结果👉', this.name, ...args);\n}\n​\nconsole.log('-------------------------myBind------------------------------');\nfnB() // 直接指向window\nfnB.myBind(object, 10, 20, 30)(40, 50) // bind函数返回的是一个函数,还需要手动执行"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252939,"cells":{"blob_id":{"kind":"string","value":"92f2dce3624a1017be8f2a0e5cebcef5e201252e"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"Vlad1m1r95/RubyTaskManager"},"path":{"kind":"string","value":"/app/assets/javascripts/tasks.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4146,"string":"4,146"},"score":{"kind":"number","value":2.515625,"string":"2.515625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":" window.onload = function() {\n let $selects_status = document.querySelectorAll('#status_select')\n let $selects_assignee = document.querySelectorAll('#assignee_select')\n let $search = document.querySelector('#search-js')\n \n let input = \"\"\n let $inputs = document.querySelectorAll('input')\n\n const task_name = document.querySelector('#task_name')\n const task_status = document.querySelector('#task_status')\n \n if(task_name){\n task_name.classList.add('form-control')\n }\n if(task_status){\n task_status.classList.add('form-control')\n}\nlet select_status = \"\"\nlet select_assignee = \"\"\nif($search){\n $search.addEventListener('click' , function(event){ \n event.preventDefault()\n $selects_status.forEach((value) => {\n select_status = value\n \n })\n\n \n $selects_assignee.forEach((value) => {\n select_assignee = value\n \n \n })\n $inputs.forEach((value) => {\n input = value\n })\n // console.log(select_status.value)\n // console.log(select_assignee.value)\n // console.log(input.value)\n })\n}\n \n \n \n\n \n \n \n \n \n \n $selects_status.forEach((select) => {\n select.classList.add('form-control')\n })\n \n $blocks = document.querySelectorAll('.block')\n \n $blocks.forEach((block) => {\n let $status = block.querySelector('.status')\n let $date = block.querySelector('.date-js')\n let $assignee = block.querySelector('.a_form')\n let $comment = block.querySelector('.comment')\n \n if($comment){\n $comment.addEventListener('click', function(){\n // let link = block.querySelector('.a-comment')\n // let href = link.getAttribute('href')\n // // document.location= href\n // // console.log(href)\n // window.history.replaceState('page2', 'Title', href); \n\n \n let comment = block.querySelector('.cmtjs')\n \n if(comment.style.opacity == 0){\n comment.style.transition = ' all 2s';\n comment.style.opacity = 1;\n comment.classList.remove('comment-close')\n \n comment.classList.add('comment-open')\n } else if(comment.style.opacity == 1){\n comment.style.opacity = 0;\n \n comment.classList.add('comment-close')\n comment.classList.remove('comment-open')\n \n comment.style.transition = '0s';\n \n }\n \n \n \n\n\n })\n }\n \n\n if($search){\n $search.addEventListener('click' , function(event){\n event.preventDefault()\n console.log($status.innerText)\n console.log($date.innerText)\n console.log($assignee.innerText)\n // if(input.value == undefined){\n // input.value = \"\"\n // }\n if(\n ($status.innerText === select_status.value && $date.innerText === input.value && $assignee.innerText === select_assignee.value) || \n ( input.value == \"\" && $status.innerText === select_status.value && select_assignee.value == \"\") || \n (input.value == \"\" && $status.innerText === select_status.value && $assignee.innerText === select_assignee.value) || \n ($date.innerText === input.value && $status.innerText === select_status.value && select_assignee.value == \"\")) {\n \n \n block.classList.add('show')\n block.classList.remove('hide')\n } else {\n block.classList.add('hide')\n block.classList.remove('show')\n }\n })\n }\n \n \n // console.log(select.value)\n \n // block.ondblclick = function(){\n // let link = block.querySelector('.a-change')\n // let href = link.getAttribute('href')\n\n // console.log(block)\n // console.log(href)\n // document.location= href\n\n // // return false\n // }\n block.addEventListener('dblclick', function(){\n link = block.querySelector('.a-change')\n href = link.getAttribute('href')\n document.location= href\n // window.history.pushState('page2', 'Title', href)\n })\n\n })\n\n//comment\n// $commentCommunuty = document.querySelector('.community-name') \n// if($commentCommunuty){\n// $commentCommunuty.classList.add(\"hide\") \n// }\n \n};\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252940,"cells":{"blob_id":{"kind":"string","value":"7b6aec39b8833845564220daacabc733646949f3"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"jealob/todo-list"},"path":{"kind":"string","value":"/controllers/todoController.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1972,"string":"1,972"},"score":{"kind":"number","value":3,"string":"3"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"// The controller contains the routes. that is control the request and response flow\n// require/immport all the dependencies including the model(todo)\nconst express = require(\"express\");\nconst task = require(\"../models/todo.js\");\nconst router = express.Router();\n// Import handlebars helper module package\nconst hbs = require('handlebars');\n\n// Create helper function to add one a value. To be use in displaying the list of task in task-block.hanldebars \nhbs.registerHelper('plusone', (val, opts) =>{\n return parseInt(val) + 1;\n });\n\n// Create the routes\n// get route/ Read\nrouter.get(\"/\", function (req, res) {\n task.all(function (data) {\n let hbsObject = {\n tasks: data\n };\n // console.log(hbsObject);\n res.render(\"index\", hbsObject);\n });\n});\n\n// Post route/ Create\nrouter.post(\"/api/tasks\", function (req, res) {\n task.create([\"task\", \"complete\"],\n [req.body.task, req.body.complete],\n function (result) {\n res.json({ id: result.insertId });\n }\n );\n});\n\n// Put Route /Update\nrouter.put(\"/api/tasks/:id\", function (req, res) {\n let condition = \"id = \" + req.params.id;\n // console.log(\"condition\", condition);\n task.update({\n complete: req.body.complete\n }, condition, function (result) {\n if (result.changedRows == 0) {\n // If no rows were changed, then the ID must not exist, so 404\n return res.status(404).end();\n } else {\n res.status(200).end();\n }\n });\n});\n\n// Delete route /delete\nrouter.delete(\"/api/tasks/:id\", function(req, res) {\n var condition = \"id = \" + req.params.id;\n \n task.delete(condition, function(result) {\n if (result.affectedRows == 0) {\n // If no rows were changed, then the ID must not exist, so 404\n return res.status(404).end();\n } else {\n res.status(200).end();\n }\n });\n });\n// Export router to server.js\nmodule.exports = router;"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252941,"cells":{"blob_id":{"kind":"string","value":"43a38b6abe0af9568df77319bd1590d186220727"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"ejohann/webpack-eslint"},"path":{"kind":"string","value":"/src/add-image.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":280,"string":"280"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"import Hd from './hd_logo.png';\n\nfunction addImage(){\n const img = document.createElement('img');\n img.alt = 'Hanne Digital Logo';\n img.width = 300;\n img.src = Hd;\n\n const body = document.querySelector('body');\n body.appendChild(img);\n}\n\nexport default addImage;"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252942,"cells":{"blob_id":{"kind":"string","value":"afa4316c66f0aa547fa45ecdb2a7983a8e78cff4"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"JohnVHumes/JohnVHumes_Web"},"path":{"kind":"string","value":"/build/web/js/components/blog.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":8267,"string":"8,267"},"score":{"kind":"number","value":2.515625,"string":"2.515625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"function blog(id) {\n\n// ` this is a \"back tick\". Use it to define multi-line strings in JavaScript.\nvar content = ` \n HW 1 Home Page\n

\n My web development experience consists of nothing, prior to this class. This is the first time I've worked on anything front end related.\n

\n

\n In this homework I learned about HTML, CSS, and how to publish a web page.\n The parts that I found easy were publishing the website, including links\n and images with html, and styling text with css \n Positioning elements in CSS is something I need to work on more, and it \n took me a little bit of time to grasp the system of nesting divs\n

\n HW 2 Routing &amp; DB\n

\n I think I briefly had an overview of Microsoft Access in a 100 level \n computer science class at Delaware County Community College. Until this \n week, that was the extent of my database exposure, to my memory. However,\n I'm taking a database class alongside this one, so I'm sure the double database\n dose will bring me up to speed quickly\n

\n

\n In this homework I learned how to include and utilize javascript files on my page, how to use javascript\n to inject html code into a page and have it be displayed, and how to set up and populate a database with MySQL Workbench\n The parts that I found easy were setting up the database, and writing Select statements \n I had trouble rewriting the code for routing and dropdowns, so I\n ended up using the provided template code, with no major tweaks.\n I ran into a issue wherein the starting page, home.js, wouldn't load initally\n

\n
    \n
  • \n To see how my routing works, click on these icons: home, then blog, then home again.\n \n
  • \n
  • \n To see my database work, click here.\n
  • \n
\n \n HW 3 Web API\n

\n Maybe unsuprisingly given my prior blog entries, this was my first jaunt\n into server-side database access code. My, how strange would it be otherwise?\n As if I'd never touched HTML, CSS, or any sort of database, but had extensive\n experience in writing database interfaces. That'd definitely be an interesting\n story to tell the kids, if you had exhausted every other possible story, every topic\n of conversation, and counted every ceiling tile prior.\n \n

\n \n
    \n Difficulties\n \n
  • \n Setting up tunneling was initally a little tricky\n
  • \n
  • \n I encountered an issue where my JSP files would suddenly and unceremoniously\n fail to acknowledge the inclusion of the gson library as valid\n
  • \n
  • \n SQL is finicky to the newcomer, and statements assembled over multiple lines\n of code can be somewhat tricky to bugfix to said newcomer.\n
  • \n
    \n Not-So-Difficulties\n \n
  • \n The GSON and mySQL connector libraries make a molehill out of a mountain, code complexity-wise\n
  • \n
  • \n The double dose from both this class and Principles of Database Systems is rapidly building my SQL tolerance, and my mySQL tolerance\n
  • \n
\n \n

\n I've implemented 3 table APIs, the faction table is linked to the web user table\n which seems important in the context of this and future assignments, but is of dubious use\n in the table's eventual purpose.\n
\n The character table is more cogent to the future mechanics of the website, but I couldn't\n dream up a sensible reason to link it to the web user table.\n
\n Thus, I've included both for your viewing pleasure.\n

\n
    \n
  • \n To see my web users api work, click here.\n
  • \n
  • \n To see my character table api work, click here.\n
  • \n
  • \n To see my faction table api work, click here.\n
  • \n
\n \n

\n Finally, before I forget, click here to see the intentionally caused and solved SQL bugs.\n
\n I fully support this part of the exercise, I feel it made the rest of the project a whole lot easier, and helped me learn a lot.\n

\n \n \n HW 4 Display Data\n

\n \n It's nearly 3am while writing this, so I'll keep this entry brief. This week\n I retrofitted last week's API into being displayed as a nice, neat table, using an ajax call.\n \n

    \n Difficulties\n \n
  • \n I spent about 3 hours trying to track down the hole where a JSON parsing call should be\n
  • \n
  • \n The lack of this call caused many functions to flag as invalid, and I spent most of that 3 hours analyzing the\n symptoms rather than the disease, as it were\n
  • \n
  • \n As this codebase grows, it's a bit of a hunt to find all the places where modifications need to allow new sample code\n to interface with other databases\n
  • \n
  • \n It took a bit of time to figure out how function scoping works in .js files, for the routing\n
  • \n
    \n Not-So-Difficulties\n \n
  • \n Updating the database tables to include images was a breeze, even though it felt like there should've been a better way to do it\n
  • \n\n
\n \n

\n \n
\n HW5 Tutorial Proposal\n \n \n \n
    \n Difficulties\n \n
  • \n I realized too late in this assignment that I probably should have just done the slideshow homework, I don't feel I've\n yet sufficiently developed my competency to deliver on this assignment\n
  • \n
  • \n I felt the selection criteria for topics was vague, and attempting to settle on an sufficient sample\n ate through most of the time and energy I had earmarked for this homework\n
  • \n\n
    \n Not-So-Difficulties\n \n
  • \n since poc.html was specified, I didn't have to wrestle with figuring out how to add a page with a unique style sheet and its\n own scripting into the routing table\n
  • \n\n
\n

\n \n HW6 Logon\n \n

\n \n

    \n Difficulties\n \n
  • \n I spent a solid 2 hours trying to fix a bug that was already fixed because I forgot to clear my cache\n
  • \n
  • \n Accidentally uploaded the .java files rather than the .class files, which baffled me for a while\n
  • \n
  • \n Deciding what an API returns and how it should return it is a little mindboggling\n
  • \n\n
    \n Not-So-Difficulties\n \n
  • \n Writing the APIs themselves\n
  • \n\n
\n

\n \n HW7 Delete\n \n

\n \n

    \n Difficulties\n \n
  • \n Many of my problems at this stage in the game are stemming from my early inconsistent use of naming conventions, I see how important a clean start is now\n
  • \n
  • \n Missing code in my table builder befuddled me for an hour\n
  • \n
  • \n It is a little tough to get my head around everything that is going on in the table builder\n
  • \n\n
    \n Not-So-Difficulties\n \n
  • \n This was a pretty easy homework overall, I had time to bring the functionalities of my faction table up to par with users and characters\n
  • \n\n
\n `;\n document.getElementById(id).innerHTML = content;\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252943,"cells":{"blob_id":{"kind":"string","value":"068f721c372ecb3487902ec6d6ba63a126445194"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"vy-b/FlixList"},"path":{"kind":"string","value":"/project/src/Tests/Movie.test.jsx"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3665,"string":"3,665"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"import React from 'react';\nimport {mount} from 'enzyme';\nimport Movie from '../Components/Movie'\nimport MovieTableEntry from '../Objects/MovieTableEntry'\nimport {BrowserRouter as Router} from 'react-router-dom'\n\ndescribe('Movie.jsx tests', () => {\n test('Renders without crashing', () => {\n const wrapper = createWrapper('testTitle', 'testYear', 'testPoster','testPlot','testCast','testRuntime','testGenre','testRated');\n });\n \n test('Has proper title.', () => {\n const movieTitle = 'testTitle';\n const wrapper = createWrapper(movieTitle, 'testYear', 'testPoster','testPlot','testCast','testRuntime','testGenre','testRated');\n const title = wrapper.find('.title');\n expect(title.length).toBe(1);\n expect(title.at(0).text()).toBe(movieTitle);\n })\n\n test('Has proper year.', () => {\n const movieYear = '2021';\n const wrapper = createWrapper('testTitle', movieYear, 'testPoster','testPlot','testCast','testRuntime','testGenre','testRated');\n const year = wrapper.find('.year');\n expect(year.length).toBe(1);\n expect(year.at(0).text()).toBe(movieYear);\n })\n\n test('Has proper poster.', () => {\n const moviePoster = 'testPoster';\n const wrapper = createWrapper('testTitle', 'testYear', moviePoster,'testPlot','testCast','testRuntime','testGenre','testRated');\n const poster = wrapper.find('.poster');\n expect(poster.length).toBe(1);\n expect(poster.find('img').prop('src')).toBe(moviePoster);\n })\n\n test('Has proper plot.', () => {\n const moviePlot = 'testPlot';\n const wrapper = createWrapper('testTitle', 'testYear', 'testPoster',moviePlot,'testCast','testRuntime','testGenre','testRated');\n const plot = wrapper.find('.plot');\n expect(plot.length).toBe(1);\n expect(plot.at(0).text()).toBe(moviePlot);\n })\n\n test('Has proper cast.', () => {\n const movieCast = 'testCast';\n const wrapper = createWrapper('testTitle', 'testYear', 'testPoster','testPlot',movieCast,'testRuntime','testGenre','testRated');\n const cast = wrapper.find('.cast');\n expect(cast.length).toBe(1);\n expect(cast.at(0).text()).toBe(movieCast);\n })\n\n test('Has proper runtime.', () => {\n const movieRuntime = '1h45m';\n const wrapper = createWrapper('testTitle', 'testYear', 'testPoster','testPlot','testCast', movieRuntime,'testGenre','testRated');\n const runtime = wrapper.find('.runtime');\n expect(runtime.length).toBe(1);\n expect(runtime.at(0).text()).toBe(movieRuntime);\n })\n test('Has proper genre.', () => {\n const movieGenre = 'testGenre';\n const wrapper = createWrapper('testTitle', 'testYear', 'testPoster','testPlot','testCast', 'testRuntime',movieGenre,'testRated');\n const genre = wrapper.find('.genre');\n expect(genre.length).toBe(1);\n expect(genre.at(0).text()).toBe(movieGenre);\n })\n test('Has proper rating.', () => {\n const movieRating = 'PG-13';\n const wrapper = createWrapper('testTitle', 'testYear', 'testPoster','testPlot','testCast', 'testRuntime','testGenre',movieRating);\n const rated = wrapper.find('.rated');\n expect(rated.length).toBe(1);\n expect(rated.at(0).text()).toBe(movieRating);\n })\n});\n\nfunction createWrapper(title, year, poster,plot,cast,runtime,genre,rated){\n const movieTableEntry = new MovieTableEntry('testId', title, plot, poster, rated, year, runtime, genre, cast);\n const movie = \n const wrapper = mount(movie);\n return wrapper;\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252944,"cells":{"blob_id":{"kind":"string","value":"479e772fac54d564c6c34851b4c36c75d6d9bb50"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"CesiumGS/cesium"},"path":{"kind":"string","value":"/packages/engine/Source/Scene/TilesetMetadata.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":5301,"string":"5,301"},"score":{"kind":"number","value":2.765625,"string":"2.765625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0","LicenseRef-scancode-free-unknown","BSD-3-Clause","LicenseRef-scancode-warranty-disclaimer","OFL-1.1","CC-BY-3.0","JSON","LicenseRef-scancode-unknown-license-reference","LicenseRef-scancode-proprietary-license","CC-BY-4.0","MPL-2.0","ISC","CC-BY-SA-2.0","LicenseRef-scancode-public-domain","MIT"],"string":"[\n \"Apache-2.0\",\n \"LicenseRef-scancode-free-unknown\",\n \"BSD-3-Clause\",\n \"LicenseRef-scancode-warranty-disclaimer\",\n \"OFL-1.1\",\n \"CC-BY-3.0\",\n \"JSON\",\n \"LicenseRef-scancode-unknown-license-reference\",\n \"LicenseRef-scancode-proprietary-license\",\n \"CC-BY-4.0\",\n \"MPL-2.0\",\n \"ISC\",\n \"CC-BY-SA-2.0\",\n \"LicenseRef-scancode-public-domain\",\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"import Check from \"../Core/Check.js\";\nimport defaultValue from \"../Core/defaultValue.js\";\nimport defined from \"../Core/defined.js\";\nimport MetadataEntity from \"./MetadataEntity.js\";\n\n/**\n * Metadata about the tileset.\n *

\n * See the {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_metadata|3DTILES_metadata Extension} for 3D Tiles\n *

\n *\n * @param {object} options Object with the following properties:\n * @param {object} options.tileset The tileset metadata JSON object.\n * @param {MetadataClass} options.class The class that tileset metadata conforms to.\n *\n * @alias TilesetMetadata\n * @constructor\n * @private\n * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.\n */\nfunction TilesetMetadata(options) {\n options = defaultValue(options, defaultValue.EMPTY_OBJECT);\n const tileset = options.tileset;\n const metadataClass = options.class;\n\n //>>includeStart('debug', pragmas.debug);\n Check.typeOf.object(\"options.tileset\", tileset);\n Check.typeOf.object(\"options.class\", metadataClass);\n //>>includeEnd('debug');\n\n const properties = defined(tileset.properties) ? tileset.properties : {};\n\n this._class = metadataClass;\n this._properties = properties;\n this._extras = tileset.extras;\n this._extensions = tileset.extensions;\n}\n\nObject.defineProperties(TilesetMetadata.prototype, {\n /**\n * The class that properties conform to.\n *\n * @memberof TilesetMetadata.prototype\n * @type {MetadataClass}\n * @readonly\n * @private\n */\n class: {\n get: function () {\n return this._class;\n },\n },\n\n /**\n * Extra user-defined properties.\n *\n * @memberof TilesetMetadata.prototype\n * @type {*}\n * @readonly\n * @private\n */\n extras: {\n get: function () {\n return this._extras;\n },\n },\n\n /**\n * An object containing extensions.\n *\n * @memberof TilesetMetadata.prototype\n * @type {object}\n * @readonly\n * @private\n */\n extensions: {\n get: function () {\n return this._extensions;\n },\n },\n});\n\n/**\n * Returns whether the tileset has this property.\n *\n * @param {string} propertyId The case-sensitive ID of the property.\n * @returns {boolean} Whether the tileset has this property.\n * @private\n */\nTilesetMetadata.prototype.hasProperty = function (propertyId) {\n return MetadataEntity.hasProperty(propertyId, this._properties, this._class);\n};\n\n/**\n * Returns whether the tileset has a property with the given semantic.\n *\n * @param {string} semantic The case-sensitive semantic of the property.\n * @returns {boolean} Whether the tileset has a property with the given semantic.\n * @private\n */\nTilesetMetadata.prototype.hasPropertyBySemantic = function (semantic) {\n return MetadataEntity.hasPropertyBySemantic(\n semantic,\n this._properties,\n this._class\n );\n};\n\n/**\n * Returns an array of property IDs.\n *\n * @param {string[]} [results] An array into which to store the results.\n * @returns {string[]} The property IDs.\n * @private\n */\nTilesetMetadata.prototype.getPropertyIds = function (results) {\n return MetadataEntity.getPropertyIds(this._properties, this._class, results);\n};\n\n/**\n * Returns a copy of the value of the property with the given ID.\n *

\n * If the property is normalized the normalized value is returned.\n *

\n *\n * @param {string} propertyId The case-sensitive ID of the property.\n * @returns {*} The value of the property or undefined if the tileset does not have this property.\n * @private\n */\nTilesetMetadata.prototype.getProperty = function (propertyId) {\n return MetadataEntity.getProperty(propertyId, this._properties, this._class);\n};\n\n/**\n * Sets the value of the property with the given ID.\n *

\n * If the property is normalized a normalized value must be provided to this function.\n *

\n *\n * @param {string} propertyId The case-sensitive ID of the property.\n * @param {*} value The value of the property that will be copied.\n * @returns {boolean} true if the property was set, false otherwise.\n * @private\n */\nTilesetMetadata.prototype.setProperty = function (propertyId, value) {\n return MetadataEntity.setProperty(\n propertyId,\n value,\n this._properties,\n this._class\n );\n};\n\n/**\n * Returns a copy of the value of the property with the given semantic.\n *\n * @param {string} semantic The case-sensitive semantic of the property.\n * @returns {*} The value of the property or undefined if the tileset does not have this semantic.\n * @private\n */\nTilesetMetadata.prototype.getPropertyBySemantic = function (semantic) {\n return MetadataEntity.getPropertyBySemantic(\n semantic,\n this._properties,\n this._class\n );\n};\n\n/**\n * Sets the value of the property with the given semantic.\n *\n * @param {string} semantic The case-sensitive semantic of the property.\n * @param {*} value The value of the property that will be copied.\n * @returns {boolean} true if the property was set, false otherwise.\n * @private\n */\nTilesetMetadata.prototype.setPropertyBySemantic = function (semantic, value) {\n return MetadataEntity.setPropertyBySemantic(\n semantic,\n value,\n this._properties,\n this._class\n );\n};\n\nexport default TilesetMetadata;\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252945,"cells":{"blob_id":{"kind":"string","value":"788be35ea9ced76b104fff7f44a576b1567ff6f8"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"zonghuang/learning-js-data-structures"},"path":{"kind":"string","value":"/src/01.Array/05.concat-array.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":417,"string":"417"},"score":{"kind":"number","value":3.671875,"string":"3.671875"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"// 数组合并 concat()\n/**\nconcat() 连接 2 个或 2 个已上的数组,并返回结果。\nconcat() 可以向一个数组传递数组、对象或是元素。数组会按照该方法传入的参数顺序连接指定的数组。\n*/\n\nconst zero = 0;\nconst positiveNumbers = [1, 2, 3];\nconst negativeNumbers = [-3, -2, -1];\nlet numbers = negativeNumbers.concat(zero, positiveNumbers); // [-3, -2, -1, 0, 1, 2, 3]\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252946,"cells":{"blob_id":{"kind":"string","value":"c02dc57bb488208fb560bb71f318043fb5d4e35b"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"CarolineVinet/project-m5-e-commerce"},"path":{"kind":"string","value":"/client/src/reducers/companies-reducer.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":893,"string":"893"},"score":{"kind":"number","value":2.921875,"string":"2.921875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"const initialState = {\n companies: null,\n status:\"idle\"\n}\n\nconst companiesReducer = (state = initialState, action)=> {\n switch(action.type) {\n case 'REQUEST_COMPANIES' : {\n return { ...state, status: \"loading\" }\n }\n case 'RECEIVE_COMPANIES' : {\n return {\n ...state,\n items : action.companies,\n status: 'idle'\n }\n }\n case 'RECEIVE_COMPANIES_ERROR' : {\n return { ...state, status: \"error\" }\n }\n default: return state\n }\n}\n\nexport default companiesReducer;\n\n// helpers\n// here the state refers to the global state with all the reducers combined\n// get an array with all the companies\nexport const getCompaniesArray = (state) => state.companies.companies;\n// get the status\nexport const getCompaniesArrayStatus = (state) => state.companies.status;"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252947,"cells":{"blob_id":{"kind":"string","value":"ba778580b604fcd32885ff330746f950b15dbf7f"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"interestdashing/test-data"},"path":{"kind":"string","value":"/makeType1.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1121,"string":"1,121"},"score":{"kind":"number","value":3.328125,"string":"3.328125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"const process = require(\"process\");\nconst fs = require(\"fs\");\nconst iterations = process.argv[2] || 0;\nconst makeGuid = function () {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = Math.random() * 16 | 0;\n const v = c === \"x\" ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n};\n\nconst makeRandomString = function (min, max) {\n const options = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n const chars = min + (Math.random() * (max - min));\n \n let result = \"\";\n for (let i = 0; i < chars; i++) {\n result += options[Math.floor(Math.random() * options.length)];\n }\n return result;\n};\n\nfor (let i = 0; i < iterations; i++) {\n const item = {\n id: makeGuid(),\n name: \"This is a random type1 object \" + makeRandomString(10, 100),\n description: \"Description \" + makeRandomString(100, 500),\n x: Math.random(),\n y: Math.random(),\n width: Math.random(),\n height: Math.random()\n };\n fs.writeFileSync(\"type1/\" + item.id + \".json\", JSON.stringify(item, undefined, 4));\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252948,"cells":{"blob_id":{"kind":"string","value":"28f300aa1b113df9c54c55d21b0af67623fb8f02"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"leebyp/n-queens"},"path":{"kind":"string","value":"/src/solvers.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":9929,"string":"9,929"},"score":{"kind":"number","value":3.5,"string":"3.5"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"/* _\n ___ ___ | |_ _____ _ __ ___\n / __|/ _ \\| \\ \\ / / _ \\ '__/ __|\n \\__ \\ (_) | |\\ V / __/ | \\__ \\\n |___/\\___/|_| \\_/ \\___|_| |___/\n\n*/\n\n// hint: you'll need to do a full-search of all possible arrangements of pieces!\n// (There are also optimizations that will allow you to skip a lot of the dead search space)\n// take a look at solversSpec.js to see what the tests are expecting\n\n\n// return a matrix (an array of arrays) representing a single nxn chessboard, with n rooks placed such that none of them can attack each other\n\nwindow.findNRooksSolution = function(n, board) {\n var solution = undefined; //fixme\n //for every point in the board\n //try to place a rook there,\n // if rookconflict detected, remove back from the board\n //continue until all rooks for placed\n //return board\n var board = board || new Board({n: n});\n for(var i = 0; i < n; i++) {\n for(var j = 0; j < n; j++) {\n board.togglePiece(i, j);\n if (board.hasAnyRooksConflicts()) {\n board.togglePiece(i,j);\n }\n }\n }\n // console.dir(board);\n //console.log('Single solution for ' + n + ' rooks:', JSON.stringify(board));\n return board.rows();\n};\n\n\n\n// return the number of nxn chessboards that exist, with n rooks placed such that none of them can attack each other\nwindow.countNRooksSolutions = function(n) {\n\n var outcomes = [];\n var iterateBoard = function(currentBoard, row){\n\n if (row === 0) { //base case\n outcomes.push(currentBoard.rows());\n } else {\n var newBoard = new Board(currentBoard.rows()); //create a copy of currentBoard\n\n for (var i=0; i>1, (usedMinors | bitColumn) << 1);\n// }\n// }\n// };\n// iterateBoard(0, 0, 0, 0);\n// return outcomes;\n// };\n\n//================== n=12 ~65ms, refactored code to exclude board, unused cloned varibles\n//================== and bitshifted with numbers to keep track of used spaces\n//==================================================== \n\n\n// window.countNQueensSolutions = function(n){\n\n// var outcomes = 0;\n\n// //if ( n%2 === 0){\n// var iterateBoard = function(row, usedColumns, usedMajors, usedMinors){\n// if (row === n){\n// outcomes++;\n// }\n// for (var column=0; column>1, (usedMinors | bitColumn) << 1);\n// }\n// }\n// };\n// for (var firstRowColumn=0; firstRowColumn>1, bitColumn << 1);\n// }\n// return outcomes*2;\n// //}\n\n// };\n\n//================== n=12 ~39ms, attempt at using symmetry for even n\n//==================================================== \n\n\nwindow.countNQueensSolutions = function(n){\n\n var outcomes = 0;\n\n var iterateBoard = function(row, usedColumns, usedMajors, usedMinors){\n if (row === n){\n outcomes++;\n }\n for (var column=0; column>1, (usedMinors | bitColumn) << 1);\n }\n }\n };\n\n if ( n%2 === 0){\n for (var firstRowColumn=0; firstRowColumn>1, bitColumn<<1);\n }\n return outcomes*2;\n }\n else {\n for (var firstRowColumn=0; firstRowColumn>1, bitColumn<<1);\n }\n return outcomes;\n }\n\n};\n\n//================== n=12 ~40ms, \n//================== n=13 ~400ms // ~250ms on a mac mini\n//================== attempt at using symmetry for even n\n//==================================================== \n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252949,"cells":{"blob_id":{"kind":"string","value":"34d08a03c289b4c846ce3a9de424289e76165ddc"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"brendonion/midterm-project"},"path":{"kind":"string","value":"/server/routes/resources.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4988,"string":"4,988"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"'use strict';\n\nconst express = require('express');\nconst router = express.Router();\nconst dateNow = new Date();\nconst theDate = dateNow.toLocaleString();\nconst mw = require('../routes/middleware');\n\nmodule.exports = (knex) => {\n // adds middleware to this page\n const middleware = mw(knex);\n\n //retrieves create new resource page\n router.get('/new', middleware.ensureLoggedIn, (req, res) => {\n res.render('../public/views/resource_new', {user: {\n username: req.username,\n userid: req.id\n }});\n });\n\n //retrieves resource id and displays the info of the resource\n router.get('/:resource_id', (req, res) => {\n const key = req.params.resource_id;\n let resource = {};\n let creatorName = '';\n let creatorId = 0;\n let likes = 0;\n let rating = 0;\n let commentsArr = [];\n let hasLiked = false;\n\n //links user with resource\n knex('users')\n .join('resources', 'users.id', '=', 'creator')\n .select('username', 'creator')\n .where('resources.id', req.params.resource_id)\n .asCallback((err, results) => {\n if (err) return console.error(err);\n creatorName = results[0].username;\n creatorId = results[0].creator;\n });\n\n //links resource likes\n knex('resources').join('likes', 'resource_id', '=', 'resources.id')\n .count().where('resource_id', req.params.resource_id)\n .asCallback((err, results) => {\n if (err) return console.error(err);\n likes = results[0].count;\n });\n\n knex('likes').count()\n .where('user_id', req.session.user_id)\n .andWhere('resource_id', req.params.resource_id)\n .then((results) => {\n if (results[0].count == 1) {\n hasLiked = true;\n } else {\n hasLiked = false;\n }\n }).catch(function(error){\n console.log(error);\n })\n\n //links resource ratings\n knex('resources').join('ratings', 'resource_id', '=', 'resources.id')\n .select('value').where('resource_id', req.params.resource_id)\n .asCallback((err, results) => {\n if (err) return console.error(err);\n let ratings = results;\n for (let i = 0; i < ratings.length; i++) {\n rating += ratings[i].value;\n }\n rating = rating / ratings.length;\n rating = Math.max( Math.round(rating * 10) / 10, 1 ).toFixed(1);\n });\n\n //links resource comments with the user who commented and date created\n knex('resources').join('comments', 'resource_id', '=', 'resources.id')\n .join('users', 'user_id', '=', 'users.id')\n .where('resource_id', req.params.resource_id)\n .asCallback((err, results) => {\n let dateTime = '';\n if (err) return console.error(err);\n for (let i = 0; i < results.length; i++){\n dateTime = (results[i].date_created).toLocaleString();\n let comment = {\n comment: results[i].comment,\n date: dateTime,\n commenter: results[i].username\n }\n commentsArr.push(comment);\n }\n })\n\n //retrieves resource from database\n knex.select().from('resources').where('id', req.params.resource_id)\n .asCallback((err, results) => {\n if (err) return console.error(err);\n resource = results;\n }).then(function() {\n commentsArr.sort(function(a,b){\n return new Date(b.date) - new Date(a.date);\n });\n\n let templateVars = {\n resource: resource[0],\n creator: {\n id: creatorId,\n username: creatorName\n },\n user: {\n username: req.username,\n userid: req.session.user_id\n },\n likesCount: {\n likes: likes\n },\n hasLiked: {\n hasLiked: hasLiked\n },\n totalRating: {\n rating: rating\n },\n allComments: commentsArr\n }\n res.render('../public/views/resource_id', templateVars);\n }).catch(function(error){\n console.log(error);\n })\n });\n\n\n //posts new resource to /:resource_id. If url is used\n //then it redirects back to resources/new\n router.post('/create', middleware.ensureLoggedIn, (req, res) => {\n if (!req.body.title || !req.body.description || !req.body.url) {\n req.flash('errors', 'Title, URL, description, and topic required');\n return;\n }\n const findReqUrl = knex('resources')\n .select('url')\n .where({url: req.body.url})\n .limit(1);\n\n findReqUrl.then((results) => {\n if (results.length) {\n // TODO make this into a flash message\n console.log('Resource already used');\n res.redirect('/resources/new');\n return;\n } else {\n knex.insert([{\n title: req.body.title,\n url: req.body.url,\n description: req.body.description,\n topic: req.body.topic.toLowerCase(),\n creator: req.session.user_id,\n date_created: theDate\n }]).returning('id')\n .into('resources')\n .then((id) => {\n res.redirect('/resources/' + id);\n return;\n })\n }\n });\n });\n\n return router;\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252950,"cells":{"blob_id":{"kind":"string","value":"d08716029c92b1d40210fea281b98cd55f55bab0"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"daniellenguyen/nguyen-danielle-webdev"},"path":{"kind":"string","value":"/public/project/views/search/controllers/petDetails.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2956,"string":"2,956"},"score":{"kind":"number","value":2.625,"string":"2.625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"(function() {\n angular\n .module(\"PetWebsite\")\n .controller(\"PetDetailsController\", PetDetailsController);\n\n function PetDetailsController($location, $routeParams, SearchService) {\n var vm = this;\n vm.petId = $routeParams[\"petId\"];\n vm.carouselHelper = carouselHelper;\n vm.toRegister = toRegister;\n vm.toLogin = toLogin;\n vm.isUserLoggedIn = false;\n\n function init() {\n var promise = SearchService.getSinglePet(vm.petId);\n\n promise.then(function (response) {\n vm.pet = response.data;\n vm.age = vm.pet.age;\n vm.breed = vm.pet.breeds.breed[0];\n vm.email = vm.pet.contact.email;\n vm.phone = vm.pet.contact.phone;\n vm.description = vm.pet.description;\n vm.id = vm.pet.id;\n vm.name = vm.pet.name;\n vm.size = vm.pet.size;\n vm.photos = vm.pet.media;\n prettifySex();\n prettifySize();\n prettifyStatus();\n prettifyDetails();\n });\n }\n\n init();\n\n function prettifyStatus() {\n if(vm.pet.status === 'A') {\n vm.status = 'ready to adopt!'\n }\n else if(vm.pet.status === 'X') {\n vm.status = 'that has already been adopted!'\n }\n else {\n vm.status = '';\n }\n }\n\n function prettifySize() {\n if(vm.pet.size === 'S') {\n vm.size = 'Small';\n }\n else if(vm.pet.size === 'M') {\n vm.size = 'Medium';\n }\n else if(vm.pet.size === 'L') {\n vm.size = 'Large';\n }\n else if(vm.pet.size === 'XL') {\n vm.size = 'Very Large';\n }\n else {\n vm.size = '';\n }\n }\n\n function prettifySex() {\n if(vm.pet.sex === 'M') {\n vm.sex = 'Male';\n }\n else if (vm.pet.sex === 'F') {\n vm.sex = 'Female';\n }\n else {\n vm.sex = '';\n }\n }\n\n function prettifyDetails() {\n var oldDetails = vm.pet.options.option;\n var newDetails = '';\n for(var i = 0; i < Object.keys(oldDetails).length; i++) {\n if (oldDetails[i] === \"hasShots\") {\n newDetails = newDetails + 'has shots, ';\n }\n else if (oldDetails[i] === \"noDogs\") {\n newDetails = newDetails + 'can\\'t be around dogs, ';\n }\n else if (oldDetails[i] === \"altered\") {\n if(vm.sex === 'Male') {\n newDetails = newDetails + 'neutered, ';\n }\n else if (vm.sex === 'Female') {\n newDetails = newDetails + 'spayed, ';\n }\n }\n else {\n newDetails = newDetails + \" \" + oldDetails[i] + ', ';\n }\n }\n newDetails = newDetails.slice(0, -2);\n vm.details = newDetails;\n }\n\n function carouselHelper(index) {\n if(index === 0) {\n return \"item active\";\n }\n else {\n return \"item\";\n }\n }\n\n function toRegister() {\n $location.url(\"/register\");\n }\n\n function toLogin() {\n $location.url(\"/login\");\n }\n\n\n }\n\n})();"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252951,"cells":{"blob_id":{"kind":"string","value":"2c3ab08f98f36bd5ad5211071688e49243addbd0"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"Naixes/demo-collection"},"path":{"kind":"string","value":"/learnVue/vue-cli-webpack/src/pages/jsxScopSlot/components/levelFunction.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":535,"string":"535"},"score":{"kind":"number","value":2.609375,"string":"2.609375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"// 返回不同级别的标题:l=1/2/3/4/5/6\nexport default {\n props: {\n l: {\n type: Number\n }\n },\n render (h) {\n let tag = `h${this.l}`\n // return {this.$slots.default}\n return h(tag, {}, this.$slots.default)\n\n // h方法的参数:\n // h1 on-click={()=>{alert(1)}} style={{color:'red'}}>你好\n // h('h1',{\n // on:{\n // click(){\n // alert(1)\n // },\n // },\n // attrs:{\n // a:1\n // }\n // },[h('span',{},'你好')])\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252952,"cells":{"blob_id":{"kind":"string","value":"ad9ce9a6884770ed8053a0b07a8e112faf1ad066"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"guoyu07/jSound"},"path":{"kind":"string","value":"/src/jSound.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2341,"string":"2,341"},"score":{"kind":"number","value":2.828125,"string":"2.828125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"/*!\n * jSound 0.0.1 preview\n * @author TooBug \n * @license MIT\n */\n\n(function(w){\n\n\t'use strict';\n\n\tvar jSound = {};\n\n\tvar elem;\n\n\tvar init = function(){\n\n\t\telem = document.createElement('audio');\n\t\tif (!elem.canPlayType){\n\t\t\telem = document.createElement('bgsound');\n\t\t}\n\t\tdocument.body.appendChild(elem);\n\t};\n\t\n\t/**\n\t * 播放音效\n\t * @param {String} src 要播放的音频文件URL\n\t * @param {Object} ops 播放设置\n\t * @param {Boolean} ops.loop 是否循环播放\n\t * @param {Number} ops.volume 音量大小,取值为0-100\n\t * @return {undefined}\n\t */\n\tjSound.play = function(src,ops){\n\t\tvar options;\n\n\t\t// 如果只传了ops,没有传src\n\t\tif (typeof src === 'object'){\n\t\t\toptions = src;\n\t\t}else{\n\t\t\toptions = ops || {};\n\t\t\toptions.src = src;\n\t\t}\n\t\tif (options.loop){\n\t\t\telem.loop = elem.canPlayType?true:-1;\n\t\t}else{\n\t\t\telem.loop = elem.canPlayType?false:1;\n\t\t}\n\t\tif (options.volume !== undefined){\n\t\t\telem.volume = elem.canPlayType?options.volume/100:-(options.volume-100)*(options.volume-100);\n\t\t}\n\t\telem.src=options.src;\n\t\tif (elem.canPlayType){\n\t\t\telem.play();\n\t\t}\n\t};\n\n\t/**\n\t * 停止播放音效\n\t * @return {undefined}\n\t */\n\tjSound.stop = function(){\n\t\tif (elem.canPlayType){\n\t\t\telem.pause();\n\t\t}else{\n\t\t\telem.src='';\n\t\t}\n\t};\n\n\t/**\n\t * 播放内置音效\n\t * @param {String} toneName 音效名字\n\t * @return {undefined}\n\t */\n\tjSound.playTone = function(toneName){\n\t\telem.src='data:audio/wav;base64,'+this.sounds[toneName];\n\t\tif (elem.canPlayType){\n\t\t\telem.play();\n\t\t}\n\t};\n\n\t/**\n\t * 对指定字符重复count次,返回一个重复字符串\n\t * @param {String} str 要重复的字符串\n\t * @param {Number} count 要重复的次数\n\t * @return {String} 对str重复count次之后的新字符串\n\t */\n\tjSound._repeatStr = function(str,count){\n\t\tvar tempstr = '';\n\t\tfor (var i=count; i-- ; ){\n\t\t\ttempstr += str;\n\t\t}\n\t\treturn tempstr;\n\t}\n\n\t//detect DOM Ready Event\n\tif (window.addEventListener){\n\t\tjSound.domReady = function(readyFunc){\n\t\t\tdocument.addEventListener('DOMContentLoaded',readyFunc,false);\n\t\t};\n\t}else if (window.attachEvent){\n\t\tjSound.domReady = function(readyFunc){\n\t\t\tdocument.attachEvent('onreadystatechange',function(){\n\t\t\t\tif (document.readyState === 'complete'){\n\t\t\t\t\treadyFunc();\n\t\t\t\t}\n\t\t\t});\n\t\t};\n\t}\n\n\tjSound.domReady(function(){\n\t\tinit();\n\t});\n\n\tw.jSound = jSound;\n\n})(window);"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252953,"cells":{"blob_id":{"kind":"string","value":"b8371f2ca5aeebe985daf2c865e81b9ccbf006bf"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"edsonlima2506/Eventoge"},"path":{"kind":"string","value":"/src/App.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2890,"string":"2,890"},"score":{"kind":"number","value":2.65625,"string":"2.65625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"import Header from './Components/Header';\nimport Form from './Components/Form';\nimport Pratos from './Components/Pratos';\nimport Result from './Components/Result';\nimport Lista from './Components/Lista'\nimport pratosInfos from './data';\nimport { funcionarios } from './data'\nimport './App.css';\nimport React from 'react';\n\nclass App extends React.Component {\n constructor() {\n super()\n\n this.state = {\n totalCalorias: 0,\n inputNome: '',\n inputIdade: 0,\n inputSso: 0,\n inputPeso: 0,\n sexo: 'Masculino',\n listaVazia: true,\n }\n\n this.somaCalorias = this.somaCalorias.bind(this);\n this.handleChange = this.handleChange.bind(this);\n this.clearInputs = this.clearInputs.bind(this);\n }\n\n somaCalorias({ target }) {\n const cal = target.value\n this.setState((estadoAnterior, _props) => ({\n totalCalorias: Number(estadoAnterior.totalCalorias) + Number(cal)\n }))\n }\n\n handleChange({ target }) {\n const { name, value } = target\n this.setState({\n [name]: value\n });\n }\n\n clearInputs() {\n const { totalCalorias } = this.state;\n const nome = document.getElementsByName('inputNome');\n const idade = document.getElementsByName('inputIdade');\n const sso = document.getElementsByName('inputSso');\n const peso = document.getElementsByName('inputPeso');\n const sexo = document.getElementsByName('sexo');\n funcionarios.push({\n nome: nome[0].value,\n idade: idade[0].value,\n sso: sso[0].value,\n peso: peso[0].value,\n sexo: sexo[0].value,\n total: totalCalorias\n })\n nome[0].value = '';\n idade[0].value = '';\n sso[0].value = '';\n peso[0].value = '';\n this.setState ({\n totalCalorias: 0,\n inputNome: '',\n inputIdade: 0,\n inputSso: 0,\n inputPeso: 0,\n sexo: 'Masculino',\n listaVazia: false,\n })\n localStorage.setItem('funcionarios', JSON.stringify(funcionarios))\n }\n\n render() {\n const { totalCalorias, inputNome, inputIdade, inputPeso, inputSso, sexo, listaVazia } = this.state;\n const funcionariosSalvos = JSON.parse(localStorage.getItem('funcionarios'));\n return (\n
\n
\n
\n
\n { pratosInfos.map((prato) => \n \n ) }\n
\n \n { listaVazia === false && }\n
\n );\n }\n }\n\nexport default App;\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252954,"cells":{"blob_id":{"kind":"string","value":"992e68d69fdfeb51aa26ea4dfa2d0e74455791be"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"mazsola739/Rika-s-Katas"},"path":{"kind":"string","value":"/Curious_Constructors/5 kyu Simple Fun #166: Best Match/index.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1723,"string":"1,723"},"score":{"kind":"number","value":4.09375,"string":"4.09375"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"/*\nTask\n\n\"AL-AHLY\" and \"Zamalek\" are the best teams in Egypt, but \"AL-AHLY\" always wins the matches between them. \"Zamalek\" managers want to know what \nis the best match they've played so far.\n\nThe best match is the match they lost with the minimum goal difference. If there is more than one match with the same difference, choose the one \n\"Zamalek\" scored more goals in.\n\nGiven the information about all matches they played, return the index of the best match (0-based). If more than one valid result, return the smallest index.\nExample\n\nFor ALAHLYGoals = [6,4] and zamalekGoals = [1,2], the output should be 1.\n\nBecause 4 - 2 is less than 6 - 1\n\nFor ALAHLYGoals = [1,2,3,4,5] and zamalekGoals = [0,1,2,3,4], the output should be 4.\n\nThe goal difference of all matches are 1, but at 4th match \"Zamalek\" scored more goals in. So the result is 4.\nInput/Output\n\n [input] integer array ALAHLYGoals\n\nThe number of goals \"AL-AHLY\" scored in each match.\n\n [input] integer array zamalekGoals\n\nThe number of goals \"Zamalek\" scored in each match. It is guaranteed that zamalekGoals[i] < ALAHLYGoals[i] for each element.\n\n [output] an integer\n\nIndex of the best match.\n\n*/\n\n//My solution\n\nfunction bestMatch(ALAHLYGoals, zamalekGoals) {\n let firstMatch = ALAHLYGoals[0] - zamalekGoals[0],\n bestMatch = 0,\n zamalek = zamalekGoals[0];\n for (let i = 0; i < ALAHLYGoals.length; i++) {\n let diff = ALAHLYGoals[i] - zamalekGoals[i];\n if (firstMatch > diff) {\n firstMatch = diff;\n zamalek = zamalekGoals[i];\n bestMatch = i;\n } else if (diff === firstMatch && zamalekGoals[i] > zamalek) {\n firstMatch = diff;\n zamalek = zamalekGoals[i];\n bestMatch = i;\n }\n }\n return bestMatch;\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252955,"cells":{"blob_id":{"kind":"string","value":"283ff6ffbeac76884004372be7647a43cdb540bb"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"edmundho/ongoing_study"},"path":{"kind":"string","value":"/jul2018/jul18/linked_list_cycle_ii.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":942,"string":"942"},"score":{"kind":"number","value":3.953125,"string":"3.953125"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"// Given a linked list, return the node where the cycle begins.If there is no cycle, return null.\n\n// Note: Do not modify the linked list.\n\n// Follow up:\n// Can you solve it without using extra space ?\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\n\nconst detectCycle = function (head) {\n let scout1;\n if (head === null || head.next === null) { return null; }\n\n if (head.next) {\n if (head.next.next) {\n scout1 = head.next.next;\n }\n } \n \n let current = head;\n while (current && scout1) {\n if (current === scout1) {\n let newCurrent = head;\n while (current !== newCurrent) {\n current = current.next;\n newCurrent = newCurrent.next;\n }\n return newCurrent;\n }\n \n scout1 = scout1.next.next;\n current = current.next;\n }\n \n return null;\n};\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252956,"cells":{"blob_id":{"kind":"string","value":"18f5da13575eb45f132b313dddd0bae593d97810"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"emilti/ParkingSystem"},"path":{"kind":"string","value":"/client/src/Utils/dropdowns.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2844,"string":"2,844"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"const buildCategoriesDropdown = async (dropdownType) =>{\n let serverOptions = await getCategories()\n switch(dropdownType){\n case \"Edit visit\":\n return [...serverOptions]\n case \"Enter visit\": \n return [{\"value\": \"\", \"label\": \"Select category\"}, ...serverOptions]\n case \"Filter visits\":\n return [{\"value\": \"0\", \"label\": \"All categories\"}, ...serverOptions]\n }\n}\n\nconst buildDiscountsDropdown = async (dropdownType) =>{\n let serverOptions = await getDiscounts()\n switch(dropdownType){\n case \"Edit visit\":\n return [{\"value\": \"999\", \"label\": \"No discounts\"}, ...serverOptions]\n case \"Enter visit\": \n return [{\"value\": \"\", \"label\": \"Select discount\"}, ...serverOptions]\n case \"Filter visits\":\n return [{\"value\": \"0\", \"label\": \"All discounts\"}, ...serverOptions, {\"value\": \"999\", \"label\": \"No discounts\"}]\n }\n}\n\nconst getCategories = async () => {\n const promise = await fetch('http://localhost:57740/parking/getcategories')\n const categories = await promise.json()\n let options = []\n options = categories.map(c => ({\n \"value\": c.categoryId,\n \"label\": c.name + \" (Occupied spaces: \" + c.parkingSpaces + \")\"\n }))\n\n return options\n}\n\nconst getDiscounts = async () => {\n const promise = await fetch('http://localhost:57740/parking/getdiscounts')\n const discounts = await promise.json()\n let options = []\n options = discounts.map(d => ({\n \"value\": d.discountId,\n \"label\": d.name + \" \" + d.discountPercentage + \"%\"\n }))\n return options\n}\n\nconst getIsInParkingOptions = async () => {\n let options = [\n {\"value\": 'all', \"label\": \"All\"},\n {\"value\": true, \"label\": \"Yes\"},\n {\"value\": false, \"label\": \"No\"}]\n return options\n}\n\nconst getIsInParkingEditOptions = () => {\n let options = [\n {\"value\": true, \"label\": \"Yes\"},\n {\"value\": false, \"label\": \"No\"}]\n return options\n}\n\nconst getSorting = async () => {\n let options = [\n {\"value\": '', \"label\": \"No sorting\"},\n {\"value\": \"1\", \"label\": \"Due Amount\"},\n {\"value\": \"2\", \"label\": \"Registration Number\"},\n {\"value\": \"3\", \"label\": \"Entered Parking Date\"}]\n return options\n}\n\nconst getSortingOrder = async () => {\n let options = [\n {\"value\": '', \"label\": \"No sorting\"},\n {\"value\": \"1\", \"label\": \"Ascending\"},\n {\"value\": \"2\", \"label\": \"Descending\"}]\n return options\n}\n\nconst getPageOptions = async () => {\n let options = [\n {\"value\": '10', \"label\": \"10\"},\n {\"value\": \"20\", \"label\": \"20\"},\n {\"value\": \"50\", \"label\": \"50\"}]\n return options\n}\n\n\nexport {buildCategoriesDropdown, buildDiscountsDropdown, getIsInParkingOptions, getIsInParkingEditOptions, getSorting, getSortingOrder, getPageOptions}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252957,"cells":{"blob_id":{"kind":"string","value":"35c3ef22c067194bef65f8b4e3f4fec5c54d0f89"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"aakash2028/Assignment-6"},"path":{"kind":"string","value":"/CoinFlipGame/script.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":658,"string":"658"},"score":{"kind":"number","value":3.859375,"string":"3.859375"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"var coinFlip = Math.round(Math.random());\nvar result = \"\";\nvar choice = window.prompt(\"Enter 'H' for Heads or 'T' for Tails\");\nif(coinFlip == 0){\n result = \"F\";\n}else if(coinFlip == 1){\n result = \"H\";\n}\nif(result == \"H\" && choice == \"H\"){\n window.alert(\"The flip was heads and you chose heads...you win!\");\n}else if(result == \"H\" && choice == \"T\"){\n window.alert(\"The flip was heads but you chose tails...you lose!\");\n}else if(result == \"T\" && choice == \"H\"){\n window.alert(\"The flip was tails but you chose heads...you lose!\");\n}else if(result == \"T\" && choice == \"T\"){\n window.alert(\"The flip was tails and you chose tails...you win!\");\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252958,"cells":{"blob_id":{"kind":"string","value":"5772833aa6a307fea2ba94a3cca93347a6e42c83"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"EasonLin0716/rgb-to-hex-converter"},"path":{"kind":"string","value":"/main.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1638,"string":"1,638"},"score":{"kind":"number","value":3.578125,"string":"3.578125"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"// red part\nconst redSlider = document.querySelector('#red-silder')\nlet redValue = document.querySelector('.red-value')\nlet redOutCome = document.querySelector('.red-outcome')\n// green part\nconst greenSlider = document.querySelector('#green-slider')\nlet greenValue = document.querySelector('.green-value')\nlet greenOutCome = document.querySelector('.green-outcome')\n// blue part\nconst blueSlider = document.querySelector('#blue-slider')\nlet blueValue = document.querySelector('.blue-value')\nlet blueOutCome = document.querySelector('.blue-outcome')\n// color output\nlet colorValue = document.querySelector('.color-value')\n// background changing\nlet container = document.querySelector('.container')\n\nredSlider.addEventListener('mousemove', function (event) {\n changeValue(redValue, redSlider, redOutCome)\n changeBackground()\n})\n\ngreenSlider.addEventListener('mousemove', function (event) {\n changeValue(greenValue, greenSlider, greenOutCome)\n changeBackground()\n})\n\nblueSlider.addEventListener('mousemove', function (event) {\n changeValue(blueValue, blueSlider, blueOutCome)\n changeBackground()\n})\n\n\n// 此函式改變顏色數字的值\nfunction changeValue(value, slider, outcome) {\n value.textContent = slider.value\n if (+value.textContent < 10) {\n // 如果小於0會再補上一個0\n outcome.innerHTML = `0${value.textContent}`\n } else {\n // 轉為16進位\n outcome.innerHTML = (+value.textContent).toString(16)\n }\n}\n\n// 此函式改變背景顏色\nfunction changeBackground() {\n let color = `#${redOutCome.textContent}${greenOutCome.textContent}${blueOutCome.textContent}`\n\n container.style.background = color\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252959,"cells":{"blob_id":{"kind":"string","value":"112f14825e4304c56dded5a90e45336743aeaf8b"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"ducaale/t9-server"},"path":{"kind":"string","value":"/src/t9.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":800,"string":"800"},"score":{"kind":"number","value":3.234375,"string":"3.234375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"const Dictionary = require('./dictionary')\nconst WordRanker = require('./wordRanker')\n\nconst dictionary = new Dictionary()\nconst wordRanker = new WordRanker()\n\nfunction collectWords(path, words, current = '', depth = 0) {\n if (!dictionary.isValidPrefix(current)) { return }\n if (current.length == path.length) {\n words.push(current)\n return\n }\n for (const l of path[depth].split('')) {\n collectWords(path, words, current + l, depth+1)\n } \n}\n\nfunction predictWord(input) {\n const t9 = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']\n const path = input.split('').map(n => t9[n-2])\n const possibleWords = []\n collectWords(path, possibleWords)\n possibleWords.sort((a, b) => wordRanker.rank(a) - wordRanker.rank(b))\n return possibleWords\n}\n\nmodule.exports = { predictWord }"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252960,"cells":{"blob_id":{"kind":"string","value":"e21a9acd5ffbe628bd4455948031ed86610df452"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"dandyman2601/react-modal-json"},"path":{"kind":"string","value":"/index.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":642,"string":"642"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"const express = require('express');\nconst path = require('path');\nconst list = require('./Test JSON.json')\nconst app = express();\nconst cors = require('cors');\n\napp.use(cors());\n// Serve the static files from the React app\napp.use(express.static(path.join(__dirname, './build')));\n\n// An api endpoint that returns a short list of items\napp.get('/api/getList', (req, res) => {\n res.json(list);\n console.log('Sent list of items');\n});\n\napp.get('*', (req, res) => {\n res.sendFile(path.join(__dirname + '/build/index.html'));\n});\n\nconst port = process.env.PORT || 5000;\napp.listen(port);\n\nconsole.log('App is listening on port ' + port);"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252961,"cells":{"blob_id":{"kind":"string","value":"edf166f652a9dab8c0dce94203849779bbdcb390"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"alissin4444/javascript-study"},"path":{"kind":"string","value":"/ArrayMethodsThatIShouldKnow.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":5033,"string":"5,033"},"score":{"kind":"number","value":4.59375,"string":"4.59375"},"int_score":{"kind":"number","value":5,"string":"5"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"// forEach faz com que você consiga percorrer um array\nconst arr = [1, 2, 3, 4, 5, 6];\n\n arr.forEach(item => {\n console.log(item); // output: 1 2 3 4 5 6\n });\n\n-----------------------------------------------------------------------------------\n// includes permite você checar se existe existe um elemento no array baseado em seu valor\nconst arr = [1, 2, 3, 4, 5, 6];\n\n arr.includes(2); // output: true\n arr.includes(7); // output: false\n \n-----------------------------------------------------------------------------------\n// filter eu sei que esse método está em meu arquivo de javascript sobre como retirar elementos de um array, mas com essa short sytax tudo se torna mais fácil\n const arr = [1, 2, 3, 4, 5, 6];\n\n // item(s) greater than 3\n const filtered = arr.filter(num => num > 3);\n console.log(filtered); // output: [4, 5, 6]\n\n console.log(arr); // output: [1, 2, 3, 4, 5, 6]\n\n-----------------------------------------------------------------------------------\n// map é um método que cria um novo array e para cada index desse array, tu pode fazer o que tu quiser\nconst arr = [1, 2, 3, 4, 5, 6];\n\n // add one to every element\n const oneAdded = arr.map(num => num + 1);\n console.log(oneAdded); // output [2, 3, 4, 5, 6, 7]\n\n console.log(arr); // output: [1, 2, 3, 4, 5, 6]\n\n -----------------------------------------------------------------------------------\n // reduce irá percorrer um array da esquerda para direita e irá transforma-lo em um único valor\n const arr = [1, 2, 3, 4, 5, 6];\n\n const sum = arr.reduce((total, value) => total + value, 0);\n console.log(sum); // 21\n \n -----------------------------------------------------------------------------------\n // O método some irá fazer uma condicional com o último elemento de um array. Caso ele passe na condicional, a função retornará true. Caso contrário, retornará false\n const arr = [1, 2, 3, 4, 5, 6];\n\n // at least one element is greater than 4?\n const largeNum = arr.some(num => num > 4);\n console.log(largeNum); // output: true\n\n // at least one element is less than or equal to 0?\n const smallNum = arr.some(num => num <= 0);\n console.log(smallNum); // output: false\n \n -----------------------------------------------------------------------------------\n // every irá verificar se TODOS os elementos passam em uma condição. Se passar, retornará true. Caso contrário, retornará false\n const arr = [1, 2, 3, 4, 5, 6];\n\n // all elements are greater than 4\n const greaterFour = arr.every(num => num > 4);\n console.log(greaterFour); // output: false\n\n // all elements are less than 10\n const lessTen = arr.every(num => num < 10);\n console.log(lessTen); // output: true\n \n -----------------------------------------------------------------------------------\n // sort method. Ele irá organizar o array de forma anscedente ou descendente\n const arr = [1, 2, 3, 4, 5, 6];\n const alpha = ['e', 'a', 'c', 'u', 'y'];\n\n // sort in descending order\n descOrder = arr.sort((a, b) => a > b ? -1 : 1);\n console.log(descOrder); // output: [6, 5, 4, 3, 2, 1]\n\n // sort in ascending order\n ascOrder = alpha.sort((a, b) => a > b ? 1 : -1);\n console.log(ascOrder); // output: ['a', 'c', 'e', 'u', 'y']\n \n -----------------------------------------------------------------------------------\n // Array.from irá retornar um novo array com tudo separado KKK. Mano, não entendi muito bem, mas ok\n const name = 'frugence';\n const nameArray = Array.from(name);\n\n console.log(name); // output: frugence\n console.log(nameArray); // output: ['f', 'r', 'u', 'g', 'e', 'n', 'c', 'e']\n \n // Além disso tu pode trabalhar com a DOM. Caralho, ele é MUITO interessante akakakak\n // I assume that you have created unorder list of items in our html file.\n\n const lis = document.querySelectorAll('li');\n const lisArray = Array.from(document.querySelectorAll('li'));\n\n // is true array?\n console.log(Array.isArray(lis)); // output: false\n console.log(Array.isArray(lisArray)); // output: true\n \n -----------------------------------------------------------------------------------\n // Array.of irá adicionar um todos os elementos para dentro do array. Bem, eu não vi tanta utilidade nisso, mas OK.\n const nums = Array.of(1, 2, 3, 4, 5, 6);\n console.log(nums); // output: [1, 2, 3, 4, 5, 6]\n \n -----------------------------------------------------------------------------------\n // while loop executará x até a condição se tornar falsa\n var sum = 0;\n var number = 1;\n while (number <= 50) { // -- condition\n sum += number; // -- body\n number++; // -- updater\n }\n alert(\"Sum = \" + sum); // => Sum = 1275\n \n -----------------------------------------------------------------------------------\n // for irá fazer o mesmo que while\n var sum = 0;\n for (var i = 1; i <= 50; i++) {\n sum = sum + i;\n }\n alert(\"Sum = \" + sum); // => Sum = 1275\n \n -----------------------------------------------------------------------------------\n \n\n \n \n \n \n \n \n \n \n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252962,"cells":{"blob_id":{"kind":"string","value":"f28424efdad41c55f4ea8480b13b7c9bbff08c9c"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"wangcylive/code"},"path":{"kind":"string","value":"/javascript/test/drag/mobile/main.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4784,"string":"4,784"},"score":{"kind":"number","value":2.625,"string":"2.625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"/**\n * Created by Wangcy on 2015/2/3.\n */\n(function(w, d) {\n var drag1 = d.getElementById(\"drag1\"),\n drag2 = d.getElementById(\"drag2\");\n\n var dragList = d.querySelectorAll(\".story\");\n\n var dragCoords1 = (function() {\n var x = drag1.offsetLeft,\n width = drag1.offsetWidth,\n y = drag1.offsetTop,\n height = drag1.offsetHeight;\n\n return {\n x: {\n min: x,\n max: x + width\n },\n y: {\n min: y,\n max: y + height\n }\n }\n }());\n\n var dragCoords2 = (function() {\n var x = drag2.offsetLeft,\n width = drag2.offsetWidth,\n y = drag2.offsetTop,\n height = drag2.offsetHeight;\n\n return {\n x: {\n min: x,\n max: x + width\n },\n y: {\n min: y,\n max: y + height\n }\n }\n }());\n\n (function() {\n var i = 0,\n length = dragList.length;\n\n var fn = function(dom) {\n var touchStartTime = 0,\n canMove = 0,\n startX = 0,\n startY = 0,\n startTranslateX = 0,\n startTranslateY = 0,\n translateX = 0,\n translateY = 0,\n timeOut;\n\n dom.addEventListener(\"touchstart\", function(event) {\n event.preventDefault();\n\n var t = this,\n touch = event.targetTouches[0];\n touchStartTime = event.timeStamp;\n startX = touch.pageX;\n startY = touch.pageY;\n startTranslateX = translateX;\n startTranslateY = translateY;\n timeOut = setTimeout(function() {\n t.classList.add(\"touch-state\");\n canMove = 1;\n }, 800);\n }, false);\n\n dom.addEventListener(\"touchmove\", function(event) {\n event.preventDefault();\n\n var touch = event.targetTouches[0],\n moveX = touch.pageX - startX,\n moveY = touch.pageY - startY,\n clientX = touch.clientX,\n clientY = touch.clientY;\n\n // 容错处理,在800ms内触发并且移动的距离大于10px时失效\n if(event.timeStamp - touchStartTime < 800 && (moveX > 10 || moveY > 10)) {\n clearTimeout(timeOut);\n return false;\n }\n\n // touchstart 时间大于零(这里在touchstart的时候会设置)\n // 是在长按 800ms 后\n if(touchStartTime > 0 && event.timeStamp - touchStartTime >= 800 && canMove) {\n var x = moveX + startTranslateX,\n y = moveY + startTranslateY;\n\n this.style.transform = \"translate(\" + x + \"px,\" + y + \"px)\";\n translateX = x;\n translateY = y;\n\n if(clientX > dragCoords1.x.min && clientX < dragCoords1.x.max && clientY > dragCoords1.y.min &&\n clientY < dragCoords1.y.max) {\n drag1.style.setProperty(\"border-color\", \"red\", \"\");\n } else {\n drag1.style.removeProperty(\"border-color\");\n }\n\n if(clientX > dragCoords2.x.min && clientX < dragCoords2.x.max && clientY > dragCoords2.y.min &&\n clientY < dragCoords2.y.max) {\n drag2.style.setProperty(\"border-color\", \"red\", \"\");\n } else {\n drag2.style.removeProperty(\"border-color\");\n }\n }\n }, false);\n\n dom.addEventListener(\"touchend\", function(event) {\n event.preventDefault();\n\n var touch = event.changedTouches[0],\n clientX = touch.clientX,\n clientY = touch.clientY;\n\n clearTimeout(timeOut);\n touchStartTime = 0;\n canMove = 0;\n this.classList.remove(\"touch-state\");\n\n if(clientX > dragCoords1.x.min && clientX < dragCoords1.x.max && clientY > dragCoords1.y.min &&\n clientY < dragCoords1.y.max) {\n dom.style.removeProperty(\"transform\");\n drag1.appendChild(dom);\n } else {\n drag1.style.removeProperty(\"border-color\");\n }\n }, false);\n };\n\n for(; i < length; i++) {\n fn(dragList[i]);\n }\n }());\n}(window, document));"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252963,"cells":{"blob_id":{"kind":"string","value":"804401a6d7be0946d5a1eea40e2f056914fe0a7f"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"dbwcooper/chatgroup-backend"},"path":{"kind":"string","value":"/controller/comment.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1338,"string":"1,338"},"score":{"kind":"number","value":2.65625,"string":"2.65625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\nconst { _findRoomByLink } = require('../models/room');\n\nconst { _createComment, _getRoomDetailByLink } = require('../models/comment');\n\n\n/**\n * 增加一条评论\n * userName: 'George James',\n * roomLink: \n * avatar: { color: '#1890ff', alif: 'C' },\n * moment: 1521300207000,\n * content: '12321332',\n * md: true\n * @param {*} ctx \n */\nconst createComment = async (comment) => {\n let result = {};\n comment = JSON.parse(comment);\n let data = await _findRoomByLink(comment.roomLink);\n if (data === 400 || !data.roomLink) {\n result.code = 400;\n result.msg = \"聊天室不存在!\";\n }\n\n let code = await _createComment(comment);\n if(code === 400) {\n result.code = 400;\n result.msg = \"评论失败!\";\n } else {\n result.code = 200;\n result.msg = \"评论成功\";\n }\n return result;\n}\n\n// 根据roomLink 找到所有的评论 以时间降序\nconst getRoomDetailByLink = async (ctx) => {\n let roomLink = ctx.params.roomLink; //拿到房间名\n let data = await _getRoomDetailByLink(roomLink);\n let result = {};\n if (data === 400) {\n result.code = 400;\n result.msg = \"获取失败\";\n } else {\n result.code = 200;\n result.msg = \"获取成功\";\n result.data = data;\n }\n ctx.response.body = result;\n}\n\nmodule.exports = {\n createComment,\n getRoomDetailByLink\n}\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252964,"cells":{"blob_id":{"kind":"string","value":"557127d132b849f2496c6516443ee53db8619c2e"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"calvinfreese/Weather-App"},"path":{"kind":"string","value":"/script.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":9189,"string":"9,189"},"score":{"kind":"number","value":2.796875,"string":"2.796875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"$(document).ready(function () {\n const APIkey = \"39a1d34577f4801b22aafca38b9e1e96\";\n var weatherIconCode = \"\";\n var inputResponse = \"\";\n var history = [];\n\n function loadLastSearch() {\n if (localStorage.getItem(\"key_0\") != null) {\n // for (i = 0; i < localStorage.length; i++) {\n\n var keyIndex = localStorage.length - 1;\n var values = localStorage.getItem(\"key_\" + keyIndex);\n \n \n var locationInput = values.replace(/\"/g, \"\");\n console.log(locationInput);\n var queryURL =\n \"https://api.openweathermap.org/data/2.5/weather?q=\" +\n locationInput +\n \"&appid=\" +\n APIkey;\n\n $.ajax({\n url: queryURL,\n method: \"GET\",\n }).then(function (response) {\n inputResponse = response;\n weatherIconCode = response.weather[0].icon;\n var weatherURL =\n \"http://openweathermap.org/img/w/\" + weatherIconCode + \".png\";\n\n var currentDate = moment().format(\"L\");\n //grab Kelvin and convert to F\n var kelvin = response.main.temp;\n var temp = ((kelvin - 273.15) * 1.8 + 32).toFixed(2);\n //humidity\n var humidity = response.main.humidity;\n //wind speed\n var windSpeed = response.wind.speed;\n\n $(\".current-location\").text(`${response.name} ${currentDate}`);\n $(\"#weatherDisplay\").attr(\"src\", weatherURL);\n $(\"#weatherDisplay\").attr(\"alt\", \"weather icon\");\n $(\".current-temp\").text(\"Temp: \" + temp + \" F\");\n $(\".current-humidity\").text(\"Humidity: \" + humidity + \"%\");\n $(\".wind-speed\").text(\"Wind Speed: \" + windSpeed + \" mph\");\n\n getUVIndex();\n\n getFiveDayForecast();\n });\n \n }\n }\n\n loadLastSearch();\n\n //Gets UV Index - called by city submission ajax req.\n function getUVIndex() {\n var lat = inputResponse.coord.lat;\n var lon = inputResponse.coord.lon;\n var urlUVIndex =\n \"https://api.openweathermap.org/data/2.5/uvi?appid=\" +\n APIkey +\n \"&lat=\" +\n lat +\n \"&lon=\" +\n lon;\n\n $.ajax({\n url: urlUVIndex,\n method: \"GET\",\n }).then(function (r) {\n //Hey! this is the UV Index :D\n var uvIndex = r.value;\n $(\".current-uv-index\").text(\"UV Index: \" + uvIndex);\n if (uvIndex >= 8) {\n $(\".current-uv-index\").attr(\"class\", \"current-uv-index very-high-uv\");\n } else if (uvIndex < 8 && uvIndex >= 6) {\n $(\".current-uv-index\").attr(\"class\", \"current-uv-index high-uv\");\n } else if (uvIndex < 6 && uvIndex >= 3) {\n $(\".current-uv-index\").attr(\"class\", \"current-uv-index mod-uv\");\n } else {\n $(\".current-uv-index\").attr(\"class\", \"current-uv-index low-uv\");\n }\n });\n }\n\n //Gets Five day forecast\n function getFiveDayForecast() {\n var city = inputResponse.name;\n var forecastURL =\n \"https://api.openweathermap.org/data/2.5/forecast?q=\" +\n city +\n \"&appid=\" +\n APIkey;\n\n $.ajax({\n url: forecastURL,\n method: \"GET\",\n }).then(function (r) {\n var forecastList = r.list;\n\n //loop through forecast days, grab time index time @ 12p for each day, and print info to forecast cards in html\n for (i = 4; i < forecastList.length; i += 8) {\n var forecastIcon = forecastList[i].weather[0].icon;\n var weatherURL =\n \"http://openweathermap.org/img/w/\" + forecastIcon + \".png\";\n $(\"#weatherDisplay\").attr(\"src\", weatherURL);\n var temp = ((kelvin - 273.15) * 1.8 + 32).toFixed(2);\n var forecastDate = forecastList[i].dt_txt;\n var kelvin = forecastList[i].main.temp;\n var temp = ((kelvin - 273.15) * 1.8 + 32).toFixed(2);\n var forecastDateFormat = moment(forecastDate).format(\"L\");\n var humidity = forecastList[i].main.humidity;\n\n if (i == 4) {\n $(\".forecast1-date\").text(forecastDateFormat);\n $(\".forecast1-img\").attr(\"src\", weatherURL);\n $(\".forecast1-img\").attr(\"alt\", \"weather icon\");\n $(\".forecast1-temp\").text(\"Temp: \" + temp + \" F\");\n $(\".forecast1-humidity\").text(\"Humidity: \" + humidity);\n } else if (i == 12) {\n $(\".forecast2-date\").text(forecastDateFormat);\n $(\".forecast2-img\").attr(\"src\", weatherURL);\n $(\".forecast2-img\").attr(\"alt\", \"weather icon\");\n $(\".forecast2-temp\").text(\"Temp: \" + temp + \" F\");\n $(\".forecast2-humidity\").text(\"Humidity: \" + humidity);\n } else if (i == 20) {\n $(\".forecast3-date\").text(forecastDateFormat);\n $(\".forecast3-img\").attr(\"src\", weatherURL);\n $(\".forecast3-img\").attr(\"alt\", \"weather icon\");\n $(\".forecast3-temp\").text(\"Temp: \" + temp + \" F\");\n $(\".forecast3-humidity\").text(\"Humidity: \" + humidity);\n } else if (i == 28) {\n $(\".forecast4-date\").text(forecastDateFormat);\n $(\".forecast4-img\").attr(\"src\", weatherURL);\n $(\".forecast4-img\").attr(\"alt\", \"weather icon\");\n $(\".forecast4-temp\").text(\"Temp: \" + temp + \" F\");\n $(\".forecast4-humidity\").text(\"Humidity: \" + humidity);\n } else if (i == 36) {\n $(\".forecast5-date\").text(forecastDateFormat);\n $(\".forecast5-img\").attr(\"src\", weatherURL);\n $(\".forecast5-temp\").text(\"Temp: \" + temp + \" F\");\n $(\".forecast5-humidity\").text(\"Humidity: \" + humidity);\n }\n }\n });\n }\n\n //Adds historical searches as list items on page and stores them to localStorage\n\n function appendHistory() {\n var listGroup = $(\".list-group\");\n \n var keys = Object.keys(localStorage);\n\n console.log(\"storing key index of \" + keys.length);\n console.log(history);\n localStorage.setItem(\n \"key_\" + keys.length,\n JSON.stringify(history[history.length - 1])\n );\n\n listGroup.prepend(\n ``\n );\n \n }\n\n function loadStorage() {\n var listGroup = $(\".list-group\");\n\n if (localStorage.getItem(\"key_0\") != null) {\n for (i = 0; i < localStorage.length; i++) {\n var storedSearches = localStorage.getItem(\"key_\" + i);\n //history.push(storedSearches)\n storedSearches = storedSearches.replace(/\"/g, \"\");\n\n listGroup.prepend(\n ` `\n );\n }\n }\n }\n\n loadStorage();\n\n //this happens first\n $(\"#locationForm\").on(\"submit\", function (e) {\n e.preventDefault();\n var locationInput = $(\"#locationInput\").val();\n var queryURL =\n \"https://api.openweathermap.org/data/2.5/weather?q=\" +\n locationInput +\n \"&appid=\" +\n APIkey;\n\n $.ajax({\n url: queryURL,\n method: \"GET\",\n }).then(function (response) {\n inputResponse = response;\n weatherIconCode = response.weather[0].icon;\n var weatherURL =\n \"https://openweathermap.org/img/w/\" + weatherIconCode + \".png\";\n\n var currentDate = moment().format(\"L\");\n //grab Kelvin and convert to F\n var kelvin = response.main.temp;\n var temp = ((kelvin - 273.15) * 1.8 + 32).toFixed(2);\n //humidity\n var humidity = response.main.humidity;\n //wind speed\n var windSpeed = response.wind.speed;\n\n $(\".current-location\").text(`${response.name} ${currentDate}`);\n $(\"#weatherDisplay\").attr(\"src\", weatherURL);\n $(\"#weatherDisplay\").attr(\"alt\", \"weather icon\");\n $(\".current-temp\").text(\"Temp: \" + temp + \" F\");\n $(\".current-humidity\").text(\"Humidity: \" + humidity + \"%\");\n $(\".wind-speed\").text(\"Wind Speed: \" + windSpeed + \" mph\");\n\n history.push(response.name);\n\n getUVIndex();\n\n getFiveDayForecast();\n\n appendHistory();\n\n $(\"#locationInput\").val(\"\");\n });\n });\n\n $(document).on(\"click\", \".historical-search\", function () {\n var locationInput = $(this).text();\n\n var queryURL =\n \"https://api.openweathermap.org/data/2.5/weather?q=\" +\n locationInput +\n \"&appid=\" +\n APIkey;\n\n $.ajax({\n url: queryURL,\n method: \"GET\",\n }).then(function (response) {\n inputResponse = response;\n weatherIconCode = response.weather[0].icon;\n var weatherURL =\n \"http://openweathermap.org/img/w/\" + weatherIconCode + \".png\";\n\n var currentDate = moment().format(\"L\");\n //grab Kelvin and convert to F\n var kelvin = response.main.temp;\n var temp = ((kelvin - 273.15) * 1.8 + 32).toFixed(2);\n //humidity\n var humidity = response.main.humidity;\n //wind speed\n var windSpeed = response.wind.speed;\n\n $(\".current-location\").text(`${response.name} ${currentDate}`);\n $(\"#weatherDisplay\").attr(\"src\", weatherURL);\n $(\"#weatherDisplay\").attr(\"alt\", \"weather icon\");\n $(\".current-temp\").text(\"Temp: \" + temp + \" F\");\n $(\".current-humidity\").text(\"Humidity: \" + humidity + \"%\");\n $(\".wind-speed\").text(\"Wind Speed: \" + windSpeed + \" mph\");\n\n getUVIndex();\n\n getFiveDayForecast();\n });\n });\n\n $(\"#clear-history\").on(\"click\", function (e) {\n localStorage.clear();\n $(\".list-group\").empty();\n });\n});\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252965,"cells":{"blob_id":{"kind":"string","value":"020328c22700af2811af408d04095c93fa2f6da2"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"erin-smith/menu-maker"},"path":{"kind":"string","value":"/client/src/components/MainCard/index.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4501,"string":"4,501"},"score":{"kind":"number","value":2.515625,"string":"2.515625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"import React, {useState, useEffect} from \"react\";\nimport MenuSelectButton from \"../MenuSelectButton\";\nimport EditButton from \"../EditButton\";\nimport MenuList from \"../MenuList\";\nimport API from \"../../utils/API\";\nimport CategoryModal from \"../CategoryModal\"\n\n\n\nfunction MainCard (){\n\n const [selectedMenuData, setSelectedMenuData] = useState({categories:[], menuTime:\"\", daypart:\"\"});\n const [selectedMenuId, setSelectedMenuId] = useState();\n const [menuList, setMenuList] = useState([]);\n \n // Load entrees and store them with menu\n useEffect(() => {\n console.log(\"fetching\");\n API.getMenus()\n .then(res => {\n //console.log(\"db data:\",res)\n setMenuList(res.data.map((x)=>{\n return {id:x._id, daypart:x.daypart}\n }));\n if(res.data.length){\n selectMenu(res.data[0]._id);\n }\n })\n .catch(err => console.log(err, \"Right here Error!!\"));\n\n }, [])\n \n function selectMenu(id) {\n loadMenu(id);\n setSelectedMenuId(id);\n };\n\n function loadMenu(id){\n console.log(\"loading menu\", id);\n API.getMenu(id)\n .then(res => {\n setSelectedMenuData(res.data)\n console.log(\"menu data loaded\")\n })\n .catch(err => console.log(err, \"Right here Error!!\"));\n }\n\n function onNewCategory(name){\n setSelectedMenuData((oldMenu)=>\n {\n let newCat = {id:Date.now(), name:name, items:[]}\n let updatedMenu = JSON.parse(JSON.stringify(oldMenu));\n updatedMenu.categories.push(newCat);\n console.log(\"menuid\",selectedMenuId);\n console.log(updatedMenu);\n API.updateMenu(selectedMenuId, updatedMenu)\n .then(() => console.log(\"new category added\", name))\n .catch((err) => console.log(err));\n return updatedMenu;\n } )\n }\n\n function onItemUpdate(itemData, category){\n setSelectedMenuData((oldMenu)=>\n {\n let updatedMenu = JSON.parse(JSON.stringify(oldMenu));\n const cat = updatedMenu.categories.find(x=> x.id ===category.id);\n const i = cat.items.findIndex(x => x.id === itemData.id);\n cat.items[i] = itemData;\n \n API.updateMenu(selectedMenuId, updatedMenu)\n .then(() => console.log(\"updated item\", itemData.name))\n .catch((err) => console.log(err));\n return updatedMenu;\n } )\n }\n\n function onMenuSelectChange(newMenu){\n console.log(\"menu selected\", newMenu)\n selectMenu(newMenu)\n }\n\n function onItemClick(){\n \n }\n\n function onNewItem(categoryId, itemData){\n setSelectedMenuData((oldMenu)=>\n {\n let updatedMenu = JSON.parse(JSON.stringify(oldMenu));\n const cat = updatedMenu.categories.find(x=> x.id ===categoryId);\n cat.items.push(itemData);\n\n API.updateMenu(selectedMenuId, updatedMenu)\n .then(() => console.log(\"Item added: \", itemData.name))\n .catch((err) => console.log(err));\n return updatedMenu;\n } )\n }\n\n function onTimeChange(newTime){\n setSelectedMenuData((oldMenu)=>\n {\n let updatedMenu = JSON.parse(JSON.stringify(oldMenu));\n updatedMenu.menuTime = newTime;\n \n API.updateMenu(selectedMenuId, updatedMenu)\n .then(() => console.log(\"updated time\",newTime))\n .catch((err) => console.log(err));\n return updatedMenu;\n } )\n }\n\n return (\n
\n
\n
\n
\n
\n \n
\n
\n {selectedMenuId ? (\n \n ):(
)}\n
\n
\n
\n
\n
\n
\n \n \n
\n
\n \n \n
\n
\n
\n );\n };\n export default MainCard;"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252966,"cells":{"blob_id":{"kind":"string","value":"692de6f5197c74c3ee070ee1a268b83916143efc"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"mindbullet/mindbullet.github.io"},"path":{"kind":"string","value":"/chapter14/fishcreek/scripts/fishcreek.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":219,"string":"219"},"score":{"kind":"number","value":2.765625,"string":"2.765625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\n$(function() {\n // show last modified date at bottom of page\n var dateDisplay = $('#date-display');\n var message = 'This page was last modified on: ' + document.lastModified;\n dateDisplay.html(message);\n});"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252967,"cells":{"blob_id":{"kind":"string","value":"77204c03bbec222d84f1d8a99cb30af7df481fc6"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"simCecca/ClassicGames"},"path":{"kind":"string","value":"/src/games/gameLogics/SnakeLogic.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1317,"string":"1,317"},"score":{"kind":"number","value":3.171875,"string":"3.171875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"class SnakeLogic{\n constructor(boardDimensions){\n this.boardDimensions = boardDimensions;\n }\n newApplePosition(){\n return {row: Math.floor(Math.random() * this.boardDimensions), column: Math.floor(Math.random() * this.boardDimensions)};\n }\n\n controller(event, direction){\n const newDirection = direction;\n if (event.keyCode === 38) { //up arrow\n if (direction.y !== 1) { //if you are going down you can't going up\n newDirection.x = 0;\n newDirection.y = -1;\n }\n } else if (event.keyCode === 40) {//down arrow\n if (direction.y !== -1) {//if you are going up you can't going down\n newDirection.x = 0;\n newDirection.y = 1;\n }\n } else if (event.keyCode === 39) {//right arrow\n if (direction.x !== -1) {//if you are going to left you can't turn right\n newDirection.x = 1;\n newDirection.y = 0;\n }\n } else if (event.keyCode === 37) { //left arrow\n if (direction.x !== 1) {//if you are going to right you can't turn left\n newDirection.x = -1;\n newDirection.y = 0;\n }\n }\n return newDirection;\n }\n\n snake\n}\n\nexport default SnakeLogic;"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252968,"cells":{"blob_id":{"kind":"string","value":"defc351f90e8c8d9c11bc02367c903b691cdd5df"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"ZECTBynmo/gyp-to-obj"},"path":{"kind":"string","value":"/gyp-to-obj.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1165,"string":"1,165"},"score":{"kind":"number","value":2.953125,"string":"2.953125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"//////////////////////////////////////////////////////////////////////////\n// gyp-to-obj - Read gyp files and serialize them into JavaScript objects\n//////////////////////////////////////////////////////////////////////////\n//\n// Main script!\n/* ----------------------------------------------------------------------\n\t\t\t\t\t\t\t\t\t\t\t\t\tObject Structures\n-------------------------------------------------------------------------\n\t\n*/\n//////////////////////////////////////////////////////////////////////////\n// Requires\nvar JSON5 = require(\"JSON5\"),\n\tfs = require(\"fs\");\n\n//////////////////////////////////////////////////////////////////////////\n// Namespace (lol)\nvar SHOW_DEBUG_PRINTS = true;\nvar log = function( a ) { if(SHOW_DEBUG_PRINTS) console.log(a); };\t// A log function we can turn off\n\n\nvar GypToObj = exports;\n\n\n//////////////////////////////////////////////////////////////////////////\n// Read in a gyp file and return it's object representation \nGypToObj.read = function( path ) {\n\tcontents = {};\n\n\ttry { \n\t\tvar contents = JSON5.parse(fs.readFileSync(path, \"utf8\"));\n\t} catch( err ) {\n\t\tconsole.log( \"ERROR\" );\n\t\tconsole.log( err );\n\t}\n\n\treturn contents\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252969,"cells":{"blob_id":{"kind":"string","value":"e5f123c0c54b87357b70d7a72a89fcc4e57ba64e"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"YoKaramfilova/SoftUni-Coursework"},"path":{"kind":"string","value":"/Programming Fundamentals with JavaScript/Mid Exam/03-mid-exam.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1871,"string":"1,871"},"score":{"kind":"number","value":3.515625,"string":"3.515625"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"function solve(arr) {\n let collection = arr.shift().split(' ');\n\n for (let i = 0; i < arr.length; i++) {\n let command = arr[i].split(' ');\n\n if (command.includes('Delete')) {\n let index = +command[1];\n\n if (index >= 0 && index < collection.length) {\n collection.splice(index + 1, 1);\n }\n\n } else if (command.includes('Swap')) {\n let word1 = command[1];\n let word2 = command[2];\n\n if (collection.includes(word1) && collection.includes(word2)) {\n let index1 = collection.indexOf(word1);\n let index2 = collection.indexOf(word2);\n collection[index1] = word2;\n collection[index2] = word1;\n }\n\n } else if (command.includes('Put')) {\n let word = command[1];\n let index = +command[2];\n\n if (index === collection.length - 1) {\n collection.push(word);\n } else if (index > 0 && index < collection.length - 1) {\n collection.splice(index - 1, 0, word);\n } \n\n } else if (command.includes('Sort')) {\n\n collection.sort((a, b) => b.localeCompare(a));\n\n } else if (command.includes('Replace')) {\n let word1 = command[1];\n let word2 = command[2];\n\n while (collection.includes(word2)) {\n collection[collection.indexOf(word2)] = word1;\n }\n\n } else if (command.includes('Stop')) {\n break;\n }\n }\n\n console.log(collection.join(' '));\n\n}\n\nsolve(([\"Congratulations! You last also through the have challenge!\",\n \"Swap have last\",\n \"Replace made have\",\n \"Delete 2\",\n \"Put it 4\",\n \"Stop\"]));\nsolve(([\"This the my quest! final\",\n \"Put is 2\",\n \"Swap final quest!\",\n \"Delete 2\",\n \"Stop\"]))\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252970,"cells":{"blob_id":{"kind":"string","value":"b17d35f5c3dd4c75c19e4e848d6cf64937dbcf85"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"aslafy-z/home-assistant-polymer"},"path":{"kind":"string","value":"/src/panels/lovelace/cards/hui-entity-filter-card.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2113,"string":"2,113"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"import { PolymerElement } from \"@polymer/polymer/polymer-element\";\n\nimport { createCardElement } from \"../common/create-card-element\";\nimport { processConfigEntities } from \"../common/process-config-entities\";\n\nfunction getEntities(hass, filterState, entities) {\n return entities.filter((entityConf) => {\n const stateObj = hass.states[entityConf.entity];\n return stateObj && filterState.includes(stateObj.state);\n });\n}\n\nclass HuiEntitiesCard extends PolymerElement {\n static get properties() {\n return {\n hass: {\n type: Object,\n observer: \"_hassChanged\",\n },\n };\n }\n\n getCardSize() {\n return this.lastChild ? this.lastChild.getCardSize() : 1;\n }\n\n setConfig(config) {\n if (!config.state_filter || !Array.isArray(config.state_filter)) {\n throw new Error(\"Incorrect filter config.\");\n }\n\n this._config = config;\n this._configEntities = processConfigEntities(config.entities);\n\n if (this.lastChild) {\n this.removeChild(this.lastChild);\n this._element = null;\n }\n\n const card = \"card\" in config ? { ...config.card } : {};\n if (!card.type) card.type = \"entities\";\n card.entities = [];\n\n const element = createCardElement(card);\n element._filterRawConfig = card;\n this._updateCardConfig(element);\n\n this._element = element;\n }\n\n _hassChanged() {\n this._updateCardConfig(this._element);\n }\n\n _updateCardConfig(element) {\n if (!element || element.tagName === \"HUI-ERROR-CARD\" || !this.hass) return;\n const entitiesList = getEntities(\n this.hass,\n this._config.state_filter,\n this._configEntities\n );\n\n if (entitiesList.length === 0 && this._config.show_empty === false) {\n this.style.display = \"none\";\n return;\n }\n\n this.style.display = \"block\";\n element.setConfig({ ...element._filterRawConfig, entities: entitiesList });\n element.isPanel = this.isPanel;\n element.hass = this.hass;\n\n // Attach element if it has never been attached.\n if (!this.lastChild) this.appendChild(element);\n }\n}\ncustomElements.define(\"hui-entity-filter-card\", HuiEntitiesCard);\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252971,"cells":{"blob_id":{"kind":"string","value":"a16491e921c45db9a3e37abf4800eed56b3ddf13"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"landongn/sleepy"},"path":{"kind":"string","value":"/src/level/schemes/DenseCastleScheme.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":9326,"string":"9,326"},"score":{"kind":"number","value":2.671875,"string":"2.671875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"import { digExits } from '../LevelConnections';\nimport TileContainer from '../TileContainer';\nimport { TILE_TYPE_FLOOR, TILE_TYPE_WALL } from '../TileData';\nimport { pickRandom, randomInt } from '../../utils/rand';\nimport { computeAStar } from '../../utils/AStar';\nimport { diagonalDistance } from '../../utils/diagonalDistance';\nimport TileScheme from '../TileScheme';\n\nconst VERTICAL = 0;\nconst HORIZONTAL = 1;\n\nlet curId = 1;\nconst createNodeId = () => curId++;\n\nconst splitNodeVertical = (node, cut) => {\n const leftId = createNodeId();\n const rightId = createNodeId();\n const left = {\n id: leftId,\n isLeaf: true,\n parentId: node.id,\n siblingId: rightId,\n offsetX: node.offsetX,\n offsetY: node.offsetY,\n width: cut,\n height: node.height,\n };\n const right = {\n id: rightId,\n isLeaf: true,\n parentId: node.id,\n siblingId: leftId,\n offsetX: node.offsetX + cut,\n offsetY: node.offsetY,\n width: node.width - cut,\n height: node.height,\n };\n return [left, right];\n};\n\nconst splitNodeHorizontal = (node, cut) => {\n const topId = createNodeId();\n const bottomId = createNodeId();\n const top = {\n id: topId,\n isLeaf: true,\n parentId: node.id,\n siblingId: bottomId,\n offsetX: node.offsetX,\n offsetY: node.offsetY,\n width: node.width,\n height: cut,\n };\n const bottom = {\n id: bottomId,\n isLeaf: true,\n parentId: node.id,\n siblingId: topId,\n offsetX: node.offsetX,\n offsetY: node.offsetY + cut,\n width: node.width,\n height: node.height - cut,\n };\n\n return [top, bottom];\n};\n\nexport class DenseCastleScheme extends TileScheme {\n static generate(settings) {\n const width = settings.width;\n const height = settings.height;\n const exits = settings.exits || [];\n\n const minRoomWidth = settings.minRoomWidth || 4;\n const minRoomHeight = settings.minRoomHeight || 4;\n\n const maxRoomWidth = settings.maxRoomWidth || 12;\n const maxRoomHeight = settings.maxRoomHeight || 12;\n\n const splitIgnoreChance = settings.splitIgnoreChance || 0.8;\n\n const loopiness = settings.loopiness || 35;\n\n const tiles = new TileContainer(width, height);\n\n for (let i = 0; i < width; i++) {\n for (let j = 0; j < height; j++) {\n if (i === 0 || i === width - 1 || j === 0 || j === height - 1) {\n tiles.setTileType(i, j, TILE_TYPE_WALL);\n } else {\n tiles.setTileType(i, j, TILE_TYPE_FLOOR);\n }\n }\n }\n\n const nodes = [\n {\n isLeaf: true,\n parentId: null,\n siblingId: null,\n id: createNodeId(),\n offsetX: 0,\n offsetY: 0,\n height: height - 1,\n width: width - 1,\n },\n ];\n\n const graph = [];\n\n while (nodes.length > 0) {\n const node = nodes.pop();\n graph.push(node);\n\n if (node.width < maxRoomWidth && node.height < maxRoomHeight) {\n const ignoreSplit = Math.random() < splitIgnoreChance;\n\n if (ignoreSplit) {\n continue;\n }\n }\n\n const directions = [];\n\n if (node.width - minRoomWidth - 1 > minRoomWidth) {\n directions.push(VERTICAL);\n }\n\n if (node.height - minRoomHeight - 1 > minRoomHeight) {\n directions.push(HORIZONTAL);\n }\n\n if (directions.length <= 0) {\n continue;\n }\n\n const direction = pickRandom(directions);\n\n if (direction === VERTICAL) {\n const cut = randomInt(\n minRoomWidth + 1,\n node.width - minRoomWidth - 1\n );\n\n nodes.push(...splitNodeVertical(node, cut));\n } else {\n const cut = randomInt(\n minRoomHeight + 1,\n node.height - minRoomHeight - 1\n );\n\n nodes.push(...splitNodeHorizontal(node, cut));\n }\n\n node.isLeaf = false;\n }\n\n graph.forEach((node) => {\n if (node.parentId === null) {\n return;\n }\n\n if (node.isLeaf) {\n const room = tiles.createRoom(\n node.offsetX + 1,\n node.offsetY + 1,\n node.width - 1,\n node.height - 1\n );\n\n room.includeWalls = true;\n\n for (let i = 0; i < node.width; i++) {\n tiles.setTileType(\n node.offsetX + i,\n node.offsetY,\n TILE_TYPE_WALL\n );\n }\n\n for (let j = 0; j < node.height; j++) {\n tiles.setTileType(\n node.offsetX,\n node.offsetY + j,\n TILE_TYPE_WALL\n );\n }\n return;\n }\n });\n\n graph.forEach((node) => {\n if (node.parentId === null) {\n return;\n }\n\n const sibling = graph.find((n) => n.id === node.siblingId);\n\n let doorCandidates = [];\n let hasSib = false;\n\n if (sibling.offsetX < node.offsetX) {\n hasSib = true;\n for (let i = 1; i < node.height; i++) {\n const x = node.offsetX;\n const y = node.offsetY + i;\n const tile = tiles.getTile(x, y);\n\n if (\n tiles.tileTypeMatches(x - 1, y, TILE_TYPE_FLOOR) &&\n tiles.tileTypeMatches(x + 1, y, TILE_TYPE_FLOOR)\n ) {\n doorCandidates.push(tile);\n }\n }\n } else if (sibling.offsetY < node.offsetY) {\n hasSib = true;\n for (let i = 1; i < node.width; i++) {\n const x = node.offsetX + i;\n const y = node.offsetY;\n const tile = tiles.getTile(x, y);\n\n if (\n tiles.tileTypeMatches(x, y - 1, TILE_TYPE_FLOOR) &&\n tiles.tileTypeMatches(x, y + 1, TILE_TYPE_FLOOR)\n ) {\n doorCandidates.push(tile);\n }\n }\n }\n\n const door = pickRandom(doorCandidates);\n\n if (hasSib && !door) {\n console.warn(\n 'cannot make door!?',\n node,\n node.width,\n node.height\n );\n }\n\n if (door) {\n const room = tiles.getRoomForTile(door.x, door.y);\n\n if (room) {\n room.addExit(door.x, door.y);\n }\n\n tiles.setTileType(door.x, door.y, TILE_TYPE_FLOOR);\n }\n });\n\n const cost = (a, b) => {\n if (tiles.tileTypeMatches(b.x, b.y, TILE_TYPE_FLOOR)) {\n return diagonalDistance(a, b);\n }\n\n return Infinity;\n };\n\n const tryAddLoop = (a, b) => {\n if (a.isType(TILE_TYPE_FLOOR) && b.isType(TILE_TYPE_FLOOR)) {\n const start = {\n x: b.x,\n y: b.y,\n };\n const goal = {\n x: a.x,\n y: a.y,\n };\n const path = computeAStar({\n start,\n goal,\n cost,\n });\n\n if (path.success && path.cost >= loopiness) {\n return true;\n }\n }\n\n return false;\n };\n\n tiles.data\n .filter((tile) => tile.isType(TILE_TYPE_WALL))\n .forEach((tile) => {\n const north = tiles.getTile(tile.x, tile.y - 1);\n const south = tiles.getTile(tile.x, tile.y + 1);\n\n if (tryAddLoop(north, south)) {\n tiles.setTileType(tile.x, tile.y, TILE_TYPE_FLOOR);\n\n const room = tiles.getRoomForTile(tile.x, tile.y);\n\n if (room) {\n room.addExit(tile.x, tile.y);\n }\n\n return;\n }\n\n const east = tiles.getTile(tile.x - 1, tile.y);\n const west = tiles.getTile(tile.x + 1, tile.y);\n\n if (tryAddLoop(east, west)) {\n tiles.setTileType(tile.x, tile.y, TILE_TYPE_FLOOR);\n\n const room = tiles.getRoomForTile(tile.x, tile.y);\n\n if (room) {\n room.addExit(tile.x, tile.y);\n }\n\n return;\n }\n });\n\n digExits(tiles, exits);\n\n return tiles;\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252972,"cells":{"blob_id":{"kind":"string","value":"9ed4dcb8fe46791f6e06bd1b6d232a46d40187be"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"jccastiblancor/forms"},"path":{"kind":"string","value":"/src/customHooks/useForm.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":643,"string":"643"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"import { useState } from \"react\";\n\nconst useForm = (validateForm) => {\n const [errors, setErrors] = useState({});\n const [values, setValues] = useState({});\n\n const handleChange = (evt) => {\n setValues({\n ...values,\n [evt.target.name]: evt.target.value,\n });\n };\n\n const initialValues = (val) => {\n const obj = {};\n\n for (const key of val) {\n obj[key] = \"\";\n }\n\n setValues(obj);\n };\n\n const handleSubmit = (evt) => {\n evt.preventDefault();\n setErrors(validateForm(values));\n console.log(values);\n };\n\n return { handleChange, initialValues, handleSubmit, errors };\n};\n\nexport default useForm;\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252973,"cells":{"blob_id":{"kind":"string","value":"ef493df9d602d1d218ff418faa1d1d20103279af"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"yehor-dykhov/SS"},"path":{"kind":"string","value":"/OLD/hw_1602015_module5/group.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1081,"string":"1,081"},"score":{"kind":"number","value":3.21875,"string":"3.21875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"function Group (_nameGroup) {\n var nameGroup = _nameGroup,\n students = [];\n\n this.getNameGroup = function () {\n return nameGroup;\n };\n\n this.addStudent = function (name) {\n students.push(new Student(name));\n\n console.log('Student %s was added', name);\n };\n\n this.addStudents = function (names) {\n var i;\n\n for (i = 0; i < names.length; i++) {\n this.addStudent(names[i]);\n }\n };\n\n this.getStudents = function () {\n return students;\n };\n\n this.removeStudent = function (name) {\n var deletedStudents,\n i;\n\n for (i = 0; i < students.length; i++) {\n if (students[i].getName() === name) {\n deletedStudents = students.slice(i, 1);\n break;\n }\n }\n\n console.log('Student %s was deleted.', deletedStudents[0].getName());\n\n return deletedStudents[0].getName();\n };\n\n this.clearGroup = function () {\n students = [];\n\n console.log('Group was cleaned.');\n };\n\n return this;\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252974,"cells":{"blob_id":{"kind":"string","value":"7228699fb588f8dbb7b7a5723a6635c45f0ea11b"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"riebel/pixi-babel-webpack"},"path":{"kind":"string","value":"/src/app.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1323,"string":"1,323"},"score":{"kind":"number","value":2.84375,"string":"2.84375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"import * as PIXI from 'pixi.js'\n\nclass App {\n constructor() {\n this.renderer = PIXI.autoDetectRenderer(800, 600, { antialias: true });\n \n // create the root of the scene graph\n this.stage = new PIXI.Container();\n\n this.speed = 0.01;\n this.frame = 0;\n\n this.render();\n\n // run the render loop\n this.animate();\n }\n\n render() {\n const richText = new PIXI.Text('PIXI.js',{\n fontFamily : 'Arial',\n fontSize : '240px',\n fontStyle : 'italic',\n fontWeight : 'bold',\n fill : '#F7EDCA',\n stroke : '#4a1850',\n strokeThickness : 5\n });\n\n richText.x = 400;\n richText.y = 300;\n richText.anchor = {x: 0.5, y: 0.5};\n\n this.stage.addChild(richText);\n\n return this;\n }\n\n animate() {\n requestAnimationFrame( this.animate.bind(this) );\n this.frame++;\n\n const richText = this.stage.children[0];\n const sine = Math.sin(this.speed * this.frame);\n\n richText.rotation = sine * 6.3;\n richText.width = (sine / 2 + 0.5) * 800;\n richText.height = (sine / 2 + 0.5) * 600;\n\n this.renderer.render(this.stage);\n }\n}\n\nexport const app = new App();\n\ndocument.body.appendChild(app.renderer.view);"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252975,"cells":{"blob_id":{"kind":"string","value":"84cb3fc4fc3ea4e18f17e07c787852c7bcd1f514"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"Sivory/sivory.github.com"},"path":{"kind":"string","value":"/mylab/cs/game/scripts/Old/background.backup.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3465,"string":"3,465"},"score":{"kind":"number","value":2.71875,"string":"2.71875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"var Util = imports('util');\n\nvar actorList = [\n\t// assets('zombie001'),\n\t// assets('zombie002'),\n\t// assets('zombie003'),\n\t// assets('zombie004'),\n\t// assets('zombie005'),\n\t// assets('zombie006'),\n\t// assets('zombie007'),\n\t// assets('zombie008'),\n\t// assets('zombie009')\n];\n\nvar Background = function(callbackCenter) {\n\tthis.aimPosX = 0;\n\tthis.aimPosY = 0;\n\tvar that = this;\n\tcallbackCenter.register('aimPos', function(aimInfo) {\n\t\tthat.onAimPos(aimInfo);\n\t});\n\tcallbackCenter.register('fire', function() {\n\t\tthat.onFire();\n\t});\n\tthis.image = assets('b1');\n\tthis.actors = [];\n};\n\nBackground.prototype.onAimPos = function(aimInfo) {\n\tthis.aimPosX = aimInfo.x;\n\tthis.aimPosY = aimInfo.y;\n};\n\nBackground.prototype.onFire = function() {\n\tvar checkX = this.aimPosX + window.innerWidth / 2;\n\tvar checkY = this.aimPosY + window.innerHeight / 2;\n\tfor (var i = this.actors.length - 1; i >= 0; i--) {\n\t\tif (this.actors[i].image.complete && this.actors[i].deadScale == null) {\n\t\t\tif (Util.checkInBox(checkX, checkY, this.actors[i].area_x, this.actors[i].area_y, this.actors[i].area_w, this.actors[i].area_h)) {\n\t\t\t\tthis.actors[i].deadScale = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n};\n\nBackground.prototype.update = function() {\n\tif (Math.random() < 0.02 && this.actors.length < 5) {\n\t\treturn;\n\t\tvar index = Math.floor(Math.random() * 9);\n\t\tvar image = actorList[index];\n\t\tthis.actors.push({\n\t\t\timage: image,\n\t\t\tx: Math.random() * 300 - 150,\n\t\t\ty: Math.random() * 40,\n\t\t\tscale: 0.1,\n\t\t\tarea_x: 0,\n\t\t\tarea_y: 0,\n\t\t\tarea_w: 0,\n\t\t\tarea_h: 0\n\t\t});\n\t}\n\tfor (var i = 0; i < this.actors.length; i++) {\n\t\tif (this.actors[i].deadScale == null) {\n\t\t\tthis.actors[i].scale += 0.001;\n\t\t\tif (this.actors[i].scale >= 0.4) {\n\t\t\t\tthis.actors.splice(i, 1);\n\t\t\t\ti--;\n\t\t\t}\n\t\t} else {\n\t\t\tthis.actors[i].deadScale -= 0.05;\n\t\t\tif (this.actors[i].deadScale <= 0) {\n\t\t\t\tthis.actors.splice(i, 1);\n\t\t\t\ti--;\n\t\t\t}\n\t\t}\n\t}\n\tthis.actors.sort(function(a, b) {\n\t\treturn a.scale - b.scale;\n\t});\n};\n\nBackground.prototype.draw = function(ctx) {\n\tif (this.image.complete) {\n\t\tvar srcWidth = this.image.width;\n\t\tvar srcHeight = this.image.height;\n\t\tvar tarWidth = ctx.canvas.width;\n\t\tvar tarHeight = ctx.canvas.height;\n\t\tvar width = tarWidth;\n\t\tvar height = srcHeight / srcWidth * tarWidth;\n\t\tif (height < tarHeight) {\n\t\t\theight = tarHeight;\n\t\t\twidth = srcWidth / srcHeight * tarHeight;\n\t\t}\n\t\tvar drawWidth = width * 1.2;\n\t\tvar drawHeight = height * 1.2;\n\t\tvar startX = tarWidth / 2 - drawWidth / 2 - this.aimPosX / (tarWidth / 2) * width * 0.1;\n\t\tvar startY = tarHeight / 2 - drawHeight / 2 - this.aimPosY / (tarHeight / 2) * height * 0.1;\n\t\tctx.drawImage(this.image, startX, startY, drawWidth, drawHeight);\n\n\t\tfor (var i = 0; i < this.actors.length; i++) {\n\t\t\tif (this.actors[i].image == null) console.log(i);\n\t\t\tif (this.actors[i].image.complete) {\n\t\t\t\tvar w = this.actors[i].image.width * this.actors[i].scale;\n\t\t\t\tvar h = this.actors[i].image.height * this.actors[i].scale;\n\t\t\t\tvar x = tarWidth / 2 + this.actors[i].x - w / 2 - this.aimPosX / (tarWidth / 2) * width * 0.1;\n\t\t\t\tvar y = tarHeight / 2 + this.actors[i].y - h / 2 - this.aimPosY / (tarHeight / 2) * height * 0.1;\n\t\t\t\tif (this.actors[i].deadScale != null) {\n\t\t\t\t\ty += h * (1 - this.actors[i].deadScale);\n\t\t\t\t\th = h * this.actors[i].deadScale;\n\t\t\t\t}\n\t\t\t\tctx.drawImage(this.actors[i].image, x, y, w, h);\n\t\t\t\tthis.actors[i].area_x = x;\n\t\t\t\tthis.actors[i].area_y = y;\n\t\t\t\tthis.actors[i].area_w = w;\n\t\t\t\tthis.actors[i].area_h = h;\n\t\t\t}\n\t\t}\n\t}\n};\n\nexports = Background;"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252976,"cells":{"blob_id":{"kind":"string","value":"90c343833432624058cd2439c1661b8747957ac4"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"dart-lang/webdev"},"path":{"kind":"string","value":"/dwds/debug_extension/web/devtools.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2238,"string":"2,238"},"score":{"kind":"number","value":2.578125,"string":"2.578125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause"],"string":"[\n \"BSD-3-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"(function loadDevToolsScript() {\n const DDR_DART_APP_ATTRIBUTE = 'data-ddr-dart-app';\n // Note: Changes to the DEBUGGER_PANEL_NAME and INSPECTOR_PANEL_NAME\n // must be reflected in `tool/update_dev_files.dart` as well.\n const DEBUGGER_PANEL_NAME = 'Dart Debugger';\n const INSPECTOR_PANEL_NAME = 'Flutter Inspector';\n\n let debuggerCreated = false;\n let inspectorCreated = false;\n let checkDartCount = 0;\n let checkFlutterCount = 0;\n\n chrome.devtools.network.onNavigated.addListener(createDebuggerPanelIfDartApp)\n const checkDartAppInterval = setInterval(createDebuggerPanelIfDartApp, 1000)\n createDebuggerPanelIfDartApp()\n\n function createDebuggerPanelIfDartApp() {\n if (debuggerCreated || checkDartCount++ > 20) {\n clearInterval(checkDartAppInterval);\n return;\n }\n\n checkIsDartApp();\n }\n\n function checkIsDartApp() {\n // TODO(elliette): Remove the DDR data attribute check when we are ready to launch externally,\n // and instead replace it with the following: !!window.$dartAppId \n // Note: we must remove the useContentScriptContext option as well.\n chrome.devtools.inspectedWindow.eval(\n `document.documentElement.hasAttribute(\"${DDR_DART_APP_ATTRIBUTE}\")`,\n { useContentScriptContext: true },\n function (isDartApp) {\n if (!isDartApp) return;\n\n chrome.devtools.panels.create(\n DEBUGGER_PANEL_NAME, '', 'debugger_panel.html'\n );\n debuggerCreated = true;\n createInspectorPanelIfFlutterApp();\n });\n }\n\n function createInspectorPanelIfFlutterApp() {\n const checkFlutterAppInterval = setInterval(function () {\n if (inspectorCreated || checkFlutterCount++ > 10) {\n clearInterval(checkFlutterAppInterval);\n return;\n }\n\n // The following value is loaded asynchronously, which is why\n // we check for it every 1 second:\n chrome.devtools.inspectedWindow.eval(\n '!!window._flutter_web_set_location_strategy',\n function (isFlutterWeb) {\n if (isFlutterWeb) {\n chrome.devtools.panels.create(\n INSPECTOR_PANEL_NAME, '', 'inspector_panel.html'\n );\n inspectorCreated = true;\n }\n }\n );\n }, 1000)\n }\n}());\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252977,"cells":{"blob_id":{"kind":"string","value":"042112a3209f6b7af105f2c68b304fbee9e791c6"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"yiy142/gallerize"},"path":{"kind":"string","value":"/server/store.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4817,"string":"4,817"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"\"use strict\";\n\nconst _ = require(\"lodash\");\nconst bodyParser = require(\"body-parser\");\nconst express = require(\"express\");\nconst mongodb = require(\"mongodb\");\nconst colors = require(\"colors/safe\");\n\nconst app = express();\nconst cors = require('cors');\napp.options('*', cors());\nconst MongoClient = mongodb.MongoClient;\nconst port = process.env.port || 7001;\nconst mongoCreds = require(\"./auth.json\");\nconst mongoURL = `mongodb://${mongoCreds.user}:${mongoCreds.password}@127.0.0.1/gallerize?authSource=admin`\nconst mongoose = require(\"mongoose\");\nmongoose.set('useCreateIndex', true);\n\nfunction makeMessage(text) {\n return `${colors.blue(\"[store]\")} ${text}`;\n}\n\nfunction log(text) {\n console.log(makeMessage(text));\n}\n\nfunction error(text) {\n console.error(makeMessage(text));\n}\n\nfunction failure(response, text) {\n const message = makeMessage(text);\n console.error(message);\n return response.status(500).send(message);\n}\n\nfunction success(response, text) {\n const message = makeMessage(text);\n console.log(message);\n return response.send(message);\n}\n\nfunction mongoConnectWithRetry(delayInMilliseconds, callback) {\n mongoose.connect(mongoURL,{\n useNewUrlParser: true\n },(err, connection) => {\n //MongoClient.connect(mongoURL, { useNewUrlParser: true}, (err, connection) => {\n if (err) {\n console.error(`Error connecting to MongoDB: ${err}`);\n setTimeout(\n () => mongoConnectWithRetry(delayInMilliseconds, callback),\n delayInMilliseconds\n );\n } else {\n log(\"connected succesfully to mongodb\");\n callback(connection);\n }\n }\n );\n}\n\nlet Draw = require(\"./models/draw.model\");\nfunction serve() {\n mongoConnectWithRetry(2000, connection => {\n app.use(cors());\n app.use(express.json());\n //app.use(bodyParser.json({ limit: \"50mb\" })); // added bll\n //app.use(bodyParser.urlencoded({ extended: true, limit: \"50mb\" }));\n \n console.log('Connected to mongo server.');\n\n app.post(\"/db/add\", (req, res) => {\n console.log(`In Add.`);\n const newDraw = new Draw({\n filename: req.body.filename,\n age: req.body.age,\n valid: req.body.valid,\n class: req.body.class\n });\n\n newDraw\n .save()\n .then(() => res.json(\"new Draw added!\"))\n .catch(err => res.status(400).json(\"Error: \" + err));\n });\n\n /* Update Data Query */\n app.put(\"/db/update-data\", (request, response) => {\n Draw.findOneAndUpdate({\n filename: request.body.filename\n },\n {valid: request.body.valid },\n {new: true},\n (error, result)=>{\n if(error){\n response.status(400).json(\"Error: \" + error);\n }\n else{\n response.status(200).send(\"valid updated!\");\n }\n }\n );\n });\n\n /* Get all classes query*/\n app.get(\"/db/get-classes\", (request, response) => {\n console.log(request.body);\n Draw.find().distinct('class',\n function (err, result) {\n if (err) {\n response.status(400).json(\"Error: \" + err);\n }\n else {\n response.status(200).json(result.sort());\n }\n }\n );\n });\n \n /* Get Data Query */\n app.post(\"/db/get-data\", (request, response) => {\n console.log(request.body);\n const order = request.body.order;\n const range = request.body.ageRange;\n const classes = request.body.classes;\n const validToken = parseInt(request.body.validToken); //-1 only invalids. 0 unchecked. 1 only valids. 2 for ALL\n let valids = [validToken];\n if (validToken === 2) {\n valids = [-1, 0, 1];\n }\n console.log(valids);\n var sortObject = {\n };\n if (order === \"Age (Young - Old) Group By Class\"){\n sortObject.age = 1;\n sortObject.class = 1;\n }\n else if( order === \"Age (Old - Young) Group By Class\") {\n sortObject.age = -1;\n sortObject.class = 1;\n } else if (order === \"Class (A - Z) Group By Age\"){\n sortObject.class = 1;\n sortObject.age = 1;\n }\n else if( order === \"Class (Z - A) Group By Age\") {\n sortObject.class = -1;\n sortObject.age = 1;\n }\n\n Draw.aggregate([\n {\n $match: {\n class: { $in: classes },\n age: { $gte: parseInt(range[0]), $lte: parseInt(range[1]) },\n valid: { $in: valids }\n }\n },\n {\n $sort: sortObject\n }\n ],\n function (err, result) {\n if (err) {\n response.status(400).json(\"Error: \" + err);\n }\n else {\n response.json(result);\n }\n }\n );\n });\n\n app.listen(port, () => {\n log(`running at http://localhost:${port}`);\n });\n });\n}\n\nserve();\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252978,"cells":{"blob_id":{"kind":"string","value":"f401f098646681f5aa8e63cfecbb88e08935a2c2"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"chezhiangit/BabyCare"},"path":{"kind":"string","value":"/App/Reducers/babyDetailsReducer.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1072,"string":"1,072"},"score":{"kind":"number","value":2.75,"string":"2.75"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"const DEFAULT_STATE = [{\n key:'',\n babyName:'',\n DOB:'',\n placeOfBirth:'',\n birthWeight:'',\n lengthAtBirth:'',\n bloodGroup:'',\n identification:'',\n remarks:''\n}]\n\nexport default (state = DEFAULT_STATE, action)=> {\n // console.log('baby details reducer : Action type: '+action.type)\n switch(action.type) {\n \n case 'LOAD_BABYDETAILS':\n return {\n ...state,\n babyDetails:action.data\n }\n // case 'ADD_BABYDETAILS':\n // return {\n // ...state,\n // babyDetails:[...state.babyDetails,action.data.item]\n // }\n // case 'UPDATE_BABYDETAILS':\n // const updatelist = [...state.babyDetails];\n // updatelist[action.data.index]=action.data.item\n // return {\n // ...state,\n // babyDetails:updatelist\n // }\n // case 'DELETE_BABYDETAILS':\n // const babylist = [...state.babyDetails];\n // babylist.splice(action.data.index, 1);\n // return {\n // ...state,\n // babyDetails:babylist\n // }\n default:\n return state\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252979,"cells":{"blob_id":{"kind":"string","value":"1ad6c669736c92a9edb1068627aaf55f0d31882a"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"Seb6277/form_project"},"path":{"kind":"string","value":"/routes/event.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":833,"string":"833"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"const express = require('express');\nconst router = express.Router();\n\n// Event model\nconst Event = require('../models/Event');\n\nrouter.get('/places', (req, res) => {\n Event.find((err, items) => {\n if (err) {\n console.log(err);\n res.end();\n } else {\n res.send(items);\n res.end();\n }\n });\n});\n\nrouter.post('/create', (req, res) => {\n if ((req.body.name !== null) && (req.body.nbr_places !== null)) {\n const newEvent = new Event({\n \"name\": req.body.name,\n \"nbr_places\": req.body.nbr_places\n });\n newEvent.save().then((item) => {\n res.status(201).json(item).end();\n }).catch((error) => {\n console.log(error);\n res.status(500).end();\n });\n }\n});\n\nmodule.exports = router;"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252980,"cells":{"blob_id":{"kind":"string","value":"443a4ff8aedf88bdd4dc02e21584ecf85dbf6b2a"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"nttung1211/coding-archive"},"path":{"kind":"string","value":"/node/Jonas/bootcamp/1-node-farm/starter/index.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1227,"string":"1,227"},"score":{"kind":"number","value":3.078125,"string":"3.078125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"// SYNCHRONOUS\n// const fs = require('fs');\n\n// const data = fs.readFileSync(__dirname + '/txt/input.txt', { encoding: 'utf-8' });\n// console.log(data);\n\n// const input = `Nguyễn Thanh Tùng: ${data}`;\n// fs.writeFileSync(__dirname + '/txt/output.txt', input, { flag: 'w' });\n//=======================================================================================\n\n// ASYNCHRONOUS\n// const fs = require('fs');\n\n// fs.readFile('./txt/input.txt', 'utf-8', (err, data) => { // if options is string it will see as encoding\n// if (err) {\n// console.log(err);\n// } else {\n// fs.writeFile('./txt/output.txt', data, { flag: 'w' }, (err) => {\n// if (err) {\n// console.log(err);\n// } else {\n// console.log('Wrote file successfully.');\n// }\n// });\n// }\n// });\n\n// console.log('Reading file...');\n\n//================================================================================================\n\n// CREATE FIRST WEB SERVER\n// const http = require('http');\n\n// const server = http.createServer(requestListener);\n\n// function requestListener(req, res) {\n// res.end('Tung dep trai');\n// }\n\n// server.listen(3000, '127.0.0.1', () => {\n// console.log('Server is listening on port 3000');\n// });\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252981,"cells":{"blob_id":{"kind":"string","value":"90fcf512371ce84d05611a019db93174f3b02a8b"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"hoodielive/esVersions"},"path":{"kind":"string","value":"/es6/syntax-changes-additions/fatArrows/fatArrow.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":297,"string":"297"},"score":{"kind":"number","value":3.9375,"string":"3.9375"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"// let fn = () => console.log('Hellerrrrr!'); \nlet fn = () => \"Hello!\"; \nconsole.log(fn()); \n\nlet fn2 = () => {\n let a = 2; \n let b = 3; \n return a + b; \n}\nconsole.log(fn2()); \n\n// or \nlet fn3 = (a, b) => a + b \nconsole.log(fn3(3, 8)); \n\nsetTimeout(() => console.log(\"Helleeerrrr!\"), 1000); \n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252982,"cells":{"blob_id":{"kind":"string","value":"568e7b2dae11b5ff0780a77d75628949e927d0a4"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"creograf-experience/2sport"},"path":{"kind":"string","value":"/app/client/public/lib/workout-instagram.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1578,"string":"1,578"},"score":{"kind":"number","value":2.625,"string":"2.625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"import _ from 'lodash';\nimport d3 from 'd3';\n\nexport function drawChartInstagram(element, times, values) {\n var margin = {top: 20, right: 20, bottom: 30, left: 20},\n width = 612 - margin.left - margin.right,\n height = 120 - margin.top - margin.bottom;\n\n // Set the ranges\n var x = d3.time.scale()\n .domain(d3.extent(times, d => d))\n .range([0, width]);\n\n var y = d3.scale.linear()\n .domain([0, _.max(values)])\n .nice(1)\n .range([height, 0]);\n\n // Define the axes\n var xAxis = d3.svg.axis()\n .scale(x)\n .ticks(5)\n .tickFormat(d3.time.format.utc('%H:%M'))\n .orient(\"bottom\");\n\n var yAxis = d3.svg.axis()\n .scale(y)\n .orient(\"right\")\n .tickSize(width)\n .ticks(4);\n\n // Define the line\n var valueline = d3.svg.line()\n .x(d => x(d[0]))\n .y(d => y(d[1]));\n\n // Adds the svg canvas\n var svg = d3.select(element)\n .append(\"svg\")\n .attr(\"width\", width + margin.left + margin.right)\n .attr(\"height\", height + margin.top + margin.bottom)\n .append(\"g\")\n .attr(\"transform\", `translate(${margin.left},${margin.top})`);\n\n // Add the valueline path.\n svg.append(\"path\")\n .attr(\"class\", \"line\")\n .attr(\"d\", valueline(_.zip(times, values)));\n\n // Add the X Axis\n svg.append(\"g\")\n .attr(\"class\", \"x axis\")\n .attr(\"transform\", `translate(0,${height})`)\n .call(xAxis);\n\n // Add the Y Axis\n const gy = svg.append(\"g\")\n .attr(\"class\", \"y axis\")\n .call(yAxis);\n\n gy.selectAll(\"g\").filter(d => d)\n .classed(\"minor\", true);\n\n gy.selectAll(\"text\")\n .attr(\"x\", 4)\n .attr(\"dy\", -4);\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252983,"cells":{"blob_id":{"kind":"string","value":"7d2ed25615003296ccf65a87e6a4f9440002dc28"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"teintinu/bd-stampy"},"path":{"kind":"string","value":"/utils/Paginate.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":278,"string":"278"},"score":{"kind":"number","value":2.6875,"string":"2.6875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause"],"string":"[\n \"BSD-3-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"/*eslint-disable */\nvar Paginate = function (array, ammount, page){\n var start = page * ammount;\n var end = start + ammount;\n\n if(start >= array.length) {\n start = array.length - ammount; \n }\n\n return array.slice(start, end);\n};\n\nmodule.exports = Paginate;"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252984,"cells":{"blob_id":{"kind":"string","value":"f961229244ad131a26369a4806b975dac06497a8"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"comicrelief/lambda-wrapper"},"path":{"kind":"string","value":"/src/Model/Model.model.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":771,"string":"771"},"score":{"kind":"number","value":2.890625,"string":"2.890625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"/* eslint-disable class-methods-use-this */\nimport validate from 'validate.js/validate';\n\n/**\n * Model base class\n */\nexport default class Model {\n /**\n * Instantiate a function with a value if defined\n *\n * @param classFunctionName string\n * @param value mixed\n */\n instantiateFunctionWithDefinedValue(classFunctionName, value) {\n if (typeof value !== 'undefined') {\n this[classFunctionName](value);\n }\n }\n\n /**\n * Validate values against constraints\n *\n * @param values object\n * @param constraints object\n * @returns {boolean}\n */\n validateAgainstConstraints(values: object, constraints: object): boolean {\n const validation = validate(values, constraints);\n return typeof validation === 'undefined';\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252985,"cells":{"blob_id":{"kind":"string","value":"eb5bbfdbef30bc079164b0e0569b33019ec9b904"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"vvuri/learn_babel"},"path":{"kind":"string","value":"/src/main.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":205,"string":"205"},"score":{"kind":"number","value":2.71875,"string":"2.71875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"let a = 5;\nconst b = (\"const\"[(a, b)] = [b, a]);\n\nclass First {\n constructor(x) {\n this.x = x;\n }\n}\n\nclass Second extends First {\n set x(d) {\n this.x = d;\n }\n get x() {\n return this.x;\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252986,"cells":{"blob_id":{"kind":"string","value":"2a153cad7072d88d74be39a987981f970f5d9185"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"trentclainor/ready"},"path":{"kind":"string","value":"/ready.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":445,"string":"445"},"score":{"kind":"number","value":2.6875,"string":"2.6875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"var ready = function(f) {\n\tif (!ready.r) ready.r = [];\n\tif (!ready.t) ready.t = null;\n\tready.r.push(f);\n\tvar run = function() {\n\t\tclearTimeout(ready.t);\n\t\twhile (ready.r.length)\n\t\t\tready.r.splice(0,1)[0]();\n\t}\n\tvar check = function() {\n\t\tif (document && document.getElementsByTagName && document.getElementById && document.body) {\n\t\t\trun();\n\t\t} else {\n\t\t\tready.t = setTimeout(check, 13);\n\t\t}\n\t}\n\tif (ready.t == null)\n\t\tcheck();\n\treturn ready;\n};"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252987,"cells":{"blob_id":{"kind":"string","value":"750891761ab63ef41e44acb1fc86bd39571c517e"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"kilic/relais"},"path":{"kind":"string","value":"/test/helpers/dateHelper.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":297,"string":"297"},"score":{"kind":"number","value":2.953125,"string":"2.953125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"const DAY = 86400\n\nfunction now() {\n return Math.round(new Date().getTime()/1000)\n}\n\nfunction yesterday() {\n return Math.round(new Date().getTime()/1000) - DAY\n}\n\nfunction daysAhead(days) {\n return Math.round(new Date().getTime()/1000) + DAY*days\n}\n\nmodule.exports = {now,yesterday,daysAhead}\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252988,"cells":{"blob_id":{"kind":"string","value":"2b0c7e07630e3a9fd14bea65881532d012347fe8"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"Barry-B15/weather-app"},"path":{"kind":"string","value":"/public/js/app.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1945,"string":"1,945"},"score":{"kind":"number","value":3.21875,"string":"3.21875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"//11 p5.js uses a set up func, create one and move all code inside it\nfunction setup() {\n noCanvas(); //11.2 we do not need a canvas for this project\n const video = createCapture(VIDEO); //11.3 we need videocam instead\n video.size(300, 240); // resize the video\n\n //8.1 def the lat lon\n let lat, lon;\n\n //def the btn and add click listener\n const button = document.getElementById('submit');\n button.addEventListener('click', async event => {\n const status = document.getElementById('status').value;\n\n //11.4 def a const to hold the image\n video.loadPixels(); //1st tell video to load pixels\n const img64 = video.canvas.toDataURL();\n\n const data = {\n lat,\n lon,\n status,\n img64 // 11.5 add the new image to data set\n };\n const options = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(data)\n };\n const response = await fetch('api', options);\n const json = await response.json();\n console.log(json);\n });\n\n //take data (geolocation) from client\n if ('geolocation' in navigator) {\n console.log('geolocation available');\n\n //get current position\n navigator.geolocation.getCurrentPosition(async position => {\n //def lat lon and get the coords\n\n lat = position.coords.latitude;\n lon = position.coords.longitude;\n document.getElementById('latitude').textContent = lat;\n document.getElementById('longitude').textContent = lon;\n console.log(position); //console log the pos\n });\n } else {\n console.log('geolocation not available'); // if geolocation is not available\n }\n //11.1 test to see a canvas created by adding p5.js\n //background(255, 0, 0); // we will not use it, so remove\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252989,"cells":{"blob_id":{"kind":"string","value":"9408741a7bfa41dc8c5ca75f6aeab0e313c7efbb"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"lfgg/lfgg.github.io"},"path":{"kind":"string","value":"/assets/js/lfgg.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4482,"string":"4,482"},"score":{"kind":"number","value":2.515625,"string":"2.515625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"const Nav = {\n elems: {\n toggle: document.querySelector('#toggle-nav'),\n site: document.querySelector('#site')\n },\n\n isOpen: false,\n\n toggle: function() {\n document.documentElement.classList.toggle('nav-open');\n this.isOpen = !this.isOpen;\n },\n\n open: function() {\n document.documentElement.classList.add('nav-open');\n this.isOpen = true;\n },\n\n close: function() {\n document.documentElement.classList.remove('nav-open');\n this.isOpen = false;\n },\n\n init: function() {\n this.elems.toggle.addEventListener('click', (e) => {\n e.preventDefault();\n this.toggle();\n });\n\n window.addEventListener('resize', (e) => {\n this.close();\n });\n\n this.elems.site.addEventListener('click', (e) => {\n if (this.isOpen) {\n this.close();\n }\n });\n }\n}\nNav.init();\n\n\nconst PostFilters = {\n elems: {\n filters: null,\n clearFilters: null\n },\n\n shuffleInstance = null,\n\n init: function() {\n var Shuffle = window.Shuffle;\n var shuffleWrap = document.querySelector('.c-filter-posts');\n\n this.elems.filters = document.querySelectorAll('.js-filter');\n this.elems.clearFilters = document.querySelector('.js-clear-filters');\n\n if (this.elems.filters && this.elems.clearFilters) {\n this.shuffleInstance = new Shuffle(shuffleWrap, {\n itemSelector: '.c-card'\n });\n\n this.elems.filters.forEach((filter) => {\n filter.addEventListener('click', (e) => {\n e.preventDefault();\n\n this.elems.filters.forEach((filter) => {\n filter.classList.remove('is-active');\n });\n filter.classList.add('is-active');\n\n let cat = filter.getAttribute('data-category');\n this.shuffleInstance.filter(cat);\n\n // Show clear filters btn\n this.elems.clearFilters.classList.add('is-visible');\n });\n });\n\n this.elems.clearFilters.addEventListener('click', (e) => {\n e.preventDefault();\n\n this.elems.filters.forEach((filter) => {\n filter.classList.remove('is-active');\n });\n\n // Show all items\n this.shuffleInstance.filter();\n\n // Hide clear filters btn\n this.elems.clearFilters.classList.remove('is-visible');\n });\n }\n }\n}\nPostFilters.init();\n\n\nconst LazyLoadHandler = {\n lazyLoad: null,\n\n init: function() {\n this.lazyLoad = new LazyLoad({\n elements_selector: '.lazy'\n });\n }\n}\nLazyLoadHandler.init();\n\n\nconst Page = {\n elems: {\n loader: document.querySelector('#loader')\n },\n\n init: function() {\n const swup = new Swup({\n elements: ['#page-main'],\n animationSelector: '[class*=\"u-transition-\"]'\n });\n\n swup.on('animationOutStart', () => {\n // Hide mobile menu\n Nav.close();\n\n let newLoader = this.elems.loader.cloneNode(true);\n this.elems.loader.parentNode.replaceChild(newLoader, this.elems.loader);\n this.elems.loader = newLoader;\n });\n\n swup.on('contentReplaced', () => {\n let lazyImgs = document.querySelectorAll('.lazy');\n lazyImgs.forEach((el) => {\n el.classList.remove('loaded');\n el.classList.remove('initial');\n el.classList.remove('loading');\n el.setAttribute('data-was-processed', '');\n });\n });\n\n swup.on('animationInDone', () => {\n LazyLoadHandler.init();\n PostFilters.init();\n });\n\n // Back button \n swup.on('popState', () => {\n setTimeout(function() {\n let lazyImgs = document.querySelectorAll('.lazy');\n lazyImgs.forEach((el) => {\n el.classList.add('loaded');\n });\n\n PostFilters.init();\n }, 100);\n });\n\n window.addEventListener('load', () => {\n setTimeout(() => {\n document.documentElement.classList.remove('is-animating', 'is-preload');\n }, 500);\n });\n }\n}\nPage.init();"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252990,"cells":{"blob_id":{"kind":"string","value":"a0979c3e92c4efa06b7f8cc9d71f98b1aeaf5052"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"emanuelecaruso/InteractiveGraphics"},"path":{"kind":"string","value":"/models/robot.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1162,"string":"1,162"},"score":{"kind":"number","value":3.359375,"string":"3.359375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"\t// call the render function\r\n\tvar step = 0;\r\n\r\n\t// once everything is loaded, we run our Three.js stuff.\r\n\tvar keyboard\t= new THREEx.KeyboardState();\r\n\t\r\n\tvar velocity=0;\r\n\tvar maxvelocity= 3.5;\r\n\tvar robotScale=2;\r\n\t\r\n\t// create meshes\r\n\tvar sphere = createMesh(new THREE.SphereGeometry(robotScale, 10, 10));\r\n\tsphere.position.set(0,-2,0);\r\n\tvar neck = createMesh(new THREE.CylinderGeometry(0.1*robotScale,0.1*robotScale,2,7*robotScale))\r\n\tneck.position.set(0,0,0);\r\n\r\n\tvar robot = new THREE.Group();\r\n\trobot.add( neck );\r\n\trobot.add( sphere );\r\n\t\r\n\t// add the sphere to the scene\r\n\r\n\r\n\tscene.add(robot);\r\n\t\r\n\tneck.add(sphere);\r\n\r\n\t//render();\r\n\r\n\tfunction moveRobot() {\r\n\r\n\t\tif(keyboard.pressed(\"D\"))\r\n\t\t{\r\n\t\t\tif (velocity-maxvelocity)\r\n\t\t\t\tvelocity -= 0.1;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tif (Math.abs(velocity)>0.01)\r\n\t\t\t\tvelocity = velocity/1.1;\r\n\t\t\telse\r\n\t\t\t\tvelocity = 0;\r\n\t\t}\r\n\t\t\r\n\t\tsphere.rotation.z = step -= 0.05*velocity;\r\n\t\tvar axis = new THREE.Vector3(neck.position.x+(velocity),neck.position.y,0);\r\n\t\tneck.translateOnAxis(neck.worldToLocal(axis),0.05); \r\n\r\n\t}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252991,"cells":{"blob_id":{"kind":"string","value":"56a302179fcdff7643d9280f10300c5731cb870b"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"randelreiss/tutorial"},"path":{"kind":"string","value":"/server.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2053,"string":"2,053"},"score":{"kind":"number","value":3.21875,"string":"3.21875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"// An HTTP server with a callback function\n// that is called for each request.\n// In the callback function, you create a response\n// with a status code of 200 (indicating that the request\n// was fulfilled successfully) and the message \"Hello World\".\n// Finally, you specify which port the server listens to.\n// When Node.js projects run within Cloud 9 IDE,\n// you can retrieve the port information with process.env.PORT\n\nvar appName = String(\"Randel's Tutorial\");\nvar appVersion = String(\"0.0\");\nvar appCopyright = String(\"2011, ALL RIGHTS RESERVED\");\n\n// Name of the module for the name of the local variable\nvar localHTTP = require('http');\nvar localURL = require(\"url\");\n\n// Extend server's start() function to pass the route function \nfunction start(route) {\n function onRequest(req, res) {\n // server code\n console.log(\"Request Received\");\n\n var pathname = localURL.parse(req.url).pathname;\n console.log(\"Request for \" + pathname + \" received.\");\n \n route(pathname);\n\n switch (pathname) {\n case '/':\n\n res.writeHead(200, {'Content-Type': 'text/plain'});\n appId(res);\n res.end('res.end\\n');\n break;\n\n default:\n fourZeroFour(res);\n\n }\n }\n\n var server = localHTTP.createServer(onRequest);\n\n if (process.env.PORT === undefined) {\n console.log('Running locally; browse to http://localhost:8888/\\n');\n server.listen(8888, '127.0.0.1');\n } else { // Running on c9.io.\n server.listen(process.env.PORT, '0.0.0.0');\n console.log(\"Server has started.\");\n console.log(\"Listning on port: \" + process.env.PORT);\n }\n}\n\n// Export this function\nexports.start = start;\n\nfunction appId(res) {\n res.write(\"Welcome to \" + appName + \"\\n\");\n res.write(\"Version: \" + appVersion + \"\\n\");\n res.write(\"Copyright \" + appCopyright + \"\\n\");\n}\n\nfunction fourZeroFour(res) {\n res.writehead(404);\n res.write(\"Yeah, baby, where saying: 404 Not found./n\");\n res.end(\"res.end\\n\");\n}\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252992,"cells":{"blob_id":{"kind":"string","value":"a7cf65f08ff2edda69765a825adf1d7e37e1eeb9"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"hello-chenchen/leet-code-algorithms"},"path":{"kind":"string","value":"/linked-list/leetcode-1290/solution.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":533,"string":"533"},"score":{"kind":"number","value":3.609375,"string":"3.609375"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":["WTFPL"],"string":"[\n \"WTFPL\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"/**\r\n * Definition for singly-linked list.\r\n * function ListNode(val, next) {\r\n * this.val = (val===undefined ? 0 : val)\r\n * this.next = (next===undefined ? null : next)\r\n * }\r\n */\r\n/**\r\n * @param {ListNode} head\r\n * @return {number}\r\n */\r\nvar getDecimalValue = function(head) {\r\n let result = 0;\r\n while(undefined != head) {\r\n if(1 == head.val) {\r\n result = (result << 1) + 1;\r\n } else {\r\n result = result << 1;\r\n }\r\n head = head.next;\r\n }\r\n\r\n return result;\r\n};"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252993,"cells":{"blob_id":{"kind":"string","value":"8408842bca2a527b063d125b1b1aa14afe8e38ff"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"Foorkan14/functions"},"path":{"kind":"string","value":"/arrowfunctions/arrowfunctions.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2281,"string":"2,281"},"score":{"kind":"number","value":4.96875,"string":"4.96875"},"int_score":{"kind":"number","value":5,"string":"5"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"//alternative way of writingfunctions\n//dont have to wrte functinn keyword all you have to do is this:\n\n\n//example 1 a function expression without arrow format\n\n// const square = function(x){ //x is what will be passed through as the argument\n// return x * x; \n// }\n\n// //now same function as arrow function\n// const square = (x) => {\n// return x * x;\n// }\n\n//really only difference is that we dont write function key word\n//they also behave differently when it comes to the keyword this\n\n\n\n//example 2 \n\nconst isEven = (num) =>{\n return num % 2 === 0;\n}\nconsole.log(isEven(4)); //will return true\n\n//example 3\n\nconst multiply = (x, y) =>{\n return(x * y);\n}\n\n\n//2 rules for arrow functions \n\n//rule 1 parenthesis are optioma if there is only one parameter\nconst square = x =>{\n return x * x;\n}\n\n\n//rule number 2 you can use empty parenthesis for functions with no parameters;\n\nconst singAsong = () => {\n return \"LA LA LA LA LA LA \";\n}\n\n//ARROW FUNCTIONS WITH IMPLICIT RETURN STATEMENTS\n\n//WORKS IN CERTAIN SCENARIOS\n\n//MEANS YOU DONT HAVE TO WRITE RETURN STATEMENT ITSELF\n\n//EXAMPLE 1\n\n// const square = n => {\n// return n * n;\n// }\n\n//consists of a single expression that we are returning,we arent doing any other logic first, we arent using a conditional , we arent making a variable we are simply returning a expression\n//in scenarios where we are returning a expressuon we can rewrite the function with parenthesis instead of curly brackets\n\nconst square = n => (\n n * n\n)\n\n//we can even leave out the parenthesis and do everything in one line\n\nconst square = n => n * n\n\n\n//with arrays\n\n//example 1 without arrow function\n\nconst nums = [1, 2, 3, 4, 5, 6, 7, 8];\n\nconst doubles1 = nums.map(function(n){\n return n * 2;\n})\n\n//now use arrow function\n\nconst doubles2 = nums.map(n =>{\n return n *2\n})\n\n//since we have single expression in this case n we can rewrite the function with parenthesis instead\n\nconst doubles3 = nums.map(n => n * 2);\n\n\n\n// example 2 \n\n\nconst parodyList = nums.map(function(n){\n if (n%2 ===0){\n return even;\n }else{\n return odd;\n }\n})\n\n//now same function as arrow function\n\nconst parodyList = nums.map(n =>{\n if (n%2 === 0){\n return 'even'; \n } else{\n return 'odd';\n }\n})\n\n\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252994,"cells":{"blob_id":{"kind":"string","value":"691b21d0172e688d2f603554b8815b14d4b11e6a"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"MidoriyaDeku/algorithm"},"path":{"kind":"string","value":"/search/binary_search_tree.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":6203,"string":"6,203"},"score":{"kind":"number","value":3.796875,"string":"3.796875"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"// 二叉查找树结构\r\nfunction BSTree(data, left, right, parent) {\r\n this.data = data;\r\n this.left = left;\r\n this.right = right;\r\n this.parent = parent;\r\n}\r\n\r\n// 二叉查找树的插入操作\r\n// bstree 查找树;data 要插入的数;\r\nfunction insertBST(bstree, data) {\r\n var current = bstree; // 当前节点\r\n var parent = null; // 父节点\r\n while (true) {\r\n parent = current; // 当前为父节点\r\n \r\n // 要插入的数据 小于当前节点的数据\r\n if (data < current.data) {\r\n current = current.left; // 当前节点为左节点\r\n if (current === null) { // 如果当前节点为空直接插入这个节点\r\n parent.left = new BSTree(data, null, null, parent);\r\n break;\r\n }\r\n }\r\n else { // 大于等于当前节点的数走这里\r\n current = current.right; // 当前节点为左节点\r\n if (current === null) { // 如果当前节点为空直接插入这个节点\r\n parent.right = new BSTree(data, null, null, parent);\r\n break;\r\n }\r\n }\r\n }\r\n}\r\n\r\n// 创建二叉查找树\r\n// list 要创建的数据表\r\nfunction createBST(list) {\r\n // 构建BST中的根节点\r\n var bstree = new BSTree(list[0], null, null, null);\r\n\r\n for (var i = 1; i < list.length; ++i) {\r\n insertBST(bstree, list[i]);\r\n }\r\n\r\n return bstree;\r\n}\r\n\r\n// 在二叉查找树中搜索指定节点的数据\r\n// bstree 查找树;data 要在树中查找的数\r\nfunction searchBST(bstree, data) {\r\n // 如果bstree为空,说明已经遍历到头了\r\n if (bstree === null) {\r\n return false;\r\n }\r\n\r\n // 找到了\r\n if (bstree.data === data) {\r\n return true;\r\n }\r\n\r\n if (data < bstree.data) {\r\n return searchBST(bstree.left, data);\r\n }\r\n else {\r\n return searchBST(bstree.right, data);\r\n }\r\n}\r\n\r\n// 先序遍历二叉查找树\r\n// bstree 查找树\r\nfunction dlrBST(bstree) {\r\n if (bstree != null)\r\n {\r\n // 输出节点数据\r\n console.log(bstree.data + \"\");\r\n\r\n // 遍历左子树\r\n dlrBST(bstree.left);\r\n\r\n // 遍历右子树\r\n dlrBST(bstree.right);\r\n }\r\n}\r\n\r\n// 中序遍历二叉查找树\r\n// bstree 查找树\r\nfunction ldrBST(bstree) {\r\n if (bstree != null)\r\n {\r\n // 遍历左子树\r\n ldrBST(bstree.left);\r\n\r\n // 输出节点数据\r\n console.log(bstree.data + \"\");\r\n\r\n // 遍历右子树\r\n ldrBST(bstree.right);\r\n }\r\n}\r\n\r\n// 后序遍历二叉查找树\r\n// bstree 查找树\r\nfunction lrdBST(bstree) {\r\n if (bstree != null)\r\n {\r\n // 遍历左子树\r\n lrdBST(bstree.left);\r\n\r\n // 遍历右子树\r\n lrdBST(bstree.right);\r\n\r\n // 输出节点数据\r\n console.log(bstree.data + \"\");\r\n }\r\n}\r\n\r\n// 删除二叉排序树中指定key节点\r\n// bstree 查找树;key 要删除的key节点\r\nfunction deleteBST(bstree, data) {\r\n if (bstree === null) {\r\n return;\r\n }\r\n\r\n if (bstree.data === data) {\r\n // 第一种情况:叶子节点\r\n if (bstree.left === null && bstree.right === null) {\r\n if (bstree.data < bstree.parent.data) {\r\n bstree.parent.left = null;\r\n }\r\n else {\r\n bstree.parent.right = null;\r\n }\r\n delete bstree;\r\n bstree = null;\r\n return;\r\n }\r\n // 第二种情况:左子树不为空\r\n if (bstree.left !== null && bstree.right === null) {\r\n if (bstree.left.data < bstree.parent.data) {\r\n bstree.parent.left = bstree.left;\r\n }\r\n else {\r\n bstree.parent.right = bstree.left;\r\n }\r\n delete bstree;\r\n bstree = null;\r\n return;\r\n }\r\n // 第三种情况,右子树不为空\r\n if (bstree.left === null && bstree.right !== null) {\r\n if (bstree.right.data < bstree.parent.data) {\r\n bstree.parent.left = bstree.right;\r\n }\r\n else {\r\n bstree.parent.right = bstree.right;\r\n }\r\n delete bstree;\r\n bstree = null;\r\n return;\r\n }\r\n // 第四种情况,左右子树都不为空\r\n if (bstree.left !== null && bstree.right !== null) {\r\n var node = bstree.right; // 被删除节点的右孩子\r\n \r\n //找到右子树中的最左节点\r\n while (node.left !== null) {\r\n node = node.left; // 遍历它的左子树\r\n }\r\n // 替换掉要删除的节点的数据(将要删除节点的右子树的最左节点的数据给它)\r\n bstree.data = node.data;\r\n\r\n // 删除节点的右节点没有左节点的时候。即上边的while循环没执行。\r\n if (node.parent.right === node) {\r\n bstree.right = node.right;\r\n }\r\n else {\r\n // 删除节点的右节点有左节点的时候。\r\n if (node.parent.left === node) {\r\n node.parent.left = node.right;\r\n }\r\n }\r\n node = null; // 将换位到删除节点去的右子树的最左子树赋值为空。\r\n return;\r\n }\r\n }\r\n /*\r\n 60\r\n 30 80\r\n 10 35 70 120\r\n 20 90\r\n */\r\n\r\n if (data < bstree.data) {\r\n deleteBST(bstree.left, data);\r\n }\r\n else {\r\n deleteBST(bstree.right, data);\r\n }\r\n}\r\n\r\nvar list = [60, 30, 80, 10, 120, 90, 70, 20, 35];\r\nvar data = 20;\r\nvar bstree = createBST(list);\r\nconsole.log(\"-----中序遍历-----\");\r\nldrBST(bstree);\r\nconsole.log(\"-----中序遍历-----\");\r\n\r\n/*var is_include = searchBST(bstree, data);\r\nconsole.log(data, \"是否包含在二叉树中: \", is_include);*/\r\n\r\n/*var del_value = 60;\r\ndeleteBST(bstree, del_value);\r\nconsole.log(\"删除二叉树中的\", del_value);\r\nconsole.log(\"-----中序遍历-----\");\r\nldrBST(bstree);\r\nconsole.log(\"-----中序遍历-----\");*/"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252995,"cells":{"blob_id":{"kind":"string","value":"094853d82b57829029a6b82a1ee651f176fe51eb"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"DevNeoLee/canadaTouristRefactor"},"path":{"kind":"string","value":"/src/main.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2198,"string":"2,198"},"score":{"kind":"number","value":3.046875,"string":"3.046875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"\n//load raw CSV, travel_province_data using D3.js\n//prepare only relavant data set array of objects\n//initiate putting minimized data cut with default or listened event input\nimport { putData } from './put_data.js';\n\nd3.csv('data/travel_province_data.csv', function(data) {\n const initialDataCut = [];\n data.forEach((ele) => {\n if ((ele.GEO == \"Newfoundland and Labrador\" ||\n ele.GEO == \"Prince Edward Island\" ||\n ele.GEO == \"Nova Scotia\" ||\n ele.GEO == \"New Brunswick\" ||\n ele.GEO == \"Quebec\" ||\n ele.GEO == \"Ontario\" ||\n ele.GEO == \"Manitoba\" ||\n ele.GEO == \"Saskatchewan\" ||\n ele.GEO == \"Alberta\" ||\n ele.GEO == \"British Columbia\" ||\n ele.GEO == \"Yukon\" ||\n ele.GEO == \"Nunavut\") &&\n (ele['Traveller characteristics'] == \"Total non resident tourists\") &&\n (ele['Seasonal adjustment'] == \"Unadjusted\") &&\n (ele.REF_DATE[0] == '2'))\n {\n initialDataCut.push(ele);\n }\n });\n\n//eventListener for 'year' data input\n//send data to 'putData' method\ndocument.querySelector('.select').addEventListener(\"change\", function () { \n \n //firstly delete previous data \n d3.selectAll(\"svg\")\n .remove();\n \n //call putData method\n putData(initialDataCut, document.querySelector('.select').value, document.querySelector('.slider').value);\n});\n\nconst months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n\n//eventListner for 'month' data input\n//send dat to 'putData' method\ndocument.querySelector('.slider').addEventListener(\"change\", function () {\n const value = document.querySelector('.slider').value;\n document.querySelector('.monthDisplay').innerText = months[value - 1];\n \n //firstly delete previous data \n d3.selectAll(\"svg\")\n .remove();\n \n //call putData method\n putData(initialDataCut, document.querySelector('.select').value, value);\n});\n \n //call initial default drawing with default data \n putData(initialDataCut); \n});\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252996,"cells":{"blob_id":{"kind":"string","value":"b335a1e840e6accea9cc4c8f8c3c3cdaaa78059a"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"emddutton/diceroller"},"path":{"kind":"string","value":"/dice.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1905,"string":"1,905"},"score":{"kind":"number","value":2.921875,"string":"2.921875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"/**\n * Created by emddutton on 3/4/2015.\n */\n$(document).ready(function(){\n\n function reset() {\n $(\".dice\").removeClass('animated shake');\n $(\".dots\").hide();\n console.log('bye');\n }\n\n function roll(side) {\n var one = (side + \".centerdot\");\n var two = (side + '.rightcorner');\n var three = (side + '.leftcorner');\n var four = (side + '.rightbottom');\n var five = (side + '.leftbottom');\n var six = (side + '.sideright');\n var seven = (side + '.sideleft');\n\n\n var diceroll = Math.floor(Math.random() * 6 + 1);\n if (diceroll == 1) {\n $(one).show();\n console.log('one');\n }\n else if (diceroll == 2) {\n $(three).show();\n $(four).show();\n console.log('two');\n }\n else if (diceroll == 3) {\n $(one).show();\n $(three).show();\n $(four).show();\n console.log('three');\n }\n else if (diceroll == 4) {\n $(two).show();\n $(three).show();\n $(four).show();\n $(five).show();\n console.log('four');\n }\n else if (diceroll == 5) {\n $(one).show();\n $(two).show();\n $(three).show();\n $(four).show();\n $(five).show();\n console.log('five');\n }\n else if (diceroll == 6) {\n $(two).show();\n $(three).show();\n $(four).show();\n $(five).show();\n $(six).show();\n $(seven).show();\n console.log('six');\n }\n return diceroll;\n }\n\n\n $('button').on('click', function() {\n reset();\n $(\".dice\").addClass('animated shake');\n setTimeout(function() {\n roll(\".left\");\n roll(\".right\");\n }, 1000);\n });\n\n });\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252997,"cells":{"blob_id":{"kind":"string","value":"a6a67b75e4ea0a0b45b7d2d729f2f7819fa9b47b"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"DN8630/lotide"},"path":{"kind":"string","value":"/middle.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":488,"string":"488"},"score":{"kind":"number","value":2.984375,"string":"2.984375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"const eqArray = require(\"./eqArrays\");\nconst assertArrayEqual = require(\"./assertArraysEqual\");\n\nconst middle = function(array) {\n let output = [];\n let arrLength = array.length;\n let index = parseInt((arrLength - 1) / 2);\n if (arrLength <= 2) {\n return output;\n } else if (arrLength % 2 === 0) {\n output.push(array[index]);\n output.push(array[index + 1]);\n } else if (arrLength % 2 !== 0) {\n output.push(array[index]);\n }\n return output;\n};\nmodule.exports = middle;\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252998,"cells":{"blob_id":{"kind":"string","value":"ab75d251fbfa638c2616aa8b5c20d5a6ae77610e"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"MikeHitrov/SoftUni"},"path":{"kind":"string","value":"/JS Advanced/Exam 19.12.2016/01. Move Towns Up Down (Simple DOM Interaction)/move-up-down.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":301,"string":"301"},"score":{"kind":"number","value":2.765625,"string":"2.765625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"function move(num) {\n let selected = $('#towns :selected');\n let action = num > 0 ? moveDown : moveUp;\n action(selected);\n\n function moveUp(option) {\n $(option).insertBefore(option.prev());\n }\n\n function moveDown(option) {\n $(option).insertAfter(option.next());\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":13252999,"cells":{"blob_id":{"kind":"string","value":"bce8e5b32ba8fc7e213571ca2bc356b43654e8a9"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"hello-kozloff/fodesign"},"path":{"kind":"string","value":"/src/blocks/_parts/navigation/navigation.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":460,"string":"460"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"$(document).ready(() => {\n $(\".navigation\").on('click', function(event) {\n if (event.target !== this) return;\n\n hideNavigationPanel();\n });\n\n $(\".navigation__button\").on(\"click\", function (event) {\n event.preventDefault();\n hideNavigationPanel();\n });\n});\n\nfunction hideNavigationPanel() {\n const _navigation = $(\".navigation\");\n _navigation.toggleClass(\"navigation_hidden\");\n\n $(\"body\").removeClass(\"fixed\");\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":132529,"numItemsPerPage":100,"numTotalItems":13253430,"offset":13252900,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjUxODc1MSwic3ViIjoiL2RhdGFzZXRzL2hvbmdsaXU5OTAzL3N0YWNrX2VkdV9qYXZhc2NyaXB0IiwiZXhwIjoxNzU2NTIyMzUxLCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.PCeWGTyVToL48DOAUGU72FdzNBrjpYozpg_NxGALYAjZW4zjSYug_90x26UmKh7hZNz1e8pA3mSCpG0NBAfPCQ","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
3
236
src_encoding
stringclasses
29 values
length_bytes
int64
8
7.94M
score
float64
2.52
5.72
int_score
int64
3
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
8
7.94M
download_success
bool
1 class
35f7e151898cc098ecd3d5b14b20b8a4fb3b9d27
JavaScript
colleencleary/weirdworld
/public/js/Comments.js
UTF-8
3,714
3.0625
3
[]
no_license
class Comments extends React.Component { constructor(props){ super(props) this.state = { commentListIsVisible: true, addCommentIsVisible: false, commentIsVisible: false, editCommentIsVisible: false, comments: [], comment: {} } this.toggleState = this.toggleState.bind(this) this.getComments = this.getComments.bind(this) this.deleteComment = this.deleteComment.bind(this) this.updateComment = this.updateComment.bind(this) this.handleCreate = this.handleCreate.bind(this) this.handleCreateSubmit = this.handleCreateSubmit.bind(this) } //Did Mount componentDidMount(){ this.getComments(); } //DELETE deleteComment(comment, index){ //console.log('DELETE'); fetch('/comments/' + comment.id, { method: 'DELETE' }) .then(data => { this.setState({ comments: [ ...this.state.comments.slice(0, index), ...this.state.comments.slice(index + 1) ] }) }) } //Handle Create handleCreate(comment){ console.log('handle create'); console.log([comment, ...this.state.comments]) this.setState({comments:[comment, ...this.state.comments]}) } //Handle Create Submit handleCreateSubmit(comment){ console.log('Create Submit Handled'); fetch('/comments', { body: JSON.stringify(comment), method: 'POST', headers: { 'Accept':'application/json, text/plain, */*', 'Content-Type': 'application/json' } }) .then(createdComment => { return createdComment.json() }) .then(jsonComment => { this.handleCreate(jsonComment) this.toggleState('addCommentIsVisible', 'commentListIsVisible') }).catch(error => console.log(error)) } //Handle Update Submit updateComment(comment){ console.log('Update Submit Handled'); fetch('/comments/'+ comment.id, { body: JSON.stringify(comment), method: 'PUT', headers: { 'Accept' : 'applications/json, text/plain, */*', 'Content-Type': 'application/json' } }) .then(updatedComment =>{ return updatedComment.json() }) .then(jsonComment => { this.getComment() this.toggleState('commentListIsVisible', 'commentIsVisible') }) .catch(error => console.log(error)) } //GET ONE getComment(comment){ this.setState({ comment: comment }) } //Get ALL getComments(){ fetch('/comments') .then(response => response.json()) .then(data => { this.setState({ comments: data }) }).catch(error => console.log(error)) } //toggleState toggleState(state1, state2){ this.setState({ [state1]: !this.state[state1], [state2]: !this.state[state2] }) } render(){ //console.log('^^^^^',this.state.comments); return ( <div> <h2> comments </h2> { this.state.commentListIsVisible ? <button onClick={()=>this.toggleState("addcommentIsVisible", "commentListIsVisible")} >Add a comment</button> : '' } <CommentList toggleState={this.toggleState} comments={this.state.comments} getComment={this.getComment} deleteComment={this.deleteComment} /> <CommentForm toggleState={this.toggleState} handleCreate = {this.handleCreate} handleSubmit = {this.handleCreateSubmit} /> <Comment toggleState={this.toggleState} comment={this.state.comment} handleSubmit = {this.handleUpdateSubmit} /> </div> ) } }
true
918909a0709cd5be8caa013799fa2909bad1e441
JavaScript
joedevgee/cms-hitech-apd
/api/routes/states/put.js
UTF-8
3,878
2.53125
3
[ "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
const logger = require('../../logger')('states route put'); const joi = require('joi'); const pick = require('lodash.pick'); const { loggedIn } = require('../../middleware'); const defaultDataHelper = require('./data'); module.exports = (app, dataHelper = defaultDataHelper) => { const { getFields, putFields, getStateFromUserOrID } = dataHelper; const medicaidOfficeSchema = joi.object().keys({ address1: joi.string().required(), address2: joi.string(), city: joi.string().required(), state: joi.string().required(), zip: joi.string().required(), director: joi.object().keys({ name: joi.string().required(), phone: joi.string().required(), email: joi .string() .email() .required() }) }); const pocSchema = joi.array().items( joi.object().keys({ name: joi.string().required(), email: joi .string() .email() .required(), position: joi.string().required() }) ); const put = async (req, res) => { logger.silly(req, 'handling PUT /states route'); try { const state = await getStateFromUserOrID(req.params.id, req.user.id); // If there's not a state, then it couldn't be found. if (!state) { logger.verbose(req, `no such state [${req.params.id}]`); return res.status(404).end(); } // If there is a state but it doesn't have an ID, then // we got it from a user relationship. For whatever reason, // bookshelf gives us a model with no data rather than no // object. 🤷‍♂️ if (!state.get('id')) { logger.verbose(req, 'user does not have an associated state'); return res.status(401).end(); } // Hang on to this. The state model will only have the updated // fields after we save it, so this is a shortcut for sending // back the whole object. const oldData = state.pick(getFields); logger.silly(req, 'picking out just updateable fields'); const newData = pick(req.body, putFields); logger.silly(req, newData); logger.silly(req, 'validating program benefits'); if ( joi .string() .allow('') .validate(newData.program_benefits).error ) { logger.verbose(req, 'invalid program benefits'); return res .status(400) .send({ error: 'edit-state-invalid-benefits' }) .end(); } logger.silly(req, 'validating program vision'); if ( joi .string() .allow('') .validate(newData.program_vision).error ) { logger.verbose(req, 'invalid program vision'); return res .status(400) .send({ error: 'edit-state-invalid-vision' }) .end(); } logger.silly(req, 'validating state Medicaid office address'); if (medicaidOfficeSchema.validate(newData.medicaid_office).error) { logger.verbose(req, 'invalid Medicaid office'); return res .status(400) .send({ error: 'edit-state-invalid-medicaid-office' }) .end(); } logger.silly(req, 'validating state Medicaid points of contact'); if (pocSchema.validate(newData.state_pocs).error) { logger.verbose(req, 'invalid points of contact'); return res .status(400) .send({ error: 'edit-state-invalid-state-pocs' }) .end(); } state.set(newData); await state.save(); // Overwrite the old data with the new, and we will have what now // exists in the database. Good job, team! return res.send({ ...oldData, ...newData }); } catch (e) { logger.error(req, e); return res.status(500).end(); } }; logger.silly('setting up PUT /states route'); app.put('/states', loggedIn, put); };
true
114c072180fb29f7cbcb5e8ed21df40ab04396a7
JavaScript
jodonnell/AnnoTATE
/line.js
UTF-8
429
2.859375
3
[]
no_license
var Line = Class.extend({ init: function(point) { this.points = []; if (point) this.addPoint(point); }, load: function(points) { this.points = points; }, addPoint: function(point) { this.points.push(point); }, explodePoints: function() { var points = []; for (var i = 0; i < this.points.length; i++) { points.push([this.points[i].x, this.points[i].y]); } return points; } });
true
b996b08524ea4d6d74c8ef7276af4209ebed5a24
JavaScript
adriennedomingus/travel_map_blog
/app/assets/javascripts/view_selectors.js
UTF-8
1,808
2.59375
3
[]
no_license
function setCSS(controlDiv, map, text) { var controlUI = document.createElement('div'); controlUI.style.backgroundColor = '#fff'; controlUI.style.border = '2px solid grey'; controlUI.style.borderRadius = '3px'; controlUI.style.cursor = 'pointer'; controlUI.style.marginBottom = '22px'; controlUI.style.textAlign = 'center'; controlDiv.appendChild(controlUI); var controlText = document.createElement('div'); controlText.style.color = 'rgb(25,25,25)'; controlText.style.fontSize = '16px'; controlText.style.lineHeight = '38px'; controlText.style.paddingLeft = '5px'; controlText.style.paddingRight = '5px'; controlText.innerHTML = text; controlUI.appendChild(controlText); return controlUI; } function setMapOnAllBlog(map) { for (var i = 0; i < blogMarkers.length; i++) { blogMarkers[i].setMap(map); } } function setMapOnAllPhoto(map) { for (var i = 0; i < photoMarkers.length; i++) { photoMarkers[i].setMap(map); } } function clearBlogMarkers() { setMapOnAllBlog(null); } function clearPhotoMarkers() { setMapOnAllPhoto(null); } function setViewButtons() { var photoBlogControlDiv = document.createElement('div'); var photoBlogControl = new PhotoBlogControl(photoBlogControlDiv, map); photoBlogControlDiv.index = 1; map.controls[google.maps.ControlPosition.TOP_CENTER].push(photoBlogControlDiv); var blogControlDiv = document.createElement('div'); var blogControl = new BlogControl(blogControlDiv, map); blogControlDiv.index = 1; map.controls[google.maps.ControlPosition.TOP_CENTER].push(blogControlDiv); var photoControlDiv = document.createElement('div'); var photoControl = new PhotoControl(photoControlDiv, map); photoControlDiv.index = 1; map.controls[google.maps.ControlPosition.TOP_CENTER].push(photoControlDiv); }
true
8034d6f1ebd67e52e2f3568f4178d26d055c0ca6
JavaScript
adamgarwacki/iskra-przewodnik
/assets/js/new-char.js
UTF-8
2,697
3.671875
4
[]
no_license
// new-char.js // let strInput = document.getElementById('char-str'); // if(strInput) { // console.log(strInput.value); // } // ponieważ jest jeden plik js (bundle.js), // muszę sprawdzać czy odnosi się do konkretnej // strony // tu będą przechowywane informacje o postaci let charData = { charName: '', charSpecies: '', charConcept: '', charAttributes: '', charAbilities: {}, charEquipment: {}, charHealth: '', charFocus: '', charNotes: '' }; console.log(charData); let changeAbilityScore = (targets) => { let sum = -3; for (const e of targets) { sum -= parseInt(e.value); }; let pointsLeft = document.getElementById('attr-points'); if (sum < 0) { pointsLeft.classList.add('glow-red'); } else { pointsLeft.classList.remove('glow-red'); } pointsLeft.innerText = sum; } // ability add / remove let removeAbility = (key) => { document.getElementById(key).remove(); } let addAbility = () => { let abilityName = document.getElementById('ability-name').value; let abilityDesc = document.getElementById('ability-desc').value; let key = Date.now(); charData.charAbilities[key] = { abilityName: abilityName, abilityDesc: abilityDesc } let abilityList = document.getElementById('ability-list'); let abilityContainer = document.createElement('div'); let abilityContainerName = document.createElement('h3'); let abilityContainerDesc = document.createElement('p'); let abilityContainerRemove = document.createElement('button'); abilityContainerName.innerText = abilityName; abilityContainerDesc.innerText = abilityDesc; abilityContainerRemove.innerText = 'Usuń'; abilityContainerRemove.classList.add('btn'); abilityContainerRemove.addEventListener('click', () => { removeAbility(key); }); abilityContainer.appendChild(abilityContainerName); abilityContainer.appendChild(abilityContainerDesc); abilityContainer.appendChild(abilityContainerRemove); abilityContainer.id = key; abilityContainer.classList.add('ability-container'); abilityList.appendChild(abilityContainer); console.log(charData); } let newCharForm = document.getElementById('new-char-form'); if (newCharForm != undefined) { // attributes let attrInputs = document.getElementsByClassName('attr-input'); for (const e of attrInputs) { e.addEventListener('change', () => changeAbilityScore(attrInputs)); }; changeAbilityScore(attrInputs); // abilities document.getElementById('add-ability').addEventListener('click', () => { addAbility(); }); }
true
da804f82c2ab59a5a1dd6b5a434660ab56cf25b2
JavaScript
alyzaw/BirthControlProject4
/static/js/predict.js
UTF-8
6,204
2.921875
3
[]
no_license
function makePredictions() { // Grab a reference to the dropdown select element var input1 = d3.select("#selDataset1").node().value; var input2 = d3.select("#selDataset2").node().value; var input3 = d3.select("#selDataset3").node().value; var input4 = d3.select("#selDataset4").node().value; var input5 = d3.select("#selDataset5").node().value; document.getElementById("pre-img").style.display = "none"; // var $image = $('#result-img'); // // var $text = $('#result-text'); // // console.log("toggling", $image); // $image.toggleClass('transparent'); // // $text.toggleClass('transparent'); d3.json(`/mlm/(${input1}, ${input2}, ${input3}, ${input4}, ${input5})`).then(data => { result = data.data; try { switch (result) { case "0": // document.getElementById("result-img"); img = document.getElementById("result-img"); img.style.display = "block"; img.src = "../static/css/surgical.png"; document.getElementById("result-text").innerText = "AI predicts: Surgical Sterilization"; break; case "1": document.getElementById("result-img"); img.style.display = "block"; img.src = "../static/css/iud_implant.png"; document.getElementById("result-text").innerText = "AI predicts: IUD or Implant"; break; case "2": img = document.getElementById("result-img"); img.style.display = "block"; img.src = "../static/css/ring_patch_shot_pill.png"; document.getElementById("result-text").innerText = "AI predicts: Pill, Ring, Patch, Shot"; break; case "3": document.getElementById("result-img"); img.style.display = "block"; img.src = "../static/css/condoms.png"; document.getElementById("result-text").innerText = "AI predicts: Condoms"; break; case "5": document.getElementById("result-img"); img.style.display = "block"; img.src = "../static/css/calender_withdrawal.png"; document.getElementById("result-text").innerText = "AI predicts: Withdrawal/Family Planning Techniques"; break; case "99": document.getElementById("result-img"); img.style.display = "block"; img.src = "../static/css/shrug.png"; document.getElementById("result-text").innerText = "Shoot, I dunno"; break; } } catch (err) { // document.getElementById("result-img").src ="../static/css/shrug"; // document.getElementById("result-text").innerText="Shoot, I dunno"; console.log(err); } // console.log("togglign agan") // setTimeout(() => $image.toggleClass('transparent'), 1000 ) // // setTimeout(() => $text.toggleClass('transparent'), 1000 ) }); } // function init(){ // document.getElementById("result-img").src ="../static/css/theVillain.jpg"; // document.getElementById("result-text").innerText="What will our AI predict???"; // }; // init(); // function makePredictions() { // // Grab a reference to the dropdown select element // var input1 = d3.select("#selDataset1").node().value; // var input2 = d3.select("#selDataset2").node().value; // var input3 = d3.select("#selDataset3").node().value; // var input4 = d3.select("#selDataset4").node().value; // document.getElementById("pre-img").style.display = "none"; // // var $image = $('#result-img'); // // // var $text = $('#result-text'); // // // console.log("toggling", $image); // // $image.toggleClass('transparent'); // // // $text.toggleClass('transparent'); // d3.json(`/mlm/(${input1}, ${input2}, ${input3}, ${input4})`).then(data => { // result = data.data; // try { // switch (result) { // case "0": // // document.getElementById("result-img"); // img = document.getElementById("result-img"); // img.style.display = "block"; // img.src = "../static/css/surgical.png"; // document.getElementById("result-text").innerText = // "Surgical Sterilization"; // break; // case "1": // document.getElementById("result-img").src = // "../static/css/iud_implant.png"; // document.getElementById("result-text").innerText = "IUD/Implant"; // break; // case "2": // img = document.getElementById("result-img"); // // img.style = "transition-duration: 2s"; // // img.style = "display: none"; // img.style.display = "block"; // img.src = "../static/css/ring_patch_shot_pill.png"; // document.getElementById("result-text").innerText = // "Pill/Ring/Patch/Shot"; // break; // case "3": // document.getElementById("result-img").src = // "../static/css/condoms.png"; // document.getElementById("result-text").innerText = "Condoms"; // break; // case "5": // document.getElementById("result-img").src = // "../static/css/calender_withdrawal.png"; // document.getElementById("result-text").innerText = // "Withdrawal/Calender"; // break; // case "99": // document.getElementById("result-img").src = "../static/css/shrug.png"; // document.getElementById("result-text").innerText = "Shoot, I dunno"; // break; // } // } catch (err) { // // document.getElementById("result-img").src ="../static/css/shrug"; // // document.getElementById("result-text").innerText="Shoot, I dunno"; // console.log(err); // } // console.log("togglign agan") // // setTimeout(() => $image.toggleClass('transparent'), 1000 ) // // // setTimeout(() => $text.toggleClass('transparent'), 1000 ) // }); // } // // function init(){ // // document.getElementById("result-img").src ="../static/css/theVillain.jpg"; // // document.getElementById("result-text").innerText="What will our AI predict???"; // // }; // // init();
true
2a1a671bd5d998914ab64b5cb0cfb75396b910f8
JavaScript
skywalkerFE/skywalker
/packages/components/notification/src/notification.js
UTF-8
1,715
2.546875
3
[]
no_license
import Vue from 'vue'; import Notification from './main.js'; const NotificationConstructor = Vue.extend(Notification) let instance; let instances = [] let seed = 1 const NotificationFun = function(options){ if (Vue.prototype.$isServer) return; options = options || {}; const userOnClose = options.onClose; const id = 'notification_' + seed++; const position = options.position || 'top-right'; options.onClose = function() { Notification.close(id, userOnClose) } instance = new NotificationConstructor({ data: options }) instance.id = id instance.$mount(); document.body.appendChild(instance.$el); instance.show = true let verticalOffset = 0 instances.filter(item => item.position === position).forEach(element => { verticalOffset += element.$el.offsetHeight + 16 }); verticalOffset += 16 instance.verticalOffset = verticalOffset instances.push(instance) console.log() return instance; } Notification.close = function(id, userOnClose) { let index = -1 const len = instances.length const instance = instances.filter((instance, i) => { if (instance.id === id) { index = i; return true; } return false; })[0] if (!instance) return if (typeof userOnClose === 'function') { userOnClose(instance); } instances.splice(index, 1) if (len <= 1) return const position = instance.position; const removedHeight = instance.$el.offsetHeight for (let i = index; i < len - 1; i++){ if (instances[i].position === position) { instances[i].$el.style[instance.verticalProperty] = parseInt(instances[i].$el.style[instance.verticalProperty], 10) - removedHeight - 16 + 'px' } } } export default NotificationFun
true
f442a891e8e3900bb7c4ebafa83232a65a4a0751
JavaScript
Sharfik69/Sharfik69.github.io
/src/my-script.js
UTF-8
3,617
2.546875
3
[]
no_license
$(function(){ var id = 0, check = false; $('.add-new-list').click(function() { $('.add-new-list').before( '<div class="new-list" id="' + id + '">' + '<p class="delete"> x </p> ' + '<input class="edit-name-column" type="text" placeholder="Введите название колонки">' + '<input id="add-column" class="button-add-card add-col" type="button" value="Добавить колонку">' + '<h2 class="name-column"> Введите название колонки </h2>' + '<div class="card" id="sortable' + id + '"> </div>' + '<div class="adding-field">' + '<textarea class="field-add-card" type="text" cols=39> </textarea>' + '<input class="button-add-card" type="button" value="Добавить карточку">' + '</div>' + '<p class="add-card-text"> Добавить карточку </p>' + '</div>' ); id++; $('.add-card-text').unbind("click").click(function(){ if (!check) { $('div[id=' + $(this).parent().attr('id') + ']').children('.adding-field').show(); $('div[id=' + $(this).parent().attr('id') + ']').children('.add-card-text').text('Скрыть поле ввода'); check = true; } else { $('div[id=' + $(this).parent().attr('id') + ']').children('.adding-field').hide(); $('div[id=' + $(this).parent().attr('id') + ']').children('.add-card-text').text('Добавить карточку'); check = false; } }); $('.button-add-card').unbind("click").click(function(){ var x = $(this).parent().parent().attr('id'); if (($('div[id=' + x +'] .field-add-card').val()).length == 0) { alert('Карточка пустая :('); } else { $('div[id=' + $(this).parent().parent().attr('id') + ']').children('.card').append( '<div class="card-element ui-state-default">' + '<p class="card-text" >' + $('div[id=' + x +'] .field-add-card').val() + '</p>' + '</div>' ); $('.field-add-card').val(''); } }); $('#add-column.button-add-card.add-col').unbind("click").click(function(){ var x = $(this).parent().attr('id'); $('div#' + x).children('.edit-name-column').hide(); $('div#' + x).children('#add-column').hide(); $('div#' + x).children('.name-column').show(); var new_name = $('div#' + x).children('.edit-name-column').val(); if (new_name == '') { $('div#' + x).children('.name-column').text('Новая колонка'); } else { $('div#' + x).children('.name-column').text(new_name); } $('div#' + x).children('.add-card-text').show(); }); $('.delete').unbind("click").click(function(){ var x = $('div[id=' + $(this).parent().attr('id') + ']').attr('id'); $('div[id=' + x + ']').remove(); }); for (var i = 0; i <= id; i++) { $("#sortable" + i).sortable({ connectWith: "div" }); $("#sortable" + i).disableSelection(); } }); });
true
846907bef243d4722e4a5539f69426287e1ec8b6
JavaScript
raged07/test
/www/js/platzom.js
UTF-8
2,291
4.46875
4
[]
no_license
//si la palabra termina en "ar", se le quitan los dos ultimos caracteres function platzom(str){ let translation = str; if (str.toLowerCase().endsWith('ar')){ translation = str.slice(0,-2);//corta la cadera, elimina los 2 ultimos caracteres } /*Si la palabra inicia con "z"se le anade los caracteres "pe" al final de la palabra*/ if (str.toLowerCase().startsWith('z')){ translation +='pe' } /*Si la palabra traducida tiene 10 o mas letras se debe partir a la mitad y unir con un guion*/ if(str.length>=10){ separador = "" limite = str.length/2 arregloDeSubCadenas = str.split(separador, limite); //A,B,C,D,E... arregloAcadena = arregloDeSubCadenas.join(""); subCadena = str.substring(str.length, str.length/2);//Final de cadena translation = `${arregloAcadena}${'-'}${subCadena}`; } /* letlength = translation.length if(length >= 10){ const fHalf = trnaslation.slice(0, Math.round(length/2)); const sHalf = translation.slice(Math.round(length/2)); translation = `${fHalf} - ${sHalf}`; }*/ /*Si la palabra original es un palindromo ninguna de las anteriores reglas funciona, y se devuelve la palabra intercalando entre mayusculas y minusculas*/ const reverse = (str)=>+ //es lo mismo que const reverse = function(str) str.split('').reverse().join(''); function minMay(str){ const l = str.length; let translation = ""; let capitalize = true; for (let i=0; i<l;i++){ const char = str.charAt(i); translation += capitalize ? char.toUpperCase() : char.toLowerCase();//? comparacion ? } return translation } } if(str = reverse(str)){ return minMay(str);// } return translation } console.log(platzom("programar")); console.log(platzom("Zorro")); console.log(platzom("ABCDEFGHIJKMNOPQRSTUVWXY")); /*var cadena = "ABCDEFGHIJ"; separador = "" limite = cadena.length/2 arregloDeSubCadenas = cadena.split(separador, limite); //A,B,C,D,E... arregloAcadena = arregloDeSubCadenas.join(""); subCadena = cadena.substring(cadena.length, cadena.length/2);//Final de cadena console.log(arregloAcadena + '-' + subCadena);*/
true
601e662314cdfd01f0553aca611e753978ea3c67
JavaScript
Gaja24/it1_1718
/intro_til_firebase/julekalender/julemain.js
UTF-8
816
2.890625
3
[]
no_license
// Initialize Firebase var config = { apiKey: "AIzaSyA8AG8SMweTNFHrkMIv_sFzN0xAA2iX7xo", authDomain: "firestore-224e3.firebaseapp.com", databaseURL: "https://firestore-224e3.firebaseio.com", projectId: "firestore-224e3", storageBucket: "firestore-224e3.appspot.com", messagingSenderId: "146684242749" }; firebase.initializeApp(config); var db = firebase.firestore(); /***Legge til 24 luker for(var lukenummer = 1; lukenummer<=24; lukenummer++){ db.collection("julekalender").add({ luke: lukenummer }); } */ var pakkerE = document.querySelector('.pakker'); var ref = db.collection('julekalender'); var query = ref.where('luke', '==', 24); query.onSnapshot(function (data) { var objekt = data.docs; for(var x in objekt){ pakkerE.innerHTML += objekt[x].data().luke } });
true
e68f730da3de95c073e1a8aa5bd0ea44900c7b19
JavaScript
jeetsj/CovidDashboard
/OOD/OOD/OOD-Server/src/Routes/userRoutes.js
UTF-8
1,617
2.5625
3
[]
no_license
const express = require('express'); const uniqueString = require('unique-string'); const router = express.Router(); const jwt = require('jsonwebtoken'); const fs = require('file-system'); router.post('/', (req, res) => { console.log(req.body); const { email, password } = req.body; fs.readFile("./assets/users.json", (err, data) => { if (err) { console.log(err); return res.status(422).send(err); } const users = JSON.parse(data); const user = users.filter(u => u.email === email); console.log("User", user); if (user.length === 0) { const u = { id: uniqueString(), email: email, password: password } users.push(u); fs.writeFile("./assets/users.json", JSON.stringify(users, null, 2) ,(err) => { if (err) { console.log(err); return res.status(422).send(err); } const userAdded = users.filter(user => user.id === u.id) const token = jwt.sign({userId: userAdded[0].id}, 'My_Secret_Key'); return res.send({token}); }) } else { console.log("existing user", user); if (password === user[0].password) { const token = jwt.sign({userId:user[0].id}, "My_Secret_Key"); return res.send({token}); } else { res.send("Authentication Failed"); } } }) }); module.exports = router;
true
12f302310adf1f9474b4468f9c1f32758b726f95
JavaScript
watership/housingloan-calc
/test/index_old.js
UTF-8
2,974
2.90625
3
[ "MIT" ]
permissive
const Big = require('big.js'); // 等额本息计算方式 exports.fixCalc = function(loan, year, rate) { let oldLoan = loan; loan = Big(loan).times(10000); let months = Number.parseInt(Big(year).times(12)); rate = Big(rate).div(100); const rateMounth = rate.div(12) const a = (rateMounth.plus(1)).pow(months); const b = (loan.times(rateMounth)).times(a); const c = a.minus(1) const repaymentMonthly = b.div(c); const interest = Big(repaymentMonthly.times(months) - loan).div(10000); const total = Big(oldLoan).plus(interest); const incomeMonthly = repaymentMonthly.times(2); return { type: "等额本息", loan: oldLoan.toFixed(2), // 总贷款额 total: total.toFixed(2), // 总还款额 interest: interest.toFixed(2), // 总利息 months: months.toString(), // 贷款总月份数 repaymentMonthly: repaymentMonthly.toFixed(2), // 每月月供额 incomeMonthly: Number.parseInt(incomeMonthly), monthlyData: [] } }; // 等额本金计算方式 exports.capitalCalc = function(loan, year, rate) { let oldLoan = loan; loan = Big(loan).times(10000); let months = Number.parseInt(Big(year).times(12)); rate = Big(rate).div(100); const rateMounth = rate.div(12) const a = loan.div(months); const b = loan.times(rateMounth); const c = rateMounth.plus(1); const d = (a.plus(b)).plus(a.times(c)); const e = loan.div(months); const f = loan.times(rateMounth); // 总利息 const interest = ((d.div(2)).times(months).minus(loan)).div(10000); // 总还款额 const total = Big(oldLoan).plus(interest); const repaymentMonthly = e.plus(f); const incomeMonthly = repaymentMonthly.times(2); function calc(n) { let monthlyRepay = a; const g = loan.minus(a.times(n-1)); const h = g.times(rateMounth); let monthlyInterest = h; let monthlyAll = monthlyRepay.plus(monthlyInterest); const surplus = loan.minus(a.times(n)); return { monthlyRepay: monthlyRepay.toFixed(2), // 月供本金 monthlyInterest: monthlyInterest.toFixed(2), // 月供利息 monthlyAll: monthlyAll.toFixed(2), // 月供 = 月供本金 + 月供利息 surplus: surplus.toFixed(2) } } let calcDataArray = []; for(let i=0;i<months;i++){ calcDataArray.push(calc(i)); } return { type: "等额本金", loan: oldLoan.toFixed(2), // 总贷款额 total: total.toFixed(2), // 总还款额 interest: interest.toFixed(2), // 总利息 months: months.toString(), // 贷款总月份数 repaymentMonthly: repaymentMonthly.toFixed(2), // 每月月供额 incomeMonthly: Number.parseInt(incomeMonthly), monthlyData: calcDataArray, } }
true
aa308ee418011e9d76919f34180e6630540bd2ab
JavaScript
SiddharthMeyan/React-Habit-Streak
/src/App.js
UTF-8
6,148
2.59375
3
[]
no_license
import { useState, useEffect } from "react"; import "./App.css"; import { fire, db, timestamp } from "./firebase/config"; import Timer from "./components/Timer"; import { Main } from "./components/Main"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import History from "./components/History"; function App() { const [onoff, setOnoff] = useState(false); const [originalTime, setOriginalTime] = useState(null); const [currenttime, setCurrenttime] = useState(null); const [streaktime, setStreaktime] = useState(null); const [totalmilisec, setTotalmilisec] = useState(null); const [myachivement, setMyachivement] = useState(""); // for firebase const [user, setUser] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [isuser, setIsuser] = useState(true); const [errorMessage, setErrorMessage] = useState(""); const [myHistory, setMyHistory] = useState([]); const achivement = [ "👶🏻Noob", "👦🏻New Kid", "👲🏻Cool Kid", "🏄🏻‍♂️Firm believer", "👨🏻‍🎓Apprentice", "🏋🏻‍♂️Resilient Bastard", "🧙🏻Master", "🧙🏻‍♂️Grandmaster", "🦸🏻‍♂️Transcendend Entity", ]; const getPrev = () => { const documents = []; db.collection("History") .where("uid", "==", user.uid) .get() .then((querySnapshot) => { querySnapshot.forEach((doc) => { // doc.data() is never undefined for query doc snapshots console.log(doc.id, " => ", doc.data()); documents.push({ ...doc.data() }); }); setMyHistory(documents); }) .catch((error) => { console.log("Error getting documents: ", error); }); }; const startTimer = () => { if (onoff === true) { const endStreak = window.confirm("Give Up?"); if (endStreak) { const timeCreated = timestamp(); const thingsRef = db.collection("History"); thingsRef.add({ uid: user.uid, highScore: streaktime, myachivement: myachivement, createdAt: timeCreated, }); setOnoff(!onoff); } } else { let i = new Date(); setOriginalTime(i); setInterval(() => { let ctime = new Date(); setCurrenttime(ctime); }, 1000); setOnoff(!onoff); } }; const timeDiffCalc = (dateFuture, dateNow) => { var delta = Math.abs(dateFuture - dateNow) / 1000; setTotalmilisec(delta); // calculate (and subtract) whole days var days = Math.floor(delta / 86400); delta -= days * 86400; // calculate (and subtract) whole hours var hours = Math.floor(delta / 3600) % 24; delta -= hours * 3600; // calculate (and subtract) whole minutes var minutes = Math.floor(delta / 60) % 60; delta -= minutes * 60; // what's left is seconds var seconds = Math.floor(delta % 60); // return seconds; let difference = ""; if (days > 0) { difference += days === 1 ? `${days} day, ` : `${days} days, `; } difference += hours === 0 || hours === 1 ? `${hours} hour, ` : `${hours} hours, `; difference += minutes === 0 || hours === 1 ? `${minutes} minutes ` : `${minutes} minutes `; difference += seconds === 0 || minutes === 1 ? `${seconds} seconds ` : `${seconds} seconds `; return difference; }; const SignUp = () => { fire .auth() .createUserWithEmailAndPassword(email, password) .catch((error) => { var errorMessage = error.message; setErrorMessage(errorMessage); }); setEmail(""); setErrorMessage(""); setPassword(""); }; const Login = () => { fire .auth() .signInWithEmailAndPassword(email, password) .catch((error) => { var errorMessage = error.message; setErrorMessage(errorMessage); }); setEmail(""); setErrorMessage(""); setPassword(""); }; const Logout = () => { fire.auth().signOut(); }; const authListener = () => { fire.auth().onAuthStateChanged((user) => { if (user) { setUser(user); } else { setUser(""); } }); }; useEffect(() => { authListener(); if (user) { if (onoff === true) { let stTime = timeDiffCalc(currenttime, originalTime); setStreaktime(stTime); } else { setOriginalTime(null); setCurrenttime(null); setStreaktime(null); setMyachivement(null); } } }, [currenttime]); return ( <Router> <Switch> <Route exact path="/"> <div className="App"> <header className="App-header"> {user ? ( <> <Timer getPrev={getPrev} myHistory={myHistory} Logout={Logout} user={user} onoff={onoff} setOnoff={setOnoff} startTimer={startTimer} streaktime={streaktime} currenttime={currenttime} totalmilisec={totalmilisec} myachivement={myachivement} setMyachivement={setMyachivement} achivement={achivement} /> </> ) : ( <Main setEmail={setEmail} email={email} password={password} setPassword={setPassword} isuser={isuser} setIsuser={setIsuser} errorMessage={errorMessage} setErrorMessage={errorMessage} SignUp={SignUp} Login={Login} /> )} </header> </div> </Route> <Route path="/history"> <History user={user} myHistory={myHistory} /> </Route> </Switch> </Router> ); } export default App;
true
9ad6d46ae1972ef0518968125fa94e5a2ac720dd
JavaScript
Romanskiy94/New_year
/assets/js/index.js
UTF-8
1,045
3.390625
3
[]
no_license
timeend= new Date(); // IE и FF по разному отрабатывают getYear() timeend= new Date(timeend.getYear()>1900?(timeend.getYear()+1):(timeend.getYear()+1901),0,1); // для задания обратного отсчета до определенной даты укажите дату в формате: // timeend= new Date(ГОД, МЕСЯЦ-1, ДЕНЬ); // Для задания даты с точностью до времени укажите дату в формате: // timeend= new Date(ГОД, МЕСЯЦ-1, ДЕНЬ, ЧАСЫ-1, МИНУТЫ); function time() { today = new Date(); today = Math.floor((timeend-today)/1000); tsec=today%60; today=Math.floor(today/60); if(tsec<10)tsec='0'+tsec; tmin=today%60; today=Math.floor(today/60); if(tmin<10)tmin='0'+tmin; thour=today%24; today=Math.floor(today/24); timestr=today +" дней "+ thour+" часов "+tmin+" минут "+tsec+" секунд"; document.getElementById('t').innerHTML=timestr; window.setTimeout("time()",1000); }
true
f415f39f9fd3a23846191f2efc0f86647ec5e130
JavaScript
rphansen91/OurPromise
/ourPromise.spec.js
UTF-8
2,253
2.828125
3
[]
no_license
var expect = require('expect'); var ourPromise = require('./ourPromise'); describe('Promise Implementation', function () { it('should throw an error if no resolver ', function () { expect(ourPromise).toThrow(/You must pass a resolver function/) }) it('should throw an error if new keyword not used ', function () { var bindPromise = ourPromise.bind(this, function (resolve, reject) {}) expect(bindPromise).toThrow(/Please use the 'new' operator/) }) it('should be thenable', function () { var promise = new ourPromise(function (resolve, reject) {}) var actual = typeof promise.then; var expected = "function"; expect(actual).toBe(expected); }) it('should be catchable', function () { var deferred = new ourPromise(function (resolve, reject) {}) var actual = typeof deferred.catch; var expected = "function"; expect(actual).toBe(expected); }) it('should callback to then on success', function () { var defered = new ourPromise(function (resolve, reject) { resolve(true); }); var actual = false; defered .then(function (val) { actual = val; }) var expected = true; expect(actual).toBe(expected); }) it('should callback to catch on error', function () { var defered = new ourPromise(function (resolve, reject) { reject(true); }); var actual = false; defered .then(function () { actual = false; }) .catch(function (err) { actual = err; }) var expected = true; expect(actual).toBe(expected); }) it('should be chainable', function () { var defered = new ourPromise(function (resolve, reject) { resolve(false); }); var actual = false; defered .then(function () { return true; }) .then(function (val) { actual = val; }) .catch(function (val) { actual = false; }) var expected = true; expect(actual).toBe(expected); }) })
true
83c0934b07222a355fa13fa94ba2790727578d51
JavaScript
Tom-Fitz-3/2105-OKU-Wizard-News-Starting-Point
/app.js
UTF-8
3,186
2.609375
3
[]
no_license
const express = require("express"); const morgan = require("morgan"); const {PORT = 1337} = process.env; const posts = require("./postBank"); const app = express(); app.use(morgan('dev')); app.use(express.static('public')); app.get("/test", (req, res) => res.send("Hello World!")); app.get("/", (req, res) => { const postList = posts.list(); const outputList = postList.map(post => `<p> <span class="news-position"> ${post.id}. <a href="/posts/${post.id}">${post.title}</a> <br> <small>By: ${post.name}</small> </span> </p> <small class="news-info"> ${post.upvotes} upvotes | ${post.date} </small>` ); const output =`<!DOCTYPE html> <html> <head> <title>Wizard-News</title> <link rel="stylesheet" href="/style.css" /> </head> <body> <header><img src="/logo.png"/>Wizard News</header> <div class="news-list">Headlines <div class="news-item"> ${outputList.join('')} </div> </div> </body> </html>` res.send(output); }) app.get( "/posts/:id", (req, res) => { const id = req.params.id; const post = posts.find(id); if (!post.id) { throw new Error('Not Found') } const output =`<!DOCTYPE html> <html> <head> <title>Wizard-News</title> <link rel="stylesheet" href="/style.css" /> </head> <body> <header><img src="/logo.png"/><a class="news" href="/">Wizard News</a></header> <div class="news-item"> <p> <span> ${post.title} <br> <small>By: ${post.name} | ${post.date}</small> </span> </p> <div class="news-info">${post.content}</div> </div> </body> </html>` res.send(output); }) app.use(function (err, req, res, next) { console.error(err.stack); res.status(404); const html = `<!DOCTYPE html> <html> <head> <title>Wizard News</title> <link rel="stylesheet" href="/style.css" /> </head> <body> <header><img src="/logo.png"/><a class="news" href="/">Wizard News</a></header> <div class="not-found"> <p>404</p> <p>Accio Page! 🧙‍♀️ ... Page Not Found</p> </div> </body> </html>` res.send(html); }) app.listen(PORT, () => { console.log(`App listening in port ${PORT}`); });
true
a6fd1d7d00df3d5f28630362bccdf10756c5319a
JavaScript
denniswong0106/lotide
/test/countLettersTest.js
UTF-8
1,206
3.21875
3
[]
no_license
const countLetters = require('../countLetters'); const assert = require('chai').assert; describe('#countLetters',() => { const sentence = 'hello darkness my old friend'; console.log('const sentence = ', sentence); it('it should return 2 if given countLetters(sentence)["n"]', () => { let actualOutput = countLetters(sentence)["n"]; let expectedOutput = 2; assert.equal(actualOutput, expectedOutput); }) it('it should return undefined if given countLetters(sentence)["z"]', ()=> { let actualOutput = countLetters(sentence)["z"]; let expectedOutput = undefined; assert.equal(actualOutput, expectedOutput); }) console.log('#OutputObject', { h: 1, e: 3, l: 3, o: 2, ' ': 4, d: 3, a: 1, r: 2, k: 1, n: 2, s: 2, m: 1, y: 1, f: 1, i: 1 } ) it('it should return #OutputObject if given sentence', ()=> { let actualOutput = countLetters(sentence); let expectedOutput = { h: 1, e: 3, l: 3, o: 2, ' ': 4, d: 3, a: 1, r: 2, k: 1, n: 2, s: 2, m: 1, y: 1, f: 1, i: 1 }; assert.deepEqual(actualOutput, expectedOutput); }) });
true
af2ad42a1cf37efdc8c7ea32fe9d3d201188ed96
JavaScript
Delpire/Delpire.github.io
/projects/heliattack/background.js
UTF-8
2,698
3.015625
3
[]
no_license
var LEVEL_LENGTH = [3000, 6000, 6000] // Background class //---------------------------------- var Background = function(game, x, y) { this.game = game; this.back_x = x; this.mid_x = x; this.front_x = x; }; Background.prototype = { render: function(context) { context.save(); // Draw the background. context.drawImage(Resource.Image.levels[this.game.level], this.back_x, 0, 800, 480, 0, 0, 800, 480); // If mid_x is 3000, there is no longer a need to draw from the source twice. // Reset mid_x, allowing the render to draw from the beginning of the image again. if(this.mid_x >= LEVEL_LENGTH[this.game.level]){ this.mid_x = 0; } // If out mid_x is past 2200, it will draw past the image. // Draw to the end of the image, and from there draw the beginning // of the image. if(this.mid_x > LEVEL_LENGTH[this.game.level] - 800){ context.drawImage(Resource.Image.levels[this.game.level], this.mid_x, 480, LEVEL_LENGTH[this.game.level] - this.mid_x, 480, 0, 0, LEVEL_LENGTH[this.game.level] - this.mid_x, 480); context.drawImage(Resource.Image.levels[this.game.level], 0, 480, 800, 480, LEVEL_LENGTH[this.game.level] - this.mid_x, 0, 800, 480); } else{ // Draw the mid ground. context.drawImage(Resource.Image.levels[this.game.level], this.mid_x, 480, 800, 480, 0, 0, 800, 480); } // If front_x is 3000, there is no longer a need to draw from the source twice. // Reset front_x, allowing the render to draw from the beginning of the image again. if(this.front_x >= LEVEL_LENGTH[this.game.level]){ this.front_x = 0; } // If out front_x is past 2200, it will draw past the image. // Draw to the end of the image, and from there draw the beginning // of the image. if(this.front_x > LEVEL_LENGTH[this.game.level] - 800){ context.drawImage(Resource.Image.levels[this.game.level], this.front_x, 960, LEVEL_LENGTH[this.game.level] - this.front_x, 480, 0, 0, LEVEL_LENGTH[this.game.level] - this.front_x, 480); context.drawImage(Resource.Image.levels[this.game.level], 0, 960, 800, 480, LEVEL_LENGTH[this.game.level] - this.front_x, 0, 800, 480); } else{ // Draw the foreground. context.drawImage(Resource.Image.levels[this.game.level], this.front_x, 960, 800, 480, 0, 0, 800, 480); } context.restore(); }, update: function(){ this.back_x += 5; this.mid_x += 8; this.front_x += 13; }, nextLevel: function(){ this.back_x = 0; this.mid_x = 0; this.front_x = 0; } };
true
215fa332fa71ce07b5257dfbebd0b47549a22b71
JavaScript
cadencegail/cadencegail.github.io
/mashUp/mashup-gh-pages/mashup.js
UTF-8
6,561
2.546875
3
[]
no_license
//FACEBOOK // This is called with the results from from FB.getLoginStatus(). function statusChangeCallback(response) { console.log('statusChangeCallback'); console.log(response); // The response object is returned with a status field that lets the // app know the current login status of the person. // Full docs on the response object can be found in the documentation // for FB.getLoginStatus(). if (response.status === 'connected') { // Logged into your app and Facebook. testAPI(); FB.api("/me/home", { "with": "location" }, function(response) { console.log(response); if (response && !response.error) { var waldo = { lat: Math.random() * 170 - 85, lng: Math.random() * 360 - 180, friendname: "Waldo", friendid:"whereswaldo", placename:"Waldo's place", message: "You found me!" } markers = [waldo]; for (var i in response['data']) { friendlocation = { lat: response.data[i].place.location.latitude, lng: response.data[i].place.location.longitude, friendname: response.data[i].from.name, friendid: response.data[i].from.id, placename: response.data[i].place.name } if (response.data[i].hasOwnProperty('story')) { friendlocation.message = '"'+response.data[i].story+'"'; } else if (response.data[i].hasOwnProperty('message')) { friendlocation.message = '"'+response.data[i].message+'"'; } else { friendlocation.message = ""; } if (response.data[i].hasOwnProperty('picture')) { friendlocation.picture = response.data[i].picture; } markers.push(friendlocation); } loadMarkers(markers); } } ); } else if (response.status === 'not_authorized') { // The person is logged into Facebook, but not your app. document.getElementById('status').innerHTML = 'Log in ' + 'to find your friends!'; } else { // The person is not logged into Facebook, so we're not sure if // they are logged into this app or not. document.getElementById('status').innerHTML = 'Log in ' + 'to find your friends!'; } } // This function is called when someone finishes with the Login // Button. See the onlogin handler attached to it in the sample // code below. function checkLoginState() { FB.getLoginStatus(function(response) { statusChangeCallback(response); }); } window.fbAsyncInit = function() { FB.init({ appId : '1396726507284343', cookie : true, // enable cookies to allow the server to access // the session xfbml : true, // parse social plugins on this page version : 'v2.1' // use version 2.1 }); // Now that we've initialized the JavaScript SDK, we call // FB.getLoginStatus(). This function gets the state of the // person visiting this page and can return one of three states to // the callback you provide. They can be: // // 1. Logged into your app ('connected') // 2. Logged into Facebook, but not your app ('not_authorized') // 3. Not logged into Facebook and can't tell if they are logged into // your app or not. // // These three cases are handled in the callback function. FB.getLoginStatus(function(response) { console.log(response); statusChangeCallback(response); }); FB.Event.subscribe('auth.logout', logout_event); }; // Load the SDK asynchronously (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); // Here we run a very simple test of the Graph API after login is // successful. See statusChangeCallback() for when this call is made. function testAPI() { console.log('Welcome! Fetching your information.... '); FB.api('/me', function(response) { console.log('Successful login for: ' + response.name); document.getElementById('status').innerHTML = 'Where\'s Waldo?'; }); } var logout_event = function(response) { console.log("WE ARE HERE"); var myMap = document.getElementById("map-canvas"); var myBody = document.getElementById("map"); myBody.removeChild(myMap); myBody.innerHTML += "<div id='map-canvas'></div>"; initialize(); } // GOOGLE MAPS function initialize() { var mapOptions = { center: { lat: 0, lng: 0}, zoom: 0 }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); } google.maps.event.addDomListener(window, 'load', initialize); function loadMarkers(markers) { var bounds = new google.maps.LatLngBounds(); // Display multiple markers on a map var infoWindow = new google.maps.InfoWindow(), marker, i; var infoWindowContent = []; for (i = 0; i < markers.length; i++) { var str = '<div class="info_content">' + '<a href="https://www.facebook.com/'+markers[i].friendid+'">'+ '<img src="https://graph.facebook.com/'+markers[i].friendid+'/picture" />'+ '<h3>'+markers[i].friendname+'</h3>' + '</a>'+ '<p>' + markers[i].message + '</p>' if (markers[i].hasOwnProperty('picture')) { str += '<img src="'+markers[i].picture+'" />' } infoWindowContent.push(str); } // Loop through our array of markers & place each one on the map for( i = 0; i < markers.length; i++ ) { var position = new google.maps.LatLng(markers[i].lat, markers[i].lng); bounds.extend(position); marker = new google.maps.Marker({ position: position, map: map, title: markers[i].placename }); // Allow each marker to have an info window google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infoWindow.setContent(infoWindowContent[i]); infoWindow.open(map, marker); } })(marker, i)); // Automatically center the map fitting all markers on the screen map.fitBounds(bounds); } }
true
77fc8475742fc00c590cf0d0d6c4493ffb3d5aac
JavaScript
Indre101/Indre101.github.io
/Door_game/js/script.js
UTF-8
12,876
3.109375
3
[]
no_license
const landingPageContainer = document.getElementById("landingPageContainer"); const startGamePage = document.getElementById("startGamePage"); const popUpInstructionsContainer = document.getElementById("popUpInstructionsContainer"); const gameContainer = document.querySelector(".body"); const startButton = document.getElementById("startButton"); const infoButtonContainer = document.getElementById("infoButtonContainer"); const returnButtonContainer = document.getElementById("returnButtonContainer"); let state = ""; let openDoorsCount = 0; let lives = 3; let score = 0; // AUDIO const backgroundSound = new Audio("./audio/backgroundSound.mp3"); function randomNumberGenerator(l) { let n = Math.floor(Math.random() * l.length) return n } // chaning background image function changeBackground(x, u) { x.style.backgroundImage = u; } // function to toggle classes function toggleClasses(x, c) { x.classList.toggle(c) } function addClass(x, a) { x.classList.add(a) } function removeClass(x, a) { x.classList.remove(a); } // function to clear img src; function clearImgSrc(x) { x.src = ""; } // class variables let dBlock = "d-block"; let dNone = "d-none"; // startButton.onclick = function () { // start page changes to the game beginng let url1 = "url('./images/images/bg_2.jpg')" changeBackground(gameContainer, url1); toggleClasses(landingPageContainer, dNone); toggleClasses(startGamePage, dBlock); toggleClasses(startGamePage, dNone); // assigns first level img assignImage(); // } // instruction button infoButtonContainer.onclick = function () { toggleClasses(popUpInstructionsContainer, dNone); } // TRANSITION FUNCTION FOR BUTTONS ON HOVER function mouseOverAndOut(triggerElement, changingElement, className) { triggerElement.onmouseover = function () { addClass(changingElement, className) } triggerElement.onmouseout = function () { removeClass(changingElement, className) } } mouseOverAndOut(returnButtonContainer, document.querySelector(".returnButton"), "returnButtonHover") mouseOverAndOut(infoButtonContainer, document.getElementById("infoButtonBg"), "infoButtonHover") mouseOverAndOut(document.getElementById("soundContainer"), document.querySelector(".soundBgMain"), "soundBgHover") mouseOverAndOut(document.getElementById("gotIt"), document.querySelector(".gotItbg"), "gotItHover") // MUSIC CONTROLS let clickCount = 0 document.getElementById("soundContainer").onclick = function () { clickCount++; document.querySelector(".soundIconMain").src = "./images/buttons_icons/sound_off.svg"; backgroundSound.addEventListener('ended', function () { this.currentTime = 0; this.play(); }, false); backgroundSound.play(); if (clickCount === 2) { clickCount = 0; document.querySelector(".soundIconMain").src = "./images/buttons_icons/sound_on.svg"; backgroundSound.pause(); } } // return button inside pup up instructions returnButtonContainer.onclick = function () { toggleClasses(popUpInstructionsContainer, dNone); } //FUNCTION TO ADD THE DOORS // declared variables for function to add another column once level up const htmlColumn = window.getComputedStyle(document.querySelector("html")); const doorContainer = document.getElementById("styleOftheDoorContainer"); const colNum = parseInt(htmlColumn.getPropertyValue("--colNum")); let columnNumber = colNum // SELECT ALL function selectAllQuery(c) { let nodeArray = document.querySelectorAll(c); return nodeArray; } // function to add another grid and another column and frame-door element function winScenario() { columnNumber++ document.documentElement.style.setProperty("--colNum", columnNumber); let elmnt = document.querySelector(".entrance"); let cln = elmnt.cloneNode(true); doorContainer.appendChild(cln); cln.querySelectorAll('img')[3].classList.remove("door-animation"); cln.querySelectorAll('img')[3].style.pointerEvents = "auto"; let doorsOpeningNew = selectAllQuery(".open") let doorsOpeningArr = Array.prototype.slice.call(doorsOpeningNew); doorsOpeningFunction(doorsOpeningNew, doorsOpeningArr) } let doorsOpening = selectAllQuery(".open"); let imgBehidDoors = selectAllQuery(".imgBehidDoors") let doorsOpeningArr = Array.prototype.slice.call(doorsOpening); // function to assign images let inf1 = "./images/images/in_1.png"; let inf2 = "./images/images/in_2.png"; function selectAll(h) { let i = document.querySelectorAll(h); return i; } let goodImg = ["./images/images/bunny_1.png", "./images/images/bunny_2.png", "./images/images/puppy_1.png"]; let messageSrcArr = ["./images/images/message_1.png", "./images/images/message_2.png", "./images/images/message_3.png", "./images/images/message_4.png"] let looseImg = [inf1, inf2]; function assignImage() { let i = selectAllQuery(".imgBehidDoors"); i.forEach((e) => { // e.src === "#" e.removeAttribute('src') }) i[randomNumberGenerator(i)].src = goodImg[randomNumberGenerator(goodImg)] let behidDoorsNumber_2 = randomNumberGenerator(imgBehidDoors); i.forEach((e) => { if (e.src === "") { e.src = looseImg[randomNumberGenerator(looseImg)] } }) } // function for the imgBehindDoors when there is four doors function assignImageIfTwoCilckableImg() { let i = selectAllQuery(".imgBehidDoors"); i.forEach((e) => { e.removeAttribute('src') }) let behidDoorsNumber_2 = randomNumberGenerator(i) let behidDoorsNumber = randomNumberGenerator(i) do { behidDoorsNumber_2 = randomNumberGenerator(i); } while (behidDoorsNumber_2 === behidDoorsNumber) if (behidDoorsNumber_2 != behidDoorsNumber) { i[behidDoorsNumber].src = goodImg[randomNumberGenerator(goodImg)] i[behidDoorsNumber_2].src = goodImg[randomNumberGenerator(goodImg)] i.forEach((e) => { if (e.src === "") { e.src = looseImg[randomNumberGenerator(looseImg)] } }) } } // FUNCTION FOR BOTH THREE OR LESS AND FOUR OR MORE DOOR GAME function doorsOpeningFunction(arrDoor, doorConvertedArray) { arrDoor.forEach((f) => { f.onclick = function () { let i = selectAllQuery(".imgBehidDoors"); let messageInf = selectAllQuery(".message") addClass(this, "door-animation") let a = doorConvertedArray.indexOf(this) openDoorsCount++ if (arrDoor.length >= 4 && openDoorsCount === 1) { assignImageIfTwoCilckableImg(); if (looseImg.includes(i[a].getAttribute('src'))) { messageInf[a].src = messageSrcArr[randomNumberGenerator(messageSrcArr)]; messageInf[a].classList.remove("d-none"); i[a].classList.add("inf") state = "loose" arrDoor.forEach(d => { d.style.pointerEvents = "none"; }) startNewLevel(arrDoor, i) countLives() } else if (goodImg.includes(i[a].getAttribute('src'))) { state = "win" openDoorsCount++ } } if (arrDoor.length >= 4 && openDoorsCount === 3) { if (looseImg.includes(i[a].getAttribute('src'))) { i[a].classList.add("inf") messageInf[a].src = messageSrcArr[randomNumberGenerator(messageSrcArr)]; messageInf[a].classList.remove("d-none"); arrDoor.forEach(d => { d.style.pointerEvents = "none"; }) startNewLevel(arrDoor, i) countLives() } else if (state === "win") { arrDoor.forEach(d => { d.style.pointerEvents = "none"; }) startNewLevel(arrDoor, i) calculateScore() } } // win or loose for less or equal to three doors if (arrDoor.length <= 3) { openDoorsCount++ assignImage() arrDoor.forEach(d => { d.style.pointerEvents = "none"; }) if (goodImg.includes(i[a].getAttribute('src'))) { state = "win" startNewLevel(arrDoor, i) calculateScore() } else if (looseImg.includes(i[a].getAttribute('src'))) { i[a].classList.add("inf") messageInf[a].src = messageSrcArr[randomNumberGenerator(messageSrcArr)]; messageInf[a].classList.remove("d-none"); startNewLevel(arrDoor, i) state = "loose" countLives() } } } }) } // FUNCTIONS FOR LIVES AND SCORE NUMBERS let livesCount = document.getElementById("liveCount"); let scoreCount = document.getElementById("scoreCount"); let heartIcon = document.querySelector(".img-icon-1"); let highScore = []; let looseColor = document.querySelector(".looseColor") // COUNT LIVES function countLives() { let elmnt = selectAllQuery(".open"); lives--; if (lives === 1) { addClass(heartIcon, "heartPulse") } else if (lives === 0) { removeClass(heartIcon, "heartPulse"); removeClass(looseColor, "d-none"); highScore.push(score); document.querySelectorAll(".playAgain").forEach(playAgainBtn => { playAgainBtn.onclick = function () { gameOver() doorsOpeningFunction(doorsOpening, doorsOpeningArr); } }) elmnt.forEach(entrances => { entrances.onclick = function () { this.style.pointerEvents = "none"; } }) } livesCount.textContent = lives; } // CALCULATE SCORE function calculateScore() { score++; let elmnt = selectAllQuery(".open"); if (score === 4) { let b = document.querySelector(".winColor") setTimeout(() => { b.classList.remove("d-none"); elmnt.forEach(entrances => { entrances.onclick = function () { this.style.pointerEvents = "none"; } }) }, 1000); // highScore.push(score); document.querySelectorAll(".playAgain").forEach(playAgainBtn => { playAgainBtn.onclick = function () { gameOver() doorsOpeningFunction(doorsOpening, doorsOpeningArr); b.classList.add("d-none"); } }) // } else if (score === 2) { let c = document.querySelector(".third") setTimeout(() => { elmnt.forEach(entrances => { entrances.onclick = function () { this.style.pointerEvents = "none"; } }) c.classList.remove("d-none"); }, 1000); document.getElementById("gotIt").onclick = function () { c.classList.add("d-none"); winScenario() elmnt.forEach(entrances => { entrances.style.pointerEvents = "auto"; }) } } else if (score === 1) { let b = selectAllQuery(".shout")[randomNumberGenerator(selectAllQuery(".shout"))] setTimeout(() => { b.classList.remove("d-none"); // elmnt.forEach(entrances => { entrances.onclick = function () { this.style.pointerEvents = "none"; } }) // }, 1000); setTimeout(() => { winScenario() b.classList.add("d-none"); elmnt.forEach(entrances => { entrances.style.pointerEvents = "auto"; }) }, 3500); } scoreCount.textContent = score; } function startNewLevel(arr, imgBehinddor) { let messageInf = selectAllQuery(".message") let i = selectAllQuery(".imgBehidDoors"); openDoorsCount = 0; arr.forEach((f) => { setTimeout(() => { removeClass(f, "door-animation"); f.style.pointerEvents = "auto"; messageInf.forEach(messageImg => { messageImg.classList.add("d-none"); }) i.forEach(imgInf => { imgInf.classList.remove("inf"); }) // missing animation to display for loose }, 2000); }) } function gameOver() { addClass(looseColor, "d-none"); // document.getElementById("highScore").textContent = Math.max(highScore); document.getElementById("highScore").textContent = Math.max.apply(null, highScore); openDoorsCount = 0; columnNumber = 2; document.documentElement.style.setProperty("--colNum", columnNumber); score = 0; lives = 3; scoreCount.textContent = score; livesCount.textContent = lives; let i = selectAllQuery(".imgBehidDoors") i.forEach(imgBehind => { imgBehind.classList.remove("inf"); }) let doorsOpening = selectAllQuery(".open"); // let elmnt = selectAllQuery(".entrance"); let select = document.querySelector('#styleOftheDoorContainer'); let child = select.lastElementChild; if (doorsOpening.length === 4) { select.removeChild(child); child = select.lastElementChild; select.removeChild(child); } else if (doorsOpening.length === 3) { child = select.lastElementChild; select.removeChild(child); } } doorsOpeningFunction(doorsOpening, doorsOpeningArr);
true
8cfc20340c187845ecdf0b6600ba025174a9e255
JavaScript
dylanmei/Whendle
/whendle/api/observable.js
UTF-8
657
2.625
3
[ "MIT" ]
permissive
Whendle.Observable = Class.create({ initialize: function() { this._hash = new Hash(); }, observe: function(name, handler) { var handlers = this.handlers(name); if (handlers.length) { handlers.push(handler); } else { this._hash.set(name, [handler]); } }, ignore: function(name, handler) { if (!name) return; if (!handler) this._hash.unset(name); else { var handlers = this.handlers(name) .without(handler); this._hash.set(name, handlers); } }, handlers: function(name) { return this._hash.get(name) || []; }, fire: function(name, data) { this.handlers(name) .each(function(f) { f(data); }); } });
true
748e52fa30b15779d4a14c71ea19025cb00a5452
JavaScript
Albertosnp/weather-app-consola
/app.js
UTF-8
1,593
2.921875
3
[]
no_license
const { leerInput, inquirerMenu, pause, ciudadesAelegir } = require("./helpers/inquirer"); require("dotenv").config() require('colors') const Busquedas = require("./models/Busquedas"); const main = async () => { let option = 0 const busquedas = new Busquedas() do { option = await inquirerMenu() switch (option) { case 1: await buscarCiudad(busquedas) break; case 2: console.log('\nHistorial de búsquedas\n'.green); console.log(busquedas.historial.join('\n')); break; } if (option !== 0) await pause() } while (option !== 0); }; const buscarCiudad = async (busquedas) => { const lugar = await leerInput('Introduce el nombre del lugar que quiere buscar:\n'); //Buscar los lugares en API const lugares = await busquedas.buscarCiudad(lugar) //Seleccionar un lugar const id_lugar = await ciudadesAelegir(lugares) //Cancelar la búsqueda if (id_lugar == 0) return const lugarSelecc = lugares.find(lugar => lugar.id === id_lugar) //Llamada api de tiempo por coordenadas const clima = await busquedas.buscarClimaPorLugar(lugarSelecc.lat, lugarSelecc.lng) //Mostrar los detalles del lugar clima console.clear(); console.log('\nInformación de la ciudad\n'.green); console.log('Ciudad', lugarSelecc.nombre.green); console.log('Latitud', lugarSelecc.lat); console.log('Longitud', lugarSelecc.lng); console.log('Temperatura', clima.main); console.log('Descripción', clima.weather[0].description.green); //Guardar en db busquedas.agregarHistorial(lugarSelecc.nombre) }; main()
true
e2f66720d63b5cd15d80123171295aed28de3bb1
JavaScript
RadAtanasov/Clock
/assets/js/script.js
UTF-8
1,219
3.296875
3
[]
no_license
var hourHand = document.getElementsByClassName('hour_hand')[0]; var minuteHand = document.getElementsByClassName('minute_hand')[0]; var secondHand = document.getElementsByClassName('second_hand')[0]; //var startDate = new Date(); //var startRotateSecondHand = startDate.getSeconds(); //var startRotateMinuteHand = startDate.getMinutes(); //var startRotateHourHand = startDate.getHours(); //secondHand.style.transform = 'rotate'+'('+(startRotateSecondHand)+')'; //minuteHand.style.transform = 'rotate'+'('+(startRotateMinuteHand)+')'; //hourHand.style.transform = 'rotate'+'('+(startRotateHourHand)+')'; var countTime = setInterval(function(){ var date = new Date(); var degRotateSecondHand = (360 * date.getSeconds()/60)+'deg'; var degRotateMinuteHand = (360 * date.getMinutes()/60)+'deg'; var degRotateHourHand = (360 * date.getHours()/12)+0.5*(360 * date.getMinutes()/360)+'deg'; secondHand.style.transform = 'rotate'+'('+(degRotateSecondHand)+')'; minuteHand.style.transform = 'rotate'+'('+(degRotateMinuteHand)+')'; hourHand.style.transform = 'rotate'+'('+(degRotateHourHand)+')'; secondHand.style.display = 'block'; minuteHand.style.display = 'block'; hourHand.style.display = 'block'; }, 200);
true
7aef1ba58276fb495b2d18f86be9e7c1dcaa3be8
JavaScript
lolwuz/it
/react-buggle/src/reducers/checkReducer.js
UTF-8
1,404
2.65625
3
[]
no_license
/* src/reducers/checkReducer.js */ export default (state = { loading: false, guesses: [], solutions: [], points: 0, totalPoints: 0 }, action) => { switch (action.type) { case 'R_BOARD_CHECK': return { ...state, loading: true } case 'S_BOARD_CHECK': let guess = action.payload.data if (!guess.is_valid) guess.is_valid = 0 else guess.is_valid = 1 for (let i = 0; i < state.guesses.length; i++) { if (state.guesses[i].word === guess.word) { guess.is_valid = 2 } } return { ...state, loading: false, guesses: [guess, ...state.guesses], points: state.points + guess.points } case 'F_BOARD_CHECK': return { ...state, loading: false, error: 'Error while fetching check' } case 'R_BOARD_SOLUTION': return { ...state, loading: true } case 'S_BOARD_SOLUTION': return { ...state, loading: false, solutions: action.payload.data.solved, totalPoints: action.payload.data.points } case 'F_BOARD_SOLUTION': return { ...state, loading: false, error: 'Error while fetching solution' } case 'DELETE_BOARD': return { ...state, loading: false, guesses: [], solutions: [], points: 0 } default: return state } }
true
56cb362bb6b95fc8beca3afcb0033066b9cadf88
JavaScript
PorcelainAddict/Tues_Painter_Decorator
/specs/room_spec.js
UTF-8
711
2.828125
3
[]
no_license
const assert = require('assert'); const Room = require('../room.js'); describe('Room', function() { beforeEach(function() { //space reserved for room something soemthing room = new Room (10); }); it('should have an area in square meters', function() { const actual = room.area; const expected = 10; assert.strictEqual(actual, expected); }); it('should start not painted', function() { const actual = room.isItPainted(); const expected = false; assert.strictEqual(actual, expected) }); it('should be painted', function() { room.paintASquareMeter(3); room.paintASquareMeter(3); room.paintASquareMeter(3); assert.strictEqual(9, room.paintedArea); }); });
true
b8664c996608c849314f40a70e0506a7494d8259
JavaScript
kauesedrez/CedrosDatabase
/cedrosDb.jss
UTF-8
26,424
2.59375
3
[ "MIT", "Apache-2.0" ]
permissive
 /*** [cdoc] #autor: Winetu Kaue Sedrez Bilhalva #name: Database Class #obs: https://msdn.microsoft.com/en-us/library/hww8txat(v=vs.84).aspx - documentação ***/ /* [init block] #desc: testa se a jquery está funcionando */ if(typeof $ == "undefined") { document.write("<h1>Cedros Database</h1><h2>Hello Folks! It Works.</h2><h3>More? <a target='_blank' href='http://www.cedrosdev.com.br'>Cedros Development</a></h3><hr />"); document.write("<h3>[!] Atenção [!] - Está faltando a jquery!</h3><hr />"); } /* [end block] */ /* [init block] #name: teste de compatibilidade */ $(function(){ try{ fso = new ActiveXObject("Scripting.FileSystemObject"); } catch(e) { document.write("O site não foi adicionado aos sites confiáveis<hr>Vá em Ferramentas>Opções da Internet>Segurança>Sites Confiáveis>sites>Adicionar este site a zona>Adicionar<p>Nessa versão o sistema funciona apenas no Internet Explorer<p>Erro Original<p><i>"+e.message); } }); /*** [init function] #name: Database() ***/ var CedrosDatabase = function() { var valor=[]; this.numLines=[]; this.numLins; this.numCols=[]; this.table_; this.database_; /** define com qual tabela o objeto irá trabalhar permanentemente **/ // ------------------------------------------------------------------------------------------------ /*** [init function] #name:escreve(); ***/ this.escreve = function(x){ $("#output").append(x+"<p>"); } /*** [end function] ***/ // ------------------------------------------------------------------------------------------------ /*** [init block] #name: trims ***/ this.trim = function(str) { return str.replace(/^\s+|\s+$/g,""); } //left trim this.ltrim=function(str) { return str.replace(/^\s+/,""); } //right trim this.rtrim = function(str) { return str.replace(/\s+$/,""); } /*** [end block] ***/ // ------------------------------------------------------------------------------------------------ /* [init function] #name: itWorks(); */ this.itWorks = function() { document.write("<h1>Cedros Database</h1><h2>Hello Folks! It Works.</h2><h3>More? <a target='_blank' href='http://www.cedrosdev.com.br'>Cedros Development</a></h3><hr />"); //testa o path if(typeof PATH == 'undefined') { document.write("<h3>[!] Atenção [!] - Está faltando o path.txt !</h3><hr />"); } else { document.write("<h3>Ótimo, tudo parece ter sido configurado corretamente. Não esqueça das barras no final do path.txt ;) </h3><hr /> Leia a documentação do CBD em cedrosdev.com.br/cdb/docs"); } } /* [end function] */ /*** [init function] #name: getWhen(); ***/ this.getWhen = function (retorno_,coluna_,valor_){ /** get nome(retorno_) when categoria(coluna_)=advogado(valor_) , retorna apenas uma ocorrencia**/ var fso = new ActiveXObject("Scripting.FileSystemObject"); var file = fso.OpenTextFile(PATH+this.database_+"\\"+this.table_+".cdb",1); if (file.AtEndOfStream) arquivoOriginal=""; else arquivoOriginal=file.ReadAll(); file.Close(); //arquivoOriginal retem todo o arquivo de banco de dados this.numLines=arquivoOriginal.split("\n"); for(a=0;a<this.numLines.length;a++) { valor[a]=this.numLines[a].split("|-$-|"); } //################################################################################### getWhenConfirm1=false; getWhenConfirm2=false; //tenho que descobrir em que this.numLines categoria=advogado for(i=0;i<valor[0].length;i++){ /** valor[0].length retem o total de colunas da nossa tabela **/ //GET telefone if(this.trim(valor[0][i])==coluna_){ numCol=i; /** numero da coluna passada no parametro retorno **/ getWhenConfirm1=true; } } if(!getWhenConfirm1){ return "getWhen Error (01): A coluna '"+coluna_+"' não existe na tabela "+this.table_; } //max if(valor_ == "max") { var tt=0; for(i=1;i<this.numLines.length;i++){ /** começa em 1 por 0 é o nome da coluna e não o valor a ser computado **/ hh=parseInt(this.trim(valor[i][numCol])); if(i==1)tt=hh; if(hh>tt)tt=hh; } return tt; } //min if(valor_ == "min") { var tt=0; for(i=1;i<this.numLines.length;i++){ hh=parseInt(this.trim(valor[i][numCol])); if(i==1)tt=hh; if(hh<tt)tt=hh; } return tt; } for(i=0;i<this.numLines.length;i++){ if(this.trim(valor[i][numCol])==valor_) { numLin=i; getWhenConfirm2=true; } } if(!getWhenConfirm2){ return "getWhen Error (01): O valor '"+valor_+"' não foi localizado na coluna '"+coluna_+"' da tabela "+this.table_; } this.numCols=valor[0].length; return this.get(retorno_,numLin); } /*** [end function] ***/ // ------------------------------------------------------------------------------------------------ /*** [init function] #name: get(); ***/ this.get = function (coluna,linha){ getConfirm=false; for(asx=0;asx<valor[0].length;asx++){ if(this.trim(valor[0][asx])==coluna){ return valor[linha][asx]; getConfirm=true; } } if(!getConfirm) { return "get Error (01): A coluna '"+coluna+"' não existe na tabela "+this.table_; } } /*** [end function] ***/ // ------------------------------------------------------------------------------------------------ /*** [init function] #name : getWhere #desc: get from fornecedores where categoria=desenvolvimento get from table_ where coluna_=valor_ ***/ this.getWhere = function(coluna_,valor_,modificador_) { var testGetwhere1=false; valor = []; var fso = new ActiveXObject("Scripting.FileSystemObject"); var file = fso.OpenTextFile(PATH+this.database_+"\\"+this.table_+".cdb",1); if (file.AtEndOfStream) arquivoOriginal=""; else arquivoOriginal=file.ReadAll(); file.Close(); //arquivoOriginal retem todo o arquivo de banco de dados this.numLines=arquivoOriginal.split("\n"); for(a=0;a<this.numLines.length;a++) { valor[a]=this.numLines[a].split("|-$-|"); } //primeiro devemos achar as this.numLiness onde categoria=desenvolvimento for(i=0;i<valor[0].length;i++){ /** valor[0].length retem o total de colunas da nossa tabela **/ //GET telefone if(this.trim(valor[0][i])==coluna_){ numCol=i; /** numero da coluna passada no parametro retorno **/ testGetwhere1=true; } } if(!testGetwhere1) { document.write("getWhere Fatal Error: A coluna "+coluna_+" não existe na tabela "+this.table_); return void(0); } if(modificador_==">") { numLin = []; a=0; for(i=0;i<this.numLines.length;i++){ if(parseInt(this.trim(valor[i][numCol]))>parseInt(valor_)) { a++; numLin[a]=i; /** numLin.length agora retem o total de matches **/ //a++; } } } else if(modificador_==">=") { numLin = []; a=0; for(i=0;i<this.numLines.length;i++){ if(parseInt(this.trim(valor[i][numCol]))>=parseInt(valor_)) { a++; numLin[a]=i; /** numLin.length agora retem o total de matches **/ //a++; } } } else if(modificador_=="<") { numLin = []; a=0; for(i=0;i<this.numLines.length;i++){ if(parseInt(this.trim(valor[i][numCol]))<parseInt(valor_)) { a++; numLin[a]=i; /** numLin.length agora retem o total de matches **/ //a++; } } }else if(modificador_=="<=") { numLin = []; a=0; for(i=0;i<this.numLines.length;i++){ if(parseInt(this.trim(valor[i][numCol]))<=parseInt(valor_)) { a++; numLin[a]=i; /** numLin.length agora retem o total de matches **/ //a++; } } } else { numLin = []; a=0; for(i=0;i<this.numLines.length;i++){ if(this.trim(valor[i][numCol])==valor_) { a++; numLin[a]=i; /** numLin.length agora retem o total de matches **/ //a++; } } } //alert(numLin.length +"|"+ numLin[0] +"|"+ numLin[1]); //alert(this.numLines.length); //agora já sei que tenho que pegar todas as informações da this.numLines 4 e 5 //preciso jogar cada informação dentro de uma variavel ou array que possa ser tratada /* total = get from fornecedores where categoria=desenvolvimento for (i=0;i<total;i++) { nome=total.nome[i]; telefone=total.telefone[i]; write(nome + telefone); } total==numthis.numLines.length */ this.numCols=valor[0].length; this.numLins=numLin.length-1; if(this.numLins<0)this.numLins=0; return numLin; } /*** [end function] ***/ // ------------------------------------------------------------------------------------------------ /* [init function] #name: getAll() #desc: seleciona toda tabela e retorna um array bidimensional com todos os dados puros #return: array bidimensional valor */ this.getAll = function(coluna_,valor_,modificador_) { if(coluna_){ resultado = this.getWhere(coluna_,valor_,modificador_); } else { resultado = this.getWhere("LINE","0",">="); } return valor; } /* [end function] */ // ------------------------------------------------------------------------------------------------ /*** [init function] #name: showTable(); #desc: Mostra toda estrutura da tabela em uma div flutuante; ***/ var showTableControle=true; this.showTable = function() { output_="<input type='button' value=' X ' onClick=\"$('#divOutput').fadeOut('slow')\"><h2>Show Table</h2>Tabela: "+this.table_+"<p>"; output_+="<table id='tableOutput'>"; resultado = this.getWhere("LINE","0",">="); for(lpo=0;lpo<this.numLines.length;lpo++) { output_+="<tr>"; for(lpi=0;lpi<valor[0].length;lpi++) { if(lpi==0) output_+="<td><b>"+valor[lpo][lpi]+"</b></td>"; else output_+="<td>"+valor[lpo][lpi]+"</td>"; } output_+="</tr>"; } output_+="</table>"; if(showTableControle) { //primeira vez $('body').append("<div id='divOutput'></div>"); $('#divOutput').html(output_); showTableControle=false; } else{ //apenas atualiza a div $('#divOutput').html(output_).fadeIn('slow'); } $("#divOutput").css("position","absolute").css("backgroundColor","#eee").css("top",20).css("left",20).css("width","900").css("height","400").css("overflow","auto").css("padding",10).css("margin",10).css("borderColor","red").css("borderBottomWidth","5").css("fontFamily","Calibri"); $("#tableOutput td").css("fontFamily","Courier New").css("fontSize","12px").css("borderBottom", "1px solid #ddd").css("borderLeft", "1px solid #ddd").css("padding","5px"); } /*** [end function] ***/ // ------------------------------------------------------------------------------------------------ /*** [init function] #name: insert(); #desc: insert into table values("..",".."); ***/ this.insert = function(params,html) { var str=""; if(html==true) { for (i=0; i<params.length; i++) { params[i]=params[i].toString().replace(/\n/g,"<br />"); } } for (i=0; i<params.length; i++) { if(i==params.length-1){ str+=params[i]; } else { str+=params[i]+"|-$-|"; } } LINE = this.getWhen(null,"LINE","max")+1; str="\n"+LINE+"|-$-|"+str; //escreve a nova this.numLines no arquivo var fso = new ActiveXObject("Scripting.FileSystemObject"); var file = fso.OpenTextFile(PATH+this.database_+"\\"+this.table_+".cdb",8,-1,0); file.Write(str); file.Close(); } /*** [end function] ***/ // ------------------------------------------------------------------------------------------------ /*** [init function] #name: update(); #desc: update nome(coluna1_)='Black'(valor1_) when id(coluna2_)=6(valor2_) o modificador é opcional para >=,<=,>,< ; se nao for definido será igual o modificar serve apenas para colunas numericas ***/ this.update = function(coluna1_,valor1_,coluna2_,valor2_,modificador) { // --> explode var fso = new ActiveXObject("Scripting.FileSystemObject"); var file = fso.OpenTextFile(PATH+this.database_+"\\"+this.table_+".cdb",1); if (file.AtEndOfStream) arquivoOriginal=""; else arquivoOriginal=file.ReadAll(); file.Close(); //arquivoOriginal retem todo o arquivo de banco de dados this.numLines=arquivoOriginal.split("\n"); for(a=0;a<this.numLines.length;a++) { valor[a]=this.numLines[a].split("|-$-|"); } // <-- explode // --> descobre a coluna nome for(i=0;i<valor[0].length;i++){ if(this.trim(valor[0][i])==coluna1_){ numCol1=i; } } // numCol1 retem o numero da coluna 'nome' for(i=0;i<valor[0].length;i++){ if(this.trim(valor[0][i])==coluna2_){ numCol2=i; } } //numCol2 retem o numero da coluna 'id' // <-- descobre a coluna nome // --> remonta o arquivo var resultadoUpdate=""; for(g=0;g<this.numLines.length;g++) { if(modificador==">") { for(u=0;u<valor[0].length;u++) { //remonta a this.numLines if(u==numCol2) { if(parseInt(this.trim(valor[g][numCol2]))>parseInt(valor2_)) { valor[g][numCol1]=valor1_; } } } } else if(modificador=="<") { for(u=0;u<valor[0].length;u++) { //remonta a this.numLines if(u==numCol2) { if(parseInt(this.trim(valor[g][numCol2]))<parseInt(valor2_)) { valor[g][numCol1]=valor1_; } } } } else if(modificador==">=") { for(u=0;u<valor[0].length;u++) { //remonta a this.numLines if(u==numCol2) { if(parseInt(this.trim(valor[g][numCol2]))>=parseInt(valor2_)) { valor[g][numCol1]=valor1_; } } } } else if(modificador=="<=") { for(u=0;u<valor[0].length;u++) { //remonta a this.numLines if(u==numCol2) { if(parseInt(this.trim(valor[g][numCol2]))<=parseInt(valor2_)) { valor[g][numCol1]=valor1_; } } } } else { for(u=0;u<valor[0].length;u++) { //remonta a this.numLines if(u==numCol2) { if(this.trim(valor[g][numCol2])==valor2_) { valor[g][numCol1]=valor1_; } } } } for(u=0;u<valor[0].length;u++) { if((u==(valor[0].length-1))&&(g==(this.numLines.length-1))){ /** ultima this.numLines e coluna **/ resultadoUpdate+=valor[g][u]; } else if(u==(valor[0].length-1)) { /** ultima coluna **/ resultadoUpdate+=valor[g][u]+"\n"; } else { resultadoUpdate+=valor[g][u]+"|-$-|"; } } } // <-- remonta o arquivo // --> grava o arquivo var fso = new ActiveXObject("Scripting.FileSystemObject"); var file = fso.OpenTextFile(PATH+this.database_+"\\"+this.table_+".cdb",2,-1,0); file.Write(resultadoUpdate); file.Close(); // <-- grava o arquivo } /*** [end function] ***/ // ------------------------------------------------------------------------------------------------ /*** [init function] #name: erase(); #desc: erase e-mail when id=002 ***/ this.erase = function(coluna1_,coluna2_,valor_,modificador) { if(modificador==undefined) this.update(coluna1_,"",coluna2_,valor_); else this.update(coluna1_,"",coluna2_,valor_,modificador); } /*** [end function] ***/ // ------------------------------------------------------------------------------------------------ /*** [init function] #name: delete #desc: deleta uma this.numLines inteira do banco de dados delete when id=004 ***/ this.del = function(coluna_,valor_,modificador) { // --> explode var fso = new ActiveXObject("Scripting.FileSystemObject"); var file = fso.OpenTextFile(PATH+this.database_+"\\"+this.table_+".cdb",1); if (file.AtEndOfStream) arquivoOriginal=""; else arquivoOriginal=file.ReadAll(); file.Close(); //arquivoOriginal retem todo o arquivo de banco de dados this.numLines=arquivoOriginal.split("\n"); for(a=0;a<this.numLines.length;a++) { valor[a]=this.numLines[a].split("|-$-|"); } // <-- explode if(this.numLines.length>0) { // --> descobre a coluna for(i=0;i<valor[0].length;i++){ if(this.trim(valor[0][i])==coluna_){ numCol=i; } } // <-- descobre a coluna // --> remonta o arquivo var resDelete=""; for(g=0;g<this.numLines.length;g++) { //remonta a this.numLines switch(modificador) { default: if(valor[g][numCol]!=valor_) { resDelete+=this.numLines[g]+"\n"; } break; case ">": if(g==0) { resDelete+=this.numLines[g]+"\n"; } else { if(parseInt(valor[g][numCol])<=parseInt(valor_)) { resDelete+=this.numLines[g]+"\n"; } } break; case ">=": if(g==0) { resDelete+=this.numLines[g]+"\n"; } else { if(parseInt(valor[g][numCol])<parseInt(valor_)) { resDelete+=this.numLines[g]+"\n"; } } break; case "<": if(g==0) { resDelete+=this.numLines[g]+"\n"; } else { if(parseInt(valor[g][numCol])>=parseInt(valor_)) { resDelete+=this.numLines[g]+"\n"; } } break; case "<=": if(g==0) { resDelete+=this.numLines[g]+"\n"; } else { if(parseInt(valor[g][numCol])>parseInt(valor_)) { resDelete+=this.numLines[g]+"\n"; } } break; } } // <-- remonta o arquivo // --> grava o arquivo if(resDelete.substring((resDelete.length-1),resDelete.length)=="\n")resDelete=resDelete.substring(0,(resDelete.length - 1)); var fso = new ActiveXObject("Scripting.FileSystemObject"); var file = fso.OpenTextFile(PATH+this.database_+"\\"+this.table_+".cdb",2,-1,0); file.Write(resDelete); file.Close(); // <-- grava o arquivo // --> corrige a coluna LINE // --> explode var fso = new ActiveXObject("Scripting.FileSystemObject"); var file = fso.OpenTextFile(PATH+this.database_+"\\"+this.table_+".cdb",1); if (file.AtEndOfStream) arquivoOriginal=""; else arquivoOriginal=file.ReadAll(); file.Close(); //arquivoOriginal retem todo o arquivo de banco de dados this.numLines=arquivoOriginal.split("\n"); for(a=0;a<this.numLines.length;a++) { valor[a]=this.numLines[a].split("|-$-|"); } // <-- explode resultadoUpdate=""; for(j=0;j<this.numLines.length;j++) { for(k=0;k<valor[0].length;k++) { if(k==0) { if(j==0) resultadoUpdate+="LINE|-$-|"; else resultadoUpdate+=j+"|-$-|"; } else { if(k==(valor[0].length-1)) resultadoUpdate+=valor[j][k]; else resultadoUpdate+=valor[j][k]+"|-$-|"; } } resultadoUpdate+="\n"; } //remove o ultimo \n if(resultadoUpdate.substring((resultadoUpdate.length-1),resultadoUpdate.length)=="\n")resultadoUpdate=resultadoUpdate.substring(0,(resultadoUpdate.length - 1)); // <-- corrige a coluna LINE // --> grava o arquivo var fso = new ActiveXObject("Scripting.FileSystemObject"); var file = fso.OpenTextFile(PATH+this.database_+"\\"+this.table_+".cdb",2,-1,0); file.Write(resultadoUpdate); file.Close(); // <-- grava o arquivo } } /*** [end function] ***/ // --------------------------------------------------------------------| // MODULO CDBMyAdmin --------------------------------------------------| // Neste modulo a formula muda, agora o banco deve ser passado por ----| // parâmetro, e não mais por variável estática ------------------------| // --------------------------------------------------------------------| /* [init function] #name: getDatabases(); #desc: usa a função GetFolder para listar todos os subfolders dentro do path PATH. usa a função Enumerator para listar todos usa o for (; !fc.atEnd(); fc.moveNext()) para varrer os subfolders fc.item() retem o caminho completo fc.item().name retem apenas o nome do folder #return: Retorno um array com o nome de todos os folders: bds[]; */ this.getDatabases = function() { var dbs = []; var fso = new ActiveXObject("Scripting.FileSystemObject"); f = fso.GetFolder(PATH); fc=new Enumerator(f.SubFolders); s = 0; for (; !fc.atEnd(); fc.moveNext()) { dbs[s]=fc.item().name; s++; } return dbs; } /* [end function] */ /* [init function] #name: getTables() #desc: Usa GetBaseName em Enumerator(f.files) para listar o nome de cada arquivo .cdb dentro do banco de dados 'db' #pars: string db -> O banco de dados (pasta) selecionado #return: array tbs contendo o nome simples - sem extensão - de cada arquivo dentro da pasta db */ this.getTables = function(db) { var tbs = []; var fso = new ActiveXObject("Scripting.FileSystemObject"); f = fso.GetFolder(PATH+"\\"+db+"\\"); fc=new Enumerator(f.files); s = 0; for (; !fc.atEnd(); fc.moveNext()) { tbs[s]=fso.GetBaseName(fc.item()); s++; } return tbs; } /* [end function] */ /* [init function] #name: renameTable(); #desc: renomeia a tabela tb passado como parametro para newName #pars: string db-->banco , string tb-->tabela, string newName-->novo nome da tabela #return : true; */ this.renameTable = function(db,tb,newName) { var fso = new ActiveXObject("Scripting.FileSystemObject"); f = fso.GetFile(PATH+"\\"+db+"\\"+tb+".cdb"); f.name=newName+".cdb"; return true; } /* [end function] */ /* [init function] #name: renameDatabase(); #desc: renomeia o banco de dados (pasta) passada por parâmetro #pars: string db-->banco, string newName-->novo nome do banco de dados #return : true; */ this.renameDatabase = function(db,newName) { var fso = new ActiveXObject("Scripting.FileSystemObject"); f = fso.GetFolder(PATH+"\\"+db+"\\"); f.name=newName; return true; } /* [end function] */ /* [init function] #name: deleteDatabase() */ this.deleteDatabase = function(db) { var fso = new ActiveXObject("Scripting.FileSystemObject"); f = fso.GetFolder(PATH+"\\"+db); fso.DeleteFolder(f); return true; } /* [end function] */ /* [init function] #name: deleteTable(); */ this.deleteTable = function(db,tb){ var fso = new ActiveXObject("Scripting.FileSystemObject"); f = fso.GetFile(PATH+"\\"+db+"\\"+tb+".cdb"); fso.deleteFile(f); return true; } /* [end function] */ /* [init function] #name: createTable(); */ this.createTable = function(tb,colunas) { var fso = new ActiveXObject("Scripting.FileSystemObject"); try{ f=fso.CreateTextFile(PATH+conexao.database_+"\\"+tb+".cdb",false); f.Write("LINE|-$-|"+colunas.replace(/,/g,"|-$-|")); f.Close(); return "ok"; } catch(e){ return "<hr>Erro: Não foi possivel criar a tabela. Ela já existe?<br>Erro original: "+e.message+"<hr>"; } } /* [end function] */ /*** [init function] #name: createDatabase(); ***/ this.createDatabase = function(db) { var fso = new ActiveXObject("Scripting.FileSystemObject"); try{ f=fso.CreateFolder(PATH+db) return "ok"; } catch(e){ return "<hr>Erro: Não foi possivel criar o banco de dados. Ele já existe?<br>Erro original: "+e.message+"<hr>"; } } } /*** [end function] ***/ // valor[0][0] retem os valores do banco de dados //valor[0][1],[0][2],[0][3] retem os nomes das colunas //valor[1][0],[2][0],[3][0] retem o numero da this.numLines //this.numLines.length retem o total de this.numLiness do banco de dados //valor[0].length retem o total de colunas do banco de dados
true
2f3f1d6350a4c58d3838929ab3f57e33ea9cbde1
JavaScript
Stephaaan/ang_itat_reg_be_server
/src/runners/tokenRemover.runner.js
UTF-8
386
2.8125
3
[]
no_license
const state = require("../state/state"); module.exports = () => { const oldTokens = state("tokens"); const newTokens = [] oldTokens.forEach(token => { console.log("kukame tokeny"); if(Date.now() < token.validUntil){ console.log("ma to nevymazat"); newTokens.push(token) } }) state("tokens", newTokens); }
true
367bd81d8c8030f13ab3c58460691880e1d7bdf4
JavaScript
vbuzato/tic-tac-toe
/src/components/Board.jsx
UTF-8
847
2.65625
3
[]
no_license
import React from 'react'; class Board extends React.Component { render() { const { board, play, resetGame } = this.props; return ( <div className="board"> {board.map((_, index,) => { let option, choice, choose = ''; if (board[index] !== 'E') { choice = board[index]; option = 'inactive'; choose = () => {console.log('not allowed')}; } else { choose = (e, index) => play(e, index); } return ( <div onClick={(e) => choose(e, index)} key={`${index}`} id={`${index}`} className={`box pos${index} ${option}`}> <span className="bt-choice">{choice}</span> </div> )} )} <button onClick={resetGame}>Reset game</button> </div> ); } } export default Board;
true
430aa5b3f54e2ea358276ae2f5eca07e961c897a
JavaScript
jsera/gatest
/public/js/resultview.js
UTF-8
2,379
2.84375
3
[]
no_license
var ResultView = function(controller, resultModel) { this.controller = controller; this.model = resultModel; this.element = document.createElement("div"); this.favorited = false; this.details = null; this.init(); }; (function() { ResultView.prototype.init = function() { var scope = this; var favorites = this.controller.getFavorites(); var templates = this.controller.getTemplates(); var search = this.controller.getSearch(); this.element = templates.getResult(this.model.Title, this.model.imdbID); var title = this.element.getElementsByClassName("movie_title")[0]; title.onclick = addPreventDefault(function() { if (scope.details == null) { // We want a spinner var spinner = templates.getSpinner(); scope.element.appendChild(spinner); // Kick it off search.onSearchSuccess = function(searchObj) { scope.element.removeChild(spinner); scope.details = new DetailsView(scope.controller, searchObj.response); scope.element.appendChild(scope.details.element); }; search.onSearchError = function(searchObj) { scope.element.removeChild(spinner); var error = templates.getError("Couldn't load details!"); scope.element.appendChild(error); }; search.getDetails(scope.model); } }, scope); var like = this.element.getElementsByClassName("like")[0]; this.favorited = favorites.getFaveByID(this.model.imdbID); if (this.favorited) { // In a production app, you'd never hardcode things like this, instead, // you'd get it from a localization dictionary or something similar. like.innerHTML = "Liked!"; } like.onclick = addPreventDefault(function() { if (!scope.favorited) { like.innerHTML = "Liked!"; scope.favorited = true; favorites.favorite(this.model); } }, scope); }; ResultView.prototype.getElement = function() { return this.element; }; })();
true
9be4637f7a68581d09d505382c64ba93e9cb3cf1
JavaScript
LL0814/microCourseOnine
/static/assets/javascripts/profile.js
UTF-8
4,463
2.578125
3
[]
no_license
//upload header image $("#uploadHeadImg").on('change', function(){ var file = document.querySelector("#uploadHeadImg").files[0]; var min_width = 150; var min_height = 150; if (file && /\.(jpe?g|png|gif)$/i.test(file.name) ) { //读取图片数据 var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function (e) { var data = e.target.result; //加载图片获取图片真实宽度和高度 var image = new Image(); image.onload=function(){ var width = this.width; var height = this.height; ifPreview(width, min_width, height, min_height, data, file, "headImg","head"); }; image.src= data; }; } else{ alert('格式不正确'); } }); $("#update-password").on('click', function () { var password = $("#password").val(); var repassword = $("#password-confirmation").val(); var pwdpattern = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,21}$/; var step = 1; if (step == 1) { if (password == "" || password == null) { danger("errorTips", "密码不能为空"); } else { step = 2; } } if (step == 2) { if (pwdpattern.test(password) == false) { danger("errorTips", "密码由6-21字母和数字组成,不能是纯数字或纯英文"); } else { step = 3; } } if (step == 3) { if (password != repassword) { danger("errorTips", "两次密码不匹配"); } else { step = 4; } } if (step == 4) { $.ajax({ type: "POST", url: "/profile/", data: { 'password': repassword, 'action':'resetpassword' }, headers: { 'X-CSRFToken': $.cookie('csrftoken') }, async: true, error: function (request) { danger("errorTips", "对不起, 修改密码失败, 请稍后再试"); }, success: function (callback) { if(callback == 'success'){ window.location.href = '/profile/'; }else{ danger("errorTips", '对不起, 修改密码失败, 请稍后再试'); } } }); } }); $('#profile-save').on('click', function() { let nickname = $('#nickname').val(); let teacherId = $('#select-teacher').val(); let gradeId = Number($('#select-grade').val()); let classId = Number($('#select-class').val()); $.ajax({ type: "POST", url: "/profile/", data: { 'nickname': nickname, 'teacherId': teacherId, 'gradeId': gradeId, 'classId': classId, 'action':'editprofile' }, headers: { 'X-CSRFToken': $.cookie('csrftoken') }, async: true, error: function (request) { danger("errorTips", "对不起, 编辑失败, 请稍后再试"); }, success: function (callback) { if(callback == 'success'){ window.location.href = '/profile/'; }else{ danger("errorTips", '对不起, 编辑失败, 请稍后再试'); } } }); }); function danger(tid, tips) { $("#" + tid).removeClass('hidden').text(tips); } function removeTips(tid) { $("#" + tid).addClass("hidden"); } function ifPreview(width, min_width, height, min_height, data, file, id, prefix){ if(width < min_width || height < min_height){ alert("请上传宽度大于 "+min_width+"px,高度大于 "+min_height+"px 的封面图片。"); } else{ //preview and update $("#"+id).attr("src", data); imgUpload(file, prefix); } } function imgUpload(file, prefix) { var formData = new FormData(); formData.append("imgFile", file); formData.append("prefix", prefix); ajax(formData, "/upload_imgs/"); } function ajax(formData, URL){ $.ajax({ type:'POST', url: URL, data: formData, headers: { 'X-CSRFToken': $.cookie('csrftoken') }, processData: false, contentType: false, async: false, success: function(callback) { window.location.reload(); } }); } //proile update
true
fa1eb66e25522389883bb9e1d161f62636ff04d9
JavaScript
ItsJuice/quizzlr
/app/assets/javascripts/quizzlr/quiz/quiz-functions.js
UTF-8
7,398
2.96875
3
[ "MIT" ]
permissive
$(function() { // // // ***** Control progress bar ***** // // function updateProgress(percentage) { // Set progress bar's width and update text to the correct percentage $('#msch-progress').css('width', '' + percentage + '%'); $('#msch-progress_text').html('' + percentage + '% Complete'); } // // // ***** Reset progress bar ***** // // updateProgress(0); // // // ***** Scroll around the quiz ***** // // function scrollQuiz(location) { // Variables for scrolling amounts and duration // Ideally Sharepoint should scroll to an element's position not by a set amount, in case the Sharepoint layout ever changes var duration = 600; var sharepointTop = 450; var sharepointBottom = 2000; // Top or bottom of quiz? switch (location) { // Top of questions, for new page case 'top' : // Target different elements based on whether you're inside Sharepoint or not if ($('#s4-workspace').length > 0) { // Sharepoint $('#s4-workspace').animate({scrollTop: sharepointTop}, duration); } else { // Local $('html, body').animate({scrollTop: $('#quiz-top').offset().top}, duration); } break; // Bottom of quiz, to see Next buttons case 'bottom' : // Target different elements based on whether you're inside Sharepoint or not if ($('#s4-workspace').length > 0) { // Sharepoint $('#s4-workspace').animate({scrollTop: sharepointBottom}, duration); } else { // Local $('html, body').animate({scrollTop: $('#quiz-bottom').offset().top}, duration); } break; } } // count how many steps there are var step_count = $('div[id*="step-"]').size(); $('input[id*="submit_"]').click(function(e) { //prevent default link behaviour e.preventDefault(); //console.log("button clicked " + this.id); next_step(this.id.substring(7)) }); // hide everything that needs hiding for the initial step $('div[id*="step-"]').hide(); $('#results').hide(); $( ".progress-wrap" ).css("display", "none"); $( "#start-quiz" ).click(function(e) { // Prevent the link executing e.preventDefault(); first_step(); }); function first_step() { $('#intro').fadeOut('fast'); window.setTimeout(function(){ $('#step-1').fadeIn('slow'); $( ".progress-wrap" ).fadeIn('slow'); }, 200); } function next_step(current_step) { var progress = Math.round(current_step * (100 / step_count)); // Show your progress updateProgress(progress); $('#step-'+current_step).fadeOut('fast'); if(current_step < step_count) { // Remove screen 1, show screen 2 var t = window.setTimeout(function(){ $('#step-'+(eval(current_step)+1)).fadeIn('slow'); }, 200); } else { //console.log("Doing final step"); final_step(); } } function final_step() { $("#quiz_form").bind("ajax:success", function(evt, data, status, xhr){ //this assumes the action returns an HTML snippet handle_results(data.correct_answers); }).bind("ajax:error", function(evt, data, status, xhr){ //do something with the error here }); $('#quiz_form').submit(); } function handle_results(correctAnswers) { var totalAnswers = step_count; // You now know how many answer there are and how many you got right, so turn that into a percentage var percentageCorrect = Math.round((correctAnswers / totalAnswers) * 100); // Pass mark is 70% - show pass or fail message if (percentageCorrect >= 70) { // Set pass title and score message $('#quiz-results-message').html('Well done!'); $('#quiz-results-text').html('You scored ' + percentageCorrect + '% - you obviously paid attention and have successfully passed the quiz!'); // Submit score (pass) MySiteQuizSubmit(percentageCorrect, true); // You've passed, so no need to show the Try Again button $('#quiz-retry-button').hide(); } else { // Set failure title and score message //$('#quiz-results-message').html('So close!'); //$('#quiz-results-text').html("You scored " + percentageCorrect + "%"); $('#quiz-results-text').html("<h3>You scored <span class=\"large\">" + percentageCorrect + "%</span> " + "(" + correctAnswers + "/" + totalAnswers + ")</h3>"); $('#quiz-attempts-text').html("<h3>YOU HAVE 3 ATTEMPTS LEFT</h3>"); //$('#quiz-results-text').html("<h4>You scored " + percentageCorrect + "%</h3>"); //$('#quiz-attempts-text').html("<h3>You have 3 attempts remaining</h4>"); // Submit score (fail) MySiteQuizSubmit(percentageCorrect, false); // Make sure the Try Again button is visible $('#quiz-retry-button').show(); } // Remove screen X, show screen X+1 $('#results').slideDown(); // Remove the progress bar $('#msch-progress_bar').hide(); } // // // ***** Disable the quiz page submit buttons until you've answered enough questions on each page ***** // // $('.msch-quiz-button').attr('disabled', 'disabled'); $('.msch-quiz-button').addClass('msch-quiz-button-disabled'); $('.msch-quiz-button').fadeTo(0, 0.5); // Reverse the above for the Try Again button at the end of the quiz $('#quiz-retry-button').removeAttr('disabled'); $('#quiz-retry-button').removeClass('msch-quiz-button-disabled'); $('#quiz-retry-button').fadeTo(0, 1); // // // ***** Watch for the user clicking an answer radio button to count answers on each page ***** // // // Select all radio buttons the user could click to answer var answerCheckRadioButtons = $('#msch-container input[type=radio]'); // Add a click action to them answerCheckRadioButtons.on('click', function() { var answerCounter = $('#msch-container input[type=radio]:checked').size(); var numberOfQuestionsPerPage = 1; var targetQuizPage = answerCounter / numberOfQuestionsPerPage; var targetButton = $('#submit_' + targetQuizPage); // Turn that target into an addressable submit button, then remove the disabled class from that button // If you have the correct button, switch it back on and remove the disabled classes if (targetButton) { targetButton.removeAttr('disabled'); targetButton.removeClass('msch-quiz-button-disabled'); targetButton.fadeTo(0, 1); // Kill the reference to the target button, ready for the next click targetButton = null; } }); });
true
0d19111d92250b607d509301fd4500e3298c30ea
JavaScript
CSA-DanielVillamizar/voteomatic
/resources/js/mixins/meetingMixin.js
UTF-8
1,166
2.625
3
[]
no_license
/** * For any component that needs access to the * current meeting. * * @type {{computed: {}}} */ module.exports = { data: function () { return { linkBase: "https://voteomatic.com/lti-entry/" } }, computed: { /** * The current global meeting */ meeting: { get : function(){ return this.$store.getters.getActiveMeeting; }, set : function(v){ this.$store.commit('setMeeting', v); } }, /** * The link that the user will enter into * canvas */ meetingLink: { get: function () { return this.linkBase + this.meeting.id; }, default: false }, meetingName: function () { if (_.isUndefined(this.meeting) || _.isNull(this.meeting)) return ''; return this.meeting.name; }, meetingDate: function () { if (_.isUndefined(this.meeting) || _.isNull(this.meeting)) return ''; return this.meeting.readableDate(); }, } };
true
4c84362c7bf6b37f9dfaa5a577f195af642adbec
JavaScript
alermar69/StairsGit
/StairsGit/JavaScript/work/calculator/timber_stock/change_offer.js
UTF-8
20,884
2.5625
3
[]
no_license
function changeOffer() { var stairModel = params.stairModel; var model = params.model; /*меняем главное описание*/ if (model == "тетивы") { document.getElementById('description').innerHTML = "<p>Изящная полностью деревянная лестница в классическом стиле." + "Лестница изготавливается из клееного мебельного щита высочайшего качества." + "Каркас лестницы - две клееные деревянные балки с пазами, в которые устанавливаются ступени." "Пазы фрезеруются на специализированном фрезерном станке с программным управлением, что обеспечивает" + "идеальную точность размеров, аккуратность соединений и отсутствие скрипов во время эксплуатации." + "Лестница отличается высочайшим качеством изготовления, использованием натуральных экологичных материалов" + "и великолепным современным дизайном. Предназначена для установки внутри помещения в частных домах и квартирах." + "</p>" + "<h2>Особенности модели</h2>" + "<ul class='galka'>" + "<li>Надежная конструкция выдерживает нагрузку до 400 кг;</li>" + "<li>Лестница красится в заводских условиях в выбранный Вами цвет;</li>" + "<li>Лестница идеально подойдет Вам, так как изготавливается на заказ под Ваш размер;</li>" + "<li>Лестница изготавливается на автоматическом оборудовании, что обеспечивает высочайшую точность и качество всех деталей;</li>" + "<li>Продуманная конструкция позволяет собрать и установить лестницу на объекте за 3-4 часа.;</li>" + "</ul>"; } if (model == "косоуры") { document.getElementById('description').innerHTML = "<p>Классическая полностью деревянная лестница на косоурах." + "Лестница изготавливается из клееного мебельного щита высочайшего качества. " + "Каркас лестницы - две клееные деревянные балки с вырезами, в которые устанавливаются ступени. " + "Косоуры изготавливаюстя на специализированном фрезерном станке с программным управлением, что обеспечивает" + "идеальную точность размеров, аккуратность соединений и отсутствие скрипов во время эксплуатации." + "Лестница отличается высочайшим качеством изготовления, использованием натуральных экологичных материалов" + "и строгим классическим дизайном. Предназначена для установки внутри помещения в частных домах и квартирах." + "</p>" + "</p>" + "<h2>Особенности модели</h2>" + "<ul class='galka'>" + "<li>Надежная конструкция выдерживает нагрузку до 400 кг;</li>" + "<li>Лестница красится в заводских условиях в выбранный Вами цвет;</li>" + "<li>Лестница идеально подойдет Вам, так как изготавливается на заказ под Ваш размер;</li>" + "<li>Лестница изготавливается на автоматическом оборудовании, что обеспечивает высочайшую точность и качество всех деталей;</li>" + "<li>Продуманная конструкция позволяет собрать и установить лестницу на объекте за 3-4 часа.;</li>" + "</ul>"; } if (model == "тетива+косоур") { document.getElementById('description').innerHTML = "<p>Классическая полностью деревянная лестница на косоурах." + "Лестница изготавливается из клееного мебельного щита высочайшего качества." + "Каркас лестницы - две клееные деревянные балки с вырезами, в которые устанавливаются ступени." "Косоуры изготавливаюстя на специализированном фрезерном станке с программным управлением, что обеспечивает" + "идеальную точность размеров, аккуратность соединений и отсутствие скрипов во время эксплуатации." + "Лестница отличается высочайшим качеством изготовления, использованием натуральных экологичных материалов" + "и строгим классическим дизайном. Предназначена для установки внутри помещения в частных домах и квартирах." + "</p>" + "</p>" + "<h2>Особенности модели</h2>" + "<ul class='galka'>" + "<li>Надежная конструкция выдерживает нагрузку до 400 кг;</li>" + "<li>Лестница красится в заводских условиях в выбранный Вами цвет;</li>" + "<li>Лестница идеально подойдет Вам, так как изготавливается на заказ под Ваш размер;</li>" + "<li>Лестница изготавливается на автоматическом оборудовании, что обеспечивает высочайшую точность и качество всех деталей;</li>" + "<li>Продуманная конструкция позволяет собрать и установить лестницу на объекте за 3-4 часа.;</li>" + "</ul>"; } //complectDescription(); } function complectDescription(){ /*конструкция*/ var stairModel = params.stairModel; var model = params.model; var metalPaint = params.metalPaint; var carcasText_3; var carcasText_4; var carcasImage; if (stairModel == "Прямая") carcasImage = "001.jpg"; if (stairModel == "Г-образная с площадкой") carcasImage = "002.jpg"; if (stairModel == "Г-образная с забегом") carcasImage = "004.jpg"; if (stairModel == "П-образная с площадкой") carcasImage = "003.jpg"; if (stairModel == "П-образная с забегом") carcasImage = "005.jpg"; if (stairModel == "П-образная трехмаршевая") carcasImage = "005.jpg"; //document.getElementById('carcasImage').innerHTML = "<a href='/calculator/new_calc/images/carcas/" + carcasImage + "' rel='fancy'><img src='/calculator/new_calc/images/carcas/" + carcasImage + "' width='300px'></a>"; if (model == "лт") carcasText_3 = "Каркас остается видимым, подчеркивая оригинальность дизайна;"; if (model == "ко") carcasText_3 = "Каркас можно легко и быстро обшить гипсокартоном, построить под лестницей стенку или оставить видимым;"; if (metalPaint == "нет") carcasText_4 = "Детали каркаса поставляются зачищенными и подготовленными под покраску;"; if (metalPaint == "грунт") carcasText_4 = "Детали каркаса поставляются покрытыми антикоррозийным гнутом;"; if (metalPaint == "порошок") carcasText_4 = "Каркас покрываются красивой, прочной и долговечной порошковой краской;"; if (metalPaint == "автоэмаль") carcasText_4 = "Для идеального внешнего вида, детали каркаса шпаклюются, шлифуются и покрываются высокоглянцевой автомобильной эмалью в 3 слоя;"; document.getElementById('carcasText_3').innerHTML = carcasText_3; document.getElementById('carcasText_4').innerHTML = carcasText_4; /*ступени*/ setTreadDescr(); /*ограждения*/ var railingModel = document.getElementById('railingModel').options[document.getElementById('railingModel').selectedIndex].value; var handrail = document.getElementById('handrail').options[document.getElementById('handrail').selectedIndex].value; var rackType = null;//document.getElementById('banisterMaterial').options[document.getElementById('banisterMaterial').selectedIndex].value; var rigelMaterial = null;//document.getElementById('rigelMaterial').options[document.getElementById('rigelMaterial').selectedIndex].value; var rigelAmt = null;//document.getElementById('rigelAmt').options[document.getElementById('rigelAmt').selectedIndex].value; var railingMetalPaint; var railingTimberPaint; var railingHeader; var railingImage; var railingText_1; var railingText_2; var railingText_3; var railingText_4; var railingText_5; var railingText_6; /*поручень*/ if (handrail == "40х20 черн."){ railingText_2 = "Поручень из профильной трубы 40х20мм из конструкционной стали"; railingMetalPaint = "сталь"; } if (handrail == "40х40 черн."){ railingText_2 = "Поручень из профильной трубы 40х40мм из конструкционной стали"; railingMetalPaint = "сталь"; } if (handrail == "60х30 черн."){ railingText_2 = "Поручень из профильной трубы 60х30мм из конструкционной стали"; railingMetalPaint = "сталь"; } if (handrail == "кованый полукруглый"){ railingText_2 = "Кованый полукруглый поручень подчеркивает оригинальность ограждений;"; railingMetalPaint = "сталь"; } if (handrail == "40х40 нерж."){ railingText_2 = "Поручень из квадратной нержавеющей трубы 40х40мм подчеркивает оригинальность ограждений;"; } if (handrail == "Ф50 нерж."){ railingText_2 = "Поручень из круглой нержавеющей трубы подчеркивает оригинальность ограждений;"; } if (handrail == "Ф50 сосна"){ railingText_2 = "Круглый поручень из массива сосны теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;"; railingTimberPaint = "дерево"; } if (handrail == "омега-образный сосна"){ railingText_2 = "Классический фигурный поручень из массива сосны теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;"; railingTimberPaint = "дерево"; } if (handrail == "50х50 сосна"){ railingText_2 = "Квадратный поручень из массива сосны теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;"; railingTimberPaint = "дерево"; } if (handrail == "40х60 береза"){ railingText_2 = "Прямоугольный поручень из массива березы теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;"; railingTimberPaint = "дерево"; } if (handrail == "омега-образный дуб"){ railingText_2 = "Классический фигурный поручень из массива дуба теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;"; railingTimberPaint = "дерево"; } if (handrail == "40х60 дуб"){ railingText_2 = "Прямоугольный поручень из массива дуба теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;"; railingTimberPaint = "дерево"; } if (handrail == "40х60 дуб с пазом"){ railingText_2 = "Прямоугольный поручень из массива дуба теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;"; railingTimberPaint = "дерево"; } if (handrail == "Ф50 нерж. с пазом"){ railingText_2 = "Круглый нержавеющий поручень подчеркивает оригинальность ограждений;"; } if (handrail == "40х60 нерж. с пазом"){ railingText_2 = "Прямоугольный нержавеющий поручень подчеркивает оригинальность ограждений;"; } if (handrail == "нет"){ railingText_2 = "Отсутствие поручня подчеркивает оригинальность ограждений;"; } if (handrail == "сосна"){ railingText_2 = "Прямоугольный поручень из массива сосны теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;"; railingTimberPaint = "дерево"; } if (handrail == "береза"){ railingText_2 = "Прямоугольный поручень из массива березы теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;"; railingTimberPaint = "дерево"; } if (handrail == "лиственница"){ railingText_2 = "Прямоугольный поручень из массива лиственницы теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;"; railingTimberPaint = "дерево"; } if (handrail == "дуб паркет."){ railingText_2 = "Прямоугольный поручень из массива дуба теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;"; railingTimberPaint = "дерево"; } if (handrail == "дуб ц/л"){ railingText_2 = "Прямоугольный поручень из массива дуба теплый и приятный на ощупь подчеркивает оригинальный дизайн ограждений;"; railingTimberPaint = "дерево"; } if (handrail == "ПВХ"){ railingText_2 = "Круглый поручень из ПВХ, теплый и приятный на ощупь, подчеркивает оригинальный дизайн ограждений;"; railingTimberPaint = "дерево"; } if (railingModel == "Ригели") { railingHeader = "Ограждения с ригелями"; railingText_1 = "Изящные минималистичные ограждения с горизонтальным заполнением (ригелями)"; railingImage = "001.jpg"; if (rackType == "40х40 черн.") { railingText_3 = "Стойки из квадратной профильной трубы 40х40мм из конструкционной стали"; railingMetalPaint = "сталь"; } if (rackType == "40х40 нерж+дуб") { railingText_3 = "Стойки квадратного сечения из нержавейки со вставками из массива дуба;"; railingTimberPaint = "дерево"; } if (rackType == "40х40 нерж.") { railingText_3 = "Стойки из профильной трубы 40х40мм из полированной нержавеющей стали;"; } if (rigelMaterial == "20х20 черн.") { railingText_4 = "Ригеля из квадратной 20х20мм из конструкционной стали, " + rigelAmt + "шт.;" railingMetalPaint = "сталь"; } if (rigelMaterial == "Ф12 нерж.") { railingText_4 = "Ригеля из круглой неравеющей трубки Ф12мм, " + rigelAmt + "шт.;" } if (rigelMaterial == "Ф16 нерж."){ railingText_4 = "Ригеля из круглой неравеющей трубки Ф16мм, " + rigelAmt + "шт.;" } } if (railingModel == "Стекло на стойках") { railingHeader = "Стеклянные ограждения на стойках"; railingText_1 = "Ограждения в современном стиле со стеклом, установенным между стойкаи"; railingImage = "003.jpg"; if (rackType == "40х40 черн.") { railingText_3 = "Квадратные стойки из конструкционной стали сечением 40х40"; railingMetalPaint = "сталь"; } if (rackType == "40х40 нерж+дуб") { railingText_3 = "Стойки квадратного сечения из нержавейки со вставками из массива дуба;"; railingTimberPaint = "дерево"; } if (rackType == "40х40 нерж.") { railingText_3 = "Стойки квадратного сечения из полированной нержавеющей стали;"; } railingText_4 = "Между стойками устанавливается закаленное стекло толщиной 8мм;" } if (railingModel == "Самонесущее стекло") { railingHeader = "Стеклянные ограждения без стоек"; railingText_1 = "Стильные полностью стеклянные ограждения. Толстое закаленное стекло крепится прямо к торцу марша"; railingImage = "004.jpg"; railingText_3 = "Ограждение из толстого закаленного стекла толщиной 12мм;" railingText_4 = ""; } if (railingTimberPaint == "дерево"){ if (timberPaint == "нет") railingText_6 = "Деревянные детали ограждений поставляются отшлифованными и подготовленными к покраске"; if (timberPaint == "лак") railingText_6 = "Деревянные детали ограждений покрываются прозрачным лаком"; if (timberPaint == "морилка+лак") railingText_6 = "Деревянные детали ограждений тонируются в выбранный Вами цвет и покрываются лаком"; } document.getElementById('railingHeader').innerHTML = railingHeader; document.getElementById('railingImage').innerHTML = "<a href='/calculator/new_calc/images/railing/lt/" + railingImage + "' rel='fancy'><img src='/calculator/new_calc/images/railing/lt/" + railingImage + "' width='300px'></a>"; document.getElementById('railingText_1').innerHTML =railingText_1; document.getElementById('railingText_2').innerHTML =railingText_2; document.getElementById('railingText_3').innerHTML =railingText_3; document.getElementById('railingText_4').innerHTML =railingText_4; document.getElementById('railingText_5').innerHTML =railingText_5; document.getElementById('railingText_6').innerHTML =railingText_6; if (!railingText_4) document.getElementById('railingText_4').style.display = "none"; else document.getElementById('railingText_4').style.display = "list-item"; if (!railingText_5) document.getElementById('railingText_5').style.display = "none"; else document.getElementById('railingText_5').style.display = "list-item"; if (!railingText_6) document.getElementById('railingText_6').style.display = "none"; else document.getElementById('railingText_6').style.display = "list-item"; }
true
ee5b0b3da4f94fbff31cbaf05db6acea9485376f
JavaScript
LoriWinston/lab-04-pokemon-api
/src/Components/Sort.js
UTF-8
738
2.546875
3
[]
no_license
// import React, { Component } from 'react' // import pokeData from '../Data' // export default class Sort extends Component { // render() { // return ( // <select // value={this.props.currentValue} // onChange={this.props.handleChange} // > // { // // we are passed an array of options from the parent // this.props.options.sort( // // for each list item // (a, b) => a[this.props.pokemon].localeCompare(b[this.props.pokemon]) // console.log(this.props.pokemon, 'HELP') // ) // } // </select> // ) // } // }
true
71543857d7cc2a259e012b8f966e149b0bd37ecb
JavaScript
karanaso/node-cluster-phrases
/specs/unit/source/phrasesAssessor.spec.js
UTF-8
4,406
2.796875
3
[]
no_license
const should = require('should'); const rewire = require('rewire'); const os = require('os'); const phrasesAssessor = rewire('../../../source/phrasesAssessor'); describe('phrasesAssessor.js', () => { let textData; beforeEach(() => { textData = 'hypertensive disorder' + os.EOL + 'acid reflosux' + os.EOL + 'gastritus'; }); describe('textDataToArray', () => { it('should be an empyt array if no data are present', () => { const textDataToArray = phrasesAssessor.__get__('textDataToArray'); textDataToArray().should.have.length(0); }); it('should return an array with three objects', () => { const textDataToArray = phrasesAssessor.__get__('textDataToArray'); const expectedResult = ['hypertensive disorder', 'acid reflosux', 'gastritus']; textDataToArray(textData).should.have.length(3); }); it('first item should be "hypertensive disorder"', () => { const textDataToArray = phrasesAssessor.__get__('textDataToArray'); textDataToArray(textData)[0].should.equal('hypertensive disorder') }); it('second item should be "acid reflosux"', () => { const textDataToArray = phrasesAssessor.__get__('textDataToArray'); textDataToArray(textData)[1].should.equal('acid reflosux'); }); it('third item should be "gastritus"', () => { const textDataToArray = phrasesAssessor.__get__('textDataToArray'); textDataToArray(textData)[2].should.equal('gastritus'); }); }); describe('transformToObj', () => { let transformToObj; let obj; beforeEach(() => { transformToObj = phrasesAssessor.__get__('transformToObj'); obj = phrasesAssessor.__get__('obj'); }); it('should create an internal object "obj" to hold keys and values', () => { transformToObj(['a b c']); obj.should.exist; Object.keys(obj).should.have.length(1); }); it('should replace spaces with underscore', () => { transformToObj(['a b c']); obj['a_b_c'].should.exist; }); it('should set the value to 0 to for a non existing key', () => { transformToObj(['a b c']); obj['a_b_c'].should.equal(0); }); it('should not increase the value of a key if found twice', () => { transformToObj(['a b c']); transformToObj(['a b c']); obj['a_b_c'].should.equal(0); }); }); describe('prepareData', () => { it('should prepare the data for processing into obj', () => { const obj = phrasesAssessor.prepareData(textData); Object.keys(obj).should.have.length(4); obj['a_b_c'].should.equal(0);; obj['hypertensive_disorder'].should.equal(0); obj['acid_reflosux'].should.equal[0]; obj['gastritus'].should.equal(0); }); }); describe('increaseCounterForKeys', () => { it('should increase counters for ["gastritus","hypertensive_disorder"]', () => { const increaseCounterForKeys = phrasesAssessor.__get__('increaseCounterForKeys'); const obj = phrasesAssessor.__get__('obj'); increaseCounterForKeys(["gastritus", "hypertensive_disorder"]); obj['gastritus'].should.equal(1); obj['hypertensive_disorder'].should.equal(1); }); }); describe('underScoresToSpaces', () => { it('should return "hypertensive disorder" for key ["hypertensive_disorder"]', () => { const underScoresToSpaces = phrasesAssessor.__get__('underScoresToSpaces'); const obj = phrasesAssessor.__get__('obj'); underScoresToSpaces(["hypertensive_disorder"])[0].should.equal('hypertensive disorder') }); }); describe('assessPhrase', () => { it('should return only "gastritus" from phrase "I have gastritus"', () => { phrasesAssessor.assessPhrase('I have gastritus')[0].should.equal('gastritus'); }); it('should return only "hypertensive_disorder" phrase "I have hypertensive disorder"', () => { phrasesAssessor.assessPhrase('I have hypertensive disorder')[0].should.equal('hypertensive disorder'); }); it('should return ["gastritus","hypertensive disorder" from phrase "I think I gastritus and hypertensive disorder"', () => { const phrase = "I think I gastritus and hypertensive disorder"; const results = phrasesAssessor.assessPhrase(phrase); results.indexOf('hypertensive disorder').should.be.above(-1); results.indexOf('gastritus').should.be.above(-1); }); }); });
true
4c47f4ceb2979fec9d04472b7333a0f9203c26ae
JavaScript
captain-blue210/typescript-lesson
/function-class/points.js
UTF-8
225
2.703125
3
[]
no_license
var Point = /** @class */ (function () { function Point() { this.x = 0; this.y = 0; } return Point; }()); var pointA = new Point(); var pointB = { x: 2, y: 4 }; var pointC = { x: 5, y: 5, z: 10 };
true
146e2fe6a2fc5585f8bfb7d79208e9854401f7e1
JavaScript
derhuerst/vbb-rest
/lib/to-ndjson-buf.js
UTF-8
310
2.578125
3
[ "ISC" ]
permissive
const toNdjsonBuf = (items) => { const chunks = [] let i = 0, bytes = 0 for (const item of items) { const sep = i++ === 0 ? '' : '\n' const buf = Buffer.from(sep + JSON.stringify(item), 'utf8') chunks.push(buf) bytes += buf.length } return Buffer.concat(chunks, bytes) } export { toNdjsonBuf, }
true
e733b0d37f8bd4e512fcaa59cec834941047c782
JavaScript
kscarrot/involution
/src/leetcode/LC104.js
UTF-8
296
3.234375
3
[ "MIT" ]
permissive
/** * @param {TreeNode} root * @return {number} * @tag tree * @description [二叉树的最大深度](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/) */ var maxDepth = function (root) { if (!root) return 0 return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1 }
true
c763b453c9f07bfe633c47fe12dee7f5f2a6c89b
JavaScript
jike132/doc
/js/func.js
UTF-8
4,473
4.03125
4
[]
no_license
//手写实现call /* 思路: context容错处理 Symbol实现唯一key值 context对象新增唯一key属性,赋值:myCall的调用者 此时this已指向context对象 执行context对象里面的调用者函数 删除添加的唯一key值属性 */ */ Function.prototype.call2 = function (context) { var context = context || window; context.fn = this; var args = []; for(var i = 1, len = arguments.length; i < len; i++) { args.push('arguments[' + i + ']'); } var result = eval('context.fn(' + args +')'); delete context.fn return result; } function test(y,z){ return y+z } console.log(test.call2(this,1,2)); window.name = 'global_name_ts' const object = { name: 'Jake' } Function.prototype.myCall = function (context, ...args) { /*       错误做法:直接 context = context || window       context值为null和undefined的,this会自动指向全局对象       值为数字0、空字符串、布尔值false的this也会指向该原始值的实例对象   */ context = [null, undefined].includes(context) ? window : Object(context) // 给context对象新增一个独一无二的属性以免覆盖原有同名属性,并赋值为:调用者fun函数 console.log('新增属性前:', context); const key = Symbol('call中独一无二的属性') context[key] = this console.log('新增属性后:', context); // 执行context对象里面的fun函数,此时fun函数里面的this指向调用者context const res = context[key](...args)    delete context[key] return res } console.log('-------------------------myCall------------------------------'); fnA() // 直接指向window fnA.myCall(object, 1, 2) //手写实现 apply // (window)全局默认name值 window.name = 'global_name_ts' ​ const object = { name: 'Jake' } ​ Function.prototype.myApply = function (context, args) { context = [null, undefined].includes(context) ? window : Object(context) ​    const key = Symbol('apply中独一无二的属性') context[key] = this ​    const res = context[key](...args) ​    delete context[key] return res } ​ function fnA (...args) { console.log('结果👉', this.name, ...args) } ​ console.log('-------------------------myApply------------------------------'); fnA() // 直接指向window fnA.myApply(object, [1, 2]) //手写实现bind /* 思路: 拷贝调用源:通过变量储存源函数 编写返回函数: 源函数再调用call或者apply函数进行this改向 new判断:通过instanceof判断函数是否通过new调用,来决定绑定的context 绑定this并且传递参数(参数 = myBind调用传参 + 内部返回函数调用传参) 复制源函数的prototype给bindFn 返回内部函数 */ // (window)全局默认name值 window.name = 'global_name_ts' ​ const object = { name: 'Jake' } ​ Function.prototype.myBind = function (context) { context = [null, undefined].includes(context) ? window : Object(context) ​    const that = this; // 指向类数组arguments对象,使用数组的slice方法得到新数组 let args1 = [...arguments].slice(1) // let args1 = Array.prototype.slice.call(arguments, 1); ​    let bindFn = function () { let args2 = [...arguments] // let args2 = Array.prototype.slice.call(arguments); ​ /*         判断this instanceof bindFn是因为原生bind是可以new那个bind后返回的函数的       不是new的情况下this指向才会是context;       */ return that.call(this instanceof bindFn ? this : context, ...args1.concat(args2)); // return that.apply(this instanceof bindFn ? this : context, args1.concat(args2)); } ​ // 复制源函数的prototype给bindFn,因为一些情况下函数没有prototype,比如箭头函数 let Fn = function () { }; Fn.prototype = that.prototype; bindFn.prototype = new Fn(); ​ // 或者 // bindFn.prototype = that.prototype // 但是有修改会被同时改动 // bindFn.prototype = Object.create(that.prototype || Function.prototype) ​    return bindFn; } ​ function fnB (...args) { console.log('结果👉', this.name, ...args); } ​ console.log('-------------------------myBind------------------------------'); fnB() // 直接指向window fnB.myBind(object, 10, 20, 30)(40, 50) // bind函数返回的是一个函数,还需要手动执行
true
92f2dce3624a1017be8f2a0e5cebcef5e201252e
JavaScript
Vlad1m1r95/RubyTaskManager
/app/assets/javascripts/tasks.js
UTF-8
4,146
2.515625
3
[]
no_license
window.onload = function() { let $selects_status = document.querySelectorAll('#status_select') let $selects_assignee = document.querySelectorAll('#assignee_select') let $search = document.querySelector('#search-js') let input = "" let $inputs = document.querySelectorAll('input') const task_name = document.querySelector('#task_name') const task_status = document.querySelector('#task_status') if(task_name){ task_name.classList.add('form-control') } if(task_status){ task_status.classList.add('form-control') } let select_status = "" let select_assignee = "" if($search){ $search.addEventListener('click' , function(event){ event.preventDefault() $selects_status.forEach((value) => { select_status = value }) $selects_assignee.forEach((value) => { select_assignee = value }) $inputs.forEach((value) => { input = value }) // console.log(select_status.value) // console.log(select_assignee.value) // console.log(input.value) }) } $selects_status.forEach((select) => { select.classList.add('form-control') }) $blocks = document.querySelectorAll('.block') $blocks.forEach((block) => { let $status = block.querySelector('.status') let $date = block.querySelector('.date-js') let $assignee = block.querySelector('.a_form') let $comment = block.querySelector('.comment') if($comment){ $comment.addEventListener('click', function(){ // let link = block.querySelector('.a-comment') // let href = link.getAttribute('href') // // document.location= href // // console.log(href) // window.history.replaceState('page2', 'Title', href); let comment = block.querySelector('.cmtjs') if(comment.style.opacity == 0){ comment.style.transition = ' all 2s'; comment.style.opacity = 1; comment.classList.remove('comment-close') comment.classList.add('comment-open') } else if(comment.style.opacity == 1){ comment.style.opacity = 0; comment.classList.add('comment-close') comment.classList.remove('comment-open') comment.style.transition = '0s'; } }) } if($search){ $search.addEventListener('click' , function(event){ event.preventDefault() console.log($status.innerText) console.log($date.innerText) console.log($assignee.innerText) // if(input.value == undefined){ // input.value = "" // } if( ($status.innerText === select_status.value && $date.innerText === input.value && $assignee.innerText === select_assignee.value) || ( input.value == "" && $status.innerText === select_status.value && select_assignee.value == "") || (input.value == "" && $status.innerText === select_status.value && $assignee.innerText === select_assignee.value) || ($date.innerText === input.value && $status.innerText === select_status.value && select_assignee.value == "")) { block.classList.add('show') block.classList.remove('hide') } else { block.classList.add('hide') block.classList.remove('show') } }) } // console.log(select.value) // block.ondblclick = function(){ // let link = block.querySelector('.a-change') // let href = link.getAttribute('href') // console.log(block) // console.log(href) // document.location= href // // return false // } block.addEventListener('dblclick', function(){ link = block.querySelector('.a-change') href = link.getAttribute('href') document.location= href // window.history.pushState('page2', 'Title', href) }) }) //comment // $commentCommunuty = document.querySelector('.community-name') // if($commentCommunuty){ // $commentCommunuty.classList.add("hide") // } };
true
7b6aec39b8833845564220daacabc733646949f3
JavaScript
jealob/todo-list
/controllers/todoController.js
UTF-8
1,972
3
3
[]
no_license
// The controller contains the routes. that is control the request and response flow // require/immport all the dependencies including the model(todo) const express = require("express"); const task = require("../models/todo.js"); const router = express.Router(); // Import handlebars helper module package const hbs = require('handlebars'); // Create helper function to add one a value. To be use in displaying the list of task in task-block.hanldebars hbs.registerHelper('plusone', (val, opts) =>{ return parseInt(val) + 1; }); // Create the routes // get route/ Read router.get("/", function (req, res) { task.all(function (data) { let hbsObject = { tasks: data }; // console.log(hbsObject); res.render("index", hbsObject); }); }); // Post route/ Create router.post("/api/tasks", function (req, res) { task.create(["task", "complete"], [req.body.task, req.body.complete], function (result) { res.json({ id: result.insertId }); } ); }); // Put Route /Update router.put("/api/tasks/:id", function (req, res) { let condition = "id = " + req.params.id; // console.log("condition", condition); task.update({ complete: req.body.complete }, condition, function (result) { if (result.changedRows == 0) { // If no rows were changed, then the ID must not exist, so 404 return res.status(404).end(); } else { res.status(200).end(); } }); }); // Delete route /delete router.delete("/api/tasks/:id", function(req, res) { var condition = "id = " + req.params.id; task.delete(condition, function(result) { if (result.affectedRows == 0) { // If no rows were changed, then the ID must not exist, so 404 return res.status(404).end(); } else { res.status(200).end(); } }); }); // Export router to server.js module.exports = router;
true
43a38b6abe0af9568df77319bd1590d186220727
JavaScript
ejohann/webpack-eslint
/src/add-image.js
UTF-8
280
2.546875
3
[]
no_license
import Hd from './hd_logo.png'; function addImage(){ const img = document.createElement('img'); img.alt = 'Hanne Digital Logo'; img.width = 300; img.src = Hd; const body = document.querySelector('body'); body.appendChild(img); } export default addImage;
true
afa4316c66f0aa547fa45ecdb2a7983a8e78cff4
JavaScript
JohnVHumes/JohnVHumes_Web
/build/web/js/components/blog.js
UTF-8
8,267
2.515625
3
[]
no_license
function blog(id) { // ` this is a "back tick". Use it to define multi-line strings in JavaScript. var content = ` HW 1 Home Page <p> My web development experience consists of nothing, prior to this class. This is the first time I've worked on anything front end related. </p> <p> In this homework I learned about HTML, CSS, and how to publish a web page. The parts that I found easy were publishing the website, including links and images with html, and styling text with css Positioning elements in CSS is something I need to work on more, and it took me a little bit of time to grasp the system of nesting divs </p> HW 2 Routing &amp; DB <p> I think I briefly had an overview of Microsoft Access in a 100 level computer science class at Delaware County Community College. Until this week, that was the extent of my database exposure, to my memory. However, I'm taking a database class alongside this one, so I'm sure the double database dose will bring me up to speed quickly </p> <p> In this homework I learned how to include and utilize javascript files on my page, how to use javascript to inject html code into a page and have it be displayed, and how to set up and populate a database with MySQL Workbench The parts that I found easy were setting up the database, and writing Select statements I had trouble rewriting the code for routing and dropdowns, so I ended up using the provided template code, with no major tweaks. I ran into a issue wherein the starting page, home.js, wouldn't load initally </p> <ul> <li> To see how my routing works, click on these icons: home, then blog, then home again. </li> <li> To see my database work, click <a href="misc/databaseScreenshots.pdf">here</a>. </li> </ul> HW 3 Web API <p> Maybe unsuprisingly given my prior blog entries, this was my first jaunt into server-side database access code. My, how strange would it be otherwise? As if I'd never touched HTML, CSS, or any sort of database, but had extensive experience in writing database interfaces. That'd definitely be an interesting story to tell the kids, <i>if you had exhausted every other possible story, every topic of conversation, and counted every ceiling tile prior.</i> </p> <ul> <b> Difficulties</b> <li> Setting up tunneling was initally a little tricky </li> <li> I encountered an issue where my JSP files would suddenly and unceremoniously fail to acknowledge the inclusion of the gson library as valid </li> <li> SQL is finicky to the newcomer, and statements assembled over multiple lines of code can be somewhat tricky to bugfix to said newcomer. </li> <br> <b> Not-So-Difficulties</b> <li> The GSON and mySQL connector libraries make a molehill out of a mountain, code complexity-wise </li> <li> The double dose from both this class and Principles of Database Systems is rapidly building my SQL tolerance, and my mySQL tolerance </li> </ul> <p> I've implemented 3 table APIs, the faction table is linked to the web user table which seems important in the context of this and future assignments, but is of dubious use in the table's eventual purpose. <br> The character table is more cogent to the future mechanics of the website, but I couldn't dream up a sensible reason to link it to the web user table. <br> Thus, I've included both for your viewing pleasure. </p> <ul> <li> To see my web users api work, click <a href="webAPIs/listUsersAPI.jsp">here</a>. </li> <li> To see my character table api work, click <a href="webAPIs/listCharacterAPI.jsp">here</a>. </li> <li> To see my faction table api work, click <a href="webAPIs/listFactionsAPI.jsp">here</a>. </li> </ul> <p> Finally, before I forget, click <a href="misc/SQL_errors.docx">here</a> to see the intentionally caused and solved SQL bugs. <br> I fully support this part of the exercise, I feel it made the rest of the project a whole lot easier, and helped me learn a lot. </p> HW 4 Display Data <p> It's nearly 3am while writing this, so I'll keep this entry brief. This week I retrofitted last week's API into being displayed as a nice, neat table, using an ajax call. <ul> <b> Difficulties</b> <li> I spent about 3 hours trying to track down the hole where a JSON parsing call should be </li> <li> The lack of this call caused many functions to flag as invalid, and I spent most of that 3 hours analyzing the symptoms rather than the disease, as it were </li> <li> As this codebase grows, it's a bit of a hunt to find all the places where modifications need to allow new sample code to interface with other databases </li> <li> It took a bit of time to figure out how function scoping works in .js files, for the routing </li> <br> <b> Not-So-Difficulties</b> <li> Updating the database tables to include images was a breeze, even though it felt like there should've been a better way to do it </li> </ul> </p> <br> HW5 Tutorial Proposal <ul> <li><a href="tutorial/proposal.pdf">Proposal PDF</a> <hr/></li> <li><a href="tutorial/poc.html">Proof of Concept</a> <hr/></li> </ul> <ul> <b> Difficulties</b> <li> I realized too late in this assignment that I probably should have just done the slideshow homework, I don't feel I've yet sufficiently developed my competency to deliver on this assignment </li> <li> I felt the selection criteria for topics was vague, and attempting to settle on an sufficient sample ate through most of the time and energy I had earmarked for this homework </li> <br> <b> Not-So-Difficulties</b> <li> since poc.html was specified, I didn't have to wrestle with figuring out how to add a page with a unique style sheet and its own scripting into the routing table </li> </ul> </p> HW6 Logon <p> <ul> <b> Difficulties</b> <li> I spent a solid 2 hours trying to fix a bug that was already fixed because I forgot to clear my cache </li> <li> Accidentally uploaded the .java files rather than the .class files, which baffled me for a while </li> <li> Deciding what an API returns and how it should return it is a little mindboggling </li> <br> <b> Not-So-Difficulties</b> <li> Writing the APIs themselves </li> </ul> </p> HW7 Delete <p> <ul> <b> Difficulties</b> <li> Many of my problems at this stage in the game are stemming from my early inconsistent use of naming conventions, I see how important a clean start is now </li> <li> Missing code in my table builder befuddled me for an hour </li> <li> It is a little tough to get my head around everything that is going on in the table builder </li> <br> <b> Not-So-Difficulties</b> <li> This was a pretty easy homework overall, I had time to bring the functionalities of my faction table up to par with users and characters </li> </ul> `; document.getElementById(id).innerHTML = content; }
true
068f721c372ecb3487902ec6d6ba63a126445194
JavaScript
vy-b/FlixList
/project/src/Tests/Movie.test.jsx
UTF-8
3,665
2.5625
3
[]
no_license
import React from 'react'; import {mount} from 'enzyme'; import Movie from '../Components/Movie' import MovieTableEntry from '../Objects/MovieTableEntry' import {BrowserRouter as Router} from 'react-router-dom' describe('Movie.jsx tests', () => { test('Renders without crashing', () => { const wrapper = createWrapper('testTitle', 'testYear', 'testPoster','testPlot','testCast','testRuntime','testGenre','testRated'); }); test('Has proper title.', () => { const movieTitle = 'testTitle'; const wrapper = createWrapper(movieTitle, 'testYear', 'testPoster','testPlot','testCast','testRuntime','testGenre','testRated'); const title = wrapper.find('.title'); expect(title.length).toBe(1); expect(title.at(0).text()).toBe(movieTitle); }) test('Has proper year.', () => { const movieYear = '2021'; const wrapper = createWrapper('testTitle', movieYear, 'testPoster','testPlot','testCast','testRuntime','testGenre','testRated'); const year = wrapper.find('.year'); expect(year.length).toBe(1); expect(year.at(0).text()).toBe(movieYear); }) test('Has proper poster.', () => { const moviePoster = 'testPoster'; const wrapper = createWrapper('testTitle', 'testYear', moviePoster,'testPlot','testCast','testRuntime','testGenre','testRated'); const poster = wrapper.find('.poster'); expect(poster.length).toBe(1); expect(poster.find('img').prop('src')).toBe(moviePoster); }) test('Has proper plot.', () => { const moviePlot = 'testPlot'; const wrapper = createWrapper('testTitle', 'testYear', 'testPoster',moviePlot,'testCast','testRuntime','testGenre','testRated'); const plot = wrapper.find('.plot'); expect(plot.length).toBe(1); expect(plot.at(0).text()).toBe(moviePlot); }) test('Has proper cast.', () => { const movieCast = 'testCast'; const wrapper = createWrapper('testTitle', 'testYear', 'testPoster','testPlot',movieCast,'testRuntime','testGenre','testRated'); const cast = wrapper.find('.cast'); expect(cast.length).toBe(1); expect(cast.at(0).text()).toBe(movieCast); }) test('Has proper runtime.', () => { const movieRuntime = '1h45m'; const wrapper = createWrapper('testTitle', 'testYear', 'testPoster','testPlot','testCast', movieRuntime,'testGenre','testRated'); const runtime = wrapper.find('.runtime'); expect(runtime.length).toBe(1); expect(runtime.at(0).text()).toBe(movieRuntime); }) test('Has proper genre.', () => { const movieGenre = 'testGenre'; const wrapper = createWrapper('testTitle', 'testYear', 'testPoster','testPlot','testCast', 'testRuntime',movieGenre,'testRated'); const genre = wrapper.find('.genre'); expect(genre.length).toBe(1); expect(genre.at(0).text()).toBe(movieGenre); }) test('Has proper rating.', () => { const movieRating = 'PG-13'; const wrapper = createWrapper('testTitle', 'testYear', 'testPoster','testPlot','testCast', 'testRuntime','testGenre',movieRating); const rated = wrapper.find('.rated'); expect(rated.length).toBe(1); expect(rated.at(0).text()).toBe(movieRating); }) }); function createWrapper(title, year, poster,plot,cast,runtime,genre,rated){ const movieTableEntry = new MovieTableEntry('testId', title, plot, poster, rated, year, runtime, genre, cast); const movie = <Router><Movie movieInfo={movieTableEntry} clickable={false}/></Router> const wrapper = mount(movie); return wrapper; }
true
479e772fac54d564c6c34851b4c36c75d6d9bb50
JavaScript
CesiumGS/cesium
/packages/engine/Source/Scene/TilesetMetadata.js
UTF-8
5,301
2.765625
3
[ "Apache-2.0", "LicenseRef-scancode-free-unknown", "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "OFL-1.1", "CC-BY-3.0", "JSON", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license", "CC-BY-4.0", "MPL-2.0", "ISC", "CC-BY-SA-2.0", "LicenseRef-scancode-public-domain", "MIT" ]
permissive
import Check from "../Core/Check.js"; import defaultValue from "../Core/defaultValue.js"; import defined from "../Core/defined.js"; import MetadataEntity from "./MetadataEntity.js"; /** * Metadata about the tileset. * <p> * See the {@link https://github.com/CesiumGS/3d-tiles/tree/main/extensions/3DTILES_metadata|3DTILES_metadata Extension} for 3D Tiles * </p> * * @param {object} options Object with the following properties: * @param {object} options.tileset The tileset metadata JSON object. * @param {MetadataClass} options.class The class that tileset metadata conforms to. * * @alias TilesetMetadata * @constructor * @private * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy. */ function TilesetMetadata(options) { options = defaultValue(options, defaultValue.EMPTY_OBJECT); const tileset = options.tileset; const metadataClass = options.class; //>>includeStart('debug', pragmas.debug); Check.typeOf.object("options.tileset", tileset); Check.typeOf.object("options.class", metadataClass); //>>includeEnd('debug'); const properties = defined(tileset.properties) ? tileset.properties : {}; this._class = metadataClass; this._properties = properties; this._extras = tileset.extras; this._extensions = tileset.extensions; } Object.defineProperties(TilesetMetadata.prototype, { /** * The class that properties conform to. * * @memberof TilesetMetadata.prototype * @type {MetadataClass} * @readonly * @private */ class: { get: function () { return this._class; }, }, /** * Extra user-defined properties. * * @memberof TilesetMetadata.prototype * @type {*} * @readonly * @private */ extras: { get: function () { return this._extras; }, }, /** * An object containing extensions. * * @memberof TilesetMetadata.prototype * @type {object} * @readonly * @private */ extensions: { get: function () { return this._extensions; }, }, }); /** * Returns whether the tileset has this property. * * @param {string} propertyId The case-sensitive ID of the property. * @returns {boolean} Whether the tileset has this property. * @private */ TilesetMetadata.prototype.hasProperty = function (propertyId) { return MetadataEntity.hasProperty(propertyId, this._properties, this._class); }; /** * Returns whether the tileset has a property with the given semantic. * * @param {string} semantic The case-sensitive semantic of the property. * @returns {boolean} Whether the tileset has a property with the given semantic. * @private */ TilesetMetadata.prototype.hasPropertyBySemantic = function (semantic) { return MetadataEntity.hasPropertyBySemantic( semantic, this._properties, this._class ); }; /** * Returns an array of property IDs. * * @param {string[]} [results] An array into which to store the results. * @returns {string[]} The property IDs. * @private */ TilesetMetadata.prototype.getPropertyIds = function (results) { return MetadataEntity.getPropertyIds(this._properties, this._class, results); }; /** * Returns a copy of the value of the property with the given ID. * <p> * If the property is normalized the normalized value is returned. * </p> * * @param {string} propertyId The case-sensitive ID of the property. * @returns {*} The value of the property or <code>undefined</code> if the tileset does not have this property. * @private */ TilesetMetadata.prototype.getProperty = function (propertyId) { return MetadataEntity.getProperty(propertyId, this._properties, this._class); }; /** * Sets the value of the property with the given ID. * <p> * If the property is normalized a normalized value must be provided to this function. * </p> * * @param {string} propertyId The case-sensitive ID of the property. * @param {*} value The value of the property that will be copied. * @returns {boolean} <code>true</code> if the property was set, <code>false</code> otherwise. * @private */ TilesetMetadata.prototype.setProperty = function (propertyId, value) { return MetadataEntity.setProperty( propertyId, value, this._properties, this._class ); }; /** * Returns a copy of the value of the property with the given semantic. * * @param {string} semantic The case-sensitive semantic of the property. * @returns {*} The value of the property or <code>undefined</code> if the tileset does not have this semantic. * @private */ TilesetMetadata.prototype.getPropertyBySemantic = function (semantic) { return MetadataEntity.getPropertyBySemantic( semantic, this._properties, this._class ); }; /** * Sets the value of the property with the given semantic. * * @param {string} semantic The case-sensitive semantic of the property. * @param {*} value The value of the property that will be copied. * @returns {boolean} <code>true</code> if the property was set, <code>false</code> otherwise. * @private */ TilesetMetadata.prototype.setPropertyBySemantic = function (semantic, value) { return MetadataEntity.setPropertyBySemantic( semantic, value, this._properties, this._class ); }; export default TilesetMetadata;
true
788be35ea9ced76b104fff7f44a576b1567ff6f8
JavaScript
zonghuang/learning-js-data-structures
/src/01.Array/05.concat-array.js
UTF-8
417
3.671875
4
[ "MIT" ]
permissive
// 数组合并 concat() /** concat() 连接 2 个或 2 个已上的数组,并返回结果。 concat() 可以向一个数组传递数组、对象或是元素。数组会按照该方法传入的参数顺序连接指定的数组。 */ const zero = 0; const positiveNumbers = [1, 2, 3]; const negativeNumbers = [-3, -2, -1]; let numbers = negativeNumbers.concat(zero, positiveNumbers); // [-3, -2, -1, 0, 1, 2, 3]
true
c02dc57bb488208fb560bb71f318043fb5d4e35b
JavaScript
CarolineVinet/project-m5-e-commerce
/client/src/reducers/companies-reducer.js
UTF-8
893
2.921875
3
[]
no_license
const initialState = { companies: null, status:"idle" } const companiesReducer = (state = initialState, action)=> { switch(action.type) { case 'REQUEST_COMPANIES' : { return { ...state, status: "loading" } } case 'RECEIVE_COMPANIES' : { return { ...state, items : action.companies, status: 'idle' } } case 'RECEIVE_COMPANIES_ERROR' : { return { ...state, status: "error" } } default: return state } } export default companiesReducer; // helpers // here the state refers to the global state with all the reducers combined // get an array with all the companies export const getCompaniesArray = (state) => state.companies.companies; // get the status export const getCompaniesArrayStatus = (state) => state.companies.status;
true
ba778580b604fcd32885ff330746f950b15dbf7f
JavaScript
interestdashing/test-data
/makeType1.js
UTF-8
1,121
3.328125
3
[]
no_license
const process = require("process"); const fs = require("fs"); const iterations = process.argv[2] || 0; const makeGuid = function () { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { const r = Math.random() * 16 | 0; const v = c === "x" ? r : (r & 0x3 | 0x8); return v.toString(16); }); }; const makeRandomString = function (min, max) { const options = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; const chars = min + (Math.random() * (max - min)); let result = ""; for (let i = 0; i < chars; i++) { result += options[Math.floor(Math.random() * options.length)]; } return result; }; for (let i = 0; i < iterations; i++) { const item = { id: makeGuid(), name: "This is a random type1 object " + makeRandomString(10, 100), description: "Description " + makeRandomString(100, 500), x: Math.random(), y: Math.random(), width: Math.random(), height: Math.random() }; fs.writeFileSync("type1/" + item.id + ".json", JSON.stringify(item, undefined, 4)); }
true
28f300aa1b113df9c54c55d21b0af67623fb8f02
JavaScript
leebyp/n-queens
/src/solvers.js
UTF-8
9,929
3.5
4
[]
no_license
/* _ ___ ___ | |_ _____ _ __ ___ / __|/ _ \| \ \ / / _ \ '__/ __| \__ \ (_) | |\ V / __/ | \__ \ |___/\___/|_| \_/ \___|_| |___/ */ // hint: you'll need to do a full-search of all possible arrangements of pieces! // (There are also optimizations that will allow you to skip a lot of the dead search space) // take a look at solversSpec.js to see what the tests are expecting // return a matrix (an array of arrays) representing a single nxn chessboard, with n rooks placed such that none of them can attack each other window.findNRooksSolution = function(n, board) { var solution = undefined; //fixme //for every point in the board //try to place a rook there, // if rookconflict detected, remove back from the board //continue until all rooks for placed //return board var board = board || new Board({n: n}); for(var i = 0; i < n; i++) { for(var j = 0; j < n; j++) { board.togglePiece(i, j); if (board.hasAnyRooksConflicts()) { board.togglePiece(i,j); } } } // console.dir(board); //console.log('Single solution for ' + n + ' rooks:', JSON.stringify(board)); return board.rows(); }; // return the number of nxn chessboards that exist, with n rooks placed such that none of them can attack each other window.countNRooksSolutions = function(n) { var outcomes = []; var iterateBoard = function(currentBoard, row){ if (row === 0) { //base case outcomes.push(currentBoard.rows()); } else { var newBoard = new Board(currentBoard.rows()); //create a copy of currentBoard for (var i=0; i<n; i++){ newBoard.togglePiece(n - row, i); if (!newBoard.hasAnyRooksConflicts()){ //recursive case when no conflict iterateBoard(newBoard, row - 1); } newBoard.togglePiece(n-row, i); //remove to continue checking next slot } } }; iterateBoard(new Board({n: n}), n); console.log('Number of solutions for ' + n + ' rooks:', outcomes.length); return outcomes.length; }; // return a matrix (an array of arrays) representing a single nxn chessboard, with n queens placed such that none of them can attack each other window.findNQueensSolution = function(n) { var board = board || new Board({n: n}); for(var i = 0; i < n; i++) { for(var j = 0; j < n; j++) { board.togglePiece(i, j); if (board.hasAnyQueensConflicts()) { board.togglePiece(i,j); } } } // console.dir(board); //console.log('Single solution for ' + n + ' rooks:', JSON.stringify(board)); return board.rows(); }; //==================================================== // window.countNQueensSolutions = function(n) { // var outcomes = []; // var iterateBoard = function(currentBoard, rounds){ // if (rounds === 0) { //base case // outcomes.push(currentBoard.rows()); // } else { // var newBoard = new Board(currentBoard.rows()); //create a copy of currentBoard // for (var i=0; i<n; i++){ // newBoard.togglePiece(n - rounds, i); // if (!newBoard.hasAnyQueensConflicts()){ //recursive case when no conflict // iterateBoard(newBoard, rounds - 1); // } // newBoard.togglePiece(n-rounds, i); //remove to continue checking next slot // } // } // }; // iterateBoard(new Board({n: n}), n); // console.log('Number of solutions for ' + n + ' rooks:', outcomes.length); // return outcomes.length; // }; //================== n=9, ~9000ms //==================================================== // window.countNQueensSolutions = function(n){ // // . place queen on each position in first row // // . place each position on next row // // .if collision at that new location, remove, and do nothing // // .if no collision, continue at each position on next row // var outcomes = []; // var iterateBoard = function(currentBoard, row){ // if (row === n){ // outcomes.push(currentBoard.rows()); // } else { // var newBoard = new Board(currentBoard.rows()); // for (var i=0; i<n; i++){ // newBoard.togglePiece(row, i); // if (!newBoard.hasAnyQueenConflictsOn(row, i)){ // iterateBoard(newBoard, row+1); // } // newBoard.togglePiece(row, i); // } // } // } // iterateBoard(new Board({n:n}), 0); // return outcomes.length; // } //================== n=9, ~1500ms, only checking for conflicts at new position on board //==================================================== // window.countNQueensSolutions = function(n){ // // . place queen on each position in first row // // . place each position on next row // // .if collision at that new location, remove, and do nothing // // .if no collision, continue at each position on next row // var outcomes = []; // var iterateBoard = function(currentBoard, row, usedColumns, usedMajor, usedMinor){ // if (row === n){ // outcomes.push(currentBoard.rows()); // } else { // var newBoard = new Board(currentBoard.rows()); // for (var i=0; i<n; i++){ // newBoard.togglePiece(row, i); // if ((!(i in usedColumns) && !((i-row) in usedMajor)) && !((i+row) in usedMinor)){ // var newUsedColumns = _.clone(usedColumns); // newUsedColumns[i] = true; // var newUsedMajor = _.clone(usedMajor); // newUsedMajor[i-row] = true; // var newUsedMinor = _.clone(usedMinor); // newUsedMinor[i+row] = true; // iterateBoard(newBoard, row+1, newUsedColumns, newUsedMajor, newUsedMinor); // } // newBoard.togglePiece(row, i); // } // } // }; // iterateBoard(new Board({n:n}), 0, {}, {}, {}); // return outcomes.length; // }; //================== n=9, ~750ms, keeping a log of used columns, major and minor diagonals //==================================================== // window.countNQueensSolutions = function(n){ // var outcomes = []; // var iterateBoard = function(currentBoard, row, usedColumns, usedMajor, usedMinor){ // if (row === n){ // outcomes.push(currentBoard); // } else { // var newBoard = currentBoard.slice(); // for (var column=0; column<n; column++){ // if ((!(column in usedColumns) && !((column-row) in usedMajor)) && !((column+row) in usedMinor)){ // newBoard[row] = column; // var newUsedColumns = _.clone(usedColumns); // newUsedColumns[column] = true; // var newUsedMajor = _.clone(usedMajor); // newUsedMajor[column-row] = true; // var newUsedMinor = _.clone(usedMinor); // newUsedMinor[column+row] = true; // iterateBoard(newBoard, row+1, newUsedColumns, newUsedMajor, newUsedMinor); // } // } // } // }; // iterateBoard(new Array(n), 0, {}, {}, {}); // return outcomes.length; // }; //================== n=9, ~230ms, using a simple array instead of the board class, where key = row, value = column //==================================================== // window.countNQueensSolutions = function(n){ // var outcomes = 0; // var iterateBoard = function(row, usedColumns, usedMajors, usedMinors){ // if (row === n){ // outcomes++; // } // for (var column=0; column<n; column++){ // var bitColumn = 1 << column; // if (~(usedColumns | usedMajors | usedMinors) & bitColumn){ // iterateBoard(row+1, usedColumns | bitColumn, (usedMajors | bitColumn)>>1, (usedMinors | bitColumn) << 1); // } // } // }; // iterateBoard(0, 0, 0, 0); // return outcomes; // }; //================== n=12 ~65ms, refactored code to exclude board, unused cloned varibles //================== and bitshifted with numbers to keep track of used spaces //==================================================== // window.countNQueensSolutions = function(n){ // var outcomes = 0; // //if ( n%2 === 0){ // var iterateBoard = function(row, usedColumns, usedMajors, usedMinors){ // if (row === n){ // outcomes++; // } // for (var column=0; column<n; column++){ // var bitColumn = 1 << column; // if (~(usedColumns | usedMajors | usedMinors) & bitColumn){ // iterateBoard(row+1, usedColumns | bitColumn, (usedMajors | bitColumn)>>1, (usedMinors | bitColumn) << 1); // } // } // }; // for (var firstRowColumn=0; firstRowColumn<n/2; firstRowColumn++){ // var bitColumn = 1 << firstRowColumn; // iterateBoard(1, bitColumn, bitColumn>>1, bitColumn << 1); // } // return outcomes*2; // //} // }; //================== n=12 ~39ms, attempt at using symmetry for even n //==================================================== window.countNQueensSolutions = function(n){ var outcomes = 0; var iterateBoard = function(row, usedColumns, usedMajors, usedMinors){ if (row === n){ outcomes++; } for (var column=0; column<n; column++){ var bitColumn = 1 << column; if (~(usedColumns | usedMajors | usedMinors) & bitColumn){ iterateBoard(row+1, usedColumns | bitColumn, (usedMajors | bitColumn)>>1, (usedMinors | bitColumn) << 1); } } }; if ( n%2 === 0){ for (var firstRowColumn=0; firstRowColumn<n/2; firstRowColumn++){ var bitColumn = 1 << firstRowColumn; iterateBoard(1, bitColumn, bitColumn>>1, bitColumn<<1); } return outcomes*2; } else { for (var firstRowColumn=0; firstRowColumn<n; firstRowColumn++){ var bitColumn = 1 << firstRowColumn; iterateBoard(1, bitColumn, bitColumn>>1, bitColumn<<1); } return outcomes; } }; //================== n=12 ~40ms, //================== n=13 ~400ms // ~250ms on a mac mini //================== attempt at using symmetry for even n //====================================================
true
34d08a03c289b4c846ce3a9de424289e76165ddc
JavaScript
brendonion/midterm-project
/server/routes/resources.js
UTF-8
4,988
2.546875
3
[]
no_license
'use strict'; const express = require('express'); const router = express.Router(); const dateNow = new Date(); const theDate = dateNow.toLocaleString(); const mw = require('../routes/middleware'); module.exports = (knex) => { // adds middleware to this page const middleware = mw(knex); //retrieves create new resource page router.get('/new', middleware.ensureLoggedIn, (req, res) => { res.render('../public/views/resource_new', {user: { username: req.username, userid: req.id }}); }); //retrieves resource id and displays the info of the resource router.get('/:resource_id', (req, res) => { const key = req.params.resource_id; let resource = {}; let creatorName = ''; let creatorId = 0; let likes = 0; let rating = 0; let commentsArr = []; let hasLiked = false; //links user with resource knex('users') .join('resources', 'users.id', '=', 'creator') .select('username', 'creator') .where('resources.id', req.params.resource_id) .asCallback((err, results) => { if (err) return console.error(err); creatorName = results[0].username; creatorId = results[0].creator; }); //links resource likes knex('resources').join('likes', 'resource_id', '=', 'resources.id') .count().where('resource_id', req.params.resource_id) .asCallback((err, results) => { if (err) return console.error(err); likes = results[0].count; }); knex('likes').count() .where('user_id', req.session.user_id) .andWhere('resource_id', req.params.resource_id) .then((results) => { if (results[0].count == 1) { hasLiked = true; } else { hasLiked = false; } }).catch(function(error){ console.log(error); }) //links resource ratings knex('resources').join('ratings', 'resource_id', '=', 'resources.id') .select('value').where('resource_id', req.params.resource_id) .asCallback((err, results) => { if (err) return console.error(err); let ratings = results; for (let i = 0; i < ratings.length; i++) { rating += ratings[i].value; } rating = rating / ratings.length; rating = Math.max( Math.round(rating * 10) / 10, 1 ).toFixed(1); }); //links resource comments with the user who commented and date created knex('resources').join('comments', 'resource_id', '=', 'resources.id') .join('users', 'user_id', '=', 'users.id') .where('resource_id', req.params.resource_id) .asCallback((err, results) => { let dateTime = ''; if (err) return console.error(err); for (let i = 0; i < results.length; i++){ dateTime = (results[i].date_created).toLocaleString(); let comment = { comment: results[i].comment, date: dateTime, commenter: results[i].username } commentsArr.push(comment); } }) //retrieves resource from database knex.select().from('resources').where('id', req.params.resource_id) .asCallback((err, results) => { if (err) return console.error(err); resource = results; }).then(function() { commentsArr.sort(function(a,b){ return new Date(b.date) - new Date(a.date); }); let templateVars = { resource: resource[0], creator: { id: creatorId, username: creatorName }, user: { username: req.username, userid: req.session.user_id }, likesCount: { likes: likes }, hasLiked: { hasLiked: hasLiked }, totalRating: { rating: rating }, allComments: commentsArr } res.render('../public/views/resource_id', templateVars); }).catch(function(error){ console.log(error); }) }); //posts new resource to /:resource_id. If url is used //then it redirects back to resources/new router.post('/create', middleware.ensureLoggedIn, (req, res) => { if (!req.body.title || !req.body.description || !req.body.url) { req.flash('errors', 'Title, URL, description, and topic required'); return; } const findReqUrl = knex('resources') .select('url') .where({url: req.body.url}) .limit(1); findReqUrl.then((results) => { if (results.length) { // TODO make this into a flash message console.log('Resource already used'); res.redirect('/resources/new'); return; } else { knex.insert([{ title: req.body.title, url: req.body.url, description: req.body.description, topic: req.body.topic.toLowerCase(), creator: req.session.user_id, date_created: theDate }]).returning('id') .into('resources') .then((id) => { res.redirect('/resources/' + id); return; }) } }); }); return router; }
true
d08716029c92b1d40210fea281b98cd55f55bab0
JavaScript
daniellenguyen/nguyen-danielle-webdev
/public/project/views/search/controllers/petDetails.js
UTF-8
2,956
2.625
3
[]
no_license
(function() { angular .module("PetWebsite") .controller("PetDetailsController", PetDetailsController); function PetDetailsController($location, $routeParams, SearchService) { var vm = this; vm.petId = $routeParams["petId"]; vm.carouselHelper = carouselHelper; vm.toRegister = toRegister; vm.toLogin = toLogin; vm.isUserLoggedIn = false; function init() { var promise = SearchService.getSinglePet(vm.petId); promise.then(function (response) { vm.pet = response.data; vm.age = vm.pet.age; vm.breed = vm.pet.breeds.breed[0]; vm.email = vm.pet.contact.email; vm.phone = vm.pet.contact.phone; vm.description = vm.pet.description; vm.id = vm.pet.id; vm.name = vm.pet.name; vm.size = vm.pet.size; vm.photos = vm.pet.media; prettifySex(); prettifySize(); prettifyStatus(); prettifyDetails(); }); } init(); function prettifyStatus() { if(vm.pet.status === 'A') { vm.status = 'ready to adopt!' } else if(vm.pet.status === 'X') { vm.status = 'that has already been adopted!' } else { vm.status = ''; } } function prettifySize() { if(vm.pet.size === 'S') { vm.size = 'Small'; } else if(vm.pet.size === 'M') { vm.size = 'Medium'; } else if(vm.pet.size === 'L') { vm.size = 'Large'; } else if(vm.pet.size === 'XL') { vm.size = 'Very Large'; } else { vm.size = ''; } } function prettifySex() { if(vm.pet.sex === 'M') { vm.sex = 'Male'; } else if (vm.pet.sex === 'F') { vm.sex = 'Female'; } else { vm.sex = ''; } } function prettifyDetails() { var oldDetails = vm.pet.options.option; var newDetails = ''; for(var i = 0; i < Object.keys(oldDetails).length; i++) { if (oldDetails[i] === "hasShots") { newDetails = newDetails + 'has shots, '; } else if (oldDetails[i] === "noDogs") { newDetails = newDetails + 'can\'t be around dogs, '; } else if (oldDetails[i] === "altered") { if(vm.sex === 'Male') { newDetails = newDetails + 'neutered, '; } else if (vm.sex === 'Female') { newDetails = newDetails + 'spayed, '; } } else { newDetails = newDetails + " " + oldDetails[i] + ', '; } } newDetails = newDetails.slice(0, -2); vm.details = newDetails; } function carouselHelper(index) { if(index === 0) { return "item active"; } else { return "item"; } } function toRegister() { $location.url("/register"); } function toLogin() { $location.url("/login"); } } })();
true
2c3ab08f98f36bd5ad5211071688e49243addbd0
JavaScript
Naixes/demo-collection
/learnVue/vue-cli-webpack/src/pages/jsxScopSlot/components/levelFunction.js
UTF-8
535
2.609375
3
[]
no_license
// 返回不同级别的标题:l=1/2/3/4/5/6 export default { props: { l: { type: Number } }, render (h) { let tag = `h${this.l}` // return <tag>{this.$slots.default}</tag> return h(tag, {}, this.$slots.default) // h方法的参数: // h1 on-click={()=>{alert(1)}} style={{color:'red'}}>你好</h1> // h('h1',{ // on:{ // click(){ // alert(1) // }, // }, // attrs:{ // a:1 // } // },[h('span',{},'你好')]) } }
true
ad9ce9a6884770ed8053a0b07a8e112faf1ad066
JavaScript
guoyu07/jSound
/src/jSound.js
UTF-8
2,341
2.828125
3
[]
no_license
/*! * jSound 0.0.1 preview * @author TooBug <[email protected]> * @license MIT */ (function(w){ 'use strict'; var jSound = {}; var elem; var init = function(){ elem = document.createElement('audio'); if (!elem.canPlayType){ elem = document.createElement('bgsound'); } document.body.appendChild(elem); }; /** * 播放音效 * @param {String} src 要播放的音频文件URL * @param {Object} ops 播放设置 * @param {Boolean} ops.loop 是否循环播放 * @param {Number} ops.volume 音量大小,取值为0-100 * @return {undefined} */ jSound.play = function(src,ops){ var options; // 如果只传了ops,没有传src if (typeof src === 'object'){ options = src; }else{ options = ops || {}; options.src = src; } if (options.loop){ elem.loop = elem.canPlayType?true:-1; }else{ elem.loop = elem.canPlayType?false:1; } if (options.volume !== undefined){ elem.volume = elem.canPlayType?options.volume/100:-(options.volume-100)*(options.volume-100); } elem.src=options.src; if (elem.canPlayType){ elem.play(); } }; /** * 停止播放音效 * @return {undefined} */ jSound.stop = function(){ if (elem.canPlayType){ elem.pause(); }else{ elem.src=''; } }; /** * 播放内置音效 * @param {String} toneName 音效名字 * @return {undefined} */ jSound.playTone = function(toneName){ elem.src='data:audio/wav;base64,'+this.sounds[toneName]; if (elem.canPlayType){ elem.play(); } }; /** * 对指定字符重复count次,返回一个重复字符串 * @param {String} str 要重复的字符串 * @param {Number} count 要重复的次数 * @return {String} 对str重复count次之后的新字符串 */ jSound._repeatStr = function(str,count){ var tempstr = ''; for (var i=count; i-- ; ){ tempstr += str; } return tempstr; } //detect DOM Ready Event if (window.addEventListener){ jSound.domReady = function(readyFunc){ document.addEventListener('DOMContentLoaded',readyFunc,false); }; }else if (window.attachEvent){ jSound.domReady = function(readyFunc){ document.attachEvent('onreadystatechange',function(){ if (document.readyState === 'complete'){ readyFunc(); } }); }; } jSound.domReady(function(){ init(); }); w.jSound = jSound; })(window);
true
b8371f2ca5aeebe985daf2c865e81b9ccbf006bf
JavaScript
edsonlima2506/Eventoge
/src/App.js
UTF-8
2,890
2.65625
3
[]
no_license
import Header from './Components/Header'; import Form from './Components/Form'; import Pratos from './Components/Pratos'; import Result from './Components/Result'; import Lista from './Components/Lista' import pratosInfos from './data'; import { funcionarios } from './data' import './App.css'; import React from 'react'; class App extends React.Component { constructor() { super() this.state = { totalCalorias: 0, inputNome: '', inputIdade: 0, inputSso: 0, inputPeso: 0, sexo: 'Masculino', listaVazia: true, } this.somaCalorias = this.somaCalorias.bind(this); this.handleChange = this.handleChange.bind(this); this.clearInputs = this.clearInputs.bind(this); } somaCalorias({ target }) { const cal = target.value this.setState((estadoAnterior, _props) => ({ totalCalorias: Number(estadoAnterior.totalCalorias) + Number(cal) })) } handleChange({ target }) { const { name, value } = target this.setState({ [name]: value }); } clearInputs() { const { totalCalorias } = this.state; const nome = document.getElementsByName('inputNome'); const idade = document.getElementsByName('inputIdade'); const sso = document.getElementsByName('inputSso'); const peso = document.getElementsByName('inputPeso'); const sexo = document.getElementsByName('sexo'); funcionarios.push({ nome: nome[0].value, idade: idade[0].value, sso: sso[0].value, peso: peso[0].value, sexo: sexo[0].value, total: totalCalorias }) nome[0].value = ''; idade[0].value = ''; sso[0].value = ''; peso[0].value = ''; this.setState ({ totalCalorias: 0, inputNome: '', inputIdade: 0, inputSso: 0, inputPeso: 0, sexo: 'Masculino', listaVazia: false, }) localStorage.setItem('funcionarios', JSON.stringify(funcionarios)) } render() { const { totalCalorias, inputNome, inputIdade, inputPeso, inputSso, sexo, listaVazia } = this.state; const funcionariosSalvos = JSON.parse(localStorage.getItem('funcionarios')); return ( <div className="App"> <Header /> <Form handleChange={ this.handleChange }/> <div className="containerPratos"> { pratosInfos.map((prato) => <Pratos image={ prato.imagem } name={ prato.nome } calorias={ prato.calorias } somaCalorias={ this.somaCalorias }/> ) } </div> <Result totalCalorias={ totalCalorias } inputNome={ inputNome } inputIdade={ inputIdade } inputPeso={ inputPeso } inputSso={ inputSso } sexo={ sexo } clearInputs={ this.clearInputs } /> { listaVazia === false && <Lista funcionariosSalvos={ funcionariosSalvos } /> } </div> ); } } export default App;
true
992e68d69fdfeb51aa26ea4dfa2d0e74455791be
JavaScript
mazsola739/Rika-s-Katas
/Curious_Constructors/5 kyu Simple Fun #166: Best Match/index.js
UTF-8
1,723
4.09375
4
[]
no_license
/* Task "AL-AHLY" and "Zamalek" are the best teams in Egypt, but "AL-AHLY" always wins the matches between them. "Zamalek" managers want to know what is the best match they've played so far. The best match is the match they lost with the minimum goal difference. If there is more than one match with the same difference, choose the one "Zamalek" scored more goals in. Given the information about all matches they played, return the index of the best match (0-based). If more than one valid result, return the smallest index. Example For ALAHLYGoals = [6,4] and zamalekGoals = [1,2], the output should be 1. Because 4 - 2 is less than 6 - 1 For ALAHLYGoals = [1,2,3,4,5] and zamalekGoals = [0,1,2,3,4], the output should be 4. The goal difference of all matches are 1, but at 4th match "Zamalek" scored more goals in. So the result is 4. Input/Output [input] integer array ALAHLYGoals The number of goals "AL-AHLY" scored in each match. [input] integer array zamalekGoals The number of goals "Zamalek" scored in each match. It is guaranteed that zamalekGoals[i] < ALAHLYGoals[i] for each element. [output] an integer Index of the best match. */ //My solution function bestMatch(ALAHLYGoals, zamalekGoals) { let firstMatch = ALAHLYGoals[0] - zamalekGoals[0], bestMatch = 0, zamalek = zamalekGoals[0]; for (let i = 0; i < ALAHLYGoals.length; i++) { let diff = ALAHLYGoals[i] - zamalekGoals[i]; if (firstMatch > diff) { firstMatch = diff; zamalek = zamalekGoals[i]; bestMatch = i; } else if (diff === firstMatch && zamalekGoals[i] > zamalek) { firstMatch = diff; zamalek = zamalekGoals[i]; bestMatch = i; } } return bestMatch; }
true
283ff6ffbeac76884004372be7647a43cdb540bb
JavaScript
edmundho/ongoing_study
/jul2018/jul18/linked_list_cycle_ii.js
UTF-8
942
3.953125
4
[]
no_license
// Given a linked list, return the node where the cycle begins.If there is no cycle, return null. // Note: Do not modify the linked list. // Follow up: // Can you solve it without using extra space ? /** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @return {ListNode} */ const detectCycle = function (head) { let scout1; if (head === null || head.next === null) { return null; } if (head.next) { if (head.next.next) { scout1 = head.next.next; } } let current = head; while (current && scout1) { if (current === scout1) { let newCurrent = head; while (current !== newCurrent) { current = current.next; newCurrent = newCurrent.next; } return newCurrent; } scout1 = scout1.next.next; current = current.next; } return null; };
true
18f5da13575eb45f132b313dddd0bae593d97810
JavaScript
emilti/ParkingSystem
/client/src/Utils/dropdowns.js
UTF-8
2,844
2.546875
3
[ "MIT" ]
permissive
const buildCategoriesDropdown = async (dropdownType) =>{ let serverOptions = await getCategories() switch(dropdownType){ case "Edit visit": return [...serverOptions] case "Enter visit": return [{"value": "", "label": "Select category"}, ...serverOptions] case "Filter visits": return [{"value": "0", "label": "All categories"}, ...serverOptions] } } const buildDiscountsDropdown = async (dropdownType) =>{ let serverOptions = await getDiscounts() switch(dropdownType){ case "Edit visit": return [{"value": "999", "label": "No discounts"}, ...serverOptions] case "Enter visit": return [{"value": "", "label": "Select discount"}, ...serverOptions] case "Filter visits": return [{"value": "0", "label": "All discounts"}, ...serverOptions, {"value": "999", "label": "No discounts"}] } } const getCategories = async () => { const promise = await fetch('http://localhost:57740/parking/getcategories') const categories = await promise.json() let options = [] options = categories.map(c => ({ "value": c.categoryId, "label": c.name + " (Occupied spaces: " + c.parkingSpaces + ")" })) return options } const getDiscounts = async () => { const promise = await fetch('http://localhost:57740/parking/getdiscounts') const discounts = await promise.json() let options = [] options = discounts.map(d => ({ "value": d.discountId, "label": d.name + " " + d.discountPercentage + "%" })) return options } const getIsInParkingOptions = async () => { let options = [ {"value": 'all', "label": "All"}, {"value": true, "label": "Yes"}, {"value": false, "label": "No"}] return options } const getIsInParkingEditOptions = () => { let options = [ {"value": true, "label": "Yes"}, {"value": false, "label": "No"}] return options } const getSorting = async () => { let options = [ {"value": '', "label": "No sorting"}, {"value": "1", "label": "Due Amount"}, {"value": "2", "label": "Registration Number"}, {"value": "3", "label": "Entered Parking Date"}] return options } const getSortingOrder = async () => { let options = [ {"value": '', "label": "No sorting"}, {"value": "1", "label": "Ascending"}, {"value": "2", "label": "Descending"}] return options } const getPageOptions = async () => { let options = [ {"value": '10', "label": "10"}, {"value": "20", "label": "20"}, {"value": "50", "label": "50"}] return options } export {buildCategoriesDropdown, buildDiscountsDropdown, getIsInParkingOptions, getIsInParkingEditOptions, getSorting, getSortingOrder, getPageOptions}
true
35c3ef22c067194bef65f8b4e3f4fec5c54d0f89
JavaScript
aakash2028/Assignment-6
/CoinFlipGame/script.js
UTF-8
658
3.859375
4
[]
no_license
var coinFlip = Math.round(Math.random()); var result = ""; var choice = window.prompt("Enter 'H' for Heads or 'T' for Tails"); if(coinFlip == 0){ result = "F"; }else if(coinFlip == 1){ result = "H"; } if(result == "H" && choice == "H"){ window.alert("The flip was heads and you chose heads...you win!"); }else if(result == "H" && choice == "T"){ window.alert("The flip was heads but you chose tails...you lose!"); }else if(result == "T" && choice == "H"){ window.alert("The flip was tails but you chose heads...you lose!"); }else if(result == "T" && choice == "T"){ window.alert("The flip was tails and you chose tails...you win!"); }
true
5772833aa6a307fea2ba94a3cca93347a6e42c83
JavaScript
EasonLin0716/rgb-to-hex-converter
/main.js
UTF-8
1,638
3.578125
4
[]
no_license
// red part const redSlider = document.querySelector('#red-silder') let redValue = document.querySelector('.red-value') let redOutCome = document.querySelector('.red-outcome') // green part const greenSlider = document.querySelector('#green-slider') let greenValue = document.querySelector('.green-value') let greenOutCome = document.querySelector('.green-outcome') // blue part const blueSlider = document.querySelector('#blue-slider') let blueValue = document.querySelector('.blue-value') let blueOutCome = document.querySelector('.blue-outcome') // color output let colorValue = document.querySelector('.color-value') // background changing let container = document.querySelector('.container') redSlider.addEventListener('mousemove', function (event) { changeValue(redValue, redSlider, redOutCome) changeBackground() }) greenSlider.addEventListener('mousemove', function (event) { changeValue(greenValue, greenSlider, greenOutCome) changeBackground() }) blueSlider.addEventListener('mousemove', function (event) { changeValue(blueValue, blueSlider, blueOutCome) changeBackground() }) // 此函式改變顏色數字的值 function changeValue(value, slider, outcome) { value.textContent = slider.value if (+value.textContent < 10) { // 如果小於0會再補上一個0 outcome.innerHTML = `0${value.textContent}` } else { // 轉為16進位 outcome.innerHTML = (+value.textContent).toString(16) } } // 此函式改變背景顏色 function changeBackground() { let color = `#${redOutCome.textContent}${greenOutCome.textContent}${blueOutCome.textContent}` container.style.background = color }
true
112f14825e4304c56dded5a90e45336743aeaf8b
JavaScript
ducaale/t9-server
/src/t9.js
UTF-8
800
3.234375
3
[]
no_license
const Dictionary = require('./dictionary') const WordRanker = require('./wordRanker') const dictionary = new Dictionary() const wordRanker = new WordRanker() function collectWords(path, words, current = '', depth = 0) { if (!dictionary.isValidPrefix(current)) { return } if (current.length == path.length) { words.push(current) return } for (const l of path[depth].split('')) { collectWords(path, words, current + l, depth+1) } } function predictWord(input) { const t9 = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'] const path = input.split('').map(n => t9[n-2]) const possibleWords = [] collectWords(path, possibleWords) possibleWords.sort((a, b) => wordRanker.rank(a) - wordRanker.rank(b)) return possibleWords } module.exports = { predictWord }
true
e21a9acd5ffbe628bd4455948031ed86610df452
JavaScript
dandyman2601/react-modal-json
/index.js
UTF-8
642
2.5625
3
[]
no_license
const express = require('express'); const path = require('path'); const list = require('./Test JSON.json') const app = express(); const cors = require('cors'); app.use(cors()); // Serve the static files from the React app app.use(express.static(path.join(__dirname, './build'))); // An api endpoint that returns a short list of items app.get('/api/getList', (req, res) => { res.json(list); console.log('Sent list of items'); }); app.get('*', (req, res) => { res.sendFile(path.join(__dirname + '/build/index.html')); }); const port = process.env.PORT || 5000; app.listen(port); console.log('App is listening on port ' + port);
true
edf166f652a9dab8c0dce94203849779bbdcb390
JavaScript
alissin4444/javascript-study
/ArrayMethodsThatIShouldKnow.js
UTF-8
5,033
4.59375
5
[]
no_license
// forEach faz com que você consiga percorrer um array const arr = [1, 2, 3, 4, 5, 6]; arr.forEach(item => { console.log(item); // output: 1 2 3 4 5 6 }); ----------------------------------------------------------------------------------- // includes permite você checar se existe existe um elemento no array baseado em seu valor const arr = [1, 2, 3, 4, 5, 6]; arr.includes(2); // output: true arr.includes(7); // output: false ----------------------------------------------------------------------------------- // filter eu sei que esse método está em meu arquivo de javascript sobre como retirar elementos de um array, mas com essa short sytax tudo se torna mais fácil const arr = [1, 2, 3, 4, 5, 6]; // item(s) greater than 3 const filtered = arr.filter(num => num > 3); console.log(filtered); // output: [4, 5, 6] console.log(arr); // output: [1, 2, 3, 4, 5, 6] ----------------------------------------------------------------------------------- // map é um método que cria um novo array e para cada index desse array, tu pode fazer o que tu quiser const arr = [1, 2, 3, 4, 5, 6]; // add one to every element const oneAdded = arr.map(num => num + 1); console.log(oneAdded); // output [2, 3, 4, 5, 6, 7] console.log(arr); // output: [1, 2, 3, 4, 5, 6] ----------------------------------------------------------------------------------- // reduce irá percorrer um array da esquerda para direita e irá transforma-lo em um único valor const arr = [1, 2, 3, 4, 5, 6]; const sum = arr.reduce((total, value) => total + value, 0); console.log(sum); // 21 ----------------------------------------------------------------------------------- // O método some irá fazer uma condicional com o último elemento de um array. Caso ele passe na condicional, a função retornará true. Caso contrário, retornará false const arr = [1, 2, 3, 4, 5, 6]; // at least one element is greater than 4? const largeNum = arr.some(num => num > 4); console.log(largeNum); // output: true // at least one element is less than or equal to 0? const smallNum = arr.some(num => num <= 0); console.log(smallNum); // output: false ----------------------------------------------------------------------------------- // every irá verificar se TODOS os elementos passam em uma condição. Se passar, retornará true. Caso contrário, retornará false const arr = [1, 2, 3, 4, 5, 6]; // all elements are greater than 4 const greaterFour = arr.every(num => num > 4); console.log(greaterFour); // output: false // all elements are less than 10 const lessTen = arr.every(num => num < 10); console.log(lessTen); // output: true ----------------------------------------------------------------------------------- // sort method. Ele irá organizar o array de forma anscedente ou descendente const arr = [1, 2, 3, 4, 5, 6]; const alpha = ['e', 'a', 'c', 'u', 'y']; // sort in descending order descOrder = arr.sort((a, b) => a > b ? -1 : 1); console.log(descOrder); // output: [6, 5, 4, 3, 2, 1] // sort in ascending order ascOrder = alpha.sort((a, b) => a > b ? 1 : -1); console.log(ascOrder); // output: ['a', 'c', 'e', 'u', 'y'] ----------------------------------------------------------------------------------- // Array.from irá retornar um novo array com tudo separado KKK. Mano, não entendi muito bem, mas ok const name = 'frugence'; const nameArray = Array.from(name); console.log(name); // output: frugence console.log(nameArray); // output: ['f', 'r', 'u', 'g', 'e', 'n', 'c', 'e'] // Além disso tu pode trabalhar com a DOM. Caralho, ele é MUITO interessante akakakak // I assume that you have created unorder list of items in our html file. const lis = document.querySelectorAll('li'); const lisArray = Array.from(document.querySelectorAll('li')); // is true array? console.log(Array.isArray(lis)); // output: false console.log(Array.isArray(lisArray)); // output: true ----------------------------------------------------------------------------------- // Array.of irá adicionar um todos os elementos para dentro do array. Bem, eu não vi tanta utilidade nisso, mas OK. const nums = Array.of(1, 2, 3, 4, 5, 6); console.log(nums); // output: [1, 2, 3, 4, 5, 6] ----------------------------------------------------------------------------------- // while loop executará x até a condição se tornar falsa var sum = 0; var number = 1; while (number <= 50) { // -- condition sum += number; // -- body number++; // -- updater } alert("Sum = " + sum); // => Sum = 1275 ----------------------------------------------------------------------------------- // for irá fazer o mesmo que while var sum = 0; for (var i = 1; i <= 50; i++) { sum = sum + i; } alert("Sum = " + sum); // => Sum = 1275 -----------------------------------------------------------------------------------
true
f28424efdad41c55f4ea8480b13b7c9bbff08c9c
JavaScript
wangcylive/code
/javascript/test/drag/mobile/main.js
UTF-8
4,784
2.625
3
[]
no_license
/** * Created by Wangcy on 2015/2/3. */ (function(w, d) { var drag1 = d.getElementById("drag1"), drag2 = d.getElementById("drag2"); var dragList = d.querySelectorAll(".story"); var dragCoords1 = (function() { var x = drag1.offsetLeft, width = drag1.offsetWidth, y = drag1.offsetTop, height = drag1.offsetHeight; return { x: { min: x, max: x + width }, y: { min: y, max: y + height } } }()); var dragCoords2 = (function() { var x = drag2.offsetLeft, width = drag2.offsetWidth, y = drag2.offsetTop, height = drag2.offsetHeight; return { x: { min: x, max: x + width }, y: { min: y, max: y + height } } }()); (function() { var i = 0, length = dragList.length; var fn = function(dom) { var touchStartTime = 0, canMove = 0, startX = 0, startY = 0, startTranslateX = 0, startTranslateY = 0, translateX = 0, translateY = 0, timeOut; dom.addEventListener("touchstart", function(event) { event.preventDefault(); var t = this, touch = event.targetTouches[0]; touchStartTime = event.timeStamp; startX = touch.pageX; startY = touch.pageY; startTranslateX = translateX; startTranslateY = translateY; timeOut = setTimeout(function() { t.classList.add("touch-state"); canMove = 1; }, 800); }, false); dom.addEventListener("touchmove", function(event) { event.preventDefault(); var touch = event.targetTouches[0], moveX = touch.pageX - startX, moveY = touch.pageY - startY, clientX = touch.clientX, clientY = touch.clientY; // 容错处理,在800ms内触发并且移动的距离大于10px时失效 if(event.timeStamp - touchStartTime < 800 && (moveX > 10 || moveY > 10)) { clearTimeout(timeOut); return false; } // touchstart 时间大于零(这里在touchstart的时候会设置) // 是在长按 800ms 后 if(touchStartTime > 0 && event.timeStamp - touchStartTime >= 800 && canMove) { var x = moveX + startTranslateX, y = moveY + startTranslateY; this.style.transform = "translate(" + x + "px," + y + "px)"; translateX = x; translateY = y; if(clientX > dragCoords1.x.min && clientX < dragCoords1.x.max && clientY > dragCoords1.y.min && clientY < dragCoords1.y.max) { drag1.style.setProperty("border-color", "red", ""); } else { drag1.style.removeProperty("border-color"); } if(clientX > dragCoords2.x.min && clientX < dragCoords2.x.max && clientY > dragCoords2.y.min && clientY < dragCoords2.y.max) { drag2.style.setProperty("border-color", "red", ""); } else { drag2.style.removeProperty("border-color"); } } }, false); dom.addEventListener("touchend", function(event) { event.preventDefault(); var touch = event.changedTouches[0], clientX = touch.clientX, clientY = touch.clientY; clearTimeout(timeOut); touchStartTime = 0; canMove = 0; this.classList.remove("touch-state"); if(clientX > dragCoords1.x.min && clientX < dragCoords1.x.max && clientY > dragCoords1.y.min && clientY < dragCoords1.y.max) { dom.style.removeProperty("transform"); drag1.appendChild(dom); } else { drag1.style.removeProperty("border-color"); } }, false); }; for(; i < length; i++) { fn(dragList[i]); } }()); }(window, document));
true
804401a6d7be0946d5a1eea40e2f056914fe0a7f
JavaScript
dbwcooper/chatgroup-backend
/controller/comment.js
UTF-8
1,338
2.65625
3
[]
no_license
const { _findRoomByLink } = require('../models/room'); const { _createComment, _getRoomDetailByLink } = require('../models/comment'); /** * 增加一条评论 * userName: 'George James', * roomLink: * avatar: { color: '#1890ff', alif: 'C' }, * moment: 1521300207000, * content: '<span style="color: red">12321332</span>', * md: true * @param {*} ctx */ const createComment = async (comment) => { let result = {}; comment = JSON.parse(comment); let data = await _findRoomByLink(comment.roomLink); if (data === 400 || !data.roomLink) { result.code = 400; result.msg = "聊天室不存在!"; } let code = await _createComment(comment); if(code === 400) { result.code = 400; result.msg = "评论失败!"; } else { result.code = 200; result.msg = "评论成功"; } return result; } // 根据roomLink 找到所有的评论 以时间降序 const getRoomDetailByLink = async (ctx) => { let roomLink = ctx.params.roomLink; //拿到房间名 let data = await _getRoomDetailByLink(roomLink); let result = {}; if (data === 400) { result.code = 400; result.msg = "获取失败"; } else { result.code = 200; result.msg = "获取成功"; result.data = data; } ctx.response.body = result; } module.exports = { createComment, getRoomDetailByLink }
true
557127d132b849f2496c6516443ee53db8619c2e
JavaScript
calvinfreese/Weather-App
/script.js
UTF-8
9,189
2.796875
3
[ "MIT" ]
permissive
$(document).ready(function () { const APIkey = "39a1d34577f4801b22aafca38b9e1e96"; var weatherIconCode = ""; var inputResponse = ""; var history = []; function loadLastSearch() { if (localStorage.getItem("key_0") != null) { // for (i = 0; i < localStorage.length; i++) { var keyIndex = localStorage.length - 1; var values = localStorage.getItem("key_" + keyIndex); var locationInput = values.replace(/"/g, ""); console.log(locationInput); var queryURL = "https://api.openweathermap.org/data/2.5/weather?q=" + locationInput + "&appid=" + APIkey; $.ajax({ url: queryURL, method: "GET", }).then(function (response) { inputResponse = response; weatherIconCode = response.weather[0].icon; var weatherURL = "http://openweathermap.org/img/w/" + weatherIconCode + ".png"; var currentDate = moment().format("L"); //grab Kelvin and convert to F var kelvin = response.main.temp; var temp = ((kelvin - 273.15) * 1.8 + 32).toFixed(2); //humidity var humidity = response.main.humidity; //wind speed var windSpeed = response.wind.speed; $(".current-location").text(`${response.name} ${currentDate}`); $("#weatherDisplay").attr("src", weatherURL); $("#weatherDisplay").attr("alt", "weather icon"); $(".current-temp").text("Temp: " + temp + " F"); $(".current-humidity").text("Humidity: " + humidity + "%"); $(".wind-speed").text("Wind Speed: " + windSpeed + " mph"); getUVIndex(); getFiveDayForecast(); }); } } loadLastSearch(); //Gets UV Index - called by city submission ajax req. function getUVIndex() { var lat = inputResponse.coord.lat; var lon = inputResponse.coord.lon; var urlUVIndex = "https://api.openweathermap.org/data/2.5/uvi?appid=" + APIkey + "&lat=" + lat + "&lon=" + lon; $.ajax({ url: urlUVIndex, method: "GET", }).then(function (r) { //Hey! this is the UV Index :D var uvIndex = r.value; $(".current-uv-index").text("UV Index: " + uvIndex); if (uvIndex >= 8) { $(".current-uv-index").attr("class", "current-uv-index very-high-uv"); } else if (uvIndex < 8 && uvIndex >= 6) { $(".current-uv-index").attr("class", "current-uv-index high-uv"); } else if (uvIndex < 6 && uvIndex >= 3) { $(".current-uv-index").attr("class", "current-uv-index mod-uv"); } else { $(".current-uv-index").attr("class", "current-uv-index low-uv"); } }); } //Gets Five day forecast function getFiveDayForecast() { var city = inputResponse.name; var forecastURL = "https://api.openweathermap.org/data/2.5/forecast?q=" + city + "&appid=" + APIkey; $.ajax({ url: forecastURL, method: "GET", }).then(function (r) { var forecastList = r.list; //loop through forecast days, grab time index time @ 12p for each day, and print info to forecast cards in html for (i = 4; i < forecastList.length; i += 8) { var forecastIcon = forecastList[i].weather[0].icon; var weatherURL = "http://openweathermap.org/img/w/" + forecastIcon + ".png"; $("#weatherDisplay").attr("src", weatherURL); var temp = ((kelvin - 273.15) * 1.8 + 32).toFixed(2); var forecastDate = forecastList[i].dt_txt; var kelvin = forecastList[i].main.temp; var temp = ((kelvin - 273.15) * 1.8 + 32).toFixed(2); var forecastDateFormat = moment(forecastDate).format("L"); var humidity = forecastList[i].main.humidity; if (i == 4) { $(".forecast1-date").text(forecastDateFormat); $(".forecast1-img").attr("src", weatherURL); $(".forecast1-img").attr("alt", "weather icon"); $(".forecast1-temp").text("Temp: " + temp + " F"); $(".forecast1-humidity").text("Humidity: " + humidity); } else if (i == 12) { $(".forecast2-date").text(forecastDateFormat); $(".forecast2-img").attr("src", weatherURL); $(".forecast2-img").attr("alt", "weather icon"); $(".forecast2-temp").text("Temp: " + temp + " F"); $(".forecast2-humidity").text("Humidity: " + humidity); } else if (i == 20) { $(".forecast3-date").text(forecastDateFormat); $(".forecast3-img").attr("src", weatherURL); $(".forecast3-img").attr("alt", "weather icon"); $(".forecast3-temp").text("Temp: " + temp + " F"); $(".forecast3-humidity").text("Humidity: " + humidity); } else if (i == 28) { $(".forecast4-date").text(forecastDateFormat); $(".forecast4-img").attr("src", weatherURL); $(".forecast4-img").attr("alt", "weather icon"); $(".forecast4-temp").text("Temp: " + temp + " F"); $(".forecast4-humidity").text("Humidity: " + humidity); } else if (i == 36) { $(".forecast5-date").text(forecastDateFormat); $(".forecast5-img").attr("src", weatherURL); $(".forecast5-temp").text("Temp: " + temp + " F"); $(".forecast5-humidity").text("Humidity: " + humidity); } } }); } //Adds historical searches as list items on page and stores them to localStorage function appendHistory() { var listGroup = $(".list-group"); var keys = Object.keys(localStorage); console.log("storing key index of " + keys.length); console.log(history); localStorage.setItem( "key_" + keys.length, JSON.stringify(history[history.length - 1]) ); listGroup.prepend( `<li class='list-group-item list-group-item-action historical-search'> ${ history[history.length - 1] } </li>` ); } function loadStorage() { var listGroup = $(".list-group"); if (localStorage.getItem("key_0") != null) { for (i = 0; i < localStorage.length; i++) { var storedSearches = localStorage.getItem("key_" + i); //history.push(storedSearches) storedSearches = storedSearches.replace(/"/g, ""); listGroup.prepend( `<li class='list-group-item list-group-item-action historical-search'> ${storedSearches} </li> ` ); } } } loadStorage(); //this happens first $("#locationForm").on("submit", function (e) { e.preventDefault(); var locationInput = $("#locationInput").val(); var queryURL = "https://api.openweathermap.org/data/2.5/weather?q=" + locationInput + "&appid=" + APIkey; $.ajax({ url: queryURL, method: "GET", }).then(function (response) { inputResponse = response; weatherIconCode = response.weather[0].icon; var weatherURL = "https://openweathermap.org/img/w/" + weatherIconCode + ".png"; var currentDate = moment().format("L"); //grab Kelvin and convert to F var kelvin = response.main.temp; var temp = ((kelvin - 273.15) * 1.8 + 32).toFixed(2); //humidity var humidity = response.main.humidity; //wind speed var windSpeed = response.wind.speed; $(".current-location").text(`${response.name} ${currentDate}`); $("#weatherDisplay").attr("src", weatherURL); $("#weatherDisplay").attr("alt", "weather icon"); $(".current-temp").text("Temp: " + temp + " F"); $(".current-humidity").text("Humidity: " + humidity + "%"); $(".wind-speed").text("Wind Speed: " + windSpeed + " mph"); history.push(response.name); getUVIndex(); getFiveDayForecast(); appendHistory(); $("#locationInput").val(""); }); }); $(document).on("click", ".historical-search", function () { var locationInput = $(this).text(); var queryURL = "https://api.openweathermap.org/data/2.5/weather?q=" + locationInput + "&appid=" + APIkey; $.ajax({ url: queryURL, method: "GET", }).then(function (response) { inputResponse = response; weatherIconCode = response.weather[0].icon; var weatherURL = "http://openweathermap.org/img/w/" + weatherIconCode + ".png"; var currentDate = moment().format("L"); //grab Kelvin and convert to F var kelvin = response.main.temp; var temp = ((kelvin - 273.15) * 1.8 + 32).toFixed(2); //humidity var humidity = response.main.humidity; //wind speed var windSpeed = response.wind.speed; $(".current-location").text(`${response.name} ${currentDate}`); $("#weatherDisplay").attr("src", weatherURL); $("#weatherDisplay").attr("alt", "weather icon"); $(".current-temp").text("Temp: " + temp + " F"); $(".current-humidity").text("Humidity: " + humidity + "%"); $(".wind-speed").text("Wind Speed: " + windSpeed + " mph"); getUVIndex(); getFiveDayForecast(); }); }); $("#clear-history").on("click", function (e) { localStorage.clear(); $(".list-group").empty(); }); });
true
020328c22700af2811af408d04095c93fa2f6da2
JavaScript
erin-smith/menu-maker
/client/src/components/MainCard/index.js
UTF-8
4,501
2.515625
3
[]
no_license
import React, {useState, useEffect} from "react"; import MenuSelectButton from "../MenuSelectButton"; import EditButton from "../EditButton"; import MenuList from "../MenuList"; import API from "../../utils/API"; import CategoryModal from "../CategoryModal" function MainCard (){ const [selectedMenuData, setSelectedMenuData] = useState({categories:[], menuTime:"", daypart:""}); const [selectedMenuId, setSelectedMenuId] = useState(); const [menuList, setMenuList] = useState([]); // Load entrees and store them with menu useEffect(() => { console.log("fetching"); API.getMenus() .then(res => { //console.log("db data:",res) setMenuList(res.data.map((x)=>{ return {id:x._id, daypart:x.daypart} })); if(res.data.length){ selectMenu(res.data[0]._id); } }) .catch(err => console.log(err, "Right here Error!!")); }, []) function selectMenu(id) { loadMenu(id); setSelectedMenuId(id); }; function loadMenu(id){ console.log("loading menu", id); API.getMenu(id) .then(res => { setSelectedMenuData(res.data) console.log("menu data loaded") }) .catch(err => console.log(err, "Right here Error!!")); } function onNewCategory(name){ setSelectedMenuData((oldMenu)=> { let newCat = {id:Date.now(), name:name, items:[]} let updatedMenu = JSON.parse(JSON.stringify(oldMenu)); updatedMenu.categories.push(newCat); console.log("menuid",selectedMenuId); console.log(updatedMenu); API.updateMenu(selectedMenuId, updatedMenu) .then(() => console.log("new category added", name)) .catch((err) => console.log(err)); return updatedMenu; } ) } function onItemUpdate(itemData, category){ setSelectedMenuData((oldMenu)=> { let updatedMenu = JSON.parse(JSON.stringify(oldMenu)); const cat = updatedMenu.categories.find(x=> x.id ===category.id); const i = cat.items.findIndex(x => x.id === itemData.id); cat.items[i] = itemData; API.updateMenu(selectedMenuId, updatedMenu) .then(() => console.log("updated item", itemData.name)) .catch((err) => console.log(err)); return updatedMenu; } ) } function onMenuSelectChange(newMenu){ console.log("menu selected", newMenu) selectMenu(newMenu) } function onItemClick(){ } function onNewItem(categoryId, itemData){ setSelectedMenuData((oldMenu)=> { let updatedMenu = JSON.parse(JSON.stringify(oldMenu)); const cat = updatedMenu.categories.find(x=> x.id ===categoryId); cat.items.push(itemData); API.updateMenu(selectedMenuId, updatedMenu) .then(() => console.log("Item added: ", itemData.name)) .catch((err) => console.log(err)); return updatedMenu; } ) } function onTimeChange(newTime){ setSelectedMenuData((oldMenu)=> { let updatedMenu = JSON.parse(JSON.stringify(oldMenu)); updatedMenu.menuTime = newTime; API.updateMenu(selectedMenuId, updatedMenu) .then(() => console.log("updated time",newTime)) .catch((err) => console.log(err)); return updatedMenu; } ) } return ( <div className="container-fluid mt-5"> <div className="card mb-4"> <div className="card-header pt-4"> <div className="row"> <div className="col"> <MenuSelectButton onSelectionChange={onMenuSelectChange} selectedMenu={selectedMenuId} menuList={menuList}/> </div> <div className="col"> {selectedMenuId ? ( <EditButton onTimeChange={onTimeChange} timeData={selectedMenuData.menuTime} className="d-inline float-right"/> ):(<div></div>)} </div> </div> </div> <div className="card-body"> <div className="container-fluid"> <div className= "col-md-8"> <MenuList menus={selectedMenuData} onNewItem={onNewItem} onItemClick={onItemClick} onItemUpdate={onItemUpdate}/> <CategoryModal onNewCategory={onNewCategory}/> </div> </div> </div> </div> </div> ); }; export default MainCard;
true
692de6f5197c74c3ee070ee1a268b83916143efc
JavaScript
mindbullet/mindbullet.github.io
/chapter14/fishcreek/scripts/fishcreek.js
UTF-8
219
2.765625
3
[]
no_license
$(function() { // show last modified date at bottom of page var dateDisplay = $('#date-display'); var message = 'This page was last modified on: ' + document.lastModified; dateDisplay.html(message); });
true
77204c03bbec222d84f1d8a99cb30af7df481fc6
JavaScript
simCecca/ClassicGames
/src/games/gameLogics/SnakeLogic.js
UTF-8
1,317
3.171875
3
[]
no_license
class SnakeLogic{ constructor(boardDimensions){ this.boardDimensions = boardDimensions; } newApplePosition(){ return {row: Math.floor(Math.random() * this.boardDimensions), column: Math.floor(Math.random() * this.boardDimensions)}; } controller(event, direction){ const newDirection = direction; if (event.keyCode === 38) { //up arrow if (direction.y !== 1) { //if you are going down you can't going up newDirection.x = 0; newDirection.y = -1; } } else if (event.keyCode === 40) {//down arrow if (direction.y !== -1) {//if you are going up you can't going down newDirection.x = 0; newDirection.y = 1; } } else if (event.keyCode === 39) {//right arrow if (direction.x !== -1) {//if you are going to left you can't turn right newDirection.x = 1; newDirection.y = 0; } } else if (event.keyCode === 37) { //left arrow if (direction.x !== 1) {//if you are going to right you can't turn left newDirection.x = -1; newDirection.y = 0; } } return newDirection; } snake } export default SnakeLogic;
true
defc351f90e8c8d9c11bc02367c903b691cdd5df
JavaScript
ZECTBynmo/gyp-to-obj
/gyp-to-obj.js
UTF-8
1,165
2.953125
3
[]
no_license
////////////////////////////////////////////////////////////////////////// // gyp-to-obj - Read gyp files and serialize them into JavaScript objects ////////////////////////////////////////////////////////////////////////// // // Main script! /* ---------------------------------------------------------------------- Object Structures ------------------------------------------------------------------------- */ ////////////////////////////////////////////////////////////////////////// // Requires var JSON5 = require("JSON5"), fs = require("fs"); ////////////////////////////////////////////////////////////////////////// // Namespace (lol) var SHOW_DEBUG_PRINTS = true; var log = function( a ) { if(SHOW_DEBUG_PRINTS) console.log(a); }; // A log function we can turn off var GypToObj = exports; ////////////////////////////////////////////////////////////////////////// // Read in a gyp file and return it's object representation GypToObj.read = function( path ) { contents = {}; try { var contents = JSON5.parse(fs.readFileSync(path, "utf8")); } catch( err ) { console.log( "ERROR" ); console.log( err ); } return contents }
true
e5f123c0c54b87357b70d7a72a89fcc4e57ba64e
JavaScript
YoKaramfilova/SoftUni-Coursework
/Programming Fundamentals with JavaScript/Mid Exam/03-mid-exam.js
UTF-8
1,871
3.515625
4
[]
no_license
function solve(arr) { let collection = arr.shift().split(' '); for (let i = 0; i < arr.length; i++) { let command = arr[i].split(' '); if (command.includes('Delete')) { let index = +command[1]; if (index >= 0 && index < collection.length) { collection.splice(index + 1, 1); } } else if (command.includes('Swap')) { let word1 = command[1]; let word2 = command[2]; if (collection.includes(word1) && collection.includes(word2)) { let index1 = collection.indexOf(word1); let index2 = collection.indexOf(word2); collection[index1] = word2; collection[index2] = word1; } } else if (command.includes('Put')) { let word = command[1]; let index = +command[2]; if (index === collection.length - 1) { collection.push(word); } else if (index > 0 && index < collection.length - 1) { collection.splice(index - 1, 0, word); } } else if (command.includes('Sort')) { collection.sort((a, b) => b.localeCompare(a)); } else if (command.includes('Replace')) { let word1 = command[1]; let word2 = command[2]; while (collection.includes(word2)) { collection[collection.indexOf(word2)] = word1; } } else if (command.includes('Stop')) { break; } } console.log(collection.join(' ')); } solve((["Congratulations! You last also through the have challenge!", "Swap have last", "Replace made have", "Delete 2", "Put it 4", "Stop"])); solve((["This the my quest! final", "Put is 2", "Swap final quest!", "Delete 2", "Stop"]))
true
b17d35f5c3dd4c75c19e4e848d6cf64937dbcf85
JavaScript
aslafy-z/home-assistant-polymer
/src/panels/lovelace/cards/hui-entity-filter-card.js
UTF-8
2,113
2.53125
3
[ "Apache-2.0" ]
permissive
import { PolymerElement } from "@polymer/polymer/polymer-element"; import { createCardElement } from "../common/create-card-element"; import { processConfigEntities } from "../common/process-config-entities"; function getEntities(hass, filterState, entities) { return entities.filter((entityConf) => { const stateObj = hass.states[entityConf.entity]; return stateObj && filterState.includes(stateObj.state); }); } class HuiEntitiesCard extends PolymerElement { static get properties() { return { hass: { type: Object, observer: "_hassChanged", }, }; } getCardSize() { return this.lastChild ? this.lastChild.getCardSize() : 1; } setConfig(config) { if (!config.state_filter || !Array.isArray(config.state_filter)) { throw new Error("Incorrect filter config."); } this._config = config; this._configEntities = processConfigEntities(config.entities); if (this.lastChild) { this.removeChild(this.lastChild); this._element = null; } const card = "card" in config ? { ...config.card } : {}; if (!card.type) card.type = "entities"; card.entities = []; const element = createCardElement(card); element._filterRawConfig = card; this._updateCardConfig(element); this._element = element; } _hassChanged() { this._updateCardConfig(this._element); } _updateCardConfig(element) { if (!element || element.tagName === "HUI-ERROR-CARD" || !this.hass) return; const entitiesList = getEntities( this.hass, this._config.state_filter, this._configEntities ); if (entitiesList.length === 0 && this._config.show_empty === false) { this.style.display = "none"; return; } this.style.display = "block"; element.setConfig({ ...element._filterRawConfig, entities: entitiesList }); element.isPanel = this.isPanel; element.hass = this.hass; // Attach element if it has never been attached. if (!this.lastChild) this.appendChild(element); } } customElements.define("hui-entity-filter-card", HuiEntitiesCard);
true
a16491e921c45db9a3e37abf4800eed56b3ddf13
JavaScript
landongn/sleepy
/src/level/schemes/DenseCastleScheme.js
UTF-8
9,326
2.671875
3
[]
no_license
import { digExits } from '../LevelConnections'; import TileContainer from '../TileContainer'; import { TILE_TYPE_FLOOR, TILE_TYPE_WALL } from '../TileData'; import { pickRandom, randomInt } from '../../utils/rand'; import { computeAStar } from '../../utils/AStar'; import { diagonalDistance } from '../../utils/diagonalDistance'; import TileScheme from '../TileScheme'; const VERTICAL = 0; const HORIZONTAL = 1; let curId = 1; const createNodeId = () => curId++; const splitNodeVertical = (node, cut) => { const leftId = createNodeId(); const rightId = createNodeId(); const left = { id: leftId, isLeaf: true, parentId: node.id, siblingId: rightId, offsetX: node.offsetX, offsetY: node.offsetY, width: cut, height: node.height, }; const right = { id: rightId, isLeaf: true, parentId: node.id, siblingId: leftId, offsetX: node.offsetX + cut, offsetY: node.offsetY, width: node.width - cut, height: node.height, }; return [left, right]; }; const splitNodeHorizontal = (node, cut) => { const topId = createNodeId(); const bottomId = createNodeId(); const top = { id: topId, isLeaf: true, parentId: node.id, siblingId: bottomId, offsetX: node.offsetX, offsetY: node.offsetY, width: node.width, height: cut, }; const bottom = { id: bottomId, isLeaf: true, parentId: node.id, siblingId: topId, offsetX: node.offsetX, offsetY: node.offsetY + cut, width: node.width, height: node.height - cut, }; return [top, bottom]; }; export class DenseCastleScheme extends TileScheme { static generate(settings) { const width = settings.width; const height = settings.height; const exits = settings.exits || []; const minRoomWidth = settings.minRoomWidth || 4; const minRoomHeight = settings.minRoomHeight || 4; const maxRoomWidth = settings.maxRoomWidth || 12; const maxRoomHeight = settings.maxRoomHeight || 12; const splitIgnoreChance = settings.splitIgnoreChance || 0.8; const loopiness = settings.loopiness || 35; const tiles = new TileContainer(width, height); for (let i = 0; i < width; i++) { for (let j = 0; j < height; j++) { if (i === 0 || i === width - 1 || j === 0 || j === height - 1) { tiles.setTileType(i, j, TILE_TYPE_WALL); } else { tiles.setTileType(i, j, TILE_TYPE_FLOOR); } } } const nodes = [ { isLeaf: true, parentId: null, siblingId: null, id: createNodeId(), offsetX: 0, offsetY: 0, height: height - 1, width: width - 1, }, ]; const graph = []; while (nodes.length > 0) { const node = nodes.pop(); graph.push(node); if (node.width < maxRoomWidth && node.height < maxRoomHeight) { const ignoreSplit = Math.random() < splitIgnoreChance; if (ignoreSplit) { continue; } } const directions = []; if (node.width - minRoomWidth - 1 > minRoomWidth) { directions.push(VERTICAL); } if (node.height - minRoomHeight - 1 > minRoomHeight) { directions.push(HORIZONTAL); } if (directions.length <= 0) { continue; } const direction = pickRandom(directions); if (direction === VERTICAL) { const cut = randomInt( minRoomWidth + 1, node.width - minRoomWidth - 1 ); nodes.push(...splitNodeVertical(node, cut)); } else { const cut = randomInt( minRoomHeight + 1, node.height - minRoomHeight - 1 ); nodes.push(...splitNodeHorizontal(node, cut)); } node.isLeaf = false; } graph.forEach((node) => { if (node.parentId === null) { return; } if (node.isLeaf) { const room = tiles.createRoom( node.offsetX + 1, node.offsetY + 1, node.width - 1, node.height - 1 ); room.includeWalls = true; for (let i = 0; i < node.width; i++) { tiles.setTileType( node.offsetX + i, node.offsetY, TILE_TYPE_WALL ); } for (let j = 0; j < node.height; j++) { tiles.setTileType( node.offsetX, node.offsetY + j, TILE_TYPE_WALL ); } return; } }); graph.forEach((node) => { if (node.parentId === null) { return; } const sibling = graph.find((n) => n.id === node.siblingId); let doorCandidates = []; let hasSib = false; if (sibling.offsetX < node.offsetX) { hasSib = true; for (let i = 1; i < node.height; i++) { const x = node.offsetX; const y = node.offsetY + i; const tile = tiles.getTile(x, y); if ( tiles.tileTypeMatches(x - 1, y, TILE_TYPE_FLOOR) && tiles.tileTypeMatches(x + 1, y, TILE_TYPE_FLOOR) ) { doorCandidates.push(tile); } } } else if (sibling.offsetY < node.offsetY) { hasSib = true; for (let i = 1; i < node.width; i++) { const x = node.offsetX + i; const y = node.offsetY; const tile = tiles.getTile(x, y); if ( tiles.tileTypeMatches(x, y - 1, TILE_TYPE_FLOOR) && tiles.tileTypeMatches(x, y + 1, TILE_TYPE_FLOOR) ) { doorCandidates.push(tile); } } } const door = pickRandom(doorCandidates); if (hasSib && !door) { console.warn( 'cannot make door!?', node, node.width, node.height ); } if (door) { const room = tiles.getRoomForTile(door.x, door.y); if (room) { room.addExit(door.x, door.y); } tiles.setTileType(door.x, door.y, TILE_TYPE_FLOOR); } }); const cost = (a, b) => { if (tiles.tileTypeMatches(b.x, b.y, TILE_TYPE_FLOOR)) { return diagonalDistance(a, b); } return Infinity; }; const tryAddLoop = (a, b) => { if (a.isType(TILE_TYPE_FLOOR) && b.isType(TILE_TYPE_FLOOR)) { const start = { x: b.x, y: b.y, }; const goal = { x: a.x, y: a.y, }; const path = computeAStar({ start, goal, cost, }); if (path.success && path.cost >= loopiness) { return true; } } return false; }; tiles.data .filter((tile) => tile.isType(TILE_TYPE_WALL)) .forEach((tile) => { const north = tiles.getTile(tile.x, tile.y - 1); const south = tiles.getTile(tile.x, tile.y + 1); if (tryAddLoop(north, south)) { tiles.setTileType(tile.x, tile.y, TILE_TYPE_FLOOR); const room = tiles.getRoomForTile(tile.x, tile.y); if (room) { room.addExit(tile.x, tile.y); } return; } const east = tiles.getTile(tile.x - 1, tile.y); const west = tiles.getTile(tile.x + 1, tile.y); if (tryAddLoop(east, west)) { tiles.setTileType(tile.x, tile.y, TILE_TYPE_FLOOR); const room = tiles.getRoomForTile(tile.x, tile.y); if (room) { room.addExit(tile.x, tile.y); } return; } }); digExits(tiles, exits); return tiles; } }
true
9ed4dcb8fe46791f6e06bd1b6d232a46d40187be
JavaScript
jccastiblancor/forms
/src/customHooks/useForm.js
UTF-8
643
2.5625
3
[]
no_license
import { useState } from "react"; const useForm = (validateForm) => { const [errors, setErrors] = useState({}); const [values, setValues] = useState({}); const handleChange = (evt) => { setValues({ ...values, [evt.target.name]: evt.target.value, }); }; const initialValues = (val) => { const obj = {}; for (const key of val) { obj[key] = ""; } setValues(obj); }; const handleSubmit = (evt) => { evt.preventDefault(); setErrors(validateForm(values)); console.log(values); }; return { handleChange, initialValues, handleSubmit, errors }; }; export default useForm;
true
ef493df9d602d1d218ff418faa1d1d20103279af
JavaScript
yehor-dykhov/SS
/OLD/hw_1602015_module5/group.js
UTF-8
1,081
3.21875
3
[]
no_license
function Group (_nameGroup) { var nameGroup = _nameGroup, students = []; this.getNameGroup = function () { return nameGroup; }; this.addStudent = function (name) { students.push(new Student(name)); console.log('Student %s was added', name); }; this.addStudents = function (names) { var i; for (i = 0; i < names.length; i++) { this.addStudent(names[i]); } }; this.getStudents = function () { return students; }; this.removeStudent = function (name) { var deletedStudents, i; for (i = 0; i < students.length; i++) { if (students[i].getName() === name) { deletedStudents = students.slice(i, 1); break; } } console.log('Student %s was deleted.', deletedStudents[0].getName()); return deletedStudents[0].getName(); }; this.clearGroup = function () { students = []; console.log('Group was cleaned.'); }; return this; }
true
7228699fb588f8dbb7b7a5723a6635c45f0ea11b
JavaScript
riebel/pixi-babel-webpack
/src/app.js
UTF-8
1,323
2.84375
3
[]
no_license
import * as PIXI from 'pixi.js' class App { constructor() { this.renderer = PIXI.autoDetectRenderer(800, 600, { antialias: true }); // create the root of the scene graph this.stage = new PIXI.Container(); this.speed = 0.01; this.frame = 0; this.render(); // run the render loop this.animate(); } render() { const richText = new PIXI.Text('PIXI.js',{ fontFamily : 'Arial', fontSize : '240px', fontStyle : 'italic', fontWeight : 'bold', fill : '#F7EDCA', stroke : '#4a1850', strokeThickness : 5 }); richText.x = 400; richText.y = 300; richText.anchor = {x: 0.5, y: 0.5}; this.stage.addChild(richText); return this; } animate() { requestAnimationFrame( this.animate.bind(this) ); this.frame++; const richText = this.stage.children[0]; const sine = Math.sin(this.speed * this.frame); richText.rotation = sine * 6.3; richText.width = (sine / 2 + 0.5) * 800; richText.height = (sine / 2 + 0.5) * 600; this.renderer.render(this.stage); } } export const app = new App(); document.body.appendChild(app.renderer.view);
true
84cb3fc4fc3ea4e18f17e07c787852c7bcd1f514
JavaScript
Sivory/sivory.github.com
/mylab/cs/game/scripts/Old/background.backup.js
UTF-8
3,465
2.71875
3
[]
no_license
var Util = imports('util'); var actorList = [ // assets('zombie001'), // assets('zombie002'), // assets('zombie003'), // assets('zombie004'), // assets('zombie005'), // assets('zombie006'), // assets('zombie007'), // assets('zombie008'), // assets('zombie009') ]; var Background = function(callbackCenter) { this.aimPosX = 0; this.aimPosY = 0; var that = this; callbackCenter.register('aimPos', function(aimInfo) { that.onAimPos(aimInfo); }); callbackCenter.register('fire', function() { that.onFire(); }); this.image = assets('b1'); this.actors = []; }; Background.prototype.onAimPos = function(aimInfo) { this.aimPosX = aimInfo.x; this.aimPosY = aimInfo.y; }; Background.prototype.onFire = function() { var checkX = this.aimPosX + window.innerWidth / 2; var checkY = this.aimPosY + window.innerHeight / 2; for (var i = this.actors.length - 1; i >= 0; i--) { if (this.actors[i].image.complete && this.actors[i].deadScale == null) { if (Util.checkInBox(checkX, checkY, this.actors[i].area_x, this.actors[i].area_y, this.actors[i].area_w, this.actors[i].area_h)) { this.actors[i].deadScale = 1; break; } } } }; Background.prototype.update = function() { if (Math.random() < 0.02 && this.actors.length < 5) { return; var index = Math.floor(Math.random() * 9); var image = actorList[index]; this.actors.push({ image: image, x: Math.random() * 300 - 150, y: Math.random() * 40, scale: 0.1, area_x: 0, area_y: 0, area_w: 0, area_h: 0 }); } for (var i = 0; i < this.actors.length; i++) { if (this.actors[i].deadScale == null) { this.actors[i].scale += 0.001; if (this.actors[i].scale >= 0.4) { this.actors.splice(i, 1); i--; } } else { this.actors[i].deadScale -= 0.05; if (this.actors[i].deadScale <= 0) { this.actors.splice(i, 1); i--; } } } this.actors.sort(function(a, b) { return a.scale - b.scale; }); }; Background.prototype.draw = function(ctx) { if (this.image.complete) { var srcWidth = this.image.width; var srcHeight = this.image.height; var tarWidth = ctx.canvas.width; var tarHeight = ctx.canvas.height; var width = tarWidth; var height = srcHeight / srcWidth * tarWidth; if (height < tarHeight) { height = tarHeight; width = srcWidth / srcHeight * tarHeight; } var drawWidth = width * 1.2; var drawHeight = height * 1.2; var startX = tarWidth / 2 - drawWidth / 2 - this.aimPosX / (tarWidth / 2) * width * 0.1; var startY = tarHeight / 2 - drawHeight / 2 - this.aimPosY / (tarHeight / 2) * height * 0.1; ctx.drawImage(this.image, startX, startY, drawWidth, drawHeight); for (var i = 0; i < this.actors.length; i++) { if (this.actors[i].image == null) console.log(i); if (this.actors[i].image.complete) { var w = this.actors[i].image.width * this.actors[i].scale; var h = this.actors[i].image.height * this.actors[i].scale; var x = tarWidth / 2 + this.actors[i].x - w / 2 - this.aimPosX / (tarWidth / 2) * width * 0.1; var y = tarHeight / 2 + this.actors[i].y - h / 2 - this.aimPosY / (tarHeight / 2) * height * 0.1; if (this.actors[i].deadScale != null) { y += h * (1 - this.actors[i].deadScale); h = h * this.actors[i].deadScale; } ctx.drawImage(this.actors[i].image, x, y, w, h); this.actors[i].area_x = x; this.actors[i].area_y = y; this.actors[i].area_w = w; this.actors[i].area_h = h; } } } }; exports = Background;
true
90c343833432624058cd2439c1661b8747957ac4
JavaScript
dart-lang/webdev
/dwds/debug_extension/web/devtools.js
UTF-8
2,238
2.578125
3
[ "BSD-3-Clause" ]
permissive
(function loadDevToolsScript() { const DDR_DART_APP_ATTRIBUTE = 'data-ddr-dart-app'; // Note: Changes to the DEBUGGER_PANEL_NAME and INSPECTOR_PANEL_NAME // must be reflected in `tool/update_dev_files.dart` as well. const DEBUGGER_PANEL_NAME = 'Dart Debugger'; const INSPECTOR_PANEL_NAME = 'Flutter Inspector'; let debuggerCreated = false; let inspectorCreated = false; let checkDartCount = 0; let checkFlutterCount = 0; chrome.devtools.network.onNavigated.addListener(createDebuggerPanelIfDartApp) const checkDartAppInterval = setInterval(createDebuggerPanelIfDartApp, 1000) createDebuggerPanelIfDartApp() function createDebuggerPanelIfDartApp() { if (debuggerCreated || checkDartCount++ > 20) { clearInterval(checkDartAppInterval); return; } checkIsDartApp(); } function checkIsDartApp() { // TODO(elliette): Remove the DDR data attribute check when we are ready to launch externally, // and instead replace it with the following: !!window.$dartAppId // Note: we must remove the useContentScriptContext option as well. chrome.devtools.inspectedWindow.eval( `document.documentElement.hasAttribute("${DDR_DART_APP_ATTRIBUTE}")`, { useContentScriptContext: true }, function (isDartApp) { if (!isDartApp) return; chrome.devtools.panels.create( DEBUGGER_PANEL_NAME, '', 'debugger_panel.html' ); debuggerCreated = true; createInspectorPanelIfFlutterApp(); }); } function createInspectorPanelIfFlutterApp() { const checkFlutterAppInterval = setInterval(function () { if (inspectorCreated || checkFlutterCount++ > 10) { clearInterval(checkFlutterAppInterval); return; } // The following value is loaded asynchronously, which is why // we check for it every 1 second: chrome.devtools.inspectedWindow.eval( '!!window._flutter_web_set_location_strategy', function (isFlutterWeb) { if (isFlutterWeb) { chrome.devtools.panels.create( INSPECTOR_PANEL_NAME, '', 'inspector_panel.html' ); inspectorCreated = true; } } ); }, 1000) } }());
true
042112a3209f6b7af105f2c68b304fbee9e791c6
JavaScript
yiy142/gallerize
/server/store.js
UTF-8
4,817
2.5625
3
[ "MIT" ]
permissive
"use strict"; const _ = require("lodash"); const bodyParser = require("body-parser"); const express = require("express"); const mongodb = require("mongodb"); const colors = require("colors/safe"); const app = express(); const cors = require('cors'); app.options('*', cors()); const MongoClient = mongodb.MongoClient; const port = process.env.port || 7001; const mongoCreds = require("./auth.json"); const mongoURL = `mongodb://${mongoCreds.user}:${mongoCreds.password}@127.0.0.1/gallerize?authSource=admin` const mongoose = require("mongoose"); mongoose.set('useCreateIndex', true); function makeMessage(text) { return `${colors.blue("[store]")} ${text}`; } function log(text) { console.log(makeMessage(text)); } function error(text) { console.error(makeMessage(text)); } function failure(response, text) { const message = makeMessage(text); console.error(message); return response.status(500).send(message); } function success(response, text) { const message = makeMessage(text); console.log(message); return response.send(message); } function mongoConnectWithRetry(delayInMilliseconds, callback) { mongoose.connect(mongoURL,{ useNewUrlParser: true },(err, connection) => { //MongoClient.connect(mongoURL, { useNewUrlParser: true}, (err, connection) => { if (err) { console.error(`Error connecting to MongoDB: ${err}`); setTimeout( () => mongoConnectWithRetry(delayInMilliseconds, callback), delayInMilliseconds ); } else { log("connected succesfully to mongodb"); callback(connection); } } ); } let Draw = require("./models/draw.model"); function serve() { mongoConnectWithRetry(2000, connection => { app.use(cors()); app.use(express.json()); //app.use(bodyParser.json({ limit: "50mb" })); // added bll //app.use(bodyParser.urlencoded({ extended: true, limit: "50mb" })); console.log('Connected to mongo server.'); app.post("/db/add", (req, res) => { console.log(`In Add.`); const newDraw = new Draw({ filename: req.body.filename, age: req.body.age, valid: req.body.valid, class: req.body.class }); newDraw .save() .then(() => res.json("new Draw added!")) .catch(err => res.status(400).json("Error: " + err)); }); /* Update Data Query */ app.put("/db/update-data", (request, response) => { Draw.findOneAndUpdate({ filename: request.body.filename }, {valid: request.body.valid }, {new: true}, (error, result)=>{ if(error){ response.status(400).json("Error: " + error); } else{ response.status(200).send("valid updated!"); } } ); }); /* Get all classes query*/ app.get("/db/get-classes", (request, response) => { console.log(request.body); Draw.find().distinct('class', function (err, result) { if (err) { response.status(400).json("Error: " + err); } else { response.status(200).json(result.sort()); } } ); }); /* Get Data Query */ app.post("/db/get-data", (request, response) => { console.log(request.body); const order = request.body.order; const range = request.body.ageRange; const classes = request.body.classes; const validToken = parseInt(request.body.validToken); //-1 only invalids. 0 unchecked. 1 only valids. 2 for ALL let valids = [validToken]; if (validToken === 2) { valids = [-1, 0, 1]; } console.log(valids); var sortObject = { }; if (order === "Age (Young - Old) Group By Class"){ sortObject.age = 1; sortObject.class = 1; } else if( order === "Age (Old - Young) Group By Class") { sortObject.age = -1; sortObject.class = 1; } else if (order === "Class (A - Z) Group By Age"){ sortObject.class = 1; sortObject.age = 1; } else if( order === "Class (Z - A) Group By Age") { sortObject.class = -1; sortObject.age = 1; } Draw.aggregate([ { $match: { class: { $in: classes }, age: { $gte: parseInt(range[0]), $lte: parseInt(range[1]) }, valid: { $in: valids } } }, { $sort: sortObject } ], function (err, result) { if (err) { response.status(400).json("Error: " + err); } else { response.json(result); } } ); }); app.listen(port, () => { log(`running at http://localhost:${port}`); }); }); } serve();
true
f401f098646681f5aa8e63cfecbb88e08935a2c2
JavaScript
chezhiangit/BabyCare
/App/Reducers/babyDetailsReducer.js
UTF-8
1,072
2.75
3
[]
no_license
const DEFAULT_STATE = [{ key:'', babyName:'', DOB:'', placeOfBirth:'', birthWeight:'', lengthAtBirth:'', bloodGroup:'', identification:'', remarks:'' }] export default (state = DEFAULT_STATE, action)=> { // console.log('baby details reducer : Action type: '+action.type) switch(action.type) { case 'LOAD_BABYDETAILS': return { ...state, babyDetails:action.data } // case 'ADD_BABYDETAILS': // return { // ...state, // babyDetails:[...state.babyDetails,action.data.item] // } // case 'UPDATE_BABYDETAILS': // const updatelist = [...state.babyDetails]; // updatelist[action.data.index]=action.data.item // return { // ...state, // babyDetails:updatelist // } // case 'DELETE_BABYDETAILS': // const babylist = [...state.babyDetails]; // babylist.splice(action.data.index, 1); // return { // ...state, // babyDetails:babylist // } default: return state } }
true
1ad6c669736c92a9edb1068627aaf55f0d31882a
JavaScript
Seb6277/form_project
/routes/event.js
UTF-8
833
2.546875
3
[]
no_license
const express = require('express'); const router = express.Router(); // Event model const Event = require('../models/Event'); router.get('/places', (req, res) => { Event.find((err, items) => { if (err) { console.log(err); res.end(); } else { res.send(items); res.end(); } }); }); router.post('/create', (req, res) => { if ((req.body.name !== null) && (req.body.nbr_places !== null)) { const newEvent = new Event({ "name": req.body.name, "nbr_places": req.body.nbr_places }); newEvent.save().then((item) => { res.status(201).json(item).end(); }).catch((error) => { console.log(error); res.status(500).end(); }); } }); module.exports = router;
true
443a4ff8aedf88bdd4dc02e21584ecf85dbf6b2a
JavaScript
nttung1211/coding-archive
/node/Jonas/bootcamp/1-node-farm/starter/index.js
UTF-8
1,227
3.078125
3
[]
no_license
// SYNCHRONOUS // const fs = require('fs'); // const data = fs.readFileSync(__dirname + '/txt/input.txt', { encoding: 'utf-8' }); // console.log(data); // const input = `Nguyễn Thanh Tùng: ${data}`; // fs.writeFileSync(__dirname + '/txt/output.txt', input, { flag: 'w' }); //======================================================================================= // ASYNCHRONOUS // const fs = require('fs'); // fs.readFile('./txt/input.txt', 'utf-8', (err, data) => { // if options is string it will see as encoding // if (err) { // console.log(err); // } else { // fs.writeFile('./txt/output.txt', data, { flag: 'w' }, (err) => { // if (err) { // console.log(err); // } else { // console.log('Wrote file successfully.'); // } // }); // } // }); // console.log('Reading file...'); //================================================================================================ // CREATE FIRST WEB SERVER // const http = require('http'); // const server = http.createServer(requestListener); // function requestListener(req, res) { // res.end('Tung dep trai'); // } // server.listen(3000, '127.0.0.1', () => { // console.log('Server is listening on port 3000'); // });
true
90fcf512371ce84d05611a019db93174f3b02a8b
JavaScript
hoodielive/esVersions
/es6/syntax-changes-additions/fatArrows/fatArrow.js
UTF-8
297
3.9375
4
[]
no_license
// let fn = () => console.log('Hellerrrrr!'); let fn = () => "Hello!"; console.log(fn()); let fn2 = () => { let a = 2; let b = 3; return a + b; } console.log(fn2()); // or let fn3 = (a, b) => a + b console.log(fn3(3, 8)); setTimeout(() => console.log("Helleeerrrr!"), 1000);
true
568e7b2dae11b5ff0780a77d75628949e927d0a4
JavaScript
creograf-experience/2sport
/app/client/public/lib/workout-instagram.js
UTF-8
1,578
2.625
3
[]
no_license
import _ from 'lodash'; import d3 from 'd3'; export function drawChartInstagram(element, times, values) { var margin = {top: 20, right: 20, bottom: 30, left: 20}, width = 612 - margin.left - margin.right, height = 120 - margin.top - margin.bottom; // Set the ranges var x = d3.time.scale() .domain(d3.extent(times, d => d)) .range([0, width]); var y = d3.scale.linear() .domain([0, _.max(values)]) .nice(1) .range([height, 0]); // Define the axes var xAxis = d3.svg.axis() .scale(x) .ticks(5) .tickFormat(d3.time.format.utc('%H:%M')) .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .orient("right") .tickSize(width) .ticks(4); // Define the line var valueline = d3.svg.line() .x(d => x(d[0])) .y(d => y(d[1])); // Adds the svg canvas var svg = d3.select(element) .append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", `translate(${margin.left},${margin.top})`); // Add the valueline path. svg.append("path") .attr("class", "line") .attr("d", valueline(_.zip(times, values))); // Add the X Axis svg.append("g") .attr("class", "x axis") .attr("transform", `translate(0,${height})`) .call(xAxis); // Add the Y Axis const gy = svg.append("g") .attr("class", "y axis") .call(yAxis); gy.selectAll("g").filter(d => d) .classed("minor", true); gy.selectAll("text") .attr("x", 4) .attr("dy", -4); }
true
7d2ed25615003296ccf65a87e6a4f9440002dc28
JavaScript
teintinu/bd-stampy
/utils/Paginate.js
UTF-8
278
2.6875
3
[ "BSD-3-Clause" ]
permissive
/*eslint-disable */ var Paginate = function (array, ammount, page){ var start = page * ammount; var end = start + ammount; if(start >= array.length) { start = array.length - ammount; } return array.slice(start, end); }; module.exports = Paginate;
true
f961229244ad131a26369a4806b975dac06497a8
JavaScript
comicrelief/lambda-wrapper
/src/Model/Model.model.js
UTF-8
771
2.890625
3
[]
no_license
/* eslint-disable class-methods-use-this */ import validate from 'validate.js/validate'; /** * Model base class */ export default class Model { /** * Instantiate a function with a value if defined * * @param classFunctionName string * @param value mixed */ instantiateFunctionWithDefinedValue(classFunctionName, value) { if (typeof value !== 'undefined') { this[classFunctionName](value); } } /** * Validate values against constraints * * @param values object * @param constraints object * @returns {boolean} */ validateAgainstConstraints(values: object, constraints: object): boolean { const validation = validate(values, constraints); return typeof validation === 'undefined'; } }
true
eb5bbfdbef30bc079164b0e0569b33019ec9b904
JavaScript
vvuri/learn_babel
/src/main.js
UTF-8
205
2.71875
3
[]
no_license
let a = 5; const b = ("const"[(a, b)] = [b, a]); class First { constructor(x) { this.x = x; } } class Second extends First { set x(d) { this.x = d; } get x() { return this.x; } }
true
2a153cad7072d88d74be39a987981f970f5d9185
JavaScript
trentclainor/ready
/ready.js
UTF-8
445
2.6875
3
[]
no_license
var ready = function(f) { if (!ready.r) ready.r = []; if (!ready.t) ready.t = null; ready.r.push(f); var run = function() { clearTimeout(ready.t); while (ready.r.length) ready.r.splice(0,1)[0](); } var check = function() { if (document && document.getElementsByTagName && document.getElementById && document.body) { run(); } else { ready.t = setTimeout(check, 13); } } if (ready.t == null) check(); return ready; };
true
750891761ab63ef41e44acb1fc86bd39571c517e
JavaScript
kilic/relais
/test/helpers/dateHelper.js
UTF-8
297
2.953125
3
[]
no_license
const DAY = 86400 function now() { return Math.round(new Date().getTime()/1000) } function yesterday() { return Math.round(new Date().getTime()/1000) - DAY } function daysAhead(days) { return Math.round(new Date().getTime()/1000) + DAY*days } module.exports = {now,yesterday,daysAhead}
true
2b0c7e07630e3a9fd14bea65881532d012347fe8
JavaScript
Barry-B15/weather-app
/public/js/app.js
UTF-8
1,945
3.21875
3
[]
no_license
//11 p5.js uses a set up func, create one and move all code inside it function setup() { noCanvas(); //11.2 we do not need a canvas for this project const video = createCapture(VIDEO); //11.3 we need videocam instead video.size(300, 240); // resize the video //8.1 def the lat lon let lat, lon; //def the btn and add click listener const button = document.getElementById('submit'); button.addEventListener('click', async event => { const status = document.getElementById('status').value; //11.4 def a const to hold the image video.loadPixels(); //1st tell video to load pixels const img64 = video.canvas.toDataURL(); const data = { lat, lon, status, img64 // 11.5 add the new image to data set }; const options = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }; const response = await fetch('api', options); const json = await response.json(); console.log(json); }); //take data (geolocation) from client if ('geolocation' in navigator) { console.log('geolocation available'); //get current position navigator.geolocation.getCurrentPosition(async position => { //def lat lon and get the coords lat = position.coords.latitude; lon = position.coords.longitude; document.getElementById('latitude').textContent = lat; document.getElementById('longitude').textContent = lon; console.log(position); //console log the pos }); } else { console.log('geolocation not available'); // if geolocation is not available } //11.1 test to see a canvas created by adding p5.js //background(255, 0, 0); // we will not use it, so remove }
true
9408741a7bfa41dc8c5ca75f6aeab0e313c7efbb
JavaScript
lfgg/lfgg.github.io
/assets/js/lfgg.js
UTF-8
4,482
2.515625
3
[]
no_license
const Nav = { elems: { toggle: document.querySelector('#toggle-nav'), site: document.querySelector('#site') }, isOpen: false, toggle: function() { document.documentElement.classList.toggle('nav-open'); this.isOpen = !this.isOpen; }, open: function() { document.documentElement.classList.add('nav-open'); this.isOpen = true; }, close: function() { document.documentElement.classList.remove('nav-open'); this.isOpen = false; }, init: function() { this.elems.toggle.addEventListener('click', (e) => { e.preventDefault(); this.toggle(); }); window.addEventListener('resize', (e) => { this.close(); }); this.elems.site.addEventListener('click', (e) => { if (this.isOpen) { this.close(); } }); } } Nav.init(); const PostFilters = { elems: { filters: null, clearFilters: null }, shuffleInstance = null, init: function() { var Shuffle = window.Shuffle; var shuffleWrap = document.querySelector('.c-filter-posts'); this.elems.filters = document.querySelectorAll('.js-filter'); this.elems.clearFilters = document.querySelector('.js-clear-filters'); if (this.elems.filters && this.elems.clearFilters) { this.shuffleInstance = new Shuffle(shuffleWrap, { itemSelector: '.c-card' }); this.elems.filters.forEach((filter) => { filter.addEventListener('click', (e) => { e.preventDefault(); this.elems.filters.forEach((filter) => { filter.classList.remove('is-active'); }); filter.classList.add('is-active'); let cat = filter.getAttribute('data-category'); this.shuffleInstance.filter(cat); // Show clear filters btn this.elems.clearFilters.classList.add('is-visible'); }); }); this.elems.clearFilters.addEventListener('click', (e) => { e.preventDefault(); this.elems.filters.forEach((filter) => { filter.classList.remove('is-active'); }); // Show all items this.shuffleInstance.filter(); // Hide clear filters btn this.elems.clearFilters.classList.remove('is-visible'); }); } } } PostFilters.init(); const LazyLoadHandler = { lazyLoad: null, init: function() { this.lazyLoad = new LazyLoad({ elements_selector: '.lazy' }); } } LazyLoadHandler.init(); const Page = { elems: { loader: document.querySelector('#loader') }, init: function() { const swup = new Swup({ elements: ['#page-main'], animationSelector: '[class*="u-transition-"]' }); swup.on('animationOutStart', () => { // Hide mobile menu Nav.close(); let newLoader = this.elems.loader.cloneNode(true); this.elems.loader.parentNode.replaceChild(newLoader, this.elems.loader); this.elems.loader = newLoader; }); swup.on('contentReplaced', () => { let lazyImgs = document.querySelectorAll('.lazy'); lazyImgs.forEach((el) => { el.classList.remove('loaded'); el.classList.remove('initial'); el.classList.remove('loading'); el.setAttribute('data-was-processed', ''); }); }); swup.on('animationInDone', () => { LazyLoadHandler.init(); PostFilters.init(); }); // Back button swup.on('popState', () => { setTimeout(function() { let lazyImgs = document.querySelectorAll('.lazy'); lazyImgs.forEach((el) => { el.classList.add('loaded'); }); PostFilters.init(); }, 100); }); window.addEventListener('load', () => { setTimeout(() => { document.documentElement.classList.remove('is-animating', 'is-preload'); }, 500); }); } } Page.init();
true
a0979c3e92c4efa06b7f8cc9d71f98b1aeaf5052
JavaScript
emanuelecaruso/InteractiveGraphics
/models/robot.js
UTF-8
1,162
3.359375
3
[]
no_license
// call the render function var step = 0; // once everything is loaded, we run our Three.js stuff. var keyboard = new THREEx.KeyboardState(); var velocity=0; var maxvelocity= 3.5; var robotScale=2; // create meshes var sphere = createMesh(new THREE.SphereGeometry(robotScale, 10, 10)); sphere.position.set(0,-2,0); var neck = createMesh(new THREE.CylinderGeometry(0.1*robotScale,0.1*robotScale,2,7*robotScale)) neck.position.set(0,0,0); var robot = new THREE.Group(); robot.add( neck ); robot.add( sphere ); // add the sphere to the scene scene.add(robot); neck.add(sphere); //render(); function moveRobot() { if(keyboard.pressed("D")) { if (velocity<maxvelocity) velocity += 0.1; } else if(keyboard.pressed("A")) { if (velocity>-maxvelocity) velocity -= 0.1; } else { if (Math.abs(velocity)>0.01) velocity = velocity/1.1; else velocity = 0; } sphere.rotation.z = step -= 0.05*velocity; var axis = new THREE.Vector3(neck.position.x+(velocity),neck.position.y,0); neck.translateOnAxis(neck.worldToLocal(axis),0.05); }
true
56a302179fcdff7643d9280f10300c5731cb870b
JavaScript
randelreiss/tutorial
/server.js
UTF-8
2,053
3.21875
3
[]
no_license
// An HTTP server with a callback function // that is called for each request. // In the callback function, you create a response // with a status code of 200 (indicating that the request // was fulfilled successfully) and the message "Hello World". // Finally, you specify which port the server listens to. // When Node.js projects run within Cloud 9 IDE, // you can retrieve the port information with process.env.PORT var appName = String("Randel's Tutorial"); var appVersion = String("0.0"); var appCopyright = String("2011, ALL RIGHTS RESERVED"); // Name of the module for the name of the local variable var localHTTP = require('http'); var localURL = require("url"); // Extend server's start() function to pass the route function function start(route) { function onRequest(req, res) { // server code console.log("Request Received"); var pathname = localURL.parse(req.url).pathname; console.log("Request for " + pathname + " received."); route(pathname); switch (pathname) { case '/': res.writeHead(200, {'Content-Type': 'text/plain'}); appId(res); res.end('res.end\n'); break; default: fourZeroFour(res); } } var server = localHTTP.createServer(onRequest); if (process.env.PORT === undefined) { console.log('Running locally; browse to http://localhost:8888/\n'); server.listen(8888, '127.0.0.1'); } else { // Running on c9.io. server.listen(process.env.PORT, '0.0.0.0'); console.log("Server has started."); console.log("Listning on port: " + process.env.PORT); } } // Export this function exports.start = start; function appId(res) { res.write("Welcome to " + appName + "\n"); res.write("Version: " + appVersion + "\n"); res.write("Copyright " + appCopyright + "\n"); } function fourZeroFour(res) { res.writehead(404); res.write("Yeah, baby, where saying: 404 Not found./n"); res.end("res.end\n"); }
true
a7cf65f08ff2edda69765a825adf1d7e37e1eeb9
JavaScript
hello-chenchen/leet-code-algorithms
/linked-list/leetcode-1290/solution.js
UTF-8
533
3.609375
4
[ "WTFPL" ]
permissive
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @return {number} */ var getDecimalValue = function(head) { let result = 0; while(undefined != head) { if(1 == head.val) { result = (result << 1) + 1; } else { result = result << 1; } head = head.next; } return result; };
true
8408842bca2a527b063d125b1b1aa14afe8e38ff
JavaScript
Foorkan14/functions
/arrowfunctions/arrowfunctions.js
UTF-8
2,281
4.96875
5
[]
no_license
//alternative way of writingfunctions //dont have to wrte functinn keyword all you have to do is this: //example 1 a function expression without arrow format // const square = function(x){ //x is what will be passed through as the argument // return x * x; // } // //now same function as arrow function // const square = (x) => { // return x * x; // } //really only difference is that we dont write function key word //they also behave differently when it comes to the keyword this //example 2 const isEven = (num) =>{ return num % 2 === 0; } console.log(isEven(4)); //will return true //example 3 const multiply = (x, y) =>{ return(x * y); } //2 rules for arrow functions //rule 1 parenthesis are optioma if there is only one parameter const square = x =>{ return x * x; } //rule number 2 you can use empty parenthesis for functions with no parameters; const singAsong = () => { return "LA LA LA LA LA LA "; } //ARROW FUNCTIONS WITH IMPLICIT RETURN STATEMENTS //WORKS IN CERTAIN SCENARIOS //MEANS YOU DONT HAVE TO WRITE RETURN STATEMENT ITSELF //EXAMPLE 1 // const square = n => { // return n * n; // } //consists of a single expression that we are returning,we arent doing any other logic first, we arent using a conditional , we arent making a variable we are simply returning a expression //in scenarios where we are returning a expressuon we can rewrite the function with parenthesis instead of curly brackets const square = n => ( n * n ) //we can even leave out the parenthesis and do everything in one line const square = n => n * n //with arrays //example 1 without arrow function const nums = [1, 2, 3, 4, 5, 6, 7, 8]; const doubles1 = nums.map(function(n){ return n * 2; }) //now use arrow function const doubles2 = nums.map(n =>{ return n *2 }) //since we have single expression in this case n we can rewrite the function with parenthesis instead const doubles3 = nums.map(n => n * 2); // example 2 const parodyList = nums.map(function(n){ if (n%2 ===0){ return even; }else{ return odd; } }) //now same function as arrow function const parodyList = nums.map(n =>{ if (n%2 === 0){ return 'even'; } else{ return 'odd'; } })
true
691b21d0172e688d2f603554b8815b14d4b11e6a
JavaScript
MidoriyaDeku/algorithm
/search/binary_search_tree.js
UTF-8
6,203
3.796875
4
[]
no_license
// 二叉查找树结构 function BSTree(data, left, right, parent) { this.data = data; this.left = left; this.right = right; this.parent = parent; } // 二叉查找树的插入操作 // bstree 查找树;data 要插入的数; function insertBST(bstree, data) { var current = bstree; // 当前节点 var parent = null; // 父节点 while (true) { parent = current; // 当前为父节点 // 要插入的数据 小于当前节点的数据 if (data < current.data) { current = current.left; // 当前节点为左节点 if (current === null) { // 如果当前节点为空直接插入这个节点 parent.left = new BSTree(data, null, null, parent); break; } } else { // 大于等于当前节点的数走这里 current = current.right; // 当前节点为左节点 if (current === null) { // 如果当前节点为空直接插入这个节点 parent.right = new BSTree(data, null, null, parent); break; } } } } // 创建二叉查找树 // list 要创建的数据表 function createBST(list) { // 构建BST中的根节点 var bstree = new BSTree(list[0], null, null, null); for (var i = 1; i < list.length; ++i) { insertBST(bstree, list[i]); } return bstree; } // 在二叉查找树中搜索指定节点的数据 // bstree 查找树;data 要在树中查找的数 function searchBST(bstree, data) { // 如果bstree为空,说明已经遍历到头了 if (bstree === null) { return false; } // 找到了 if (bstree.data === data) { return true; } if (data < bstree.data) { return searchBST(bstree.left, data); } else { return searchBST(bstree.right, data); } } // 先序遍历二叉查找树 // bstree 查找树 function dlrBST(bstree) { if (bstree != null) { // 输出节点数据 console.log(bstree.data + ""); // 遍历左子树 dlrBST(bstree.left); // 遍历右子树 dlrBST(bstree.right); } } // 中序遍历二叉查找树 // bstree 查找树 function ldrBST(bstree) { if (bstree != null) { // 遍历左子树 ldrBST(bstree.left); // 输出节点数据 console.log(bstree.data + ""); // 遍历右子树 ldrBST(bstree.right); } } // 后序遍历二叉查找树 // bstree 查找树 function lrdBST(bstree) { if (bstree != null) { // 遍历左子树 lrdBST(bstree.left); // 遍历右子树 lrdBST(bstree.right); // 输出节点数据 console.log(bstree.data + ""); } } // 删除二叉排序树中指定key节点 // bstree 查找树;key 要删除的key节点 function deleteBST(bstree, data) { if (bstree === null) { return; } if (bstree.data === data) { // 第一种情况:叶子节点 if (bstree.left === null && bstree.right === null) { if (bstree.data < bstree.parent.data) { bstree.parent.left = null; } else { bstree.parent.right = null; } delete bstree; bstree = null; return; } // 第二种情况:左子树不为空 if (bstree.left !== null && bstree.right === null) { if (bstree.left.data < bstree.parent.data) { bstree.parent.left = bstree.left; } else { bstree.parent.right = bstree.left; } delete bstree; bstree = null; return; } // 第三种情况,右子树不为空 if (bstree.left === null && bstree.right !== null) { if (bstree.right.data < bstree.parent.data) { bstree.parent.left = bstree.right; } else { bstree.parent.right = bstree.right; } delete bstree; bstree = null; return; } // 第四种情况,左右子树都不为空 if (bstree.left !== null && bstree.right !== null) { var node = bstree.right; // 被删除节点的右孩子 //找到右子树中的最左节点 while (node.left !== null) { node = node.left; // 遍历它的左子树 } // 替换掉要删除的节点的数据(将要删除节点的右子树的最左节点的数据给它) bstree.data = node.data; // 删除节点的右节点没有左节点的时候。即上边的while循环没执行。 if (node.parent.right === node) { bstree.right = node.right; } else { // 删除节点的右节点有左节点的时候。 if (node.parent.left === node) { node.parent.left = node.right; } } node = null; // 将换位到删除节点去的右子树的最左子树赋值为空。 return; } } /* 60 30 80 10 35 70 120 20 90 */ if (data < bstree.data) { deleteBST(bstree.left, data); } else { deleteBST(bstree.right, data); } } var list = [60, 30, 80, 10, 120, 90, 70, 20, 35]; var data = 20; var bstree = createBST(list); console.log("-----中序遍历-----"); ldrBST(bstree); console.log("-----中序遍历-----"); /*var is_include = searchBST(bstree, data); console.log(data, "是否包含在二叉树中: ", is_include);*/ /*var del_value = 60; deleteBST(bstree, del_value); console.log("删除二叉树中的", del_value); console.log("-----中序遍历-----"); ldrBST(bstree); console.log("-----中序遍历-----");*/
true
094853d82b57829029a6b82a1ee651f176fe51eb
JavaScript
DevNeoLee/canadaTouristRefactor
/src/main.js
UTF-8
2,198
3.046875
3
[ "MIT" ]
permissive
//load raw CSV, travel_province_data using D3.js //prepare only relavant data set array of objects //initiate putting minimized data cut with default or listened event input import { putData } from './put_data.js'; d3.csv('data/travel_province_data.csv', function(data) { const initialDataCut = []; data.forEach((ele) => { if ((ele.GEO == "Newfoundland and Labrador" || ele.GEO == "Prince Edward Island" || ele.GEO == "Nova Scotia" || ele.GEO == "New Brunswick" || ele.GEO == "Quebec" || ele.GEO == "Ontario" || ele.GEO == "Manitoba" || ele.GEO == "Saskatchewan" || ele.GEO == "Alberta" || ele.GEO == "British Columbia" || ele.GEO == "Yukon" || ele.GEO == "Nunavut") && (ele['Traveller characteristics'] == "Total non resident tourists") && (ele['Seasonal adjustment'] == "Unadjusted") && (ele.REF_DATE[0] == '2')) { initialDataCut.push(ele); } }); //eventListener for 'year' data input //send data to 'putData' method document.querySelector('.select').addEventListener("change", function () { //firstly delete previous data d3.selectAll("svg") .remove(); //call putData method putData(initialDataCut, document.querySelector('.select').value, document.querySelector('.slider').value); }); const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; //eventListner for 'month' data input //send dat to 'putData' method document.querySelector('.slider').addEventListener("change", function () { const value = document.querySelector('.slider').value; document.querySelector('.monthDisplay').innerText = months[value - 1]; //firstly delete previous data d3.selectAll("svg") .remove(); //call putData method putData(initialDataCut, document.querySelector('.select').value, value); }); //call initial default drawing with default data putData(initialDataCut); });
true
b335a1e840e6accea9cc4c8f8c3c3cdaaa78059a
JavaScript
emddutton/diceroller
/dice.js
UTF-8
1,905
2.921875
3
[]
no_license
/** * Created by emddutton on 3/4/2015. */ $(document).ready(function(){ function reset() { $(".dice").removeClass('animated shake'); $(".dots").hide(); console.log('bye'); } function roll(side) { var one = (side + ".centerdot"); var two = (side + '.rightcorner'); var three = (side + '.leftcorner'); var four = (side + '.rightbottom'); var five = (side + '.leftbottom'); var six = (side + '.sideright'); var seven = (side + '.sideleft'); var diceroll = Math.floor(Math.random() * 6 + 1); if (diceroll == 1) { $(one).show(); console.log('one'); } else if (diceroll == 2) { $(three).show(); $(four).show(); console.log('two'); } else if (diceroll == 3) { $(one).show(); $(three).show(); $(four).show(); console.log('three'); } else if (diceroll == 4) { $(two).show(); $(three).show(); $(four).show(); $(five).show(); console.log('four'); } else if (diceroll == 5) { $(one).show(); $(two).show(); $(three).show(); $(four).show(); $(five).show(); console.log('five'); } else if (diceroll == 6) { $(two).show(); $(three).show(); $(four).show(); $(five).show(); $(six).show(); $(seven).show(); console.log('six'); } return diceroll; } $('button').on('click', function() { reset(); $(".dice").addClass('animated shake'); setTimeout(function() { roll(".left"); roll(".right"); }, 1000); }); });
true
a6a67b75e4ea0a0b45b7d2d729f2f7819fa9b47b
JavaScript
DN8630/lotide
/middle.js
UTF-8
488
2.984375
3
[]
no_license
const eqArray = require("./eqArrays"); const assertArrayEqual = require("./assertArraysEqual"); const middle = function(array) { let output = []; let arrLength = array.length; let index = parseInt((arrLength - 1) / 2); if (arrLength <= 2) { return output; } else if (arrLength % 2 === 0) { output.push(array[index]); output.push(array[index + 1]); } else if (arrLength % 2 !== 0) { output.push(array[index]); } return output; }; module.exports = middle;
true
ab75d251fbfa638c2616aa8b5c20d5a6ae77610e
JavaScript
MikeHitrov/SoftUni
/JS Advanced/Exam 19.12.2016/01. Move Towns Up Down (Simple DOM Interaction)/move-up-down.js
UTF-8
301
2.765625
3
[ "MIT" ]
permissive
function move(num) { let selected = $('#towns :selected'); let action = num > 0 ? moveDown : moveUp; action(selected); function moveUp(option) { $(option).insertBefore(option.prev()); } function moveDown(option) { $(option).insertAfter(option.next()); } }
true
bce8e5b32ba8fc7e213571ca2bc356b43654e8a9
JavaScript
hello-kozloff/fodesign
/src/blocks/_parts/navigation/navigation.js
UTF-8
460
2.53125
3
[]
no_license
$(document).ready(() => { $(".navigation").on('click', function(event) { if (event.target !== this) return; hideNavigationPanel(); }); $(".navigation__button").on("click", function (event) { event.preventDefault(); hideNavigationPanel(); }); }); function hideNavigationPanel() { const _navigation = $(".navigation"); _navigation.toggleClass("navigation_hidden"); $("body").removeClass("fixed"); }
true