{ // 获取包含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 !== 'PDF TO Markdown' && linkText !== 'PDF TO Markdown' ) { link.textContent = 'PDF TO 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 !== 'Voice Cloning' ) { link.textContent = 'Voice Cloning'; link.href = 'https://vibevoice.info/'; 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, 'PDF TO 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"},"repo_name":{"kind":"string","value":"simonmysun/praxis"},"path":{"kind":"string","value":"TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/287e3522261d64438d0e0f0d0ab25b1bbc0d4b902207719bf1a7761ee019b24a.html"},"language":{"kind":"string","value":"HTML"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":550,"string":"550"}}},{"rowIdx":2814,"cells":{"code":{"kind":"string","value":"personalprojects\n================\n\nA bunch of little things I made in my freetime\n\n\n### PyPong\nA simple pong game made in Python and Pygame.\n**Changes Made**: Made the AI a bit (a lot) worse, you can actually win now.\n\n### Maze Runner\nA maze app that uses Deep Field Search (DFS) to make a perfect maze and then uses the same algorithm in reverse to solve. Requires PyGame.\n**Usage**: Run it, enter your resolution, and let it run! Press \"Escape\" at anytime to quit.\n**Changes Made**: Exits more elegantly, colors are more visible.\n\n### Find the Cow\nA joke of a game inspired by a conversation at dinner with friends. I challenged myself to keep it under 100 lines of code. Requires PyGame.\n**Usage**: Click to guess where the cow is. The volume of the \"moo\" indicates how far away the cow is. Once the cow is found, press spacebar to go to the next level.\n**ToDo**: Add a menu, although, I want to keep this under 100 lines of code.\n\n### Binary Clock\nSomething I thought I would finish, but never had the initative. It was supposed to be a simple 5 row binary clock. Maybe someday it will get a life.\n"},"repo_name":{"kind":"string","value":"tanishq-dubey/personalprojects"},"path":{"kind":"string","value":"README.md"},"language":{"kind":"string","value":"Markdown"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":1102,"string":"1,102"}}},{"rowIdx":2815,"cells":{"code":{"kind":"string","value":"// Copyright (c) 2020 The Firo Core Developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#ifndef FIRO_ELYSIUM_SIGMAWALLETV0_H\n#define FIRO_ELYSIUM_SIGMAWALLETV0_H\n\n#include \"sigmawallet.h\"\n\nnamespace elysium {\n\nclass SigmaWalletV0 : public SigmaWallet\n{\npublic:\n SigmaWalletV0();\n\nprotected:\n uint32_t BIP44ChangeIndex() const;\n SigmaPrivateKey GeneratePrivateKey(uint512 const &seed);\n\n class Database : public SigmaWallet::Database {\n public:\n Database();\n\n public:\n bool WriteMint(SigmaMintId const &id, SigmaMint const &mint, CWalletDB *db = nullptr);\n bool ReadMint(SigmaMintId const &id, SigmaMint &mint, CWalletDB *db = nullptr) const;\n bool EraseMint(SigmaMintId const &id, CWalletDB *db = nullptr);\n bool HasMint(SigmaMintId const &id, CWalletDB *db = nullptr) const;\n\n bool WriteMintId(uint160 const &hash, SigmaMintId const &mintId, CWalletDB *db = nullptr);\n bool ReadMintId(uint160 const &hash, SigmaMintId &mintId, CWalletDB *db = nullptr) const;\n bool EraseMintId(uint160 const &hash, CWalletDB *db = nullptr);\n bool HasMintId(uint160 const &hash, CWalletDB *db = nullptr) const;\n\n bool WriteMintPool(std::vector const &mints, CWalletDB *db = nullptr);\n bool ReadMintPool(std::vector &mints, CWalletDB *db = nullptr);\n\n void ListMints(std::function const&, CWalletDB *db = nullptr);\n };\n\npublic:\n using SigmaWallet::GeneratePrivateKey;\n};\n\n}\n\n#endif // FIRO_ELYSIUM_SIGMAWALLETV0_H"},"repo_name":{"kind":"string","value":"zcoinofficial/zcoin"},"path":{"kind":"string","value":"src/elysium/sigmawalletv0.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":1664,"string":"1,664"}}},{"rowIdx":2816,"cells":{"code":{"kind":"string","value":"# Gears #\n\n*Documentation may be outdated or incomplete as some URLs may no longer exist.*\n\n*Warning! This codebase is deprecated and will no longer receive support; excluding critical issues.*\n\nA PHP class that loads template files, binds variables to a single file or globally without the need for custom placeholders/variables, allows for parent-child hierarchy and parses the template structure.\n\nGear is a play on words for: Engine + Gears + Structure.\n\n* Loads any type of file into the system\n* Binds variables to a single file or to all files globally\n* Template files DO NOT need custom markup and placeholders for variables\n* Can access and use variables in a template just as you would a PHP file\n* Allows for parent-child hierarchy\n* Parse a parent template to parse all children, and their children, and so on\n* Can destroy template indexes on the fly\n* No eval() or security flaws\n* And much more...\n\n## Introduction ##\n\nMost of the template systems today use a very robust setup where the template files contain no server-side code. Instead they use a system where they use custom variables and markup to get the job done. For example, in your template you may have a variable called {pageTitle} and in your code you assign that variable a value of \"Welcome\". This is all well and good, but to be able to parse this \"system\", it requires loads of regex and matching/replacing/looping which can be quite slow and cumbersome. It also requires you to learn a new markup language, specific for the system you are using. Why would you want to learn a new markup language and structure simply to do an if statement or go through a loop? In Gears, the goal is to remove all that custom code, separate your markup from your code, allow the use of standard PHP functions, loops, statements, etc within templates, and much more!\n\n## Installation ##\n\nInstall by manually downloading the library or defining a [Composer dependency](http://getcomposer.org/).\n\n```javascript\n{\n \"require\": {\n \"mjohnson/gears\": \"4.0.0\"\n }\n}\n```\n\nOnce available, instantiate the class and create template files.\n\n```php\n// index.php\n$temp = new mjohnson\\gears\\Gears(dirname(__FILE__) . 'templates/');\n$temp->setLayout('layouts/default');\n\n// templates/layouts/default.tpl\n\n\n\n <?php echo $pageTitle; ?>\n \n\n\n getContent(); ?>\n\n\n```\n\nWithin the code block above I am initiating the class by calling `new mjohnson\\gears\\Gears($path)` (where `$path` is the path to your templates directory) and storing it within a `$temp` variable. Next I am setting the layout I want to use; a layout is the outer HTML that will wrap the inner content pages. Within a layout you can use `getContent()` which will output the inner HTML wherever you please.\n\n## Binding Variables ##\n\nIt's now time to bind data to variables within your templates; to do this we use the `bind()` method. The bind method will take an array of key value pairs, or key value arguments.\n\n```php\n$temp->bind(array(\n 'pageTitle' => 'Gears - Template Engine',\n 'description' => 'A PHP class that loads template files, binds variables, allows for parent-child hierarchy all the while rendering the template structure.'\n));\n```\n\nThe way binding variables works is extremely easy to understand. In the data being binded, the key is the name of the variable within the template, and the value is what the variable will be output. For instance the variable pageTitle (Gears - Template Engine) above will be assigned to the variable `$pageTitle` within the `layouts/default.tpl`.\n\nVariables are binded globally to all templates, includes and the layout.\n\n## Displaying the Templates ##\n\nTo render templates, use the `display()` method. The display method takes two arguments, the name of the template you want to display and the key to use for caching.\n\n```php\necho $temp->display('index');\n```\n\nThe second argument defines the name of the key to use for caching. Generally it will be the same name as the template name, but you do have the option to name it whatever you please.\n\n```php\necho $temp->display('index', 'index');\n```\n\nIt's also possible to display templates within folders by separating the path with a forward slash.\n\n```php\necho $temp->display('users/login');\n```\n\n## Opening a Template ##\n\nTo render a template within another template you would use the `open()` method. The `open()` method takes 3 arguments: the path to the template (relative to the templates folder), an array of key value pairs to define as custom scoped variables and an array of cache settings.\n\n```php\necho $this->open('includes/footer', array('date' => date('Y'));\n```\n\nBy default, includes are not cached but you can enable caching by passing true as the third argument or an array of settings. The viable settings are key and duration, where key is the name of the cached file (usually the path) and duration is the length of the cache.\n\n```php\necho $this->open('includes/footer', array('date' => date('Y')), true);\n\n// Custom settings\necho $this->open('includes/footer', array('date' => date('Y')), array(\n 'key' => 'cacheKey',\n 'duration' => '+10 minutes'\n));\n```\n\n## Caching ##\n\nGears comes packaged with a basic caching mechanism. By default caching is disabled, but to enable caching you can use `setCaching()`. This method will take the cache location as its 1st argument (best to place it in the same templates folder) and the expiration duration as the 2nd argument (default +1 day).\n\n```php\n$temp->setCaching(dirname(__FILE__) . '/templates/cache/');\n```\n\nYou can customize the duration by using the strtotime() format. You can also pass null as the first argument and the system will place the cache files within your template path.\n\n```php\n$temp->setCaching(null, '+15 minutes');\n```\n\nTo clear all cached files, you can use `flush()`.\n\n```php\n$temp->flush();\n```\n\nFor a better example of how to output cached data, refer to the tests folder within the Gears package.\n"},"repo_name":{"kind":"string","value":"milesj/gears"},"path":{"kind":"string","value":"docs/usage.md"},"language":{"kind":"string","value":"Markdown"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":6088,"string":"6,088"}}},{"rowIdx":2817,"cells":{"code":{"kind":"string","value":"/*\n* @Author: justinwebb\n* @Date: 2015-09-24 21:08:23\n* @Last Modified by: justinwebb\n* @Last Modified time: 2015-09-24 22:19:45\n*/\n(function (window) {\n 'use strict';\n\n window.JWLB = window.JWLB || {};\n window.JWLB.View = window.JWLB.View || {};\n\n\n //--------------------------------------------------------------------\n // Event handling\n //--------------------------------------------------------------------\n var wallOnClick = function (event) {\n\n if (event.target.tagName.toLowerCase() === 'img') {\n var id = event.target.parentNode.dataset.id;\n var selectedPhoto = this.photos.filter(function (photo) {\n if (photo.id === id) {\n photo.portrait.id = id;\n return photo;\n }\n })[0];\n this.sendEvent('gallery', selectedPhoto.portrait);\n }\n };\n\n //--------------------------------------------------------------------\n // View overrides\n //--------------------------------------------------------------------\n var addUIListeners = function () {\n this.ui.wall.addEventListener('click', wallOnClick.bind(this));\n };\n\n var initUI = function () {\n var isUIValid = false;\n var comp = document.querySelector(this.selector);\n\n this.ui.wall = comp;\n\n if (this.ui.wall) {\n this.reset();\n isUIValid = true;\n }\n\n return isUIValid;\n };\n\n //--------------------------------------------------------------------\n // Constructor\n //--------------------------------------------------------------------\n var Gallery = function (domId) {\n // Overriden View class methods\n this.initUI = initUI;\n this.addUIListeners = addUIListeners;\n this.name = 'Gallery';\n\n // Instance properties\n this.photos = [];\n\n // Initialize View\n JWLB.View.call(this, domId);\n };\n\n //--------------------------------------------------------------------\n // Inheritance\n //--------------------------------------------------------------------\n Gallery.prototype = Object.create(JWLB.View.prototype);\n Gallery.prototype.constructor = Gallery;\n\n //--------------------------------------------------------------------\n // Instance methods\n //--------------------------------------------------------------------\n\n Gallery.prototype.addThumb = function (data, id) {\n // Store image data for future reference\n var photo = {\n id: id,\n thumb: null,\n portrait: data.size[0]\n };\n data.size.forEach(function (elem) {\n if (elem.label === 'Square') {\n photo.thumb = elem;\n }\n if (elem.height > photo.portrait.height) {\n photo.portrait = elem;\n }\n });\n this.photos.push(photo);\n\n // Build thumbnail UI\n var node = document.createElement('div');\n node.setAttribute('data-id', id);\n node.setAttribute('class', 'thumb');\n var img = document.createElement('img');\n img.setAttribute('src', photo.thumb.source);\n img.setAttribute('title', 'id: '+ id);\n node.appendChild(img);\n this.ui.wall.querySelector('article[name=foobar]').appendChild(node);\n };\n\n Gallery.prototype.reset = function () {\n if (this.ui.wall.children.length > 0) {\n var article = this.ui.wall.children.item(0)\n article.parentElement.removeChild(article);\n }\n var article = document.createElement('article');\n article.setAttribute('name', 'foobar');\n this.ui.wall.appendChild(article);\n };\n\n window.JWLB.View.Gallery = Gallery;\n})(window);\n"},"repo_name":{"kind":"string","value":"JustinWebb/lightbox-demo"},"path":{"kind":"string","value":"app/js/helpers/view/gallery.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":3410,"string":"3,410"}}},{"rowIdx":2818,"cells":{"code":{"kind":"string","value":"module InfinityTest\n module Core\n class Base\n # Specify the Ruby Version Manager to run\n cattr_accessor :strategy\n # ==== Options\n # * :rvm\n # * :rbenv\n # * :ruby_normal (Use when don't pass any rubies to run)\n # * :auto_discover(defaults)\n self.strategy = :auto_discover\n\n # Specify Ruby version(s) to test against\n #\n # ==== Examples\n # rubies = %w(ree jruby)\n #\n cattr_accessor :rubies\n self.rubies = []\n\n # Options to include in the command.\n #\n cattr_accessor :specific_options\n self.specific_options = ''\n\n # Test Framework to use Rspec, Bacon, Test::Unit or AutoDiscover(defaults)\n # ==== Options\n # * :rspec\n # * :bacon\n # * :test_unit (Test unit here apply to this two libs: test/unit and minitest)\n # * :auto_discover(defaults)\n #\n # This will load a exactly a class constantize by name.\n #\n cattr_accessor :test_framework\n self.test_framework = :auto_discover\n\n # Framework to know the folders and files that need to monitoring by the observer.\n #\n # ==== Options\n # * :rails\n # * :rubygems\n # * :auto_discover(defaults)\n #\n # This will load a exactly a class constantize by name.\n #\n cattr_accessor :framework\n self.framework = :auto_discover\n\n # Framework to observer watch the dirs.\n #\n # ==== Options\n # * watchr\n #\n cattr_accessor :observer\n self.observer = :watchr\n\n # Ignore test files.\n #\n # ==== Examples\n # ignore_test_files = [ 'spec/generators/controller_generator_spec.rb' ]\n #\n cattr_accessor :ignore_test_files\n self.ignore_test_files = []\n\n # Ignore test folders.\n #\n # ==== Examples\n # # Imagine that you don't want to run integration specs.\n # ignore_test_folders = [ 'spec/integration' ]\n #\n cattr_accessor :ignore_test_folders\n self.ignore_test_folders = []\n\n # Verbose Mode. Print commands before executing them.\n #\n cattr_accessor :verbose\n self.verbose = true\n\n # Set the notification framework to use with Infinity Test.\n #\n # ==== Options\n # * :growl\n # * :lib_notify\n # * :auto_discover(defaults)\n #\n # This will load a exactly a class constantize by name.\n #\n cattr_writer :notifications\n self.notifications = :auto_discover\n\n # You can set directory to show images matched by the convention names.\n # => http://github.com/tomas-stefano/infinity_test/tree/master/images/ )\n #\n # Infinity test will work on these names in the notification framework:\n #\n # * success (png, gif, jpeg)\n # * failure (png, gif, jpeg)\n # * pending (png, gif, jpeg)\n #\n cattr_accessor :mode\n\n #\n # => This will show images in the folder:\n # http://github.com/tomas-stefano/infinity_test/tree/master/images/simpson\n #\n self.mode = :simpson\n\n # Success Image to show after the tests run.\n #\n cattr_accessor :success_image\n\n # Pending Image to show after the tests run.\n #\n cattr_accessor :pending_image\n\n # Failure Image to show after the tests run.\n #\n cattr_accessor :failure_image\n\n # Use a specific gemset for each ruby.\n # OBS.: This only will work for RVM strategy.\n #\n cattr_accessor :gemset\n\n # InfinityTest try to use bundler if Gemfile is present.\n # Set to false if you don't want use bundler.\n #\n cattr_accessor :bundler\n self.bundler = true\n\n # Callbacks accessor to handle before or after all run and for each ruby!\n cattr_accessor :callbacks\n self.callbacks = []\n\n # Run the observer to monitor files.\n # If set to false will just Run tests and exit.\n # Defaults to true: run tests and monitoring the files.\n #\n cattr_accessor :infinity_and_beyond\n self.infinity_and_beyond = true\n\n # The extension files that Infinity Test will search.\n # You can observe python, erlang, etc files.\n #\n cattr_accessor :extension\n self.extension = :rb\n\n # Setup Infinity Test passing the ruby versions and others setting.\n # See the class accessors for more information.\n #\n # ==== Examples\n #\n # InfinityTest::Base.setup do |config|\n # config.strategy = :rbenv\n # config.rubies = %w(ree jruby rbx 1.9.2)\n # end\n #\n def self.setup\n yield self\n end\n\n # Receives a object that quacks like InfinityTest::Options and do the merge with self(Base class).\n #\n def self.merge!(options)\n ConfigurationMerge.new(self, options).merge!\n end\n\n def self.start_continuous_test_server\n continuous_test_server.start\n end\n\n def self.continuous_test_server\n @continuous_test_server ||= ContinuousTestServer.new(self)\n end\n\n # Just a shortcut to bundler class accessor.\n #\n def self.using_bundler?\n bundler\n end\n\n # Just a shortcut to bundler class accessor.\n #\n def self.verbose?\n verbose\n end\n\n # Callback method to handle before all run and for each ruby too!\n #\n # ==== Examples\n #\n # before(:all) do\n # # ...\n # end\n #\n # before(:each_ruby) do |environment|\n # # ...\n # end\n #\n # before do # if you pass not then will use :all option\n # # ...\n # end\n #\n def self.before(scope, &block)\n # setting_callback(Callbacks::BeforeCallback, scope, &block)\n end\n\n # Callback method to handle after all run and for each ruby too!\n #\n # ==== Examples\n #\n # after(:all) do\n # # ...\n # end\n #\n # after(:each_ruby) do\n # # ...\n # end\n #\n # after do # if you pass not then will use :all option\n # # ...\n # end\n #\n def self.after(scope, &block)\n # setting_callback(Callbacks::AfterCallback, scope, &block)\n end\n\n # Clear the terminal (Useful in the before callback)\n #\n def self.clear_terminal\n system('clear')\n end\n\n ###### This methods will be removed in the Infinity Test v2.0.1 or 2.0.2 ######\n\n # DEPRECATED: Please use .notification= instead.\n #\n def self.notifications(notification_name = nil, &block)\n if notification_name.blank?\n self.class_variable_get(:@@notifications)\n else\n message = <<-MESSAGE\n .notifications is DEPRECATED.\n Use this instead:\n InfinityTest.setup do |config|\n config.notifications = :growl\n end\n MESSAGE\n ActiveSupport::Deprecation.warn(message)\n self.notifications = notification_name\n self.instance_eval(&block) if block_given?\n end\n end\n\n # DEPRECATED: Please use:\n # success_image= or\n # pending_image= or\n # failure_image= or\n # mode= instead.\n #\n def self.show_images(options)\n message = <<-MESSAGE\n .show_images is DEPRECATED.\n Use this instead:\n InfinityTest.setup do |config|\n config.success_image = 'some_image.png'\n config.pending_image = 'some_image.png'\n config.failure_image = 'some_image.png'\n config.mode = 'infinity_test_dir_that_contain_images'\n end\n MESSAGE\n ActiveSupport::Deprecation.warn(message)\n self.success_image = options[:success_image] || options[:sucess_image] if options[:success_image].present? || options[:sucess_image].present? # for fail typo in earlier versions.\n self.pending_image = options[:pending_image] if options[:pending_image].present?\n self.failure_image = options[:failure_image] if options[:failure_image].present?\n self.mode = options[:mode] if options[:mode].present?\n end\n\n # DEPRECATED: Please use:\n # .rubies = or\n # .specific_options = or\n # .test_framework = or\n # .framework = or\n # .verbose = or\n # .gemset = instead\n #\n def self.use(options)\n message = <<-MESSAGE\n .use is DEPRECATED.\n Use this instead:\n InfinityTest.setup do |config|\n config.rubies = %w(2.0 jruby)\n config.specific_options = '-J'\n config.test_framework = :rspec\n config.framework = :padrino\n config.verbose = true\n config.gemset = :some_gemset\n end\n MESSAGE\n ActiveSupport::Deprecation.warn(message)\n self.rubies = options[:rubies] if options[:rubies].present?\n self.specific_options = options[:specific_options] if options[:specific_options].present?\n self.test_framework = options[:test_framework] if options[:test_framework].present?\n self.framework = options[:app_framework] if options[:app_framework].present?\n self.verbose = options[:verbose] unless options[:verbose].nil?\n self.gemset = options[:gemset] if options[:gemset].present?\n end\n\n # DEPRECATED: Please use .clear_terminal instead.\n #\n def self.clear(option)\n message = '.clear(:terminal) is DEPRECATED. Please use .clear_terminal instead.'\n ActiveSupport::Deprecation.warn(message)\n clear_terminal\n end\n\n def self.heuristics(&block)\n # There is a spec pending.\n end\n\n def self.replace_patterns(&block)\n # There is a spec pending.\n end\n\n private\n\n # def self.setting_callback(callback_class, scope, &block)\n # callback_instance = callback_class.new(scope, &block)\n # self.callbacks.push(callback_instance)\n # callback_instance\n # end\n end\n end\nend"},"repo_name":{"kind":"string","value":"tomas-stefano/infinity_test"},"path":{"kind":"string","value":"lib/infinity_test/core/base.rb"},"language":{"kind":"string","value":"Ruby"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":10064,"string":"10,064"}}},{"rowIdx":2819,"cells":{"code":{"kind":"string","value":"\";\n echo \"code: \".$error[ 'code'].\"
\";\n echo \"message: \".$error[ 'message'].\"
\";\n }\n }\n }\n}else{\n print \"aqui la estabas cagando\";\n}\n?>\n"},"repo_name":{"kind":"string","value":"smukideejeah/GaysonTaxi"},"path":{"kind":"string","value":"cpanel/nuevoCotidiano.php"},"language":{"kind":"string","value":"PHP"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":822,"string":"822"}}},{"rowIdx":2820,"cells":{"code":{"kind":"string","value":"holiwish\n========\n"},"repo_name":{"kind":"string","value":"aldarondo/holiwish"},"path":{"kind":"string","value":"README.md"},"language":{"kind":"string","value":"Markdown"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":18,"string":"18"}}},{"rowIdx":2821,"cells":{"code":{"kind":"string","value":"python -m unittest \n"},"repo_name":{"kind":"string","value":"nrdhm/max_dump"},"path":{"kind":"string","value":"test.sh"},"language":{"kind":"string","value":"Shell"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":20,"string":"20"}}},{"rowIdx":2822,"cells":{"code":{"kind":"string","value":"using System;\nusing NetOffice;\nusing NetOffice.Attributes;\nnamespace NetOffice.MSProjectApi.Enums\n{\n\t /// \n\t /// SupportByVersion MSProject 11, 12, 14\n\t /// \n\t /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff863548(v=office.14).aspx \n\t[SupportByVersion(\"MSProject\", 11,12,14)]\n\t[EntityType(EntityType.IsEnum)]\n\tpublic enum PjMonthLabel\n\t{\n\t\t /// \n\t\t /// SupportByVersion MSProject 11, 12, 14\n\t\t /// \n\t\t /// 57\n\t\t [SupportByVersion(\"MSProject\", 11,12,14)]\n\t\t pjMonthLabelMonth_mm = 57,\n\n\t\t /// \n\t\t /// SupportByVersion MSProject 11, 12, 14\n\t\t /// \n\t\t /// 86\n\t\t [SupportByVersion(\"MSProject\", 11,12,14)]\n\t\t pjMonthLabelMonth_mm_yy = 86,\n\n\t\t /// \n\t\t /// SupportByVersion MSProject 11, 12, 14\n\t\t /// \n\t\t /// 85\n\t\t [SupportByVersion(\"MSProject\", 11,12,14)]\n\t\t pjMonthLabelMonth_mm_yyy = 85,\n\n\t\t /// \n\t\t /// SupportByVersion MSProject 11, 12, 14\n\t\t /// \n\t\t /// 11\n\t\t [SupportByVersion(\"MSProject\", 11,12,14)]\n\t\t pjMonthLabelMonth_m = 11,\n\n\t\t /// \n\t\t /// SupportByVersion MSProject 11, 12, 14\n\t\t /// \n\t\t /// 10\n\t\t [SupportByVersion(\"MSProject\", 11,12,14)]\n\t\t pjMonthLabelMonth_mmm = 10,\n\n\t\t /// \n\t\t /// SupportByVersion MSProject 11, 12, 14\n\t\t /// \n\t\t /// 8\n\t\t [SupportByVersion(\"MSProject\", 11,12,14)]\n\t\t pjMonthLabelMonth_mmm_yyy = 8,\n\n\t\t /// \n\t\t /// SupportByVersion MSProject 11, 12, 14\n\t\t /// \n\t\t /// 9\n\t\t [SupportByVersion(\"MSProject\", 11,12,14)]\n\t\t pjMonthLabelMonth_mmmm = 9,\n\n\t\t /// \n\t\t /// SupportByVersion MSProject 11, 12, 14\n\t\t /// \n\t\t /// 7\n\t\t [SupportByVersion(\"MSProject\", 11,12,14)]\n\t\t pjMonthLabelMonth_mmmm_yyyy = 7,\n\n\t\t /// \n\t\t /// SupportByVersion MSProject 11, 12, 14\n\t\t /// \n\t\t /// 59\n\t\t [SupportByVersion(\"MSProject\", 11,12,14)]\n\t\t pjMonthLabelMonthFromEnd_mm = 59,\n\n\t\t /// \n\t\t /// SupportByVersion MSProject 11, 12, 14\n\t\t /// \n\t\t /// 58\n\t\t [SupportByVersion(\"MSProject\", 11,12,14)]\n\t\t pjMonthLabelMonthFromEnd_Mmm = 58,\n\n\t\t /// \n\t\t /// SupportByVersion MSProject 11, 12, 14\n\t\t /// \n\t\t /// 45\n\t\t [SupportByVersion(\"MSProject\", 11,12,14)]\n\t\t pjMonthLabelMonthFromEnd_Month_mm = 45,\n\n\t\t /// \n\t\t /// SupportByVersion MSProject 11, 12, 14\n\t\t /// \n\t\t /// 61\n\t\t [SupportByVersion(\"MSProject\", 11,12,14)]\n\t\t pjMonthLabelMonthFromStart_mm = 61,\n\n\t\t /// \n\t\t /// SupportByVersion MSProject 11, 12, 14\n\t\t /// \n\t\t /// 60\n\t\t [SupportByVersion(\"MSProject\", 11,12,14)]\n\t\t pjMonthLabelMonthFromStart_Mmm = 60,\n\n\t\t /// \n\t\t /// SupportByVersion MSProject 11, 12, 14\n\t\t /// \n\t\t /// 44\n\t\t [SupportByVersion(\"MSProject\", 11,12,14)]\n\t\t pjMonthLabelMonthFromStart_Month_mm = 44,\n\n\t\t /// \n\t\t /// SupportByVersion MSProject 11, 12, 14\n\t\t /// \n\t\t /// 35\n\t\t [SupportByVersion(\"MSProject\", 11,12,14)]\n\t\t pjMonthLabelNoDateFormat = 35\n\t}\n}"},"repo_name":{"kind":"string","value":"NetOfficeFw/NetOffice"},"path":{"kind":"string","value":"Source/MSProject/Enums/PjMonthLabel.cs"},"language":{"kind":"string","value":"C#"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":3276,"string":"3,276"}}},{"rowIdx":2823,"cells":{"code":{"kind":"string","value":"using System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n// General Information about an assembly is controlled through the following \n// set of attributes. Change these attribute values to modify the information\n// associated with an assembly.\n[assembly: AssemblyTitle(\"CircleAreaAndCircumference\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: AssemblyConfiguration(\"\")]\n[assembly: AssemblyCompany(\"\")]\n[assembly: AssemblyProduct(\"CircleAreaAndCircumference\")]\n[assembly: AssemblyCopyright(\"Copyright © 2014\")]\n[assembly: AssemblyTrademark(\"\")]\n[assembly: AssemblyCulture(\"\")]\n\n// Setting ComVisible to false makes the types in this assembly not visible \n// to COM components. If you need to access a type in this assembly from \n// COM, set the ComVisible attribute to true on that type.\n[assembly: ComVisible(false)]\n\n// The following GUID is for the ID of the typelib if this project is exposed to COM\n[assembly: Guid(\"24a850d9-a2e2-4979-a7f8-47602b439978\")]\n\n// Version information for an assembly consists of the following four values:\n//\n// Major Version\n// Minor Version \n// Build Number\n// Revision\n//\n// You can specify all the values or you can default the Build and Revision Numbers \n// by using the '*' as shown below:\n// [assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyVersion(\"1.0.0.0\")]\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n"},"repo_name":{"kind":"string","value":"frostblooded/TelerikHomework"},"path":{"kind":"string","value":"C# Part 1/ConsoleInputOutput/CircleAreaAndCircumference/Properties/AssemblyInfo.cs"},"language":{"kind":"string","value":"C#"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":1428,"string":"1,428"}}},{"rowIdx":2824,"cells":{"code":{"kind":"string","value":"//#define USE_TOUCH_SCRIPT\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\nusing DG.Tweening;\n\n/*\n * ドラッグ操作でのカメラの移動コントロールクラス\n * マウス&タッチ対応\n */ \nnamespace GarageKit\n{\n [RequireComponent(typeof(Camera))]\n public class FlyThroughCamera : MonoBehaviour\n {\n public static bool winTouch = false;\n public static bool updateEnable = true;\n\n // フライスルーのコントロールタイプ\n public enum FLYTHROUGH_CONTROLL_TYPE\n {\n DRAG = 0,\n DRAG_HOLD\n }\n\n public FLYTHROUGH_CONTROLL_TYPE controllType;\n\n // 移動軸の方向\n public enum FLYTHROUGH_MOVE_TYPE\n {\n XZ = 0,\n XY\n }\n\n public FLYTHROUGH_MOVE_TYPE moveType;\n\n public Collider groundCollider;\n public Collider limitAreaCollider;\n public bool useLimitArea = false;\n public float moveBias = 1.0f;\n public float moveSmoothTime = 0.1f;\n public bool dragInvertX = false;\n public bool dragInvertY = false;\n public float rotateBias = 1.0f;\n public float rotateSmoothTime = 0.1f;\n public bool rotateInvert = false;\n public OrbitCamera combinationOrbitCamera;\n\n private GameObject flyThroughRoot;\n public GameObject FlyThroughRoot { get{ return flyThroughRoot; } }\n private GameObject shiftTransformRoot;\n public Transform ShiftTransform { get{ return shiftTransformRoot.transform; } }\n\n private bool inputLock;\n public bool IsInputLock { get{ return inputLock; } }\n private object lockObject;\n\n private Vector3 defaultPos;\n private Quaternion defaultRot;\n\n private bool isFirstTouch;\n private Vector3 oldScrTouchPos;\n\n private Vector3 dragDelta;\n private Vector3 velocitySmoothPos;\n private Vector3 dampDragDelta = Vector3.zero;\n private Vector3 pushMoveDelta = Vector3.zero;\n\n private float velocitySmoothRot;\n private float dampRotateDelta = 0.0f;\n private float pushRotateDelta = 0.0f;\n\n public Vector3 currentPos { get{ return flyThroughRoot.transform.position; } }\n public Quaternion currentRot { get{ return flyThroughRoot.transform.rotation; } }\n\n\n void Awake()\n {\n\n }\n\n void Start()\n {\n // 設定ファイルより入力タイプを取得\n if(!ApplicationSetting.Instance.GetBool(\"UseMouse\"))\n winTouch = true;\n\n inputLock = false;\n\n // 地面上視点位置に回転ルートを設定する\n Ray ray = new Ray(this.transform.position, this.transform.forward);\n RaycastHit hitInfo;\n if(groundCollider.Raycast(ray, out hitInfo, float.PositiveInfinity))\n {\n flyThroughRoot = new GameObject(this.gameObject.name + \" FlyThrough Root\");\n flyThroughRoot.transform.SetParent(this.gameObject.transform.parent, false);\n flyThroughRoot.transform.position = hitInfo.point;\n flyThroughRoot.transform.rotation = Quaternion.identity;\n\n shiftTransformRoot = new GameObject(this.gameObject.name + \" ShiftTransform Root\");\n shiftTransformRoot.transform.SetParent(flyThroughRoot.transform, true);\n shiftTransformRoot.transform.localPosition = Vector3.zero;\n shiftTransformRoot.transform.localRotation = Quaternion.identity;\n\n this.gameObject.transform.SetParent(shiftTransformRoot.transform, true);\n }\n else\n {\n Debug.LogWarning(\"FlyThroughCamera :: not set the ground collider !!\");\n return;\n }\n\n // 初期値を保存\n defaultPos = flyThroughRoot.transform.position;\n defaultRot = flyThroughRoot.transform.rotation;\n\n ResetInput();\n }\n\n void Update()\n {\t\n if(!inputLock && ButtonObjectEvent.PressBtnsTotal == 0)\n GetInput();\n else\n ResetInput();\n\n UpdateFlyThrough();\n UpdateOrbitCombination();\n }\n\n private void ResetInput()\n {\n isFirstTouch = true;\n oldScrTouchPos = Vector3.zero;\n dragDelta = Vector3.zero;\n }\n\n private void GetInput()\n {\n // for Touch\n if(Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)\n {\n if(Input.touchCount == 1)\n {\t\n // ドラッグ量を計算\n Vector3 currentScrTouchPos = Input.GetTouch(0).position;\n\n if(isFirstTouch)\n {\n oldScrTouchPos = currentScrTouchPos;\n isFirstTouch = false;\n return;\n }\n\n dragDelta = currentScrTouchPos - oldScrTouchPos;\n\n if(controllType == FLYTHROUGH_CONTROLL_TYPE.DRAG)\n oldScrTouchPos = currentScrTouchPos;\n }\n else\n ResetInput();\n }\n\n#if UNITY_STANDALONE_WIN\n else if(Application.platform == RuntimePlatform.WindowsPlayer && winTouch)\n {\n#if !USE_TOUCH_SCRIPT\n if(Input.touchCount == 1)\n {\t\n // ドラッグ量を計算\n Vector3 currentScrTouchPos = Input.touches[0].position;\n#else\n if(TouchScript.TouchManager.Instance.PressedPointersCount == 1)\n {\t\n // ドラッグ量を計算\n Vector3 currentScrTouchPos = TouchScript.TouchManager.Instance.PressedPointers[0].Position;\n#endif\n if(isFirstTouch)\n {\n oldScrTouchPos = currentScrTouchPos;\n isFirstTouch = false;\n return;\n }\n\n dragDelta = currentScrTouchPos - oldScrTouchPos;\n\n if(controllType == FLYTHROUGH_CONTROLL_TYPE.DRAG)\n oldScrTouchPos = currentScrTouchPos;\n }\n else\n ResetInput();\n }\n#endif\n // for Mouse\n else\n {\n if(Input.GetMouseButton(0))\n {\t\n // ドラッグ量を計算\n Vector3 currentScrTouchPos = Input.mousePosition;\n\n if(isFirstTouch)\n {\n oldScrTouchPos = currentScrTouchPos;\n isFirstTouch = false;\n return;\n }\n\n dragDelta = currentScrTouchPos - oldScrTouchPos;\n\n if(controllType == FLYTHROUGH_CONTROLL_TYPE.DRAG)\n oldScrTouchPos = currentScrTouchPos;\n }\n else\n ResetInput();\t\n }\n }\n\n /// \n /// Input更新のLock\n /// \n public void LockInput(object sender)\n {\n if(!inputLock)\n {\n lockObject = sender;\n inputLock = true;\n }\n }\n\n /// \n /// Input更新のUnLock\n /// \n public void UnlockInput(object sender)\n {\n if(inputLock && lockObject == sender)\n inputLock = false;\n }\n\n /// \n /// フライスルーを更新\n /// \n private void UpdateFlyThrough()\n {\n if(!FlyThroughCamera.updateEnable || flyThroughRoot == null)\n return;\t\n\n // 位置\n float dragX = dragDelta.x * (dragInvertX ? -1.0f : 1.0f);\n float dragY = dragDelta.y * (dragInvertY ? -1.0f : 1.0f);\n\n if(moveType == FLYTHROUGH_MOVE_TYPE.XZ)\n dampDragDelta = Vector3.SmoothDamp(dampDragDelta, new Vector3(dragX, 0.0f, dragY) * moveBias + pushMoveDelta, ref velocitySmoothPos, moveSmoothTime);\n else if(moveType == FLYTHROUGH_MOVE_TYPE.XY)\n dampDragDelta = Vector3.SmoothDamp(dampDragDelta, new Vector3(dragX, dragY, 0.0f) * moveBias + pushMoveDelta, ref velocitySmoothPos, moveSmoothTime);\n\n flyThroughRoot.transform.Translate(dampDragDelta, Space.Self);\n pushMoveDelta = Vector3.zero;\n\n if(useLimitArea)\n {\n // 移動範囲限界を設定\n if(limitAreaCollider != null)\n {\t\n Vector3 movingLimitMin = limitAreaCollider.bounds.min + limitAreaCollider.bounds.center - limitAreaCollider.gameObject.transform.position;\n Vector3 movingLimitMax = limitAreaCollider.bounds.max + limitAreaCollider.bounds.center - limitAreaCollider.gameObject.transform.position;\n \n if(moveType == FLYTHROUGH_MOVE_TYPE.XZ)\n {\n float limitX = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.x, movingLimitMax.x), movingLimitMin.x);\n float limitZ = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.z, movingLimitMax.z), movingLimitMin.z);\n flyThroughRoot.transform.position = new Vector3(limitX, flyThroughRoot.transform.position.y, limitZ);\n }\n else if(moveType == FLYTHROUGH_MOVE_TYPE.XY)\n {\n float limitX = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.x, movingLimitMax.x), movingLimitMin.x);\n float limitY = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.y, movingLimitMax.y), movingLimitMin.y);\n flyThroughRoot.transform.position = new Vector3(limitX, limitY, flyThroughRoot.transform.position.z);\n }\n }\n }\n\n // 方向\n dampRotateDelta = Mathf.SmoothDamp(dampRotateDelta, pushRotateDelta * rotateBias, ref velocitySmoothRot, rotateSmoothTime);\n if(moveType == FLYTHROUGH_MOVE_TYPE.XZ)\n flyThroughRoot.transform.Rotate(Vector3.up, dampRotateDelta, Space.Self);\n else if(moveType == FLYTHROUGH_MOVE_TYPE.XY)\n flyThroughRoot.transform.Rotate(Vector3.forward, dampRotateDelta, Space.Self);\n pushRotateDelta = 0.0f;\n }\n\n private void UpdateOrbitCombination()\n {\n // 連携機能\n if(combinationOrbitCamera != null && combinationOrbitCamera.OrbitRoot != null)\n {\n Vector3 lookPoint = combinationOrbitCamera.OrbitRoot.transform.position;\n Transform orbitParent = combinationOrbitCamera.OrbitRoot.transform.parent;\n combinationOrbitCamera.OrbitRoot.transform.parent = null;\n flyThroughRoot.transform.LookAt(lookPoint, Vector3.up);\n flyThroughRoot.transform.rotation = Quaternion.Euler(\n 0.0f, flyThroughRoot.transform.rotation.eulerAngles.y + 180.0f, 0.0f);\n combinationOrbitCamera.OrbitRoot.transform.parent = orbitParent;\n }\n }\n\n /// \n /// 目標位置にカメラを移動させる\n /// \n public void MoveToFlyThrough(Vector3 targetPosition, float time = 1.0f)\n {\n dampDragDelta = Vector3.zero;\n\n flyThroughRoot.transform.DOMove(targetPosition, time)\n .SetEase(Ease.OutCubic)\n .Play();\n }\n\n /// \n /// 指定値でカメラを移動させる\n /// \n public void TranslateToFlyThrough(Vector3 move)\n {\n dampDragDelta = Vector3.zero;\n flyThroughRoot.transform.Translate(move, Space.Self);\n }\n\n /// \n /// 目標方向にカメラを回転させる\n /// \n public void RotateToFlyThrough(float targetAngle, float time = 1.0f)\n {\n dampRotateDelta = 0.0f;\n\n Vector3 targetEulerAngles = flyThroughRoot.transform.rotation.eulerAngles;\n targetEulerAngles.y = targetAngle;\n flyThroughRoot.transform.DORotate(targetEulerAngles, time)\n .SetEase(Ease.OutCubic)\n .Play();\n }\n\n /// \n /// 外部トリガーで移動させる\n /// \n public void PushMove(Vector3 move)\n {\n pushMoveDelta = move;\n }\n\n /// \n /// 外部トリガーでカメラ方向を回転させる\n /// \n public void PushRotate(float rotate)\n {\n pushRotateDelta = rotate;\n }\n\n /// \n /// フライスルーを初期化\n /// \n public void ResetFlyThrough()\n {\n ResetInput();\n\n MoveToFlyThrough(defaultPos);\n RotateToFlyThrough(defaultRot.eulerAngles.y);\n }\n }\n}\n"},"repo_name":{"kind":"string","value":"sharkattack51/GarageKit_for_Unity"},"path":{"kind":"string","value":"UnityProject/Assets/__ProjectName__/Scripts/Utils/CameraContorol/FlyThroughCamera.cs"},"language":{"kind":"string","value":"C#"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":13347,"string":"13,347"}}},{"rowIdx":2825,"cells":{"code":{"kind":"string","value":"\"use strict\";\n\nconst readdir = require(\"../../\");\nconst dir = require(\"../utils/dir\");\nconst { expect } = require(\"chai\");\nconst through2 = require(\"through2\");\nconst fs = require(\"fs\");\n\nlet nodeVersion = parseFloat(process.version.substr(1));\n\ndescribe(\"Stream API\", () => {\n it(\"should be able to pipe to other streams as a Buffer\", done => {\n let allData = [];\n\n readdir.stream(\"test/dir\")\n .pipe(through2((data, enc, next) => {\n try {\n // By default, the data is streamed as a Buffer\n expect(data).to.be.an.instanceOf(Buffer);\n\n // Buffer.toString() returns the file name\n allData.push(data.toString());\n\n next(null, data);\n }\n catch (e) {\n next(e);\n }\n }))\n .on(\"finish\", () => {\n try {\n expect(allData).to.have.same.members(dir.shallow.data);\n done();\n }\n catch (e) {\n done(e);\n }\n })\n .on(\"error\", err => {\n done(err);\n });\n });\n\n it('should be able to pipe to other streams in \"object mode\"', done => {\n let allData = [];\n\n readdir.stream(\"test/dir\")\n .pipe(through2({ objectMode: true }, (data, enc, next) => {\n try {\n // In \"object mode\", the data is a string\n expect(data).to.be.a(\"string\");\n\n allData.push(data);\n next(null, data);\n }\n catch (e) {\n next(e);\n }\n }))\n .on(\"finish\", () => {\n try {\n expect(allData).to.have.same.members(dir.shallow.data);\n done();\n }\n catch (e) {\n done(e);\n }\n })\n .on(\"error\", err => {\n done(err);\n });\n });\n\n it('should be able to pipe fs.Stats to other streams in \"object mode\"', done => {\n let allData = [];\n\n readdir.stream(\"test/dir\", { stats: true })\n .pipe(through2({ objectMode: true }, (data, enc, next) => {\n try {\n // The data is an fs.Stats object\n expect(data).to.be.an(\"object\");\n expect(data).to.be.an.instanceOf(fs.Stats);\n\n allData.push(data.path);\n next(null, data);\n }\n catch (e) {\n next(e);\n }\n }))\n .on(\"finish\", () => {\n try {\n expect(allData).to.have.same.members(dir.shallow.data);\n done();\n }\n catch (e) {\n done(e);\n }\n })\n .on(\"error\", done);\n });\n\n it(\"should be able to pause & resume the stream\", done => {\n let allData = [];\n\n let stream = readdir.stream(\"test/dir\")\n .on(\"data\", data => {\n allData.push(data);\n\n // The stream should not be paused\n expect(stream.isPaused()).to.equal(false);\n\n if (allData.length === 3) {\n // Pause for one second\n stream.pause();\n setTimeout(() => {\n try {\n // The stream should still be paused\n expect(stream.isPaused()).to.equal(true);\n\n // The array should still only contain 3 items\n expect(allData).to.have.lengthOf(3);\n\n // Read the rest of the stream\n stream.resume();\n }\n catch (e) {\n done(e);\n }\n }, 1000);\n }\n })\n .on(\"end\", () => {\n expect(allData).to.have.same.members(dir.shallow.data);\n done();\n })\n .on(\"error\", done);\n });\n\n it('should be able to use \"readable\" and \"read\"', done => {\n let allData = [];\n let nullCount = 0;\n\n let stream = readdir.stream(\"test/dir\")\n .on(\"readable\", () => {\n // Manually read the next chunk of data\n let data = stream.read();\n\n while (true) { // eslint-disable-line\n if (data === null) {\n // The stream is done\n nullCount++;\n break;\n }\n else {\n // The data should be a string (the file name)\n expect(data).to.be.a(\"string\").with.length.of.at.least(1);\n allData.push(data);\n\n data = stream.read();\n }\n }\n })\n .on(\"end\", () => {\n if (nodeVersion >= 12) {\n // In Node >= 12, the \"readable\" event fires twice,\n // and stream.read() returns null twice\n expect(nullCount).to.equal(2);\n }\n else if (nodeVersion >= 10) {\n // In Node >= 10, the \"readable\" event only fires once,\n // and stream.read() only returns null once\n expect(nullCount).to.equal(1);\n }\n else {\n // In Node < 10, the \"readable\" event fires 13 times (once per file),\n // and stream.read() returns null each time\n expect(nullCount).to.equal(13);\n }\n\n expect(allData).to.have.same.members(dir.shallow.data);\n done();\n })\n .on(\"error\", done);\n });\n\n it('should be able to subscribe to custom events instead of \"data\"', done => {\n let allFiles = [];\n let allSubdirs = [];\n\n let stream = readdir.stream(\"test/dir\");\n\n // Calling \"resume\" is required, since we're not handling the \"data\" event\n stream.resume();\n\n stream\n .on(\"file\", filename => {\n expect(filename).to.be.a(\"string\").with.length.of.at.least(1);\n allFiles.push(filename);\n })\n .on(\"directory\", subdir => {\n expect(subdir).to.be.a(\"string\").with.length.of.at.least(1);\n allSubdirs.push(subdir);\n })\n .on(\"end\", () => {\n expect(allFiles).to.have.same.members(dir.shallow.files);\n expect(allSubdirs).to.have.same.members(dir.shallow.dirs);\n done();\n })\n .on(\"error\", done);\n });\n\n it('should handle errors that occur in the \"data\" event listener', done => {\n testErrorHandling(\"data\", dir.shallow.data, 7, done);\n });\n\n it('should handle errors that occur in the \"file\" event listener', done => {\n testErrorHandling(\"file\", dir.shallow.files, 3, done);\n });\n\n it('should handle errors that occur in the \"directory\" event listener', done => {\n testErrorHandling(\"directory\", dir.shallow.dirs, 2, done);\n });\n\n it('should handle errors that occur in the \"symlink\" event listener', done => {\n testErrorHandling(\"symlink\", dir.shallow.symlinks, 5, done);\n });\n\n function testErrorHandling (eventName, expected, expectedErrors, done) {\n let errors = [], data = [];\n let stream = readdir.stream(\"test/dir\");\n\n // Capture all errors\n stream.on(\"error\", error => {\n errors.push(error);\n });\n\n stream.on(eventName, path => {\n data.push(path);\n\n if (path.indexOf(\".txt\") >= 0 || path.indexOf(\"dir-\") >= 0) {\n throw new Error(\"Epic Fail!!!\");\n }\n else {\n return true;\n }\n });\n\n stream.on(\"end\", () => {\n try {\n // Make sure the correct number of errors were thrown\n expect(errors).to.have.lengthOf(expectedErrors);\n for (let error of errors) {\n expect(error.message).to.equal(\"Epic Fail!!!\");\n }\n\n // All of the events should have still been emitted, despite the errors\n expect(data).to.have.same.members(expected);\n\n done();\n }\n catch (e) {\n done(e);\n }\n });\n\n stream.resume();\n }\n});\n"},"repo_name":{"kind":"string","value":"BigstickCarpet/readdir-enhanced"},"path":{"kind":"string","value":"test/specs/stream.spec.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":7232,"string":"7,232"}}},{"rowIdx":2826,"cells":{"code":{"kind":"string","value":"\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace PHPExiftool\\Driver\\Tag\\Font;\n\nuse JMS\\Serializer\\Annotation\\ExclusionPolicy;\nuse PHPExiftool\\Driver\\AbstractTag;\n\n/**\n * @ExclusionPolicy(\"all\")\n */\nclass PreferredSubfamily extends AbstractTag\n{\n\n protected $Id = 17;\n\n protected $Name = 'PreferredSubfamily';\n\n protected $FullName = 'Font::Name';\n\n protected $GroupName = 'Font';\n\n protected $g0 = 'Font';\n\n protected $g1 = 'Font';\n\n protected $g2 = 'Document';\n\n protected $Type = '?';\n\n protected $Writable = false;\n\n protected $Description = 'Preferred Subfamily';\n}\n"},"repo_name":{"kind":"string","value":"romainneutron/PHPExiftool"},"path":{"kind":"string","value":"lib/PHPExiftool/Driver/Tag/Font/PreferredSubfamily.php"},"language":{"kind":"string","value":"PHP"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":792,"string":"792"}}},{"rowIdx":2827,"cells":{"code":{"kind":"string","value":"\n\n\n\n\nU-Index\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n\n
\n\n\n\n\n\n\n\n
\n
\n\n\n\n
    \n
  • \n\n\n
  • \n
\n
\n\n\n
\n\n\n
\n\n
\n
&nbsp;
\n\n
M&nbsp;U&nbsp;\n\n\n

U

\n
\n
UsingTheGridLayout - Class in main
\n
&nbsp;
\n
UsingTheGridLayout() - Constructor for class main.UsingTheGridLayout
\n
&nbsp;
\n
\nM&nbsp;U&nbsp;
\n\n
\n\n\n\n\n\n\n\n
\n
\n\n\n\n
\n\n\n
\n\n\n
\n\n\n\n"},"repo_name":{"kind":"string","value":"tliang1/Java-Practice"},"path":{"kind":"string","value":"Practice/Intro-To-Java-8th-Ed-Daniel-Y.-Liang/Chapter-12/Chapter12P03/doc/index-files/index-2.html"},"language":{"kind":"string","value":"HTML"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":5390,"string":"5,390"}}},{"rowIdx":2828,"cells":{"code":{"kind":"string","value":"/**\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for\n * license information.\n *\n * Code generated by Microsoft (R) AutoRest Code Generator.\n */\n\npackage com.microsoft.azure.management.synapse.v2019_06_01_preview;\n\nimport java.util.Collection;\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.microsoft.rest.ExpandableStringEnum;\n\n/**\n * Defines values for IntegrationRuntimeState.\n */\npublic final class IntegrationRuntimeState extends ExpandableStringEnum {\n /** Static value Initial for IntegrationRuntimeState. */\n public static final IntegrationRuntimeState INITIAL = fromString(\"Initial\");\n\n /** Static value Stopped for IntegrationRuntimeState. */\n public static final IntegrationRuntimeState STOPPED = fromString(\"Stopped\");\n\n /** Static value Started for IntegrationRuntimeState. */\n public static final IntegrationRuntimeState STARTED = fromString(\"Started\");\n\n /** Static value Starting for IntegrationRuntimeState. */\n public static final IntegrationRuntimeState STARTING = fromString(\"Starting\");\n\n /** Static value Stopping for IntegrationRuntimeState. */\n public static final IntegrationRuntimeState STOPPING = fromString(\"Stopping\");\n\n /** Static value NeedRegistration for IntegrationRuntimeState. */\n public static final IntegrationRuntimeState NEED_REGISTRATION = fromString(\"NeedRegistration\");\n\n /** Static value Online for IntegrationRuntimeState. */\n public static final IntegrationRuntimeState ONLINE = fromString(\"Online\");\n\n /** Static value Limited for IntegrationRuntimeState. */\n public static final IntegrationRuntimeState LIMITED = fromString(\"Limited\");\n\n /** Static value Offline for IntegrationRuntimeState. */\n public static final IntegrationRuntimeState OFFLINE = fromString(\"Offline\");\n\n /** Static value AccessDenied for IntegrationRuntimeState. */\n public static final IntegrationRuntimeState ACCESS_DENIED = fromString(\"AccessDenied\");\n\n /**\n * Creates or finds a IntegrationRuntimeState from its string representation.\n * @param name a name to look for\n * @return the corresponding IntegrationRuntimeState\n */\n @JsonCreator\n public static IntegrationRuntimeState fromString(String name) {\n return fromString(name, IntegrationRuntimeState.class);\n }\n\n /**\n * @return known IntegrationRuntimeState values\n */\n public static Collection values() {\n return values(IntegrationRuntimeState.class);\n }\n}\n"},"repo_name":{"kind":"string","value":"selvasingh/azure-sdk-for-java"},"path":{"kind":"string","value":"sdk/synapse/mgmt-v2019_06_01_preview/src/main/java/com/microsoft/azure/management/synapse/v2019_06_01_preview/IntegrationRuntimeState.java"},"language":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":2607,"string":"2,607"}}},{"rowIdx":2829,"cells":{"code":{"kind":"string","value":"// Copyright 2015 Peter Beverloo. All rights reserved.\n// Use of this source code is governed by the MIT license, a copy of which can\n// be found in the LICENSE file.\n\n// Base class for a module. Stores the environment and handles magic such as route annotations.\nexport class Module {\n constructor(env) {\n this.env_ = env;\n\n let decoratedRoutes = Object.getPrototypeOf(this).decoratedRoutes_;\n if (!decoratedRoutes)\n return;\n\n decoratedRoutes.forEach(route => {\n env.dispatcher.addRoute(route.method, route.route_path, ::this[route.handler]);\n });\n }\n};\n\n// Annotation that can be used on modules to indicate that the annotated method is the request\n// handler for a |method| (GET, POST) request for |route_path|.\nexport function route(method, route_path) {\n return (target, handler) => {\n if (!target.hasOwnProperty('decoratedRoutes_'))\n target.decoratedRoutes_ = [];\n\n target.decoratedRoutes_.push({ method, route_path, handler });\n };\n}\n"},"repo_name":{"kind":"string","value":"beverloo/node-home-server"},"path":{"kind":"string","value":"src/module.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":981,"string":"981"}}},{"rowIdx":2830,"cells":{"code":{"kind":"string","value":"\n * Dariusz Rumiński \n *\n * This source file is subject to the MIT license that is bundled\n * with this source code in the file LICENSE.\n */\n\nnamespace PhpCsFixer\\Fixer\\PhpUnit;\n\nuse PhpCsFixer\\AbstractFixer;\nuse PhpCsFixer\\FixerDefinition\\CodeSample;\nuse PhpCsFixer\\FixerDefinition\\FixerDefinition;\nuse PhpCsFixer\\Tokenizer\\Tokens;\n\n/**\n * @author Roland Franssen \n */\nfinal class PhpUnitFqcnAnnotationFixer extends AbstractFixer\n{\n /**\n * {@inheritdoc}\n */\n public function getDefinition()\n {\n return new FixerDefinition(\n 'PHPUnit annotations should be a FQCNs including a root namespace.',\n array(new CodeSample(\n'isTokenKindFound(T_DOC_COMMENT);\n }\n\n /**\n * {@inheritdoc}\n */\n protected function applyFix(\\SplFileInfo $file, Tokens $tokens)\n {\n foreach ($tokens as $token) {\n if ($token->isGivenKind(T_DOC_COMMENT)) {\n $token->setContent(preg_replace(\n '~^(\\s*\\*\\s*@(?:expectedException|covers|coversDefaultClass|uses)\\h+)(\\w.*)$~m', '$1\\\\\\\\$2',\n $token->getContent()\n ));\n }\n }\n }\n}\n"},"repo_name":{"kind":"string","value":"cedricleblond35/capvisu-site_supervision"},"path":{"kind":"string","value":"vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitFqcnAnnotationFixer.php"},"language":{"kind":"string","value":"PHP"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":1919,"string":"1,919"}}},{"rowIdx":2831,"cells":{"code":{"kind":"string","value":"---\nlayout: post\ntitle: \"从头学算法(二、搞算法你必须知道的OJ)\"\ndate: 2016-12-20 11:36:52\ncategories: 数据结构及算法\ntags: OJ algorithms\nmathjax: true\n---\n\n在没接触算法之前,我从没听说过OJ这个缩写,没关系,现在开始认识还来得及。等你真正开始研究算法,你才发现你又进入了一个新的世界。\n这个世界,你不关注它的时候,它好像并不存在,而一旦你关注它了,每一个花草都让你叹为观止。\n来看看百度百科是怎么说的吧:\n\n OJ是Online Judge系统的简称,用来在线检测程序源代码的正确性。著名的OJ有TYVJ、RQNOJ、URAL等。国内著名的题库有北京大学题库、浙江大学题库、电子科技大学题库、杭州电子科技大学等。国外的题库包括乌拉尔大学、瓦拉杜利德大学题库等。\n \n\n\n\n\n而作为程序员,你必须知道Leetcode这个OJ,相比起国内各大著名高校的OJ,为什么我更推荐程序员们选择LeetCode OJ呢?原因有两点:\n\n第一,大学OJ上的题目一般都是为ACM选手做准备的,难度大,属于竞技范畴;LeetCode的题相对简单,更为实用,更适合以后从事开发等岗位的程序员们。\n\n第二,LeetCode非常流行,用户的量级几乎要比其他OJ高出将近三到五个级别。大量的活跃用户,将会为我们提供数不清的经验交流和可供参考的GitHub源代码。\n\n刷LeetCode不是为了学会某些牛逼的算法,也不是为了突破某道难题而可能获得的智趣上的快感。学习和练习正确的思考方法,锻炼考虑各种条件的能力,在代码实现前就已经尽可能避免大多数常见错误带来的bug,养成简洁代码的审美习惯。\n通过OJ刷题,配合算法的相关书籍进行理解,对算法的学习是很有帮助的,作为一个程序员,不刷几道LeetCode,真的说不过去。\n\n最后LeetCode网址:https://leetcode.com/\n接下来注册开始搞吧!\n![image_1bf90k08d19p01391i8pfvkqhbm.png-65.6kB][1]\n![image_1bf90orko1ccn1opj29j93cc7f13.png-91.4kB][2]\n\nLeetCode刷过一阵子之后,发现很多都是收费的,这就很不友好了。本着方便大家的原则,向大家推荐lintcode,题目相对也很全,支持中、英双语,最重要是免费。\n\n\n [1]: http://static.zybuluo.com/coldxiangyu/j2xlu88omsuprk7c7qinubug/image_1bf90k08d19p01391i8pfvkqhbm.png\n [2]: http://static.zybuluo.com/coldxiangyu/fztippzc74u7j9ww7av2vvn3/image_1bf90orko1ccn1opj29j93cc7f13.png\n"},"repo_name":{"kind":"string","value":"coldxiangyu/coldxiangyu.github.io"},"path":{"kind":"string","value":"_posts/2016-12-20-从头学算法(二、搞算法你必须知道的OJ).md"},"language":{"kind":"string","value":"Markdown"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":2556,"string":"2,556"}}},{"rowIdx":2832,"cells":{"code":{"kind":"string","value":"package com.timotheteus.raincontrol.handlers;\n\nimport com.timotheteus.raincontrol.tileentities.IGUITile;\nimport com.timotheteus.raincontrol.tileentities.TileEntityInventoryBase;\nimport net.minecraft.client.Minecraft;\nimport net.minecraft.client.gui.GuiScreen;\nimport net.minecraft.entity.player.EntityPlayer;\nimport net.minecraft.inventory.IInventory;\nimport net.minecraft.tileentity.TileEntity;\nimport net.minecraft.util.math.BlockPos;\nimport net.minecraft.world.World;\nimport net.minecraftforge.fml.common.network.IGuiHandler;\nimport net.minecraftforge.fml.network.FMLPlayMessages;\nimport net.minecraftforge.fml.network.NetworkHooks;\n\nimport javax.annotation.Nullable;\n\npublic class GuiHandler implements IGuiHandler {\n\n public static GuiScreen openGui(FMLPlayMessages.OpenContainer openContainer) {\n BlockPos pos = openContainer.getAdditionalData().readBlockPos();\n// new GUIChest(type, (IInventory) Minecraft.getInstance().player.inventory, (IInventory) Minecraft.getInstance().world.getTileEntity(pos));\n TileEntityInventoryBase te = (TileEntityInventoryBase) Minecraft.getInstance().world.getTileEntity(pos);\n if (te != null) {\n return te.createGui(Minecraft.getInstance().player);\n }\n return null;\n }\n\n //TODO can remove these, I think\n\n @Nullable\n @Override\n public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {\n BlockPos pos = new BlockPos(x, y, z);\n TileEntity te = world.getTileEntity(pos);\n if (te instanceof IGUITile) {\n return ((IGUITile) te).createContainer(player);\n }\n return null;\n }\n\n @Nullable\n @Override\n public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {\n BlockPos pos = new BlockPos(x, y, z);\n TileEntity te = world.getTileEntity(pos);\n if (te instanceof IGUITile) {\n return ((IGUITile) te).createGui(player);\n }\n return null;\n }\n\n}\n"},"repo_name":{"kind":"string","value":"kristofersokk/RainControl"},"path":{"kind":"string","value":"src/main/java/com/timotheteus/raincontrol/handlers/GuiHandler.java"},"language":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":2028,"string":"2,028"}}},{"rowIdx":2833,"cells":{"code":{"kind":"string","value":"=')) {\n error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);\n } else {\n error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_USER_NOTICE);\n }\n break;\n\n default:\n header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);\n echo 'The application environment is not set correctly.';\n exit(1); // EXIT_ERROR\n}\n\n/*\n *---------------------------------------------------------------\n * SYSTEM FOLDER NAME\n *---------------------------------------------------------------\n *\n * This variable must contain the name of your \"system\" folder.\n * Include the path if the folder is not in the same directory\n * as this file.\n */\n$system_path = 'system';\n\n/*\n *---------------------------------------------------------------\n * APPLICATION FOLDER NAME\n *---------------------------------------------------------------\n *\n * If you want this front controller to use a different \"application\"\n * folder than the default one you can set its name here. The folder\n * can also be renamed or relocated anywhere on your server. If\n * you do, use a full server path. For more info please see the user guide:\n * http://codeigniter.com/user_guide/general/managing_apps.html\n *\n * NO TRAILING SLASH!\n */\n$application_folder = 'application';\n\n/*\n *---------------------------------------------------------------\n * VIEW FOLDER NAME\n *---------------------------------------------------------------\n *\n * If you want to move the view folder out of the application\n * folder set the path to the folder here. The folder can be renamed\n * and relocated anywhere on your server. If blank, it will default\n * to the standard location inside your application folder. If you\n * do move this, use the full server path to this folder.\n *\n * NO TRAILING SLASH!\n */\n$view_folder = '';\n\n$templates = $view_folder . '/templates/';\n/*\n * --------------------------------------------------------------------\n * DEFAULT CONTROLLER\n * --------------------------------------------------------------------\n *\n * Normally you will set your default controller in the routes.php file.\n * You can, however, force a custom routing by hard-coding a\n * specific controller class/function here. For most applications, you\n * WILL NOT set your routing here, but it's an option for those\n * special instances where you might want to override the standard\n * routing in a specific front controller that shares a common CI installation.\n *\n * IMPORTANT: If you set the routing here, NO OTHER controller will be\n * callable. In essence, this preference limits your application to ONE\n * specific controller. Leave the function name blank if you need\n * to call functions dynamically via the URI.\n *\n * Un-comment the $routing array below to use this feature\n */\n// The directory name, relative to the \"controllers\" folder. Leave blank\n// if your controller is not in a sub-folder within the \"controllers\" folder\n// $routing['directory'] = '';\n\n// The controller class file name. Example: mycontroller\n// $routing['controller'] = '';\n\n// The controller function you wish to be called.\n// $routing['function']\t= '';\n\n\n/*\n * -------------------------------------------------------------------\n * CUSTOM CONFIG VALUES\n * -------------------------------------------------------------------\n *\n * The $assign_to_config array below will be passed dynamically to the\n * config class when initialized. This allows you to set custom config\n * items or override any default config values found in the config.php file.\n * This can be handy as it permits you to share one application between\n * multiple front controller files, with each file containing different\n * config values.\n *\n * Un-comment the $assign_to_config array below to use this feature\n */\n// $assign_to_config['name_of_config_item'] = 'value of config item';\n\n\n// --------------------------------------------------------------------\n// END OF USER CONFIGURABLE SETTINGS. DO NOT EDIT BELOW THIS LINE\n// --------------------------------------------------------------------\n\n/*\n * ---------------------------------------------------------------\n * Resolve the system path for increased reliability\n * ---------------------------------------------------------------\n */\n\n// Set the current directory correctly for CLI requests\nif (defined('STDIN')) {\n chdir(dirname(__FILE__));\n}\n\nif (($_temp = realpath($system_path)) !== FALSE) {\n $system_path = $_temp . '/';\n} else {\n // Ensure there's a trailing slash\n $system_path = rtrim($system_path, '/') . '/';\n}\n\n// Is the system path correct?\nif (!is_dir($system_path)) {\n header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);\n echo 'Your system folder path does not appear to be set correctly. Please open the following file and correct this: ' . pathinfo(__FILE__, PATHINFO_BASENAME);\n exit(3); // EXIT_CONFIG\n}\n\n/*\n * -------------------------------------------------------------------\n * Now that we know the path, set the main path constants\n * -------------------------------------------------------------------\n */\n// The name of THIS file\ndefine('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));\n\n// Path to the system folder\ndefine('BASEPATH', str_replace('\\\\', '/', $system_path));\n\n// Path to the front controller (this file)\ndefine('FCPATH', dirname(__FILE__) . '/');\n\n// Name of the \"system folder\"\ndefine('SYSDIR', trim(strrchr(trim(BASEPATH, '/'), '/'), '/'));\n\n// The path to the \"application\" folder\nif (is_dir($application_folder)) {\n if (($_temp = realpath($application_folder)) !== FALSE) {\n $application_folder = $_temp;\n }\n\n define('APPPATH', $application_folder . DIRECTORY_SEPARATOR);\n} else {\n if (!is_dir(BASEPATH . $application_folder . DIRECTORY_SEPARATOR)) {\n header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);\n echo 'Your application folder path does not appear to be set correctly. Please open the following file and correct this: ' . SELF;\n exit(3); // EXIT_CONFIG\n }\n\n define('APPPATH', BASEPATH . $application_folder . DIRECTORY_SEPARATOR);\n}\n\n// The path to the \"views\" folder\nif (!is_dir($view_folder)) {\n if (!empty($view_folder) && is_dir(APPPATH . $view_folder . DIRECTORY_SEPARATOR)) {\n $view_folder = APPPATH . $view_folder;\n } elseif (!is_dir(APPPATH . 'views' . DIRECTORY_SEPARATOR)) {\n header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);\n echo 'Your view folder path does not appear to be set correctly. Please open the following file and correct this: ' . SELF;\n exit(3); // EXIT_CONFIG\n } else {\n $view_folder = APPPATH . 'views';\n }\n}\n\nif (($_temp = realpath($view_folder)) !== FALSE) {\n $view_folder = $_temp . DIRECTORY_SEPARATOR;\n} else {\n $view_folder = rtrim($view_folder, '/\\\\') . DIRECTORY_SEPARATOR;\n}\n\ndefine('VIEWPATH', $view_folder);\n\n/*\n * --------------------------------------------------------------------\n * LOAD THE BOOTSTRAP FILE\n * --------------------------------------------------------------------\n *\n * And away we go...\n */\nrequire_once BASEPATH . 'core/CodeIgniter.php';"},"repo_name":{"kind":"string","value":"dayanstef/perfect-php-framework"},"path":{"kind":"string","value":"index.php"},"language":{"kind":"string","value":"PHP"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":10005,"string":"10,005"}}},{"rowIdx":2834,"cells":{"code":{"kind":"string","value":"version https://git-lfs.github.com/spec/v1\noid sha256:be847f24aac166b803f1ff5ccc7e4d7bc3fb5d960543e35f779068a754294c94\nsize 1312\n"},"repo_name":{"kind":"string","value":"yogeshsaroya/new-cdnjs"},"path":{"kind":"string","value":"ajax/libs/extjs/4.2.1/src/app/domain/Direct.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":129,"string":"129"}}},{"rowIdx":2835,"cells":{"code":{"kind":"string","value":"\n */\n private $activeLocksByName = array();\n\n /**\n * @param string $lockDirectory Path to the directory that contains the locks.\n */\n public function __construct($lockDirectory)\n {\n $this->lockDirectory = $lockDirectory;\n }\n\n /**\n * Obtains a lock for the provided name.\n *\n * The lock must be released before it can be obtained again.\n *\n * @param string $name\n * @return boolean True if the lock was obtained, false otherwise.\n */\n public function lock($name)\n {\n if ($this->isLocked($name)) {\n return false;\n }\n $lock = new LockHandler($name . '.lock', $this->lockDirectory);\n if ($lock->lock()) {\n // Obtained lock.\n $this->activeLocksByName[$name] = $lock;\n return true;\n }\n return false;\n }\n\n /**\n * Releases the lock with the provided name.\n *\n * If the lock does not exist, then this method will do nothing.\n *\n * @param string $name\n */\n public function release($name)\n {\n if (!$this->isLocked($name)) {\n return;\n }\n /* @var $lock LockHandler */\n $lock = $this->activeLocksByName[$name];\n $lock->release();\n unset($this->activeLocksByName[$name]);\n }\n\n /**\n * Checks if a lock with the given name is active.\n *\n * @param string $name\n * @return boolean\n */\n private function isLocked($name)\n {\n return isset($this->activeLocksByName[$name]);\n }\n}\n"},"repo_name":{"kind":"string","value":"Matthimatiker/CommandLockingBundle"},"path":{"kind":"string","value":"Locking/FileLockManager.php"},"language":{"kind":"string","value":"PHP"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":2166,"string":"2,166"}}},{"rowIdx":2836,"cells":{"code":{"kind":"string","value":"// Core is a collection of helpers\n// Nothing specific to the emultor application\n\n\"use strict\";\n\n// all code is defined in this namespace\nwindow.te = window.te || {};\n\n// te.provide creates a namespace if not previously defined.\n// Levels are seperated by a `.` Each level is a generic JS object.\n// Example: \n// te.provide(\"my.name.space\");\n// my.name.foo = function(){};\n// my.name.space.bar = function(){};\nte.provide = function(ns /*string*/ , root) {\n\tvar parts = ns.split('.');\n\tvar lastLevel = root || window;\n\n\tfor (var i = 0; i < parts.length; i++) {\n\t\tvar p = parts[i];\n\n\t\tif (!lastLevel[p]) {\n\t\t\tlastLevel = lastLevel[p] = {};\n\t\t} else if (typeof lastLevel[p] !== 'object') {\n\t\t\tthrow new Error('Error creating namespace.');\n\t\t} else {\n\t\t\tlastLevel = lastLevel[p];\n\t\t}\n\t}\n};\n\n// A simple UID generator. Returned UIDs are guaranteed to be unique to the page load\nte.Uid = (function() {\n\tvar id = 1;\n\n\tfunction next() {\n\t\treturn id++;\n\t}\n\n\treturn {\n\t\tnext: next\n\t};\n})();\n\n// defaultOptionParse is a helper for functions that expect an options\n// var passed in. This merges the passed in options with a set of defaults.\n// Example:\n// foo function(options) {\n// tf.defaultOptionParse(options, {bar:true, fizz:\"xyz\"});\n// }\nte.defaultOptionParse = function(src, defaults) {\n\tsrc = src || {};\n\n\tvar keys = Object.keys(defaults);\n\tfor (var i = 0; i < keys.length; i++) {\n\t\tvar k = keys[i];\n\n\t\tif (src[k] === undefined) {\n\t\t\tsrc[k] = defaults[k];\n\t\t}\n\t}\n\treturn src;\n};\n\n// Simple string replacement, eg:\n// tf.sprintf('{0} and {1}', 'foo', 'bar'); // outputs: foo and bar\nte.sprintf = function(str) {\n\tfor (var i = 1; i < arguments.length; i++) {\n\t\tvar re = new RegExp('\\\\{' + (i - 1) + '\\\\}', 'gm');\n\t\tstr = str.replace(re, arguments[i]);\n\t}\n\treturn str;\n};"},"repo_name":{"kind":"string","value":"tyleregeto/8bit-emulator"},"path":{"kind":"string","value":"src/core.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":1772,"string":"1,772"}}},{"rowIdx":2837,"cells":{"code":{"kind":"string","value":"##\n# Backup v4.x Configuration\n#\n# Documentation: http://meskyanichi.github.io/backup\n# Issue Tracker: https://github.com/meskyanichi/backup/issues\n\n##\n# Config Options\n#\n# The options here may be overridden on the command line, but the result\n# will depend on the use of --root-path on the command line.\n#\n# If --root-path is used on the command line, then all paths set here\n# will be overridden. If a path (like --tmp-path) is not given along with\n# --root-path, that path will use it's default location _relative to --root-path_.\n#\n# If --root-path is not used on the command line, a path option (like --tmp-path)\n# given on the command line will override the tmp_path set here, but all other\n# paths set here will be used.\n#\n# Note that relative paths given on the command line without --root-path\n# are relative to the current directory. The root_path set here only applies\n# to relative paths set here.\n#\n# ---\n#\n# Sets the root path for all relative paths, including default paths.\n# May be an absolute path, or relative to the current working directory.\n#\n# root_path 'my/root'\n#\n# Sets the path where backups are processed until they're stored.\n# This must have enough free space to hold apx. 2 backups.\n# May be an absolute path, or relative to the current directory or +root_path+.\n#\n# tmp_path 'my/tmp'\n#\n# Sets the path where backup stores persistent information.\n# When Backup's Cycler is used, small YAML files are stored here.\n# May be an absolute path, or relative to the current directory or +root_path+.\n#\n# data_path 'my/data'\n\n##\n# Utilities\n#\n# If you need to use a utility other than the one Backup detects,\n# or a utility can not be found in your $PATH.\n#\n# Utilities.configure do\n# tar '/usr/bin/gnutar'\n# redis_cli '/opt/redis/redis-cli'\n# end\n\n##\n# Logging\n#\n# Logging options may be set on the command line, but certain settings\n# may only be configured here.\n#\n# Logger.configure do\n# console.quiet = true # Same as command line: --quiet\n# logfile.max_bytes = 2_000_000 # Default: 500_000\n# syslog.enabled = true # Same as command line: --syslog\n# syslog.ident = 'my_app_backup' # Default: 'backup'\n# end\n#\n# Command line options will override those set here.\n# For example, the following would override the example settings above\n# to disable syslog and enable console output.\n# backup perform --trigger my_backup --no-syslog --no-quiet\n\n##\n# Component Defaults\n#\n# Set default options to be applied to components in all models.\n# Options set within a model will override those set here.\n#\n# Storage::S3.defaults do |s3|\n# s3.access_key_id = \"my_access_key_id\"\n# s3.secret_access_key = \"my_secret_access_key\"\n# end\n#\n# Notifier::Mail.defaults do |mail|\n# mail.from = 'sender@email.com'\n# mail.to = 'receiver@email.com'\n# mail.address = 'smtp.gmail.com'\n# mail.port = 587\n# mail.domain = 'your.host.name'\n# mail.user_name = 'sender@email.com'\n# mail.password = 'my_password'\n# mail.authentication = 'plain'\n# mail.encryption = :starttls\n# end\n\n##\n# Preconfigured Models\n#\n# Create custom models with preconfigured components.\n# Components added within the model definition will\n# +add to+ the preconfigured components.\n#\n# preconfigure 'MyModel' do\n# archive :user_pictures do |archive|\n# archive.add '~/pictures'\n# end\n#\n# notify_by Mail do |mail|\n# mail.to = 'admin@email.com'\n# end\n# end\n#\n# MyModel.new(:john_smith, 'John Smith Backup') do\n# archive :user_music do |archive|\n# archive.add '~/music'\n# end\n#\n# notify_by Mail do |mail|\n# mail.to = 'john.smith@email.com'\n# end\n# end\n"},"repo_name":{"kind":"string","value":"dockerizedrupal/backer"},"path":{"kind":"string","value":"src/backer/build/modules/build/files/root/Backup/config.rb"},"language":{"kind":"string","value":"Ruby"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":3832,"string":"3,832"}}},{"rowIdx":2838,"cells":{"code":{"kind":"string","value":"import Ember from 'ember';\n\n\nlet __TRANSLATION_MAP__ = {};\nexport default Ember.Service.extend({ map: __TRANSLATION_MAP__ });\n"},"repo_name":{"kind":"string","value":"alexBaizeau/ember-fingerprint-translations"},"path":{"kind":"string","value":"app/services/translation-map.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":126,"string":"126"}}},{"rowIdx":2839,"cells":{"code":{"kind":"string","value":"import React from 'react';\n<<<<<<< HEAD\nimport { Switch, Route } from 'react-router-dom';\n\nimport Home from './Home';\nimport About from './About';\nimport Blog from './Blog';\nimport Resume from './Resume';\nimport Error404 from './Error404';\n=======\n\n// import GithubForm from './forms/github/GithubForm';\nimport GithubRecent from './forms/github/RecentList';\n\nimport './Content.css';\n>>>>>>> 23d814bedfd5c07e05ea49d9a90053074a4c829a\n\nclass Content extends React.Component {\n render() {\n return (\n
\n<<<<<<< HEAD\n \n \n {/* */}\n \n \n=======\n
\n
College Student. Love Coding. Interested in Web and Machine Learning.\n
\n
\n
\n
\n

Recent Projects

\n {/* */}\n \n {/*

Activity

*/}\n

Experience

\n

Education

\n
    \n
  • Computer Science

    Colorado State University, Fort Collins (2017 -)
  • \n
\n
\n
\n
\n {/*
\n

Recent Works

\n

updated in 2 months

\n
*/}\n {/*

Recent

\n */}\n {/*

Lifetime

\n {/* */}\n {/*
\n

Recent Posts

\n

written in 2 months

\n
\n */}\n>>>>>>> 23d814bedfd5c07e05ea49d9a90053074a4c829a\n
\n );\n }\n}\n\nexport default Content;\n"},"repo_name":{"kind":"string","value":"slkjse9/slkjse9.github.io"},"path":{"kind":"string","value":"src/components/Content.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":2049,"string":"2,049"}}},{"rowIdx":2840,"cells":{"code":{"kind":"string","value":"package cmd\n\nimport (\n\t\"github.com/fatih/color\"\n\tout \"github.com/plouc/go-gitlab-client/cli/output\"\n\t\"github.com/spf13/cobra\"\n)\n\nfunc init() {\n\tgetCmd.AddCommand(getProjectVarCmd)\n}\n\nvar getProjectVarCmd = &cobra.Command{\n\tUse: resourceCmd(\"project-var\", \"project-var\"),\n\tAliases: []string{\"pv\"},\n\tShort: \"Get the details of a project's specific variable\",\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tids, err := config.aliasIdsOrArgs(currentAlias, \"project-var\", args)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcolor.Yellow(\"Fetching project variable (id: %s, key: %s)…\", ids[\"project_id\"], ids[\"var_key\"])\n\n\t\tloader.Start()\n\t\tvariable, meta, err := client.ProjectVariable(ids[\"project_id\"], ids[\"var_key\"])\n\t\tloader.Stop()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tout.Variable(output, outputFormat, variable)\n\n\t\tprintMeta(meta, false)\n\n\t\treturn nil\n\t},\n}\n"},"repo_name":{"kind":"string","value":"plouc/go-gitlab-client"},"path":{"kind":"string","value":"cli/cmd/get_project_var_cmd.go"},"language":{"kind":"string","value":"GO"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":873,"string":"873"}}},{"rowIdx":2841,"cells":{"code":{"kind":"string","value":"export interface IContact {\n id?: number;\n email: string;\n listName: string;\n name: string;\n}\n"},"repo_name":{"kind":"string","value":"SimpleCom/simplecom-web"},"path":{"kind":"string","value":"src/interfaces/contacts.interface.ts"},"language":{"kind":"string","value":"TypeScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":98,"string":"98"}}},{"rowIdx":2842,"cells":{"code":{"kind":"string","value":"// The MIT License (MIT)\n// \n// Copyright (c) Andrew Armstrong/FacticiusVir 2020\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n// This file was automatically generated and should not be edited directly.\n\nusing System;\nusing System.Runtime.InteropServices;\n\nnamespace SharpVk.Interop\n{\n /// \n /// \n /// \n [StructLayout(LayoutKind.Sequential)]\n public unsafe partial struct ExternalMemoryImageCreateInfo\n {\n /// \n /// The type of this structure.\n /// \n public SharpVk.StructureType SType; \n \n /// \n /// Null or an extension-specific structure.\n /// \n public void* Next; \n \n /// \n /// \n /// \n public SharpVk.ExternalMemoryHandleTypeFlags HandleTypes; \n }\n}\n"},"repo_name":{"kind":"string","value":"FacticiusVir/SharpVk"},"path":{"kind":"string","value":"src/SharpVk/Interop/ExternalMemoryImageCreateInfo.gen.cs"},"language":{"kind":"string","value":"C#"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":1882,"string":"1,882"}}},{"rowIdx":2843,"cells":{"code":{"kind":"string","value":"package unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletBasicWalletAvailableBalance;\n\nimport com.bitdubai.fermat_api.layer.dmp_basic_wallet.common.exceptions.CantRegisterCreditException;\nimport com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.interfaces.BitcoinWalletTransactionRecord;\nimport com.bitdubai.fermat_api.layer.osa_android.database_system.Database;\nimport com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable;\nimport com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord;\nimport com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTransaction;\nimport com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantLoadTableToMemoryException;\nimport com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException;\nimport com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException;\nimport com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletBasicWalletAvailableBalance;\nimport com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletDatabaseConstants;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;\nimport org.mockito.runners.MockitoJUnitRunner;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.mocks.MockBitcoinWalletTransactionRecord;\nimport unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.mocks.MockDatabaseTableRecord;\n\nimport static com.googlecode.catchexception.CatchException.catchException;\nimport static com.googlecode.catchexception.CatchException.caughtException;\nimport static org.fest.assertions.api.Assertions.*;\nimport static org.mockito.Mockito.doThrow;\nimport static org.mockito.Mockito.when;\n\n/**\n * Created by jorgegonzalez on 2015.07.14..\n */\n@RunWith(MockitoJUnitRunner.class)\npublic class CreditTest {\n\n @Mock\n private Database mockDatabase;\n @Mock\n private DatabaseTable mockWalletTable;\n @Mock\n private DatabaseTable mockBalanceTable;\n @Mock\n private DatabaseTransaction mockTransaction;\n\n private List mockRecords;\n\n private DatabaseTableRecord mockBalanceRecord;\n\n private DatabaseTableRecord mockWalletRecord;\n\n private BitcoinWalletTransactionRecord mockTransactionRecord;\n\n private BitcoinWalletBasicWalletAvailableBalance testBalance;\n\n @Before\n public void setUpMocks(){\n mockTransactionRecord = new MockBitcoinWalletTransactionRecord();\n mockBalanceRecord = new MockDatabaseTableRecord();\n mockWalletRecord = new MockDatabaseTableRecord();\n mockRecords = new ArrayList<>();\n mockRecords.add(mockBalanceRecord);\n setUpMockitoRules();\n }\n\n public void setUpMockitoRules(){\n when(mockDatabase.getTable(BitcoinWalletDatabaseConstants.BITCOIN_WALLET_TABLE_NAME)).thenReturn(mockWalletTable);\n when(mockDatabase.getTable(BitcoinWalletDatabaseConstants.BITCOIN_WALLET_BALANCE_TABLE_NAME)).thenReturn(mockBalanceTable);\n when(mockBalanceTable.getRecords()).thenReturn(mockRecords);\n when(mockWalletTable.getEmptyRecord()).thenReturn(mockWalletRecord);\n when(mockDatabase.newTransaction()).thenReturn(mockTransaction);\n }\n\n @Before\n public void setUpAvailableBalance(){\n testBalance = new BitcoinWalletBasicWalletAvailableBalance(mockDatabase);\n }\n\n @Test\n public void Credit_SuccesfullyInvoked_ReturnsAvailableBalance() throws Exception{\n catchException(testBalance).credit(mockTransactionRecord);\n assertThat(caughtException()).isNull();\n }\n\n @Test\n public void Credit_OpenDatabaseCantOpenDatabase_ThrowsCantRegisterCreditException() throws Exception{\n doThrow(new CantOpenDatabaseException(\"MOCK\", null, null, null)).when(mockDatabase).openDatabase();\n\n catchException(testBalance).credit(mockTransactionRecord);\n assertThat(caughtException())\n .isNotNull()\n .isInstanceOf(CantRegisterCreditException.class);\n }\n\n @Test\n public void Credit_OpenDatabaseDatabaseNotFound_ThrowsCantRegisterCreditException() throws Exception{\n doThrow(new DatabaseNotFoundException(\"MOCK\", null, null, null)).when(mockDatabase).openDatabase();\n\n catchException(testBalance).credit(mockTransactionRecord);\n assertThat(caughtException())\n .isNotNull()\n .isInstanceOf(CantRegisterCreditException.class);\n }\n\n @Test\n public void Credit_DaoCantCalculateBalanceException_ThrowsCantRegisterCreditException() throws Exception{\n doThrow(new CantLoadTableToMemoryException(\"MOCK\", null, null, null)).when(mockWalletTable).loadToMemory();\n\n catchException(testBalance).credit(mockTransactionRecord);\n assertThat(caughtException())\n .isNotNull()\n .isInstanceOf(CantRegisterCreditException.class);\n }\n\n @Test\n public void Credit_GeneralException_ThrowsCantRegisterCreditException() throws Exception{\n when(mockBalanceTable.getRecords()).thenReturn(null);\n\n catchException(testBalance).credit(mockTransactionRecord);\n assertThat(caughtException())\n .isNotNull()\n .isInstanceOf(CantRegisterCreditException.class);\n }\n\n}\n"},"repo_name":{"kind":"string","value":"fvasquezjatar/fermat-unused"},"path":{"kind":"string","value":"DMP/plugin/basic_wallet/fermat-dmp-plugin-basic-wallet-bitcoin-wallet-bitdubai/src/test/java/unit/com/bitdubai/fermat_dmp_plugin/layer/basic_wallet/bitcoin_wallet/developer/bitdubai/version_1/structure/BitcoinWalletBasicWalletAvailableBalance/CreditTest.java"},"language":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":5641,"string":"5,641"}}},{"rowIdx":2844,"cells":{"code":{"kind":"string","value":"using System;\n\nnamespace Sherlock\n{\n /// \n /// A reader than can read values from a pipe.\n /// \n /// The type of value to read.\n public interface IPipeReader : IDisposable\n {\n /// \n /// Attempts to read a value from the pipe.\n /// \n /// The read value.\n /// A value indicating success.\n bool Read(out T item);\n\n /// \n /// Closes the reader.\n /// \n void Close();\n\n /// \n /// Gets a value indicating whether the reader is closed.\n /// \n bool IsClosed { get; }\n }\n}\n"},"repo_name":{"kind":"string","value":"tessellator/sherlock"},"path":{"kind":"string","value":"Sherlock/IPipeReader.cs"},"language":{"kind":"string","value":"C#"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":742,"string":"742"}}},{"rowIdx":2845,"cells":{"code":{"kind":"string","value":"# Nitrogen 2.0 New Features\n\n### New Elements, Actions, and API functions\n\n* wf:wire can now act upon CSS classes or full JQuery Paths, not just Nitrogen elements. For example, wf:wire(\".people > .address\", Actions) will wire actions to any HTML elements with an \"address\" class underneath a \"people\" class. Anything on http://api.jquery.com/category/selectors/ is supported\n* Added wf:replace(ID, Elements), remove an element from the page, put new elements in their place.\n* Added wf:remove(ID), remove an element from the page.\n* New #api{} action allows you to define a javascript method that takes parameters and will trigger a postback. Javascript parameters are automatically translated to Erlang, allowing for pattern matching. \n* New #grid{} element provides a Nitrogen interface to the 960 Grid System (http://960.gs) for page layouts.\n* The #upload{} event callbacks have changed. Event fires both on start of upload and when upload finishes. \n* Upload callbacks take a Node parameter so that file uploads work even when a postback hits a different node.\n* Many methods that used to be in 'nitrogen.erl' are now in 'wf.erl'. Also, some method signatures in wf.erl have changed.\n* wf:get_page_module changed to wf:page_module\n* wf:q(ID) no longer returns a list, just the value.\n* wf:qs(ID) returns a list.\n* wf:depickle(Data, TTL) returns undefined if expired.\n\n### Comet Pools\n\n* Behind the scenes, combined logic for comet and continue events. This now all goes through the same channel. You can switch async mode between comet and intervalled polling by calling wf:switch_to_comet() or wf:switch_to_polling(IntervalMS), respectively.\n* Comet processes can now register in a local pool (for a specific session) or a global pool (across the entire Nitrogen cluster). All other processes in the pool are alerted when a process joins or leaves. The first process in a pool gets a special init message.\n* Use wf:send(Pool, Message) or wf:send_global(Pool, Message) to broadcast a message to the entire pool.\n* wf:comet_flush() is now wf:flush()\n\n### Architectural Changes\n\n* Nitrogen now runs _under_ other web frameworks (inets, mochiweb, yaws, misultin) using simple_bridge. In other words, you hook into the other frameworks like normal (mochiweb loop, yaws appmod, etc.) and then call nitrogen:run() from within that process.\n* Handlers are the new mechanism to extend the inner parts of Nitrogen, such as session storage, authentication, etc.\n* New route handler code means that pages can exist in any namespace, don't have to start with /web/... (see dynamic_route_handler and named_route_handler)\n* Changed interface to elements and actions, any custom elements and actions will need tweaks.\n* sync:go() recompiles any changed files more intelligently by scanning for Emakefiles.\n* New ability to package Nitrogen projects as self-contained directories using rebar.\n\n# Nitrogen 1.0 Changelog\n\n2009-05-02\n- Added changes and bugfixes by Tom McNulty.\n\n2009-04-05\n- Added a templateroot setting in .app file, courtesy of Ville Koivula.\n\n2009-03-28\n- Added file upload support.\n\n2009-03-22 \n- Added alt text support to #image elements by Robert Schonberger.\n- Fixed bug, 'nitrogen create (PROJECT)' now does a recursive copy of the Nitrogen support files, by Jay Doane.\n- Added radio button support courtesy of Benjamin Nortier and Tom McNulty.\n\n2009-03-16\n- Added .app configuration setting to bind Nitrogen to a specific IP address, by Tom McNulty.\n\n2009-03-08\n- Added DatePicker element by Torbjorn Tornkvist.\n- Upgrade to JQuery 1.3.2 and JQuery UI 1.7.\n- Created initial VERSIONS file.\n- Added code from Tom McNulty to expose Mochiweb loop.\n- Added coverage code from Michael Mullis, including lib/coverize submodule.\n- Added wf_platform:get_peername/0 code from Marius A. Eriksen.\n\n2009-03-07\n- Added code by Torbjorn Tornkvist: Basic Authentication, Hostname settings, access to HTTP Headers, and a Max Length validator.\n\n2009-01-26\n- Added Gravatar support by Dan Bravender.\n\n2009-01-24\n- Add code-level documentation around comet.\n- Fix bug where comet functions would continue running after a user left the page.\n- Apply patch by Tom McNulty to allow request object access within the route/1 function.\n- Apply patch by Tom McNulty to correctly bind binaries.\n- Apply patch by Tom McNulty for wf_tags library to correctly handle binaries.\n\n2009-01-16\n- Clean up code around timeout events. (Events that will start running after X seconds on the browser.)\n\n2009-01-08\n- Apply changes by Jon Gretar to support 'nitrogen create PROJECT' and 'nitrogen page /web/page' scripts.\n- Finish putting all properties into .app file. Put request/1 into application module file.\n- Add ability to route through route/1 in application module file.\n- Remove need for wf_global.erl\n- Start Yaws process underneath the main Nitrogen supervisor. (Used to be separate.)\n\n2009-01-06\n- Make Nitrogen a supervised OTP application, startable and stoppable via nitrogen:start() and nitrogen:stop().\n- Apply changes by Dave Peticolas to fix session bugs and turn sessions into supervised processes.\n\n2009-01-04\n- Update sync module, add mirror module. These tools allow you to deploy and start applications on a bare remote node.\n\n2009-01-03 \n- Allow Nitrogen to be run as an OTP application. See Quickstart project for example.\n- Apply Tom McNulty's patch to create and implement wf_tags library. Emit html tags more cleanly.\n- Change templates to allow multiple callbacks, and use first one that is defined. Basic idea and starter code by Tom McNulty.\n- Apply Martin Scholl's patch to optimize copy_to_baserecord in wf_utils.\n\n"},"repo_name":{"kind":"string","value":"kbaldyga/Bazy"},"path":{"kind":"string","value":"CHANGELOG.markdown"},"language":{"kind":"string","value":"Markdown"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":5623,"string":"5,623"}}},{"rowIdx":2846,"cells":{"code":{"kind":"string","value":"package gogo\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/golib/assert\"\n)\n\nfunc Test_NewResponse(t *testing.T) {\n\tit := assert.New(t)\n\trecorder := httptest.NewRecorder()\n\n\tresponse := NewResponse(recorder)\n\tit.Implements((*Responser)(nil), response)\n\tit.Equal(http.StatusOK, response.Status())\n\tit.Equal(nonHeaderFlushed, response.Size())\n}\n\nfunc Test_ResponseWriteHeader(t *testing.T) {\n\tit := assert.New(t)\n\trecorder := httptest.NewRecorder()\n\n\tresponse := NewResponse(recorder)\n\tresponse.WriteHeader(http.StatusRequestTimeout)\n\tit.Equal(http.StatusRequestTimeout, response.Status())\n\tit.Equal(nonHeaderFlushed, response.Size())\n}\n\nfunc Test_ResponseFlushHeader(t *testing.T) {\n\tit := assert.New(t)\n\trecorder := httptest.NewRecorder()\n\n\tresponse := NewResponse(recorder)\n\tresponse.WriteHeader(http.StatusRequestTimeout)\n\tresponse.FlushHeader()\n\tit.Equal(http.StatusRequestTimeout, recorder.Code)\n\tit.NotEqual(nonHeaderFlushed, response.Size())\n\n\t// no effect after flushed headers\n\tresponse.WriteHeader(http.StatusOK)\n\tit.Equal(http.StatusOK, response.Status())\n\tresponse.FlushHeader()\n\tit.NotEqual(http.StatusOK, recorder.Code)\n}\n\nfunc Test_ResponseWrite(t *testing.T) {\n\tit := assert.New(t)\n\trecorder := httptest.NewRecorder()\n\thello := []byte(\"Hello,\")\n\tworld := []byte(\"world!\")\n\texpected := []byte(\"Hello,world!\")\n\n\tresponse := NewResponse(recorder)\n\tresponse.Write(hello)\n\tresponse.Write(world)\n\tit.True(response.HeaderFlushed())\n\tit.Equal(len(expected), response.Size())\n\tit.Equal(expected, recorder.Body.Bytes())\n}\n\nfunc Benchmark_ResponseWrite(b *testing.B) {\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\n\thello := []byte(\"Hello,\")\n\tworld := []byte(\"world!\")\n\n\trecorder := httptest.NewRecorder()\n\tresponse := NewResponse(recorder)\n\tfor i := 0; i < b.N; i++ {\n\t\tresponse.Write(hello)\n\t\tresponse.Write(world)\n\t}\n}\n\nfunc Test_ResponseHijack(t *testing.T) {\n\tit := assert.New(t)\n\trecorder := httptest.NewRecorder()\n\texpected := []byte(\"Hello,world!\")\n\n\tresponse := NewResponse(recorder)\n\tresponse.Write(expected)\n\tit.True(response.HeaderFlushed())\n\tit.Equal(recorder, response.(*Response).ResponseWriter)\n\tit.Equal(len(expected), response.Size())\n\n\tresponse.Hijack(httptest.NewRecorder())\n\tit.False(response.HeaderFlushed())\n\tit.NotEqual(recorder, response.(*Response).ResponseWriter)\n\tit.Equal(nonHeaderFlushed, response.Size())\n}\n\nfunc Benchmark_ResponseHijack(b *testing.B) {\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\n\trecorder := httptest.NewRecorder()\n\tresponse := NewResponse(recorder)\n\tfor i := 0; i < b.N; i++ {\n\t\tresponse.Hijack(recorder)\n\t}\n}\n"},"repo_name":{"kind":"string","value":"dolab/gogo"},"path":{"kind":"string","value":"response_test.go"},"language":{"kind":"string","value":"GO"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":2566,"string":"2,566"}}},{"rowIdx":2847,"cells":{"code":{"kind":"string","value":"#if !defined(AFX_DIALOG3_H__8EF7DE42_F33E_4217_87B0_FE9ACBCE3E84__INCLUDED_)\r\n#define AFX_DIALOG3_H__8EF7DE42_F33E_4217_87B0_FE9ACBCE3E84__INCLUDED_\r\n\r\n#if _MSC_VER > 1000\r\n#pragma once\r\n#endif // _MSC_VER > 1000\r\n// Dialog3.h : header file\r\n//\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CDialog3 dialog\r\n\r\nclass CDialog3 : public CDialog\r\n{\r\n// Construction\r\npublic:\r\n\tCDialog3(CWnd* pParent = NULL); // standard constructor\r\n\r\n// Dialog Data\r\n\t//{{AFX_DATA(CDialog3)\r\n\tenum { IDD = IDD_DIALOG3 };\r\n\t//}}AFX_DATA\r\n\r\n\r\n// Overrides\r\n\t// ClassWizard generated virtual function overrides\r\n\t//{{AFX_VIRTUAL(CDialog3)\r\n\tprotected:\r\n\tvirtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support\r\n\t//}}AFX_VIRTUAL\r\n\r\n// Implementation\r\nprotected:\r\n\r\n\t// Generated message map functions\r\n\t//{{AFX_MSG(CDialog3)\r\n\tvirtual BOOL OnInitDialog();\r\n\t//}}AFX_MSG\r\n\tDECLARE_MESSAGE_MAP()\r\n};\r\n\r\n//{{AFX_INSERT_LOCATION}}\r\n// Microsoft Visual C++ will insert additional declarations immediately before the previous line.\r\n\r\n#endif // !defined(AFX_DIALOG3_H__8EF7DE42_F33E_4217_87B0_FE9ACBCE3E84__INCLUDED_)\r\n"},"repo_name":{"kind":"string","value":"Hao-Wu/MEDA"},"path":{"kind":"string","value":"Dialog3.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":1146,"string":"1,146"}}},{"rowIdx":2848,"cells":{"code":{"kind":"string","value":"# Load DSL and set up stages\nrequire 'capistrano/setup'\n\n# Include default deployment tasks\nrequire 'capistrano/deploy'\n\n# Include tasks from other gems included in your Gemfile\nrequire 'capistrano/rvm'\nrequire 'capistrano/bundler'\nrequire 'capistrano/rails'\nrequire 'capistrano/rails/migrations'\nrequire 'capistrano/nginx_unicorn'\nrequire 'capistrano/rails/assets'\n\n# Load custom tasks from `lib/capistrano/tasks` if you have any defined\nDir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }\n"},"repo_name":{"kind":"string","value":"a11ejandro/project_prototype"},"path":{"kind":"string","value":"Capfile.rb"},"language":{"kind":"string","value":"Ruby"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":501,"string":"501"}}},{"rowIdx":2849,"cells":{"code":{"kind":"string","value":"var mongoose = require('mongoose');\nvar bcrypt = require('bcrypt');\nvar saltRounds = 10;\n\nvar userSchema = new mongoose.Schema({\n\temail: {\n\t\ttype: String,\n\t\tindex: {unique: true}\n\t},\n\tpassword: String,\n\tname: String\n});\n\n//hash password\nuserSchema.methods.generateHash = function(password){\n\treturn bcrypt.hashSync(password, bcrypt.genSaltSync(saltRounds));\n}\n\nuserSchema.methods.validPassword = function(password){\n\treturn bcrypt.compareSync(password, this.password);\n}\n\nvar User = mongoose.model('User',userSchema);\n\nmodule.exports = User;"},"repo_name":{"kind":"string","value":"zymokey/mission-park"},"path":{"kind":"string","value":"models/user/user.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":541,"string":"541"}}},{"rowIdx":2850,"cells":{"code":{"kind":"string","value":"ImCodeVerwendeteKultur in der .csproj-Datei\n//in einer fest. Wenn Sie in den Quelldateien beispielsweise Deutsch\n//(Deutschland) verwenden, legen Sie auf \\\"de-DE\\\" fest. Heben Sie dann die Auskommentierung\n//des nachstehenden NeutralResourceLanguage-Attributs auf. Aktualisieren Sie \"en-US\" in der nachstehenden Zeile,\n//sodass es mit der UICulture-Einstellung in der Projektdatei übereinstimmt.\n\n//[assembly: NeutralResourcesLanguage(\"en-US\", UltimateResourceFallbackLocation.Satellite)]\n\n\n[assembly: ThemeInfo(\n ResourceDictionaryLocation.None, //Speicherort der designspezifischen Ressourcenwörterbücher\n //(wird verwendet, wenn eine Ressource auf der Seite\n // oder in den Anwendungsressourcen-Wörterbüchern nicht gefunden werden kann.)\n ResourceDictionaryLocation.SourceAssembly //Speicherort des generischen Ressourcenwörterbuchs\n //(wird verwendet, wenn eine Ressource auf der Seite, in der Anwendung oder einem \n // designspezifischen Ressourcenwörterbuch nicht gefunden werden kann.)\n)]\n\n\n// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:\n//\n// Hauptversion\n// Nebenversion \n// Buildnummer\n// Revision\n//\n// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern \n// übernehmen, indem Sie \"*\" eingeben:\n// [assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyVersion(\"1.0.0.0\")]\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n"},"repo_name":{"kind":"string","value":"Aniel/RedditImageDownloader"},"path":{"kind":"string","value":"RedditImageDownloader.GUI/Properties/AssemblyInfo.cs"},"language":{"kind":"string","value":"C#"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":2715,"string":"2,715"}}},{"rowIdx":2854,"cells":{"code":{"kind":"string","value":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n__author__ = 'ar'\n\nfrom layers_basic import LW_Layer, default_data_format\nfrom layers_convolutional import conv_output_length\n\n###############################################\nclass _LW_Pooling1D(LW_Layer):\n input_dim = 3\n def __init__(self, pool_size=2, strides=None, padding='valid'):\n if strides is None:\n strides = pool_size\n assert padding in {'valid', 'same'}, 'border_mode must be in {valid, same}'\n self.pool_length = pool_size\n self.stride = strides\n self.border_mode = padding\n def get_output_shape_for(self, input_shape):\n length = conv_output_length(input_shape[1], self.pool_length, self.border_mode, self.stride)\n return (input_shape[0], length, input_shape[2])\n\nclass LW_MaxPooling1D(_LW_Pooling1D):\n def __init__(self, pool_size=2, strides=None, padding='valid'):\n super(LW_MaxPooling1D, self).__init__(pool_size, strides, padding)\n\nclass LW_AveragePooling1D(_LW_Pooling1D):\n def __init__(self, pool_size=2, strides=None, padding='valid'):\n super(LW_AveragePooling1D, self).__init__(pool_size, strides, padding)\n\n###############################################\nclass _LW_Pooling2D(LW_Layer):\n def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format='default'):\n if data_format == 'default':\n data_format = default_data_format\n assert data_format in {'channels_last', 'channels_first'}, 'data_format must be in {channels_last, channels_first}'\n self.pool_size = tuple(pool_size)\n if strides is None:\n strides = self.pool_size\n self.strides = tuple(strides)\n assert padding in {'valid', 'same'}, 'border_mode must be in {valid, same}'\n self.border_mode = padding\n self.dim_ordering = data_format\n def get_output_shape_for(self, input_shape):\n if self.dim_ordering == 'channels_first':\n rows = input_shape[2]\n cols = input_shape[3]\n elif self.dim_ordering == 'channels_last':\n rows = input_shape[1]\n cols = input_shape[2]\n else:\n raise Exception('Invalid dim_ordering: ' + self.dim_ordering)\n rows = conv_output_length(rows, self.pool_size[0], self.border_mode, self.strides[0])\n cols = conv_output_length(cols, self.pool_size[1], self.border_mode, self.strides[1])\n if self.dim_ordering == 'channels_first':\n return (input_shape[0], input_shape[1], rows, cols)\n elif self.dim_ordering == 'channels_last':\n return (input_shape[0], rows, cols, input_shape[3])\n else:\n raise Exception('Invalid dim_ordering: ' + self.dim_ordering)\n\nclass LW_MaxPooling2D(_LW_Pooling2D):\n def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format='default'):\n super(LW_MaxPooling2D, self).__init__(pool_size, strides, padding, data_format)\n\nclass LW_AveragePooling2D(_LW_Pooling2D):\n def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format='default'):\n super(LW_AveragePooling2D, self).__init__(pool_size, strides, padding, data_format)\n\n###############################################\nclass _LW_Pooling3D(LW_Layer):\n def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='default'):\n if dim_ordering == 'default':\n dim_ordering = default_data_format\n assert dim_ordering in {'channels_last', 'channels_first'}, 'data_format must be in {channels_last, channels_first}'\n self.pool_size = tuple(pool_size)\n if strides is None:\n strides = self.pool_size\n self.strides = tuple(strides)\n assert border_mode in {'valid', 'same'}, 'border_mode must be in {valid, same}'\n self.border_mode = border_mode\n self.dim_ordering = dim_ordering\n def get_output_shape_for(self, input_shape):\n if self.dim_ordering == 'channels_first':\n len_dim1 = input_shape[2]\n len_dim2 = input_shape[3]\n len_dim3 = input_shape[4]\n elif self.dim_ordering == 'channels_last':\n len_dim1 = input_shape[1]\n len_dim2 = input_shape[2]\n len_dim3 = input_shape[3]\n else:\n raise Exception('Invalid dim_ordering: ' + self.dim_ordering)\n len_dim1 = conv_output_length(len_dim1, self.pool_size[0], self.border_mode, self.strides[0])\n len_dim2 = conv_output_length(len_dim2, self.pool_size[1], self.border_mode, self.strides[1])\n len_dim3 = conv_output_length(len_dim3, self.pool_size[2], self.border_mode, self.strides[2])\n if self.dim_ordering == 'channels_first':\n return (input_shape[0], input_shape[1], len_dim1, len_dim2, len_dim3)\n elif self.dim_ordering == 'channels_last':\n return (input_shape[0], len_dim1, len_dim2, len_dim3, input_shape[4])\n else:\n raise Exception('Invalid dim_ordering: ' + self.dim_ordering)\n\nclass LW_MaxPooling3D(_LW_Pooling3D):\n def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='default'):\n super(LW_MaxPooling3D, self).__init__(pool_size, strides, border_mode, dim_ordering)\n\nclass LW_AveragePooling3D(_LW_Pooling3D):\n def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='default'):\n super(LW_AveragePooling3D, self).__init__(pool_size, strides, border_mode, dim_ordering)\n\n###############################################\nclass _LW_GlobalPooling1D(LW_Layer):\n def __init__(self):\n pass\n def get_output_shape_for(self, input_shape):\n return (input_shape[0], input_shape[2])\n\nclass LW_GlobalAveragePooling1D(_LW_GlobalPooling1D):\n pass\n\nclass LW_GlobalMaxPooling1D(_LW_GlobalPooling1D):\n pass\n\n###############################################\nclass _LW_GlobalPooling2D(LW_Layer):\n\n def __init__(self, data_format='default'):\n if data_format == 'default':\n data_format = default_data_format\n self.dim_ordering = data_format\n def get_output_shape_for(self, input_shape):\n if self.dim_ordering == 'channels_last':\n return (input_shape[0], input_shape[3])\n else:\n return (input_shape[0], input_shape[1])\n\nclass LW_GlobalAveragePooling2D(_LW_GlobalPooling2D):\n pass\n\nclass LW_GlobalMaxPooling2D(_LW_GlobalPooling2D):\n pass\n\n###############################################\nclass _LW_GlobalPooling3D(LW_Layer):\n def __init__(self, data_format='default'):\n if data_format == 'default':\n data_format = default_data_format\n self.dim_ordering = data_format\n def get_output_shape_for(self, input_shape):\n if self.dim_ordering == 'channels_last':\n return (input_shape[0], input_shape[4])\n else:\n return (input_shape[0], input_shape[1])\n\nclass LW_GlobalAveragePooling3D(_LW_GlobalPooling3D):\n pass\n\nclass LW_GlobalMaxPooling3D(_LW_GlobalPooling3D):\n pass\n\n###############################################\nif __name__ == '__main__':\n pass"},"repo_name":{"kind":"string","value":"SummaLabs/DLS"},"path":{"kind":"string","value":"app/backend/core/models-keras-2x-api/lightweight_layers/layers_pooling.py"},"language":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":7111,"string":"7,111"}}},{"rowIdx":2855,"cells":{"code":{"kind":"string","value":"class CreateEventTypes < ActiveRecord::Migration\n def change\n create_table :event_types do |t|\n t.string :name, :limit => 80\n\n t.timestamps\n end\n end\nend\n"},"repo_name":{"kind":"string","value":"nac13k/iAdmin"},"path":{"kind":"string","value":"db/migrate/20140408042944_create_event_types.rb"},"language":{"kind":"string","value":"Ruby"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":172,"string":"172"}}},{"rowIdx":2856,"cells":{"code":{"kind":"string","value":"/*\r\n * Copyright 2013 MongoDB, Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n\r\n\r\n#ifndef BSON_COMPAT_H\r\n#define BSON_COMPAT_H\r\n\r\n\r\n#if !defined (BSON_INSIDE) && !defined (BSON_COMPILATION)\r\n# error \"Only can be included directly.\"\r\n#endif\r\n\r\n\r\n#if defined(__MINGW32__)\r\n# if defined(__USE_MINGW_ANSI_STDIO)\r\n# if __USE_MINGW_ANSI_STDIO < 1\r\n# error \"__USE_MINGW_ANSI_STDIO > 0 is required for correct PRI* macros\"\r\n# endif\r\n# else\r\n# define __USE_MINGW_ANSI_STDIO 1\r\n# endif\r\n#endif\r\n\r\n#include \"bson-config.h\"\r\n#include \"bson-macros.h\"\r\n\r\n\r\n#ifdef BSON_OS_WIN32\r\n# if defined(_WIN32_WINNT) && (_WIN32_WINNT < 0x0600)\r\n# undef _WIN32_WINNT\r\n# endif\r\n# ifndef _WIN32_WINNT\r\n# define _WIN32_WINNT 0x0600\r\n# endif\r\n# ifndef NOMINMAX\r\n# define NOMINMAX\r\n# endif\r\n# include \r\n# ifndef WIN32_LEAN_AND_MEAN\r\n# define WIN32_LEAN_AND_MEAN\r\n# include \r\n# undef WIN32_LEAN_AND_MEAN\r\n# else\r\n# include \r\n# endif\r\n#include \r\n#include \r\n#endif\r\n\r\n\r\n#ifdef BSON_OS_UNIX\r\n# include \r\n# include \r\n#endif\r\n\r\n\r\n#include \"bson-macros.h\"\r\n\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\nBSON_BEGIN_DECLS\r\n\r\n\r\n#ifdef _MSC_VER\r\n# include \"bson-stdint-win32.h\"\r\n# ifndef __cplusplus\r\n /* benign redefinition of type */\r\n# pragma warning (disable :4142)\r\n# ifndef _SSIZE_T_DEFINED\r\n# define _SSIZE_T_DEFINED\r\n typedef SSIZE_T ssize_t;\r\n# endif\r\n typedef SIZE_T size_t;\r\n# pragma warning (default :4142)\r\n# else\r\n /*\r\n * MSVC++ does not include ssize_t, just size_t.\r\n * So we need to synthesize that as well.\r\n */\r\n# pragma warning (disable :4142)\r\n# ifndef _SSIZE_T_DEFINED\r\n# define _SSIZE_T_DEFINED\r\n typedef SSIZE_T ssize_t;\r\n# endif\r\n# pragma warning (default :4142)\r\n# endif\r\n# define PRIi32 \"d\"\r\n# define PRId32 \"d\"\r\n# define PRIu32 \"u\"\r\n# define PRIi64 \"I64i\"\r\n# define PRId64 \"I64i\"\r\n# define PRIu64 \"I64u\"\r\n#else\r\n# include \"bson-stdint.h\"\r\n# include \r\n#endif\r\n\r\n#if defined(__MINGW32__) && ! defined(INIT_ONCE_STATIC_INIT)\r\n# define INIT_ONCE_STATIC_INIT RTL_RUN_ONCE_INIT\r\ntypedef RTL_RUN_ONCE INIT_ONCE;\r\n#endif\r\n\r\n#ifdef BSON_HAVE_STDBOOL_H\r\n# include \r\n#elif !defined(__bool_true_false_are_defined)\r\n# ifndef __cplusplus\r\n typedef signed char bool;\r\n# define false 0\r\n# define true 1\r\n# endif\r\n# define __bool_true_false_are_defined 1\r\n#endif\r\n\r\n\r\n#if defined(__GNUC__)\r\n# if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)\r\n# define bson_sync_synchronize() __sync_synchronize()\r\n# elif defined(__i386__ ) || defined( __i486__ ) || defined( __i586__ ) || \\\r\n defined( __i686__ ) || defined( __x86_64__ )\r\n# define bson_sync_synchronize() asm volatile(\"mfence\":::\"memory\")\r\n# else\r\n# define bson_sync_synchronize() asm volatile(\"sync\":::\"memory\")\r\n# endif\r\n#elif defined(_MSC_VER)\r\n# define bson_sync_synchronize() MemoryBarrier()\r\n#endif\r\n\r\n\r\n#if !defined(va_copy) && defined(__va_copy)\r\n# define va_copy(dst,src) __va_copy(dst, src)\r\n#endif\r\n\r\n\r\n#if !defined(va_copy)\r\n# define va_copy(dst,src) ((dst) = (src))\r\n#endif\r\n\r\n\r\nBSON_END_DECLS\r\n\r\n\r\n#endif /* BSON_COMPAT_H */\r\n"},"repo_name":{"kind":"string","value":"kangseung/JSTrader"},"path":{"kind":"string","value":"include/mongoc-win/libbson/bson-compat.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":3827,"string":"3,827"}}},{"rowIdx":2857,"cells":{"code":{"kind":"string","value":"require \"empty_port/version\"\nrequire 'socket'\nrequire 'timeout'\n\n# ## Example\n# require 'empty_port'\n# class YourServerTest < Test::Unit::TestCase\n# def setup\n# @port = EmptyPort.get\n# @server_pid = Process.fork do\n# server = TCPServer.open('localhost', @port)\n# end\n# EmptyPort.wait(@port)\n# end\n#\n# def test_something_with_server\n# end\n#\n# def teardown\n# Process.kill(@server_pid)\n# end\n# end\n#\nmodule EmptyPort\n class NotFoundException < Exception; end\n\n module ClassMethods\n # SEE http://www.iana.org/assignments/port-numbers\n MIN_PORT_NUMBER = 49152\n MAX_PORT_NUMBER = 65535\n\n # get an empty port except well-known-port.\n def get\n random_port = MIN_PORT_NUMBER + ( rand() * 1000 ).to_i\n while random_port < MAX_PORT_NUMBER\n begin\n sock = TCPSocket.open('localhost', random_port)\n sock.close\n rescue Errno::ECONNREFUSED => e\n return random_port\n end\n random_port += 1\n end\n raise NotFoundException\n end\n\n def listened?(port)\n begin\n sock = TCPSocket.open('localhost', port)\n sock.close\n return true\n rescue Errno::ECONNREFUSED\n return false\n end\n end\n\n DEFAULT_TIMEOUT = 2\n DEFAULT_INTERVAL = 0.1\n\n def wait(port, options={})\n options[:timeout] ||= DEFAULT_TIMEOUT\n options[:interval] ||= DEFAULT_INTERVAL\n\n timeout(options[:timeout]) do\n start = Time.now\n loop do\n if self.listened?(port)\n finished = Time.now\n return finished - start\n end\n sleep(options[:interval])\n end\n end\n end\n end\n\n extend ClassMethods\nend\n\n"},"repo_name":{"kind":"string","value":"walf443/empty_port"},"path":{"kind":"string","value":"lib/empty_port.rb"},"language":{"kind":"string","value":"Ruby"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":1760,"string":"1,760"}}},{"rowIdx":2858,"cells":{"code":{"kind":"string","value":"module.exports = {\n 'throttle': 10,\n 'hash': true,\n 'gzip': false,\n 'baseDir': 'public',\n 'buildDir': 'build',\n 'prefix': ''\n};"},"repo_name":{"kind":"string","value":"wunderlist/bilder-aws"},"path":{"kind":"string","value":"lib/defaults.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":133,"string":"133"}}},{"rowIdx":2859,"cells":{"code":{"kind":"string","value":".vertical-center {\n min-height: 100%; /* Fallback for browsers do NOT support vh unit */\n min-height: 100vh; /* These two lines are counted as one :-) */\n\n display: flex;\n align-items: center;\n}\n\n@media (min-width: 768px){\n #wrapper {/*padding-right: 225px;*/ padding-left: 0;}\n .side-nav{right: 0;left: auto;}\n}\n\n/*!\n * Start Bootstrap - SB Admin (http://startbootstrap.com/)\n * Copyright 2013-2016 Start Bootstrap\n * Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap/blob/gh-pages/LICENSE)\n */\n\n/* Global Styles */\n\nbody {\n background-color: #222;\n}\n\n\n\n#wrapper {\n padding-left: 0;\n}\n\n#page-wrapper {\n width: 100%;\n padding: 0;\n background-color: #fff;\n}\n\n.huge {\n font-size: 50px;\n line-height: normal;\n}\n\n@media(min-width:768px) {\n #wrapper {\n padding-left: 225px;\n }\n\n #page-wrapper {\n padding: 10px;\n margin-top: 20px;\n }\n}\n\n/* Top Navigation */\n\n.top-nav {\n padding: 0 15px;\n}\n\n.top-nav>li {\n display: inline-block;\n float: left;\n}\n\n.top-nav>li>a {\n padding-top: 15px;\n padding-bottom: 15px;\n line-height: 20px;\n color: #999;\n}\n\n.top-nav>li>a:hover,\n.top-nav>li>a:focus,\n.top-nav>.open>a,\n.top-nav>.open>a:hover,\n.top-nav>.open>a:focus {\n color: #fff;\n background-color: #000;\n}\n\n.top-nav>.open>.dropdown-menu {\n float: left;\n position: absolute;\n margin-top: 0;\n border: 1px solid rgba(0,0,0,.15);\n border-top-left-radius: 0;\n border-top-right-radius: 0;\n background-color: #fff;\n -webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175);\n box-shadow: 0 6px 12px rgba(0,0,0,.175);\n}\n\n.top-nav>.open>.dropdown-menu>li>a {\n white-space: normal;\n}\n\nul.message-dropdown {\n padding: 0;\n max-height: 250px;\n overflow-x: hidden;\n overflow-y: auto;\n}\n\nli.message-preview {\n width: 275px;\n border-bottom: 1px solid rgba(0,0,0,.15);\n}\n\nli.message-preview>a {\n padding-top: 15px;\n padding-bottom: 15px;\n}\n\nli.message-footer {\n margin: 5px 0;\n}\n\nul.alert-dropdown {\n width: 200px;\n}\n\n.alert-danger {\n margin-top: 50px;\n}\n\n/* Side Navigation */\n\n@media(min-width:768px) {\n .side-nav {\n position: fixed;\n top: 51px;\n/* left: 225px;*/\n left: 0px;\n width: 225px;\n/* margin-left: -225px;*/\n border: none;\n border-radius: 0;\n overflow-y: auto;\n background-color: #222;\n bottom: 0;\n overflow-x: hidden;\n padding-bottom: 40px;\n }\n\n .side-nav>li>a {\n width: 225px;\n }\n\n .side-nav li a:hover,\n .side-nav li a:focus {\n outline: none;\n background-color: #000 !important;\n }\n}\n\n.side-nav>li>ul {\n padding: 0;\n}\n\n.side-nav>li>ul>li>a {\n display: block;\n padding: 10px 15px 10px 38px;\n text-decoration: none;\n color: #999;\n}\n\n.side-nav>li>ul>li>a:hover {\n color: #fff;\n}\n\n/* Flot Chart Containers */\n\n.flot-chart {\n display: block;\n height: 400px;\n}\n\n.flot-chart-content {\n width: 100%;\n height: 100%;\n}\n\n/* Custom Colored Panels */\n\n.huge {\n font-size: 40px;\n}\n\n.panel-green {\n border-color: #5cb85c;\n}\n\n.panel-green > .panel-heading {\n border-color: #5cb85c;\n color: #fff;\n background-color: #5cb85c;\n}\n\n.panel-green > a {\n color: #5cb85c;\n}\n\n.panel-green > a:hover {\n color: #3d8b3d;\n}\n\n.panel-red {\n border-color: #d9534f;\n}\n\n.panel-red > .panel-heading {\n border-color: #d9534f;\n color: #fff;\n background-color: #d9534f;\n}\n\n.panel-red > a {\n color: #d9534f;\n}\n\n.panel-red > a:hover {\n color: #b52b27;\n}\n\n.panel-yellow {\n border-color: #f0ad4e;\n}\n\n.panel-yellow > .panel-heading {\n border-color: #f0ad4e;\n color: #fff;\n background-color: #f0ad4e;\n}\n\n.panel-yellow > a {\n color: #f0ad4e;\n}\n\n.panel-yellow > a:hover {\n color: #df8a13;\n}\n\n.navbar-nav > li > ul > li.active {\n background: rgba(9, 9, 9, 0.57);\n}"},"repo_name":{"kind":"string","value":"antodoms/beaconoid"},"path":{"kind":"string","value":"app/assets/stylesheets/admin.css"},"language":{"kind":"string","value":"CSS"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":3884,"string":"3,884"}}},{"rowIdx":2860,"cells":{"code":{"kind":"string","value":"\n\n\n \n 使用 button 定义按钮\n\n\n
\n
\n
\n
\n\n\n\n\n"},"repo_name":{"kind":"string","value":"llinmeng/learn-fe"},"path":{"kind":"string","value":"src/ex/crazy-fe-book/2017/H5/03/3-1-4.html"},"language":{"kind":"string","value":"HTML"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":351,"string":"351"}}},{"rowIdx":2861,"cells":{"code":{"kind":"string","value":"---\nlayout: post\ntitle: Tweets\ndate: 2019-08-08\nsummary: These are the tweets for August 8, 2019.\ncategories:\n---\n\n"},"repo_name":{"kind":"string","value":"alexlitel/congresstweets"},"path":{"kind":"string","value":"_posts/2019-08-08--tweets.md"},"language":{"kind":"string","value":"Markdown"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":115,"string":"115"}}},{"rowIdx":2862,"cells":{"code":{"kind":"string","value":"import type { FormatRelativeFn } from '../../../types'\n\n// Source: https://www.unicode.org/cldr/charts/32/summary/te.html\n\nconst formatRelativeLocale = {\n lastWeek: \"'గత' eeee p\", // CLDR #1384\n yesterday: \"'నిన్న' p\", // CLDR #1393\n today: \"'ఈ రోజు' p\", // CLDR #1394\n tomorrow: \"'రేపు' p\", // CLDR #1395\n nextWeek: \"'తదుపరి' eeee p\", // CLDR #1386\n other: 'P',\n}\n\nconst formatRelative: FormatRelativeFn = (token, _date, _baseDate, _options) =>\n formatRelativeLocale[token]\n\nexport default formatRelative\n"},"repo_name":{"kind":"string","value":"date-fns/date-fns"},"path":{"kind":"string","value":"src/locale/te/_lib/formatRelative/index.ts"},"language":{"kind":"string","value":"TypeScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":557,"string":"557"}}},{"rowIdx":2863,"cells":{"code":{"kind":"string","value":"INSERT INTO customers(id, name)\nVALUES (1, 'Jane Woods');\nINSERT INTO customers(id, name)\nVALUES (2, 'Michael Li');\nINSERT INTO customers(id, name)\nVALUES (3, 'Heidi Hasselbach');\nINSERT INTO customers(id, name)\nVALUES (4, 'Rahul Pour');\n"},"repo_name":{"kind":"string","value":"afh/yabab"},"path":{"kind":"string","value":"pre-populate.sql"},"language":{"kind":"string","value":"SQL"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":238,"string":"238"}}},{"rowIdx":2864,"cells":{"code":{"kind":"string","value":"/*\n *\n * BitcoinLikeKeychain\n * ledger-core\n *\n * Created by Pierre Pollastri on 17/01/2017.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 Ledger\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n */\n#ifndef LEDGER_CORE_BITCOINLIKEKEYCHAIN_HPP\n#define LEDGER_CORE_BITCOINLIKEKEYCHAIN_HPP\n\n#include \"../../../bitcoin/BitcoinLikeExtendedPublicKey.hpp\"\n#include \n#include \n#include \n#include \"../../../utils/Option.hpp\"\n#include \"../../../preferences/Preferences.hpp\"\n#include \"../../../api/Configuration.hpp\"\n#include \"../../../api/DynamicObject.hpp\"\n#include \n#include \n#include \n#include \n\n#include \n\nnamespace ledger {\n namespace core {\n\n class BitcoinLikeKeychain: public api::Keychain {\n public:\n enum KeyPurpose {\n RECEIVE, CHANGE\n };\n\n public:\n using Address = std::shared_ptr;\n\n BitcoinLikeKeychain(\n const std::shared_ptr& configuration,\n const api::Currency& params,\n int account,\n const std::shared_ptr& preferences);\n\n virtual bool markAsUsed(const std::vector& addresses);\n virtual bool markAsUsed(const std::string& address, bool needExtendKeychain = true);\n virtual bool markPathAsUsed(const DerivationPath& path, bool needExtendKeychain = true) = 0;\n\n virtual std::vector
getAllObservableAddresses(uint32_t from, uint32_t to) = 0;\n virtual std::vector getAllObservableAddressString(uint32_t from, uint32_t to) = 0;\n virtual std::vector
getAllObservableAddresses(KeyPurpose purpose, uint32_t from, uint32_t to) = 0;\n\n virtual Address getFreshAddress(KeyPurpose purpose) = 0;\n virtual std::vector
getFreshAddresses(KeyPurpose purpose, size_t n) = 0;\n\n virtual Option getAddressPurpose(const std::string& address) const = 0;\n virtual Option getAddressDerivationPath(const std::string& address) const = 0;\n virtual bool isEmpty() const = 0;\n\n int getAccountIndex() const;\n const api::BitcoinLikeNetworkParameters& getNetworkParameters() const;\n const api::Currency& getCurrency() const;\n\n virtual Option> getPublicKey(const std::string& address) const = 0;\n\n\n std::shared_ptr getConfiguration() const;\n const DerivationScheme& getDerivationScheme() const;\n const DerivationScheme& getFullDerivationScheme() const;\n std::string getKeychainEngine() const;\n bool isSegwit() const;\n bool isNativeSegwit() const;\n\n virtual std::string getRestoreKey() const = 0;\n virtual int32_t getObservableRangeSize() const = 0;\n virtual bool contains(const std::string& address) const = 0;\n virtual std::vector
getAllAddresses() = 0;\n virtual int32_t getOutputSizeAsSignedTxInput() const = 0;\n\n static bool isSegwit(const std::string &keychainEngine);\n static bool isNativeSegwit(const std::string &keychainEngine);\n std::shared_ptr getPreferences() const;\n\n protected:\n DerivationScheme& getDerivationScheme();\n\n private:\n const api::Currency _currency;\n DerivationScheme _scheme;\n DerivationScheme _fullScheme;\n int _account;\n std::shared_ptr _preferences;\n std::shared_ptr _configuration;\n };\n }\n}\n\n#endif //LEDGER_CORE_BITCOINLIKEKEYCHAIN_HPP\n"},"repo_name":{"kind":"string","value":"LedgerHQ/lib-ledger-core"},"path":{"kind":"string","value":"core/src/wallet/bitcoin/keychains/BitcoinLikeKeychain.hpp"},"language":{"kind":"string","value":"C++"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":4962,"string":"4,962"}}},{"rowIdx":2865,"cells":{"code":{"kind":"string","value":"\n /// A string containing the player's 64 bit ID.\n /// \n [JsonProperty(\"SteamID\")]\n [ProtoMember(1, IsRequired = true)]\n public ulong SteamId {get; set;}\n\n /// \n /// Boolean indicating whether or not the player is banned from Community\n /// \n [JsonProperty(\"CommunityBanned\")]\n [ProtoMember(2)]\n public bool IsCommunityBanned {get; set;}\n\n /// \n /// Boolean indicating whether or not the player has VAC bans on record.\n /// \n [JsonProperty(\"VACBanned\")]\n [ProtoMember(3)]\n public bool IsVACBanned {get; set;}\n\n /// \n /// Amount of VAC bans on record.\n /// \n [JsonProperty(\"NumberOfVACBans\")]\n [ProtoMember(4)]\n public int VACBanCount {get; set;}\n\n /// \n /// Amount of days since last ban.\n /// \n [JsonProperty(\"DaysSinceLastBan\")]\n [ProtoMember(5)]\n public int DaysSinceLastBan {get; set;}\n\n /// \n /// String containing the player's ban status in the economy. If the player has no bans on record the string will be \"none\", if the player is on probation it will say \"probation\", and so forth.\n /// \n [JsonProperty(\"EconomyBan\")]\n [ProtoMember(6)]\n public string EconomyBan {get; set;}\n\n public override int GetHashCode()\n {\n return SteamId.GetHashCode();\n }\n\n public override bool Equals(object obj)\n {\n var other = obj as PlayerBans;\n return other != null && SteamId.Equals(other.SteamId);\n }\n }\n}"},"repo_name":{"kind":"string","value":"inlinevoid/Overust"},"path":{"kind":"string","value":"Steam/Models/PlayerBans.cs"},"language":{"kind":"string","value":"C#"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":2083,"string":"2,083"}}},{"rowIdx":2868,"cells":{"code":{"kind":"string","value":"/*\n * Business.h\n * UsersService\n *\n\n * Copyright 2011 QuickBlox team. All rights reserved.\n *\n */\n\n#import \"QBUsersModels.h\""},"repo_name":{"kind":"string","value":"bluecitymoon/demo-swift-ios"},"path":{"kind":"string","value":"demo-swift/Quickblox.framework/Versions/A/Headers/QBUsersBusiness.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":128,"string":"128"}}},{"rowIdx":2869,"cells":{"code":{"kind":"string","value":"---\r\nlayout: post\r\ntitle: ESPN took a picture of me\r\ncategories: link\r\n---\r\n\r\nCheck [this link](http://espn.go.com/college-football/story/_/id/9685394/how-do-nebraska-fans-feel-bo-pelini-recent-behavior) for some story about Bo Pelini's goofing off, and -- look there in the last photo! -- it's some goofball in a Nebraska trilby.\r\n"},"repo_name":{"kind":"string","value":"samervin/blog.samerv.in"},"path":{"kind":"string","value":"_posts/link/2013-09-17-espn-picture.md"},"language":{"kind":"string","value":"Markdown"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":332,"string":"332"}}},{"rowIdx":2870,"cells":{"code":{"kind":"string","value":"//\n// GFTestAppDelegate.h\n// TestChaosApp\n//\n// Created by Michael Charkin on 2/26/14.\n// Copyright (c) 2014 GitFlub. All rights reserved.\n//\n\n#import \n\n@interface GFTestAppDelegate : UIResponder \n\n@property (strong, nonatomic) UIWindow *window;\n\n@end\n"},"repo_name":{"kind":"string","value":"firemuzzy/GFChaos"},"path":{"kind":"string","value":"TestChaosApp/TestChaosApp/GFTestAppDelegate.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":294,"string":"294"}}},{"rowIdx":2871,"cells":{"code":{"kind":"string","value":"var modules = {\n\t\"success\" : [\n\t\t{id: 1, name:\"控制台\", code:\"console\", protocol:\"http\", domain:\"console.ecc.com\", port:\"18333\", created:'2017-03-08 00:00:00', creator:'1', modified:'2017-03-08 00:00:00', modifier:'1'},\n\t\t{id: 2, name:\"服务中心\", code:\"service-center\", protocol:\"http\", domain:\"sc.ecc.com\", port:\"18222\", created:'2017-03-08 00:00:00', creator:'1', modified:'2017-03-08 00:00:00', modifier:'1'}\n\t],\n\t\"error\" : {\n\t\tcode : \"0200-ERROR\", msg : \"There are some errors occured.\"\n\t}\n}\n\nmodule.exports = {\n\t\"modules\": modules\n}\n"},"repo_name":{"kind":"string","value":"chinakite/wukong"},"path":{"kind":"string","value":"data/datas/modules.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":545,"string":"545"}}},{"rowIdx":2872,"cells":{"code":{"kind":"string","value":"const {\n createServer,\n plugins: { queryParser, serveStatic }\n} = require('restify');\nconst { join } = require('path');\nconst fetch = require('node-fetch');\nconst proxy = require('http-proxy-middleware');\n\nconst { PORT = 5000 } = process.env;\nconst server = createServer();\n\nserver.use(queryParser());\n\nserver.get('/', async (req, res, next) => {\n if (!req.query.b) {\n const tokenRes = await fetch('https://webchat-mockbot.azurewebsites.net/directline/token', {\n headers: {\n origin: 'http://localhost:5000'\n },\n method: 'POST'\n });\n\n if (!tokenRes.ok) {\n return res.send(500);\n }\n\n const { token } = await tokenRes.json();\n\n return res.send(302, null, {\n location: `/?b=webchat-mockbot&t=${encodeURIComponent(token)}`\n });\n }\n\n return serveStatic({\n directory: join(__dirname, 'dist'),\n file: 'index.html'\n })(req, res, next);\n});\n\nserver.get('/embed/*/config', proxy({ changeOrigin: true, target: 'https://webchat.botframework.com/' }));\n\nserver.listen(PORT, () => console.log(`Embed dev server is listening to port ${PORT}`));\n"},"repo_name":{"kind":"string","value":"billba/botchat"},"path":{"kind":"string","value":"packages/embed/hostDevServer.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":1094,"string":"1,094"}}},{"rowIdx":2873,"cells":{"code":{"kind":"string","value":"/**\n * @author: * @date: 2016/1/21\n */\ndefine([\"core/js/layout/Panel\"],\n function (Panel) {\n var view = Panel.extend({\n /*Panel的配置项 start*/\n title:\"表单-\",\n help:\"内容\",\n brief:\"摘要\",\n\n /*Panel 配置 End*/\n oninitialized:function(triggerEvent){\n this._super();\n this.mainRegion={\n comXtype:$Component.TREE,\n comConf:{\n data:[this.getModuleTree(\"core/js/base/AbstractView\")],\n }\n };\n var that = this;\n this.footerRegion = {\n comXtype: $Component.TOOLSTRIP,\n comConf: {\n /*Panel的配置项 start*/\n textAlign: $TextAlign.RIGHT,\n items: [{\n text: \"展开所有节点\",\n onclick: function (e) {\n that.getMainRegionRef().getComRef().expandAll();\n },\n },{\n text: \"折叠所有节点\",\n onclick: function (e) {\n that.getMainRegionRef().getComRef().collapseAll();\n },\n }]\n /*Panel 配置 End*/\n }\n };\n },\n getModuleTree:function(moduleName,arr){\n var va = window.rtree.tree[moduleName];\n var tree = {title: moduleName};\n if(!arr){\n arr = [];\n }else{\n if(_.contains(arr,moduleName)){\n return false;\n }\n }\n arr.push(moduleName);\n if(va&&va.deps&&va.deps.length>0){\n tree.children = [];\n tree.folder=true;\n for(var i=0;i\n\n\n\n\n\n\n\n\n\n\n

Hello World!

\n\n"},"repo_name":{"kind":"string","value":"stivalet/PHP-Vulnerability-test-suite"},"path":{"kind":"string","value":"XSS/CWE_79/safe/CWE_79__array-GET__CAST-func_settype_float__Unsafe_use_untrusted_data-comment.php"},"language":{"kind":"string","value":"PHP"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":1367,"string":"1,367"}}},{"rowIdx":2876,"cells":{"code":{"kind":"string","value":"$('#modalUploader').on('show.bs.modal', function (event) {\n var uploader = new qq.FileUploaderBasic({\n element: document.getElementById('file-uploader-demo1'),\n button: document.getElementById('areaSubir'),\n action: '/Files/Upload',\n params: { ruta: $('#RutaActual').val() },\n allowedExtensions: ['jpg', 'jpeg', 'png', 'gif', 'doc', 'docx', 'pdf'],\n multiple: false,\n onComplete: function (id, fileName, responseJSON) {\n $.gritter.add({\n title: 'Upload file',\n text: responseJSON.message\n });\n\n },\n onSubmit: function (id, fileName) {\n var strHtml = \"
  • \" + fileName + \"
  • \";\n $(\"#dvxArchivos\").append(strHtml);\n\n }\n });\n});\n\n$('#modalUploader').on('hidden.bs.modal', function () {\n RecargarRuta();\n\n})\n\nfunction AbrirCarpeta(pCarpeta) {\n $(\"#RutaSolicitada\").val(pCarpeta);\n $(\"#frmMain\").submit();\n\n}\nfunction AbrirRuta(pCarpeta) {\n $(\"#RutaSolicitada\").val(pCarpeta);\n $(\"#frmMain\").submit();\n}\n\nfunction RecargarRuta() {\n AbrirCarpeta($(\"#RutaActual\").val());\n}\n\nfunction EliminarArchivo(pRuta) {\n\n if (confirm(\"Are you sure that want to delete this file?\")) {\n $.gritter.add({\n title: 'Delete file',\n text: \"File deleted\"\n });\n $(\"#ArchivoParaEliminar\").val(pRuta);\n AbrirCarpeta($(\"#RutaActual\").val());\n\n }\n}\n\nfunction SubirNivel() {\n if ($(\"#TieneSuperior\").val() == \"1\") {\n var strRutaAnterior = $(\"#RutaSuperior\").val();\n AbrirRuta(strRutaAnterior);\n\n }\n}\nfunction IrInicio() {\n AbrirRuta($(\"#RutaRaiz\").val());\n}\n\nfunction AbrirDialogoArchivo() {\n\n\n $(\"#modalUploader\").modal();\n}\n\n\nfunction getParameterByName(name) {\n name = name.replace(/[\\[]/, \"\\\\\\[\").replace(/[\\]]/, \"\\\\\\]\");\n var regexS = \"[\\\\?&]\" + name + \"=([^&#]*)\";\n var regex = new RegExp(regexS);\n var results = regex.exec(window.location.search);\n if (results == null)\n return \"\";\n else\n return decodeURIComponent(results[1].replace(/\\+/g, \" \"));\n}\n"},"repo_name":{"kind":"string","value":"walalm/MVC-Azure-Explorer"},"path":{"kind":"string","value":"MVC_Azure_Explorer/MVC_Azure_Explorer/Scripts/UtilsFileManager.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":2111,"string":"2,111"}}},{"rowIdx":2877,"cells":{"code":{"kind":"string","value":"// setToken when re-connecting\nvar originalReconnect = Meteor.connection.onReconnect;\nMeteor.connection.onReconnect = function() {\n setToken();\n if(originalReconnect) {\n originalReconnect();\n }\n};\n\nif(Meteor.status().connected) {\n setToken();\n}\n\nfunction setToken() {\n var firewallHumanToken = Cookie.get('sikka-human-token');\n Meteor.call('setSikkaHumanToken', firewallHumanToken);\n}\n\n// reloading the page\nwindow.sikkaCommands = sikkaCommands = new Mongo.Collection('sikka-commands');\nsikkaCommands.find({}).observe({\n added: function(command) {\n if(command._id === \"reload\") {\n location.reload();\n }\n }\n});"},"repo_name":{"kind":"string","value":"meteorhacks/sikka"},"path":{"kind":"string","value":"lib/client/core.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":631,"string":"631"}}},{"rowIdx":2878,"cells":{"code":{"kind":"string","value":"<% nameScope = @config['name_scope'] %>\n
    \n
    \n \n\n \n \n\n \n \n \n \n \n <% if @config['js_include'].to_s.strip.length != 0 %>\n <% @config['js_include'].each do |js| %>\n \n <% end %>\n <% end %>\n \n <% if @config['components_include'].to_s.strip.length != 0 %>\n <% @config['components_include'].each do |component| %>\n \">\n <% end %>\n <% end %>\n\n\n"},"repo_name":{"kind":"string","value":"yorthehunter/humblekit"},"path":{"kind":"string","value":"vendor/assets/bower_components/Cortana/_footer.html"},"language":{"kind":"string","value":"HTML"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":2093,"string":"2,093"}}},{"rowIdx":2879,"cells":{"code":{"kind":"string","value":"//\n// rbLinkedList.h\n// rbLinkedList\n//\n// Created by Ryan Bemowski on 4/6/15.\n//\n\n#pragma once\n\n#include \n\nstruct Node \n{\n int key;\n Node *next;\n};\n\nclass rbLinkedList \n{\npublic:\n /** Constructor for the rbLinkedList class.\n */\n rbLinkedList();\n /** Deconstructor for the rbLinkedList class.\n */\n ~rbLinkedList();\n /** Determine if the collection is empty or not.\n * @return: A bool that will be true if the collection is empty and false\n * otherwise.\n */\n bool IsEmpty();\n /** Determine the number of nodes within the linked list.\n * @return: An integer that represents the number of nodes between the head\n * and tail nodes.\n */\n int Size();\n\n void AddKey(int key);\n void RemoveKey(int key);\n std::string ToString();\n\nprivate:\n Node *h_;\n Node *z_;\n};\n"},"repo_name":{"kind":"string","value":"rrbemo/cppLinkedList"},"path":{"kind":"string","value":"ccpLinkedList/rbLinkedList.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":835,"string":"835"}}},{"rowIdx":2880,"cells":{"code":{"kind":"string","value":"//\n// KAAppDelegate.h\n// UIViewController-KeyboardAdditions\n//\n// Created by CocoaPods on 02/03/2015.\n// Copyright (c) 2014 Andrew Podkovyrin. All rights reserved.\n//\n\n#import \n\n@interface KAAppDelegate : UIResponder \n\n@property (strong, nonatomic) UIWindow *window;\n\n@end\n"},"repo_name":{"kind":"string","value":"podkovyrin/UIViewController-KeyboardAdditions"},"path":{"kind":"string","value":"Example/UIViewController-KeyboardAdditions/KAAppDelegate.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":315,"string":"315"}}},{"rowIdx":2881,"cells":{"code":{"kind":"string","value":"\n\n \n \n Basic Example\n \n \n \n \n \n \n \n \t

    React 允许将代码封装成组件(component),然后像插入普通 HTML 标签一样,在网页中插入这个组件。React.createClass 方法就用于生成一个组件类

    \n

    组件的属性可以在组件类的 this.props 对象上获取

    \n

    添加组件属性,有一个地方需要注意,就是 class 属性需要写成 className ,for 属性需要写成 htmlFor ,这是因为 class 和 for 是 JavaScript 的保留字。

    \n
    \n\n \n\n"},"repo_name":{"kind":"string","value":"MR03/exercise-test-demo"},"path":{"kind":"string","value":"demo/demo004/003.html"},"language":{"kind":"string","value":"HTML"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":921,"string":"921"}}},{"rowIdx":2882,"cells":{"code":{"kind":"string","value":"using System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing GalaSoft.MvvmLight.Command;\n\nnamespace Treehopper.Mvvm.ViewModels\n{\n /// \n /// A delegate called when the selected board changes\n /// \n /// The caller\n /// The new selected board\n public delegate void SelectedBoardChangedEventHandler(object sender, SelectedBoardChangedEventArgs e);\n\n /// \n /// A delegate called when the selected board has connected\n /// \n /// The caller\n /// The connected board\n public delegate void BoardConnectedEventHandler(object sender, BoardConnectedEventArgs e);\n\n /// \n /// A delegate called when the selected board has disconnected\n /// \n /// The caller\n /// The disconnected board\n public delegate void BoardDisconnectedEventHandler(object sender, BoardDisconnectedEventArgs e);\n\n /// \n /// Base interface for the selector view model\n /// \n public interface ISelectorViewModel : INotifyPropertyChanged\n {\n /// \n /// Get the collection of boards\n /// \n ObservableCollection Boards { get; }\n\n /// \n /// Whether the board selection can be changed\n /// \n bool CanChangeBoardSelection { get; set; }\n\n /// \n /// The currently selected board\n /// \n TreehopperUsb SelectedBoard { get; set; }\n\n /// \n /// Occurs when the window closes\n /// \n RelayCommand WindowClosing { get; set; }\n\n /// \n /// Occurs when the connection occurs\n /// \n RelayCommand ConnectCommand { get; set; }\n\n /// \n /// Connect button text\n /// \n string ConnectButtonText { get; set; }\n\n /// \n /// Close command\n /// \n RelayCommand CloseCommand { get; set; }\n\n /// \n /// Board selection changed\n /// \n event SelectedBoardChangedEventHandler OnSelectedBoardChanged;\n\n /// \n /// Board connected\n /// \n event BoardConnectedEventHandler OnBoardConnected;\n\n /// \n /// Board disconnected\n /// \n event BoardDisconnectedEventHandler OnBoardDisconnected;\n }\n}"},"repo_name":{"kind":"string","value":"treehopper-electronics/treehopper-sdk"},"path":{"kind":"string","value":"NET/Demos/WPF/DeviceManager/ViewModels/ISelectorViewModel.cs"},"language":{"kind":"string","value":"C#"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":2665,"string":"2,665"}}},{"rowIdx":2883,"cells":{"code":{"kind":"string","value":"import React from 'react';\nimport ReactDOM from 'react-dom';\nimport componentOrElement from 'react-prop-types/lib/componentOrElement';\nimport ownerDocument from './utils/ownerDocument';\nimport getContainer from './utils/getContainer';\n\n/**\n * The `` component renders its children into a new \"subtree\" outside of current component hierarchy.\n * You can think of it as a declarative `appendChild()`, or jQuery's `$.fn.appendTo()`.\n * The children of `` component will be appended to the `container` specified.\n */\nlet Portal = React.createClass({\n\n displayName: 'Portal',\n\n propTypes: {\n /**\n * A Node, Component instance, or function that returns either. The `container` will have the Portal children\n * appended to it.\n */\n container: React.PropTypes.oneOfType([\n componentOrElement,\n React.PropTypes.func\n ]),\n\n /**\n * Classname to use for the Portal Component\n */\n className: React.PropTypes.string\n },\n\n componentDidMount() {\n this._renderOverlay();\n },\n\n componentDidUpdate() {\n this._renderOverlay();\n },\n\n componentWillReceiveProps(nextProps) {\n if (this._overlayTarget && nextProps.container !== this.props.container) {\n this._portalContainerNode.removeChild(this._overlayTarget);\n this._portalContainerNode = getContainer(nextProps.container, ownerDocument(this).body);\n this._portalContainerNode.appendChild(this._overlayTarget);\n }\n },\n\n componentWillUnmount() {\n this._unrenderOverlay();\n this._unmountOverlayTarget();\n },\n\n\n _mountOverlayTarget() {\n if (!this._overlayTarget) {\n this._overlayTarget = document.createElement('div');\n \n if (this.props.className) {\n this._overlayTarget.className = this.props.className;\n }\n this._portalContainerNode = getContainer(this.props.container, ownerDocument(this).body);\n this._portalContainerNode.appendChild(this._overlayTarget);\n }\n },\n\n _unmountOverlayTarget() {\n if (this._overlayTarget) {\n this._portalContainerNode.removeChild(this._overlayTarget);\n this._overlayTarget = null;\n }\n this._portalContainerNode = null;\n },\n\n _renderOverlay() {\n\n let overlay = !this.props.children\n ? null\n : React.Children.only(this.props.children);\n\n // Save reference for future access.\n if (overlay !== null) {\n this._mountOverlayTarget();\n this._overlayInstance = ReactDOM.unstable_renderSubtreeIntoContainer(\n this, overlay, this._overlayTarget\n );\n } else {\n // Unrender if the component is null for transitions to null\n this._unrenderOverlay();\n this._unmountOverlayTarget();\n }\n },\n\n _unrenderOverlay() {\n if (this._overlayTarget) {\n ReactDOM.unmountComponentAtNode(this._overlayTarget);\n this._overlayInstance = null;\n }\n },\n\n render() {\n return null;\n },\n\n getMountNode(){\n return this._overlayTarget;\n },\n\n getOverlayDOMNode() {\n if (!this.isMounted()) {\n throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.');\n }\n\n if (this._overlayInstance) {\n return ReactDOM.findDOMNode(this._overlayInstance);\n }\n\n return null;\n }\n\n});\n\nexport default Portal;\n"},"repo_name":{"kind":"string","value":"HPate-Riptide/react-overlays"},"path":{"kind":"string","value":"src/Portal.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":3227,"string":"3,227"}}},{"rowIdx":2884,"cells":{"code":{"kind":"string","value":"dojo.provide(\"plugins.dijit.SyncDialog\");\n\n// HAS A\ndojo.require(\"dijit.Dialog\");\ndojo.require(\"dijit.form.Button\");\ndojo.require(\"dijit.form.ValidationTextBox\");\n\n// INHERITS\ndojo.require(\"plugins.core.Common\");\n\ndojo.declare( \"plugins.dijit.SyncDialog\",\n\t[ dijit._Widget, dijit._Templated, plugins.core.Common ], {\n\t\n//Path to the template of this widget. \ntemplatePath: dojo.moduleUrl(\"plugins\", \"dijit/templates/syncdialog.html\"),\n\n// OR USE @import IN HTML TEMPLATE\ncssFiles : [\n\tdojo.moduleUrl(\"plugins\", \"dijit/css/syncdialog.css\")\n],\n\n// Calls dijit._Templated.widgetsInTemplate\nwidgetsInTemplate : true,\n\n// PARENT plugins.workflow.Apps WIDGET\nparentWidget : null,\n\n// DISPLAYED MESSAGE \nmessage : null,\n\n//////}}\nconstructor : function(args) {\n\tconsole.log(\"SyncDialog.constructor args:\");\n\tconsole.dir({args:args});\n\n\t// LOAD CSS\n\tthis.loadCSS();\n},\npostCreate : function() {\n\t//////console.log(\"SyncDialog.postCreate plugins.dijit.SyncDialog.postCreate()\");\n\n\tthis.startup();\n},\nstartup : function () {\n\t////console.log(\"SyncDialog.startup plugins.dijit.SyncDialog.startup()\");\n\t////console.log(\"SyncDialog.startup this.parentWidget: \" + this.parentWidget);\n\n\tthis.inherited(arguments);\n\n\t// SET UP DIALOG\n\tthis.setDialogue();\n\n\t// SET KEY LISTENER\t\t\n\tthis.setKeyListener();\n\t\n\t// ADD CSS NAMESPACE CLASS FOR TITLE CSS STYLING\n\tthis.setNamespaceClass(\"syncDialog\");\n},\nsetKeyListener : function () {\n\tdojo.connect(this.dialog, \"onkeypress\", dojo.hitch(this, \"handleOnKeyPress\"));\n},\nhandleOnKeyPress: function (event) {\n\tvar key = event.charOrCode;\n\tconsole.log(\"SyncDialog.handleOnKeyPress key: \" + key);\n\tif ( key == null )\treturn;\n\tevent.stopPropagation();\n\t\n\tif ( key == dojo.keys.ESCAPE )\tthis.hide();\n},\nsetNamespaceClass : function (ccsClass) {\n// ADD CSS NAMESPACE CLASS\n\tdojo.addClass(this.dialog.domNode, ccsClass);\n\tdojo.addClass(this.dialog.titleNode, ccsClass);\n\tdojo.addClass(this.dialog.closeButtonNode, ccsClass);\t\n},\nshow: function () {\n// SHOW THE DIALOGUE\n\tthis.dialog.show();\n\tthis.message.focus();\n},\nhide: function () {\n// HIDE THE DIALOGUE\n\tthis.dialog.hide();\n},\ndoEnter : function(type) {\n// RUN ENTER CALLBACK IF 'ENTER' CLICKED\n\tconsole.log(\"SyncDialog.doEnter plugins.dijit.SyncDialog.doEnter()\");\n\n\tvar inputs = this.validateInputs([\"message\", \"details\"]);\n\tconsole.log(\"SyncDialog.doEnter inputs:\");\n\tconsole.dir({inputs:inputs});\n\tif ( ! inputs ) {\n\t\tconsole.log(\"SyncDialog.doEnter inputs is null. Returning\");\n\t\treturn;\n\t}\n\n\t// RESET\n\tthis.message.set('value', \"\");\n\tthis.details.value = \"\";\n\n // HIDE\n this.hide();\n\t\n\t// DO CALLBACK\n\tthis.dialog.enterCallback(inputs);\t\n},\nvalidateInputs : function (keys) {\n\tconsole.log(\"Hub.validateInputs keys: \");\n\tconsole.dir({keys:keys});\n\n\tvar inputs = new Object;\n\tthis.isValid = true;\n\tfor ( var i = 0; i < keys.length; i++ ) {\n\t\tconsole.log(\"Hub.validateInputs Doing keys[\" + i + \"]: \" + keys[i]);\n\t\tinputs[keys[i]] = this.verifyInput(keys[i]);\n\t}\n\tconsole.log(\"Hub.validateInputs inputs: \");\n\tconsole.dir({inputs:inputs});\n\n\tif ( ! this.isValid ) \treturn null;\t\n\treturn inputs;\n},\nverifyInput : function (input) {\n\tconsole.log(\"Aws.verifyInput input: \");\n\tconsole.dir({this_input:this[input]});\n\tvar value = this[input].value;\n\tconsole.log(\"Aws.verifyInput value: \" + value);\n\n\tvar className = this.getClassName(this[input]);\n\tconsole.log(\"Aws.verifyInput className: \" + className);\n\tif ( className ) {\n\t\tconsole.log(\"Aws.verifyInput this[input].isValid(): \" + this[input].isValid());\n\t\tif ( ! value || ! this[input].isValid() ) {\n\t\t\tconsole.log(\"Aws.verifyInput input \" + input + \" value is empty. Adding class 'invalid'\");\n\t\t\tdojo.addClass(this[input].domNode, 'invalid');\n\t\t\tthis.isValid = false;\n\t\t}\n\t\telse {\n\t\t\tconsole.log(\"SyncDialog.verifyInput value is NOT empty. Removing class 'invalid'\");\n\t\t\tdojo.removeClass(this[input].domNode, 'invalid');\n\t\t\treturn value;\n\t\t}\n\t}\n\telse {\n\t\tif ( input.match(/;/) || input.match(/`/) ) {\n\t\t\tconsole.log(\"SyncDialog.verifyInput value is INVALID. Adding class 'invalid'\");\n\t\t\tdojo.addClass(this[input], 'invalid');\n\t\t\tthis.isValid = false;\n\t\t\treturn null;\n\t\t}\n\t\telse {\n\t\t\tconsole.log(\"SyncDialog.verifyInput value is VALID. Removing class 'invalid'\");\n\t\t\tdojo.removeClass(this[input], 'invalid');\n\t\t\treturn value;\n\t\t}\n\t}\n\t\n\treturn null;\n},\ndoCancel : function() {\n// RUN CANCEL CALLBACK IF 'CANCEL' CLICKED\n\t////console.log(\"SyncDialog.doCancel plugins.dijit.SyncDialog.doCancel()\");\n\tthis.dialog.cancelCallback();\n\tthis.dialog.hide();\n},\nsetDialogue : function () {\n\t// APPEND DIALOG TO DOCUMENT\n\tdocument.body.appendChild(this.dialog.domNode);\n\t\n\tthis.dialog.parentWidget = this;\n\t\n\t// AVOID this._fadeOutDeferred NOT DEFINED ERROR\n\tthis._fadeOutDeferred = function () {};\n},\nload : function (args) {\n\tconsole.log(\"SyncDialog.load args:\");\n\tconsole.dir({args:args});\n\n if ( args.title ) {\n console.log(\"SyncDialog.load SETTING TITLE: \" + args.title);\n \tthis.dialog.set('title', args.title);\n }\n \n\tthis.headerNode.innerHTML\t\t=\targs.header;\n\tif (args.message)\tthis.message.set('value', args.message);\n\tif (args.details) \tthis.details.value = args.details;\n\t//if (args.details) \tthis.details.innerHTML(args.details);\n\tthis.dialog.enterCallback\t\t=\targs.enterCallback;\n\n\tthis.show();\n}\n\n\n});\n\t\n"},"repo_name":{"kind":"string","value":"agua/aguadev"},"path":{"kind":"string","value":"html/plugins/dijit/SyncDialog.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":5315,"string":"5,315"}}},{"rowIdx":2885,"cells":{"code":{"kind":"string","value":"namespace TraktApiSharp.Objects.Basic.Json.Factories\n{\n using Objects.Basic.Json.Reader;\n using Objects.Basic.Json.Writer;\n using Objects.Json;\n\n internal class CommentLikeJsonIOFactory : IJsonIOFactory\n {\n public IObjectJsonReader CreateObjectReader() => new CommentLikeObjectJsonReader();\n\n public IArrayJsonReader CreateArrayReader() => new CommentLikeArrayJsonReader();\n\n public IObjectJsonWriter CreateObjectWriter() => new CommentLikeObjectJsonWriter();\n }\n}\n"},"repo_name":{"kind":"string","value":"henrikfroehling/TraktApiSharp"},"path":{"kind":"string","value":"Source/Lib/TraktApiSharp/Objects/Basic/Json/Factories/CommentLikeJsonIOFactory.cs"},"language":{"kind":"string","value":"C#"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":583,"string":"583"}}},{"rowIdx":2886,"cells":{"code":{"kind":"string","value":"package com.sdl.selenium.extjs3.button;\r\n\r\nimport com.sdl.selenium.bootstrap.button.Download;\r\nimport com.sdl.selenium.extjs3.ExtJsComponent;\r\nimport com.sdl.selenium.web.SearchType;\r\nimport com.sdl.selenium.web.WebLocator;\r\n\r\npublic class DownloadLink extends ExtJsComponent implements Download {\r\n\r\n public DownloadLink() {\r\n setClassName(\"DownloadLink\");\r\n setTag(\"a\");\r\n }\r\n\r\n public DownloadLink(WebLocator container) {\r\n this();\r\n setContainer(container);\r\n }\r\n\r\n public DownloadLink(WebLocator container, String text) {\r\n this(container);\r\n setText(text, SearchType.EQUALS);\r\n }\r\n\r\n /**\r\n * Wait for the element to be activated when there is deactivation mask on top of it\r\n *\r\n * @param seconds time\r\n */\r\n @Override\r\n public boolean waitToActivate(int seconds) {\r\n return getXPath().contains(\"ext-ux-livegrid\") || super.waitToActivate(seconds);\r\n }\r\n\r\n /**\r\n * if WebDriverConfig.isSilentDownload() is true, se face silentDownload, is is false se face download with AutoIT.\r\n * Download file with AutoIT, works only on FireFox. SilentDownload works FireFox and Chrome\r\n * Use only this: button.download(\"C:\\\\TestSet.tmx\");\r\n * return true if the downloaded file is the same one that is meant to be downloaded, otherwise returns false.\r\n *\r\n * @param fileName e.g. \"TestSet.tmx\"\r\n */\r\n @Override\r\n public boolean download(String fileName) {\r\n openBrowse();\r\n return executor.download(fileName, 10000L);\r\n }\r\n\r\n private void openBrowse() {\r\n executor.browse(this);\r\n }\r\n}\r\n"},"repo_name":{"kind":"string","value":"sdl/Testy"},"path":{"kind":"string","value":"src/main/java/com/sdl/selenium/extjs3/button/DownloadLink.java"},"language":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":1642,"string":"1,642"}}},{"rowIdx":2887,"cells":{"code":{"kind":"string","value":"angular.module('perCapita.controllers', [])\n\n .controller('AppCtrl', ['$scope', '$rootScope', '$ionicModal', '$timeout', '$localStorage', '$ionicPlatform', 'AuthService',\n function ($scope, $rootScope, $ionicModal, $timeout, $localStorage, $ionicPlatform, AuthService) {\n\n $scope.loginData = $localStorage.getObject('userinfo', '{}');\n $scope.reservation = {};\n $scope.registration = {};\n $scope.loggedIn = false;\n\n if (AuthService.isAuthenticated()) {\n $scope.loggedIn = true;\n $scope.username = AuthService.getUsername();\n }\n\n // Create the login modal that we will use later\n $ionicModal.fromTemplateUrl('templates/login.html', {\n scope: $scope\n }).then(function (modal) {\n $scope.modal = modal;\n });\n\n // Triggered in the login modal to close it\n $scope.closeLogin = function () {\n $scope.modal.hide();\n };\n\n // Open the login modal\n $scope.login = function () {\n $scope.modal.show();\n };\n\n // Perform the login action when the user submits the login form\n $scope.doLogin = function () {\n console.log('Doing login', $scope.loginData);\n $localStorage.storeObject('userinfo', $scope.loginData);\n\n AuthService.login($scope.loginData);\n\n $scope.closeLogin();\n };\n\n $scope.logOut = function () {\n AuthService.logout();\n $scope.loggedIn = false;\n $scope.username = '';\n };\n\n $rootScope.$on('login:Successful', function () {\n $scope.loggedIn = AuthService.isAuthenticated();\n $scope.username = AuthService.getUsername();\n });\n\n\n $ionicModal.fromTemplateUrl('templates/register.html', {\n scope: $scope\n }).then(function (modal) {\n $scope.registerform = modal;\n });\n\n $scope.closeRegister = function () {\n $scope.registerform.hide();\n };\n\n $scope.register = function () {\n $scope.registerform.show();\n };\n\n $scope.doRegister = function () {\n console.log('Doing registration', $scope.registration);\n $scope.loginData.username = $scope.registration.username;\n $scope.loginData.password = $scope.registration.password;\n\n AuthService.register($scope.registration);\n $timeout(function () {\n $scope.closeRegister();\n }, 1000);\n };\n\n $rootScope.$on('registration:Successful', function () {\n $localStorage.storeObject('userinfo', $scope.loginData);\n });\n\n }])\n\n .controller('FavoriteDetailsController', ['$scope', '$rootScope', '$state', '$stateParams', 'Favorites', function ($scope, $rootScope, $state, $stateParams, Favorites) {\n\n $scope.showFavButton = false;\n\n // Lookup favorites for a given user id\n Favorites.findById({id: $stateParams.id})\n .$promise.then(\n function (response) {\n $scope.city = response;\n },\n function (response) {\n $scope.message = \"Error: \" + response.status + \" \" + response.statusText;\n }\n );\n\n }])\n\n\n .controller('HomeController', ['$scope', 'perCapitaService', '$stateParams', '$rootScope', 'Favorites', '$ionicPlatform', '$cordovaLocalNotification', '$cordovaToast', function ($scope, perCapitaService, $stateParams, $rootScope, Favorites, $ionicPlatform, $cordovaLocalNotification, $cordovaToast) {\n\n $scope.showFavButton = $rootScope.currentUser;\n\n $scope.controlsData = {skills: $rootScope.skills};\n\n\n // Look up jobs data\n $scope.doLookup = function () {\n $rootScope.skills = $scope.controlsData.skills;\n perCapitaService.lookup($scope.controlsData.skills);\n };\n\n // Post process the jobs data, by adding Indeeds link and calculating jobsPer1kPeople and jobsRank\n $scope.updatePerCapitaData = function () {\n $scope.cities = perCapitaService.response.data.docs;\n\n var arrayLength = $scope.cities.length;\n for (var i = 0; i < arrayLength; i++) {\n var obj = $scope.cities[i];\n obj.jobsPer1kPeople = Math.round(obj.totalResults / obj.population * 1000);\n obj.url = \"https://www.indeed.com/jobs?q=\" + $scope.controlsData.skills + \"&l=\" + obj.city + \", \" + obj.state;\n }\n\n // rank jobs\n var sortedObjs;\n if (perCapitaService.isSkills) {\n sortedObjs = _.sortBy($scope.cities, 'totalResults').reverse();\n } else {\n sortedObjs = _.sortBy($scope.cities, 'jobsPer1kPeople').reverse();\n }\n $scope.cities.forEach(function (element) {\n element.jobsRank = sortedObjs.indexOf(element) + 1;\n });\n\n if (!$scope.$$phase) {\n $scope.$apply();\n }\n $rootScope.cities = $scope.cities;\n console.log(\"Loaded \" + arrayLength + \" results.\")\n\n };\n\n perCapitaService.registerObserverCallback($scope.updatePerCapitaData);\n\n $scope.addToFavorites = function () {\n delete $scope.city._id;\n delete $scope.city._rev;\n $scope.city.customerId = $rootScope.currentUser.id\n Favorites.create($scope.city);\n\n $ionicPlatform.ready(function () {\n\n $cordovaLocalNotification.schedule({\n id: 1,\n title: \"Added Favorite\",\n text: $scope.city.city\n }).then(function () {\n console.log('Added Favorite ' + $scope.city.city);\n },\n function () {\n console.log('Failed to add Favorite ');\n });\n\n $cordovaToast\n .show('Added Favorite ' + $scope.city.city, 'long', 'center')\n .then(function (success) {\n // success\n }, function (error) {\n // error\n });\n\n\n });\n\n }\n\n if ($stateParams.id) {\n console.log(\"param \" + $stateParams.id);\n $scope.city = $rootScope.cities.filter(function (obj) {\n return obj._id === $stateParams.id;\n })[0];\n\n console.log($scope.city);\n } else {\n $scope.doLookup();\n }\n\n\n }])\n\n .controller('AboutController', ['$scope', function ($scope) {\n\n }])\n\n .controller('FavoritesController', ['$scope', '$rootScope', '$state', 'Favorites', '$ionicListDelegate', '$ionicPopup', function ($scope, $rootScope, $state, Favorites, $ionicListDelegate, $ionicPopup) {\n\n $scope.shouldShowDelete = false;\n\n /*$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {\n console.log(\"State changed: \", toState);\n if(toState.name === \"app.favorites\") $scope.refreshItems();\n });*/\n\n $scope.refreshItems = function () {\n if ($rootScope.currentUser) {\n\n Favorites.find({\n filter: {\n where: {\n customerId: $rootScope.currentUser.id\n }\n }\n }).$promise.then(\n function (response) {\n $scope.favorites = response;\n console.log(\"Got favorites\");\n },\n function (response) {\n console.log(response);\n });\n }\n else {\n $scope.message = \"You are not logged in\"\n }\n }\n\n $scope.refreshItems();\n\n $scope.toggleDelete = function () {\n $scope.shouldShowDelete = !$scope.shouldShowDelete;\n console.log($scope.shouldShowDelete);\n }\n\n $scope.deleteFavorite = function (favoriteid) {\n\n var confirmPopup = $ionicPopup.confirm({\n title: '

    Confirm Delete

    ',\n template: '

    Are you sure you want to delete this item?

    '\n });\n\n confirmPopup.then(function (res) {\n if (res) {\n console.log('Ok to delete');\n Favorites.deleteById({id: favoriteid}).$promise.then(\n function (response) {\n $scope.favorites = $scope.favorites.filter(function (el) {\n return el.id !== favoriteid;\n });\n $state.go($state.current, {}, {reload: false});\n // $window.location.reload();\n },\n function (response) {\n console.log(response);\n $state.go($state.current, {}, {reload: false});\n });\n } else {\n console.log('Canceled delete');\n }\n });\n $scope.shouldShowDelete = false;\n\n }\n\n }])\n\n;\n"},"repo_name":{"kind":"string","value":"vjuylov/percapita-mobile"},"path":{"kind":"string","value":"www/js/controllers/controllers.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":8105,"string":"8,105"}}},{"rowIdx":2888,"cells":{"code":{"kind":"string","value":"# VBA.ModernTheme\n\n### Windows Phone Colour Palette and

    Colour Selector using WithEvents\n\nVersion 1.0.1\n\nThe *Windows Phone Theme Colours* is a tight, powerful, and well balanced palette.\n\nThis tiny Microsoft Access application makes it a snap to select and pick a value. And it doubles as an intro to implementing *WithEvents*, one of Access' hidden gems.\n\n![General](https://raw.githubusercontent.com/GustavBrock/VBA.ModernTheme/master/images/ModernThemeHeader.png)\n\nFull documentation is found here:\n\n![EE Logo](https://raw.githubusercontent.com/GustavBrock/VBA.ModernTheme/master/images/EE%20Logo.png)\n\n[Create Windows Phone Colour Palette and Selector using WithEvents](https://www.experts-exchange.com/articles/29554/Create-Windows-Phone-Colour-Palette-and-Selector-using-WithEvents.html?preview=yawJg2wkMzc%3D)\n\n


    \n\n*If you wish to support my work or need extended support or advice, feel free to:*\n\n

    \n\n[](https://www.buymeacoffee.com/gustav/)"},"repo_name":{"kind":"string","value":"GustavBrock/VBA.ModernTheme"},"path":{"kind":"string","value":"README.md"},"language":{"kind":"string","value":"Markdown"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":1060,"string":"1,060"}}},{"rowIdx":2889,"cells":{"code":{"kind":"string","value":"var http = require(\"http\");\nvar querystring = require(\"querystring\"); // 核心模块\nvar SBuffer=require(\"../tools/SBuffer\");\nvar common=require(\"../tools/common\");\nvar zlib=require(\"zlib\");\nvar redis_pool=require(\"../tools/connection_pool\"); \n\nvar events = require('events');\nvar util = require('util'); \n\nfunction ProxyAgent(preHeaders,preAnalysisFields,logName){\n\tthis.headNeeds = preHeaders||\"\";\n\tthis.preAnalysisFields = preAnalysisFields||\"\";\n\tthis.AnalysisFields = {};\n\tthis.logName=logName||\"\";\n\tthis.response=null;\n\tthis.reqConf={};\n\tthis.retData=[];\n\tthis.redis =null; // redis {} redis_key\n\tevents.EventEmitter.call(this);\n}\n\n/**\n * 获取服务配置信息\n * @param 服务名\n * @return object \n */ \nProxyAgent.prototype.getReqConfig = function(logName){\n\tvar _self=this;\n\tvar Obj={};\n\tObj=Config[logName];\n\tObj.logger=Analysis.getLogger(logName);\n\tObj.name=logName;\n\treturn Obj;\n}\n\nProxyAgent.prototype.doRequest=function(_req,_res){\n\tvar _self=this;\n\t_self.reqConf=_self.getReqConfig(this.logName);\n\tlogger.debug('进入'+_self.reqConf.desc+\"服务\");\n\t\n\tvar header_obj =this.packageHeaders(_req.headers,this.headNeeds);\n\t\t\n\tvar url_obj = url.parse(request.url, true);\n\tvar query_obj = url_obj.query; \n\t\n\tvar postData = request.body|| \"\"; // 获取请求参数\n\t\n\t_res.setHeader(\"Content-Type\", config.contentType);\n\t_res.setHeader(config.headerkey, config.headerval);\n\tvar opts=_self.packData(header_obj,query_obj,postData);\n\tlogger.debug(header_obj.mobileid +_self.reqConf.desc+ '接口参数信息:'+opts[0].path +\" data:\"+ opts[1]);\n\t\n\tif(typeof(postData) ==\"object\" && postData.redis_key.length>0){\n\t this.getRedis(opts[0],opts[1]);\n\t}\n\telse{\n\t\tthis.httpProxy(opts[0],opts[1]);\n\t}\n\t\n}\n\n/**\n * 封装get post接口\n * @param headers\n * @param query\n * @param body\n * @return []\n */ \nProxyAgent.prototype.packData=function(headers,query,body){\n\tvar _self=this;\n\t//resType 解释 \"\"==>GET,\"body\"==>POST,\"json\"==>特殊poi,\"raw\"==>原始数据\n\tvar type=_self.reqConf.resType || \"\"; \n\tbody = body || \"\";\n\tvar len=0;\n\tvar query_str=\"\";\n\tvar body_str=\"\";\n\tif(type==\"\"){\n\t\tquery=common.extends(query,headers);\n\t\tquery_str = querystring.stringify(query, '&', '=');\n\t}\n\telse if(type==\"body\"){\n\t\tbody=common.extends(body,headers);\n\t\tbody_str = querystring.stringify(body, '&', '=');\n\t\tlen=body_str.length;\t\t\n\t\t\tif(body.redis_key){\n\t\t\t\tthis.redis={};\n\t\t\t\tthis.redis.redis_key=body.redis_key;\n\t\t\t}\n\t}\n\telse if(type==\"json\"){\n\t\tquery=common.extends(query,headers);\n\t\tquery_str = 'json='+querystring.stringify(query, '&', '=');\n\t}\n\telse if(type==\"raw\"){\n\t\tlen=body.length;\n\t\tbody_str=body;\n\t}\n\tvar actionlocation = headers.actionlocation || \"\";\n\tif(actionlocation==\"\"){\n\t\tactionlocation=query.actionlocation||\"\";\n\t}\n\tvar opts=_self.getRequestOptions(len,actionlocation);\n\n\topts.path+=((opts.path.indexOf(\"?\")>=0)?\"&\":\"?\")+query_str;\n\t\n\treturn [opts,body_str];\n}\n\n/**\n * 获取请求头信息\n * @param len数据长度\n * @param actiontion 通用访问地址\n * @return object 头信息\n */ \nProxyAgent.prototype.getRequestOptions=function(len,actionlocation){\n\tvar _self=this;\n\t\n\tvar options = {\t\t\t\t\t\t\t\t\t\t\t\t//http请求参数设置\n\t host: _self.reqConf.host,\t\t\t\t\t\t\t\t// 远端服务器域名\n\t port: _self.reqConf.port,\t\t\t\t\t\t\t\t// 远端服务器端口号\n\t path: _self.reqConf.path||\"\",\t\t\t\t\t\t\t\n\t headers : {'Connection' : 'keep-alive'}\n\t};\n\tif(actionlocation.length>0){\n\t\toptions.path=actionlocation;\n\t}\n\t\n\tvar rtype= _self.reqConf.reqType || \"\";\n\tif(rtype.length>0){\n\t\toptions.headers['Content-Type']=rtype; \n }\n if(len>0){\n\t\toptions.headers['Content-Length']=len;\n }\n\n\treturn options;\n}\n\nProxyAgent.prototype.getRedisOptions=function(options,actionlocation){\n\tvar obj={};\n\n\treturn obj;\n}\n\n\n/**\n * 获取头部信息进行封装\n * @param request.headers\n * @param need fields ;split with ','\n * @return object headers\n */\nProxyAgent.prototype.packageHeaders = function(headers) {\n\tvar fields=arguments[1]||\"\";\n\tvar query_obj = {};\n\tvar reqip = headers['x-real-ip'] || '0'; // 客户端请求的真实ip地址\n\tvar forward = headers['x-forwarded-for'] || '0'; // 客户端请求来源\n\tvar osversion = headers['osversion'] || '0';// 客户端系统\n\tvar devicemodel = headers['devicemodel'] || '0';// 客户端型号\n\tvar manufacturername = headers['manufacturername'] || '0';// 制造厂商\n\tvar actionlocation = headers['actionlocation']; // 请求后台地址\n\tvar dpi = headers['dpi'] || '2.0';// 密度\n\tvar imsi = headers['imsi'] || '0'; // 客户端imsi\n\tvar mobileid = headers['mobileid'] || '0'; // 客户端mibileid\n\tvar version = headers['version'] || '0';// 客户端版本version\n\tvar selflon = headers['selflon'] || '0';// 经度\n\tvar selflat = headers['selflat'] || '0';// 维度\n\tvar uid = headers['uid'] || '0'; // 犬号\n\tvar radius=headers['radius']||'0';//误差半径\n\tvar platform=headers['platform']||\"\";//平台 ios ,android\n \tvar gender= headers['gender'] || '0'; \n \t\n \tquery_obj.gender = gender;\n\tquery_obj.reqip = reqip;\n\tquery_obj.forward = forward;\n\tquery_obj.osversion = osversion;\n\tquery_obj.devicemodel = devicemodel;\n\tquery_obj.manufacturername = manufacturername;\n\tquery_obj.actionlocation = actionlocation;\n\tquery_obj.dpi = dpi;\n\tquery_obj.imsi = imsi;\n\tquery_obj.mobileid = mobileid;\n\tquery_obj.version = version;\n\tquery_obj.selflon = selflon;\n\tquery_obj.selflat = selflat;\n\tquery_obj.uid = uid;\n\tquery_obj.radius=radius;\n\tquery_obj.platform=platform;\n\t\n\tif(fields.length > 0){\n\t\tvar afields = fields.split(\",\");\n\t\tvar newObj = {};\n\t\tfor(var i = 0; i < afields.length ; i ++){\n\t\t\tnewObj[afields[i]] = query_obj[afields[i]] || \"\";\t\t\n\t\t}\n\t\treturn newObj;\n\t}\n\telse{\n\t\treturn query_obj;\n\t}\n}\n\n\n/**\n * http 请求代理\n * @param options 远程接口信息\n * @param reqData 请求内容 req.method== get时一般为空\n */ \nProxyAgent.prototype.httpProxy = function (options,reqData){\n\tvar _self=this;\n\tvar TongjiObj={};\n\tvar req = http.request(options, function(res) {\n\t\t\n\t\tTongjiObj.statusCode = res.statusCode ||500;\n\t\tvar tmptime=Date.now();\n\t\tTongjiObj.restime = tmptime;\n\t\tTongjiObj.resEnd =tmptime;\t\n\t\tTongjiObj.ends = tmptime;\n\t\tTongjiObj.length = 0;\n\t\tTongjiObj.last = tmptime;\n\n\t var sbuffer=new SBuffer();\n\t\tres.setEncoding(\"utf-8\");\n\t\tres.on('data', function (trunk) {\n\t\t\tsbuffer.append(trunk);\n\t\t});\n\t\tres.on('end', function () {\n\t\t\tTongjiObj.resEnd = Date.now();\n\t\t\t//doRequestCB(response, {\"data\":sbuffer.toString(),\"status\":res.statusCode},TongjiObj,redisOpt);\n\t\t\t_self.emmit(\"onDone\",sbuffer,TongjiObj);\n\t\t});\n\t});\n\treq.setTimeout(timeout,function(){\n\t\t req.emit('timeOut',{message:'have been timeout...'});\n\t});\n\treq.on('error', function(e) {\n\t\tTongjiObj.statusCode=500;\n\t\t_self.emmit(\"onDone\",\"\",500,TongjiObj);\n\t});\n\treq.on('timeOut', function(e) {\n\t\treq.abort();\n\t\tTongjiObj.statusCode=500;\n\t\tTongjiObj.last = Date.now();\n\t\t_self.emmit(\"onDone\",\"\",500,TongjiObj);\n\t});\n\treq.end(reqData);\n}\n\n/**\n * 设置缓存\n * @param redis_key\n * @param redis_time\n * @param resultBuffer\n */\nProxyAgent.prototype.setRedis = function (redis_key, redis_time, resultBuffer) {\n\tredis_pool.acquire(function(err, client) {\n\t\tif (!err) {\n\t\t\tclient.setex(redis_key, redis_time, resultBuffer, function(err,\n\t\t\t\t\trepliy) {\n\t\t\t\tredis_pool.release(client); // 链接使用完毕释放链接\n\t\t\t});\n\t\t\tlogger.debug(redis_key + '设置缓存数据成功!');\n\t\t} else {\n\t\t\twriteLogs.logs(Analysis.getLogger('error'), 'error', {\n\t\t\t\tmsg : 'redis_general保存数据到redis缓存数据库时链接redis数据库异常',\n\t\t\t\terr : 14\n\t\t\t});\n\t\t\tlogger.debug(redis_key + '设置缓存数据失败!');\n\t\t}\n\t});\n}\n\n\n/**\n * 从缓存中获取数据,如果获取不到,则请求后台返回的数据返回给客户端 并且将返回的数据设置到redis缓存\n * redis_key通过self变量中取\n * @param options\n * @param reqData\n */\nProxyAgent.prototype.getRedis = function ( options, reqData) {\n\tvar _self=this;\n\tvar redis_key=this.redis.redis_key || \"\";\n\tredis_pool.acquire(function(err, client) {\n\t\tif (!err) {\n\t\t\tclient.get(redis_key, function(err, date) {\n\t\t\t\tredis_pool.release(client) // 用完之后释放链接\n\t\t\t\tif (!err && date != null) {\n\t\t\t\t\tvar resultBuffer = new Buffer(date);\n\t\t\t\t\t_self.response.statusCode = 200;\n\t\t\t\t\t_self.response.setHeader(\"Content-Length\", resultBuffer.length);\n\t\t\t\t\t_self.response.write(resultBuffer); // 以二进制流的方式输出数据\n\t\t\t\t\t_self.response.end();\n\t\t\t\t\tlogger.debug(redis_key + '通用接口下行缓存数据:' + date);\n\t\t\t\t} else {\n\t\t\t\t\t_self.httpProxy(options, reqData);\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\t_self.httpProxy(options, reqData);\n\t\t}\n\t});\n}\n\n\n/**\n * 输出gzip数据\n * response 内置\n * @param resultBuffer \n */\nProxyAgent.prototype.gzipOutPut = function (resultBuffer){\n\tvar _self=this;\n\tzlib.gzip(resultBuffer, function(code, buffer){\t\t\t\t\t\t// 对服务器返回的数据进行压缩\n if (code != null) { // 如果正常结束\n \tlogger.debug('压缩成功,压缩前:'+resultBuffer.length+',压缩后:'+buffer.length);\n \t_self.response.setHeader('Content-Encoding', 'gzip');\t\t\t\t\t//压缩标志\n } else {\n\t\t\tbuffer = new Buffer( '{\"msg\":[\"服务器返回数据非JSON格式\"]}');\n\t\t\t_self.response.statusCode=500;\n }\n _self.response.setHeader(\"Content-Length\", buffer.length);\n\t\t_self.response.write(buffer);\n\t _self.response.end();\t\n\t});\n}\n\n/**\n * 请求完毕处理\n * @param buffer type buffer/string\n * @param status 请求http状态\n * @param tongji object统计对象\n */ \nProxyAgent.prototype.onDone =function(buffer,status){\n\tvar tongji=arguments[2] ||\"\";\n\tvar _self=this;\n\tvar resultStr = typeof(buffer)==\"object\"?buffer.toString():buffer;\n\tif(this.reqConf.isjson==1){\n\t\tvar resultObj = common.isJson( resultStr, _self.reqConf.logName); // 判断返回结果是否是json格式\n\t\tif (resultObj) { // 返回结果是json格式\n\t\t\tresultStr = JSON.stringify(resultObj);\n\t\t\t_self.response.statusCode = status;\n\t\t} else {\n\t\t\tresultStr = '{\"msg\":[\"gis服务器返回数据非JSON格式\"]}';\n\t\t\t_self.response.statusCode = 500;\n\t\t}\n\t}\n\telse{\n\t\t_self.response.statusCode = status;\n\t}\t\n\t\t\t\t \n\tvar resultBuffer = new Buffer(resultStr);\n\tif(tongji!=\"\"){\n\t\ttongji.ends = Date.now();\n\t\ttongji.length = resultBuffer.length;\n\t}\n\tif(resultBuffer.length > 500 ){\n\t\t//压缩输出\n\t\t_self.gzipOutPut(resultBuffer);\n\t\t\n\t}else{\n\t\t_self.response.setHeader(\"Content-Length\", resultBuffer.length);\n\t\t_self.response.write(resultBuffer); // 以二进制流的方式输出数据\n\t\t_self.response.end();\n\t}\n\t\n\tif(tongji!=\"\"){\n\t\ttongji.last= Date.now();\n\t\ttongji=common.extends(tongji,_self.preAnalysisFields);\n\t\tlogger.debug('耗时:' + (tongji.last - tongji.start)+'ms statusCode='+status);\n\t\twriteLogs.logs(poiDetailServer,'poiDetailServer',obj);\n\t}\n});\n\n\nProxyAgent.prototype.onDones =function(buffer,status){\n\tvar tongji=arguments[2] ||\"\";\n\tthis.retData.push([buffer,status,tongji];\n});\n\nProxyAgent.prototype.dealDones =function(){\n\tvar tongji=arguments[2] ||\"\";\n\tthis.retData.push([buffer,status,tongji];\n});\n\n//ProxyAgent 从event 集成\n//utils.inherit(ProxyAgent,event);\n\nexports.ProxyAgent=ProxyAgent;\n"},"repo_name":{"kind":"string","value":"RazarDessun/fastProxy"},"path":{"kind":"string","value":"test/test_timeout2.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":11087,"string":"11,087"}}},{"rowIdx":2890,"cells":{"code":{"kind":"string","value":"---\nlayout: post\ntitle: \"Hello World\"\nimage:\n feature: nomadsland.jpg\ndate: 2016-09-19 20:24:11 +0200\ncategories: personal, coding\n---\nI enjoy tinkering - building little electronic gadgets and apps - especially if it has something to do with [cryptocurrencies]. Currently my day-job is building Bitcoin infrastructure. The purpose of this weblog is to record the progress on various projects outside my normal scope of work. Working with software, I seem to hit a lot of **\"Hmmm, I wonder how this works?\"** moments. Hopefully these pages provide some useful information to somebody working on and wondering about the same things.\n\n## Begin\nI'm a fan of the maxim \"Done is better than perfect\" so my current goal is to get this blog up and running as quickly as possible. Instead of wondering about which software or host to use, I decided to power it with [Jekyll] and host it on [Github pages]. I already have a code/text editor I like using and git is already part of my daily workflow so it seemed like a natural fit. I picked a theme I liked but just as I got something that looked vaguely OK, I ran into the first **\"Hmmm, I wonder\"** moment.\n\nIt turns out Jekyll/Github pages deployments are not intuitive. \n\n[Jekyll's Basic Usage Guide] does a pretty good job of explaining how to get up and running locally, but trying to find GH-Pages deployment instructions (and failing miserably) made me realise things don't work as I'd expect.\n\n## Jekyll & Github\nJekyll uses plugins and templates to help authors perform dynamic blog-related things like themeing, categorising and indexing posts, generating \"about\" pages and more.\n\n`jekyll build` produces a static \"render\" of the blog at the time it is called so that you can just upload the HTML/JS/CSS contents of the generated `_site` directory to a server that serves static content. You could host it on dropbox if you wanted to, there's no server-side scripts like PHP or Rails to generate content from data stored in a database.\n\n`_site` gets destroyed and re-created every time you call `jekyll build` and it is listed in `.gitignore` so it's not part of the repo, so how in the world do you tell Github to serve the contents of `_site`? Am I supposed to create a manual deploy script that adds `_site` to a repo and push that?\n\n## Hmmm, I wonder...\n\nSo which is it? \n\nTurns out you simply push your jekyll source repo to `master`. You don't even need to call `jekyll build`. Your site just magically appears on Github. That leaves only two possibilities:\n\n1. Either Github calls `jekyll build` and serves the `_site` directory after each push, or\n\n2. Github is running `jekyll serve` to generate content every request. \n\nTurns out it's the latter. Github actually runs Jekyll, and supports [some Jekyll plugins].\n\n## Done\nSo, one \"git push\" later and these pages should be live! \n\n*\"Done is better than perfect\"*\n\n[BitX]: https://www.bitx.co/\n[cryptocurrencies]: https://en.wikipedia.org/wiki/Cryptocurrency\n[jekyll]: https://jekyllrb.com\n[Jekyll's Basic Usage Guide]: https://jekyllrb.com/docs/usage/\n[Github pages]: https://pages.github.com/\n[some Jekyll plugins]: https://help.github.com/articles/adding-jekyll-plugins-to-a-github-pages-site/"},"repo_name":{"kind":"string","value":"carelvwyk/carelvwyk.github.io"},"path":{"kind":"string","value":"_posts/2016-09-19-hello-world.markdown"},"language":{"kind":"string","value":"Markdown"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":3210,"string":"3,210"}}},{"rowIdx":2891,"cells":{"code":{"kind":"string","value":"getRules('*');\r\n\r\n $this->assertEmpty($rules, 'expected remove comments');\r\n }\r\n\r\n /**\r\n * @dataProvider generateDataFor2Test\r\n */\r\n public function testRemoveCommentsFromValue($robotsTxtContent, $expectedDisallowValue)\r\n {\r\n $parser = new RobotsTxtParser($robotsTxtContent);\r\n\r\n\r\n $rules = $parser->getRules('*');\r\n\r\n $this->assertNotEmpty($rules, 'expected data');\r\n $this->assertArrayHasKey('disallow', $rules);\r\n $this->assertNotEmpty($rules['disallow'], 'disallow expected');\r\n $this->assertEquals($expectedDisallowValue, $rules['disallow'][0]);\r\n }\r\n\r\n /**\r\n * Generate test case data\r\n * @return array\r\n */\r\n public function generateDataForTest()\r\n {\r\n return array(\r\n array(\r\n \"\r\n\t\t\t\tUser-agent: *\r\n\t\t\t\t#Disallow: /tech\r\n\t\t\t\"\r\n ),\r\n array(\r\n \"\r\n\t\t\t\tUser-agent: *\r\n\t\t\t\tDisallow: #/tech\r\n\t\t\t\"\r\n ),\r\n array(\r\n \"\r\n\t\t\t\tUser-agent: *\r\n\t\t\t\tDisal # low: /tech\r\n\t\t\t\"\r\n ),\r\n array(\r\n \"\r\n\t\t\t\tUser-agent: *\r\n\t\t\t\tDisallow#: /tech # ds\r\n\t\t\t\"\r\n ),\r\n );\r\n }\r\n\r\n /**\r\n * Generate test case data\r\n * @return array\r\n */\r\n public function generateDataFor2Test()\r\n {\r\n return array(\r\n array(\r\n \"User-agent: *\r\n\t\t\t\t\tDisallow: /tech #comment\",\r\n 'disallowValue' => '/tech',\r\n ),\r\n );\r\n }\r\n}\r\n"},"repo_name":{"kind":"string","value":"bopoda/robots-txt-parser"},"path":{"kind":"string","value":"tests/RobotsTxtParser/CommentsTest.php"},"language":{"kind":"string","value":"PHP"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":1834,"string":"1,834"}}},{"rowIdx":2892,"cells":{"code":{"kind":"string","value":"/*\n * The MIT License\n *\n * Copyright 2016 njacinto.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\npackage org.nfpj.utils.arrays;\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\nimport java.util.function.Predicate;\nimport org.nfpj.utils.predicates.TruePredicate;\n\n/**\n *\n * @author njacinto\n * @param the type of object being returned by this iterator\n */\npublic class ArrayFilterIterator implements Iterator {\n protected static final int END_OF_ITERATION = -2;\n //\n private int nextIndex;\n //\n protected final T[] array;\n protected final Predicate predicate;\n\n // \n /**\n * Creates an instance of this class\n * \n * @param array the array from where this instance will extract the elements\n * @param predicate the filter to be applied to the elements\n */\n public ArrayFilterIterator(T[] array, Predicate predicate) {\n this(array, predicate, -1);\n }\n \n /**\n * \n * @param array\n * @param predicate \n * @param prevIndex \n */\n protected ArrayFilterIterator(T[] array, Predicate predicate, int prevIndex) {\n this.array = array!=null ? array : ArrayUtil.empty();\n this.predicate = predicate!=null ? predicate : TruePredicate.getInstance();\n this.nextIndex = getNextIndex(prevIndex);\n }\n // \n // \n \n /**\n * {@inheritDoc}\n */\n @Override\n public boolean hasNext() {\n return nextIndex != END_OF_ITERATION;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public T next() {\n if(nextIndex==END_OF_ITERATION){\n throw new NoSuchElementException(\"The underline collection has no elements.\");\n }\n int index = nextIndex;\n nextIndex = getNextIndex(nextIndex);\n return array[index];\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void remove() {\n throw new UnsupportedOperationException(\"The iterator doesn't allow changes.\");\n }\n // \n // \n /**\n * Searches for the next element that matches the filtering conditions and\n * returns it.\n * \n * @param currIndex\n * @return the next element that matches the filtering conditions or null\n * if no more elements are available\n */\n protected int getNextIndex(int currIndex){\n if(currIndex!=END_OF_ITERATION){\n for(int i=currIndex+1; i\n}\n"},"repo_name":{"kind":"string","value":"njacinto/Utils"},"path":{"kind":"string","value":"src/main/java/org/nfpj/utils/arrays/ArrayFilterIterator.java"},"language":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":3840,"string":"3,840"}}},{"rowIdx":2893,"cells":{"code":{"kind":"string","value":"---\nlayout: post\ntitle: slacker로 slack bot 만들기\ncomments: true\ntags:\n- python\n- slack\n- 봇\n- slacker\n---\n&nbsp;&nbsp;&nbsp; 멘토님께서 라인의 `notification`을 이용해서 봇 만든것을 보고 따라 만들었다. 봇 만들고 싶은데 핑계가 없어서 고민하다가 동아리에서 `slack`을 쓰기 때문에 슬랙봇을 만들어보기로 했다. 스터디하는 사람들을 대상으로 커밋한지 얼마나 되었는지 알려주는 용도로 만들었다. 결과물은 아래와 같다.\n\n\"클린\n\n&nbsp;&nbsp;&nbsp; 먼저 봇을 등록해야한다. [Slack Apps](https://studytcp.slack.com/apps)의 우측 상단에 `Build`를 눌러서 등록을 한다. 아래와 같은 화면이 나온다. 다른 팀에게 공개하지 않을 것이라서 `Something just for my team`을 선택했다.\n![slackbot 등록]({{ site.url }}/images/slackbot_0.png)\n\n&nbsp;&nbsp;&nbsp; 두 번째 `Bots`를 선택한다.\n![slackbot 등록]({{ site.url }}/images/slackbot_1.png)\n\n&nbsp;&nbsp;&nbsp; 적절한 설정을 하고 `token`을 꼭 기억(복사)해 두자.\n\n&nbsp;&nbsp;&nbsp; pip로 필요한 것을 설치하자. [github3.py](https://github3py.readthedocs.io/en/master/), [slacker](https://pypi.python.org/pypi/slacker/), datetime, pytz를 사용했다.\n

    $ pip install slacker\n$ pip install github3.py\n$ pip install datetime\n$ pip install pytz
    \n\n&nbsp;&nbsp;&nbsp; 전체 코드는 아래와 같다.\n\n```python\nfrom slacker import Slacker\nimport github3\nimport datetime\nimport pytz\n\nlocal_tz = pytz.timezone('Asia/Seoul')\ntoken = 'xoxb-발급받은-토큰'\nslack = Slacker(token)\nchannels = ['#채널1', '#채널2']\n\ndef post_to_channel(message):\n slack.chat.post_message(channels[0], message, as_user=True)\n\ndef get_repo_last_commit_delta_time(owner, repo):\n repo = github3.repository(owner, repo)\n return repo.pushed_at.astimezone(local_tz)\n\ndef get_delta_time(last_commit):\n now = datetime.datetime.now(local_tz)\n delta = now - last_commit\n return delta.days\n\ndef main():\n members = (\n # (git 계정 이름, repo 이름, 이름),\n # [...]\n )\n reports = []\n\n for owner, repo, name in members:\n last_commit = get_repo_last_commit_delta_time(owner, repo)\n delta_time = get_delta_time(last_commit)\n\n if(delta_time == 0):\n reports.append('*%s* 님은 오늘 커밋을 하셨어요!' % (name))\n else:\n reports.append('*%s* 님은 *%s* 일이나 커밋을 안하셨어요!' % (name, delta_time))\n\n post_to_channel('\\n 안녕 친구들! 과제 점검하는 커밋벨이야 호호 \\n' + '\\n'.join(reports))\n\nif __name__ == '__main__':\n main()\n```\n\n## **해결하지 못한 것**\n* **X-RateLimit-Limit 올리기** \n&nbsp;&nbsp;&nbsp; 테스트 때문에 꽤 많이 돌리다 보니까 횟수제한에 걸렸다. 에러 메시지는 아래와 같다.\n
    github3.models.GitHubError: 403 API rate limit exceeded for 106.246.181.100. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)
    \n\n&nbsp;&nbsp;&nbsp; 찾아보니까 하나의 IP당 한 시간에 보낼 수 있는 횟수가 정해져 있다고 한다. 출력해 보면 아래와 같다. `X-RateLimit-Limit`은 기본이 60이고 최대 5000으로 올릴 수 있다는데 헤더 수정을 어떻게 해야할지 모르겠다. 사실 이거 해결한다고 시간이 꽤 지나버려서 해결(?)이 되었다.\n
    [...]\nStatus: 403 Forbidden\nX-RateLimit-Limit: 60\nX-RateLimit-Remaining: 0\nX-RateLimit-Reset: 1475913003\n[...]
    \n\n* **이 코드를 어디서 돌려야 하는가.** \n&nbsp;&nbsp;&nbsp; 하루에 2-3번? 정도 해당 채널에 알림을 보낼 것이다. 사실 동아리 서버 쓰면 된다고는 하는데.. 개인 서버를 쓰고는 싶고 그렇다고 AWS 쓰자니 별로 하는것도 없는데 달마다 치킨 값을 헌납해야해서 고민이다.\n\n## **참고자료**\n* [https://corikachu.github.io/articles/python/python-slack-bot-slacker](https://corikachu.github.io/articles/python/python-slack-bot-slacker)\n* [https://www.fullstackpython.com/blog/build-first-slack-bot-python.html](https://www.fullstackpython.com/blog/build-first-slack-bot-python.html)\n* [https://godoftyping.wordpress.com/2015/04/19/python-%EB%82%A0%EC%A7%9C-%EC%8B%9C%EA%B0%84%EA%B4%80%EB%A0%A8-%EB%AA%A8%EB%93%88/](https://godoftyping.wordpress.com/2015/04/19/python-%EB%82%A0%EC%A7%9C-%EC%8B%9C%EA%B0%84%EA%B4%80%EB%A0%A8-%EB%AA%A8%EB%93%88/)\n"},"repo_name":{"kind":"string","value":"hyesun03/hyesun03.github.io"},"path":{"kind":"string","value":"_posts/2016-10-08-slackbot.md"},"language":{"kind":"string","value":"Markdown"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":4664,"string":"4,664"}}},{"rowIdx":2894,"cells":{"code":{"kind":"string","value":"import React from 'react';\nimport IconBase from './../components/IconBase/IconBase';\n\nexport default class IosHeart extends React.Component {\n\trender() {\nif(this.props.bare) {\n\t\t\treturn \n\n\n\n\t\t\t;\n\t\t}\t\treturn \n\n;\n\t}\n};IosHeart.defaultProps = {bare: false}"},"repo_name":{"kind":"string","value":"fbfeix/react-icons"},"path":{"kind":"string","value":"src/icons/IosHeart.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":1031,"string":"1,031"}}},{"rowIdx":2895,"cells":{"code":{"kind":"string","value":"add(NAVBAR_TITLE, tep_href_link(FILENAME_SPECIALS));\n\n require(DIR_WS_INCLUDES . 'template_top.php');\n?>\n\n

    \n\n
    \n
    \n\nnumber_of_rows > 0) && ((PREV_NEXT_BAR_LOCATION == '1') || (PREV_NEXT_BAR_LOCATION == '3'))) {\n?>\n\n
    \n display_links(MAX_DISPLAY_PAGE_LINKS, tep_get_all_get_params(array('page', 'info', 'x', 'y'))); ?>\n\n display_count(TEXT_DISPLAY_NUMBER_OF_SPECIALS); ?>\n
    \n\n
    \n\n\n\n \n \nsql_query);\n while ($specials = tep_db_fetch_array($specials_query)) {\n $row++;\n\n echo '' . \"\\n\";\n\n if ((($row / 3) == floor($row / 3))) {\n?>\n \n \n\n \n
    ' . tep_image(DIR_WS_IMAGES . $specials['products_image'], $specials['products_name'], SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT) . '
    ' . $specials['products_name'] . '
    ' . $currencies->display_price($specials['products_price'], tep_get_tax_rate($specials['products_tax_class_id'])) . '
    ' . $currencies->display_price($specials['specials_new_products_price'], tep_get_tax_rate($specials['products_tax_class_id'])) . '
    \n\nnumber_of_rows > 0) && ((PREV_NEXT_BAR_LOCATION == '2') || (PREV_NEXT_BAR_LOCATION == '3'))) {\n?>\n\n
    \n\n
    \n display_links(MAX_DISPLAY_PAGE_LINKS, tep_get_all_get_params(array('page', 'info', 'x', 'y'))); ?>\n\n display_count(TEXT_DISPLAY_NUMBER_OF_SPECIALS); ?>\n
    \n\n\n\n
    \n
    \n\n\n"},"repo_name":{"kind":"string","value":"gliss/oscommerce-bootstrap"},"path":{"kind":"string","value":"catalog/specials.php"},"language":{"kind":"string","value":"PHP"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":3956,"string":"3,956"}}},{"rowIdx":2896,"cells":{"code":{"kind":"string","value":"---\nlayout: home\ntitle: JARVARS\ncomments: false\n---\n"},"repo_name":{"kind":"string","value":"jarvars/jarvars.github.io"},"path":{"kind":"string","value":"index.html"},"language":{"kind":"string","value":"HTML"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":52,"string":"52"}}},{"rowIdx":2897,"cells":{"code":{"kind":"string","value":"{% extends \"admin/base.html\" %}\n{% load i18n %}\n\n{% block title %}{{ title }} | {% trans 'lab purchase management' %}{% endblock %}\n\n{% block branding %}\n

    {% trans 'LabHamster' %}

    \n{% endblock %}\n\n{% block nav-global %}{% endblock %}\n"},"repo_name":{"kind":"string","value":"graik/labhamster"},"path":{"kind":"string","value":"site_templates/admin/base_site.html"},"language":{"kind":"string","value":"HTML"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":256,"string":"256"}}},{"rowIdx":2898,"cells":{"code":{"kind":"string","value":"/*\n * Copyright (c) 2007 Mockito contributors\n * This program is made available under the terms of the MIT License.\n */\npackage org.mockitousage.verification;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.fail;\nimport static org.mockito.Mockito.anyString;\nimport static org.mockito.Mockito.atMost;\nimport static org.mockito.Mockito.atMostOnce;\nimport static org.mockito.Mockito.inOrder;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.verifyNoMoreInteractions;\n\nimport java.util.List;\n\nimport org.junit.Test;\nimport org.mockito.InOrder;\nimport org.mockito.Mock;\nimport org.mockito.exceptions.base.MockitoException;\nimport org.mockito.exceptions.verification.MoreThanAllowedActualInvocations;\nimport org.mockito.exceptions.verification.NoInteractionsWanted;\nimport org.mockitoutil.TestBase;\n\npublic class AtMostXVerificationTest extends TestBase {\n\n @Mock private List mock;\n\n @Test\n public void shouldVerifyAtMostXTimes() throws Exception {\n mock.clear();\n mock.clear();\n\n verify(mock, atMost(2)).clear();\n verify(mock, atMost(3)).clear();\n\n try {\n verify(mock, atMostOnce()).clear();\n fail();\n } catch (MoreThanAllowedActualInvocations e) {\n }\n }\n\n @Test\n public void shouldWorkWithArgumentMatchers() throws Exception {\n mock.add(\"one\");\n verify(mock, atMost(5)).add(anyString());\n\n try {\n verify(mock, atMost(0)).add(anyString());\n fail();\n } catch (MoreThanAllowedActualInvocations e) {\n }\n }\n\n @Test\n public void shouldNotAllowNegativeNumber() throws Exception {\n try {\n verify(mock, atMost(-1)).clear();\n fail();\n } catch (MockitoException e) {\n assertEquals(\"Negative value is not allowed here\", e.getMessage());\n }\n }\n\n @Test\n public void shouldPrintDecentMessage() throws Exception {\n mock.clear();\n mock.clear();\n\n try {\n verify(mock, atMostOnce()).clear();\n fail();\n } catch (MoreThanAllowedActualInvocations e) {\n assertEquals(\"\\nWanted at most 1 time but was 2\", e.getMessage());\n }\n }\n\n @Test\n public void shouldNotAllowInOrderMode() throws Exception {\n mock.clear();\n InOrder inOrder = inOrder(mock);\n\n try {\n inOrder.verify(mock, atMostOnce()).clear();\n fail();\n } catch (MockitoException e) {\n assertEquals(\"AtMost is not implemented to work with InOrder\", e.getMessage());\n }\n }\n\n @Test\n public void shouldMarkInteractionsAsVerified() throws Exception {\n mock.clear();\n mock.clear();\n\n verify(mock, atMost(3)).clear();\n verifyNoMoreInteractions(mock);\n }\n\n @Test\n public void shouldDetectUnverifiedInMarkInteractionsAsVerified() throws Exception {\n mock.clear();\n mock.clear();\n undesiredInteraction();\n\n verify(mock, atMost(3)).clear();\n try {\n verifyNoMoreInteractions(mock);\n fail();\n } catch (NoInteractionsWanted e) {\n assertThat(e).hasMessageContaining(\"undesiredInteraction(\");\n }\n }\n\n private void undesiredInteraction() {\n mock.add(\"\");\n }\n}\n"},"repo_name":{"kind":"string","value":"ze-pequeno/mockito"},"path":{"kind":"string","value":"src/test/java/org/mockitousage/verification/AtMostXVerificationTest.java"},"language":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":3400,"string":"3,400"}}},{"rowIdx":2899,"cells":{"code":{"kind":"string","value":"db);\n$model->addCondition($model->fieldName()->name, '=', 'Mustard');\n\n// use default.\n$app->getExecutorFactory()->useTriggerDefault(ExecutorFactory::TABLE_BUTTON);\n\n$edit = $model->getUserAction('edit');\n$edit->callback = function (Product $model) {\n return $model->product_category_id->getTitle() . ' - ' . $model->product_sub_category_id->getTitle();\n};\n\n$crud = Crud::addTo($app);\n$crud->setModel($model, [$model->fieldName()->name]);\n"},"repo_name":{"kind":"string","value":"atk4/ui"},"path":{"kind":"string","value":"demos/_unit-test/lookup.php"},"language":{"kind":"string","value":"PHP"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":709,"string":"709"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":28,"numItemsPerPage":100,"numTotalItems":115086922,"offset":2800,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1ODIzNDYxNCwic3ViIjoiL2RhdGFzZXRzL2xvdWJuYWJubC9naXRodWItY29kZS1kdXBsaWNhdGUiLCJleHAiOjE3NTgyMzgyMTQsImlzcyI6Imh0dHBzOi8vaHVnZ2luZ2ZhY2UuY28ifQ.cNK_d72VX9bC4-RnJ67xTnAmX_zImHgQ3ClwWaZ4cM9plJa0pJBsdqhN0mirkB-vXdf-AQYSoq4InJsFnJmMCA","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
    code
    stringlengths
    3
    1.05M
    repo_name
    stringlengths
    4
    116
    path
    stringlengths
    3
    942
    language
    stringclasses
    30 values
    license
    stringclasses
    15 values
    size
    int32
    3
    1.05M
    import { Component, OnInit } from '@angular/core'; // import { TreeModule, TreeNode } from "primeng/primeng"; import { BlogPostService } from '../shared/blog-post.service'; import { BlogPostDetails } from '../shared/blog-post.model'; @Component({ selector: 'ejc-blog-archive', templateUrl: './blog-archive.component.html', styleUrls: ['./blog-archive.component.scss'] }) export class BlogArchiveComponent implements OnInit { constructor( // private postService: BlogPostService ) { } ngOnInit() { } // // it would be best if the data in the blog post details file was already organized into tree nodes // private buildTreeNodes(): TreeNode[] {} }
    ejchristie/ejchristie.github.io
    src/app/blog/blog-archive/blog-archive.component.ts
    TypeScript
    mit
    676
    require 'active_record' module ActiveRecord class Migration def migrate_with_multidb(direction) if defined? self.class::DATABASE_NAME ActiveRecord::Base.establish_connection(self.class::DATABASE_NAME.to_sym) migrate_without_multidb(direction) ActiveRecord::Base.establish_connection(Rails.env.to_sym) else migrate_without_multidb(direction) end end alias_method_chain :migrate, :multidb end end
    sinsoku/banana
    lib/banana/migration.rb
    Ruby
    mit
    462
    const os = require("os"); const fs = require("fs"); const config = { } let libs; switch (os.platform()) { case "darwin": { libs = [ "out/Debug_x64/libpvpkcs11.dylib", "out/Debug/libpvpkcs11.dylib", "out/Release_x64/libpvpkcs11.dylib", "out/Release/libpvpkcs11.dylib", ]; break; } case "win32": { libs = [ "out/Debug_x64/pvpkcs11.dll", "out/Debug/pvpkcs11.dll", "out/Release_x64/pvpkcs11.dll", "out/Release/pvpkcs11.dll", ]; break; } default: throw new Error("Cannot get pvpkcs11 compiled library. Unsupported OS"); } config.lib = libs.find(o => fs.existsSync(o)); if (!config.lib) { throw new Error("config.lib is empty"); } module.exports = config;
    PeculiarVentures/pvpkcs11
    test/config.js
    JavaScript
    mit
    742
    class RenameMembers < ActiveRecord::Migration[5.1] def change rename_table :members, :memberships end end
    miljinx/helpdo-api
    db/migrate/20170613234831_rename_members.rb
    Ruby
    mit
    114
    using System; using Xunit; using System.Linq; using hihapi.Models; using hihapi.Controllers; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.OData.Results; using hihapi.test.common; namespace hihapi.unittest.Finance { [Collection("HIHAPI_UnitTests#1")] public class FinanceDocumentTypesControllerTest { private SqliteDatabaseFixture fixture = null; public FinanceDocumentTypesControllerTest(SqliteDatabaseFixture fixture) { this.fixture = fixture; } [Theory] [InlineData("")] [InlineData(DataSetupUtility.UserA)] public async Task TestCase_Read(string strusr) { var context = fixture.GetCurrentDataContext(); // 1. Read it without User assignment var control = new FinanceDocumentTypesController(context); if (String.IsNullOrEmpty(strusr)) { var userclaim = DataSetupUtility.GetClaimForUser(strusr); control.ControllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext() { User = userclaim } }; } var getresult = control.Get(); Assert.NotNull(getresult); var getokresult = Assert.IsType<OkObjectResult>(getresult); var getqueryresult = Assert.IsAssignableFrom<IQueryable<FinanceDocumentType>>(getokresult.Value); Assert.NotNull(getqueryresult); if (String.IsNullOrEmpty(strusr)) { var dbcategories = (from tt in context.FinDocumentTypes where tt.HomeID == null select tt).ToList<FinanceDocumentType>(); Assert.Equal(dbcategories.Count, getqueryresult.Count()); } await context.DisposeAsync(); } [Theory] [InlineData(DataSetupUtility.UserA, DataSetupUtility.Home1ID, "Test 1")] [InlineData(DataSetupUtility.UserB, DataSetupUtility.Home2ID, "Test 2")] public async Task TestCase_CRUD(string currentUser, int hid, string name) { var context = fixture.GetCurrentDataContext(); // 1. Read it out before insert. var control = new FinanceDocumentTypesController(context); var userclaim = DataSetupUtility.GetClaimForUser(currentUser); control.ControllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext() { User = userclaim } }; var getresult = control.Get(); Assert.NotNull(getresult); var getokresult = Assert.IsType<OkObjectResult>(getresult); var getqueryresult = Assert.IsAssignableFrom<IQueryable<FinanceDocumentType>>(getokresult.Value); Assert.NotNull(getqueryresult); // 2. Insert a new one. FinanceDocumentType ctgy = new FinanceDocumentType(); ctgy.HomeID = hid; ctgy.Name = name; ctgy.Comment = name; var postresult = await control.Post(ctgy); var createdResult = Assert.IsType<CreatedODataResult<FinanceDocumentType>>(postresult); Assert.NotNull(createdResult); short nctgyid = createdResult.Entity.ID; Assert.Equal(hid, createdResult.Entity.HomeID); Assert.Equal(ctgy.Name, createdResult.Entity.Name); Assert.Equal(ctgy.Comment, createdResult.Entity.Comment); // 3. Read it out var getsingleresult = control.Get(nctgyid); Assert.NotNull(getsingleresult); var getctgy = Assert.IsType<FinanceDocumentType>(getsingleresult); Assert.Equal(hid, getctgy.HomeID); Assert.Equal(ctgy.Name, getctgy.Name); Assert.Equal(ctgy.Comment, getctgy.Comment); // 4. Change it getctgy.Comment += "Changed"; var putresult = control.Put(nctgyid, getctgy); Assert.NotNull(putresult); // 5. Delete it var deleteresult = control.Delete(nctgyid); Assert.NotNull(deleteresult); await context.DisposeAsync(); } } }
    alvachien/achihapi
    test/hihapi.test/UnitTests/Finance/Config/FinanceDocumentTypesControllerTest.cs
    C#
    mit
    4,350
    <?php # MantisBT - a php based bugtracking system # MantisBT is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # MantisBT is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with MantisBT. If not, see <http://www.gnu.org/licenses/>. /** * @package MantisBT * @copyright Copyright (C) 2000 - 2002 Kenzaburo Ito - [email protected] * @copyright Copyright (C) 2002 - 2011 MantisBT Team - [email protected] * @link http://www.mantisbt.org */ /** * MantisBT Core API's */ require_once( 'core.php' ); require_once( 'email_api.php' ); form_security_validate( 'signup' ); $f_username = strip_tags( gpc_get_string( 'username' ) ); $f_email = strip_tags( gpc_get_string( 'email' ) ); $f_captcha = gpc_get_string( 'captcha', '' ); $f_public_key = gpc_get_int( 'public_key', '' ); $f_username = trim( $f_username ); $f_email = email_append_domain( trim( $f_email ) ); $f_captcha = utf8_strtolower( trim( $f_captcha ) ); # force logout on the current user if already authenticated if( auth_is_user_authenticated() ) { auth_logout(); } # Check to see if signup is allowed if ( OFF == config_get_global( 'allow_signup' ) ) { print_header_redirect( 'login_page.php' ); exit; } if( ON == config_get( 'signup_use_captcha' ) && get_gd_version() > 0 && helper_call_custom_function( 'auth_can_change_password', array() ) ) { # captcha image requires GD library and related option to ON $t_key = utf8_strtolower( utf8_substr( md5( config_get( 'password_confirm_hash_magic_string' ) . $f_public_key ), 1, 5) ); if ( $t_key != $f_captcha ) { trigger_error( ERROR_SIGNUP_NOT_MATCHING_CAPTCHA, ERROR ); } } email_ensure_not_disposable( $f_email ); # notify the selected group a new user has signed-up if( user_signup( $f_username, $f_email ) ) { email_notify_new_account( $f_username, $f_email ); } form_security_purge( 'signup' ); html_page_top1(); html_page_top2a(); ?> <br /> <div align="center"> <table class="width50" cellspacing="1"> <tr> <td class="center"> <b><?php echo lang_get( 'signup_done_title' ) ?></b><br /> <?php echo "[$f_username - $f_email] " ?> </td> </tr> <tr> <td> <br /> <?php echo lang_get( 'password_emailed_msg' ) ?> <br /><br /> <?php echo lang_get( 'no_reponse_msg') ?> <br /><br /> </td> </tr> </table> <br /> <?php print_bracket_link( 'login_page.php', lang_get( 'proceed' ) ); ?> </div> <?php html_page_bottom1a( __FILE__ );
    eazulay/mantis
    signup.php
    PHP
    mit
    2,896
    team_mapping = { "SY": "Sydney", "WB": "Western Bulldogs", "WC": "West Coast", "HW": "Hawthorn", "GE": "Geelong", "FR": "Fremantle", "RI": "Richmond", "CW": "Collingwood", "CA": "Carlton", "GW": "Greater Western Sydney", "AD": "Adelaide", "GC": "Gold Coast", "ES": "Essendon", "ME": "Melbourne", "NM": "North Melbourne", "PA": "Port Adelaide", "BL": "Brisbane Lions", "SK": "St Kilda" } def get_team_name(code): return team_mapping[code] def get_team_code(full_name): for code, name in team_mapping.items(): if name == full_name: return code return full_name def get_match_description(response): match_container = response.xpath("//td[@colspan = '5' and @align = 'center']")[0] match_details = match_container.xpath(".//text()").extract() return { "round": match_details[1], "venue": match_details[3], "date": match_details[6], "attendance": match_details[8], "homeTeam": response.xpath("(//a[contains(@href, 'teams/')])[1]/text()").extract_first(), "awayTeam": response.xpath("(//a[contains(@href, 'teams/')])[2]/text()").extract_first(), "homeScore": int(response.xpath("//table[1]/tr[2]/td[5]/b/text()").extract_first()), "awayScore": int(response.xpath("//table[1]/tr[3]/td[5]/b/text()").extract_first()) } def get_match_urls(response): for match in response.xpath("//a[contains(@href, 'stats/games/')]/@href").extract(): yield response.urljoin(match)
    bairdj/beveridge
    src/scrapy/afltables/afltables/common.py
    Python
    mit
    1,563
    from keras.applications import imagenet_utils from keras.applications import mobilenet def dummyPreprocessInput(image): image -= 127.5 return image def getPreprocessFunction(preprocessType): if preprocessType == "dummy": return dummyPreprocessInput elif preprocessType == "mobilenet": return mobilenet.preprocess_input elif preprocessType == "imagenet": return imagenet_utils.preprocess_input else: raise Exception(preprocessType + " not supported")
    SlipknotTN/Dogs-Vs-Cats-Playground
    deep_learning/keras/lib/preprocess/preprocess.py
    Python
    mit
    511
    // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace TheS.Runtime { internal class CallbackException : FatalException { public CallbackException() { } public CallbackException(string message, Exception innerException) : base(message, innerException) { // This can't throw something like ArgumentException because that would be worse than // throwing the callback exception that was requested. Fx.Assert(innerException != null, "CallbackException requires an inner exception."); Fx.Assert(!Fx.IsFatal(innerException), "CallbackException can't be used to wrap fatal exceptions."); } } }
    teerachail/SoapWithAttachments
    JavaWsBinding/TheS.ServiceModel/_Runtime/CallbackException.cs
    C#
    mit
    874
    <?php namespace App\Http\Controllers; use App\Jobs\GetInstance; use App\Models\Build; use App\Models\Commit; use App\Models\Repository; use App\RepositoryProviders\GitHub; use Illuminate\Support\Facades\DB; class DashboardController extends Controller { public function index() { $repositories = Repository::all(); $commits = Commit::select('branch', DB::raw('max(created_at) as created_at')) ->orderBy('created_at', 'desc') ->groupBy('branch') ->get(); $masterInfo = Commit::getBranchInfo('master'); $branches = []; foreach ($commits as $commit) { $info = Commit::getBranchInfo($commit->branch); $branches[] = [ 'branch' => $commit->branch, 'status' => $info['status'], 'label' => $info['label'], 'last_commit_id' => $info['last_commit_id'], ]; } return view('dashboard', compact('repositories', 'branches', 'masterInfo')); } public function build(Commit $commit, $attempt = null) { $count = Build::where(['commit_id' => $commit->id])->count(); $query = Build::where(['commit_id' => $commit->id]) ->orderBy('attempt', 'desc'); if ($attempt) { $query->where(['attempt' => $attempt]); } $build = $query->first(); $logs = json_decode($build->log, true); $next = $build->attempt < $count ? "/build/$build->id/" . ($build->attempt + 1) : null; return view('build', compact('build', 'commit', 'attempt', 'logs', 'count', 'next')); } public function rebuild(Build $build) { $rebuild = new Build(); $rebuild->commit_id = $build->commit_id; $rebuild->attempt = $build->attempt + 1; $rebuild->status = 'QUEUED'; $rebuild->save(); $github = new GitHub( $rebuild->commit->repository->name, $rebuild->commit->commit_id, env('PROJECT_URL') . '/build/' . $rebuild->commit_id ); $github->notifyPendingBuild(); dispatch(new GetInstance($rebuild->id)); return redirect("/build/$rebuild->commit_id"); } }
    michaelst/ci
    app/Http/Controllers/DashboardController.php
    PHP
    mit
    2,283
    #pragma once /** * Copyright (c) blueback * Released under the MIT License * https://github.com/bluebackblue/brownie/blob/master/LICENSE.txt * http://bbbproject.sakura.ne.jp/wordpress/mitlicense * @brief OpenGL。 */ /** include */ #pragma warning(push) #pragma warning(disable:4464) #include "../types/types.h" #pragma warning(pop) /** include */ #pragma warning(push) #pragma warning(disable:4464) #include "../actionbatching/actionbatching.h" #pragma warning(pop) /** include */ #include "./opengl_impl.h" #include "./opengl_impl_include.h" /** NBsys::NOpengl */ #if(BSYS_OPENGL_ENABLE) #pragma warning(push) #pragma warning(disable:4710) namespace NBsys{namespace NOpengl { /** バーテックスバッファ作成。 */ class Opengl_Impl_ActionBatching_Shader_Load : public NBsys::NActionBatching::ActionBatching_ActionItem_Base { private: /** opengl_impl */ Opengl_Impl& opengl_impl; /** shaderlayout */ sharedptr<Opengl_ShaderLayout> shaderlayout; /** asyncresult */ AsyncResult<bool> asyncresult; public: /** constructor */ Opengl_Impl_ActionBatching_Shader_Load(Opengl_Impl& a_opengl_impl,const sharedptr<Opengl_ShaderLayout>& a_shaderlayout,AsyncResult<bool>& a_asyncresult) : opengl_impl(a_opengl_impl), shaderlayout(a_shaderlayout), asyncresult(a_asyncresult) { } /** destructor */ virtual ~Opengl_Impl_ActionBatching_Shader_Load() { } private: /** copy constructor禁止。 */ Opengl_Impl_ActionBatching_Shader_Load(const Opengl_Impl_ActionBatching_Shader_Load& a_this) = delete; /** コピー禁止。 */ void operator =(const Opengl_Impl_ActionBatching_Shader_Load& a_this) = delete; public: /** アクション開始。 */ virtual void Start() { } /** アクション中。 */ virtual s32 Do(f32& a_delta,bool a_endrequest) { if(a_endrequest == true){ //中断。 } if(this->shaderlayout->IsBusy() == true){ //継続。 a_delta -= 1.0f; return 0; } //Render_LoadShader this->opengl_impl.Render_LoadShader(this->shaderlayout); //asyncresult this->asyncresult.Set(true); //成功。 return 1; } }; }} #pragma warning(pop) #endif
    bluebackblue/brownie
    source/bsys/opengl/opengl_impl_actionbatching_shader_load.h
    C
    mit
    2,340
    <?php namespace Vich\UploaderBundle\Mapping; use Vich\UploaderBundle\Naming\NamerInterface; /** * PropertyMapping. * * @author Dustin Dobervich <[email protected]> */ class PropertyMapping { /** * @var \ReflectionProperty $property */ protected $property; /** * @var \ReflectionProperty $fileNameProperty */ protected $fileNameProperty; /** * @var NamerInterface $namer */ protected $namer; /** * @var array $mapping */ protected $mapping; /** * @var string $mappingName */ protected $mappingName; /** * Gets the reflection property that represents the * annotated property. * * @return \ReflectionProperty The property. */ public function getProperty() { return $this->property; } /** * Sets the reflection property that represents the annotated * property. * * @param \ReflectionProperty $property The reflection property. */ public function setProperty(\ReflectionProperty $property) { $this->property = $property; $this->property->setAccessible(true); } /** * Gets the reflection property that represents the property * which holds the file name for the mapping. * * @return \ReflectionProperty The reflection property. */ public function getFileNameProperty() { return $this->fileNameProperty; } /** * Sets the reflection property that represents the property * which holds the file name for the mapping. * * @param \ReflectionProperty $fileNameProperty The reflection property. */ public function setFileNameProperty(\ReflectionProperty $fileNameProperty) { $this->fileNameProperty = $fileNameProperty; $this->fileNameProperty->setAccessible(true); } /** * Gets the configured namer. * * @return null|NamerInterface The namer. */ public function getNamer() { return $this->namer; } /** * Sets the namer. * * @param \Vich\UploaderBundle\Naming\NamerInterface $namer The namer. */ public function setNamer(NamerInterface $namer) { $this->namer = $namer; } /** * Determines if the mapping has a custom namer configured. * * @return bool True if has namer, false otherwise. */ public function hasNamer() { return null !== $this->namer; } /** * Sets the configured configuration mapping. * * @param array $mapping The mapping; */ public function setMapping(array $mapping) { $this->mapping = $mapping; } /** * Gets the configured configuration mapping name. * * @return string The mapping name. */ public function getMappingName() { return $this->mappingName; } /** * Sets the configured configuration mapping name. * * @param $mappingName The mapping name. */ public function setMappingName($mappingName) { $this->mappingName = $mappingName; } /** * Gets the name of the annotated property. * * @return string The name. */ public function getPropertyName() { return $this->property->getName(); } /** * Gets the value of the annotated property. * * @param object $obj The object. * @return UploadedFile The file. */ public function getPropertyValue($obj) { return $this->property->getValue($obj); } /** * Gets the configured file name property name. * * @return string The name. */ public function getFileNamePropertyName() { return $this->fileNameProperty->getName(); } /** * Gets the configured upload directory. * * @return string The configured upload directory. */ public function getUploadDir() { return $this->mapping['upload_dir']; } /** * Determines if the file should be deleted upon removal of the * entity. * * @return bool True if delete on remove, false otherwise. */ public function getDeleteOnRemove() { return $this->mapping['delete_on_remove']; } /** * Determines if the uploadable field should be injected with a * Symfony\Component\HttpFoundation\File\File instance when * the object is loaded from the datastore. * * @return bool True if the field should be injected, false otherwise. */ public function getInjectOnLoad() { return $this->mapping['inject_on_load']; } }
    marius1092/test
    vendor/bundles/Vich/UploaderBundle/Mapping/PropertyMapping.php
    PHP
    mit
    4,671
    ------------------------------------------------------------------- -- The Long night -- The night gives me black eyes, but I use it to find the light. -- In 2017 -- 公共状态 ------------------------------------------------------------------- L_StatePublic = {} setmetatable(L_StatePublic, {__index = _G}) local _this = L_StatePublic _this.stateNone = function (o , eNtity) local state = L_State.New(o , eNtity) function state:Enter() print("------进入None状态------") end function state:Execute(nTime) --do thing end function state:Exit() print("------退出None状态------") end return state end _this.stateLoad = function (o , eNtity) local state = L_State.New(o , eNtity) function state:Enter() print("------进入Load状态------") self.m_nTimer = 0 self.m_nTick = 0 end function state:Execute(nTime) --do thing if 0 == self.m_nTick then self.m_nTimer = self.m_nTimer + nTime print(self.m_nTimer) if self.m_nTimer > 3 then self.m_eNtity:ChangeToState(self.m_eNtity.stateNone) end end end function state:Exit() print("------退出Load状态------") end return state end _this.stateExit = function (o , eNtity) local state = L_State.New(o , eNtity) function state:Enter() print("------进入Exit状态------") self.m_nTimer = 0 self.m_nTick = 0 end function state:Execute(nTime) --do thing if 0 == self.m_nTick then self.m_nTimer = self.m_nTimer + nTime print(self.m_nTimer) if self.m_nTimer > 3 then self.m_eNtity:ChangeToState(self.m_eNtity.stateNone) end end end function state:Exit() print("------退出Exit状态------") end return state end
    cheney247689848/Cloud-edge
    Assets/Script_Lua/scene/L_StatePublic.lua
    Lua
    mit
    2,033
    <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>18 --> 19</title> <link href="./../../assets/style.css" rel="stylesheet"> </head> <body> <h2>You have to be fast</h2> <a href="./ed6c3fe87a92e6b0939903db98d3209d32dcf2e96bee3586c1c6da3985c58ae4.html">Teleport</a> <hr> <a href="./../../about.md">About</a> (Spoilers! ) <script src="./../../assets/md5.js"></script> <script> window.currentLevel = 7; </script> <script src="./../../assets/script.js"></script> </body> </html>
    simonmysun/praxis
    TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/287e3522261d64438d0e0f0d0ab25b1bbc0d4b902207719bf1a7761ee019b24a.html
    HTML
    mit
    550
    personalprojects ================ A bunch of little things I made in my freetime ### PyPong A simple pong game made in Python and Pygame. **Changes Made**: Made the AI a bit (a lot) worse, you can actually win now. ### Maze Runner A maze app that uses Deep Field Search (DFS) to make a perfect maze and then uses the same algorithm in reverse to solve. Requires PyGame. **Usage**: Run it, enter your resolution, and let it run! Press "Escape" at anytime to quit. **Changes Made**: Exits more elegantly, colors are more visible. ### Find the Cow A joke of a game inspired by a conversation at dinner with friends. I challenged myself to keep it under 100 lines of code. Requires PyGame. **Usage**: Click to guess where the cow is. The volume of the "moo" indicates how far away the cow is. Once the cow is found, press spacebar to go to the next level. **ToDo**: Add a menu, although, I want to keep this under 100 lines of code. ### Binary Clock Something I thought I would finish, but never had the initative. It was supposed to be a simple 5 row binary clock. Maybe someday it will get a life.
    tanishq-dubey/personalprojects
    README.md
    Markdown
    mit
    1,102
    // Copyright (c) 2020 The Firo Core Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef FIRO_ELYSIUM_SIGMAWALLETV0_H #define FIRO_ELYSIUM_SIGMAWALLETV0_H #include "sigmawallet.h" namespace elysium { class SigmaWalletV0 : public SigmaWallet { public: SigmaWalletV0(); protected: uint32_t BIP44ChangeIndex() const; SigmaPrivateKey GeneratePrivateKey(uint512 const &seed); class Database : public SigmaWallet::Database { public: Database(); public: bool WriteMint(SigmaMintId const &id, SigmaMint const &mint, CWalletDB *db = nullptr); bool ReadMint(SigmaMintId const &id, SigmaMint &mint, CWalletDB *db = nullptr) const; bool EraseMint(SigmaMintId const &id, CWalletDB *db = nullptr); bool HasMint(SigmaMintId const &id, CWalletDB *db = nullptr) const; bool WriteMintId(uint160 const &hash, SigmaMintId const &mintId, CWalletDB *db = nullptr); bool ReadMintId(uint160 const &hash, SigmaMintId &mintId, CWalletDB *db = nullptr) const; bool EraseMintId(uint160 const &hash, CWalletDB *db = nullptr); bool HasMintId(uint160 const &hash, CWalletDB *db = nullptr) const; bool WriteMintPool(std::vector<MintPoolEntry> const &mints, CWalletDB *db = nullptr); bool ReadMintPool(std::vector<MintPoolEntry> &mints, CWalletDB *db = nullptr); void ListMints(std::function<void(SigmaMintId&, SigmaMint&)> const&, CWalletDB *db = nullptr); }; public: using SigmaWallet::GeneratePrivateKey; }; } #endif // FIRO_ELYSIUM_SIGMAWALLETV0_H
    zcoinofficial/zcoin
    src/elysium/sigmawalletv0.h
    C
    mit
    1,664
    # Gears # *Documentation may be outdated or incomplete as some URLs may no longer exist.* *Warning! This codebase is deprecated and will no longer receive support; excluding critical issues.* A PHP class that loads template files, binds variables to a single file or globally without the need for custom placeholders/variables, allows for parent-child hierarchy and parses the template structure. Gear is a play on words for: Engine + Gears + Structure. * Loads any type of file into the system * Binds variables to a single file or to all files globally * Template files DO NOT need custom markup and placeholders for variables * Can access and use variables in a template just as you would a PHP file * Allows for parent-child hierarchy * Parse a parent template to parse all children, and their children, and so on * Can destroy template indexes on the fly * No eval() or security flaws * And much more... ## Introduction ## Most of the template systems today use a very robust setup where the template files contain no server-side code. Instead they use a system where they use custom variables and markup to get the job done. For example, in your template you may have a variable called {pageTitle} and in your code you assign that variable a value of "Welcome". This is all well and good, but to be able to parse this "system", it requires loads of regex and matching/replacing/looping which can be quite slow and cumbersome. It also requires you to learn a new markup language, specific for the system you are using. Why would you want to learn a new markup language and structure simply to do an if statement or go through a loop? In Gears, the goal is to remove all that custom code, separate your markup from your code, allow the use of standard PHP functions, loops, statements, etc within templates, and much more! ## Installation ## Install by manually downloading the library or defining a [Composer dependency](http://getcomposer.org/). ```javascript { "require": { "mjohnson/gears": "4.0.0" } } ``` Once available, instantiate the class and create template files. ```php // index.php $temp = new mjohnson\gears\Gears(dirname(__FILE__) . 'templates/'); $temp->setLayout('layouts/default'); // templates/layouts/default.tpl <!DOCTYPE html> <html> <head> <title><?php echo $pageTitle; ?></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <?php echo $this->getContent(); ?> </body> </html> ``` Within the code block above I am initiating the class by calling `new mjohnson\gears\Gears($path)` (where `$path` is the path to your templates directory) and storing it within a `$temp` variable. Next I am setting the layout I want to use; a layout is the outer HTML that will wrap the inner content pages. Within a layout you can use `getContent()` which will output the inner HTML wherever you please. ## Binding Variables ## It's now time to bind data to variables within your templates; to do this we use the `bind()` method. The bind method will take an array of key value pairs, or key value arguments. ```php $temp->bind(array( 'pageTitle' => 'Gears - Template Engine', 'description' => 'A PHP class that loads template files, binds variables, allows for parent-child hierarchy all the while rendering the template structure.' )); ``` The way binding variables works is extremely easy to understand. In the data being binded, the key is the name of the variable within the template, and the value is what the variable will be output. For instance the variable pageTitle (Gears - Template Engine) above will be assigned to the variable `$pageTitle` within the `layouts/default.tpl`. Variables are binded globally to all templates, includes and the layout. ## Displaying the Templates ## To render templates, use the `display()` method. The display method takes two arguments, the name of the template you want to display and the key to use for caching. ```php echo $temp->display('index'); ``` The second argument defines the name of the key to use for caching. Generally it will be the same name as the template name, but you do have the option to name it whatever you please. ```php echo $temp->display('index', 'index'); ``` It's also possible to display templates within folders by separating the path with a forward slash. ```php echo $temp->display('users/login'); ``` ## Opening a Template ## To render a template within another template you would use the `open()` method. The `open()` method takes 3 arguments: the path to the template (relative to the templates folder), an array of key value pairs to define as custom scoped variables and an array of cache settings. ```php echo $this->open('includes/footer', array('date' => date('Y')); ``` By default, includes are not cached but you can enable caching by passing true as the third argument or an array of settings. The viable settings are key and duration, where key is the name of the cached file (usually the path) and duration is the length of the cache. ```php echo $this->open('includes/footer', array('date' => date('Y')), true); // Custom settings echo $this->open('includes/footer', array('date' => date('Y')), array( 'key' => 'cacheKey', 'duration' => '+10 minutes' )); ``` ## Caching ## Gears comes packaged with a basic caching mechanism. By default caching is disabled, but to enable caching you can use `setCaching()`. This method will take the cache location as its 1st argument (best to place it in the same templates folder) and the expiration duration as the 2nd argument (default +1 day). ```php $temp->setCaching(dirname(__FILE__) . '/templates/cache/'); ``` You can customize the duration by using the strtotime() format. You can also pass null as the first argument and the system will place the cache files within your template path. ```php $temp->setCaching(null, '+15 minutes'); ``` To clear all cached files, you can use `flush()`. ```php $temp->flush(); ``` For a better example of how to output cached data, refer to the tests folder within the Gears package.
    milesj/gears
    docs/usage.md
    Markdown
    mit
    6,088
    /* * @Author: justinwebb * @Date: 2015-09-24 21:08:23 * @Last Modified by: justinwebb * @Last Modified time: 2015-09-24 22:19:45 */ (function (window) { 'use strict'; window.JWLB = window.JWLB || {}; window.JWLB.View = window.JWLB.View || {}; //-------------------------------------------------------------------- // Event handling //-------------------------------------------------------------------- var wallOnClick = function (event) { if (event.target.tagName.toLowerCase() === 'img') { var id = event.target.parentNode.dataset.id; var selectedPhoto = this.photos.filter(function (photo) { if (photo.id === id) { photo.portrait.id = id; return photo; } })[0]; this.sendEvent('gallery', selectedPhoto.portrait); } }; //-------------------------------------------------------------------- // View overrides //-------------------------------------------------------------------- var addUIListeners = function () { this.ui.wall.addEventListener('click', wallOnClick.bind(this)); }; var initUI = function () { var isUIValid = false; var comp = document.querySelector(this.selector); this.ui.wall = comp; if (this.ui.wall) { this.reset(); isUIValid = true; } return isUIValid; }; //-------------------------------------------------------------------- // Constructor //-------------------------------------------------------------------- var Gallery = function (domId) { // Overriden View class methods this.initUI = initUI; this.addUIListeners = addUIListeners; this.name = 'Gallery'; // Instance properties this.photos = []; // Initialize View JWLB.View.call(this, domId); }; //-------------------------------------------------------------------- // Inheritance //-------------------------------------------------------------------- Gallery.prototype = Object.create(JWLB.View.prototype); Gallery.prototype.constructor = Gallery; //-------------------------------------------------------------------- // Instance methods //-------------------------------------------------------------------- Gallery.prototype.addThumb = function (data, id) { // Store image data for future reference var photo = { id: id, thumb: null, portrait: data.size[0] }; data.size.forEach(function (elem) { if (elem.label === 'Square') { photo.thumb = elem; } if (elem.height > photo.portrait.height) { photo.portrait = elem; } }); this.photos.push(photo); // Build thumbnail UI var node = document.createElement('div'); node.setAttribute('data-id', id); node.setAttribute('class', 'thumb'); var img = document.createElement('img'); img.setAttribute('src', photo.thumb.source); img.setAttribute('title', 'id: '+ id); node.appendChild(img); this.ui.wall.querySelector('article[name=foobar]').appendChild(node); }; Gallery.prototype.reset = function () { if (this.ui.wall.children.length > 0) { var article = this.ui.wall.children.item(0) article.parentElement.removeChild(article); } var article = document.createElement('article'); article.setAttribute('name', 'foobar'); this.ui.wall.appendChild(article); }; window.JWLB.View.Gallery = Gallery; })(window);
    JustinWebb/lightbox-demo
    app/js/helpers/view/gallery.js
    JavaScript
    mit
    3,410
    module InfinityTest module Core class Base # Specify the Ruby Version Manager to run cattr_accessor :strategy # ==== Options # * :rvm # * :rbenv # * :ruby_normal (Use when don't pass any rubies to run) # * :auto_discover(defaults) self.strategy = :auto_discover # Specify Ruby version(s) to test against # # ==== Examples # rubies = %w(ree jruby) # cattr_accessor :rubies self.rubies = [] # Options to include in the command. # cattr_accessor :specific_options self.specific_options = '' # Test Framework to use Rspec, Bacon, Test::Unit or AutoDiscover(defaults) # ==== Options # * :rspec # * :bacon # * :test_unit (Test unit here apply to this two libs: test/unit and minitest) # * :auto_discover(defaults) # # This will load a exactly a class constantize by name. # cattr_accessor :test_framework self.test_framework = :auto_discover # Framework to know the folders and files that need to monitoring by the observer. # # ==== Options # * :rails # * :rubygems # * :auto_discover(defaults) # # This will load a exactly a class constantize by name. # cattr_accessor :framework self.framework = :auto_discover # Framework to observer watch the dirs. # # ==== Options # * watchr # cattr_accessor :observer self.observer = :watchr # Ignore test files. # # ==== Examples # ignore_test_files = [ 'spec/generators/controller_generator_spec.rb' ] # cattr_accessor :ignore_test_files self.ignore_test_files = [] # Ignore test folders. # # ==== Examples # # Imagine that you don't want to run integration specs. # ignore_test_folders = [ 'spec/integration' ] # cattr_accessor :ignore_test_folders self.ignore_test_folders = [] # Verbose Mode. Print commands before executing them. # cattr_accessor :verbose self.verbose = true # Set the notification framework to use with Infinity Test. # # ==== Options # * :growl # * :lib_notify # * :auto_discover(defaults) # # This will load a exactly a class constantize by name. # cattr_writer :notifications self.notifications = :auto_discover # You can set directory to show images matched by the convention names. # => http://github.com/tomas-stefano/infinity_test/tree/master/images/ ) # # Infinity test will work on these names in the notification framework: # # * success (png, gif, jpeg) # * failure (png, gif, jpeg) # * pending (png, gif, jpeg) # cattr_accessor :mode # # => This will show images in the folder: # http://github.com/tomas-stefano/infinity_test/tree/master/images/simpson # self.mode = :simpson # Success Image to show after the tests run. # cattr_accessor :success_image # Pending Image to show after the tests run. # cattr_accessor :pending_image # Failure Image to show after the tests run. # cattr_accessor :failure_image # Use a specific gemset for each ruby. # OBS.: This only will work for RVM strategy. # cattr_accessor :gemset # InfinityTest try to use bundler if Gemfile is present. # Set to false if you don't want use bundler. # cattr_accessor :bundler self.bundler = true # Callbacks accessor to handle before or after all run and for each ruby! cattr_accessor :callbacks self.callbacks = [] # Run the observer to monitor files. # If set to false will just <b>Run tests and exit</b>. # Defaults to true: run tests and monitoring the files. # cattr_accessor :infinity_and_beyond self.infinity_and_beyond = true # The extension files that Infinity Test will search. # You can observe python, erlang, etc files. # cattr_accessor :extension self.extension = :rb # Setup Infinity Test passing the ruby versions and others setting. # <b>See the class accessors for more information.</b> # # ==== Examples # # InfinityTest::Base.setup do |config| # config.strategy = :rbenv # config.rubies = %w(ree jruby rbx 1.9.2) # end # def self.setup yield self end # Receives a object that quacks like InfinityTest::Options and do the merge with self(Base class). # def self.merge!(options) ConfigurationMerge.new(self, options).merge! end def self.start_continuous_test_server continuous_test_server.start end def self.continuous_test_server @continuous_test_server ||= ContinuousTestServer.new(self) end # Just a shortcut to bundler class accessor. # def self.using_bundler? bundler end # Just a shortcut to bundler class accessor. # def self.verbose? verbose end # Callback method to handle before all run and for each ruby too! # # ==== Examples # # before(:all) do # # ... # end # # before(:each_ruby) do |environment| # # ... # end # # before do # if you pass not then will use :all option # # ... # end # def self.before(scope, &block) # setting_callback(Callbacks::BeforeCallback, scope, &block) end # Callback method to handle after all run and for each ruby too! # # ==== Examples # # after(:all) do # # ... # end # # after(:each_ruby) do # # ... # end # # after do # if you pass not then will use :all option # # ... # end # def self.after(scope, &block) # setting_callback(Callbacks::AfterCallback, scope, &block) end # Clear the terminal (Useful in the before callback) # def self.clear_terminal system('clear') end ###### This methods will be removed in the Infinity Test v2.0.1 or 2.0.2 ###### # <b>DEPRECATED:</b> Please use <tt>.notification=</tt> instead. # def self.notifications(notification_name = nil, &block) if notification_name.blank? self.class_variable_get(:@@notifications) else message = <<-MESSAGE .notifications is DEPRECATED. Use this instead: InfinityTest.setup do |config| config.notifications = :growl end MESSAGE ActiveSupport::Deprecation.warn(message) self.notifications = notification_name self.instance_eval(&block) if block_given? end end # <b>DEPRECATED:</b> Please use: # <tt>success_image=</tt> or # <tt>pending_image=</tt> or # <tt>failure_image=</tt> or # <tt>mode=</tt> instead. # def self.show_images(options) message = <<-MESSAGE .show_images is DEPRECATED. Use this instead: InfinityTest.setup do |config| config.success_image = 'some_image.png' config.pending_image = 'some_image.png' config.failure_image = 'some_image.png' config.mode = 'infinity_test_dir_that_contain_images' end MESSAGE ActiveSupport::Deprecation.warn(message) self.success_image = options[:success_image] || options[:sucess_image] if options[:success_image].present? || options[:sucess_image].present? # for fail typo in earlier versions. self.pending_image = options[:pending_image] if options[:pending_image].present? self.failure_image = options[:failure_image] if options[:failure_image].present? self.mode = options[:mode] if options[:mode].present? end # <b>DEPRECATED:</b> Please use: # .rubies = or # .specific_options = or # .test_framework = or # .framework = or # .verbose = or # .gemset = instead # def self.use(options) message = <<-MESSAGE .use is DEPRECATED. Use this instead: InfinityTest.setup do |config| config.rubies = %w(2.0 jruby) config.specific_options = '-J' config.test_framework = :rspec config.framework = :padrino config.verbose = true config.gemset = :some_gemset end MESSAGE ActiveSupport::Deprecation.warn(message) self.rubies = options[:rubies] if options[:rubies].present? self.specific_options = options[:specific_options] if options[:specific_options].present? self.test_framework = options[:test_framework] if options[:test_framework].present? self.framework = options[:app_framework] if options[:app_framework].present? self.verbose = options[:verbose] unless options[:verbose].nil? self.gemset = options[:gemset] if options[:gemset].present? end # <b>DEPRECATED:</b> Please use .clear_terminal instead. # def self.clear(option) message = '.clear(:terminal) is DEPRECATED. Please use .clear_terminal instead.' ActiveSupport::Deprecation.warn(message) clear_terminal end def self.heuristics(&block) # There is a spec pending. end def self.replace_patterns(&block) # There is a spec pending. end private # def self.setting_callback(callback_class, scope, &block) # callback_instance = callback_class.new(scope, &block) # self.callbacks.push(callback_instance) # callback_instance # end end end end
    tomas-stefano/infinity_test
    lib/infinity_test/core/base.rb
    Ruby
    mit
    10,064
    <?php session_start(); require_once('../php/conexion.php'); $conect = connect::conn(); $user = $_SESSION['usuario']; if($_SERVER['REQUEST_METHOD'] == 'POST'){ $sql = "insert into cotidiano (dir_origen,dir_destino,semana,hora,usuario,estado) values (?,?,?,?,?,?);"; $favo = sqlsrv_query($conect,$sql,array($_POST['Dir_o'],$_POST['Dir_d'],$_POST['semana'],$_POST['reloj'],$user['usuario'],1)); if($favo){ echo 'Inserccion correcta'; } else{ if( ($errors = sqlsrv_errors() ) != null) { foreach( $errors as $error ) { echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />"; echo "code: ".$error[ 'code']."<br />"; echo "message: ".$error[ 'message']."<br />"; } } } }else{ print "aqui la estabas cagando"; } ?>
    smukideejeah/GaysonTaxi
    cpanel/nuevoCotidiano.php
    PHP
    mit
    822
    holiwish ========
    aldarondo/holiwish
    README.md
    Markdown
    mit
    18
    python -m unittest
    nrdhm/max_dump
    test.sh
    Shell
    mit
    20
    using System; using NetOffice; using NetOffice.Attributes; namespace NetOffice.MSProjectApi.Enums { /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> ///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff863548(v=office.14).aspx </remarks> [SupportByVersion("MSProject", 11,12,14)] [EntityType(EntityType.IsEnum)] public enum PjMonthLabel { /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>57</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonth_mm = 57, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>86</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonth_mm_yy = 86, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>85</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonth_mm_yyy = 85, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>11</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonth_m = 11, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>10</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonth_mmm = 10, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>8</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonth_mmm_yyy = 8, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>9</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonth_mmmm = 9, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>7</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonth_mmmm_yyyy = 7, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>59</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonthFromEnd_mm = 59, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>58</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonthFromEnd_Mmm = 58, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>45</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonthFromEnd_Month_mm = 45, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>61</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonthFromStart_mm = 61, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>60</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonthFromStart_Mmm = 60, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>44</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonthFromStart_Month_mm = 44, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>35</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelNoDateFormat = 35 } }
    NetOfficeFw/NetOffice
    Source/MSProject/Enums/PjMonthLabel.cs
    C#
    mit
    3,276
    using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CircleAreaAndCircumference")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CircleAreaAndCircumference")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("24a850d9-a2e2-4979-a7f8-47602b439978")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
    frostblooded/TelerikHomework
    C# Part 1/ConsoleInputOutput/CircleAreaAndCircumference/Properties/AssemblyInfo.cs
    C#
    mit
    1,428
    //#define USE_TOUCH_SCRIPT using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; /* * ドラッグ操作でのカメラの移動コントロールクラス * マウス&タッチ対応 */ namespace GarageKit { [RequireComponent(typeof(Camera))] public class FlyThroughCamera : MonoBehaviour { public static bool winTouch = false; public static bool updateEnable = true; // フライスルーのコントロールタイプ public enum FLYTHROUGH_CONTROLL_TYPE { DRAG = 0, DRAG_HOLD } public FLYTHROUGH_CONTROLL_TYPE controllType; // 移動軸の方向 public enum FLYTHROUGH_MOVE_TYPE { XZ = 0, XY } public FLYTHROUGH_MOVE_TYPE moveType; public Collider groundCollider; public Collider limitAreaCollider; public bool useLimitArea = false; public float moveBias = 1.0f; public float moveSmoothTime = 0.1f; public bool dragInvertX = false; public bool dragInvertY = false; public float rotateBias = 1.0f; public float rotateSmoothTime = 0.1f; public bool rotateInvert = false; public OrbitCamera combinationOrbitCamera; private GameObject flyThroughRoot; public GameObject FlyThroughRoot { get{ return flyThroughRoot; } } private GameObject shiftTransformRoot; public Transform ShiftTransform { get{ return shiftTransformRoot.transform; } } private bool inputLock; public bool IsInputLock { get{ return inputLock; } } private object lockObject; private Vector3 defaultPos; private Quaternion defaultRot; private bool isFirstTouch; private Vector3 oldScrTouchPos; private Vector3 dragDelta; private Vector3 velocitySmoothPos; private Vector3 dampDragDelta = Vector3.zero; private Vector3 pushMoveDelta = Vector3.zero; private float velocitySmoothRot; private float dampRotateDelta = 0.0f; private float pushRotateDelta = 0.0f; public Vector3 currentPos { get{ return flyThroughRoot.transform.position; } } public Quaternion currentRot { get{ return flyThroughRoot.transform.rotation; } } void Awake() { } void Start() { // 設定ファイルより入力タイプを取得 if(!ApplicationSetting.Instance.GetBool("UseMouse")) winTouch = true; inputLock = false; // 地面上視点位置に回転ルートを設定する Ray ray = new Ray(this.transform.position, this.transform.forward); RaycastHit hitInfo; if(groundCollider.Raycast(ray, out hitInfo, float.PositiveInfinity)) { flyThroughRoot = new GameObject(this.gameObject.name + " FlyThrough Root"); flyThroughRoot.transform.SetParent(this.gameObject.transform.parent, false); flyThroughRoot.transform.position = hitInfo.point; flyThroughRoot.transform.rotation = Quaternion.identity; shiftTransformRoot = new GameObject(this.gameObject.name + " ShiftTransform Root"); shiftTransformRoot.transform.SetParent(flyThroughRoot.transform, true); shiftTransformRoot.transform.localPosition = Vector3.zero; shiftTransformRoot.transform.localRotation = Quaternion.identity; this.gameObject.transform.SetParent(shiftTransformRoot.transform, true); } else { Debug.LogWarning("FlyThroughCamera :: not set the ground collider !!"); return; } // 初期値を保存 defaultPos = flyThroughRoot.transform.position; defaultRot = flyThroughRoot.transform.rotation; ResetInput(); } void Update() { if(!inputLock && ButtonObjectEvent.PressBtnsTotal == 0) GetInput(); else ResetInput(); UpdateFlyThrough(); UpdateOrbitCombination(); } private void ResetInput() { isFirstTouch = true; oldScrTouchPos = Vector3.zero; dragDelta = Vector3.zero; } private void GetInput() { // for Touch if(Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer) { if(Input.touchCount == 1) { // ドラッグ量を計算 Vector3 currentScrTouchPos = Input.GetTouch(0).position; if(isFirstTouch) { oldScrTouchPos = currentScrTouchPos; isFirstTouch = false; return; } dragDelta = currentScrTouchPos - oldScrTouchPos; if(controllType == FLYTHROUGH_CONTROLL_TYPE.DRAG) oldScrTouchPos = currentScrTouchPos; } else ResetInput(); } #if UNITY_STANDALONE_WIN else if(Application.platform == RuntimePlatform.WindowsPlayer && winTouch) { #if !USE_TOUCH_SCRIPT if(Input.touchCount == 1) { // ドラッグ量を計算 Vector3 currentScrTouchPos = Input.touches[0].position; #else if(TouchScript.TouchManager.Instance.PressedPointersCount == 1) { // ドラッグ量を計算 Vector3 currentScrTouchPos = TouchScript.TouchManager.Instance.PressedPointers[0].Position; #endif if(isFirstTouch) { oldScrTouchPos = currentScrTouchPos; isFirstTouch = false; return; } dragDelta = currentScrTouchPos - oldScrTouchPos; if(controllType == FLYTHROUGH_CONTROLL_TYPE.DRAG) oldScrTouchPos = currentScrTouchPos; } else ResetInput(); } #endif // for Mouse else { if(Input.GetMouseButton(0)) { // ドラッグ量を計算 Vector3 currentScrTouchPos = Input.mousePosition; if(isFirstTouch) { oldScrTouchPos = currentScrTouchPos; isFirstTouch = false; return; } dragDelta = currentScrTouchPos - oldScrTouchPos; if(controllType == FLYTHROUGH_CONTROLL_TYPE.DRAG) oldScrTouchPos = currentScrTouchPos; } else ResetInput(); } } /// <summary> /// Input更新のLock /// </summary> public void LockInput(object sender) { if(!inputLock) { lockObject = sender; inputLock = true; } } /// <summary> /// Input更新のUnLock /// </summary> public void UnlockInput(object sender) { if(inputLock && lockObject == sender) inputLock = false; } /// <summary> /// フライスルーを更新 /// </summary> private void UpdateFlyThrough() { if(!FlyThroughCamera.updateEnable || flyThroughRoot == null) return; // 位置 float dragX = dragDelta.x * (dragInvertX ? -1.0f : 1.0f); float dragY = dragDelta.y * (dragInvertY ? -1.0f : 1.0f); if(moveType == FLYTHROUGH_MOVE_TYPE.XZ) dampDragDelta = Vector3.SmoothDamp(dampDragDelta, new Vector3(dragX, 0.0f, dragY) * moveBias + pushMoveDelta, ref velocitySmoothPos, moveSmoothTime); else if(moveType == FLYTHROUGH_MOVE_TYPE.XY) dampDragDelta = Vector3.SmoothDamp(dampDragDelta, new Vector3(dragX, dragY, 0.0f) * moveBias + pushMoveDelta, ref velocitySmoothPos, moveSmoothTime); flyThroughRoot.transform.Translate(dampDragDelta, Space.Self); pushMoveDelta = Vector3.zero; if(useLimitArea) { // 移動範囲限界を設定 if(limitAreaCollider != null) { Vector3 movingLimitMin = limitAreaCollider.bounds.min + limitAreaCollider.bounds.center - limitAreaCollider.gameObject.transform.position; Vector3 movingLimitMax = limitAreaCollider.bounds.max + limitAreaCollider.bounds.center - limitAreaCollider.gameObject.transform.position; if(moveType == FLYTHROUGH_MOVE_TYPE.XZ) { float limitX = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.x, movingLimitMax.x), movingLimitMin.x); float limitZ = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.z, movingLimitMax.z), movingLimitMin.z); flyThroughRoot.transform.position = new Vector3(limitX, flyThroughRoot.transform.position.y, limitZ); } else if(moveType == FLYTHROUGH_MOVE_TYPE.XY) { float limitX = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.x, movingLimitMax.x), movingLimitMin.x); float limitY = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.y, movingLimitMax.y), movingLimitMin.y); flyThroughRoot.transform.position = new Vector3(limitX, limitY, flyThroughRoot.transform.position.z); } } } // 方向 dampRotateDelta = Mathf.SmoothDamp(dampRotateDelta, pushRotateDelta * rotateBias, ref velocitySmoothRot, rotateSmoothTime); if(moveType == FLYTHROUGH_MOVE_TYPE.XZ) flyThroughRoot.transform.Rotate(Vector3.up, dampRotateDelta, Space.Self); else if(moveType == FLYTHROUGH_MOVE_TYPE.XY) flyThroughRoot.transform.Rotate(Vector3.forward, dampRotateDelta, Space.Self); pushRotateDelta = 0.0f; } private void UpdateOrbitCombination() { // 連携機能 if(combinationOrbitCamera != null && combinationOrbitCamera.OrbitRoot != null) { Vector3 lookPoint = combinationOrbitCamera.OrbitRoot.transform.position; Transform orbitParent = combinationOrbitCamera.OrbitRoot.transform.parent; combinationOrbitCamera.OrbitRoot.transform.parent = null; flyThroughRoot.transform.LookAt(lookPoint, Vector3.up); flyThroughRoot.transform.rotation = Quaternion.Euler( 0.0f, flyThroughRoot.transform.rotation.eulerAngles.y + 180.0f, 0.0f); combinationOrbitCamera.OrbitRoot.transform.parent = orbitParent; } } /// <summary> /// 目標位置にカメラを移動させる /// </summary> public void MoveToFlyThrough(Vector3 targetPosition, float time = 1.0f) { dampDragDelta = Vector3.zero; flyThroughRoot.transform.DOMove(targetPosition, time) .SetEase(Ease.OutCubic) .Play(); } /// <summary> /// 指定値でカメラを移動させる /// </summary> public void TranslateToFlyThrough(Vector3 move) { dampDragDelta = Vector3.zero; flyThroughRoot.transform.Translate(move, Space.Self); } /// <summary> /// 目標方向にカメラを回転させる /// </summary> public void RotateToFlyThrough(float targetAngle, float time = 1.0f) { dampRotateDelta = 0.0f; Vector3 targetEulerAngles = flyThroughRoot.transform.rotation.eulerAngles; targetEulerAngles.y = targetAngle; flyThroughRoot.transform.DORotate(targetEulerAngles, time) .SetEase(Ease.OutCubic) .Play(); } /// <summary> /// 外部トリガーで移動させる /// </summary> public void PushMove(Vector3 move) { pushMoveDelta = move; } /// <summary> /// 外部トリガーでカメラ方向を回転させる /// </summary> public void PushRotate(float rotate) { pushRotateDelta = rotate; } /// <summary> /// フライスルーを初期化 /// </summary> public void ResetFlyThrough() { ResetInput(); MoveToFlyThrough(defaultPos); RotateToFlyThrough(defaultRot.eulerAngles.y); } } }
    sharkattack51/GarageKit_for_Unity
    UnityProject/Assets/__ProjectName__/Scripts/Utils/CameraContorol/FlyThroughCamera.cs
    C#
    mit
    13,347
    "use strict"; const readdir = require("../../"); const dir = require("../utils/dir"); const { expect } = require("chai"); const through2 = require("through2"); const fs = require("fs"); let nodeVersion = parseFloat(process.version.substr(1)); describe("Stream API", () => { it("should be able to pipe to other streams as a Buffer", done => { let allData = []; readdir.stream("test/dir") .pipe(through2((data, enc, next) => { try { // By default, the data is streamed as a Buffer expect(data).to.be.an.instanceOf(Buffer); // Buffer.toString() returns the file name allData.push(data.toString()); next(null, data); } catch (e) { next(e); } })) .on("finish", () => { try { expect(allData).to.have.same.members(dir.shallow.data); done(); } catch (e) { done(e); } }) .on("error", err => { done(err); }); }); it('should be able to pipe to other streams in "object mode"', done => { let allData = []; readdir.stream("test/dir") .pipe(through2({ objectMode: true }, (data, enc, next) => { try { // In "object mode", the data is a string expect(data).to.be.a("string"); allData.push(data); next(null, data); } catch (e) { next(e); } })) .on("finish", () => { try { expect(allData).to.have.same.members(dir.shallow.data); done(); } catch (e) { done(e); } }) .on("error", err => { done(err); }); }); it('should be able to pipe fs.Stats to other streams in "object mode"', done => { let allData = []; readdir.stream("test/dir", { stats: true }) .pipe(through2({ objectMode: true }, (data, enc, next) => { try { // The data is an fs.Stats object expect(data).to.be.an("object"); expect(data).to.be.an.instanceOf(fs.Stats); allData.push(data.path); next(null, data); } catch (e) { next(e); } })) .on("finish", () => { try { expect(allData).to.have.same.members(dir.shallow.data); done(); } catch (e) { done(e); } }) .on("error", done); }); it("should be able to pause & resume the stream", done => { let allData = []; let stream = readdir.stream("test/dir") .on("data", data => { allData.push(data); // The stream should not be paused expect(stream.isPaused()).to.equal(false); if (allData.length === 3) { // Pause for one second stream.pause(); setTimeout(() => { try { // The stream should still be paused expect(stream.isPaused()).to.equal(true); // The array should still only contain 3 items expect(allData).to.have.lengthOf(3); // Read the rest of the stream stream.resume(); } catch (e) { done(e); } }, 1000); } }) .on("end", () => { expect(allData).to.have.same.members(dir.shallow.data); done(); }) .on("error", done); }); it('should be able to use "readable" and "read"', done => { let allData = []; let nullCount = 0; let stream = readdir.stream("test/dir") .on("readable", () => { // Manually read the next chunk of data let data = stream.read(); while (true) { // eslint-disable-line if (data === null) { // The stream is done nullCount++; break; } else { // The data should be a string (the file name) expect(data).to.be.a("string").with.length.of.at.least(1); allData.push(data); data = stream.read(); } } }) .on("end", () => { if (nodeVersion >= 12) { // In Node >= 12, the "readable" event fires twice, // and stream.read() returns null twice expect(nullCount).to.equal(2); } else if (nodeVersion >= 10) { // In Node >= 10, the "readable" event only fires once, // and stream.read() only returns null once expect(nullCount).to.equal(1); } else { // In Node < 10, the "readable" event fires 13 times (once per file), // and stream.read() returns null each time expect(nullCount).to.equal(13); } expect(allData).to.have.same.members(dir.shallow.data); done(); }) .on("error", done); }); it('should be able to subscribe to custom events instead of "data"', done => { let allFiles = []; let allSubdirs = []; let stream = readdir.stream("test/dir"); // Calling "resume" is required, since we're not handling the "data" event stream.resume(); stream .on("file", filename => { expect(filename).to.be.a("string").with.length.of.at.least(1); allFiles.push(filename); }) .on("directory", subdir => { expect(subdir).to.be.a("string").with.length.of.at.least(1); allSubdirs.push(subdir); }) .on("end", () => { expect(allFiles).to.have.same.members(dir.shallow.files); expect(allSubdirs).to.have.same.members(dir.shallow.dirs); done(); }) .on("error", done); }); it('should handle errors that occur in the "data" event listener', done => { testErrorHandling("data", dir.shallow.data, 7, done); }); it('should handle errors that occur in the "file" event listener', done => { testErrorHandling("file", dir.shallow.files, 3, done); }); it('should handle errors that occur in the "directory" event listener', done => { testErrorHandling("directory", dir.shallow.dirs, 2, done); }); it('should handle errors that occur in the "symlink" event listener', done => { testErrorHandling("symlink", dir.shallow.symlinks, 5, done); }); function testErrorHandling (eventName, expected, expectedErrors, done) { let errors = [], data = []; let stream = readdir.stream("test/dir"); // Capture all errors stream.on("error", error => { errors.push(error); }); stream.on(eventName, path => { data.push(path); if (path.indexOf(".txt") >= 0 || path.indexOf("dir-") >= 0) { throw new Error("Epic Fail!!!"); } else { return true; } }); stream.on("end", () => { try { // Make sure the correct number of errors were thrown expect(errors).to.have.lengthOf(expectedErrors); for (let error of errors) { expect(error.message).to.equal("Epic Fail!!!"); } // All of the events should have still been emitted, despite the errors expect(data).to.have.same.members(expected); done(); } catch (e) { done(e); } }); stream.resume(); } });
    BigstickCarpet/readdir-enhanced
    test/specs/stream.spec.js
    JavaScript
    mit
    7,232
    <?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Font; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class PreferredSubfamily extends AbstractTag { protected $Id = 17; protected $Name = 'PreferredSubfamily'; protected $FullName = 'Font::Name'; protected $GroupName = 'Font'; protected $g0 = 'Font'; protected $g1 = 'Font'; protected $g2 = 'Document'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Preferred Subfamily'; }
    romainneutron/PHPExiftool
    lib/PHPExiftool/Driver/Tag/Font/PreferredSubfamily.php
    PHP
    mit
    792
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (10.0.2) on Fri Sep 21 22:00:31 PDT 2018 --> <title>U-Index</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="date" content="2018-09-21"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../jquery/jquery-ui.css" title="Style"> <script type="text/javascript" src="../script.js"></script> <script type="text/javascript" src="../jquery/jszip/dist/jszip.min.js"></script> <script type="text/javascript" src="../jquery/jszip-utils/dist/jszip-utils.min.js"></script> <!--[if IE]> <script type="text/javascript" src="../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script> <![endif]--> <script type="text/javascript" src="../jquery/jquery-1.10.2.js"></script> <script type="text/javascript" src="../jquery/jquery-ui.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="U-Index"; } } catch(err) { } //--> var pathtoroot = "../";loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="fixedNav"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../main/package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li><a href="../main/package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-1.html">Prev Letter</a></li> <li>Next Letter</li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-2.html" target="_top">Frames</a></li> <li><a href="index-2.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <ul class="navListSearch"> <li><label for="search">SEARCH:</label> <input type="text" id="search" value="search" disabled="disabled"> <input type="reset" id="reset" value="reset" disabled="disabled"> </li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> </div> <div class="navPadding">&nbsp;</div> <script type="text/javascript"><!-- $('.navPadding').css('padding-top', $('.fixedNav').css("height")); //--> </script> <div class="contentContainer"><a href="index-1.html">M</a>&nbsp;<a href="index-2.html">U</a>&nbsp;<a name="I:U"> <!-- --> </a> <h2 class="title">U</h2> <dl> <dt><a href="../main/UsingTheGridLayout.html" title="class in main"><span class="typeNameLink">UsingTheGridLayout</span></a> - Class in <a href="../main/package-summary.html">main</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../main/UsingTheGridLayout.html#UsingTheGridLayout--">UsingTheGridLayout()</a></span> - Constructor for class main.<a href="../main/UsingTheGridLayout.html" title="class in main">UsingTheGridLayout</a></dt> <dd>&nbsp;</dd> </dl> <a href="index-1.html">M</a>&nbsp;<a href="index-2.html">U</a>&nbsp;</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../main/package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li><a href="../main/package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-1.html">Prev Letter</a></li> <li>Next Letter</li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-2.html" target="_top">Frames</a></li> <li><a href="index-2.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
    tliang1/Java-Practice
    Practice/Intro-To-Java-8th-Ed-Daniel-Y.-Liang/Chapter-12/Chapter12P03/doc/index-files/index-2.html
    HTML
    mit
    5,390
    /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.synapse.v2019_06_01_preview; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for IntegrationRuntimeState. */ public final class IntegrationRuntimeState extends ExpandableStringEnum<IntegrationRuntimeState> { /** Static value Initial for IntegrationRuntimeState. */ public static final IntegrationRuntimeState INITIAL = fromString("Initial"); /** Static value Stopped for IntegrationRuntimeState. */ public static final IntegrationRuntimeState STOPPED = fromString("Stopped"); /** Static value Started for IntegrationRuntimeState. */ public static final IntegrationRuntimeState STARTED = fromString("Started"); /** Static value Starting for IntegrationRuntimeState. */ public static final IntegrationRuntimeState STARTING = fromString("Starting"); /** Static value Stopping for IntegrationRuntimeState. */ public static final IntegrationRuntimeState STOPPING = fromString("Stopping"); /** Static value NeedRegistration for IntegrationRuntimeState. */ public static final IntegrationRuntimeState NEED_REGISTRATION = fromString("NeedRegistration"); /** Static value Online for IntegrationRuntimeState. */ public static final IntegrationRuntimeState ONLINE = fromString("Online"); /** Static value Limited for IntegrationRuntimeState. */ public static final IntegrationRuntimeState LIMITED = fromString("Limited"); /** Static value Offline for IntegrationRuntimeState. */ public static final IntegrationRuntimeState OFFLINE = fromString("Offline"); /** Static value AccessDenied for IntegrationRuntimeState. */ public static final IntegrationRuntimeState ACCESS_DENIED = fromString("AccessDenied"); /** * Creates or finds a IntegrationRuntimeState from its string representation. * @param name a name to look for * @return the corresponding IntegrationRuntimeState */ @JsonCreator public static IntegrationRuntimeState fromString(String name) { return fromString(name, IntegrationRuntimeState.class); } /** * @return known IntegrationRuntimeState values */ public static Collection<IntegrationRuntimeState> values() { return values(IntegrationRuntimeState.class); } }
    selvasingh/azure-sdk-for-java
    sdk/synapse/mgmt-v2019_06_01_preview/src/main/java/com/microsoft/azure/management/synapse/v2019_06_01_preview/IntegrationRuntimeState.java
    Java
    mit
    2,607
    // Copyright 2015 Peter Beverloo. All rights reserved. // Use of this source code is governed by the MIT license, a copy of which can // be found in the LICENSE file. // Base class for a module. Stores the environment and handles magic such as route annotations. export class Module { constructor(env) { this.env_ = env; let decoratedRoutes = Object.getPrototypeOf(this).decoratedRoutes_; if (!decoratedRoutes) return; decoratedRoutes.forEach(route => { env.dispatcher.addRoute(route.method, route.route_path, ::this[route.handler]); }); } }; // Annotation that can be used on modules to indicate that the annotated method is the request // handler for a |method| (GET, POST) request for |route_path|. export function route(method, route_path) { return (target, handler) => { if (!target.hasOwnProperty('decoratedRoutes_')) target.decoratedRoutes_ = []; target.decoratedRoutes_.push({ method, route_path, handler }); }; }
    beverloo/node-home-server
    src/module.js
    JavaScript
    mit
    981
    <?php /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <[email protected]> * Dariusz Rumiński <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Fixer\PhpUnit; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\Tokenizer\Tokens; /** * @author Roland Franssen <[email protected]> */ final class PhpUnitFqcnAnnotationFixer extends AbstractFixer { /** * {@inheritdoc} */ public function getDefinition() { return new FixerDefinition( 'PHPUnit annotations should be a FQCNs including a root namespace.', array(new CodeSample( '<?php final class MyTest extends \PHPUnit_Framework_TestCase { /** * @expectedException InvalidArgumentException * @covers Project\NameSpace\Something * @coversDefaultClass Project\Default * @uses Project\Test\Util */ public function testSomeTest() { } } ' )) ); } /** * {@inheritdoc} */ public function getPriority() { // should be run before NoUnusedImportsFixer return -9; } /** * {@inheritdoc} */ public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_DOC_COMMENT); } /** * {@inheritdoc} */ protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $token) { if ($token->isGivenKind(T_DOC_COMMENT)) { $token->setContent(preg_replace( '~^(\s*\*\s*@(?:expectedException|covers|coversDefaultClass|uses)\h+)(\w.*)$~m', '$1\\\\$2', $token->getContent() )); } } } }
    cedricleblond35/capvisu-site_supervision
    vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitFqcnAnnotationFixer.php
    PHP
    mit
    1,919
    --- layout: post title: "从头学算法(二、搞算法你必须知道的OJ)" date: 2016-12-20 11:36:52 categories: 数据结构及算法 tags: OJ algorithms mathjax: true --- 在没接触算法之前,我从没听说过OJ这个缩写,没关系,现在开始认识还来得及。等你真正开始研究算法,你才发现你又进入了一个新的世界。 这个世界,你不关注它的时候,它好像并不存在,而一旦你关注它了,每一个花草都让你叹为观止。 来看看百度百科是怎么说的吧: OJ是Online Judge系统的简称,用来在线检测程序源代码的正确性。著名的OJ有TYVJ、RQNOJ、URAL等。国内著名的题库有北京大学题库、浙江大学题库、电子科技大学题库、杭州电子科技大学等。国外的题库包括乌拉尔大学、瓦拉杜利德大学题库等。 而作为程序员,你必须知道Leetcode这个OJ,相比起国内各大著名高校的OJ,为什么我更推荐程序员们选择LeetCode OJ呢?原因有两点: 第一,大学OJ上的题目一般都是为ACM选手做准备的,难度大,属于竞技范畴;LeetCode的题相对简单,更为实用,更适合以后从事开发等岗位的程序员们。 第二,LeetCode非常流行,用户的量级几乎要比其他OJ高出将近三到五个级别。大量的活跃用户,将会为我们提供数不清的经验交流和可供参考的GitHub源代码。 刷LeetCode不是为了学会某些牛逼的算法,也不是为了突破某道难题而可能获得的智趣上的快感。学习和练习正确的思考方法,锻炼考虑各种条件的能力,在代码实现前就已经尽可能避免大多数常见错误带来的bug,养成简洁代码的审美习惯。 通过OJ刷题,配合算法的相关书籍进行理解,对算法的学习是很有帮助的,作为一个程序员,不刷几道LeetCode,真的说不过去。 最后LeetCode网址:https://leetcode.com/ 接下来注册开始搞吧! ![image_1bf90k08d19p01391i8pfvkqhbm.png-65.6kB][1] ![image_1bf90orko1ccn1opj29j93cc7f13.png-91.4kB][2] LeetCode刷过一阵子之后,发现很多都是收费的,这就很不友好了。本着方便大家的原则,向大家推荐lintcode,题目相对也很全,支持中、英双语,最重要是免费。 [1]: http://static.zybuluo.com/coldxiangyu/j2xlu88omsuprk7c7qinubug/image_1bf90k08d19p01391i8pfvkqhbm.png [2]: http://static.zybuluo.com/coldxiangyu/fztippzc74u7j9ww7av2vvn3/image_1bf90orko1ccn1opj29j93cc7f13.png
    coldxiangyu/coldxiangyu.github.io
    _posts/2016-12-20-从头学算法(二、搞算法你必须知道的OJ).md
    Markdown
    mit
    2,556
    package com.timotheteus.raincontrol.handlers; import com.timotheteus.raincontrol.tileentities.IGUITile; import com.timotheteus.raincontrol.tileentities.TileEntityInventoryBase; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.common.network.IGuiHandler; import net.minecraftforge.fml.network.FMLPlayMessages; import net.minecraftforge.fml.network.NetworkHooks; import javax.annotation.Nullable; public class GuiHandler implements IGuiHandler { public static GuiScreen openGui(FMLPlayMessages.OpenContainer openContainer) { BlockPos pos = openContainer.getAdditionalData().readBlockPos(); // new GUIChest(type, (IInventory) Minecraft.getInstance().player.inventory, (IInventory) Minecraft.getInstance().world.getTileEntity(pos)); TileEntityInventoryBase te = (TileEntityInventoryBase) Minecraft.getInstance().world.getTileEntity(pos); if (te != null) { return te.createGui(Minecraft.getInstance().player); } return null; } //TODO can remove these, I think @Nullable @Override public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { BlockPos pos = new BlockPos(x, y, z); TileEntity te = world.getTileEntity(pos); if (te instanceof IGUITile) { return ((IGUITile) te).createContainer(player); } return null; } @Nullable @Override public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { BlockPos pos = new BlockPos(x, y, z); TileEntity te = world.getTileEntity(pos); if (te instanceof IGUITile) { return ((IGUITile) te).createGui(player); } return null; } }
    kristofersokk/RainControl
    src/main/java/com/timotheteus/raincontrol/handlers/GuiHandler.java
    Java
    mit
    2,028
    <?php /** * CodeIgniter * * An open source application development framework for PHP * * This content is released under the MIT License (MIT) * * Copyright (c) 2014 - 2015, British Columbia Institute of Technology * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @package CodeIgniter * @author EllisLab Dev Team * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) * @copyright Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/) * @license http://opensource.org/licenses/MIT MIT License * @link http://codeigniter.com * @since Version 1.0.0 * @filesource */ /* *--------------------------------------------------------------- * APPLICATION ENVIRONMENT *--------------------------------------------------------------- * * You can load different configurations depending on your * current environment. Setting the environment also influences * things like logging and error reporting. * * This can be set to anything, but default usage is: * * development * testing * production * * NOTE: If you change these, also change the error_reporting() code below */ define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development'); /* *--------------------------------------------------------------- * ERROR REPORTING *--------------------------------------------------------------- * * Different environments will require different levels of error reporting. * By default development will show errors but testing and live will hide them. */ switch (ENVIRONMENT) { case 'development': error_reporting(-1); ini_set('display_errors', 1); break; case 'testing': case 'production': ini_set('display_errors', 0); if (version_compare(PHP_VERSION, '5.3', '>=')) { error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED); } else { error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_USER_NOTICE); } break; default: header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); echo 'The application environment is not set correctly.'; exit(1); // EXIT_ERROR } /* *--------------------------------------------------------------- * SYSTEM FOLDER NAME *--------------------------------------------------------------- * * This variable must contain the name of your "system" folder. * Include the path if the folder is not in the same directory * as this file. */ $system_path = 'system'; /* *--------------------------------------------------------------- * APPLICATION FOLDER NAME *--------------------------------------------------------------- * * If you want this front controller to use a different "application" * folder than the default one you can set its name here. The folder * can also be renamed or relocated anywhere on your server. If * you do, use a full server path. For more info please see the user guide: * http://codeigniter.com/user_guide/general/managing_apps.html * * NO TRAILING SLASH! */ $application_folder = 'application'; /* *--------------------------------------------------------------- * VIEW FOLDER NAME *--------------------------------------------------------------- * * If you want to move the view folder out of the application * folder set the path to the folder here. The folder can be renamed * and relocated anywhere on your server. If blank, it will default * to the standard location inside your application folder. If you * do move this, use the full server path to this folder. * * NO TRAILING SLASH! */ $view_folder = ''; $templates = $view_folder . '/templates/'; /* * -------------------------------------------------------------------- * DEFAULT CONTROLLER * -------------------------------------------------------------------- * * Normally you will set your default controller in the routes.php file. * You can, however, force a custom routing by hard-coding a * specific controller class/function here. For most applications, you * WILL NOT set your routing here, but it's an option for those * special instances where you might want to override the standard * routing in a specific front controller that shares a common CI installation. * * IMPORTANT: If you set the routing here, NO OTHER controller will be * callable. In essence, this preference limits your application to ONE * specific controller. Leave the function name blank if you need * to call functions dynamically via the URI. * * Un-comment the $routing array below to use this feature */ // The directory name, relative to the "controllers" folder. Leave blank // if your controller is not in a sub-folder within the "controllers" folder // $routing['directory'] = ''; // The controller class file name. Example: mycontroller // $routing['controller'] = ''; // The controller function you wish to be called. // $routing['function'] = ''; /* * ------------------------------------------------------------------- * CUSTOM CONFIG VALUES * ------------------------------------------------------------------- * * The $assign_to_config array below will be passed dynamically to the * config class when initialized. This allows you to set custom config * items or override any default config values found in the config.php file. * This can be handy as it permits you to share one application between * multiple front controller files, with each file containing different * config values. * * Un-comment the $assign_to_config array below to use this feature */ // $assign_to_config['name_of_config_item'] = 'value of config item'; // -------------------------------------------------------------------- // END OF USER CONFIGURABLE SETTINGS. DO NOT EDIT BELOW THIS LINE // -------------------------------------------------------------------- /* * --------------------------------------------------------------- * Resolve the system path for increased reliability * --------------------------------------------------------------- */ // Set the current directory correctly for CLI requests if (defined('STDIN')) { chdir(dirname(__FILE__)); } if (($_temp = realpath($system_path)) !== FALSE) { $system_path = $_temp . '/'; } else { // Ensure there's a trailing slash $system_path = rtrim($system_path, '/') . '/'; } // Is the system path correct? if (!is_dir($system_path)) { header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); echo 'Your system folder path does not appear to be set correctly. Please open the following file and correct this: ' . pathinfo(__FILE__, PATHINFO_BASENAME); exit(3); // EXIT_CONFIG } /* * ------------------------------------------------------------------- * Now that we know the path, set the main path constants * ------------------------------------------------------------------- */ // The name of THIS file define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME)); // Path to the system folder define('BASEPATH', str_replace('\\', '/', $system_path)); // Path to the front controller (this file) define('FCPATH', dirname(__FILE__) . '/'); // Name of the "system folder" define('SYSDIR', trim(strrchr(trim(BASEPATH, '/'), '/'), '/')); // The path to the "application" folder if (is_dir($application_folder)) { if (($_temp = realpath($application_folder)) !== FALSE) { $application_folder = $_temp; } define('APPPATH', $application_folder . DIRECTORY_SEPARATOR); } else { if (!is_dir(BASEPATH . $application_folder . DIRECTORY_SEPARATOR)) { header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); echo 'Your application folder path does not appear to be set correctly. Please open the following file and correct this: ' . SELF; exit(3); // EXIT_CONFIG } define('APPPATH', BASEPATH . $application_folder . DIRECTORY_SEPARATOR); } // The path to the "views" folder if (!is_dir($view_folder)) { if (!empty($view_folder) && is_dir(APPPATH . $view_folder . DIRECTORY_SEPARATOR)) { $view_folder = APPPATH . $view_folder; } elseif (!is_dir(APPPATH . 'views' . DIRECTORY_SEPARATOR)) { header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); echo 'Your view folder path does not appear to be set correctly. Please open the following file and correct this: ' . SELF; exit(3); // EXIT_CONFIG } else { $view_folder = APPPATH . 'views'; } } if (($_temp = realpath($view_folder)) !== FALSE) { $view_folder = $_temp . DIRECTORY_SEPARATOR; } else { $view_folder = rtrim($view_folder, '/\\') . DIRECTORY_SEPARATOR; } define('VIEWPATH', $view_folder); /* * -------------------------------------------------------------------- * LOAD THE BOOTSTRAP FILE * -------------------------------------------------------------------- * * And away we go... */ require_once BASEPATH . 'core/CodeIgniter.php';
    dayanstef/perfect-php-framework
    index.php
    PHP
    mit
    10,005
    version https://git-lfs.github.com/spec/v1 oid sha256:be847f24aac166b803f1ff5ccc7e4d7bc3fb5d960543e35f779068a754294c94 size 1312
    yogeshsaroya/new-cdnjs
    ajax/libs/extjs/4.2.1/src/app/domain/Direct.js
    JavaScript
    mit
    129
    <?php namespace Matthimatiker\CommandLockingBundle\Locking; use Symfony\Component\Filesystem\LockHandler; /** * Uses files to create locks. * * @see \Symfony\Component\Filesystem\LockHandler * @see http://symfony.com/doc/current/components/filesystem/lock_handler.html */ class FileLockManager implements LockManagerInterface { /** * The directory that contains the lock files. * * @var string */ private $lockDirectory = null; /** * Contains the locks that are currently active. * * The name of the lock is used as key. * * @var array<string, LockHandler> */ private $activeLocksByName = array(); /** * @param string $lockDirectory Path to the directory that contains the locks. */ public function __construct($lockDirectory) { $this->lockDirectory = $lockDirectory; } /** * Obtains a lock for the provided name. * * The lock must be released before it can be obtained again. * * @param string $name * @return boolean True if the lock was obtained, false otherwise. */ public function lock($name) { if ($this->isLocked($name)) { return false; } $lock = new LockHandler($name . '.lock', $this->lockDirectory); if ($lock->lock()) { // Obtained lock. $this->activeLocksByName[$name] = $lock; return true; } return false; } /** * Releases the lock with the provided name. * * If the lock does not exist, then this method will do nothing. * * @param string $name */ public function release($name) { if (!$this->isLocked($name)) { return; } /* @var $lock LockHandler */ $lock = $this->activeLocksByName[$name]; $lock->release(); unset($this->activeLocksByName[$name]); } /** * Checks if a lock with the given name is active. * * @param string $name * @return boolean */ private function isLocked($name) { return isset($this->activeLocksByName[$name]); } }
    Matthimatiker/CommandLockingBundle
    Locking/FileLockManager.php
    PHP
    mit
    2,166
    // Core is a collection of helpers // Nothing specific to the emultor application "use strict"; // all code is defined in this namespace window.te = window.te || {}; // te.provide creates a namespace if not previously defined. // Levels are seperated by a `.` Each level is a generic JS object. // Example: // te.provide("my.name.space"); // my.name.foo = function(){}; // my.name.space.bar = function(){}; te.provide = function(ns /*string*/ , root) { var parts = ns.split('.'); var lastLevel = root || window; for (var i = 0; i < parts.length; i++) { var p = parts[i]; if (!lastLevel[p]) { lastLevel = lastLevel[p] = {}; } else if (typeof lastLevel[p] !== 'object') { throw new Error('Error creating namespace.'); } else { lastLevel = lastLevel[p]; } } }; // A simple UID generator. Returned UIDs are guaranteed to be unique to the page load te.Uid = (function() { var id = 1; function next() { return id++; } return { next: next }; })(); // defaultOptionParse is a helper for functions that expect an options // var passed in. This merges the passed in options with a set of defaults. // Example: // foo function(options) { // tf.defaultOptionParse(options, {bar:true, fizz:"xyz"}); // } te.defaultOptionParse = function(src, defaults) { src = src || {}; var keys = Object.keys(defaults); for (var i = 0; i < keys.length; i++) { var k = keys[i]; if (src[k] === undefined) { src[k] = defaults[k]; } } return src; }; // Simple string replacement, eg: // tf.sprintf('{0} and {1}', 'foo', 'bar'); // outputs: foo and bar te.sprintf = function(str) { for (var i = 1; i < arguments.length; i++) { var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm'); str = str.replace(re, arguments[i]); } return str; };
    tyleregeto/8bit-emulator
    src/core.js
    JavaScript
    mit
    1,772
    ## # Backup v4.x Configuration # # Documentation: http://meskyanichi.github.io/backup # Issue Tracker: https://github.com/meskyanichi/backup/issues ## # Config Options # # The options here may be overridden on the command line, but the result # will depend on the use of --root-path on the command line. # # If --root-path is used on the command line, then all paths set here # will be overridden. If a path (like --tmp-path) is not given along with # --root-path, that path will use it's default location _relative to --root-path_. # # If --root-path is not used on the command line, a path option (like --tmp-path) # given on the command line will override the tmp_path set here, but all other # paths set here will be used. # # Note that relative paths given on the command line without --root-path # are relative to the current directory. The root_path set here only applies # to relative paths set here. # # --- # # Sets the root path for all relative paths, including default paths. # May be an absolute path, or relative to the current working directory. # # root_path 'my/root' # # Sets the path where backups are processed until they're stored. # This must have enough free space to hold apx. 2 backups. # May be an absolute path, or relative to the current directory or +root_path+. # # tmp_path 'my/tmp' # # Sets the path where backup stores persistent information. # When Backup's Cycler is used, small YAML files are stored here. # May be an absolute path, or relative to the current directory or +root_path+. # # data_path 'my/data' ## # Utilities # # If you need to use a utility other than the one Backup detects, # or a utility can not be found in your $PATH. # # Utilities.configure do # tar '/usr/bin/gnutar' # redis_cli '/opt/redis/redis-cli' # end ## # Logging # # Logging options may be set on the command line, but certain settings # may only be configured here. # # Logger.configure do # console.quiet = true # Same as command line: --quiet # logfile.max_bytes = 2_000_000 # Default: 500_000 # syslog.enabled = true # Same as command line: --syslog # syslog.ident = 'my_app_backup' # Default: 'backup' # end # # Command line options will override those set here. # For example, the following would override the example settings above # to disable syslog and enable console output. # backup perform --trigger my_backup --no-syslog --no-quiet ## # Component Defaults # # Set default options to be applied to components in all models. # Options set within a model will override those set here. # # Storage::S3.defaults do |s3| # s3.access_key_id = "my_access_key_id" # s3.secret_access_key = "my_secret_access_key" # end # # Notifier::Mail.defaults do |mail| # mail.from = '[email protected]' # mail.to = '[email protected]' # mail.address = 'smtp.gmail.com' # mail.port = 587 # mail.domain = 'your.host.name' # mail.user_name = '[email protected]' # mail.password = 'my_password' # mail.authentication = 'plain' # mail.encryption = :starttls # end ## # Preconfigured Models # # Create custom models with preconfigured components. # Components added within the model definition will # +add to+ the preconfigured components. # # preconfigure 'MyModel' do # archive :user_pictures do |archive| # archive.add '~/pictures' # end # # notify_by Mail do |mail| # mail.to = '[email protected]' # end # end # # MyModel.new(:john_smith, 'John Smith Backup') do # archive :user_music do |archive| # archive.add '~/music' # end # # notify_by Mail do |mail| # mail.to = '[email protected]' # end # end
    dockerizedrupal/backer
    src/backer/build/modules/build/files/root/Backup/config.rb
    Ruby
    mit
    3,832
    import Ember from 'ember'; let __TRANSLATION_MAP__ = {}; export default Ember.Service.extend({ map: __TRANSLATION_MAP__ });
    alexBaizeau/ember-fingerprint-translations
    app/services/translation-map.js
    JavaScript
    mit
    126
    import React from 'react'; <<<<<<< HEAD import { Switch, Route } from 'react-router-dom'; import Home from './Home'; import About from './About'; import Blog from './Blog'; import Resume from './Resume'; import Error404 from './Error404'; ======= // import GithubForm from './forms/github/GithubForm'; import GithubRecent from './forms/github/RecentList'; import './Content.css'; >>>>>>> 23d814bedfd5c07e05ea49d9a90053074a4c829a class Content extends React.Component { render() { return ( <div className="app-content"> <<<<<<< HEAD <Switch> <Route exact path="/" component={Home} /> {/* <Route exact path="/about" component={About} /> */} <Route component={Error404} /> </Switch> ======= <div className="content-description"> <br />College Student. Love Coding. Interested in Web and Machine Learning. </div> <hr /> <div className="content-list"> <div className="list-projects"> <h3>Recent Projects</h3> {/* <GithubRecent userName="slkjse9" standardDate={5259492000} /> */} <GithubRecent userName="hejuby" standardDate={3.154e+10} /> {/* <h2>Activity</h2> */} <h3>Experience</h3> <h3>Education</h3> <ul> <li><h4>Computer Science</h4>Colorado State University, Fort Collins (2017 -)</li> </ul> <br /> </div> </div> {/* <div className="content-home-github-recent-title"> <h2>Recent Works</h2> <h3>updated in 2 months</h3> </div> */} {/* <h3>Recent</h3> <GithubForm contentType="recent"/> */} {/* <h3>Lifetime</h3> {/* <GithubForm contentType="life"/> */} {/* <div className="content-home-blog-recent-title"> <h2>Recent Posts</h2> <h3>written in 2 months</h3> </div> <BlogRecent /> */} >>>>>>> 23d814bedfd5c07e05ea49d9a90053074a4c829a </div> ); } } export default Content;
    slkjse9/slkjse9.github.io
    src/components/Content.js
    JavaScript
    mit
    2,049
    package cmd import ( "github.com/fatih/color" out "github.com/plouc/go-gitlab-client/cli/output" "github.com/spf13/cobra" ) func init() { getCmd.AddCommand(getProjectVarCmd) } var getProjectVarCmd = &cobra.Command{ Use: resourceCmd("project-var", "project-var"), Aliases: []string{"pv"}, Short: "Get the details of a project's specific variable", RunE: func(cmd *cobra.Command, args []string) error { ids, err := config.aliasIdsOrArgs(currentAlias, "project-var", args) if err != nil { return err } color.Yellow("Fetching project variable (id: %s, key: %s)…", ids["project_id"], ids["var_key"]) loader.Start() variable, meta, err := client.ProjectVariable(ids["project_id"], ids["var_key"]) loader.Stop() if err != nil { return err } out.Variable(output, outputFormat, variable) printMeta(meta, false) return nil }, }
    plouc/go-gitlab-client
    cli/cmd/get_project_var_cmd.go
    GO
    mit
    873
    export interface IContact { id?: number; email: string; listName: string; name: string; }
    SimpleCom/simplecom-web
    src/interfaces/contacts.interface.ts
    TypeScript
    mit
    98
    // The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir 2020 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // This file was automatically generated and should not be edited directly. using System; using System.Runtime.InteropServices; namespace SharpVk.Interop { /// <summary> /// /// </summary> [StructLayout(LayoutKind.Sequential)] public unsafe partial struct ExternalMemoryImageCreateInfo { /// <summary> /// The type of this structure. /// </summary> public SharpVk.StructureType SType; /// <summary> /// Null or an extension-specific structure. /// </summary> public void* Next; /// <summary> /// /// </summary> public SharpVk.ExternalMemoryHandleTypeFlags HandleTypes; } }
    FacticiusVir/SharpVk
    src/SharpVk/Interop/ExternalMemoryImageCreateInfo.gen.cs
    C#
    mit
    1,882
    package unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletBasicWalletAvailableBalance; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.common.exceptions.CantRegisterCreditException; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.interfaces.BitcoinWalletTransactionRecord; import com.bitdubai.fermat_api.layer.osa_android.database_system.Database; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTransaction; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantLoadTableToMemoryException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException; import com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletBasicWalletAvailableBalance; import com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletDatabaseConstants; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.ArrayList; import java.util.List; import unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.mocks.MockBitcoinWalletTransactionRecord; import unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.mocks.MockDatabaseTableRecord; import static com.googlecode.catchexception.CatchException.catchException; import static com.googlecode.catchexception.CatchException.caughtException; import static org.fest.assertions.api.Assertions.*; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; /** * Created by jorgegonzalez on 2015.07.14.. */ @RunWith(MockitoJUnitRunner.class) public class CreditTest { @Mock private Database mockDatabase; @Mock private DatabaseTable mockWalletTable; @Mock private DatabaseTable mockBalanceTable; @Mock private DatabaseTransaction mockTransaction; private List<DatabaseTableRecord> mockRecords; private DatabaseTableRecord mockBalanceRecord; private DatabaseTableRecord mockWalletRecord; private BitcoinWalletTransactionRecord mockTransactionRecord; private BitcoinWalletBasicWalletAvailableBalance testBalance; @Before public void setUpMocks(){ mockTransactionRecord = new MockBitcoinWalletTransactionRecord(); mockBalanceRecord = new MockDatabaseTableRecord(); mockWalletRecord = new MockDatabaseTableRecord(); mockRecords = new ArrayList<>(); mockRecords.add(mockBalanceRecord); setUpMockitoRules(); } public void setUpMockitoRules(){ when(mockDatabase.getTable(BitcoinWalletDatabaseConstants.BITCOIN_WALLET_TABLE_NAME)).thenReturn(mockWalletTable); when(mockDatabase.getTable(BitcoinWalletDatabaseConstants.BITCOIN_WALLET_BALANCE_TABLE_NAME)).thenReturn(mockBalanceTable); when(mockBalanceTable.getRecords()).thenReturn(mockRecords); when(mockWalletTable.getEmptyRecord()).thenReturn(mockWalletRecord); when(mockDatabase.newTransaction()).thenReturn(mockTransaction); } @Before public void setUpAvailableBalance(){ testBalance = new BitcoinWalletBasicWalletAvailableBalance(mockDatabase); } @Test public void Credit_SuccesfullyInvoked_ReturnsAvailableBalance() throws Exception{ catchException(testBalance).credit(mockTransactionRecord); assertThat(caughtException()).isNull(); } @Test public void Credit_OpenDatabaseCantOpenDatabase_ThrowsCantRegisterCreditException() throws Exception{ doThrow(new CantOpenDatabaseException("MOCK", null, null, null)).when(mockDatabase).openDatabase(); catchException(testBalance).credit(mockTransactionRecord); assertThat(caughtException()) .isNotNull() .isInstanceOf(CantRegisterCreditException.class); } @Test public void Credit_OpenDatabaseDatabaseNotFound_ThrowsCantRegisterCreditException() throws Exception{ doThrow(new DatabaseNotFoundException("MOCK", null, null, null)).when(mockDatabase).openDatabase(); catchException(testBalance).credit(mockTransactionRecord); assertThat(caughtException()) .isNotNull() .isInstanceOf(CantRegisterCreditException.class); } @Test public void Credit_DaoCantCalculateBalanceException_ThrowsCantRegisterCreditException() throws Exception{ doThrow(new CantLoadTableToMemoryException("MOCK", null, null, null)).when(mockWalletTable).loadToMemory(); catchException(testBalance).credit(mockTransactionRecord); assertThat(caughtException()) .isNotNull() .isInstanceOf(CantRegisterCreditException.class); } @Test public void Credit_GeneralException_ThrowsCantRegisterCreditException() throws Exception{ when(mockBalanceTable.getRecords()).thenReturn(null); catchException(testBalance).credit(mockTransactionRecord); assertThat(caughtException()) .isNotNull() .isInstanceOf(CantRegisterCreditException.class); } }
    fvasquezjatar/fermat-unused
    DMP/plugin/basic_wallet/fermat-dmp-plugin-basic-wallet-bitcoin-wallet-bitdubai/src/test/java/unit/com/bitdubai/fermat_dmp_plugin/layer/basic_wallet/bitcoin_wallet/developer/bitdubai/version_1/structure/BitcoinWalletBasicWalletAvailableBalance/CreditTest.java
    Java
    mit
    5,641
    using System; namespace Sherlock { /// <summary> /// A reader than can read values from a pipe. /// </summary> /// <typeparam name="T">The type of value to read.</typeparam> public interface IPipeReader<T> : IDisposable { /// <summary> /// Attempts to read a value from the pipe. /// </summary> /// <param name="item">The read value.</param> /// <returns>A value indicating success.</returns> bool Read(out T item); /// <summary> /// Closes the reader. /// </summary> void Close(); /// <summary> /// Gets a value indicating whether the reader is closed. /// </summary> bool IsClosed { get; } } }
    tessellator/sherlock
    Sherlock/IPipeReader.cs
    C#
    mit
    742
    # Nitrogen 2.0 New Features ### New Elements, Actions, and API functions * wf:wire can now act upon CSS classes or full JQuery Paths, not just Nitrogen elements. For example, wf:wire(".people > .address", Actions) will wire actions to any HTML elements with an "address" class underneath a "people" class. Anything on http://api.jquery.com/category/selectors/ is supported * Added wf:replace(ID, Elements), remove an element from the page, put new elements in their place. * Added wf:remove(ID), remove an element from the page. * New #api{} action allows you to define a javascript method that takes parameters and will trigger a postback. Javascript parameters are automatically translated to Erlang, allowing for pattern matching. * New #grid{} element provides a Nitrogen interface to the 960 Grid System (http://960.gs) for page layouts. * The #upload{} event callbacks have changed. Event fires both on start of upload and when upload finishes. * Upload callbacks take a Node parameter so that file uploads work even when a postback hits a different node. * Many methods that used to be in 'nitrogen.erl' are now in 'wf.erl'. Also, some method signatures in wf.erl have changed. * wf:get_page_module changed to wf:page_module * wf:q(ID) no longer returns a list, just the value. * wf:qs(ID) returns a list. * wf:depickle(Data, TTL) returns undefined if expired. ### Comet Pools * Behind the scenes, combined logic for comet and continue events. This now all goes through the same channel. You can switch async mode between comet and intervalled polling by calling wf:switch_to_comet() or wf:switch_to_polling(IntervalMS), respectively. * Comet processes can now register in a local pool (for a specific session) or a global pool (across the entire Nitrogen cluster). All other processes in the pool are alerted when a process joins or leaves. The first process in a pool gets a special init message. * Use wf:send(Pool, Message) or wf:send_global(Pool, Message) to broadcast a message to the entire pool. * wf:comet_flush() is now wf:flush() ### Architectural Changes * Nitrogen now runs _under_ other web frameworks (inets, mochiweb, yaws, misultin) using simple_bridge. In other words, you hook into the other frameworks like normal (mochiweb loop, yaws appmod, etc.) and then call nitrogen:run() from within that process. * Handlers are the new mechanism to extend the inner parts of Nitrogen, such as session storage, authentication, etc. * New route handler code means that pages can exist in any namespace, don't have to start with /web/... (see dynamic_route_handler and named_route_handler) * Changed interface to elements and actions, any custom elements and actions will need tweaks. * sync:go() recompiles any changed files more intelligently by scanning for Emakefiles. * New ability to package Nitrogen projects as self-contained directories using rebar. # Nitrogen 1.0 Changelog 2009-05-02 - Added changes and bugfixes by Tom McNulty. 2009-04-05 - Added a templateroot setting in .app file, courtesy of Ville Koivula. 2009-03-28 - Added file upload support. 2009-03-22 - Added alt text support to #image elements by Robert Schonberger. - Fixed bug, 'nitrogen create (PROJECT)' now does a recursive copy of the Nitrogen support files, by Jay Doane. - Added radio button support courtesy of Benjamin Nortier and Tom McNulty. 2009-03-16 - Added .app configuration setting to bind Nitrogen to a specific IP address, by Tom McNulty. 2009-03-08 - Added DatePicker element by Torbjorn Tornkvist. - Upgrade to JQuery 1.3.2 and JQuery UI 1.7. - Created initial VERSIONS file. - Added code from Tom McNulty to expose Mochiweb loop. - Added coverage code from Michael Mullis, including lib/coverize submodule. - Added wf_platform:get_peername/0 code from Marius A. Eriksen. 2009-03-07 - Added code by Torbjorn Tornkvist: Basic Authentication, Hostname settings, access to HTTP Headers, and a Max Length validator. 2009-01-26 - Added Gravatar support by Dan Bravender. 2009-01-24 - Add code-level documentation around comet. - Fix bug where comet functions would continue running after a user left the page. - Apply patch by Tom McNulty to allow request object access within the route/1 function. - Apply patch by Tom McNulty to correctly bind binaries. - Apply patch by Tom McNulty for wf_tags library to correctly handle binaries. 2009-01-16 - Clean up code around timeout events. (Events that will start running after X seconds on the browser.) 2009-01-08 - Apply changes by Jon Gretar to support 'nitrogen create PROJECT' and 'nitrogen page /web/page' scripts. - Finish putting all properties into .app file. Put request/1 into application module file. - Add ability to route through route/1 in application module file. - Remove need for wf_global.erl - Start Yaws process underneath the main Nitrogen supervisor. (Used to be separate.) 2009-01-06 - Make Nitrogen a supervised OTP application, startable and stoppable via nitrogen:start() and nitrogen:stop(). - Apply changes by Dave Peticolas to fix session bugs and turn sessions into supervised processes. 2009-01-04 - Update sync module, add mirror module. These tools allow you to deploy and start applications on a bare remote node. 2009-01-03 - Allow Nitrogen to be run as an OTP application. See Quickstart project for example. - Apply Tom McNulty's patch to create and implement wf_tags library. Emit html tags more cleanly. - Change templates to allow multiple callbacks, and use first one that is defined. Basic idea and starter code by Tom McNulty. - Apply Martin Scholl's patch to optimize copy_to_baserecord in wf_utils.
    kbaldyga/Bazy
    CHANGELOG.markdown
    Markdown
    mit
    5,623
    package gogo import ( "net/http" "net/http/httptest" "testing" "github.com/golib/assert" ) func Test_NewResponse(t *testing.T) { it := assert.New(t) recorder := httptest.NewRecorder() response := NewResponse(recorder) it.Implements((*Responser)(nil), response) it.Equal(http.StatusOK, response.Status()) it.Equal(nonHeaderFlushed, response.Size()) } func Test_ResponseWriteHeader(t *testing.T) { it := assert.New(t) recorder := httptest.NewRecorder() response := NewResponse(recorder) response.WriteHeader(http.StatusRequestTimeout) it.Equal(http.StatusRequestTimeout, response.Status()) it.Equal(nonHeaderFlushed, response.Size()) } func Test_ResponseFlushHeader(t *testing.T) { it := assert.New(t) recorder := httptest.NewRecorder() response := NewResponse(recorder) response.WriteHeader(http.StatusRequestTimeout) response.FlushHeader() it.Equal(http.StatusRequestTimeout, recorder.Code) it.NotEqual(nonHeaderFlushed, response.Size()) // no effect after flushed headers response.WriteHeader(http.StatusOK) it.Equal(http.StatusOK, response.Status()) response.FlushHeader() it.NotEqual(http.StatusOK, recorder.Code) } func Test_ResponseWrite(t *testing.T) { it := assert.New(t) recorder := httptest.NewRecorder() hello := []byte("Hello,") world := []byte("world!") expected := []byte("Hello,world!") response := NewResponse(recorder) response.Write(hello) response.Write(world) it.True(response.HeaderFlushed()) it.Equal(len(expected), response.Size()) it.Equal(expected, recorder.Body.Bytes()) } func Benchmark_ResponseWrite(b *testing.B) { b.ReportAllocs() b.ResetTimer() hello := []byte("Hello,") world := []byte("world!") recorder := httptest.NewRecorder() response := NewResponse(recorder) for i := 0; i < b.N; i++ { response.Write(hello) response.Write(world) } } func Test_ResponseHijack(t *testing.T) { it := assert.New(t) recorder := httptest.NewRecorder() expected := []byte("Hello,world!") response := NewResponse(recorder) response.Write(expected) it.True(response.HeaderFlushed()) it.Equal(recorder, response.(*Response).ResponseWriter) it.Equal(len(expected), response.Size()) response.Hijack(httptest.NewRecorder()) it.False(response.HeaderFlushed()) it.NotEqual(recorder, response.(*Response).ResponseWriter) it.Equal(nonHeaderFlushed, response.Size()) } func Benchmark_ResponseHijack(b *testing.B) { b.ReportAllocs() b.ResetTimer() recorder := httptest.NewRecorder() response := NewResponse(recorder) for i := 0; i < b.N; i++ { response.Hijack(recorder) } }
    dolab/gogo
    response_test.go
    GO
    mit
    2,566
    #if !defined(AFX_DIALOG3_H__8EF7DE42_F33E_4217_87B0_FE9ACBCE3E84__INCLUDED_) #define AFX_DIALOG3_H__8EF7DE42_F33E_4217_87B0_FE9ACBCE3E84__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // Dialog3.h : header file // ///////////////////////////////////////////////////////////////////////////// // CDialog3 dialog class CDialog3 : public CDialog { // Construction public: CDialog3(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CDialog3) enum { IDD = IDD_DIALOG3 }; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDialog3) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CDialog3) virtual BOOL OnInitDialog(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DIALOG3_H__8EF7DE42_F33E_4217_87B0_FE9ACBCE3E84__INCLUDED_)
    Hao-Wu/MEDA
    Dialog3.h
    C
    mit
    1,146
    # Load DSL and set up stages require 'capistrano/setup' # Include default deployment tasks require 'capistrano/deploy' # Include tasks from other gems included in your Gemfile require 'capistrano/rvm' require 'capistrano/bundler' require 'capistrano/rails' require 'capistrano/rails/migrations' require 'capistrano/nginx_unicorn' require 'capistrano/rails/assets' # Load custom tasks from `lib/capistrano/tasks` if you have any defined Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }
    a11ejandro/project_prototype
    Capfile.rb
    Ruby
    mit
    501
    var mongoose = require('mongoose'); var bcrypt = require('bcrypt'); var saltRounds = 10; var userSchema = new mongoose.Schema({ email: { type: String, index: {unique: true} }, password: String, name: String }); //hash password userSchema.methods.generateHash = function(password){ return bcrypt.hashSync(password, bcrypt.genSaltSync(saltRounds)); } userSchema.methods.validPassword = function(password){ return bcrypt.compareSync(password, this.password); } var User = mongoose.model('User',userSchema); module.exports = User;
    zymokey/mission-park
    models/user/user.js
    JavaScript
    mit
    541
    <?php namespace Wolphy\Jobs; use Illuminate\Bus\Queueable; abstract class Job { /* |-------------------------------------------------------------------------- | Queueable Jobs |-------------------------------------------------------------------------- | | This job base class provides a central location to place any logic that | is shared across all of your jobs. The trait included with the class | provides access to the "queueOn" and "delay" queue helper methods. | */ use Queueable; }
    lezhnev74/wolphy
    app/Jobs/Job.php
    PHP
    mit
    538
    #!/bin/sh echo "Stopping web-server ..." COUNT_PROCESS=1 while [ $COUNT_PROCESS -gt 0 ] do COUNT_PROCESS=`ps -Aef | grep node | grep -c server.js` if [ $COUNT_PROCESS -gt 0 ]; then PID_PROCESS=`ps -Aef | grep node | grep server.js | awk '{print $2}'` if [ ! -z "$PID_PROCESS" ]; then echo "Killing web server PID=$PID_PROCESS" kill "$PID_PROCESS" fi fi echo "Waiting on web-server to stop ..." sleep 1 done echo "This web-server is stopped" exit 0
    stefanreichhart/tribe
    src/scripts/stopServer.sh
    Shell
    mit
    468
    <?php namespace RectorPrefix20210615; if (\class_exists('t3lib_collection_StaticRecordCollection')) { return; } class t3lib_collection_StaticRecordCollection { } \class_alias('t3lib_collection_StaticRecordCollection', 't3lib_collection_StaticRecordCollection', \false);
    RectorPHP/Rector
    vendor/ssch/typo3-rector/stubs/t3lib_collection_StaticRecordCollection.php
    PHP
    mit
    276
    using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("RedditImageDownloader.GUI")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RedditImageDownloader.GUI")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] //Um mit dem Erstellen lokalisierbarer Anwendungen zu beginnen, legen Sie //<UICulture>ImCodeVerwendeteKultur</UICulture> in der .csproj-Datei //in einer <PropertyGroup> fest. Wenn Sie in den Quelldateien beispielsweise Deutsch //(Deutschland) verwenden, legen Sie <UICulture> auf \"de-DE\" fest. Heben Sie dann die Auskommentierung //des nachstehenden NeutralResourceLanguage-Attributs auf. Aktualisieren Sie "en-US" in der nachstehenden Zeile, //sodass es mit der UICulture-Einstellung in der Projektdatei übereinstimmt. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //Speicherort der designspezifischen Ressourcenwörterbücher //(wird verwendet, wenn eine Ressource auf der Seite // oder in den Anwendungsressourcen-Wörterbüchern nicht gefunden werden kann.) ResourceDictionaryLocation.SourceAssembly //Speicherort des generischen Ressourcenwörterbuchs //(wird verwendet, wenn eine Ressource auf der Seite, in der Anwendung oder einem // designspezifischen Ressourcenwörterbuch nicht gefunden werden kann.) )] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
    Aniel/RedditImageDownloader
    RedditImageDownloader.GUI/Properties/AssemblyInfo.cs
    C#
    mit
    2,715
    #!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'ar' from layers_basic import LW_Layer, default_data_format from layers_convolutional import conv_output_length ############################################### class _LW_Pooling1D(LW_Layer): input_dim = 3 def __init__(self, pool_size=2, strides=None, padding='valid'): if strides is None: strides = pool_size assert padding in {'valid', 'same'}, 'border_mode must be in {valid, same}' self.pool_length = pool_size self.stride = strides self.border_mode = padding def get_output_shape_for(self, input_shape): length = conv_output_length(input_shape[1], self.pool_length, self.border_mode, self.stride) return (input_shape[0], length, input_shape[2]) class LW_MaxPooling1D(_LW_Pooling1D): def __init__(self, pool_size=2, strides=None, padding='valid'): super(LW_MaxPooling1D, self).__init__(pool_size, strides, padding) class LW_AveragePooling1D(_LW_Pooling1D): def __init__(self, pool_size=2, strides=None, padding='valid'): super(LW_AveragePooling1D, self).__init__(pool_size, strides, padding) ############################################### class _LW_Pooling2D(LW_Layer): def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format='default'): if data_format == 'default': data_format = default_data_format assert data_format in {'channels_last', 'channels_first'}, 'data_format must be in {channels_last, channels_first}' self.pool_size = tuple(pool_size) if strides is None: strides = self.pool_size self.strides = tuple(strides) assert padding in {'valid', 'same'}, 'border_mode must be in {valid, same}' self.border_mode = padding self.dim_ordering = data_format def get_output_shape_for(self, input_shape): if self.dim_ordering == 'channels_first': rows = input_shape[2] cols = input_shape[3] elif self.dim_ordering == 'channels_last': rows = input_shape[1] cols = input_shape[2] else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) rows = conv_output_length(rows, self.pool_size[0], self.border_mode, self.strides[0]) cols = conv_output_length(cols, self.pool_size[1], self.border_mode, self.strides[1]) if self.dim_ordering == 'channels_first': return (input_shape[0], input_shape[1], rows, cols) elif self.dim_ordering == 'channels_last': return (input_shape[0], rows, cols, input_shape[3]) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) class LW_MaxPooling2D(_LW_Pooling2D): def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format='default'): super(LW_MaxPooling2D, self).__init__(pool_size, strides, padding, data_format) class LW_AveragePooling2D(_LW_Pooling2D): def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format='default'): super(LW_AveragePooling2D, self).__init__(pool_size, strides, padding, data_format) ############################################### class _LW_Pooling3D(LW_Layer): def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='default'): if dim_ordering == 'default': dim_ordering = default_data_format assert dim_ordering in {'channels_last', 'channels_first'}, 'data_format must be in {channels_last, channels_first}' self.pool_size = tuple(pool_size) if strides is None: strides = self.pool_size self.strides = tuple(strides) assert border_mode in {'valid', 'same'}, 'border_mode must be in {valid, same}' self.border_mode = border_mode self.dim_ordering = dim_ordering def get_output_shape_for(self, input_shape): if self.dim_ordering == 'channels_first': len_dim1 = input_shape[2] len_dim2 = input_shape[3] len_dim3 = input_shape[4] elif self.dim_ordering == 'channels_last': len_dim1 = input_shape[1] len_dim2 = input_shape[2] len_dim3 = input_shape[3] else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) len_dim1 = conv_output_length(len_dim1, self.pool_size[0], self.border_mode, self.strides[0]) len_dim2 = conv_output_length(len_dim2, self.pool_size[1], self.border_mode, self.strides[1]) len_dim3 = conv_output_length(len_dim3, self.pool_size[2], self.border_mode, self.strides[2]) if self.dim_ordering == 'channels_first': return (input_shape[0], input_shape[1], len_dim1, len_dim2, len_dim3) elif self.dim_ordering == 'channels_last': return (input_shape[0], len_dim1, len_dim2, len_dim3, input_shape[4]) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) class LW_MaxPooling3D(_LW_Pooling3D): def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='default'): super(LW_MaxPooling3D, self).__init__(pool_size, strides, border_mode, dim_ordering) class LW_AveragePooling3D(_LW_Pooling3D): def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='default'): super(LW_AveragePooling3D, self).__init__(pool_size, strides, border_mode, dim_ordering) ############################################### class _LW_GlobalPooling1D(LW_Layer): def __init__(self): pass def get_output_shape_for(self, input_shape): return (input_shape[0], input_shape[2]) class LW_GlobalAveragePooling1D(_LW_GlobalPooling1D): pass class LW_GlobalMaxPooling1D(_LW_GlobalPooling1D): pass ############################################### class _LW_GlobalPooling2D(LW_Layer): def __init__(self, data_format='default'): if data_format == 'default': data_format = default_data_format self.dim_ordering = data_format def get_output_shape_for(self, input_shape): if self.dim_ordering == 'channels_last': return (input_shape[0], input_shape[3]) else: return (input_shape[0], input_shape[1]) class LW_GlobalAveragePooling2D(_LW_GlobalPooling2D): pass class LW_GlobalMaxPooling2D(_LW_GlobalPooling2D): pass ############################################### class _LW_GlobalPooling3D(LW_Layer): def __init__(self, data_format='default'): if data_format == 'default': data_format = default_data_format self.dim_ordering = data_format def get_output_shape_for(self, input_shape): if self.dim_ordering == 'channels_last': return (input_shape[0], input_shape[4]) else: return (input_shape[0], input_shape[1]) class LW_GlobalAveragePooling3D(_LW_GlobalPooling3D): pass class LW_GlobalMaxPooling3D(_LW_GlobalPooling3D): pass ############################################### if __name__ == '__main__': pass
    SummaLabs/DLS
    app/backend/core/models-keras-2x-api/lightweight_layers/layers_pooling.py
    Python
    mit
    7,111
    class CreateEventTypes < ActiveRecord::Migration def change create_table :event_types do |t| t.string :name, :limit => 80 t.timestamps end end end
    nac13k/iAdmin
    db/migrate/20140408042944_create_event_types.rb
    Ruby
    mit
    172
    /* * Copyright 2013 MongoDB, Inc. * * 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. */ #ifndef BSON_COMPAT_H #define BSON_COMPAT_H #if !defined (BSON_INSIDE) && !defined (BSON_COMPILATION) # error "Only <bson.h> can be included directly." #endif #if defined(__MINGW32__) # if defined(__USE_MINGW_ANSI_STDIO) # if __USE_MINGW_ANSI_STDIO < 1 # error "__USE_MINGW_ANSI_STDIO > 0 is required for correct PRI* macros" # endif # else # define __USE_MINGW_ANSI_STDIO 1 # endif #endif #include "bson-config.h" #include "bson-macros.h" #ifdef BSON_OS_WIN32 # if defined(_WIN32_WINNT) && (_WIN32_WINNT < 0x0600) # undef _WIN32_WINNT # endif # ifndef _WIN32_WINNT # define _WIN32_WINNT 0x0600 # endif # ifndef NOMINMAX # define NOMINMAX # endif # include <winsock2.h> # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # include <windows.h> # undef WIN32_LEAN_AND_MEAN # else # include <windows.h> # endif #include <direct.h> #include <io.h> #endif #ifdef BSON_OS_UNIX # include <unistd.h> # include <sys/time.h> #endif #include "bson-macros.h" #include <errno.h> #include <ctype.h> #include <limits.h> #include <fcntl.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> BSON_BEGIN_DECLS #ifdef _MSC_VER # include "bson-stdint-win32.h" # ifndef __cplusplus /* benign redefinition of type */ # pragma warning (disable :4142) # ifndef _SSIZE_T_DEFINED # define _SSIZE_T_DEFINED typedef SSIZE_T ssize_t; # endif typedef SIZE_T size_t; # pragma warning (default :4142) # else /* * MSVC++ does not include ssize_t, just size_t. * So we need to synthesize that as well. */ # pragma warning (disable :4142) # ifndef _SSIZE_T_DEFINED # define _SSIZE_T_DEFINED typedef SSIZE_T ssize_t; # endif # pragma warning (default :4142) # endif # define PRIi32 "d" # define PRId32 "d" # define PRIu32 "u" # define PRIi64 "I64i" # define PRId64 "I64i" # define PRIu64 "I64u" #else # include "bson-stdint.h" # include <inttypes.h> #endif #if defined(__MINGW32__) && ! defined(INIT_ONCE_STATIC_INIT) # define INIT_ONCE_STATIC_INIT RTL_RUN_ONCE_INIT typedef RTL_RUN_ONCE INIT_ONCE; #endif #ifdef BSON_HAVE_STDBOOL_H # include <stdbool.h> #elif !defined(__bool_true_false_are_defined) # ifndef __cplusplus typedef signed char bool; # define false 0 # define true 1 # endif # define __bool_true_false_are_defined 1 #endif #if defined(__GNUC__) # if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) # define bson_sync_synchronize() __sync_synchronize() # elif defined(__i386__ ) || defined( __i486__ ) || defined( __i586__ ) || \ defined( __i686__ ) || defined( __x86_64__ ) # define bson_sync_synchronize() asm volatile("mfence":::"memory") # else # define bson_sync_synchronize() asm volatile("sync":::"memory") # endif #elif defined(_MSC_VER) # define bson_sync_synchronize() MemoryBarrier() #endif #if !defined(va_copy) && defined(__va_copy) # define va_copy(dst,src) __va_copy(dst, src) #endif #if !defined(va_copy) # define va_copy(dst,src) ((dst) = (src)) #endif BSON_END_DECLS #endif /* BSON_COMPAT_H */
    kangseung/JSTrader
    include/mongoc-win/libbson/bson-compat.h
    C
    mit
    3,827
    require "empty_port/version" require 'socket' require 'timeout' # ## Example # require 'empty_port' # class YourServerTest < Test::Unit::TestCase # def setup # @port = EmptyPort.get # @server_pid = Process.fork do # server = TCPServer.open('localhost', @port) # end # EmptyPort.wait(@port) # end # # def test_something_with_server # end # # def teardown # Process.kill(@server_pid) # end # end # module EmptyPort class NotFoundException < Exception; end module ClassMethods # SEE http://www.iana.org/assignments/port-numbers MIN_PORT_NUMBER = 49152 MAX_PORT_NUMBER = 65535 # get an empty port except well-known-port. def get random_port = MIN_PORT_NUMBER + ( rand() * 1000 ).to_i while random_port < MAX_PORT_NUMBER begin sock = TCPSocket.open('localhost', random_port) sock.close rescue Errno::ECONNREFUSED => e return random_port end random_port += 1 end raise NotFoundException end def listened?(port) begin sock = TCPSocket.open('localhost', port) sock.close return true rescue Errno::ECONNREFUSED return false end end DEFAULT_TIMEOUT = 2 DEFAULT_INTERVAL = 0.1 def wait(port, options={}) options[:timeout] ||= DEFAULT_TIMEOUT options[:interval] ||= DEFAULT_INTERVAL timeout(options[:timeout]) do start = Time.now loop do if self.listened?(port) finished = Time.now return finished - start end sleep(options[:interval]) end end end end extend ClassMethods end
    walf443/empty_port
    lib/empty_port.rb
    Ruby
    mit
    1,760
    module.exports = { 'throttle': 10, 'hash': true, 'gzip': false, 'baseDir': 'public', 'buildDir': 'build', 'prefix': '' };
    wunderlist/bilder-aws
    lib/defaults.js
    JavaScript
    mit
    133
    .vertical-center { min-height: 100%; /* Fallback for browsers do NOT support vh unit */ min-height: 100vh; /* These two lines are counted as one :-) */ display: flex; align-items: center; } @media (min-width: 768px){ #wrapper {/*padding-right: 225px;*/ padding-left: 0;} .side-nav{right: 0;left: auto;} } /*! * Start Bootstrap - SB Admin (http://startbootstrap.com/) * Copyright 2013-2016 Start Bootstrap * Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap/blob/gh-pages/LICENSE) */ /* Global Styles */ body { background-color: #222; } #wrapper { padding-left: 0; } #page-wrapper { width: 100%; padding: 0; background-color: #fff; } .huge { font-size: 50px; line-height: normal; } @media(min-width:768px) { #wrapper { padding-left: 225px; } #page-wrapper { padding: 10px; margin-top: 20px; } } /* Top Navigation */ .top-nav { padding: 0 15px; } .top-nav>li { display: inline-block; float: left; } .top-nav>li>a { padding-top: 15px; padding-bottom: 15px; line-height: 20px; color: #999; } .top-nav>li>a:hover, .top-nav>li>a:focus, .top-nav>.open>a, .top-nav>.open>a:hover, .top-nav>.open>a:focus { color: #fff; background-color: #000; } .top-nav>.open>.dropdown-menu { float: left; position: absolute; margin-top: 0; border: 1px solid rgba(0,0,0,.15); border-top-left-radius: 0; border-top-right-radius: 0; background-color: #fff; -webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175); box-shadow: 0 6px 12px rgba(0,0,0,.175); } .top-nav>.open>.dropdown-menu>li>a { white-space: normal; } ul.message-dropdown { padding: 0; max-height: 250px; overflow-x: hidden; overflow-y: auto; } li.message-preview { width: 275px; border-bottom: 1px solid rgba(0,0,0,.15); } li.message-preview>a { padding-top: 15px; padding-bottom: 15px; } li.message-footer { margin: 5px 0; } ul.alert-dropdown { width: 200px; } .alert-danger { margin-top: 50px; } /* Side Navigation */ @media(min-width:768px) { .side-nav { position: fixed; top: 51px; /* left: 225px;*/ left: 0px; width: 225px; /* margin-left: -225px;*/ border: none; border-radius: 0; overflow-y: auto; background-color: #222; bottom: 0; overflow-x: hidden; padding-bottom: 40px; } .side-nav>li>a { width: 225px; } .side-nav li a:hover, .side-nav li a:focus { outline: none; background-color: #000 !important; } } .side-nav>li>ul { padding: 0; } .side-nav>li>ul>li>a { display: block; padding: 10px 15px 10px 38px; text-decoration: none; color: #999; } .side-nav>li>ul>li>a:hover { color: #fff; } /* Flot Chart Containers */ .flot-chart { display: block; height: 400px; } .flot-chart-content { width: 100%; height: 100%; } /* Custom Colored Panels */ .huge { font-size: 40px; } .panel-green { border-color: #5cb85c; } .panel-green > .panel-heading { border-color: #5cb85c; color: #fff; background-color: #5cb85c; } .panel-green > a { color: #5cb85c; } .panel-green > a:hover { color: #3d8b3d; } .panel-red { border-color: #d9534f; } .panel-red > .panel-heading { border-color: #d9534f; color: #fff; background-color: #d9534f; } .panel-red > a { color: #d9534f; } .panel-red > a:hover { color: #b52b27; } .panel-yellow { border-color: #f0ad4e; } .panel-yellow > .panel-heading { border-color: #f0ad4e; color: #fff; background-color: #f0ad4e; } .panel-yellow > a { color: #f0ad4e; } .panel-yellow > a:hover { color: #df8a13; } .navbar-nav > li > ul > li.active { background: rgba(9, 9, 9, 0.57); }
    antodoms/beaconoid
    app/assets/stylesheets/admin.css
    CSS
    mit
    3,884
    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>使用 button 定义按钮</title> </head> <body> <form action="http://www.baidu.com" method="get"> <button type="button"><b>提交</b></button><br/> <button type="submit"><img sec="./img/3.jpg" alt="图片"></button><br/> </form> </body> </html>
    llinmeng/learn-fe
    src/ex/crazy-fe-book/2017/H5/03/3-1-4.html
    HTML
    mit
    351
    --- layout: post title: Tweets date: 2019-08-08 summary: These are the tweets for August 8, 2019. categories: ---
    alexlitel/congresstweets
    _posts/2019-08-08--tweets.md
    Markdown
    mit
    115
    import type { FormatRelativeFn } from '../../../types' // Source: https://www.unicode.org/cldr/charts/32/summary/te.html const formatRelativeLocale = { lastWeek: "'గత' eeee p", // CLDR #1384 yesterday: "'నిన్న' p", // CLDR #1393 today: "'ఈ రోజు' p", // CLDR #1394 tomorrow: "'రేపు' p", // CLDR #1395 nextWeek: "'తదుపరి' eeee p", // CLDR #1386 other: 'P', } const formatRelative: FormatRelativeFn = (token, _date, _baseDate, _options) => formatRelativeLocale[token] export default formatRelative
    date-fns/date-fns
    src/locale/te/_lib/formatRelative/index.ts
    TypeScript
    mit
    557
    INSERT INTO customers(id, name) VALUES (1, 'Jane Woods'); INSERT INTO customers(id, name) VALUES (2, 'Michael Li'); INSERT INTO customers(id, name) VALUES (3, 'Heidi Hasselbach'); INSERT INTO customers(id, name) VALUES (4, 'Rahul Pour');
    afh/yabab
    pre-populate.sql
    SQL
    mit
    238
    /* * * BitcoinLikeKeychain * ledger-core * * Created by Pierre Pollastri on 17/01/2017. * * The MIT License (MIT) * * Copyright (c) 2016 Ledger * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #ifndef LEDGER_CORE_BITCOINLIKEKEYCHAIN_HPP #define LEDGER_CORE_BITCOINLIKEKEYCHAIN_HPP #include "../../../bitcoin/BitcoinLikeExtendedPublicKey.hpp" #include <string> #include <vector> #include <utils/DerivationScheme.hpp> #include "../../../utils/Option.hpp" #include "../../../preferences/Preferences.hpp" #include "../../../api/Configuration.hpp" #include "../../../api/DynamicObject.hpp" #include <api/Currency.hpp> #include <api/AccountCreationInfo.hpp> #include <api/ExtendedKeyAccountCreationInfo.hpp> #include <api/Keychain.hpp> #include <bitcoin/BitcoinLikeAddress.hpp> namespace ledger { namespace core { class BitcoinLikeKeychain: public api::Keychain { public: enum KeyPurpose { RECEIVE, CHANGE }; public: using Address = std::shared_ptr<BitcoinLikeAddress>; BitcoinLikeKeychain( const std::shared_ptr<api::DynamicObject>& configuration, const api::Currency& params, int account, const std::shared_ptr<Preferences>& preferences); virtual bool markAsUsed(const std::vector<std::string>& addresses); virtual bool markAsUsed(const std::string& address, bool needExtendKeychain = true); virtual bool markPathAsUsed(const DerivationPath& path, bool needExtendKeychain = true) = 0; virtual std::vector<Address> getAllObservableAddresses(uint32_t from, uint32_t to) = 0; virtual std::vector<std::string> getAllObservableAddressString(uint32_t from, uint32_t to) = 0; virtual std::vector<Address> getAllObservableAddresses(KeyPurpose purpose, uint32_t from, uint32_t to) = 0; virtual Address getFreshAddress(KeyPurpose purpose) = 0; virtual std::vector<Address> getFreshAddresses(KeyPurpose purpose, size_t n) = 0; virtual Option<KeyPurpose> getAddressPurpose(const std::string& address) const = 0; virtual Option<std::string> getAddressDerivationPath(const std::string& address) const = 0; virtual bool isEmpty() const = 0; int getAccountIndex() const; const api::BitcoinLikeNetworkParameters& getNetworkParameters() const; const api::Currency& getCurrency() const; virtual Option<std::vector<uint8_t>> getPublicKey(const std::string& address) const = 0; std::shared_ptr<api::DynamicObject> getConfiguration() const; const DerivationScheme& getDerivationScheme() const; const DerivationScheme& getFullDerivationScheme() const; std::string getKeychainEngine() const; bool isSegwit() const; bool isNativeSegwit() const; virtual std::string getRestoreKey() const = 0; virtual int32_t getObservableRangeSize() const = 0; virtual bool contains(const std::string& address) const = 0; virtual std::vector<Address> getAllAddresses() = 0; virtual int32_t getOutputSizeAsSignedTxInput() const = 0; static bool isSegwit(const std::string &keychainEngine); static bool isNativeSegwit(const std::string &keychainEngine); std::shared_ptr<Preferences> getPreferences() const; protected: DerivationScheme& getDerivationScheme(); private: const api::Currency _currency; DerivationScheme _scheme; DerivationScheme _fullScheme; int _account; std::shared_ptr<Preferences> _preferences; std::shared_ptr<api::DynamicObject> _configuration; }; } } #endif //LEDGER_CORE_BITCOINLIKEKEYCHAIN_HPP
    LedgerHQ/lib-ledger-core
    core/src/wallet/bitcoin/keychains/BitcoinLikeKeychain.hpp
    C++
    mit
    4,962
    <?php namespace AppBundle\Repository; /** * Buyers_PropertiesRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class Buyers_PropertiesRepository extends \Doctrine\ORM\EntityRepository { }
    asimo124/MLSSite
    src/AppBundle/Repository/Buyers_PropertiesRepository.php
    PHP
    mit
    257
    #!/usr/bin/env ruby #Example handler file.. infile = ARGV.first outfile = File.basename(infile, ".tif") + ".jpg.tif" system("~/cm/processing_scripts/rgb_to_jpeg_tif.rb --internal-mask #{infile} #{outfile}")
    spruceboy/jays_geo_tools
    examples/sample_handler_for_do_several_at_once.rb
    Ruby
    mit
    210
    using Newtonsoft.Json; using ProtoBuf; using ITK.ModelManager; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Steam.Models { [Model("SteamPlayerBans")] [ProtoContract] [JsonObject(MemberSerialization.OptIn)] public class PlayerBans { /// <summary> /// A string containing the player's 64 bit ID. /// </summary> [JsonProperty("SteamID")] [ProtoMember(1, IsRequired = true)] public ulong SteamId {get; set;} /// <summary> /// Boolean indicating whether or not the player is banned from Community /// </summary> [JsonProperty("CommunityBanned")] [ProtoMember(2)] public bool IsCommunityBanned {get; set;} /// <summary> /// Boolean indicating whether or not the player has VAC bans on record. /// </summary> [JsonProperty("VACBanned")] [ProtoMember(3)] public bool IsVACBanned {get; set;} /// <summary> /// Amount of VAC bans on record. /// </summary> [JsonProperty("NumberOfVACBans")] [ProtoMember(4)] public int VACBanCount {get; set;} /// <summary> /// Amount of days since last ban. /// </summary> [JsonProperty("DaysSinceLastBan")] [ProtoMember(5)] public int DaysSinceLastBan {get; set;} /// <summary> /// String containing the player's ban status in the economy. If the player has no bans on record the string will be "none", if the player is on probation it will say "probation", and so forth. /// </summary> [JsonProperty("EconomyBan")] [ProtoMember(6)] public string EconomyBan {get; set;} public override int GetHashCode() { return SteamId.GetHashCode(); } public override bool Equals(object obj) { var other = obj as PlayerBans; return other != null && SteamId.Equals(other.SteamId); } } }
    inlinevoid/Overust
    Steam/Models/PlayerBans.cs
    C#
    mit
    2,083
    /* * Business.h * UsersService * * Copyright 2011 QuickBlox team. All rights reserved. * */ #import "QBUsersModels.h"
    bluecitymoon/demo-swift-ios
    demo-swift/Quickblox.framework/Versions/A/Headers/QBUsersBusiness.h
    C
    mit
    128
    --- layout: post title: ESPN took a picture of me categories: link --- Check [this link](http://espn.go.com/college-football/story/_/id/9685394/how-do-nebraska-fans-feel-bo-pelini-recent-behavior) for some story about Bo Pelini's goofing off, and -- look there in the last photo! -- it's some goofball in a Nebraska trilby.
    samervin/blog.samerv.in
    _posts/link/2013-09-17-espn-picture.md
    Markdown
    mit
    332
    // // GFTestAppDelegate.h // TestChaosApp // // Created by Michael Charkin on 2/26/14. // Copyright (c) 2014 GitFlub. All rights reserved. // #import <UIKit/UIKit.h> @interface GFTestAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
    firemuzzy/GFChaos
    TestChaosApp/TestChaosApp/GFTestAppDelegate.h
    C
    mit
    294
    var modules = { "success" : [ {id: 1, name:"控制台", code:"console", protocol:"http", domain:"console.ecc.com", port:"18333", created:'2017-03-08 00:00:00', creator:'1', modified:'2017-03-08 00:00:00', modifier:'1'}, {id: 2, name:"服务中心", code:"service-center", protocol:"http", domain:"sc.ecc.com", port:"18222", created:'2017-03-08 00:00:00', creator:'1', modified:'2017-03-08 00:00:00', modifier:'1'} ], "error" : { code : "0200-ERROR", msg : "There are some errors occured." } } module.exports = { "modules": modules }
    chinakite/wukong
    data/datas/modules.js
    JavaScript
    mit
    545
    const { createServer, plugins: { queryParser, serveStatic } } = require('restify'); const { join } = require('path'); const fetch = require('node-fetch'); const proxy = require('http-proxy-middleware'); const { PORT = 5000 } = process.env; const server = createServer(); server.use(queryParser()); server.get('/', async (req, res, next) => { if (!req.query.b) { const tokenRes = await fetch('https://webchat-mockbot.azurewebsites.net/directline/token', { headers: { origin: 'http://localhost:5000' }, method: 'POST' }); if (!tokenRes.ok) { return res.send(500); } const { token } = await tokenRes.json(); return res.send(302, null, { location: `/?b=webchat-mockbot&t=${encodeURIComponent(token)}` }); } return serveStatic({ directory: join(__dirname, 'dist'), file: 'index.html' })(req, res, next); }); server.get('/embed/*/config', proxy({ changeOrigin: true, target: 'https://webchat.botframework.com/' })); server.listen(PORT, () => console.log(`Embed dev server is listening to port ${PORT}`));
    billba/botchat
    packages/embed/hostDevServer.js
    JavaScript
    mit
    1,094
    /** * @author: * @date: 2016/1/21 */ define(["core/js/layout/Panel"], function (Panel) { var view = Panel.extend({ /*Panel的配置项 start*/ title:"表单-", help:"内容", brief:"摘要", /*Panel 配置 End*/ oninitialized:function(triggerEvent){ this._super(); this.mainRegion={ comXtype:$Component.TREE, comConf:{ data:[this.getModuleTree("core/js/base/AbstractView")], } }; var that = this; this.footerRegion = { comXtype: $Component.TOOLSTRIP, comConf: { /*Panel的配置项 start*/ textAlign: $TextAlign.RIGHT, items: [{ text: "展开所有节点", onclick: function (e) { that.getMainRegionRef().getComRef().expandAll(); }, },{ text: "折叠所有节点", onclick: function (e) { that.getMainRegionRef().getComRef().collapseAll(); }, }] /*Panel 配置 End*/ } }; }, getModuleTree:function(moduleName,arr){ var va = window.rtree.tree[moduleName]; var tree = {title: moduleName}; if(!arr){ arr = []; }else{ if(_.contains(arr,moduleName)){ return false; } } arr.push(moduleName); if(va&&va.deps&&va.deps.length>0){ tree.children = []; tree.folder=true; for(var i=0;i<va.deps.length;i++){ var newTree = this.getModuleTree(va.deps[i],arr); if(newTree){ tree.children.push(newTree); }else{ if(!tree.count){ tree.count = 0; } tree.count++; } } } return tree; } }); return view; });
    huangfeng19820712/hfast
    example/view/tree/treeAndTable.js
    JavaScript
    mit
    2,606
    # Django Media Albums [![Build Status](https://travis-ci.org/VelocityWebworks/django-media-albums.svg?branch=master)](https://travis-ci.org/VelocityWebworks/django-media-albums) This app is used to create albums consisting of any combination of the following: * Photos * Video files * Audio files This app also optionally allows regular (non-staff) users to upload photos. This app requires Django 1.8, 1.9, 1.10, or 1.11. ## Installation ### Step 1 of 5: Install the required packages Install using pip: ```bash pip install django-media-albums ``` If you will be using the templates that come with this app, also install these packages using pip: ```bash pip install django-bootstrap-pagination sorl-thumbnail ``` If you will be allowing regular (non-staff) users to upload photos and will be using the `upload.html` template that comes with this app, also install the `django-crispy-forms` package using pip: ```bash pip install django-crispy-forms ``` ### Step 2 of 5: Update `settings.py` Make sure the following settings are all configured the way you want them in your `settings.py`: ``` MEDIA_ROOT MEDIA_URL STATIC_ROOT STATIC_URL ``` If you will be allowing regular (non-staff) users to upload photos, you will also need to have the `DEFAULT_FROM_EMAIL` setting present in your `settings.py` (for the notification email that gets sent out when a user uploads a photo). Add `'media_albums'` to your `settings.py` INSTALLED_APPS: ```python INSTALLED_APPS = ( ... 'media_albums', ... ) ``` If you will be using the templates that come with this app, also add the following to your `settings.py` INSTALLED_APPS: ```python INSTALLED_APPS = ( ... 'bootstrap_pagination', 'sorl.thumbnail', ... ) ``` If you will be allowing regular (non-staff) users to upload photos and will be using the `upload.html` template that comes with this app, also add `'crispy_forms'` to your `settings.py` INSTALLED_APPS and make sure the `CRISPY_TEMPLATE_PACK` setting is configured the way you want it: ```python INSTALLED_APPS = ( ... 'crispy_forms', ... ) CRISPY_TEMPLATE_PACK = 'bootstrap3' ``` If you will be enabling audio and/or video and will be using the templates that come with this app, also enable the `'django.template.context_processors.media'` context processor: ```python TEMPLATES = [ ... { ... 'OPTIONS': { ... 'context_processors': [ ... 'django.template.context_processors.media', ... ], ... }, ... }, ... ] ``` ### Step 3 of 5: Update `urls.py` Create a URL pattern in your `urls.py`: ```python from django.conf.urls import include, url urlpatterns = [ ... url(r'^media-albums/', include('media_albums.urls')), ... ] ``` ### Step 4 of 5: Add the database tables Run the following command: ```bash python manage.py migrate ``` ### Step 5 of 5: Update your project's `base.html` template (if necessary) If you will be using the templates that come with this app, make sure your project has a `base.html` template and that it has these blocks: ``` content extra_styles ``` ## Configuration To override any of the default settings, create a dictionary named `MEDIA_ALBUMS` in your `settings.py` with each setting you want to override. For example, if you wanted to enable audio and video, but leave all of the other settings alone, you would add this to your `settings.py`: ```python MEDIA_ALBUMS = { 'audio_files_enabled': True, 'video_files_enabled': True, } ``` These are the settings: ### `photos_enabled` (default: `True`) When set to `True`, albums may contain photos. ### `audio_files_enabled` (default: `False`) When set to `True`, albums may contain audio files. ### `audio_files_format1_extension` (default: `'mp3'`) When an audio file is uploaded, the "Audio file 1" field must have this extension. This setting is only relevant if `audio_files_enabled` is set to `True`. ### `audio_files_format2_extension` (default: `'ogg'`) When an audio file is uploaded, the "Audio file 2" field must have this extension. This setting is only relevant if `audio_files_enabled` is set to `True`. ### `audio_files_format2_required` (default: `False`) When set to `True`, the "Audio file 2" field will be marked as required. This setting is only relevant if `audio_files_enabled` is set to `True`. ### `video_files_enabled` (default: `False`) When set to `True`, albums may contain video files. ### `video_files_format1_extension` (default: `'mp4'`) When an video file is uploaded, the "Video file 1" field must have this extension. This setting is only relevant if `video_files_enabled` is set to `True`. ### `video_files_format2_extension` (default: `'webm'`) When an video file is uploaded, the "Video file 2" field must have this extension. This setting is only relevant if `video_files_enabled` is set to `True`. ### `video_files_format2_required` (default: `False`) When set to `True`, the "Video file 2" field will be marked as required. This setting is only relevant if `video_files_enabled` is set to `True`. ### `user_uploaded_photos_enabled` (default: `False`) When set to `True`, regular (non-staff) users may upload photos. However, they still must be approved by a staff user. ### `user_uploaded_photos_login_required` (default: `True`) When set to `True`, regular (non-staff) users may only upload photos if they are logged in. This setting is only relevant if `user_uploaded_photos_enabled` is set to `True`. ### `user_uploaded_photos_album_name` (default: `'User Photos'`) When a staff user approves a photo uploaded by a regular (non-staff) user, the photo will be added to the album with this name. This setting is only relevant if `user_uploaded_photos_enabled` is set to `True`. ### `user_uploaded_photos_album_slug` (default: `'user-photos'`) When a staff user approves a photo uploaded by a regular (non-staff) user, the photo will be added to the album with this slug. This setting is only relevant if `user_uploaded_photos_enabled` is set to `True`. ### `paginate_by` (default: `10`) This setting determines how many items can be on a single page. This applies to the list of albums as well as the list of items within albums.
    VelocityWebworks/django-media-albums
    README.md
    Markdown
    mit
    6,320
    <!-- Safe sample input : get the $_GET['userData'] in an array sanitize : settype (float) File : unsafe, use of untrusted data in a comment --> <!--Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.--> <!DOCTYPE html> <html> <head> <!-- <?php $array = array(); $array[] = 'safe' ; $array[] = $_GET['userData'] ; $array[] = 'safe' ; $tainted = $array[1] ; if(settype($tainted, "float")) $tainted = $tainted ; else $tainted = 0.0 ; echo $tainted ; ?> --> </head> <body> <h1>Hello World!</h1> </body> </html>
    stivalet/PHP-Vulnerability-test-suite
    XSS/CWE_79/safe/CWE_79__array-GET__CAST-func_settype_float__Unsafe_use_untrusted_data-comment.php
    PHP
    mit
    1,367
    $('#modalUploader').on('show.bs.modal', function (event) { var uploader = new qq.FileUploaderBasic({ element: document.getElementById('file-uploader-demo1'), button: document.getElementById('areaSubir'), action: '/Files/Upload', params: { ruta: $('#RutaActual').val() }, allowedExtensions: ['jpg', 'jpeg', 'png', 'gif', 'doc', 'docx', 'pdf'], multiple: false, onComplete: function (id, fileName, responseJSON) { $.gritter.add({ title: 'Upload file', text: responseJSON.message }); }, onSubmit: function (id, fileName) { var strHtml = "<li>" + fileName + "</li>"; $("#dvxArchivos").append(strHtml); } }); }); $('#modalUploader').on('hidden.bs.modal', function () { RecargarRuta(); }) function AbrirCarpeta(pCarpeta) { $("#RutaSolicitada").val(pCarpeta); $("#frmMain").submit(); } function AbrirRuta(pCarpeta) { $("#RutaSolicitada").val(pCarpeta); $("#frmMain").submit(); } function RecargarRuta() { AbrirCarpeta($("#RutaActual").val()); } function EliminarArchivo(pRuta) { if (confirm("Are you sure that want to delete this file?")) { $.gritter.add({ title: 'Delete file', text: "File deleted" }); $("#ArchivoParaEliminar").val(pRuta); AbrirCarpeta($("#RutaActual").val()); } } function SubirNivel() { if ($("#TieneSuperior").val() == "1") { var strRutaAnterior = $("#RutaSuperior").val(); AbrirRuta(strRutaAnterior); } } function IrInicio() { AbrirRuta($("#RutaRaiz").val()); } function AbrirDialogoArchivo() { $("#modalUploader").modal(); } function getParameterByName(name) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regexS = "[\\?&]" + name + "=([^&#]*)"; var regex = new RegExp(regexS); var results = regex.exec(window.location.search); if (results == null) return ""; else return decodeURIComponent(results[1].replace(/\+/g, " ")); }
    walalm/MVC-Azure-Explorer
    MVC_Azure_Explorer/MVC_Azure_Explorer/Scripts/UtilsFileManager.js
    JavaScript
    mit
    2,111
    // setToken when re-connecting var originalReconnect = Meteor.connection.onReconnect; Meteor.connection.onReconnect = function() { setToken(); if(originalReconnect) { originalReconnect(); } }; if(Meteor.status().connected) { setToken(); } function setToken() { var firewallHumanToken = Cookie.get('sikka-human-token'); Meteor.call('setSikkaHumanToken', firewallHumanToken); } // reloading the page window.sikkaCommands = sikkaCommands = new Mongo.Collection('sikka-commands'); sikkaCommands.find({}).observe({ added: function(command) { if(command._id === "reload") { location.reload(); } } });
    meteorhacks/sikka
    lib/client/core.js
    JavaScript
    mit
    631
    <% nameScope = @config['name_scope'] %> </div> </div> </div> <footer class="cortana-footer"> Build with love using Trulia's <a href="https://github.com/trulia/hologram">Hologram</a> and <a href="https://github.com/Yago/Cortana">Cortana</a> ! </footer> </div> <script src="theme-build/js/vendors.min.js"></script> <script type="text/javascript"> var jQuery_no_conflict = $.noConflict(true); </script> <script src="theme-build/js/main.js"></script> <script type="text/javascript"> function TypeaheadCtrl($scope) { $scope.selected = undefined; $scope.searchData = <%= "[" %> <% @pages.each do |file_name, page| %> <% if not page[:blocks].empty? %> <% page[:blocks].each do |block| %> <% file_path = block[:categories][0].to_s.gsub(' ', '_').downcase + '.html' %> <% file_id = "#"+block[:name].to_s %> <%= "{" %> <%= "\"title\": \""+block[:title].to_s+"\"," %> <%= "\"breadcrumb\": \""+block[:categories][0].to_s+" > "+block[:title]+"\"," %> <%= "\"path\": \""+file_path+file_id+"\"" %> <%= "}," %> <% end %> <% end %> <% end %> <%= "{}]" %>; $scope.onSelect = function ($item, $model, $label) { window.location.replace($item.path); }; } </script> <script type="text/ng-template" id="customTemplate.html"> <a href="{{match.model.path}}"> <p class="cortana-search-title">{{match.model.title}}</p> <p class="cortana-search-path">{{match.model.breadcrumb}}</p> </a> </script> <% if @config['js_include'].to_s.strip.length != 0 %> <% @config['js_include'].each do |js| %> <script type="text/javascript" src="<%= js %>"></script> <% end %> <% end %> <!-- Source Components --> <% if @config['components_include'].to_s.strip.length != 0 %> <% @config['components_include'].each do |component| %> <link rel="import" href="<%= component %>"> <% end %> <% end %> </body> </html>
    yorthehunter/humblekit
    vendor/assets/bower_components/Cortana/_footer.html
    HTML
    mit
    2,093
    // // rbLinkedList.h // rbLinkedList // // Created by Ryan Bemowski on 4/6/15. // #pragma once #include <string> struct Node { int key; Node *next; }; class rbLinkedList { public: /** Constructor for the rbLinkedList class. */ rbLinkedList(); /** Deconstructor for the rbLinkedList class. */ ~rbLinkedList(); /** Determine if the collection is empty or not. * @return: A bool that will be true if the collection is empty and false * otherwise. */ bool IsEmpty(); /** Determine the number of nodes within the linked list. * @return: An integer that represents the number of nodes between the head * and tail nodes. */ int Size(); void AddKey(int key); void RemoveKey(int key); std::string ToString(); private: Node *h_; Node *z_; };
    rrbemo/cppLinkedList
    ccpLinkedList/rbLinkedList.h
    C
    mit
    835
    // // KAAppDelegate.h // UIViewController-KeyboardAdditions // // Created by CocoaPods on 02/03/2015. // Copyright (c) 2014 Andrew Podkovyrin. All rights reserved. // #import <UIKit/UIKit.h> @interface KAAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
    podkovyrin/UIViewController-KeyboardAdditions
    Example/UIViewController-KeyboardAdditions/KAAppDelegate.h
    C
    mit
    315
    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Basic Example</title> <link rel="stylesheet" href="css/base.css" /> <script src="../../asset/react/react.js"></script> <script src="../../asset/react/react-dom.js"></script> <script src="../../asset/react/browser.min.js"></script> <script src="js/app/index.jsx" type="text/babel"></script> </head> <body> <h1>React 允许将代码封装成组件(component),然后像插入普通 HTML 标签一样,在网页中插入这个组件。React.createClass 方法就用于生成一个组件类</h1> <h1>组件的属性可以在组件类的 this.props 对象上获取</h1> <h1>添加组件属性,有一个地方需要注意,就是 class 属性需要写成 className ,for 属性需要写成 htmlFor ,这是因为 class 和 for 是 JavaScript 的保留字。</h1> <div id="message"></div> </body> </html>
    MR03/exercise-test-demo
    demo/demo004/003.html
    HTML
    mit
    921
    using System.Collections.ObjectModel; using System.ComponentModel; using GalaSoft.MvvmLight.Command; namespace Treehopper.Mvvm.ViewModels { /// <summary> /// A delegate called when the selected board changes /// </summary> /// <param name="sender">The caller</param> /// <param name="e">The new selected board</param> public delegate void SelectedBoardChangedEventHandler(object sender, SelectedBoardChangedEventArgs e); /// <summary> /// A delegate called when the selected board has connected /// </summary> /// <param name="sender">The caller</param> /// <param name="e">The connected board</param> public delegate void BoardConnectedEventHandler(object sender, BoardConnectedEventArgs e); /// <summary> /// A delegate called when the selected board has disconnected /// </summary> /// <param name="sender">The caller</param> /// <param name="e">The disconnected board</param> public delegate void BoardDisconnectedEventHandler(object sender, BoardDisconnectedEventArgs e); /// <summary> /// Base interface for the selector view model /// </summary> public interface ISelectorViewModel : INotifyPropertyChanged { /// <summary> /// Get the collection of boards /// </summary> ObservableCollection<TreehopperUsb> Boards { get; } /// <summary> /// Whether the board selection can be changed /// </summary> bool CanChangeBoardSelection { get; set; } /// <summary> /// The currently selected board /// </summary> TreehopperUsb SelectedBoard { get; set; } /// <summary> /// Occurs when the window closes /// </summary> RelayCommand WindowClosing { get; set; } /// <summary> /// Occurs when the connection occurs /// </summary> RelayCommand ConnectCommand { get; set; } /// <summary> /// Connect button text /// </summary> string ConnectButtonText { get; set; } /// <summary> /// Close command /// </summary> RelayCommand CloseCommand { get; set; } /// <summary> /// Board selection changed /// </summary> event SelectedBoardChangedEventHandler OnSelectedBoardChanged; /// <summary> /// Board connected /// </summary> event BoardConnectedEventHandler OnBoardConnected; /// <summary> /// Board disconnected /// </summary> event BoardDisconnectedEventHandler OnBoardDisconnected; } }
    treehopper-electronics/treehopper-sdk
    NET/Demos/WPF/DeviceManager/ViewModels/ISelectorViewModel.cs
    C#
    mit
    2,665
    import React from 'react'; import ReactDOM from 'react-dom'; import componentOrElement from 'react-prop-types/lib/componentOrElement'; import ownerDocument from './utils/ownerDocument'; import getContainer from './utils/getContainer'; /** * The `<Portal/>` component renders its children into a new "subtree" outside of current component hierarchy. * You can think of it as a declarative `appendChild()`, or jQuery's `$.fn.appendTo()`. * The children of `<Portal/>` component will be appended to the `container` specified. */ let Portal = React.createClass({ displayName: 'Portal', propTypes: { /** * A Node, Component instance, or function that returns either. The `container` will have the Portal children * appended to it. */ container: React.PropTypes.oneOfType([ componentOrElement, React.PropTypes.func ]), /** * Classname to use for the Portal Component */ className: React.PropTypes.string }, componentDidMount() { this._renderOverlay(); }, componentDidUpdate() { this._renderOverlay(); }, componentWillReceiveProps(nextProps) { if (this._overlayTarget && nextProps.container !== this.props.container) { this._portalContainerNode.removeChild(this._overlayTarget); this._portalContainerNode = getContainer(nextProps.container, ownerDocument(this).body); this._portalContainerNode.appendChild(this._overlayTarget); } }, componentWillUnmount() { this._unrenderOverlay(); this._unmountOverlayTarget(); }, _mountOverlayTarget() { if (!this._overlayTarget) { this._overlayTarget = document.createElement('div'); if (this.props.className) { this._overlayTarget.className = this.props.className; } this._portalContainerNode = getContainer(this.props.container, ownerDocument(this).body); this._portalContainerNode.appendChild(this._overlayTarget); } }, _unmountOverlayTarget() { if (this._overlayTarget) { this._portalContainerNode.removeChild(this._overlayTarget); this._overlayTarget = null; } this._portalContainerNode = null; }, _renderOverlay() { let overlay = !this.props.children ? null : React.Children.only(this.props.children); // Save reference for future access. if (overlay !== null) { this._mountOverlayTarget(); this._overlayInstance = ReactDOM.unstable_renderSubtreeIntoContainer( this, overlay, this._overlayTarget ); } else { // Unrender if the component is null for transitions to null this._unrenderOverlay(); this._unmountOverlayTarget(); } }, _unrenderOverlay() { if (this._overlayTarget) { ReactDOM.unmountComponentAtNode(this._overlayTarget); this._overlayInstance = null; } }, render() { return null; }, getMountNode(){ return this._overlayTarget; }, getOverlayDOMNode() { if (!this.isMounted()) { throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.'); } if (this._overlayInstance) { return ReactDOM.findDOMNode(this._overlayInstance); } return null; } }); export default Portal;
    HPate-Riptide/react-overlays
    src/Portal.js
    JavaScript
    mit
    3,227
    dojo.provide("plugins.dijit.SyncDialog"); // HAS A dojo.require("dijit.Dialog"); dojo.require("dijit.form.Button"); dojo.require("dijit.form.ValidationTextBox"); // INHERITS dojo.require("plugins.core.Common"); dojo.declare( "plugins.dijit.SyncDialog", [ dijit._Widget, dijit._Templated, plugins.core.Common ], { //Path to the template of this widget. templatePath: dojo.moduleUrl("plugins", "dijit/templates/syncdialog.html"), // OR USE @import IN HTML TEMPLATE cssFiles : [ dojo.moduleUrl("plugins", "dijit/css/syncdialog.css") ], // Calls dijit._Templated.widgetsInTemplate widgetsInTemplate : true, // PARENT plugins.workflow.Apps WIDGET parentWidget : null, // DISPLAYED MESSAGE message : null, //////}} constructor : function(args) { console.log("SyncDialog.constructor args:"); console.dir({args:args}); // LOAD CSS this.loadCSS(); }, postCreate : function() { //////console.log("SyncDialog.postCreate plugins.dijit.SyncDialog.postCreate()"); this.startup(); }, startup : function () { ////console.log("SyncDialog.startup plugins.dijit.SyncDialog.startup()"); ////console.log("SyncDialog.startup this.parentWidget: " + this.parentWidget); this.inherited(arguments); // SET UP DIALOG this.setDialogue(); // SET KEY LISTENER this.setKeyListener(); // ADD CSS NAMESPACE CLASS FOR TITLE CSS STYLING this.setNamespaceClass("syncDialog"); }, setKeyListener : function () { dojo.connect(this.dialog, "onkeypress", dojo.hitch(this, "handleOnKeyPress")); }, handleOnKeyPress: function (event) { var key = event.charOrCode; console.log("SyncDialog.handleOnKeyPress key: " + key); if ( key == null ) return; event.stopPropagation(); if ( key == dojo.keys.ESCAPE ) this.hide(); }, setNamespaceClass : function (ccsClass) { // ADD CSS NAMESPACE CLASS dojo.addClass(this.dialog.domNode, ccsClass); dojo.addClass(this.dialog.titleNode, ccsClass); dojo.addClass(this.dialog.closeButtonNode, ccsClass); }, show: function () { // SHOW THE DIALOGUE this.dialog.show(); this.message.focus(); }, hide: function () { // HIDE THE DIALOGUE this.dialog.hide(); }, doEnter : function(type) { // RUN ENTER CALLBACK IF 'ENTER' CLICKED console.log("SyncDialog.doEnter plugins.dijit.SyncDialog.doEnter()"); var inputs = this.validateInputs(["message", "details"]); console.log("SyncDialog.doEnter inputs:"); console.dir({inputs:inputs}); if ( ! inputs ) { console.log("SyncDialog.doEnter inputs is null. Returning"); return; } // RESET this.message.set('value', ""); this.details.value = ""; // HIDE this.hide(); // DO CALLBACK this.dialog.enterCallback(inputs); }, validateInputs : function (keys) { console.log("Hub.validateInputs keys: "); console.dir({keys:keys}); var inputs = new Object; this.isValid = true; for ( var i = 0; i < keys.length; i++ ) { console.log("Hub.validateInputs Doing keys[" + i + "]: " + keys[i]); inputs[keys[i]] = this.verifyInput(keys[i]); } console.log("Hub.validateInputs inputs: "); console.dir({inputs:inputs}); if ( ! this.isValid ) return null; return inputs; }, verifyInput : function (input) { console.log("Aws.verifyInput input: "); console.dir({this_input:this[input]}); var value = this[input].value; console.log("Aws.verifyInput value: " + value); var className = this.getClassName(this[input]); console.log("Aws.verifyInput className: " + className); if ( className ) { console.log("Aws.verifyInput this[input].isValid(): " + this[input].isValid()); if ( ! value || ! this[input].isValid() ) { console.log("Aws.verifyInput input " + input + " value is empty. Adding class 'invalid'"); dojo.addClass(this[input].domNode, 'invalid'); this.isValid = false; } else { console.log("SyncDialog.verifyInput value is NOT empty. Removing class 'invalid'"); dojo.removeClass(this[input].domNode, 'invalid'); return value; } } else { if ( input.match(/;/) || input.match(/`/) ) { console.log("SyncDialog.verifyInput value is INVALID. Adding class 'invalid'"); dojo.addClass(this[input], 'invalid'); this.isValid = false; return null; } else { console.log("SyncDialog.verifyInput value is VALID. Removing class 'invalid'"); dojo.removeClass(this[input], 'invalid'); return value; } } return null; }, doCancel : function() { // RUN CANCEL CALLBACK IF 'CANCEL' CLICKED ////console.log("SyncDialog.doCancel plugins.dijit.SyncDialog.doCancel()"); this.dialog.cancelCallback(); this.dialog.hide(); }, setDialogue : function () { // APPEND DIALOG TO DOCUMENT document.body.appendChild(this.dialog.domNode); this.dialog.parentWidget = this; // AVOID this._fadeOutDeferred NOT DEFINED ERROR this._fadeOutDeferred = function () {}; }, load : function (args) { console.log("SyncDialog.load args:"); console.dir({args:args}); if ( args.title ) { console.log("SyncDialog.load SETTING TITLE: " + args.title); this.dialog.set('title', args.title); } this.headerNode.innerHTML = args.header; if (args.message) this.message.set('value', args.message); if (args.details) this.details.value = args.details; //if (args.details) this.details.innerHTML(args.details); this.dialog.enterCallback = args.enterCallback; this.show(); } });
    agua/aguadev
    html/plugins/dijit/SyncDialog.js
    JavaScript
    mit
    5,315
    namespace TraktApiSharp.Objects.Basic.Json.Factories { using Objects.Basic.Json.Reader; using Objects.Basic.Json.Writer; using Objects.Json; internal class CommentLikeJsonIOFactory : IJsonIOFactory<ITraktCommentLike> { public IObjectJsonReader<ITraktCommentLike> CreateObjectReader() => new CommentLikeObjectJsonReader(); public IArrayJsonReader<ITraktCommentLike> CreateArrayReader() => new CommentLikeArrayJsonReader(); public IObjectJsonWriter<ITraktCommentLike> CreateObjectWriter() => new CommentLikeObjectJsonWriter(); } }
    henrikfroehling/TraktApiSharp
    Source/Lib/TraktApiSharp/Objects/Basic/Json/Factories/CommentLikeJsonIOFactory.cs
    C#
    mit
    583
    package com.sdl.selenium.extjs3.button; import com.sdl.selenium.bootstrap.button.Download; import com.sdl.selenium.extjs3.ExtJsComponent; import com.sdl.selenium.web.SearchType; import com.sdl.selenium.web.WebLocator; public class DownloadLink extends ExtJsComponent implements Download { public DownloadLink() { setClassName("DownloadLink"); setTag("a"); } public DownloadLink(WebLocator container) { this(); setContainer(container); } public DownloadLink(WebLocator container, String text) { this(container); setText(text, SearchType.EQUALS); } /** * Wait for the element to be activated when there is deactivation mask on top of it * * @param seconds time */ @Override public boolean waitToActivate(int seconds) { return getXPath().contains("ext-ux-livegrid") || super.waitToActivate(seconds); } /** * if WebDriverConfig.isSilentDownload() is true, se face silentDownload, is is false se face download with AutoIT. * Download file with AutoIT, works only on FireFox. SilentDownload works FireFox and Chrome * Use only this: button.download("C:\\TestSet.tmx"); * return true if the downloaded file is the same one that is meant to be downloaded, otherwise returns false. * * @param fileName e.g. "TestSet.tmx" */ @Override public boolean download(String fileName) { openBrowse(); return executor.download(fileName, 10000L); } private void openBrowse() { executor.browse(this); } }
    sdl/Testy
    src/main/java/com/sdl/selenium/extjs3/button/DownloadLink.java
    Java
    mit
    1,642
    angular.module('perCapita.controllers', []) .controller('AppCtrl', ['$scope', '$rootScope', '$ionicModal', '$timeout', '$localStorage', '$ionicPlatform', 'AuthService', function ($scope, $rootScope, $ionicModal, $timeout, $localStorage, $ionicPlatform, AuthService) { $scope.loginData = $localStorage.getObject('userinfo', '{}'); $scope.reservation = {}; $scope.registration = {}; $scope.loggedIn = false; if (AuthService.isAuthenticated()) { $scope.loggedIn = true; $scope.username = AuthService.getUsername(); } // Create the login modal that we will use later $ionicModal.fromTemplateUrl('templates/login.html', { scope: $scope }).then(function (modal) { $scope.modal = modal; }); // Triggered in the login modal to close it $scope.closeLogin = function () { $scope.modal.hide(); }; // Open the login modal $scope.login = function () { $scope.modal.show(); }; // Perform the login action when the user submits the login form $scope.doLogin = function () { console.log('Doing login', $scope.loginData); $localStorage.storeObject('userinfo', $scope.loginData); AuthService.login($scope.loginData); $scope.closeLogin(); }; $scope.logOut = function () { AuthService.logout(); $scope.loggedIn = false; $scope.username = ''; }; $rootScope.$on('login:Successful', function () { $scope.loggedIn = AuthService.isAuthenticated(); $scope.username = AuthService.getUsername(); }); $ionicModal.fromTemplateUrl('templates/register.html', { scope: $scope }).then(function (modal) { $scope.registerform = modal; }); $scope.closeRegister = function () { $scope.registerform.hide(); }; $scope.register = function () { $scope.registerform.show(); }; $scope.doRegister = function () { console.log('Doing registration', $scope.registration); $scope.loginData.username = $scope.registration.username; $scope.loginData.password = $scope.registration.password; AuthService.register($scope.registration); $timeout(function () { $scope.closeRegister(); }, 1000); }; $rootScope.$on('registration:Successful', function () { $localStorage.storeObject('userinfo', $scope.loginData); }); }]) .controller('FavoriteDetailsController', ['$scope', '$rootScope', '$state', '$stateParams', 'Favorites', function ($scope, $rootScope, $state, $stateParams, Favorites) { $scope.showFavButton = false; // Lookup favorites for a given user id Favorites.findById({id: $stateParams.id}) .$promise.then( function (response) { $scope.city = response; }, function (response) { $scope.message = "Error: " + response.status + " " + response.statusText; } ); }]) .controller('HomeController', ['$scope', 'perCapitaService', '$stateParams', '$rootScope', 'Favorites', '$ionicPlatform', '$cordovaLocalNotification', '$cordovaToast', function ($scope, perCapitaService, $stateParams, $rootScope, Favorites, $ionicPlatform, $cordovaLocalNotification, $cordovaToast) { $scope.showFavButton = $rootScope.currentUser; $scope.controlsData = {skills: $rootScope.skills}; // Look up jobs data $scope.doLookup = function () { $rootScope.skills = $scope.controlsData.skills; perCapitaService.lookup($scope.controlsData.skills); }; // Post process the jobs data, by adding Indeeds link and calculating jobsPer1kPeople and jobsRank $scope.updatePerCapitaData = function () { $scope.cities = perCapitaService.response.data.docs; var arrayLength = $scope.cities.length; for (var i = 0; i < arrayLength; i++) { var obj = $scope.cities[i]; obj.jobsPer1kPeople = Math.round(obj.totalResults / obj.population * 1000); obj.url = "https://www.indeed.com/jobs?q=" + $scope.controlsData.skills + "&l=" + obj.city + ", " + obj.state; } // rank jobs var sortedObjs; if (perCapitaService.isSkills) { sortedObjs = _.sortBy($scope.cities, 'totalResults').reverse(); } else { sortedObjs = _.sortBy($scope.cities, 'jobsPer1kPeople').reverse(); } $scope.cities.forEach(function (element) { element.jobsRank = sortedObjs.indexOf(element) + 1; }); if (!$scope.$$phase) { $scope.$apply(); } $rootScope.cities = $scope.cities; console.log("Loaded " + arrayLength + " results.") }; perCapitaService.registerObserverCallback($scope.updatePerCapitaData); $scope.addToFavorites = function () { delete $scope.city._id; delete $scope.city._rev; $scope.city.customerId = $rootScope.currentUser.id Favorites.create($scope.city); $ionicPlatform.ready(function () { $cordovaLocalNotification.schedule({ id: 1, title: "Added Favorite", text: $scope.city.city }).then(function () { console.log('Added Favorite ' + $scope.city.city); }, function () { console.log('Failed to add Favorite '); }); $cordovaToast .show('Added Favorite ' + $scope.city.city, 'long', 'center') .then(function (success) { // success }, function (error) { // error }); }); } if ($stateParams.id) { console.log("param " + $stateParams.id); $scope.city = $rootScope.cities.filter(function (obj) { return obj._id === $stateParams.id; })[0]; console.log($scope.city); } else { $scope.doLookup(); } }]) .controller('AboutController', ['$scope', function ($scope) { }]) .controller('FavoritesController', ['$scope', '$rootScope', '$state', 'Favorites', '$ionicListDelegate', '$ionicPopup', function ($scope, $rootScope, $state, Favorites, $ionicListDelegate, $ionicPopup) { $scope.shouldShowDelete = false; /*$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) { console.log("State changed: ", toState); if(toState.name === "app.favorites") $scope.refreshItems(); });*/ $scope.refreshItems = function () { if ($rootScope.currentUser) { Favorites.find({ filter: { where: { customerId: $rootScope.currentUser.id } } }).$promise.then( function (response) { $scope.favorites = response; console.log("Got favorites"); }, function (response) { console.log(response); }); } else { $scope.message = "You are not logged in" } } $scope.refreshItems(); $scope.toggleDelete = function () { $scope.shouldShowDelete = !$scope.shouldShowDelete; console.log($scope.shouldShowDelete); } $scope.deleteFavorite = function (favoriteid) { var confirmPopup = $ionicPopup.confirm({ title: '<h3>Confirm Delete</h3>', template: '<p>Are you sure you want to delete this item?</p>' }); confirmPopup.then(function (res) { if (res) { console.log('Ok to delete'); Favorites.deleteById({id: favoriteid}).$promise.then( function (response) { $scope.favorites = $scope.favorites.filter(function (el) { return el.id !== favoriteid; }); $state.go($state.current, {}, {reload: false}); // $window.location.reload(); }, function (response) { console.log(response); $state.go($state.current, {}, {reload: false}); }); } else { console.log('Canceled delete'); } }); $scope.shouldShowDelete = false; } }]) ;
    vjuylov/percapita-mobile
    www/js/controllers/controllers.js
    JavaScript
    mit
    8,105
    # VBA.ModernTheme ### Windows Phone Colour Palette and<p>Colour Selector using WithEvents Version 1.0.1 The *Windows Phone Theme Colours* is a tight, powerful, and well balanced palette. This tiny Microsoft Access application makes it a snap to select and pick a value. And it doubles as an intro to implementing *WithEvents*, one of Access' hidden gems. ![General](https://raw.githubusercontent.com/GustavBrock/VBA.ModernTheme/master/images/ModernThemeHeader.png) Full documentation is found here: ![EE Logo](https://raw.githubusercontent.com/GustavBrock/VBA.ModernTheme/master/images/EE%20Logo.png) [Create Windows Phone Colour Palette and Selector using WithEvents](https://www.experts-exchange.com/articles/29554/Create-Windows-Phone-Colour-Palette-and-Selector-using-WithEvents.html?preview=yawJg2wkMzc%3D) <hr> *If you wish to support my work or need extended support or advice, feel free to:* <p> [<img src="https://raw.githubusercontent.com/GustavBrock/VBA.ModernTheme/master/images/BuyMeACoffee.png">](https://www.buymeacoffee.com/gustav/)
    GustavBrock/VBA.ModernTheme
    README.md
    Markdown
    mit
    1,060
    var http = require("http"); var querystring = require("querystring"); // 核心模块 var SBuffer=require("../tools/SBuffer"); var common=require("../tools/common"); var zlib=require("zlib"); var redis_pool=require("../tools/connection_pool"); var events = require('events'); var util = require('util'); function ProxyAgent(preHeaders,preAnalysisFields,logName){ this.headNeeds = preHeaders||""; this.preAnalysisFields = preAnalysisFields||""; this.AnalysisFields = {}; this.logName=logName||""; this.response=null; this.reqConf={}; this.retData=[]; this.redis =null; // redis {} redis_key events.EventEmitter.call(this); } /** * 获取服务配置信息 * @param 服务名 * @return object */ ProxyAgent.prototype.getReqConfig = function(logName){ var _self=this; var Obj={}; Obj=Config[logName]; Obj.logger=Analysis.getLogger(logName); Obj.name=logName; return Obj; } ProxyAgent.prototype.doRequest=function(_req,_res){ var _self=this; _self.reqConf=_self.getReqConfig(this.logName); logger.debug('进入'+_self.reqConf.desc+"服务"); var header_obj =this.packageHeaders(_req.headers,this.headNeeds); var url_obj = url.parse(request.url, true); var query_obj = url_obj.query; var postData = request.body|| ""; // 获取请求参数 _res.setHeader("Content-Type", config.contentType); _res.setHeader(config.headerkey, config.headerval); var opts=_self.packData(header_obj,query_obj,postData); logger.debug(header_obj.mobileid +_self.reqConf.desc+ '接口参数信息:'+opts[0].path +" data:"+ opts[1]); if(typeof(postData) =="object" && postData.redis_key.length>0){ this.getRedis(opts[0],opts[1]); } else{ this.httpProxy(opts[0],opts[1]); } } /** * 封装get post接口 * @param headers * @param query * @param body * @return [] */ ProxyAgent.prototype.packData=function(headers,query,body){ var _self=this; //resType 解释 ""==>GET,"body"==>POST,"json"==>特殊poi,"raw"==>原始数据 var type=_self.reqConf.resType || ""; body = body || ""; var len=0; var query_str=""; var body_str=""; if(type==""){ query=common.extends(query,headers); query_str = querystring.stringify(query, '&', '='); } else if(type=="body"){ body=common.extends(body,headers); body_str = querystring.stringify(body, '&', '='); len=body_str.length; if(body.redis_key){ this.redis={}; this.redis.redis_key=body.redis_key; } } else if(type=="json"){ query=common.extends(query,headers); query_str = 'json='+querystring.stringify(query, '&', '='); } else if(type=="raw"){ len=body.length; body_str=body; } var actionlocation = headers.actionlocation || ""; if(actionlocation==""){ actionlocation=query.actionlocation||""; } var opts=_self.getRequestOptions(len,actionlocation); opts.path+=((opts.path.indexOf("?")>=0)?"&":"?")+query_str; return [opts,body_str]; } /** * 获取请求头信息 * @param len数据长度 * @param actiontion 通用访问地址 * @return object 头信息 */ ProxyAgent.prototype.getRequestOptions=function(len,actionlocation){ var _self=this; var options = { //http请求参数设置 host: _self.reqConf.host, // 远端服务器域名 port: _self.reqConf.port, // 远端服务器端口号 path: _self.reqConf.path||"", headers : {'Connection' : 'keep-alive'} }; if(actionlocation.length>0){ options.path=actionlocation; } var rtype= _self.reqConf.reqType || ""; if(rtype.length>0){ options.headers['Content-Type']=rtype; } if(len>0){ options.headers['Content-Length']=len; } return options; } ProxyAgent.prototype.getRedisOptions=function(options,actionlocation){ var obj={}; return obj; } /** * 获取头部信息进行封装 * @param request.headers * @param need fields ;split with ',' * @return object headers */ ProxyAgent.prototype.packageHeaders = function(headers) { var fields=arguments[1]||""; var query_obj = {}; var reqip = headers['x-real-ip'] || '0'; // 客户端请求的真实ip地址 var forward = headers['x-forwarded-for'] || '0'; // 客户端请求来源 var osversion = headers['osversion'] || '0';// 客户端系统 var devicemodel = headers['devicemodel'] || '0';// 客户端型号 var manufacturername = headers['manufacturername'] || '0';// 制造厂商 var actionlocation = headers['actionlocation']; // 请求后台地址 var dpi = headers['dpi'] || '2.0';// 密度 var imsi = headers['imsi'] || '0'; // 客户端imsi var mobileid = headers['mobileid'] || '0'; // 客户端mibileid var version = headers['version'] || '0';// 客户端版本version var selflon = headers['selflon'] || '0';// 经度 var selflat = headers['selflat'] || '0';// 维度 var uid = headers['uid'] || '0'; // 犬号 var radius=headers['radius']||'0';//误差半径 var platform=headers['platform']||"";//平台 ios ,android var gender= headers['gender'] || '0'; query_obj.gender = gender; query_obj.reqip = reqip; query_obj.forward = forward; query_obj.osversion = osversion; query_obj.devicemodel = devicemodel; query_obj.manufacturername = manufacturername; query_obj.actionlocation = actionlocation; query_obj.dpi = dpi; query_obj.imsi = imsi; query_obj.mobileid = mobileid; query_obj.version = version; query_obj.selflon = selflon; query_obj.selflat = selflat; query_obj.uid = uid; query_obj.radius=radius; query_obj.platform=platform; if(fields.length > 0){ var afields = fields.split(","); var newObj = {}; for(var i = 0; i < afields.length ; i ++){ newObj[afields[i]] = query_obj[afields[i]] || ""; } return newObj; } else{ return query_obj; } } /** * http 请求代理 * @param options 远程接口信息 * @param reqData 请求内容 req.method== get时一般为空 */ ProxyAgent.prototype.httpProxy = function (options,reqData){ var _self=this; var TongjiObj={}; var req = http.request(options, function(res) { TongjiObj.statusCode = res.statusCode ||500; var tmptime=Date.now(); TongjiObj.restime = tmptime; TongjiObj.resEnd =tmptime; TongjiObj.ends = tmptime; TongjiObj.length = 0; TongjiObj.last = tmptime; var sbuffer=new SBuffer(); res.setEncoding("utf-8"); res.on('data', function (trunk) { sbuffer.append(trunk); }); res.on('end', function () { TongjiObj.resEnd = Date.now(); //doRequestCB(response, {"data":sbuffer.toString(),"status":res.statusCode},TongjiObj,redisOpt); _self.emmit("onDone",sbuffer,TongjiObj); }); }); req.setTimeout(timeout,function(){ req.emit('timeOut',{message:'have been timeout...'}); }); req.on('error', function(e) { TongjiObj.statusCode=500; _self.emmit("onDone","",500,TongjiObj); }); req.on('timeOut', function(e) { req.abort(); TongjiObj.statusCode=500; TongjiObj.last = Date.now(); _self.emmit("onDone","",500,TongjiObj); }); req.end(reqData); } /** * 设置缓存 * @param redis_key * @param redis_time * @param resultBuffer */ ProxyAgent.prototype.setRedis = function (redis_key, redis_time, resultBuffer) { redis_pool.acquire(function(err, client) { if (!err) { client.setex(redis_key, redis_time, resultBuffer, function(err, repliy) { redis_pool.release(client); // 链接使用完毕释放链接 }); logger.debug(redis_key + '设置缓存数据成功!'); } else { writeLogs.logs(Analysis.getLogger('error'), 'error', { msg : 'redis_general保存数据到redis缓存数据库时链接redis数据库异常', err : 14 }); logger.debug(redis_key + '设置缓存数据失败!'); } }); } /** * 从缓存中获取数据,如果获取不到,则请求后台返回的数据返回给客户端 并且将返回的数据设置到redis缓存 * redis_key通过self变量中取 * @param options * @param reqData */ ProxyAgent.prototype.getRedis = function ( options, reqData) { var _self=this; var redis_key=this.redis.redis_key || ""; redis_pool.acquire(function(err, client) { if (!err) { client.get(redis_key, function(err, date) { redis_pool.release(client) // 用完之后释放链接 if (!err && date != null) { var resultBuffer = new Buffer(date); _self.response.statusCode = 200; _self.response.setHeader("Content-Length", resultBuffer.length); _self.response.write(resultBuffer); // 以二进制流的方式输出数据 _self.response.end(); logger.debug(redis_key + '通用接口下行缓存数据:' + date); } else { _self.httpProxy(options, reqData); } }); } else { _self.httpProxy(options, reqData); } }); } /** * 输出gzip数据 * response 内置 * @param resultBuffer */ ProxyAgent.prototype.gzipOutPut = function (resultBuffer){ var _self=this; zlib.gzip(resultBuffer, function(code, buffer){ // 对服务器返回的数据进行压缩 if (code != null) { // 如果正常结束 logger.debug('压缩成功,压缩前:'+resultBuffer.length+',压缩后:'+buffer.length); _self.response.setHeader('Content-Encoding', 'gzip'); //压缩标志 } else { buffer = new Buffer( '{"msg":["服务器返回数据非JSON格式"]}'); _self.response.statusCode=500; } _self.response.setHeader("Content-Length", buffer.length); _self.response.write(buffer); _self.response.end(); }); } /** * 请求完毕处理 * @param buffer type buffer/string * @param status 请求http状态 * @param tongji object统计对象 */ ProxyAgent.prototype.onDone =function(buffer,status){ var tongji=arguments[2] ||""; var _self=this; var resultStr = typeof(buffer)=="object"?buffer.toString():buffer; if(this.reqConf.isjson==1){ var resultObj = common.isJson( resultStr, _self.reqConf.logName); // 判断返回结果是否是json格式 if (resultObj) { // 返回结果是json格式 resultStr = JSON.stringify(resultObj); _self.response.statusCode = status; } else { resultStr = '{"msg":["gis服务器返回数据非JSON格式"]}'; _self.response.statusCode = 500; } } else{ _self.response.statusCode = status; } var resultBuffer = new Buffer(resultStr); if(tongji!=""){ tongji.ends = Date.now(); tongji.length = resultBuffer.length; } if(resultBuffer.length > 500 ){ //压缩输出 _self.gzipOutPut(resultBuffer); }else{ _self.response.setHeader("Content-Length", resultBuffer.length); _self.response.write(resultBuffer); // 以二进制流的方式输出数据 _self.response.end(); } if(tongji!=""){ tongji.last= Date.now(); tongji=common.extends(tongji,_self.preAnalysisFields); logger.debug('耗时:' + (tongji.last - tongji.start)+'ms statusCode='+status); writeLogs.logs(poiDetailServer,'poiDetailServer',obj); } }); ProxyAgent.prototype.onDones =function(buffer,status){ var tongji=arguments[2] ||""; this.retData.push([buffer,status,tongji]; }); ProxyAgent.prototype.dealDones =function(){ var tongji=arguments[2] ||""; this.retData.push([buffer,status,tongji]; }); //ProxyAgent 从event 集成 //utils.inherit(ProxyAgent,event); exports.ProxyAgent=ProxyAgent;
    RazarDessun/fastProxy
    test/test_timeout2.js
    JavaScript
    mit
    11,087
    --- layout: post title: "Hello World" image: feature: nomadsland.jpg date: 2016-09-19 20:24:11 +0200 categories: personal, coding --- I enjoy tinkering - building little electronic gadgets and apps - especially if it has something to do with [cryptocurrencies]. Currently my day-job is building Bitcoin infrastructure. The purpose of this weblog is to record the progress on various projects outside my normal scope of work. Working with software, I seem to hit a lot of **"Hmmm, I wonder how this works?"** moments. Hopefully these pages provide some useful information to somebody working on and wondering about the same things. ## Begin I'm a fan of the maxim "Done is better than perfect" so my current goal is to get this blog up and running as quickly as possible. Instead of wondering about which software or host to use, I decided to power it with [Jekyll] and host it on [Github pages]. I already have a code/text editor I like using and git is already part of my daily workflow so it seemed like a natural fit. I picked a theme I liked but just as I got something that looked vaguely OK, I ran into the first **"Hmmm, I wonder"** moment. It turns out Jekyll/Github pages deployments are not intuitive. [Jekyll's Basic Usage Guide] does a pretty good job of explaining how to get up and running locally, but trying to find GH-Pages deployment instructions (and failing miserably) made me realise things don't work as I'd expect. ## Jekyll & Github Jekyll uses plugins and templates to help authors perform dynamic blog-related things like themeing, categorising and indexing posts, generating "about" pages and more. `jekyll build` produces a static "render" of the blog at the time it is called so that you can just upload the HTML/JS/CSS contents of the generated `_site` directory to a server that serves static content. You could host it on dropbox if you wanted to, there's no server-side scripts like PHP or Rails to generate content from data stored in a database. `_site` gets destroyed and re-created every time you call `jekyll build` and it is listed in `.gitignore` so it's not part of the repo, so how in the world do you tell Github to serve the contents of `_site`? Am I supposed to create a manual deploy script that adds `_site` to a repo and push that? ## Hmmm, I wonder... So which is it? Turns out you simply push your jekyll source repo to `master`. You don't even need to call `jekyll build`. Your site just magically appears on Github. That leaves only two possibilities: 1. Either Github calls `jekyll build` and serves the `_site` directory after each push, or 2. Github is running `jekyll serve` to generate content every request. Turns out it's the latter. Github actually runs Jekyll, and supports [some Jekyll plugins]. ## Done So, one "git push" later and these pages should be live! *"Done is better than perfect"* [BitX]: https://www.bitx.co/ [cryptocurrencies]: https://en.wikipedia.org/wiki/Cryptocurrency [jekyll]: https://jekyllrb.com [Jekyll's Basic Usage Guide]: https://jekyllrb.com/docs/usage/ [Github pages]: https://pages.github.com/ [some Jekyll plugins]: https://help.github.com/articles/adding-jekyll-plugins-to-a-github-pages-site/
    carelvwyk/carelvwyk.github.io
    _posts/2016-09-19-hello-world.markdown
    Markdown
    mit
    3,210
    <?php namespace RobotsTxtParser; class CommentsTest extends \PHPUnit\Framework\TestCase { /** * @dataProvider generateDataForTest */ public function testRemoveComments($robotsTxtContent) { $parser = new RobotsTxtParser($robotsTxtContent); $rules = $parser->getRules('*'); $this->assertEmpty($rules, 'expected remove comments'); } /** * @dataProvider generateDataFor2Test */ public function testRemoveCommentsFromValue($robotsTxtContent, $expectedDisallowValue) { $parser = new RobotsTxtParser($robotsTxtContent); $rules = $parser->getRules('*'); $this->assertNotEmpty($rules, 'expected data'); $this->assertArrayHasKey('disallow', $rules); $this->assertNotEmpty($rules['disallow'], 'disallow expected'); $this->assertEquals($expectedDisallowValue, $rules['disallow'][0]); } /** * Generate test case data * @return array */ public function generateDataForTest() { return array( array( " User-agent: * #Disallow: /tech " ), array( " User-agent: * Disallow: #/tech " ), array( " User-agent: * Disal # low: /tech " ), array( " User-agent: * Disallow#: /tech # ds " ), ); } /** * Generate test case data * @return array */ public function generateDataFor2Test() { return array( array( "User-agent: * Disallow: /tech #comment", 'disallowValue' => '/tech', ), ); } }
    bopoda/robots-txt-parser
    tests/RobotsTxtParser/CommentsTest.php
    PHP
    mit
    1,834
    /* * The MIT License * * Copyright 2016 njacinto. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.nfpj.utils.arrays; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.function.Predicate; import org.nfpj.utils.predicates.TruePredicate; /** * * @author njacinto * @param <T> the type of object being returned by this iterator */ public class ArrayFilterIterator<T> implements Iterator<T> { protected static final int END_OF_ITERATION = -2; // private int nextIndex; // protected final T[] array; protected final Predicate<T> predicate; // <editor-fold defaultstate="expanded" desc="Constructors"> /** * Creates an instance of this class * * @param array the array from where this instance will extract the elements * @param predicate the filter to be applied to the elements */ public ArrayFilterIterator(T[] array, Predicate<T> predicate) { this(array, predicate, -1); } /** * * @param array * @param predicate * @param prevIndex */ protected ArrayFilterIterator(T[] array, Predicate<T> predicate, int prevIndex) { this.array = array!=null ? array : ArrayUtil.empty(); this.predicate = predicate!=null ? predicate : TruePredicate.getInstance(); this.nextIndex = getNextIndex(prevIndex); } // </editor-fold> // <editor-fold defaultstate="expanded" desc="Public methods"> /** * {@inheritDoc} */ @Override public boolean hasNext() { return nextIndex != END_OF_ITERATION; } /** * {@inheritDoc} */ @Override public T next() { if(nextIndex==END_OF_ITERATION){ throw new NoSuchElementException("The underline collection has no elements."); } int index = nextIndex; nextIndex = getNextIndex(nextIndex); return array[index]; } /** * {@inheritDoc} */ @Override public void remove() { throw new UnsupportedOperationException("The iterator doesn't allow changes."); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Protected methods"> /** * Searches for the next element that matches the filtering conditions and * returns it. * * @param currIndex * @return the next element that matches the filtering conditions or null * if no more elements are available */ protected int getNextIndex(int currIndex){ if(currIndex!=END_OF_ITERATION){ for(int i=currIndex+1; i<array.length; i++){ if(predicate.test(array[i])){ return i; } } } return END_OF_ITERATION; } // </editor-fold> }
    njacinto/Utils
    src/main/java/org/nfpj/utils/arrays/ArrayFilterIterator.java
    Java
    mit
    3,840
    --- layout: post title: slacker로 slack bot 만들기 comments: true tags: - python - slack - 봇 - slacker --- &nbsp;&nbsp;&nbsp; 멘토님께서 라인의 `notification`을 이용해서 봇 만든것을 보고 따라 만들었다. 봇 만들고 싶은데 핑계가 없어서 고민하다가 동아리에서 `slack`을 쓰기 때문에 슬랙봇을 만들어보기로 했다. 스터디하는 사람들을 대상으로 커밋한지 얼마나 되었는지 알려주는 용도로 만들었다. 결과물은 아래와 같다. <img src="/images/commit-bell.jpeg" alt="클린 코드를 위한 테스트 주도 개발" style="width: 480px; margin-left: auto; margin-right: auto; "/> &nbsp;&nbsp;&nbsp; 먼저 봇을 등록해야한다. [Slack Apps](https://studytcp.slack.com/apps)의 우측 상단에 `Build`를 눌러서 등록을 한다. 아래와 같은 화면이 나온다. 다른 팀에게 공개하지 않을 것이라서 `Something just for my team`을 선택했다. ![slackbot 등록]({{ site.url }}/images/slackbot_0.png) &nbsp;&nbsp;&nbsp; 두 번째 `Bots`를 선택한다. ![slackbot 등록]({{ site.url }}/images/slackbot_1.png) &nbsp;&nbsp;&nbsp; 적절한 설정을 하고 `token`을 꼭 기억(복사)해 두자. &nbsp;&nbsp;&nbsp; pip로 필요한 것을 설치하자. [github3.py](https://github3py.readthedocs.io/en/master/), [slacker](https://pypi.python.org/pypi/slacker/), datetime, pytz를 사용했다. <pre>$ pip install slacker $ pip install github3.py $ pip install datetime $ pip install pytz</pre> &nbsp;&nbsp;&nbsp; 전체 코드는 아래와 같다. ```python from slacker import Slacker import github3 import datetime import pytz local_tz = pytz.timezone('Asia/Seoul') token = 'xoxb-발급받은-토큰' slack = Slacker(token) channels = ['#채널1', '#채널2'] def post_to_channel(message): slack.chat.post_message(channels[0], message, as_user=True) def get_repo_last_commit_delta_time(owner, repo): repo = github3.repository(owner, repo) return repo.pushed_at.astimezone(local_tz) def get_delta_time(last_commit): now = datetime.datetime.now(local_tz) delta = now - last_commit return delta.days def main(): members = ( # (git 계정 이름, repo 이름, 이름), # [...] ) reports = [] for owner, repo, name in members: last_commit = get_repo_last_commit_delta_time(owner, repo) delta_time = get_delta_time(last_commit) if(delta_time == 0): reports.append('*%s* 님은 오늘 커밋을 하셨어요!' % (name)) else: reports.append('*%s* 님은 *%s* 일이나 커밋을 안하셨어요!' % (name, delta_time)) post_to_channel('\n 안녕 친구들! 과제 점검하는 커밋벨이야 호호 \n' + '\n'.join(reports)) if __name__ == '__main__': main() ``` ## **해결하지 못한 것** * **X-RateLimit-Limit 올리기** &nbsp;&nbsp;&nbsp; 테스트 때문에 꽤 많이 돌리다 보니까 횟수제한에 걸렸다. 에러 메시지는 아래와 같다. <pre>github3.models.GitHubError: 403 API rate limit exceeded for 106.246.181.100. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)</pre> &nbsp;&nbsp;&nbsp; 찾아보니까 하나의 IP당 한 시간에 보낼 수 있는 횟수가 정해져 있다고 한다. 출력해 보면 아래와 같다. `X-RateLimit-Limit`은 기본이 60이고 최대 5000으로 올릴 수 있다는데 헤더 수정을 어떻게 해야할지 모르겠다. 사실 이거 해결한다고 시간이 꽤 지나버려서 해결(?)이 되었다. <pre>[...] Status: 403 Forbidden X-RateLimit-Limit: 60 X-RateLimit-Remaining: 0 X-RateLimit-Reset: 1475913003 [...]</pre> * **이 코드를 어디서 돌려야 하는가.** &nbsp;&nbsp;&nbsp; 하루에 2-3번? 정도 해당 채널에 알림을 보낼 것이다. 사실 동아리 서버 쓰면 된다고는 하는데.. 개인 서버를 쓰고는 싶고 그렇다고 AWS 쓰자니 별로 하는것도 없는데 달마다 치킨 값을 헌납해야해서 고민이다. ## **참고자료** * [https://corikachu.github.io/articles/python/python-slack-bot-slacker](https://corikachu.github.io/articles/python/python-slack-bot-slacker) * [https://www.fullstackpython.com/blog/build-first-slack-bot-python.html](https://www.fullstackpython.com/blog/build-first-slack-bot-python.html) * [https://godoftyping.wordpress.com/2015/04/19/python-%EB%82%A0%EC%A7%9C-%EC%8B%9C%EA%B0%84%EA%B4%80%EB%A0%A8-%EB%AA%A8%EB%93%88/](https://godoftyping.wordpress.com/2015/04/19/python-%EB%82%A0%EC%A7%9C-%EC%8B%9C%EA%B0%84%EA%B4%80%EB%A0%A8-%EB%AA%A8%EB%93%88/)
    hyesun03/hyesun03.github.io
    _posts/2016-10-08-slackbot.md
    Markdown
    mit
    4,664
    import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class IosHeart extends React.Component { render() { if(this.props.bare) { return <g> <path d="M359.385,80C319.966,80,277.171,97.599,256,132.8C234.83,97.599,192.034,80,152.615,80C83.647,80,32,123.238,32,195.779 c0,31.288,12.562,71.924,40.923,105.657c28.359,33.735,45.229,51.7,100.153,88C228,425.738,256,432,256,432s28-6.262,82.924-42.564 c54.923-36.3,71.794-54.265,100.153-88C467.438,267.703,480,227.067,480,195.779C480,123.238,428.353,80,359.385,80z"></path> </g>; } return <IconBase> <path d="M359.385,80C319.966,80,277.171,97.599,256,132.8C234.83,97.599,192.034,80,152.615,80C83.647,80,32,123.238,32,195.779 c0,31.288,12.562,71.924,40.923,105.657c28.359,33.735,45.229,51.7,100.153,88C228,425.738,256,432,256,432s28-6.262,82.924-42.564 c54.923-36.3,71.794-54.265,100.153-88C467.438,267.703,480,227.067,480,195.779C480,123.238,428.353,80,359.385,80z"></path> </IconBase>; } };IosHeart.defaultProps = {bare: false}
    fbfeix/react-icons
    src/icons/IosHeart.js
    JavaScript
    mit
    1,031
    <?php /* $Id$ osCommerce, Open Source E-Commerce Solutions http://www.oscommerce.com Copyright (c) 2010 osCommerce Released under the GNU General Public License */ require('includes/application_top.php'); require(DIR_WS_LANGUAGES . $language . '/' . FILENAME_SPECIALS); $breadcrumb->add(NAVBAR_TITLE, tep_href_link(FILENAME_SPECIALS)); require(DIR_WS_INCLUDES . 'template_top.php'); ?> <h1><?php echo HEADING_TITLE; ?></h1> <div class="contentContainer"> <div class="contentText"> <?php // BOF Enable & Disable Categories $specials_query_raw = "select p.products_id, pd.products_name, p.products_price, p.products_tax_class_id, p.products_image, s.specials_new_products_price from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_SPECIALS . " s, " . TABLE_CATEGORIES . " c, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c where c.categories_status='1' and p.products_id = p2c.products_id and p2c.categories_id = c.categories_id and p.products_status = '1' and p.products_id = s.products_id and pd.products_id = s.products_id and pd.language_id = '" . (int)$languages_id . "' and s.status = '1' order by s.specials_date_added DESC"; // EOF Enable & Disable Categories //$specials_query_raw = "select p.products_id, pd.products_name, p.products_price, p.products_tax_class_id, p.products_image, s.specials_new_products_price from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_SPECIALS . " s where p.products_status = '1' and s.products_id = p.products_id and p.products_id = pd.products_id and pd.language_id = '" . (int)$languages_id . "' and s.status = '1' order by s.specials_date_added DESC"; $specials_split = new splitPageResults($specials_query_raw, MAX_DISPLAY_SPECIAL_PRODUCTS); if (($specials_split->number_of_rows > 0) && ((PREV_NEXT_BAR_LOCATION == '1') || (PREV_NEXT_BAR_LOCATION == '3'))) { ?> <div> <span style="float: right;"><?php echo TEXT_RESULT_PAGE . ' ' . $specials_split->display_links(MAX_DISPLAY_PAGE_LINKS, tep_get_all_get_params(array('page', 'info', 'x', 'y'))); ?></span> <span><?php echo $specials_split->display_count(TEXT_DISPLAY_NUMBER_OF_SPECIALS); ?></span> </div> <br /> <?php } ?> <table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr> <?php $row = 0; $specials_query = tep_db_query($specials_split->sql_query); while ($specials = tep_db_fetch_array($specials_query)) { $row++; echo '<td align="center" width="33%"><a href="' . tep_href_link(FILENAME_PRODUCT_INFO, 'products_id=' . $specials['products_id']) . '">' . tep_image(DIR_WS_IMAGES . $specials['products_image'], $specials['products_name'], SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT) . '</a><br /><a href="' . tep_href_link(FILENAME_PRODUCT_INFO, 'products_id=' . $specials['products_id']) . '">' . $specials['products_name'] . '</a><br /><del>' . $currencies->display_price($specials['products_price'], tep_get_tax_rate($specials['products_tax_class_id'])) . '</del><br /><span class="productSpecialPrice">' . $currencies->display_price($specials['specials_new_products_price'], tep_get_tax_rate($specials['products_tax_class_id'])) . '</span></td>' . "\n"; if ((($row / 3) == floor($row / 3))) { ?> </tr> <tr> <?php } } ?> </tr> </table> <?php if (($specials_split->number_of_rows > 0) && ((PREV_NEXT_BAR_LOCATION == '2') || (PREV_NEXT_BAR_LOCATION == '3'))) { ?> <br /> <div> <span style="float: right;"><?php echo TEXT_RESULT_PAGE . ' ' . $specials_split->display_links(MAX_DISPLAY_PAGE_LINKS, tep_get_all_get_params(array('page', 'info', 'x', 'y'))); ?></span> <span><?php echo $specials_split->display_count(TEXT_DISPLAY_NUMBER_OF_SPECIALS); ?></span> </div> <?php } ?> </div> </div> <?php require(DIR_WS_INCLUDES . 'template_bottom.php'); require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
    gliss/oscommerce-bootstrap
    catalog/specials.php
    PHP
    mit
    3,956
    --- layout: home title: JARVARS comments: false ---
    jarvars/jarvars.github.io
    index.html
    HTML
    mit
    52
    {% extends "admin/base.html" %} {% load i18n %} {% block title %}{{ title }} | {% trans 'lab purchase management' %}{% endblock %} {% block branding %} <h1 id="site-name">{% trans 'LabHamster' %}</h1> {% endblock %} {% block nav-global %}{% endblock %}
    graik/labhamster
    site_templates/admin/base_site.html
    HTML
    mit
    256
    /* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockitousage.verification; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.atMostOnce; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import java.util.List; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.exceptions.base.MockitoException; import org.mockito.exceptions.verification.MoreThanAllowedActualInvocations; import org.mockito.exceptions.verification.NoInteractionsWanted; import org.mockitoutil.TestBase; public class AtMostXVerificationTest extends TestBase { @Mock private List<String> mock; @Test public void shouldVerifyAtMostXTimes() throws Exception { mock.clear(); mock.clear(); verify(mock, atMost(2)).clear(); verify(mock, atMost(3)).clear(); try { verify(mock, atMostOnce()).clear(); fail(); } catch (MoreThanAllowedActualInvocations e) { } } @Test public void shouldWorkWithArgumentMatchers() throws Exception { mock.add("one"); verify(mock, atMost(5)).add(anyString()); try { verify(mock, atMost(0)).add(anyString()); fail(); } catch (MoreThanAllowedActualInvocations e) { } } @Test public void shouldNotAllowNegativeNumber() throws Exception { try { verify(mock, atMost(-1)).clear(); fail(); } catch (MockitoException e) { assertEquals("Negative value is not allowed here", e.getMessage()); } } @Test public void shouldPrintDecentMessage() throws Exception { mock.clear(); mock.clear(); try { verify(mock, atMostOnce()).clear(); fail(); } catch (MoreThanAllowedActualInvocations e) { assertEquals("\nWanted at most 1 time but was 2", e.getMessage()); } } @Test public void shouldNotAllowInOrderMode() throws Exception { mock.clear(); InOrder inOrder = inOrder(mock); try { inOrder.verify(mock, atMostOnce()).clear(); fail(); } catch (MockitoException e) { assertEquals("AtMost is not implemented to work with InOrder", e.getMessage()); } } @Test public void shouldMarkInteractionsAsVerified() throws Exception { mock.clear(); mock.clear(); verify(mock, atMost(3)).clear(); verifyNoMoreInteractions(mock); } @Test public void shouldDetectUnverifiedInMarkInteractionsAsVerified() throws Exception { mock.clear(); mock.clear(); undesiredInteraction(); verify(mock, atMost(3)).clear(); try { verifyNoMoreInteractions(mock); fail(); } catch (NoInteractionsWanted e) { assertThat(e).hasMessageContaining("undesiredInteraction("); } } private void undesiredInteraction() { mock.add(""); } }
    ze-pequeno/mockito
    src/test/java/org/mockitousage/verification/AtMostXVerificationTest.java
    Java
    mit
    3,400
    <?php declare(strict_types=1); namespace Atk4\Ui\Demos; use Atk4\Ui\Crud; use Atk4\Ui\UserAction\ExecutorFactory; // Test for hasOne Lookup as dropdown control. /** @var \Atk4\Ui\App $app */ require_once __DIR__ . '/../init-app.php'; $model = new Product($app->db); $model->addCondition($model->fieldName()->name, '=', 'Mustard'); // use default. $app->getExecutorFactory()->useTriggerDefault(ExecutorFactory::TABLE_BUTTON); $edit = $model->getUserAction('edit'); $edit->callback = function (Product $model) { return $model->product_category_id->getTitle() . ' - ' . $model->product_sub_category_id->getTitle(); }; $crud = Crud::addTo($app); $crud->setModel($model, [$model->fieldName()->name]);
    atk4/ui
    demos/_unit-test/lookup.php
    PHP
    mit
    709