{ // 获取包含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"}}},{"rowIdx":1305,"cells":{"text":{"kind":"string","value":"module Main where\n\nimport Utilities\n\n-- Input processing\n\ntype Input = [Int]\n\nparse :: String -> Input\nparse = map read . lines\n\n-- Part One\n\nsolve1 :: Input -> Int\nsolve1 xs = head [product ns | (ns, _) <- choose 2 xs, sum ns == 2020]\n\ntests1 :: [(String, Int)]\ntests1 = [(testInput, 514579)]\n\ntestInput :: String\ntestInput = \"\\\n \\1721\\n\\\n \\979\\n\\\n \\366\\n\\\n \\299\\n\\\n \\675\\n\\\n \\1456\\n\"\n\n-- Part Two\n\nsolve2 :: Input -> Int\nsolve2 xs = head [product ns | (ns, _) <- choose 3 xs, sum ns == 2020]\n\ntests2 :: [(String, Int)]\ntests2 = [(testInput, 241861950)]\n\nmain :: IO ()\nmain = do\n s <- readFile \"input/01.txt\"\n let input = parse s\n putStr (unlines (failures \"solve1\" (solve1 . parse) tests1))\n print (solve1 input)\n putStr (unlines (failures \"solve2\" (solve2 . parse) tests2))\n print (solve2 input)\n"}}},{"rowIdx":1306,"cells":{"text":{"kind":"string","value":"class TopApps::Scraper\n def self.scrape_index(index_url)\n doc = Nokogiri::HTML(open(index_url))\n free_apps_section = doc.css(\".section.chart-grid.apps div.section-content\").first\n free_apps_list = free_apps_section.css(\"li\")\n\n free_apps_list.map do |app|\n {\n name: app.css(\"h3 a\").text,\n category: app.css(\"h4 a\").text,\n rank: app.css(\"strong\").text.chomp(\".\"),\n profile_url: app.css(\"a\").attribute(\"href\").value\n }\n end\n end\n\n def self.scrape_profile(profile_url)\n doc = Nokogiri::HTML(open(profile_url))\n notes = doc.css(\"div.we-editor-notes.lockup.ember-view p\").text.strip\n notes == \"\" ? notes = \"Unavailable.\" : nil\n\n {\n notes: notes,\n developer: doc.css(\"h2.product-header__identity.app-header__identity a\").text,\n rating: doc.css(\"figcaption.we-rating-count.star-rating__count\").text.split(\",\").first\n }\n end\nend\n"}}},{"rowIdx":1307,"cells":{"text":{"kind":"string","value":"delete();\n\n\t\t$userIds = App\\Models\\User::all()->pluck('id')->toArray();\n \t$messageSubjectIds = App\\Models\\MessageSubject::all()->pluck('id')->toArray();\n\n \tif(count($messageSubjectIds) > 0 && count($userIds) > 0){\n foreach ($messageSubjectIds as $messageSubject) {\n \tforeach ($userIds as $user) {\t \n\t $data = [\n\t [\n\t \"user_id\" => $user,\n\t \"message_subject_id\" => $messageSubject,\n \"created_at\" => strftime(\"%Y-%m-%d %H:%M:%S\"),\n \"updated_at\" => strftime(\"%Y-%m-%d %H:%M:%S\")\n\t ]\n\t ];\n\n \tDB::table(\"message_participants\")->insert($data);\n\t\t\t\t} \t\n }\n\n }\n }\n}\n"}}},{"rowIdx":1308,"cells":{"text":{"kind":"string","value":"package excel_data_import.repository.implementation;\r\n\r\nimport javax.persistence.EntityManager;\r\n\r\nimport excel_data_import.domain.Match;\r\nimport excel_data_import.repository.MatchRepository;\r\n\r\npublic class MatchRepositoryImpl implements MatchRepository {\r\n\r\n\t@Override\r\n\tpublic void persist(Match match) {\r\n\r\n\t\ttry {\r\n\t\t\tEntityManager entityManager = HaurRankingDatabaseUtils.createEntityManager();\r\n\t\t\tentityManager.getTransaction().begin();\r\n\r\n\t\t\tentityManager.persist(match);\r\n\t\t\tentityManager.getTransaction().commit();\r\n\r\n\t\t} catch (Exception e) {\r\n\t\t\te.printStackTrace();\r\n\r\n\t\t}\r\n\t}\r\n}\r\n"}}},{"rowIdx":1309,"cells":{"text":{"kind":"string","value":"package crypto\n\nimport (\n\t\"crypto/sha1\"\n\t\"crypto/sha256\"\n\t\"crypto/sha512\"\n\t\"fmt\"\n\t\"hash\"\n\t\"io\"\n\n\tbosherr \"github.com/cloudfoundry/bosh-utils/errors\"\n)\n\nvar (\n\tDigestAlgorithmSHA1 Algorithm = algorithmSHAImpl{\"sha1\"}\n\tDigestAlgorithmSHA256 Algorithm = algorithmSHAImpl{\"sha256\"}\n\tDigestAlgorithmSHA512 Algorithm = algorithmSHAImpl{\"sha512\"}\n)\n\ntype algorithmSHAImpl struct {\n\tname string\n}\n\nfunc (a algorithmSHAImpl) Name() string { return a.name }\n\nfunc (a algorithmSHAImpl) CreateDigest(reader io.Reader) (Digest, error) {\n\thash := a.hashFunc()\n\n\t_, err := io.Copy(hash, reader)\n\tif err != nil {\n\t\treturn nil, bosherr.WrapError(err, \"Copying file for digest calculation\")\n\t}\n\n\treturn NewDigest(a, fmt.Sprintf(\"%x\", hash.Sum(nil))), nil\n}\n\nfunc (a algorithmSHAImpl) hashFunc() hash.Hash {\n\tswitch a.name {\n\tcase \"sha1\":\n\t\treturn sha1.New()\n\tcase \"sha256\":\n\t\treturn sha256.New()\n\tcase \"sha512\":\n\t\treturn sha512.New()\n\tdefault:\n\t\tpanic(\"Internal inconsistency\")\n\t}\n}\n\ntype unknownAlgorithmImpl struct {\n\tname string\n}\n\nfunc NewUnknownAlgorithm(name string) unknownAlgorithmImpl {\n\treturn unknownAlgorithmImpl{name: name}\n}\n\nfunc (c unknownAlgorithmImpl) Name() string { return c.name }\n\nfunc (c unknownAlgorithmImpl) CreateDigest(reader io.Reader) (Digest, error) {\n\treturn nil, bosherr.Errorf(\"Unable to create digest of unknown algorithm '%s'\", c.name)\n}\n"}}},{"rowIdx":1310,"cells":{"text":{"kind":"string","value":"load->model('admin_producto_detalle_model');\n\t}\n\tpublic function index()\n\t{\n\t\t$data= array (\n\t\t\t'title' => 'CRUD || ProductosDetalles');\n\t\t$this->load->view('template/admin_header',$data);\n\t\t$this->load->view('template/admin_navbar');\n\t\t$this->load->view('admin_producto_detalle_view');\n\t\t$this->load->view('template/admin_footer');\n\t}\n\n\t//Funciones mostrar\n\tpublic function get_producto_detalle(){\n\t\t$respuesta= $this->admin_producto_detalle_model->get_producto_detalle();\n\t\techo json_encode($respuesta);\n\t}\n\tpublic function get_producto(){\n\t\t$id = $this->input->post('id');\n\t\t$respuesta = $this->admin_producto_detalle_model->get_producto($id);\n\t\techo json_encode($respuesta);\n\t}\n\t\n\tpublic function get_talla(){\n\t\t$respuesta = $this->admin_producto_detalle_model->get_talla();\n\t\techo json_encode($respuesta);\n\t}\n\tpublic function get_color(){\n\t\t$respuesta = $this->admin_producto_detalle_model->get_color();\n\t\techo json_encode($respuesta);\n\t}\n\tpublic function get_categoria(){\n\t\t$id = $this->input->post('id');\n\t\t$respuesta = $this->admin_producto_detalle_model->get_categoria();\n\t\techo json_encode($respuesta);\n\t}\n\t//Funcion buscar en tabla\n\tpublic function buscar()\n\t{\n\t\t$palabra = $this->input->post('palabra');\n\t\t$respuesta = $this->admin_producto_detalle_model->buscar_palabra($palabra);\n\t\techo json_encode($respuesta);\n\t}\n\n\t//FUNCION ELIMINAR\n\tpublic function eliminar(){\n\t\t$id = $this->input->post('id');\n\t\t$respuesta = $this->admin_producto_detalle_model->eliminar($id);\n\t\techo json_encode($respuesta);\n\t}\n\n\t//FUNCION INGRESAR\n\tpublic function ingresar(){\n\t\t$registro = $this->input->post('registro');\n\t\tif ($registro!=0) {\n\t\t\t$exist = $this->input->post('exist');\n\t\t\t$datos['producto'] = $this->input->post('producto');\n\t\t\t$datos['talla'] = $this->input->post('talla');\n\t\t\t$datos['color'] = $this->input->post('color');\n\t\t\t$cantidadInput= $this->input->post('cantidad');\n\t\t\t\n\t\t\t$cantidadSum=$exist +$cantidadInput;\n\t\t\t$datos['cantidad'] = $cantidadSum;\n\n\t\t\t$respuesta = $this->admin_producto_detalle_model->set_cantidad($datos);\n\t\t\techo json_encode($respuesta);\n\t\t}else{\n\t\t\t$datos['producto'] = $this->input->post('producto');\n\t\t\t$datos['talla'] = $this->input->post('talla');\n\t\t\t$datos['color'] = $this->input->post('color');\n\t\t\t$datos['cantidad'] = $this->input->post('cantidad');\n\t\t\t$respuesta = $this->admin_producto_detalle_model->set_detalle($datos);\n\t\t\techo json_encode($respuesta);\n\t\t}\n\t}\n\n\n\t//FUNCIONES CONSULTAS \n\tpublic function existencia(){\n\t\t$producto = $this->input->post('producto');\n\t\t$talla = $this->input->post('talla');\n\t\t$color = $this->input->post('color');\n\t\t$respuesta = $this->admin_producto_detalle_model->existencia($producto,$talla,$color);\n\t\techo json_encode($respuesta);\n\t}\n\n\n\t//FUNCIONES ACTUALIZAR\n\tpublic function get_datos(){\n\t\t$id = $this->input->post('id');\n\t\t$respuesta = $this->admin_producto_detalle_model->get_datos($id);\n\t\techo json_encode($respuesta);\n\t}\n\n\tpublic function actualizar(){\n\t\t$datos['id'] = $this->input->post('id_producto_detalle');\n\t\t$datos['cantidad'] = $this->input->post('cantidad');\n\n\t\t$respuesta = $this->admin_producto_detalle_model->actualizar($datos);\n\n\t\techo json_encode($respuesta);\n\t}\n\n\n\n\n\t/*public function get_imagen()\n\t{\n\t\t$id = $this->input->post('id');\n\t\t$respuesta= $this->admin_categoria_model->get_imagen($id);\n\t\techo json_encode($respuesta);\n\t}*/\n\n}\n\n\n?>"}}},{"rowIdx":1311,"cells":{"text":{"kind":"string","value":"import { Injectable } from '@angular/core';\nimport { HttpClientModule } from '@angular/common/http';\nimport { HttpClient } from '@angular/common/http';\n\n@Injectable({\n providedIn: 'root'\n})\nexport class CrudServiceService {\n httpOptions = {\n 'responseType': 'xml' as 'json'\n };\n constructor(private http: HttpClient) { }\n\n country: string;\n state: string;\n regNum: string;\n getdata(country:string, state:string, regNumber:string): Promise {\n return new Promise((resolve, reject) => {\n var func, url;\n switch (country) {\n case \"GBR\":\n func = \"Check\";\n break;\n case \"AUS\":\n func = \"CheckAustralia\";\n break;\n\n case \"DNK\":\n func = \"CheckDenmark\";\n break;\n case \"EST\":\n func = \"CheckEstonia\";\n break;\n\n case \"FIN\":\n func = \"CheckFinland\";\n break;\n case \"FRA\":\n func = \"CheckFrance\";\n break;\n case \"HUN\":\n func = \"CheckHungary\";\n break;\n case \"IND\":\n func = \"CheckIndia\";\n break;\n\n\n case \"IRL\":\n func = \"CheckIreland\";\n break;\n case \"ITA\":\n func = \"CheckItaly\";\n break;\n\n case \"NLD\":\n func = \"CheckNetherlands \";\n break;\n case \"NZL\":\n func = \"CheckNewZealand \";\n break;\n\n case \"NOR\":\n func = \"CheckNorway \";\n break;\n case \"PRT\":\n func = \"CheckPortugal \";\n break;\n case \"RUS\":\n func = \"CheckRussia \";\n break;\n case \"SVK\":\n func = \"CheckSlovakia \";\n break;\n\n\n\n case \"ZAF\":\n func = \"CheckSouthAfrica \";\n break;\n case \"ESP\":\n func = \"CheckSpain \";\n break;\n\n case \"LKA\":\n func = \"CheckSriLanka \";\n break;\n case \"SWE\":\n func = \"CheckSweden \";\n break;\n\n case \"ARE\":\n func = \"CheckUAE \";\n break;\n case \"USA\":\n func = \"CheckUSA\";\n break;\n }\n url = \"http://regcheck.org.uk/api/reg.asmx/\" + func + \"?RegistrationNumber=\" + regNumber + \"&username=dananos\"\n // \"http://regcheck.org.uk/api/reg.asmx/Check?RegistrationNumber=YYO7XHH&username=dananos\"\n this.http\n .get(url, this.httpOptions)\n .subscribe(\n json => {\n resolve(json);\n },\n error => {\n reject(error);\n }\n );\n });\n // });\n }\n setdata(country, state, regNum) {\n this.country = country;\n this.state = state;\n this.regNum = regNum;\n }\n getinfo() {\n return { country: this.country, state: this.state, regNum: this.regNum };\n }\n}\n"}}},{"rowIdx":1312,"cells":{"text":{"kind":"string","value":"exports.update_value_id = function(id, value) {\n document.getElementById(id).value = value;\n}\n\nexports.append_value_id = function(id, value) {\n document.getElementById(id).value += value;\n}\n\nexports.update_view_id = function(id, value) {\n document.getElementById(id).innerText = value;\n}\n\nexports.update_background_id = function (id, color) {\n document.getElementById(id).style.background = color;\n}"}}},{"rowIdx":1313,"cells":{"text":{"kind":"string","value":"# Get-VstsAssemblyReference\n[table of contents](../Commands.md#toc) | [brief](../Commands.md#get-vstsassemblyreference)\n```\nNAME\n Get-VstsAssemblyReference\n\nSYNOPSIS\n Gets assembly reference information.\n\nSYNTAX\n Get-VstsAssemblyReference [-LiteralPath] []\n\nDESCRIPTION\n Not supported for use during task execution. This function is only intended to help developers resolve\n the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client\n SDK. The interface and output may change between patch releases of the VSTS Task SDK.\n\n Only a subset of the referenced assemblies may actually be required, depending on the functionality used\n by your task. It is best to bundle only the DLLs required for your scenario.\n\n Walks an assembly's references to determine all of it's dependencies. Also walks the references of the\n dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for\n in the directory of the specified assembly. NET Framework assemblies are omitted.\n\n See https://github.com/Microsoft/azure-pipelines-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage\n when working with the TFS extended client SDK from a task.\n\nPARAMETERS\n -LiteralPath \n Assembly to walk.\n\n Required? true\n Position? 1\n Default value\n Accept pipeline input? false\n Accept wildcard characters? false\n\n \n This cmdlet supports the common parameters: Verbose, Debug,\n ErrorAction, ErrorVariable, WarningAction, WarningVariable,\n OutBuffer, PipelineVariable, and OutVariable. For more information, see\n about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216).\n\n -------------------------- EXAMPLE 1 --------------------------\n\n PS C:\\>Get-VstsAssemblyReference -LiteralPath C:\\nuget\\microsoft.teamfoundationserver.client.14.102.0\\lib\\\n net45\\Microsoft.TeamFoundation.Build2.WebApi.dll\n```\n"}}},{"rowIdx":1314,"cells":{"text":{"kind":"string","value":"class Events {\n\tprivate _callbacks = {};\n\tpublic bind(name, callback, context?) {\n\t if (!this._callbacks[name]) {\n\t this._callbacks[name] = [];\n\t }\n\t // this._callbacks[name].push({'cb':callback, context:context});\n\t this._callbacks[name].push(callback);\n\t}\n\n\tpublic unbind(name,callback) {\n\t\tfor (var i = 0; i < this._callbacks[name]; i++) {\n\t\t\tif(this._callbacks[name][i] == callback) {\n\t\t\t\tthis._callbacks[name].splice(i,1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic emit(name, args?: any) {\n\t\tif(this._callbacks[name]) {\n\t\t\tfor (var i = 0; i < this._callbacks[name].length; i++) {\n\t\t\t\tthis._callbacks[name][i](args);\n\t\t\t}\n\t\t}\n\t}\n}"}}},{"rowIdx":1315,"cells":{"text":{"kind":"string","value":"package com.spike.text.lucene.indexing.analysis;\n\nimport static org.junit.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.apache.lucene.analysis.Analyzer;\nimport org.apache.lucene.analysis.core.KeywordAnalyzer;\nimport org.apache.lucene.analysis.core.SimpleAnalyzer;\nimport org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;\nimport org.apache.lucene.document.Document;\nimport org.apache.lucene.document.Field.Store;\nimport org.apache.lucene.index.IndexOptions;\nimport org.apache.lucene.index.IndexWriter;\nimport org.apache.lucene.index.Term;\nimport org.apache.lucene.queryparser.classic.ParseException;\nimport org.apache.lucene.queryparser.classic.QueryParser;\nimport org.apache.lucene.search.IndexSearcher;\nimport org.apache.lucene.search.Query;\nimport org.apache.lucene.search.TermQuery;\nimport org.apache.lucene.search.TopDocs;\nimport org.junit.Test;\n\nimport com.spike.text.lucene.util.LuceneAppAnalyzerUtil;\nimport com.spike.text.lucene.util.LuceneAppUtil;\nimport com.spike.text.lucene.util.SearchingMemIndexTestBase;\nimport com.spike.text.lucene.util.anno.BookPartEnum;\nimport com.spike.text.lucene.util.anno.LuceneInAction2ndBook;\n\n@LuceneInAction2ndBook(part = BookPartEnum.CORE_LUCENE, chapter = 4, section = { 7 })\npublic class SearchUnAnalyzedFiledTest extends SearchingMemIndexTestBase {\n\n private static final String fld_partnum = \"partnum\";\n private static final String fldValue_partnum = \"Q36\";\n\n private static final String fld_description = \"description\";\n private static final String fldValue_description = \"Illidium Space Modulator\";\n\n /**\n * @throws IOException\n * @throws ParseException\n * @see SimpleAnalyzer\n * @see QueryParser\n * @see PerFieldAnalyzerWrapper\n * @see KeywordAnalyzer\n */\n @Test\n public void searchUnanalyzedField() throws IOException, ParseException {\n LuceneAppAnalyzerUtil.renderTokensWithFullDetails(new SimpleAnalyzer(), fldValue_partnum);\n LuceneAppAnalyzerUtil.renderTokensWithFullDetails(new SimpleAnalyzer(), fldValue_description);\n\n IndexSearcher indexSearcher = this.getIndexSearcher();\n\n Query query = new TermQuery(new Term(fld_partnum, fldValue_partnum));\n TopDocs topDocs = indexSearcher.search(query, 10);\n assertEquals(1, topDocs.totalHits);\n LuceneAppUtil.renderSearchResultWithExplain(query, indexSearcher, topDocs, fld_partnum);\n\n query =\n new QueryParser(fld_description, new SimpleAnalyzer())\n .parse(fld_partnum + \":Q36 AND SPACE\");\n assertEquals(\"+partnum:q +description:space\", query.toString());\n topDocs = indexSearcher.search(query, 10);\n assertEquals(0, topDocs.totalHits);\n LuceneAppUtil.renderSearchResultWithExplain(query, indexSearcher, topDocs, fld_description);\n\n Map analyzerPerField = new HashMap();\n // KeywordAnalyzer treat `Q36` as a complete word,\n // just as tokenized=false in indexing phase\n analyzerPerField.put(fld_partnum, new KeywordAnalyzer());\n PerFieldAnalyzerWrapper analyzerWrapper =\n LuceneAppAnalyzerUtil.constructPerFieldAnalyzerWrapper(new SimpleAnalyzer(),\n analyzerPerField);\n query = new QueryParser(fld_description, analyzerWrapper).parse(fld_partnum + \":Q36 AND SPACE\");\n System.out.println(query.toString());\n assertEquals(\"+partnum:Q36 +description:space\", query.toString());\n topDocs = indexSearcher.search(query, 10);\n assertEquals(1, topDocs.totalHits);\n LuceneAppUtil.renderSearchResultWithExplain(query, indexSearcher, topDocs, fld_description);\n }\n\n @Override\n protected Analyzer defineAnalyzer() {\n return new SimpleAnalyzer();\n }\n\n @Override\n protected void doIndexing() throws IOException {\n IndexWriter indexWriter = this.indexWriter;\n\n Document document = new Document();\n document.add(LuceneAppUtil.createStringField(fld_partnum, fldValue_partnum, Store.NO, false,\n IndexOptions.DOCS, true));\n document.add(LuceneAppUtil.createStringField(fld_description, fldValue_description, Store.YES,\n true, IndexOptions.DOCS, true));\n\n indexWriter.addDocument(document);\n\n }\n\n}\n"}}},{"rowIdx":1316,"cells":{"text":{"kind":"string","value":"namespace StripeTests.Terminal\n{\n using Newtonsoft.Json;\n using Stripe.Terminal;\n using Xunit;\n\n public class LocationTest : BaseStripeTest\n {\n public LocationTest(StripeMockFixture stripeMockFixture)\n : base(stripeMockFixture)\n {\n }\n\n [Fact]\n public void Deserialize()\n {\n string json = this.GetFixture(\"/v1/terminal/locations/loc_123\");\n var location = JsonConvert.DeserializeObject(json);\n Assert.NotNull(location);\n Assert.IsType(location);\n Assert.NotNull(location.Id);\n Assert.Equal(\"terminal.location\", location.Object);\n }\n }\n}\n"}}},{"rowIdx":1317,"cells":{"text":{"kind":"string","value":"@file:Suppress(\"CHECKRESULT\")\n\npackage com.shimmer.microcore.extension\n\nimport io.reactivex.Observable\nimport io.reactivex.android.schedulers.AndroidSchedulers\nimport io.reactivex.schedulers.Schedulers\n\ninline fun Observable.subscribe3(\n crossinline onNext: T.() -> Unit,\n crossinline onError: (Throwable) -> Unit = {},\n crossinline onComplete: () -> Unit = {},\n) {\n this.subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe({\n it.onNext()\n }, { error ->\n onError(error)\n }, {\n onComplete()\n })\n}\n"}}},{"rowIdx":1318,"cells":{"text":{"kind":"string","value":"stitching_version=\"1.9.0\"\nstitching_git_hash=\"master\"\nsynapse_version=\"1.4.1\"\nsynapse_git_hash=\"1.4.1\"\nsynapse_dask_version=\"1.3.1\"\nneuron_segmentation_version=\"1.0.0\"\nneuron_segmentation_git_hash=\"1.0.0\"\nn5_spark_tools_version=\"3.11.0\"\nn5_spark_tools_git_hash=\"exm-3.11.0\"\n"}}},{"rowIdx":1319,"cells":{"text":{"kind":"string","value":"#!/bin/bash\n\nARGS=()\n[[ -z \"$DEVICE\" ]] && ARGS+=(\"-Dwebdriver.url=https://${BROWSERSTACK_USERNAME}:${BROWSERSTACK_ACCESS_KEY}@hub-cloud.browserstack.com/wd/hub\")\n[[ ! -z \"$BROWSERSTACK_LOCAL_IDENTIFIER\" ]] && ARGS+=(\"-Dwebdriver.cap.browserstack.localIdentifier=${BROWSERSTACK_LOCAL_IDENTIFIER}\")\n[[ ! -z \"$BROWSER\" ]] && ARGS+=(\"-Dwebdriver.cap.browser=$BROWSER\")\n[[ ! -z \"$WEBDRIVER_TYPE\" ]] && ARGS+=(\"-Dwebdriver.type=$WEBDRIVER_TYPE\") || ARGS+=('-Dwebdriver.type=remote')\n[[ ! -z \"$OS\" ]] && ARGS+=(\"-Dwebdriver.cap.os=${OS}\")\n[[ ! -z \"$OS_VER\" ]] && ARGS+=(\"-Dwebdriver.cap.os_version=${OS_VER}\")\n[[ ! -z \"$DEVICE\" ]] && ARGS+=(\"-Dwebdriver.appium.url=https://${BROWSERSTACK_USERNAME}:${BROWSERSTACK_ACCESS_KEY}@hub-cloud.browserstack.com/wd/hub\")\n[[ ! -z \"$DEVICE\" ]] && ARGS+=(\"-Dwebdriver.cap.device=${DEVICE}\")\n[[ ! -z \"$DEVICE\" ]] && ARGS+=('-Dwebdriver.cap.realMobile=true')\n\nmvn clean install \"${ARGS[@]}\"\n"}}},{"rowIdx":1320,"cells":{"text":{"kind":"string","value":"package typingsSlinky.grammarkdown\n\nimport org.scalablytyped.runtime.StObject\nimport scala.scalajs.js\nimport scala.scalajs.js.`|`\nimport scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}\n\nobject stringwriterMod {\n \n @JSImport(\"grammarkdown/dist/stringwriter\", \"StringWriter\")\n @js.native\n class StringWriter () extends StObject {\n def this(eol: String) = this()\n \n var _depth: js.Any = js.native\n \n var _eol: js.Any = js.native\n \n var _indents: js.Any = js.native\n \n var _newLine: js.Any = js.native\n \n var _text: js.Any = js.native\n \n def dedent(): Unit = js.native\n \n var flushNewLine: js.Any = js.native\n \n def indent(): Unit = js.native\n \n def size: Double = js.native\n \n def write(): Unit = js.native\n def write(text: String): Unit = js.native\n \n def writeln(): Unit = js.native\n def writeln(text: String): Unit = js.native\n }\n}\n"}}},{"rowIdx":1321,"cells":{"text":{"kind":"string","value":"---\nlayout: watch\ntitle: TLP6 - 07/02/2021 - M20210207_002532_TLP_6T.jpg\ndate: 2021-02-07 00:25:32\npermalink: /2021/02/07/watch/M20210207_002532_TLP_6\ncapture: TLP6/2021/202102/20210206/M20210207_002532_TLP_6T.jpg\n---\n"}}},{"rowIdx":1322,"cells":{"text":{"kind":"string","value":"// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file\n// for details. All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n\n// OtherResources=process_sync_script.dart\n\nimport \"dart:io\";\nimport \"package:expect/expect.dart\";\nimport 'package:path/path.dart';\n\ntest(int blockCount, int stdoutBlockSize, int stderrBlockSize, int exitCode,\n [int nonWindowsExitCode]) {\n // Get the Dart script file that generates output.\n var scriptFile = new File(\n Platform.script.resolve(\"process_sync_script.dart\").toFilePath());\n var args = []\n ..addAll(Platform.executableArguments)\n ..addAll([\n scriptFile.path,\n blockCount.toString(),\n stdoutBlockSize.toString(),\n stderrBlockSize.toString(),\n exitCode.toString()\n ]);\n ProcessResult syncResult = Process.runSync(Platform.executable, args);\n Expect.equals(blockCount * stdoutBlockSize, syncResult.stdout.length);\n Expect.equals(blockCount * stderrBlockSize, syncResult.stderr.length);\n if (Platform.isWindows) {\n Expect.equals(exitCode, syncResult.exitCode);\n } else {\n if (nonWindowsExitCode == null) {\n Expect.equals(exitCode, syncResult.exitCode);\n } else {\n Expect.equals(nonWindowsExitCode, syncResult.exitCode);\n }\n }\n Process.run(Platform.executable, args).then((asyncResult) {\n Expect.equals(syncResult.stdout, asyncResult.stdout);\n Expect.equals(syncResult.stderr, asyncResult.stderr);\n Expect.equals(syncResult.exitCode, asyncResult.exitCode);\n });\n}\n\nmain() {\n test(10, 10, 10, 0);\n test(10, 100, 10, 0);\n test(10, 10, 100, 0);\n test(100, 1, 10, 0);\n test(100, 10, 1, 0);\n test(100, 1, 1, 0);\n test(1, 100000, 100000, 0);\n\n // The buffer size used in process.h.\n var kBufferSize = 16 * 1024;\n test(1, kBufferSize, kBufferSize, 0);\n test(1, kBufferSize - 1, kBufferSize - 1, 0);\n test(1, kBufferSize + 1, kBufferSize + 1, 0);\n\n test(10, 10, 10, 1);\n test(10, 10, 10, 255);\n test(10, 10, 10, -1, 255);\n test(10, 10, 10, -255, 1);\n}\n"}}},{"rowIdx":1323,"cells":{"text":{"kind":"string","value":"export interface CommonColors {\n readonly black: string;\n readonly white: string;\n readonly grey0: string;\n readonly grey1: string;\n readonly grey2: string;\n readonly grey3: string;\n readonly grey4: string;\n readonly grey5: string;\n readonly greyOutline: string;\n readonly disabled: string;\n readonly divider: string;\n readonly foreground: string;\n readonly background: string;\n}\n\nexport interface AccentColors {\n readonly primary: string;\n readonly secondary: string;\n readonly success: string;\n readonly warning: string;\n readonly error: string;\n}\n\nexport interface SocialColors {\n readonly kakao: string;\n readonly naver: string;\n readonly google: string;\n readonly facebook: string;\n readonly apple: string;\n}\n\nexport interface Colors extends CommonColors, AccentColors, SocialColors {}\n\nexport type Theme = {\n light: Colors;\n dark: Colors;\n};\n\nexport interface ThemeContextState {\n dark: boolean;\n toggleTheme: () => void;\n colors: Colors;\n}\n"}}},{"rowIdx":1324,"cells":{"text":{"kind":"string","value":"package consoleui\n\nimport (\n\t\"fmt\"\n\t\"github.com/nsf/termbox-go\"\n\t\"github.com/xosmig/roguelike/core/geom\"\n\t\"github.com/xosmig/roguelike/gamemodel/status\"\n\t\"log\"\n)\n\n// getKeyForAction accepts the set of interesting keys and waits for one of these keys to be pressed,\n// or for a cancellation request from the user (Ctrl+C pressed).\n// It returns the pressed key and a boolean flag, indicating whether the exit was requested or not.\nfunc (ui *consoleUi) getKeyForAction(actions map[termbox.Key]func()) (key termbox.Key, finish bool) {\n\tvar ev termbox.Event\n\tfor {\n\t\tev = termbox.PollEvent()\n\t\tif ev.Type != termbox.EventKey {\n\t\t\tcontinue\n\t\t}\n\t\tif ev.Key == termbox.KeyCtrlC {\n\t\t\tlog.Println(\"Ctrl+C is pressed\")\n\t\t\treturn ev.Key, true\n\t\t}\n\t\tif _, present := actions[ev.Key]; present {\n\t\t\treturn ev.Key, false\n\t\t}\n\n\t\tlog.Printf(\"Debug: Invalid command key: %v\\n\", ev.Key)\n\t}\n}\n\n// restartOrExit blocks until the user presses Ctrl+C (in this case it just returns nil),\n// or Ctrl+R (in this case it restarts the game via recursive call to Run method).\nfunc (ui *consoleUi) restartOrExit() error {\n\tui.messagef(\"Press 'Ctrl+C' to exit, or 'Ctrl+R' to restart\")\n\n\tactions := map[termbox.Key]func(){\n\t\ttermbox.KeyCtrlR: nil,\n\t}\n\n\t_, finish := ui.getKeyForAction(actions)\n\tif finish {\n\t\tlog.Println(\"Exit requested\")\n\t\treturn nil\n\t}\n\n\tui.reloadGameModel()\n\treturn ui.Run()\n}\n\n// Run does the read-execute-print-loop.\nfunc (ui *consoleUi) Run() error {\n\tvar afterRender []func()\n\t// delay delays the given function execution so that it is executed after rendering.\n\t// It's useful to adjust the rendered picture.\n\t// For example, by printing a message.\n\tdelay := func(f func()) {\n\t\tafterRender = append(afterRender, f)\n\t}\n\n\taccessItem := func(idx int) {\n\t\terr := ui.model.GetCharacter().WearOrTakeOff(idx)\n\t\tif err != nil {\n\t\t\tdelay(func() { ui.messagef(\"inventory error: %v\", err) })\n\t\t}\n\t}\n\n\tactions := map[termbox.Key]func(){\n\t\ttermbox.KeyArrowUp: func() { ui.model.DoMove(geom.Up) },\n\t\ttermbox.KeyArrowDown: func() { ui.model.DoMove(geom.Down) },\n\t\ttermbox.KeyArrowLeft: func() { ui.model.DoMove(geom.Left) },\n\t\ttermbox.KeyArrowRight: func() { ui.model.DoMove(geom.Right) },\n\t\ttermbox.KeyCtrlA: func() { accessItem(0) },\n\t\ttermbox.KeyCtrlS: func() { accessItem(1) },\n\t\ttermbox.KeyCtrlD: func() { accessItem(2) },\n\t}\n\ngameLoop:\n\tfor {\n\t\terr := ui.render()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"while rendering: %v\", err)\n\t\t}\n\n\t\tfor _, f := range afterRender {\n\t\t\tf()\n\t\t}\n\t\tafterRender = nil\n\n\t\tswitch ui.model.Status() {\n\t\tcase status.Continue:\n\t\t\t// continue\n\t\tcase status.Defeat:\n\t\t\tui.messagef(\"You lost :(\")\n\t\t\treturn ui.restartOrExit()\n\t\tcase status.Victory:\n\t\t\tui.messagef(\"You won [^_^]\")\n\t\t\treturn ui.restartOrExit()\n\t\t}\n\n\t\tkey, finish := ui.getKeyForAction(actions)\n\t\tif finish {\n\t\t\tbreak gameLoop\n\t\t}\n\n\t\tactions[key]()\n\t}\n\n\treturn nil\n}\n"}}},{"rowIdx":1325,"cells":{"text":{"kind":"string","value":"RSpec.describe NxtHttpClient do\n it 'has a version number' do\n expect(NxtHttpClient::VERSION).not_to be nil\n end\n\n context 'http methods', :vcr_cassette do\n let(:client) do\n Class.new(NxtHttpClient::Client) do\n configure do |config|\n config.base_url = nil\n end\n\n response_handler(NxtHttpClient::ResponseHandler.new) do |handler|\n handler.on(200) do |response|\n '200 from level four class level'\n end\n end\n end\n end\n\n subject do\n client.new\n end\n\n let(:url) { http_stats_url('200') }\n\n it 'calls fire with the respective http method' do\n expect(subject.post(url, params: { andy: 'calling' })).to eq('200 from level four class level')\n expect(subject.get(url)).to eq('200 from level four class level')\n expect(subject.patch(url)).to eq('200 from level four class level')\n expect(subject.put(url)).to eq('200 from level four class level')\n expect(subject.delete(url)).to eq('200 from level four class level')\n end\n end\nend\n"}}},{"rowIdx":1326,"cells":{"text":{"kind":"string","value":"import { IsInt, Max, Min } from 'class-validator';\n\nexport class UserNutritionGoalsDTO {\n @IsInt()\n @Min(600)\n @Max(20000)\n public kcal: number;\n\n @IsInt()\n @Min(1)\n @Max(98)\n public protein: number;\n\n @IsInt()\n @Min(1)\n @Max(98)\n public carbs: number;\n\n @IsInt()\n @Min(1)\n @Max(98)\n public fats: number;\n}\n"}}},{"rowIdx":1327,"cells":{"text":{"kind":"string","value":"'diaaOsama850@outlook.com' ,\n 'password'=>'brodybrody' ,\n 'password_confirmation'=>'brodybrody',\n 'name'=>'diaa osama'\n ];\n $result=$this->postJson(\"/api/auth/register\" , $userInfo)->json();\n $this->assertEquals($result['success'] , true);\n $this->assertNotEmpty($result['data']['token']);\n }\n\n public function test_un_valid_data_for_register_user(){\n $userInfo = [\n 'email'=>'' ,\n 'password'=>'brodybrody' ,\n 'password_confirmation'=>'brodybrodyd',\n 'name'=>''\n ];\n $result = $this->postJson('/api/auth/register' , $userInfo)->json();\n $this->assertEquals($result['code'] , 422);\n $this->assertCount( 3, $result['data']['errors'] );\n }\n\n public function test_login_user(){\n $user= createUser();\n $this->postJson('/api/auth/login' , [\n 'email' =>$user['email'] ,\n 'password'=>$user['password']\n ])->assertStatus(200);\n $this->assertAuthenticated();\n }\n\n public function test_un_valid_data_for_login_user(){\n $result= $this->postJson('/api/auth/login' , [])\n ->assertStatus(422)->json();\n $this->assertCount( 2, $result['data']['errors'] );\n // un valid email\n $result= $this->postJson('/api/auth/login' , [\n 'email' =>'fakeemailyahoocom',\n 'password'=>'fakepassword'\n ]) ->assertStatus(422);\n // fake account\n $this->postJson('/api/auth/login' , [\n 'email' =>'fakeemail@yahoo.com',\n 'password'=>'fakepassword'\n ])->assertStatus(403);\n }\n\n public function test_logout_user(){\n $this->login();\n $this->assertAuthenticated();\n $this->postJson('/api/auth/logout');\n $this->assertGuest();\n }\n\n public function test_refresh_token_user(){\n $authUser= $this->login();\n $result=$this->postJson('/api/auth/refresh')\n ->assertStatus(200)->json();\n $this->assertNotEmpty($result['data']['token']);\n $user= $this->login($authUser , $result['data']['token']);\n $this->assertEquals($authUser , $user);\n }\n}\n"}}},{"rowIdx":1328,"cells":{"text":{"kind":"string","value":"(ns advent-of-code-2017.day1\n (:require [clojure.string :refer [trim]]))\n\n(defn load-input []\n (trim (slurp \"resources/day1.txt\")))\n\n(defn extract-pairs [input]\n (partition 2 1\n (map\n #(Integer/valueOf (str %))\n (str input (first input))))) ;; add the first value to the end to simulate wrapping\n\n(defn solve-puzzle-1 []\n (let [input (load-input)]\n (reduce (fn [v [a b]] (if (= a b) (+ v a) v)) 0 (extract-pairs input))))\n\n(defn solve-puzzle-2 []\n (let [input (map #(Integer/valueOf (str %)) (load-input))\n l (/ (count input) 2)\n col1 (take l input)\n col2 (take-last l input)]\n (* 2\n (reduce\n +\n (map\n (fn [a b] (if (= a b) a 0))\n col1\n col2)))))\n\n(defn solve []\n (println (format \"Day 1 - solution 1: %d - solution 2: %d\" (solve-puzzle-1) (solve-puzzle-2))))\n"}}},{"rowIdx":1329,"cells":{"text":{"kind":"string","value":"#include \n#include \n#include \"gba.h\"\n#include \"drawable.h\"\n#include \"input.h\"\n#include \"tiles.h\"\n#include \"font.h\"\n#include \"text.h\"\n\n\n// The entry point for the game.\nint main()\n{\n\t// Set display options.\n\t// DCNT_MODE0 sets mode 0, which provides four tiled backgrounds.\n\t// DCNT_OBJ enables objects.\n\t// DCNT_OBJ_1D make object tiles mapped in 1D (which makes life easier).\n\tREG_DISPCNT = DCNT_MODE0 | DCNT_BG0 | DCNT_BG1 | DCNT_BG2 | DCNT_BG3 | DCNT_OBJ | DCNT_OBJ_1D;\n\t\n\t// Set background 0 options.\n\t// BG_CBB sets the charblock base (where the tiles come from).\n\t// BG_SBB sets the screenblock base (where the tilemap comes from).\n\t// BG_8BPP uses 8bpp tiles.\n\t// BG_REG_32x32 makes it a 32x32 tilemap.\n\tREG_BG0CNT = BG_CBB(0) | BG_SBB(30) | BG_8BPP | BG_REG_32x32;\n\t\n\t// Set background 1 options.\n\tREG_BG1CNT = BG_CBB(0) | BG_SBB(29) | BG_8BPP | BG_REG_32x32;\n\tREG_BG1HOFS = 0;\n\tREG_BG1VOFS = 0;\n\t\n\t// Set background 2 options.\n\tREG_BG2CNT = BG_CBB(0) | BG_SBB(28) | BG_8BPP | BG_REG_32x32;\n\tREG_BG2HOFS = 0;\n\tREG_BG2VOFS = 0;\n\t\n\t// Set background 3 options.\n\tREG_BG3CNT = BG_CBB(0) | BG_SBB(27) | BG_8BPP | BG_REG_32x32;\n\tREG_BG3HOFS = 0;\n\tREG_BG3VOFS = 0;\n\t\n\t\n\t\n\t// Set up the object palette.\n\tSetPaletteObj(0, RGB(0, 0, 0)); // blank\n\tSetPaletteObj(1, RGB(0, 0, 0)); // black\n\tSetPaletteObj(2, RGB(31, 31, 31)); // white\n\tSetPaletteObj(3, RGB(31, 31, 0)); // yellow\n\tSetPaletteObj(4, RGB(31, 0, 0)); // red\n\tSetPaletteBG(0, RGB(0, 0, 0)); // blank\n\tSetPaletteBG(1, RGB(0, 0, 0)); // black\n\tSetPaletteBG(2, RGB(31, 31, 31)); // white\n\tSetPaletteBG(3, RGB(31, 31, 0)); // bright yellow\n\tSetPaletteBG(4, RGB(31, 0, 0)); // red\n\tSetPaletteBG(5, RGB(30, 0, 15)); // magenta\n\tSetPaletteBG(6, RGB(23, 3, 5)); // pink?\n\tSetPaletteBG(7, RGB(1, 4, 28)); // blueIhope\n\tSetPaletteBG(8, RGB(2, 25, 2)); // greenish\n\tSetPaletteBG(9, RGB(10, 10, 0)); // yellow?\n\tSetPaletteBG(10, RGB(31, 31, 31)); // white\n\tSetPaletteBG(11, RGB(20, 20, 31)); // pale blue (sky)\n\tSetPaletteBG(12, RGB(25, 25, 25)); // grey (cloud)\n\tSetPaletteBG(13, RGB(20, 10, 0)); // brown (brick)\n\t\n\t\n\t\n\t// Alphabet tile counter.\n\tint tile_num = 0;\n\t// Loads the font tile-map to charblock 1.\n\tfor (tile_num = 0; tile_num < 129; tile_num++)\n\t{\n\t\tLoadTile8(1, tile_num, font_bold[tile_num]);\n\t}\n\t\n\t// Load the tile data above into video memory, putting it in charblock 0.\n\tLoadTile8(0, 1, sky_tile);\n\tLoadTile8(0, 2, cloud_tile);\n\tLoadTile8(0, 3, brick_tile);\n\tLoadTile8(0, 4, build_tile);\n\tLoadTile8(0, 5, blank_tile); // tile number 0 = blank\n\tLoadTile8(0, 6, red_box_tile); // tile number 1 = red box\n\tLoadTile8(0, 7, LSD_box_tile); // my own tile 2\n\t\n\t// Load the tiles for the objects into charblock 4.\n\t// (Charblocks 4 and 5 are for object tiles;\n\t// 8bpp tiles 0-255 are in CB 4, tiles 256-511 in CB 5.)\n\tLoadTile8(4, 1, LSD_box_tile);\n\t\n\t// set sky background and load cloud tiles\n\tfor (int y = 0; y < 32; y++)\n\t{\n\t\tfor (int x = 0; x < 32; ++x)\n\t\t{\n\t\t\tSetTile(27, x, y, 1);\n\t\t}\n\t}\n\t\n\t// clouds to screenblock 28.\n\tfor (int cl = 0; cl < 24; cl++) // cloudcounter\n\t{\n\t\tint clx = rand()%32; // generates a random position x for the clouds between numbers 1-32\n\t\tint cly = rand()%14; // generates a random position y for the clouds between numbers 1-16\n\t\tSetTile(28, clx, cly, 2); // puts down the actual tiles in the above positions\n\t}\n\t\n\t// Make sure no objects are on the screen, but why should they be?\n\tClearObjects();\n\t\n\t// Initial object parameters\n\tint smilex = 116;\n\tint smiley = 76;\n\t\n\t// Set up object 0 as a char in the middle of the screen.\n\tSetObject(0,\n\t\tATTR0_SHAPE(0) | ATTR0_8BPP | ATTR0_REG | ATTR0_Y(smiley),\n\t\tATTR1_SIZE(0) | ATTR1_X(smilex),\n\t\tATTR2_ID8(1));\n\t\n\tSetObjectX(0, 1);\n\tSetObjectY(0, 1);\n\t\t\n\t// Input handle\n\tInput input;\n\t\n\t// Initialize a frame counter.\n\tint frames = 0;\n\t\n\tint curbgOffSetX = 0;\n\tint curbgOffSetY = 0;\n\n\t\n\twhile (true)\n\t{\n\t\tframes++;\n\t\t\n\t\tText::DrawText(22, 1, \"Score:\");\n\t\t\n\t\tinput.UpdateInput();\n\t\tint dirx = input.GetInput().xdir;\n\t\tint diry = input.GetInput().ydir;\n\t\tinput.ResetInput();\n\t\t\n\t\t\n\t\tif (diry != 0)\n\t\t{\n\t\t\tsmiley += diry;\n\t\t\tSetObjectY(0, smiley);\n\t\t}\n\t\n\t\tif (dirx != 0)\n\t\t{\n\t\t\tsmilex += dirx;\n\t\t\tSetObjectX(0, smilex);\n\t\t}\n\t\n\t\tif (smilex >= SCREEN_WIDTH - 9)\n\t\t{\n\t\t\tsmilex = SCREEN_WIDTH - 9;\n\t\t}\n\t\n\t\tif (smilex <= 0 + 1)\n\t\t{\n\t\t\tsmilex = 0 + 1;\n\t\t}\n\t\t\n\t\tif (smiley >= SCREEN_HEIGHT - 9)\n\t\t{\n\t\t\tsmiley = SCREEN_HEIGHT - 9;\n\t\t}\n\t\t\n\t\tif (smiley <= 0 + 1)\n\t\t{\n\t\t\tsmiley = 0 + 1;\n\t\t}\n\t\t\n\t\tWaitVSync();\n\t\tUpdateObjects();\n\t}\n\t\n\treturn 0;\n}\n\nvoid DrawRandomCircles()\n{\n\t//WaitVSync();\n\t//x = rand() % 240;\n\t//y = rand() % 160;\n\t//r = rand() % 50 + 10;\n\t//uint16_t color = RGB(rand()%31, rand()%31, rand()%31);\n\t//DrawCircle3(x, y, r, color);\n\t//WaitVSync();\n}\n\n/// BG scroll and screen register switch\n/*\n\t\t//if ((REG_KEYINPUT & KEY_LEFT) == 0)\n\t\t//{\n\t\t//\tif (curbgOffSetX > 0)\n\t\t//\t\tcurbgOffSetX--;\n\t\t//}\n\t\t//\n\t\t//else if ((REG_KEYINPUT & KEY_RIGHT) == 0)\n\t\t//{\n\t\t//\tif (curbgOffSetX < SCREEN_WIDTH)\n\t\t//\t\tcurbgOffSetX++;\n\t\t//}\n\t\t//\n\t\t//if ((REG_KEYINPUT & KEY_UP) == 0)\n\t\t//{\n\t\t//\tif (curbgOffSetY > 0)\n\t\t//\t\tcurbgOffSetY--;\n\t\t//}\n\t\t//\n\t\t//else if ((REG_KEYINPUT & KEY_DOWN) == 0)\n\t\t//{\n\t\t//\tif (curbgOffSetY < SCREEN_HEIGHT)\n\t\t//\t\tcurbgOffSetY++;\n\t\t//}\n\t\t//\n\t\t//\n\t\t//REG_BG0HOFS = curbgOffSetX;\n\t\t//REG_BG0VOFS = curbgOffSetY;\n\t\t\n\t\t//if ((REG_KEYINPUT & KEY_A) == 0)\n\t\t//{\n\t\t//\tREG_BG0CNT = BG_CBB(0) | BG_SBB(30) | BG_8BPP | BG_REG_32x32;\n\t\t//}\n\t\t//\n\t\t//else if ((REG_KEYINPUT & KEY_B) == 0)\n\t\t//{\n\t\t//\tREG_BG0CNT = BG_CBB(0) | BG_SBB(31) | BG_8BPP | BG_REG_32x32;\n\t\t//}\n*/"}}},{"rowIdx":1330,"cells":{"text":{"kind":"string","value":"using System;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.ServiceProcess;\nusing System.Threading;\n\nnamespace BacklightShifter {\n internal static class ServiceStatusThread {\n\n private static Thread Thread;\n private static readonly ManualResetEvent CancelEvent = new ManualResetEvent(false);\n\n\n public static void Start() {\n if (Thread != null) { return; }\n\n Thread = new Thread(Run) {\n Name = \"Service status\",\n CurrentCulture = CultureInfo.InvariantCulture\n };\n Thread.Start();\n }\n\n public static void Stop() {\n try {\n CancelEvent.Set();\n while (Thread.IsAlive) { Thread.Sleep(10); }\n Thread = null;\n CancelEvent.Reset();\n } catch { }\n }\n\n\n private static void Run() {\n try {\n using (var service = new ServiceController(AppService.Instance.ServiceName)) {\n bool? lastIsRunning = null;\n Tray.SetStatusToUnknown();\n\n while (!CancelEvent.WaitOne(250, false)) {\n bool? currIsRunning;\n try {\n service.Refresh();\n currIsRunning = (service.Status == ServiceControllerStatus.Running);\n } catch (InvalidOperationException) {\n currIsRunning = null;\n }\n if (lastIsRunning != currIsRunning) {\n if (currIsRunning == null) {\n Tray.SetStatusToUnknown();\n } else if (currIsRunning == true) {\n Tray.SetStatusToRunning();\n } else {\n Tray.SetStatusToStopped();\n }\n }\n lastIsRunning = currIsRunning;\n }\n }\n } catch (ThreadAbortException) { }\n }\n\n }\n}\n"}}},{"rowIdx":1331,"cells":{"text":{"kind":"string","value":"/*\n * Copyright 2021 HM Revenue & Customs\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage uk.gov.hmrc.customs.rosmfrontend.controllers.subscription\n\nimport javax.inject.{Inject, Singleton}\nimport play.api.Application\nimport play.api.mvc.{AnyContent, Request, Session}\nimport uk.gov.hmrc.customs.rosmfrontend.controllers.FeatureFlags\nimport uk.gov.hmrc.customs.rosmfrontend.domain._\nimport uk.gov.hmrc.customs.rosmfrontend.domain.registration.UserLocation\nimport uk.gov.hmrc.customs.rosmfrontend.domain.subscription.{SubscriptionFlow, SubscriptionPage, _}\nimport uk.gov.hmrc.customs.rosmfrontend.logging.CdsLogger.logger\nimport uk.gov.hmrc.customs.rosmfrontend.models.Journey\nimport uk.gov.hmrc.customs.rosmfrontend.services.cache.{RequestSessionData, SessionCache}\nimport uk.gov.hmrc.customs.rosmfrontend.services.subscription.SubscriptionDetailsService\nimport uk.gov.hmrc.customs.rosmfrontend.util.Constants.ONE\nimport uk.gov.hmrc.http.HeaderCarrier\n\nimport scala.concurrent.ExecutionContext.Implicits.global\nimport scala.concurrent.Future\n\ncase class SubscriptionFlowConfig(\n pageBeforeFirstFlowPage: SubscriptionPage,\n pagesInOrder: List[SubscriptionPage],\n pageAfterLastFlowPage: SubscriptionPage\n) {\n\n private def lastPageInTheFlow(currentPos: Int): Boolean = currentPos == pagesInOrder.size - ONE\n\n def determinePageBeforeSubscriptionFlow(uriBeforeSubscriptionFlow: Option[String]): SubscriptionPage =\n uriBeforeSubscriptionFlow.fold(pageBeforeFirstFlowPage)(url => PreviousPage(url))\n\n def stepInformation(\n currentPage: SubscriptionPage,\n uriBeforeSubscriptionFlow: Option[String]\n ): SubscriptionFlowInfo = {\n\n val currentPos = pagesInOrder.indexOf(currentPage)\n\n val nextPage = if (lastPageInTheFlow(currentPos)) pageAfterLastFlowPage else pagesInOrder(currentPos + ONE)\n\n SubscriptionFlowInfo(stepNumber = currentPos + ONE, totalSteps = pagesInOrder.size, nextPage = nextPage)\n }\n}\n\n@Singleton\nclass SubscriptionFlowManager @Inject()(\n override val currentApp: Application,\n requestSessionData: RequestSessionData,\n cdsFrontendDataCache: SessionCache,\n subscriptionDetailsService: SubscriptionDetailsService\n) extends FeatureFlags {\n\n def currentSubscriptionFlow(implicit request: Request[AnyContent]): SubscriptionFlow =\n requestSessionData.userSubscriptionFlow\n\n def stepInformation(\n currentPage: SubscriptionPage\n )(implicit hc: HeaderCarrier, request: Request[AnyContent]): SubscriptionFlowInfo =\n SubscriptionFlows(currentSubscriptionFlow)\n .stepInformation(currentPage, requestSessionData.uriBeforeSubscriptionFlow)\n\n def startSubscriptionFlow(\n journey: Journey.Value\n )(implicit hc: HeaderCarrier, request: Request[AnyContent]): Future[(SubscriptionPage, Session)] =\n startSubscriptionFlow(None, requestSessionData.userSelectedOrganisationType, journey)\n\n def startSubscriptionFlow(\n previousPage: Option[SubscriptionPage] = None,\n cdsOrganisationType: CdsOrganisationType,\n journey: Journey.Value\n )(implicit hc: HeaderCarrier, request: Request[AnyContent]): Future[(SubscriptionPage, Session)] =\n startSubscriptionFlow(previousPage, Some(cdsOrganisationType), journey)\n\n def startSubscriptionFlow(\n previousPage: Option[SubscriptionPage],\n journey: Journey.Value\n )(implicit hc: HeaderCarrier, request: Request[AnyContent]): Future[(SubscriptionPage, Session)] =\n startSubscriptionFlow(previousPage, requestSessionData.userSelectedOrganisationType, journey)\n\n private def startSubscriptionFlow(\n previousPage: Option[SubscriptionPage],\n orgType: => Option[CdsOrganisationType],\n journey: Journey.Value\n )(implicit hc: HeaderCarrier, request: Request[AnyContent]): Future[(SubscriptionPage, Session)] = {\n val maybePreviousPageUrl = previousPage.map(page => page.url)\n cdsFrontendDataCache.registrationDetails map { registrationDetails =>\n {\n val flow = selectFlow(registrationDetails, orgType, journey)\n\n logger.info(s\"select Subscription flow: ${flow.name}\")\n (\n SubscriptionFlows(flow).pagesInOrder.head,\n requestSessionData.storeUserSubscriptionFlow(\n flow,\n SubscriptionFlows(flow).determinePageBeforeSubscriptionFlow(maybePreviousPageUrl).url\n )\n )\n }\n }\n }\n\n private def selectFlow(\n registrationDetails: RegistrationDetails,\n maybeOrgType: => Option[CdsOrganisationType],\n journey: Journey.Value\n )(implicit request: Request[AnyContent], headerCarrier: HeaderCarrier): SubscriptionFlow = {\n val userLocation = requestSessionData.selectedUserLocation\n\n val subscribePrefix = (userLocation, journey, registrationDetails.customsId, rowHaveUtrEnabled) match {\n case (\n Some(UserLocation.Islands) | Some(UserLocation.ThirdCountry),\n Journey.Migrate,\n None,\n true\n ) =>\n \"migration-eori-row-utrNino-enabled-\"\n case (\n Some(UserLocation.Islands) | Some(UserLocation.ThirdCountry),\n Journey.Migrate,\n _,\n _\n ) =>\n \"migration-eori-row-\"\n case (_, Journey.Migrate, _, _) => \"migration-eori-\" // This means UK\n case _ => \"\"\n }\n\n val selectedFlow: SubscriptionFlow =\n (registrationDetails, maybeOrgType, rowHaveUtrEnabled, registrationDetails.customsId, journey) match {\n case (_: RegistrationDetailsOrganisation, Some(CdsOrganisationType.Partnership), _, _, _) =>\n SubscriptionFlow(subscribePrefix + PartnershipSubscriptionFlow.name)\n case (_: RegistrationDetailsOrganisation, _, true, None, Journey.Migrate) =>\n SubscriptionFlow(subscribePrefix + OrganisationSubscriptionFlow.name)\n case (_: RegistrationDetailsIndividual, _, true, None, Journey.Migrate) =>\n SubscriptionFlow(subscribePrefix + IndividualSubscriptionFlow.name)\n case (_: RegistrationDetailsOrganisation, _, _, _, _) =>\n SubscriptionFlow(subscribePrefix + OrganisationSubscriptionFlow.name)\n case (_: RegistrationDetailsIndividual, _, _, _, _) =>\n SubscriptionFlow(subscribePrefix + IndividualSubscriptionFlow.name)\n case _ => throw new IllegalStateException(\"Incomplete cache cannot complete journey\")\n }\n\n maybeOrgType.fold(selectedFlow)(\n orgType => SubscriptionFlows.flows.keys.find(_.name == (subscribePrefix + orgType.id)).getOrElse(selectedFlow)\n )\n }\n}\n"}}},{"rowIdx":1332,"cells":{"text":{"kind":"string","value":"{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nmodule Game.Play.Handler where\n\nimport Prelude (IO, flip, pure, ($), (+), (<), (<$>),\n (>), (>>=))\n\nimport Control.Lens (use, view, (.=), (^.))\nimport Control.Monad (when)\nimport Control.Monad.Except (MonadError, throwError)\nimport Control.Monad.RWS (ask, get)\n\nimport Control.Monad.Random (MonadRandom)\n\nimport Control.Monad.Reader (MonadReader)\nimport Data.Monoid ((<>))\nimport TextShow (showt)\n\nimport Servant ((:<|>) (..), ServerT)\n\nimport Auth (UserInfo)\nimport qualified Database.Class as Db\nimport Handler.Types (AppError (..), HandlerAuthT)\n\nimport Game.Agent (agentDo)\nimport Game.Api.Types (ErrorOr (..), GameError (..))\nimport Game.Bot (botMoves)\nimport qualified Game.Moves as Moves\nimport Game.Play (getMaxBetValue, withGame, withPlayer)\nimport qualified Game.Play.Api as Api\nimport Game.Play.Api.Types\nimport Game.Play.Types (Seating, seatLeft, seatMe, seatRight)\nimport Game.Types\n\nhandlers :: ServerT Api.Routes (HandlerAuthT IO)\nhandlers =\n playCard\n :<|> placeBet\n\nplaceBet\n :: (Db.Read m, Db.Replace m, MonadError AppError m, MonadReader UserInfo m, MonadRandom m)\n => PlaceBetRq\n -> m (ErrorOr Game)\nplaceBet req = withGame (req ^. pbrqAuth) $ do\n seating <- ask\n min <- use gPhase >>= \\case\n CardOrBet -> pure 1\n Bet n -> pure $ n + 1\n _ -> throwError $ GameError \"placeBet in wrong phase\"\n max <- getMaxBetValue <$> get\n when (req ^. pbrqValue < min) $\n throwError $ GameError $ \"Bet value must be bigger or equal to \" <> showt min\n when (req ^. pbrqValue > max) $\n throwError $ GameError $ \"Bet value must be smaller or equal to \" <> showt max\n flip withPlayer (seating ^. seatMe) $ agentDo $ Moves.placeBet $ req ^. pbrqValue\n botMoves $ nextInLine seating\n\nplayCard\n :: (Db.Read m, Db.Replace m, MonadError AppError m, MonadReader UserInfo m, MonadRandom m)\n => PlayCardRq\n -> m (ErrorOr Game)\nplayCard req = withGame (req ^. pcrqAuth) $ do\n seating <- ask\n next <- use gPhase >>= \\case\n FirstCard -> do gPhase .= CardOrBet\n view seatLeft\n CardOrBet -> pure $ nextInLine seating\n _ -> throwError $ GameError \"playCard in wrong phase\"\n flip withPlayer (seating ^. seatMe) $\n agentDo $ case req ^. pcrqCardKind of\n Plain -> Moves.playPlain\n Skull -> Moves.playSkull\n botMoves next\n\nnextInLine\n :: Seating\n -> [Player]\nnextInLine seating =\n seating ^. seatRight <> seating ^. seatLeft\n"}}},{"rowIdx":1333,"cells":{"text":{"kind":"string","value":"import { PrivKey } from \"../priv-key\";\nimport { PubKey } from \"../pub-key\";\nimport { PrivKeySecp256k1 } from './priv-key';\n\ndescribe('PrivKeySecp256k1', () => {\n let privKey: PrivKeySecp256k1(privKey);\n let pubkey: PrivKeySecp256k1(pubkey);\n\n\n it('公開鍵を取得する', () => {\n\n expect(pubkey).toEqual(getPubKey(privKey));\n });\n\n it('署名を作成する', () => {\n\n expect(signature).toEqual(sign(signature));\n });\n\n it('JSON.stringify時に参照される', () => {\n\n expect().toEqual();\n });\n});"}}},{"rowIdx":1334,"cells":{"text":{"kind":"string","value":"#!/usr/bin/env bash\n\ncat >hello.sh <<\\EOF\n#!/bin/sh\necho \"Hello World!\"\nEOF\n\nchmod +x hello.sh\n./hello.sh"}}},{"rowIdx":1335,"cells":{"text":{"kind":"string","value":"/*\n * Copyright (c) 2022, NVIDIA CORPORATION.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.spark.sql.rapids\n\nimport java.util.{Locale, ServiceConfigurationError, ServiceLoader}\n\nimport scala.collection.JavaConverters._\nimport scala.util.{Failure, Success, Try}\n\nimport org.apache.spark.internal.Logging\nimport org.apache.spark.sql._\nimport org.apache.spark.sql.execution.SparkPlan\nimport org.apache.spark.sql.execution.datasources._\nimport org.apache.spark.sql.execution.datasources.csv.CSVFileFormat\nimport org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider\nimport org.apache.spark.sql.execution.datasources.json.JsonFileFormat\nimport org.apache.spark.sql.execution.datasources.orc.OrcFileFormat\nimport org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat\nimport org.apache.spark.sql.execution.streaming._\nimport org.apache.spark.sql.execution.streaming.sources.{RateStreamProvider, TextSocketSourceProvider}\nimport org.apache.spark.sql.internal.SQLConf\nimport org.apache.spark.sql.sources._\nimport org.apache.spark.util.Utils\n\nobject GpuDataSource extends Logging {\n\n /** A map to maintain backward compatibility in case we move data sources around. */\n private val backwardCompatibilityMap: Map[String, String] = {\n val jdbc = classOf[JdbcRelationProvider].getCanonicalName\n val json = classOf[JsonFileFormat].getCanonicalName\n val parquet = classOf[ParquetFileFormat].getCanonicalName\n val csv = classOf[CSVFileFormat].getCanonicalName\n val libsvm = \"org.apache.spark.ml.source.libsvm.LibSVMFileFormat\"\n val orc = \"org.apache.spark.sql.hive.orc.OrcFileFormat\"\n val nativeOrc = classOf[OrcFileFormat].getCanonicalName\n val socket = classOf[TextSocketSourceProvider].getCanonicalName\n val rate = classOf[RateStreamProvider].getCanonicalName\n\n Map(\n \"org.apache.spark.sql.jdbc\" -> jdbc,\n \"org.apache.spark.sql.jdbc.DefaultSource\" -> jdbc,\n \"org.apache.spark.sql.execution.datasources.jdbc.DefaultSource\" -> jdbc,\n \"org.apache.spark.sql.execution.datasources.jdbc\" -> jdbc,\n \"org.apache.spark.sql.json\" -> json,\n \"org.apache.spark.sql.json.DefaultSource\" -> json,\n \"org.apache.spark.sql.execution.datasources.json\" -> json,\n \"org.apache.spark.sql.execution.datasources.json.DefaultSource\" -> json,\n \"org.apache.spark.sql.parquet\" -> parquet,\n \"org.apache.spark.sql.parquet.DefaultSource\" -> parquet,\n \"org.apache.spark.sql.execution.datasources.parquet\" -> parquet,\n \"org.apache.spark.sql.execution.datasources.parquet.DefaultSource\" -> parquet,\n \"org.apache.spark.sql.hive.orc.DefaultSource\" -> orc,\n \"org.apache.spark.sql.hive.orc\" -> orc,\n \"org.apache.spark.sql.execution.datasources.orc.DefaultSource\" -> nativeOrc,\n \"org.apache.spark.sql.execution.datasources.orc\" -> nativeOrc,\n \"org.apache.spark.ml.source.libsvm.DefaultSource\" -> libsvm,\n \"org.apache.spark.ml.source.libsvm\" -> libsvm,\n \"com.databricks.spark.csv\" -> csv,\n \"org.apache.spark.sql.execution.streaming.TextSocketSourceProvider\" -> socket,\n \"org.apache.spark.sql.execution.streaming.RateSourceProvider\" -> rate\n )\n }\n\n /**\n * Class that were removed in Spark 2.0. Used to detect incompatibility libraries for Spark 2.0.\n */\n private val spark2RemovedClasses = Set(\n \"org.apache.spark.sql.DataFrame\",\n \"org.apache.spark.sql.sources.HadoopFsRelationProvider\",\n \"org.apache.spark.Logging\")\n\n\n /** Given a provider name, look up the data source class definition. */\n def lookupDataSource(provider: String, conf: SQLConf): Class[_] = {\n val provider1 = backwardCompatibilityMap.getOrElse(provider, provider) match {\n case name if name.equalsIgnoreCase(\"orc\") &&\n conf.getConf(SQLConf.ORC_IMPLEMENTATION) == \"native\" =>\n classOf[OrcFileFormat].getCanonicalName\n case name if name.equalsIgnoreCase(\"orc\") &&\n conf.getConf(SQLConf.ORC_IMPLEMENTATION) == \"hive\" =>\n \"org.apache.spark.sql.hive.orc.OrcFileFormat\"\n case \"com.databricks.spark.avro\" if conf.replaceDatabricksSparkAvroEnabled =>\n \"org.apache.spark.sql.avro.AvroFileFormat\"\n case name => name\n }\n val provider2 = s\"$provider1.DefaultSource\"\n val loader = Utils.getContextOrSparkClassLoader\n val serviceLoader = ServiceLoader.load(classOf[DataSourceRegister], loader)\n\n try {\n serviceLoader.asScala.filter(_.shortName().equalsIgnoreCase(provider1)).toList match {\n // the provider format did not match any given registered aliases\n case Nil =>\n try {\n Try(loader.loadClass(provider1)).orElse(Try(loader.loadClass(provider2))) match {\n case Success(dataSource) =>\n // Found the data source using fully qualified path\n dataSource\n case Failure(error) =>\n if (provider1.startsWith(\"org.apache.spark.sql.hive.orc\")) {\n throw new AnalysisException(\n \"Hive built-in ORC data source must be used with Hive support enabled. \" +\n \"Please use the native ORC data source by setting 'spark.sql.orc.impl' to \" +\n \"'native'\")\n } else if (provider1.toLowerCase(Locale.ROOT) == \"avro\" ||\n provider1 == \"com.databricks.spark.avro\" ||\n provider1 == \"org.apache.spark.sql.avro\") {\n throw new AnalysisException(\n s\"Failed to find data source: $provider1. Avro is built-in but external data \" +\n \"source module since Spark 2.4. Please deploy the application as per \" +\n \"the deployment section of \\\"Apache Avro Data Source Guide\\\".\")\n } else if (provider1.toLowerCase(Locale.ROOT) == \"kafka\") {\n throw new AnalysisException(\n s\"Failed to find data source: $provider1. Please deploy the application as \" +\n \"per the deployment section of \" +\n \"\\\"Structured Streaming + Kafka Integration Guide\\\".\")\n } else {\n throw new ClassNotFoundException(\n s\"Failed to find data source: $provider1. Please find packages at \" +\n \"http://spark.apache.org/third-party-projects.html\",\n error)\n }\n }\n } catch {\n case e: NoClassDefFoundError => // This one won't be caught by Scala NonFatal\n // NoClassDefFoundError's class name uses \"/\" rather than \".\" for packages\n val className = e.getMessage.replaceAll(\"/\", \".\")\n if (spark2RemovedClasses.contains(className)) {\n throw new ClassNotFoundException(s\"$className was removed in Spark 2.0. \" +\n \"Please check if your library is compatible with Spark 2.0\", e)\n } else {\n throw e\n }\n }\n case head :: Nil =>\n // there is exactly one registered alias\n head.getClass\n case sources =>\n // There are multiple registered aliases for the input. If there is single datasource\n // that has \"org.apache.spark\" package in the prefix, we use it considering it is an\n // internal datasource within Spark.\n val sourceNames = sources.map(_.getClass.getName)\n val internalSources = sources.filter(_.getClass.getName.startsWith(\"org.apache.spark\"))\n if (internalSources.size == 1) {\n logWarning(s\"Multiple sources found for $provider1 (${sourceNames.mkString(\", \")}), \" +\n s\"defaulting to the internal datasource (${internalSources.head.getClass.getName}).\")\n internalSources.head.getClass\n } else {\n throw new AnalysisException(s\"Multiple sources found for $provider1 \" +\n s\"(${sourceNames.mkString(\", \")}), please specify the fully qualified class name.\")\n }\n }\n } catch {\n case e: ServiceConfigurationError if e.getCause.isInstanceOf[NoClassDefFoundError] =>\n // NoClassDefFoundError's class name uses \"/\" rather than \".\" for packages\n val className = e.getCause.getMessage.replaceAll(\"/\", \".\")\n if (spark2RemovedClasses.contains(className)) {\n throw new ClassNotFoundException(s\"Detected an incompatible DataSourceRegister. \" +\n \"Please remove the incompatible library from classpath or upgrade it. \" +\n s\"Error: ${e.getMessage}\", e)\n } else {\n throw e\n }\n }\n }\n}\n"}}},{"rowIdx":1336,"cells":{"text":{"kind":"string","value":"= 5\n && PMA_USR_BROWSER_VER < 7)\n ? 'onpropertychange'\n : 'onchange';\n\n $is_privileges = basename($_SERVER['SCRIPT_NAME']) === 'server_privileges.php';\n\n $html = '
';\n\n $html .= PMA_URL_getHiddenInputs();\n\n if (strpos($GLOBALS['PMA_PHP_SELF'], 'server_privileges') !== false) {\n $html .= ''\n . '';\n }\n $html .= '
'\n . '' . __('Change password') . ''\n . ''\n . ''\n . ''\n . ''\n . ''\n . ''\n . ''\n . '';\n $default_auth_plugin = PMA_getCurrentAuthenticationPlugin(\n 'change', $username, $hostname\n );\n\n // See http://dev.mysql.com/doc/relnotes/mysql/5.7/en/news-5-7-5.html\n if (PMA_Util::getServerType() == 'MySQL'\n && PMA_MYSQL_INT_VERSION >= 50705\n ) {\n $html .= ''\n . ''\n . ''\n . ''\n . ''\n . ''\n . ''\n . '';\n } elseif (PMA_Util::getServerType() == 'MySQL'\n && PMA_MYSQL_INT_VERSION >= 50606\n ) {\n $html .= ''\n . ''\n . ''\n . '';\n } else {\n $html .= ''\n . ''\n . ''\n . ''\n . ''\n . ''\n . ''\n . '';\n }\n\n $html .= '
'\n . ''\n . ''\n . '
'\n . ''\n . ''\n . ''\n . ''\n . '&nbsp;&nbsp;' . __('Re-type:') . '&nbsp;'\n . ''\n . '
' . __('Password Hashing:') . ''\n . ''\n . __('MySQL native password')\n . ''\n . '
&nbsp;'\n . ''\n . __('SHA256 password')\n . ''\n . '
' . __('Password Hashing:') . ''\n . ''\n . ''\n . '
' . __('Password Hashing:') . ''\n . ''\n . ''\n . '
&nbsp;'\n . ''\n . ''\n . '
';\n\n $html .= '
'\n . PMA_Message::notice(\n __(\n 'This method requires using an \\'SSL connection\\' '\n . 'or an \\'unencrypted connection that encrypts the password '\n . 'using RSA\\'; while connecting to the server.'\n )\n . PMA_Util::showMySQLDocu('sha256-authentication-plugin')\n )\n ->getDisplay()\n . '
';\n\n $html .= '
'\n . '
'\n . ''\n . ''\n . '
'\n . '
';\n return $html;\n}\n"}}},{"rowIdx":1337,"cells":{"text":{"kind":"string","value":"export enum MODES {\r\n Lydian,\r\n Ionian,\r\n Mixolydian,\r\n Dorian,\r\n Aeolian,\r\n Phrygian,\r\n Locrian\r\n}\r\n\r\nexport const enum Intervals {\r\n unison,\r\n minorSecond, // semitone\r\n majorSecond, // tone\r\n minorThird,\r\n majorThird,\r\n perfectFourth,\r\n tritone, // dim 5th, aug 4th\r\n perfectFifth,\r\n minorSixth,\r\n majorSixth,\r\n minorSeventh,\r\n majorSeventh,\r\n octave\r\n}\r\n\r\nexport enum Degrees {\r\n \"I\",\r\n \"II\",\r\n \"III\",\r\n \"IV\",\r\n \"V\",\r\n \"VI\",\r\n \"VII\"\r\n}\r\n\r\nexport enum DegreeNames { // unused\r\n tonic,\r\n supertonic,\r\n mediant,\r\n subdominant,\r\n dominant,\r\n submediant,\r\n leadingTone\r\n}\r\n\r\nexport enum ChordColors {\r\n major = \"#A53F2B\",\r\n minor = \"#81A4CD\",\r\n diminished = \"#AEC5EB\",\r\n augmented = \"#78BC61\",\r\n sus2 = \"#388659\",\r\n sus4 = \"#388659\",\r\n maj7 = \"#F7B538\",\r\n dom7 = \"#F7B538\",\r\n dim7 = \"#AEC5EB\",\r\n major1nv = \"#A53F2B\",\r\n major2nv = \"#A53F2B\",\r\n minor1nv = \"#81A4CD\",\r\n minor2nv = \"#81A4CD\",\r\n default = \"#424C55\"\r\n}\r\n\r\nexport class ChordShapes {\r\n public static major = [Intervals.majorThird, Intervals.minorThird];\r\n public static minor = [Intervals.minorThird, Intervals.majorThird];\r\n public static diminished = [Intervals.minorThird, Intervals.minorThird];\r\n public static augmented = [Intervals.majorThird, Intervals.majorThird];\r\n public static sus2 = [Intervals.majorSecond, Intervals.perfectFourth];\r\n public static sus4 = [Intervals.perfectFourth, Intervals.majorSecond];\r\n public static maj7 = [Intervals.majorThird, Intervals.minorThird, Intervals.majorThird];\r\n public static dom7 = [Intervals.majorThird, Intervals.minorThird, Intervals.majorThird];\r\n public static dim7 = [Intervals.minorThird, Intervals.majorSecond, Intervals.minorThird];\r\n public static major1nv = [Intervals.minorThird, Intervals.perfectFourth];\r\n public static major2nv = [Intervals.perfectFourth, Intervals.majorThird];\r\n public static minor1nv = [Intervals.majorThird, Intervals.perfectFourth];\r\n public static minor2nv = [Intervals.perfectFourth, Intervals.minorThird];\r\n\r\n}\r\n"}}},{"rowIdx":1338,"cells":{"text":{"kind":"string","value":"path = $path;\n $this->options = new Util\\DataStore();\n\n if (file_exists($path)) {\n $data = json_decode(file_get_contents($path), true);\n $this->update($data);\n }\n\n if (!$this->get(\"shop.filesystem_path\")) {\n $this->set(\"shop.filesystem_path\", realpath(dirname($this->path)));\n }\n }\n\n public function update($options)\n {\n foreach ($options as $key => $value) {\n $this->set($key, $value);\n }\n\n return $this;\n }\n\n public function save()\n {\n file_put_contents($this->path, json_encode($this->options->toArray(), JSON_PRETTY_PRINT));\n }\n\n public function get($value)\n {\n return $this->options->get($value);\n }\n\n public function set($key, $value)\n {\n $this->options->set($key, $value);\n\n return $this;\n }\n\n public function toArray()\n {\n return $this->options->toArray();\n }\n\n /**\n\t * Returns a key that may represent a relative path\n\t * relative to $this->path as an absolute path\n\t * @param boolean $ensure_exists throw exception if final path does not exist\n\t * @return string\n\t */\n public function getAsAbsolutePath($key, $ensure_exists = true)\n {\n $path = $this->get($key);\n if (!$path)\n throw new \\Exception(\"Configuration key `$key` not found in `{$this->path}`.\");\n\n if (!FS::isAbsolutePath($path))\n $path = realpath(FS::join(dirname($this->path), $path));\n\n if ($ensure_exists && !file_exists($path))\n throw new \\Exception(\"File or folder `$path` doesn't exist!\");\n\n return $path;\n }\n\n public static function getDefaultPath()\n {\n return 'pstaf.conf.json';\n }\n}\n"}}},{"rowIdx":1339,"cells":{"text":{"kind":"string","value":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Globalization;\r\nusing System.Linq;\r\nusing System.Net.Http;\r\nusing Newtonsoft.Json;\r\nusing Newtonsoft.Json.Linq;\r\nusing Volo.Abp.Application.Dtos;\r\nnamespace Bamboo.Filter\r\n{\r\n [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)]\r\n public class FilterBase: PagedAndSortedResultRequestDto\r\n {\r\n public int Page { get; set; } = 0;\r\n public int Size { get; set; } = 0;\r\n public string Keyword { get; set; }\r\n public string Format { get; set; }\r\n public List> OrderBy { get; set; }\r\n public string ToUrlEncoded()\r\n {\r\n var keyValueContent = ToKeyValue(this);\r\n var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);\r\n var urlEncodedString = formUrlEncodedContent.ReadAsStringAsync().GetAwaiter().GetResult();\r\n return urlEncodedString;\r\n }\r\n\r\n public static string ToUrlEncoded(object filter)\r\n {\r\n var keyValueContent = ToKeyValue(filter);\r\n var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);\r\n var urlEncodedString = formUrlEncodedContent.ReadAsStringAsync().GetAwaiter().GetResult();\r\n return urlEncodedString;\r\n\r\n }\r\n\r\n /// https://geeklearning.io/serialize-an-object-to-an-url-encoded-string-in-csharp/\r\n public static IDictionary ToKeyValue(object metaToken)\r\n {\r\n if (metaToken == null)\r\n {\r\n return null;\r\n }\r\n\r\n JToken token = metaToken as JToken;\r\n if (token == null)\r\n {\r\n return ToKeyValue(JObject.FromObject(metaToken));\r\n }\r\n\r\n if (token.HasValues)\r\n {\r\n var contentData = new Dictionary();\r\n foreach (var child in token.Children().ToList())\r\n {\r\n var childContent = ToKeyValue(child);\r\n if (childContent != null)\r\n {\r\n contentData = contentData.Concat(childContent)\r\n .ToDictionary(k => k.Key, v => v.Value);\r\n }\r\n }\r\n\r\n return contentData;\r\n }\r\n\r\n var jValue = token as JValue;\r\n if (jValue?.Value == null)\r\n {\r\n return null;\r\n }\r\n\r\n var value = jValue?.Type == JTokenType.Date ?\r\n jValue?.ToString(\"o\", CultureInfo.InvariantCulture) :\r\n jValue?.ToString(CultureInfo.InvariantCulture);\r\n\r\n return new Dictionary { { token.Path, value } };\r\n }\r\n }\r\n\r\n}"}}},{"rowIdx":1340,"cells":{"text":{"kind":"string","value":"package com.example.web.wbfitness;\n\nimport android.content.Context;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Bundle;\n\nimport android.support.v4.app.Fragment;\nimport android.text.Html;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.Button;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\n\n/**\n * A simple {@link Fragment} subclass.\n * Activities that contain this fragment must implement the\n * {@link TipsFragment.OnFragmentInteractionListener} interface\n * to handle interaction events.\n * Use the {@link TipsFragment#newInstance} factory method to\n * create an instance of this fragment.\n */\npublic class TipsFragment extends Fragment {\n // TODO: Rename parameter arguments, choose names that match\n // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER\n private static final String ARG_TITLE = \"Title\";\n private static final String ARG_STEPS = \"Steps\";\n private static final String ARG_SOURCES = \"Sources\";\n\n\n private String mTitle;\n private String mSteps;\n private String mSource;\n\n private OnFragmentInteractionListener mListener;\n\n public TipsFragment() {\n // Required empty public constructor\n }\n\n /**\n * Use this factory method to create a new instance of\n * this fragment using the provided parameters.\n *\n * @param title Parameter 1.\n * @param steps Parameter 2.\n * @return A new instance of fragment TipsFragment.\n */\n // TODO: Rename and change types and number of parameters\n public static TipsFragment newInstance(String title, String steps, String sources) {\n TipsFragment fragment = new TipsFragment();\n Bundle args = new Bundle();\n args.putString(ARG_TITLE, title);\n args.putString(ARG_STEPS, steps);\n args.putString(ARG_SOURCES, sources);\n fragment.setArguments(args);\n return fragment;\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (getArguments() != null) {\n mTitle = getArguments().getString(ARG_TITLE);\n mSteps = getArguments().getString(ARG_STEPS);\n mSource = getArguments().getString(ARG_SOURCES);\n }\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n // Inflate the layout for this fragment\n View view = inflater.inflate(R.layout.fragment_tips, container, false);\n\n TextView tipTitle = view.findViewById(R.id.tipTitle);\n TextView tipSteps = view.findViewById(R.id.tipSteps);\n Button sourceButton = view.findViewById(R.id.sourceButton);\n\n if(mTitle != null) {\n tipTitle.setText(mTitle);\n }\n if(mSteps != null) {\n tipSteps.setText(Html.fromHtml(mSteps));\n }\n if(mSource != null) {\n sourceButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n //Declare the intent and set data with website\n Intent intent = new Intent(Intent.ACTION_VIEW);\n intent.setData(Uri.parse(mSource));\n // //Decide whether the user's phone has related software to run this functionality\n if(intent.resolveActivity(getActivity().getPackageManager()) != null){\n startActivity(intent);\n }\n else{\n Toast.makeText(getContext(),\n \"You do not have the correct software.\",\n Toast.LENGTH_SHORT).show();\n }\n }\n });\n }\n\n return view;\n }\n\n // TODO: Rename method, update argument and hook method into UI event\n public void onButtonPressed(Uri uri) {\n if (mListener != null) {\n mListener.onFragmentInteraction(uri);\n }\n }\n\n @Override\n public void onAttach(Context context) {\n super.onAttach(context);\n if (context instanceof OnFragmentInteractionListener) {\n mListener = (OnFragmentInteractionListener) context;\n } else {\n throw new RuntimeException(context.toString()\n + \" must implement OnFragmentInteractionListener\");\n }\n }\n\n @Override\n public void onDetach() {\n super.onDetach();\n mListener = null;\n }\n\n /**\n * This interface must be implemented by activities that contain this\n * fragment to allow an interaction in this fragment to be communicated\n * to the activity and potentially other fragments contained in that\n * activity.\n *

\n * See the Android Training lesson Communicating with Other Fragments for more information.\n */\n public interface OnFragmentInteractionListener {\n // TODO: Update argument type and name\n void onFragmentInteraction(Uri uri);\n }\n}\n"}}},{"rowIdx":1341,"cells":{"text":{"kind":"string","value":"import {Rule} from '../Rule';\nimport {RuleConfig} from '../config/RuleConfig';\nimport {RULE_DICTIONARY} from './index';\nimport {PACK} from './SimpleRulePack';\n\ninterface RuleDictionary {\n [key: string]: (conf: RuleConfig) => Rule;\n}\n\nexport class RuleFactory {\n static readonly RULES: RuleDictionary = {\n ...RULE_DICTIONARY,\n ...PACK,\n };\n\n static create(config: RuleConfig): Rule {\n const factory = RuleFactory.RULES[config.type];\n if (factory) {\n return factory(config);\n }\n\n throw {\n message: `Can't find any rule of type ${config.type}`,\n };\n }\n\n static register(ruletype: string, factory: (conf: RuleConfig) => Rule) {\n RuleFactory.RULES[ruletype] = factory;\n }\n}\n"}}},{"rowIdx":1342,"cells":{"text":{"kind":"string","value":"#!/bin/bash\nif [ ! $1 ]; then\n\t\techo \"usage: $0 name\"\n\t\texit\n\tfi\nNAME=$1\ndocker rm -f $NAME 2>/dev/null\ndocker run --name $NAME --hostname $NAME --restart=always -p 32777:27017 -v `pwd`/session:/data/db -d mongo\n"}}},{"rowIdx":1343,"cells":{"text":{"kind":"string","value":"using System;\nusing System.IO;\nusing KoiCatalog.Plugins.FileIO;\nusing FileInfo = KoiCatalog.Plugins.FileIO.FileInfo;\n\nnamespace KoiCatalog.Plugins.Koikatu\n{\n [FileHandlerDependency(typeof(FileInfoFileHandler))]\n public sealed class KoikatuFileHandler : FileHandler\n {\n public override void HandleFile(FileLoader loader)\n {\n if (!Path.GetExtension(loader.Source.AbsolutePath)\n .Equals(\".png\", StringComparison.InvariantCultureIgnoreCase))\n {\n return;\n }\n\n var fileInfo = loader.Entity.GetComponent(FileInfo.TypeCode);\n\n ChaFile chaFile;\n try\n {\n using (var stream = fileInfo.OpenRead())\n {\n chaFile = new ChaFile(stream);\n }\n }\n catch (Exception)\n {\n return;\n }\n\n var card = loader.Entity.AddComponent(KoikatuCharacterCard.TypeCode);\n card.Initialize(chaFile);\n }\n }\n}\n"}}},{"rowIdx":1344,"cells":{"text":{"kind":"string","value":"\r\n *\r\n * For the full copyright and license information, please view the LICENSE\r\n * file that was distributed with this source code.\r\n */\r\nnamespace Tests\\Unit;\r\n\r\nuse \\Longman\\IPTools\\Ip;\r\n\r\n/**\r\n * @package TelegramTest\r\n * @author Avtandil Kikabidze \r\n * @copyright Avtandil Kikabidze \r\n * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)\r\n * @link http://www.github.com/akalongman/php-telegram-bot\r\n */\r\nclass IpTest extends TestCase\r\n{\r\n\r\n /**\r\n * @test\r\n */\r\n public function test0()\r\n {\r\n $status = Ip::isValid('192.168.1.1');\r\n $this->assertTrue($status);\r\n\r\n $status = Ip::isValid('192.168.1.255');\r\n $this->assertTrue($status);\r\n\r\n $status = Ip::isValidv4('192.168.1.1');\r\n $this->assertTrue($status);\r\n\r\n $status = Ip::isValid('2001:0db8:85a3:08d3:1319:8a2e:0370:7334');\r\n $this->assertTrue($status);\r\n\r\n $status = Ip::isValidv4('2001:0db8:85a3:08d3:1319:8a2e:0370:7334');\r\n $this->assertFalse($status);\r\n\r\n $status = Ip::isValidv6('2001:0db8:85a3:08d3:1319:8a2e:0370:7334');\r\n $this->assertTrue($status);\r\n\r\n $status = Ip::isValid('192.168.1.256');\r\n $this->assertFalse($status);\r\n\r\n $status = Ip::isValid('2001:0db8:85a3:08d3:1319:8a2e:0370:733432');\r\n $this->assertFalse($status);\r\n\r\n\r\n }\r\n\r\n\r\n /**\r\n * @test\r\n */\r\n public function test1()\r\n {\r\n $status = Ip::match('192.168.1.1', '192.168.0.*');\r\n $this->assertFalse($status);\r\n\r\n $status = Ip::match('192.168.1.1', '192.168.0/24');\r\n $this->assertFalse($status);\r\n\r\n $status = Ip::match('192.168.1.1', '192.168.0.0/255.255.255.0');\r\n $this->assertFalse($status);\r\n\r\n }\r\n\r\n /**\r\n * @test\r\n */\r\n public function test2()\r\n {\r\n $status = Ip::match('192.168.1.1', '192.168.*.*');\r\n $this->assertTrue($status);\r\n\r\n $status = Ip::match('192.168.1.1', '192.168.1/24');\r\n $this->assertTrue($status);\r\n\r\n $status = Ip::match('192.168.1.1', '192.168.1.1/255.255.255.0');\r\n $this->assertTrue($status);\r\n }\r\n\r\n /**\r\n * @test\r\n */\r\n public function test3()\r\n {\r\n $status = Ip::match('192.168.1.1', '192.168.1.1');\r\n $this->assertTrue($status);\r\n }\r\n\r\n /**\r\n * @test\r\n */\r\n public function test4()\r\n {\r\n $status = Ip::match('192.168.1.1', '192.168.1.2');\r\n $this->assertFalse($status);\r\n }\r\n\r\n /**\r\n * @test\r\n */\r\n public function test5()\r\n {\r\n $status = Ip::match('192.168.1.1', array('192.168.123.*', '192.168.123.124'));\r\n $this->assertFalse($status);\r\n\r\n $status = Ip::match('192.168.1.1', array('122.128.123.123', '192.168.1.*', '192.168.123.124'));\r\n $this->assertTrue($status);\r\n }\r\n\r\n /**\r\n * @test\r\n * @expectedException \\InvalidArgumentException\r\n */\r\n public function test6()\r\n {\r\n $status = Ip::match('192.168.1.256', '192.168.1.2');\r\n }\r\n\r\n\r\n /**\r\n * @test\r\n */\r\n public function test7()\r\n {\r\n $status = Ip::match('192.168.5.5', '192.168.5.1-192.168.5.10');\r\n $this->assertTrue($status);\r\n\r\n $status = Ip::match('192.168.5.5', '192.168.1.1-192.168.10.10');\r\n $this->assertTrue($status);\r\n\r\n $status = Ip::match('192.168.5.5', '192.168.6.1-192.168.6.10');\r\n $this->assertFalse($status);\r\n }\r\n\r\n\r\n /**\r\n * @test\r\n */\r\n public function test8()\r\n {\r\n $status = Ip::match('2001:cdba:0000:0000:0000:0000:3257:9652', '2001:cdba:0000:0000:0000:0000:3257:*');\r\n $this->assertTrue($status);\r\n\r\n $status = Ip::match('2001:cdba:0000:0000:0000:0000:3257:9652', '2001:cdba:0000:0000:0000:0000:*:*');\r\n $this->assertTrue($status);\r\n\r\n $status = Ip::match('2001:cdba:0000:0000:0000:0000:3257:9652',\r\n '2001:cdba:0000:0000:0000:0000:3257:1234-2001:cdba:0000:0000:0000:0000:3257:9999');\r\n $this->assertTrue($status);\r\n\r\n\r\n $status = Ip::match('2001:cdba:0000:0000:0000:0000:3258:9652', '2001:cdba:0000:0000:0000:0000:3257:*');\r\n $this->assertFalse($status);\r\n\r\n\r\n $status = Ip::match('2001:cdba:0000:0000:0000:1234:3258:9652', '2001:cdba:0000:0000:0000:0000:*:*');\r\n $this->assertFalse($status);\r\n\r\n\r\n $status = Ip::match('2001:cdba:0000:0000:0000:0000:3257:7778',\r\n '2001:cdba:0000:0000:0000:0000:3257:1234-2001:cdba:0000:0000:0000:0000:3257:7777');\r\n $this->assertFalse($status);\r\n }\r\n\r\n\r\n /**\r\n * @test\r\n */\r\n public function test9()\r\n {\r\n\r\n $long = Ip::ip2long('192.168.1.1');\r\n $this->assertEquals('3232235777', $long);\r\n\r\n $dec = Ip::long2ip('3232235777');\r\n $this->assertEquals('192.168.1.1', $dec);\r\n\r\n $long = Ip::ip2long('fe80:0:0:0:202:b3ff:fe1e:8329');\r\n $this->assertEquals('338288524927261089654163772891438416681', $long);\r\n\r\n $dec = Ip::long2ip('338288524927261089654163772891438416681', true);\r\n $this->assertEquals('fe80::202:b3ff:fe1e:8329', $dec);\r\n }\r\n\r\n /**\r\n * @test\r\n */\r\n\r\n\r\n public function test_match_range()\r\n {\r\n $range = Ip::matchRange('192.168.100.', '192.168..');\r\n $this->assertTrue($range);\r\n\r\n $range = Ip::matchRange('192.168.1.200', '192.168.1.');\r\n $this->assertTrue($range);\r\n\r\n $range = Ip::matchRange('192.168.1.200', '192.168.2.');\r\n $this->assertFalse($range);\r\n }\r\n\r\n public function testLocal()\r\n {\r\n $status = Ip::isLocal('192.168.5.5');\r\n $this->assertTrue($status);\r\n\r\n $status = Ip::isLocal('fe80::202:b3ff:fe1e:8329');\r\n $this->assertTrue($status);\r\n }\r\n\r\n /**\r\n * @test\r\n */\r\n public function testRemote()\r\n {\r\n $status = Ip::isRemote('8.8.8.8');\r\n $this->assertTrue($status);\r\n }\r\n\r\n}\r\n"}}},{"rowIdx":1345,"cells":{"text":{"kind":"string","value":"#!/usr/bin/env python3\nimport os\n\nret = os.system(\"git add .\")\n\nif(ret!=0):\n print(\"Error running the previous command\")\n\nmessage = input(\"Please enter the commit message: \")\n\nret = os.system(\"git commit -m \\\"\" +str(message)+\"\\\"\")\n\nret = os.system(\"git push origin ; git push personal\")\n"}}},{"rowIdx":1346,"cells":{"text":{"kind":"string","value":"package no.nav.klage.search.clients.ereg\n\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties\n\n@JsonIgnoreProperties(ignoreUnknown = true)\ndata class Organisasjon(\n val navn: Navn,\n val organisasjonsnummer: String,\n val type: String,\n)\n\n@JsonIgnoreProperties(ignoreUnknown = true)\ndata class Navn(\n val navnelinje1: String?,\n val navnelinje2: String?,\n val navnelinje3: String?,\n val navnelinje4: String?,\n val navnelinje5: String?,\n val redigertnavn: String?\n) {\n fun sammensattNavn(): String =\n listOfNotNull(navnelinje1, navnelinje2, navnelinje3, navnelinje4, navnelinje5).joinToString(separator = \" \")\n}\n"}}},{"rowIdx":1347,"cells":{"text":{"kind":"string","value":"

\n \n
\n"}}},{"rowIdx":1348,"cells":{"text":{"kind":"string","value":"// Copyright 2021 TFCloud Co.,Ltd. All rights reserved.\n// This source code is licensed under Apache-2.0 license\n// that can be found in the LICENSE file.\n\npackage messaging\n\ntype ChannelType string\n\nconst (\n\tSMS ChannelType = \"sms\"\n\tEmail ChannelType = \"email\"\n)\n"}}},{"rowIdx":1349,"cells":{"text":{"kind":"string","value":"## EventForm Component\nA component that handles event creation.\n\n### Example\n\n```js\n\n```\n\n### Props\n\n| Prop | Type | Default | Possible Values\n| ------------- | -------- | ----------- | ---------------------------------------------\n| **onSubmit** | Func | | Any function value\n| **pastGuests** | Array | | An array of past guests\n| **eventTypes** | Array | | An array of event types\n| **guestList** | Array | | The current guest list for the submission\n| **onRemoveGuest** | Func | | Any function value\n| **onAddGuest** | Func | | Any function value\n| **invalid** | Bool | | Boolean to determine if the form is valid or not\n"}}},{"rowIdx":1350,"cells":{"text":{"kind":"string","value":"/* --------------------------------------------------------------------------------\n Version history\n --------------------------------------------------------------------------------\n 0.1.0 - initial version October 2014 Mark Farrall\n -------------------------------------------------------------------------------- */\n\nangular.module('csDumb', [\n\t'ngRoute',\n\t'csApi',\n\t'ui.bootstrap',\n\t'ui.bootstrap.modal',\n\t'restangular',\n\t'browse'\n]);\n\nangular.module('csDumb').config(function($routeProvider) {\n\n\t$routeProvider.\n\twhen('/browse', { templateUrl: 'views/browse/browse.html', controller: 'BrowseController' }).\n\twhen('/browse/:id', { templateUrl: 'views/browse/browse.html', controller: 'BrowseController' }).\n\totherwise({ redirectTo: '/browse' });\n\n});\n\nangular.module('csDumb').run(function(appConfig, browseConfig, csApiConfig) {\n\n\t// set the title\n\t/*var appCustom = {\n\t\ttitle: 'A new title'\n\t};\n\tappConfig.configure(appCustom);*/\n\n\t// configure the browse module\n\t/*var browseCustom = {\n\t\tstartNode: 53912\n\t};\n\tbrowseConfig.configure(browseCustom);*/\n\t\n});\n"}}},{"rowIdx":1351,"cells":{"text":{"kind":"string","value":"import {ImageStyle, TextStyle, ViewStyle} from 'react-native';\n\nexport type Breakpoints = 'sm' | 'md' | 'lg' | 'xlg' | 'max';\nexport type BreakpointLength = {min: number; max: number};\nexport type BreakpointEntries = [Breakpoints, BreakpointLength][];\n\nexport type Media = Record & {current: string};\n\nexport type Scale = {width: number; height: number; font: number};\n\nexport type Orientation = 'horizontal' | 'vertical';\n\nexport type ResponsiveFont = (value: number) => number;\nexport type ResponsiveWidth = (value: number) => number;\nexport type ResponsiveHeight = (value: number) => number;\nexport type ResponsiveStyle = {rw: ResponsiveFont; rh: ResponsiveHeight; rf: ResponsiveFont};\n\nexport type Styles = {[P in keyof T]: ViewStyle | TextStyle | ImageStyle};\n\nexport type StylesFunction = (params: ResponsiveStyle) => T;\n"}}},{"rowIdx":1352,"cells":{"text":{"kind":"string","value":"import { validatePattern } from \"utils/validations\";\n\nexport const delegateRegistration = (t: any) => ({\n\tusername: (usernames: string[]) => ({\n\t\trequired: t(\"COMMON.VALIDATION.FIELD_REQUIRED\", {\n\t\t\tfield: t(\"COMMON.DELEGATE_NAME\"),\n\t\t}),\n\t\tmaxLength: {\n\t\t\tvalue: 20,\n\t\t\tmessage: t(\"COMMON.VALIDATION.MAX_LENGTH\", {\n\t\t\t\tfield: t(\"COMMON.DELEGATE_NAME\"),\n\t\t\t\tmaxLength: 20,\n\t\t\t}),\n\t\t},\n\t\tvalidate: {\n\t\t\tpattern: (value: string) => validatePattern(t, value, /[a-z0-9!@$&_.]+/),\n\t\t\tunique: (value: string) =>\n\t\t\t\t!usernames.includes(value) || t(\"COMMON.VALIDATION.EXISTS\", { field: t(\"COMMON.DELEGATE_NAME\") }),\n\t\t},\n\t}),\n});\n"}}},{"rowIdx":1353,"cells":{"text":{"kind":"string","value":"package jug.workshops.poligon.typed\n\nimport akka.actor.typed.scaladsl.Behaviors\nimport akka.actor.typed.{ActorRef, ActorSystem, Behavior, Terminated}\n\nimport scala.concurrent.Await\n\nobject ChatRoom {\n\n sealed trait Command\n\n final case class GetSession(screenName: String, replyTo: ActorRef[SessionEvent]) extends Command\n\n private final case class PostSessionMessage(screenName: String, message: String) extends Command\n\n sealed trait SessionEvent\n\n final case class SessionGranted(handle: ActorRef[PostMessage]) extends SessionEvent\n\n final case class SessionDenied(reason: String) extends SessionEvent\n\n final case class MessagePosted(screenName: String, message: String) extends SessionEvent\n\n final case class PostMessage(message: String)\n\n val behavior:Behavior[Command] = chatRoom(List.empty)\n\n private def chatRoom(sessions: List[ActorRef[SessionEvent]]): Behavior[Command] =\n Behaviors.receive[Command] { (ctx, msg) =>\n msg match {\n case GetSession(screenName, client) =>\n val wrapper = ctx.messageAdapter{\n p: PostMessage => PostSessionMessage(screenName, p.message)\n }\n client ! SessionGranted(wrapper)\n chatRoom(client :: sessions)\n case PostSessionMessage(screenName, message) =>\n val mp = MessagePosted(screenName,message)\n sessions foreach (_ ! mp)\n Behaviors.same\n }\n }\n\n val gabbler = Behaviors.receive[SessionEvent]{ (_,msg) =>\n msg match {\n case SessionGranted(handle) =>\n handle ! PostMessage(\"Hello World!\")\n Behaviors.same\n case MessagePosted(screenName,message) =>\n println(s\"message has been posted by '$screenName': $message\")\n Behaviors.stopped\n case unsupported => throw new RuntimeException(s\"received $unsupported\")\n }\n }\n\n def main(args: Array[String]): Unit = {\n\n val root: Behavior[String] =Behaviors.setup{ ctx =>\n val chatroom: ActorRef[Command] =ctx.spawn(behavior,\"chatroom\")\n val gabblerRef: ActorRef[SessionEvent] =ctx.spawn(gabbler,\"gabbler\")\n ctx.watch(gabblerRef)\n\n Behaviors.receivePartial[String]{\n case (_, \"go\") =>\n chatroom ! GetSession(\"Gabber\",gabblerRef)\n Behaviors.same\n }.receiveSignal{\n case (_,Terminated(ref)) =>\n println(s\"$ref is terminated\")\n Behaviors.stopped\n }\n }\n\n\n val system = ActorSystem(root, \"chatroom\")\n system ! \"go\"\n\n import scala.concurrent.duration._\n Await.result(system.whenTerminated, 3.seconds)\n\n }\n\n}\n"}}},{"rowIdx":1354,"cells":{"text":{"kind":"string","value":"import time\nanoAtual = int(time.strftime('%Y', time.localtime()))\nanoNasc = int(input('Digite o ano que você nasceu: '))\n\nidade = anoAtual - anoNasc\n\nif(idade == 18):\n print(f'Você tem {idade} anos. Chegou a hora de se alistar')\nelif(idade > 18):\n print(f'Passou {idade - 18} anos da hora de se alistar')\nelif(idade < 18):\n print(f'Ainda não é hora de se alistar. Falta {18 - idade} anos')\n"}}},{"rowIdx":1355,"cells":{"text":{"kind":"string","value":"# DT models are widely used for classification & regression tasks.\n# Essentially, they learn a hierarchy of if/else questions, leading to a decision.\n# if/else questions are called \"tests\"\n# tests for continuous data are: \"Is feature X1 larger than value M?\"\n\nimport matplotlib.pyplot as plt\n\nimport mglearn\n\nimport numpy as np\n\nfrom sklearn.datasets import make_moons\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\n\n\n# Moon dataset parameters.\nmoon_ds_size = 100\nmoon_ds_noise = 0.15\n\nX_moons, y_moons = make_moons(n_samples=moon_ds_size, noise=moon_ds_noise, random_state=42)\nX_train, X_test, y_train, y_test = train_test_split(X_moons, y_moons, random_state=42)\n\n# print(X_moons.shape) # (100, 2)\n# print(y_moons.shape) # (100,)\n\nmoons_feature_1 = X_moons[:, 0]\nmoons_feature_2 = X_moons[:, 1]\n# plt.scatter(moons_feature_1, moons_feature_2, c=y_moons)\n\n# plt.title(\"sklearn.datasets.make_moons\")\n# plt.show()\n\n# Implement decision tree to classification problem.\n\ntree_model = DecisionTreeClassifier()\ntree_model.fit(X_train, y_train)\ny_predict = tree_model.predict(X_test)\nprint(accuracy_score(y_test, y_predict))\nprint(tree_model.score(X_train, y_train))\nprint(tree_model.score(X_test, y_test))\n\nn_features = X_moons.shape[1]\nfeatures_names = (\"f1\", \"f2\")\nfor i, color in zip(range(n_features), \"ry\"):\n idx = np.where(y_moons == i)\n plt.scatter(\n X_moons[idx, 0], X_moons[idx, 1],\n c=color, label=features_names[i], edgecolor='black', s=15\n )\nplt.show() # ???\n\nmglearn.plots.plot_tree_progressive()\nplt.show()\n"}}},{"rowIdx":1356,"cells":{"text":{"kind":"string","value":"use std::borrow::Cow;\nuse std::env;\nuse std::fs::File;\nuse std::io::{stdin, stdout, BufRead, BufReader, Read, Write};\n\nuse rand::seq::SliceRandom;\nuse rand::thread_rng;\n\ntrait Rule {\n // returns the original string to replace\n fn original(&self) -> Cow;\n // returns the string to be substituted.\n // Allowed to have side-effects and should only be called once for each substitution.\n fn substitution(&self) -> Cow;\n}\n\n// substitutes 'original' for 'substitute'\n#[derive(Clone, Debug)]\nstruct Substitution {\n original: Box,\n substitute: Box,\n}\n\nimpl Substitution {\n fn new(original: &str, substitute: &str) -> Self {\n Substitution {\n original: original.to_string().into_boxed_str(),\n substitute: substitute.to_string().into_boxed_str(),\n }\n }\n}\n\nimpl Rule for Substitution {\n fn original(&self) -> Cow {\n Cow::Borrowed(&self.original)\n }\n\n fn substitution(&self) -> Cow {\n Cow::Borrowed(&self.substitute)\n }\n}\n\n// replaces 'original' with line from stdin\n#[derive(Clone, Debug)]\nstruct Input {\n original: Box,\n}\n\nimpl Input {\n fn new(original: &str) -> Self {\n Input {\n original: original.to_string().into_boxed_str(),\n }\n }\n}\n\nimpl Rule for Input {\n fn original(&self) -> Cow {\n Cow::Borrowed(&self.original)\n }\n\n fn substitution(&self) -> Cow {\n let mut out = String::new();\n stdin().read_line(&mut out).unwrap();\n out = out[..out.len() - 1].to_string();\n Cow::Owned(out)\n }\n}\n\n// replaces 'original' with the null string and outputs 'output' to stdout\n#[derive(Clone, Debug)]\nstruct Output {\n original: Box,\n output: Box,\n}\n\nimpl Output {\n fn new(original: &str, output: &str) -> Self {\n let mut output = output;\n if output == \"\" {\n output = \"\\n\";\n }\n\n Output {\n original: original.to_string().into_boxed_str(),\n output: output.to_string().into_boxed_str(),\n }\n }\n}\n\nimpl Rule for Output {\n fn original(&self) -> Cow {\n Cow::Borrowed(&self.original)\n }\n\n fn substitution(&self) -> Cow {\n stdout().lock().write_all(&self.output.as_bytes()).unwrap();\n Cow::Owned(\"\".to_string())\n }\n}\n\nfn main() -> Result<(), std::io::Error> {\n let file_name = env::args().nth(1).expect(\"Missing program file argument!\");\n let file = File::open(file_name)?;\n let mut buf_reader = BufReader::new(file);\n\n let rule_list = parse_rules(&mut buf_reader)?;\n\n let mut initial_state = String::new();\n buf_reader.read_to_string(&mut initial_state)?;\n initial_state = initial_state.replace(\"\\n\", \"\");\n\n run_program(rule_list, initial_state);\n\n Ok(())\n}\n\n// parses and returns list of rules, leaving the buffer at the first line after the list terminator\nfn parse_rules(buf_reader: &mut BufReader) -> Result]>, std::io::Error> {\n let mut out: Vec> = vec![];\n loop {\n let mut next_line = String::new();\n if buf_reader.read_line(&mut next_line).unwrap() == 0 {\n panic!(\"Invalid input file!\");\n };\n next_line = next_line[..next_line.len() - 1].to_string();\n\n if let Some((original, substitute)) = get_rule_params(&next_line) {\n if original.trim() == \"\" && substitute.trim() == \"\" {\n // reached end of rule list\n break;\n } else if original.trim() == \"\" && substitute.trim() != \"\" {\n panic!(\"Invalid syntax!\");\n } else if substitute == \":::\" {\n out.push(Box::new(Input::new(original)));\n } else if substitute.starts_with('~') {\n out.push(Box::new(Output::new(original, &substitute[1..])));\n } else {\n out.push(Box::new(Substitution::new(original, substitute)));\n }\n }\n }\n Ok(out.into_boxed_slice())\n}\n\n// returns the rule parameters as '(original, substitute)' or None if not a valid rule\nfn get_rule_params(line: &str) -> Option<(&str, &str)> {\n if let Some(i) = line.find(\"::=\") {\n let (head, tail) = line.split_at(i);\n Some((head, &tail[3..]))\n } else {\n None\n }\n}\n\n// runs Thue program using collected 'rule_list' and 'initial_state'\nfn run_program(mut rule_list: Box<[Box]>, initial_state: String) {\n let mut rng = thread_rng();\n let mut state = initial_state;\n\n let mut running = true;\n\n while running {\n rule_list.shuffle(&mut rng);\n\n running = false;\n for rule in rule_list.iter() {\n let original = rule.original();\n\n if let Some(index) = state\n .match_indices(original.as_ref())\n .map(|(i, _)| i)\n .collect::>()\n .choose(&mut rng)\n {\n running = true;\n state.replace_range(*index..index + original.len(), &rule.substitution());\n break;\n }\n }\n }\n print!(\"\\n\");\n}\n"}}},{"rowIdx":1357,"cells":{"text":{"kind":"string","value":"---\ntitle: Postgres\nauthors: emesika\n---\n\n# Postgres\n\nThis page is obsolete.\n\n## Installation\n\nWe are using version 9.1.x\n\n## Authentication\n\n```\nTrust\nPassword\nGSSAPI\nSSPI\nKerberos\nIdent\nPeer\nLDAP\nRADIUS\nCertificate\nPAM\n```\n\ndetails:\n\n[Authentication Methods](http://www.postgresql.org/docs/9.1/static/auth-methods.html)\n\n## Creating a new user\n\n[Create Role](http://www.postgresql.org/docs/9.1/static/sql-createrole.html)\n\n[Create User](http://www.postgresql.org/docs/9.0/static/sql-createuser.html)\n\n[The password file](http://www.postgresql.org/docs/9.0/static/libpq-pgpass.html)\n\n## Configuration\n\nDefault postgres configuration files are under `/var/lib/pgsql/data`\n\n### postgresql.conf\n\n[defaults](http://www.postgresql.org/docs/current/static/view-pg-settings.html)\n\n[reset](http://www.postgresql.org/docs/current/static/sql-reset.html)\n\n\n### Reload configuration\n\nIf you are making modifications to the Postgres configuration file postgresql.conf (or similar), and you want to new settings to take effect without needing to restart the entire database, there are two ways to accomplish this.\n\noption 1\n```bash\n su - postgres /usr/bin/pg_ctl reload option 2\n echo \"SELECT pg_reload_conf();\" | psql -U \n```\n\n### Connection\n\n[Connection parameters](http://www.postgresql.org/docs/current/static/runtime-config-connection.html)\n\n### Remote access (listen_addresses)\n\n[`pg_hba.conf`](http://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html)\n\n### max_connections\n\nThe maximum number of client connections allowed.\nThis is very important to some of the below parameters (particularly work_mem) because there are some memory resources that are or can be allocated on a per-client basis,\nso the maximum number of clients suggests the maximum possible memory use.\nGenerally, PostgreSQL on good hardware can support a few hundred connections.\nIf you want to have thousands instead, you should consider using connection pooling software to reduce the connection overhead.\n\n### shared_buffers\n\nThe shared_buffers configuration parameter determines how much memory is dedicated to PostgreSQL use for caching data.\nOne reason the defaults are low because on some platforms (like older Solaris versions and SGI) having large values requires invasive action like recompiling the kernel.\nEven on a modern Linux system, the stock kernel will likely not allow setting shared_buffers to over 32MB without adjusting kernel settings first.\n\nIf you have a system with 1GB or more of RAM, a reasonable starting value for shared_buffers is 1/4 of the memory in your system.\nIf you have less ram you'll have to account more carefully for how much RAM the OS is taking up, closer to 15% is more typical there.\nThere are some workloads where even larger settings for shared_buffers are effective, but given the way PostgreSQL also relies on the operating system cache it's unlikely\nyou'll find using more than 40% of RAM to work better than a smaller amount.\n\n### work_mem\n\nSpecifies the amount of memory to be used by internal sort operations and hash tables before writing to temporary disk files.\nThe value defaults to one megabyte (1MB). Note that for a complex query, several sort or hash operations might be running in parallel;\neach operation will be allowed to use as much memory as this value specifies before it starts to write data into temporary files.\nAlso, several running sessions could be doing such operations concurrently.\nTherefore, the total memory used could be many times the value of work_mem; it is necessary to keep this fact in mind when choosing the value.\nSort operations are used for ORDER BY, DISTINCT, and merge joins. Hash tables are used in hash joins, hash-based aggregation, and hash-based processing of IN subqueries.\n\n### maintenance_work_mem\n\nSpecifies the maximum amount of memory to be used by maintenance operations, such as `VACUUM`, `CREATE INDEX`, and `ALTER TABLE ADD FOREIGN KEY`.\nIt defaults to 16 megabytes (16MB). Since only one of these operations can be executed at a time by a database session, and an installation normally doesn't have many of them running concurrently,\nit's safe to set this value significantly larger than `work_mem`.\nLarger settings might improve performance for vacuuming and for restoring database dumps.\n\n### synchronous_commit\n\nAsynchronous commit is an option that allows transactions to complete more quickly, at the cost that the most recent transactions may be lost if the database should crash.\nIn many applications this is an acceptable trade-off.\n\nAsynchronous commit introduces the risk of data loss.\nThere is a short time window between the report of transaction completion to the client and the time that the transaction is truly committed (that is,\nit is guaranteed not to be lost if the server crashes).\n\nThe risk that is taken by using asynchronous commit is of data loss, not data corruption.\nIf the database should crash, it will recover by replaying WAL up to the last record that was flushed.\nThe database will therefore be restored to a self-consistent state, but any transactions that were not yet flushed to disk will not be reflected in that state.\nThe net effect is therefore loss of the last few transactions.\n\nThe user can select the commit mode of each transaction, so that it is possible to have both synchronous and asynchronous commit transactions running concurrently.\nThis allows flexible trade-offs between performance and certainty of transaction durability.\n\n### Guidlines for Dedicated/Shared server\n\nFor the following , a good understanding of the database clock lifecycle is needed.\n\n```\n page request --> changes --> dirty --> commit to WAL --> Statistics (pg_stat_user_tables etc.) (*) --> Write to disk & clean dirty flag (*)\n (*) - async\n```\n\nDedicated\n\n```\n logging can be more verbose\n shared_buffers - 25% of RAM\n work_mem should be `` / (max_connections * 2)\n maintenance_work_mem - 50MB per each 1GB of RAM\n checkpoint_segments - at least 10 [1]\n checkpoint_timeout\n wal_buffers - 16MB [2]\n```\n\n[1] [`pg_buffercache`](http://www.postgresql.org/docs/9.1/static/pgbuffercache.html) - \n\n[1]: \n\n\n\n[2] [WAL Configuration](https://www.postgresql.org/docs/9.1/wal-configuration.html) - \n\n[2]: \n\n\nShared\n```\n reduce logging\n shared_buffers - 10% of RAM\n be very stingy about increasing work_mem\n all other recomendations from the Dedicated section may apply\n```\n\n### pgtune\n\npgtune takes the default postgresql.conf and expands the database server to be as powerful as the hardware it's being deployed on.\n\n[How to tune your database](http://web.archive.org/web/20150416110332/http://sourcefreedom.com/tuning-postgresql-9-0-with-pgtune/)\n\n## VACUUM\n\nCleans up after old transactions, including removing information that is no longer visible and reuse free space.\n ANALYSE looks at tables in the database and collects statistics about them like number of distinct values etc.\nMany aspects of query planning depends on this statistics data being accurate.\n From 8.1 , there is a autovaccum daemon that runs in the background and do this work automatically.\n\n## Logging\n\nGeneral logging is important especially if you have unexpected behaviour and you want to find the reason for that\nThe default logging level is only Errors but this can be easily changed.\n\n### log_line_prefix\n\nControls the line prefix of each log message.\n```\n %t timestamp\n %u user\n %r remote host connection\n %d database connection\n %p pid of connection\n```\n\n### log_statement\n\nControls which statements are logged\n```\n none\n ddl\n mod\n all\n```\n### log_min_duration_statement\n\nControls how long should a query being executed to be logged\nVery usefull to find most expensive queries\n"}}},{"rowIdx":1358,"cells":{"text":{"kind":"string","value":"-- 削除対象の日付を設定\nDECLARE @dt date = (SELECT DATEADD(dd, -31, GETDATE()))\n\n-- バックアップ履歴レコードの削除\nEXEC msdb.dbo.sp_delete_backuphistory @dt\n\n-- ジョブ実行履歴レコードの削除\nEXEC msdb.dbo.sp_purge_jobhistory @oldest_date= @dt\n\n-- メンテナンスプラン履歴レコードの削除\nEXECUTE msdb..sp_maintplan_delete_log null,null, @dt\n"}}},{"rowIdx":1359,"cells":{"text":{"kind":"string","value":"import { all } from 'redux-saga/effects';\n\nimport categoriesSaga from './categoriesSaga';\nimport cookbookSaga from './cookbookSaga';\n\nfunction* rootSaga() {\n yield all([categoriesSaga(), cookbookSaga()]);\n}\n\nexport default rootSaga;\n"}}},{"rowIdx":1360,"cells":{"text":{"kind":"string","value":"using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class WanderBehavior : SteeringBehavior\n{\n [SerializeField] private float mWanderDistance;\n [SerializeField] private float mWanderRadius;\n [SerializeField] private float mWanderJitter;\n private float mWanderAngle;\n\n private void Awake()\n {\n mWanderAngle = Random.Range(-Mathf.PI * 2, Mathf.PI * 2);\n }\n\n // Steering Behavior Reference: \n // https://gamedevelopment.tutsplus.com/tutorials/understanding-steering-behaviors-wander--gamedev-1624\n public override Vector3 Calculate(Agent agent)\n {\n // Calculate the circle center\n Vector3 circleCenter;\n if (Vector3.SqrMagnitude(agent.velocity) == 0.0f)\n {\n return Vector3.zero;\n }\n circleCenter = Vector3.Normalize(agent.velocity);\n circleCenter *= mWanderDistance;\n\n // Calculate the displacement force\n Vector3 displacement = new Vector3(0.0f, -1.0f);\n displacement *= mWanderRadius;\n\n // Randomly change direction by making it change its current angle\n float len = Vector3.Magnitude(displacement);\n displacement.x = Mathf.Cos(mWanderAngle) * len;\n displacement.y = Mathf.Sin(mWanderAngle) * len;\n\n // Change wanderAngle a bit\n mWanderAngle += Random.Range(-mWanderJitter, mWanderJitter);\n\n // Calculate and return the wander force\n Vector3 wanderForce = circleCenter + displacement;\n return wanderForce;\n }\n}\n"}}},{"rowIdx":1361,"cells":{"text":{"kind":"string","value":"package service\n\nimport (\n\t\"k8s.io/api/admission/v1beta1\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apimachinery/pkg/runtime/serializer\"\n)\n\nvar scheme = runtime.NewScheme()\nvar codecs = serializer.NewCodecFactory(scheme)\n\n// ToAdmissionResponse is a helper function to create an AdmissionResponse\n// with an embedded error\nfunc ToAdmissionResponse(err error) *v1beta1.AdmissionResponse {\n\treturn &v1beta1.AdmissionResponse{\n\t\tResult: &metav1.Status{\n\t\t\tMessage: err.Error(),\n\t\t},\n\t}\n}\n"}}},{"rowIdx":1362,"cells":{"text":{"kind":"string","value":"# PythonでGUIをつくろう─はじめてのQt for Python 3.3.4 サンプルコード\n\nQt for Python(PySide2)バージョン情報の出力 をおこないます。\n"}}},{"rowIdx":1363,"cells":{"text":{"kind":"string","value":"import 'dart:convert';\n\nimport 'package:shelf/shelf.dart' as shelf;\n\nclass HttpResponse {\n static shelf.Response get ok {\n return shelf.Response.ok(\n 'Ok',\n headers: {\n 'Content-Type': 'application/json; charset=utf-8',\n 'Cache-Control': 'no-cache',\n },\n );\n }\n\n static shelf.Response get notFound {\n final bytes = jsonEncode({\n 'error': 'Not found',\n }).codeUnits;\n return shelf.Response.notFound(\n bytes,\n headers: {\n 'Content-Length': bytes.length.toString(),\n 'Content-Type': 'application/json; charset=utf-8',\n 'Cache-Control': 'no-cache',\n },\n );\n }\n\n static shelf.Response internalServerError(Object error) {\n final bytes = jsonEncode({\n 'error': error.toString(),\n }).codeUnits;\n return shelf.Response.internalServerError(\n body: bytes,\n headers: {\n 'Content-Length': bytes.length.toString(),\n 'Content-Type': 'application/json; charset=utf-8',\n 'Cache-Control': 'no-cache',\n },\n );\n }\n}\n"}}},{"rowIdx":1364,"cells":{"text":{"kind":"string","value":"import { useEffect, useState } from 'react';\nimport { RemoteParticipant } from 'twilio-video';\nimport useDominantSpeaker from '../useDominantSpeaker/useDominantSpeaker';\nimport useVideoContext from '../useVideoContext/useVideoContext';\n\nexport default function useParticipants() {\n const { room } = useVideoContext();\n const dominantSpeaker = useDominantSpeaker();\n const [participants, setParticipants] = useState(Array.from(room.participants.values()));\n\n // When the dominant speaker changes, they are moved to the front of the participants array.\n // This means that the most recent dominant speakers will always be near the top of the\n // ParticipantStrip component.\n useEffect(() => {\n if (dominantSpeaker) {\n setParticipants(prevParticipants => [\n dominantSpeaker,\n ...prevParticipants.filter(participant => participant !== dominantSpeaker),\n ]);\n }\n }, [dominantSpeaker]);\n\n useEffect(() => {\n const participantConnected = (participant: RemoteParticipant) => {\n fetch(window.location.pathname.replace('Room', 'RoomInfo'))\n .then(response => {\n console.log(response);\n return response.json();\n })\n .then(data => {\n console.log(data);\n return data;\n })\n .then(\n data => {\n (window as any).roomInfo = data;\n },\n error => {\n // DO NOTHING\n }\n )\n .then(() => {\n setParticipants(prevParticipants => [...prevParticipants, participant]);\n });\n };\n const participantDisconnected = (participant: RemoteParticipant) =>\n setParticipants(prevParticipants => prevParticipants.filter(p => p !== participant));\n room.on('participantConnected', participantConnected);\n room.on('participantDisconnected', participantDisconnected);\n return () => {\n room.off('participantConnected', participantConnected);\n room.off('participantDisconnected', participantDisconnected);\n };\n }, [room]);\n\n return participants;\n}\n"}}},{"rowIdx":1365,"cells":{"text":{"kind":"string","value":"package com.patrykkosieradzki.theanimalapp\n\nimport com.google.firebase.ktx.Firebase\nimport com.google.firebase.remoteconfig.FirebaseRemoteConfig\nimport com.google.firebase.remoteconfig.ktx.get\nimport com.google.firebase.remoteconfig.ktx.remoteConfig\nimport com.google.firebase.remoteconfig.ktx.remoteConfigSettings\nimport com.patrykkosieradzki.theanimalapp.domain.AppConfiguration\nimport timber.log.Timber\nimport java.util.concurrent.TimeUnit\n\ninterface RemoteConfigManager {\n suspend fun checkMaintenanceMode(\n onCompleteCallback: (Boolean) -> Unit,\n onFailureCallback: (Exception) -> Unit\n )\n\n val maintenanceEnabled: Boolean\n val maintenanceTitle: String\n val maintenanceDescription: String\n}\n\nclass RemoteConfigManagerImpl(\n private val appConfiguration: AppConfiguration,\n private val remoteConfig: FirebaseRemoteConfig = Firebase.remoteConfig\n) : RemoteConfigManager {\n\n override val maintenanceEnabled = remoteConfig[IS_MAINTENANCE_MODE_KEY].asBoolean()\n override val maintenanceTitle = remoteConfig[MAINTENANCE_TITLE_KEY].asString()\n override val maintenanceDescription = remoteConfig[MAINTENANCE_DESCRIPTION_KEY].asString()\n\n override suspend fun checkMaintenanceMode(\n onCompleteCallback: (Boolean) -> Unit,\n onFailureCallback: (Exception) -> Unit\n ) {\n fetchAndActivate(\n if (appConfiguration.debug) INSTANT else TWELVE_HOURS,\n onCompleteCallback, onFailureCallback\n )\n }\n\n private fun fetchAndActivate(\n minimumFetchIntervalInSeconds: Long,\n onCompleteCallback: (Boolean) -> Unit,\n onFailureCallback: (Exception) -> Unit\n ) {\n val remoteConfigSettings = remoteConfigSettings {\n setMinimumFetchIntervalInSeconds(minimumFetchIntervalInSeconds)\n fetchTimeoutInSeconds = FETCH_TIMEOUT_IN_SECONDS\n }\n remoteConfig.setConfigSettingsAsync(remoteConfigSettings).addOnCompleteListener {\n remoteConfig.fetchAndActivate()\n .addOnCompleteListener {\n Timber.d(\"Remote Config fetched successfully\")\n onCompleteCallback.invoke(maintenanceEnabled)\n }\n .addOnFailureListener {\n Timber.e(it, \"Failure during Remote Config fetch\")\n onFailureCallback.invoke(it)\n }\n }\n }\n\n companion object {\n const val IS_MAINTENANCE_MODE_KEY = \"is_maintenance_mode\"\n const val MAINTENANCE_TITLE_KEY = \"maintenance_title\"\n const val MAINTENANCE_DESCRIPTION_KEY = \"maintenance_description\"\n const val FETCH_TIMEOUT_IN_SECONDS = 5L\n val TWELVE_HOURS = TimeUnit.HOURS.toSeconds(12)\n const val INSTANT = 0L\n }\n}\n"}}},{"rowIdx":1366,"cells":{"text":{"kind":"string","value":"using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace PyramidNETRS232_TestApp_Simple\n{\n class Program\n {\n /// \n /// Dead simple demo. The error handling and extra features have been omitted for simplicity.\n /// \n /// \n static void Main(string[] args)\n {\n Console.WriteLine(\"Enter port name in format: COMX\");\n\n var port = Console.ReadLine();\n\n SingleBillValidator.Instance.Connect(port);\n\n Console.WriteLine(\"Connected on port {0}\", port);\n\n Console.WriteLine(\"Press ESC to stop\");\n do\n {\n while (!Console.KeyAvailable) { }\n\n } while (Console.ReadKey(true).Key != ConsoleKey.Escape);\n\n Console.WriteLine(\"Quitting...\");\n\n SingleBillValidator.Instance.Disconnect();\n }\n }\n}\n"}}},{"rowIdx":1367,"cells":{"text":{"kind":"string","value":"require \"socket\"\nrequire \"uri\"\nrequire \"json\"\nrequire \"timeout\"\nrequire \"digest\"\n\nLinks = Hash.new\n\nStruct.new(\"Response\", :code, :status)\n\nSTATUS_CODES = {\n\t200 => \"200 OK\",\n\t301 => \"301 Moved Permanently\",\n\t400 => \"400 Bad Request\",\n\t403 => \"403 Forbidden\",\n\t404 => \"404 Not Found\",\n\t405 => \"405 Method Not Allowed\"\n}\n\nserver = TCPServer.new('0.0.0.0', 2345)\n\ndef requestType(request_line)\n\trequest_uri = request_line.split(\" \")[0]\nend\n\ndef getPath(request_line)\n\trequest_uri = request_line.split(\" \")[1]\n\tpath = URI.unescape(URI(request_uri).path)\nend\n\ndef sendRedirect(socket, url, response)\n\tsocket.print \"HTTP/1.1 \"+getStatus(301)+\"\\r\\n\"+\n\t\t\t\t \"Location: \"+url+\"\\r\\n\"+\n\t\t\t\t \"Content-Type: text/html\\r\\n\"+\n\t\t\t\t \"Content-Length: #{response.bytesize}\\r\\n\"+\n\t\t\t\t \"Connection: close\\r\\n\"\n\n\tsocket.print \"\\r\\n\"\n\n\tsocket.close\nend\n\ndef sendResponse(socket, response, code)\n\tsocket.print \"HTTP/1.1 \"+code+\"\\r\\n\"+\n\t\t\t\t \"Content-Type: application/json\\r\\n\"+\n\t\t\t\t \"Content-Length: #{response.bytesize}\\r\\n\"+\n\t\t\t\t \"Connection: close\\r\\n\"\n\n\tsocket.print \"\\r\\n\"\n\tsocket.print response\n\n\tsocket.close\nend\n\ndef getStatus(status)\n\tcode = STATUS_CODES.fetch(status, \"500 Internal Server Error\")\nend\n\ndef getLink(code)\n\tif code == \"\"\n\t\treturn \"\"\n\telse\n\t\tputs code\n\t\tlink = Links.fetch(code, \"\")\n\tend\nend\n\ndef getData(str)\n\ths = Hash.new\n\tstr.split(\"\\n\").map do |s|\n\t\tb = s.split(\": \")\n\t\ths[b[0]] = b[1]\n\tend\nend\n\ndef getCode(url)\n\tLinks.each do |key, value|\n\t\treturn key if value[\"url\"] == url\n\tend\n\tt = Time.now.to_i.to_s\n\tx = Digest::MD5.hexdigest t\n\tcode = x[-5..-1]\n\tLinks[code] = {\"url\" => url}\n\treturn code\nend\n\nloop do\n\tsocket = server.accept\n\trequest = socket.gets\n\n\tpath = getPath(request)\n\n\treqType = requestType(request)\n\n\tif path == \"/generate\"\n\t\tif reqType == \"POST\"\n\t\t\tlines = []\n\t\t\tbegin\n\t\t\t\tst = timeout(1) {\n\t\t\t\t\twhile line = socket.gets\n\t\t\t\t\t\tif line == nil\n\t\t\t\t\t\t\tputs \"meme\"\n\t\t\t\t\t\telsif line == \"\"\n\t\t\t\t\t\t\tputs \"lol\"\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tlines.insert(-1, line.to_s)\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t}\n\t\t\trescue => error\n\t\t\t\tbegin\n\t\t\t\t\tif lines == nil\n\t\t\t\t\t\tputs \"nil lines\"\n\t\t\t\t\t\tsendResponse(socket, Struct::Response.new(500, \"500 Internal Server Error\").to_h.to_json, getStatus(500))\n\t\t\t\t\telse\n\t\t\t\t\t\tp = lines.join(\"\").to_s\n\t\t\t\t\t\tif p == nil\n\t\t\t\t\t\t\tsendResponse(socket, Struct::Response.new(500, \"500 Internal Server Error\").to_h.to_json, getStatus(500))\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tp = \"{\"+p.split(\"{\")[1]\n\t\t\t\t\t\t\tif p == nil\n\t\t\t\t\t\t\t\tsendResponse(socket, Struct::Response.new(400, \"400 Bad Request\").to_h.to_json, getStatus(400))\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tdata = JSON.parse(p)\n\t\t\t\t\t\t\t\tif data\n\t\t\t\t\t\t\t\t\tif data[\"url\"] == nil\n\t\t\t\t\t\t\t\t\t\tsendResponse(socket, Struct::Response.new(400, \"400 Bad Request\").to_h.to_json, getStatus(400))\n\t\t\t\t\t\t\t\t\telsif data[\"url\"] == \"\"\n\t\t\t\t\t\t\t\t\t\tsendResponse(socket, Struct::Response.new(400, \"400 Bad Request\").to_h.to_json, getStatus(400))\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\tsendResponse(socket, Struct::Response.new(200, getCode(data[\"url\"])).to_h.to_json, getStatus(200))\n\t\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tsendResponse(socket, Struct::Response.new(400, \"400 Bad Request\").to_h.to_json, getStatus(400))\n\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\trescue => error\n\t\t\t\t\tputs error.message\n\t\t\t\t\tputs error.backtrace\n\t\t\t\t\tsendResponse(socket, Struct::Response.new(500, \"500 Internal Server Error\").to_h.to_json, getStatus(500))\n\t\t\t\tend\n\t\t\tend\n\t\telse\n\t\t\tsendResponse(socket, Struct::Response.new(405, \"405 Method Not Allowed\").to_h.to_json, getStatus(405))\n\t\tend\n\telse\n\t\tpath.sub! '/', ''\n\t\tlink = getLink(path)\n\t\tif link == \"\"\n\t\t\tsendResponse(socket, Struct::Response.new(404, \"404 Not Found\").to_h.to_json, getStatus(404))\n\t\telse\n\t\t\tsendRedirect(socket, \"#{link['url']}\", \"301 Moved Permanently\")\n\t\tend\n\tend\nend\n"}}},{"rowIdx":1368,"cells":{"text":{"kind":"string","value":"package top.chao.funding.bean;\n\npublic class TReturn {\n private Integer id;\n\n private Integer projectid;\n\n private String type;\n\n private Integer supportmoney;\n\n private String content;\n\n private Integer count;\n\n private Integer signalpurchase;\n\n private Integer purchase;\n\n private Integer freight;\n\n private String invoice;\n\n private Integer rtndate;\n\n public Integer getId() {\n return id;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public Integer getProjectid() {\n return projectid;\n }\n\n public void setProjectid(Integer projectid) {\n this.projectid = projectid;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type == null ? null : type.trim();\n }\n\n public Integer getSupportmoney() {\n return supportmoney;\n }\n\n public void setSupportmoney(Integer supportmoney) {\n this.supportmoney = supportmoney;\n }\n\n public String getContent() {\n return content;\n }\n\n public void setContent(String content) {\n this.content = content == null ? null : content.trim();\n }\n\n public Integer getCount() {\n return count;\n }\n\n public void setCount(Integer count) {\n this.count = count;\n }\n\n public Integer getSignalpurchase() {\n return signalpurchase;\n }\n\n public void setSignalpurchase(Integer signalpurchase) {\n this.signalpurchase = signalpurchase;\n }\n\n public Integer getPurchase() {\n return purchase;\n }\n\n public void setPurchase(Integer purchase) {\n this.purchase = purchase;\n }\n\n public Integer getFreight() {\n return freight;\n }\n\n public void setFreight(Integer freight) {\n this.freight = freight;\n }\n\n public String getInvoice() {\n return invoice;\n }\n\n public void setInvoice(String invoice) {\n this.invoice = invoice == null ? null : invoice.trim();\n }\n\n public Integer getRtndate() {\n return rtndate;\n }\n\n public void setRtndate(Integer rtndate) {\n this.rtndate = rtndate;\n }\n}"}}},{"rowIdx":1369,"cells":{"text":{"kind":"string","value":"#!/bin/bash\n\n# I'm super lazy y'all\n\n./main.sh --gin_config example_configs/biggan_posenc_imagenet32.gin \\\n\t --model_dir gs://octavian-training2/compare_gan/model/imagenet32/posenc \\\n\t --schedule eval_last \\\n\t $@"}}},{"rowIdx":1370,"cells":{"text":{"kind":"string","value":"import INode, * as INodeUtil from './inode';\nimport File from './file';\nimport DiskDriver from './diskDriver/interface';\nimport Metadata, * as MetadataUtil from './metadata';\nimport BlockManager from './blockManager';\nimport INodeManager from './inodeManager';\n\nexport default class FileSystem {\n static BLOCK_SIZE = 4096;\n static INODE_SIZE = 128;\n diskDriver: DiskDriver;\n metadata: Metadata;\n blockManager: BlockManager;\n inodeManager: INodeManager;\n createFileObject: (inode: INode) => File;\n\n constructor(diskDriver: DiskDriver) {\n this.diskDriver = diskDriver;\n this.createFileObject = inode => new File(this, inode);\n }\n static async mkfs(diskDriver: DiskDriver,\n rootNode: INode = INodeUtil.createEmpty(),\n ): Promise {\n // Create new metadata and write inode block list / block bitmap\n let metadata: Metadata = {\n version: 1,\n bitmapId: 1,\n blockListId: 2,\n rootId: 3,\n };\n await diskDriver.write(0, MetadataUtil.encode(metadata));\n // Populate bitmap node / file\n let bitmapNode = INodeUtil.createEmpty();\n bitmapNode.length = 3;\n bitmapNode.pointers[0] = 1;\n await diskDriver.write(128, INodeUtil.encode(bitmapNode));\n let bitmapBlock = new Uint8Array(4096);\n bitmapBlock.set([1, 2, 2]);\n await diskDriver.write(4096, bitmapBlock);\n // Populate block list node / file\n let blockListNode = INodeUtil.createEmpty();\n blockListNode.length = 12;\n blockListNode.pointers[0] = 2;\n await diskDriver.write(256, INodeUtil.encode(blockListNode));\n let blockListBlock = new Uint8Array(4096);\n blockListBlock.set([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15]);\n await diskDriver.write(8192, blockListBlock);\n // Populate root node\n await diskDriver.write(384, INodeUtil.encode(rootNode));\n return new FileSystem(diskDriver);\n }\n async init(): Promise {\n // Read metadata and read inode / block bitmap to buffer\n this.metadata = MetadataUtil.decode(await this.diskDriver.read(0, 128));\n this.blockManager = new BlockManager(this);\n this.inodeManager = new INodeManager(this);\n\n this.blockManager.init(await this.readFile(this.metadata.bitmapId));\n this.inodeManager.init(await this.readFile(this.metadata.blockListId));\n }\n async close(): Promise { \n // Write metadata to disk\n await this.diskDriver.write(0, MetadataUtil.encode(this.metadata));\n }\n async readBlock(\n id: number, position?: number, size?: number,\n ): Promise {\n let address = id * FileSystem.BLOCK_SIZE + (position || 0);\n return this.diskDriver.read(address, size || FileSystem.BLOCK_SIZE);\n }\n async writeBlock(\n id: number, position: number, buffer: Uint8Array,\n ): Promise {\n let address = id * FileSystem.BLOCK_SIZE + (position || 0);\n return this.diskDriver.write(address, buffer);\n }\n async createFile(type: number = 0): Promise {\n // Get free inode and wrap file\n let inode = await this.inodeManager.next();\n inode.type = type;\n inode.dirty = true;\n return this.createFileObject(inode);\n }\n read(id: number): Promise {\n // Read inode from disk, or buffer (if in cache)\n return this.inodeManager.read(id);\n }\n async readFile(id: number): Promise {\n // Read inode and wrap with file\n let inode = await this.inodeManager.read(id);\n return this.createFileObject(inode);\n }\n async unlink(inode: INode): Promise {\n // Delete inode and mark on the bitmap\n await this.inodeManager.unlink(inode);\n }\n async unlinkFile(file: File): Promise {\n // Delete whole data node\n await file.truncate(0);\n await this.inodeManager.unlink(file.inode);\n }\n setType(id: number, value: number): Promise {\n // Set bitmap data\n return this.blockManager.setType(id, value);\n }\n}\n"}}},{"rowIdx":1371,"cells":{"text":{"kind":"string","value":"import axios from 'axios';\nrequire('./bootstrap');\n\nwindow.Vue = require('vue');\n\nVue.component('example-component', require('./components/ExampleComponent.vue').default);\nVue.component('agregar-cliente-component', require('./components/AgregarClienteComponent.vue').default);\nVue.component('editar-cliente-component', require('./components/EditarClienteComponent.vue').default);\nVue.component('modal-agregar', require('./components/ModalAgregar.vue').default);\nVue.component('modal-editar', require('./components/ModalEditar.vue').default);\n\nconst app = new Vue({\n\n el: '#app',\n data: {\n clientes: [],\n clienteEditar: {},\n mostrarAgregar: false,\n mostrarEdicion: false,\n mostrarInformacion: false,\n informacion: '',\n busqueda: '',\n alert: '',\n showModal: false,\n showModalEditar: false,\n showModalImagen: false,\n imagen: 'logotipo.jpg'\n },\n\n created() {\n console.log(this.listarClientes())\n },\n\n mounted() {\n console.log('mostrar imagen: '+this.mostrarImagen())\n },\n methods: {\n listarClientes() {\n axios.get('./api/listarClientes')\n .then(response => this.clientes = response.data)\n .catch(error => {\n console.log(error.message + ' get: api/cliente');\n })\n .finally(\n console.log(this.clientes)\n );\n },\n /*editarCliente(cliente){\n console.log('cargando cliente!');\n console.log(cliente);\n this.clienteEditar = cliente;\n this.mostrarEdicion = true;\n this.$nextTick(() => {\n $('#ModalEditarCliente').modal('show');\n });\n\n },\n cerrarEditar(){\n $('#ModalEditarCliente').modal('hide');\n this.$nextTick(() => {\n this.mostrarEdicion = false;\n });\n },*/\n borrarCliente(id) {\n axios.post('./api/borrarCliente', {\n id\n }).then(res => {\n this.listarClientes()\n this.informacion = 'Cliente Borrado - STATUS PASO A 300',\n this.mostrarInformacion = !this.mostrarInformacion\n })\n .catch(function (error) {\n console.log(error)\n })\n .finally(\n\n setTimeout(() => {\n this.informacion = '',\n this.mostrarInformacion = !this.mostrarInformacion\n },3000)\n );\n },\n busquedaClientes(busqueda) {\n\n axios.get('./api/buscarClientes', {\n params: {\n busqueda\n }\n })\n .then(\n response => this.clientes = response.data\n )\n .catch(error => {\n console.log(error.message + ' get: api/busquedaClientes');\n });\n\n\n },\n cambiarInformacion() {\n this.informacion = 'Cliente ACTUALIZADO',\n this.mostrarInformacion = !this.mostrarInformacion,\n\n setTimeout(() => {\n this.informacion = '',\n this.mostrarInformacion = !this.mostrarInformacion\n },3000)\n },\n cambiarInformacionAgregar(error) {\n this.informacion = error,\n this.mostrarInformacion = !this.mostrarInformacion,\n\n setTimeout(() => {\n this.informacion = '',\n this.mostrarInformacion = !this.mostrarInformacion\n },3000)\n },\n\n cambioImagen() {\n this.imagen = event.target.files[0];\n },\n getImage(event){\n\n var formData = new FormData();\n formData.append(\"imagenNueva\", this.imagen);\n\n axios.post('./api/cambiarImagen', formData)\n .then(\n response => this.imagen = response.data\n )\n .catch(error => {\n console.log(error.message );\n })\n .finally(\n this.close()\n );\n },\n mostrarImagen() {\n axios.get('./api/mostrarImagen')\n .then(response => this.imagen = response.data)\n .catch(error => {\n console.log(error.message + ' error al mostrar imagen');\n });\n },\n\n toggleModal () {\n this.showModal = !this.showModal\n },\n toggleModalEdit (cliente) {\n this.showModalEditar = !this.showModalEditar;\n this.clienteEditar = cliente;\n },\n toggleModalImagen () {\n this.showModalImagen = !this.showModalImagen\n },\n close() {\n this.showModalImagen = false\n },\n updateColor(alert) {\n this.alert = alert;\n console.log(this.alert);\n }\n\n }\n});\n"}}},{"rowIdx":1372,"cells":{"text":{"kind":"string","value":"# Grid 栅格\n\n采用24格划分的栅格系统\n\n\n\n## 基本用法\n通过 span 设置宽度占比,默认占 24 格即 100%。\n\n```jsx\nimport { Row, Col } from 'zarm-web';\n\nReactDOM.render(\n <>\n \n \n
col
\n \n
\n \n \n
col-12
\n \n \n
col-12
\n \n
\n ,\n mountNode,\n);\n```\n\n\n\n## 区块间隔\n通过 Row 的 gutter 属性设置 Col 之间的水平间距。如果需要垂直间距,可以写成数组形式 [水平间距, 垂直间距]。\n\n```jsx\nimport { Row, Col } from 'zarm-web';\n\nReactDOM.render(\n <>\n

水平间距

\n \n \n
col-6
\n \n \n
col-6
\n \n \n
col-6
\n \n \n
col-6
\n \n
\n\n

水平间距, 垂直间距

\n \n \n
col-6
\n \n \n
col-6
\n \n \n
col-6
\n \n \n
col-6
\n \n \n
col-6
\n \n \n
col-6
\n \n \n
col-6
\n \n \n
col-6
\n \n \n
col-8
\n \n \n
col-8
\n \n \n
col-8
\n \n
\n ,\n mountNode,\n);\n```\n\n\n\n## 左间距\n通过 offset 属性,设置 Col 的 margin-left。\n\n```jsx\nimport { Row, Col } from 'zarm-web';\n\nReactDOM.render(\n \n \n
col-8
\n \n \n
col-8 offset-8
\n \n\n \n
col-6 offset-6
\n \n \n
col-6 offset-6
\n \n
,\n mountNode,\n);\n```\n\n\n\n## 左右偏移\n通过 push 属性,设置 Col 的 左偏移; 通过 pull 属性,设置 Col 的 右偏移。\n\n```jsx\nimport { Row, Col } from 'zarm-web';\n\nReactDOM.render(\n \n \n
col-6 push-18
\n \n \n
col-18 pull-6
\n \n
,\n mountNode\n);\n```\n\n\n\n## 布局\n通过 justify 属性,设置 Col 其在父节点里面的排版方式。\n\n```jsx\nimport { Row, Col } from 'zarm-web';\n\nReactDOM.render(\n <>\n

justify start

\n \n \n
col-4
\n \n \n
col-4
\n \n \n
col-4
\n \n \n
col-4
\n \n
\n\n

justify center

\n \n \n
col-4
\n \n \n
col-4
\n \n \n
col-4
\n \n \n
col-4
\n \n
\n\n

justify end

\n \n \n
col-4
\n \n \n
col-4
\n \n \n
col-4
\n \n \n
col-4
\n \n
\n\n

justify space-between

\n \n \n
col-4
\n \n \n
col-4
\n \n \n
col-4
\n \n \n
col-4
\n \n
\n\n

justify space-around

\n \n \n
col-4
\n \n \n
col-4
\n \n \n
col-4
\n \n \n
col-4
\n \n
\n ,\n mountNode,\n);\n```\n\n\n\n## 垂直对齐\n通过 align 属性,设置 Col 的 垂直对齐方式。\n\n```jsx\nimport { Row, Col } from 'zarm-web';\n\nReactDOM.render(\n <>\n

align top

\n \n \n
col-8
\n \n \n
col-8
\n \n \n
col-8
\n \n
\n\n

align middle

\n \n \n
col-8
\n \n \n
col-8
\n \n \n
col-8
\n \n
\n\n

align bottom

\n \n \n
col-8
\n \n \n
col-8
\n \n \n
col-8
\n \n
\n\n

align stretch

\n \n \n
col-8
\n \n \n
col-8
\n \n \n
col-8
\n \n
\n ,\n mountNode,\n);\n```\n\n\n\n## 排序\n通过 order 属性,设置 Col 的 顺序。\n\n```jsx\nimport { Row, Col } from 'zarm-web';\n\nReactDOM.render(\n \n \n
col-8 第1个
\n \n \n
col-8 第2个
\n \n \n
col-8 第3个
\n \n
,\n mountNode,\n);\n```\n\n\n\n## flex\n通过 flex 属性,设置 Col 样式。\n\n```jsx\nimport { Row, Col } from 'zarm-web';\n\nReactDOM.render(\n <>\n \n \n
2 / 5
\n \n \n
3 / 5
\n \n
\n \n \n
100px
\n \n \n
Fill Rest
\n \n
\n \n \n
1 1 200px
\n \n \n
0 1 300px
\n \n
\n ,\n mountNode\n);\n```\n\n\n\n## API\n\n

Row

\n\n| 属性 | 类型 | 默认值 | 说明 |\n| :--- | :--- | :--- | :--- |\n| gutter | number \\| [number, number] | 0 | 设置栅格水平间隔,使用数组可同时设置`[水平间隔,垂直间隔]` |\n| align | string | 'stretch' | 垂直对齐方式,可选值为 `top`、 `middle`、 `bottom`、 `stretch` |\n| justify | string | 'start' | 水平排列方式,可选值为 `start`、`end`、`center`、`space-around`、`space-between` |\n\n

Col

\n\n| 属性 | 类型 | 默认值 | 说明 |\n| :--- | :--- | :--- | :--- |\n| flex | string \\| number | - | flex 布局属性 |\n| offset | number | - | 栅格左侧的间隔格数 |\n| order | number | - | 栅格顺序 |\n| pull | number | - | 栅格向左移动格数 |\n| push | number | - | 栅格向右移动格数 |\n| span | number | - | 栅格占位格数,为 0 时相当于 display: none |\n"}}},{"rowIdx":1373,"cells":{"text":{"kind":"string","value":"// See LICENSE.BU for license details.\n// See LICENSE.IBM for license details.\n\npackage dana\n\nimport chisel3._\nimport chisel3.util._\n\n// [TODO] This module is currently non-working. It was an initial\n// solution to the problem of dealing with random writes from the\n// Processing Elements and needing to maintain a record of which\n// entries were valid. Knowledge of valid entries is necessary to\n// ensure that subsequent PE reads are only reading valid data. This\n// approach introduces metadata into each SRAM block that contains the\n// number of valid entries in that block.\n\nclass SRAMElementCounterResp (\n val sramDepth: Int\n) extends Bundle {\n override def cloneType = new SRAMElementCounterResp (\n sramDepth = sramDepth).asInstanceOf[this.type]\n val index = UInt(log2Up(sramDepth).W)\n}\n\nclass SRAMElementCounterInterface (\n val dataWidth: Int,\n val sramDepth: Int,\n val numPorts: Int,\n val elementWidth: Int\n) extends Bundle {\n override def cloneType = new SRAMElementInterface(\n dataWidth = dataWidth,\n sramDepth = sramDepth,\n numPorts = numPorts,\n elementWidth = elementWidth).asInstanceOf[this.type]\n val we = Output(Vec(numPorts, Bool()))\n val din = Output(Vec(numPorts, UInt(elementWidth.W)))\n val addr = Output(Vec(numPorts, UInt(log2Up(sramDepth * dataWidth / elementWidth).W)))\n val dout = Input(Vec(numPorts, UInt(dataWidth.W)))\n // lastBlock sets which is the last block in the SRAM\n val lastBlock = Input(Vec(numPorts, UInt(log2Up(sramDepth).W)))\n // lastCount sets the number of elements in the last block\n val lastCount = Input(Vec(numPorts, UInt((log2Up(dataWidth / elementWidth) + 1).W)))\n val resp = Vec(numPorts, Decoupled(new SRAMElementCounterResp (\n sramDepth = sramDepth)) )\n}\n\n\n// write (i.e., SRAMElement), but also includes a count of the number\n// of valid elements in each block. When a block is determined to be\n// completely valid, this module generates an output update signal\n// indicating which block is now valid.\nclass SRAMElementCounter (\n val dataWidth: Int = 32,\n val sramDepth: Int = 64,\n val elementWidth: Int = 8,\n val numPorts: Int = 1\n) extends Module {\n val io = IO(Flipped(new SRAMElementCounterInterface(\n dataWidth = dataWidth,\n sramDepth = sramDepth,\n numPorts = numPorts,\n elementWidth = elementWidth\n )))\n val sram = Module(new SRAM(\n dataWidth = dataWidth + log2Up(dataWidth / elementWidth) + 1,\n sramDepth = sramDepth,\n numReadPorts = numPorts,\n numWritePorts = numPorts,\n numReadWritePorts = 0\n ))\n\n val addr = Vec(numPorts, new Bundle{\n val addrHi = UInt(log2Up(sramDepth).W)\n val addrLo = UInt(log2Up(dataWidth / elementWidth).W)})\n\n val writePending = Reg(Vec(numPorts, new WritePendingBundle(\n elementWidth = elementWidth,\n dataWidth = dataWidth,\n sramDepth = sramDepth)))\n\n val tmp = Vec(numPorts, Vec(dataWidth/elementWidth, UInt(elementWidth.W)))\n val count = Vec(numPorts, UInt((log2Up(dataWidth / elementWidth) + 1).W))\n val forwarding = Vec(numPorts, Bool())\n\n // Combinational Logic\n for (i <- 0 until numPorts) {\n // Assign the addresses\n addr(i).addrHi := io.addr(i)(\n log2Up(sramDepth * dataWidth / elementWidth) - 1,\n log2Up(dataWidth / elementWidth))\n addr(i).addrLo := io.addr(i)(\n log2Up(dataWidth / elementWidth) - 1, 0)\n // Connections to the sram\n sram.io.weW(i) := writePending(i).valid\n // Explicit data and count assignments\n sram.io.dinW(i) := 0.U\n sram.io.dinW(i)(sramDepth - 1, 0) := tmp(i)\n sram.io.dinW(i)(sramDepth + log2Up(dataWidth/elementWidth) + 1 - 1) :=\n count(i) + 1.U + forwarding(i)\n sram.io.addrR(i) := addr(i).addrHi\n io.dout(i) := sram.io.doutR(i)(dataWidth - 1, 0)\n // Defaults\n io.resp(i).valid := false.B\n io.resp(i).bits.index := 0.U\n forwarding(i) := false.B\n tmp(i) := sram.io.doutR(i)(dataWidth - 1, 0)\n count(i) := sram.io.doutR(i)(\n dataWidth + log2Up(dataWidth/elementWidth) + 1 - 1, dataWidth)\n sram.io.addrW(i) := writePending(i).addrHi\n when (writePending(i).valid) {\n for (j <- 0 until dataWidth / elementWidth) {\n when (j.U === writePending(i).addrLo) {\n tmp(i)(j) := writePending(i).data\n } .elsewhen(addr(i).addrHi === writePending(i).addrHi &&\n io.we(i) &&\n j.U === addr(i).addrLo) {\n tmp(i)(j) := io.din(i)\n forwarding(i) := true.B\n } .otherwise {\n tmp(i)(j) := sram.io.doutR(i)((j+1) * elementWidth - 1, j * elementWidth)\n }\n }\n // Generate a response if we've filled up an entry. An entry is\n // full if it's count is equal to the number of elementsPerBlock\n // or if it's the last count in the last block (this covers the\n // case of a partially filled last block).\n when (count(i) + 1.U + forwarding(i) === (dataWidth / elementWidth).U ||\n (count(i) + 1.U + forwarding(i) === io.lastCount(i) &&\n writePending(i).addrHi === io.lastBlock(i))) {\n io.resp(i).valid := true.B\n io.resp(i).bits.index := writePending(i).addrHi\n sram.io.dinW(i)(sramDepth + log2Up(dataWidth/elementWidth) + 1 - 1) := 0.U\n }\n }\n }\n\n // Sequential Logic\n for (i <- 0 until numPorts) {\n // Assign the pending write data\n writePending(i).valid := false.B\n when ((io.we(i)) && (forwarding(i) === false.B)) {\n writePending(i).valid := true.B\n writePending(i).data := io.din(i)\n writePending(i).addrHi := addr(i).addrHi\n writePending(i).addrLo := addr(i).addrLo\n }\n }\n\n // Assertions\n assert(isPow2(dataWidth / elementWidth),\n \"dataWidth/elementWidth must be a power of 2\")\n}\n"}}},{"rowIdx":1374,"cells":{"text":{"kind":"string","value":"ALTER TABLE installation_statistics \n ADD COLUMN users_count INTEGER NOT NULL DEFAULT 0,\n ADD COLUMN codebases_count INTEGER NOT NULL DEFAULT 0;\n"}}},{"rowIdx":1375,"cells":{"text":{"kind":"string","value":"# Olá,Mundo!\n Primeiro repositorio de Git e GitHub\n\nrepositótio criado durante uma aula \n\nEstá linha eu adicionei diretamente no site.\n"}}},{"rowIdx":1376,"cells":{"text":{"kind":"string","value":"\nusing HKTool.Reflection.Runtime;\n\nnamespace HKTool.Reflection;\n\nstatic class FastReflection\n{\n public static Dictionary fsetter = new();\n public static Dictionary fgetter = new();\n public static Dictionary> frefgetter = new();\n public static Dictionary mcaller = new();\n public static RD_GetField GetGetter(FieldInfo field)\n {\n if (field is null) throw new ArgumentNullException(nameof(field));\n if (!fgetter.TryGetValue(field, out var getter))\n {\n DynamicMethod dm = new DynamicMethod(\"\", MethodAttributes.Static | MethodAttributes.Public,\n CallingConventions.Standard, typeof(object), new Type[]{\n typeof(object)\n }, (Type)field.DeclaringType, true);\n var il = dm.GetILGenerator();\n\n if (!field.IsStatic)\n {\n il.Emit(OpCodes.Ldarg_0);\n if (field.DeclaringType.IsValueType)\n {\n il.Emit(OpCodes.Unbox_Any, field.DeclaringType);\n }\n il.Emit(OpCodes.Ldfld, field);\n }\n else\n {\n il.Emit(OpCodes.Ldsfld, field);\n }\n if (field.FieldType.IsValueType)\n {\n il.Emit(OpCodes.Box, field.FieldType);\n }\n il.Emit(OpCodes.Ret);\n getter = (RD_GetField)dm.CreateDelegate(typeof(RD_GetField));\n fgetter[field] = getter;\n }\n return getter;\n }\n public static RD_SetField GetSetter(FieldInfo field)\n {\n if (field is null) throw new ArgumentNullException(nameof(field));\n if (!fsetter.TryGetValue(field, out var setter))\n {\n DynamicMethod dm = new DynamicMethod(\"\", MethodAttributes.Static | MethodAttributes.Public,\n CallingConventions.Standard, typeof(void), new Type[]{\n typeof(object),\n typeof(object)\n }, (Type)field.DeclaringType, true);\n var il = dm.GetILGenerator();\n\n if (field.IsStatic)\n {\n il.Emit(OpCodes.Ldarg_1);\n if (field.FieldType.IsValueType) il.Emit(OpCodes.Unbox_Any, field.FieldType);\n il.Emit(OpCodes.Stsfld, field);\n }\n else\n {\n il.Emit(OpCodes.Ldarg_0);\n if (field.DeclaringType.IsValueType)\n {\n il.Emit(OpCodes.Unbox_Any, field.DeclaringType);\n }\n il.Emit(OpCodes.Ldarg_1);\n if (field.FieldType.IsValueType) il.Emit(OpCodes.Unbox_Any, field.FieldType);\n il.Emit(OpCodes.Stfld, field);\n }\n il.Emit(OpCodes.Ret);\n setter = (RD_SetField)dm.CreateDelegate(typeof(RD_SetField));\n fsetter[field] = setter;\n }\n return setter;\n }\n internal static object CallMethod(object? @this, MethodInfo method, params object?[]? args)\n {\n if (method is null) throw new ArgumentNullException(nameof(method));\n if (!mcaller.TryGetValue(method, out var caller))\n {\n caller = method.CreateFastDelegate(true);\n mcaller[method] = caller;\n }\n return caller(@this, args ?? new object?[] { null });\n }\n internal static object GetField(object? @this, FieldInfo field)\n {\n if (field is null) throw new ArgumentNullException(nameof(field));\n try\n {\n return GetGetter(field)(@this);\n }\n catch (Exception e)\n {\n HKToolMod.logger.LogError(e);\n return field.GetValue(@this);\n }\n }\n internal static IntPtr GetFieldRef(object? @this, FieldInfo field)\n {\n if (field is null) throw new ArgumentNullException(nameof(field));\n if (frefgetter.TryGetValue(field, out var getter)) return getter.Invoke(@this!);\n DynamicMethod dm = new(\"\", MethodAttributes.Static | MethodAttributes.Public,\n CallingConventions.Standard, typeof(IntPtr), new Type[]{\n typeof(object)\n }, (Type)field.DeclaringType, true);\n var il = dm.GetILGenerator();\n\n \n\n if (!field.IsStatic)\n {\n il.Emit(OpCodes.Ldarg_0);\n if (field.DeclaringType.IsValueType)\n {\n il.Emit(OpCodes.Unbox_Any, field.DeclaringType);\n }\n il.Emit(OpCodes.Ldflda, field);\n }\n else\n {\n il.Emit(OpCodes.Ldsflda, field);\n }\n //il.Emit(OpCodes.Box, field.FieldType.MakeByRefType());\n il.Emit(OpCodes.Ret);\n getter = (Func)dm.CreateDelegate(typeof(Func));\n frefgetter[field] = getter;\n return getter.Invoke(@this!);\n }\n\n internal static void SetField(object? @this, FieldInfo field, object? val)\n {\n if (field is null) throw new ArgumentNullException(nameof(field));\n try\n {\n GetSetter(field)(@this, val);\n }\n catch (Exception e)\n {\n HKToolMod.logger.LogError(e);\n field.SetValue(@this, val);\n }\n }\n}\n\n"}}},{"rowIdx":1377,"cells":{"text":{"kind":"string","value":"import { connect } from 'react-redux'\nimport * as Redux from 'redux'\nimport { createStructuredSelector } from 'reselect'\n\nimport toJS from '../../HoC/toJS'\nimport { selectSideBarActive, selectSideBarDirection } from '../../selectors/sideBar';\nimport SideBar from '../../components/SideBar';\nimport { toggleSideBar } from '../../actions/sideBar';\nimport { push } from 'react-router-redux';\nimport { selectUserSettings } from '../../selectors/user';\nimport { setUser } from '../../actions/user';\n\nconst mapStateToProps = createStructuredSelector({\n\tactive: selectSideBarActive(),\n\tdirection: selectSideBarDirection(),\n\tuser: selectUserSettings()\n})\n\nconst mapDispatchToProps = ( dispatch: any ) => ({\n\ttoggleSideBar: (direction:string) => dispatch( toggleSideBar.success( {direction} ) ),\n\tsetUser: (user:any) => dispatch( setUser.success( {user} )),\n\tpush: ( url: string ) => dispatch( push( url ) ),\n}) as any\n\n\nexport default Redux.compose(\n\tconnect(mapStateToProps,mapDispatchToProps),\n\ttoJS\n) (SideBar) as any\n"}}},{"rowIdx":1378,"cells":{"text":{"kind":"string","value":"# lwt-simple-multi-client-server\n\nLwt の公式にあるサーバー実装\n\n```\ndune exec ./main.exe\n```\n"}}},{"rowIdx":1379,"cells":{"text":{"kind":"string","value":"import React, { useState, useEffect } from 'react';\nimport { sha256 } from 'js-sha256';\n\nimport { Box, Text } from 'rebass';\nimport { ThemeProvider } from 'emotion-theming';\n\nimport Login from 'components/auth/login';\nimport { LoginProps } from 'components/auth/auth';\nimport Dashboard from './dashboard';\nimport { theme, GlobalStyles } from 'styles';\nimport Modal from 'components/modal';\nimport ChangePassword from './change-password';\n\ntype Props = {\n db: firebase.firestore.Firestore;\n};\n\nconst Admin: React.FC = ({ db }) => {\n // set defult to true -> development only\n const [isAuthenticated, setIsAuthenticated] = useState(false);\n const [adminEmail, setAdminEmail] = useState('');\n\n const [showModal, setShowModal] = useState(false);\n const [changePassId, setChangePassId] = useState('');\n\n const [isUnauthorized, setIsUnauthorized] = useState(false);\n\n const adminUserDbRef = db.collection('admin-user');\n\n const debug = false;\n\n useEffect(() => {\n // skipping login on debug\n if (debug) {\n setIsAuthenticated(true);\n setAdminEmail('asketheral@gmail.com');\n }\n }, []);\n\n // password encrypted with sha256!!\n const login = async ({ email, password }: LoginProps) => {\n // authenticate user first\n const adminUser = await adminUserDbRef\n .where('email', '==', email)\n .where('password', '==', sha256(password))\n .get();\n\n const adminUserExists = (await adminUser.size) > 0;\n\n if (await adminUserExists) {\n setIsAuthenticated(true);\n setAdminEmail(email);\n\n if (password === '123456') {\n setShowModal(true);\n setChangePassId(adminUser.docs[0].id);\n }\n } else {\n setIsUnauthorized(true);\n }\n };\n\n const logout = () => {\n setIsAuthenticated(false);\n };\n\n return (\n \n \n {showModal && (\n \n {\n setShowModal(false);\n }}\n />\n \n )}\n {isAuthenticated ? (\n \n ) : (\n \n \n \n {isUnauthorized && (\n \n Admin user unauthorized\n \n )}\n \n \n )}\n \n );\n};\n\nexport { Admin };\n"}}},{"rowIdx":1380,"cells":{"text":{"kind":"string","value":"/*\n * Copyright 2021 EPAM Systems\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage deployment_test\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\todahuflowv1alpha1 \"github.com/odahu/odahu-flow/packages/operator/api/v1alpha1\"\n\t\"github.com/odahu/odahu-flow/packages/operator/pkg/apiclient/deployment\"\n\tapis \"github.com/odahu/odahu-flow/packages/operator/pkg/apis/deployment\"\n\t\"github.com/odahu/odahu-flow/packages/operator/pkg/config\"\n\t\"github.com/stretchr/testify/suite\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"odahu-commons/predictors\"\n\t\"testing\"\n)\n\nvar (\n\tmd = apis.ModelDeployment{\n\t\tID: \"test-md\",\n\t\tSpec: odahuflowv1alpha1.ModelDeploymentSpec{\n\t\t\tImage: \"image-name:tag\",\n\t\t\tPredictor: predictors.OdahuMLServer.ID,\n\t\t},\n\t}\n)\n\ntype mdSuite struct {\n\tsuite.Suite\n\ttestServer *httptest.Server\n\tclient deployment.Client\n}\n\nfunc (s *mdSuite) SetupSuite() {\n\ts.testServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tswitch r.URL.Path {\n\t\tcase \"/api/v1/model/deployment/test-md\":\n\t\t\tif r.Method != http.MethodGet {\n\t\t\t\tnotFound(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\tmdBytes, err := json.Marshal(md)\n\t\t\tif err != nil {\n\t\t\t\t// Must not be occurred\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\t_, err = w.Write(mdBytes)\n\t\t\tif err != nil {\n\t\t\t\t// Must not be occurred\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t// Mock endpoint that returns some HTML response (e.g. simulate Nginx error)\n\t\tcase \"/api/v1/model/deployment/get-html-response\":\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t_, err := w.Write([]byte(\"some error page\"))\n\t\t\tif err != nil {\n\t\t\t\t// Must not be occurred\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t// Mock endpoint that does not response\n\t\tcase \"/api/v1/model/deployment/no-response\":\n\t\t\tpanic(http.ErrAbortHandler)\n\t\tdefault:\n\t\t\tnotFound(w, r)\n\t\t}\n\t}))\n\n\ts.client = deployment.NewClient(config.AuthConfig{APIURL: s.testServer.URL})\n}\n\nfunc (s *mdSuite) TearDownSuite() {\n\ts.testServer.Close()\n}\n\nfunc TestMdSuite(t *testing.T) {\n\tsuite.Run(t, new(mdSuite))\n}\n\nfunc notFound(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusNotFound)\n\t_, err := fmt.Fprintf(w, \"%s url not found\", r.URL.Path)\n\tif err != nil {\n\t\t// Must not be occurred\n\t\tpanic(err)\n\t}\n}\n\nfunc (s *mdSuite) TestGetDeployment() {\n\tmdFromClient, err := s.client.GetModelDeployment(md.ID)\n\n\ts.Assertions.NoError(err)\n\ts.Assertions.Equal(md, *mdFromClient)\n}\n\nfunc (s *mdSuite) TestGetDeployment_NotFound() {\n\tmdFromClient, err := s.client.GetModelDeployment(\"nonexistent-deployment\")\n\n\ts.Assertions.Nil(mdFromClient)\n\ts.Assertions.Error(err)\n\ts.Assertions.Contains(err.Error(), \"not found\")\n}\n\nfunc (s *mdSuite) TestGetDeployment_CannotUnmarshal() {\n\tmdFromClient, err := s.client.GetModelDeployment(\"get-html-response\")\n\n\ts.Assertions.Nil(mdFromClient)\n\ts.Assertions.Error(err)\n\ts.Assertions.Contains(err.Error(), \"invalid character\")\n}\n\nfunc (s *mdSuite) TestGetDeployment_NoResponse() {\n\tmdFromClient, err := s.client.GetModelDeployment(\"no-response\")\n\n\ts.Assertions.Nil(mdFromClient)\n\ts.Assertions.Error(err)\n\ts.Assertions.Contains(err.Error(), \"EOF\")\n}\n"}}},{"rowIdx":1381,"cells":{"text":{"kind":"string","value":"#include \n#include \n#include \"Time.h\"\n\nunsigned int Time::max_year = 3000;\nunsigned int Time::min_year = 1970;\nstring Time::default_format = \"%Ex %EX\";\n\nTime::Time() {\n setTime(0);\n}\n\nTime::Time(time_t time) {\n setTime(time);\n}\n\nTime::Time(tm& time) {\n setTime(time);\n}\n\nTime::Time\n(unsigned int year, unsigned int mon, unsigned int mday,\nunsigned int hour, unsigned int min, unsigned int sec)\n{\n setTime(year, mon, mday, hour, min, sec);\n}\n\nvoid Time::setTime(time_t time) {\n if (isValid(time)) {\n m_time = time;\n } else {\n throw std::invalid_argument(\"time invalid!\");\n }\n}\n\nvoid Time::setTime(tm& time) {\n if (isValid(time)) {\n m_time = mktime(&time);\n } else {\n throw std::invalid_argument(\"time invalid!\");\n }\n}\n\nvoid Time::setTime(unsigned int year, unsigned int mon, unsigned int mday,\n unsigned int hour, unsigned int min, unsigned int sec) {\n if (isValid(year, mon, mday, hour, min, sec)) {\n tm time = {0};\n time.tm_year = year - 1900;\n time.tm_mon = mon - 1;\n time.tm_mday = mday;\n time.tm_hour = hour;\n time.tm_min = min;\n time.tm_sec = sec;\n m_time = mktime(&time);\n } else {\n throw std::invalid_argument(\"time invalid!\");\n }\n}\n\nstring Time::getTimeString(const string &format) const {\n char temp[100] = {0};\n strftime(temp, 100, format.c_str(), localtime(&m_time));\n return string(temp);\n}\n\nTime Time::now() {\n time_t time_stamp;\n time(&time_stamp);\n\n return Time(time_stamp);\n}\n\nbool Time::isValid(tm& time) {\n return isValid(time.tm_year + 1900, time.tm_mon + 1, time.tm_mday\n ,time.tm_hour, time.tm_min, time.tm_sec);\n}\n\nbool Time::isValid\n(unsigned int year, unsigned int mon, unsigned int mday,\nunsigned int hour, unsigned int min, unsigned int sec)\n{\n if (year < min_year || year > max_year) {return false;}\n if (mon < 1 || mon > 12) {return false;}\n\n unsigned int day_of_month[] = {31,28,31,30,31,30,31,31,30,31,30,31};\n if (isLeapYear(year)) {++day_of_month[2-1];}//leap year\n\n if (mday < 1 || mday > day_of_month[mon - 1]) { return false;}\n\n if(hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60) {return false;}\n\n return true;\n}\n\nostream& operator<<(ostream& out, const Time& src) {\n out << asctime(localtime(&src.m_time));\n return out;\n}\n\nistream& operator>>(istream& in, Time& dst) {\n time_t time;\n in >> time;\n dst.setTime(time);\n return in;\n}\n"}}},{"rowIdx":1382,"cells":{"text":{"kind":"string","value":"var searchData=\n[\n ['widgets',['Widgets',['../chapter18-widget.html',1,'overview']]],\n ['world',['World',['../chapter7-world.html',1,'overview']]],\n ['w',['w',['../structchai3d_1_1c_quaternion.html#adbf105b4dd0da86c8fca8ab14a66fee1',1,'chai3d::cQuaternion']]],\n ['widgets',['Widgets',['../group__widgets.html',1,'']]],\n ['world',['World',['../group__world.html',1,'']]]\n];\n"}}},{"rowIdx":1383,"cells":{"text":{"kind":"string","value":"#ifndef MEL_BALLANDBEAM_HPP\n#define MEL_BALLANDBEAM_HPP\n\n#include \n#include \n#include \n#include \n\nclass BallAndBeam {\npublic:\n\n /// Steps the ball and beam simulation\n void step_simulation(mel::Time time, double position_ref, double velocity_ref);\n\n /// Resets the ball and beam inegrators\n void reset();\n\npublic:\n\n double K_player = 30; ///< stiffness between user and beam [N/m]\n double B_player = 1; ///< damping between user and beam [N-s/m]\n double g = 9.81; ///< accerlation due to gravity [m/s^2]\n double I = 0.025; ///< beam moment of inertia [kg*m^2]\n double m = 0.25; ///< ball mass [kg]\n double R = 0.03; ///< ball radius [m]\n double L = 0.8; ///< beam length [m]\n\n double tau; ///< torque acting on beam [Nm]\n double r, rd, rdd; ///< ball state [m, m/s m/s^2]\n double q, qd, qdd; ///< beam state [rad, rad/s, rad/s^2]\n\nprivate:\n\n mel::Integrator rdd2rd; ///< integrates r'' to r'\n mel::Integrator rd2r; ///< integrates r' to r\n mel::Integrator qdd2qd; ///< integrates q'' to r'\n mel::Integrator qd2q; ///< integrates q' to q\n\n};\n\n\n#endif // MEL_BALLANDBEAM_HPP\n"}}},{"rowIdx":1384,"cells":{"text":{"kind":"string","value":"module DataFactory\n def self.configuration\n @configuration ||= Configuration.new\n end\n\n def self.configure\n yield(configuration)\n end\n\n class Configuration\n attr_reader :channels\n attr_accessor :leagues, :url, :password\n\n def initialize\n @channels = %w(fixture calendario posiciones goleadores ficha plantelxcampeonato)\n @url = 'http://feed.datafactory.la'\n @password = '60l4Zz05'\n end\n end\nend\n"}}},{"rowIdx":1385,"cells":{"text":{"kind":"string","value":"// Copyright 2016 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 or the MIT license\n// , at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n\n// This test case tests the incremental compilation hash (ICH) implementation\n// for let expressions.\n\n// The general pattern followed here is: Change one thing between rev1 and rev2\n// and make sure that the hash has changed, then change nothing between rev2 and\n// rev3 and make sure that the hash has not changed.\n\n// must-compile-successfully\n// revisions: cfail1 cfail2 cfail3\n// compile-flags: -Z query-dep-graph\n\n\n#![allow(warnings)]\n#![feature(rustc_attrs)]\n#![crate_type=\"rlib\"]\n\n// Change Name -----------------------------------------------------------------\n#[cfg(cfail1)]\npub fn change_name() {\n let _x = 2u64;\n}\n\n#[cfg(not(cfail1))]\n#[rustc_dirty(label=\"Hir\", cfg=\"cfail2\")]\n#[rustc_clean(label=\"Hir\", cfg=\"cfail3\")]\n#[rustc_metadata_dirty(cfg=\"cfail2\")]\n#[rustc_metadata_clean(cfg=\"cfail3\")]\npub fn change_name() {\n let _y = 2u64;\n}\n\n\n\n// Add Type --------------------------------------------------------------------\n#[cfg(cfail1)]\npub fn add_type() {\n let _x = 2u32;\n}\n\n#[cfg(not(cfail1))]\n#[rustc_dirty(label=\"Hir\", cfg=\"cfail2\")]\n#[rustc_clean(label=\"Hir\", cfg=\"cfail3\")]\n#[rustc_metadata_dirty(cfg=\"cfail2\")]\n#[rustc_metadata_clean(cfg=\"cfail3\")]\npub fn add_type() {\n let _x: u32 = 2u32;\n}\n\n\n\n// Change Type -----------------------------------------------------------------\n#[cfg(cfail1)]\npub fn change_type() {\n let _x: u64 = 2;\n}\n\n#[cfg(not(cfail1))]\n#[rustc_dirty(label=\"Hir\", cfg=\"cfail2\")]\n#[rustc_clean(label=\"Hir\", cfg=\"cfail3\")]\n#[rustc_metadata_dirty(cfg=\"cfail2\")]\n#[rustc_metadata_clean(cfg=\"cfail3\")]\npub fn change_type() {\n let _x: u8 = 2;\n}\n\n\n\n// Change Mutability of Reference Type -----------------------------------------\n#[cfg(cfail1)]\npub fn change_mutability_of_reference_type() {\n let _x: &u64;\n}\n\n#[cfg(not(cfail1))]\n#[rustc_dirty(label=\"Hir\", cfg=\"cfail2\")]\n#[rustc_clean(label=\"Hir\", cfg=\"cfail3\")]\n#[rustc_metadata_dirty(cfg=\"cfail2\")]\n#[rustc_metadata_clean(cfg=\"cfail3\")]\npub fn change_mutability_of_reference_type() {\n let _x: &mut u64;\n}\n\n\n\n// Change Mutability of Slot ---------------------------------------------------\n#[cfg(cfail1)]\npub fn change_mutability_of_slot() {\n let mut _x: u64 = 0;\n}\n\n#[cfg(not(cfail1))]\n#[rustc_dirty(label=\"Hir\", cfg=\"cfail2\")]\n#[rustc_clean(label=\"Hir\", cfg=\"cfail3\")]\n#[rustc_metadata_dirty(cfg=\"cfail2\")]\n#[rustc_metadata_clean(cfg=\"cfail3\")]\npub fn change_mutability_of_slot() {\n let _x: u64 = 0;\n}\n\n\n\n// Change Simple Binding to Pattern --------------------------------------------\n#[cfg(cfail1)]\npub fn change_simple_binding_to_pattern() {\n let _x = (0u8, 'x');\n}\n\n#[cfg(not(cfail1))]\n#[rustc_dirty(label=\"Hir\", cfg=\"cfail2\")]\n#[rustc_clean(label=\"Hir\", cfg=\"cfail3\")]\n#[rustc_metadata_dirty(cfg=\"cfail2\")]\n#[rustc_metadata_clean(cfg=\"cfail3\")]\npub fn change_simple_binding_to_pattern() {\n let (_a, _b) = (0u8, 'x');\n}\n\n\n\n// Change Name in Pattern ------------------------------------------------------\n#[cfg(cfail1)]\npub fn change_name_in_pattern() {\n let (_a, _b) = (1u8, 'y');\n}\n\n#[cfg(not(cfail1))]\n#[rustc_dirty(label=\"Hir\", cfg=\"cfail2\")]\n#[rustc_clean(label=\"Hir\", cfg=\"cfail3\")]\n#[rustc_metadata_dirty(cfg=\"cfail2\")]\n#[rustc_metadata_clean(cfg=\"cfail3\")]\npub fn change_name_in_pattern() {\n let (_a, _c) = (1u8, 'y');\n}\n\n\n\n// Add `ref` in Pattern --------------------------------------------------------\n#[cfg(cfail1)]\npub fn add_ref_in_pattern() {\n let (_a, _b) = (1u8, 'y');\n}\n\n#[cfg(not(cfail1))]\n#[rustc_dirty(label=\"Hir\", cfg=\"cfail2\")]\n#[rustc_clean(label=\"Hir\", cfg=\"cfail3\")]\n#[rustc_metadata_dirty(cfg=\"cfail2\")]\n#[rustc_metadata_clean(cfg=\"cfail3\")]\npub fn add_ref_in_pattern() {\n let (ref _a, _b) = (1u8, 'y');\n}\n\n\n\n// Add `&` in Pattern ----------------------------------------------------------\n#[cfg(cfail1)]\npub fn add_amp_in_pattern() {\n let (_a, _b) = (&1u8, 'y');\n}\n\n#[cfg(not(cfail1))]\n#[rustc_dirty(label=\"Hir\", cfg=\"cfail2\")]\n#[rustc_clean(label=\"Hir\", cfg=\"cfail3\")]\n#[rustc_metadata_dirty(cfg=\"cfail2\")]\n#[rustc_metadata_clean(cfg=\"cfail3\")]\npub fn add_amp_in_pattern() {\n let (&_a, _b) = (&1u8, 'y');\n}\n\n\n\n// Change Mutability of Binding in Pattern -------------------------------------\n#[cfg(cfail1)]\npub fn change_mutability_of_binding_in_pattern() {\n let (_a, _b) = (99u8, 'q');\n}\n\n#[cfg(not(cfail1))]\n#[rustc_dirty(label=\"Hir\", cfg=\"cfail2\")]\n#[rustc_clean(label=\"Hir\", cfg=\"cfail3\")]\n#[rustc_metadata_dirty(cfg=\"cfail2\")]\n#[rustc_metadata_clean(cfg=\"cfail3\")]\npub fn change_mutability_of_binding_in_pattern() {\n let (mut _a, _b) = (99u8, 'q');\n}\n\n\n\n// Add Initializer -------------------------------------------------------------\n#[cfg(cfail1)]\npub fn add_initializer() {\n let _x: i16;\n}\n\n#[cfg(not(cfail1))]\n#[rustc_dirty(label=\"Hir\", cfg=\"cfail2\")]\n#[rustc_clean(label=\"Hir\", cfg=\"cfail3\")]\n#[rustc_metadata_dirty(cfg=\"cfail2\")]\n#[rustc_metadata_clean(cfg=\"cfail3\")]\npub fn add_initializer() {\n let _x: i16 = 3i16;\n}\n\n\n\n// Change Initializer ----------------------------------------------------------\n#[cfg(cfail1)]\npub fn change_initializer() {\n let _x = 4u16;\n}\n\n#[cfg(not(cfail1))]\n#[rustc_dirty(label=\"Hir\", cfg=\"cfail2\")]\n#[rustc_clean(label=\"Hir\", cfg=\"cfail3\")]\n#[rustc_metadata_dirty(cfg=\"cfail2\")]\n#[rustc_metadata_clean(cfg=\"cfail3\")]\npub fn change_initializer() {\n let _x = 5u16;\n}\n"}}},{"rowIdx":1386,"cells":{"text":{"kind":"string","value":"我国JF22超高速风洞预计2022年建成 \n孙红雷说扫黑风暴这戏接对了 \n男子与亲外甥谈恋爱被骗100余万 \n女子公厕内拍下男子跪地偷窥全程 \n汤唯状态 \n迪丽热巴发长文告别乔晶晶 \n贵州发现6亿岁海绵宝宝 \n美国首例新冠死亡病例为2020年1月初 \n央视网评 饭圈文化该驱邪扶正了 \n国乒不组队参加今年亚锦赛 \n刘宪华把香菜让给王一博 \n塔利班称美延迟撤军将面临严重后果 \n高铁座位边的踏板别踩 \n孙兴被软禁 \n乔任梁父母回应恶评 \n美国数千只沙币被冲上海滩死亡 \n高校师生返校前提供48小时核酸证明 \n迪丽热巴好适合演女明星 \n汪东城晒吴尊AI女装换脸视频 \n大江暴揍孙兴 \n扫黑风暴 \n胖哥俩在执法人员上门检查前丢弃食材 \n张艺兴12年前用电脑和韩庚合影 \n冯提莫素颜状态 \n丁程鑫发文谈加入快乐家族 \n跑酷不去重庆的原因 \n翟潇闻演的失恋好真实 \n过期食物对人体伤害有多大 \n再不开学我都把证考完了 \n阳光玫瑰从每斤300元跌至10元 \n郑州一男子防车淹用砖支车被压身亡 \n塔利班宣布特赦阿富汗总统加尼 \n刘雨昕道歉 \n杨洋发文告别于途 \n买来补身的甲鱼比你还虚 \n买个菜感觉像上了天 \n杨舒予奥运首秀跑错入场仪式 \n严浩翔由你榜最年轻夺冠歌手 \n20年陈皮一斤卖到3000元 \n杨超越送孙俪披荆斩棘四件套 \n原来浪漫永不过期 \n外交部回应美国给立陶宛撑腰 \n原来光能被画出来 \n嫌疑人被抓时身着跳出三界外T恤 \n美国7个月大双胞胎被洪水冲走 \n你是我的荣耀观后感 \n欧阳娜娜水手服造型 \n快递小哥因想休息故意酒驾求被抓 \n今天的这些0来之不易 \n赵继伟王君瑞领证 \n阿富汗被辞退前部长在德国送外卖 \n借条的正确写法 \n"}}},{"rowIdx":1387,"cells":{"text":{"kind":"string","value":"#include \n#include \n#include \n#include \n#include \n#include \n\nusing ::std::cerr;\nusing ::std::cout;\nusing ::std::endl;\nusing ::std::stringstream;\n\n#define EXHAUSTIVE_N 4\n\nnamespace PCP_Project {\n\nTEST(ConstraintsLib,R1P_AND_Gadget) {\n initPublicParamsFromEdwardsParam();\n auto pb = Protoboard::create(R1P);\n\n VariableArray x(3, \"x\");\n Variable y(\"y\");\n auto andGadget = AND_Gadget::create(pb, x, y);\n andGadget->generateConstraints();\n\n pb->val(x[0]) = 0;\n pb->val(x[1]) = 1;\n pb->val(x[2]) = 1;\n andGadget->generateWitness();\n EXPECT_TRUE(pb->val(y) == 0);\n EXPECT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n pb->val(y) = 1;\n EXPECT_FALSE(pb->isSatisfied());\n\n pb->val(x[0]) = 1;\n andGadget->generateWitness();\n EXPECT_TRUE(pb->val(y) == 1);\n EXPECT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n\n pb->val(y) = 0;\n EXPECT_FALSE(pb->isSatisfied());\n}\n\nTEST(ConstraintsLib,LD2_AND_Gadget) {\n auto pb = Protoboard::create(LD2);\n\n VariableArray x(3,\"x\");\n Variable y(\"y\");\n auto andGadget = AND_Gadget::create(pb, x, y);\n andGadget->generateConstraints();\n\n pb->val(x[0]) = 0;\n pb->val(x[1]) = 1;\n pb->val(x[2]) = 1;\n andGadget->generateWitness();\n EXPECT_TRUE(pb->val(y) == 0);\n EXPECT_TRUE(pb->isSatisfied());\n pb->val(y) = 1;\n EXPECT_FALSE(pb->isSatisfied());\n\n pb->val(x[0]) = 1;\n andGadget->generateWitness();\n EXPECT_TRUE(pb->val(y) == 1);\n EXPECT_TRUE(pb->isSatisfied());\n\n pb->val(y) = 0;\n EXPECT_FALSE(pb->isSatisfied());\n}\n\n\nvoid andGadgetExhaustiveTest(ProtoboardPtr pb, size_t n); // Forward declaration\n\nTEST(ConstraintsLib,R1P_ANDGadget_Exhaustive) {\n initPublicParamsFromEdwardsParam();\n for(int n = 1; n <= EXHAUSTIVE_N; ++n) {\n SCOPED_TRACE(FMT(\"n = %u \\n\", n));\n auto pb = Protoboard::create(R1P);\n andGadgetExhaustiveTest(pb, n);\n }\n}\n\nTEST(ConstraintsLib,LD2_ANDGadget_Exhaustive) {\n for(int n = 2; n <= EXHAUSTIVE_N; ++n) {\n SCOPED_TRACE(FMT(\"n = %u \\n\", n));\n auto pb = Protoboard::create(LD2);\n andGadgetExhaustiveTest(pb, n);\n }\n}\n\nTEST(ConstraintsLib,BinaryAND_Gadget) {\n auto pb = Protoboard::create(LD2);\n Variable input1(\"input1\");\n Variable input2(\"input2\");\n Variable result(\"result\");\n auto andGadget = AND_Gadget::create(pb, input1, input2, result);\n andGadget->generateConstraints();\n pb->val(input1) = pb->val(input2) = 0;\n andGadget->generateWitness();\n ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n ASSERT_EQ(pb->val(result), 0);\n pb->val(result) = 1;\n ASSERT_FALSE(pb->isSatisfied());\n pb->val(result) = 0;\n pb->val(input1) = 1;\n ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n pb->val(input2) = 1;\n ASSERT_FALSE(pb->isSatisfied());\n andGadget->generateWitness();\n ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n ASSERT_EQ(pb->val(result), 1);\n}\n\nvoid orGadgetExhaustiveTest(ProtoboardPtr pb, size_t n); // Forward declaration\n\nTEST(ConstraintsLib,R1P_ORGadget_Exhaustive) {\n initPublicParamsFromEdwardsParam();\n for(int n = 1; n <= EXHAUSTIVE_N; ++n) {\n SCOPED_TRACE(FMT(\"n = %u \\n\", n));\n auto pb = Protoboard::create(R1P);\n orGadgetExhaustiveTest(pb, n);\n }\n}\n\nTEST(ConstraintsLib,LD2_ORGadget_Exhaustive) {\n for(int n = 2; n <= EXHAUSTIVE_N; ++n) {\n SCOPED_TRACE(FMT(\"n = %u \\n\", n));\n auto pb = Protoboard::create(LD2);\n orGadgetExhaustiveTest(pb, n);\n }\n}\n\nTEST(ConstraintsLib,BinaryOR_Gadget) {\n auto pb = Protoboard::create(LD2);\n Variable input1(\"input1\");\n Variable input2(\"input2\");\n Variable result(\"result\");\n auto orGadget = OR_Gadget::create(pb, input1, input2, result);\n orGadget->generateConstraints();\n pb->val(input1) = pb->val(input2) = 0;\n orGadget->generateWitness();\n ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n ASSERT_EQ(pb->val(result), 0);\n pb->val(result) = 1;\n ASSERT_FALSE(pb->isSatisfied());\n pb->val(result) = 0;\n pb->val(input1) = 1;\n ASSERT_FALSE(pb->isSatisfied());\n pb->val(result) = 1;\n ASSERT_CONSTRAINTS_SATISFIED(pb);\n pb->val(input2) = 1;\n orGadget->generateWitness();\n ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n ASSERT_EQ(pb->val(result), 1);\n}\n\nTEST(ConstraintsLib,R1P_InnerProductGadget_Exhaustive) {\n initPublicParamsFromEdwardsParam();\n const size_t n = EXHAUSTIVE_N;\n auto pb = Protoboard::create(R1P);\n VariableArray A(n, \"A\");\n VariableArray B(n, \"B\");\n Variable result(\"result\");\n auto g = InnerProduct_Gadget::create(pb, A, B, result);\n g->generateConstraints();\n for (size_t i = 0; i < 1u<val(A[k]) = i & (1u<val(B[k]) = j & (1u<generateWitness();\n EXPECT_EQ(pb->val(result) , FElem(correct));\n EXPECT_TRUE(pb->isSatisfied());\n // negative test\n pb->val(result) = 100*n+19;\n EXPECT_FALSE(pb->isSatisfied());\n }\n }\n}\n\nTEST(ConstraintsLib,LD2_InnerProductGadget_Exhaustive) {\n initPublicParamsFromEdwardsParam();\n const size_t n = EXHAUSTIVE_N > 1 ? EXHAUSTIVE_N -1 : EXHAUSTIVE_N;\n for(int len = 1; len <= n; ++len) {\n auto pb = Protoboard::create(LD2);\n VariableArray a(len, \"a\");\n VariableArray b(len, \"b\");\n Variable result(\"result\");\n auto ipGadget = InnerProduct_Gadget::create(pb, a, b, result);\n ipGadget->generateConstraints();\n // Generate Inputs & Witnesses\n vec_GF2E a_vec;\n a_vec.SetLength(len);\n for(int h = 0; h < len; ++h) { // iterate over a's elements\n for(int j = 0; j < 1u<val(a[h]) = to_GF2E(a_h);\n vec_GF2E b_vec;\n b_vec.SetLength(len);\n for(int i = 0; i < len; ++i) {\n pb->val(b[i]) = 0;\n }\n for(int i = 0; i < len; ++i) { // iterate over b's elements\n for(int k = 0; k < 1u<val(b[i]) = to_GF2E(b_i);\n ipGadget->generateWitness();\n GF2E resultGF2E;\n InnerProduct(resultGF2E, a_vec, b_vec);\n ::std::stringstream s;\n s << endl << \"i = \" << i << endl\n << \"< \" << a_vec << \" > * < \" << b_vec << \" > = \" << resultGF2E << endl\n << pb->annotation();\n SCOPED_TRACE(s.str());\n EXPECT_EQ(pb->val(result), FElem(resultGF2E));\n EXPECT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n // Negative test\n pb->val(result) = resultGF2E + to_GF2E(1);\n EXPECT_FALSE(pb->isSatisfied());\n }\n }\n }\n }\n }\n}\n\nTEST(ConstraintsLib,R1P_LooseMUX_Gadget_Exhaustive) {\ninitPublicParamsFromEdwardsParam();\nconst size_t n = EXHAUSTIVE_N;\n auto pb = Protoboard::create(R1P);\n VariableArray arr(1<generateConstraints();\n for (size_t i = 0; i < 1u<val(arr[i]) = (19*i) % (1u<val(index) = idx;\n g->generateWitness();\n if (0 <= idx && idx <= (1<val(result) , (19*idx) % (1u<val(success_flag) , 1);\n EXPECT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n pb->val(result) -= 1;\n EXPECT_FALSE(pb->isSatisfied());\n }\n else {\n EXPECT_EQ(pb->val(success_flag) , 0);\n EXPECT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n pb->val(success_flag) = 1;\n EXPECT_FALSE(pb->isSatisfied());\n }\n }\n}\n\n// Forward declaration\nvoid packing_Gadget_R1P_ExhaustiveTest(ProtoboardPtr unpackingPB, ProtoboardPtr packingPB,\n const int n, VariableArray packed, VariableArray unpacked,\n GadgetPtr packingGadget, GadgetPtr unpackingGadget);\n\nTEST(ConstraintsLib,R1P_Packing_Gadgets) {\n initPublicParamsFromEdwardsParam();\n auto unpackingPB = Protoboard::create(R1P);\n auto packingPB = Protoboard::create(R1P);\n const int n = EXHAUSTIVE_N;\n { // test CompressionPacking_Gadget\n SCOPED_TRACE(\"testing CompressionPacking_Gadget\");\n VariableArray packed(1, \"packed\");\n VariableArray unpacked(n, \"unpacked\");\n auto packingGadget = CompressionPacking_Gadget::create(packingPB, unpacked, packed,\n PackingMode::PACK);\n auto unpackingGadget = CompressionPacking_Gadget::create(unpackingPB, unpacked, packed,\n PackingMode::UNPACK);\n packing_Gadget_R1P_ExhaustiveTest(unpackingPB, packingPB, n, packed, unpacked, packingGadget,\n unpackingGadget);\n }\n { // test IntegerPacking_Gadget\n SCOPED_TRACE(\"testing IntegerPacking_Gadget\");\n VariableArray packed(1, \"packed\");\n VariableArray unpacked(n, \"unpacked\");\n auto packingGadget = IntegerPacking_Gadget::create(packingPB, unpacked, packed,\n PackingMode::PACK);\n auto unpackingGadget = IntegerPacking_Gadget::create(unpackingPB, unpacked, packed,\n PackingMode::UNPACK);\n packing_Gadget_R1P_ExhaustiveTest(unpackingPB, packingPB, n, packed, unpacked, packingGadget,\n unpackingGadget);\n }\n}\n\nTEST(ConstraintsLib,LD2_CompressionPacking_Gadget) {\n auto unpackingPB = Protoboard::create(LD2);\n auto packingPB = Protoboard::create(LD2);\n const int n = EXHAUSTIVE_N;\n VariableArray packed(1, \"packed\");\n VariableArray unpacked(n, \"unpacked\");\n auto packingGadget = CompressionPacking_Gadget::create(packingPB, unpacked, packed, \n PackingMode::PACK);\n auto unpackingGadget = CompressionPacking_Gadget::create(unpackingPB, unpacked, packed,\n PackingMode::UNPACK);\n packingGadget->generateConstraints();\n unpackingGadget->generateConstraints();\n for(int i = 0; i < 1u< bits(n);\n size_t packedGF2X = 0;\n for(int j = 0; j < n; ++j) {\n bits[j] = i & 1u<val(unpacked[j]) = bits[j]; // set unpacked bits in the packing protoboard\n }\n // set the packed value in the unpacking protoboard\n unpackingPB->val(packed[0]) = Algebra::mapIntegerToFieldElement(0,Algebra::ExtensionDegree,packedGF2X);\n unpackingGadget->generateWitness();\n packingGadget->generateWitness();\n stringstream s;\n s << endl << \"i = \" << i << \", Packed Value: \" << Algebra::mapIntegerToFieldElement(0,Algebra::ExtensionDegree,packedGF2X) << endl;\n SCOPED_TRACE(s.str());\n ASSERT_TRUE(unpackingPB->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n ASSERT_TRUE(packingPB->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n // check packed value is correct\n ASSERT_EQ(packingPB->val(packed[0]), Algebra::mapIntegerToFieldElement(0,Algebra::ExtensionDegree,packedGF2X)); \n for(int j = 0; j < n; ++j) {\n // Tests for unpacking gadget\n SCOPED_TRACE(FMT(\"\\nValue being packed/unpacked: %u, bits[%u] = %u\" , i, j, bits[j]));\n ASSERT_EQ(unpackingPB->val(unpacked[j]), bits[j] ? 1 : 0); // check bit correctness\n packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = 1-bits[j]; // flip bit\n ASSERT_FALSE(unpackingPB->isSatisfied());\n ASSERT_FALSE(packingPB->isSatisfied());\n packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = bits[j]; // restore bit\n // special case to test booleanity checks. Cause arithmetic constraints to stay\n // satisfied while ruining Booleanity\n if (j > 0 && bits[j]==1 && bits[j-1]==0 ) { \n packingPB->val(unpacked[j-1]) = unpackingPB->val(unpacked[j-1]) = getGF2E_X();\n packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = 0; \n ASSERT_FALSE(unpackingPB->isSatisfied());\n ASSERT_TRUE(packingPB->isSatisfied()); // packing should not enforce Booleanity\n // restore correct state\n packingPB->val(unpacked[j-1]) = unpackingPB->val(unpacked[j-1]) = 0; \n packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = 1;\n }\n }\n }\n }\n\nTEST(ConstraintsLib, LD2_CompressionPacking_Gadget_largeNums) {\n // Test packing/unpacking for the case of more than 1 packed element.\n using ::std::vector;\n \n //initialize the context field\n const int packedSize = 2;\n const int unpackedSize = packedSize * IRR_DEGREE;\n vector packingVal(packedSize);\n for(int i = 0; i < packedSize; ++i) {\n packingVal[i] = i;\n }\n packingVal[0] = 42; // The Answer To Life, the Universe and Everything\n packingVal[1] = 26-9-1984; // My birthday\n auto unpackingPB = Protoboard::create(LD2);\n auto packingPB = Protoboard::create(LD2);\n VariableArray packed(packedSize, \"packed\");\n VariableArray unpacked(unpackedSize, \"unpacked\");\n auto packingGadget = CompressionPacking_Gadget::create(packingPB, unpacked, packed,\n PackingMode::PACK);\n auto unpackingGadget = CompressionPacking_Gadget::create(unpackingPB, unpacked, packed,\n PackingMode::UNPACK);\n packingGadget->generateConstraints();\n unpackingGadget->generateConstraints();\n\n vector bits(unpackedSize);\n vector packedGF2X(packedSize,0);\n for(int j = 0; j < unpackedSize; ++j) {\n bits[j] = packingVal[j / IRR_DEGREE] & 1ul<<(j % IRR_DEGREE) ? 1 : 0;\n packedGF2X[j / IRR_DEGREE] |= bits[j]<<(j % IRR_DEGREE);\n packingPB->val(unpacked[j]) = bits[j]; // set unpacked bits in the packing protoboard\n }\n // set the packed value in the unpacking protoboard\n for(int j = 0; j < packedSize; ++j) {\n unpackingPB->val(packed[j]) = Algebra::mapIntegerToFieldElement(0,Algebra::ExtensionDegree,packedGF2X[j]);\n }\n unpackingGadget->generateWitness();\n packingGadget->generateWitness();\n ASSERT_TRUE(unpackingPB->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n ASSERT_TRUE(packingPB->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n // check packed values are correct\n for(int j = 0; j < packedSize; ++j) {\n ASSERT_EQ(packingPB->val(packed[j]), Algebra::mapIntegerToFieldElement(0,Algebra::ExtensionDegree,packedGF2X[j]); \n }\n for(int j = 0; j < unpackedSize; ++j) {\n // Tests for unpacking gadget\n SCOPED_TRACE(FMT(\"j = %lu\", j));\n ASSERT_EQ(unpackingPB->val(unpacked[j]), bits[j] ? 1 : 0); // check bit correctness\n packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = 1-bits[j]; // flip bit\n ASSERT_FALSE(unpackingPB->isSatisfied());\n ASSERT_FALSE(packingPB->isSatisfied());\n packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = bits[j]; // restore bit\n }\n}\n\n\nvoid equalsConstTest(ProtoboardPtr pb); // Forward declaration\n\nTEST(ConstraintsLib,R1P_EqualsConst_Gadget) {\n initPublicParamsFromEdwardsParam();\n auto pb = Protoboard::create(R1P);\n equalsConstTest(pb);\n}\n\nTEST(ConstraintsLib,LD2_EqualsConst_Gadget) {\n auto pb = Protoboard::create(LD2);\n equalsConstTest(pb);\n}\n\nTEST(ConstraintsLib,ConditionalFlag_Gadget) {\n initPublicParamsFromEdwardsParam();\n auto pb = Protoboard::create(R1P);\n FlagVariable flag;\n Variable condition(\"condition\");\n auto cfGadget = ConditionalFlag_Gadget::create(pb, condition, flag);\n cfGadget->generateConstraints();\n pb->val(condition) = 1;\n cfGadget->generateWitness();\n ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n pb->val(condition) = 42;\n cfGadget->generateWitness();\n ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n ASSERT_EQ(pb->val(flag),1);\n pb->val(condition) = 0;\n ASSERT_FALSE(pb->isSatisfied());\n cfGadget->generateWitness();\n ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n ASSERT_EQ(pb->val(flag),0);\n pb->val(flag) = 1;\n ASSERT_FALSE(pb->isSatisfied());\n}\n\nTEST(ConstraintsLib,LogicImplication_Gadget) {\n auto pb = Protoboard::create(LD2);\n FlagVariable flag;\n Variable condition(\"condition\");\n auto implyGadget = LogicImplication_Gadget::create(pb, condition, flag);\n implyGadget->generateConstraints();\n pb->val(condition) = 1;\n pb->val(flag) = 0;\n ASSERT_FALSE(pb->isSatisfied());\n implyGadget->generateWitness();\n ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n ASSERT_EQ(pb->val(flag), 1);\n pb->val(condition) = 0;\n ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n implyGadget->generateWitness();\n ASSERT_EQ(pb->val(flag), 1);\n pb->val(flag) = 0;\n ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n}\n\nvoid andGadgetExhaustiveTest(ProtoboardPtr pb, size_t n) {\n VariableArray inputs(n, \"inputs\");\n Variable output(\"output\");\n auto andGadget = AND_Gadget::create(pb, inputs, output);\n andGadget->generateConstraints();\n for (size_t curInput = 0; curInput < 1u<val(inputs[maskBit]) = (curInput & (1u<generateWitness();\n {\n SCOPED_TRACE(FMT(\"Positive (completeness) test failed. curInput: %u\", curInput));\n EXPECT_TRUE(pb->isSatisfied());\n }\n {\n SCOPED_TRACE(pb->annotation());\n SCOPED_TRACE(FMT(\"Negative (soundness) test failed. curInput: %u, Constraints \"\n \"are:\", curInput));\n pb->val(output) = (curInput == ((1u<isSatisfied());\n }\n }\n}\n\nvoid orGadgetExhaustiveTest(ProtoboardPtr pb, size_t n) {\n VariableArray inputs(n, \"inputs\");\n Variable output(\"output\");\n auto orGadget = OR_Gadget::create(pb, inputs, output);\n orGadget->generateConstraints();\n for (size_t curInput = 0; curInput < 1u<val(inputs[maskBit]) = (curInput & (1u<generateWitness();\n {\n SCOPED_TRACE(FMT(\"Positive (completeness) test failed. curInput: %u\", curInput));\n ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n }\n {\n SCOPED_TRACE(pb->annotation());\n SCOPED_TRACE(FMT(\"Negative (soundness) test failed. curInput: %u, Constraints \"\n \"are:\", curInput));\n pb->val(output) = (curInput == 0) ? 1 : 0;\n ASSERT_FALSE(pb->isSatisfied());\n }\n }\n}\n\nvoid packing_Gadget_R1P_ExhaustiveTest(ProtoboardPtr unpackingPB, ProtoboardPtr packingPB,\n const int n, VariableArray packed, VariableArray unpacked,\n GadgetPtr packingGadget, GadgetPtr unpackingGadget) {\n packingGadget->generateConstraints();\n unpackingGadget->generateConstraints();\n for(int i = 0; i < 1u< bits(n);\n for(int j = 0; j < n; ++j) {\n bits[j] = i & 1u<val(unpacked[j]) = bits[j]; // set unpacked bits in the packing protoboard\n }\n unpackingPB->val(packed[0]) = i; // set the packed value in the unpacking protoboard\n unpackingGadget->generateWitness();\n packingGadget->generateWitness();\n ASSERT_TRUE(unpackingPB->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));\n ASSERT_TRUE(packingPB->isSatisfied());\n ASSERT_EQ(packingPB->val(packed[0]), i); // check packed value is correct\n for(int j = 0; j < n; ++j) {\n // Tests for unpacking gadget\n SCOPED_TRACE(FMT(\"\\nValue being packed/unpacked: %u, bits[%u] = %u\" , i, j, bits[j]));\n ASSERT_EQ(unpackingPB->val(unpacked[j]), bits[j]); // check bit correctness\n packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = 1-bits[j]; // flip bit\n ASSERT_FALSE(unpackingPB->isSatisfied());\n ASSERT_FALSE(packingPB->isSatisfied());\n packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = bits[j]; // restore bit\n // special case to test booleanity checks. Cause arithmetic constraints to stay\n // satisfied while ruining Booleanity\n if (j > 0 && bits[j]==1 && bits[j-1]==0 ) { \n packingPB->val(unpacked[j-1]) = unpackingPB->val(unpacked[j-1]) = 2;\n packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = 0; \n ASSERT_FALSE(unpackingPB->isSatisfied());\n ASSERT_TRUE(packingPB->isSatisfied()); // packing should not enforce Booleanity\n // restore correct state\n packingPB->val(unpacked[j-1]) = unpackingPB->val(unpacked[j-1]) = 0; \n packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = 1;\n }\n }\n }\n}\n\nvoid equalsConstTest(ProtoboardPtr pb) {\n Variable input(\"input\");\n Variable result(\"result\");\n auto gadget = EqualsConst_Gadget::create(pb, 0, input, result);\n gadget->generateConstraints();\n pb->val(input) = 0;\n gadget->generateWitness();\n // Positive test for input == n\n EXPECT_EQ(pb->val(result), 1);\n EXPECT_TRUE(pb->isSatisfied());\n // Negative test\n pb->val(result) = 0;\n EXPECT_FALSE(pb->isSatisfied());\n // Positive test for input != n\n pb->val(input) = 1;\n gadget->generateWitness();\n EXPECT_EQ(pb->val(result), 0);\n EXPECT_TRUE(pb->isSatisfied());\n // Negative test\n pb->val(input) = 0;\n EXPECT_FALSE(pb->isSatisfied());\n}\n\n\n} // namespace PCP_Project \n"}}},{"rowIdx":1388,"cells":{"text":{"kind":"string","value":"from __future__ import division\nimport autopath\nimport py\n\nimport math\nimport random\nimport sets\n\nexclude_files = [\"__init__.py\", \"autopath.py\", \"conftest.py\"]\n\ndef include_file(path):\n if (\"test\" in str(path) or \"tool\" in str(path) or\n \"documentation\" in str(path) or \n \"_cache\" in str(path)):\n return False\n if path.basename in exclude_files:\n return False\n return True\n\ndef get_mod_from_path(path):\n dirs = path.get(\"dirname\")[0].split(\"/\")\n pypyindex = dirs.index(\"pypy\")\n return \".\".join(dirs[pypyindex:] + path.get(\"purebasename\"))\n\n\ndef find_references(path):\n refs = []\n for line in path.open(\"r\"):\n if line.startswith(\" \"): # ignore local imports to reduce graph size\n continue\n if \"\\\\\" in line: #ignore line continuations\n continue\n line = line.strip()\n line = line.split(\"#\")[0].strip()\n if line.startswith(\"import pypy.\"): # import pypy.bla.whatever\n if \" as \" not in line:\n refs.append((line[7:].strip(), None))\n else: # import pypy.bla.whatever as somethingelse\n assert line.count(\" as \") == 1\n line = line.split(\" as \")\n refs.append((line[0][7:].strip(), line[1].strip()))\n elif line.startswith(\"from \") and \"pypy\" in line: #from pypy.b import a\n line = line[5:]\n if \" as \" not in line:\n line = line.split(\" import \")\n what = line[1].split(\",\")\n for w in what:\n refs.append((line[0].strip() + \".\" + w.strip(), None))\n else: # prom pypy.b import a as c\n if line.count(\" as \") != 1 or \",\" in line:\n print\"can't handle this: \" + line\n continue\n line = line.split(\" as \")\n what = line[0].replace(\" import \", \".\").replace(\" \", \"\")\n refs.append((what, line[1].strip()))\n return refs\n\ndef get_module(ref, imports):\n ref = ref.split(\".\")\n i = len(ref)\n while i:\n possible_mod = \".\".join(ref[:i])\n if possible_mod in imports:\n return possible_mod\n i -= 1\n return None\n\ndef casteljeau(points, t):\n points = points[:]\n while len(points) > 1:\n for i in range(len(points) - 1):\n points[i] = points[i] * (1 - t) + points[i + 1] * t\n del points[-1]\n return points[0]\n\ndef color(t):\n points = [0, 0, 1, 0, 0]\n casteljeau([0, 0, 1, 0, 0], t) / 0.375\n\nclass ModuleGraph(object):\n def __init__(self, path):\n self.imports = {}\n self.clusters = {}\n self.mod_to_cluster = {}\n for f in path.visit(\"*.py\"):\n if include_file(f):\n self.imports[get_mod_from_path(f)] = find_references(f)\n self.remove_object_refs()\n self.remove_double_refs()\n self.incoming = {}\n for mod in self.imports:\n self.incoming[mod] = sets.Set()\n for mod, refs in self.imports.iteritems():\n for ref in refs:\n if ref[0] in self.incoming:\n self.incoming[ref[0]].add(mod)\n self.remove_single_nodes()\n self.topgraph_properties = [\"rankdir=LR\"]\n\n def remove_object_refs(self):\n # reduces cases like import pypy.translator.genc.basetype.CType to\n # import pypy.translator.genc.basetype\n for mod, refs in self.imports.iteritems():\n i = 0\n while i < len(refs):\n if refs[i][0] in self.imports:\n i += 1\n else:\n nref = get_module(refs[i][0], self.imports)\n if nref is None:\n print \"removing\", repr(refs[i])\n del refs[i]\n else:\n refs[i] = (nref, None)\n i += 1\n\n def remove_double_refs(self):\n # remove several references to the same module\n for mod, refs in self.imports.iteritems():\n i = 0\n seen_refs = sets.Set()\n while i < len(refs):\n if refs[i] not in seen_refs:\n seen_refs.add(refs[i])\n i += 1\n else:\n del refs[i]\n\n def remove_single_nodes(self):\n # remove nodes that have no attached edges\n rem = []\n for mod, refs in self.imports.iteritems():\n if len(refs) == 0 and len(self.incoming[mod]) == 0:\n rem.append(mod)\n for m in rem:\n del self.incoming[m]\n del self.imports[m]\n\n def create_clusters(self):\n self.topgraph_properties.append(\"compound=true;\")\n self.clustered = True\n hierarchy = [sets.Set() for i in range(6)]\n for mod in self.imports:\n for i, d in enumerate(mod.split(\".\")):\n hierarchy[i].add(d)\n for i in range(6):\n if len(hierarchy[i]) != 1:\n break\n for mod in self.imports:\n cluster = mod.split(\".\")[i]\n if i == len(mod.split(\".\")) - 1:\n continue\n if cluster not in self.clusters:\n self.clusters[cluster] = sets.Set()\n self.clusters[cluster].add(mod)\n self.mod_to_cluster[mod] = cluster\n\n def remove_tangling_randomly(self):\n # remove edges to nodes that have a lot incoming edges randomly\n tangled = []\n for mod, incoming in self.incoming.iteritems():\n if len(incoming) > 10:\n tangled.append(mod)\n for mod in tangled:\n remove = sets.Set()\n incoming = self.incoming[mod]\n while len(remove) < len(incoming) * 0.80:\n remove.add(random.choice(list(incoming)))\n for rem in remove:\n for i in range(len(self.imports[rem])):\n if self.imports[rem][i][1] == mod:\n break\n del self.imports[rem][i]\n incoming.remove(rem)\n print \"removing\", mod, \"<-\", rem\n self.remove_single_nodes()\n\n def dotfile(self, dot):\n f = dot.open(\"w\")\n f.write(\"digraph G {\\n\")\n for prop in self.topgraph_properties:\n f.write(\"\\t%s\\n\" % prop)\n #write clusters and inter-cluster edges\n for cluster, nodes in self.clusters.iteritems():\n f.write(\"\\tsubgraph cluster_%s {\\n\" % cluster)\n f.write(\"\\t\\tstyle=filled;\\n\\t\\tcolor=lightgrey\\n\")\n for node in nodes:\n f.write('\\t\\t\"%s\";\\n' % node[5:])\n for mod, refs in self.imports.iteritems():\n for ref in refs:\n if mod in nodes and ref[0] in nodes:\n f.write('\\t\\t\"%s\" -> \"%s\";\\n' % (mod[5:], ref[0][5:]))\n f.write(\"\\t}\\n\")\n #write edges between clusters\n for mod, refs in self.imports.iteritems():\n try:\n nodes = self.clusters[self.mod_to_cluster[mod]]\n except KeyError:\n nodes = sets.Set()\n for ref in refs:\n if ref[0] not in nodes:\n f.write('\\t\"%s\" -> \"%s\";\\n' % (mod[5:], ref[0][5:]))\n f.write(\"}\")\n f.close()\n\nif __name__ == \"__main__\":\n import sys\n if len(sys.argv) > 1:\n path = py.path.local(sys.argv[1])\n else:\n path = py.path.local(\".\")\n gr = ModuleGraph(path)\n gr.create_clusters()\n dot = path.join(\"import_graph.dot\")\n gr.dotfile(dot)\n"}}},{"rowIdx":1389,"cells":{"text":{"kind":"string","value":"import React from 'react';\nimport { Paragraph, Page, ChapterTitle } from 'components';\nimport PageLayout from 'layouts/PageLayout';\n\nexport default () => (\n \n \n A new kind in the block\n \n During the last few years, media have periodically reported news about\n Bitcoin. Sometimes it was about its incredible raise in price, sometimes\n about its incredible drop in price and sometimes about how Bitcoin was\n allegedly used by the criminals all over the world. Lots of people\n labeled Bitcoin as a ponzi scheme, other compared Bitcoin to the tulips\n bubble of 1637. Meanwhile, someone else started digging deeper, trying\n to understand how to make it possible for people all over the world to\n transfer money without a bank. They found a system that was open,\n public, censorship-resistant, secure and where innovation could be\n developed without asking any permission: the Blockchain technology.\n \n \n The Blockchain technology is becoming one of the top strategic\n priorities of the most influential companies and business leaders\n worldwide, with the promise of reducing costs, enhance trust, minimise\n inefficiencies and radically transform business models.\n \n \n \n);\n"}}},{"rowIdx":1390,"cells":{"text":{"kind":"string","value":"insert([\n ['name' => 'Administrador', 'unalterable' => 1],\n ['name' => 'Técnico', 'unalterable' => 0],\n ['name' => 'Viabilidade', 'unalterable' => 0],\n ['name' => 'Operacional', 'unalterable' => 0],\n ['name' => 'Mapper', 'unalterable' => 0],\n ['name' => 'Comercial', 'unalterable' => 0],\n ['name' => 'Avançar todos', 'unalterable' => 0],\n ['name' => 'Retornar todos', 'unalterable' => 0],\n ['name' => 'Reporter', 'unalterable' => 0]\n ]);\n }\n}\n"}}},{"rowIdx":1391,"cells":{"text":{"kind":"string","value":"package com.icthh.xm.uaa.service;\n\nimport com.icthh.xm.commons.lep.LogicExtensionPoint;\nimport com.icthh.xm.commons.lep.spring.LepService;\nimport com.icthh.xm.commons.logging.util.MdcUtils;\nimport com.icthh.xm.commons.tenant.TenantContextHolder;\nimport com.icthh.xm.commons.tenant.TenantContextUtils;\nimport com.icthh.xm.uaa.commons.UaaUtils;\nimport com.icthh.xm.uaa.commons.XmRequestContextHolder;\nimport com.icthh.xm.uaa.domain.User;\nimport com.icthh.xm.uaa.service.mail.MailService;\nimport lombok.RequiredArgsConstructor;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.transaction.annotation.Transactional;\n\n@LepService(group = \"service.account\")\n@Transactional\n@RequiredArgsConstructor\n@Slf4j\npublic class AccountMailService {\n\n private final TenantContextHolder tenantContextHolder;\n private final XmRequestContextHolder xmRequestContextHolder;\n private final MailService mailService;\n\n @LogicExtensionPoint(\"SendMailOnRegistration\")\n public void sendMailOnRegistration(User user) {\n mailService.sendActivationEmail(user,\n UaaUtils.getApplicationUrl(xmRequestContextHolder),\n TenantContextUtils.getRequiredTenantKey(tenantContextHolder),\n MdcUtils.getRid());\n }\n\n @LogicExtensionPoint(\"SendMailOnPasswordReset\")\n public void sendMailOnPasswordResetFinish(User user) {\n mailService.sendPasswordChangedMail(user,\n UaaUtils.getApplicationUrl(xmRequestContextHolder),\n TenantContextUtils.getRequiredTenantKey(tenantContextHolder),\n MdcUtils.getRid());\n }\n\n @LogicExtensionPoint(\"SendMailOnPasswordInit\")\n public void sendMailOnPasswordInit(User user) {\n mailService.sendPasswordResetMail(user,\n UaaUtils.getApplicationUrl(xmRequestContextHolder),\n TenantContextUtils.getRequiredTenantKey(tenantContextHolder),\n MdcUtils.getRid());\n }\n\n @LogicExtensionPoint(\"SendSocialRegistrationValidationEmail\")\n public void sendSocialRegistrationValidationEmail(User user ,String providerId) {\n mailService.sendSocialRegistrationValidationEmail(user, providerId,\n UaaUtils.getApplicationUrl(xmRequestContextHolder),\n TenantContextUtils.getRequiredTenantKey(tenantContextHolder),\n MdcUtils.getRid());\n }\n\n}\n"}}},{"rowIdx":1392,"cells":{"text":{"kind":"string","value":"# frozen_string_literal: true\n\nrequire 'sinatra'\nrequire 'dotenv'\nrequire 'line/bot'\n\n$atis = []\ndef client\n Dotenv.load\n @client ||= Line::Bot::Client.new do |config|\n config.channel_secret = ENV['LINE_CHANNEL_SECRET']\n config.channel_token = ENV['LINE_CHANNEL_TOKEN']\n end\nend\n\ndef get_atis\n url = URI.parse(ENV['ATIS_URL'])\n res = Net::HTTP.get_response(url)\n halt 403, { 'Content-Type' => 'text/plain' }, 'Bad Request' unless res.code != 200\n $atis = JSON.parse(res.body)\nend\n\npost '/metar/callback' do\n body = request.body.read\n\n signature = request.env['HTTP_X_LINE_SIGNATURE']\n halt 400, { 'Content-Type' => 'text/plain' }, 'Bad Request' unless client.validate_signature(body, signature)\n events = client.parse_events_from(body)\n\n events.each do |event|\n case event\n when Line::Bot::Event::Message\n case event.type\n when Line::Bot::Event::MessageType::Text\n messages = []\n stations = event.message['text'].upcase.split(/[,|\\s+]/, 0).reject(&:empty?)\n get_atis unless stations.length.zero?\n stations.each do |station|\n $atis.each_with_index do |x, i|\n next unless $atis[i]['callsign'] == station\n\n message = {\n type: 'text',\n text: x['atisdat']\n }\n messages.push(message)\n end\n end\n if messages.empty?\n message = {\n type: 'text',\n text: 'ATIS Not Provided'\n }\n messages.push(message)\n end\n client.reply_message(event['replyToken'], messages)\n end\n end\n 'OK'\n end\nend\n"}}},{"rowIdx":1393,"cells":{"text":{"kind":"string","value":"import * as express from 'express';\ndeclare const normalizeFilter: (req: express.Request, res: express.Response, next: express.NextFunction) => void;\nexport default normalizeFilter;\n"}}},{"rowIdx":1394,"cells":{"text":{"kind":"string","value":"namespace GameCreator.Stats\n{\n\tusing System.Collections;\n\tusing System.Collections.Generic;\n\tusing UnityEngine;\n\tusing UnityEngine.Events;\n\tusing GameCreator.Core;\n using GameCreator.Variables;\n\n\t#if UNITY_EDITOR\n\tusing UnityEditor;\n #endif\n\n [AddComponentMenu(\"\")]\n public class ConditionStatusEffect : ICondition\n\t{\n public enum Operation\n {\n HasStatusEffect,\n DoesNotHave\n }\n\n public TargetGameObject target = new TargetGameObject(TargetGameObject.Target.Player);\n\n public Operation condition = Operation.HasStatusEffect;\n [StatusEffectSelector]\n public StatusEffectAsset statusEffect;\n\n [Indent] public int minAmount = 1;\n\n\t\t// EXECUTABLE: ----------------------------------------------------------------------------\n\n\t\tpublic override bool Check(GameObject target)\n\t\t{\n GameObject targetGO = this.target.GetGameObject(target);\n if (!targetGO)\n {\n Debug.LogError(\"Condition Status Effect: No target defined\");\n return false;\n }\n\n Stats stats = targetGO.GetComponentInChildren();\n if (!stats)\n {\n Debug.LogError(\"Condition Status Effect: Could not get Stats component in target\");\n return false;\n }\n\n bool hasStatusEffect = stats.HasStatusEffect(this.statusEffect, this.minAmount);\n\n if (this.condition == Operation.HasStatusEffect && hasStatusEffect) return true;\n if (this.condition == Operation.DoesNotHave && !hasStatusEffect) return true;\n\n return false;\n\t\t}\n\n\t\t// +--------------------------------------------------------------------------------------+\n\t\t// | EDITOR |\n\t\t// +--------------------------------------------------------------------------------------+\n\n\t\t#if UNITY_EDITOR\n\n public const string CUSTOM_ICON_PATH = \"Assets/Plugins/GameCreator/Stats/Icons/Conditions/\";\n\n\t\tpublic static new string NAME = \"Stats/Status Effect\";\n private const string NODE_TITLE = \"{0} {1} status effect {2}\";\n\n\t\t// INSPECTOR METHODS: ---------------------------------------------------------------------\n\n\t\tpublic override string GetNodeTitle()\n\t\t{\n string statName = (!this.statusEffect\n ? \"(none)\" \n : this.statusEffect.statusEffect.uniqueName\n );\n\n string conditionName = (this.condition == Operation.HasStatusEffect\n ? \"Has\"\n : \"Does not have\"\n );\n\n return string.Format(\n NODE_TITLE,\n conditionName,\n this.target,\n statName\n );\n\t\t}\n\n\t\t#endif\n\t}\n}\n"}}},{"rowIdx":1395,"cells":{"text":{"kind":"string","value":"package xyz.qwewqa.relive.simulator.core.presets.condition\n\nimport xyz.qwewqa.relive.simulator.stage.character.School\nimport xyz.qwewqa.relive.simulator.core.stage.condition.NamedCondition\n\nval SeishoOnlyCondition = schoolCondition(School.Seisho)\nval RinmeikanOnlyCondition = schoolCondition(School.Rinmeikan)\nval FrontierOnlyCondition = schoolCondition(School.Frontier)\nval SiegfeldOnlyCondition = schoolCondition(School.Siegfeld)\nval SeiranOnlyCondition = schoolCondition(School.Seiran)\n\nprivate fun schoolCondition(school: School) = NamedCondition(school.name) {\n it.dress.character.school == school\n}\n"}}},{"rowIdx":1396,"cells":{"text":{"kind":"string","value":"\n\tmodule.exports = {\n\n\t\tversion: require('../actions/version'),\n\t\thostInformation: require('../actions/hostInfo'),\n\t\tsystemProps: require('../actions/systemProps'),\n\n\t\tcreateVm: require('../actions/create'),\n\n\t\tstart: require('../actions/start'),\n\t\tstop: require('../actions/stop'),\n\t\tsave: require('../actions/save'),\n\n\t\tclone: require('../actions/clone'),\n\t\tscreenshot: require('../actions/screenshot'),\n\n\t\tisRunning: require('../actions/isRunning'),\n\t\tgetRunning: require('../actions/getRunning'),\n\n\t\tlist: require('../actions/list'),\n\t\tvmInfo: require('../actions/vmInfo'),\n\n\t\tsetVmRam: require('../actions/setVmRam'),\n\t\tsetBootOrder: require('../actions/bootOrder'),\n\n\t\trdp: {\n\t\t\tenableRdpAuth: require('../actions/rdp/enable'),\n\t\t\tsetRdpStatus: require('../actions/rdp/setRdpStatus'),\n\t\t\tsetPort: require('../actions/rdp/setPort'),\n\t\t\taddUser: require('../actions/rdp/addUser'),\n\t\t\tremoveUser: require('../actions/rdp/removeUser'),\n\t\t\tlistUsers: require('../actions/rdp/listUsers'),\n\t\t\tauthType: require('../actions/rdp/authType'),\n\t\t},\n\n\t\tsnapshots: {\n\t\t\ttake: require('../actions/snapshots/take'),\n\t\t\trestore: require('../actions/snapshots/restore'),\n\t\t\tlist: require('../actions/snapshots/list'),\n\t\t\tdelete: require('../actions/snapshots/delete')\n\t\t},\n\n\t\tstorage: {\n\n\t\t\tlistMounted: require('../actions/storage/listMounted'),\n\t\t\tlistAllVdi: require('../actions/storage/listAllVdi'),\n\n\t\t\tattachVdi: require('../actions/storage/vdi.attach'),\n\t\t\tattachISO: require('../actions/storage/iso.attach'),\n\n\t\t\tdetach: require('../actions/storage/detach'),\n\t\t\tresizeVdi: require('../actions/storage/vdi.resize'),\n\t\t\tcreateVdi: require('../actions/storage/vdi.create'),\n\n\t\t},\n\n\t\tmetrics: {\n\t\t\tquery: require('../actions/metrics/query'),\n\t\t\tenable: require('../actions/metrics/enable'),\n\t\t\tdisable: require('../actions/metrics/disable')\n\t\t}\n\n\t};"}}},{"rowIdx":1397,"cells":{"text":{"kind":"string","value":"from . import (eyerefract,\n cable,\n unlit_generic,\n lightmap_generic,\n vertexlit_generic,\n worldvertextransition,\n unlittwotexture,\n lightmapped_4wayblend,\n decalmodulate,\n refract,\n water)\n"}}},{"rowIdx":1398,"cells":{"text":{"kind":"string","value":"\"\"\"Top-level package for EVTech.\"\"\"\n\nfrom .camera import *\nfrom .geodesy import *\nfrom .dataset import *\nfrom .ray import *\n\n__author__ = \"\"\"David Nilosek\"\"\"\n__email__ = 'david.nilosek@eagleview.com'\n__version__ = '1.1.0'\n"}}},{"rowIdx":1399,"cells":{"text":{"kind":"string","value":"#!/bin/sh\n\nVER=$1\nif [ -z $VER ];\nthen\n VER=latest\nfi\necho \"VERSION=$VER\"\n\nREPO=nmhung1210/mern-stack-docker\nTAG_NAME=$REPO:$VER\n\ndocker build -t $TAG_NAME . && \\\ndocker push $TAG_NAME\n\n\n\n\n"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":13,"numItemsPerPage":100,"numTotalItems":43696,"offset":1300,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjU4ODkwNiwic3ViIjoiL2RhdGFzZXRzL1ppaGFvLUxpL0NvZGUiLCJleHAiOjE3NTY1OTI1MDYsImlzcyI6Imh0dHBzOi8vaHVnZ2luZ2ZhY2UuY28ifQ.sUYESmwtsuLPgkR77eDUfOvsPpyPflN8qfIoLdBZv54dOhC8f521L9bhrIu19iXrdntGfvrnzqVlcDgW48OFAA","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
text
stringlengths
27
775k
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ /* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable import/no-default-export */ import { Box } from "@chakra-ui/react"; export default function Button(props: any): JSX.Element { return ( <Box px={4} py={2} as="button" transition="all 0.3s ease" borderRadius="25px" fontSize="16px" fontWeight="semibold" border="1px solid var(--chakra-colors-brand-primary)" background="brand.transparent" color="var(--chakra-colors-brand-primary)" _hover={{ background: "brand.primary", color: "white", }} _active={{ transform: "scale(0.90)", boxShadow: "md", }} {...props} boxShadow="lg" > {props.children} </Box> ); }
import React from "react"; import styles from "./styles.module.scss"; const TitleSection = ({titulo}:{titulo:string}) =>{ return( <div className={styles.TitleSection}> <h2>{titulo}</h2> </div> ) } export default TitleSection;
import 'dart:math'; import 'dart:ui'; import 'QCalHolder.dart'; import 'QCalModel.dart'; class QCalculator { // @override static List<Week> generate(Date date) { // DateTime start =DateTime.now(); DateTime firstDateInMon = DateTime(date.year, date.month, 1); int offset2FirstWeekDay = (firstDateInMon.weekday + DAYS_PERWEEK - firstDayInWeek) % DAYS_PERWEEK; DateTime firstDate = firstDateInMon.subtract(Duration(days: offset2FirstWeekDay)); List<Week> monthDate = []; for (int weekIndex = 0; weekIndex < WEEK_IN_MONTH; weekIndex++) { Week week = Week(); for (int dayIndex = 0; dayIndex < DAYS_PERWEEK; dayIndex++) { week.add( Date.from(firstDate.add(Duration(days: weekIndex * 7 + dayIndex)))); } monthDate.add(week); } // print( // "generateMonthDate: ${date}, ${firstDateInMon.weekday}, offset: ${offset2FirstWeekDay}, ${firstDate}"); // print( // "generateMonthDate: ${date}, ${DateTime.now().difference(start).inMilliseconds} ms"); return monthDate; } static Date offsetMonthTo(Date baseDate, int offset) { // int offsetYear = (offset + baseDate.month) ~/ MAX_MONTH; // int offsetMonth = ((offset + baseDate.month + MAX_MONTH) % MAX_MONTH).toInt() + 1; // int toYear = baseDate.year + offsetYear; // int toMonth = offsetMonth; // if (toMonth > MAX_MONTH+1) { // toMonth -= MAX_MONTH +1; // } DateTime toMonthMaxDate = DateTime(baseDate.year, baseDate.month + offset + 1, 1) .subtract(Duration(days: 1)); // Date date = ; // print( // "\n\n ++++++++++offsetMonthTo:: ${offset}, ${baseDate} , ${toMonthMaxDate} => ${date}"); return Date.from(DateTime(baseDate.year, baseDate.month + offset, min(toMonthMaxDate.day, baseDate.date))); } static Date offsetWeekTo(Date date, int offset) { return Date.from( date.toDateTime().add(Duration(days: offset * DAYS_PERWEEK))); } static Date calcFocusDateByOffset( Offset offset, Size size, QCalHolder model, List<Week> weeks) { int focusIndexOfWeek = -1; for (int i = 0; i < WEEK_IN_MONTH; i++) { Week week = weeks[i]; if (week.hasDate(model.focusDateTime)) { focusIndexOfWeek = i; break; } } int indexDay = offset.dx ~/ (size.width / DAYS_PERWEEK); int indexWeek = focusIndexOfWeek; switch (model.mode) { case Mode.WEEK: break; default: indexWeek = offset.dy ~/ (size.height / WEEK_IN_MONTH); } return weeks[indexWeek].dates[indexDay]; } static Date calcFocusDate( Offset offset, Size size, QCalHolder model, List<Week> weeks) { int focusIndexOfWeek = 0; for (int i = 0; i < WEEK_IN_MONTH; i++) { Week week = weeks[i]; if (week.hasDate(model.focusDateTime)) { focusIndexOfWeek = i; break; } } int indexDay = offset.dx ~/ (size.width / DAYS_PERWEEK); int indexWeek = focusIndexOfWeek; switch (model.mode) { case Mode.WEEK: break; default: indexWeek = offset.dy ~/ (size.height / WEEK_IN_MONTH); } return weeks[indexWeek].dates[indexDay]; } }
### **瓜瓜talk服务端** cdn服务器 msg服务器
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content=""> <meta name="author" content=""> <title>DevExtremeAspNetCoreApp</title> <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" /> <link rel="stylesheet" href="~/css/vendor.css" asp-append-version="true" /> <link rel="stylesheet" href="~/css/site.css" /> <script src="~/js/vendor.js" asp-append-version="true"></script> </head> <body> <div id="app-side-nav-outer-toolbar"> <div class="layout-header"> @(Html.DevExtreme().Toolbar() .Items(items => { items.Add() .Widget(w => w .Button() .Icon("menu") .OnClick("DevExtremeAspNetCoreApp.onMenuButtonClick") ) .Location(ToolbarItemLocation.Before) .CssClass("menu-button"); items.Add() .Html("<div>DevExtremeAspNetCoreApp</div>") .Location(ToolbarItemLocation.Before) .CssClass("header-title"); }) ) </div> <div class="layout-body"> @(Html.DevExtreme().Drawer() .ID("layout-drawer") .Position(DrawerPosition.Left) .Opened(new JS("DevExtremeAspNetCoreApp.restoreDrawerOpened()")) .Content(@<text> <div id="layout-drawer-scrollview" class="with-footer"> <div class="content"> @RenderBody() </div> <div class="content-block"> <div class="content-footer"> <div id="footer"> Copyright (c) 2000-2019 Developer Express Inc. <br /> All trademarks or registered trademarks are property of their respective owners. </div> </div> </div> </div> </text>) .Template(new TemplateName("navigation-menu")) ) </div> </div> @using(Html.DevExtreme().NamedTemplate("navigation-menu")) { <div class="menu-container dx-swatch-additional"> @functions{ bool IsCurrentPage(string pageName) { var pageUrl = Url.Page(pageName); var currentPageUrl = Url.Page(ViewContext.RouteData.Values["page"].ToString()); return pageUrl == currentPageUrl; } } @(Html.DevExtreme().TreeView() .Items(items => { items.Add() .Text("Home") .Icon("home") .Option("path", Url.Page("Index")) .Selected(IsCurrentPage("Index")); items.Add() .Text("About") .Icon("info") .Option("path", Url.Page("About")) .Selected(IsCurrentPage("About")); }) .ExpandEvent(TreeViewExpandEvent.Click) .SelectionMode(NavSelectionMode.Single) .SelectedExpr("selected") .FocusStateEnabled(false) .Width(250) .OnItemClick("DevExtremeAspNetCoreApp.onTreeViewItemClick") ) </div> } <script> var DevExtremeAspNetCoreApp = (function() { var DRAWER_OPENED_KEY = "DevExtremeAspNetCoreApp-drawer-opened"; var breakpoints = { xSmallMedia: window.matchMedia("(max-width: 599.99px)"), smallMedia: window.matchMedia("(min-width: 600px) and (max-width: 959.99px)"), mediumMedia: window.matchMedia("(min-width: 960px) and (max-width: 1279.99px)"), largeMedia: window.matchMedia("(min-width: 1280px)") }; function getDrawer() { return $("#layout-drawer").dxDrawer("instance"); } function restoreDrawerOpened() { var isLarge = breakpoints.largeMedia.matches; if(!isLarge) return false; var state = sessionStorage.getItem(DRAWER_OPENED_KEY); if(state === null) return isLarge; return state === "true"; } function saveDrawerOpened() { sessionStorage.setItem(DRAWER_OPENED_KEY, getDrawer().option("opened")); } function updateDrawer() { var isXSmall = breakpoints.xSmallMedia.matches, isLarge = breakpoints.largeMedia.matches; getDrawer().option({ openedStateMode: isLarge ? "shrink" : "overlap", revealMode: isXSmall ? "slide" : "expand", minSize: isXSmall ? 0 : 60, shading: !isLarge, }); } function init() { $("#layout-drawer-scrollview").dxScrollView({ direction: "vertical" }); $.each(breakpoints, function(_, size) { size.addListener(function(e) { if(e.matches) updateDrawer(); }); }); updateDrawer(); } function navigate(url, delay) { if(url) setTimeout(function() { location.href = url }, delay); } function onMenuButtonClick() { getDrawer().toggle(); saveDrawerOpened(); } function onTreeViewItemClick(e) { var drawer = getDrawer(); var savedOpened = restoreDrawerOpened(); var actualOpened = drawer.option("opened"); if(!actualOpened) { drawer.show(); } else { var willHide = !savedOpened || !breakpoints.largeMedia.matches; var willNavigate = !e.itemData.selected; if(willHide) drawer.hide(); if(willNavigate) navigate(e.itemData.path, willHide ? 400 : 0); } } return { init: init, restoreDrawerOpened: restoreDrawerOpened, onMenuButtonClick: onMenuButtonClick, onTreeViewItemClick: onTreeViewItemClick }; })(); document.addEventListener("DOMContentLoaded", function documentReady() { this.removeEventListener("DOMContentLoaded", documentReady); DevExtremeAspNetCoreApp.init(); }); </script> </body> </html>
module Main where import Utilities -- Input processing type Input = [Int] parse :: String -> Input parse = map read . lines -- Part One solve1 :: Input -> Int solve1 xs = head [product ns | (ns, _) <- choose 2 xs, sum ns == 2020] tests1 :: [(String, Int)] tests1 = [(testInput, 514579)] testInput :: String testInput = "\ \1721\n\ \979\n\ \366\n\ \299\n\ \675\n\ \1456\n" -- Part Two solve2 :: Input -> Int solve2 xs = head [product ns | (ns, _) <- choose 3 xs, sum ns == 2020] tests2 :: [(String, Int)] tests2 = [(testInput, 241861950)] main :: IO () main = do s <- readFile "input/01.txt" let input = parse s putStr (unlines (failures "solve1" (solve1 . parse) tests1)) print (solve1 input) putStr (unlines (failures "solve2" (solve2 . parse) tests2)) print (solve2 input)
class TopApps::Scraper def self.scrape_index(index_url) doc = Nokogiri::HTML(open(index_url)) free_apps_section = doc.css(".section.chart-grid.apps div.section-content").first free_apps_list = free_apps_section.css("li") free_apps_list.map do |app| { name: app.css("h3 a").text, category: app.css("h4 a").text, rank: app.css("strong").text.chomp("."), profile_url: app.css("a").attribute("href").value } end end def self.scrape_profile(profile_url) doc = Nokogiri::HTML(open(profile_url)) notes = doc.css("div.we-editor-notes.lockup.ember-view p").text.strip notes == "" ? notes = "Unavailable." : nil { notes: notes, developer: doc.css("h2.product-header__identity.app-header__identity a").text, rating: doc.css("figcaption.we-rating-count.star-rating__count").text.split(",").first } end end
<?php use Faker\Generator as Faker; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB as DB; class MessageParticipantsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run(Faker $faker) { //Empty the message_participants table // DB::table('message_participants')->delete(); $userIds = App\Models\User::all()->pluck('id')->toArray(); $messageSubjectIds = App\Models\MessageSubject::all()->pluck('id')->toArray(); if(count($messageSubjectIds) > 0 && count($userIds) > 0){ foreach ($messageSubjectIds as $messageSubject) { foreach ($userIds as $user) { $data = [ [ "user_id" => $user, "message_subject_id" => $messageSubject, "created_at" => strftime("%Y-%m-%d %H:%M:%S"), "updated_at" => strftime("%Y-%m-%d %H:%M:%S") ] ]; DB::table("message_participants")->insert($data); } } } } }
package excel_data_import.repository.implementation; import javax.persistence.EntityManager; import excel_data_import.domain.Match; import excel_data_import.repository.MatchRepository; public class MatchRepositoryImpl implements MatchRepository { @Override public void persist(Match match) { try { EntityManager entityManager = HaurRankingDatabaseUtils.createEntityManager(); entityManager.getTransaction().begin(); entityManager.persist(match); entityManager.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); } } }
package crypto import ( "crypto/sha1" "crypto/sha256" "crypto/sha512" "fmt" "hash" "io" bosherr "github.com/cloudfoundry/bosh-utils/errors" ) var ( DigestAlgorithmSHA1 Algorithm = algorithmSHAImpl{"sha1"} DigestAlgorithmSHA256 Algorithm = algorithmSHAImpl{"sha256"} DigestAlgorithmSHA512 Algorithm = algorithmSHAImpl{"sha512"} ) type algorithmSHAImpl struct { name string } func (a algorithmSHAImpl) Name() string { return a.name } func (a algorithmSHAImpl) CreateDigest(reader io.Reader) (Digest, error) { hash := a.hashFunc() _, err := io.Copy(hash, reader) if err != nil { return nil, bosherr.WrapError(err, "Copying file for digest calculation") } return NewDigest(a, fmt.Sprintf("%x", hash.Sum(nil))), nil } func (a algorithmSHAImpl) hashFunc() hash.Hash { switch a.name { case "sha1": return sha1.New() case "sha256": return sha256.New() case "sha512": return sha512.New() default: panic("Internal inconsistency") } } type unknownAlgorithmImpl struct { name string } func NewUnknownAlgorithm(name string) unknownAlgorithmImpl { return unknownAlgorithmImpl{name: name} } func (c unknownAlgorithmImpl) Name() string { return c.name } func (c unknownAlgorithmImpl) CreateDigest(reader io.Reader) (Digest, error) { return nil, bosherr.Errorf("Unable to create digest of unknown algorithm '%s'", c.name) }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class admin_producto_detalle_controller extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('admin_producto_detalle_model'); } public function index() { $data= array ( 'title' => 'CRUD || ProductosDetalles'); $this->load->view('template/admin_header',$data); $this->load->view('template/admin_navbar'); $this->load->view('admin_producto_detalle_view'); $this->load->view('template/admin_footer'); } //Funciones mostrar public function get_producto_detalle(){ $respuesta= $this->admin_producto_detalle_model->get_producto_detalle(); echo json_encode($respuesta); } public function get_producto(){ $id = $this->input->post('id'); $respuesta = $this->admin_producto_detalle_model->get_producto($id); echo json_encode($respuesta); } public function get_talla(){ $respuesta = $this->admin_producto_detalle_model->get_talla(); echo json_encode($respuesta); } public function get_color(){ $respuesta = $this->admin_producto_detalle_model->get_color(); echo json_encode($respuesta); } public function get_categoria(){ $id = $this->input->post('id'); $respuesta = $this->admin_producto_detalle_model->get_categoria(); echo json_encode($respuesta); } //Funcion buscar en tabla public function buscar() { $palabra = $this->input->post('palabra'); $respuesta = $this->admin_producto_detalle_model->buscar_palabra($palabra); echo json_encode($respuesta); } //FUNCION ELIMINAR public function eliminar(){ $id = $this->input->post('id'); $respuesta = $this->admin_producto_detalle_model->eliminar($id); echo json_encode($respuesta); } //FUNCION INGRESAR public function ingresar(){ $registro = $this->input->post('registro'); if ($registro!=0) { $exist = $this->input->post('exist'); $datos['producto'] = $this->input->post('producto'); $datos['talla'] = $this->input->post('talla'); $datos['color'] = $this->input->post('color'); $cantidadInput= $this->input->post('cantidad'); $cantidadSum=$exist +$cantidadInput; $datos['cantidad'] = $cantidadSum; $respuesta = $this->admin_producto_detalle_model->set_cantidad($datos); echo json_encode($respuesta); }else{ $datos['producto'] = $this->input->post('producto'); $datos['talla'] = $this->input->post('talla'); $datos['color'] = $this->input->post('color'); $datos['cantidad'] = $this->input->post('cantidad'); $respuesta = $this->admin_producto_detalle_model->set_detalle($datos); echo json_encode($respuesta); } } //FUNCIONES CONSULTAS public function existencia(){ $producto = $this->input->post('producto'); $talla = $this->input->post('talla'); $color = $this->input->post('color'); $respuesta = $this->admin_producto_detalle_model->existencia($producto,$talla,$color); echo json_encode($respuesta); } //FUNCIONES ACTUALIZAR public function get_datos(){ $id = $this->input->post('id'); $respuesta = $this->admin_producto_detalle_model->get_datos($id); echo json_encode($respuesta); } public function actualizar(){ $datos['id'] = $this->input->post('id_producto_detalle'); $datos['cantidad'] = $this->input->post('cantidad'); $respuesta = $this->admin_producto_detalle_model->actualizar($datos); echo json_encode($respuesta); } /*public function get_imagen() { $id = $this->input->post('id'); $respuesta= $this->admin_categoria_model->get_imagen($id); echo json_encode($respuesta); }*/ } ?>
import { Injectable } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class CrudServiceService { httpOptions = { 'responseType': 'xml' as 'json' }; constructor(private http: HttpClient) { } country: string; state: string; regNum: string; getdata(country:string, state:string, regNumber:string): Promise<any> { return new Promise((resolve, reject) => { var func, url; switch (country) { case "GBR": func = "Check"; break; case "AUS": func = "CheckAustralia"; break; case "DNK": func = "CheckDenmark"; break; case "EST": func = "CheckEstonia"; break; case "FIN": func = "CheckFinland"; break; case "FRA": func = "CheckFrance"; break; case "HUN": func = "CheckHungary"; break; case "IND": func = "CheckIndia"; break; case "IRL": func = "CheckIreland"; break; case "ITA": func = "CheckItaly"; break; case "NLD": func = "CheckNetherlands "; break; case "NZL": func = "CheckNewZealand "; break; case "NOR": func = "CheckNorway "; break; case "PRT": func = "CheckPortugal "; break; case "RUS": func = "CheckRussia "; break; case "SVK": func = "CheckSlovakia "; break; case "ZAF": func = "CheckSouthAfrica "; break; case "ESP": func = "CheckSpain "; break; case "LKA": func = "CheckSriLanka "; break; case "SWE": func = "CheckSweden "; break; case "ARE": func = "CheckUAE "; break; case "USA": func = "CheckUSA"; break; } url = "http://regcheck.org.uk/api/reg.asmx/" + func + "?RegistrationNumber=" + regNumber + "&username=dananos" // "http://regcheck.org.uk/api/reg.asmx/Check?RegistrationNumber=YYO7XHH&username=dananos" this.http .get(url, this.httpOptions) .subscribe( json => { resolve(json); }, error => { reject(error); } ); }); // }); } setdata(country, state, regNum) { this.country = country; this.state = state; this.regNum = regNum; } getinfo() { return { country: this.country, state: this.state, regNum: this.regNum }; } }
exports.update_value_id = function(id, value) { document.getElementById(id).value = value; } exports.append_value_id = function(id, value) { document.getElementById(id).value += value; } exports.update_view_id = function(id, value) { document.getElementById(id).innerText = value; } exports.update_background_id = function (id, color) { document.getElementById(id).style.background = color; }
# Get-VstsAssemblyReference [table of contents](../Commands.md#toc) | [brief](../Commands.md#get-vstsassemblyreference) ``` NAME Get-VstsAssemblyReference SYNOPSIS Gets assembly reference information. SYNTAX Get-VstsAssemblyReference [-LiteralPath] <String> [<CommonParameters>] DESCRIPTION Not supported for use during task execution. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK. Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario. Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted. See https://github.com/Microsoft/azure-pipelines-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task. PARAMETERS -LiteralPath <String> Assembly to walk. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer, PipelineVariable, and OutVariable. For more information, see about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216). -------------------------- EXAMPLE 1 -------------------------- PS C:\>Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\ net45\Microsoft.TeamFoundation.Build2.WebApi.dll ```
class Events { private _callbacks = {}; public bind(name, callback, context?) { if (!this._callbacks[name]) { this._callbacks[name] = []; } // this._callbacks[name].push({'cb':callback, context:context}); this._callbacks[name].push(callback); } public unbind(name,callback) { for (var i = 0; i < this._callbacks[name]; i++) { if(this._callbacks[name][i] == callback) { this._callbacks[name].splice(i,1); return; } } } public emit(name, args?: any) { if(this._callbacks[name]) { for (var i = 0; i < this._callbacks[name].length; i++) { this._callbacks[name][i](args); } } } }
package com.spike.text.lucene.indexing.analysis; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.core.KeywordAnalyzer; import org.apache.lucene.analysis.core.SimpleAnalyzer; import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field.Store; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.junit.Test; import com.spike.text.lucene.util.LuceneAppAnalyzerUtil; import com.spike.text.lucene.util.LuceneAppUtil; import com.spike.text.lucene.util.SearchingMemIndexTestBase; import com.spike.text.lucene.util.anno.BookPartEnum; import com.spike.text.lucene.util.anno.LuceneInAction2ndBook; @LuceneInAction2ndBook(part = BookPartEnum.CORE_LUCENE, chapter = 4, section = { 7 }) public class SearchUnAnalyzedFiledTest extends SearchingMemIndexTestBase { private static final String fld_partnum = "partnum"; private static final String fldValue_partnum = "Q36"; private static final String fld_description = "description"; private static final String fldValue_description = "Illidium Space Modulator"; /** * @throws IOException * @throws ParseException * @see SimpleAnalyzer * @see QueryParser * @see PerFieldAnalyzerWrapper * @see KeywordAnalyzer */ @Test public void searchUnanalyzedField() throws IOException, ParseException { LuceneAppAnalyzerUtil.renderTokensWithFullDetails(new SimpleAnalyzer(), fldValue_partnum); LuceneAppAnalyzerUtil.renderTokensWithFullDetails(new SimpleAnalyzer(), fldValue_description); IndexSearcher indexSearcher = this.getIndexSearcher(); Query query = new TermQuery(new Term(fld_partnum, fldValue_partnum)); TopDocs topDocs = indexSearcher.search(query, 10); assertEquals(1, topDocs.totalHits); LuceneAppUtil.renderSearchResultWithExplain(query, indexSearcher, topDocs, fld_partnum); query = new QueryParser(fld_description, new SimpleAnalyzer()) .parse(fld_partnum + ":Q36 AND SPACE"); assertEquals("+partnum:q +description:space", query.toString()); topDocs = indexSearcher.search(query, 10); assertEquals(0, topDocs.totalHits); LuceneAppUtil.renderSearchResultWithExplain(query, indexSearcher, topDocs, fld_description); Map<String, Analyzer> analyzerPerField = new HashMap<String, Analyzer>(); // KeywordAnalyzer treat `Q36` as a complete word, // just as tokenized=false in indexing phase analyzerPerField.put(fld_partnum, new KeywordAnalyzer()); PerFieldAnalyzerWrapper analyzerWrapper = LuceneAppAnalyzerUtil.constructPerFieldAnalyzerWrapper(new SimpleAnalyzer(), analyzerPerField); query = new QueryParser(fld_description, analyzerWrapper).parse(fld_partnum + ":Q36 AND SPACE"); System.out.println(query.toString()); assertEquals("+partnum:Q36 +description:space", query.toString()); topDocs = indexSearcher.search(query, 10); assertEquals(1, topDocs.totalHits); LuceneAppUtil.renderSearchResultWithExplain(query, indexSearcher, topDocs, fld_description); } @Override protected Analyzer defineAnalyzer() { return new SimpleAnalyzer(); } @Override protected void doIndexing() throws IOException { IndexWriter indexWriter = this.indexWriter; Document document = new Document(); document.add(LuceneAppUtil.createStringField(fld_partnum, fldValue_partnum, Store.NO, false, IndexOptions.DOCS, true)); document.add(LuceneAppUtil.createStringField(fld_description, fldValue_description, Store.YES, true, IndexOptions.DOCS, true)); indexWriter.addDocument(document); } }
namespace StripeTests.Terminal { using Newtonsoft.Json; using Stripe.Terminal; using Xunit; public class LocationTest : BaseStripeTest { public LocationTest(StripeMockFixture stripeMockFixture) : base(stripeMockFixture) { } [Fact] public void Deserialize() { string json = this.GetFixture("/v1/terminal/locations/loc_123"); var location = JsonConvert.DeserializeObject<Location>(json); Assert.NotNull(location); Assert.IsType<Location>(location); Assert.NotNull(location.Id); Assert.Equal("terminal.location", location.Object); } } }
@file:Suppress("CHECKRESULT") package com.shimmer.microcore.extension import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers inline fun <T> Observable<T>.subscribe3( crossinline onNext: T.() -> Unit, crossinline onError: (Throwable) -> Unit = {}, crossinline onComplete: () -> Unit = {}, ) { this.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ it.onNext() }, { error -> onError(error) }, { onComplete() }) }
stitching_version="1.9.0" stitching_git_hash="master" synapse_version="1.4.1" synapse_git_hash="1.4.1" synapse_dask_version="1.3.1" neuron_segmentation_version="1.0.0" neuron_segmentation_git_hash="1.0.0" n5_spark_tools_version="3.11.0" n5_spark_tools_git_hash="exm-3.11.0"
#!/bin/bash ARGS=() [[ -z "$DEVICE" ]] && ARGS+=("-Dwebdriver.url=https://${BROWSERSTACK_USERNAME}:${BROWSERSTACK_ACCESS_KEY}@hub-cloud.browserstack.com/wd/hub") [[ ! -z "$BROWSERSTACK_LOCAL_IDENTIFIER" ]] && ARGS+=("-Dwebdriver.cap.browserstack.localIdentifier=${BROWSERSTACK_LOCAL_IDENTIFIER}") [[ ! -z "$BROWSER" ]] && ARGS+=("-Dwebdriver.cap.browser=$BROWSER") [[ ! -z "$WEBDRIVER_TYPE" ]] && ARGS+=("-Dwebdriver.type=$WEBDRIVER_TYPE") || ARGS+=('-Dwebdriver.type=remote') [[ ! -z "$OS" ]] && ARGS+=("-Dwebdriver.cap.os=${OS}") [[ ! -z "$OS_VER" ]] && ARGS+=("-Dwebdriver.cap.os_version=${OS_VER}") [[ ! -z "$DEVICE" ]] && ARGS+=("-Dwebdriver.appium.url=https://${BROWSERSTACK_USERNAME}:${BROWSERSTACK_ACCESS_KEY}@hub-cloud.browserstack.com/wd/hub") [[ ! -z "$DEVICE" ]] && ARGS+=("-Dwebdriver.cap.device=${DEVICE}") [[ ! -z "$DEVICE" ]] && ARGS+=('-Dwebdriver.cap.realMobile=true') mvn clean install "${ARGS[@]}"
package typingsSlinky.grammarkdown import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} object stringwriterMod { @JSImport("grammarkdown/dist/stringwriter", "StringWriter") @js.native class StringWriter () extends StObject { def this(eol: String) = this() var _depth: js.Any = js.native var _eol: js.Any = js.native var _indents: js.Any = js.native var _newLine: js.Any = js.native var _text: js.Any = js.native def dedent(): Unit = js.native var flushNewLine: js.Any = js.native def indent(): Unit = js.native def size: Double = js.native def write(): Unit = js.native def write(text: String): Unit = js.native def writeln(): Unit = js.native def writeln(text: String): Unit = js.native } }
--- layout: watch title: TLP6 - 07/02/2021 - M20210207_002532_TLP_6T.jpg date: 2021-02-07 00:25:32 permalink: /2021/02/07/watch/M20210207_002532_TLP_6 capture: TLP6/2021/202102/20210206/M20210207_002532_TLP_6T.jpg ---
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // OtherResources=process_sync_script.dart import "dart:io"; import "package:expect/expect.dart"; import 'package:path/path.dart'; test(int blockCount, int stdoutBlockSize, int stderrBlockSize, int exitCode, [int nonWindowsExitCode]) { // Get the Dart script file that generates output. var scriptFile = new File( Platform.script.resolve("process_sync_script.dart").toFilePath()); var args = <String>[] ..addAll(Platform.executableArguments) ..addAll([ scriptFile.path, blockCount.toString(), stdoutBlockSize.toString(), stderrBlockSize.toString(), exitCode.toString() ]); ProcessResult syncResult = Process.runSync(Platform.executable, args); Expect.equals(blockCount * stdoutBlockSize, syncResult.stdout.length); Expect.equals(blockCount * stderrBlockSize, syncResult.stderr.length); if (Platform.isWindows) { Expect.equals(exitCode, syncResult.exitCode); } else { if (nonWindowsExitCode == null) { Expect.equals(exitCode, syncResult.exitCode); } else { Expect.equals(nonWindowsExitCode, syncResult.exitCode); } } Process.run(Platform.executable, args).then((asyncResult) { Expect.equals(syncResult.stdout, asyncResult.stdout); Expect.equals(syncResult.stderr, asyncResult.stderr); Expect.equals(syncResult.exitCode, asyncResult.exitCode); }); } main() { test(10, 10, 10, 0); test(10, 100, 10, 0); test(10, 10, 100, 0); test(100, 1, 10, 0); test(100, 10, 1, 0); test(100, 1, 1, 0); test(1, 100000, 100000, 0); // The buffer size used in process.h. var kBufferSize = 16 * 1024; test(1, kBufferSize, kBufferSize, 0); test(1, kBufferSize - 1, kBufferSize - 1, 0); test(1, kBufferSize + 1, kBufferSize + 1, 0); test(10, 10, 10, 1); test(10, 10, 10, 255); test(10, 10, 10, -1, 255); test(10, 10, 10, -255, 1); }
export interface CommonColors { readonly black: string; readonly white: string; readonly grey0: string; readonly grey1: string; readonly grey2: string; readonly grey3: string; readonly grey4: string; readonly grey5: string; readonly greyOutline: string; readonly disabled: string; readonly divider: string; readonly foreground: string; readonly background: string; } export interface AccentColors { readonly primary: string; readonly secondary: string; readonly success: string; readonly warning: string; readonly error: string; } export interface SocialColors { readonly kakao: string; readonly naver: string; readonly google: string; readonly facebook: string; readonly apple: string; } export interface Colors extends CommonColors, AccentColors, SocialColors {} export type Theme = { light: Colors; dark: Colors; }; export interface ThemeContextState { dark: boolean; toggleTheme: () => void; colors: Colors; }
package consoleui import ( "fmt" "github.com/nsf/termbox-go" "github.com/xosmig/roguelike/core/geom" "github.com/xosmig/roguelike/gamemodel/status" "log" ) // getKeyForAction accepts the set of interesting keys and waits for one of these keys to be pressed, // or for a cancellation request from the user (Ctrl+C pressed). // It returns the pressed key and a boolean flag, indicating whether the exit was requested or not. func (ui *consoleUi) getKeyForAction(actions map[termbox.Key]func()) (key termbox.Key, finish bool) { var ev termbox.Event for { ev = termbox.PollEvent() if ev.Type != termbox.EventKey { continue } if ev.Key == termbox.KeyCtrlC { log.Println("Ctrl+C is pressed") return ev.Key, true } if _, present := actions[ev.Key]; present { return ev.Key, false } log.Printf("Debug: Invalid command key: %v\n", ev.Key) } } // restartOrExit blocks until the user presses Ctrl+C (in this case it just returns nil), // or Ctrl+R (in this case it restarts the game via recursive call to Run method). func (ui *consoleUi) restartOrExit() error { ui.messagef("Press 'Ctrl+C' to exit, or 'Ctrl+R' to restart") actions := map[termbox.Key]func(){ termbox.KeyCtrlR: nil, } _, finish := ui.getKeyForAction(actions) if finish { log.Println("Exit requested") return nil } ui.reloadGameModel() return ui.Run() } // Run does the read-execute-print-loop. func (ui *consoleUi) Run() error { var afterRender []func() // delay delays the given function execution so that it is executed after rendering. // It's useful to adjust the rendered picture. // For example, by printing a message. delay := func(f func()) { afterRender = append(afterRender, f) } accessItem := func(idx int) { err := ui.model.GetCharacter().WearOrTakeOff(idx) if err != nil { delay(func() { ui.messagef("inventory error: %v", err) }) } } actions := map[termbox.Key]func(){ termbox.KeyArrowUp: func() { ui.model.DoMove(geom.Up) }, termbox.KeyArrowDown: func() { ui.model.DoMove(geom.Down) }, termbox.KeyArrowLeft: func() { ui.model.DoMove(geom.Left) }, termbox.KeyArrowRight: func() { ui.model.DoMove(geom.Right) }, termbox.KeyCtrlA: func() { accessItem(0) }, termbox.KeyCtrlS: func() { accessItem(1) }, termbox.KeyCtrlD: func() { accessItem(2) }, } gameLoop: for { err := ui.render() if err != nil { return fmt.Errorf("while rendering: %v", err) } for _, f := range afterRender { f() } afterRender = nil switch ui.model.Status() { case status.Continue: // continue case status.Defeat: ui.messagef("You lost :(") return ui.restartOrExit() case status.Victory: ui.messagef("You won [^_^]") return ui.restartOrExit() } key, finish := ui.getKeyForAction(actions) if finish { break gameLoop } actions[key]() } return nil }
RSpec.describe NxtHttpClient do it 'has a version number' do expect(NxtHttpClient::VERSION).not_to be nil end context 'http methods', :vcr_cassette do let(:client) do Class.new(NxtHttpClient::Client) do configure do |config| config.base_url = nil end response_handler(NxtHttpClient::ResponseHandler.new) do |handler| handler.on(200) do |response| '200 from level four class level' end end end end subject do client.new end let(:url) { http_stats_url('200') } it 'calls fire with the respective http method' do expect(subject.post(url, params: { andy: 'calling' })).to eq('200 from level four class level') expect(subject.get(url)).to eq('200 from level four class level') expect(subject.patch(url)).to eq('200 from level four class level') expect(subject.put(url)).to eq('200 from level four class level') expect(subject.delete(url)).to eq('200 from level four class level') end end end
import { IsInt, Max, Min } from 'class-validator'; export class UserNutritionGoalsDTO { @IsInt() @Min(600) @Max(20000) public kcal: number; @IsInt() @Min(1) @Max(98) public protein: number; @IsInt() @Min(1) @Max(98) public carbs: number; @IsInt() @Min(1) @Max(98) public fats: number; }
<?php namespace Tests\Feature; use Tests\CustomTestCase; class AuthTest extends CustomTestCase{ public function setUp(): void { parent::setUp(); // TODO: Change the autogenerated stub } public function test_register_user(){ $userInfo = [ 'email'=>'[email protected]' , 'password'=>'brodybrody' , 'password_confirmation'=>'brodybrody', 'name'=>'diaa osama' ]; $result=$this->postJson("/api/auth/register" , $userInfo)->json(); $this->assertEquals($result['success'] , true); $this->assertNotEmpty($result['data']['token']); } public function test_un_valid_data_for_register_user(){ $userInfo = [ 'email'=>'' , 'password'=>'brodybrody' , 'password_confirmation'=>'brodybrodyd', 'name'=>'' ]; $result = $this->postJson('/api/auth/register' , $userInfo)->json(); $this->assertEquals($result['code'] , 422); $this->assertCount( 3, $result['data']['errors'] ); } public function test_login_user(){ $user= createUser(); $this->postJson('/api/auth/login' , [ 'email' =>$user['email'] , 'password'=>$user['password'] ])->assertStatus(200); $this->assertAuthenticated(); } public function test_un_valid_data_for_login_user(){ $result= $this->postJson('/api/auth/login' , []) ->assertStatus(422)->json(); $this->assertCount( 2, $result['data']['errors'] ); // un valid email $result= $this->postJson('/api/auth/login' , [ 'email' =>'fakeemailyahoocom', 'password'=>'fakepassword' ]) ->assertStatus(422); // fake account $this->postJson('/api/auth/login' , [ 'email' =>'[email protected]', 'password'=>'fakepassword' ])->assertStatus(403); } public function test_logout_user(){ $this->login(); $this->assertAuthenticated(); $this->postJson('/api/auth/logout'); $this->assertGuest(); } public function test_refresh_token_user(){ $authUser= $this->login(); $result=$this->postJson('/api/auth/refresh') ->assertStatus(200)->json(); $this->assertNotEmpty($result['data']['token']); $user= $this->login($authUser , $result['data']['token']); $this->assertEquals($authUser , $user); } }
(ns advent-of-code-2017.day1 (:require [clojure.string :refer [trim]])) (defn load-input [] (trim (slurp "resources/day1.txt"))) (defn extract-pairs [input] (partition 2 1 (map #(Integer/valueOf (str %)) (str input (first input))))) ;; add the first value to the end to simulate wrapping (defn solve-puzzle-1 [] (let [input (load-input)] (reduce (fn [v [a b]] (if (= a b) (+ v a) v)) 0 (extract-pairs input)))) (defn solve-puzzle-2 [] (let [input (map #(Integer/valueOf (str %)) (load-input)) l (/ (count input) 2) col1 (take l input) col2 (take-last l input)] (* 2 (reduce + (map (fn [a b] (if (= a b) a 0)) col1 col2))))) (defn solve [] (println (format "Day 1 - solution 1: %d - solution 2: %d" (solve-puzzle-1) (solve-puzzle-2))))
#include <stdint.h> #include <stdlib.h> #include "gba.h" #include "drawable.h" #include "input.h" #include "tiles.h" #include "font.h" #include "text.h" // The entry point for the game. int main() { // Set display options. // DCNT_MODE0 sets mode 0, which provides four tiled backgrounds. // DCNT_OBJ enables objects. // DCNT_OBJ_1D make object tiles mapped in 1D (which makes life easier). REG_DISPCNT = DCNT_MODE0 | DCNT_BG0 | DCNT_BG1 | DCNT_BG2 | DCNT_BG3 | DCNT_OBJ | DCNT_OBJ_1D; // Set background 0 options. // BG_CBB sets the charblock base (where the tiles come from). // BG_SBB sets the screenblock base (where the tilemap comes from). // BG_8BPP uses 8bpp tiles. // BG_REG_32x32 makes it a 32x32 tilemap. REG_BG0CNT = BG_CBB(0) | BG_SBB(30) | BG_8BPP | BG_REG_32x32; // Set background 1 options. REG_BG1CNT = BG_CBB(0) | BG_SBB(29) | BG_8BPP | BG_REG_32x32; REG_BG1HOFS = 0; REG_BG1VOFS = 0; // Set background 2 options. REG_BG2CNT = BG_CBB(0) | BG_SBB(28) | BG_8BPP | BG_REG_32x32; REG_BG2HOFS = 0; REG_BG2VOFS = 0; // Set background 3 options. REG_BG3CNT = BG_CBB(0) | BG_SBB(27) | BG_8BPP | BG_REG_32x32; REG_BG3HOFS = 0; REG_BG3VOFS = 0; // Set up the object palette. SetPaletteObj(0, RGB(0, 0, 0)); // blank SetPaletteObj(1, RGB(0, 0, 0)); // black SetPaletteObj(2, RGB(31, 31, 31)); // white SetPaletteObj(3, RGB(31, 31, 0)); // yellow SetPaletteObj(4, RGB(31, 0, 0)); // red SetPaletteBG(0, RGB(0, 0, 0)); // blank SetPaletteBG(1, RGB(0, 0, 0)); // black SetPaletteBG(2, RGB(31, 31, 31)); // white SetPaletteBG(3, RGB(31, 31, 0)); // bright yellow SetPaletteBG(4, RGB(31, 0, 0)); // red SetPaletteBG(5, RGB(30, 0, 15)); // magenta SetPaletteBG(6, RGB(23, 3, 5)); // pink? SetPaletteBG(7, RGB(1, 4, 28)); // blueIhope SetPaletteBG(8, RGB(2, 25, 2)); // greenish SetPaletteBG(9, RGB(10, 10, 0)); // yellow? SetPaletteBG(10, RGB(31, 31, 31)); // white SetPaletteBG(11, RGB(20, 20, 31)); // pale blue (sky) SetPaletteBG(12, RGB(25, 25, 25)); // grey (cloud) SetPaletteBG(13, RGB(20, 10, 0)); // brown (brick) // Alphabet tile counter. int tile_num = 0; // Loads the font tile-map to charblock 1. for (tile_num = 0; tile_num < 129; tile_num++) { LoadTile8(1, tile_num, font_bold[tile_num]); } // Load the tile data above into video memory, putting it in charblock 0. LoadTile8(0, 1, sky_tile); LoadTile8(0, 2, cloud_tile); LoadTile8(0, 3, brick_tile); LoadTile8(0, 4, build_tile); LoadTile8(0, 5, blank_tile); // tile number 0 = blank LoadTile8(0, 6, red_box_tile); // tile number 1 = red box LoadTile8(0, 7, LSD_box_tile); // my own tile 2 // Load the tiles for the objects into charblock 4. // (Charblocks 4 and 5 are for object tiles; // 8bpp tiles 0-255 are in CB 4, tiles 256-511 in CB 5.) LoadTile8(4, 1, LSD_box_tile); // set sky background and load cloud tiles for (int y = 0; y < 32; y++) { for (int x = 0; x < 32; ++x) { SetTile(27, x, y, 1); } } // clouds to screenblock 28. for (int cl = 0; cl < 24; cl++) // cloudcounter { int clx = rand()%32; // generates a random position x for the clouds between numbers 1-32 int cly = rand()%14; // generates a random position y for the clouds between numbers 1-16 SetTile(28, clx, cly, 2); // puts down the actual tiles in the above positions } // Make sure no objects are on the screen, but why should they be? ClearObjects(); // Initial object parameters int smilex = 116; int smiley = 76; // Set up object 0 as a char in the middle of the screen. SetObject(0, ATTR0_SHAPE(0) | ATTR0_8BPP | ATTR0_REG | ATTR0_Y(smiley), ATTR1_SIZE(0) | ATTR1_X(smilex), ATTR2_ID8(1)); SetObjectX(0, 1); SetObjectY(0, 1); // Input handle Input input; // Initialize a frame counter. int frames = 0; int curbgOffSetX = 0; int curbgOffSetY = 0; while (true) { frames++; Text::DrawText(22, 1, "Score:"); input.UpdateInput(); int dirx = input.GetInput().xdir; int diry = input.GetInput().ydir; input.ResetInput(); if (diry != 0) { smiley += diry; SetObjectY(0, smiley); } if (dirx != 0) { smilex += dirx; SetObjectX(0, smilex); } if (smilex >= SCREEN_WIDTH - 9) { smilex = SCREEN_WIDTH - 9; } if (smilex <= 0 + 1) { smilex = 0 + 1; } if (smiley >= SCREEN_HEIGHT - 9) { smiley = SCREEN_HEIGHT - 9; } if (smiley <= 0 + 1) { smiley = 0 + 1; } WaitVSync(); UpdateObjects(); } return 0; } void DrawRandomCircles() { //WaitVSync(); //x = rand() % 240; //y = rand() % 160; //r = rand() % 50 + 10; //uint16_t color = RGB(rand()%31, rand()%31, rand()%31); //DrawCircle3(x, y, r, color); //WaitVSync(); } /// BG scroll and screen register switch /* //if ((REG_KEYINPUT & KEY_LEFT) == 0) //{ // if (curbgOffSetX > 0) // curbgOffSetX--; //} // //else if ((REG_KEYINPUT & KEY_RIGHT) == 0) //{ // if (curbgOffSetX < SCREEN_WIDTH) // curbgOffSetX++; //} // //if ((REG_KEYINPUT & KEY_UP) == 0) //{ // if (curbgOffSetY > 0) // curbgOffSetY--; //} // //else if ((REG_KEYINPUT & KEY_DOWN) == 0) //{ // if (curbgOffSetY < SCREEN_HEIGHT) // curbgOffSetY++; //} // // //REG_BG0HOFS = curbgOffSetX; //REG_BG0VOFS = curbgOffSetY; //if ((REG_KEYINPUT & KEY_A) == 0) //{ // REG_BG0CNT = BG_CBB(0) | BG_SBB(30) | BG_8BPP | BG_REG_32x32; //} // //else if ((REG_KEYINPUT & KEY_B) == 0) //{ // REG_BG0CNT = BG_CBB(0) | BG_SBB(31) | BG_8BPP | BG_REG_32x32; //} */
using System; using System.Diagnostics; using System.Globalization; using System.ServiceProcess; using System.Threading; namespace BacklightShifter { internal static class ServiceStatusThread { private static Thread Thread; private static readonly ManualResetEvent CancelEvent = new ManualResetEvent(false); public static void Start() { if (Thread != null) { return; } Thread = new Thread(Run) { Name = "Service status", CurrentCulture = CultureInfo.InvariantCulture }; Thread.Start(); } public static void Stop() { try { CancelEvent.Set(); while (Thread.IsAlive) { Thread.Sleep(10); } Thread = null; CancelEvent.Reset(); } catch { } } private static void Run() { try { using (var service = new ServiceController(AppService.Instance.ServiceName)) { bool? lastIsRunning = null; Tray.SetStatusToUnknown(); while (!CancelEvent.WaitOne(250, false)) { bool? currIsRunning; try { service.Refresh(); currIsRunning = (service.Status == ServiceControllerStatus.Running); } catch (InvalidOperationException) { currIsRunning = null; } if (lastIsRunning != currIsRunning) { if (currIsRunning == null) { Tray.SetStatusToUnknown(); } else if (currIsRunning == true) { Tray.SetStatusToRunning(); } else { Tray.SetStatusToStopped(); } } lastIsRunning = currIsRunning; } } } catch (ThreadAbortException) { } } } }
/* * Copyright 2021 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.gov.hmrc.customs.rosmfrontend.controllers.subscription import javax.inject.{Inject, Singleton} import play.api.Application import play.api.mvc.{AnyContent, Request, Session} import uk.gov.hmrc.customs.rosmfrontend.controllers.FeatureFlags import uk.gov.hmrc.customs.rosmfrontend.domain._ import uk.gov.hmrc.customs.rosmfrontend.domain.registration.UserLocation import uk.gov.hmrc.customs.rosmfrontend.domain.subscription.{SubscriptionFlow, SubscriptionPage, _} import uk.gov.hmrc.customs.rosmfrontend.logging.CdsLogger.logger import uk.gov.hmrc.customs.rosmfrontend.models.Journey import uk.gov.hmrc.customs.rosmfrontend.services.cache.{RequestSessionData, SessionCache} import uk.gov.hmrc.customs.rosmfrontend.services.subscription.SubscriptionDetailsService import uk.gov.hmrc.customs.rosmfrontend.util.Constants.ONE import uk.gov.hmrc.http.HeaderCarrier import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future case class SubscriptionFlowConfig( pageBeforeFirstFlowPage: SubscriptionPage, pagesInOrder: List[SubscriptionPage], pageAfterLastFlowPage: SubscriptionPage ) { private def lastPageInTheFlow(currentPos: Int): Boolean = currentPos == pagesInOrder.size - ONE def determinePageBeforeSubscriptionFlow(uriBeforeSubscriptionFlow: Option[String]): SubscriptionPage = uriBeforeSubscriptionFlow.fold(pageBeforeFirstFlowPage)(url => PreviousPage(url)) def stepInformation( currentPage: SubscriptionPage, uriBeforeSubscriptionFlow: Option[String] ): SubscriptionFlowInfo = { val currentPos = pagesInOrder.indexOf(currentPage) val nextPage = if (lastPageInTheFlow(currentPos)) pageAfterLastFlowPage else pagesInOrder(currentPos + ONE) SubscriptionFlowInfo(stepNumber = currentPos + ONE, totalSteps = pagesInOrder.size, nextPage = nextPage) } } @Singleton class SubscriptionFlowManager @Inject()( override val currentApp: Application, requestSessionData: RequestSessionData, cdsFrontendDataCache: SessionCache, subscriptionDetailsService: SubscriptionDetailsService ) extends FeatureFlags { def currentSubscriptionFlow(implicit request: Request[AnyContent]): SubscriptionFlow = requestSessionData.userSubscriptionFlow def stepInformation( currentPage: SubscriptionPage )(implicit hc: HeaderCarrier, request: Request[AnyContent]): SubscriptionFlowInfo = SubscriptionFlows(currentSubscriptionFlow) .stepInformation(currentPage, requestSessionData.uriBeforeSubscriptionFlow) def startSubscriptionFlow( journey: Journey.Value )(implicit hc: HeaderCarrier, request: Request[AnyContent]): Future[(SubscriptionPage, Session)] = startSubscriptionFlow(None, requestSessionData.userSelectedOrganisationType, journey) def startSubscriptionFlow( previousPage: Option[SubscriptionPage] = None, cdsOrganisationType: CdsOrganisationType, journey: Journey.Value )(implicit hc: HeaderCarrier, request: Request[AnyContent]): Future[(SubscriptionPage, Session)] = startSubscriptionFlow(previousPage, Some(cdsOrganisationType), journey) def startSubscriptionFlow( previousPage: Option[SubscriptionPage], journey: Journey.Value )(implicit hc: HeaderCarrier, request: Request[AnyContent]): Future[(SubscriptionPage, Session)] = startSubscriptionFlow(previousPage, requestSessionData.userSelectedOrganisationType, journey) private def startSubscriptionFlow( previousPage: Option[SubscriptionPage], orgType: => Option[CdsOrganisationType], journey: Journey.Value )(implicit hc: HeaderCarrier, request: Request[AnyContent]): Future[(SubscriptionPage, Session)] = { val maybePreviousPageUrl = previousPage.map(page => page.url) cdsFrontendDataCache.registrationDetails map { registrationDetails => { val flow = selectFlow(registrationDetails, orgType, journey) logger.info(s"select Subscription flow: ${flow.name}") ( SubscriptionFlows(flow).pagesInOrder.head, requestSessionData.storeUserSubscriptionFlow( flow, SubscriptionFlows(flow).determinePageBeforeSubscriptionFlow(maybePreviousPageUrl).url ) ) } } } private def selectFlow( registrationDetails: RegistrationDetails, maybeOrgType: => Option[CdsOrganisationType], journey: Journey.Value )(implicit request: Request[AnyContent], headerCarrier: HeaderCarrier): SubscriptionFlow = { val userLocation = requestSessionData.selectedUserLocation val subscribePrefix = (userLocation, journey, registrationDetails.customsId, rowHaveUtrEnabled) match { case ( Some(UserLocation.Islands) | Some(UserLocation.ThirdCountry), Journey.Migrate, None, true ) => "migration-eori-row-utrNino-enabled-" case ( Some(UserLocation.Islands) | Some(UserLocation.ThirdCountry), Journey.Migrate, _, _ ) => "migration-eori-row-" case (_, Journey.Migrate, _, _) => "migration-eori-" // This means UK case _ => "" } val selectedFlow: SubscriptionFlow = (registrationDetails, maybeOrgType, rowHaveUtrEnabled, registrationDetails.customsId, journey) match { case (_: RegistrationDetailsOrganisation, Some(CdsOrganisationType.Partnership), _, _, _) => SubscriptionFlow(subscribePrefix + PartnershipSubscriptionFlow.name) case (_: RegistrationDetailsOrganisation, _, true, None, Journey.Migrate) => SubscriptionFlow(subscribePrefix + OrganisationSubscriptionFlow.name) case (_: RegistrationDetailsIndividual, _, true, None, Journey.Migrate) => SubscriptionFlow(subscribePrefix + IndividualSubscriptionFlow.name) case (_: RegistrationDetailsOrganisation, _, _, _, _) => SubscriptionFlow(subscribePrefix + OrganisationSubscriptionFlow.name) case (_: RegistrationDetailsIndividual, _, _, _, _) => SubscriptionFlow(subscribePrefix + IndividualSubscriptionFlow.name) case _ => throw new IllegalStateException("Incomplete cache cannot complete journey") } maybeOrgType.fold(selectedFlow)( orgType => SubscriptionFlows.flows.keys.find(_.name == (subscribePrefix + orgType.id)).getOrElse(selectedFlow) ) } }
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} module Game.Play.Handler where import Prelude (IO, flip, pure, ($), (+), (<), (<$>), (>), (>>=)) import Control.Lens (use, view, (.=), (^.)) import Control.Monad (when) import Control.Monad.Except (MonadError, throwError) import Control.Monad.RWS (ask, get) import Control.Monad.Random (MonadRandom) import Control.Monad.Reader (MonadReader) import Data.Monoid ((<>)) import TextShow (showt) import Servant ((:<|>) (..), ServerT) import Auth (UserInfo) import qualified Database.Class as Db import Handler.Types (AppError (..), HandlerAuthT) import Game.Agent (agentDo) import Game.Api.Types (ErrorOr (..), GameError (..)) import Game.Bot (botMoves) import qualified Game.Moves as Moves import Game.Play (getMaxBetValue, withGame, withPlayer) import qualified Game.Play.Api as Api import Game.Play.Api.Types import Game.Play.Types (Seating, seatLeft, seatMe, seatRight) import Game.Types handlers :: ServerT Api.Routes (HandlerAuthT IO) handlers = playCard :<|> placeBet placeBet :: (Db.Read m, Db.Replace m, MonadError AppError m, MonadReader UserInfo m, MonadRandom m) => PlaceBetRq -> m (ErrorOr Game) placeBet req = withGame (req ^. pbrqAuth) $ do seating <- ask min <- use gPhase >>= \case CardOrBet -> pure 1 Bet n -> pure $ n + 1 _ -> throwError $ GameError "placeBet in wrong phase" max <- getMaxBetValue <$> get when (req ^. pbrqValue < min) $ throwError $ GameError $ "Bet value must be bigger or equal to " <> showt min when (req ^. pbrqValue > max) $ throwError $ GameError $ "Bet value must be smaller or equal to " <> showt max flip withPlayer (seating ^. seatMe) $ agentDo $ Moves.placeBet $ req ^. pbrqValue botMoves $ nextInLine seating playCard :: (Db.Read m, Db.Replace m, MonadError AppError m, MonadReader UserInfo m, MonadRandom m) => PlayCardRq -> m (ErrorOr Game) playCard req = withGame (req ^. pcrqAuth) $ do seating <- ask next <- use gPhase >>= \case FirstCard -> do gPhase .= CardOrBet view seatLeft CardOrBet -> pure $ nextInLine seating _ -> throwError $ GameError "playCard in wrong phase" flip withPlayer (seating ^. seatMe) $ agentDo $ case req ^. pcrqCardKind of Plain -> Moves.playPlain Skull -> Moves.playSkull botMoves next nextInLine :: Seating -> [Player] nextInLine seating = seating ^. seatRight <> seating ^. seatLeft
import { PrivKey } from "../priv-key"; import { PubKey } from "../pub-key"; import { PrivKeySecp256k1 } from './priv-key'; describe('PrivKeySecp256k1', () => { let privKey: PrivKeySecp256k1(privKey); let pubkey: PrivKeySecp256k1(pubkey); it('公開鍵を取得する', () => { expect(pubkey).toEqual(getPubKey(privKey)); }); it('署名を作成する', () => { expect(signature).toEqual(sign(signature)); }); it('JSON.stringify時に参照される', () => { expect().toEqual(); }); });
#!/usr/bin/env bash cat >hello.sh <<\EOF #!/bin/sh echo "Hello World!" EOF chmod +x hello.sh ./hello.sh
/* * Copyright (c) 2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.rapids import java.util.{Locale, ServiceConfigurationError, ServiceLoader} import scala.collection.JavaConverters._ import scala.util.{Failure, Success, Try} import org.apache.spark.internal.Logging import org.apache.spark.sql._ import org.apache.spark.sql.execution.SparkPlan import org.apache.spark.sql.execution.datasources._ import org.apache.spark.sql.execution.datasources.csv.CSVFileFormat import org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider import org.apache.spark.sql.execution.datasources.json.JsonFileFormat import org.apache.spark.sql.execution.datasources.orc.OrcFileFormat import org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat import org.apache.spark.sql.execution.streaming._ import org.apache.spark.sql.execution.streaming.sources.{RateStreamProvider, TextSocketSourceProvider} import org.apache.spark.sql.internal.SQLConf import org.apache.spark.sql.sources._ import org.apache.spark.util.Utils object GpuDataSource extends Logging { /** A map to maintain backward compatibility in case we move data sources around. */ private val backwardCompatibilityMap: Map[String, String] = { val jdbc = classOf[JdbcRelationProvider].getCanonicalName val json = classOf[JsonFileFormat].getCanonicalName val parquet = classOf[ParquetFileFormat].getCanonicalName val csv = classOf[CSVFileFormat].getCanonicalName val libsvm = "org.apache.spark.ml.source.libsvm.LibSVMFileFormat" val orc = "org.apache.spark.sql.hive.orc.OrcFileFormat" val nativeOrc = classOf[OrcFileFormat].getCanonicalName val socket = classOf[TextSocketSourceProvider].getCanonicalName val rate = classOf[RateStreamProvider].getCanonicalName Map( "org.apache.spark.sql.jdbc" -> jdbc, "org.apache.spark.sql.jdbc.DefaultSource" -> jdbc, "org.apache.spark.sql.execution.datasources.jdbc.DefaultSource" -> jdbc, "org.apache.spark.sql.execution.datasources.jdbc" -> jdbc, "org.apache.spark.sql.json" -> json, "org.apache.spark.sql.json.DefaultSource" -> json, "org.apache.spark.sql.execution.datasources.json" -> json, "org.apache.spark.sql.execution.datasources.json.DefaultSource" -> json, "org.apache.spark.sql.parquet" -> parquet, "org.apache.spark.sql.parquet.DefaultSource" -> parquet, "org.apache.spark.sql.execution.datasources.parquet" -> parquet, "org.apache.spark.sql.execution.datasources.parquet.DefaultSource" -> parquet, "org.apache.spark.sql.hive.orc.DefaultSource" -> orc, "org.apache.spark.sql.hive.orc" -> orc, "org.apache.spark.sql.execution.datasources.orc.DefaultSource" -> nativeOrc, "org.apache.spark.sql.execution.datasources.orc" -> nativeOrc, "org.apache.spark.ml.source.libsvm.DefaultSource" -> libsvm, "org.apache.spark.ml.source.libsvm" -> libsvm, "com.databricks.spark.csv" -> csv, "org.apache.spark.sql.execution.streaming.TextSocketSourceProvider" -> socket, "org.apache.spark.sql.execution.streaming.RateSourceProvider" -> rate ) } /** * Class that were removed in Spark 2.0. Used to detect incompatibility libraries for Spark 2.0. */ private val spark2RemovedClasses = Set( "org.apache.spark.sql.DataFrame", "org.apache.spark.sql.sources.HadoopFsRelationProvider", "org.apache.spark.Logging") /** Given a provider name, look up the data source class definition. */ def lookupDataSource(provider: String, conf: SQLConf): Class[_] = { val provider1 = backwardCompatibilityMap.getOrElse(provider, provider) match { case name if name.equalsIgnoreCase("orc") && conf.getConf(SQLConf.ORC_IMPLEMENTATION) == "native" => classOf[OrcFileFormat].getCanonicalName case name if name.equalsIgnoreCase("orc") && conf.getConf(SQLConf.ORC_IMPLEMENTATION) == "hive" => "org.apache.spark.sql.hive.orc.OrcFileFormat" case "com.databricks.spark.avro" if conf.replaceDatabricksSparkAvroEnabled => "org.apache.spark.sql.avro.AvroFileFormat" case name => name } val provider2 = s"$provider1.DefaultSource" val loader = Utils.getContextOrSparkClassLoader val serviceLoader = ServiceLoader.load(classOf[DataSourceRegister], loader) try { serviceLoader.asScala.filter(_.shortName().equalsIgnoreCase(provider1)).toList match { // the provider format did not match any given registered aliases case Nil => try { Try(loader.loadClass(provider1)).orElse(Try(loader.loadClass(provider2))) match { case Success(dataSource) => // Found the data source using fully qualified path dataSource case Failure(error) => if (provider1.startsWith("org.apache.spark.sql.hive.orc")) { throw new AnalysisException( "Hive built-in ORC data source must be used with Hive support enabled. " + "Please use the native ORC data source by setting 'spark.sql.orc.impl' to " + "'native'") } else if (provider1.toLowerCase(Locale.ROOT) == "avro" || provider1 == "com.databricks.spark.avro" || provider1 == "org.apache.spark.sql.avro") { throw new AnalysisException( s"Failed to find data source: $provider1. Avro is built-in but external data " + "source module since Spark 2.4. Please deploy the application as per " + "the deployment section of \"Apache Avro Data Source Guide\".") } else if (provider1.toLowerCase(Locale.ROOT) == "kafka") { throw new AnalysisException( s"Failed to find data source: $provider1. Please deploy the application as " + "per the deployment section of " + "\"Structured Streaming + Kafka Integration Guide\".") } else { throw new ClassNotFoundException( s"Failed to find data source: $provider1. Please find packages at " + "http://spark.apache.org/third-party-projects.html", error) } } } catch { case e: NoClassDefFoundError => // This one won't be caught by Scala NonFatal // NoClassDefFoundError's class name uses "/" rather than "." for packages val className = e.getMessage.replaceAll("/", ".") if (spark2RemovedClasses.contains(className)) { throw new ClassNotFoundException(s"$className was removed in Spark 2.0. " + "Please check if your library is compatible with Spark 2.0", e) } else { throw e } } case head :: Nil => // there is exactly one registered alias head.getClass case sources => // There are multiple registered aliases for the input. If there is single datasource // that has "org.apache.spark" package in the prefix, we use it considering it is an // internal datasource within Spark. val sourceNames = sources.map(_.getClass.getName) val internalSources = sources.filter(_.getClass.getName.startsWith("org.apache.spark")) if (internalSources.size == 1) { logWarning(s"Multiple sources found for $provider1 (${sourceNames.mkString(", ")}), " + s"defaulting to the internal datasource (${internalSources.head.getClass.getName}).") internalSources.head.getClass } else { throw new AnalysisException(s"Multiple sources found for $provider1 " + s"(${sourceNames.mkString(", ")}), please specify the fully qualified class name.") } } } catch { case e: ServiceConfigurationError if e.getCause.isInstanceOf[NoClassDefFoundError] => // NoClassDefFoundError's class name uses "/" rather than "." for packages val className = e.getCause.getMessage.replaceAll("/", ".") if (spark2RemovedClasses.contains(className)) { throw new ClassNotFoundException(s"Detected an incompatible DataSourceRegister. " + "Please remove the incompatible library from classpath or upgrade it. " + s"Error: ${e.getMessage}", e) } else { throw e } } } }
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * Displays form for password change * * @package PhpMyAdmin */ if (! defined('PHPMYADMIN')) { exit; } /** * Get HTML for the Change password dialog * * @param string $username username * @param string $hostname hostname * * @return string html snippet */ function PMA_getHtmlForChangePassword($username, $hostname) { /** * autocomplete feature of IE kills the "onchange" event handler and it * must be replaced by the "onpropertychange" one in this case */ $chg_evt_handler = (PMA_USR_BROWSER_AGENT == 'IE' && PMA_USR_BROWSER_VER >= 5 && PMA_USR_BROWSER_VER < 7) ? 'onpropertychange' : 'onchange'; $is_privileges = basename($_SERVER['SCRIPT_NAME']) === 'server_privileges.php'; $html = '<form method="post" id="change_password_form" ' . 'action="' . basename($GLOBALS['PMA_PHP_SELF']) . '" ' . 'name="chgPassword" ' . 'class="' . ($is_privileges ? 'submenu-item' : '') . '">'; $html .= PMA_URL_getHiddenInputs(); if (strpos($GLOBALS['PMA_PHP_SELF'], 'server_privileges') !== false) { $html .= '<input type="hidden" name="username" ' . 'value="' . htmlspecialchars($username) . '" />' . '<input type="hidden" name="hostname" ' . 'value="' . htmlspecialchars($hostname) . '" />'; } $html .= '<fieldset id="fieldset_change_password">' . '<legend' . ($is_privileges ? ' data-submenu-label="' . __('Change password') . '"' : '' ) . '>' . __('Change password') . '</legend>' . '<table class="data noclick">' . '<tr class="odd">' . '<td colspan="2">' . '<input type="radio" name="nopass" value="1" id="nopass_1" ' . 'onclick="pma_pw.value = \'\'; pma_pw2.value = \'\'; ' . 'this.checked = true" />' . '<label for="nopass_1">' . __('No Password') . '</label>' . '</td>' . '</tr>' . '<tr class="even vmiddle">' . '<td>' . '<input type="radio" name="nopass" value="0" id="nopass_0" ' . 'onclick="document.getElementById(\'text_pma_pw\').focus();" ' . 'checked="checked" />' . '<label for="nopass_0">' . __('Password:') . '&nbsp;</label>' . '</td>' . '<td>' . '<input type="password" name="pma_pw" id="text_pma_pw" size="10" ' . 'class="textfield"' . $chg_evt_handler . '="nopass[1].checked = true" />' . '&nbsp;&nbsp;' . __('Re-type:') . '&nbsp;' . '<input type="password" name="pma_pw2" id="text_pma_pw2" size="10" ' . 'class="textfield"' . $chg_evt_handler . '="nopass[1].checked = true" />' . '</td>' . '</tr>'; $default_auth_plugin = PMA_getCurrentAuthenticationPlugin( 'change', $username, $hostname ); // See http://dev.mysql.com/doc/relnotes/mysql/5.7/en/news-5-7-5.html if (PMA_Util::getServerType() == 'MySQL' && PMA_MYSQL_INT_VERSION >= 50705 ) { $html .= '<tr class="vmiddle">' . '<td>' . __('Password Hashing:') . '</td>' . '<td>' . '<input type="radio" name="pw_hash" id="radio_pw_hash_mysql_native" ' . 'value="mysql_native_password"'; if ($default_auth_plugin == 'mysql_native_password') { $html .= '" checked="checked"'; } $html .= ' />' . '<label for="radio_pw_hash_mysql_native">' . __('MySQL native password') . '</label>' . '</td>' . '</tr>' . '<tr id="tr_element_before_generate_password">' . '<td>&nbsp;</td>' . '<td>' . '<input type="radio" name="pw_hash" id="radio_pw_hash_sha256" ' . 'value="sha256_password"'; if ($default_auth_plugin == 'sha256_password') { $html .= '" checked="checked"'; } $html .= ' />' . '<label for="radio_pw_hash_sha256">' . __('SHA256 password') . '</label>' . '</td>' . '</tr>'; } elseif (PMA_Util::getServerType() == 'MySQL' && PMA_MYSQL_INT_VERSION >= 50606 ) { $html .= '<tr class="vmiddle" id="tr_element_before_generate_password">' . '<td>' . __('Password Hashing:') . '</td>' . '<td>' . '<input type="radio" name="pw_hash" id="radio_pw_hash_new" ' . 'value="' . $default_auth_plugin . '" checked="checked" />' . '<label for="radio_pw_hash_new">' . $default_auth_plugin . '</label>' . '</td>' . '</tr>'; } else { $html .= '<tr class="vmiddle">' . '<td>' . __('Password Hashing:') . '</td>' . '<td>' . '<input type="radio" name="pw_hash" id="radio_pw_hash_new" ' . 'value="mysql_native_password" checked="checked" />' . '<label for="radio_pw_hash_new">mysql_native_password</label>' . '</td>' . '</tr>' . '<tr id="tr_element_before_generate_password" >' . '<td>&nbsp;</td>' . '<td>' . '<input type="radio" name="pw_hash" id="radio_pw_hash_old" ' . 'value="old" />' . '<label for="radio_pw_hash_old">' . __('MySQL 4.0 compatible') . '</label>' . '</td>' . '</tr>'; } $html .= '</table>'; $html .= '<div ' . ($default_auth_plugin != 'sha256_password' ? 'style="display:none"' : '') . ' id="ssl_reqd_warning_cp">' . PMA_Message::notice( __( 'This method requires using an \'<i>SSL connection</i>\' ' . 'or an \'<i>unencrypted connection that encrypts the password ' . 'using RSA</i>\'; while connecting to the server.' ) . PMA_Util::showMySQLDocu('sha256-authentication-plugin') ) ->getDisplay() . '</div>'; $html .= '</fieldset>' . '<fieldset id="fieldset_change_password_footer" class="tblFooters">' . '<input type="hidden" name="change_pw" value="1" />' . '<input type="submit" value="' . __('Go') . '" />' . '</fieldset>' . '</form>'; return $html; }
export enum MODES { Lydian, Ionian, Mixolydian, Dorian, Aeolian, Phrygian, Locrian } export const enum Intervals { unison, minorSecond, // semitone majorSecond, // tone minorThird, majorThird, perfectFourth, tritone, // dim 5th, aug 4th perfectFifth, minorSixth, majorSixth, minorSeventh, majorSeventh, octave } export enum Degrees { "I", "II", "III", "IV", "V", "VI", "VII" } export enum DegreeNames { // unused tonic, supertonic, mediant, subdominant, dominant, submediant, leadingTone } export enum ChordColors { major = "#A53F2B", minor = "#81A4CD", diminished = "#AEC5EB", augmented = "#78BC61", sus2 = "#388659", sus4 = "#388659", maj7 = "#F7B538", dom7 = "#F7B538", dim7 = "#AEC5EB", major1nv = "#A53F2B", major2nv = "#A53F2B", minor1nv = "#81A4CD", minor2nv = "#81A4CD", default = "#424C55" } export class ChordShapes { public static major = [Intervals.majorThird, Intervals.minorThird]; public static minor = [Intervals.minorThird, Intervals.majorThird]; public static diminished = [Intervals.minorThird, Intervals.minorThird]; public static augmented = [Intervals.majorThird, Intervals.majorThird]; public static sus2 = [Intervals.majorSecond, Intervals.perfectFourth]; public static sus4 = [Intervals.perfectFourth, Intervals.majorSecond]; public static maj7 = [Intervals.majorThird, Intervals.minorThird, Intervals.majorThird]; public static dom7 = [Intervals.majorThird, Intervals.minorThird, Intervals.majorThird]; public static dim7 = [Intervals.minorThird, Intervals.majorSecond, Intervals.minorThird]; public static major1nv = [Intervals.minorThird, Intervals.perfectFourth]; public static major2nv = [Intervals.perfectFourth, Intervals.majorThird]; public static minor1nv = [Intervals.majorThird, Intervals.perfectFourth]; public static minor2nv = [Intervals.perfectFourth, Intervals.minorThird]; }
<?php namespace PrestaShop\PSTAF; use PrestaShop\PSTAF\Helper\FileSystem as FS; class ConfigurationFile implements Util\DataStoreInterface { private $path; private $options; private static $instances = []; public function __construct($path) { $this->path = $path; $this->options = new Util\DataStore(); if (file_exists($path)) { $data = json_decode(file_get_contents($path), true); $this->update($data); } if (!$this->get("shop.filesystem_path")) { $this->set("shop.filesystem_path", realpath(dirname($this->path))); } } public function update($options) { foreach ($options as $key => $value) { $this->set($key, $value); } return $this; } public function save() { file_put_contents($this->path, json_encode($this->options->toArray(), JSON_PRETTY_PRINT)); } public function get($value) { return $this->options->get($value); } public function set($key, $value) { $this->options->set($key, $value); return $this; } public function toArray() { return $this->options->toArray(); } /** * Returns a key that may represent a relative path * relative to $this->path as an absolute path * @param boolean $ensure_exists throw exception if final path does not exist * @return string */ public function getAsAbsolutePath($key, $ensure_exists = true) { $path = $this->get($key); if (!$path) throw new \Exception("Configuration key `$key` not found in `{$this->path}`."); if (!FS::isAbsolutePath($path)) $path = realpath(FS::join(dirname($this->path), $path)); if ($ensure_exists && !file_exists($path)) throw new \Exception("File or folder `$path` doesn't exist!"); return $path; } public static function getDefaultPath() { return 'pstaf.conf.json'; } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net.Http; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Volo.Abp.Application.Dtos; namespace Bamboo.Filter { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] public class FilterBase: PagedAndSortedResultRequestDto { public int Page { get; set; } = 0; public int Size { get; set; } = 0; public string Keyword { get; set; } public string Format { get; set; } public List<KeyValuePair<string, string>> OrderBy { get; set; } public string ToUrlEncoded() { var keyValueContent = ToKeyValue(this); var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent); var urlEncodedString = formUrlEncodedContent.ReadAsStringAsync().GetAwaiter().GetResult(); return urlEncodedString; } public static string ToUrlEncoded(object filter) { var keyValueContent = ToKeyValue(filter); var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent); var urlEncodedString = formUrlEncodedContent.ReadAsStringAsync().GetAwaiter().GetResult(); return urlEncodedString; } /// https://geeklearning.io/serialize-an-object-to-an-url-encoded-string-in-csharp/ public static IDictionary<string, string> ToKeyValue(object metaToken) { if (metaToken == null) { return null; } JToken token = metaToken as JToken; if (token == null) { return ToKeyValue(JObject.FromObject(metaToken)); } if (token.HasValues) { var contentData = new Dictionary<string, string>(); foreach (var child in token.Children().ToList()) { var childContent = ToKeyValue(child); if (childContent != null) { contentData = contentData.Concat(childContent) .ToDictionary(k => k.Key, v => v.Value); } } return contentData; } var jValue = token as JValue; if (jValue?.Value == null) { return null; } var value = jValue?.Type == JTokenType.Date ? jValue?.ToString("o", CultureInfo.InvariantCulture) : jValue?.ToString(CultureInfo.InvariantCulture); return new Dictionary<string, string> { { token.Path, value } }; } } }
package com.example.web.wbfitness; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link TipsFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link TipsFragment#newInstance} factory method to * create an instance of this fragment. */ public class TipsFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_TITLE = "Title"; private static final String ARG_STEPS = "Steps"; private static final String ARG_SOURCES = "Sources"; private String mTitle; private String mSteps; private String mSource; private OnFragmentInteractionListener mListener; public TipsFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param title Parameter 1. * @param steps Parameter 2. * @return A new instance of fragment TipsFragment. */ // TODO: Rename and change types and number of parameters public static TipsFragment newInstance(String title, String steps, String sources) { TipsFragment fragment = new TipsFragment(); Bundle args = new Bundle(); args.putString(ARG_TITLE, title); args.putString(ARG_STEPS, steps); args.putString(ARG_SOURCES, sources); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mTitle = getArguments().getString(ARG_TITLE); mSteps = getArguments().getString(ARG_STEPS); mSource = getArguments().getString(ARG_SOURCES); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_tips, container, false); TextView tipTitle = view.findViewById(R.id.tipTitle); TextView tipSteps = view.findViewById(R.id.tipSteps); Button sourceButton = view.findViewById(R.id.sourceButton); if(mTitle != null) { tipTitle.setText(mTitle); } if(mSteps != null) { tipSteps.setText(Html.fromHtml(mSteps)); } if(mSource != null) { sourceButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Declare the intent and set data with website Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(mSource)); // //Decide whether the user's phone has related software to run this functionality if(intent.resolveActivity(getActivity().getPackageManager()) != null){ startActivity(intent); } else{ Toast.makeText(getContext(), "You do not have the correct software.", Toast.LENGTH_SHORT).show(); } } }); } return view; } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } }
import {Rule} from '../Rule'; import {RuleConfig} from '../config/RuleConfig'; import {RULE_DICTIONARY} from './index'; import {PACK} from './SimpleRulePack'; interface RuleDictionary { [key: string]: (conf: RuleConfig) => Rule; } export class RuleFactory { static readonly RULES: RuleDictionary = { ...RULE_DICTIONARY, ...PACK, }; static create(config: RuleConfig): Rule { const factory = RuleFactory.RULES[config.type]; if (factory) { return factory(config); } throw { message: `Can't find any rule of type ${config.type}`, }; } static register(ruletype: string, factory: (conf: RuleConfig) => Rule) { RuleFactory.RULES[ruletype] = factory; } }
#!/bin/bash if [ ! $1 ]; then echo "usage: $0 name" exit fi NAME=$1 docker rm -f $NAME 2>/dev/null docker run --name $NAME --hostname $NAME --restart=always -p 32777:27017 -v `pwd`/session:/data/db -d mongo
using System; using System.IO; using KoiCatalog.Plugins.FileIO; using FileInfo = KoiCatalog.Plugins.FileIO.FileInfo; namespace KoiCatalog.Plugins.Koikatu { [FileHandlerDependency(typeof(FileInfoFileHandler))] public sealed class KoikatuFileHandler : FileHandler { public override void HandleFile(FileLoader loader) { if (!Path.GetExtension(loader.Source.AbsolutePath) .Equals(".png", StringComparison.InvariantCultureIgnoreCase)) { return; } var fileInfo = loader.Entity.GetComponent(FileInfo.TypeCode); ChaFile chaFile; try { using (var stream = fileInfo.OpenRead()) { chaFile = new ChaFile(stream); } } catch (Exception) { return; } var card = loader.Entity.AddComponent(KoikatuCharacterCard.TypeCode); card.Initialize(chaFile); } } }
<?php /* * This file is part of the IPTools package. * * (c) Avtandil Kikabidze aka LONGMAN <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\Unit; use \Longman\IPTools\Ip; /** * @package TelegramTest * @author Avtandil Kikabidze <[email protected]> * @copyright Avtandil Kikabidze <[email protected]> * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) * @link http://www.github.com/akalongman/php-telegram-bot */ class IpTest extends TestCase { /** * @test */ public function test0() { $status = Ip::isValid('192.168.1.1'); $this->assertTrue($status); $status = Ip::isValid('192.168.1.255'); $this->assertTrue($status); $status = Ip::isValidv4('192.168.1.1'); $this->assertTrue($status); $status = Ip::isValid('2001:0db8:85a3:08d3:1319:8a2e:0370:7334'); $this->assertTrue($status); $status = Ip::isValidv4('2001:0db8:85a3:08d3:1319:8a2e:0370:7334'); $this->assertFalse($status); $status = Ip::isValidv6('2001:0db8:85a3:08d3:1319:8a2e:0370:7334'); $this->assertTrue($status); $status = Ip::isValid('192.168.1.256'); $this->assertFalse($status); $status = Ip::isValid('2001:0db8:85a3:08d3:1319:8a2e:0370:733432'); $this->assertFalse($status); } /** * @test */ public function test1() { $status = Ip::match('192.168.1.1', '192.168.0.*'); $this->assertFalse($status); $status = Ip::match('192.168.1.1', '192.168.0/24'); $this->assertFalse($status); $status = Ip::match('192.168.1.1', '192.168.0.0/255.255.255.0'); $this->assertFalse($status); } /** * @test */ public function test2() { $status = Ip::match('192.168.1.1', '192.168.*.*'); $this->assertTrue($status); $status = Ip::match('192.168.1.1', '192.168.1/24'); $this->assertTrue($status); $status = Ip::match('192.168.1.1', '192.168.1.1/255.255.255.0'); $this->assertTrue($status); } /** * @test */ public function test3() { $status = Ip::match('192.168.1.1', '192.168.1.1'); $this->assertTrue($status); } /** * @test */ public function test4() { $status = Ip::match('192.168.1.1', '192.168.1.2'); $this->assertFalse($status); } /** * @test */ public function test5() { $status = Ip::match('192.168.1.1', array('192.168.123.*', '192.168.123.124')); $this->assertFalse($status); $status = Ip::match('192.168.1.1', array('122.128.123.123', '192.168.1.*', '192.168.123.124')); $this->assertTrue($status); } /** * @test * @expectedException \InvalidArgumentException */ public function test6() { $status = Ip::match('192.168.1.256', '192.168.1.2'); } /** * @test */ public function test7() { $status = Ip::match('192.168.5.5', '192.168.5.1-192.168.5.10'); $this->assertTrue($status); $status = Ip::match('192.168.5.5', '192.168.1.1-192.168.10.10'); $this->assertTrue($status); $status = Ip::match('192.168.5.5', '192.168.6.1-192.168.6.10'); $this->assertFalse($status); } /** * @test */ public function test8() { $status = Ip::match('2001:cdba:0000:0000:0000:0000:3257:9652', '2001:cdba:0000:0000:0000:0000:3257:*'); $this->assertTrue($status); $status = Ip::match('2001:cdba:0000:0000:0000:0000:3257:9652', '2001:cdba:0000:0000:0000:0000:*:*'); $this->assertTrue($status); $status = Ip::match('2001:cdba:0000:0000:0000:0000:3257:9652', '2001:cdba:0000:0000:0000:0000:3257:1234-2001:cdba:0000:0000:0000:0000:3257:9999'); $this->assertTrue($status); $status = Ip::match('2001:cdba:0000:0000:0000:0000:3258:9652', '2001:cdba:0000:0000:0000:0000:3257:*'); $this->assertFalse($status); $status = Ip::match('2001:cdba:0000:0000:0000:1234:3258:9652', '2001:cdba:0000:0000:0000:0000:*:*'); $this->assertFalse($status); $status = Ip::match('2001:cdba:0000:0000:0000:0000:3257:7778', '2001:cdba:0000:0000:0000:0000:3257:1234-2001:cdba:0000:0000:0000:0000:3257:7777'); $this->assertFalse($status); } /** * @test */ public function test9() { $long = Ip::ip2long('192.168.1.1'); $this->assertEquals('3232235777', $long); $dec = Ip::long2ip('3232235777'); $this->assertEquals('192.168.1.1', $dec); $long = Ip::ip2long('fe80:0:0:0:202:b3ff:fe1e:8329'); $this->assertEquals('338288524927261089654163772891438416681', $long); $dec = Ip::long2ip('338288524927261089654163772891438416681', true); $this->assertEquals('fe80::202:b3ff:fe1e:8329', $dec); } /** * @test */ public function test_match_range() { $range = Ip::matchRange('192.168.100.', '192.168..'); $this->assertTrue($range); $range = Ip::matchRange('192.168.1.200', '192.168.1.'); $this->assertTrue($range); $range = Ip::matchRange('192.168.1.200', '192.168.2.'); $this->assertFalse($range); } public function testLocal() { $status = Ip::isLocal('192.168.5.5'); $this->assertTrue($status); $status = Ip::isLocal('fe80::202:b3ff:fe1e:8329'); $this->assertTrue($status); } /** * @test */ public function testRemote() { $status = Ip::isRemote('8.8.8.8'); $this->assertTrue($status); } }
#!/usr/bin/env python3 import os ret = os.system("git add .") if(ret!=0): print("Error running the previous command") message = input("Please enter the commit message: ") ret = os.system("git commit -m \"" +str(message)+"\"") ret = os.system("git push origin ; git push personal")
package no.nav.klage.search.clients.ereg import com.fasterxml.jackson.annotation.JsonIgnoreProperties @JsonIgnoreProperties(ignoreUnknown = true) data class Organisasjon( val navn: Navn, val organisasjonsnummer: String, val type: String, ) @JsonIgnoreProperties(ignoreUnknown = true) data class Navn( val navnelinje1: String?, val navnelinje2: String?, val navnelinje3: String?, val navnelinje4: String?, val navnelinje5: String?, val redigertnavn: String? ) { fun sammensattNavn(): String = listOfNotNull(navnelinje1, navnelinje2, navnelinje3, navnelinje4, navnelinje5).joinToString(separator = " ") }
<section class="nav"> <div class="container"> <nav> <a href="{{ route('home') }}" class="{{ $nav->match('home') }}">Главная</a> <a href="{{ route('docs') }}" class="{{ $nav->match('docs') }}">Документаця</a> <a href="{{ route('articles') }}" class="{{ $nav->match('articles') }}">Статьи</a> <a href="#">Пакеты</a> <a href="#">Работа</a> <a href="#" class="hidden-sm">Pastebin</a> <a href="#" class="ideas hidden-sm"></a> </nav> </div> </section>
// Copyright 2021 TFCloud Co.,Ltd. All rights reserved. // This source code is licensed under Apache-2.0 license // that can be found in the LICENSE file. package messaging type ChannelType string const ( SMS ChannelType = "sms" Email ChannelType = "email" )
## EventForm Component A component that handles event creation. ### Example ```js <EventForm {...fields} invalid={invalid} onAddGuest={this.handleAddingGuest} onRemoveGuest={this.handleRemovingGuest} guestList={guestList} eventTypes={eventTypes} pastHosts={hosts} pastGuests={guests} onSubmit={this.handleSubmit} /> ``` ### Props | Prop | Type | Default | Possible Values | ------------- | -------- | ----------- | --------------------------------------------- | **onSubmit** | Func | | Any function value | **pastGuests** | Array | | An array of past guests | **eventTypes** | Array | | An array of event types | **guestList** | Array | | The current guest list for the submission | **onRemoveGuest** | Func | | Any function value | **onAddGuest** | Func | | Any function value | **invalid** | Bool | | Boolean to determine if the form is valid or not
/* -------------------------------------------------------------------------------- Version history -------------------------------------------------------------------------------- 0.1.0 - initial version October 2014 Mark Farrall -------------------------------------------------------------------------------- */ angular.module('csDumb', [ 'ngRoute', 'csApi', 'ui.bootstrap', 'ui.bootstrap.modal', 'restangular', 'browse' ]); angular.module('csDumb').config(function($routeProvider) { $routeProvider. when('/browse', { templateUrl: 'views/browse/browse.html', controller: 'BrowseController' }). when('/browse/:id', { templateUrl: 'views/browse/browse.html', controller: 'BrowseController' }). otherwise({ redirectTo: '/browse' }); }); angular.module('csDumb').run(function(appConfig, browseConfig, csApiConfig) { // set the title /*var appCustom = { title: 'A new title' }; appConfig.configure(appCustom);*/ // configure the browse module /*var browseCustom = { startNode: 53912 }; browseConfig.configure(browseCustom);*/ });
import {ImageStyle, TextStyle, ViewStyle} from 'react-native'; export type Breakpoints = 'sm' | 'md' | 'lg' | 'xlg' | 'max'; export type BreakpointLength = {min: number; max: number}; export type BreakpointEntries = [Breakpoints, BreakpointLength][]; export type Media = Record<Breakpoints, {min: boolean; max: boolean}> & {current: string}; export type Scale = {width: number; height: number; font: number}; export type Orientation = 'horizontal' | 'vertical'; export type ResponsiveFont = (value: number) => number; export type ResponsiveWidth = (value: number) => number; export type ResponsiveHeight = (value: number) => number; export type ResponsiveStyle = {rw: ResponsiveFont; rh: ResponsiveHeight; rf: ResponsiveFont}; export type Styles<T> = {[P in keyof T]: ViewStyle | TextStyle | ImageStyle}; export type StylesFunction<T> = (params: ResponsiveStyle) => T;
import { validatePattern } from "utils/validations"; export const delegateRegistration = (t: any) => ({ username: (usernames: string[]) => ({ required: t("COMMON.VALIDATION.FIELD_REQUIRED", { field: t("COMMON.DELEGATE_NAME"), }), maxLength: { value: 20, message: t("COMMON.VALIDATION.MAX_LENGTH", { field: t("COMMON.DELEGATE_NAME"), maxLength: 20, }), }, validate: { pattern: (value: string) => validatePattern(t, value, /[a-z0-9!@$&_.]+/), unique: (value: string) => !usernames.includes(value) || t("COMMON.VALIDATION.EXISTS", { field: t("COMMON.DELEGATE_NAME") }), }, }), });
package jug.workshops.poligon.typed import akka.actor.typed.scaladsl.Behaviors import akka.actor.typed.{ActorRef, ActorSystem, Behavior, Terminated} import scala.concurrent.Await object ChatRoom { sealed trait Command final case class GetSession(screenName: String, replyTo: ActorRef[SessionEvent]) extends Command private final case class PostSessionMessage(screenName: String, message: String) extends Command sealed trait SessionEvent final case class SessionGranted(handle: ActorRef[PostMessage]) extends SessionEvent final case class SessionDenied(reason: String) extends SessionEvent final case class MessagePosted(screenName: String, message: String) extends SessionEvent final case class PostMessage(message: String) val behavior:Behavior[Command] = chatRoom(List.empty) private def chatRoom(sessions: List[ActorRef[SessionEvent]]): Behavior[Command] = Behaviors.receive[Command] { (ctx, msg) => msg match { case GetSession(screenName, client) => val wrapper = ctx.messageAdapter{ p: PostMessage => PostSessionMessage(screenName, p.message) } client ! SessionGranted(wrapper) chatRoom(client :: sessions) case PostSessionMessage(screenName, message) => val mp = MessagePosted(screenName,message) sessions foreach (_ ! mp) Behaviors.same } } val gabbler = Behaviors.receive[SessionEvent]{ (_,msg) => msg match { case SessionGranted(handle) => handle ! PostMessage("Hello World!") Behaviors.same case MessagePosted(screenName,message) => println(s"message has been posted by '$screenName': $message") Behaviors.stopped case unsupported => throw new RuntimeException(s"received $unsupported") } } def main(args: Array[String]): Unit = { val root: Behavior[String] =Behaviors.setup{ ctx => val chatroom: ActorRef[Command] =ctx.spawn(behavior,"chatroom") val gabblerRef: ActorRef[SessionEvent] =ctx.spawn(gabbler,"gabbler") ctx.watch(gabblerRef) Behaviors.receivePartial[String]{ case (_, "go") => chatroom ! GetSession("Gabber",gabblerRef) Behaviors.same }.receiveSignal{ case (_,Terminated(ref)) => println(s"$ref is terminated") Behaviors.stopped } } val system = ActorSystem(root, "chatroom") system ! "go" import scala.concurrent.duration._ Await.result(system.whenTerminated, 3.seconds) } }
import time anoAtual = int(time.strftime('%Y', time.localtime())) anoNasc = int(input('Digite o ano que você nasceu: ')) idade = anoAtual - anoNasc if(idade == 18): print(f'Você tem {idade} anos. Chegou a hora de se alistar') elif(idade > 18): print(f'Passou {idade - 18} anos da hora de se alistar') elif(idade < 18): print(f'Ainda não é hora de se alistar. Falta {18 - idade} anos')
# DT models are widely used for classification & regression tasks. # Essentially, they learn a hierarchy of if/else questions, leading to a decision. # if/else questions are called "tests" # tests for continuous data are: "Is feature X1 larger than value M?" import matplotlib.pyplot as plt import mglearn import numpy as np from sklearn.datasets import make_moons from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier # Moon dataset parameters. moon_ds_size = 100 moon_ds_noise = 0.15 X_moons, y_moons = make_moons(n_samples=moon_ds_size, noise=moon_ds_noise, random_state=42) X_train, X_test, y_train, y_test = train_test_split(X_moons, y_moons, random_state=42) # print(X_moons.shape) # (100, 2) # print(y_moons.shape) # (100,) moons_feature_1 = X_moons[:, 0] moons_feature_2 = X_moons[:, 1] # plt.scatter(moons_feature_1, moons_feature_2, c=y_moons) # plt.title("sklearn.datasets.make_moons") # plt.show() # Implement decision tree to classification problem. tree_model = DecisionTreeClassifier() tree_model.fit(X_train, y_train) y_predict = tree_model.predict(X_test) print(accuracy_score(y_test, y_predict)) print(tree_model.score(X_train, y_train)) print(tree_model.score(X_test, y_test)) n_features = X_moons.shape[1] features_names = ("f1", "f2") for i, color in zip(range(n_features), "ry"): idx = np.where(y_moons == i) plt.scatter( X_moons[idx, 0], X_moons[idx, 1], c=color, label=features_names[i], edgecolor='black', s=15 ) plt.show() # ??? mglearn.plots.plot_tree_progressive() plt.show()
use std::borrow::Cow; use std::env; use std::fs::File; use std::io::{stdin, stdout, BufRead, BufReader, Read, Write}; use rand::seq::SliceRandom; use rand::thread_rng; trait Rule { // returns the original string to replace fn original(&self) -> Cow<str>; // returns the string to be substituted. // Allowed to have side-effects and should only be called once for each substitution. fn substitution(&self) -> Cow<str>; } // substitutes 'original' for 'substitute' #[derive(Clone, Debug)] struct Substitution { original: Box<str>, substitute: Box<str>, } impl Substitution { fn new(original: &str, substitute: &str) -> Self { Substitution { original: original.to_string().into_boxed_str(), substitute: substitute.to_string().into_boxed_str(), } } } impl Rule for Substitution { fn original(&self) -> Cow<str> { Cow::Borrowed(&self.original) } fn substitution(&self) -> Cow<str> { Cow::Borrowed(&self.substitute) } } // replaces 'original' with line from stdin #[derive(Clone, Debug)] struct Input { original: Box<str>, } impl Input { fn new(original: &str) -> Self { Input { original: original.to_string().into_boxed_str(), } } } impl Rule for Input { fn original(&self) -> Cow<str> { Cow::Borrowed(&self.original) } fn substitution(&self) -> Cow<str> { let mut out = String::new(); stdin().read_line(&mut out).unwrap(); out = out[..out.len() - 1].to_string(); Cow::Owned(out) } } // replaces 'original' with the null string and outputs 'output' to stdout #[derive(Clone, Debug)] struct Output { original: Box<str>, output: Box<str>, } impl Output { fn new(original: &str, output: &str) -> Self { let mut output = output; if output == "" { output = "\n"; } Output { original: original.to_string().into_boxed_str(), output: output.to_string().into_boxed_str(), } } } impl Rule for Output { fn original(&self) -> Cow<str> { Cow::Borrowed(&self.original) } fn substitution(&self) -> Cow<str> { stdout().lock().write_all(&self.output.as_bytes()).unwrap(); Cow::Owned("".to_string()) } } fn main() -> Result<(), std::io::Error> { let file_name = env::args().nth(1).expect("Missing program file argument!"); let file = File::open(file_name)?; let mut buf_reader = BufReader::new(file); let rule_list = parse_rules(&mut buf_reader)?; let mut initial_state = String::new(); buf_reader.read_to_string(&mut initial_state)?; initial_state = initial_state.replace("\n", ""); run_program(rule_list, initial_state); Ok(()) } // parses and returns list of rules, leaving the buffer at the first line after the list terminator fn parse_rules(buf_reader: &mut BufReader<File>) -> Result<Box<[Box<dyn Rule>]>, std::io::Error> { let mut out: Vec<Box<dyn Rule>> = vec![]; loop { let mut next_line = String::new(); if buf_reader.read_line(&mut next_line).unwrap() == 0 { panic!("Invalid input file!"); }; next_line = next_line[..next_line.len() - 1].to_string(); if let Some((original, substitute)) = get_rule_params(&next_line) { if original.trim() == "" && substitute.trim() == "" { // reached end of rule list break; } else if original.trim() == "" && substitute.trim() != "" { panic!("Invalid syntax!"); } else if substitute == ":::" { out.push(Box::new(Input::new(original))); } else if substitute.starts_with('~') { out.push(Box::new(Output::new(original, &substitute[1..]))); } else { out.push(Box::new(Substitution::new(original, substitute))); } } } Ok(out.into_boxed_slice()) } // returns the rule parameters as '(original, substitute)' or None if not a valid rule fn get_rule_params(line: &str) -> Option<(&str, &str)> { if let Some(i) = line.find("::=") { let (head, tail) = line.split_at(i); Some((head, &tail[3..])) } else { None } } // runs Thue program using collected 'rule_list' and 'initial_state' fn run_program(mut rule_list: Box<[Box<dyn Rule>]>, initial_state: String) { let mut rng = thread_rng(); let mut state = initial_state; let mut running = true; while running { rule_list.shuffle(&mut rng); running = false; for rule in rule_list.iter() { let original = rule.original(); if let Some(index) = state .match_indices(original.as_ref()) .map(|(i, _)| i) .collect::<Vec<usize>>() .choose(&mut rng) { running = true; state.replace_range(*index..index + original.len(), &rule.substitution()); break; } } } print!("\n"); }
--- title: Postgres authors: emesika --- # Postgres This page is obsolete. ## Installation We are using version 9.1.x ## Authentication ``` Trust Password GSSAPI SSPI Kerberos Ident Peer LDAP RADIUS Certificate PAM ``` details: [Authentication Methods](http://www.postgresql.org/docs/9.1/static/auth-methods.html) ## Creating a new user [Create Role](http://www.postgresql.org/docs/9.1/static/sql-createrole.html) [Create User](http://www.postgresql.org/docs/9.0/static/sql-createuser.html) [The password file](http://www.postgresql.org/docs/9.0/static/libpq-pgpass.html) ## Configuration Default postgres configuration files are under `/var/lib/pgsql/data` ### postgresql.conf [defaults](http://www.postgresql.org/docs/current/static/view-pg-settings.html) [reset](http://www.postgresql.org/docs/current/static/sql-reset.html) ### Reload configuration If you are making modifications to the Postgres configuration file postgresql.conf (or similar), and you want to new settings to take effect without needing to restart the entire database, there are two ways to accomplish this. option 1 ```bash su - postgres /usr/bin/pg_ctl reload option 2 echo "SELECT pg_reload_conf();" | psql -U <user> <database> ``` ### Connection [Connection parameters](http://www.postgresql.org/docs/current/static/runtime-config-connection.html) ### Remote access (listen_addresses) [`pg_hba.conf`](http://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html) ### max_connections The maximum number of client connections allowed. This is very important to some of the below parameters (particularly work_mem) because there are some memory resources that are or can be allocated on a per-client basis, so the maximum number of clients suggests the maximum possible memory use. Generally, PostgreSQL on good hardware can support a few hundred connections. If you want to have thousands instead, you should consider using connection pooling software to reduce the connection overhead. ### shared_buffers The shared_buffers configuration parameter determines how much memory is dedicated to PostgreSQL use for caching data. One reason the defaults are low because on some platforms (like older Solaris versions and SGI) having large values requires invasive action like recompiling the kernel. Even on a modern Linux system, the stock kernel will likely not allow setting shared_buffers to over 32MB without adjusting kernel settings first. If you have a system with 1GB or more of RAM, a reasonable starting value for shared_buffers is 1/4 of the memory in your system. If you have less ram you'll have to account more carefully for how much RAM the OS is taking up, closer to 15% is more typical there. There are some workloads where even larger settings for shared_buffers are effective, but given the way PostgreSQL also relies on the operating system cache it's unlikely you'll find using more than 40% of RAM to work better than a smaller amount. ### work_mem Specifies the amount of memory to be used by internal sort operations and hash tables before writing to temporary disk files. The value defaults to one megabyte (1MB). Note that for a complex query, several sort or hash operations might be running in parallel; each operation will be allowed to use as much memory as this value specifies before it starts to write data into temporary files. Also, several running sessions could be doing such operations concurrently. Therefore, the total memory used could be many times the value of work_mem; it is necessary to keep this fact in mind when choosing the value. Sort operations are used for ORDER BY, DISTINCT, and merge joins. Hash tables are used in hash joins, hash-based aggregation, and hash-based processing of IN subqueries. ### maintenance_work_mem Specifies the maximum amount of memory to be used by maintenance operations, such as `VACUUM`, `CREATE INDEX`, and `ALTER TABLE ADD FOREIGN KEY`. It defaults to 16 megabytes (16MB). Since only one of these operations can be executed at a time by a database session, and an installation normally doesn't have many of them running concurrently, it's safe to set this value significantly larger than `work_mem`. Larger settings might improve performance for vacuuming and for restoring database dumps. ### synchronous_commit Asynchronous commit is an option that allows transactions to complete more quickly, at the cost that the most recent transactions may be lost if the database should crash. In many applications this is an acceptable trade-off. Asynchronous commit introduces the risk of data loss. There is a short time window between the report of transaction completion to the client and the time that the transaction is truly committed (that is, it is guaranteed not to be lost if the server crashes). The risk that is taken by using asynchronous commit is of data loss, not data corruption. If the database should crash, it will recover by replaying WAL up to the last record that was flushed. The database will therefore be restored to a self-consistent state, but any transactions that were not yet flushed to disk will not be reflected in that state. The net effect is therefore loss of the last few transactions. The user can select the commit mode of each transaction, so that it is possible to have both synchronous and asynchronous commit transactions running concurrently. This allows flexible trade-offs between performance and certainty of transaction durability. ### Guidlines for Dedicated/Shared server For the following , a good understanding of the database clock lifecycle is needed. ``` page request --> changes --> dirty --> commit to WAL --> Statistics (pg_stat_user_tables etc.) (*) --> Write to disk & clean dirty flag (*) (*) - async ``` Dedicated ``` logging can be more verbose shared_buffers - 25% of RAM work_mem should be `<OS cache size>` / (max_connections * 2) maintenance_work_mem - 50MB per each 1GB of RAM checkpoint_segments - at least 10 [1] checkpoint_timeout wal_buffers - 16MB [2] ``` [1] [`pg_buffercache`](http://www.postgresql.org/docs/9.1/static/pgbuffercache.html) - <http://www.postgresql.org/docs/9.1/static/pgbuffercache.html> [1]: <http://www.postgresql.org/docs/9.1/static/pgbuffercache.html> [2] [WAL Configuration](https://www.postgresql.org/docs/9.1/wal-configuration.html) - <https://www.postgresql.org/docs/9.1/wal-configuration.html> [2]: <http://www.postgresql.org/docs/9.1/static/wal-configuration.html> Shared ``` reduce logging shared_buffers - 10% of RAM be very stingy about increasing work_mem all other recomendations from the Dedicated section may apply ``` ### pgtune pgtune takes the default postgresql.conf and expands the database server to be as powerful as the hardware it's being deployed on. [How to tune your database](http://web.archive.org/web/20150416110332/http://sourcefreedom.com/tuning-postgresql-9-0-with-pgtune/) ## VACUUM Cleans up after old transactions, including removing information that is no longer visible and reuse free space. ANALYSE looks at tables in the database and collects statistics about them like number of distinct values etc. Many aspects of query planning depends on this statistics data being accurate. From 8.1 , there is a autovaccum daemon that runs in the background and do this work automatically. ## Logging General logging is important especially if you have unexpected behaviour and you want to find the reason for that The default logging level is only Errors but this can be easily changed. ### log_line_prefix Controls the line prefix of each log message. ``` %t timestamp %u user %r remote host connection %d database connection %p pid of connection ``` ### log_statement Controls which statements are logged ``` none ddl mod all ``` ### log_min_duration_statement Controls how long should a query being executed to be logged Very usefull to find most expensive queries
-- 削除対象の日付を設定 DECLARE @dt date = (SELECT DATEADD(dd, -31, GETDATE())) -- バックアップ履歴レコードの削除 EXEC msdb.dbo.sp_delete_backuphistory @dt -- ジョブ実行履歴レコードの削除 EXEC msdb.dbo.sp_purge_jobhistory @oldest_date= @dt -- メンテナンスプラン履歴レコードの削除 EXECUTE msdb..sp_maintplan_delete_log null,null, @dt
import { all } from 'redux-saga/effects'; import categoriesSaga from './categoriesSaga'; import cookbookSaga from './cookbookSaga'; function* rootSaga() { yield all([categoriesSaga(), cookbookSaga()]); } export default rootSaga;
using System.Collections; using System.Collections.Generic; using UnityEngine; public class WanderBehavior : SteeringBehavior { [SerializeField] private float mWanderDistance; [SerializeField] private float mWanderRadius; [SerializeField] private float mWanderJitter; private float mWanderAngle; private void Awake() { mWanderAngle = Random.Range(-Mathf.PI * 2, Mathf.PI * 2); } // Steering Behavior Reference: // https://gamedevelopment.tutsplus.com/tutorials/understanding-steering-behaviors-wander--gamedev-1624 public override Vector3 Calculate(Agent agent) { // Calculate the circle center Vector3 circleCenter; if (Vector3.SqrMagnitude(agent.velocity) == 0.0f) { return Vector3.zero; } circleCenter = Vector3.Normalize(agent.velocity); circleCenter *= mWanderDistance; // Calculate the displacement force Vector3 displacement = new Vector3(0.0f, -1.0f); displacement *= mWanderRadius; // Randomly change direction by making it change its current angle float len = Vector3.Magnitude(displacement); displacement.x = Mathf.Cos(mWanderAngle) * len; displacement.y = Mathf.Sin(mWanderAngle) * len; // Change wanderAngle a bit mWanderAngle += Random.Range(-mWanderJitter, mWanderJitter); // Calculate and return the wander force Vector3 wanderForce = circleCenter + displacement; return wanderForce; } }
package service import ( "k8s.io/api/admission/v1beta1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/serializer" ) var scheme = runtime.NewScheme() var codecs = serializer.NewCodecFactory(scheme) // ToAdmissionResponse is a helper function to create an AdmissionResponse // with an embedded error func ToAdmissionResponse(err error) *v1beta1.AdmissionResponse { return &v1beta1.AdmissionResponse{ Result: &metav1.Status{ Message: err.Error(), }, } }
# PythonでGUIをつくろう─はじめてのQt for Python 3.3.4 サンプルコード Qt for Python(PySide2)バージョン情報の出力 をおこないます。
import 'dart:convert'; import 'package:shelf/shelf.dart' as shelf; class HttpResponse { static shelf.Response get ok { return shelf.Response.ok( 'Ok', headers: <String, String>{ 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-cache', }, ); } static shelf.Response get notFound { final bytes = jsonEncode(<String, Object>{ 'error': 'Not found', }).codeUnits; return shelf.Response.notFound( bytes, headers: <String, String>{ 'Content-Length': bytes.length.toString(), 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-cache', }, ); } static shelf.Response internalServerError(Object error) { final bytes = jsonEncode(<String, Object>{ 'error': error.toString(), }).codeUnits; return shelf.Response.internalServerError( body: bytes, headers: <String, String>{ 'Content-Length': bytes.length.toString(), 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-cache', }, ); } }
import { useEffect, useState } from 'react'; import { RemoteParticipant } from 'twilio-video'; import useDominantSpeaker from '../useDominantSpeaker/useDominantSpeaker'; import useVideoContext from '../useVideoContext/useVideoContext'; export default function useParticipants() { const { room } = useVideoContext(); const dominantSpeaker = useDominantSpeaker(); const [participants, setParticipants] = useState(Array.from(room.participants.values())); // When the dominant speaker changes, they are moved to the front of the participants array. // This means that the most recent dominant speakers will always be near the top of the // ParticipantStrip component. useEffect(() => { if (dominantSpeaker) { setParticipants(prevParticipants => [ dominantSpeaker, ...prevParticipants.filter(participant => participant !== dominantSpeaker), ]); } }, [dominantSpeaker]); useEffect(() => { const participantConnected = (participant: RemoteParticipant) => { fetch(window.location.pathname.replace('Room', 'RoomInfo')) .then(response => { console.log(response); return response.json(); }) .then(data => { console.log(data); return data; }) .then( data => { (window as any).roomInfo = data; }, error => { // DO NOTHING } ) .then(() => { setParticipants(prevParticipants => [...prevParticipants, participant]); }); }; const participantDisconnected = (participant: RemoteParticipant) => setParticipants(prevParticipants => prevParticipants.filter(p => p !== participant)); room.on('participantConnected', participantConnected); room.on('participantDisconnected', participantDisconnected); return () => { room.off('participantConnected', participantConnected); room.off('participantDisconnected', participantDisconnected); }; }, [room]); return participants; }
package com.patrykkosieradzki.theanimalapp import com.google.firebase.ktx.Firebase import com.google.firebase.remoteconfig.FirebaseRemoteConfig import com.google.firebase.remoteconfig.ktx.get import com.google.firebase.remoteconfig.ktx.remoteConfig import com.google.firebase.remoteconfig.ktx.remoteConfigSettings import com.patrykkosieradzki.theanimalapp.domain.AppConfiguration import timber.log.Timber import java.util.concurrent.TimeUnit interface RemoteConfigManager { suspend fun checkMaintenanceMode( onCompleteCallback: (Boolean) -> Unit, onFailureCallback: (Exception) -> Unit ) val maintenanceEnabled: Boolean val maintenanceTitle: String val maintenanceDescription: String } class RemoteConfigManagerImpl( private val appConfiguration: AppConfiguration, private val remoteConfig: FirebaseRemoteConfig = Firebase.remoteConfig ) : RemoteConfigManager { override val maintenanceEnabled = remoteConfig[IS_MAINTENANCE_MODE_KEY].asBoolean() override val maintenanceTitle = remoteConfig[MAINTENANCE_TITLE_KEY].asString() override val maintenanceDescription = remoteConfig[MAINTENANCE_DESCRIPTION_KEY].asString() override suspend fun checkMaintenanceMode( onCompleteCallback: (Boolean) -> Unit, onFailureCallback: (Exception) -> Unit ) { fetchAndActivate( if (appConfiguration.debug) INSTANT else TWELVE_HOURS, onCompleteCallback, onFailureCallback ) } private fun fetchAndActivate( minimumFetchIntervalInSeconds: Long, onCompleteCallback: (Boolean) -> Unit, onFailureCallback: (Exception) -> Unit ) { val remoteConfigSettings = remoteConfigSettings { setMinimumFetchIntervalInSeconds(minimumFetchIntervalInSeconds) fetchTimeoutInSeconds = FETCH_TIMEOUT_IN_SECONDS } remoteConfig.setConfigSettingsAsync(remoteConfigSettings).addOnCompleteListener { remoteConfig.fetchAndActivate() .addOnCompleteListener { Timber.d("Remote Config fetched successfully") onCompleteCallback.invoke(maintenanceEnabled) } .addOnFailureListener { Timber.e(it, "Failure during Remote Config fetch") onFailureCallback.invoke(it) } } } companion object { const val IS_MAINTENANCE_MODE_KEY = "is_maintenance_mode" const val MAINTENANCE_TITLE_KEY = "maintenance_title" const val MAINTENANCE_DESCRIPTION_KEY = "maintenance_description" const val FETCH_TIMEOUT_IN_SECONDS = 5L val TWELVE_HOURS = TimeUnit.HOURS.toSeconds(12) const val INSTANT = 0L } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PyramidNETRS232_TestApp_Simple { class Program { /// <summary> /// Dead simple demo. The error handling and extra features have been omitted for simplicity. /// </summary> /// <param name="args"></param> static void Main(string[] args) { Console.WriteLine("Enter port name in format: COMX"); var port = Console.ReadLine(); SingleBillValidator.Instance.Connect(port); Console.WriteLine("Connected on port {0}", port); Console.WriteLine("Press ESC to stop"); do { while (!Console.KeyAvailable) { } } while (Console.ReadKey(true).Key != ConsoleKey.Escape); Console.WriteLine("Quitting..."); SingleBillValidator.Instance.Disconnect(); } } }
require "socket" require "uri" require "json" require "timeout" require "digest" Links = Hash.new Struct.new("Response", :code, :status) STATUS_CODES = { 200 => "200 OK", 301 => "301 Moved Permanently", 400 => "400 Bad Request", 403 => "403 Forbidden", 404 => "404 Not Found", 405 => "405 Method Not Allowed" } server = TCPServer.new('0.0.0.0', 2345) def requestType(request_line) request_uri = request_line.split(" ")[0] end def getPath(request_line) request_uri = request_line.split(" ")[1] path = URI.unescape(URI(request_uri).path) end def sendRedirect(socket, url, response) socket.print "HTTP/1.1 "+getStatus(301)+"\r\n"+ "Location: "+url+"\r\n"+ "Content-Type: text/html\r\n"+ "Content-Length: #{response.bytesize}\r\n"+ "Connection: close\r\n" socket.print "\r\n" socket.close end def sendResponse(socket, response, code) socket.print "HTTP/1.1 "+code+"\r\n"+ "Content-Type: application/json\r\n"+ "Content-Length: #{response.bytesize}\r\n"+ "Connection: close\r\n" socket.print "\r\n" socket.print response socket.close end def getStatus(status) code = STATUS_CODES.fetch(status, "500 Internal Server Error") end def getLink(code) if code == "" return "" else puts code link = Links.fetch(code, "") end end def getData(str) hs = Hash.new str.split("\n").map do |s| b = s.split(": ") hs[b[0]] = b[1] end end def getCode(url) Links.each do |key, value| return key if value["url"] == url end t = Time.now.to_i.to_s x = Digest::MD5.hexdigest t code = x[-5..-1] Links[code] = {"url" => url} return code end loop do socket = server.accept request = socket.gets path = getPath(request) reqType = requestType(request) if path == "/generate" if reqType == "POST" lines = [] begin st = timeout(1) { while line = socket.gets if line == nil puts "meme" elsif line == "" puts "lol" break else lines.insert(-1, line.to_s) end end } rescue => error begin if lines == nil puts "nil lines" sendResponse(socket, Struct::Response.new(500, "500 Internal Server Error").to_h.to_json, getStatus(500)) else p = lines.join("").to_s if p == nil sendResponse(socket, Struct::Response.new(500, "500 Internal Server Error").to_h.to_json, getStatus(500)) else p = "{"+p.split("{")[1] if p == nil sendResponse(socket, Struct::Response.new(400, "400 Bad Request").to_h.to_json, getStatus(400)) else data = JSON.parse(p) if data if data["url"] == nil sendResponse(socket, Struct::Response.new(400, "400 Bad Request").to_h.to_json, getStatus(400)) elsif data["url"] == "" sendResponse(socket, Struct::Response.new(400, "400 Bad Request").to_h.to_json, getStatus(400)) else sendResponse(socket, Struct::Response.new(200, getCode(data["url"])).to_h.to_json, getStatus(200)) end else sendResponse(socket, Struct::Response.new(400, "400 Bad Request").to_h.to_json, getStatus(400)) end end end end rescue => error puts error.message puts error.backtrace sendResponse(socket, Struct::Response.new(500, "500 Internal Server Error").to_h.to_json, getStatus(500)) end end else sendResponse(socket, Struct::Response.new(405, "405 Method Not Allowed").to_h.to_json, getStatus(405)) end else path.sub! '/', '' link = getLink(path) if link == "" sendResponse(socket, Struct::Response.new(404, "404 Not Found").to_h.to_json, getStatus(404)) else sendRedirect(socket, "#{link['url']}", "301 Moved Permanently") end end end
package top.chao.funding.bean; public class TReturn { private Integer id; private Integer projectid; private String type; private Integer supportmoney; private String content; private Integer count; private Integer signalpurchase; private Integer purchase; private Integer freight; private String invoice; private Integer rtndate; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getProjectid() { return projectid; } public void setProjectid(Integer projectid) { this.projectid = projectid; } public String getType() { return type; } public void setType(String type) { this.type = type == null ? null : type.trim(); } public Integer getSupportmoney() { return supportmoney; } public void setSupportmoney(Integer supportmoney) { this.supportmoney = supportmoney; } public String getContent() { return content; } public void setContent(String content) { this.content = content == null ? null : content.trim(); } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } public Integer getSignalpurchase() { return signalpurchase; } public void setSignalpurchase(Integer signalpurchase) { this.signalpurchase = signalpurchase; } public Integer getPurchase() { return purchase; } public void setPurchase(Integer purchase) { this.purchase = purchase; } public Integer getFreight() { return freight; } public void setFreight(Integer freight) { this.freight = freight; } public String getInvoice() { return invoice; } public void setInvoice(String invoice) { this.invoice = invoice == null ? null : invoice.trim(); } public Integer getRtndate() { return rtndate; } public void setRtndate(Integer rtndate) { this.rtndate = rtndate; } }
#!/bin/bash # I'm super lazy y'all ./main.sh --gin_config example_configs/biggan_posenc_imagenet32.gin \ --model_dir gs://octavian-training2/compare_gan/model/imagenet32/posenc \ --schedule eval_last \ $@
import INode, * as INodeUtil from './inode'; import File from './file'; import DiskDriver from './diskDriver/interface'; import Metadata, * as MetadataUtil from './metadata'; import BlockManager from './blockManager'; import INodeManager from './inodeManager'; export default class FileSystem { static BLOCK_SIZE = 4096; static INODE_SIZE = 128; diskDriver: DiskDriver; metadata: Metadata; blockManager: BlockManager; inodeManager: INodeManager; createFileObject: (inode: INode) => File; constructor(diskDriver: DiskDriver) { this.diskDriver = diskDriver; this.createFileObject = inode => new File(this, inode); } static async mkfs(diskDriver: DiskDriver, rootNode: INode = INodeUtil.createEmpty(), ): Promise<FileSystem> { // Create new metadata and write inode block list / block bitmap let metadata: Metadata = { version: 1, bitmapId: 1, blockListId: 2, rootId: 3, }; await diskDriver.write(0, MetadataUtil.encode(metadata)); // Populate bitmap node / file let bitmapNode = INodeUtil.createEmpty(); bitmapNode.length = 3; bitmapNode.pointers[0] = 1; await diskDriver.write(128, INodeUtil.encode(bitmapNode)); let bitmapBlock = new Uint8Array(4096); bitmapBlock.set([1, 2, 2]); await diskDriver.write(4096, bitmapBlock); // Populate block list node / file let blockListNode = INodeUtil.createEmpty(); blockListNode.length = 12; blockListNode.pointers[0] = 2; await diskDriver.write(256, INodeUtil.encode(blockListNode)); let blockListBlock = new Uint8Array(4096); blockListBlock.set([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15]); await diskDriver.write(8192, blockListBlock); // Populate root node await diskDriver.write(384, INodeUtil.encode(rootNode)); return new FileSystem(diskDriver); } async init(): Promise<void> { // Read metadata and read inode / block bitmap to buffer this.metadata = MetadataUtil.decode(await this.diskDriver.read(0, 128)); this.blockManager = new BlockManager(this); this.inodeManager = new INodeManager(this); this.blockManager.init(await this.readFile(this.metadata.bitmapId)); this.inodeManager.init(await this.readFile(this.metadata.blockListId)); } async close(): Promise<void> { // Write metadata to disk await this.diskDriver.write(0, MetadataUtil.encode(this.metadata)); } async readBlock( id: number, position?: number, size?: number, ): Promise<Uint8Array> { let address = id * FileSystem.BLOCK_SIZE + (position || 0); return this.diskDriver.read(address, size || FileSystem.BLOCK_SIZE); } async writeBlock( id: number, position: number, buffer: Uint8Array, ): Promise<void> { let address = id * FileSystem.BLOCK_SIZE + (position || 0); return this.diskDriver.write(address, buffer); } async createFile(type: number = 0): Promise<File> { // Get free inode and wrap file let inode = await this.inodeManager.next(); inode.type = type; inode.dirty = true; return this.createFileObject(inode); } read(id: number): Promise<INode> { // Read inode from disk, or buffer (if in cache) return this.inodeManager.read(id); } async readFile(id: number): Promise<File> { // Read inode and wrap with file let inode = await this.inodeManager.read(id); return this.createFileObject(inode); } async unlink(inode: INode): Promise<void> { // Delete inode and mark on the bitmap await this.inodeManager.unlink(inode); } async unlinkFile(file: File): Promise<void> { // Delete whole data node await file.truncate(0); await this.inodeManager.unlink(file.inode); } setType(id: number, value: number): Promise<void> { // Set bitmap data return this.blockManager.setType(id, value); } }
import axios from 'axios'; require('./bootstrap'); window.Vue = require('vue'); Vue.component('example-component', require('./components/ExampleComponent.vue').default); Vue.component('agregar-cliente-component', require('./components/AgregarClienteComponent.vue').default); Vue.component('editar-cliente-component', require('./components/EditarClienteComponent.vue').default); Vue.component('modal-agregar', require('./components/ModalAgregar.vue').default); Vue.component('modal-editar', require('./components/ModalEditar.vue').default); const app = new Vue({ el: '#app', data: { clientes: [], clienteEditar: {}, mostrarAgregar: false, mostrarEdicion: false, mostrarInformacion: false, informacion: '', busqueda: '', alert: '', showModal: false, showModalEditar: false, showModalImagen: false, imagen: 'logotipo.jpg' }, created() { console.log(this.listarClientes()) }, mounted() { console.log('mostrar imagen: '+this.mostrarImagen()) }, methods: { listarClientes() { axios.get('./api/listarClientes') .then(response => this.clientes = response.data) .catch(error => { console.log(error.message + ' get: api/cliente'); }) .finally( console.log(this.clientes) ); }, /*editarCliente(cliente){ console.log('cargando cliente!'); console.log(cliente); this.clienteEditar = cliente; this.mostrarEdicion = true; this.$nextTick(() => { $('#ModalEditarCliente').modal('show'); }); }, cerrarEditar(){ $('#ModalEditarCliente').modal('hide'); this.$nextTick(() => { this.mostrarEdicion = false; }); },*/ borrarCliente(id) { axios.post('./api/borrarCliente', { id }).then(res => { this.listarClientes() this.informacion = 'Cliente Borrado - STATUS PASO A 300', this.mostrarInformacion = !this.mostrarInformacion }) .catch(function (error) { console.log(error) }) .finally( setTimeout(() => { this.informacion = '', this.mostrarInformacion = !this.mostrarInformacion },3000) ); }, busquedaClientes(busqueda) { axios.get('./api/buscarClientes', { params: { busqueda } }) .then( response => this.clientes = response.data ) .catch(error => { console.log(error.message + ' get: api/busquedaClientes'); }); }, cambiarInformacion() { this.informacion = 'Cliente ACTUALIZADO', this.mostrarInformacion = !this.mostrarInformacion, setTimeout(() => { this.informacion = '', this.mostrarInformacion = !this.mostrarInformacion },3000) }, cambiarInformacionAgregar(error) { this.informacion = error, this.mostrarInformacion = !this.mostrarInformacion, setTimeout(() => { this.informacion = '', this.mostrarInformacion = !this.mostrarInformacion },3000) }, cambioImagen() { this.imagen = event.target.files[0]; }, getImage(event){ var formData = new FormData(); formData.append("imagenNueva", this.imagen); axios.post('./api/cambiarImagen', formData) .then( response => this.imagen = response.data ) .catch(error => { console.log(error.message ); }) .finally( this.close() ); }, mostrarImagen() { axios.get('./api/mostrarImagen') .then(response => this.imagen = response.data) .catch(error => { console.log(error.message + ' error al mostrar imagen'); }); }, toggleModal () { this.showModal = !this.showModal }, toggleModalEdit (cliente) { this.showModalEditar = !this.showModalEditar; this.clienteEditar = cliente; }, toggleModalImagen () { this.showModalImagen = !this.showModalImagen }, close() { this.showModalImagen = false }, updateColor(alert) { this.alert = alert; console.log(this.alert); } } });
# Grid 栅格 采用24格划分的栅格系统 ## 基本用法 通过 span 设置宽度占比,默认占 24 格即 100%。 ```jsx import { Row, Col } from 'zarm-web'; ReactDOM.render( <> <Row> <Col> <div>col</div> </Col> </Row> <Row> <Col span={12}> <div>col-12</div> </Col> <Col span={12}> <div>col-12</div> </Col> </Row> </>, mountNode, ); ``` ## 区块间隔 通过 Row 的 gutter 属性设置 Col 之间的水平间距。如果需要垂直间距,可以写成数组形式 [水平间距, 垂直间距]。 ```jsx import { Row, Col } from 'zarm-web'; ReactDOM.render( <> <h4>水平间距</h4> <Row gutter={6}> <Col span={6}> <div>col-6</div> </Col> <Col span={6}> <div>col-6</div> </Col> <Col span={6}> <div>col-6</div> </Col> <Col span={6}> <div>col-6</div> </Col> </Row> <h4>水平间距, 垂直间距</h4> <Row gutter={[6, 10]}> <Col span={6}> <div>col-6</div> </Col> <Col span={6}> <div>col-6</div> </Col> <Col span={6}> <div>col-6</div> </Col> <Col span={6}> <div>col-6</div> </Col> <Col span={6}> <div>col-6</div> </Col> <Col span={6}> <div>col-6</div> </Col> <Col span={6}> <div>col-6</div> </Col> <Col span={6}> <div>col-6</div> </Col> <Col span={8}> <div>col-8</div> </Col> <Col span={8}> <div>col-8</div> </Col> <Col span={8}> <div>col-8</div> </Col> </Row> </>, mountNode, ); ``` ## 左间距 通过 offset 属性,设置 Col 的 margin-left。 ```jsx import { Row, Col } from 'zarm-web'; ReactDOM.render( <Row gutter={[0, 10]}> <Col span={8}> <div>col-8</div> </Col> <Col span={8} offset={8}> <div>col-8 offset-8</div> </Col> <Col span={6} offset={6}> <div>col-6 offset-6</div> </Col> <Col span={6} offset={6}> <div>col-6 offset-6</div> </Col> </Row>, mountNode, ); ``` ## 左右偏移 通过 push 属性,设置 Col 的 左偏移; 通过 pull 属性,设置 Col 的 右偏移。 ```jsx import { Row, Col } from 'zarm-web'; ReactDOM.render( <Row> <Col span={6} push={18}> <div>col-6 push-18</div> </Col> <Col span={18} pull={6}> <div>col-18 pull-6</div> </Col> </Row>, mountNode ); ``` ## 布局 通过 justify 属性,设置 Col 其在父节点里面的排版方式。 ```jsx import { Row, Col } from 'zarm-web'; ReactDOM.render( <> <h4>justify start</h4> <Row justify="start" className="row-bg"> <Col span={4}> <div>col-4</div> </Col> <Col span={4}> <div>col-4</div> </Col> <Col span={4}> <div>col-4</div> </Col> <Col span={4}> <div>col-4</div> </Col> </Row> <h4>justify center</h4> <Row justify="center" className="row-bg"> <Col span={4}> <div>col-4</div> </Col> <Col span={4}> <div>col-4</div> </Col> <Col span={4}> <div>col-4</div> </Col> <Col span={4}> <div>col-4</div> </Col> </Row> <h4>justify end</h4> <Row justify="end" className="row-bg"> <Col span={4}> <div>col-4</div> </Col> <Col span={4}> <div>col-4</div> </Col> <Col span={4}> <div>col-4</div> </Col> <Col span={4}> <div>col-4</div> </Col> </Row> <h4>justify space-between</h4> <Row justify="space-between" className="row-bg"> <Col span={4}> <div>col-4</div> </Col> <Col span={4}> <div>col-4</div> </Col> <Col span={4}> <div>col-4</div> </Col> <Col span={4}> <div>col-4</div> </Col> </Row> <h4>justify space-around</h4> <Row justify="space-around" className="row-bg"> <Col span={4}> <div>col-4</div> </Col> <Col span={4}> <div>col-4</div> </Col> <Col span={4}> <div>col-4</div> </Col> <Col span={4}> <div>col-4</div> </Col> </Row> </>, mountNode, ); ``` ## 垂直对齐 通过 align 属性,设置 Col 的 垂直对齐方式。 ```jsx import { Row, Col } from 'zarm-web'; ReactDOM.render( <> <h4>align top</h4> <Row justify="center" align="top" className=" row-bg"> <Col span={8}> <div className="col col-height-8">col-8</div> </Col> <Col span={8}> <div>col-8</div> </Col> <Col span={8}> <div className="col col-height-10">col-8</div> </Col> </Row> <h4>align middle</h4> <Row justify="center" align="middle" className=" row-bg"> <Col span={8}> <div className="col col-height-8">col-8</div> </Col> <Col span={8}> <div>col-8</div> </Col> <Col span={8}> <div className="col col-height-10">col-8</div> </Col> </Row> <h4>align bottom</h4> <Row justify="center" align="bottom" className=" row-bg"> <Col span={8}> <div className="col col-height-8">col-8</div> </Col> <Col span={8}> <div>col-8</div> </Col> <Col span={8}> <div className="col col-height-10">col-8</div> </Col> </Row> <h4>align stretch</h4> <Row justify="center" align="stretch" className=" row-stretch row-bg"> <Col span={8}> <div className="col col-height-8">col-8</div> </Col> <Col span={8}> <div>col-8</div> </Col> <Col span={8}> <div className="col col-height-10">col-8</div> </Col> </Row> </>, mountNode, ); ``` ## 排序 通过 order 属性,设置 Col 的 顺序。 ```jsx import { Row, Col } from 'zarm-web'; ReactDOM.render( <Row justify="center" align="top"> <Col span={8} order={2}> <div>col-8 第1个</div> </Col> <Col span={8} order={1}> <div>col-8 第2个</div> </Col> <Col span={8} order={0}> <div>col-8 第3个</div> </Col> </Row>, mountNode, ); ``` ## flex 通过 flex 属性,设置 Col 样式。 ```jsx import { Row, Col } from 'zarm-web'; ReactDOM.render( <> <Row gutter={[0, 10]}> <Col flex={2}> <div>2 / 5</div> </Col> <Col flex={3}> <div>3 / 5</div> </Col> </Row> <Row gutter={[0, 10]}> <Col flex="100px"> <div>100px</div> </Col> <Col flex="auto"> <div>Fill Rest</div> </Col> </Row> <Row gutter={[0, 10]}> <Col flex="1 1 200px"> <div>1 1 200px</div> </Col> <Col flex="0 1 300px"> <div>0 1 300px</div> </Col> </Row> </>, mountNode ); ``` ## API <h3>Row</h3> | 属性 | 类型 | 默认值 | 说明 | | :--- | :--- | :--- | :--- | | gutter | number \| [number, number] | 0 | 设置栅格水平间隔,使用数组可同时设置`[水平间隔,垂直间隔]` | | align | string | 'stretch' | 垂直对齐方式,可选值为 `top`、 `middle`、 `bottom`、 `stretch` | | justify | string | 'start' | 水平排列方式,可选值为 `start`、`end`、`center`、`space-around`、`space-between` | <h3>Col</h3> | 属性 | 类型 | 默认值 | 说明 | | :--- | :--- | :--- | :--- | | flex | string \| number | - | flex 布局属性 | | offset | number | - | 栅格左侧的间隔格数 | | order | number | - | 栅格顺序 | | pull | number | - | 栅格向左移动格数 | | push | number | - | 栅格向右移动格数 | | span | number | - | 栅格占位格数,为 0 时相当于 display: none |
// See LICENSE.BU for license details. // See LICENSE.IBM for license details. package dana import chisel3._ import chisel3.util._ // [TODO] This module is currently non-working. It was an initial // solution to the problem of dealing with random writes from the // Processing Elements and needing to maintain a record of which // entries were valid. Knowledge of valid entries is necessary to // ensure that subsequent PE reads are only reading valid data. This // approach introduces metadata into each SRAM block that contains the // number of valid entries in that block. class SRAMElementCounterResp ( val sramDepth: Int ) extends Bundle { override def cloneType = new SRAMElementCounterResp ( sramDepth = sramDepth).asInstanceOf[this.type] val index = UInt(log2Up(sramDepth).W) } class SRAMElementCounterInterface ( val dataWidth: Int, val sramDepth: Int, val numPorts: Int, val elementWidth: Int ) extends Bundle { override def cloneType = new SRAMElementInterface( dataWidth = dataWidth, sramDepth = sramDepth, numPorts = numPorts, elementWidth = elementWidth).asInstanceOf[this.type] val we = Output(Vec(numPorts, Bool())) val din = Output(Vec(numPorts, UInt(elementWidth.W))) val addr = Output(Vec(numPorts, UInt(log2Up(sramDepth * dataWidth / elementWidth).W))) val dout = Input(Vec(numPorts, UInt(dataWidth.W))) // lastBlock sets which is the last block in the SRAM val lastBlock = Input(Vec(numPorts, UInt(log2Up(sramDepth).W))) // lastCount sets the number of elements in the last block val lastCount = Input(Vec(numPorts, UInt((log2Up(dataWidth / elementWidth) + 1).W))) val resp = Vec(numPorts, Decoupled(new SRAMElementCounterResp ( sramDepth = sramDepth)) ) } // write (i.e., SRAMElement), but also includes a count of the number // of valid elements in each block. When a block is determined to be // completely valid, this module generates an output update signal // indicating which block is now valid. class SRAMElementCounter ( val dataWidth: Int = 32, val sramDepth: Int = 64, val elementWidth: Int = 8, val numPorts: Int = 1 ) extends Module { val io = IO(Flipped(new SRAMElementCounterInterface( dataWidth = dataWidth, sramDepth = sramDepth, numPorts = numPorts, elementWidth = elementWidth ))) val sram = Module(new SRAM( dataWidth = dataWidth + log2Up(dataWidth / elementWidth) + 1, sramDepth = sramDepth, numReadPorts = numPorts, numWritePorts = numPorts, numReadWritePorts = 0 )) val addr = Vec(numPorts, new Bundle{ val addrHi = UInt(log2Up(sramDepth).W) val addrLo = UInt(log2Up(dataWidth / elementWidth).W)}) val writePending = Reg(Vec(numPorts, new WritePendingBundle( elementWidth = elementWidth, dataWidth = dataWidth, sramDepth = sramDepth))) val tmp = Vec(numPorts, Vec(dataWidth/elementWidth, UInt(elementWidth.W))) val count = Vec(numPorts, UInt((log2Up(dataWidth / elementWidth) + 1).W)) val forwarding = Vec(numPorts, Bool()) // Combinational Logic for (i <- 0 until numPorts) { // Assign the addresses addr(i).addrHi := io.addr(i)( log2Up(sramDepth * dataWidth / elementWidth) - 1, log2Up(dataWidth / elementWidth)) addr(i).addrLo := io.addr(i)( log2Up(dataWidth / elementWidth) - 1, 0) // Connections to the sram sram.io.weW(i) := writePending(i).valid // Explicit data and count assignments sram.io.dinW(i) := 0.U sram.io.dinW(i)(sramDepth - 1, 0) := tmp(i) sram.io.dinW(i)(sramDepth + log2Up(dataWidth/elementWidth) + 1 - 1) := count(i) + 1.U + forwarding(i) sram.io.addrR(i) := addr(i).addrHi io.dout(i) := sram.io.doutR(i)(dataWidth - 1, 0) // Defaults io.resp(i).valid := false.B io.resp(i).bits.index := 0.U forwarding(i) := false.B tmp(i) := sram.io.doutR(i)(dataWidth - 1, 0) count(i) := sram.io.doutR(i)( dataWidth + log2Up(dataWidth/elementWidth) + 1 - 1, dataWidth) sram.io.addrW(i) := writePending(i).addrHi when (writePending(i).valid) { for (j <- 0 until dataWidth / elementWidth) { when (j.U === writePending(i).addrLo) { tmp(i)(j) := writePending(i).data } .elsewhen(addr(i).addrHi === writePending(i).addrHi && io.we(i) && j.U === addr(i).addrLo) { tmp(i)(j) := io.din(i) forwarding(i) := true.B } .otherwise { tmp(i)(j) := sram.io.doutR(i)((j+1) * elementWidth - 1, j * elementWidth) } } // Generate a response if we've filled up an entry. An entry is // full if it's count is equal to the number of elementsPerBlock // or if it's the last count in the last block (this covers the // case of a partially filled last block). when (count(i) + 1.U + forwarding(i) === (dataWidth / elementWidth).U || (count(i) + 1.U + forwarding(i) === io.lastCount(i) && writePending(i).addrHi === io.lastBlock(i))) { io.resp(i).valid := true.B io.resp(i).bits.index := writePending(i).addrHi sram.io.dinW(i)(sramDepth + log2Up(dataWidth/elementWidth) + 1 - 1) := 0.U } } } // Sequential Logic for (i <- 0 until numPorts) { // Assign the pending write data writePending(i).valid := false.B when ((io.we(i)) && (forwarding(i) === false.B)) { writePending(i).valid := true.B writePending(i).data := io.din(i) writePending(i).addrHi := addr(i).addrHi writePending(i).addrLo := addr(i).addrLo } } // Assertions assert(isPow2(dataWidth / elementWidth), "dataWidth/elementWidth must be a power of 2") }
ALTER TABLE installation_statistics ADD COLUMN users_count INTEGER NOT NULL DEFAULT 0, ADD COLUMN codebases_count INTEGER NOT NULL DEFAULT 0;
# Olá,Mundo! Primeiro repositorio de Git e GitHub repositótio criado durante uma aula Está linha eu adicionei diretamente no site.
 using HKTool.Reflection.Runtime; namespace HKTool.Reflection; static class FastReflection { public static Dictionary<FieldInfo, RD_SetField> fsetter = new(); public static Dictionary<FieldInfo, RD_GetField> fgetter = new(); public static Dictionary<FieldInfo, Func<object, IntPtr>> frefgetter = new(); public static Dictionary<MethodInfo, FastReflectionDelegate> mcaller = new(); public static RD_GetField GetGetter(FieldInfo field) { if (field is null) throw new ArgumentNullException(nameof(field)); if (!fgetter.TryGetValue(field, out var getter)) { DynamicMethod dm = new DynamicMethod("", MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, typeof(object), new Type[]{ typeof(object) }, (Type)field.DeclaringType, true); var il = dm.GetILGenerator(); if (!field.IsStatic) { il.Emit(OpCodes.Ldarg_0); if (field.DeclaringType.IsValueType) { il.Emit(OpCodes.Unbox_Any, field.DeclaringType); } il.Emit(OpCodes.Ldfld, field); } else { il.Emit(OpCodes.Ldsfld, field); } if (field.FieldType.IsValueType) { il.Emit(OpCodes.Box, field.FieldType); } il.Emit(OpCodes.Ret); getter = (RD_GetField)dm.CreateDelegate(typeof(RD_GetField)); fgetter[field] = getter; } return getter; } public static RD_SetField GetSetter(FieldInfo field) { if (field is null) throw new ArgumentNullException(nameof(field)); if (!fsetter.TryGetValue(field, out var setter)) { DynamicMethod dm = new DynamicMethod("", MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, typeof(void), new Type[]{ typeof(object), typeof(object) }, (Type)field.DeclaringType, true); var il = dm.GetILGenerator(); if (field.IsStatic) { il.Emit(OpCodes.Ldarg_1); if (field.FieldType.IsValueType) il.Emit(OpCodes.Unbox_Any, field.FieldType); il.Emit(OpCodes.Stsfld, field); } else { il.Emit(OpCodes.Ldarg_0); if (field.DeclaringType.IsValueType) { il.Emit(OpCodes.Unbox_Any, field.DeclaringType); } il.Emit(OpCodes.Ldarg_1); if (field.FieldType.IsValueType) il.Emit(OpCodes.Unbox_Any, field.FieldType); il.Emit(OpCodes.Stfld, field); } il.Emit(OpCodes.Ret); setter = (RD_SetField)dm.CreateDelegate(typeof(RD_SetField)); fsetter[field] = setter; } return setter; } internal static object CallMethod(object? @this, MethodInfo method, params object?[]? args) { if (method is null) throw new ArgumentNullException(nameof(method)); if (!mcaller.TryGetValue(method, out var caller)) { caller = method.CreateFastDelegate(true); mcaller[method] = caller; } return caller(@this, args ?? new object?[] { null }); } internal static object GetField(object? @this, FieldInfo field) { if (field is null) throw new ArgumentNullException(nameof(field)); try { return GetGetter(field)(@this); } catch (Exception e) { HKToolMod.logger.LogError(e); return field.GetValue(@this); } } internal static IntPtr GetFieldRef(object? @this, FieldInfo field) { if (field is null) throw new ArgumentNullException(nameof(field)); if (frefgetter.TryGetValue(field, out var getter)) return getter.Invoke(@this!); DynamicMethod dm = new("", MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, typeof(IntPtr), new Type[]{ typeof(object) }, (Type)field.DeclaringType, true); var il = dm.GetILGenerator(); if (!field.IsStatic) { il.Emit(OpCodes.Ldarg_0); if (field.DeclaringType.IsValueType) { il.Emit(OpCodes.Unbox_Any, field.DeclaringType); } il.Emit(OpCodes.Ldflda, field); } else { il.Emit(OpCodes.Ldsflda, field); } //il.Emit(OpCodes.Box, field.FieldType.MakeByRefType()); il.Emit(OpCodes.Ret); getter = (Func<object, IntPtr>)dm.CreateDelegate(typeof(Func<object, IntPtr>)); frefgetter[field] = getter; return getter.Invoke(@this!); } internal static void SetField(object? @this, FieldInfo field, object? val) { if (field is null) throw new ArgumentNullException(nameof(field)); try { GetSetter(field)(@this, val); } catch (Exception e) { HKToolMod.logger.LogError(e); field.SetValue(@this, val); } } }
import { connect } from 'react-redux' import * as Redux from 'redux' import { createStructuredSelector } from 'reselect' import toJS from '../../HoC/toJS' import { selectSideBarActive, selectSideBarDirection } from '../../selectors/sideBar'; import SideBar from '../../components/SideBar'; import { toggleSideBar } from '../../actions/sideBar'; import { push } from 'react-router-redux'; import { selectUserSettings } from '../../selectors/user'; import { setUser } from '../../actions/user'; const mapStateToProps = createStructuredSelector({ active: selectSideBarActive(), direction: selectSideBarDirection(), user: selectUserSettings() }) const mapDispatchToProps = ( dispatch: any ) => ({ toggleSideBar: (direction:string) => dispatch( toggleSideBar.success( {direction} ) ), setUser: (user:any) => dispatch( setUser.success( {user} )), push: ( url: string ) => dispatch( push( url ) ), }) as any export default Redux.compose( connect(mapStateToProps,mapDispatchToProps), toJS ) (SideBar) as any
# lwt-simple-multi-client-server Lwt の公式にあるサーバー実装 ``` dune exec ./main.exe ```
import React, { useState, useEffect } from 'react'; import { sha256 } from 'js-sha256'; import { Box, Text } from 'rebass'; import { ThemeProvider } from 'emotion-theming'; import Login from 'components/auth/login'; import { LoginProps } from 'components/auth/auth'; import Dashboard from './dashboard'; import { theme, GlobalStyles } from 'styles'; import Modal from 'components/modal'; import ChangePassword from './change-password'; type Props = { db: firebase.firestore.Firestore; }; const Admin: React.FC<Props> = ({ db }) => { // set defult to true -> development only const [isAuthenticated, setIsAuthenticated] = useState(false); const [adminEmail, setAdminEmail] = useState(''); const [showModal, setShowModal] = useState(false); const [changePassId, setChangePassId] = useState(''); const [isUnauthorized, setIsUnauthorized] = useState(false); const adminUserDbRef = db.collection('admin-user'); const debug = false; useEffect(() => { // skipping login on debug if (debug) { setIsAuthenticated(true); setAdminEmail('[email protected]'); } }, []); // password encrypted with sha256!! const login = async ({ email, password }: LoginProps) => { // authenticate user first const adminUser = await adminUserDbRef .where('email', '==', email) .where('password', '==', sha256(password)) .get(); const adminUserExists = (await adminUser.size) > 0; if (await adminUserExists) { setIsAuthenticated(true); setAdminEmail(email); if (password === '123456') { setShowModal(true); setChangePassId(adminUser.docs[0].id); } } else { setIsUnauthorized(true); } }; const logout = () => { setIsAuthenticated(false); }; return ( <ThemeProvider theme={theme}> <GlobalStyles /> {showModal && ( <Modal center={true}> <ChangePassword db={db} changePassId={changePassId} closeModal={() => { setShowModal(false); }} /> </Modal> )} {isAuthenticated ? ( <Dashboard db={db} logout={logout} adminEmail={adminEmail} /> ) : ( <Modal center={true}> <Box bg="#fff" p={[5]} width={['80vw', '70vw', '400px']}> <Login login={login} submitValue="Login as admin" /> {isUnauthorized && ( <Text variant="formError" mt={[4]} sx={{ textAlign: 'center' }} > Admin user unauthorized </Text> )} </Box> </Modal> )} </ThemeProvider> ); }; export { Admin };
/* * Copyright 2021 EPAM Systems * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package deployment_test import ( "encoding/json" "fmt" odahuflowv1alpha1 "github.com/odahu/odahu-flow/packages/operator/api/v1alpha1" "github.com/odahu/odahu-flow/packages/operator/pkg/apiclient/deployment" apis "github.com/odahu/odahu-flow/packages/operator/pkg/apis/deployment" "github.com/odahu/odahu-flow/packages/operator/pkg/config" "github.com/stretchr/testify/suite" "net/http" "net/http/httptest" "odahu-commons/predictors" "testing" ) var ( md = apis.ModelDeployment{ ID: "test-md", Spec: odahuflowv1alpha1.ModelDeploymentSpec{ Image: "image-name:tag", Predictor: predictors.OdahuMLServer.ID, }, } ) type mdSuite struct { suite.Suite testServer *httptest.Server client deployment.Client } func (s *mdSuite) SetupSuite() { s.testServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/api/v1/model/deployment/test-md": if r.Method != http.MethodGet { notFound(w, r) return } w.WriteHeader(http.StatusOK) mdBytes, err := json.Marshal(md) if err != nil { // Must not be occurred panic(err) } _, err = w.Write(mdBytes) if err != nil { // Must not be occurred panic(err) } // Mock endpoint that returns some HTML response (e.g. simulate Nginx error) case "/api/v1/model/deployment/get-html-response": w.WriteHeader(http.StatusOK) _, err := w.Write([]byte("<html>some error page</html>")) if err != nil { // Must not be occurred panic(err) } // Mock endpoint that does not response case "/api/v1/model/deployment/no-response": panic(http.ErrAbortHandler) default: notFound(w, r) } })) s.client = deployment.NewClient(config.AuthConfig{APIURL: s.testServer.URL}) } func (s *mdSuite) TearDownSuite() { s.testServer.Close() } func TestMdSuite(t *testing.T) { suite.Run(t, new(mdSuite)) } func notFound(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) _, err := fmt.Fprintf(w, "%s url not found", r.URL.Path) if err != nil { // Must not be occurred panic(err) } } func (s *mdSuite) TestGetDeployment() { mdFromClient, err := s.client.GetModelDeployment(md.ID) s.Assertions.NoError(err) s.Assertions.Equal(md, *mdFromClient) } func (s *mdSuite) TestGetDeployment_NotFound() { mdFromClient, err := s.client.GetModelDeployment("nonexistent-deployment") s.Assertions.Nil(mdFromClient) s.Assertions.Error(err) s.Assertions.Contains(err.Error(), "not found") } func (s *mdSuite) TestGetDeployment_CannotUnmarshal() { mdFromClient, err := s.client.GetModelDeployment("get-html-response") s.Assertions.Nil(mdFromClient) s.Assertions.Error(err) s.Assertions.Contains(err.Error(), "invalid character") } func (s *mdSuite) TestGetDeployment_NoResponse() { mdFromClient, err := s.client.GetModelDeployment("no-response") s.Assertions.Nil(mdFromClient) s.Assertions.Error(err) s.Assertions.Contains(err.Error(), "EOF") }
#include <exception> #include <stdexcept> #include "Time.h" unsigned int Time::max_year = 3000; unsigned int Time::min_year = 1970; string Time::default_format = "%Ex %EX"; Time::Time() { setTime(0); } Time::Time(time_t time) { setTime(time); } Time::Time(tm& time) { setTime(time); } Time::Time (unsigned int year, unsigned int mon, unsigned int mday, unsigned int hour, unsigned int min, unsigned int sec) { setTime(year, mon, mday, hour, min, sec); } void Time::setTime(time_t time) { if (isValid(time)) { m_time = time; } else { throw std::invalid_argument("time invalid!"); } } void Time::setTime(tm& time) { if (isValid(time)) { m_time = mktime(&time); } else { throw std::invalid_argument("time invalid!"); } } void Time::setTime(unsigned int year, unsigned int mon, unsigned int mday, unsigned int hour, unsigned int min, unsigned int sec) { if (isValid(year, mon, mday, hour, min, sec)) { tm time = {0}; time.tm_year = year - 1900; time.tm_mon = mon - 1; time.tm_mday = mday; time.tm_hour = hour; time.tm_min = min; time.tm_sec = sec; m_time = mktime(&time); } else { throw std::invalid_argument("time invalid!"); } } string Time::getTimeString(const string &format) const { char temp[100] = {0}; strftime(temp, 100, format.c_str(), localtime(&m_time)); return string(temp); } Time Time::now() { time_t time_stamp; time(&time_stamp); return Time(time_stamp); } bool Time::isValid(tm& time) { return isValid(time.tm_year + 1900, time.tm_mon + 1, time.tm_mday ,time.tm_hour, time.tm_min, time.tm_sec); } bool Time::isValid (unsigned int year, unsigned int mon, unsigned int mday, unsigned int hour, unsigned int min, unsigned int sec) { if (year < min_year || year > max_year) {return false;} if (mon < 1 || mon > 12) {return false;} unsigned int day_of_month[] = {31,28,31,30,31,30,31,31,30,31,30,31}; if (isLeapYear(year)) {++day_of_month[2-1];}//leap year if (mday < 1 || mday > day_of_month[mon - 1]) { return false;} if(hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60) {return false;} return true; } ostream& operator<<(ostream& out, const Time& src) { out << asctime(localtime(&src.m_time)); return out; } istream& operator>>(istream& in, Time& dst) { time_t time; in >> time; dst.setTime(time); return in; }
var searchData= [ ['widgets',['Widgets',['../chapter18-widget.html',1,'overview']]], ['world',['World',['../chapter7-world.html',1,'overview']]], ['w',['w',['../structchai3d_1_1c_quaternion.html#adbf105b4dd0da86c8fca8ab14a66fee1',1,'chai3d::cQuaternion']]], ['widgets',['Widgets',['../group__widgets.html',1,'']]], ['world',['World',['../group__world.html',1,'']]] ];
#ifndef MEL_BALLANDBEAM_HPP #define MEL_BALLANDBEAM_HPP #include <MEL/Core/Time.hpp> #include <MEL/Math/Constants.hpp> #include <MEL/Math/Functions.hpp> #include <MEL/Math/Integrator.hpp> class BallAndBeam { public: /// Steps the ball and beam simulation void step_simulation(mel::Time time, double position_ref, double velocity_ref); /// Resets the ball and beam inegrators void reset(); public: double K_player = 30; ///< stiffness between user and beam [N/m] double B_player = 1; ///< damping between user and beam [N-s/m] double g = 9.81; ///< accerlation due to gravity [m/s^2] double I = 0.025; ///< beam moment of inertia [kg*m^2] double m = 0.25; ///< ball mass [kg] double R = 0.03; ///< ball radius [m] double L = 0.8; ///< beam length [m] double tau; ///< torque acting on beam [Nm] double r, rd, rdd; ///< ball state [m, m/s m/s^2] double q, qd, qdd; ///< beam state [rad, rad/s, rad/s^2] private: mel::Integrator rdd2rd; ///< integrates r'' to r' mel::Integrator rd2r; ///< integrates r' to r mel::Integrator qdd2qd; ///< integrates q'' to r' mel::Integrator qd2q; ///< integrates q' to q }; #endif // MEL_BALLANDBEAM_HPP
module DataFactory def self.configuration @configuration ||= Configuration.new end def self.configure yield(configuration) end class Configuration attr_reader :channels attr_accessor :leagues, :url, :password def initialize @channels = %w(fixture calendario posiciones goleadores ficha plantelxcampeonato) @url = 'http://feed.datafactory.la' @password = '60l4Zz05' end end end
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // This test case tests the incremental compilation hash (ICH) implementation // for let expressions. // The general pattern followed here is: Change one thing between rev1 and rev2 // and make sure that the hash has changed, then change nothing between rev2 and // rev3 and make sure that the hash has not changed. // must-compile-successfully // revisions: cfail1 cfail2 cfail3 // compile-flags: -Z query-dep-graph #![allow(warnings)] #![feature(rustc_attrs)] #![crate_type="rlib"] // Change Name ----------------------------------------------------------------- #[cfg(cfail1)] pub fn change_name() { let _x = 2u64; } #[cfg(not(cfail1))] #[rustc_dirty(label="Hir", cfg="cfail2")] #[rustc_clean(label="Hir", cfg="cfail3")] #[rustc_metadata_dirty(cfg="cfail2")] #[rustc_metadata_clean(cfg="cfail3")] pub fn change_name() { let _y = 2u64; } // Add Type -------------------------------------------------------------------- #[cfg(cfail1)] pub fn add_type() { let _x = 2u32; } #[cfg(not(cfail1))] #[rustc_dirty(label="Hir", cfg="cfail2")] #[rustc_clean(label="Hir", cfg="cfail3")] #[rustc_metadata_dirty(cfg="cfail2")] #[rustc_metadata_clean(cfg="cfail3")] pub fn add_type() { let _x: u32 = 2u32; } // Change Type ----------------------------------------------------------------- #[cfg(cfail1)] pub fn change_type() { let _x: u64 = 2; } #[cfg(not(cfail1))] #[rustc_dirty(label="Hir", cfg="cfail2")] #[rustc_clean(label="Hir", cfg="cfail3")] #[rustc_metadata_dirty(cfg="cfail2")] #[rustc_metadata_clean(cfg="cfail3")] pub fn change_type() { let _x: u8 = 2; } // Change Mutability of Reference Type ----------------------------------------- #[cfg(cfail1)] pub fn change_mutability_of_reference_type() { let _x: &u64; } #[cfg(not(cfail1))] #[rustc_dirty(label="Hir", cfg="cfail2")] #[rustc_clean(label="Hir", cfg="cfail3")] #[rustc_metadata_dirty(cfg="cfail2")] #[rustc_metadata_clean(cfg="cfail3")] pub fn change_mutability_of_reference_type() { let _x: &mut u64; } // Change Mutability of Slot --------------------------------------------------- #[cfg(cfail1)] pub fn change_mutability_of_slot() { let mut _x: u64 = 0; } #[cfg(not(cfail1))] #[rustc_dirty(label="Hir", cfg="cfail2")] #[rustc_clean(label="Hir", cfg="cfail3")] #[rustc_metadata_dirty(cfg="cfail2")] #[rustc_metadata_clean(cfg="cfail3")] pub fn change_mutability_of_slot() { let _x: u64 = 0; } // Change Simple Binding to Pattern -------------------------------------------- #[cfg(cfail1)] pub fn change_simple_binding_to_pattern() { let _x = (0u8, 'x'); } #[cfg(not(cfail1))] #[rustc_dirty(label="Hir", cfg="cfail2")] #[rustc_clean(label="Hir", cfg="cfail3")] #[rustc_metadata_dirty(cfg="cfail2")] #[rustc_metadata_clean(cfg="cfail3")] pub fn change_simple_binding_to_pattern() { let (_a, _b) = (0u8, 'x'); } // Change Name in Pattern ------------------------------------------------------ #[cfg(cfail1)] pub fn change_name_in_pattern() { let (_a, _b) = (1u8, 'y'); } #[cfg(not(cfail1))] #[rustc_dirty(label="Hir", cfg="cfail2")] #[rustc_clean(label="Hir", cfg="cfail3")] #[rustc_metadata_dirty(cfg="cfail2")] #[rustc_metadata_clean(cfg="cfail3")] pub fn change_name_in_pattern() { let (_a, _c) = (1u8, 'y'); } // Add `ref` in Pattern -------------------------------------------------------- #[cfg(cfail1)] pub fn add_ref_in_pattern() { let (_a, _b) = (1u8, 'y'); } #[cfg(not(cfail1))] #[rustc_dirty(label="Hir", cfg="cfail2")] #[rustc_clean(label="Hir", cfg="cfail3")] #[rustc_metadata_dirty(cfg="cfail2")] #[rustc_metadata_clean(cfg="cfail3")] pub fn add_ref_in_pattern() { let (ref _a, _b) = (1u8, 'y'); } // Add `&` in Pattern ---------------------------------------------------------- #[cfg(cfail1)] pub fn add_amp_in_pattern() { let (_a, _b) = (&1u8, 'y'); } #[cfg(not(cfail1))] #[rustc_dirty(label="Hir", cfg="cfail2")] #[rustc_clean(label="Hir", cfg="cfail3")] #[rustc_metadata_dirty(cfg="cfail2")] #[rustc_metadata_clean(cfg="cfail3")] pub fn add_amp_in_pattern() { let (&_a, _b) = (&1u8, 'y'); } // Change Mutability of Binding in Pattern ------------------------------------- #[cfg(cfail1)] pub fn change_mutability_of_binding_in_pattern() { let (_a, _b) = (99u8, 'q'); } #[cfg(not(cfail1))] #[rustc_dirty(label="Hir", cfg="cfail2")] #[rustc_clean(label="Hir", cfg="cfail3")] #[rustc_metadata_dirty(cfg="cfail2")] #[rustc_metadata_clean(cfg="cfail3")] pub fn change_mutability_of_binding_in_pattern() { let (mut _a, _b) = (99u8, 'q'); } // Add Initializer ------------------------------------------------------------- #[cfg(cfail1)] pub fn add_initializer() { let _x: i16; } #[cfg(not(cfail1))] #[rustc_dirty(label="Hir", cfg="cfail2")] #[rustc_clean(label="Hir", cfg="cfail3")] #[rustc_metadata_dirty(cfg="cfail2")] #[rustc_metadata_clean(cfg="cfail3")] pub fn add_initializer() { let _x: i16 = 3i16; } // Change Initializer ---------------------------------------------------------- #[cfg(cfail1)] pub fn change_initializer() { let _x = 4u16; } #[cfg(not(cfail1))] #[rustc_dirty(label="Hir", cfg="cfail2")] #[rustc_clean(label="Hir", cfg="cfail3")] #[rustc_metadata_dirty(cfg="cfail2")] #[rustc_metadata_clean(cfg="cfail3")] pub fn change_initializer() { let _x = 5u16; }
我国JF22超高速风洞预计2022年建成 孙红雷说扫黑风暴这戏接对了 男子与亲外甥谈恋爱被骗100余万 女子公厕内拍下男子跪地偷窥全程 汤唯状态 迪丽热巴发长文告别乔晶晶 贵州发现6亿岁海绵宝宝 美国首例新冠死亡病例为2020年1月初 央视网评 饭圈文化该驱邪扶正了 国乒不组队参加今年亚锦赛 刘宪华把香菜让给王一博 塔利班称美延迟撤军将面临严重后果 高铁座位边的踏板别踩 孙兴被软禁 乔任梁父母回应恶评 美国数千只沙币被冲上海滩死亡 高校师生返校前提供48小时核酸证明 迪丽热巴好适合演女明星 汪东城晒吴尊AI女装换脸视频 大江暴揍孙兴 扫黑风暴 胖哥俩在执法人员上门检查前丢弃食材 张艺兴12年前用电脑和韩庚合影 冯提莫素颜状态 丁程鑫发文谈加入快乐家族 跑酷不去重庆的原因 翟潇闻演的失恋好真实 过期食物对人体伤害有多大 再不开学我都把证考完了 阳光玫瑰从每斤300元跌至10元 郑州一男子防车淹用砖支车被压身亡 塔利班宣布特赦阿富汗总统加尼 刘雨昕道歉 杨洋发文告别于途 买来补身的甲鱼比你还虚 买个菜感觉像上了天 杨舒予奥运首秀跑错入场仪式 严浩翔由你榜最年轻夺冠歌手 20年陈皮一斤卖到3000元 杨超越送孙俪披荆斩棘四件套 原来浪漫永不过期 外交部回应美国给立陶宛撑腰 原来光能被画出来 嫌疑人被抓时身着跳出三界外T恤 美国7个月大双胞胎被洪水冲走 你是我的荣耀观后感 欧阳娜娜水手服造型 快递小哥因想休息故意酒驾求被抓 今天的这些0来之不易 赵继伟王君瑞领证 阿富汗被辞退前部长在德国送外卖 借条的正确写法
#include <iostream> #include <sstream> #include <gtest/gtest.h> #include <gadgetlib2/pp.hpp> #include <gadgetlib2/protoboard.hpp> #include <gadgetlib2/gadget.hpp> using ::std::cerr; using ::std::cout; using ::std::endl; using ::std::stringstream; #define EXHAUSTIVE_N 4 namespace PCP_Project { TEST(ConstraintsLib,R1P_AND_Gadget) { initPublicParamsFromEdwardsParam(); auto pb = Protoboard::create(R1P); VariableArray x(3, "x"); Variable y("y"); auto andGadget = AND_Gadget::create(pb, x, y); andGadget->generateConstraints(); pb->val(x[0]) = 0; pb->val(x[1]) = 1; pb->val(x[2]) = 1; andGadget->generateWitness(); EXPECT_TRUE(pb->val(y) == 0); EXPECT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); pb->val(y) = 1; EXPECT_FALSE(pb->isSatisfied()); pb->val(x[0]) = 1; andGadget->generateWitness(); EXPECT_TRUE(pb->val(y) == 1); EXPECT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); pb->val(y) = 0; EXPECT_FALSE(pb->isSatisfied()); } TEST(ConstraintsLib,LD2_AND_Gadget) { auto pb = Protoboard::create(LD2); VariableArray x(3,"x"); Variable y("y"); auto andGadget = AND_Gadget::create(pb, x, y); andGadget->generateConstraints(); pb->val(x[0]) = 0; pb->val(x[1]) = 1; pb->val(x[2]) = 1; andGadget->generateWitness(); EXPECT_TRUE(pb->val(y) == 0); EXPECT_TRUE(pb->isSatisfied()); pb->val(y) = 1; EXPECT_FALSE(pb->isSatisfied()); pb->val(x[0]) = 1; andGadget->generateWitness(); EXPECT_TRUE(pb->val(y) == 1); EXPECT_TRUE(pb->isSatisfied()); pb->val(y) = 0; EXPECT_FALSE(pb->isSatisfied()); } void andGadgetExhaustiveTest(ProtoboardPtr pb, size_t n); // Forward declaration TEST(ConstraintsLib,R1P_ANDGadget_Exhaustive) { initPublicParamsFromEdwardsParam(); for(int n = 1; n <= EXHAUSTIVE_N; ++n) { SCOPED_TRACE(FMT("n = %u \n", n)); auto pb = Protoboard::create(R1P); andGadgetExhaustiveTest(pb, n); } } TEST(ConstraintsLib,LD2_ANDGadget_Exhaustive) { for(int n = 2; n <= EXHAUSTIVE_N; ++n) { SCOPED_TRACE(FMT("n = %u \n", n)); auto pb = Protoboard::create(LD2); andGadgetExhaustiveTest(pb, n); } } TEST(ConstraintsLib,BinaryAND_Gadget) { auto pb = Protoboard::create(LD2); Variable input1("input1"); Variable input2("input2"); Variable result("result"); auto andGadget = AND_Gadget::create(pb, input1, input2, result); andGadget->generateConstraints(); pb->val(input1) = pb->val(input2) = 0; andGadget->generateWitness(); ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); ASSERT_EQ(pb->val(result), 0); pb->val(result) = 1; ASSERT_FALSE(pb->isSatisfied()); pb->val(result) = 0; pb->val(input1) = 1; ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); pb->val(input2) = 1; ASSERT_FALSE(pb->isSatisfied()); andGadget->generateWitness(); ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); ASSERT_EQ(pb->val(result), 1); } void orGadgetExhaustiveTest(ProtoboardPtr pb, size_t n); // Forward declaration TEST(ConstraintsLib,R1P_ORGadget_Exhaustive) { initPublicParamsFromEdwardsParam(); for(int n = 1; n <= EXHAUSTIVE_N; ++n) { SCOPED_TRACE(FMT("n = %u \n", n)); auto pb = Protoboard::create(R1P); orGadgetExhaustiveTest(pb, n); } } TEST(ConstraintsLib,LD2_ORGadget_Exhaustive) { for(int n = 2; n <= EXHAUSTIVE_N; ++n) { SCOPED_TRACE(FMT("n = %u \n", n)); auto pb = Protoboard::create(LD2); orGadgetExhaustiveTest(pb, n); } } TEST(ConstraintsLib,BinaryOR_Gadget) { auto pb = Protoboard::create(LD2); Variable input1("input1"); Variable input2("input2"); Variable result("result"); auto orGadget = OR_Gadget::create(pb, input1, input2, result); orGadget->generateConstraints(); pb->val(input1) = pb->val(input2) = 0; orGadget->generateWitness(); ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); ASSERT_EQ(pb->val(result), 0); pb->val(result) = 1; ASSERT_FALSE(pb->isSatisfied()); pb->val(result) = 0; pb->val(input1) = 1; ASSERT_FALSE(pb->isSatisfied()); pb->val(result) = 1; ASSERT_CONSTRAINTS_SATISFIED(pb); pb->val(input2) = 1; orGadget->generateWitness(); ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); ASSERT_EQ(pb->val(result), 1); } TEST(ConstraintsLib,R1P_InnerProductGadget_Exhaustive) { initPublicParamsFromEdwardsParam(); const size_t n = EXHAUSTIVE_N; auto pb = Protoboard::create(R1P); VariableArray A(n, "A"); VariableArray B(n, "B"); Variable result("result"); auto g = InnerProduct_Gadget::create(pb, A, B, result); g->generateConstraints(); for (size_t i = 0; i < 1u<<n; ++i) { for (size_t j = 0; j < 1u<<n; ++j) { size_t correct = 0; for (size_t k = 0; k < n; ++k) { pb->val(A[k]) = i & (1u<<k) ? 1 : 0; pb->val(B[k]) = j & (1u<<k) ? 1 : 0; correct += (i & (1u<<k)) && (j & (1u<<k)) ? 1 : 0; } g->generateWitness(); EXPECT_EQ(pb->val(result) , FElem(correct)); EXPECT_TRUE(pb->isSatisfied()); // negative test pb->val(result) = 100*n+19; EXPECT_FALSE(pb->isSatisfied()); } } } TEST(ConstraintsLib,LD2_InnerProductGadget_Exhaustive) { initPublicParamsFromEdwardsParam(); const size_t n = EXHAUSTIVE_N > 1 ? EXHAUSTIVE_N -1 : EXHAUSTIVE_N; for(int len = 1; len <= n; ++len) { auto pb = Protoboard::create(LD2); VariableArray a(len, "a"); VariableArray b(len, "b"); Variable result("result"); auto ipGadget = InnerProduct_Gadget::create(pb, a, b, result); ipGadget->generateConstraints(); // Generate Inputs & Witnesses vec_GF2E a_vec; a_vec.SetLength(len); for(int h = 0; h < len; ++h) { // iterate over a's elements for(int j = 0; j < 1u<<n; ++j) { // all possible options for a[h] GF2X a_h; for(int coeff = 0; coeff < n; ++coeff) { // set a[h] coefficients SetCoeff(a_h, coeff, j & 1<<coeff); } a_vec[h] = to_GF2E(a_h); pb->val(a[h]) = to_GF2E(a_h); vec_GF2E b_vec; b_vec.SetLength(len); for(int i = 0; i < len; ++i) { pb->val(b[i]) = 0; } for(int i = 0; i < len; ++i) { // iterate over b's elements for(int k = 0; k < 1u<<n; ++k) { // all possible options for b[i] GF2X b_i; for(int coeff = 0; coeff < n; ++coeff) { // set b[i] coefficients SetCoeff(b_i, coeff, k & 1<<coeff); } b_vec[i] = to_GF2E(b_i); pb->val(b[i]) = to_GF2E(b_i); ipGadget->generateWitness(); GF2E resultGF2E; InnerProduct(resultGF2E, a_vec, b_vec); ::std::stringstream s; s << endl << "i = " << i << endl << "< " << a_vec << " > * < " << b_vec << " > = " << resultGF2E << endl << pb->annotation(); SCOPED_TRACE(s.str()); EXPECT_EQ(pb->val(result), FElem(resultGF2E)); EXPECT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); // Negative test pb->val(result) = resultGF2E + to_GF2E(1); EXPECT_FALSE(pb->isSatisfied()); } } } } } } TEST(ConstraintsLib,R1P_LooseMUX_Gadget_Exhaustive) { initPublicParamsFromEdwardsParam(); const size_t n = EXHAUSTIVE_N; auto pb = Protoboard::create(R1P); VariableArray arr(1<<n, "arr"); Variable index("index"); Variable result("result"); Variable success_flag("success_flag"); auto g = LooseMUX_Gadget::create(pb, arr, index, result, success_flag); g->generateConstraints(); for (size_t i = 0; i < 1u<<n; ++i) { pb->val(arr[i]) = (19*i) % (1u<<n); } for (int idx = -1; idx <= (1<<n); ++idx) { pb->val(index) = idx; g->generateWitness(); if (0 <= idx && idx <= (1<<n) - 1) { EXPECT_EQ(pb->val(result) , (19*idx) % (1u<<n)); EXPECT_EQ(pb->val(success_flag) , 1); EXPECT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); pb->val(result) -= 1; EXPECT_FALSE(pb->isSatisfied()); } else { EXPECT_EQ(pb->val(success_flag) , 0); EXPECT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); pb->val(success_flag) = 1; EXPECT_FALSE(pb->isSatisfied()); } } } // Forward declaration void packing_Gadget_R1P_ExhaustiveTest(ProtoboardPtr unpackingPB, ProtoboardPtr packingPB, const int n, VariableArray packed, VariableArray unpacked, GadgetPtr packingGadget, GadgetPtr unpackingGadget); TEST(ConstraintsLib,R1P_Packing_Gadgets) { initPublicParamsFromEdwardsParam(); auto unpackingPB = Protoboard::create(R1P); auto packingPB = Protoboard::create(R1P); const int n = EXHAUSTIVE_N; { // test CompressionPacking_Gadget SCOPED_TRACE("testing CompressionPacking_Gadget"); VariableArray packed(1, "packed"); VariableArray unpacked(n, "unpacked"); auto packingGadget = CompressionPacking_Gadget::create(packingPB, unpacked, packed, PackingMode::PACK); auto unpackingGadget = CompressionPacking_Gadget::create(unpackingPB, unpacked, packed, PackingMode::UNPACK); packing_Gadget_R1P_ExhaustiveTest(unpackingPB, packingPB, n, packed, unpacked, packingGadget, unpackingGadget); } { // test IntegerPacking_Gadget SCOPED_TRACE("testing IntegerPacking_Gadget"); VariableArray packed(1, "packed"); VariableArray unpacked(n, "unpacked"); auto packingGadget = IntegerPacking_Gadget::create(packingPB, unpacked, packed, PackingMode::PACK); auto unpackingGadget = IntegerPacking_Gadget::create(unpackingPB, unpacked, packed, PackingMode::UNPACK); packing_Gadget_R1P_ExhaustiveTest(unpackingPB, packingPB, n, packed, unpacked, packingGadget, unpackingGadget); } } TEST(ConstraintsLib,LD2_CompressionPacking_Gadget) { auto unpackingPB = Protoboard::create(LD2); auto packingPB = Protoboard::create(LD2); const int n = EXHAUSTIVE_N; VariableArray packed(1, "packed"); VariableArray unpacked(n, "unpacked"); auto packingGadget = CompressionPacking_Gadget::create(packingPB, unpacked, packed, PackingMode::PACK); auto unpackingGadget = CompressionPacking_Gadget::create(unpackingPB, unpacked, packed, PackingMode::UNPACK); packingGadget->generateConstraints(); unpackingGadget->generateConstraints(); for(int i = 0; i < 1u<<n; ++i) { ::std::vector<int> bits(n); size_t packedGF2X = 0; for(int j = 0; j < n; ++j) { bits[j] = i & 1u<<j ? 1 : 0 ; packedGF2X |= bits[j]<<j; packingPB->val(unpacked[j]) = bits[j]; // set unpacked bits in the packing protoboard } // set the packed value in the unpacking protoboard unpackingPB->val(packed[0]) = Algebra::mapIntegerToFieldElement(0,Algebra::ExtensionDegree,packedGF2X); unpackingGadget->generateWitness(); packingGadget->generateWitness(); stringstream s; s << endl << "i = " << i << ", Packed Value: " << Algebra::mapIntegerToFieldElement(0,Algebra::ExtensionDegree,packedGF2X) << endl; SCOPED_TRACE(s.str()); ASSERT_TRUE(unpackingPB->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); ASSERT_TRUE(packingPB->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); // check packed value is correct ASSERT_EQ(packingPB->val(packed[0]), Algebra::mapIntegerToFieldElement(0,Algebra::ExtensionDegree,packedGF2X)); for(int j = 0; j < n; ++j) { // Tests for unpacking gadget SCOPED_TRACE(FMT("\nValue being packed/unpacked: %u, bits[%u] = %u" , i, j, bits[j])); ASSERT_EQ(unpackingPB->val(unpacked[j]), bits[j] ? 1 : 0); // check bit correctness packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = 1-bits[j]; // flip bit ASSERT_FALSE(unpackingPB->isSatisfied()); ASSERT_FALSE(packingPB->isSatisfied()); packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = bits[j]; // restore bit // special case to test booleanity checks. Cause arithmetic constraints to stay // satisfied while ruining Booleanity if (j > 0 && bits[j]==1 && bits[j-1]==0 ) { packingPB->val(unpacked[j-1]) = unpackingPB->val(unpacked[j-1]) = getGF2E_X(); packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = 0; ASSERT_FALSE(unpackingPB->isSatisfied()); ASSERT_TRUE(packingPB->isSatisfied()); // packing should not enforce Booleanity // restore correct state packingPB->val(unpacked[j-1]) = unpackingPB->val(unpacked[j-1]) = 0; packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = 1; } } } } TEST(ConstraintsLib, LD2_CompressionPacking_Gadget_largeNums) { // Test packing/unpacking for the case of more than 1 packed element. using ::std::vector; //initialize the context field const int packedSize = 2; const int unpackedSize = packedSize * IRR_DEGREE; vector<int64_t> packingVal(packedSize); for(int i = 0; i < packedSize; ++i) { packingVal[i] = i; } packingVal[0] = 42; // The Answer To Life, the Universe and Everything packingVal[1] = 26-9-1984; // My birthday auto unpackingPB = Protoboard::create(LD2); auto packingPB = Protoboard::create(LD2); VariableArray packed(packedSize, "packed"); VariableArray unpacked(unpackedSize, "unpacked"); auto packingGadget = CompressionPacking_Gadget::create(packingPB, unpacked, packed, PackingMode::PACK); auto unpackingGadget = CompressionPacking_Gadget::create(unpackingPB, unpacked, packed, PackingMode::UNPACK); packingGadget->generateConstraints(); unpackingGadget->generateConstraints(); vector<int> bits(unpackedSize); vector<size_t> packedGF2X(packedSize,0); for(int j = 0; j < unpackedSize; ++j) { bits[j] = packingVal[j / IRR_DEGREE] & 1ul<<(j % IRR_DEGREE) ? 1 : 0; packedGF2X[j / IRR_DEGREE] |= bits[j]<<(j % IRR_DEGREE); packingPB->val(unpacked[j]) = bits[j]; // set unpacked bits in the packing protoboard } // set the packed value in the unpacking protoboard for(int j = 0; j < packedSize; ++j) { unpackingPB->val(packed[j]) = Algebra::mapIntegerToFieldElement(0,Algebra::ExtensionDegree,packedGF2X[j]); } unpackingGadget->generateWitness(); packingGadget->generateWitness(); ASSERT_TRUE(unpackingPB->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); ASSERT_TRUE(packingPB->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); // check packed values are correct for(int j = 0; j < packedSize; ++j) { ASSERT_EQ(packingPB->val(packed[j]), Algebra::mapIntegerToFieldElement(0,Algebra::ExtensionDegree,packedGF2X[j]); } for(int j = 0; j < unpackedSize; ++j) { // Tests for unpacking gadget SCOPED_TRACE(FMT("j = %lu", j)); ASSERT_EQ(unpackingPB->val(unpacked[j]), bits[j] ? 1 : 0); // check bit correctness packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = 1-bits[j]; // flip bit ASSERT_FALSE(unpackingPB->isSatisfied()); ASSERT_FALSE(packingPB->isSatisfied()); packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = bits[j]; // restore bit } } void equalsConstTest(ProtoboardPtr pb); // Forward declaration TEST(ConstraintsLib,R1P_EqualsConst_Gadget) { initPublicParamsFromEdwardsParam(); auto pb = Protoboard::create(R1P); equalsConstTest(pb); } TEST(ConstraintsLib,LD2_EqualsConst_Gadget) { auto pb = Protoboard::create(LD2); equalsConstTest(pb); } TEST(ConstraintsLib,ConditionalFlag_Gadget) { initPublicParamsFromEdwardsParam(); auto pb = Protoboard::create(R1P); FlagVariable flag; Variable condition("condition"); auto cfGadget = ConditionalFlag_Gadget::create(pb, condition, flag); cfGadget->generateConstraints(); pb->val(condition) = 1; cfGadget->generateWitness(); ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); pb->val(condition) = 42; cfGadget->generateWitness(); ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); ASSERT_EQ(pb->val(flag),1); pb->val(condition) = 0; ASSERT_FALSE(pb->isSatisfied()); cfGadget->generateWitness(); ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); ASSERT_EQ(pb->val(flag),0); pb->val(flag) = 1; ASSERT_FALSE(pb->isSatisfied()); } TEST(ConstraintsLib,LogicImplication_Gadget) { auto pb = Protoboard::create(LD2); FlagVariable flag; Variable condition("condition"); auto implyGadget = LogicImplication_Gadget::create(pb, condition, flag); implyGadget->generateConstraints(); pb->val(condition) = 1; pb->val(flag) = 0; ASSERT_FALSE(pb->isSatisfied()); implyGadget->generateWitness(); ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); ASSERT_EQ(pb->val(flag), 1); pb->val(condition) = 0; ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); implyGadget->generateWitness(); ASSERT_EQ(pb->val(flag), 1); pb->val(flag) = 0; ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); } void andGadgetExhaustiveTest(ProtoboardPtr pb, size_t n) { VariableArray inputs(n, "inputs"); Variable output("output"); auto andGadget = AND_Gadget::create(pb, inputs, output); andGadget->generateConstraints(); for (size_t curInput = 0; curInput < 1u<<n; ++curInput) { for (size_t maskBit = 0; maskBit < n; ++maskBit) { pb->val(inputs[maskBit]) = (curInput & (1u<<maskBit)) ? 1 : 0; } andGadget->generateWitness(); { SCOPED_TRACE(FMT("Positive (completeness) test failed. curInput: %u", curInput)); EXPECT_TRUE(pb->isSatisfied()); } { SCOPED_TRACE(pb->annotation()); SCOPED_TRACE(FMT("Negative (soundness) test failed. curInput: %u, Constraints " "are:", curInput)); pb->val(output) = (curInput == ((1u<<n) - 1)) ? 0 : 1; EXPECT_FALSE(pb->isSatisfied()); } } } void orGadgetExhaustiveTest(ProtoboardPtr pb, size_t n) { VariableArray inputs(n, "inputs"); Variable output("output"); auto orGadget = OR_Gadget::create(pb, inputs, output); orGadget->generateConstraints(); for (size_t curInput = 0; curInput < 1u<<n; ++curInput) { for (size_t maskBit = 0; maskBit < n; ++maskBit) { pb->val(inputs[maskBit]) = (curInput & (1u<<maskBit)) ? 1 : 0; } orGadget->generateWitness(); { SCOPED_TRACE(FMT("Positive (completeness) test failed. curInput: %u", curInput)); ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); } { SCOPED_TRACE(pb->annotation()); SCOPED_TRACE(FMT("Negative (soundness) test failed. curInput: %u, Constraints " "are:", curInput)); pb->val(output) = (curInput == 0) ? 1 : 0; ASSERT_FALSE(pb->isSatisfied()); } } } void packing_Gadget_R1P_ExhaustiveTest(ProtoboardPtr unpackingPB, ProtoboardPtr packingPB, const int n, VariableArray packed, VariableArray unpacked, GadgetPtr packingGadget, GadgetPtr unpackingGadget) { packingGadget->generateConstraints(); unpackingGadget->generateConstraints(); for(int i = 0; i < 1u<<n; ++i) { ::std::vector<int> bits(n); for(int j = 0; j < n; ++j) { bits[j] = i & 1u<<j ? 1 : 0 ; packingPB->val(unpacked[j]) = bits[j]; // set unpacked bits in the packing protoboard } unpackingPB->val(packed[0]) = i; // set the packed value in the unpacking protoboard unpackingGadget->generateWitness(); packingGadget->generateWitness(); ASSERT_TRUE(unpackingPB->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED)); ASSERT_TRUE(packingPB->isSatisfied()); ASSERT_EQ(packingPB->val(packed[0]), i); // check packed value is correct for(int j = 0; j < n; ++j) { // Tests for unpacking gadget SCOPED_TRACE(FMT("\nValue being packed/unpacked: %u, bits[%u] = %u" , i, j, bits[j])); ASSERT_EQ(unpackingPB->val(unpacked[j]), bits[j]); // check bit correctness packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = 1-bits[j]; // flip bit ASSERT_FALSE(unpackingPB->isSatisfied()); ASSERT_FALSE(packingPB->isSatisfied()); packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = bits[j]; // restore bit // special case to test booleanity checks. Cause arithmetic constraints to stay // satisfied while ruining Booleanity if (j > 0 && bits[j]==1 && bits[j-1]==0 ) { packingPB->val(unpacked[j-1]) = unpackingPB->val(unpacked[j-1]) = 2; packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = 0; ASSERT_FALSE(unpackingPB->isSatisfied()); ASSERT_TRUE(packingPB->isSatisfied()); // packing should not enforce Booleanity // restore correct state packingPB->val(unpacked[j-1]) = unpackingPB->val(unpacked[j-1]) = 0; packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = 1; } } } } void equalsConstTest(ProtoboardPtr pb) { Variable input("input"); Variable result("result"); auto gadget = EqualsConst_Gadget::create(pb, 0, input, result); gadget->generateConstraints(); pb->val(input) = 0; gadget->generateWitness(); // Positive test for input == n EXPECT_EQ(pb->val(result), 1); EXPECT_TRUE(pb->isSatisfied()); // Negative test pb->val(result) = 0; EXPECT_FALSE(pb->isSatisfied()); // Positive test for input != n pb->val(input) = 1; gadget->generateWitness(); EXPECT_EQ(pb->val(result), 0); EXPECT_TRUE(pb->isSatisfied()); // Negative test pb->val(input) = 0; EXPECT_FALSE(pb->isSatisfied()); } } // namespace PCP_Project
from __future__ import division import autopath import py import math import random import sets exclude_files = ["__init__.py", "autopath.py", "conftest.py"] def include_file(path): if ("test" in str(path) or "tool" in str(path) or "documentation" in str(path) or "_cache" in str(path)): return False if path.basename in exclude_files: return False return True def get_mod_from_path(path): dirs = path.get("dirname")[0].split("/") pypyindex = dirs.index("pypy") return ".".join(dirs[pypyindex:] + path.get("purebasename")) def find_references(path): refs = [] for line in path.open("r"): if line.startswith(" "): # ignore local imports to reduce graph size continue if "\\" in line: #ignore line continuations continue line = line.strip() line = line.split("#")[0].strip() if line.startswith("import pypy."): # import pypy.bla.whatever if " as " not in line: refs.append((line[7:].strip(), None)) else: # import pypy.bla.whatever as somethingelse assert line.count(" as ") == 1 line = line.split(" as ") refs.append((line[0][7:].strip(), line[1].strip())) elif line.startswith("from ") and "pypy" in line: #from pypy.b import a line = line[5:] if " as " not in line: line = line.split(" import ") what = line[1].split(",") for w in what: refs.append((line[0].strip() + "." + w.strip(), None)) else: # prom pypy.b import a as c if line.count(" as ") != 1 or "," in line: print"can't handle this: " + line continue line = line.split(" as ") what = line[0].replace(" import ", ".").replace(" ", "") refs.append((what, line[1].strip())) return refs def get_module(ref, imports): ref = ref.split(".") i = len(ref) while i: possible_mod = ".".join(ref[:i]) if possible_mod in imports: return possible_mod i -= 1 return None def casteljeau(points, t): points = points[:] while len(points) > 1: for i in range(len(points) - 1): points[i] = points[i] * (1 - t) + points[i + 1] * t del points[-1] return points[0] def color(t): points = [0, 0, 1, 0, 0] casteljeau([0, 0, 1, 0, 0], t) / 0.375 class ModuleGraph(object): def __init__(self, path): self.imports = {} self.clusters = {} self.mod_to_cluster = {} for f in path.visit("*.py"): if include_file(f): self.imports[get_mod_from_path(f)] = find_references(f) self.remove_object_refs() self.remove_double_refs() self.incoming = {} for mod in self.imports: self.incoming[mod] = sets.Set() for mod, refs in self.imports.iteritems(): for ref in refs: if ref[0] in self.incoming: self.incoming[ref[0]].add(mod) self.remove_single_nodes() self.topgraph_properties = ["rankdir=LR"] def remove_object_refs(self): # reduces cases like import pypy.translator.genc.basetype.CType to # import pypy.translator.genc.basetype for mod, refs in self.imports.iteritems(): i = 0 while i < len(refs): if refs[i][0] in self.imports: i += 1 else: nref = get_module(refs[i][0], self.imports) if nref is None: print "removing", repr(refs[i]) del refs[i] else: refs[i] = (nref, None) i += 1 def remove_double_refs(self): # remove several references to the same module for mod, refs in self.imports.iteritems(): i = 0 seen_refs = sets.Set() while i < len(refs): if refs[i] not in seen_refs: seen_refs.add(refs[i]) i += 1 else: del refs[i] def remove_single_nodes(self): # remove nodes that have no attached edges rem = [] for mod, refs in self.imports.iteritems(): if len(refs) == 0 and len(self.incoming[mod]) == 0: rem.append(mod) for m in rem: del self.incoming[m] del self.imports[m] def create_clusters(self): self.topgraph_properties.append("compound=true;") self.clustered = True hierarchy = [sets.Set() for i in range(6)] for mod in self.imports: for i, d in enumerate(mod.split(".")): hierarchy[i].add(d) for i in range(6): if len(hierarchy[i]) != 1: break for mod in self.imports: cluster = mod.split(".")[i] if i == len(mod.split(".")) - 1: continue if cluster not in self.clusters: self.clusters[cluster] = sets.Set() self.clusters[cluster].add(mod) self.mod_to_cluster[mod] = cluster def remove_tangling_randomly(self): # remove edges to nodes that have a lot incoming edges randomly tangled = [] for mod, incoming in self.incoming.iteritems(): if len(incoming) > 10: tangled.append(mod) for mod in tangled: remove = sets.Set() incoming = self.incoming[mod] while len(remove) < len(incoming) * 0.80: remove.add(random.choice(list(incoming))) for rem in remove: for i in range(len(self.imports[rem])): if self.imports[rem][i][1] == mod: break del self.imports[rem][i] incoming.remove(rem) print "removing", mod, "<-", rem self.remove_single_nodes() def dotfile(self, dot): f = dot.open("w") f.write("digraph G {\n") for prop in self.topgraph_properties: f.write("\t%s\n" % prop) #write clusters and inter-cluster edges for cluster, nodes in self.clusters.iteritems(): f.write("\tsubgraph cluster_%s {\n" % cluster) f.write("\t\tstyle=filled;\n\t\tcolor=lightgrey\n") for node in nodes: f.write('\t\t"%s";\n' % node[5:]) for mod, refs in self.imports.iteritems(): for ref in refs: if mod in nodes and ref[0] in nodes: f.write('\t\t"%s" -> "%s";\n' % (mod[5:], ref[0][5:])) f.write("\t}\n") #write edges between clusters for mod, refs in self.imports.iteritems(): try: nodes = self.clusters[self.mod_to_cluster[mod]] except KeyError: nodes = sets.Set() for ref in refs: if ref[0] not in nodes: f.write('\t"%s" -> "%s";\n' % (mod[5:], ref[0][5:])) f.write("}") f.close() if __name__ == "__main__": import sys if len(sys.argv) > 1: path = py.path.local(sys.argv[1]) else: path = py.path.local(".") gr = ModuleGraph(path) gr.create_clusters() dot = path.join("import_graph.dot") gr.dotfile(dot)
import React from 'react'; import { Paragraph, Page, ChapterTitle } from 'components'; import PageLayout from 'layouts/PageLayout'; export default () => ( <PageLayout> <Page> <ChapterTitle>A new kind in the block</ChapterTitle> <Paragraph> During the last few years, media have periodically reported news about Bitcoin. Sometimes it was about its incredible raise in price, sometimes about its incredible drop in price and sometimes about how Bitcoin was allegedly used by the criminals all over the world. Lots of people labeled Bitcoin as a ponzi scheme, other compared Bitcoin to the tulips bubble of 1637. Meanwhile, someone else started digging deeper, trying to understand how to make it possible for people all over the world to transfer money without a bank. They found a system that was open, public, censorship-resistant, secure and where innovation could be developed without asking any permission: the Blockchain technology. </Paragraph> <Paragraph> The Blockchain technology is becoming one of the top strategic priorities of the most influential companies and business leaders worldwide, with the promise of reducing costs, enhance trust, minimise inefficiencies and radically transform business models. </Paragraph> </Page> </PageLayout> );
<?php use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class RoleSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('roles')->insert([ ['name' => 'Administrador', 'unalterable' => 1], ['name' => 'Técnico', 'unalterable' => 0], ['name' => 'Viabilidade', 'unalterable' => 0], ['name' => 'Operacional', 'unalterable' => 0], ['name' => 'Mapper', 'unalterable' => 0], ['name' => 'Comercial', 'unalterable' => 0], ['name' => 'Avançar todos', 'unalterable' => 0], ['name' => 'Retornar todos', 'unalterable' => 0], ['name' => 'Reporter', 'unalterable' => 0] ]); } }
package com.icthh.xm.uaa.service; import com.icthh.xm.commons.lep.LogicExtensionPoint; import com.icthh.xm.commons.lep.spring.LepService; import com.icthh.xm.commons.logging.util.MdcUtils; import com.icthh.xm.commons.tenant.TenantContextHolder; import com.icthh.xm.commons.tenant.TenantContextUtils; import com.icthh.xm.uaa.commons.UaaUtils; import com.icthh.xm.uaa.commons.XmRequestContextHolder; import com.icthh.xm.uaa.domain.User; import com.icthh.xm.uaa.service.mail.MailService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.transaction.annotation.Transactional; @LepService(group = "service.account") @Transactional @RequiredArgsConstructor @Slf4j public class AccountMailService { private final TenantContextHolder tenantContextHolder; private final XmRequestContextHolder xmRequestContextHolder; private final MailService mailService; @LogicExtensionPoint("SendMailOnRegistration") public void sendMailOnRegistration(User user) { mailService.sendActivationEmail(user, UaaUtils.getApplicationUrl(xmRequestContextHolder), TenantContextUtils.getRequiredTenantKey(tenantContextHolder), MdcUtils.getRid()); } @LogicExtensionPoint("SendMailOnPasswordReset") public void sendMailOnPasswordResetFinish(User user) { mailService.sendPasswordChangedMail(user, UaaUtils.getApplicationUrl(xmRequestContextHolder), TenantContextUtils.getRequiredTenantKey(tenantContextHolder), MdcUtils.getRid()); } @LogicExtensionPoint("SendMailOnPasswordInit") public void sendMailOnPasswordInit(User user) { mailService.sendPasswordResetMail(user, UaaUtils.getApplicationUrl(xmRequestContextHolder), TenantContextUtils.getRequiredTenantKey(tenantContextHolder), MdcUtils.getRid()); } @LogicExtensionPoint("SendSocialRegistrationValidationEmail") public void sendSocialRegistrationValidationEmail(User user ,String providerId) { mailService.sendSocialRegistrationValidationEmail(user, providerId, UaaUtils.getApplicationUrl(xmRequestContextHolder), TenantContextUtils.getRequiredTenantKey(tenantContextHolder), MdcUtils.getRid()); } }
# frozen_string_literal: true require 'sinatra' require 'dotenv' require 'line/bot' $atis = [] def client Dotenv.load @client ||= Line::Bot::Client.new do |config| config.channel_secret = ENV['LINE_CHANNEL_SECRET'] config.channel_token = ENV['LINE_CHANNEL_TOKEN'] end end def get_atis url = URI.parse(ENV['ATIS_URL']) res = Net::HTTP.get_response(url) halt 403, { 'Content-Type' => 'text/plain' }, 'Bad Request' unless res.code != 200 $atis = JSON.parse(res.body) end post '/metar/callback' do body = request.body.read signature = request.env['HTTP_X_LINE_SIGNATURE'] halt 400, { 'Content-Type' => 'text/plain' }, 'Bad Request' unless client.validate_signature(body, signature) events = client.parse_events_from(body) events.each do |event| case event when Line::Bot::Event::Message case event.type when Line::Bot::Event::MessageType::Text messages = [] stations = event.message['text'].upcase.split(/[,|\s+]/, 0).reject(&:empty?) get_atis unless stations.length.zero? stations.each do |station| $atis.each_with_index do |x, i| next unless $atis[i]['callsign'] == station message = { type: 'text', text: x['atisdat'] } messages.push(message) end end if messages.empty? message = { type: 'text', text: 'ATIS Not Provided' } messages.push(message) end client.reply_message(event['replyToken'], messages) end end 'OK' end end
import * as express from 'express'; declare const normalizeFilter: (req: express.Request, res: express.Response, next: express.NextFunction) => void; export default normalizeFilter;
namespace GameCreator.Stats { using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using GameCreator.Core; using GameCreator.Variables; #if UNITY_EDITOR using UnityEditor; #endif [AddComponentMenu("")] public class ConditionStatusEffect : ICondition { public enum Operation { HasStatusEffect, DoesNotHave } public TargetGameObject target = new TargetGameObject(TargetGameObject.Target.Player); public Operation condition = Operation.HasStatusEffect; [StatusEffectSelector] public StatusEffectAsset statusEffect; [Indent] public int minAmount = 1; // EXECUTABLE: ---------------------------------------------------------------------------- public override bool Check(GameObject target) { GameObject targetGO = this.target.GetGameObject(target); if (!targetGO) { Debug.LogError("Condition Status Effect: No target defined"); return false; } Stats stats = targetGO.GetComponentInChildren<Stats>(); if (!stats) { Debug.LogError("Condition Status Effect: Could not get Stats component in target"); return false; } bool hasStatusEffect = stats.HasStatusEffect(this.statusEffect, this.minAmount); if (this.condition == Operation.HasStatusEffect && hasStatusEffect) return true; if (this.condition == Operation.DoesNotHave && !hasStatusEffect) return true; return false; } // +--------------------------------------------------------------------------------------+ // | EDITOR | // +--------------------------------------------------------------------------------------+ #if UNITY_EDITOR public const string CUSTOM_ICON_PATH = "Assets/Plugins/GameCreator/Stats/Icons/Conditions/"; public static new string NAME = "Stats/Status Effect"; private const string NODE_TITLE = "{0} {1} status effect {2}"; // INSPECTOR METHODS: --------------------------------------------------------------------- public override string GetNodeTitle() { string statName = (!this.statusEffect ? "(none)" : this.statusEffect.statusEffect.uniqueName ); string conditionName = (this.condition == Operation.HasStatusEffect ? "Has" : "Does not have" ); return string.Format( NODE_TITLE, conditionName, this.target, statName ); } #endif } }
package xyz.qwewqa.relive.simulator.core.presets.condition import xyz.qwewqa.relive.simulator.stage.character.School import xyz.qwewqa.relive.simulator.core.stage.condition.NamedCondition val SeishoOnlyCondition = schoolCondition(School.Seisho) val RinmeikanOnlyCondition = schoolCondition(School.Rinmeikan) val FrontierOnlyCondition = schoolCondition(School.Frontier) val SiegfeldOnlyCondition = schoolCondition(School.Siegfeld) val SeiranOnlyCondition = schoolCondition(School.Seiran) private fun schoolCondition(school: School) = NamedCondition(school.name) { it.dress.character.school == school }
module.exports = { version: require('../actions/version'), hostInformation: require('../actions/hostInfo'), systemProps: require('../actions/systemProps'), createVm: require('../actions/create'), start: require('../actions/start'), stop: require('../actions/stop'), save: require('../actions/save'), clone: require('../actions/clone'), screenshot: require('../actions/screenshot'), isRunning: require('../actions/isRunning'), getRunning: require('../actions/getRunning'), list: require('../actions/list'), vmInfo: require('../actions/vmInfo'), setVmRam: require('../actions/setVmRam'), setBootOrder: require('../actions/bootOrder'), rdp: { enableRdpAuth: require('../actions/rdp/enable'), setRdpStatus: require('../actions/rdp/setRdpStatus'), setPort: require('../actions/rdp/setPort'), addUser: require('../actions/rdp/addUser'), removeUser: require('../actions/rdp/removeUser'), listUsers: require('../actions/rdp/listUsers'), authType: require('../actions/rdp/authType'), }, snapshots: { take: require('../actions/snapshots/take'), restore: require('../actions/snapshots/restore'), list: require('../actions/snapshots/list'), delete: require('../actions/snapshots/delete') }, storage: { listMounted: require('../actions/storage/listMounted'), listAllVdi: require('../actions/storage/listAllVdi'), attachVdi: require('../actions/storage/vdi.attach'), attachISO: require('../actions/storage/iso.attach'), detach: require('../actions/storage/detach'), resizeVdi: require('../actions/storage/vdi.resize'), createVdi: require('../actions/storage/vdi.create'), }, metrics: { query: require('../actions/metrics/query'), enable: require('../actions/metrics/enable'), disable: require('../actions/metrics/disable') } };
from . import (eyerefract, cable, unlit_generic, lightmap_generic, vertexlit_generic, worldvertextransition, unlittwotexture, lightmapped_4wayblend, decalmodulate, refract, water)
"""Top-level package for EVTech.""" from .camera import * from .geodesy import * from .dataset import * from .ray import * __author__ = """David Nilosek""" __email__ = '[email protected]' __version__ = '1.1.0'
#!/bin/sh VER=$1 if [ -z $VER ]; then VER=latest fi echo "VERSION=$VER" REPO=nmhung1210/mern-stack-docker TAG_NAME=$REPO:$VER docker build -t $TAG_NAME . && \ docker push $TAG_NAME