code
stringlengths
4
1.01M
language
stringclasses
2 values
require_relative 'base' module Terjira module Client class StatusCategory < Base class << self def all @all_statuscategory ||= file_cache.fetch("all") do resp = api_get "statuscategory" resp.map { |category| build(category) } end end def file_cache Terjira::FileCache.new("resource/statuscategory", 60 * 60 * 48) end end end end end
Java
## 1.3.3 - 修复 #782 默认主题配置颜色选择透明度无法修改问题 - 修复 #774 部分情况 TOC 链接错误问题 ## 1.3.2 - 新增博客导出至 Hugo - 评论新增 [Waline](https://waline.js.org) 和 [Valine](https://valine.js.org) 的支持 - 修复 #748 代码高亮的问题 ## 1.3.1 - 修复配置 COS 之后上传图片会带上当前域名的问题 #737 - 修复代码块不显示最后一行的问题 #740 - 修复后台分享部分二级分类不显示的问题 ## 1.3.0 - 新增文章删除回收站 #734 - 新增标题自动转换成拼音URL #735 ## 1.2.8 - 修复标签管理无法打开的问题 #642 - 修复 is_public 属性值错误 ## 1.2.7 - 修复分类没有文章导致首页 500 问题 #641 - 修复主题管理主题配置显示错误问题 - 用户管理禁止删除有文章数的用户 ## 1.2.6 - 重构文章分类获取逻辑 - 文章更新后增加最新文章列表的缓存清除 - 修复接口允许自己选择自己为父分类的问题 #637 ## 1.2.5 - 修复有时候发布文章会变成编辑文章的问题 #628 ## 1.2.4 - 修复腾讯云 OSS 上传失败问题 #611 - 修复基本设置信息不显示,主题无法修改的错误 #612 - 修复投稿者可以内网登录的问题 #613 - 修复后台文章列表时间问题 #615 - 修复后台 icon 不显示问题 #618 - 修复 yarn 安装错误问题 #624 ## 1.2.3 - 登录新增自动登录选项 #571 - 修复用户管理用户最近登录时间不准确问题 #591 - 修复编辑文章插入内链格式错误问题 #599 - 修复编辑文章时间显示异常问题 #607 - 修复腾讯云 COS 支持后台选项丢失问题 #608 - 修复后台页面打开异常问题 #583 ## 1.2.2 - 重新修复后台无法访问问题 ## 1.2.1 - 紧急修复后台无法访问问题 ## 1.2.0 - 后台使用 React 16, TypeScript, Antd, Mobx 进行重构 - 新增上传到腾讯云 COS 支持 - 修复模板转义错误 #565 - 修复后台文章列表分类选择分页错误 ## 1.1.2 - 修复 Markdown 文件导入错误 #549 - 修复重复文件上传的报错问题 #555 - 修复主题自定义 404 错误页问题 #554 - 修复文章发布作者选择问题 - 修复标签页文章列表显示问题 - 修复多个安全漏洞 ## 1.1.1 - 修复安装时参数错误 #545 - 移除部分数据表的本地缓存功能 ## 1.1.0 - 新增 RSS 定时导入支持 - 新增上传到 AWS S3 支持 - 安装界面增加邮箱输入支持 - 默认主题修改了目录样式 - 修复 sitemap 缺少文章和页面数据的问题 - 修复 hexo 导出标签出错问题 #541 - 修复推送文章更新报错并增加推送封面图支持 #540 - 修复中文分类跳转的问题 #437 - 修复又拍云上传的兼容问题 ## 1.0.4 - 后台文章分类勾选新增父子分类联动 - 修复 0.x 迁移导致的一些BUG - 修复 #520 simtemap.xml 生成问题 - 修复 #530 后台用户删除问题 - 修复导入数据可能导致的安全问题 ## 1.0.3 - 增加 DISALLOW_FILE_EDIT 禁止编辑主题配置项 - 修复文件上传跨磁盘报错的问题 - 修复子分类列表页404问题 ## 1.0.2 - 增加内网登录支持,具体实现可参考[如何实现内网登录](https://github.com/firekylin/firekylin/wiki/%E9%97%AE%E9%A2%98%E8%A7%A3%E7%AD%94#%E5%A6%82%E4%BD%95%E5%AE%9E%E7%8E%B0%E5%86%85%E7%BD%91%E7%99%BB%E5%BD%95) - 模板分类数据增加二级分类输出 - 修复 #512 数据导出错误 - 修复 #508 评论模块数据相同问题 ## 1.0.1 - 发布文章支持选择作者功能 - 修复 #502,七牛上传等多个上传问题 - 修复 #503 主题保存问题 ## 1.0.0 - 使用 ThinkJS3 重构项目,0.x 进入版本维护阶段 ## 0.15.18 - 新增 LDAP 登录支持 - 修复文件上传的安全漏洞 ## 0.15.17 - 新增 [sm.ms](http://sm.ms) 上传支持 - 新增 [gitalk](https://gitalk.github.io/) 评论支持 - referrer 校验仅校验主域部分,避免端口和协议不同导致的 `REFERRER_ERROR` 报错 - 安装允许 MySQL 密码为空 - 修复封面图片无法删除问题 - 修复 Markdown 上传导致的安全问题 ## 0.15.16 - 新增阿里云 OSS 上传支持 - 修复上传文件报错问题 - 修复标签缓存不生效问题 ## 0.15.15 - 修复多个安全漏洞 ## 0.15.14 - 更新 ThinkJS 依赖修复安全漏洞 - 修复默认主题图片懒加载失败问题 - Fix #431 后台搜索分页逻辑错误 - Fix #427 后台用户邮箱修改判断错误 - Fix #436 `qrcode-react` 升级造成的安装错误 ## 0.15.13 - 代码高亮优化 - BUG 修复 ## 0.15.12 - 新增文章/页面前台预览功能 - 新增文章封面图选项 - 新增找回密码功能 - Fix #395 编辑器自适应高度 - Fix 导出不正常错误 ## 0.15.11 - 紧急修复安装时无法输入数据库账号问题 - Hexo 导出增强 ## 0.15.10 - 新增导出到 WordPress, Hexo, Jekyll 功能 - 新增代码行号显示,语言显示以及高亮功能 - Fix #355 表格数学公式不生效以及摘要问题 - Fix #375 页面单选复选框被隐藏问题 - Fix #380 安装时自动创建数据库 - Fix #382 编辑器高度问题 ## 0.15.9 - 新增数学公式的支持,目前暂不支持后台实时渲染,语法为: - ``` `$E=mc^2$` ``` - ` ```math E=mc^2 ``` ` - 增加导出功能,目前支持导出为 Markdown - 重构安装流程,检测到旧数据后不删除,安装时自动检测 `utf8mb4` - 新增 Hello World 文章数据 - Fix #338 Markdown导入错误 - Fix #345 部分不可见字符导致 RSS 错误 ## 0.15.8 - 紧急修复 0.15.7 版本安装包没有默认主题的BUG ## 0.15.7 - 【重要】使用自定义主题者请将主题内 `tag.html` 中的 `for tag in list` 改为 `for tag in tags` - #306 - 文章页模板增加作者邮箱数据 - 菜单管理增加编辑功能 - 后台文章列表增加分类过滤功能 - 增加 `opensearch.xml` 支持 - #306 模板增加 `lastPostList` 最近文章和 `tags` 标签列表变量 - Fix #279 首页去除 stc 编译修复后台修改模板文件不生效问题 - Fix 推送 `modelInstance` 定义报错失败问题 - Fix #303,#304 自定义首页不生效 - Fix 标签、分类为空时页面500问题 - Fix 文章页面标签跳转失败问题 ## 0.15.6 - 增加审核通过时更新发文时间功能 #259 - 增加文章自动生成摘要功能 #252 - 默认主题增加图片懒加载 #278 - 优化 SEO `sitemap.xml` 增加多个页面索引 #280 - 优化 URL 图片抓取功能,支持上传到又拍/七牛 - Fix #263 增加公安部备案选项 - Fix 搜索页分页 #269 - Fix #286 禁止删除当前用户 ## 0.15.5 - 【重要】修复主题接口安全漏洞 - 修复文章和页面地址相同时无法添加内容的问题 - Fix #254 编辑主题内容丢失问题 - Fix #248 WordPress 导入失败问题 - 第三方评论增加网易云跟帖的支持 ## 0.15.4 - 修复编辑修改文章时会发布文章的权限判断问题 - 修复文章推送报错问题 - Fix #249 Ghost 导入失败 - Fix #225 #246 编辑器增加字数统计显示以及同滚功能 ## 0.15.3 - Fix #240 粘贴图片无后缀 - 图片上传增加类型和 5M 大小限制 - 第三方评论增加畅言的支持 - 修复草稿在列表显示顺序错误的问题,之前的草稿需要自行设置下发布时间 ## 0.15.2 - Fix #230 后台编辑用户无法显示用户数据 - Fix 文章内单引号被替换成双引号的问题 - Fix 文章推送失败的问题 - 编译取消默认模板的代码压缩 ## 0.15.1 - 导入数据增加 Hexo, Jekyll, Markdown文件的支持,使用方法参考:<https://github.com/firekylin/firekylin/wiki/导入> - 修复页面编辑无法编辑内容的问题 ## 0.15.0 - 增加 `/sitemap.xml` 和 `/rss.xml` 两个路由 - 增加后台在线编辑主题功能 - 增加自定义错误页功能 - 页面编辑增加自定义主题功能 - 增加自定义站点首页功能,使用方法参考:https://imnerd.org/firekylin-custom-index.html ## 0.14.4 - 紧急修复页面管理无法保存问题 ## 0.14.3 - 提前祝大家鸡年大吉! - 用户列表新增文章数和评论数显示 - 文章列表增加是否公开显示,去除更新日期显示仅显示发布日期,未来发布的文章会显示为“即将发布”,文章排序从之前的 ID 排序修改为发布日期排序 - 阅读设置新增是否关闭自动生成TOC功能,关闭后在文章内可添加 `<!--toc-->` 再次开启 - Fix RSS数据错误问题 - Fix WP文件导入错误 - Fix 安装后无默认导航菜单数据 - Fix 安装后 `npm start` 账号错误 - Fix 主题设置编辑器不正常问题 ## 0.14.2 - 🎄祝大家圣诞快乐 - Fix #198 后台本地上传文件报错 - Fix #199 RSS 页面报错 - Fix #200 非管理员无法修改密码的问题 ## 0.14.1 - 增加阅读设置,支持设置每页显示文章数和聚合输出方式 - 修改 TOC 目录在文章开头插入,并在摘要中忽略 TOC - 修改编辑器工具栏样式支持拖拽调整编辑器长度 - 修改编辑器弹窗增加 ESC 和 Enter 快捷键支持 ## 0.14.0 - 增加从 Ghost 导入功能 - 增加在线更新功能 - 增加 CHANGELOG 并在更新提示中增加链接方便查看 - 编辑器上传图片增加上传中提示 - 重构了上传文件和导入博客数据的代码 - Fix #186 删除用户后文章页面列表显示不正常 ## 0.13.1 - 紧急修复七牛/又拍图片无法上传的BUG - 后台编辑器增加粘贴上传功能 - 概况页增加"新增页面"和"修改外观"的链接 ## 0.13.0 - 上传图片增加七牛和又拍云的支持 - 后台代码分块压缩减少首次加载的 JS 体积,提升加载速度 - 修复获取主题接口有其它非正常主题文件时的BUG - Fix #139 修复文章审核通过报错的问题 - Fix #177 修复评论设置不更新的问题 - Fix #173 允许非管理员上传图片 - 修复新建文章页面推送网站不显示的问题 - 修复清空标题编辑页面不正常的BUG
Java
Date.CultureInfo = { /* Culture Name */ name: "fr-FR", englishName: "French (France)", nativeName: "français (France)", /* Day Name Strings */ dayNames: ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"], abbreviatedDayNames: ["dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam."], shortestDayNames: ["di", "lu", "ma", "me", "je", "ve", "sa"], firstLetterDayNames: ["d", "l", "m", "m", "j", "v", "s"], /* Month Name Strings */ monthNames: ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"], abbreviatedMonthNames: ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."], /* AM/PM Designators */ amDesignator: "", pmDesignator: "", firstDayOfWeek: 1, twoDigitYearMax: 2029, /** * The dateElementOrder is based on the order of the * format specifiers in the formatPatterns.DatePattern. * * Example: <pre> shortDatePattern dateElementOrder ------------------ ---------------- "M/d/yyyy" "mdy" "dd/MM/yyyy" "dmy" "yyyy-MM-dd" "ymd" </pre> * * The correct dateElementOrder is required by the parser to * determine the expected order of the date elements in the * string being parsed. */ dateElementOrder: "dmy", /* Standard date and time format patterns */ formatPatterns: { shortDate: "dd/MM/yyyy", longDate: "dddd d MMMM yyyy", shortTime: "HH:mm", longTime: "HH:mm:ss", fullDateTime: "dddd d MMMM yyyy HH:mm:ss", sortableDateTime: "yyyy-MM-ddTHH:mm:ss", universalSortableDateTime: "yyyy-MM-dd HH:mm:ssZ", rfc1123: "ddd, dd MMM yyyy HH:mm:ss GMT", monthDay: "d MMMM", yearMonth: "MMMM yyyy" }, /** * NOTE: If a string format is not parsing correctly, but * you would expect it parse, the problem likely lies below. * * The following regex patterns control most of the string matching * within the parser. * * The Month name and Day name patterns were automatically generated * and in general should be (mostly) correct. * * Beyond the month and day name patterns are natural language strings. * Example: "next", "today", "months" * * These natural language string may NOT be correct for this culture. * If they are not correct, please translate and edit this file * providing the correct regular expression pattern. * * If you modify this file, please post your revised CultureInfo file * to the Datejs Forum located at http://www.datejs.com/forums/. * * Please mark the subject of the post with [CultureInfo]. Example: * Subject: [CultureInfo] Translated "da-DK" Danish(Denmark) * * We will add the modified patterns to the master source files. * * As well, please review the list of "Future Strings" section below. */ regexPatterns: { jan: /^janv(\.|ier)?/i, feb: /^févr(\.|ier)?/i, mar: /^mars/i, apr: /^avr(\.|il)?/i, may: /^mai/i, jun: /^juin/i, jul: /^juil(\.|let)?/i, aug: /^août/i, sep: /^sept(\.|embre)?/i, oct: /^oct(\.|obre)?/i, nov: /^nov(\.|embre)?/i, dec: /^déc(\.|embre)?/i, sun: /^di(\.|m|m\.|anche)?/i, mon: /^lu(\.|n|n\.|di)?/i, tue: /^ma(\.|r|r\.|di)?/i, wed: /^me(\.|r|r\.|credi)?/i, thu: /^je(\.|u|u\.|di)?/i, fri: /^ve(\.|n|n\.|dredi)?/i, sat: /^sa(\.|m|m\.|edi)?/i, future: /^next/i, past: /^last|past|prev(ious)?/i, add: /^(\+|aft(er)?|from|hence)/i, subtract: /^(\-|bef(ore)?|ago)/i, yesterday: /^yes(terday)?/i, today: /^t(od(ay)?)?/i, tomorrow: /^tom(orrow)?/i, now: /^n(ow)?/i, millisecond: /^ms|milli(second)?s?/i, second: /^sec(ond)?s?/i, minute: /^mn|min(ute)?s?/i, hour: /^h(our)?s?/i, week: /^w(eek)?s?/i, month: /^m(onth)?s?/i, day: /^d(ay)?s?/i, year: /^y(ear)?s?/i, shortMeridian: /^(a|p)/i, longMeridian: /^(a\.?m?\.?|p\.?m?\.?)/i, timezone: /^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt|utc)/i, ordinalSuffix: /^\s*(st|nd|rd|th)/i, timeContext: /^\s*(\:|a(?!u|p)|p)/i }, timezones: [{name:"UTC", offset:"-000"}, {name:"GMT", offset:"-000"}, {name:"EST", offset:"-0500"}, {name:"EDT", offset:"-0400"}, {name:"CST", offset:"-0600"}, {name:"CDT", offset:"-0500"}, {name:"MST", offset:"-0700"}, {name:"MDT", offset:"-0600"}, {name:"PST", offset:"-0800"}, {name:"PDT", offset:"-0700"}] }; /******************** ** Future Strings ** ******************** * * The following list of strings may not be currently being used, but * may be incorporated into the Datejs library later. * * We would appreciate any help translating the strings below. * * If you modify this file, please post your revised CultureInfo file * to the Datejs Forum located at http://www.datejs.com/forums/. * * Please mark the subject of the post with [CultureInfo]. Example: * Subject: [CultureInfo] Translated "da-DK" Danish(Denmark)b * * English Name Translated * ------------------ ----------------- * about about * ago ago * date date * time time * calendar calendar * show show * hourly hourly * daily daily * weekly weekly * bi-weekly bi-weekly * fortnight fortnight * monthly monthly * bi-monthly bi-monthly * quarter quarter * quarterly quarterly * yearly yearly * annual annual * annually annually * annum annum * again again * between between * after after * from now from now * repeat repeat * times times * per per * min (abbrev minute) min * morning morning * noon noon * night night * midnight midnight * mid-night mid-night * evening evening * final final * future future * spring spring * summer summer * fall fall * winter winter * end of end of * end end * long long * short short */
Java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <base href="../../../" /> <script src="list.js"></script> <script src="page.js"></script> <link type="text/css" rel="stylesheet" href="page.css" /> </head> <body> <h1>[name]</h1> <p class="desc">Class representing a 3D [link:https://en.wikipedia.org/wiki/Vector_space vector]. A 3D vector is an ordered triplet of numbers (labeled x, y, and z), which can be used to represent a number of things, such as: </p> <ul> <li> A point in 3D space. </li> <li> A direction and length in 3D space. In three.js the length will always be the [link:https://en.wikipedia.org/wiki/Euclidean_distance Euclidean distance] (straight-line distance) from (0, 0, 0) to (x, y, z) and the direction is also measured from (0, 0, 0) towards (x, y, z). </li> <li> Any arbitrary ordered triplet of numbers. </li> </ul> <p> There are other things a 3D vector can be used to represent, such as momentum vectors and so on, however these are the most common uses in three.js. </p> <h2>Example</h2> <code> var a = new THREE.Vector3( 0, 1, 0 ); //no arguments; will be initialised to (0, 0, 0) var b = new THREE.Vector3( ); var d = a.distanceTo( b ); </code> <h2>Constructor</h2> <h3>[name]( [param:Float x], [param:Float y], [param:Float z] )</h3> <p> [page:Float x] - the x value of the vector. Default is *0*.<br /> [page:Float y] - the y value of the vector. Default is *0*.<br /> [page:Float z] - the z value of the vector. Default is *0*.<br /><br /> Creates a new [name]. </p> <h2>Properties</h2> <h3>[property:Boolean isVector3]</h3> <p> Used to check whether this or derived classes are Vector3s. Default is *true*.<br /><br /> You should not change this, as it is used internally for optimisation. </p> <h3>[property:Float x]</h3> <h3>[property:Float y]</h3> <h3>[property:Float z]</h3> <h2>Methods</h2> <h3>[method:this add]( [param:Vector3 v] )</h3> <p>Adds [page:Vector3 v] to this vector.</p> <h3>[method:this addScalar]( [param:Float s] )</h3> <p>Adds the scalar value s to this vector's [page:.x x], [page:.y y] and [page:.z z] values.</p> <h3>[method:this addScaledVector]( [param:Vector3 v], [param:Float s] )</h3> <p>Adds the multiple of [page:Vector3 v] and [page:Float s] to this vector.</p> <h3>[method:this addVectors]( [param:Vector3 a], [param:Vector3 b] )</h3> <p>Sets this vector to [page:Vector3 a] + [page:Vector3 b].</p> <h3>[method:this applyAxisAngle]( [param:Vector3 axis], [param:Float angle] )</h3> <p> [page:Vector3 axis] - A normalized [page:Vector3].<br /> [page:Float angle] - An angle in radians.<br /><br /> Applies a rotation specified by an axis and an angle to this vector. </p> <h3>[method:this applyEuler]( [param:Euler euler] )</h3> <p> Applies euler transform to this vector by converting the [page:Euler] object to a [page:Quaternion] and applying. </p> <h3>[method:this applyMatrix3]( [param:Matrix3 m] )</h3> <p>Multiplies this vector by [page:Matrix3 m]</p> <h3>[method:this applyMatrix4]( [param:Matrix4 m] )</h3> <p> Multiplies this vector (with an implicit 1 in the 4th dimension) and m, and divides by perspective. </p> <h3>[method:this applyQuaternion]( [param:Quaternion quaternion] )</h3> <p> Applies a [page:Quaternion] transform to this vector. </p> <h3>[method:Float angleTo]( [param:Vector3 v] )</h3> <p> Returns the angle between this vector and vector [page:Vector3 v] in radians. </p> <h3>[method:this ceil]()</h3> <p> The [page:.x x], [page:.y y] and [page:.z z] components of the vector are rounded up to the nearest integer value. </p> <h3>[method:this clamp]( [param:Vector3 min], [param:Vector3 max] )</h3> <p> [page:Vector3 min] - the minimum [page:.x x], [page:.y y] and [page:.z z] values.<br /> [page:Vector3 max] - the maximum [page:.x x], [page:.y y] and [page:.z z] values in the desired range<br /><br /> If this vector's x, y or z value is greater than the max vector's x, y or z value, it is replaced by the corresponding value. <br /><br /> If this vector's x, y or z value is less than the min vector's x, y or z value, it is replaced by the corresponding value. </p> <h3>[method:this clampLength]( [param:Float min], [param:Float max] )</h3> <p> [page:Float min] - the minimum value the length will be clamped to <br /> [page:Float max] - the maximum value the length will be clamped to<br /><br /> If this vector's length is greater than the max value, it is replaced by the max value. <br /><br /> If this vector's length is less than the min value, it is replaced by the min value. </p> <h3>[method:this clampScalar]( [param:Float min], [param:Float max] )</h3> <p> [page:Float min] - the minimum value the components will be clamped to <br /> [page:Float max] - the maximum value the components will be clamped to<br /><br /> If this vector's x, y or z values are greater than the max value, they are replaced by the max value. <br /><br /> If this vector's x, y or z values are less than the min value, they are replaced by the min value. </p> <h3>[method:Vector3 clone]()</h3> <p> Returns a new vector3 with the same [page:.x x], [page:.y y] and [page:.z z] values as this one. </p> <h3>[method:this copy]( [param:Vector3 v] )</h3> <p> Copies the values of the passed vector3's [page:.x x], [page:.y y] and [page:.z z] properties to this vector3. </p> <h3>[method:this cross]( [param:Vector3 v] )</h3> <p> Sets this vector to [link:https://en.wikipedia.org/wiki/Cross_product cross product] of itself and [page:Vector3 v]. </p> <h3>[method:this crossVectors]( [param:Vector3 a], [param:Vector3 b] )</h3> <p> Sets this vector to [link:https://en.wikipedia.org/wiki/Cross_product cross product] of [page:Vector3 a] and [page:Vector3 b]. </p> <h3>[method:Float distanceTo]( [param:Vector3 v] )</h3> <p>Computes the distance from this vector to [page:Vector3 v].</p> <h3>[method:Float manhattanDistanceTo]( [param:Vector3 v] )</h3> <p> Computes the [link:https://en.wikipedia.org/wiki/Taxicab_geometry Manhattan distance] from this vector to [page:Vector3 v]. </p> <h3>[method:Float distanceToSquared]( [param:Vector3 v] )</h3> <p> Computes the squared distance from this vector to [page:Vector3 v]. If you are just comparing the distance with another distance, you should compare the distance squared instead as it is slightly more efficient to calculate. </p> <h3>[method:this divide]( [param:Vector3 v] )</h3> <p>Divides this vector by [page:Vector3 v].</p> <h3>[method:this divideScalar]( [param:Float s] )</h3> <p> Divides this vector by scalar [page:Float s].<br /> Sets vector to *( 0, 0, 0 )* if *[page:Float s] = 0*. </p> <h3>[method:Float dot]( [param:Vector3 v] )</h3> <p> Calculate the [link:https://en.wikipedia.org/wiki/Dot_product dot product] of this vector and [page:Vector3 v]. </p> <h3>[method:Boolean equals]( [param:Vector3 v] )</h3> <p>Checks for strict equality of this vector and [page:Vector3 v].</p> <h3>[method:this floor]()</h3> <p>The components of the vector are rounded down to the nearest integer value.</p> <h3>[method:this fromArray]( [param:Array array], [param:Integer offset] )</h3> <p> [page:Array array] - the source array.<br /> [page:Integer offset] - ( optional) offset into the array. Default is 0.<br /><br /> Sets this vector's [page:.x x] value to be array[ offset + 0 ], [page:.y y] value to be array[ offset + 1 ] and [page:.z z] value to be array[ offset + 2 ]. </p> <h3>[method:this fromBufferAttribute]( [param:BufferAttribute attribute], [param:Integer index] )</h3> <p> [page:BufferAttribute attribute] - the source attribute.<br /> [page:Integer index] - index in the attribute.<br /><br /> Sets this vector's [page:.x x], [page:.y y] and [page:.z z] values from the [page:BufferAttribute attribute]. </p> <h3>[method:Float getComponent]( [param:Integer index] )</h3> <p> [page:Integer index] - 0, 1 or 2.<br /><br /> If index equals 0 returns the [page:.x x] value. <br /> If index equals 1 returns the [page:.y y] value. <br /> If index equals 2 returns the [page:.z z] value. </p> <h3>[method:Float length]()</h3> <p>Computes the [link:https://en.wikipedia.org/wiki/Euclidean_distance Euclidean length] (straight-line length) from (0, 0, 0) to (x, y, z).</p> <h3>[method:Float manhattanLength]()</h3> <p> Computes the [link:http://en.wikipedia.org/wiki/Taxicab_geometry Manhattan length] of this vector. </p> <h3>[method:Float lengthSq]()</h3> <p> Computes the square of the [link:https://en.wikipedia.org/wiki/Euclidean_distance Euclidean length] (straight-line length) from (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should compare the length squared instead as it is slightly more efficient to calculate. </p> <h3>[method:this lerp]( [param:Vector3 v], [param:Float alpha] )</h3> <p> [page:Vector3 v] - [page:Vector3] to interpolate towards.<br /> [page:Float alpha] - interpolation factor, typically in the closed interval [0, 1].<br /><br /> Linearly interpolate between this vector and [page:Vector3 v], where alpha is the percent distance along the line - alpha = 0 will be this vector, and alpha = 1 will be [page:Vector3 v]. </p> <h3>[method:this lerpVectors]( [param:Vector3 v1], [param:Vector3 v2], [param:Float alpha] )</h3> <p> [page:Vector3 v1] - the starting [page:Vector3].<br /> [page:Vector3 v2] - [page:Vector3] to interpolate towards.<br /> [page:Float alpha] - interpolation factor, typically in the closed interval [0, 1].<br /><br /> Sets this vector to be the vector linearly interpolated between [page:Vector3 v1] and [page:Vector3 v2] where alpha is the percent distance along the line connecting the two vectors - alpha = 0 will be [page:Vector3 v1], and alpha = 1 will be [page:Vector3 v2]. </p> <h3>[method:this max]( [param:Vector3 v] )</h3> <p> If this vector's x, y or z value is less than [page:Vector3 v]'s x, y or z value, replace that value with the corresponding max value. </p> <h3>[method:this min]( [param:Vector3 v] )</h3> <p> If this vector's x, y or z value is greater than [page:Vector3 v]'s x, y or z value, replace that value with the corresponding min value. </p> <h3>[method:this multiply]( [param:Vector3 v] )</h3> <p>Multiplies this vector by [page:Vector3 v].</p> <h3>[method:this multiplyScalar]( [param:Float s] )</h3> <p>Multiplies this vector by scalar [page:Float s].</p> <h3>[method:this multiplyVectors]( [param:Vector3 a], [param:Vector3 b] )</h3> <p>Sets this vector equal to [page:Vector3 a] * [page:Vector3 b], component-wise.</p> <h3>[method:this negate]()</h3> <p>Inverts this vector - i.e. sets x = -x, y = -y and z = -z.</p> <h3>[method:this normalize]()</h3> <p> Convert this vector to a [link:https://en.wikipedia.org/wiki/Unit_vector unit vector] - that is, sets it equal to the vector with the same direction as this one, but [page:.length length] 1. </p> <h3>[method:this project]( [param:Camera camera] )</h3> <p> [page:Camera camera] — camera to use in the projection.<br /><br /> [link:https://en.wikipedia.org/wiki/Vector_projection Projects] the vector with the camera. </p> <h3>[method:this projectOnPlane]( [param:Vector3 planeNormal] )</h3> <p> [page:Vector3 planeNormal] - A vector representing a plane normal.<br /><br /> [link:https://en.wikipedia.org/wiki/Vector_projection Projects] this vector onto a plane by subtracting this vector projected onto the plane's normal from this vector. </p> <h3>[method:this projectOnVector]( [param:Vector3] )</h3> <p>[link:https://en.wikipedia.org/wiki/Vector_projection Projects] this vector onto another vector.</p> <h3>[method:this reflect]( [param:Vector3 normal] )</h3> <p> [page:Vector3 normal] - the normal to the reflecting plane<br /><br /> Reflect the vector off of plane orthogonal to [page:Vector3 normal]. Normal is assumed to have unit length. </p> <h3>[method:this round]()</h3> <p>The components of the vector are rounded to the nearest integer value.</p> <h3>[method:this roundToZero]()</h3> <p> The components of the vector are rounded towards zero (up if negative, down if positive) to an integer value. </p> <h3>[method:this set]( [param:Float x], [param:Float y], [param:Float z] )</h3> <p>Sets the [page:.x x], [page:.y y] and [page:.z z] components of this vector.</p> <h3>[method:null setComponent]( [param:Integer index], [param:Float value] )</h3> <p> [page:Integer index] - 0, 1 or 2.<br /> [page:Float value] - [page:Float]<br /><br /> If index equals 0 set [page:.x x] to [page:Float value].<br /> If index equals 1 set [page:.y y] to [page:Float value].<br /> If index equals 2 set [page:.z z] to [page:Float value] </p> <h3>[method:this setFromCylindrical]( [param:Cylindrical c] )</h3> <p> Sets this vector from the cylindrical coordinates [page:Cylindrical c]. </p> <h3>[method:this setFromCylindricalCoords]( [param:Float radius], [param:Float theta], [param:Float y] )</h3> <p>Sets this vector from the cylindrical coordinates [page:Cylindrical radius], [page:Cylindrical theta] and [page:Cylindrical y].</p> <h3>[method:this setFromMatrixColumn]( [param:Matrix4 matrix], [param:Integer index] )</h3> <p> Sets this vector's [page:.x x], [page:.y y] and [page:.z z] equal to the column of the [page:Matrix4 matrix] specified by the [page:Integer index]. </p> <h3>[method:this setFromMatrixPosition]( [param:Matrix4 m] )</h3> <p> Sets this vector to the position elements of the [link:https://en.wikipedia.org/wiki/Transformation_matrix transformation matrix] [page:Matrix4 m]. </p> <h3>[method:this setFromMatrixScale]( [param:Matrix4 m] )</h3> <p> Sets this vector to the scale elements of the [link:https://en.wikipedia.org/wiki/Transformation_matrix transformation matrix] [page:Matrix4 m]. </p> <h3>[method:this setFromSpherical]( [param:Spherical s] )</h3> <p> Sets this vector from the spherical coordinates [page:Spherical s]. </p> <h3>[method:this setFromSphericalCoords]( [param:Float radius], [param:Float phi], [param:Float theta] )</h3> <p>Sets this vector from the spherical coordinates [page:Spherical radius], [page:Spherical phi] and [page:Spherical theta].</p> <h3>[method:this setLength]( [param:Float l] )</h3> <p> Set this vector to the vector with the same direction as this one, but [page:.length length] [page:Float l]. </p> <h3>[method:this setScalar]( [param:Float scalar] )</h3> <p> Set the [page:.x x], [page:.y y] and [page:.z z] values of this vector both equal to [page:Float scalar]. </p> <h3>[method:this setX]( [param:Float x] )</h3> <p>Replace this vector's [page:.x x] value with [page:Float x].</p> <h3>[method:this setY]( [param:Float y] )</h3> <p>Replace this vector's [page:.y y] value with [page:Float y].</p> <h3>[method:this setZ]( [param:Float z] )</h3> <p>Replace this vector's [page:.z z] value with [page:Float z].</p> <h3>[method:this sub]( [param:Vector3 v] )</h3> <p>Subtracts [page:Vector3 v] from this vector.</p> <h3>[method:this subScalar]( [param:Float s] )</h3> <p>Subtracts [page:Float s] from this vector's [page:.x x], [page:.y y] and [page:.z z] compnents.</p> <h3>[method:this subVectors]( [param:Vector3 a], [param:Vector3 b] )</h3> <p>Sets this vector to [page:Vector3 a] - [page:Vector3 b].</p> <h3>[method:Array toArray]( [param:Array array], [param:Integer offset] )</h3> <p> [page:Array array] - (optional) array to store the vector to. If this is not provided a new array will be created.<br /> [page:Integer offset] - (optional) optional offset into the array.<br /><br /> Returns an array [x, y, z], or copies x, y and z into the provided [page:Array array]. </p> <h3>[method:this transformDirection]( [param:Matrix4 m] )</h3> <p> Transforms the direction of this vector by a matrix (the upper left 3 x 3 subset of a [page:Matrix4 m]) and then [page:.normalize normalizes] the result. </p> <h3>[method:this unproject]( [param:Camera camera] )</h3> <p> [page:Camera camera] — camera to use in the projection.<br /><br /> [link:https://en.wikipedia.org/wiki/Vector_projection Unprojects] the vector with the camera's projection matrix. </p> <h2>Source</h2> [link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js] </body> </html>
Java
testMipmap = function() local f = {0} local g = {} local h = {6} local k = {0} f[1] = f[1] + 1 k[1] = h[1] - f[1]; g[1] = k[1]^2 print (g[1]) end testMipmap()
Java
#include "UniformBuffer.hpp" #include <iostream> #include <cstring> UniformBuffer::UniformBuffer(const void* data, unsigned int size, VkDevice device, VkPhysicalDevice physicalDevice, VkDescriptorPool descriptorPool, VkShaderStageFlags flags) : Buffer(device, physicalDevice, descriptorPool) { this->device = device; this->physicalDevice = physicalDevice; this->descriptorPool = descriptorPool; createBuffer(size, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &buffer, &bufferMemory); // Copy data to mapped memory. setData(data, size); // Create descriptor set. createDescriptorSetLayout(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, flags); createDescriptorSet(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, buffer, size); } UniformBuffer::~UniformBuffer() { vkDestroyBuffer(device, buffer, nullptr); vkFreeMemory(device, bufferMemory, nullptr); } void UniformBuffer::setData(const void* data, unsigned int size) { void* mappedMemory; vkMapMemory(device, bufferMemory, 0, size, 0, &mappedMemory); memcpy(mappedMemory, data, size); vkUnmapMemory(device, bufferMemory); }
Java
class Test { public static int[] test() { return null; } public static void main(String[] args) { int [] arr = test(); System.out.println(arr); }
Java
// // ColorInfoView.h // ASCFlatUIColors // // Created by André Schneider on 02.05.14. // Copyright (c) 2014 André Schneider. All rights reserved. // #import <UIKit/UIKit.h> @interface ColorInfoView : UIView - (void)showWithTitle:(NSString *)title forColorAtIndexPath:(NSIndexPath *)indexPath; - (void)hide; @end
Java
import { Component, ViewChild, ElementRef } from '@angular/core'; import { jqxButtonGroupComponent } from '../../../../../jqwidgets-ts/angular_jqxbuttongroup'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { @ViewChild('myButtonGroup') myButtonGroup: jqxButtonGroupComponent; @ViewChild('myLog') myLog: ElementRef; myDefaultModeButtonChecked(): void { this.myButtonGroup.mode('default'); }; myRadioModeButtonChecked(): void { this.myButtonGroup.mode('radio'); }; myCheckBoxModeButtonChecked(): void { this.myButtonGroup.mode('checkbox'); }; groupOnBtnClick(event: any): void { let clickedButton = event.args.button; this.myLog.nativeElement.innerHTML = `Clicked: ${clickedButton[0].id}`; } }
Java
-- MENUS DELETE FROM `sys_menu_items` WHERE `set_name`='sys_account_dashboard' AND `name`='dashboard-massmailer'; SET @iMoAccountDashboard = (SELECT IFNULL(MAX(`order`), 0) FROM `sys_menu_items` WHERE `set_name`='sys_account_dashboard' LIMIT 1); INSERT INTO `sys_menu_items` (`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `addon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `editable`, `order`) VALUES ('sys_account_dashboard', @sName, 'dashboard-massmailer', '_bx_massmailer_menu_item_title_system_admt_mailer', '_bx_massmailer_menu_item_title_admt_mailer', 'page.php?i=massmailer-campaigns', '', '', 'envelope col-red', '', '', 128, 1, 0, 1, @iMoAccountDashboard + 1); -- GRIDS DELETE FROM `sys_grid_fields` WHERE `object`='bx_massmailer_campaigns'; INSERT INTO `sys_grid_fields` (`object`, `name`, `title`, `width`, `translatable`, `chars_limit`, `params`, `order`) VALUES ('bx_massmailer_campaigns', 'checkbox', '_sys_select', '2%', 0, '', '', 1), ('bx_massmailer_campaigns', 'title', '_bx_massmailer_grid_column_title_adm_title', '26%', 0, '22', '', 2), ('bx_massmailer_campaigns', 'author', '_bx_massmailer_grid_column_title_adm_author', '8%', 0, '22', '', 3), ('bx_massmailer_campaigns', 'segments', '_bx_massmailer_grid_column_title_adm_segment', '10%', 0, '22', '', 4), ('bx_massmailer_campaigns', 'is_one_per_account', '_bx_massmailer_grid_column_title_adm_is_one_per_account', '10%', 0, '0', '', 5), ('bx_massmailer_campaigns', 'added', '_bx_massmailer_grid_column_title_adm_date_created', '10%', 0, '15', '', 6), ('bx_massmailer_campaigns', 'date_sent', '_bx_massmailer_grid_column_title_adm_date_sent', '10%', 0, '22', '', 7), ('bx_massmailer_campaigns', 'actions', '', '24%', 0, '', '', 8);
Java
<?php declare(strict_types=1); /** * Copyright (c) 2013-2018 OpenCFP * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. * * @see https://github.com/opencfp/opencfp */ namespace OpenCFP\Test\Integration\Http\Action\Signup; use OpenCFP\Test\Integration\WebTestCase; final class PrivacyActionTest extends WebTestCase { /** * @test */ public function privacyPolicyRenders() { $response = $this->get('/privacy'); $this->assertResponseIsSuccessful($response); $this->assertResponseBodyContains('Privacy Policy', $response); $this->assertResponseBodyContains('General Data Protection Regulation', $response); } }
Java
using System; using System.Windows.Input; namespace CustomBA.Commands { /// <summary> /// Based on http://wpftutorial.net/DelegateCommand.html /// </summary> public class DelegateCommand : ICommand { private readonly Predicate<object> _canExecute; private readonly Action<object> _execute; public event EventHandler CanExecuteChanged; public DelegateCommand(Action<object> execute) : this(execute, null) { } public DelegateCommand(Action<object> execute, Predicate<object> canExecute) { _execute = execute; _canExecute = canExecute; } public bool CanExecute(object parameter) { if (_canExecute == null) { return true; } return _canExecute(parameter); } public void Execute(object parameter) { _execute(parameter); } public void RaiseCanExecuteChanged() { if (CanExecuteChanged != null) { CanExecuteChanged(this, EventArgs.Empty); } } } }
Java
export declare class SampleComponent { constructor(); }
Java
# SSH ## SSH keys An SSH key allows you to establish a secure connection between your computer and GitLab. Before generating an SSH key in your shell, check if your system already has one by running the following command: ```bash cat ~/.ssh/id_rsa.pub ``` If you see a long string starting with `ssh-rsa` or `ssh-dsa`, you can skip the `ssh-keygen` step. Note: It is a best practice to use a password for an SSH key, but it is not required and you can skip creating a password by pressing enter. Note that the password you choose here can't be altered or retrieved. To generate a new SSH key, use the following commandGitLab```bash ssh-keygen -t rsa -C "$your_email" ``` This command will prompt you for a location and filename to store the key pair and for a password. When prompted for the location and filename, you can press enter to use the default. Use the command below to show your public key: ```bash cat ~/.ssh/id_rsa.pub ``` Copy-paste the key to the 'My SSH Keys' section under the 'SSH' tab in your user profile. Please copy the complete key starting with `ssh-` and ending with your username and host. To copy your public key to the clipboard, use code below. Depending on your OS you'll need to use a different command: **Windows:** ```bash clip < ~/.ssh/id_rsa.pub ``` **Mac:** ```bash pbcopy < ~/.ssh/id_rsa.pub ``` **GNU/Linux (requires xclip):** ```bash xclip -sel clip < ~/.ssh/id_rsa.pub ``` ## Deploy keys Deploy keys allow read-only access to multiple projects with a single SSH key. This is really useful for cloning repositories to your Continuous Integration (CI) server. By using deploy keys, you don't have to setup a dummy user account. If you are a project master or owner, you can add a deploy key in the project settings under the section 'Deploy Keys'. Press the 'New Deploy Key' button and upload a public SSH key. After this, the machine that uses the corresponding private key has read-only access to the project. You can't add the same deploy key twice with the 'New Deploy Key' option. If you want to add the same key to another project, please enable it in the list that says 'Deploy keys from projects available to you'. All the deploy keys of all the projects you have access to are available. This project access can happen through being a direct member of the project, or through a group. See `def accessible_deploy_keys` in `app/models/user.rb` for more information. Deploy keys can be shared between projects, you just need to add them to each project. ## Applications ### Eclipse How to add your ssh key to Eclipse: https://wiki.eclipse.org/EGit/User_Guide#Eclipse_SSH_Configuration ## Tip: Non-default OpenSSH key file names or locations If, for whatever reason, you decide to specify a non-default location and filename for your GitLab SSH key pair, you must configure your SSH client to find your GitLab SSH private key for connections to your GitLab server (perhaps gitlab.com). For OpenSSH clients, this is handled in the `~/.ssh/config` file with a stanza similar to the following: ``` # # Main gitlab.com server # Host gitlab.com RSAAuthentication yes IdentityFile ~/my-ssh-key-directory/my-gitlab-private-key-filename User mygitlabusername ``` Another example ``` # # Our company's internal GitLab server # Host my-gitlab.company.com RSAAuthentication yes IdentityFile ~/my-ssh-key-directory/company-com-private-key-filename ``` Note in the gitlab.com example above a username was specified to override the default chosen by OpenSSH (your local username). This is only required if your local and remote usernames differ. Due to the wide variety of SSH clients and their very large number of configuration options, further explanation of these topics is beyond the scope of this document. Public SSH keys need to be unique, as they will bind to your account. Your SSH key is the only identifier you'll have when pushing code via SSH. That's why it needs to uniquely map to a single user.
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc on Fri Nov 26 15:38:56 EST 2010 --> <TITLE> Xerces Native Interface: Package org.apache.xerces.xni </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../../../org/apache/xerces/xni/package-summary.html" TARGET="classFrame">org.apache.xerces.xni</A></FONT> <TABLE BORDER="0" WIDTH="100%"> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Interfaces</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="Augmentations.html" TARGET="classFrame"><I>Augmentations</I></A> <BR> <A HREF="NamespaceContext.html" TARGET="classFrame"><I>NamespaceContext</I></A> <BR> <A HREF="XMLAttributes.html" TARGET="classFrame"><I>XMLAttributes</I></A> <BR> <A HREF="XMLDocumentFragmentHandler.html" TARGET="classFrame"><I>XMLDocumentFragmentHandler</I></A> <BR> <A HREF="XMLDocumentHandler.html" TARGET="classFrame"><I>XMLDocumentHandler</I></A> <BR> <A HREF="XMLDTDContentModelHandler.html" TARGET="classFrame"><I>XMLDTDContentModelHandler</I></A> <BR> <A HREF="XMLDTDHandler.html" TARGET="classFrame"><I>XMLDTDHandler</I></A> <BR> <A HREF="XMLLocator.html" TARGET="classFrame"><I>XMLLocator</I></A> <BR> <A HREF="XMLResourceIdentifier.html" TARGET="classFrame"><I>XMLResourceIdentifier</I></A></FONT></TD> </TR> </TABLE> <TABLE BORDER="0" WIDTH="100%"> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="QName.html" TARGET="classFrame">QName</A> <BR> <A HREF="XMLString.html" TARGET="classFrame">XMLString</A></FONT></TD> </TR> </TABLE> <TABLE BORDER="0" WIDTH="100%"> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Exceptions</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="XNIException.html" TARGET="classFrame">XNIException</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
Java
#ifndef _WLC_CONTEXT_H_ #define _WLC_CONTEXT_H_ #include <stdbool.h> #include <EGL/egl.h> #include <EGL/eglext.h> struct wl_display; struct wlc_backend_surface; struct ctx; struct wlc_context_api { void (*terminate)(struct ctx *context); bool (*bind)(struct ctx *context); bool (*bind_to_wl_display)(struct ctx *context, struct wl_display *display); void (*swap)(struct ctx *context, struct wlc_backend_surface *bsurface); void* (*get_proc_address)(struct ctx *context, const char *procname); // EGL EGLBoolean (*query_buffer)(struct ctx *context, struct wl_resource *buffer, EGLint attribute, EGLint *value); EGLImageKHR (*create_image)(struct ctx *context, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list); EGLBoolean (*destroy_image)(struct ctx *context, EGLImageKHR image); }; struct wlc_context { void *context; // internal surface context (EGL, etc) struct wlc_context_api api; }; void* wlc_context_get_proc_address(struct wlc_context *context, const char *procname); EGLBoolean wlc_context_query_buffer(struct wlc_context *context, struct wl_resource *buffer, EGLint attribute, EGLint *value); EGLImageKHR wlc_context_create_image(struct wlc_context *context, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list); EGLBoolean wlc_context_destroy_image(struct wlc_context *context, EGLImageKHR image); bool wlc_context_bind(struct wlc_context *context); bool wlc_context_bind_to_wl_display(struct wlc_context *context, struct wl_display *display); void wlc_context_swap(struct wlc_context *context, struct wlc_backend_surface *bsurface); void wlc_context_release(struct wlc_context *context); bool wlc_context(struct wlc_context *context, struct wlc_backend_surface *bsurface); #endif /* _WLC_CONTEXT_H_ */
Java
import {Component} from '@angular/core'; @Component({ selector: 'not-found', templateUrl: 'app/404.component/404.component.html', styleUrls: ['app/404.component/404.component.css'], }) export class NotFoundComponent {}
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_33) on Tue Aug 20 12:20:59 EDT 2013 --> <TITLE> mars.util Class Hierarchy </TITLE> <META NAME="date" CONTENT="2013-08-20"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="mars.util Class Hierarchy"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../mars/tools/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../mars/venus/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html?mars/util/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> Hierarchy For Package mars.util </H2> </CENTER> <DL> <DT><B>Package Hierarchies:</B><DD><A HREF="../../overview-tree.html">All Packages</A></DL> <HR> <H2> Class Hierarchy </H2> <UL> <LI TYPE="circle">java.lang.<A HREF="http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><B>Object</B></A><UL> <LI TYPE="circle">mars.util.<A HREF="../../mars/util/Binary.html" title="class in mars.util"><B>Binary</B></A><LI TYPE="circle">mars.util.<A HREF="../../mars/util/EditorFont.html" title="class in mars.util"><B>EditorFont</B></A><LI TYPE="circle">mars.util.<A HREF="../../mars/util/FilenameFinder.html" title="class in mars.util"><B>FilenameFinder</B></A><LI TYPE="circle">mars.util.<A HREF="../../mars/util/MemoryDump.html" title="class in mars.util"><B>MemoryDump</B></A><LI TYPE="circle">mars.util.<A HREF="../../mars/util/PropertiesFile.html" title="class in mars.util"><B>PropertiesFile</B></A><LI TYPE="circle">mars.util.<A HREF="../../mars/util/SystemIO.html" title="class in mars.util"><B>SystemIO</B></A></UL> </UL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../mars/tools/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../mars/venus/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html?mars/util/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
Java
call target.bat %1\haxe.exe %2\compile-%TARGET%.hxml
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>type_mat3x2.hpp Source File</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="logo-mini.png"/></td> </tr> </tbody> </table> </div> <!-- Generated by Doxygen 1.8.0 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> </ul> </div> </div> <div class="header"> <div class="headertitle"> <div class="title">type_mat3x2.hpp</div> </div> </div><!--header--> <div class="contents"> <a href="a00101.html">Go to the documentation of this file.</a><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <a name="l00002"></a>00002 <a name="l00003"></a>00003 <a name="l00004"></a>00004 <a name="l00005"></a>00005 <a name="l00006"></a>00006 <a name="l00007"></a>00007 <a name="l00008"></a>00008 <a name="l00009"></a>00009 <a name="l00010"></a>00010 <a name="l00011"></a>00011 <a name="l00012"></a>00012 <a name="l00013"></a>00013 <a name="l00014"></a>00014 <a name="l00015"></a>00015 <a name="l00016"></a>00016 <a name="l00017"></a>00017 <a name="l00018"></a>00018 <a name="l00019"></a>00019 <a name="l00020"></a>00020 <a name="l00021"></a>00021 <a name="l00022"></a>00022 <a name="l00023"></a>00023 <a name="l00024"></a>00024 <a name="l00025"></a>00025 <a name="l00026"></a>00026 <a name="l00027"></a>00027 <a name="l00028"></a>00028 <a name="l00029"></a>00029 <span class="preprocessor">#ifndef glm_core_type_mat3x2</span> <a name="l00030"></a>00030 <span class="preprocessor"></span><span class="preprocessor">#define glm_core_type_mat3x2</span> <a name="l00031"></a>00031 <span class="preprocessor"></span> <a name="l00032"></a>00032 <span class="preprocessor">#include &quot;<a class="code" href="a00097.html" title="OpenGL Mathematics (glm.g-truc.net)">type_mat.hpp</a>&quot;</span> <a name="l00033"></a>00033 <a name="l00034"></a>00034 <span class="keyword">namespace </span>glm{ <a name="l00035"></a>00035 <span class="keyword">namespace </span>detail <a name="l00036"></a>00036 { <a name="l00037"></a>00037 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tvec1; <a name="l00038"></a>00038 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tvec2; <a name="l00039"></a>00039 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tvec3; <a name="l00040"></a>00040 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tvec4; <a name="l00041"></a>00041 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tmat2x2; <a name="l00042"></a>00042 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tmat2x3; <a name="l00043"></a>00043 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tmat2x4; <a name="l00044"></a>00044 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tmat3x2; <a name="l00045"></a>00045 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tmat3x3; <a name="l00046"></a>00046 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tmat3x4; <a name="l00047"></a>00047 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tmat4x2; <a name="l00048"></a>00048 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tmat4x3; <a name="l00049"></a>00049 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tmat4x4; <a name="l00050"></a>00050 <a name="l00051"></a>00051 <span class="comment">// \brief Template for 3 columns and 2 rows matrix of floating-point numbers.</span> <a name="l00052"></a>00052 <span class="comment">// \ingroup core_template</span> <a name="l00053"></a>00053 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00054"></a>00054 <span class="keyword">struct </span>tmat3x2 <a name="l00055"></a>00055 { <a name="l00056"></a>00056 <span class="keyword">enum</span> ctor{null}; <a name="l00057"></a>00057 <span class="keyword">typedef</span> T value_type; <a name="l00058"></a>00058 <span class="keyword">typedef</span> std::size_t size_type; <a name="l00059"></a>00059 <span class="keyword">typedef</span> tvec2&lt;T&gt; col_type; <a name="l00060"></a>00060 <span class="keyword">typedef</span> tvec3&lt;T&gt; row_type; <a name="l00061"></a>00061 GLM_FUNC_DECL size_type <a class="code" href="a00129.html#ga282360c8bb80b80d3c7f5bc00766d873" title="Returns the length of x, i.e., sqrt(x * x).">length</a>() <span class="keyword">const</span>; <a name="l00062"></a>00062 <span class="keyword">static</span> GLM_FUNC_DECL size_type col_size(); <a name="l00063"></a>00063 <span class="keyword">static</span> GLM_FUNC_DECL size_type row_size(); <a name="l00064"></a>00064 <a name="l00065"></a>00065 <span class="keyword">typedef</span> tmat3x2&lt;T&gt; type; <a name="l00066"></a>00066 <span class="keyword">typedef</span> tmat2x3&lt;T&gt; transpose_type; <a name="l00067"></a>00067 <a name="l00068"></a>00068 <span class="keyword">private</span>: <a name="l00069"></a>00069 <span class="comment">// Data</span> <a name="l00070"></a>00070 col_type value[3]; <a name="l00071"></a>00071 <a name="l00072"></a>00072 <span class="keyword">public</span>: <a name="l00073"></a>00073 <span class="comment">// Constructors</span> <a name="l00074"></a>00074 GLM_FUNC_DECL tmat3x2(); <a name="l00075"></a>00075 GLM_FUNC_DECL tmat3x2(tmat3x2 <span class="keyword">const</span> &amp; m); <a name="l00076"></a>00076 <a name="l00077"></a>00077 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2( <a name="l00078"></a>00078 ctor); <a name="l00079"></a>00079 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2( <a name="l00080"></a>00080 value_type <span class="keyword">const</span> &amp; s); <a name="l00081"></a>00081 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2( <a name="l00082"></a>00082 value_type <span class="keyword">const</span> &amp; x0, value_type <span class="keyword">const</span> &amp; y0, <a name="l00083"></a>00083 value_type <span class="keyword">const</span> &amp; x1, value_type <span class="keyword">const</span> &amp; y1, <a name="l00084"></a>00084 value_type <span class="keyword">const</span> &amp; x2, value_type <span class="keyword">const</span> &amp; y2); <a name="l00085"></a>00085 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2( <a name="l00086"></a>00086 col_type <span class="keyword">const</span> &amp; v0, <a name="l00087"></a>00087 col_type <span class="keyword">const</span> &amp; v1, <a name="l00088"></a>00088 col_type <span class="keyword">const</span> &amp; v2); <a name="l00089"></a>00089 <a name="l00091"></a>00091 <span class="comment">// Conversions</span> <a name="l00092"></a>00092 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> U&gt; <a name="l00093"></a>00093 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2( <a name="l00094"></a>00094 U <span class="keyword">const</span> &amp; x); <a name="l00095"></a>00095 <a name="l00096"></a>00096 <span class="keyword">template</span> <a name="l00097"></a>00097 &lt; <a name="l00098"></a>00098 <span class="keyword">typename</span> X1, <span class="keyword">typename</span> Y1, <a name="l00099"></a>00099 <span class="keyword">typename</span> X2, <span class="keyword">typename</span> Y2, <a name="l00100"></a>00100 <span class="keyword">typename</span> X3, <span class="keyword">typename</span> Y3 <a name="l00101"></a>00101 &gt; <a name="l00102"></a>00102 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2( <a name="l00103"></a>00103 X1 <span class="keyword">const</span> &amp; x1, Y1 <span class="keyword">const</span> &amp; y1, <a name="l00104"></a>00104 X2 <span class="keyword">const</span> &amp; x2, Y2 <span class="keyword">const</span> &amp; y2, <a name="l00105"></a>00105 X3 <span class="keyword">const</span> &amp; x3, Y3 <span class="keyword">const</span> &amp; y3); <a name="l00106"></a>00106 <a name="l00107"></a>00107 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> V1, <span class="keyword">typename</span> V2, <span class="keyword">typename</span> V3&gt; <a name="l00108"></a>00108 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2( <a name="l00109"></a>00109 tvec2&lt;V1&gt; <span class="keyword">const</span> &amp; v1, <a name="l00110"></a>00110 tvec2&lt;V2&gt; <span class="keyword">const</span> &amp; v2, <a name="l00111"></a>00111 tvec2&lt;V3&gt; <span class="keyword">const</span> &amp; v3); <a name="l00112"></a>00112 <a name="l00113"></a>00113 <span class="comment">// Matrix conversions</span> <a name="l00114"></a>00114 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> U&gt; <a name="l00115"></a>00115 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2(tmat3x2&lt;U&gt; <span class="keyword">const</span> &amp; m); <a name="l00116"></a>00116 <a name="l00117"></a>00117 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2(tmat2x2&lt;T&gt; <span class="keyword">const</span> &amp; x); <a name="l00118"></a>00118 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2(tmat3x3&lt;T&gt; <span class="keyword">const</span> &amp; x); <a name="l00119"></a>00119 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2(tmat4x4&lt;T&gt; <span class="keyword">const</span> &amp; x); <a name="l00120"></a>00120 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2(tmat2x3&lt;T&gt; <span class="keyword">const</span> &amp; x); <a name="l00121"></a>00121 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2(tmat2x4&lt;T&gt; <span class="keyword">const</span> &amp; x); <a name="l00122"></a>00122 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2(tmat3x4&lt;T&gt; <span class="keyword">const</span> &amp; x); <a name="l00123"></a>00123 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2(tmat4x2&lt;T&gt; <span class="keyword">const</span> &amp; x); <a name="l00124"></a>00124 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2(tmat4x3&lt;T&gt; <span class="keyword">const</span> &amp; x); <a name="l00125"></a>00125 <a name="l00126"></a>00126 <span class="comment">// Accesses</span> <a name="l00127"></a>00127 GLM_FUNC_DECL col_type &amp; operator[](size_type i); <a name="l00128"></a>00128 GLM_FUNC_DECL col_type <span class="keyword">const</span> &amp; operator[](size_type i) <span class="keyword">const</span>; <a name="l00129"></a>00129 <a name="l00130"></a>00130 <span class="comment">// Unary updatable operators</span> <a name="l00131"></a>00131 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator= (tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m); <a name="l00132"></a>00132 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> U&gt; <a name="l00133"></a>00133 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator= (tmat3x2&lt;U&gt; <span class="keyword">const</span> &amp; m); <a name="l00134"></a>00134 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> U&gt; <a name="l00135"></a>00135 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator+= (U <span class="keyword">const</span> &amp; s); <a name="l00136"></a>00136 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> U&gt; <a name="l00137"></a>00137 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator+= (tmat3x2&lt;U&gt; <span class="keyword">const</span> &amp; m); <a name="l00138"></a>00138 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> U&gt; <a name="l00139"></a>00139 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator-= (U <span class="keyword">const</span> &amp; s); <a name="l00140"></a>00140 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> U&gt; <a name="l00141"></a>00141 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator-= (tmat3x2&lt;U&gt; <span class="keyword">const</span> &amp; m); <a name="l00142"></a>00142 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> U&gt; <a name="l00143"></a>00143 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator*= (U <span class="keyword">const</span> &amp; s); <a name="l00144"></a>00144 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> U&gt; <a name="l00145"></a>00145 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator*= (tmat3x2&lt;U&gt; <span class="keyword">const</span> &amp; m); <a name="l00146"></a>00146 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> U&gt; <a name="l00147"></a>00147 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator/= (U <span class="keyword">const</span> &amp; s); <a name="l00148"></a>00148 <a name="l00149"></a>00149 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator++ (); <a name="l00150"></a>00150 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator-- (); <a name="l00151"></a>00151 }; <a name="l00152"></a>00152 <a name="l00153"></a>00153 <span class="comment">// Binary operators</span> <a name="l00154"></a>00154 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00155"></a>00155 tmat3x2&lt;T&gt; operator+ ( <a name="l00156"></a>00156 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m, <a name="l00157"></a>00157 <span class="keyword">typename</span> tmat3x2&lt;T&gt;::value_type <span class="keyword">const</span> &amp; s); <a name="l00158"></a>00158 <a name="l00159"></a>00159 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00160"></a>00160 tmat3x2&lt;T&gt; operator+ ( <a name="l00161"></a>00161 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m1, <a name="l00162"></a>00162 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m2); <a name="l00163"></a>00163 <a name="l00164"></a>00164 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00165"></a>00165 tmat3x2&lt;T&gt; operator- ( <a name="l00166"></a>00166 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m, <a name="l00167"></a>00167 <span class="keyword">typename</span> tmat3x2&lt;T&gt;::value_type <span class="keyword">const</span> &amp; s); <a name="l00168"></a>00168 <a name="l00169"></a>00169 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00170"></a>00170 tmat3x2&lt;T&gt; operator- ( <a name="l00171"></a>00171 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m1, <a name="l00172"></a>00172 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m2); <a name="l00173"></a>00173 <a name="l00174"></a>00174 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00175"></a>00175 tmat3x2&lt;T&gt; operator* ( <a name="l00176"></a>00176 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m, <a name="l00177"></a>00177 <span class="keyword">typename</span> tmat3x2&lt;T&gt;::value_type <span class="keyword">const</span> &amp; s); <a name="l00178"></a>00178 <a name="l00179"></a>00179 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00180"></a>00180 tmat3x2&lt;T&gt; operator* ( <a name="l00181"></a>00181 <span class="keyword">typename</span> tmat3x2&lt;T&gt;::value_type <span class="keyword">const</span> &amp; s, <a name="l00182"></a>00182 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m); <a name="l00183"></a>00183 <a name="l00184"></a>00184 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00185"></a>00185 <span class="keyword">typename</span> tmat3x2&lt;T&gt;::col_type operator* ( <a name="l00186"></a>00186 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m, <a name="l00187"></a>00187 <span class="keyword">typename</span> tmat3x2&lt;T&gt;::row_type <span class="keyword">const</span> &amp; v); <a name="l00188"></a>00188 <a name="l00189"></a>00189 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00190"></a>00190 <span class="keyword">typename</span> tmat3x2&lt;T&gt;::row_type operator* ( <a name="l00191"></a>00191 <span class="keyword">typename</span> tmat3x2&lt;T&gt;::col_type <span class="keyword">const</span> &amp; v, <a name="l00192"></a>00192 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m); <a name="l00193"></a>00193 <a name="l00194"></a>00194 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00195"></a>00195 tmat2x2&lt;T&gt; operator* ( <a name="l00196"></a>00196 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m1, <a name="l00197"></a>00197 tmat2x3&lt;T&gt; <span class="keyword">const</span> &amp; m2); <a name="l00198"></a>00198 <a name="l00199"></a>00199 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00200"></a>00200 tmat3x2&lt;T&gt; operator* ( <a name="l00201"></a>00201 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m1, <a name="l00202"></a>00202 tmat3x3&lt;T&gt; <span class="keyword">const</span> &amp; m2); <a name="l00203"></a>00203 <a name="l00204"></a>00204 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00205"></a>00205 tmat4x2&lt;T&gt; operator* ( <a name="l00206"></a>00206 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m1, <a name="l00207"></a>00207 tmat4x3&lt;T&gt; <span class="keyword">const</span> &amp; m2); <a name="l00208"></a>00208 <a name="l00209"></a>00209 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00210"></a>00210 tmat3x2&lt;T&gt; operator/ ( <a name="l00211"></a>00211 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m, <a name="l00212"></a>00212 <span class="keyword">typename</span> tmat3x2&lt;T&gt;::value_type <span class="keyword">const</span> &amp; s); <a name="l00213"></a>00213 <a name="l00214"></a>00214 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00215"></a>00215 tmat3x2&lt;T&gt; operator/ ( <a name="l00216"></a>00216 <span class="keyword">typename</span> tmat3x2&lt;T&gt;::value_type <span class="keyword">const</span> &amp; s, <a name="l00217"></a>00217 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m); <a name="l00218"></a>00218 <a name="l00219"></a>00219 <span class="comment">// Unary constant operators</span> <a name="l00220"></a>00220 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00221"></a>00221 tmat3x2&lt;T&gt; <span class="keyword">const</span> operator- ( <a name="l00222"></a>00222 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m); <a name="l00223"></a>00223 <a name="l00224"></a>00224 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00225"></a>00225 tmat3x2&lt;T&gt; <span class="keyword">const</span> operator-- ( <a name="l00226"></a>00226 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m, <a name="l00227"></a>00227 <span class="keywordtype">int</span>); <a name="l00228"></a>00228 <a name="l00229"></a>00229 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00230"></a>00230 tmat3x2&lt;T&gt; <span class="keyword">const</span> operator++ ( <a name="l00231"></a>00231 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m, <a name="l00232"></a>00232 <span class="keywordtype">int</span>); <a name="l00233"></a>00233 <a name="l00234"></a>00234 } <span class="comment">//namespace detail</span> <a name="l00235"></a>00235 <a name="l00238"></a>00238 <a name="l00244"></a><a class="code" href="a00141.html#ga745259412efbd5e07b1a4062190e3135">00244</a> <span class="keyword">typedef</span> detail::tmat3x2&lt;lowp_float&gt; <a class="code" href="a00141.html#ga745259412efbd5e07b1a4062190e3135" title="3 columns of 2 components matrix of low precision floating-point numbers.">lowp_mat3x2</a>; <a name="l00245"></a>00245 <a name="l00251"></a><a class="code" href="a00141.html#ga08c1cebbdb2cdfa0a62b23981db1c059">00251</a> <span class="keyword">typedef</span> detail::tmat3x2&lt;mediump_float&gt; <a class="code" href="a00141.html#ga08c1cebbdb2cdfa0a62b23981db1c059" title="3 columns of 2 components matrix of medium precision floating-point numbers.">mediump_mat3x2</a>; <a name="l00252"></a>00252 <a name="l00258"></a><a class="code" href="a00141.html#gae5e017b25e88ff5c61f4538a2dd5647a">00258</a> <span class="keyword">typedef</span> detail::tmat3x2&lt;highp_float&gt; <a class="code" href="a00141.html#gae5e017b25e88ff5c61f4538a2dd5647a" title="3 columns of 2 components matrix of high precision floating-point numbers.">highp_mat3x2</a>; <a name="l00259"></a>00259 <a name="l00261"></a>00261 }<span class="comment">//namespace glm</span> <a name="l00262"></a>00262 <a name="l00263"></a>00263 <span class="preprocessor">#ifndef GLM_EXTERNAL_TEMPLATE</span> <a name="l00264"></a>00264 <span class="preprocessor"></span><span class="preprocessor">#include &quot;type_mat3x2.inl&quot;</span> <a name="l00265"></a>00265 <span class="preprocessor">#endif</span> <a name="l00266"></a>00266 <span class="preprocessor"></span> <a name="l00267"></a>00267 <span class="preprocessor">#endif //glm_core_type_mat3x2</span> </pre></div></div><!-- contents --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.0 </small></address> </body> </html>
Java
<?php require_once('library/HTML5/Parser.php'); require_once('library/HTMLPurifier.auto.php'); function arr_add_hashes(&$item,$k) { $item = '#' . $item; } function parse_url_content(&$a) { $text = null; $str_tags = ''; if(x($_GET,'binurl')) $url = trim(hex2bin($_GET['binurl'])); else $url = trim($_GET['url']); if($_GET['title']) $title = strip_tags(trim($_GET['title'])); if($_GET['description']) $text = strip_tags(trim($_GET['description'])); if($_GET['tags']) { $arr_tags = str_getcsv($_GET['tags']); if(count($arr_tags)) { array_walk($arr_tags,'arr_add_hashes'); $str_tags = '<br />' . implode(' ',$arr_tags) . '<br />'; } } logger('parse_url: ' . $url); $template = "<br /><a class=\"bookmark\" href=\"%s\" >%s</a>%s<br />"; $arr = array('url' => $url, 'text' => ''); call_hooks('parse_link', $arr); if(strlen($arr['text'])) { echo $arr['text']; killme(); } if($url && $title && $text) { $text = '<br /><br /><blockquote>' . $text . '</blockquote><br />'; $title = str_replace(array("\r","\n"),array('',''),$title); $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags; logger('parse_url (unparsed): returns: ' . $result); echo $result; killme(); } if($url) { $s = fetch_url($url); } else { echo ''; killme(); } // logger('parse_url: data: ' . $s, LOGGER_DATA); if(! $s) { echo sprintf($template,$url,$url,'') . $str_tags; killme(); } $matches = ''; $c = preg_match('/\<head(.*?)\>(.*?)\<\/head\>/ism',$s,$matches); if($c) { // logger('parse_url: header: ' . $matches[2], LOGGER_DATA); try { $domhead = HTML5_Parser::parse($matches[2]); } catch (DOMException $e) { logger('scrape_dfrn: parse error: ' . $e); } if($domhead) logger('parsed header'); } if(! $title) { if(strpos($s,'<title>')) { $title = substr($s,strpos($s,'<title>')+7,64); if(strpos($title,'<') !== false) $title = strip_tags(substr($title,0,strpos($title,'<'))); } } $config = HTMLPurifier_Config::createDefault(); $config->set('Cache.DefinitionImpl', null); $purifier = new HTMLPurifier($config); $s = $purifier->purify($s); // logger('purify_output: ' . $s); try { $dom = HTML5_Parser::parse($s); } catch (DOMException $e) { logger('scrape_dfrn: parse error: ' . $e); } if(! $dom) { echo sprintf($template,$url,$url,'') . $str_tags; killme(); } $items = $dom->getElementsByTagName('title'); if($items) { foreach($items as $item) { $title = trim($item->textContent); break; } } if(! $text) { $divs = $dom->getElementsByTagName('div'); if($divs) { foreach($divs as $div) { $class = $div->getAttribute('class'); if($class && (stristr($class,'article') || stristr($class,'content'))) { $items = $div->getElementsByTagName('p'); if($items) { foreach($items as $item) { $text = $item->textContent; if(stristr($text,'<script')) { $text = ''; continue; } $text = strip_tags($text); if(strlen($text) < 100) { $text = ''; continue; } $text = substr($text,0,250) . '...' ; break; } } } if($text) break; } } if(! $text) { $items = $dom->getElementsByTagName('p'); if($items) { foreach($items as $item) { $text = $item->textContent; if(stristr($text,'<script')) continue; $text = strip_tags($text); if(strlen($text) < 100) { $text = ''; continue; } $text = substr($text,0,250) . '...' ; break; } } } } if(! $text) { logger('parsing meta'); $items = $domhead->getElementsByTagName('meta'); if($items) { foreach($items as $item) { $property = $item->getAttribute('property'); if($property && (stristr($property,':description'))) { $text = $item->getAttribute('content'); if(stristr($text,'<script')) { $text = ''; continue; } $text = strip_tags($text); $text = substr($text,0,250) . '...' ; } if($property && (stristr($property,':image'))) { $image = $item->getAttribute('content'); if(stristr($text,'<script')) { $image = ''; continue; } $image = strip_tags($image); $i = fetch_url($image); if($i) { require_once('include/Photo.php'); $ph = new Photo($i); if($ph->is_valid()) { if($ph->getWidth() > 300 || $ph->getHeight() > 300) { $ph->scaleImage(300); $new_width = $ph->getWidth(); $new_height = $ph->getHeight(); $image = '<br /><br /><img height="' . $new_height . '" width="' . $new_width . '" src="' .$image . '" alt="photo" />'; } else $image = '<br /><br /><img src="' . $image . '" alt="photo" />'; } else $image = ''; } } } } } if(strlen($text)) { $text = '<br /><br /><blockquote>' . $text . '</blockquote><br />'; } if($image) { $text = $image . '<br />' . $text; } $title = str_replace(array("\r","\n"),array('',''),$title); $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags; logger('parse_url: returns: ' . $result); echo $result; killme(); }
Java
package com.example.exampleeureka; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class ExampleEurekaApplicationTests { @Test public void contextLoads() { } }
Java
using System.Runtime.Serialization; namespace BungieNetPlatform.Enums { [DataContract] public enum ForumPostSort { [EnumMember] Default = 0, [EnumMember] OldestFirst = 1 } }
Java
A GLMListPresentation simply shows the given elements within a list. Instance Variables tagsBlock: <Object> tagsFilterBlock: <Object> tagsBlock - xxxxx tagsFilterBlock - xxxxx
Java
using System.Net.Http; using System.Threading.Tasks; namespace WebApiContrib.IoC.Mef.Tests.Parts { public class PrecannedMessageHandler : DelegatingHandler { private readonly HttpResponseMessage _response; public PrecannedMessageHandler(HttpResponseMessage response) { _response = response; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { if (request.Method == HttpMethod.Get) { _response.RequestMessage = request; var tcs = new TaskCompletionSource<HttpResponseMessage>(); tcs.SetResult(_response); return tcs.Task; } return null; } } }
Java
#include "gamelib/components/editor/LineBrushComponent.hpp" #include "gamelib/components/geometry/Polygon.hpp" #include "gamelib/components/rendering/MeshRenderer.hpp" #include "gamelib/core/ecs/Entity.hpp" #include "gamelib/properties/PropComponent.hpp" namespace gamelib { LineBrushComponent::LineBrushComponent() : _linewidth(32) { auto cb = +[](const ComponentReference<PolygonCollider>* val, LineBrushComponent* self) { self->_line = *val; self->regenerate(); }; _props.registerProperty("linewidth", _linewidth, PROP_METHOD(_linewidth, setWidth), this); registerProperty(_props, "line", _line, *this, cb); } void LineBrushComponent::setWidth(int width) { if (_linewidth == width) return; _linewidth = width; regenerate(); } int LineBrushComponent::getWidth() const { return _linewidth; } PolygonCollider* LineBrushComponent::getBrushPolygon() const { return _line.get(); } void LineBrushComponent::regenerate() const { if (!_shape || !_pol || !_line || _line->size() == 0) return; math::Vec2f lastd, dir; bool start = true; auto cb = [&](const math::Line2f& seg) { float area = 0; auto norm = seg.d.normalized(); if (start) { start = false; lastd = seg.d; } else { // Compute if the line turns clockwise or counter clockwise // Total hours wasted here because I didn't google the // problem / didn't knew what exactly to google for: 11 auto p1 = seg.p - lastd; auto p3 = seg.p + seg.d; // Break if the direction hasn't changed if (lastd.normalized() == norm) return false; area = (seg.p.x - p1.x) * (seg.p.y + p1.y) + (p3.x - seg.p.x) * (p3.y + seg.p.y) + (p1.x - p3.x) * (p1.y + p3.y); } dir = (norm + lastd.normalized()).right().normalized(); dir *= (_linewidth / 2.0) / dir.angle_cos(lastd.right()); _pol->add(seg.p - dir); _pol->add(seg.p + dir); // depending on clockwise or counter clockwise line direction, // different vertices have to be added. if (area != 0) { auto len = norm.right() * _linewidth; if (area > 0) // clockwise { _pol->add(seg.p - dir); _pol->add(seg.p - dir + len); } else // counter clockwise { _pol->add(seg.p + dir - len); _pol->add(seg.p + dir); } } lastd = seg.d; return false; }; auto& linepol = _line->getLocal(); _pol->clear(); linepol.foreachSegment(cb); dir = lastd.right().normalized() * (_linewidth / 2.0); _pol->add(linepol.get(linepol.size() - 1) - dir); _pol->add(linepol.get(linepol.size() - 1) + dir); _shape->fetch(_pol->getLocal(), sf::TriangleStrip); } }
Java
/////////////////////// /// UTILS /// /////////////////////// var u = {}; u.distance = function (p1, p2) { var dx = p2.x - p1.x; var dy = p2.y - p1.y; return Math.sqrt((dx * dx) + (dy * dy)); }; u.angle = function(p1, p2) { var dx = p2.x - p1.x; var dy = p2.y - p1.y; return u.degrees(Math.atan2(dy, dx)); }; u.findCoord = function(p, d, a) { var b = {x: 0, y: 0}; a = u.radians(a); b.x = p.x - d * Math.cos(a); b.y = p.y - d * Math.sin(a); return b; }; u.radians = function(a) { return a * (Math.PI / 180); }; u.degrees = function(a) { return a * (180 / Math.PI); }; u.bindEvt = function (el, type, handler) { if (el.addEventListener) { el.addEventListener(type, handler, false); } else if (el.attachEvent) { el.attachEvent(type, handler); } }; u.unbindEvt = function (el, type, handler) { if (el.removeEventListener) { el.removeEventListener(type, handler); } else if (el.detachEvent) { el.detachEvent(type, handler); } }; u.trigger = function (el, type, data) { var evt = new CustomEvent(type, data); el.dispatchEvent(evt); }; u.prepareEvent = function (evt) { evt.preventDefault(); return isTouch ? evt.changedTouches : evt; }; u.getScroll = function () { var x = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body) .scrollLeft; var y = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body) .scrollTop; return { x: x, y: y }; }; u.applyPosition = function (el, pos) { if (pos.x && pos.y) { el.style.left = pos.x + 'px'; el.style.top = pos.y + 'px'; } else if (pos.top || pos.right || pos.bottom || pos.left) { el.style.top = pos.top; el.style.right = pos.right; el.style.bottom = pos.bottom; el.style.left = pos.left; } }; u.getTransitionStyle = function (property, values, time) { var obj = u.configStylePropertyObject(property); for (var i in obj) { if (obj.hasOwnProperty(i)) { if (typeof values === 'string') { obj[i] = values + ' ' + time; } else { var st = ''; for (var j = 0, max = values.length; j < max; j += 1) { st += values[j] + ' ' + time + ', '; } obj[i] = st.slice(0, -2); } } } return obj; }; u.getVendorStyle = function (property, value) { var obj = u.configStylePropertyObject(property); for (var i in obj) { if (obj.hasOwnProperty(i)) { obj[i] = value; } } return obj; }; u.configStylePropertyObject = function (prop) { var obj = {}; obj[prop] = ''; var vendors = ['webkit', 'Moz', 'o']; vendors.forEach(function (vendor) { obj[vendor + prop.charAt(0).toUpperCase() + prop.slice(1)] = ''; }); return obj; }; u.extend = function (objA, objB) { for (var i in objB) { if (objB.hasOwnProperty(i)) { objA[i] = objB[i]; } } };
Java
# coding: utf-8 unless defined?(CARDS_CONF) File.open(File.expand_path("../../cards_config.rb", __FILE__)) { |f| CARDS_CONF = eval(f.read()) if(CARDS_CONF.class == Hash) then f.close() end } end
Java
package styles import ( "github.com/alecthomas/chroma" ) // Doom One 2 style. Inspired by Atom One and Doom Emacs's Atom One theme var DoomOne2 = Register(chroma.MustNewStyle("doom-one2", chroma.StyleEntries{ chroma.Text: "#b0c4de", chroma.Error: "#b0c4de", chroma.Comment: "italic #8a93a5", chroma.CommentHashbang: "bold", chroma.Keyword: "#76a9f9", chroma.KeywordConstant: "#e5c07b", chroma.KeywordType: "#e5c07b", chroma.Operator: "#54b1c7", chroma.OperatorWord: "bold #b756ff", chroma.Punctuation: "#abb2bf", chroma.Name: "#aa89ea", chroma.NameAttribute: "#cebc3a", chroma.NameBuiltin: "#e5c07b", chroma.NameClass: "#ca72ff", chroma.NameConstant: "bold", chroma.NameDecorator: "#e5c07b", chroma.NameEntity: "#bda26f", chroma.NameException: "bold #fd7474", chroma.NameFunction: "#00b1f7", chroma.NameProperty: "#cebc3a", chroma.NameLabel: "#f5a40d", chroma.NameNamespace: "#ca72ff", chroma.NameTag: "#76a9f9", chroma.NameVariable: "#DCAEEA", chroma.NameVariableClass: "#DCAEEA", chroma.NameVariableGlobal: "bold #DCAEEA", chroma.NameVariableInstance: "#e06c75", chroma.NameVariableMagic: "#DCAEEA", chroma.Literal: "#98c379", chroma.LiteralDate: "#98c379", chroma.Number: "#d19a66", chroma.NumberBin: "#d19a66", chroma.NumberFloat: "#d19a66", chroma.NumberHex: "#d19a66", chroma.NumberInteger: "#d19a66", chroma.NumberIntegerLong: "#d19a66", chroma.NumberOct: "#d19a66", chroma.String: "#98c379", chroma.StringAffix: "#98c379", chroma.StringBacktick: "#98c379", chroma.StringDelimiter: "#98c379", chroma.StringDoc: "#7e97c3", chroma.StringDouble: "#63c381", chroma.StringEscape: "bold #d26464", chroma.StringHeredoc: "#98c379", chroma.StringInterpol: "#98c379", chroma.StringOther: "#70b33f", chroma.StringRegex: "#56b6c2", chroma.StringSingle: "#98c379", chroma.StringSymbol: "#56b6c2", chroma.Generic: "#b0c4de", chroma.GenericDeleted: "#b0c4de", chroma.GenericEmph: "italic", chroma.GenericHeading: "bold #a2cbff", chroma.GenericInserted: "#a6e22e", chroma.GenericOutput: "#a6e22e", chroma.GenericUnderline: "underline", chroma.GenericPrompt: "#a6e22e", chroma.GenericStrong: "bold", chroma.GenericSubheading: "#a2cbff", chroma.GenericTraceback: "#a2cbff", chroma.Background: "#b0c4de bg:#282c34", }))
Java
#include "multi_modelstruct.h" #include "multivar_support.h" #include <math.h> #include <assert.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_errno.h> /** * ccs, 05.06.2012 * \todo this all needs to be checked carefully against an example that works in R * \todo valgrind for mem-leaks * \bug no error checking in linalg * \bug no error checking in alloc * \bug is there error checking in file handles? * * ccs, 19.06.2012 * if you allocate a multi_modelstruct m * then m->pca_model_array[i]->xmodel == m->xmodel * the value in the pca_model_array is just a pointer to m, do we really want this? */ /** * allocates a multi_modelstruct, like alloc_modelstruct_2, * but for multivariate models with t output values at each location * * @param model_in: (n x d) matrix of the design * @param training_matrix: (n x t) matrix of the values of the training values at each of the n locations * @param cov_fn_index: POWEREXPCOVFN, MATERN32, or MATERN52 * @param regression_order: 0, 1, 2, or 3 * @param varfrac: the minimum fractional variance that should be retained during the PCA decomp * * applies a pca decomp to training_matrix to reduce the dimensionality * */ multi_modelstruct* alloc_multimodelstruct(gsl_matrix *xmodel_in, gsl_matrix *training_matrix_in, int cov_fn_index, int regression_order, double varfrac) { assert(training_matrix_in->size1 == xmodel_in->size1); assert(training_matrix_in->size1 > 0); assert(training_matrix_in->size2 > 0); assert(xmodel_in->size2 > 0); int i; double mean_temp = 0.0; int nt = training_matrix_in->size2; int nmodel_points = xmodel_in->size1; int nparams = xmodel_in->size2; gsl_vector_view col_view; /* use default if out of range */ if (regression_order < 0 || regression_order > 3) regression_order = 0; /* use a sensible default for the variance fraction */ if(varfrac < 0 || varfrac > 1) varfrac = 0.95; /* ntheta is a function of cov_fn_index and nparams */ int nthetas; if ((cov_fn_index == MATERN32) || (cov_fn_index == MATERN52)) { nthetas = 3; } else if (cov_fn_index == POWEREXPCOVFN) { nthetas = nparams + 2; } else { cov_fn_index = POWEREXPCOVFN; nthetas = nparams + 2; } // this doesn't seem to be allocating correctly, seems to be a broken defn of MallocChecked // strangely, code will build in this case... //multi_modelstruct * model = (multi_modelstruct*)MallocChecked(sizeof(multi_modelstruct)); multi_modelstruct * model = (multi_modelstruct*)malloc(sizeof(multi_modelstruct)); // fill in model->nt = nt; model->nr = 0; // init at zero model->nmodel_points = nmodel_points; model->nparams = nparams; model->xmodel = xmodel_in; model->training_matrix = training_matrix_in; model->training_mean = gsl_vector_alloc(nt); model->regression_order = regression_order; model->cov_fn_index = cov_fn_index; /* fill in the mean vector, should probably sum this more carefully... */ for(i = 0; i < nt; i++){ col_view = gsl_matrix_column(model->training_matrix, i); mean_temp = vector_elt_sum(&col_view.vector, nmodel_points); //printf("%lf\n", (mean_temp/((double)nmodel_points))); gsl_vector_set(model->training_mean, i, (mean_temp/((double)nmodel_points)) ); } /* carry out the pca decomp on this model, this is defined in multivar_support for now * this will fill in nr, pca_eigenvalues, pca_eigenvectors, pca_evals_r, pca_evecs_r * * this is making a mess if nt = 1 */ gen_pca_decomp(model, varfrac); /* fill in pca_model_array */ gen_pca_model_array(model); return model; } /** * fill in pca_model_array * requires: * - the pca decomp to have been calculated, so nr and all the pca_... fields are allocated and filled in * - m to have been allocated up to: nt, nmodel_points, and xmodel * * is it possible we could start running out of memory doing all these allocs? */ void gen_pca_model_array(multi_modelstruct *m) { int nr = m->nr; int i; gsl_vector_view col_view; gsl_vector* temp_train_vector = gsl_vector_alloc(m->nmodel_points); //gsl_matrix* temp_xmodel = gsl_matrix_alloc(m->nmodel_points, m->nparams); //gsl_matrix_mempcy(temp_xmodel, m->xmodel); // alloc the array of nr model structs //m->pca_model_array = (modelstruct**)MallocChecked(sizeof(modelstruct*)*nr); m->pca_model_array = (modelstruct**)malloc(sizeof(modelstruct*)*nr); // fill in the modelstructs correctly for(i = 0; i < nr; i++){ col_view = gsl_matrix_column(m->pca_zmatrix, i); gsl_vector_memcpy(temp_train_vector, &(col_view.vector)); // this isn't copying in the training vector correctly for somereason m->pca_model_array[i] = alloc_modelstruct_2(m->xmodel, temp_train_vector, m->cov_fn_index, m->regression_order); // see if brute forcing it will work m->pca_model_array[i]->training_vector = gsl_vector_alloc(m->nmodel_points); gsl_vector_memcpy(m->pca_model_array[i]->training_vector, temp_train_vector); } gsl_vector_free(temp_train_vector); } /** * carries out a pca decomp on m->training_matrix; * setting m->nr, m->pca_eigenvalues, m->pca_eigenvectors and * initializing m->pca_model_array * * the pca decomp is pretty simple: * let Y_ij = m->y_training * let mu_i = (1/nmodel_points) sum_{j=1}^{nmodel_points} Y_{ij} // the sample mean * let ysub_i = Y_i - rep(mu_i,nmodel_points) //subtract the sample means from each column * let sigma_ij = (1/nmodel_points) ( ysub * t(ysub)) // this is the covariance matrix * * then all we need to do is compute the eigendecomposition * * sigma_ij = U^{-1} Lambda U * * where Lambda is a diagonal matrix of t eigenvalues and U is a t x t matrix with the eigenvectors as columns * * requires: * - 0 < vfrac < 1 (0.95 is a good value) * - m to have allocated and filled out, nt, nmodel_points, trianing_matrix, (doesn't need xmodel explicitly) */ void gen_pca_decomp(multi_modelstruct *m, double vfrac) { FILE *fptr; // for debug output int i,j; int nt = m->nt; int retval; double total_variance = 0.0, frac = 0.0; gsl_matrix *pca_zmatrix_temp; gsl_matrix *y_sub_mat = gsl_matrix_alloc(m->nmodel_points, nt); gsl_matrix *y_temp_mat = gsl_matrix_alloc(m->nmodel_points, nt); gsl_matrix *y_cov_mat = gsl_matrix_alloc(nt, nt); gsl_vector *evals_temp = gsl_vector_alloc(nt); gsl_matrix *evecs_temp = gsl_matrix_alloc(nt,nt); gsl_eigen_symmv_workspace *ework = gsl_eigen_symmv_alloc(nt); gsl_vector_view col_view; // why is this here? gsl_matrix_memcpy(y_sub_mat, m->training_matrix); // subtract out the mean for(i = 0; i < nt; i++){ //col_view = gsl_matrix_column(y_sub_mat, i); printf("# y(%d) mean: %lf\n", i, gsl_vector_get(m->training_mean, i)); for(j = 0; j < m->nmodel_points; j++){ gsl_matrix_set(y_sub_mat, j, i, gsl_matrix_get(y_sub_mat, j, i) - gsl_vector_get(m->training_mean, i)); } } // compute the sample-variance, by multiplying y_sub_mat, with itself transposed gsl_matrix_memcpy(y_temp_mat, y_sub_mat); gsl_matrix_set_zero(y_cov_mat); /** — Function: int gsl_blas_dgemm (CBLAS_TRANSPOSE_t TransA, CBLAS_TRANSPOSE_t TransB, double alpha, const gsl_matrix * A, const gsl_matrix * B, double beta, gsl_matrix * C) (always forget this one)*/ /* want C (nt x nt ) so we need to do: (nt x nmodel_points) * (nmodel_points x nt) */ /** * this is strange, the upper triangle is not obviously correct */ //retval = gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, y_temp_mat, y_sub_mat, 0.0, y_cov_mat); retval = gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, y_sub_mat, y_temp_mat, 0.0, y_cov_mat); if(retval){ printf("# gen_pca_decomp:gsl_blas_dgemm %s\n", gsl_strerror(retval)); exit(EXIT_FAILURE); } gsl_matrix_scale(y_cov_mat, (1.0/((double)m->nmodel_points))); /** * debug output */ #ifdef DEBUGPCA fptr = fopen("pca-debug.dat","w"); fprintf(fptr, "# ycov:\n"); for(j = 0; j < nt; j++){ for(i = 0; i < nt; i++) fprintf(fptr, "%lf ", gsl_matrix_get(y_cov_mat, i, j)); fprintf(fptr, "\n"); } #endif /** now the eigendecomp * y_cov_mat is symmetric and better be real so we can use gsl_eigen_symmv, * note that the ?upper? triangle of y_cov_mat is borked during this process * also: the evals are not sorted by order, but the evectors are in the order of the evalues. * so we need to sort the evalues and the evectors correctly before we can use them * using * — Function: int gsl_eigen_symmv_sort (gsl_vector * eval, gsl_matrix * evec, gsl_eigen_sort_t sort_type) * sort them into descending order (biggest first) */ gsl_eigen_symmv(y_cov_mat, evals_temp, evecs_temp, ework); gsl_eigen_symmv_sort(evals_temp, evecs_temp, GSL_EIGEN_SORT_VAL_DESC); /** * eigenvectors are stored in columns of pca_evecs*/ total_variance = vector_elt_sum(evals_temp, nt); #ifdef DEBUGPCA fprintf(fptr, "# evals:\n"); for(i = 0; i < nt; i++) fprintf(fptr, "%lf %lf\n", gsl_vector_get(evals_temp, i), gsl_vector_get(evals_temp, i) / total_variance); fprintf(fptr, "# evecs:\n"); for(j = 0; j < nt; j++){ for(i = 0; i < nt; i++) fprintf(fptr, "%lf ", gsl_matrix_get(evecs_temp, i, j)); fprintf(fptr, "\n"); } #endif i=0; while( frac < vfrac && (i+1) < nt){ frac = (1.0/total_variance) * vector_elt_sum(evals_temp, i); i++; } m->nr = i; if(nt == 1){ //printf("# 1d case, nr=1\n"); m->nr = 1; } m->pca_evals_r = gsl_vector_alloc(m->nr); m->pca_evecs_r = gsl_matrix_alloc(m->nt, m->nr); // debug... fprintf(stderr, "# nr: %d frac: %lf\n", m->nr, frac); for(i = 0; i < m->nr; i++){ gsl_vector_set(m->pca_evals_r, i, gsl_vector_get(evals_temp, i)); col_view = gsl_matrix_column(evecs_temp, i); gsl_matrix_set_col(m->pca_evecs_r, i, &col_view.vector); } // fill in pca_zmatrix m->pca_zmatrix = gsl_matrix_alloc(m->nmodel_points, m->nr); pca_zmatrix_temp = gsl_matrix_alloc(m->nmodel_points, m->nr); // zmat: (nmodel_points x nr) = (nmodel_points x nt) * ( nt x nr ) /** — Function: int gsl_blas_dgemm (CBLAS_TRANSPOSE_t TransA, CBLAS_TRANSPOSE_t TransB, double alpha, const gsl_matrix * A, const gsl_matrix * B, double beta, gsl_matrix * C) (always forget this one)*/ gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, y_sub_mat, m->pca_evecs_r, 0.0, m->pca_zmatrix); #ifdef DEBUGPCA fprintf(fptr, "# evecs R:\n"); for(i = 0; i < m->nt; i++){ for(j = 0; j < m->nr; j++) fprintf(fptr, "%lf ", gsl_matrix_get(m->pca_evecs_r, i, j)); fprintf(fptr, "\n"); } #endif gsl_matrix_free(y_temp_mat); y_temp_mat = gsl_matrix_alloc(m->nr, m->nr); for(i = 0; i < m->nr; i++) // scale the diagonal by the evalue */ gsl_matrix_set(y_temp_mat, i, i, 1.0/(sqrt(gsl_vector_get(m->pca_evals_r, i)))); //print_matrix(y_temp_mat, m->nr, m->nr); // if nr != nt this won't work! //gsl_matrix_memcpy(y_sub_mat, m->pca_zmatrix); gsl_matrix_memcpy(pca_zmatrix_temp, m->pca_zmatrix); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, pca_zmatrix_temp, y_temp_mat, 0.0, m->pca_zmatrix); #ifdef DEBUGPCA fprintf(fptr, "# zmat:\n"); for(i = 0; i < 5; i++){ for(j = 0; j < m->nr; j++) fprintf(fptr, "%lf ", gsl_matrix_get(m->pca_zmatrix, i, j)); fprintf(fptr, "\n"); } fclose(fptr); #endif gsl_vector_free(evals_temp); gsl_matrix_free(evecs_temp); gsl_matrix_free(pca_zmatrix_temp); gsl_eigen_symmv_free(ework); gsl_matrix_free(y_sub_mat); gsl_matrix_free(y_temp_mat); gsl_matrix_free(y_cov_mat); } /** * dump the multimodelstruct to fptr, follows from dump_modelstruct_2 * we first dump the new fields and then iterate through the nr additional models which are dumped as before * so we dump a lot of the same info, but this is probably ok, the advantage is that each section defining * a model can be pulled out and worked on separately... */ void dump_multi_modelstruct(FILE* fptr, multi_modelstruct *m){ assert(fptr); int i,j; int nt = m->nt; int nr = m->nr; int nparams = m->nparams; int nmodel_points = m->nmodel_points; int cov_fn_index = m->cov_fn_index; int regression_order = m->regression_order; fprintf(fptr, "%d\n", nt); fprintf(fptr, "%d\n", nr); fprintf(fptr, "%d\n", nparams); fprintf(fptr, "%d\n", nmodel_points); fprintf(fptr, "%d\n", cov_fn_index); fprintf(fptr, "%d\n", regression_order); // multimodel thetas are inside pca_model_array... for(i = 0; i < nmodel_points; i++){ for(j = 0; j < nparams; j++) fprintf(fptr, "%.17lf ", gsl_matrix_get(m->xmodel, i, j)); fprintf(fptr, "\n"); } for(i = 0; i < nmodel_points; i++){ for(j = 0; j < nt; j++) fprintf(fptr, "%.17lf ", gsl_matrix_get(m->training_matrix, i, j)); fprintf(fptr, "\n"); } // now the rest of the pca information for(i = 0; i < nr; i++) fprintf(fptr, "%.17lf ", gsl_vector_get(m->pca_evals_r, i)); fprintf(fptr, "\n"); for(i = 0; i < nt; i++){ for(j = 0; j < nr; j++) fprintf(fptr, "%.17lf ", gsl_matrix_get(m->pca_evecs_r, i, j)); fprintf(fptr, "\n"); } for(i = 0; i < nmodel_points; i++){ for(j = 0; j < nr; j++) fprintf(fptr, "%.17lf ", gsl_matrix_get(m->pca_zmatrix, i, j)); fprintf(fptr, "\n"); } // now the pca_model_array // these could go in separate files... for(i = 0; i < nr; i++){ dump_modelstruct_2(fptr, m->pca_model_array[i]); } } /** * loads a multivariate modelstructure from fptr */ multi_modelstruct *load_multi_modelstruct(FILE* fptr){ multi_modelstruct *m = (multi_modelstruct*)malloc(sizeof(multi_modelstruct)); int i,j; int nt, nr; int nparams, nmodel_points; int cov_fn_index; int regression_order; double mean_temp; gsl_vector_view col_view; fscanf(fptr, "%d%*c", & nt); fscanf(fptr, "%d%*c", & nr); fscanf(fptr, "%d%*c", & nparams); fscanf(fptr, "%d%*c", & nmodel_points); fscanf(fptr, "%d%*c", & cov_fn_index); fscanf(fptr, "%d%*c", & regression_order); m->nt = nt; m->nr = nr; m->nparams = nparams; m->nmodel_points = nmodel_points; m->cov_fn_index = cov_fn_index; m->regression_order = regression_order; // now we can allocate everything in m m->xmodel = gsl_matrix_alloc(nmodel_points, nparams); m->training_matrix = gsl_matrix_alloc(nmodel_points, nt); m->training_mean = gsl_vector_alloc(nt); // do we need this? (yes!) m->pca_model_array = (modelstruct**)malloc(sizeof(modelstruct*)*nr); m->pca_evals_r = gsl_vector_alloc(nr); m->pca_evecs_r = gsl_matrix_alloc(nt, nr); m->pca_zmatrix = gsl_matrix_alloc(nmodel_points, nr); for(i = 0; i < nmodel_points; i++) for(j = 0; j < nparams; j++) fscanf(fptr, "%lf%*c", gsl_matrix_ptr(m->xmodel, i, j)); for(i = 0; i < nmodel_points; i++) for(j = 0; j < nt; j++) fscanf(fptr, "%lf%*c", gsl_matrix_ptr(m->training_matrix, i, j)); // now the rest of the pca information for(i = 0; i < nr; i++) fscanf(fptr, "%lf%*c", gsl_vector_ptr(m->pca_evals_r, i)); for(i = 0; i < nt; i++) for(j = 0; j < nr; j++) fscanf(fptr, "%lf%*c", gsl_matrix_ptr(m->pca_evecs_r, i, j)); for(i = 0; i < nmodel_points; i++) for(j = 0; j < nr; j++) fscanf(fptr, "%lf%*c", gsl_matrix_ptr(m->pca_zmatrix, i, j)); for(i = 0; i < nr; i++) m->pca_model_array[i] = load_modelstruct_2(fptr); /* fill in the mean vector */ for(i = 0; i < nt; i++){ col_view = gsl_matrix_column(m->training_matrix, i); mean_temp = vector_elt_sum(&col_view.vector, nmodel_points); gsl_vector_set(m->training_mean, i, (mean_temp/((double)nmodel_points)) ); } return m; } /** * return the sum of the elements of vec from 0:nstop */ double vector_elt_sum(gsl_vector* vec, int nstop) { assert(nstop >= 0); assert((unsigned)nstop <= vec->size); int i; double sum = 0.0; for(i = 0; i < nstop; i++){ sum += gsl_vector_get(vec, i); } return(sum); } /** * this free's everything in m */ void free_multimodelstruct(multi_modelstruct *m) { int i; gsl_vector_free(m->training_mean); for(i = 0; i < m->nr; i++){ free_modelstruct_2(m->pca_model_array[i]); //gsl_matrix_free(m->pca_model_array[i]->xmodel); } free(m->pca_model_array); gsl_matrix_free(m->xmodel); gsl_matrix_free(m->training_matrix); gsl_vector_free(m->pca_evals_r); gsl_matrix_free(m->pca_evecs_r); gsl_matrix_free(m->pca_zmatrix); }
Java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `strpbrk` fn in crate `libc`."> <meta name="keywords" content="rust, rustlang, rust-lang, strpbrk"> <title>libc::strpbrk - Rust</title> <link rel="stylesheet" type="text/css" href="../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../main.css"> <link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <a href='../libc/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='logo' width='100'></a> <p class='location'><a href='index.html'>libc</a></p><script>window.sidebarCurrent = {name: 'strpbrk', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content fn"> <h1 class='fqn'><span class='in-band'><a href='index.html'>libc</a>::<wbr><a class='fn' href=''>strpbrk</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-217' class='srclink' href='../src/libc/lib.rs.html#233' title='goto source code'>[src]</a></span></h1> <pre class='rust fn'>pub unsafe extern fn strpbrk(cs: <a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.pointer.html'>*const </a><a class='type' href='../libc/type.c_char.html' title='libc::c_char'>c_char</a>, ct: <a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.pointer.html'>*const </a><a class='type' href='../libc/type.c_char.html' title='libc::c_char'>c_char</a>) -&gt; <a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.pointer.html'>*mut </a><a class='type' href='../libc/type.c_char.html' title='libc::c_char'>c_char</a></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../"; window.currentCrate = "libc"; window.playgroundUrl = ""; </script> <script src="../jquery.js"></script> <script src="../main.js"></script> <script defer src="../search-index.js"></script> </body> </html>
Java
#!/bin/sh sudo apt-get install xorg-dev libglu1-mesa-dev -y # sfml-window sudo apt-get install libx11-dev -y sudo apt-get install libxcb1-dev -y sudo apt-get install libx11-xcb-dev -y sudo apt-get install libxcb-randr0-dev -y sudo apt-get install libxcb-image0-dev -y sudo apt-get install libgl1-mesa-dev -y sudo apt-get install libudev-dev -y # sfml-graphics sudo apt-get install libfreetype6-dev -y sudo apt-get install libjpeg-dev -y # sfml-audio sudo apt-get install libopenal-dev -y sudo apt-get install libflac-dev -y sudo apt-get install libvorbis-dev -y
Java
const core = require('brigadehub-core') var pkg = require('./package.json') var brigade = require('./brigade')()[0] const bhConfig = { dotenv: require('./dotenv')(), info: '[Brigadehub]', version: pkg.version, brigade: brigade } core(bhConfig)
Java
#include <assert.h> #include <stdint.h> #include <OpenP2P/Buffer.hpp> #include <OpenP2P/Stream/BinaryStream.hpp> #include <OpenP2P/Event/Source.hpp> #include <OpenP2P/Event/Wait.hpp> #include <OpenP2P/RootNetwork/Endpoint.hpp> #include <OpenP2P/RootNetwork/Packet.hpp> #include <OpenP2P/RootNetwork/PacketSocket.hpp> #include <OpenP2P/RootNetwork/SignedPacket.hpp> namespace OpenP2P { namespace RootNetwork { PacketSocket::PacketSocket(Socket<UDP::Endpoint, Buffer>& udpSocket) : udpSocket_(udpSocket) { } bool PacketSocket::isValid() const { return udpSocket_.isValid(); } Event::Source PacketSocket::eventSource() const { return udpSocket_.eventSource(); } bool PacketSocket::receive(Endpoint& endpoint, SignedPacket& signedPacket) { UDP::Endpoint udpEndpoint; Buffer buffer; if (!udpSocket_.receive(udpEndpoint, buffer)) { return false; } endpoint.kind = Endpoint::UDPIPV6; endpoint.udpEndpoint = udpEndpoint; BufferIterator bufferIterator(buffer); BinaryIStream blockingReader(bufferIterator); signedPacket.packet = ReadPacket(blockingReader); signedPacket.signature = ReadSignature(blockingReader); return true; } bool PacketSocket::send(const Endpoint& endpoint, const SignedPacket& signedPacket) { assert(endpoint.kind == Endpoint::UDPIPV6); Buffer buffer; BufferBuilder bufferBuilder(buffer); BinaryOStream blockingWriter(bufferBuilder); WritePacket(blockingWriter, signedPacket.packet); WriteSignature(blockingWriter, signedPacket.signature); return udpSocket_.send(endpoint.udpEndpoint, buffer); } } }
Java
/* -*- C++ -*- */ #include <QtGlobal> #include <QtAlgorithms> #include <QChar> #include <QDebug> #include <QList> #include <QMap> #include <QPointer> #include <QRegExp> #include <QSettings> #include <QSharedData> #include <QSharedDataPointer> #include "qluaapplication.h" #include "qtluaengine.h" #include "qluamainwindow.h" #include "qluatextedit.h" #include "qluamode.h" #include <string.h> #include <ctype.h> #define DEBUG 0 // ======================================== // USERDATA namespace { enum TokenType { // generic tokens Other, Identifier, Number, String, // tokens SemiColon, ThreeDots, Comma, Dot, Colon, LParen, RParen, LBracket, RBracket, LBrace, RBrace, // keywords Kand, Kfalse, Kfunction, Knil, Knot, Kor, Ktrue, Kin, // keywords that kill statements Kbreak, Kdo, Kelse, Kelseif, Kend, Kfor, Kif, Klocal, Krepeat, Kreturn, Kthen, Kuntil, Kwhile, // special Eof, Chunk, Statement, StatementCont, FunctionBody, FunctionName, FirstKeyword = Kand, FirstStrictKeyword = Kbreak, }; struct Keywords { const char *text; TokenType type; }; Keywords skeywords[] = { {"and", Kand}, {"break", Kbreak}, {"do", Kdo}, {"else", Kelse}, {"elseif", Kelseif}, {"end", Kend}, {"false", Kfalse}, {"for", Kfor}, {"function", Kfunction}, {"if", Kif}, {"in", Kin}, {"local", Klocal}, {"nil", Knil}, {"not", Knot}, {"or", Kor}, {"repeat", Krepeat}, {"return", Kreturn}, {"then", Kthen}, {"true", Ktrue}, {"until", Kuntil}, {"while", Kwhile}, {";", SemiColon}, {"...", ThreeDots}, {",", Comma}, {".", Dot}, {":", Colon}, {"(", LParen}, {")", RParen}, {"[", LBracket}, {"]", RBracket}, {"{", LBrace}, {"}", RBrace}, {0} }; struct Node; struct PNode : public QSharedDataPointer<Node> { PNode(); PNode(TokenType t, int p, int l, PNode n); PNode(TokenType t, int p, int l, int i, PNode n); TokenType type() const; int pos() const; int len() const; int indent() const; PNode next() const; }; struct Node : public QSharedData { Node(TokenType t, int p, int l, PNode n) : next(n), type(t),pos(p),len(l),indent(-1) {} Node(TokenType t, int p, int l, int i, PNode n) : next(n), type(t),pos(p),len(l),indent(i) {} PNode next; TokenType type; int pos; int len; int indent; }; PNode::PNode() : QSharedDataPointer<Node>() {} PNode::PNode(TokenType t, int p, int l, PNode n) : QSharedDataPointer<Node>(new Node(t,p,l,n)) {} PNode::PNode(TokenType t, int p, int l, int i, PNode n) : QSharedDataPointer<Node>(new Node(t,p,l,i,n)) {} inline TokenType PNode::type() const { const Node *n = constData(); return (n) ? n->type : Chunk; } inline int PNode::pos() const { const Node *n = constData(); return (n) ? n->pos : 0; } inline int PNode::len() const { const Node *n = constData(); return (n) ? n->len : 0; } inline int PNode::indent() const { const Node *n = constData(); return (n) ? n->indent : 0; } inline PNode PNode::next() const { const Node *n = constData(); return (n) ? n->next : PNode(); } struct UserData : public QLuaModeUserData { // lexical state int lexState; int lexPos; int lexN; // parser state PNode nodes; int lastPos; // initialize UserData() : lexState(0), lexPos(0), lexN(0), lastPos(0) {} virtual int highlightState() { return (lexState<<16)^lexN; } }; } // ======================================== // QLUAMODELUA class QLuaModeLua : public QLuaMode { Q_OBJECT public: QLuaModeLua(QLuaTextEditModeFactory *f, QLuaTextEdit *e); void gotLine(UserData *d, int pos, int len, QString); void gotToken(UserData *d, int pos, int len, QString, TokenType); bool supportsComplete() { return true; } bool supportsLua() { return true; } virtual void parseBlock(int pos, const QTextBlock &block, const QLuaModeUserData *idata, QLuaModeUserData *&odata ); QStringList computeFileCompletions(QString s, bool escape, QString &stem); QStringList computeSymbolCompletions(QString s, QString &stem); virtual bool doComplete(); private: QMap<QString,TokenType> keywords; QRegExp reNum, reSym, reId; int bi; }; QLuaModeLua::QLuaModeLua(QLuaTextEditModeFactory *f, QLuaTextEdit *e) : QLuaMode(f,e), reNum("^(0x[0-9a-fA-F]+|\\.[0-9]+|[0-9]+(\\.[0-9]*)?([Ee][-+]?[0-9]*)?)"), reSym("^(\\.\\.\\.|<=|>=|==|~=|.)"), reId("^[A-Za-z_][A-Za-z0-9_]*"), bi(3) { // basic indent QSettings s; s.beginGroup("luaMode"); bi = s.value("basicIndent", 3).toInt(); // tokens for (int i=0; skeywords[i].text; i++) keywords[QString(skeywords[i].text)] = skeywords[i].type; } void QLuaModeLua::parseBlock(int pos, const QTextBlock &block, const QLuaModeUserData *idata, QLuaModeUserData *&odata ) { QString text = block.text(); UserData *data = new UserData; // input state if (idata) *data = *static_cast<const UserData*>(idata); // hack for statements that seem complete if (data->nodes.type() == Statement) setIndent(data->lastPos, data->nodes.next().indent()); // process line gotLine(data, pos, block.length(), block.text()); // flush parser stack on last block if (! block.next().isValid()) gotToken(data, data->lastPos+1, 0, QString(), Eof); // output state odata = data; } // ======================================== // QLUAMODELUA - LEXICAL ANALYSIS void QLuaModeLua::gotLine(UserData *d, int pos, int len, QString s) { // default indent if (pos == 0) setIndent(-1, 0); // lexical analysis int p = 0; int n = d->lexN; int r = d->lexPos - pos; int state = d->lexState; int slen = s.size(); while (p < len) { int c = (p < slen) ? s[p].toAscii() : '\n'; switch(state) { case 0: state = -1; if (c == '#') { r = p; n = 0; state = -4; } continue; default: case -1: if (isspace(c)) { break; } if (isalpha(c) || c=='_') { r = p; state = -2; } else if (c=='\'') { setIndentOverlay(pos+p+1, -1); r = p; n = -c; state = -3; } else if (c=='\"') { setIndentOverlay(pos+p+1, -1); r = p; n = -c; state = -3; } else if (c=='[') { r = p; n = 0; state = -3; int t = p + 1; while (t < slen && s[t] == '=') t += 1; if (t < slen && s[t] == '[') { n = t - p; setIndentOverlay(pos+p, -1); } else { state = -1; gotToken(d, pos+p, 1, QString(), LBracket); } } else if (c=='-' && p+1 < slen && s[p+1]=='-') { r = p; n = 0; state = -4; if (p+2 < slen && s[p+2]=='[') { int t = p + 3; while (t < slen && s[t] == '=') t += 1; if (t < slen && s[t] == '[') { n = t - p - 2; setIndentOverlay(pos+p, 0); setIndentOverlay(pos+t+1, (n > 1) ? -1 : e->indentAfter(pos+t+1, +1) ); } } } else if (reNum.indexIn(s,p,QRegExp::CaretAtOffset)>=0) { int l = reNum.matchedLength(); QString m = s.mid(p,l); setFormat(pos+p, l, "number"); gotToken(d, pos+p, l, m, Number); p += l - 1; } else if (reSym.indexIn(s,p,QRegExp::CaretAtOffset)>=0) { int l = reSym.matchedLength(); QString m = s.mid(p,l); if (keywords.contains(m)) gotToken(d, pos+p, l, QString(), keywords[m]); else gotToken(d, pos+p, l, m, Other); p += l - 1; } break; case -2: // identifier if (!isalnum(c) && c!='_') { QString m = s.mid(r, p-r); if (keywords.contains(m)) { setFormat(pos+r, p-r, "keyword"); gotToken(d, pos+r, p-r, QString(), keywords[m]); } else gotToken(d, pos+r, p-r, m, Identifier); state = -1; continue; } break; case -3: // string if (n <= 0 && (c == -n || c == '\n' || c == '\r')) { setFormat(pos+r,p-r+1,"string"); setIndentOverlay(pos+p+1); gotToken(d, pos+r,p-r+1, QString(), String); state = -1; } else if (n <= 0 && c=='\\') { p += 1; } else if (n > 0 && c==']' && p>=n && s[p-n]==']') { int t = p - n + 1; while (t < slen && s[t] == '=') t += 1; if (t == p) { setFormat(pos+r,p-r+1,"string"); setIndentOverlay(pos+p+1); gotToken(d, pos+r,p-r+1,QString(),String); state = -1; } } break; case -4: // comment if (n <= 0 && (c == '\n' || c == '\r')) { setFormat(pos+r, p-r, "comment"); state = -1; } else if (n > 0 && c==']' && p>=n && s[p-n]==']') { int t = p - n + 1; while (t < slen && s[t] == '=') t += 1; if (t == p) { setFormat(pos+r, p-r+1, "comment"); setIndentOverlay(pos+p-n, 2); setIndentOverlay(pos+p+1); state = -1; } } break; } p += 1; } // save state d->lexN = n; d->lexPos = r + pos; d->lexState = state; // format incomplete tokens if (state == -4) setFormat(qMax(pos,pos+r),qMin(len,len-r),"comment"); else if (state == -3) setFormat(qMax(pos,pos+r),qMin(len,len-r),"string"); } // ======================================== // QLUAMODELUA - PARSING #if DEBUG QDebug operator<<(QDebug d, const TokenType &t) { d.nospace(); # define DO(x) if (t==x) d << #x; else DO(Other) DO(Identifier) DO(Number) DO(String) DO(SemiColon) DO(ThreeDots) DO(Comma) DO(Dot) DO(Colon) DO(LParen) DO(RParen) DO(LBracket) DO(RBracket) DO(LBrace) DO(RBrace) DO(Kand) DO(Kfalse) DO(Kfunction) DO(Knil) DO(Knot) DO(Kor) DO(Ktrue) DO(Kin) DO(Kbreak) DO(Kdo) DO(Kelse) DO(Kelseif) DO(Kend) DO(Kfor) DO(Kif) DO(Klocal) DO(Krepeat) DO(Kreturn) DO(Kthen) DO(Kuntil) DO(Kwhile) DO(Statement) DO(StatementCont) DO(Chunk) DO(FunctionBody) DO(FunctionName) DO(Eof) # undef DO d << "<Unknown>"; return d.space(); } #endif void QLuaModeLua::gotToken(UserData *d, int pos, int len, QString s, TokenType ltype) { PNode &n = d->nodes; TokenType ntype = n.type(); #if DEBUG qDebug() << " node:" << n << ntype << n.pos() << n.len() << n.indent() << n.next().type() << n.next().next().type(); if (s.isEmpty()) qDebug() << " token:" << pos << len << ltype; else qDebug() << " token:" << pos << len << ltype << s; #endif // close statements if ( ((ntype==Statement) && (ltype==Identifier || ltype==Kfunction) ) || ((ntype==Statement || ntype==StatementCont || ntype==Klocal || ntype==Kreturn ) && (ltype==SemiColon || ltype>=FirstStrictKeyword) ) ) { int epos = (ltype==SemiColon) ? pos+len : d->lastPos; int spos = n.pos(); n = n.next(); setBalance(spos, epos, n.type()==Chunk); setIndent(epos, n.indent()); } if ((ntype == FunctionName || ntype == Kfunction) && (ltype!=Identifier && ltype!=Dot && ltype!=Colon) ) { if (ntype == FunctionName) n=n.next(); ntype = n->type = FunctionBody; setIndent(pos, n.indent()); } ntype = n.type(); // fixup hacked indents if (ntype == StatementCont) n->type = Statement; if (d->lastPos < pos && ntype == Statement) setIndent(pos, n.indent()); d->lastPos = pos + len; // parse switch (ltype) { badOne: { setIndent(pos, -1); while (n.type() != Chunk && n.len() == 0) n = n.next(); setErrorMatch(pos, len, n.pos(), n.len()); n = n.next(); setIndent(pos+len, n.indent()); break; } case RParen: if (ntype != LParen) goto badOne; goto rightOne; case RBracket: if (ntype != LBracket) goto badOne; goto rightOne; case RBrace: if (ntype != LBrace) goto badOne; goto rightOne; case Kend: if (ntype!=Kdo && ntype!=Kelse && ntype!=Kthen && ntype!=Kfunction && ntype!=FunctionBody) goto badOne; rightOne: { setRightMatch(pos, len, n.pos(), n.len()); int fpos = followMatch(n.pos(),n.len()); int indent = n.indent(); n = n.next(); if (ltype < FirstKeyword) indent = qMin(qMax(0,indent-bi),e->indentAt(fpos)); else indent = n.indent(); setIndent(pos, indent); setIndent(pos+len, n.indent()); setBalance(fpos, pos+len, n.type()==Chunk); break; } case Kuntil: if (ntype != Krepeat) goto badOne; { setRightMatch(pos, len, n.pos(), n.len()); setIndent(pos, n.next().indent()); setIndent(pos+len, n.indent()); n->len = 0; n->type = StatementCont; break; } case Kthen: if (ntype!=Kif && ntype!=Kelseif) goto badOne; goto middleOne; case Kelse: case Kelseif: if (ntype!=Kthen) goto badOne; middleOne: { setMiddleMatch(pos, len, n.pos(), n.len()); setIndent(pos, n.next().indent()); setIndent(pos+len, n.indent()); n->type = ltype; n->pos = pos; n->len = len; break; } case Kdo: if (ntype==Kfor || ntype==Kwhile) goto middleOne; goto leftOne; case Kfunction: if (ntype == Klocal) goto middleOne; goto leftOne; case Kfor: case Kif: case Kwhile: case Krepeat: case Klocal: case Kreturn: case LParen: case LBracket: case LBrace: leftOne: { int indent = n.indent() + bi; if (ltype == LBrace && ntype == StatementCont) indent = n.indent(); else if (ltype < FirstKeyword) indent = e->indentAfter(pos+len); setIndent(pos, n.indent()); n = PNode(ltype, pos, len, indent, n); setIndent(pos+len, indent); setLeftMatch(pos, len); break; } case SemiColon: case Eof: break; case Identifier: if (ntype == Kfunction) n = PNode(FunctionName, pos, len, n.indent(), n); if (n.type() == FunctionName) setFormat(pos, len, "function"); goto openStatement; case Dot: case Colon: if (ntype == FunctionName) setFormat(pos, len, "function"); case Kand: case Kor: case Knot: case Kin: case Comma: case Other: if (n.type() == Statement) { n->type = StatementCont; setIndent(pos, n.indent()); } default: openStatement: { if (ntype==Chunk || ntype==Kdo || ntype==Kthen || ntype==Kelse || ntype==Krepeat || ntype==FunctionBody) { int indent = n.indent() + bi; n = PNode(Statement, pos, 0, indent, n); setIndent(pos+len, indent); } else if (ntype==Klocal) n->type = StatementCont; else if (ntype==Kreturn) n->type = Statement; break; } } } // ======================================== // COMPLETION static int comp_lex(QString s, int len, int state, int n, int &q) { QChar z; int p = 0; while (p < len) { switch(state) { default: case -1: // misc if (isalpha(s[p].toAscii()) || s[p]=='_') { q = p; state = -2; } else if (s[p]=='\'') { q = p+1; z = s[p]; n = 0; state = -3; } else if (s[p]=='\"') { q = p+1; z = s[p]; n = 0; state = -3; } else if (s[p]=='[') { n = 0; state = -3; int t = p + 1; while (t < len && s[t] == '=') t += 1; if (t < len && s[t] == '[') { q = t + 1; n = t - p; } else state = -1; } else if (s[p]=='-' && s[p+1]=='-') { n = 0; state = -4; if (s[p+2]=='[') { int t = p + 3; while (t < len && s[t] == '=') t += 1; if (t < len && s[t] == '[') n = t - p - 2; } } break; case -2: // identifier if (!isalnum(s[p].toAscii()) && s[p]!='_' && s[p]!='.' && s[p]!=':') { state = -1; continue; } break; case -3: // string if (n == 0 && s[p] == z) { state = -1; } else if (n == 0 && s[p]=='\\') { p += 1; } else if (n && s[p]==']' && p>=n && s[p-n]==']') { int t = p - n + 1; while (t < len && s[t] == '=') t += 1; if (t == p) state = -1; } break; case -4: // comment if (n == 0 && (s[p] == '\n' || s[p] == '\r')) { state = -1; } else if (n && s[p]==']' && p>=n && s[p-n]==']') { int t = p - n + 1; while (t < len && s[t] == '=') t += 1; if (t == p) state = -1; } break; } p += 1; } return state; } bool QLuaModeLua::doComplete() { QString stem; QStringList completions; QTextCursor c = e->textCursor(); QTextBlock b = c.block(); int len = c.position() - b.position(); QString text = b.text().left(len); int state = -1; int q = 0; int n = 0; QTextBlock pb = b.previous(); if (pb.isValid()) { UserData *data = static_cast<UserData*>(pb.userData()); if (! data) return false; state = data->lexState; n = data->lexN; } state = comp_lex(text, len, state, n, q); if (state == -3 && q >= 0 && q <= len) completions = computeFileCompletions(text.mid(q, len-q), n>0, stem); if (state == -2 && q >= 0 && q <= len) completions = computeSymbolCompletions(text.mid(q, len-q), stem); int selected = 0; if (completions.size() > 1) { qSort(completions.begin(), completions.end()); for (int i=completions.size()-2; i>=0; i--) if (completions[i] == completions[i+1]) completions.removeAt(i); selected = askCompletion(stem, completions); } if (selected >= 0 && selected < completions.size()) { c.insertText(completions[selected]); e->setTextCursor(c); return true; } return false; } static const char *escape1 = "abfnrtv"; static const char *escape2 = "\a\b\f\n\r\t\v"; static QByteArray unescapeString(const char *s) { int c; QByteArray r; while ((c = *s++)) { if (c != '\\') r += c; else { c = *s++; const char *e = strchr(escape1, c); if (e) r += escape2[e - escape1]; else if (c >= '0' && c <= '7') { c = c - '0'; if (*s >= '0' && *s <= '7') c = c * 8 + *s++ - '0'; if (*s >= '0' && *s <= '7') c = c * 8 + *s++ - '0'; r += c; } else r += c; } } return r; } static QString unescapeString(QString s) { return QString::fromLocal8Bit(unescapeString(s.toLocal8Bit().constData())); } static QByteArray escapeString(const char *s) { int c; QByteArray r; while ((c = *s++)) { const char *e; if (! isascii(c)) r += c; else if (iscntrl(c) && (e = strchr(escape2, c))) r += escape1[e - escape2]; else if (isprint(c) || isspace(c)) r += c; else { char buffer[8]; sprintf(buffer, "\\%03o", c); r += buffer; } } return r; } static QString escapeString(QString s) { return QString::fromLocal8Bit(escapeString(s.toLocal8Bit().constData())); } QStringList QLuaModeLua::computeFileCompletions(QString s, bool escape, QString &stem) { QStringList list; s.remove(QRegExp("^.*\\s")); stem = s; if (escape) stem = unescapeString(s); fileCompletion(stem, list); if (escape) { QStringList nl; foreach(QString s, list) nl += escapeString(s); stem = escapeString(stem); list = nl; } return list; } static const char * comp_keywords[] = { "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while", 0 }; QStringList QLuaModeLua::computeSymbolCompletions(QString s, QString &stem) { QStringList list; QByteArray f = s.toLocal8Bit(); int flen = f.size(); // stem stem = s.remove(QRegExp("^.*[.:]")); // keywords for (const char **k = comp_keywords; *k; k++) if (!strncmp(f.constData(), *k, flen)) list += QString::fromLocal8Bit(*k + flen); // symbols QtLuaEngine *engine = QLuaApplication::engine(); if (engine) { QtLuaLocker lua(engine, 250); struct lua_State *L = lua; if (lua) { lua_pushcfunction(L, luaQ_complete); lua_pushlstring(L, f.constData(), flen); if (!lua_pcall(L, 1, 1, 0) && lua_istable(L, -1)) { int n = lua_objlen(L, -1); for (int j=1; j<=n; j++) { lua_rawgeti(L, -1, j); list += QString::fromLocal8Bit(lua_tostring(L, -1)); lua_pop(L, 1); } } lua_pop(L, 1); } else { QWidget *w = e->window(); QLuaMainWindow *m = qobject_cast<QLuaMainWindow*>(w); if (m) m->showStatusMessage(tr("Auto-completions is restricted " "while Lua is running.") ); QLuaApplication::beep(); } } return list; } // ======================================== // FACTORY static QLuaModeFactory<QLuaModeLua> textModeFactory("Lua", "lua"); // ======================================== // MOC #include "qluamode_lua.moc" /* ------------------------------------------------------------- Local Variables: c++-font-lock-extra-types: ("\\sw+_t" "\\(lua_\\)?[A-Z]\\sw*[a-z]\\sw*") End: ------------------------------------------------------------- */
Java
// Copyright (c) 2020 The Gulden developers // Authored by: Malcolm MacLeod (mmacleod@gmx.com) // Distributed under the GULDEN software license, see the accompanying // file COPYING //Workaround braindamaged 'hack' in libtool.m4 that defines DLL_EXPORT when building a dll via libtool (this in turn imports unwanted symbols from e.g. pthread that breaks static pthread linkage) #ifdef DLL_EXPORT #undef DLL_EXPORT #endif // Unity specific includes #include "unity_impl.h" #include "libinit.h" // Standard gulden headers #include "appname.h" #include "clientversion.h" #include "util.h" #include "witnessutil.h" #include "ui_interface.h" #include "unity/appmanager.h" #include "utilmoneystr.h" #include <chain.h> #include "consensus/validation.h" #include "net.h" #include "wallet/mnemonic.h" #include "net_processing.h" #include "wallet/spvscanner.h" #include "sync.h" #include "init.h" // Djinni generated files #include "i_library_controller.hpp" #include "i_library_listener.hpp" #include "qr_code_record.hpp" #include "balance_record.hpp" #include "uri_record.hpp" #include "uri_recipient.hpp" #include "mutation_record.hpp" #include "input_record.hpp" #include "output_record.hpp" #include "address_record.hpp" #include "peer_record.hpp" #include "block_info_record.hpp" #include "monitor_record.hpp" #include "monitor_listener.hpp" #include "payment_result_status.hpp" #include "mnemonic_record.hpp" #ifdef __ANDROID__ #include "djinni_support.hpp" #endif // External libraries #include <boost/algorithm/string.hpp> #include <boost/program_options/parsers.hpp> #include <qrencode.h> #include <memory> #include "pow/pow.h" #include <crypto/hash/sigma/sigma.h> #include <algorithm> std::shared_ptr<ILibraryListener> signalHandler; CCriticalSection cs_monitoringListeners; std::set<std::shared_ptr<MonitorListener> > monitoringListeners; boost::asio::io_context ioctx; boost::asio::executor_work_guard<boost::asio::io_context::executor_type> work = boost::asio::make_work_guard(ioctx); boost::thread run_thread(boost::bind(&boost::asio::io_context::run, boost::ref(ioctx))); static const int64_t nClientStartupTime = GetTime(); std::vector<CAccount*> GetAccountsForAccount(CAccount* forAccount) { std::vector<CAccount*> forAccounts; forAccounts.push_back(forAccount); for (const auto& [accountUUID, account] : pactiveWallet->mapAccounts) { (unused) accountUUID; if (account->getParentUUID() == forAccount->getUUID()) { forAccounts.push_back(account); } } return forAccounts; } TransactionStatus getStatusForTransaction(const CWalletTx* wtx) { TransactionStatus status; int depth = wtx->GetDepthInMainChain(); if (depth < 0) status = TransactionStatus::CONFLICTED; else if (depth == 0) { if (wtx->isAbandoned()) status = TransactionStatus::ABANDONED; else status = TransactionStatus::UNCONFIRMED; } else if (depth < RECOMMENDED_CONFIRMATIONS) { status = TransactionStatus::CONFIRMING; } else { status = TransactionStatus::CONFIRMED; } return status; } std::string getRecipientAddressesForWalletTransaction(CAccount* forAccount, CWallet* pWallet, const CWalletTx* wtx, bool isSentByUs) { std::string address = ""; for (const CTxOut& txout: wtx->tx->vout) { bool isMine = false; if (forAccount && IsMine(*forAccount, txout)) { isMine = true; } if (!forAccount && pWallet && IsMine(*pWallet, txout)) { isMine = true; } if ((isSentByUs && !isMine) || (!isSentByUs && isMine)) { CNativeAddress addr; CTxDestination dest; if (!ExtractDestination(txout, dest) && !txout.IsUnspendable()) { dest = CNoDestination(); } if (addr.Set(dest)) { if (!address.empty()) address += ", "; address += addr.ToString(); } } } return address; } void addMutationsForTransaction(const CWalletTx* wtx, std::vector<MutationRecord>& mutations, CAccount* forAccount) { // exclude generated that are orphaned if (wtx->IsCoinBase() && wtx->GetDepthInMainChain() < 1) return; int64_t subtracted = wtx->GetDebit(ISMINE_SPENDABLE, forAccount, true); int64_t added = wtx->GetCredit(ISMINE_SPENDABLE, forAccount, true) + wtx->GetImmatureCredit(false, forAccount, true); uint64_t time = wtx->nTimeSmart; std::string hash = wtx->GetHash().ToString(); TransactionStatus status = getStatusForTransaction(wtx); int depth = wtx->GetDepthInMainChain(); // if any funds were subtracted the transaction was sent by us if (subtracted > 0) { int64_t fee = subtracted - wtx->tx->GetValueOut(); int64_t change = wtx->GetChange(); std::string recipientAddresses = getRecipientAddressesForWalletTransaction(forAccount, pactiveWallet, wtx, true); // detect internal transfer and split it if (subtracted - fee == added) { // amount received mutations.push_back(MutationRecord(added - change, time, hash, recipientAddresses, status, depth)); // amount send including fee mutations.push_back(MutationRecord(change - subtracted, time, hash, recipientAddresses, status, depth)); } else { mutations.push_back(MutationRecord(added - subtracted, time, hash, recipientAddresses, status, depth)); } } else if (added != 0) // nothing subtracted so we received funds { std::string recipientAddresses = getRecipientAddressesForWalletTransaction(forAccount, pactiveWallet, wtx, false); mutations.push_back(MutationRecord(added, time, hash, recipientAddresses, status, depth)); } } TransactionRecord calculateTransactionRecordForWalletTransaction(const CWalletTx& wtx, std::vector<CAccount*>& forAccounts, bool& anyInputsOrOutputsAreMine) { CWallet* pwallet = pactiveWallet; std::vector<InputRecord> inputs; std::vector<OutputRecord> outputs; int64_t subtracted=0; int64_t added=0; for (const auto& account : forAccounts) { subtracted += wtx.GetDebit(ISMINE_SPENDABLE, account, true); added += wtx.GetCredit(ISMINE_SPENDABLE, account, true); } CAmount fee = 0; // if any funds were subtracted the transaction was sent by us if (subtracted > 0) fee = subtracted - wtx.tx->GetValueOut(); const CTransaction& tx = *wtx.tx; for (const CTxIn& txin: tx.vin) { std::string address; CNativeAddress addr; CTxDestination dest = CNoDestination(); // Try to extract destination, this is not possible in general. Only if the previous // ouput of our input happens to be in our wallet. Which will usually only be the case for // our own transactions. uint256 txHash; if (txin.GetPrevOut().isHash) { txHash = txin.GetPrevOut().getTransactionHash(); } else { if (!pwallet->GetTxHash(txin.GetPrevOut(), txHash)) { LogPrintf("Transaction with no corresponding hash found, txid [%d] [%d]\n", txin.GetPrevOut().getTransactionBlockNumber(), txin.GetPrevOut().getTransactionIndex()); continue; } } std::map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(txHash); if (mi != pwallet->mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.GetPrevOut().n < prev.tx->vout.size()) { const auto& prevOut = prev.tx->vout[txin.GetPrevOut().n]; if (!ExtractDestination(prevOut, dest) && !prevOut.IsUnspendable()) { LogPrintf("Unknown transaction type found, txid %s\n", wtx.GetHash().ToString()); dest = CNoDestination(); } } } if (addr.Set(dest)) { address = addr.ToString(); } std::string label; std::string description; if (pwallet->mapAddressBook.count(address)) { const auto& data = pwallet->mapAddressBook[address]; label = data.name; description = data.description; } bool isMine = false; for (const auto& account : forAccounts) { if (static_cast<const CExtWallet*>(pwallet)->IsMine(*account, txin)) { isMine = true; anyInputsOrOutputsAreMine = true; } } inputs.push_back(InputRecord(address, label, description, isMine)); } for (const CTxOut& txout: tx.vout) { std::string address; CNativeAddress addr; CTxDestination dest; if (!ExtractDestination(txout, dest) && !txout.IsUnspendable()) { LogPrintf("Unknown transaction type found, txid %s\n", tx.GetHash().ToString()); dest = CNoDestination(); } if (addr.Set(dest)) { address = addr.ToString(); } std::string label; std::string description; if (pwallet->mapAddressBook.count(address)) { const auto& data = pwallet->mapAddressBook[address]; label = data.name; description = data.description; } bool isMine = false; for (const auto& account : forAccounts) { if (IsMine(*account, txout)) { isMine = true; anyInputsOrOutputsAreMine = true; } } outputs.push_back(OutputRecord(txout.nValue, address, label, description, isMine)); } TransactionStatus status = getStatusForTransaction(&wtx); return TransactionRecord(wtx.GetHash().ToString(), wtx.nTimeSmart, added - subtracted, fee, status, wtx.nHeight, wtx.nBlockTime, wtx.GetDepthInMainChain(), inputs, outputs); } // rate limited balance change notifier static CRateLimit<int>* balanceChangeNotifier=nullptr; // rate limited new mutations notifier static CRateLimit<std::pair<uint256, bool>>* newMutationsNotifier=nullptr; void terminateUnityFrontend() { if (signalHandler) { signalHandler->notifyShutdown(); } // Allow frontend time to clean up and free any references to objects before unloading the library // Otherwise we get a free after close (on macOS at least) while (signalHandler.use_count() > 1) { MilliSleep(50); } signalHandler=nullptr; } #include <boost/chrono/thread_clock.hpp> static float lastProgress=0; void handlePostInitMain() { //fixme: (SIGMA) (PHASE4) Remove this once we have witness-header-sync // Select appropriate verification factor based on devices performance. std::thread([=] { // When available measure thread relative cpu time to avoid effects of thread suspension // which occur when observing system time. #if false && defined(BOOST_CHRONO_HAS_THREAD_CLOCK) && BOOST_CHRONO_THREAD_CLOCK_IS_STEADY boost::chrono::time_point tpStart = boost::chrono::thread_clock::now(); #else uint64_t nStart = GetTimeMicros(); #endif // note that measurement is on single thread, which makes the measurement more stable // actual verification might use more threads which helps overall app performance sigma_verify_context verify(defaultSigmaSettings, 1); CBlockHeader header; verify.verifyHeader<1>(header); // We want at least 1000 blocks per second #if false && defined(BOOST_CHRONO_HAS_THREAD_CLOCK) && BOOST_CHRONO_THREAD_CLOCK_IS_STEADY boost::chrono::microseconds ms = boost::chrono::duration_cast<boost::chrono::microseconds>(boost::chrono::thread_clock::now() - tpStart); uint64_t nTotal = ms.count(); #else uint64_t nTotal = GetTimeMicros() - nStart; #endif uint64_t nPerSec = 1000000/nTotal; if (nPerSec > 1000) // Fast enough to do most the blocks { verifyFactor = 5; } else if(nPerSec > 0) // Slower so reduce the number of blocks { // 2 in verifyFactor chance of verifying. // We verify 2 in verifyFactor blocks - or target_speed/(num_per_sec/2) verifyFactor = 1000/(nPerSec/2.0); verifyFactor = std::max((uint64_t)5, verifyFactor); verifyFactor = std::min((uint64_t)200, verifyFactor); } LogPrintf("unity: selected verification factor %d", verifyFactor); }).detach(); if (signalHandler) { signalHandler->notifyCoreReady(); } // unified progress notification if (!GetBoolArg("-spv", DEFAULT_SPV)) { static bool haveFinishedHeaderSync=false; static int totalHeaderCount=0; static int startHeight = chainActive.Tip() ? chainActive.Tip()->nHeight : 0; // If tip is relatively recent set progress to "completed" to begin with if (chainActive.Tip() && ((GetTime() - chainActive.Tip()->nTime) < 3600)) { lastProgress = 1.0; } // Weight a full header sync as 20%, blocks as rest uiInterface.NotifyHeaderProgress.connect([=](int currentCount, int probableHeight, int headerTipHeight, int64_t headerTipTime) { totalHeaderCount = currentCount; if (currentCount == probableHeight) { haveFinishedHeaderSync = true; } if (!haveFinishedHeaderSync && signalHandler && IsInitialBlockDownload()) { float progress = ((((float)currentCount-startHeight)/((float)probableHeight-startHeight))*0.20); if (lastProgress != 1 && (progress-lastProgress > 0.02 || progress == 1)) { lastProgress = progress; signalHandler->notifyUnifiedProgress(progress); } } }); uiInterface.NotifyBlockTip.connect([=](bool isInitialBlockDownload, const CBlockIndex* pNewTip) { if (haveFinishedHeaderSync && signalHandler) { float progress = pNewTip->nHeight==totalHeaderCount?1:((0.20+((((float)pNewTip->nHeight-startHeight)/((float)totalHeaderCount-startHeight))*0.80))); if (lastProgress != 1 && (progress-lastProgress > 0.02 || progress == 1)) { lastProgress = progress; signalHandler->notifyUnifiedProgress(progress); } } }); } else { uiInterface.NotifyUnifiedProgress.connect([=](float progress) { if (signalHandler) { signalHandler->notifyUnifiedProgress(progress); } }); // monitoring listeners notifications uiInterface.NotifyHeaderProgress.connect([=](int, int, int, int64_t) { int32_t height, probable_height, offset; { LOCK(cs_main); height = partialChain.Height(); probable_height = GetProbableHeight(); offset = partialChain.HeightOffset(); } LOCK(cs_monitoringListeners); for (const auto &listener: monitoringListeners) { listener->onPartialChain(height, probable_height, offset); } }); uiInterface.NotifySPVPrune.connect([=](int height) { LOCK(cs_monitoringListeners); for (const auto &listener: monitoringListeners) { listener->onPruned(height); } }); uiInterface.NotifySPVProgress.connect([=](int /*start_height*/, int processed_height, int /*probable_height*/) { LOCK(cs_monitoringListeners); for (const auto &listener: monitoringListeners) { listener->onProcessedSPVBlocks(processed_height); } }); } // Update transaction/balance changes if (pactiveWallet) { // Fire events for transaction depth changes (up to depth 10 only) pactiveWallet->NotifyTransactionDepthChanged.connect( [&](CWallet* pwallet, const uint256& hash) { LOCK2(cs_main, pwallet->cs_wallet); if (pwallet->mapWallet.find(hash) != pwallet->mapWallet.end()) { const CWalletTx& wtx = pwallet->mapWallet[hash]; LogPrintf("unity: notify transaction depth changed %s",hash.ToString().c_str()); if (signalHandler) { std::vector<CAccount*> forAccounts = GetAccountsForAccount(pactiveWallet->activeAccount); bool anyInputsOrOutputsAreMine = false; TransactionRecord walletTransaction = calculateTransactionRecordForWalletTransaction(wtx, forAccounts, anyInputsOrOutputsAreMine); if (anyInputsOrOutputsAreMine) { signalHandler->notifyUpdatedTransaction(walletTransaction); } } } } ); // Fire events for transaction status changes, or new transactions (this won't fire for simple depth changes) pactiveWallet->NotifyTransactionChanged.connect( [&](CWallet* pwallet, const uint256& hash, ChangeType status, bool fSelfComitted) { LOCK2(cs_main, pwallet->cs_wallet); if (pwallet->mapWallet.find(hash) != pwallet->mapWallet.end()) { if (status == CT_NEW) { newMutationsNotifier->trigger(std::make_pair(hash, fSelfComitted)); } else if (status == CT_UPDATED && signalHandler) { LogPrintf("unity: notify tx updated %s",hash.ToString().c_str()); const CWalletTx& wtx = pwallet->mapWallet[hash]; std::vector<CAccount*> forAccounts = GetAccountsForAccount(pactiveWallet->activeAccount); bool anyInputsOrOutputsAreMine = false; TransactionRecord walletTransaction = calculateTransactionRecordForWalletTransaction(wtx, forAccounts, anyInputsOrOutputsAreMine); if (anyInputsOrOutputsAreMine) { signalHandler->notifyUpdatedTransaction(walletTransaction); } } //fixme: (UNITY) - Consider implementing f.e.x if a 0 conf transaction gets deleted... // else if (status == CT_DELETED) } balanceChangeNotifier->trigger(0); }); // Fire once immediately to update with latest on load. balanceChangeNotifier->trigger(0); } } void handleInitWithExistingWallet() { if (signalHandler) { signalHandler->notifyInitWithExistingWallet(); } AppLifecycleManager::gApp->initialize(); } void handleInitWithoutExistingWallet() { signalHandler->notifyInitWithoutExistingWallet(); } std::string ILibraryController::BuildInfo() { std::string info = FormatThreeDigitVersion(); #if defined(__aarch64__) info += " aarch64"; #elif defined(__arm__) info += " arm (32bit)"; #elif defined(__x86_64__) info += " x86_64"; #elif defined(__i386__) info += " x86"; #endif return info; } bool ILibraryController::InitWalletFromRecoveryPhrase(const std::string& phrase, const std::string& password) { // Refuse to acknowledge an empty recovery phrase, or one that doesn't pass even the most obvious requirement if (phrase.length() < 16) { return false; } //fixme: (UNITY) (SPV) - Handle all the various birth date (or lack of birthdate) cases here instead of just the one. SecureString phraseOnly; int phraseBirthNumber = 0; AppLifecycleManager::gApp->splitRecoveryPhraseAndBirth(phrase.c_str(), phraseOnly, phraseBirthNumber); if (!checkMnemonic(phraseOnly)) { return false; } // ensure that wallet is initialized with a starting time (else it will start from now and old tx will not be scanned) // Use the hardcoded timestamp 1441212522 of block 250000, we didn't have any recovery phrase style wallets (using current phrase system) before that. if (phraseBirthNumber == 0) phraseBirthNumber = timeToBirthNumber(1441212522L); //fixme: (UNITY) (SPV) - Handle all the various birth date (or lack of birthdate) cases here instead of just the one. AppLifecycleManager::gApp->setRecoveryPhrase(phraseOnly); AppLifecycleManager::gApp->setRecoveryBirthNumber(phraseBirthNumber); AppLifecycleManager::gApp->setRecoveryPassword(password.c_str()); AppLifecycleManager::gApp->isRecovery = true; AppLifecycleManager::gApp->initialize(); return true; } void DoRescanInternal() { if (pactiveWallet) { ResetSPVStartRescanThread(); } } bool ValidateAndSplitRecoveryPhrase(const std::string & phrase, SecureString& mnemonic, int& birthNumber) { if (phrase.length() < 16) return false; AppLifecycleManager::gApp->splitRecoveryPhraseAndBirth(phrase.c_str(), mnemonic, birthNumber); return checkMnemonic(mnemonic) && (birthNumber == 0 || Base10ChecksumDecode(birthNumber, nullptr)); } bool ILibraryController::ContinueWalletFromRecoveryPhrase(const std::string& phrase, const std::string& password) { SecureString phraseOnly; int phraseBirthNumber; if (!ValidateAndSplitRecoveryPhrase(phrase, phraseOnly, phraseBirthNumber)) return false; // ensure that wallet is initialized with a starting time (else it will start from now and old tx will not be scanned) // Use the hardcoded timestamp 1441212522 of block 250000, we didn't have any recovery phrase style wallets (using current phrase system) before that. if (phraseBirthNumber == 0) phraseBirthNumber = timeToBirthNumber(1441212522L); if (!pactiveWallet) { LogPrintf("ContineWalletFromRecoveryPhrase: No active wallet"); return false; } LOCK2(cs_main, pactiveWallet->cs_wallet); AppLifecycleManager::gApp->setRecoveryPhrase(phraseOnly); AppLifecycleManager::gApp->setRecoveryBirthNumber(phraseBirthNumber); AppLifecycleManager::gApp->setRecoveryPassword(password.c_str()); AppLifecycleManager::gApp->isRecovery = true; CWallet::CreateSeedAndAccountFromPhrase(pactiveWallet); // Allow update of balance for deleted accounts/transactions LogPrintf("%s: Update balance and rescan", __func__); balanceChangeNotifier->trigger(0); // Rescan for transactions on the linked account DoRescanInternal(); return true; } bool ILibraryController::IsValidRecoveryPhrase(const std::string & phrase) { SecureString dummyMnemonic; int dummyNumber; return ValidateAndSplitRecoveryPhrase(phrase, dummyMnemonic, dummyNumber); } #include "base58.h" std::string ILibraryController::GenerateGenesisKeys() { std::string address = GetReceiveAddress(); CNativeAddress addr(address); CTxDestination dest = addr.Get(); CPubKey vchPubKeyDevSubsidy; pactiveWallet->GetPubKey(boost::get<CKeyID>(dest), vchPubKeyDevSubsidy); std::string devSubsidyPubKey = HexStr(vchPubKeyDevSubsidy); std::string devSubsidyPubKeyID = boost::get<CKeyID>(dest).GetHex(); CKey key; key.MakeNewKey(true); CPrivKey vchPrivKey = key.GetPrivKey(); CPubKey vchPubKey = key.GetPubKey(); std::string privkey = HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end()).c_str(); std::string pubKeyID = vchPubKey.GetID().GetHex(); std::string witnessKeys = GLOBAL_APP_URIPREFIX"://witnesskeys?keys=" + CEncodedSecretKey(key).ToString() + strprintf("#%s", GetAdjustedTime()); return "privkey: "+privkey+"\n"+"pubkeyID: "+pubKeyID+"\n"+"witness: "+witnessKeys+"\n"+"dev subsidy addr: "+address+"\n"+"dev subsidy pubkey: "+devSubsidyPubKey+"\n"+"dev subsidy pubkey ID: "+devSubsidyPubKeyID+"\n"; } MnemonicRecord ILibraryController::GenerateRecoveryMnemonic() { std::vector<unsigned char> entropy(16); GetStrongRandBytes(&entropy[0], 16); int64_t birthTime = GetAdjustedTime(); SecureString phraseOnly = mnemonicFromEntropy(entropy, entropy.size()*8); return ComposeRecoveryPhrase(phraseOnly.c_str(), birthTime); } MnemonicRecord ILibraryController::ComposeRecoveryPhrase(const std::string & mnemonic, int64_t birthTime) { const auto& result = AppLifecycleManager::composeRecoveryPhrase(SecureString(mnemonic), birthTime); return MnemonicRecord(result.first.c_str(), mnemonic.c_str(), result.second); } bool ILibraryController::InitWalletLinkedFromURI(const std::string& linked_uri, const std::string& password) { CEncodedSecretKeyExt<CExtKey> linkedKey; if (!linkedKey.fromURIString(linked_uri)) { return false; } AppLifecycleManager::gApp->setLinkKey(linkedKey); AppLifecycleManager::gApp->isLink = true; AppLifecycleManager::gApp->setRecoveryPassword(password.c_str()); AppLifecycleManager::gApp->initialize(); return true; } bool ILibraryController::ContinueWalletLinkedFromURI(const std::string & linked_uri, const std::string& password) { if (!pactiveWallet) { LogPrintf("%s: No active wallet", __func__); return false; } LOCK2(cs_main, pactiveWallet->cs_wallet); CEncodedSecretKeyExt<CExtKey> linkedKey; if (!linkedKey.fromURIString(linked_uri)) { LogPrintf("%s: Failed to parse link URI", __func__); return false; } AppLifecycleManager::gApp->setLinkKey(linkedKey); AppLifecycleManager::gApp->setRecoveryPassword(password.c_str()); AppLifecycleManager::gApp->isLink = true; CWallet::CreateSeedAndAccountFromLink(pactiveWallet); // Allow update of balance for deleted accounts/transactions LogPrintf("%s: Update balance and rescan", __func__); balanceChangeNotifier->trigger(0); // Rescan for transactions on the linked account DoRescanInternal(); return true; } bool ILibraryController::ReplaceWalletLinkedFromURI(const std::string& linked_uri, const std::string& password) { LOCK2(cs_main, pactiveWallet->cs_wallet); if (!pactiveWallet || !pactiveWallet->activeAccount) { LogPrintf("ReplaceWalletLinkedFromURI: No active wallet"); return false; } // Create ext key for new linked account from parsed data CEncodedSecretKeyExt<CExtKey> linkedKey; if (!linkedKey.fromURIString(linked_uri)) { LogPrintf("ReplaceWalletLinkedFromURI: Failed to parse link URI"); return false; } // Ensure we have a valid location to send all the funds CNativeAddress address(linkedKey.getPayAccount()); if (!address.IsValid()) { LogPrintf("ReplaceWalletLinkedFromURI: invalid address %s", linkedKey.getPayAccount().c_str()); return false; } // Empty wallet to target address LogPrintf("ReplaceWalletLinkedFromURI: Empty accounts into linked address"); bool fSubtractFeeFromAmount = true; std::vector<std::tuple<CWalletTx*, CReserveKeyOrScript*>> transactionsToCommit; for (const auto& [accountUUID, pAccount] : pactiveWallet->mapAccounts) { CAmount nBalance = pactiveWallet->GetBalance(pAccount, false, true, true); if (nBalance > 0) { LogPrintf("ReplaceWalletLinkedFromURI: Empty account into linked address [%s]", getUUIDAsString(accountUUID).c_str()); std::vector<CRecipient> vecSend; CRecipient recipient = GetRecipientForDestination(address.Get(), nBalance, fSubtractFeeFromAmount, GetPoW2Phase(chainTip())); vecSend.push_back(recipient); CWalletTx* pWallettx = new CWalletTx(); CAmount nFeeRequired; int nChangePosRet = -1; std::string strError; CReserveKeyOrScript* pReserveKey = new CReserveKeyOrScript(pactiveWallet, pAccount, KEYCHAIN_CHANGE); std::vector<CKeyStore*> accountsToTry; for ( const auto& accountPair : pactiveWallet->mapAccounts ) { if(accountPair.second->getParentUUID() == pAccount->getUUID()) { accountsToTry.push_back(accountPair.second); } accountsToTry.push_back(pAccount); } if (!pactiveWallet->CreateTransaction(accountsToTry, vecSend, *pWallettx, *pReserveKey, nFeeRequired, nChangePosRet, strError)) { LogPrintf("ReplaceWalletLinkedFromURI: Failed to create transaction %s [%d]",strError.c_str(), nBalance); return false; } transactionsToCommit.push_back(std::tuple(pWallettx, pReserveKey)); } else { LogPrintf("ReplaceWalletLinkedFromURI: Account already empty [%s]", getUUIDAsString(accountUUID).c_str()); } } if (!EraseWalletSeedsAndAccounts()) { LogPrintf("ReplaceWalletLinkedFromURI: Failed to erase seed and accounts"); return false; } AppLifecycleManager::gApp->setLinkKey(linkedKey); AppLifecycleManager::gApp->setRecoveryPassword(password.c_str()); AppLifecycleManager::gApp->isLink = true; CWallet::CreateSeedAndAccountFromLink(pactiveWallet); for (auto& [pWalletTx, pReserveKey] : transactionsToCommit) { CValidationState state; //NB! We delibritely pass nullptr for connman here to prevent transaction from relaying //We allow the relaying to occur inside DoRescan instead if (!pactiveWallet->CommitTransaction(*pWalletTx, *pReserveKey, nullptr, state)) { LogPrintf("ReplaceWalletLinkedFromURI: Failed to commit transaction"); return false; } delete pWalletTx; delete pReserveKey; } // Allow update of balance for deleted accounts/transactions LogPrintf("ReplaceWalletLinkedFromURI: Update balance and rescan"); balanceChangeNotifier->trigger(0); // Rescan for transactions on the linked account DoRescanInternal(); return true; } bool ILibraryController::EraseWalletSeedsAndAccounts() { pactiveWallet->EraseWalletSeedsAndAccounts(); return true; } bool ILibraryController::IsValidLinkURI(const std::string& linked_uri) { CEncodedSecretKeyExt<CExtKey> linkedKey; if (!linkedKey.fromURIString(linked_uri)) return false; return true; } bool testnet_; bool spvMode_; std::string extraArgs_; std::string staticFilterPath_; int64_t staticFilterOffset_; int64_t staticFilterLength_; int32_t ILibraryController::InitUnityLib(const std::string& dataDir, const std::string& staticFilterPath, int64_t staticFilterOffset, int64_t staticFilterLength, bool testnet, bool spvMode, const std::shared_ptr<ILibraryListener>& signalHandler_, const std::string& extraArgs) { balanceChangeNotifier = new CRateLimit<int>([](int) { if (pactiveWallet && signalHandler) { WalletBalances balances; pactiveWallet->GetBalances(balances, pactiveWallet->activeAccount, true); signalHandler->notifyBalanceChange(BalanceRecord(balances.availableIncludingLocked, balances.availableExcludingLocked, balances.availableLocked, balances.unconfirmedIncludingLocked, balances.unconfirmedExcludingLocked, balances.unconfirmedLocked, balances.immatureIncludingLocked, balances.immatureExcludingLocked, balances.immatureLocked, balances.totalLocked)); } }, std::chrono::milliseconds(BALANCE_NOTIFY_THRESHOLD_MS)); newMutationsNotifier = new CRateLimit<std::pair<uint256, bool>>([](const std::pair<uint256, bool>& txInfo) { if (pactiveWallet && signalHandler) { const uint256& txHash = txInfo.first; const bool fSelfComitted = txInfo.second; LOCK2(cs_main, pactiveWallet->cs_wallet); if (pactiveWallet->mapWallet.find(txHash) != pactiveWallet->mapWallet.end()) { const CWalletTx& wtx = pactiveWallet->mapWallet[txHash]; std::vector<MutationRecord> mutations; addMutationsForTransaction(&wtx, mutations, pactiveWallet->activeAccount); for (auto& m: mutations) { LogPrintf("unity: notify new mutation for tx %s", txHash.ToString().c_str()); signalHandler->notifyNewMutation(m, fSelfComitted); } } } }, std::chrono::milliseconds(NEW_MUTATIONS_NOTIFY_THRESHOLD_MS)); // Force the datadir to specific place on e.g. android devices defaultDataDirOverride = dataDir; signalHandler = signalHandler_; testnet_ = testnet; spvMode_ = spvMode; extraArgs_ = extraArgs; staticFilterPath_ = staticFilterPath; staticFilterOffset_ = staticFilterOffset; staticFilterLength_ = staticFilterLength; return InitUnity(); } void InitAppSpecificConfigParamaters() { if (spvMode_) { // SPV wallets definitely shouldn't be listening for incoming connections at all SoftSetArg("-listen", "0"); // Minimise logging for performance reasons SoftSetArg("-debug", "0"); // Turn SPV mode on SoftSetArg("-fullsync", "0"); SoftSetArg("-spv", "1"); #ifdef DJINNI_NODEJS #ifdef SPV_MULTI_ACCOUNT SoftSetArg("-accountpool", "3"); SoftSetArg("-accountpoolmobi", "1"); SoftSetArg("-accountpoolwitness", "1"); SoftSetArg("-accountpoolmining", "1"); #else SoftSetArg("-accountpool", "0"); SoftSetArg("-accountpoolmobi", "0"); SoftSetArg("-accountpoolwitness", "0"); SoftSetArg("-accountpoolmining", "0"); #endif SoftSetArg("-keypool", "10"); #else // Minimise lookahead size for performance reasons SoftSetArg("-accountpool", "1"); // Minimise background threads and memory consumption SoftSetArg("-par", "-100"); SoftSetArg("-maxsigcachesize", "0"); SoftSetArg("-dbcache", "4"); SoftSetArg("-maxmempool", "5"); SoftSetArg("-maxconnections", "8"); //fixme: (FUT) (UNITY) Reverse headers // Temporarily disable reverse headers for mobile until memory requirements can be reduced. SoftSetArg("-reverseheaders", "false"); #endif } SoftSetArg("-spvstaticfilterfile", staticFilterPath_); SoftSetArg("-spvstaticfilterfileoffset", i64tostr(staticFilterOffset_)); SoftSetArg("-spvstaticfilterfilelength", i64tostr(staticFilterLength_)); // Change client name #if defined(__APPLE__) && TARGET_OS_IPHONE == 1 SoftSetArg("-clientname", GLOBAL_APPNAME" ios"); #elif defined(__ANDROID__) SoftSetArg("-clientname", GLOBAL_APPNAME" android"); #else SoftSetArg("-clientname", GLOBAL_APPNAME" desktop"); #endif // Testnet if (testnet_) { SoftSetArg("-testnet", "S1595347850:60"); SoftSetArg("-addnode", "178.62.195.19"); } else { SoftSetArg("-addnode", "178.62.195.19"); SoftSetArg("-addnode", "149.210.165.218"); } if (!extraArgs_.empty()) { std::vector<const char*> args; auto splitted = boost::program_options::split_unix(extraArgs_); for(const auto& part: splitted) args.push_back(part.c_str()); gArgs.ParseExtraParameters(int(args.size()), args.data()); } } void ILibraryController::InitUnityLibThreaded(const std::string& dataDir, const std::string& staticFilterPath, int64_t staticFilterOffset, int64_t staticFilterLength, bool testnet, bool spvMode, const std::shared_ptr<ILibraryListener>& signalHandler_, const std::string& extraArgs) { std::thread([=] { InitUnityLib(dataDir, staticFilterPath, staticFilterOffset, staticFilterLength, testnet, spvMode, signalHandler_, extraArgs); }).detach(); } void ILibraryController::TerminateUnityLib() { // Terminate in thread so we don't block interprocess communication std::thread([=] { work.reset(); ioctx.stop(); AppLifecycleManager::gApp->shutdown(); AppLifecycleManager::gApp->waitForShutDown(); run_thread.join(); }).detach(); } QrCodeRecord ILibraryController::QRImageFromString(const std::string& qr_string, int32_t width_hint) { QRcode* code = QRcode_encodeString(qr_string.c_str(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); if (!code) { return QrCodeRecord(0, std::vector<uint8_t>()); } else { const int32_t generatedWidth = code->width; const int32_t finalWidth = (width_hint / generatedWidth) * generatedWidth; const int32_t scaleMultiplier = finalWidth / generatedWidth; std::vector<uint8_t> dataVector; dataVector.reserve(finalWidth*finalWidth); int nIndex=0; for (int nRow=0; nRow<generatedWidth; ++nRow) { for (int nCol=0; nCol<generatedWidth; ++nCol) { dataVector.insert(dataVector.end(), scaleMultiplier, (code->data[nIndex++] & 1) * 255); } for (int i=1; i<scaleMultiplier; ++i) { dataVector.insert(dataVector.end(), dataVector.end()-finalWidth, dataVector.end()); } } QRcode_free(code); return QrCodeRecord(finalWidth, dataVector); } } std::string ILibraryController::GetReceiveAddress() { LOCK2(cs_main, pactiveWallet->cs_wallet); if (!pactiveWallet || !pactiveWallet->activeAccount) return ""; CReserveKeyOrScript* receiveAddress = new CReserveKeyOrScript(pactiveWallet, pactiveWallet->activeAccount, KEYCHAIN_EXTERNAL); CPubKey pubKey; if (receiveAddress->GetReservedKey(pubKey)) { CKeyID keyID = pubKey.GetID(); receiveAddress->ReturnKey(); delete receiveAddress; return CNativeAddress(keyID).ToString(); } else { return ""; } } //fixme: (UNITY) - find a way to use char[] here as well as on the java side. MnemonicRecord ILibraryController::GetRecoveryPhrase() { if (pactiveWallet && pactiveWallet->activeAccount) { LOCK2(cs_main, pactiveWallet->cs_wallet); //WalletModel::UnlockContext ctx(walletModel->requestUnlock()); //if (ctx.isValid()) { int64_t birthTime = pactiveWallet->birthTime(); std::set<SecureString> allPhrases; for (const auto& seedIter : pactiveWallet->mapSeeds) { SecureString phrase = seedIter.second->getMnemonic(); return ComposeRecoveryPhrase(phrase.c_str(), birthTime); } } } return MnemonicRecord("", "", 0); } bool ILibraryController::IsMnemonicWallet() { if (!pactiveWallet || !pactiveWallet->activeAccount) throw std::runtime_error(_("No active internal wallet.")); LOCK2(cs_main, pactiveWallet->cs_wallet); return pactiveWallet->activeSeed != nullptr; } bool ILibraryController::IsMnemonicCorrect(const std::string & phrase) { if (!pactiveWallet || !pactiveWallet->activeAccount) throw std::runtime_error(_("No active internal wallet.")); SecureString mnemonicPhrase; int birthNumber; AppLifecycleManager::splitRecoveryPhraseAndBirth(SecureString(phrase), mnemonicPhrase, birthNumber); LOCK2(cs_main, pactiveWallet->cs_wallet); for (const auto& seedIter : pactiveWallet->mapSeeds) { if (mnemonicPhrase == seedIter.second->getMnemonic()) return true; } return false; } std::vector<std::string> ILibraryController::GetMnemonicDictionary() { return getMnemonicDictionary(); } //fixme: (UNITY) HIGH - take a timeout value and always lock again after timeout bool ILibraryController::UnlockWallet(const std::string& password) { if (!pactiveWallet) { LogPrintf("UnlockWallet: No active wallet"); return false; } if (!dynamic_cast<CExtWallet*>(pactiveWallet)->IsCrypted()) { LogPrintf("UnlockWallet: Wallet not encrypted"); return false; } return pactiveWallet->Unlock(password.c_str()); } bool ILibraryController::LockWallet() { if (!pactiveWallet) { LogPrintf("LockWallet: No active wallet"); return false; } if (dynamic_cast<CExtWallet*>(pactiveWallet)->IsLocked()) return true; return dynamic_cast<CExtWallet*>(pactiveWallet)->Lock(); } bool ILibraryController::ChangePassword(const std::string& oldPassword, const std::string& newPassword) { if (!pactiveWallet) { LogPrintf("ChangePassword: No active wallet"); return false; } if (newPassword.length() == 0) { LogPrintf("ChangePassword: Refusing invalid password of length 0"); return false; } return pactiveWallet->ChangeWalletPassphrase(oldPassword.c_str(), newPassword.c_str()); } bool ILibraryController::HaveUnconfirmedFunds() { if (!pactiveWallet) return true; WalletBalances balances; pactiveWallet->GetBalances(balances, pactiveWallet->activeAccount, true); if (balances.unconfirmedIncludingLocked > 0 || balances.immatureIncludingLocked > 0) { return true; } return false; } int64_t ILibraryController::GetBalance() { if (!pactiveWallet) return 0; WalletBalances balances; pactiveWallet->GetBalances(balances, pactiveWallet->activeAccount, true); return balances.availableIncludingLocked + balances.unconfirmedIncludingLocked + balances.immatureIncludingLocked; } void ILibraryController::DoRescan() { if (!pactiveWallet) return; // Allocate some extra keys //fixme: Persist this across runs in some way static int32_t extraKeys=0; extraKeys += 5; int nKeyPoolTargetDepth = GetArg("-keypool", DEFAULT_ACCOUNT_KEYPOOL_SIZE)+extraKeys; pactiveWallet->TopUpKeyPool(nKeyPoolTargetDepth, 0, nullptr, 1); // Do the rescan DoRescanInternal(); } UriRecipient ILibraryController::IsValidRecipient(const UriRecord & request) { // return if URI is not valid or is no Gulden: URI std::string lowerCaseScheme = boost::algorithm::to_lower_copy(request.scheme); if (lowerCaseScheme != "gulden") return UriRecipient(false, "", "", "", 0); if (!CNativeAddress(request.path).IsValid()) return UriRecipient(false, "", "", "", 0); std::string address = request.path; std::string label = ""; std::string description = ""; CAmount amount = 0; if (request.items.find("amount") != request.items.end()) { ParseMoney(request.items.find("amount")->second, amount); } if (pactiveWallet) { LOCK2(cs_main, pactiveWallet->cs_wallet); if (pactiveWallet->mapAddressBook.find(address) != pactiveWallet->mapAddressBook.end()) { const auto& data = pactiveWallet->mapAddressBook[address]; label = data.name; description = data.description; } } return UriRecipient(true, address, label, description, amount); } bool ILibraryController::IsValidNativeAddress(const std::string& address) { CNativeAddress addr(address); return addr.IsValid(); } bool ILibraryController::IsValidBitcoinAddress(const std::string& address) { CNativeAddress addr(address); return addr.IsValidBitcoin(); } int64_t ILibraryController::feeForRecipient(const UriRecipient & request) { if (!pactiveWallet) throw std::runtime_error(_("No active internal wallet.")); LOCK2(cs_main, pactiveWallet->cs_wallet); CNativeAddress address(request.address); if (!address.IsValid()) { LogPrintf("feeForRecipient: invalid address %s", request.address.c_str()); throw std::runtime_error(_("Invalid address")); } CRecipient recipient = GetRecipientForDestination(address.Get(), std::min(GetBalance(), request.amount), true, GetPoW2Phase(chainTip())); std::vector<CRecipient> vecSend; vecSend.push_back(recipient); CWalletTx wtx; CAmount nFeeRequired; int nChangePosRet = -1; std::string strError; CReserveKeyOrScript reservekey(pactiveWallet, pactiveWallet->activeAccount, KEYCHAIN_CHANGE); std::vector<CKeyStore*> accountsToTry; for ( const auto& accountPair : pactiveWallet->mapAccounts ) { if(accountPair.second->getParentUUID() == pactiveWallet->activeAccount->getUUID()) { accountsToTry.push_back(accountPair.second); } accountsToTry.push_back(pactiveWallet->activeAccount); } if (!pactiveWallet->CreateTransaction(accountsToTry, vecSend, wtx, reservekey, nFeeRequired, nChangePosRet, strError, NULL, false)) { LogPrintf("feeForRecipient: failed to create transaction %s",strError.c_str()); throw std::runtime_error(strprintf(_("Failed to calculate fee\n%s"), strError)); } return nFeeRequired; } PaymentResultStatus ILibraryController::performPaymentToRecipient(const UriRecipient & request, bool substract_fee) { if (!pactiveWallet) throw std::runtime_error(_("No active internal wallet.")); LOCK2(cs_main, pactiveWallet->cs_wallet); CNativeAddress address(request.address); if (!address.IsValid()) { LogPrintf("performPaymentToRecipient: invalid address %s", request.address.c_str()); throw std::runtime_error(_("Invalid address")); } CRecipient recipient = GetRecipientForDestination(address.Get(), request.amount, substract_fee, GetPoW2Phase(chainTip())); std::vector<CRecipient> vecSend; vecSend.push_back(recipient); CWalletTx wtx; CAmount nFeeRequired; int nChangePosRet = -1; std::string strError; CReserveKeyOrScript reservekey(pactiveWallet, pactiveWallet->activeAccount, KEYCHAIN_CHANGE); std::vector<CKeyStore*> accountsToTry; for ( const auto& accountPair : pactiveWallet->mapAccounts ) { if(accountPair.second->getParentUUID() == pactiveWallet->activeAccount->getUUID()) { accountsToTry.push_back(accountPair.second); } accountsToTry.push_back(pactiveWallet->activeAccount); } if (!pactiveWallet->CreateTransaction(accountsToTry, vecSend, wtx, reservekey, nFeeRequired, nChangePosRet, strError)) { if (!substract_fee && request.amount + nFeeRequired > GetBalance()) { return PaymentResultStatus::INSUFFICIENT_FUNDS; } LogPrintf("performPaymentToRecipient: failed to create transaction %s",strError.c_str()); throw std::runtime_error(strprintf(_("Failed to create transaction\n%s"), strError)); } CValidationState state; if (!pactiveWallet->CommitTransaction(wtx, reservekey, g_connman.get(), state)) { strError = strprintf("Error: The transaction was rejected! Reason given: %s", state.GetRejectReason()); LogPrintf("performPaymentToRecipient: failed to commit transaction %s",strError.c_str()); throw std::runtime_error(strprintf(_("Transaction rejected, reason: %s"), state.GetRejectReason())); } // Prevent accidental double spends for (const auto &txin : wtx.tx->vin) { pactiveWallet->LockCoin(txin.GetPrevOut()); } return PaymentResultStatus::SUCCESS; } std::vector<TransactionRecord> getTransactionHistoryForAccount(CAccount* forAccount) { std::vector<TransactionRecord> ret; LOCK2(cs_main, pactiveWallet->cs_wallet); std::vector<CAccount*> forAccounts = GetAccountsForAccount(forAccount); for (const auto& [hash, wtx] : pactiveWallet->mapWallet) { bool anyInputsOrOutputsAreMine = false; TransactionRecord tx = calculateTransactionRecordForWalletTransaction(wtx, forAccounts, anyInputsOrOutputsAreMine); if (anyInputsOrOutputsAreMine) { ret.push_back(tx); } } std::sort(ret.begin(), ret.end(), [&](TransactionRecord& x, TransactionRecord& y){ return (x.timeStamp > y.timeStamp); }); return ret; } std::vector<TransactionRecord> ILibraryController::getTransactionHistory() { if (!pactiveWallet) return std::vector<TransactionRecord>(); return getTransactionHistoryForAccount(pactiveWallet->activeAccount); } TransactionRecord ILibraryController::getTransaction(const std::string& txHash) { if (!pactiveWallet) throw std::runtime_error(strprintf("No active wallet to query tx hash [%s]", txHash)); uint256 hash = uint256S(txHash); LOCK2(cs_main, pactiveWallet->cs_wallet); if (pactiveWallet->mapWallet.find(hash) == pactiveWallet->mapWallet.end()) throw std::runtime_error(strprintf("No transaction found for hash [%s]", txHash)); std::vector<CAccount*> forAccounts = GetAccountsForAccount(pactiveWallet->activeAccount); const CWalletTx& wtx = pactiveWallet->mapWallet[hash]; bool anyInputsOrOutputsAreMine = false; return calculateTransactionRecordForWalletTransaction(wtx, forAccounts, anyInputsOrOutputsAreMine); } std::string ILibraryController::resendTransaction(const std::string& txHash) { if (!pactiveWallet) throw std::runtime_error(strprintf("No active wallet to query tx hash [%s]", txHash)); uint256 hash = uint256S(txHash); LOCK2(cs_main, pactiveWallet->cs_wallet); if (pactiveWallet->mapWallet.find(hash) == pactiveWallet->mapWallet.end()) return ""; const CWalletTx& wtx = pactiveWallet->mapWallet[hash]; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << *wtx.tx; std::string strHex = HexStr(ssTx.begin(), ssTx.end()); if(!g_connman) return ""; const uint256& hashTx = wtx.tx->GetHash(); CInv inv(MSG_TX, hashTx); g_connman->ForEachNode([&inv](CNode* pnode) { pnode->PushInventory(inv); }); return strHex; } std::vector<MutationRecord> getMutationHistoryForAccount(CAccount* forAccount) { std::vector<MutationRecord> ret; LOCK2(cs_main, pactiveWallet->cs_wallet); // wallet transactions in reverse chronological ordering std::vector<const CWalletTx*> vWtx; for (const auto& [hash, wtx] : pactiveWallet->mapWallet) { vWtx.push_back(&wtx); } std::sort(vWtx.begin(), vWtx.end(), [&](const CWalletTx* x, const CWalletTx* y){ return (x->nTimeSmart > y->nTimeSmart); }); // build mutation list based on transactions for (const CWalletTx* wtx : vWtx) { addMutationsForTransaction(wtx, ret, forAccount); } return ret; } std::vector<MutationRecord> ILibraryController::getMutationHistory() { if (!pactiveWallet) return std::vector<MutationRecord>(); return getMutationHistoryForAccount(pactiveWallet->activeAccount); } std::vector<AddressRecord> ILibraryController::getAddressBookRecords() { std::vector<AddressRecord> ret; if (pactiveWallet) { LOCK2(cs_main, pactiveWallet->cs_wallet); for(const auto& [address, addressData] : pactiveWallet->mapAddressBook) { ret.emplace_back(AddressRecord(address, addressData.name, addressData.description, addressData.purpose)); } } return ret; } void ILibraryController::addAddressBookRecord(const AddressRecord& address) { if (pactiveWallet) { pactiveWallet->SetAddressBook(address.address, address.name, address.desc, address.purpose); } } void ILibraryController::deleteAddressBookRecord(const AddressRecord& address) { if (pactiveWallet) { pactiveWallet->DelAddressBook(address.address); } } void ILibraryController::PersistAndPruneForSPV() { PersistAndPruneForPartialSync(); } void ILibraryController::ResetUnifiedProgress() { CWallet::ResetUnifiedSPVProgressNotification(); } float ILibraryController::getUnifiedProgress() { if (!GetBoolArg("-spv", DEFAULT_SPV)) { return lastProgress; } else { return CSPVScanner::lastProgressReported; } } std::vector<BlockInfoRecord> ILibraryController::getLastSPVBlockInfos() { std::vector<BlockInfoRecord> ret; LOCK(cs_main); int height = partialChain.Height(); while (ret.size() < 32 && height > partialChain.HeightOffset()) { const CBlockIndex* pindex = partialChain[height]; ret.push_back(BlockInfoRecord(pindex->nHeight, pindex->GetBlockTime(), pindex->GetBlockHashPoW2().ToString())); height--; } return ret; } MonitorRecord ILibraryController::getMonitoringStats() { LOCK(cs_main); int32_t partialHeight_ = partialChain.Height(); int32_t partialOffset_ = partialChain.HeightOffset(); int32_t prunedHeight_ = nPartialPruneHeightDone; int32_t processedSPVHeight_ = CSPVScanner::getProcessedHeight(); int32_t probableHeight_ = GetProbableHeight(); return MonitorRecord(partialHeight_, partialOffset_, prunedHeight_, processedSPVHeight_, probableHeight_); } void ILibraryController::RegisterMonitorListener(const std::shared_ptr<MonitorListener> & listener) { LOCK(cs_monitoringListeners); monitoringListeners.insert(listener); } void ILibraryController::UnregisterMonitorListener(const std::shared_ptr<MonitorListener> & listener) { LOCK(cs_monitoringListeners); monitoringListeners.erase(listener); } std::unordered_map<std::string, std::string> ILibraryController::getClientInfo() { std::unordered_map<std::string, std::string> ret; ret.insert(std::pair("client_version", FormatFullVersion())); ret.insert(std::pair("user_agent", strSubVersion)); ret.insert(std::pair("datadir_path", GetDataDir().string())); std::string logfilePath = (GetDataDir() / "debug.log").string(); ret.insert(std::pair("logfile_path", logfilePath)); ret.insert(std::pair("startup_timestamp", i64tostr(nClientStartupTime))); if (!g_connman->GetNetworkActive()) { ret.insert(std::pair("network_status", "disabled")); ret.insert(std::pair("num_connections_in", "0")); ret.insert(std::pair("num_connections_out", "0")); } else { ret.insert(std::pair("network_status", "enabled")); std::string connectionsIn = i64tostr(g_connman->GetNodeCount(CConnman::NumConnections::CONNECTIONS_IN)); std::string connectionsOut = i64tostr(g_connman->GetNodeCount(CConnman::NumConnections::CONNECTIONS_OUT)); ret.insert(std::pair("num_connections_in", connectionsIn)); ret.insert(std::pair("num_connections_out", connectionsOut)); } if (fSPV) { if (partialChain.Tip()) { ret.insert(std::pair("chain_tip_height", i64tostr(partialChain.Height()))); ret.insert(std::pair("chain_tip_time", i64tostr(partialChain.Tip()->GetBlockTime()))); ret.insert(std::pair("chain_tip_hash", partialChain.Tip()->GetBlockHashPoW2().ToString())); ret.insert(std::pair("chain_offset", i64tostr(partialChain.HeightOffset()))); ret.insert(std::pair("chain_pruned_height", i64tostr(nPartialPruneHeightDone))); ret.insert(std::pair("chain_processed_height", i64tostr(CSPVScanner::getProcessedHeight()))); ret.insert(std::pair("chain_probable_height", i64tostr(GetProbableHeight()))); } } else if (chainActive.Tip()) { ret.insert(std::pair("chain_tip_height", i64tostr(chainActive.Tip()->nHeight))); ret.insert(std::pair("chain_tip_time", i64tostr(chainActive.Tip()->GetBlockTime()))); ret.insert(std::pair("chain_tip_hash", chainActive.Tip()->GetBlockHashPoW2().ToString())); } ret.insert(std::pair("mempool_transaction_count", i64tostr(mempool.size()))); ret.insert(std::pair("mempool_memory_size", i64tostr(mempool.GetTotalTxSize()))); return ret; }
Java
/* * DBAdapter.h * Main Class to manage DB operations * Created by: Ozgur Pekcagliyan - 2014-09-25 09:28:43 PM EEST * Last edited by: Ozgur Pekcagliyan - 2015-03-01 * Notes: * errorCode will be used to return specific error values back to user; * * Potential error codes are; * * * 0: success * * * 1: user name or password is incorrect * * * 2: db doesn't exist * * * 3: invalid sql query * * * 4: problem with disconnect * * * 5: failed to create sqlfile * * * 6-1000: unknown (reserved) * * * bigger than 1000 - SQL server error system (Ex: 1045000 means 1045) * type will hold the database that will be connected * * possible values are; * * * 1: mysql (default value) * * * 2: oracle * * * 3: sqlite * * * rest of the codes will be added in time by developers * In selectData function, data will be returned in a string vector, fields will be seperated by a user defined char * selectData function appendFlag will decide wethrer returnVal will be cleared or results will be appended to the returnVal * * 0: no append (default val) * * 1: append */ #ifndef DBADAPTER_H #define DBADAPTER_H #include <mysql/mysql.h> #include <sqlite3.h> #include <string> #include <vector> #include <list> #include "Logger.h" #define DEFAULT_SQLITE_DBNAME "defaultSQDB.db" typedef std::vector< std::list< std::string > > SQL_RET_TYPE; class DBAdapter { public: enum db_types_t {MYSQL = 1, ORACLE = 2, SQLITE = 3}; DBAdapter(); //Default constructor explicit DBAdapter(const db_types_t type); //constructor to set db type at initialization, imlicit initialization is not allowed ~DBAdapter(); //Destructor bool setDbType(const int &ty); //function to change db type in runtime, if there is an active connection, this function will not run bool connect (const char *ip, const int port, const char *user, const char *pass, int &errorCode); //connects database and resturns the result bool connect (const char *filename, int &errorCode); //connects database and resturns the result for sqlite bool disconnect (int &errorCode); //disconnect from database and return the result bool selectDB(const std::string &dbName, int &errorCode); //selecting DB to connect //bool execQuery(const string &sql, int &errorCode, char * reason); //execute a specific user written query, also returns a failure reason as set of chars bool execQuery(const std::string &sql, int &errorCode); //overloaded version bool execQuery(const void *sql, const int& querySize, int &errorCode); //overloaded version which accepts binary data bool insertData(const std::string &fields, const std::string& values, const std::string &table, int &errorCode); /*inserts data into specific tables Example usage: insertData("name, surname, age", "'john', 'smith', 52", "users", errorCodeVar); */ bool selectData(const std::string &fields, const std::string& condition, const std::string &table, SQL_RET_TYPE &returnVal, int &errorCode, int appendFlag = 0); /*select data from specific tables Example usage: selecttData("name, surname, age", "name='john' or age < 52", "users", errorCodeVar); */ bool selectData(const std::string &fields, const std::string &table, SQL_RET_TYPE &returnVal, int &errorCode, int appendFlag = 0); //overloaded version of select bool deleteData(const std::string& condition, const std::string &table, int &errorCode); /*delete data from specific tables Example usage: deleteData("name=john and age >= 63", "users", errorCodeVar); */ bool updateData(const std::string &fields, const std::string& values, const std::string &condition, const std::string &table, int &errorCode); /*inserts data to specific tables Example usage updatetData("name, surname, age", "'john', 'smith', 52", "name=john and age >= 63", "users", errorCodeVar); */ bool updateData(const std::string &fields, const std::string& values, const std::string &table, int &errorCode); // overloaded version private: int type; //this variable will hold the type of connection bool isConnected; //holds the status of connection SQL_RET_TYPE *rVal; //MYSQL variables start here ::MYSQL *myConnection, myInit; //used for mysql operations and holds connection, myInit is not a pointer because we don't want to handle memory operations for it - Ozgur //MYSQL_RES *myResult; //holds results of the queries //MYSQL_ROW myRow; //holds rows for each result //ORACLE variables will be here //SQLITE variables will be here sqlite3 *SQlitedb; //Other DB variables will be here //Logger object is here Logger *logger; public: //Here starts special functions friend int callBack(void *data, int argc, char **argv, char **azColName); }; #endif
Java
<div> <a href="#/templates">Go Back</a> <br><br> <div class="col-md-4"> <img class="img-full" src="img/{{mainImage}}"> <div class="row"> <div ng-repeat="image in template.images | limitTo:4"> <div class="col-md-3"> <img class="img-full" ng-src="img/{{image.name}}" ng-click="setImage(image)"> </div> </div> </div> </div> <div class="col-md-8"> <h3>{{template.name}}</h3> <p>{{template.description}}</p> <p>Type: {{template.type}}</p> <h4>{{template.price}}</h4> <form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post"> <!-- Specifies Buy Now Button --> <input type="hidden" name="cmd" value="_xclick"> <!-- PayPal Email --> <input type="hidden" name="business" value="techguyseller@sandbox.com"> <!-- Item Name --> <input type="hidden" name="item_name" value="{{template.name}}"> <!-- Item ID --> <input type="hidden" name="item_number" value="{{template.id}}"> <!-- Currency Code --> <input type="hidden" name="currency_code" value="USD"> <!-- Price --> <input type="hidden" name="amount" value="{{template.price}}"> <!-- Specify Shipping --> <input type='hidden' name='no_shipping' value='1'> <!-- Return method --> <input type='hidden' name='rm' value='2'> <!-- Return URL --> <input type="hidden" name="return" value="http://localhost:8000"> <!-- Cancel Return URL --> <input type="hidden" name="cancel_return" value="http://localhost:8000"> <!-- Button --> <input type="image" src="https://www.paypalobjects.com/webstatic/en_US/btn/btn_buynow_107x26.png" name="submit" alt="Buy Now"> </form> </div> </div>
Java
class CreateActiveAdminComments < ActiveRecord::Migration[5.1] def self.up create_table :active_admin_comments do |t| t.string :namespace t.text :body t.string :resource_id, null: false t.string :resource_type, null: false t.references :author, polymorphic: true t.timestamps end add_index :active_admin_comments, [:namespace] add_index :active_admin_comments, [:resource_type, :resource_id] end def self.down drop_table :active_admin_comments end end
Java
namespace _03BarracksFactory.Data { using System; using Contracts; using System.Collections.Generic; using System.Text; class UnitRepository : IRepository { private IDictionary<string, int> amountOfUnits; public UnitRepository() { this.amountOfUnits = new SortedDictionary<string, int>(); } public string Statistics { get { StringBuilder statBuilder = new StringBuilder(); foreach (var entry in amountOfUnits) { string formatedEntry = string.Format("{0} -> {1}", entry.Key, entry.Value); statBuilder.AppendLine(formatedEntry); } return statBuilder.ToString().Trim(); } } public void AddUnit(IUnit unit) { string unitType = unit.GetType().Name; if (!this.amountOfUnits.ContainsKey(unitType)) { this.amountOfUnits.Add(unitType, 0); } this.amountOfUnits[unitType]++; } public void RemoveUnit(string unitType) { if (this.amountOfUnits[unitType] > 0) { this.amountOfUnits[unitType]--; } else { throw new ArgumentException("Not enought units."); } } } }
Java
/// @copyright /// Copyright (C) 2020 Assured Information Security, Inc. /// /// @copyright /// 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: /// /// @copyright /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// @copyright /// 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 TLS_T_HPP #define TLS_T_HPP #include <state_save_t.hpp> #include <bsl/array.hpp> #include <bsl/convert.hpp> #include <bsl/cstdint.hpp> #include <bsl/errc_type.hpp> #include <bsl/safe_integral.hpp> #pragma pack(push, 1) namespace mk { /// @brief defines the size of the reserved1 field in the tls_t constexpr auto TLS_T_RESERVED1_SIZE{0x020_umx}; /// @brief defines the size of the reserved2 field in the tls_t constexpr auto TLS_T_RESERVED2_SIZE{0x008_umx}; /// @brief defines the size of the reserved3 field in the tls_t constexpr auto TLS_T_RESERVED3_SIZE{0x007_umx}; /// @brief defines the size of the reserved4 field in the tls_t constexpr auto TLS_T_RESERVED4_SIZE{0x040_umx}; /// IMPORTANT: /// - If the size of the TLS is changed, the mk_main_entry will need to /// be updated to reflect the new size. It might make sense to have a /// header file that defines a constant that both this code and the /// assembly logic can share /// /// @brief defines the the total size of the TLS block constexpr auto TLS_T_SIZE{0x400_umx}; /// <!-- description --> /// @brief Defines the layout of the microkernel's TLS block. This /// should not be confused with the TLS blocks given to an extension, /// for which there are two, the TLS block for thread_local and the /// TLS block provided by the microkernel's ABI. /// struct tls_t final { /// -------------------------------------------------------------------- /// Microkernel State /// -------------------------------------------------------------------- /// @brief stores the value of x18 for the microkernel (0x000) bsl::uintmx mk_x18; /// @brief stores the value of x19 for the microkernel (0x008) bsl::uintmx mk_x19; /// @brief stores the value of x20 for the microkernel (0x010) bsl::uintmx mk_x20; /// @brief stores the value of x21 for the microkernel (0x018) bsl::uintmx mk_x21; /// @brief stores the value of x22 for the microkernel (0x020) bsl::uintmx mk_x22; /// @brief stores the value of x23 for the microkernel (0x028) bsl::uintmx mk_x23; /// @brief stores the value of x24 for the microkernel (0x030) bsl::uintmx mk_x24; /// @brief stores the value of x25 for the microkernel (0x038) bsl::uintmx mk_x25; /// @brief stores the value of x26 for the microkernel (0x040) bsl::uintmx mk_x26; /// @brief stores the value of x27 for the microkernel (0x048) bsl::uintmx mk_x27; /// @brief stores the value of x28 for the microkernel (0x050) bsl::uintmx mk_x28; /// @brief stores the value of x29 for the microkernel (0x058) bsl::uintmx mk_x29; /// @brief stores the value of x30 for the microkernel (0x060) bsl::uintmx mk_x30; /// -------------------------------------------------------------------- /// Extension State /// -------------------------------------------------------------------- /// @brief x0, stores the extension's syscall (0x068) bsl::uintmx ext_syscall; /// @brief x1, stores the value of REG1 for the extension (0x070) bsl::uintmx ext_reg0; /// @brief x2, stores the value of REG1 for the extension (0x078) bsl::uintmx ext_reg1; /// @brief x3, stores the value of REG1 for the extension (0x080) bsl::uintmx ext_reg2; /// @brief x4, stores the value of REG1 for the extension (0x088) bsl::uintmx ext_reg3; /// @brief x5, stores the value of REG1 for the extension (0x090) bsl::uintmx ext_reg4; /// @brief x6, stores the value of REG1 for the extension (0x098) bsl::uintmx ext_reg5; /// @brief x7, stores the value of REG1 for the extension (0x0A0) bsl::uintmx reserved_reg7; /// @brief x8, stores the value of REG1 for the extension (0x0A8) bsl::uintmx reserved_reg8; /// @brief x9, stores the value of REG1 for the extension (0x0B0) bsl::uintmx reserved_reg9; /// @brief x10, stores the value of REG1 for the extension (0x0B8) bsl::uintmx reserved_reg10; /// @brief x11, stores the value of REG1 for the extension (0x0C0) bsl::uintmx reserved_reg11; /// @brief x12, stores the value of REG1 for the extension (0x0C8) bsl::uintmx reserved_reg12; /// @brief x13, stores the value of REG1 for the extension (0x0D0) bsl::uintmx reserved_reg13; /// @brief x14, stores the value of REG1 for the extension (0x0D8) bsl::uintmx reserved_reg14; /// @brief x15, stores the value of REG1 for the extension (0x0E0) bsl::uintmx reserved_reg15; /// @brief x16, stores the value of REG1 for the extension (0x0E8) bsl::uintmx reserved_reg16; /// @brief x17, stores the value of REG1 for the extension (0x0F0) bsl::uintmx reserved_reg17; /// @brief x18, stores the value of REG1 for the extension (0x0F8) bsl::uintmx reserved_reg18; /// @brief x19, stores the value of REG1 for the extension (0x100) bsl::uintmx reserved_reg19; /// @brief x20, stores the value of REG1 for the extension (0x108) bsl::uintmx reserved_reg20; /// @brief x21, stores the value of REG1 for the extension (0x110) bsl::uintmx reserved_reg21; /// @brief x22, stores the value of REG1 for the extension (0x118) bsl::uintmx reserved_reg22; /// @brief x23, stores the value of REG1 for the extension (0x120) bsl::uintmx reserved_reg23; /// @brief x24, stores the value of REG1 for the extension (0x128) bsl::uintmx reserved_reg24; /// @brief x25, stores the value of REG1 for the extension (0x130) bsl::uintmx reserved_reg25; /// @brief x26, stores the value of REG1 for the extension (0x138) bsl::uintmx reserved_reg26; /// @brief x27, stores the value of REG1 for the extension (0x140) bsl::uintmx reserved_reg27; /// @brief x28, stores the value of REG1 for the extension (0x148) bsl::uintmx reserved_reg28; /// @brief x29, stores the value of REG1 for the extension (0x150) bsl::uintmx reserved_reg29; /// @brief x30, stores the value of REG1 for the extension (0x158) bsl::uintmx reserved_reg30; /// -------------------------------------------------------------------- /// ESR State /// -------------------------------------------------------------------- /// @brief stores the value of x0 for the ESR (0x160) bsl::uintmx esr_x0; /// @brief stores the value of x1 for the ESR (0x168) bsl::uintmx esr_x1; /// @brief stores the value of x2 for the ESR (0x170) bsl::uintmx esr_x2; /// @brief stores the value of x3 for the ESR (0x178) bsl::uintmx esr_x3; /// @brief stores the value of x4 for the ESR (0x180) bsl::uintmx esr_x4; /// @brief stores the value of x5 for the ESR (0x188) bsl::uintmx esr_x5; /// @brief stores the value of x6 for the ESR (0x190) bsl::uintmx esr_x6; /// @brief stores the value of x7 for the ESR (0x198) bsl::uintmx esr_x7; /// @brief stores the value of x8 for the ESR (0x1A0) bsl::uintmx esr_x8; /// @brief stores the value of x9 for the ESR (0x1A8) bsl::uintmx esr_x9; /// @brief stores the value of x10 for the ESR (0x1B0) bsl::uintmx esr_x10; /// @brief stores the value of x11 for the ESR (0x1B8) bsl::uintmx esr_x11; /// @brief stores the value of x12 for the ESR (0x1C0) bsl::uintmx esr_x12; /// @brief stores the value of x13 for the ESR (0x1C8) bsl::uintmx esr_x13; /// @brief stores the value of x14 for the ESR (0x1D0) bsl::uintmx esr_x14; /// @brief stores the value of x15 for the ESR (0x1D8) bsl::uintmx esr_x15; /// @brief stores the value of x16 for the ESR (0x1E0) bsl::uintmx esr_x16; /// @brief stores the value of x17 for the ESR (0x1E8) bsl::uintmx esr_x17; /// @brief stores the value of x18 for the ESR (0x1F0) bsl::uintmx esr_x18; /// @brief stores the value of x19 for the ESR (0x1F8) bsl::uintmx esr_x19; /// @brief stores the value of x20 for the ESR (0x200) bsl::uintmx esr_x20; /// @brief stores the value of x21 for the ESR (0x208) bsl::uintmx esr_x21; /// @brief stores the value of x22 for the ESR (0x210) bsl::uintmx esr_x22; /// @brief stores the value of x23 for the ESR (0x218) bsl::uintmx esr_x23; /// @brief stores the value of x24 for the ESR (0x220) bsl::uintmx esr_x24; /// @brief stores the value of x25 for the ESR (0x228) bsl::uintmx esr_x25; /// @brief stores the value of x26 for the ESR (0x230) bsl::uintmx esr_x26; /// @brief stores the value of x27 for the ESR (0x238) bsl::uintmx esr_x27; /// @brief stores the value of x28 for the ESR (0x240) bsl::uintmx esr_x28; /// @brief stores the value of x29 for the ESR (0x248) bsl::uintmx esr_x29; /// @brief stores the value of x30 for the ESR (0x250) bsl::uintmx esr_x30; /// @brief stores the value of sp for the ESR (0x258) bsl::uintmx esr_sp; /// @brief stores the value of ip for the ESR (0x260) bsl::uintmx esr_ip; /// @brief stores the value of the ESR vector (0x268) bsl::uintmx esr_vector; /// @brief stores the value of the ESR error code (0x270) bsl::uintmx esr_error_code; /// @brief stores the value of far for the ESR (0x278) bsl::uintmx esr_pf_addr; /// @brief stores the value of esr for the ESR (0x280) bsl::uintmx esr_esr; /// @brief stores the value of SPSR for the ESR (0x288) bsl::uintmx esr_spsr; /// -------------------------------------------------------------------- /// Fast Fail Information /// -------------------------------------------------------------------- /// @brief stores the current fast fail address (0x290) bsl::uintmx current_fast_fail_ip; /// @brief stores the current fast fail stack (0x298) bsl::uintmx current_fast_fail_sp; /// @brief stores the mk_main fast fail address (0x2A0) bsl::uintmx mk_main_fast_fail_ip; /// @brief stores the mk_main fast fail stack (0x2A8) bsl::uintmx mk_main_fast_fail_sp; /// @brief stores the call_ext fast fail address (0x2B0) bsl::uintmx call_ext_fast_fail_ip; /// @brief stores the call_ext fast fail stack (0x2B8) bsl::uintmx call_ext_fast_fail_sp; /// @brief stores the dispatch_syscall fast fail address (0x2C0) bsl::uintmx dispatch_syscall_fast_fail_ip; /// @brief stores the dispatch_syscall fast fail stack (0x2C8) bsl::uintmx dispatch_syscall_fast_fail_sp; /// @brief stores the vmexit loop address (0x2D0) bsl::uintmx vmexit_loop_ip; /// @brief stores the vmexit loop stack (0x2D8) bsl::uintmx vmexit_loop_sp; /// @brief reserve the rest of the TLS block for later use. bsl::array<bsl::uint8, TLS_T_RESERVED1_SIZE.get()> reserved1; /// -------------------------------------------------------------------- /// Context Information /// -------------------------------------------------------------------- /// @brief stores the virtual address of this TLS block (0x300) tls_t *self; /// @brief stores the currently active VMID (0x308) bsl::uint16 ppid; /// @brief stores the total number of online PPs (0x30A) bsl::uint16 online_pps; /// @brief reserved (0x30C) bsl::uint16 reserved_padding0; /// @brief reserved (0x30E) bsl::uint16 reserved_padding1; /// @brief stores the currently active extension (0x310) void *ext; /// @brief stores the extension registered for VMExits (0x318) void *ext_vmexit; /// @brief stores the extension registered for fast fail events (0x320) void *ext_fail; /// @brief stores the loader provided state for the microkernel (0x328) loader::state_save_t *mk_state; /// @brief stores the loader provided state for the root VP (0x330) loader::state_save_t *root_vp_state; /// @brief stores the currently active extension ID (0x338) bsl::uint16 active_extid; /// @brief stores the currently active VMID (0x33A) bsl::uint16 active_vmid; /// @brief stores the currently active VPID (0x33C) bsl::uint16 active_vpid; /// @brief stores the currently active VSID (0x33E) bsl::uint16 active_vsid; /// @brief stores the sp used by extensions for callbacks (0x340) bsl::uintmx sp; /// @brief stores the tps used by extensions for callbacks (0x348) bsl::uintmx tp; /// @brief used to store a return address for unsafe ops (0x350) bsl::uintmx unsafe_rip; /// @brief reserved (0x358) bsl::uintmx reserved_padding2; /// @brief reserved (0x360) bsl::uintmx reserved_padding3; /// @brief stores whether or not the first launch succeeded (0x368) bsl::uintmx first_launch_succeeded; /// @brief stores the currently active root page table (0x370) void *active_rpt; /// @brief reserve the rest of the TLS block for later use. bsl::array<bsl::uint8, TLS_T_RESERVED2_SIZE.get()> reserved2; }; /// @brief make sure the tls_t is the size of a page static_assert(sizeof(tls_t) == TLS_T_SIZE); } #pragma pack(pop) #endif
Java
package com.github.bachelorpraktikum.visualisierbar.model; import com.github.bachelorpraktikum.visualisierbar.model.Element.State; import com.github.bachelorpraktikum.visualisierbar.model.Element.Type; public class ElementShapeableTest extends ShapeableImplementationTest { @Override protected Shapeable<?> getShapeable() { Context context = new Context(); Node node = Node.in(context).create("node", new Coordinates(0, 0)); return Element.in(context).create("element", Type.HauptSignal, node, State.FAHRT); } }
Java
/** * @license Angular v4.0.3 * (c) 2010-2017 Google, Inc. https://angular.io/ * License: MIT */ import { Compiler, ComponentFactoryResolver, Directive, ElementRef, EventEmitter, Inject, Injector, NgModule, NgZone, ReflectiveInjector, SimpleChange, Testability, Version } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @module * @description * Entry point for all public APIs of the common package. */ /** * \@stable */ const VERSION = new Version('4.0.3'); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @return {?} */ function noNg() { throw new Error('AngularJS v1.x is not loaded!'); } let angular = ({ bootstrap: noNg, module: noNg, element: noNg, version: noNg, resumeBootstrap: noNg, getTestability: noNg }); try { if (window.hasOwnProperty('angular')) { angular = ((window)).angular; } } catch (e) { } /** * Resets the AngularJS library. * * Used when angularjs is loaded lazily, and not available on `window`. * * \@stable * @param {?} ng * @return {?} */ /** * Returns the current version of the AngularJS library. * * \@stable * @return {?} */ const bootstrap = (e, modules, config) => angular.bootstrap(e, modules, config); const module$1 = (prefix, dependencies) => angular.module(prefix, dependencies); const element = (e) => angular.element(e); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ const $COMPILE = '$compile'; const $CONTROLLER = '$controller'; const $HTTP_BACKEND = '$httpBackend'; const $INJECTOR = '$injector'; const $PARSE = '$parse'; const $ROOT_SCOPE = '$rootScope'; const $SCOPE = '$scope'; const $TEMPLATE_CACHE = '$templateCache'; const $$TESTABILITY = '$$testability'; const COMPILER_KEY = '$$angularCompiler'; const INJECTOR_KEY = '$$angularInjector'; const NG_ZONE_KEY = '$$angularNgZone'; const REQUIRE_INJECTOR = '?^^' + INJECTOR_KEY; const REQUIRE_NG_MODEL = '?ngModel'; /** * A `PropertyBinding` represents a mapping between a property name * and an attribute name. It is parsed from a string of the form * `"prop: attr"`; or simply `"propAndAttr" where the property * and attribute have the same identifier. */ class PropertyBinding { /** * @param {?} prop * @param {?} attr */ constructor(prop, attr) { this.prop = prop; this.attr = attr; this.parseBinding(); } /** * @return {?} */ parseBinding() { this.bracketAttr = `[${this.attr}]`; this.parenAttr = `(${this.attr})`; this.bracketParenAttr = `[(${this.attr})]`; const /** @type {?} */ capitalAttr = this.attr.charAt(0).toUpperCase() + this.attr.substr(1); this.onAttr = `on${capitalAttr}`; this.bindAttr = `bind${capitalAttr}`; this.bindonAttr = `bindon${capitalAttr}`; } } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @param {?} e * @return {?} */ function onError(e) { // TODO: (misko): We seem to not have a stack trace here! if (console.error) { console.error(e, e.stack); } else { // tslint:disable-next-line:no-console console.log(e, e.stack); } throw e; } /** * @param {?} name * @return {?} */ function controllerKey(name) { return '$' + name + 'Controller'; } /** * @param {?} node * @return {?} */ /** * @param {?} component * @return {?} */ function getComponentName(component) { // Return the name of the component or the first line of its stringified version. return ((component)).overriddenName || component.name || component.toString().split('\n')[0]; } class Deferred { constructor() { this.promise = new Promise((res, rej) => { this.resolve = res; this.reject = rej; }); } } /** * @param {?} component * @return {?} Whether the passed-in component implements the subset of the * `ControlValueAccessor` interface needed for AngularJS `ng-model` * compatibility. */ function supportsNgModel(component) { return typeof component.writeValue === 'function' && typeof component.registerOnChange === 'function'; } /** * Glue the AngularJS `NgModelController` (if it exists) to the component * (if it implements the needed subset of the `ControlValueAccessor` interface). * @param {?} ngModel * @param {?} component * @return {?} */ function hookupNgModel(ngModel, component) { if (ngModel && supportsNgModel(component)) { ngModel.$render = () => { component.writeValue(ngModel.$viewValue); }; component.registerOnChange(ngModel.$setViewValue.bind(ngModel)); } } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ const INITIAL_VALUE = { __UNINITIALIZED__: true }; class DowngradeComponentAdapter { /** * @param {?} id * @param {?} element * @param {?} attrs * @param {?} scope * @param {?} ngModel * @param {?} parentInjector * @param {?} $injector * @param {?} $compile * @param {?} $parse * @param {?} componentFactory */ constructor(id, element, attrs, scope, ngModel, parentInjector, $injector, $compile, $parse, componentFactory) { this.id = id; this.element = element; this.attrs = attrs; this.scope = scope; this.ngModel = ngModel; this.parentInjector = parentInjector; this.$injector = $injector; this.$compile = $compile; this.$parse = $parse; this.componentFactory = componentFactory; this.inputChangeCount = 0; this.inputChanges = null; this.componentRef = null; this.component = null; this.changeDetector = null; this.element[0].id = id; this.componentScope = scope.$new(); } /** * @return {?} */ compileContents() { const /** @type {?} */ compiledProjectableNodes = []; const /** @type {?} */ projectableNodes = this.groupProjectableNodes(); const /** @type {?} */ linkFns = projectableNodes.map(nodes => this.$compile(nodes)); this.element.empty(); linkFns.forEach(linkFn => { linkFn(this.scope, (clone) => { compiledProjectableNodes.push(clone); this.element.append(clone); }); }); return compiledProjectableNodes; } /** * @param {?} projectableNodes * @return {?} */ createComponent(projectableNodes) { const /** @type {?} */ childInjector = ReflectiveInjector.resolveAndCreate([{ provide: $SCOPE, useValue: this.componentScope }], this.parentInjector); this.componentRef = this.componentFactory.create(childInjector, projectableNodes, this.element[0]); this.changeDetector = this.componentRef.changeDetectorRef; this.component = this.componentRef.instance; hookupNgModel(this.ngModel, this.component); } /** * @return {?} */ setupInputs() { const /** @type {?} */ attrs = this.attrs; const /** @type {?} */ inputs = this.componentFactory.inputs || []; for (let /** @type {?} */ i = 0; i < inputs.length; i++) { const /** @type {?} */ input = new PropertyBinding(inputs[i].propName, inputs[i].templateName); let /** @type {?} */ expr = null; if (attrs.hasOwnProperty(input.attr)) { const /** @type {?} */ observeFn = (prop => { let /** @type {?} */ prevValue = INITIAL_VALUE; return (currValue) => { if (prevValue === INITIAL_VALUE) { prevValue = currValue; } this.updateInput(prop, prevValue, currValue); prevValue = currValue; }; })(input.prop); attrs.$observe(input.attr, observeFn); } else if (attrs.hasOwnProperty(input.bindAttr)) { expr = ((attrs) /** TODO #9100 */)[input.bindAttr]; } else if (attrs.hasOwnProperty(input.bracketAttr)) { expr = ((attrs) /** TODO #9100 */)[input.bracketAttr]; } else if (attrs.hasOwnProperty(input.bindonAttr)) { expr = ((attrs) /** TODO #9100 */)[input.bindonAttr]; } else if (attrs.hasOwnProperty(input.bracketParenAttr)) { expr = ((attrs) /** TODO #9100 */)[input.bracketParenAttr]; } if (expr != null) { const /** @type {?} */ watchFn = (prop => (currValue, prevValue) => this.updateInput(prop, prevValue, currValue))(input.prop); this.componentScope.$watch(expr, watchFn); } } const /** @type {?} */ prototype = this.componentFactory.componentType.prototype; if (prototype && ((prototype)).ngOnChanges) { // Detect: OnChanges interface this.inputChanges = {}; this.componentScope.$watch(() => this.inputChangeCount, () => { const /** @type {?} */ inputChanges = this.inputChanges; this.inputChanges = {}; ((this.component)).ngOnChanges(inputChanges); }); } this.componentScope.$watch(() => this.changeDetector && this.changeDetector.detectChanges()); } /** * @return {?} */ setupOutputs() { const /** @type {?} */ attrs = this.attrs; const /** @type {?} */ outputs = this.componentFactory.outputs || []; for (let /** @type {?} */ j = 0; j < outputs.length; j++) { const /** @type {?} */ output = new PropertyBinding(outputs[j].propName, outputs[j].templateName); let /** @type {?} */ expr = null; let /** @type {?} */ assignExpr = false; const /** @type {?} */ bindonAttr = output.bindonAttr ? output.bindonAttr.substring(0, output.bindonAttr.length - 6) : null; const /** @type {?} */ bracketParenAttr = output.bracketParenAttr ? `[(${output.bracketParenAttr.substring(2, output.bracketParenAttr.length - 8)})]` : null; if (attrs.hasOwnProperty(output.onAttr)) { expr = ((attrs) /** TODO #9100 */)[output.onAttr]; } else if (attrs.hasOwnProperty(output.parenAttr)) { expr = ((attrs) /** TODO #9100 */)[output.parenAttr]; } else if (attrs.hasOwnProperty(bindonAttr)) { expr = ((attrs) /** TODO #9100 */)[bindonAttr]; assignExpr = true; } else if (attrs.hasOwnProperty(bracketParenAttr)) { expr = ((attrs) /** TODO #9100 */)[bracketParenAttr]; assignExpr = true; } if (expr != null && assignExpr != null) { const /** @type {?} */ getter = this.$parse(expr); const /** @type {?} */ setter = getter.assign; if (assignExpr && !setter) { throw new Error(`Expression '${expr}' is not assignable!`); } const /** @type {?} */ emitter = (this.component[output.prop]); if (emitter) { emitter.subscribe({ next: assignExpr ? ((setter) => (v /** TODO #9100 */) => setter(this.scope, v))(setter) : ((getter) => (v /** TODO #9100 */) => getter(this.scope, { $event: v }))(getter) }); } else { throw new Error(`Missing emitter '${output.prop}' on component '${getComponentName(this.componentFactory.componentType)}'!`); } } } } /** * @return {?} */ registerCleanup() { this.element.bind('$destroy', () => { this.componentScope.$destroy(); this.componentRef.destroy(); }); } /** * @return {?} */ getInjector() { return this.componentRef && this.componentRef.injector; } /** * @param {?} prop * @param {?} prevValue * @param {?} currValue * @return {?} */ updateInput(prop, prevValue, currValue) { if (this.inputChanges) { this.inputChangeCount++; this.inputChanges[prop] = new SimpleChange(prevValue, currValue, prevValue === currValue); } this.component[prop] = currValue; } /** * @return {?} */ groupProjectableNodes() { let /** @type {?} */ ngContentSelectors = this.componentFactory.ngContentSelectors; return groupNodesBySelector(ngContentSelectors, this.element.contents()); } } /** * Group a set of DOM nodes into `ngContent` groups, based on the given content selectors. * @param {?} ngContentSelectors * @param {?} nodes * @return {?} */ function groupNodesBySelector(ngContentSelectors, nodes) { const /** @type {?} */ projectableNodes = []; let /** @type {?} */ wildcardNgContentIndex; for (let /** @type {?} */ i = 0, /** @type {?} */ ii = ngContentSelectors.length; i < ii; ++i) { projectableNodes[i] = []; } for (let /** @type {?} */ j = 0, /** @type {?} */ jj = nodes.length; j < jj; ++j) { const /** @type {?} */ node = nodes[j]; const /** @type {?} */ ngContentIndex = findMatchingNgContentIndex(node, ngContentSelectors); if (ngContentIndex != null) { projectableNodes[ngContentIndex].push(node); } } return projectableNodes; } /** * @param {?} element * @param {?} ngContentSelectors * @return {?} */ function findMatchingNgContentIndex(element, ngContentSelectors) { const /** @type {?} */ ngContentIndices = []; let /** @type {?} */ wildcardNgContentIndex; for (let /** @type {?} */ i = 0; i < ngContentSelectors.length; i++) { const /** @type {?} */ selector = ngContentSelectors[i]; if (selector === '*') { wildcardNgContentIndex = i; } else { if (matchesSelector(element, selector)) { ngContentIndices.push(i); } } } ngContentIndices.sort(); if (wildcardNgContentIndex !== undefined) { ngContentIndices.push(wildcardNgContentIndex); } return ngContentIndices.length ? ngContentIndices[0] : null; } let _matches; /** * @param {?} el * @param {?} selector * @return {?} */ function matchesSelector(el, selector) { if (!_matches) { const /** @type {?} */ elProto = (Element.prototype); _matches = elProto.matches || elProto.matchesSelector || elProto.mozMatchesSelector || elProto.msMatchesSelector || elProto.oMatchesSelector || elProto.webkitMatchesSelector; } return el.nodeType === Node.ELEMENT_NODE ? _matches.call(el, selector) : false; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ let downgradeCount = 0; /** * \@whatItDoes * * *Part of the [upgrade/static](/docs/ts/latest/api/#!?query=upgrade%2Fstatic) * library for hybrid upgrade apps that support AoT compilation* * * Allows an Angular component to be used from AngularJS. * * \@howToUse * * Let's assume that you have an Angular component called `ng2Heroes` that needs * to be made available in AngularJS templates. * * {\@example upgrade/static/ts/module.ts region="ng2-heroes"} * * We must create an AngularJS [directive](https://docs.angularjs.org/guide/directive) * that will make this Angular component available inside AngularJS templates. * The `downgradeComponent()` function returns a factory function that we * can use to define the AngularJS directive that wraps the "downgraded" component. * * {\@example upgrade/static/ts/module.ts region="ng2-heroes-wrapper"} * * \@description * * A helper function that returns a factory function to be used for registering an * AngularJS wrapper directive for "downgrading" an Angular component. * * The parameter contains information about the Component that is being downgraded: * * * `component: Type<any>`: The type of the Component that will be downgraded * * \@experimental * @param {?} info * @return {?} */ function downgradeComponent(info) { const /** @type {?} */ idPrefix = `NG2_UPGRADE_${downgradeCount++}_`; let /** @type {?} */ idCount = 0; const /** @type {?} */ directiveFactory = function ($compile, $injector, $parse) { return { restrict: 'E', terminal: true, require: [REQUIRE_INJECTOR, REQUIRE_NG_MODEL], link: (scope, element, attrs, required) => { // We might have to compile the contents asynchronously, because this might have been // triggered by `UpgradeNg1ComponentAdapterBuilder`, before the Angular templates have // been compiled. const /** @type {?} */ parentInjector = required[0] || $injector.get(INJECTOR_KEY); const /** @type {?} */ ngModel = required[1]; const /** @type {?} */ downgradeFn = (injector) => { const /** @type {?} */ componentFactoryResolver = injector.get(ComponentFactoryResolver); const /** @type {?} */ componentFactory = componentFactoryResolver.resolveComponentFactory(info.component); if (!componentFactory) { throw new Error('Expecting ComponentFactory for: ' + getComponentName(info.component)); } const /** @type {?} */ id = idPrefix + (idCount++); const /** @type {?} */ injectorPromise = new ParentInjectorPromise$1(element); const /** @type {?} */ facade = new DowngradeComponentAdapter(id, element, attrs, scope, ngModel, injector, $injector, $compile, $parse, componentFactory); const /** @type {?} */ projectableNodes = facade.compileContents(); facade.createComponent(projectableNodes); facade.setupInputs(); facade.setupOutputs(); facade.registerCleanup(); injectorPromise.resolve(facade.getInjector()); }; if (parentInjector instanceof ParentInjectorPromise$1) { parentInjector.then(downgradeFn); } else { downgradeFn(parentInjector); } } }; }; // bracket-notation because of closure - see #14441 directiveFactory['$inject'] = [$COMPILE, $INJECTOR, $PARSE]; return directiveFactory; } /** * Synchronous promise-like object to wrap parent injectors, * to preserve the synchronous nature of Angular 1's $compile. */ class ParentInjectorPromise$1 { /** * @param {?} element */ constructor(element) { this.element = element; this.injectorKey = controllerKey(INJECTOR_KEY); this.callbacks = []; // Store the promise on the element. element.data(this.injectorKey, this); } /** * @param {?} callback * @return {?} */ then(callback) { if (this.injector) { callback(this.injector); } else { this.callbacks.push(callback); } } /** * @param {?} injector * @return {?} */ resolve(injector) { this.injector = injector; // Store the real injector on the element. this.element.data(this.injectorKey, injector); // Release the element to prevent memory leaks. this.element = null; // Run the queued callbacks. this.callbacks.forEach(callback => callback(injector)); this.callbacks.length = 0; } } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * \@whatItDoes * * *Part of the [upgrade/static](/docs/ts/latest/api/#!?query=upgrade%2Fstatic) * library for hybrid upgrade apps that support AoT compilation* * * Allow an Angular service to be accessible from AngularJS. * * \@howToUse * * First ensure that the service to be downgraded is provided in an {\@link NgModule} * that will be part of the upgrade application. For example, let's assume we have * defined `HeroesService` * * {\@example upgrade/static/ts/module.ts region="ng2-heroes-service"} * * and that we have included this in our upgrade app {\@link NgModule} * * {\@example upgrade/static/ts/module.ts region="ng2-module"} * * Now we can register the `downgradeInjectable` factory function for the service * on an AngularJS module. * * {\@example upgrade/static/ts/module.ts region="downgrade-ng2-heroes-service"} * * Inside an AngularJS component's controller we can get hold of the * downgraded service via the name we gave when downgrading. * * {\@example upgrade/static/ts/module.ts region="example-app"} * * \@description * * Takes a `token` that identifies a service provided from Angular. * * Returns a [factory function](https://docs.angularjs.org/guide/di) that can be * used to register the service on an AngularJS module. * * The factory function provides access to the Angular service that * is identified by the `token` parameter. * * \@experimental * @param {?} token * @return {?} */ function downgradeInjectable(token) { const /** @type {?} */ factory = function (i) { return i.get(token); }; ((factory)).$inject = [INJECTOR_KEY]; return factory; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ const CAMEL_CASE = /([A-Z])/g; const INITIAL_VALUE$1 = { __UNINITIALIZED__: true }; const NOT_SUPPORTED = 'NOT_SUPPORTED'; class UpgradeNg1ComponentAdapterBuilder { /** * @param {?} name */ constructor(name) { this.name = name; this.inputs = []; this.inputsRename = []; this.outputs = []; this.outputsRename = []; this.propertyOutputs = []; this.checkProperties = []; this.propertyMap = {}; this.linkFn = null; this.directive = null; this.$controller = null; const selector = name.replace(CAMEL_CASE, (all /** TODO #9100 */, next) => '-' + next.toLowerCase()); const self = this; this.type = Directive({ selector: selector, inputs: this.inputsRename, outputs: this.outputsRename }) .Class({ constructor: [ new Inject($SCOPE), ElementRef, function (scope, elementRef) { return new UpgradeNg1ComponentAdapter(self.linkFn, scope, self.directive, elementRef, self.$controller, self.inputs, self.outputs, self.propertyOutputs, self.checkProperties, self.propertyMap); } ], ngOnInit: function () { }, ngOnChanges: function () { }, ngDoCheck: function () { }, ngOnDestroy: function () { }, }); } /** * @param {?} injector * @return {?} */ extractDirective(injector) { const /** @type {?} */ directives = injector.get(this.name + 'Directive'); if (directives.length > 1) { throw new Error('Only support single directive definition for: ' + this.name); } const /** @type {?} */ directive = directives[0]; if (directive.replace) this.notSupported('replace'); if (directive.terminal) this.notSupported('terminal'); const /** @type {?} */ link = directive.link; if (typeof link == 'object') { if (((link)).post) this.notSupported('link.post'); } return directive; } /** * @param {?} feature * @return {?} */ notSupported(feature) { throw new Error(`Upgraded directive '${this.name}' does not support '${feature}'.`); } /** * @return {?} */ extractBindings() { const /** @type {?} */ btcIsObject = typeof this.directive.bindToController === 'object'; if (btcIsObject && Object.keys(this.directive.scope).length) { throw new Error(`Binding definitions on scope and controller at the same time are not supported.`); } const /** @type {?} */ context = (btcIsObject) ? this.directive.bindToController : this.directive.scope; if (typeof context == 'object') { for (const /** @type {?} */ name in context) { if (((context)).hasOwnProperty(name)) { let /** @type {?} */ localName = context[name]; const /** @type {?} */ type = localName.charAt(0); const /** @type {?} */ typeOptions = localName.charAt(1); localName = typeOptions === '?' ? localName.substr(2) : localName.substr(1); localName = localName || name; const /** @type {?} */ outputName = 'output_' + name; const /** @type {?} */ outputNameRename = outputName + ': ' + name; const /** @type {?} */ outputNameRenameChange = outputName + ': ' + name + 'Change'; const /** @type {?} */ inputName = 'input_' + name; const /** @type {?} */ inputNameRename = inputName + ': ' + name; switch (type) { case '=': this.propertyOutputs.push(outputName); this.checkProperties.push(localName); this.outputs.push(outputName); this.outputsRename.push(outputNameRenameChange); this.propertyMap[outputName] = localName; this.inputs.push(inputName); this.inputsRename.push(inputNameRename); this.propertyMap[inputName] = localName; break; case '@': // handle the '<' binding of angular 1.5 components case '<': this.inputs.push(inputName); this.inputsRename.push(inputNameRename); this.propertyMap[inputName] = localName; break; case '&': this.outputs.push(outputName); this.outputsRename.push(outputNameRename); this.propertyMap[outputName] = localName; break; default: let /** @type {?} */ json = JSON.stringify(context); throw new Error(`Unexpected mapping '${type}' in '${json}' in '${this.name}' directive.`); } } } } } /** * @param {?} compile * @param {?} templateCache * @param {?} httpBackend * @return {?} */ compileTemplate(compile, templateCache, httpBackend) { if (this.directive.template !== undefined) { this.linkFn = compileHtml(isFunction(this.directive.template) ? this.directive.template() : this.directive.template); } else if (this.directive.templateUrl) { const /** @type {?} */ url = isFunction(this.directive.templateUrl) ? this.directive.templateUrl() : this.directive.templateUrl; const /** @type {?} */ html = templateCache.get(url); if (html !== undefined) { this.linkFn = compileHtml(html); } else { return new Promise((resolve, err) => { httpBackend('GET', url, null, (status /** TODO #9100 */, response /** TODO #9100 */) => { if (status == 200) { resolve(this.linkFn = compileHtml(templateCache.put(url, response))); } else { err(`GET ${url} returned ${status}: ${response}`); } }); }); } } else { throw new Error(`Directive '${this.name}' is not a component, it is missing template.`); } return null; /** * @param {?} html * @return {?} */ function compileHtml(html /** TODO #9100 */) { const /** @type {?} */ div = document.createElement('div'); div.innerHTML = html; return compile(div.childNodes); } } /** * Upgrade ng1 components into Angular. * @param {?} exportedComponents * @param {?} injector * @return {?} */ static resolve(exportedComponents, injector) { const /** @type {?} */ promises = []; const /** @type {?} */ compile = injector.get($COMPILE); const /** @type {?} */ templateCache = injector.get($TEMPLATE_CACHE); const /** @type {?} */ httpBackend = injector.get($HTTP_BACKEND); const /** @type {?} */ $controller = injector.get($CONTROLLER); for (const /** @type {?} */ name in exportedComponents) { if (((exportedComponents)).hasOwnProperty(name)) { const /** @type {?} */ exportedComponent = exportedComponents[name]; exportedComponent.directive = exportedComponent.extractDirective(injector); exportedComponent.$controller = $controller; exportedComponent.extractBindings(); const /** @type {?} */ promise = exportedComponent.compileTemplate(compile, templateCache, httpBackend); if (promise) promises.push(promise); } } return Promise.all(promises); } } class UpgradeNg1ComponentAdapter { /** * @param {?} linkFn * @param {?} scope * @param {?} directive * @param {?} elementRef * @param {?} $controller * @param {?} inputs * @param {?} outputs * @param {?} propOuts * @param {?} checkProperties * @param {?} propertyMap */ constructor(linkFn, scope, directive, elementRef, $controller, inputs, outputs, propOuts, checkProperties, propertyMap) { this.linkFn = linkFn; this.directive = directive; this.$controller = $controller; this.inputs = inputs; this.outputs = outputs; this.propOuts = propOuts; this.checkProperties = checkProperties; this.propertyMap = propertyMap; this.controllerInstance = null; this.destinationObj = null; this.checkLastValues = []; this.$element = null; this.element = elementRef.nativeElement; this.componentScope = scope.$new(!!directive.scope); this.$element = element(this.element); const controllerType = directive.controller; if (directive.bindToController && controllerType) { this.controllerInstance = this.buildController(controllerType); this.destinationObj = this.controllerInstance; } else { this.destinationObj = this.componentScope; } for (let i = 0; i < inputs.length; i++) { this /** TODO #9100 */[inputs[i]] = null; } for (let j = 0; j < outputs.length; j++) { const emitter = this /** TODO #9100 */[outputs[j]] = new EventEmitter(); this.setComponentProperty(outputs[j], ((emitter /** TODO #9100 */) => (value /** TODO #9100 */) => emitter.emit(value))(emitter)); } for (let k = 0; k < propOuts.length; k++) { this /** TODO #9100 */[propOuts[k]] = new EventEmitter(); this.checkLastValues.push(INITIAL_VALUE$1); } } /** * @return {?} */ ngOnInit() { if (!this.directive.bindToController && this.directive.controller) { this.controllerInstance = this.buildController(this.directive.controller); } if (this.controllerInstance && isFunction(this.controllerInstance.$onInit)) { this.controllerInstance.$onInit(); } let /** @type {?} */ link = this.directive.link; if (typeof link == 'object') link = ((link)).pre; if (link) { const /** @type {?} */ attrs = NOT_SUPPORTED; const /** @type {?} */ transcludeFn = NOT_SUPPORTED; const /** @type {?} */ linkController = this.resolveRequired(this.$element, this.directive.require); ((this.directive.link))(this.componentScope, this.$element, attrs, linkController, transcludeFn); } const /** @type {?} */ childNodes = []; let /** @type {?} */ childNode; while (childNode = this.element.firstChild) { this.element.removeChild(childNode); childNodes.push(childNode); } this.linkFn(this.componentScope, (clonedElement, scope) => { for (let /** @type {?} */ i = 0, /** @type {?} */ ii = clonedElement.length; i < ii; i++) { this.element.appendChild(clonedElement[i]); } }, { parentBoundTranscludeFn: (scope /** TODO #9100 */, cloneAttach /** TODO #9100 */) => { cloneAttach(childNodes); } }); if (this.controllerInstance && isFunction(this.controllerInstance.$postLink)) { this.controllerInstance.$postLink(); } } /** * @param {?} changes * @return {?} */ ngOnChanges(changes) { const /** @type {?} */ ng1Changes = {}; Object.keys(changes).forEach(name => { const /** @type {?} */ change = changes[name]; this.setComponentProperty(name, change.currentValue); ng1Changes[this.propertyMap[name]] = change; }); if (isFunction(this.destinationObj.$onChanges)) { this.destinationObj.$onChanges(ng1Changes); } } /** * @return {?} */ ngDoCheck() { const /** @type {?} */ destinationObj = this.destinationObj; const /** @type {?} */ lastValues = this.checkLastValues; const /** @type {?} */ checkProperties = this.checkProperties; for (let /** @type {?} */ i = 0; i < checkProperties.length; i++) { const /** @type {?} */ value = destinationObj[checkProperties[i]]; const /** @type {?} */ last = lastValues[i]; if (value !== last) { if (typeof value == 'number' && isNaN(value) && typeof last == 'number' && isNaN(last)) { } else { const /** @type {?} */ eventEmitter = ((this) /** TODO #9100 */)[this.propOuts[i]]; eventEmitter.emit(lastValues[i] = value); } } } if (this.controllerInstance && isFunction(this.controllerInstance.$doCheck)) { this.controllerInstance.$doCheck(); } } /** * @return {?} */ ngOnDestroy() { if (this.controllerInstance && isFunction(this.controllerInstance.$onDestroy)) { this.controllerInstance.$onDestroy(); } } /** * @param {?} name * @param {?} value * @return {?} */ setComponentProperty(name, value) { this.destinationObj[this.propertyMap[name]] = value; } /** * @param {?} controllerType * @return {?} */ buildController(controllerType /** TODO #9100 */) { const /** @type {?} */ locals = { $scope: this.componentScope, $element: this.$element }; const /** @type {?} */ controller = this.$controller(controllerType, locals, null, this.directive.controllerAs); this.$element.data(controllerKey(this.directive.name), controller); return controller; } /** * @param {?} $element * @param {?} require * @return {?} */ resolveRequired($element, require) { if (!require) { return undefined; } else if (typeof require == 'string') { let /** @type {?} */ name = (require); let /** @type {?} */ isOptional = false; let /** @type {?} */ startParent = false; let /** @type {?} */ searchParents = false; if (name.charAt(0) == '?') { isOptional = true; name = name.substr(1); } if (name.charAt(0) == '^') { searchParents = true; name = name.substr(1); } if (name.charAt(0) == '^') { startParent = true; name = name.substr(1); } const /** @type {?} */ key = controllerKey(name); if (startParent) $element = $element.parent(); const /** @type {?} */ dep = searchParents ? $element.inheritedData(key) : $element.data(key); if (!dep && !isOptional) { throw new Error(`Can not locate '${require}' in '${this.directive.name}'.`); } return dep; } else if (require instanceof Array) { const /** @type {?} */ deps = []; for (let /** @type {?} */ i = 0; i < require.length; i++) { deps.push(this.resolveRequired($element, require[i])); } return deps; } throw new Error(`Directive '${this.directive.name}' require syntax unrecognized: ${this.directive.require}`); } } /** * @param {?} value * @return {?} */ function isFunction(value) { return typeof value === 'function'; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ let upgradeCount = 0; /** * Use `UpgradeAdapter` to allow AngularJS and Angular to coexist in a single application. * * The `UpgradeAdapter` allows: * 1. creation of Angular component from AngularJS component directive * (See [UpgradeAdapter#upgradeNg1Component()]) * 2. creation of AngularJS directive from Angular component. * (See [UpgradeAdapter#downgradeNg2Component()]) * 3. Bootstrapping of a hybrid Angular application which contains both of the frameworks * coexisting in a single application. * * ## Mental Model * * When reasoning about how a hybrid application works it is useful to have a mental model which * describes what is happening and explains what is happening at the lowest level. * * 1. There are two independent frameworks running in a single application, each framework treats * the other as a black box. * 2. Each DOM element on the page is owned exactly by one framework. Whichever framework * instantiated the element is the owner. Each framework only updates/interacts with its own * DOM elements and ignores others. * 3. AngularJS directives always execute inside AngularJS framework codebase regardless of * where they are instantiated. * 4. Angular components always execute inside Angular framework codebase regardless of * where they are instantiated. * 5. An AngularJS component can be upgraded to an Angular component. This creates an * Angular directive, which bootstraps the AngularJS component directive in that location. * 6. An Angular component can be downgraded to an AngularJS component directive. This creates * an AngularJS directive, which bootstraps the Angular component in that location. * 7. Whenever an adapter component is instantiated the host element is owned by the framework * doing the instantiation. The other framework then instantiates and owns the view for that * component. This implies that component bindings will always follow the semantics of the * instantiation framework. The syntax is always that of Angular syntax. * 8. AngularJS is always bootstrapped first and owns the bottom most view. * 9. The new application is running in Angular zone, and therefore it no longer needs calls to * `$apply()`. * * ### Example * * ``` * const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module), myCompilerOptions); * const module = angular.module('myExample', []); * module.directive('ng2Comp', adapter.downgradeNg2Component(Ng2Component)); * * module.directive('ng1Hello', function() { * return { * scope: { title: '=' }, * template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)' * }; * }); * * * \@Component({ * selector: 'ng2-comp', * inputs: ['name'], * template: 'ng2[<ng1-hello [title]="name">transclude</ng1-hello>](<ng-content></ng-content>)', * directives: * }) * class Ng2Component { * } * * \@NgModule({ * declarations: [Ng2Component, adapter.upgradeNg1Component('ng1Hello')], * imports: [BrowserModule] * }) * class MyNg2Module {} * * * document.body.innerHTML = '<ng2-comp name="World">project</ng2-comp>'; * * adapter.bootstrap(document.body, ['myExample']).ready(function() { * expect(document.body.textContent).toEqual( * "ng2[ng1[Hello World!](transclude)](project)"); * }); * * ``` * * \@stable */ class UpgradeAdapter { /** * @param {?} ng2AppModule * @param {?=} compilerOptions */ constructor(ng2AppModule, compilerOptions) { this.ng2AppModule = ng2AppModule; this.compilerOptions = compilerOptions; this.idPrefix = `NG2_UPGRADE_${upgradeCount++}_`; this.downgradedComponents = []; /** * An internal map of ng1 components which need to up upgraded to ng2. * * We can't upgrade until injector is instantiated and we can retrieve the component metadata. * For this reason we keep a list of components to upgrade until ng1 injector is bootstrapped. * * \@internal */ this.ng1ComponentsToBeUpgraded = {}; this.upgradedProviders = []; this.moduleRef = null; if (!ng2AppModule) { throw new Error('UpgradeAdapter cannot be instantiated without an NgModule of the Angular app.'); } } /** * Allows Angular Component to be used from AngularJS. * * Use `downgradeNg2Component` to create an AngularJS Directive Definition Factory from * Angular Component. The adapter will bootstrap Angular component from within the * AngularJS template. * * ## Mental Model * * 1. The component is instantiated by being listed in AngularJS template. This means that the * host element is controlled by AngularJS, but the component's view will be controlled by * Angular. * 2. Even thought the component is instantiated in AngularJS, it will be using Angular * syntax. This has to be done, this way because we must follow Angular components do not * declare how the attributes should be interpreted. * 3. `ng-model` is controlled by AngularJS and communicates with the downgraded Angular component * by way of the `ControlValueAccessor` interface from \@angular/forms. Only components that * implement this interface are eligible. * * ## Supported Features * * - Bindings: * - Attribute: `<comp name="World">` * - Interpolation: `<comp greeting="Hello {{name}}!">` * - Expression: `<comp [name]="username">` * - Event: `<comp (close)="doSomething()">` * - ng-model: `<comp ng-model="name">` * - Content projection: yes * * ### Example * * ``` * const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module)); * const module = angular.module('myExample', []); * module.directive('greet', adapter.downgradeNg2Component(Greeter)); * * \@Component({ * selector: 'greet', * template: '{{salutation}} {{name}}! - <ng-content></ng-content>' * }) * class Greeter { * \@Input() salutation: string; * \@Input() name: string; * } * * \@NgModule({ * declarations: [Greeter], * imports: [BrowserModule] * }) * class MyNg2Module {} * * document.body.innerHTML = * 'ng1 template: <greet salutation="Hello" [name]="world">text</greet>'; * * adapter.bootstrap(document.body, ['myExample']).ready(function() { * expect(document.body.textContent).toEqual("ng1 template: Hello world! - text"); * }); * ``` * @param {?} component * @return {?} */ downgradeNg2Component(component) { this.downgradedComponents.push(component); return downgradeComponent({ component }); } /** * Allows AngularJS Component to be used from Angular. * * Use `upgradeNg1Component` to create an Angular component from AngularJS Component * directive. The adapter will bootstrap AngularJS component from within the Angular * template. * * ## Mental Model * * 1. The component is instantiated by being listed in Angular template. This means that the * host element is controlled by Angular, but the component's view will be controlled by * AngularJS. * * ## Supported Features * * - Bindings: * - Attribute: `<comp name="World">` * - Interpolation: `<comp greeting="Hello {{name}}!">` * - Expression: `<comp [name]="username">` * - Event: `<comp (close)="doSomething()">` * - Transclusion: yes * - Only some of the features of * [Directive Definition Object](https://docs.angularjs.org/api/ng/service/$compile) are * supported: * - `compile`: not supported because the host element is owned by Angular, which does * not allow modifying DOM structure during compilation. * - `controller`: supported. (NOTE: injection of `$attrs` and `$transclude` is not supported.) * - `controllerAs`: supported. * - `bindToController`: supported. * - `link`: supported. (NOTE: only pre-link function is supported.) * - `name`: supported. * - `priority`: ignored. * - `replace`: not supported. * - `require`: supported. * - `restrict`: must be set to 'E'. * - `scope`: supported. * - `template`: supported. * - `templateUrl`: supported. * - `terminal`: ignored. * - `transclude`: supported. * * * ### Example * * ``` * const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module)); * const module = angular.module('myExample', []); * * module.directive('greet', function() { * return { * scope: {salutation: '=', name: '=' }, * template: '{{salutation}} {{name}}! - <span ng-transclude></span>' * }; * }); * * module.directive('ng2', adapter.downgradeNg2Component(Ng2Component)); * * \@Component({ * selector: 'ng2', * template: 'ng2 template: <greet salutation="Hello" [name]="world">text</greet>' * }) * class Ng2Component { * } * * \@NgModule({ * declarations: [Ng2Component, adapter.upgradeNg1Component('greet')], * imports: [BrowserModule] * }) * class MyNg2Module {} * * document.body.innerHTML = '<ng2></ng2>'; * * adapter.bootstrap(document.body, ['myExample']).ready(function() { * expect(document.body.textContent).toEqual("ng2 template: Hello world! - text"); * }); * ``` * @param {?} name * @return {?} */ upgradeNg1Component(name) { if (((this.ng1ComponentsToBeUpgraded)).hasOwnProperty(name)) { return this.ng1ComponentsToBeUpgraded[name].type; } else { return (this.ng1ComponentsToBeUpgraded[name] = new UpgradeNg1ComponentAdapterBuilder(name)) .type; } } /** * Registers the adapter's AngularJS upgrade module for unit testing in AngularJS. * Use this instead of `angular.mock.module()` to load the upgrade module into * the AngularJS testing injector. * * ### Example * * ``` * const upgradeAdapter = new UpgradeAdapter(MyNg2Module); * * // configure the adapter with upgrade/downgrade components and services * upgradeAdapter.downgradeNg2Component(MyComponent); * * let upgradeAdapterRef: UpgradeAdapterRef; * let $compile, $rootScope; * * // We must register the adapter before any calls to `inject()` * beforeEach(() => { * upgradeAdapterRef = upgradeAdapter.registerForNg1Tests(['heroApp']); * }); * * beforeEach(inject((_$compile_, _$rootScope_) => { * $compile = _$compile_; * $rootScope = _$rootScope_; * })); * * it("says hello", (done) => { * upgradeAdapterRef.ready(() => { * const element = $compile("<my-component></my-component>")($rootScope); * $rootScope.$apply(); * expect(element.html()).toContain("Hello World"); * done(); * }) * }); * * ``` * * @param {?=} modules any AngularJS modules that the upgrade module should depend upon * @return {?} an {\@link UpgradeAdapterRef}, which lets you register a `ready()` callback to * run assertions once the Angular components are ready to test through AngularJS. */ registerForNg1Tests(modules) { const /** @type {?} */ windowNgMock = ((window))['angular'].mock; if (!windowNgMock || !windowNgMock.module) { throw new Error('Failed to find \'angular.mock.module\'.'); } this.declareNg1Module(modules); windowNgMock.module(this.ng1Module.name); const /** @type {?} */ upgrade = new UpgradeAdapterRef(); this.ng2BootstrapDeferred.promise.then((ng1Injector) => { ((upgrade))._bootstrapDone(this.moduleRef, ng1Injector); }, onError); return upgrade; } /** * Bootstrap a hybrid AngularJS / Angular application. * * This `bootstrap` method is a direct replacement (takes same arguments) for AngularJS * [`bootstrap`](https://docs.angularjs.org/api/ng/function/angular.bootstrap) method. Unlike * AngularJS, this bootstrap is asynchronous. * * ### Example * * ``` * const adapter = new UpgradeAdapter(MyNg2Module); * const module = angular.module('myExample', []); * module.directive('ng2', adapter.downgradeNg2Component(Ng2)); * * module.directive('ng1', function() { * return { * scope: { title: '=' }, * template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)' * }; * }); * * * \@Component({ * selector: 'ng2', * inputs: ['name'], * template: 'ng2[<ng1 [title]="name">transclude</ng1>](<ng-content></ng-content>)' * }) * class Ng2 { * } * * \@NgModule({ * declarations: [Ng2, adapter.upgradeNg1Component('ng1')], * imports: [BrowserModule] * }) * class MyNg2Module {} * * document.body.innerHTML = '<ng2 name="World">project</ng2>'; * * adapter.bootstrap(document.body, ['myExample']).ready(function() { * expect(document.body.textContent).toEqual( * "ng2[ng1[Hello World!](transclude)](project)"); * }); * ``` * @param {?} element * @param {?=} modules * @param {?=} config * @return {?} */ bootstrap(element$$1, modules, config) { this.declareNg1Module(modules); const /** @type {?} */ upgrade = new UpgradeAdapterRef(); // Make sure resumeBootstrap() only exists if the current bootstrap is deferred const /** @type {?} */ windowAngular = ((window) /** TODO #???? */)['angular']; windowAngular.resumeBootstrap = undefined; this.ngZone.run(() => { bootstrap(element$$1, [this.ng1Module.name], config); }); const /** @type {?} */ ng1BootstrapPromise = new Promise((resolve) => { if (windowAngular.resumeBootstrap) { const /** @type {?} */ originalResumeBootstrap = windowAngular.resumeBootstrap; windowAngular.resumeBootstrap = function () { windowAngular.resumeBootstrap = originalResumeBootstrap; windowAngular.resumeBootstrap.apply(this, arguments); resolve(); }; } else { resolve(); } }); Promise.all([this.ng2BootstrapDeferred.promise, ng1BootstrapPromise]).then(([ng1Injector]) => { element(element$$1).data(controllerKey(INJECTOR_KEY), this.moduleRef.injector); this.moduleRef.injector.get(NgZone).run(() => { ((upgrade))._bootstrapDone(this.moduleRef, ng1Injector); }); }, onError); return upgrade; } /** * Allows AngularJS service to be accessible from Angular. * * * ### Example * * ``` * class Login { ... } * class Server { ... } * * \@Injectable() * class Example { * constructor(\@Inject('server') server, login: Login) { * ... * } * } * * const module = angular.module('myExample', []); * module.service('server', Server); * module.service('login', Login); * * const adapter = new UpgradeAdapter(MyNg2Module); * adapter.upgradeNg1Provider('server'); * adapter.upgradeNg1Provider('login', {asToken: Login}); * * adapter.bootstrap(document.body, ['myExample']).ready((ref) => { * const example: Example = ref.ng2Injector.get(Example); * }); * * ``` * @param {?} name * @param {?=} options * @return {?} */ upgradeNg1Provider(name, options) { const /** @type {?} */ token = options && options.asToken || name; this.upgradedProviders.push({ provide: token, useFactory: ($injector) => $injector.get(name), deps: [$INJECTOR] }); } /** * Allows Angular service to be accessible from AngularJS. * * * ### Example * * ``` * class Example { * } * * const adapter = new UpgradeAdapter(MyNg2Module); * * const module = angular.module('myExample', []); * module.factory('example', adapter.downgradeNg2Provider(Example)); * * adapter.bootstrap(document.body, ['myExample']).ready((ref) => { * const example: Example = ref.ng1Injector.get('example'); * }); * * ``` * @param {?} token * @return {?} */ downgradeNg2Provider(token) { return downgradeInjectable(token); } /** * Declare the AngularJS upgrade module for this adapter without bootstrapping the whole * hybrid application. * * This method is automatically called by `bootstrap()` and `registerForNg1Tests()`. * * @param {?=} modules The AngularJS modules that this upgrade module should depend upon. * @return {?} The AngularJS upgrade module that is declared by this method * * ### Example * * ``` * const upgradeAdapter = new UpgradeAdapter(MyNg2Module); * upgradeAdapter.declareNg1Module(['heroApp']); * ``` */ declareNg1Module(modules = []) { const /** @type {?} */ delayApplyExps = []; let /** @type {?} */ original$applyFn; let /** @type {?} */ rootScopePrototype; let /** @type {?} */ rootScope; const /** @type {?} */ upgradeAdapter = this; const /** @type {?} */ ng1Module = this.ng1Module = module$1(this.idPrefix, modules); const /** @type {?} */ platformRef = platformBrowserDynamic(); this.ngZone = new NgZone({ enableLongStackTrace: Zone.hasOwnProperty('longStackTraceZoneSpec') }); this.ng2BootstrapDeferred = new Deferred(); ng1Module.factory(INJECTOR_KEY, () => this.moduleRef.injector.get(Injector)) .constant(NG_ZONE_KEY, this.ngZone) .factory(COMPILER_KEY, () => this.moduleRef.injector.get(Compiler)) .config([ '$provide', '$injector', (provide, ng1Injector) => { provide.decorator($ROOT_SCOPE, [ '$delegate', function (rootScopeDelegate) { // Capture the root apply so that we can delay first call to $apply until we // bootstrap Angular and then we replay and restore the $apply. rootScopePrototype = rootScopeDelegate.constructor.prototype; if (rootScopePrototype.hasOwnProperty('$apply')) { original$applyFn = rootScopePrototype.$apply; rootScopePrototype.$apply = (exp) => delayApplyExps.push(exp); } else { throw new Error('Failed to find \'$apply\' on \'$rootScope\'!'); } return rootScope = rootScopeDelegate; } ]); if (ng1Injector.has($$TESTABILITY)) { provide.decorator($$TESTABILITY, [ '$delegate', function (testabilityDelegate) { const /** @type {?} */ originalWhenStable = testabilityDelegate.whenStable; // Cannot use arrow function below because we need the context const /** @type {?} */ newWhenStable = function (callback) { originalWhenStable.call(this, function () { const /** @type {?} */ ng2Testability = upgradeAdapter.moduleRef.injector.get(Testability); if (ng2Testability.isStable()) { callback.apply(this, arguments); } else { ng2Testability.whenStable(newWhenStable.bind(this, callback)); } }); }; testabilityDelegate.whenStable = newWhenStable; return testabilityDelegate; } ]); } } ]); ng1Module.run([ '$injector', '$rootScope', (ng1Injector, rootScope) => { UpgradeNg1ComponentAdapterBuilder.resolve(this.ng1ComponentsToBeUpgraded, ng1Injector) .then(() => { // At this point we have ng1 injector and we have lifted ng1 components into ng2, we // now can bootstrap ng2. const /** @type {?} */ DynamicNgUpgradeModule = NgModule({ providers: [ { provide: $INJECTOR, useFactory: () => ng1Injector }, { provide: $COMPILE, useFactory: () => ng1Injector.get($COMPILE) }, this.upgradedProviders ], imports: [this.ng2AppModule], entryComponents: this.downgradedComponents }).Class({ constructor: function DynamicNgUpgradeModule() { }, ngDoBootstrap: function () { } }); ((platformRef)) ._bootstrapModuleWithZone(DynamicNgUpgradeModule, this.compilerOptions, this.ngZone) .then((ref) => { this.moduleRef = ref; this.ngZone.run(() => { if (rootScopePrototype) { rootScopePrototype.$apply = original$applyFn; // restore original $apply while (delayApplyExps.length) { rootScope.$apply(delayApplyExps.shift()); } rootScopePrototype = null; } }); }) .then(() => this.ng2BootstrapDeferred.resolve(ng1Injector), onError) .then(() => { let /** @type {?} */ subscription = this.ngZone.onMicrotaskEmpty.subscribe({ next: () => rootScope.$digest() }); rootScope.$on('$destroy', () => { subscription.unsubscribe(); }); }); }) .catch((e) => this.ng2BootstrapDeferred.reject(e)); } ]); return ng1Module; } } /** * Use `UpgradeAdapterRef` to control a hybrid AngularJS / Angular application. * * \@stable */ class UpgradeAdapterRef { constructor() { this._readyFn = null; this.ng1RootScope = null; this.ng1Injector = null; this.ng2ModuleRef = null; this.ng2Injector = null; } /** * @param {?} ngModuleRef * @param {?} ng1Injector * @return {?} */ _bootstrapDone(ngModuleRef, ng1Injector) { this.ng2ModuleRef = ngModuleRef; this.ng2Injector = ngModuleRef.injector; this.ng1Injector = ng1Injector; this.ng1RootScope = ng1Injector.get($ROOT_SCOPE); this._readyFn && this._readyFn(this); } /** * Register a callback function which is notified upon successful hybrid AngularJS / Angular * application has been bootstrapped. * * The `ready` callback function is invoked inside the Angular zone, therefore it does not * require a call to `$apply()`. * @param {?} fn * @return {?} */ ready(fn) { this._readyFn = fn; } /** * Dispose of running hybrid AngularJS / Angular application. * @return {?} */ dispose() { this.ng1Injector.get($ROOT_SCOPE).$destroy(); this.ng2ModuleRef.destroy(); } } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @module * @description * Entry point for all public APIs of the upgrade/dynamic package, allowing * Angular 1 and Angular 2+ to run side by side in the same application. */ // This file only re-exports content of the `src` folder. Keep it that way. /** * Generated bundle index. Do not edit. */ export { VERSION, UpgradeAdapter, UpgradeAdapterRef }; //# sourceMappingURL=upgrade.js.map
Java
package gb import ( "errors" "fmt" "io" "path/filepath" "reflect" "testing" ) func TestExecuteBuildAction(t *testing.T) { tests := []struct { pkg string err error }{{ pkg: "a", err: nil, }, { pkg: "b", // actually command err: nil, }, { pkg: "c", err: nil, }, { pkg: "d.v1", err: nil, }, { pkg: "x", err: errors.New("import cycle detected: x -> y -> x"), }, { pkg: "h", // imports "blank", which is blank, see issue #131 err: fmt.Errorf("no buildable Go source files in %s", filepath.Join(getwd(t), "testdata", "src", "blank")), }} for _, tt := range tests { ctx := testContext(t) pkg, err := ctx.ResolvePackage(tt.pkg) if !sameErr(err, tt.err) { t.Errorf("ctx.ResolvePackage(%v): want %v, got %v", tt.pkg, tt.err, err) continue } if err != nil { continue } action, err := BuildPackages(pkg) if err != nil { t.Errorf("BuildAction(%v): ", tt.pkg, err) continue } if err := Execute(action); !sameErr(err, tt.err) { t.Errorf("Execute(%v): want: %v, got %v", action.Name, tt.err, err) } ctx.Destroy() } } var niltask = TaskFn(func() error { return nil }) var executorTests = []struct { action *Action // root action err error // expected error }{{ action: &Action{ Name: "no error", Task: niltask, }, }, { action: &Action{ Name: "root error", Task: TaskFn(func() error { return io.EOF }), }, err: io.EOF, }, { action: &Action{ Name: "child, child, error", Task: TaskFn(func() error { return fmt.Errorf("I should not have been called") }), Deps: []*Action{&Action{ Name: "child, error", Task: niltask, Deps: []*Action{&Action{ Name: "error", Task: TaskFn(func() error { return io.EOF }), }}, }}, }, err: io.EOF, }, { action: &Action{ Name: "once only", Task: TaskFn(func() error { if c1 != 1 || c2 != 1 || c3 != 1 { return fmt.Errorf("unexpected count, c1: %v, c2: %v, c3: %v", c1, c2, c3) } return nil }), Deps: []*Action{createDag()}, }, }, { action: &Action{ Name: "failure count", Task: TaskFn(func() error { return fmt.Errorf("I should not have been called") }), Deps: []*Action{createFailDag()}, }, err: fmt.Errorf("task3 called 1 time"), }} func createDag() *Action { task1 := TaskFn(func() error { c1++; return nil }) task2 := TaskFn(func() error { c2++; return nil }) task3 := TaskFn(func() error { c3++; return nil }) action1 := Action{Name: "c1", Task: task1} action2 := Action{Name: "c2", Task: task2} action3 := Action{Name: "c3", Task: task3} action1.Deps = append(action1.Deps, &action2, &action3) action2.Deps = append(action2.Deps, &action3) return &action1 } func createFailDag() *Action { task1 := TaskFn(func() error { c1++; return nil }) task2 := TaskFn(func() error { c2++; return fmt.Errorf("task2 called %v time", c2) }) task3 := TaskFn(func() error { c3++; return fmt.Errorf("task3 called %v time", c3) }) action1 := Action{Name: "c1", Task: task1} action2 := Action{Name: "c2", Task: task2} action3 := Action{Name: "c3", Task: task3} action1.Deps = append(action1.Deps, &action2, &action3) action2.Deps = append(action2.Deps, &action3) return &action1 } var c1, c2, c3 int func executeReset() { c1 = 0 c2 = 0 c3 = 0 // reset executor test variables } func TestExecute(t *testing.T) { for _, tt := range executorTests { executeReset() got := Execute(tt.action) if !reflect.DeepEqual(got, tt.err) { t.Errorf("Execute: %v: want err: %v, got err %v", tt.action.Name, tt.err, got) } } } func testExecuteConcurrentN(t *testing.T, n int) { for _, tt := range executorTests { executeReset() got := ExecuteConcurrent(tt.action, n) if !reflect.DeepEqual(got, tt.err) { t.Errorf("ExecuteConcurrent(%v): %v: want err: %v, got err %v", n, tt.action.Name, tt.err, got) } } } func TestExecuteConcurrent1(t *testing.T) { testExecuteConcurrentN(t, 1) } func TestExecuteConcurrent2(t *testing.T) { testExecuteConcurrentN(t, 2) } func TestExecuteConcurrent4(t *testing.T) { testExecuteConcurrentN(t, 4) } func TestExecuteConcurrent7(t *testing.T) { testExecuteConcurrentN(t, 7) }
Java
<?php /** * @Created By ECMall PhpCacheServer * @Time:2015-01-23 06:18:10 */ if(filemtime(__FILE__) + 1800 < time())return false; return array ( 'id' => 5553, 'goods' => array ( 'goods_id' => '5553', 'store_id' => '132', 'type' => 'material', 'goods_name' => '百枣纲目夹心枣核桃100g', 'description' => '<p style="text-align: center;"><img src="http://wap.bqmart.cn/data/files/store_132/goods_42/201501191027226980.jpg" alt="6956459400622_01.jpg" /><img src="http://wap.bqmart.cn/data/files/store_132/goods_43/201501191027236092.jpg" alt="6956459400622_02.jpg" /><img src="http://wap.bqmart.cn/data/files/store_132/goods_43/201501191027234428.jpg" alt="6956459400622_03.jpg" /><img src="http://wap.bqmart.cn/data/files/store_132/goods_43/201501191027239736.jpg" alt="6956459400622_04.jpg" /><img src="http://wap.bqmart.cn/data/files/store_132/goods_43/201501191027232880.jpg" alt="6956459400622_05.jpg" /><img src="http://wap.bqmart.cn/data/files/store_132/goods_47/201501191027276363.jpg" alt="6956459400622_06.jpg" /><img src="http://wap.bqmart.cn/data/files/store_132/goods_47/201501191027278226.jpg" alt="6956459400622_07.jpg" /></p>', 'cate_id' => '816', 'cate_name' => '地方特产 山东特产', 'brand' => '百枣纲目', 'spec_qty' => '0', 'spec_name_1' => '', 'spec_name_2' => '', 'if_show' => '1', 'if_seckill' => '0', 'closed' => '0', 'close_reason' => NULL, 'add_time' => '1421605662', 'last_update' => '1421605662', 'default_spec' => '5557', 'default_image' => 'data/files/store_132/goods_20/small_201501191027007132.jpg', 'recommended' => '0', 'cate_id_1' => '815', 'cate_id_2' => '816', 'cate_id_3' => '0', 'cate_id_4' => '0', 'price' => '19.80', 'tags' => array ( 0 => '百枣纲目 夹心枣核桃', ), 'cuxiao_ids' => NULL, 'from_goods_id' => '0', 'quanzhong' => NULL, 'state' => '1', '_specs' => array ( 0 => array ( 'spec_id' => '5557', 'goods_id' => '5553', 'spec_1' => '', 'spec_2' => '', 'color_rgb' => '', 'price' => '19.80', 'stock' => '1000', 'sku' => '6956459400622', ), ), '_images' => array ( 0 => array ( 'image_id' => '5204', 'goods_id' => '5553', 'image_url' => 'data/files/store_132/goods_20/201501191027007132.jpg', 'thumbnail' => 'data/files/store_132/goods_20/small_201501191027007132.jpg', 'sort_order' => '1', 'file_id' => '21028', ), 1 => array ( 'image_id' => '5205', 'goods_id' => '5553', 'image_url' => 'data/files/store_132/goods_24/201501191027045479.jpg', 'thumbnail' => 'data/files/store_132/goods_24/small_201501191027045479.jpg', 'sort_order' => '255', 'file_id' => '21027', ), 2 => array ( 'image_id' => '5206', 'goods_id' => '5553', 'image_url' => 'data/files/store_132/goods_33/201501191027133651.jpg', 'thumbnail' => 'data/files/store_132/goods_33/small_201501191027133651.jpg', 'sort_order' => '255', 'file_id' => '21030', ), ), '_scates' => array ( ), 'views' => '1', 'collects' => '0', 'carts' => '0', 'orders' => '0', 'sales' => '0', 'comments' => '0', 'related_info' => array ( ), ), 'store_data' => array ( 'store_id' => '132', 'store_name' => '大地锐城店', 'owner_name' => '倍全', 'owner_card' => '370832200104057894', 'region_id' => '2213', 'region_name' => '中国 山东 济南 历下区', 'address' => '', 'zipcode' => '', 'tel' => '15666660007', 'sgrade' => '系统默认', 'apply_remark' => '', 'credit_value' => '0', 'praise_rate' => '0.00', 'domain' => '', 'state' => '1', 'close_reason' => '', 'add_time' => '1418929047', 'end_time' => '0', 'certification' => 'autonym,material', 'sort_order' => '65535', 'recommended' => '0', 'theme' => '', 'store_banner' => NULL, 'store_logo' => 'data/files/store_132/other/store_logo.jpg', 'description' => '', 'image_1' => '', 'image_2' => '', 'image_3' => '', 'im_qq' => '', 'im_ww' => '', 'im_msn' => '', 'hot_search' => '', 'business_scope' => '', 'online_service' => array ( ), 'hotline' => '', 'pic_slides' => '', 'pic_slides_wap' => '{"1":{"url":"data/files/store_132/pic_slides_wap/pic_slides_wap_1.jpg","link":"http://wap.bqmart.cn/index.php?app=zhuanti&id=7"},"2":{"url":"data/files/store_132/pic_slides_wap/pic_slides_wap_2.jpg","link":"http://wap.bqmart.cn/index.php?keyword= %E6%B4%97%E8%A1%A3%E5%B9%B2%E6%B4%97&app=store&act=search&id=132"},"3":{"url":"data/files/store_132/pic_slides_wap/pic_slides_wap_3.jpg","link":"http://wap.bqmart.cn/index.php?app=search&cate_id=691&id=132"}}', 'enable_groupbuy' => '0', 'enable_radar' => '1', 'waptheme' => '', 'is_open_pay' => '0', 'area_peisong' => NULL, 'power_coupon' => '0', 's_long' => '117.096102', 's_lat' => '36.68974', 'user_name' => 'bq516', 'email' => '111111111@qq.com', 'certifications' => array ( 0 => 'autonym', 1 => 'material', ), 'credit_image' => 'http://wap.bqmart.cn/themes/store/default/styles/default/images/heart_1.gif', 'store_owner' => array ( 'user_id' => '132', 'user_name' => 'bq516', 'email' => '111111111@qq.com', 'password' => '9cbf8a4dcb8e30682b927f352d6559a0', 'real_name' => '新生活家园', 'gender' => '0', 'birthday' => '', 'phone_tel' => NULL, 'phone_mob' => NULL, 'im_qq' => '', 'im_msn' => '', 'im_skype' => NULL, 'im_yahoo' => NULL, 'im_aliww' => NULL, 'reg_time' => '1418928900', 'last_login' => '1421874055', 'last_ip' => '123.233.201.48', 'logins' => '136', 'ugrade' => '0', 'portrait' => NULL, 'outer_id' => '0', 'activation' => NULL, 'feed_config' => NULL, 'uin' => '0', 'parentid' => '0', 'user_level' => '0', 'from_weixin' => '0', 'wx_openid' => NULL, 'wx_nickname' => NULL, 'wx_city' => NULL, 'wx_country' => NULL, 'wx_province' => NULL, 'wx_language' => NULL, 'wx_headimgurl' => NULL, 'wx_subscribe_time' => '0', 'wx_id' => '0', 'from_public' => '0', 'm_storeid' => '0', ), 'store_navs' => array ( ), 'kmenus' => false, 'kmenusinfo' => array ( ), 'radio_new' => 1, 'radio_recommend' => 1, 'radio_hot' => 1, 'goods_count' => '1106', 'store_gcates' => array ( ), 'functions' => array ( 'editor_multimedia' => 'editor_multimedia', 'coupon' => 'coupon', 'groupbuy' => 'groupbuy', 'enable_radar' => 'enable_radar', 'seckill' => 'seckill', ), 'hot_saleslist' => array ( 3043 => array ( 'goods_id' => '3043', 'goods_name' => '黑牛高钙豆奶粉480g', 'default_image' => 'data/files/store_132/goods_19/small_201412171103393194.gif', 'price' => '15.80', 'sales' => '7', ), 3459 => array ( 'goods_id' => '3459', 'goods_name' => '七度空间纯棉表层透气夜用超薄卫生巾10片状', 'default_image' => 'data/files/store_132/goods_110/small_201412180915101043.jpg', 'price' => '9.60', 'sales' => '7', ), 3650 => array ( 'goods_id' => '3650', 'goods_name' => '美汁源果粒橙450ml果汁', 'default_image' => 'data/files/store_132/goods_5/small_201412181056459752.jpg', 'price' => '3.00', 'sales' => '5', ), 3457 => array ( 'goods_id' => '3457', 'goods_name' => '心相印红卷纸单包装120g卫生纸', 'default_image' => 'data/files/store_132/goods_71/small_201412180914313610.jpg', 'price' => '2.50', 'sales' => '4', ), 3666 => array ( 'goods_id' => '3666', 'goods_name' => '乐百氏脉动水蜜桃600ml', 'default_image' => 'data/files/store_132/goods_101/small_201412181105019926.jpg', 'price' => '4.00', 'sales' => '3', ), 3660 => array ( 'goods_id' => '3660', 'goods_name' => '雪碧清爽柠檬味汽水330ml', 'default_image' => 'data/files/store_132/goods_150/small_201412181102308979.jpg', 'price' => '2.00', 'sales' => '1', ), 3230 => array ( 'goods_id' => '3230', 'goods_name' => '圣牧全程有机奶1X12X250ml', 'default_image' => 'data/files/store_132/goods_69/small_201412171617496624.jpg', 'price' => '98.00', 'sales' => '1', ), 3708 => array ( 'goods_id' => '3708', 'goods_name' => '怡泉+c500ml功能饮料', 'default_image' => 'data/files/store_132/goods_115/small_201412181125154319.jpg', 'price' => '4.00', 'sales' => '1', ), 4012 => array ( 'goods_id' => '4012', 'goods_name' => '【39元区】羊毛外套 羊绒大衣', 'default_image' => 'data/files/store_132/goods_186/small_201501041619467368.jpg', 'price' => '39.00', 'sales' => '1', ), 3464 => array ( 'goods_id' => '3464', 'goods_name' => '大白兔奶糖114g牛奶糖', 'default_image' => 'data/files/store_132/goods_79/small_201412180917594452.jpg', 'price' => '7.50', 'sales' => '0', ), ), 'collect_goodslist' => array ( 5494 => array ( 'goods_id' => '5494', 'goods_name' => '青岛啤酒奥古特500ml', 'default_image' => 'data/files/store_42/goods_0/small_201412181433205122.jpg', 'price' => '9.80', 'collects' => '1', ), 3570 => array ( 'goods_id' => '3570', 'goods_name' => '康师傅蜂蜜绿茶490ml', 'default_image' => 'data/files/store_132/goods_10/small_201412181016503047.jpg', 'price' => '3.00', 'collects' => '1', ), 3777 => array ( 'goods_id' => '3777', 'goods_name' => '海天苹果醋450ml', 'default_image' => 'data/files/store_132/goods_47/small_201412181157271271.jpg', 'price' => '6.50', 'collects' => '1', ), 3871 => array ( 'goods_id' => '3871', 'goods_name' => '品食客手抓饼葱香味400g速冻食品', 'default_image' => 'data/files/store_132/goods_103/small_201412181421434694.jpg', 'price' => '11.80', 'collects' => '1', ), 3457 => array ( 'goods_id' => '3457', 'goods_name' => '心相印红卷纸单包装120g卫生纸', 'default_image' => 'data/files/store_132/goods_71/small_201412180914313610.jpg', 'price' => '2.50', 'collects' => '1', ), 3043 => array ( 'goods_id' => '3043', 'goods_name' => '黑牛高钙豆奶粉480g', 'default_image' => 'data/files/store_132/goods_19/small_201412171103393194.gif', 'price' => '15.80', 'collects' => '1', ), 3800 => array ( 'goods_id' => '3800', 'goods_name' => '蒙牛冠益乳草莓味风味发酵乳450g', 'default_image' => 'data/files/store_132/goods_12/small_201412181310121305.jpg', 'price' => '13.50', 'collects' => '1', ), 3459 => array ( 'goods_id' => '3459', 'goods_name' => '七度空间纯棉表层透气夜用超薄卫生巾10片状', 'default_image' => 'data/files/store_132/goods_110/small_201412180915101043.jpg', 'price' => '9.60', 'collects' => '1', ), 3130 => array ( 'goods_id' => '3130', 'goods_name' => '迪士尼巧克力味心宠杯25g', 'default_image' => 'data/files/store_132/goods_110/small_201412171515106856.jpg', 'price' => '2.50', 'collects' => '1', ), 3464 => array ( 'goods_id' => '3464', 'goods_name' => '大白兔奶糖114g牛奶糖', 'default_image' => 'data/files/store_132/goods_79/small_201412180917594452.jpg', 'price' => '7.50', 'collects' => '0', ), ), 'left_rec_goods' => array ( 3043 => array ( 'goods_name' => '黑牛高钙豆奶粉480g', 'default_image' => 'data/files/store_132/goods_19/small_201412171103393194.gif', 'price' => '15.80', 'sales' => '7', 'goods_id' => '3043', ), 3457 => array ( 'goods_name' => '心相印红卷纸单包装120g卫生纸', 'default_image' => 'data/files/store_132/goods_71/small_201412180914313610.jpg', 'price' => '2.50', 'sales' => '4', 'goods_id' => '3457', ), 3459 => array ( 'goods_name' => '七度空间纯棉表层透气夜用超薄卫生巾10片状', 'default_image' => 'data/files/store_132/goods_110/small_201412180915101043.jpg', 'price' => '9.60', 'sales' => '7', 'goods_id' => '3459', ), 3570 => array ( 'goods_name' => '康师傅蜂蜜绿茶490ml', 'default_image' => 'data/files/store_132/goods_10/small_201412181016503047.jpg', 'price' => '3.00', 'sales' => '0', 'goods_id' => '3570', ), 5494 => array ( 'goods_name' => '青岛啤酒奥古特500ml', 'default_image' => 'data/files/store_42/goods_0/small_201412181433205122.jpg', 'price' => '9.80', 'sales' => '0', 'goods_id' => '5494', ), ), ), 'cur_local' => array ( 0 => array ( 'text' => '所有分类', 'url' => 'index.php?app=category', ), 1 => array ( 'text' => '地方特产', 'url' => 'index.php?app=search&amp;cate_id=815', ), 2 => array ( 'text' => '山东特产', 'url' => 'index.php?app=search&amp;cate_id=816', ), 3 => array ( 'text' => '商品详情', ), ), 'share' => array ( 4 => array ( 'title' => '开心网', 'link' => 'http://www.kaixin001.com/repaste/share.php?rtitle=%E7%99%BE%E6%9E%A3%E7%BA%B2%E7%9B%AE%E5%A4%B9%E5%BF%83%E6%9E%A3%E6%A0%B8%E6%A1%83100g-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E&rurl=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D5553', 'type' => 'share', 'sort_order' => 255, 'logo' => 'data/system/kaixin001.gif', ), 3 => array ( 'title' => 'QQ书签', 'link' => 'http://shuqian.qq.com/post?from=3&title=%E7%99%BE%E6%9E%A3%E7%BA%B2%E7%9B%AE%E5%A4%B9%E5%BF%83%E6%9E%A3%E6%A0%B8%E6%A1%83100g-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E++++++&uri=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D5553&jumpback=2&noui=1', 'type' => 'collect', 'sort_order' => 255, 'logo' => 'data/system/qqshuqian.gif', ), 2 => array ( 'title' => '人人网', 'link' => 'http://share.renren.com/share/buttonshare.do?link=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D5553&title=%E7%99%BE%E6%9E%A3%E7%BA%B2%E7%9B%AE%E5%A4%B9%E5%BF%83%E6%9E%A3%E6%A0%B8%E6%A1%83100g-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E', 'type' => 'share', 'sort_order' => 255, 'logo' => 'data/system/renren.gif', ), 1 => array ( 'title' => '百度收藏', 'link' => 'http://cang.baidu.com/do/add?it=%E7%99%BE%E6%9E%A3%E7%BA%B2%E7%9B%AE%E5%A4%B9%E5%BF%83%E6%9E%A3%E6%A0%B8%E6%A1%83100g-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E++++++&iu=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D5553&fr=ien#nw=1', 'type' => 'collect', 'sort_order' => 255, 'logo' => 'data/system/baidushoucang.gif', ), ), ); ?>
Java
# Fetching User Objects Fetching user objects is a simple way to get at specific objects that you know the IDs of or to access all user objects. This does not access objects owned by the application. If you know more detail about the object you are looking for, but do not know the object ids, you might find it easier to use the [Object Search](#/javascript#searching-for-user-objects) feature instead. If you want to access all objects stored in your logged in user, use `ws.get()`: ```js // Assuming the ws object is a WebService instance with a logged in user // Lets say you had an object with an id "comedians" an the value of: // { favorite: "Lewis Black", second: "Louis CK" } // and another object with a value of "cheesecake" var response = ws.get(); response.on('success', function(data, response) { // Data returned on success will be keyed by id, unsorted. console.log(data); // { // comedians: { // favorite: "Lewis Black", // second: "Louis CK" // }, // another_object: "cheesecake", // ... and every other object in your application... // } }); ``` {{note "Fetch operations are limited to 50 results by default. To retreive more objects you need to specify a limit, or page through results. See Sorting and Paging for more information."}} To fetch application objects while using a logged in WebService instance: ```js ws.get({applevel: true}).on(function(data, response) { console.log(data); // Contents of data contains all application objects. }); ``` To fetch a single object, simply give the key of the object: ```js ws.get('comedians').on('success', function(data, response) { // Only the comedians object will be returned, but still keyed by the object id. console.log(data); // { // comedians: { // favorite: "Lewis Black", // second: "Louis CK" // }, // another_object: "cheesecake", // ... and every other object in your application... // } }); ``` Or you can give a list of ids to fetch multiple objects: ```js ws.get(['another_object', 'comedians']).on('success', function(data, response) { console.log(data); // { // comedians: { // favorite: "Lewis Black", // second: "Louis CK" // }, // another_object: "cheesecake" // } }); ``` {{caution "Even if you specify a list of more than 50 items, the results will still be limited to the 50 items unless you specify a limit."}} {{jsEvents 'success.ok' 'error.unauthorized.notfound' 'complete'}}
Java
<html dir="rtl"> <head> <title>Testing textpath</title> <style type="text/css"> @import "../../../../../dojo/resources/dojo.css"; @import "../../../../../dijit/tests/css/dijitTests.css"; </style> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="../../../../../dojo/dojo.js" djConfig="isDebug: true, gfxRenderer:'canvas'"></script> <script type="text/javascript"> dojo.require("dojox.gfx"); dojo.require("dojox.gfx._gfxBidiSupport"); dojo.require("doh.runner"); var CPD = 30, tp1, tp2, tp3, tp4, tp5, tp6, t1, t2, t3, t4, t5, t6; var g1 = null, g2 = null, g3, g4; var surfaceLTR = null, surfaceRTL = null, surfaceAUTO = null; var placeAnchor = function(surface, x, y){ surface.createLine({x1: x - 2, y1: y, x2: x + 2, y2: y}); surface.createLine({x1: x, y1: y - 2, x2: x, y2: y + 2}); }; var makeText = function(surface, text, font, fill, stroke){ var t = surface.createText(text); if(font) t.setFont(font); if(fill) t.setFill(fill); if(stroke) t.setStroke(stroke); placeAnchor(surface, text.x, text.y); return t; }; makeShapes = function(){ var m = dojox.gfx.matrix; surfaceLTR = dojox.gfx.createSurface("testLTR", 500, 170, "ltr"); console.debug("surfaceLTR created"); var p = surfaceLTR.createPath({}) .moveTo(0, 15) .setAbsoluteMode(false) .curveTo(CPD, 0, 0, 0, 50, 0) ; console.debug("p created"); tp1 = surfaceLTR.createTextPath({ text: "\u05d4\u05ea\u05d7\u05dc\u05d4 end. " , align: "start" }) .moveTo(0, 15) .setAbsoluteMode(false) .curveTo(CPD, 0, 0, 0, 100, 0) .setFont({family: "times", size: "12pt"}) .setFill("blue") ; console.debug("tp1 created"); tp2 = surfaceLTR.createTextPath({ text: "Beginning \u05e1\u05d5\u05e3." , align: "start" }) .moveTo(0, 50) .setAbsoluteMode(false) .curveTo(CPD, 0, 0, 0, 100, 0) .setFont({family: "times", size: "12pt"}) .setFill("blue") ; console.debug("tp2 created"); g1 = surfaceLTR.createGroup(); g1.setTextDir("rtl"); // surfaceLTR.setTextDir("ltr"); t1 = makeText(g1, {id: "t1",x: 0, y: 100, text: "1.) \u05d4\u05ea\u05d7\u05dc\u05d4 end!"}, {family: "Times", size: "18pt"}, "black", "blue") .setTransform(m.rotategAt(0, 250, 150)); t2 = makeText(surfaceLTR, {x: 0, y: 140, text: "1.) Beginning \u05e1\u05d5\u05e3!"}, {family: "Times", size: "18pt"}, "black", "blue") .setTransform(m.rotategAt(0, 250, 100)); surfaceRTL = dojox.gfx.createSurface("testRTL", 500, 170); console.debug("surfaceRTL created"); var p2 = surfaceRTL.createPath({}) .moveTo(0, 15) .setAbsoluteMode(false) .curveTo(CPD, 0, 0, 0, 100, 0) ; console.debug("p2 created"); tp3 = surfaceRTL.createTextPath({ text: "\u05d4\u05ea\u05d7\u05dc\u05d4 end. " , align: "start" //, rotated: true }) .moveTo(0, 15) .setAbsoluteMode(false) .curveTo(CPD, 0, 100 - CPD, 0, 100, 0) .setFont({family: "times", size: "12pt"}) .setFill("red") ; g2 = surfaceRTL.createGroup(); g2.add(tp3); g2.setTextDir("ltr"); g3 = g2.createGroup("rtl"); g4 = surfaceRTL.createGroup("auto"); tp4 = surfaceRTL.createTextPath({ text: "Beginning \u05e1\u05d5\u05e3." , align: "start" //, rotated: true }) //.setShape(p.shape) .moveTo(0, 50) .setAbsoluteMode(false) .curveTo(CPD, 0, 100 - CPD, 0, 100, 0) .setFont({family: "times", size: "12pt"}) .setFill("red") ; console.debug("tp4 created"); t3 = makeText(g3, {id: "t1",x: 0, y: 100, text: "1.) \u05d4\u05ea\u05d7\u05dc\u05d4 end!"}, {family: "Times", size: "18pt"}, "black", "red") .setTransform(m.rotategAt(0, 250, 150)); t4 = makeText(surfaceRTL, {x: 0, y: 140, text: "1.) Beginning \u05e1\u05d5\u05e3!"}, {family: "Times", size: "18pt"}, "black", "red") .setTransform(m.rotategAt(0, 250, 100)); surfaceAUTO = dojox.gfx.createSurface("testAUTO", 500, 170,"auto"); console.debug("surfaceAUTO created"); var p3 = surfaceAUTO.createPath({}) .moveTo(0, 15) .setAbsoluteMode(false) .curveTo(CPD, 0, 0, 0, 100, 0) ; console.debug("p3 created"); tp5 = surfaceAUTO.createTextPath({ text: "\u05d4\u05ea\u05d7\u05dc\u05d4 end. " , align: "start" //, rotated: true }) //.setShape(p.shape) .moveTo(0, 15) .setAbsoluteMode(false) .curveTo(CPD, 0, 100 - CPD, 0, 100, 0) .setFont({family: "times", size: "12pt"}) .setFill("red") ; console.debug("tp5 created"); tp6 = surfaceAUTO.createTextPath({ text: "Beginning \u05e1\u05d5\u05e3." , align: "start" //, rotated: true }) //.setShape(p.shape) .moveTo(0, 50) .setAbsoluteMode(false) .curveTo(CPD, 0, 100 - CPD, 0, 100, 0) .setFont({family: "times", size: "12pt"}) .setFill("blue") ; console.debug("tp6 created"); t5 = makeText(surfaceAUTO, {id: "t1",x: 0, y: 100, text: "1.) \u05d4\u05ea\u05d7\u05dc\u05d4 end!"}, {family: "Times", size: "18pt"}, "black", "red") .setTransform(m.rotategAt(0, 250, 150)); t6 = makeText(surfaceAUTO, {x: 0, y: 140, text: "1.) Beginning \u05e1\u05d5\u05e3!"}, {family: "Times", size: "18pt"}, "black", "blue") .setTransform(m.rotategAt(0, 250, 100)); }; dojo.addOnLoad(function(){ makeShapes(); doh.register("Test inheritance", [ function surfaces_TextDir(){ doh.is("ltr", surfaceLTR.getTextDir(), "surfaceLTR.getTextDir"); doh.is("rtl", surfaceRTL.getTextDir(), "surfaceRTL.getTextDir"); doh.is("auto", surfaceAUTO.getTextDir(), "surfaceAUTO.getTextDir"); }, function groups_TextDir(){ doh.is("rtl", g1.getTextDir(), "g1.getTextDir"); doh.is("ltr", g2.getTextDir(), "g2.getTextDir"); doh.is("rtl", g3.getTextDir(), "g3.getTextDir"); doh.is("auto", g4.getTextDir(), "g4.getTextDir"); }, function gfxText_TextDir(){ doh.is("rtl", t1.textDir, "t1.getTextDir"); doh.is("ltr", t2.textDir, "t2.getTextDir"); doh.is("rtl", t3.textDir, "t3.getTextDir"); doh.is("rtl", t4.textDir, "t4.getTextDir"); doh.is("auto", t5.textDir, "t5.getTextDir"); doh.is("auto", t6.textDir, "t6h.getTextDir"); }, function gfxTextPath_TextDir(){ doh.is("ltr", tp1.textDir, "tp1.getTextDir"); doh.is("ltr", tp2.textDir, "tp2.getTextDir"); doh.is("ltr", tp3.textDir, "tp3.getTextDir"); doh.is("rtl", tp4.textDir, "tp4.getTextDir"); doh.is("auto", tp5.textDir, "tp5.getTextDir"); doh.is("auto", tp6.textDir, "tp6.getTextDir"); }, function changeSurfaceRTLextDir(){ surfaceRTL.setTextDir("ltr"); doh.is("ltr", surfaceRTL.getTextDir(), "surfaceRTL.getTextDir"); doh.is("ltr", g2.getTextDir(), "g2.getTextDir"); doh.is("ltr", g3.getTextDir(), "g3.getTextDir"); doh.is("ltr", g4.getTextDir(), "g4.getTextDir"); doh.is("ltr", t3.textDir, "t3.getTextDir"); doh.is("ltr", t4.textDir, "t4.getTextDir"); doh.is("ltr", tp3.textDir, "tp3.getTextDir"); doh.is("ltr", tp4.textDir, "tp4.getTextDir"); }, function changeGroupTextDir(){ g3.add(tp5); g3.add(t2); g2.setTextDir("rtl"); doh.is("rtl", g2.getTextDir(), "g2.getTextDir"); // son of g2 doh.is("rtl", g3.getTextDir(), "g3.getTextDir"); doh.is("rtl", t2.textDir, "t2.getTextDir"); doh.is("rtl", t3.textDir, "t3.getTextDir"); doh.is("rtl", tp5.textDir, "tp3.getTextDir"); } ]); doh.run(); }); </script> </head> <body> <h1>dojox.gfx Text on a Path test</h1> <h2>LTR TextPath and Text first two are TextPath and two others are Text</h2> <div id="testLTR" style="width: 500px;"></div> <h2>RTL Text Path and Text first two are TextPath and two others are Text</h2> <div id="testRTL" style="width: 500px;"></div> <h2>AUTO Text Path and Text first two are TextPath and two others are Text</h2> <div id="testAUTO" style="width: 500px;"></div> <p>That's all Folks!</p> </body> </html>
Java
/** * The MIT License * * Copyright (c) 2019, Mahmoud Ben Hassine (mahmoud.benhassine@icloud.com) * * 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.jeasy.random; import static org.jeasy.random.FieldPredicates.*; import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.jeasy.random.api.ContextAwareRandomizer; import org.jeasy.random.api.RandomizerContext; import org.jeasy.random.beans.*; import org.jeasy.random.beans.exclusion.A; import org.jeasy.random.beans.exclusion.B; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import org.jeasy.random.beans.exclusion.C; @ExtendWith(MockitoExtension.class) class FieldExclusionTest { private EasyRandom easyRandom; @BeforeEach void setUp() { easyRandom = new EasyRandom(); } @Test void excludedFieldsShouldNotBePopulated() { // given EasyRandomParameters parameters = new EasyRandomParameters() .excludeField(named("name")); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); //then assertThat(person).isNotNull(); assertThat(person.getName()).isNull(); } @Test void excludedFieldsUsingSkipRandomizerShouldNotBePopulated() { // given EasyRandomParameters parameters = new EasyRandomParameters() .excludeField(named("name").and(ofType(String.class)).and(inClass(Human.class))); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); // then assertThat(person).isNotNull(); assertThat(person.getName()).isNull(); } @Test void excludedFieldsUsingFieldDefinitionShouldNotBePopulated() { // given EasyRandomParameters parameters = new EasyRandomParameters().excludeField(named("name")); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); // then assertThat(person).isNotNull(); assertThat(person.getAddress()).isNotNull(); assertThat(person.getAddress().getStreet()).isNotNull(); // person.name and street.name should be null assertThat(person.getName()).isNull(); assertThat(person.getAddress().getStreet().getName()).isNull(); } @Test void excludedDottedFieldsShouldNotBePopulated() { // given EasyRandomParameters parameters = new EasyRandomParameters() .excludeField(named("name").and(inClass(Street.class))); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); // then assertThat(person).isNotNull(); assertThat(person.getAddress()).isNotNull(); assertThat(person.getAddress().getStreet()).isNotNull(); assertThat(person.getAddress().getStreet().getName()).isNull(); } @Test void fieldsExcludedWithAnnotationShouldNotBePopulated() { Person person = easyRandom.nextObject(Person.class); assertThat(person).isNotNull(); assertThat(person.getExcluded()).isNull(); } @Test @SuppressWarnings("deprecation") void fieldsExcludedWithAnnotationViaFieldDefinitionShouldNotBePopulated() { // given EasyRandomParameters parameters = new EasyRandomParameters().excludeField(isAnnotatedWith(Deprecated.class)); easyRandom = new EasyRandom(parameters); // when Website website = easyRandom.nextObject(Website.class); // then assertThat(website).isNotNull(); assertThat(website.getProvider()).isNull(); } @Test void fieldsExcludedFromTypeViaFieldDefinitionShouldNotBePopulated() { // given EasyRandomParameters parameters = new EasyRandomParameters().excludeField(inClass(Address.class)); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); // then assertThat(person).isNotNull(); assertThat(person.getAddress()).isNotNull(); // all fields declared in class Address must be null assertThat(person.getAddress().getCity()).isNull(); assertThat(person.getAddress().getStreet()).isNull(); assertThat(person.getAddress().getZipCode()).isNull(); assertThat(person.getAddress().getCountry()).isNull(); } @Test void testFirstLevelExclusion() { EasyRandomParameters parameters = new EasyRandomParameters() .excludeField(named("b2").and(inClass(C.class))); easyRandom = new EasyRandom(parameters); C c = easyRandom.nextObject(C.class); assertThat(c).isNotNull(); // B1 and its "children" must not be null assertThat(c.getB1()).isNotNull(); assertThat(c.getB1().getA1()).isNotNull(); assertThat(c.getB1().getA1().getS1()).isNotNull(); assertThat(c.getB1().getA1().getS2()).isNotNull(); assertThat(c.getB1().getA2()).isNotNull(); assertThat(c.getB1().getA2().getS1()).isNotNull(); assertThat(c.getB1().getA2().getS2()).isNotNull(); // B2 must be null assertThat(c.getB2()).isNull(); } @Test void testSecondLevelExclusion() { // goal: exclude only b2.a2 EasyRandomParameters parameters = new EasyRandomParameters() .randomize(ofType(A.class).and(inClass(B.class)), new ContextAwareRandomizer<A>() { private RandomizerContext context; @Override public void setRandomizerContext(RandomizerContext context) { this.context = context; } @Override public A getRandomValue() { if (context.getCurrentField().equals("b2.a2")) { return null; } return new EasyRandom().nextObject(A.class); } }); easyRandom = new EasyRandom(parameters); C c = easyRandom.nextObject(C.class); assertThat(c).isNotNull(); // B1 and its "children" must not be null assertThat(c.getB1()).isNotNull(); assertThat(c.getB1().getA1()).isNotNull(); assertThat(c.getB1().getA1().getS1()).isNotNull(); assertThat(c.getB1().getA1().getS2()).isNotNull(); assertThat(c.getB1().getA2()).isNotNull(); assertThat(c.getB1().getA2().getS1()).isNotNull(); assertThat(c.getB1().getA2().getS2()).isNotNull(); // Only B2.A2 must be null assertThat(c.getB2()).isNotNull(); assertThat(c.getB2().getA1()).isNotNull(); assertThat(c.getB2().getA1().getS1()).isNotNull(); assertThat(c.getB2().getA1().getS2()).isNotNull(); assertThat(c.getB2().getA2()).isNull(); } @Test void testThirdLevelExclusion() { // goal: exclude only b2.a2.s2 EasyRandomParameters parameters = new EasyRandomParameters() .randomize(FieldPredicates.named("s2").and(inClass(A.class)), new ContextAwareRandomizer<String>() { private RandomizerContext context; @Override public void setRandomizerContext(RandomizerContext context) { this.context = context; } @Override public String getRandomValue() { if (context.getCurrentField().equals("b2.a2.s2")) { return null; } return new EasyRandom().nextObject(String.class); } }); easyRandom = new EasyRandom(parameters); C c = easyRandom.nextObject(C.class); // B1 and its "children" must not be null assertThat(c.getB1()).isNotNull(); assertThat(c.getB1().getA1()).isNotNull(); assertThat(c.getB1().getA1().getS1()).isNotNull(); assertThat(c.getB1().getA1().getS2()).isNotNull(); assertThat(c.getB1().getA2()).isNotNull(); assertThat(c.getB1().getA2().getS1()).isNotNull(); assertThat(c.getB1().getA2().getS2()).isNotNull(); // Only B2.A2.S2 must be null assertThat(c.getB2()).isNotNull(); assertThat(c.getB2().getA1()).isNotNull(); assertThat(c.getB2().getA1().getS1()).isNotNull(); assertThat(c.getB2().getA1().getS2()).isNotNull(); assertThat(c.getB2().getA2().getS1()).isNotNull(); assertThat(c.getB2().getA2().getS2()).isNull(); } @Test void testFirstLevelCollectionExclusion() { EasyRandomParameters parameters = new EasyRandomParameters() .excludeField(FieldPredicates.named("b3").and(inClass(C.class))); easyRandom = new EasyRandom(parameters); C c = easyRandom.nextObject(C.class); assertThat(c).isNotNull(); // B1 and its "children" must not be null assertThat(c.getB1()).isNotNull(); assertThat(c.getB1().getA1()).isNotNull(); assertThat(c.getB1().getA1().getS1()).isNotNull(); assertThat(c.getB1().getA1().getS2()).isNotNull(); assertThat(c.getB1().getA2()).isNotNull(); assertThat(c.getB1().getA2().getS1()).isNotNull(); assertThat(c.getB1().getA2().getS2()).isNotNull(); // B1 and its "children" must not be null assertThat(c.getB2()).isNotNull(); assertThat(c.getB2().getA1()).isNotNull(); assertThat(c.getB2().getA1().getS1()).isNotNull(); assertThat(c.getB2().getA1().getS2()).isNotNull(); assertThat(c.getB2().getA2()).isNotNull(); assertThat(c.getB2().getA2().getS1()).isNotNull(); assertThat(c.getB2().getA2().getS2()).isNotNull(); // B3 must be null assertThat(c.getB3()).isNull(); } @Test void testSecondLevelCollectionExclusion() { // b3.a2 does not make sense, should be ignored EasyRandomParameters parameters = new EasyRandomParameters() .randomize(FieldPredicates.named("a2").and(inClass(B.class)), new ContextAwareRandomizer<A>() { private RandomizerContext context; @Override public void setRandomizerContext(RandomizerContext context) { this.context = context; } @Override public A getRandomValue() { if (context.getCurrentField().equals("b3.a2")) { return null; } return new EasyRandom().nextObject(A.class); } }); easyRandom = new EasyRandom(parameters); C c = easyRandom.nextObject(C.class); assertThat(c).isNotNull(); // B1 and its "children" must not be null assertThat(c.getB1()).isNotNull(); assertThat(c.getB1().getA1()).isNotNull(); assertThat(c.getB1().getA1().getS1()).isNotNull(); assertThat(c.getB1().getA1().getS2()).isNotNull(); assertThat(c.getB1().getA2()).isNotNull(); assertThat(c.getB1().getA2().getS1()).isNotNull(); assertThat(c.getB1().getA2().getS2()).isNotNull(); // B2 and its "children" must not be null assertThat(c.getB2()).isNotNull(); assertThat(c.getB2().getA1()).isNotNull(); assertThat(c.getB2().getA1().getS1()).isNotNull(); assertThat(c.getB2().getA1().getS2()).isNotNull(); assertThat(c.getB2().getA2()).isNotNull(); assertThat(c.getB2().getA2().getS1()).isNotNull(); assertThat(c.getB2().getA2().getS2()).isNotNull(); // B3 must not be null assertThat(c.getB3()).isNotNull(); } @Test void whenFieldIsExcluded_thenItsInlineInitializationShouldBeUsedAsIs() { // given EasyRandomParameters parameters = new EasyRandomParameters() .excludeField(named("myList").and(ofType(List.class)).and(inClass(InlineInitializationBean.class))); easyRandom = new EasyRandom(parameters); // when InlineInitializationBean bean = easyRandom.nextObject(InlineInitializationBean.class); // then assertThat(bean).isNotNull(); assertThat(bean.getMyList()).isEmpty(); } @Test void whenFieldIsExcluded_thenItsInlineInitializationShouldBeUsedAsIs_EvenIfBeanHasNoPublicConstructor() { // given EasyRandomParameters parameters = new EasyRandomParameters() .excludeField(named("myList").and(ofType(List.class)).and(inClass(InlineInitializationBeanPrivateConstructor.class))); easyRandom = new EasyRandom(parameters); // when InlineInitializationBeanPrivateConstructor bean = easyRandom.nextObject(InlineInitializationBeanPrivateConstructor.class); // then assertThat(bean.getMyList()).isEmpty(); } @Test void fieldsExcludedWithOneModifierShouldNotBePopulated() { // given EasyRandomParameters parameters = new EasyRandomParameters().excludeField(hasModifiers(Modifier.TRANSIENT)); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); // then assertThat(person).isNotNull(); assertThat(person.getEmail()).isNull(); } @Test void fieldsExcludedWithTwoModifiersShouldNotBePopulated() { // given EasyRandomParameters parameters = new EasyRandomParameters().excludeField(hasModifiers(Modifier.TRANSIENT | Modifier.PROTECTED)); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); // then assertThat(person).isNotNull(); assertThat(person.getEmail()).isNull(); } @Test void fieldsExcludedWithTwoModifiersShouldBePopulatedIfOneModifierIsNotFit() { // given EasyRandomParameters parameters = new EasyRandomParameters().excludeField(hasModifiers(Modifier.TRANSIENT | Modifier.PUBLIC)); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); // then assertThat(person).isNotNull(); assertThat(person.getEmail()).isNotNull(); } public static class InlineInitializationBean { private List<String> myList = new ArrayList<>(); public List<String> getMyList() { return myList; } public void setMyList(List<String> myList) { this.myList = myList; } } public static class InlineInitializationBeanPrivateConstructor { private List<String> myList = new ArrayList<>(); public List<String> getMyList() { return myList; } private InlineInitializationBeanPrivateConstructor() {} } }
Java
__all__ = [] import pkgutil import inspect # http://stackoverflow.com/questions/22209564/python-qualified-import-all-in-package for loader, name, is_pkg in pkgutil.walk_packages(__path__): module = loader.find_module(name).load_module(name) for name, value in inspect.getmembers(module): if name.startswith('__'): continue globals()[name] = value __all__.append(name)
Java
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2015-2018 Baldur Karlsson * Copyright (c) 2014 Crytek * * 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. ******************************************************************************/ #include "../gl_driver.h" #include "3rdparty/tinyfiledialogs/tinyfiledialogs.h" #include "common/common.h" #include "strings/string_utils.h" enum GLbufferbitfield { }; DECLARE_REFLECTION_ENUM(GLbufferbitfield); template <> std::string DoStringise(const GLbufferbitfield &el) { RDCCOMPILE_ASSERT(sizeof(GLbufferbitfield) == sizeof(GLbitfield) && sizeof(GLbufferbitfield) == sizeof(uint32_t), "Fake bitfield enum must be uint32_t sized"); BEGIN_BITFIELD_STRINGISE(GLbufferbitfield); { STRINGISE_BITFIELD_BIT(GL_DYNAMIC_STORAGE_BIT); STRINGISE_BITFIELD_BIT(GL_MAP_READ_BIT); STRINGISE_BITFIELD_BIT(GL_MAP_WRITE_BIT); STRINGISE_BITFIELD_BIT(GL_MAP_PERSISTENT_BIT); STRINGISE_BITFIELD_BIT(GL_MAP_COHERENT_BIT); STRINGISE_BITFIELD_BIT(GL_CLIENT_STORAGE_BIT); } END_BITFIELD_STRINGISE(); } #pragma region Buffers template <typename SerialiserType> bool WrappedOpenGL::Serialise_glGenBuffers(SerialiserType &ser, GLsizei n, GLuint *buffers) { SERIALISE_ELEMENT(n); SERIALISE_ELEMENT_LOCAL(buffer, GetResourceManager()->GetID(BufferRes(GetCtx(), *buffers))) .TypedAs("GLResource"); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { GLuint real = 0; m_Real.glGenBuffers(1, &real); GLResource res = BufferRes(GetCtx(), real); ResourceId live = m_ResourceManager->RegisterResource(res); GetResourceManager()->AddLiveResource(buffer, res); AddResource(buffer, ResourceType::Buffer, "Buffer"); m_Buffers[live].resource = res; m_Buffers[live].curType = eGL_NONE; m_Buffers[live].creationFlags = BufferCategory::NoFlags; } return true; } void WrappedOpenGL::glGenBuffers(GLsizei n, GLuint *buffers) { SERIALISE_TIME_CALL(m_Real.glGenBuffers(n, buffers)); for(GLsizei i = 0; i < n; i++) { GLResource res = BufferRes(GetCtx(), buffers[i]); ResourceId id = GetResourceManager()->RegisterResource(res); if(IsCaptureMode(m_State)) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glGenBuffers(ser, 1, buffers + i); chunk = scope.Get(); } GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id); RDCASSERT(record); record->AddChunk(chunk); } else { GetResourceManager()->AddLiveResource(id, res); m_Buffers[id].resource = res; m_Buffers[id].curType = eGL_NONE; m_Buffers[id].creationFlags = BufferCategory::NoFlags; } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glCreateBuffers(SerialiserType &ser, GLsizei n, GLuint *buffers) { SERIALISE_ELEMENT(n); SERIALISE_ELEMENT_LOCAL(buffer, GetResourceManager()->GetID(BufferRes(GetCtx(), *buffers))) .TypedAs("GLResource"); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { GLuint real = 0; m_Real.glCreateBuffers(1, &real); GLResource res = BufferRes(GetCtx(), real); ResourceId live = m_ResourceManager->RegisterResource(res); GetResourceManager()->AddLiveResource(buffer, res); AddResource(buffer, ResourceType::Buffer, "Buffer"); m_Buffers[live].resource = res; m_Buffers[live].curType = eGL_NONE; m_Buffers[live].creationFlags = BufferCategory::NoFlags; } return true; } void WrappedOpenGL::glCreateBuffers(GLsizei n, GLuint *buffers) { SERIALISE_TIME_CALL(m_Real.glCreateBuffers(n, buffers)); for(GLsizei i = 0; i < n; i++) { GLResource res = BufferRes(GetCtx(), buffers[i]); ResourceId id = GetResourceManager()->RegisterResource(res); if(IsCaptureMode(m_State)) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glCreateBuffers(ser, 1, buffers + i); chunk = scope.Get(); } GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id); RDCASSERT(record); record->AddChunk(chunk); } else { GetResourceManager()->AddLiveResource(id, res); m_Buffers[id].resource = res; m_Buffers[id].curType = eGL_NONE; m_Buffers[id].creationFlags = BufferCategory::NoFlags; } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glBindBuffer(SerialiserType &ser, GLenum target, GLuint bufferHandle) { SERIALISE_ELEMENT(target); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(target == eGL_NONE) { // ... } else if(buffer.name == 0) { m_Real.glBindBuffer(target, 0); } else { // if we're just loading, make sure not to trample state (e.g. element array buffer // binding in a VAO), since this is just a bind-to-create chunk. GLuint prevbuf = 0; if(IsLoading(m_State) && m_CurEventID == 0 && target != eGL_NONE) m_Real.glGetIntegerv(BufferBinding(target), (GLint *)&prevbuf); m_Real.glBindBuffer(target, buffer.name); m_Buffers[GetResourceManager()->GetID(buffer)].curType = target; m_Buffers[GetResourceManager()->GetID(buffer)].creationFlags |= MakeBufferCategory(target); if(IsLoading(m_State) && m_CurEventID == 0 && target != eGL_NONE) m_Real.glBindBuffer(target, prevbuf); } AddResourceInitChunk(buffer); } return true; } void WrappedOpenGL::glBindBuffer(GLenum target, GLuint buffer) { SERIALISE_TIME_CALL(m_Real.glBindBuffer(target, buffer)); ContextData &cd = GetCtxData(); size_t idx = BufferIdx(target); if(IsActiveCapturing(m_State)) { Chunk *chunk = NULL; if(buffer == 0) cd.m_BufferRecord[idx] = NULL; else cd.m_BufferRecord[idx] = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glBindBuffer(ser, target, buffer); if(cd.m_BufferRecord[idx]) cd.m_BufferRecord[idx]->datatype = target; chunk = scope.Get(); } if(buffer) { FrameRefType refType = eFrameRef_Read; // these targets write to the buffer if(target == eGL_ATOMIC_COUNTER_BUFFER || target == eGL_COPY_WRITE_BUFFER || target == eGL_PIXEL_PACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER || target == eGL_TRANSFORM_FEEDBACK_BUFFER) refType = eFrameRef_ReadBeforeWrite; GetResourceManager()->MarkResourceFrameReferenced(cd.m_BufferRecord[idx]->GetResourceID(), refType); } m_ContextRecord->AddChunk(chunk); } if(buffer == 0) { cd.m_BufferRecord[idx] = NULL; return; } if(IsCaptureMode(m_State)) { GLResourceRecord *r = cd.m_BufferRecord[idx] = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); if(!r) { RDCERR("Invalid/unrecognised buffer passed: glBindBuffer(%s, %u)", ToStr(target).c_str(), buffer); return; } // it's legal to re-type buffers, generate another BindBuffer chunk to rename if(r->datatype != target) { Chunk *chunk = NULL; r->LockChunks(); for(;;) { Chunk *end = r->GetLastChunk(); if(end->GetChunkType<GLChunk>() == GLChunk::glBindBuffer || end->GetChunkType<GLChunk>() == GLChunk::glBindBufferARB) { SAFE_DELETE(end); r->PopChunk(); continue; } break; } r->UnlockChunks(); r->datatype = target; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glBindBuffer(ser, target, buffer); chunk = scope.Get(); } r->AddChunk(chunk); } // element array buffer binding is vertex array record state, record there (if we've not just // stopped) if(IsBackgroundCapturing(m_State) && target == eGL_ELEMENT_ARRAY_BUFFER && RecordUpdateCheck(cd.m_VertexArrayRecord)) { GLuint vao = cd.m_VertexArrayRecord->Resource.name; // use glVertexArrayElementBuffer to ensure the vertex array is bound when we bind the // element buffer USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glVertexArrayElementBuffer); Serialise_glVertexArrayElementBuffer(ser, vao, buffer); cd.m_VertexArrayRecord->AddChunk(scope.Get()); } // store as transform feedback record state if(IsBackgroundCapturing(m_State) && target == eGL_TRANSFORM_FEEDBACK_BUFFER && RecordUpdateCheck(cd.m_FeedbackRecord)) { GLuint feedback = cd.m_FeedbackRecord->Resource.name; // use glTransformFeedbackBufferBase to ensure the feedback object is bound when we bind the // buffer USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glTransformFeedbackBufferBase); Serialise_glTransformFeedbackBufferBase(ser, feedback, 0, buffer); cd.m_FeedbackRecord->AddChunk(scope.Get()); } // immediately consider buffers bound to transform feedbacks/SSBOs/atomic counters as dirty if(target == eGL_TRANSFORM_FEEDBACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER || target == eGL_ATOMIC_COUNTER_BUFFER) { if(IsBackgroundCapturing(m_State)) GetResourceManager()->MarkDirtyResource(r->GetResourceID()); else m_MissingTracks.insert(r->GetResourceID()); } } else { m_Buffers[GetResourceManager()->GetID(BufferRes(GetCtx(), buffer))].curType = target; m_Buffers[GetResourceManager()->GetID(BufferRes(GetCtx(), buffer))].creationFlags |= MakeBufferCategory(target); } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glNamedBufferStorageEXT(SerialiserType &ser, GLuint bufferHandle, GLsizeiptr size, const void *data, GLbitfield flags) { SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT_LOCAL(bytesize, (uint64_t)size); SERIALISE_ELEMENT_ARRAY(data, bytesize); if(ser.IsWriting()) { uint64_t offs = ser.GetWriter()->GetOffset() - bytesize; RDCASSERT((offs % 64) == 0); GLResourceRecord *record = GetResourceManager()->GetResourceRecord(buffer); RDCASSERT(record); record->SetDataOffset(offs); } SERIALISE_ELEMENT_TYPED(GLbufferbitfield, flags); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // remove persistent flag - we will never persistently map so this is a nice // hint. It helps especially when self-hosting, as we don't want tons of // overhead added when we won't use it. flags &= ~GL_MAP_PERSISTENT_BIT; // can't have coherent without persistent, so remove as well flags &= ~GL_MAP_COHERENT_BIT; m_Real.glNamedBufferStorageEXT(buffer.name, (GLsizeiptr)bytesize, data, flags); m_Buffers[GetResourceManager()->GetID(buffer)].size = bytesize; AddResourceInitChunk(buffer); } return true; } void WrappedOpenGL::Common_glNamedBufferStorageEXT(ResourceId id, GLsizeiptr size, const void *data, GLbitfield flags) { if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(id); RDCASSERTMSG("Couldn't identify object used in function. Unbound or bad GLuint?", record); if(record == NULL) return; USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glNamedBufferStorageEXT(ser, record->Resource.name, size, data, flags); Chunk *chunk = scope.Get(); { record->AddChunk(chunk); record->SetDataPtr(chunk->GetData()); record->Length = (int32_t)size; record->DataInSerialiser = true; } // We immediately map the whole range with appropriate flags, to be copied into whenever we // need to propogate changes. Note: Coherent buffers are not mapped coherent, but this is // because the user code isn't writing into them anyway and we're inserting invisible sync // points - so there's no need for it to be coherently mapped (and there's no requirement // that a buffer declared as coherent must ALWAYS be mapped as coherent). if(flags & GL_MAP_PERSISTENT_BIT) { record->Map.persistentPtr = (byte *)m_Real.glMapNamedBufferRangeEXT( record->Resource.name, 0, size, GL_MAP_WRITE_BIT | GL_MAP_FLUSH_EXPLICIT_BIT | GL_MAP_PERSISTENT_BIT); RDCASSERT(record->Map.persistentPtr); // persistent maps always need both sets of shadow storage, so allocate up front. record->AllocShadowStorage(size); // ensure shadow pointers have up to date data for diffing memcpy(record->GetShadowPtr(0), data, size); memcpy(record->GetShadowPtr(1), data, size); } } else { m_Buffers[id].size = size; } } void WrappedOpenGL::glNamedBufferStorageEXT(GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags) { byte *dummy = NULL; if(IsCaptureMode(m_State) && data == NULL) { dummy = new byte[size]; memset(dummy, 0xdd, size); data = dummy; } SERIALISE_TIME_CALL(m_Real.glNamedBufferStorageEXT(buffer, size, data, flags)); Common_glNamedBufferStorageEXT(GetResourceManager()->GetID(BufferRes(GetCtx(), buffer)), size, data, flags); SAFE_DELETE_ARRAY(dummy); } void WrappedOpenGL::glNamedBufferStorage(GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags) { // only difference to EXT function is size parameter, so just upcast glNamedBufferStorageEXT(buffer, size, data, flags); } void WrappedOpenGL::glBufferStorage(GLenum target, GLsizeiptr size, const void *data, GLbitfield flags) { byte *dummy = NULL; if(IsCaptureMode(m_State) && data == NULL) { dummy = new byte[size]; memset(dummy, 0xdd, size); data = dummy; } SERIALISE_TIME_CALL(m_Real.glBufferStorage(target, size, data, flags)); if(IsCaptureMode(m_State)) Common_glNamedBufferStorageEXT(GetCtxData().m_BufferRecord[BufferIdx(target)]->GetResourceID(), size, data, flags); else RDCERR("Internal buffers should be allocated via dsa interfaces"); SAFE_DELETE_ARRAY(dummy); } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glNamedBufferDataEXT(SerialiserType &ser, GLuint bufferHandle, GLsizeiptr size, const void *data, GLenum usage) { SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT_LOCAL(bytesize, (uint64_t)size); SERIALISE_ELEMENT_ARRAY(data, bytesize); if(ser.IsWriting()) { uint64_t offs = ser.GetWriter()->GetOffset() - bytesize; RDCASSERT((offs % 64) == 0); GLResourceRecord *record = GetResourceManager()->GetResourceRecord(buffer); RDCASSERT(record); record->SetDataOffset(offs); } SERIALISE_ELEMENT(usage); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { m_Real.glNamedBufferDataEXT(buffer.name, (GLsizeiptr)bytesize, data, usage); m_Buffers[GetResourceManager()->GetID(buffer)].size = bytesize; AddResourceInitChunk(buffer); } return true; } void WrappedOpenGL::glNamedBufferDataEXT(GLuint buffer, GLsizeiptr size, const void *data, GLenum usage) { byte *dummy = NULL; if(IsCaptureMode(m_State) && data == NULL) { dummy = new byte[size]; memset(dummy, 0xdd, size); data = dummy; } SERIALISE_TIME_CALL(m_Real.glNamedBufferDataEXT(buffer, size, data, usage)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); RDCASSERTMSG("Couldn't identify object passed to function. Mismatched or bad GLuint?", record, buffer); if(record == NULL) { SAFE_DELETE_ARRAY(dummy); return; } // detect buffer orphaning and just update backing store if(IsBackgroundCapturing(m_State) && record->HasDataPtr() && size == (GLsizeiptr)record->Length && usage == record->usage) { if(data) memcpy(record->GetDataPtr(), data, (size_t)size); else memset(record->GetDataPtr(), 0xbe, (size_t)size); SAFE_DELETE_ARRAY(dummy); return; } // if we're recreating the buffer, clear the record and add new chunks. Normally // we would just mark this record as dirty and pick it up on the capture frame as initial // data, but we don't support (if it's even possible) querying out size etc. // we need to add only the chunks required - glGenBuffers, glBindBuffer to current target, // and this buffer storage. All other chunks have no effect if(IsBackgroundCapturing(m_State) && (record->HasDataPtr() || (record->Length > 0 && size != (GLsizeiptr)record->Length))) { // we need to maintain chunk ordering, so fetch the first two chunk IDs. // We should have at least two by this point - glGenBuffers and whatever gave the record // a size before. RDCASSERT(record->NumChunks() >= 2); // remove all but the first two chunks while(record->NumChunks() > 2) { Chunk *c = record->GetLastChunk(); SAFE_DELETE(c); record->PopChunk(); } int32_t id2 = record->GetLastChunkID(); { Chunk *c = record->GetLastChunk(); SAFE_DELETE(c); record->PopChunk(); } int32_t id1 = record->GetLastChunkID(); { Chunk *c = record->GetLastChunk(); SAFE_DELETE(c); record->PopChunk(); } RDCASSERT(!record->HasChunks()); // add glGenBuffers chunk { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glGenBuffers); Serialise_glGenBuffers(ser, 1, &buffer); record->AddChunk(scope.Get(), id1); } // add glBindBuffer chunk { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glBindBuffer); Serialise_glBindBuffer(ser, record->datatype, buffer); record->AddChunk(scope.Get(), id2); } // we're about to add the buffer data chunk } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glNamedBufferDataEXT(ser, buffer, size, data, usage); Chunk *chunk = scope.Get(); // if we've already created this is a renaming/data updating call. It should go in // the frame record so we can 'update' the buffer as it goes in the frame. // if we haven't created the buffer at all, it could be a mid-frame create and we // should place it in the resource record, to happen before the frame. if(IsActiveCapturing(m_State) && record->HasDataPtr()) { // we could perhaps substitute this for a 'fake' glBufferSubData chunk? m_ContextRecord->AddChunk(chunk); GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(), eFrameRef_Write); } else { record->AddChunk(chunk); record->SetDataPtr(chunk->GetData()); record->Length = (int32_t)size; record->usage = usage; record->DataInSerialiser = true; } } else { m_Buffers[GetResourceManager()->GetID(BufferRes(GetCtx(), buffer))].size = size; } SAFE_DELETE_ARRAY(dummy); } void WrappedOpenGL::glNamedBufferData(GLuint buffer, GLsizeiptr size, const void *data, GLenum usage) { // only difference to EXT function is size parameter, so just upcast glNamedBufferDataEXT(buffer, size, data, usage); } void WrappedOpenGL::glBufferData(GLenum target, GLsizeiptr size, const void *data, GLenum usage) { byte *dummy = NULL; if(IsCaptureMode(m_State) && data == NULL) { dummy = new byte[size]; memset(dummy, 0xdd, size); data = dummy; } SERIALISE_TIME_CALL(m_Real.glBufferData(target, size, data, usage)); size_t idx = BufferIdx(target); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetCtxData().m_BufferRecord[idx]; RDCASSERTMSG("Couldn't identify implicit object at binding. Mismatched or bad GLuint?", record, target); if(record == NULL) { SAFE_DELETE_ARRAY(dummy); return; } // detect buffer orphaning and just update backing store if(IsBackgroundCapturing(m_State) && record->HasDataPtr() && size == (GLsizeiptr)record->Length && usage == record->usage) { if(data) memcpy(record->GetDataPtr(), data, (size_t)size); else memset(record->GetDataPtr(), 0xbe, (size_t)size); SAFE_DELETE_ARRAY(dummy); return; } GLuint buffer = record->Resource.name; // if we're recreating the buffer, clear the record and add new chunks. Normally // we would just mark this record as dirty and pick it up on the capture frame as initial // data, but we don't support (if it's even possible) querying out size etc. // we need to add only the chunks required - glGenBuffers, glBindBuffer to current target, // and this buffer storage. All other chunks have no effect if(IsBackgroundCapturing(m_State) && (record->HasDataPtr() || (record->Length > 0 && size != (GLsizeiptr)record->Length))) { // we need to maintain chunk ordering, so fetch the first two chunk IDs. // We should have at least two by this point - glGenBuffers and whatever gave the record // a size before. RDCASSERT(record->NumChunks() >= 2); // remove all but the first two chunks while(record->NumChunks() > 2) { Chunk *c = record->GetLastChunk(); SAFE_DELETE(c); record->PopChunk(); } int32_t id2 = record->GetLastChunkID(); { Chunk *c = record->GetLastChunk(); SAFE_DELETE(c); record->PopChunk(); } int32_t id1 = record->GetLastChunkID(); { Chunk *c = record->GetLastChunk(); SAFE_DELETE(c); record->PopChunk(); } RDCASSERT(!record->HasChunks()); // add glGenBuffers chunk { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glGenBuffers); Serialise_glGenBuffers(ser, 1, &buffer); record->AddChunk(scope.Get(), id1); } // add glBindBuffer chunk { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glBindBuffer); Serialise_glBindBuffer(ser, record->datatype, buffer); record->AddChunk(scope.Get(), id2); } // we're about to add the buffer data chunk } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glNamedBufferDataEXT(ser, buffer, size, data, usage); Chunk *chunk = scope.Get(); // if we've already created this is a renaming/data updating call. It should go in // the frame record so we can 'update' the buffer as it goes in the frame. // if we haven't created the buffer at all, it could be a mid-frame create and we // should place it in the resource record, to happen before the frame. if(IsActiveCapturing(m_State) && record->HasDataPtr()) { // we could perhaps substitute this for a 'fake' glBufferSubData chunk? m_ContextRecord->AddChunk(chunk); GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(), eFrameRef_Write); } else { record->AddChunk(chunk); record->SetDataPtr(chunk->GetData()); record->Length = size; record->usage = usage; record->DataInSerialiser = true; } } else { RDCERR("Internal buffers should be allocated via dsa interfaces"); } SAFE_DELETE_ARRAY(dummy); } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glNamedBufferSubDataEXT(SerialiserType &ser, GLuint bufferHandle, GLintptr offsetPtr, GLsizeiptr size, const void *data) { SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr); SERIALISE_ELEMENT_LOCAL(bytesize, (uint64_t)size); SERIALISE_ELEMENT_ARRAY(data, bytesize); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { m_Real.glNamedBufferSubDataEXT(buffer.name, (GLintptr)offset, (GLsizeiptr)bytesize, data); } return true; } void WrappedOpenGL::glNamedBufferSubDataEXT(GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data) { SERIALISE_TIME_CALL(m_Real.glNamedBufferSubDataEXT(buffer, offset, size, data)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); RDCASSERTMSG("Couldn't identify object passed to function. Mismatched or bad GLuint?", record); if(record == NULL) return; if(m_HighTrafficResources.find(record->GetResourceID()) != m_HighTrafficResources.end() && IsBackgroundCapturing(m_State)) return; USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glNamedBufferSubDataEXT(ser, buffer, offset, size, data); Chunk *chunk = scope.Get(); if(IsActiveCapturing(m_State)) { m_ContextRecord->AddChunk(chunk); m_MissingTracks.insert(record->GetResourceID()); GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(), eFrameRef_ReadBeforeWrite); } else { record->AddChunk(chunk); record->UpdateCount++; if(record->UpdateCount > 10) { m_HighTrafficResources.insert(record->GetResourceID()); GetResourceManager()->MarkDirtyResource(record->GetResourceID()); } } } } void WrappedOpenGL::glNamedBufferSubData(GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data) { // only difference to EXT function is size parameter, so just upcast glNamedBufferSubDataEXT(buffer, offset, size, data); } void WrappedOpenGL::glBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const void *data) { SERIALISE_TIME_CALL(m_Real.glBufferSubData(target, offset, size, data)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetCtxData().m_BufferRecord[BufferIdx(target)]; RDCASSERTMSG("Couldn't identify implicit object at binding. Mismatched or bad GLuint?", record, target); if(record == NULL) return; GLResource res = record->Resource; if(m_HighTrafficResources.find(record->GetResourceID()) != m_HighTrafficResources.end() && IsBackgroundCapturing(m_State)) return; USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glNamedBufferSubDataEXT(ser, res.name, offset, size, data); Chunk *chunk = scope.Get(); if(IsActiveCapturing(m_State)) { m_ContextRecord->AddChunk(chunk); m_MissingTracks.insert(record->GetResourceID()); GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(), eFrameRef_ReadBeforeWrite); } else { record->AddChunk(chunk); record->UpdateCount++; if(record->UpdateCount > 10) { m_HighTrafficResources.insert(record->GetResourceID()); GetResourceManager()->MarkDirtyResource(record->GetResourceID()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glNamedCopyBufferSubDataEXT(SerialiserType &ser, GLuint readBufferHandle, GLuint writeBufferHandle, GLintptr readOffsetPtr, GLintptr writeOffsetPtr, GLsizeiptr sizePtr) { SERIALISE_ELEMENT_LOCAL(readBuffer, BufferRes(GetCtx(), readBufferHandle)); SERIALISE_ELEMENT_LOCAL(writeBuffer, BufferRes(GetCtx(), writeBufferHandle)); SERIALISE_ELEMENT_LOCAL(readOffset, (uint64_t)readOffsetPtr); SERIALISE_ELEMENT_LOCAL(writeOffset, (uint64_t)writeOffsetPtr); SERIALISE_ELEMENT_LOCAL(size, (uint64_t)sizePtr); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { m_Real.glNamedCopyBufferSubDataEXT(readBuffer.name, writeBuffer.name, (GLintptr)readOffset, (GLintptr)writeOffset, (GLsizeiptr)size); } return true; } void WrappedOpenGL::glNamedCopyBufferSubDataEXT(GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size) { CoherentMapImplicitBarrier(); SERIALISE_TIME_CALL( m_Real.glNamedCopyBufferSubDataEXT(readBuffer, writeBuffer, readOffset, writeOffset, size)); if(IsCaptureMode(m_State)) { GLResourceRecord *readrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), readBuffer)); GLResourceRecord *writerecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), writeBuffer)); RDCASSERT(readrecord && writerecord); if(m_HighTrafficResources.find(writerecord->GetResourceID()) != m_HighTrafficResources.end() && IsBackgroundCapturing(m_State)) return; if(GetResourceManager()->IsResourceDirty(readrecord->GetResourceID()) && IsBackgroundCapturing(m_State)) { m_HighTrafficResources.insert(writerecord->GetResourceID()); GetResourceManager()->MarkDirtyResource(writerecord->GetResourceID()); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glNamedCopyBufferSubDataEXT(ser, readBuffer, writeBuffer, readOffset, writeOffset, size); Chunk *chunk = scope.Get(); if(IsActiveCapturing(m_State)) { m_ContextRecord->AddChunk(chunk); m_MissingTracks.insert(writerecord->GetResourceID()); GetResourceManager()->MarkResourceFrameReferenced(writerecord->GetResourceID(), eFrameRef_ReadBeforeWrite); } else { writerecord->AddChunk(chunk); writerecord->AddParent(readrecord); writerecord->UpdateCount++; if(writerecord->UpdateCount > 60) { m_HighTrafficResources.insert(writerecord->GetResourceID()); GetResourceManager()->MarkDirtyResource(writerecord->GetResourceID()); } } } } void WrappedOpenGL::glCopyNamedBufferSubData(GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size) { glNamedCopyBufferSubDataEXT(readBuffer, writeBuffer, readOffset, writeOffset, size); } void WrappedOpenGL::glCopyBufferSubData(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size) { CoherentMapImplicitBarrier(); SERIALISE_TIME_CALL( m_Real.glCopyBufferSubData(readTarget, writeTarget, readOffset, writeOffset, size)); if(IsCaptureMode(m_State)) { GLResourceRecord *readrecord = GetCtxData().m_BufferRecord[BufferIdx(readTarget)]; GLResourceRecord *writerecord = GetCtxData().m_BufferRecord[BufferIdx(writeTarget)]; RDCASSERT(readrecord && writerecord); if(m_HighTrafficResources.find(writerecord->GetResourceID()) != m_HighTrafficResources.end() && IsBackgroundCapturing(m_State)) return; if(GetResourceManager()->IsResourceDirty(readrecord->GetResourceID()) && IsBackgroundCapturing(m_State)) { m_HighTrafficResources.insert(writerecord->GetResourceID()); GetResourceManager()->MarkDirtyResource(writerecord->GetResourceID()); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glNamedCopyBufferSubDataEXT( ser, readrecord->Resource.name, writerecord->Resource.name, readOffset, writeOffset, size); Chunk *chunk = scope.Get(); if(IsActiveCapturing(m_State)) { m_ContextRecord->AddChunk(chunk); m_MissingTracks.insert(writerecord->GetResourceID()); GetResourceManager()->MarkResourceFrameReferenced(writerecord->GetResourceID(), eFrameRef_ReadBeforeWrite); } else { writerecord->AddChunk(chunk); writerecord->AddParent(readrecord); writerecord->UpdateCount++; if(writerecord->UpdateCount > 60) { m_HighTrafficResources.insert(writerecord->GetResourceID()); GetResourceManager()->MarkDirtyResource(writerecord->GetResourceID()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glBindBufferBase(SerialiserType &ser, GLenum target, GLuint index, GLuint bufferHandle) { SERIALISE_ELEMENT(target); SERIALISE_ELEMENT(index); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { m_Real.glBindBufferBase(target, index, buffer.name); AddResourceInitChunk(buffer); } return true; } void WrappedOpenGL::glBindBufferBase(GLenum target, GLuint index, GLuint buffer) { ContextData &cd = GetCtxData(); SERIALISE_TIME_CALL(m_Real.glBindBufferBase(target, index, buffer)); if(IsCaptureMode(m_State)) { size_t idx = BufferIdx(target); GLResourceRecord *r = NULL; if(buffer == 0) r = cd.m_BufferRecord[idx] = NULL; else r = cd.m_BufferRecord[idx] = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); if(buffer && IsActiveCapturing(m_State)) { FrameRefType refType = eFrameRef_Read; // these targets write to the buffer if(target == eGL_ATOMIC_COUNTER_BUFFER || target == eGL_COPY_WRITE_BUFFER || target == eGL_PIXEL_PACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER || target == eGL_TRANSFORM_FEEDBACK_BUFFER) refType = eFrameRef_ReadBeforeWrite; GetResourceManager()->MarkResourceFrameReferenced(cd.m_BufferRecord[idx]->GetResourceID(), refType); } // it's legal to re-type buffers, generate another BindBuffer chunk to rename if(r && r->datatype != target) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glBindBuffer); Serialise_glBindBuffer(ser, target, buffer); chunk = scope.Get(); } r->datatype = target; r->AddChunk(chunk); } // store as transform feedback record state if(IsBackgroundCapturing(m_State) && target == eGL_TRANSFORM_FEEDBACK_BUFFER && RecordUpdateCheck(cd.m_FeedbackRecord)) { GLuint feedback = cd.m_FeedbackRecord->Resource.name; // use glTransformFeedbackBufferBase to ensure the feedback object is bound when we bind the // buffer USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glTransformFeedbackBufferBase); Serialise_glTransformFeedbackBufferBase(ser, feedback, index, buffer); cd.m_FeedbackRecord->AddChunk(scope.Get()); } // immediately consider buffers bound to transform feedbacks/SSBOs/atomic counters as dirty if(r && (target == eGL_TRANSFORM_FEEDBACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER || target == eGL_ATOMIC_COUNTER_BUFFER)) { if(IsActiveCapturing(m_State)) m_MissingTracks.insert(r->GetResourceID()); else GetResourceManager()->MarkDirtyResource(BufferRes(GetCtx(), buffer)); } if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glBindBufferBase(ser, target, index, buffer); m_ContextRecord->AddChunk(scope.Get()); } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glBindBufferRange(SerialiserType &ser, GLenum target, GLuint index, GLuint bufferHandle, GLintptr offsetPtr, GLsizeiptr sizePtr) { SERIALISE_ELEMENT(target); SERIALISE_ELEMENT(index); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr); SERIALISE_ELEMENT_LOCAL(size, (uint64_t)sizePtr); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { m_Real.glBindBufferRange(target, index, buffer.name, (GLintptr)offset, (GLsizeiptr)size); AddResourceInitChunk(buffer); } return true; } void WrappedOpenGL::glBindBufferRange(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size) { ContextData &cd = GetCtxData(); SERIALISE_TIME_CALL(m_Real.glBindBufferRange(target, index, buffer, offset, size)); if(IsCaptureMode(m_State)) { size_t idx = BufferIdx(target); GLResourceRecord *r = NULL; if(buffer == 0) r = cd.m_BufferRecord[idx] = NULL; else r = cd.m_BufferRecord[idx] = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); if(buffer && IsActiveCapturing(m_State)) { FrameRefType refType = eFrameRef_Read; // these targets write to the buffer if(target == eGL_ATOMIC_COUNTER_BUFFER || target == eGL_COPY_WRITE_BUFFER || target == eGL_PIXEL_PACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER || target == eGL_TRANSFORM_FEEDBACK_BUFFER) refType = eFrameRef_ReadBeforeWrite; GetResourceManager()->MarkResourceFrameReferenced(cd.m_BufferRecord[idx]->GetResourceID(), refType); } // it's legal to re-type buffers, generate another BindBuffer chunk to rename if(r && r->datatype != target) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glBindBuffer); Serialise_glBindBuffer(ser, target, buffer); chunk = scope.Get(); } r->datatype = target; r->AddChunk(chunk); } // store as transform feedback record state if(IsBackgroundCapturing(m_State) && target == eGL_TRANSFORM_FEEDBACK_BUFFER && RecordUpdateCheck(cd.m_FeedbackRecord)) { GLuint feedback = cd.m_FeedbackRecord->Resource.name; // use glTransformFeedbackBufferRange to ensure the feedback object is bound when we bind the // buffer USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glTransformFeedbackBufferRange); Serialise_glTransformFeedbackBufferRange(ser, feedback, index, buffer, offset, (GLsizei)size); cd.m_FeedbackRecord->AddChunk(scope.Get()); } // immediately consider buffers bound to transform feedbacks/SSBOs/atomic counters as dirty if(r && (target == eGL_TRANSFORM_FEEDBACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER || target == eGL_ATOMIC_COUNTER_BUFFER)) { if(IsActiveCapturing(m_State)) m_MissingTracks.insert(r->GetResourceID()); else GetResourceManager()->MarkDirtyResource(BufferRes(GetCtx(), buffer)); } if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glBindBufferRange(ser, target, index, buffer, offset, size); m_ContextRecord->AddChunk(scope.Get()); } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glBindBuffersBase(SerialiserType &ser, GLenum target, GLuint first, GLsizei count, const GLuint *bufferHandles) { SERIALISE_ELEMENT(target); SERIALISE_ELEMENT(first); SERIALISE_ELEMENT(count); // can't serialise arrays of GL handles since they're not wrapped or typed :(. std::vector<GLResource> buffers; if(ser.IsWriting()) { buffers.reserve(count); for(GLsizei i = 0; i < count; i++) buffers.push_back(BufferRes(GetCtx(), bufferHandles[i])); } SERIALISE_ELEMENT(buffers); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { std::vector<GLuint> bufs; bufs.reserve(count); for(GLsizei i = 0; i < count; i++) { bufs.push_back(buffers[i].name); AddResourceInitChunk(buffers[i]); } m_Real.glBindBuffersBase(target, first, count, bufs.data()); } return true; } void WrappedOpenGL::glBindBuffersBase(GLenum target, GLuint first, GLsizei count, const GLuint *buffers) { SERIALISE_TIME_CALL(m_Real.glBindBuffersBase(target, first, count, buffers)); if(IsCaptureMode(m_State) && buffers && count > 0) { ContextData &cd = GetCtxData(); size_t idx = BufferIdx(target); GLResourceRecord *r = NULL; if(buffers[0] == 0) r = cd.m_BufferRecord[idx] = NULL; else r = cd.m_BufferRecord[idx] = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffers[0])); if(IsActiveCapturing(m_State)) { FrameRefType refType = eFrameRef_Read; // these targets write to the buffer if(target == eGL_ATOMIC_COUNTER_BUFFER || target == eGL_COPY_WRITE_BUFFER || target == eGL_PIXEL_PACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER || target == eGL_TRANSFORM_FEEDBACK_BUFFER) refType = eFrameRef_ReadBeforeWrite; for(GLsizei i = 0; i < count; i++) { if(buffers[i]) { ResourceId id = GetResourceManager()->GetID(BufferRes(GetCtx(), buffers[i])); GetResourceManager()->MarkResourceFrameReferenced(id, eFrameRef_ReadBeforeWrite); m_MissingTracks.insert(id); } } } for(int i = 0; i < count; i++) { GLResourceRecord *bufrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffers[i])); // it's legal to re-type buffers, generate another BindBuffer chunk to rename if(bufrecord->datatype != target) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glBindBuffer); Serialise_glBindBuffer(ser, target, buffers[i]); chunk = scope.Get(); } bufrecord->datatype = target; bufrecord->AddChunk(chunk); } } // store as transform feedback record state if(IsBackgroundCapturing(m_State) && target == eGL_TRANSFORM_FEEDBACK_BUFFER && RecordUpdateCheck(cd.m_FeedbackRecord)) { GLuint feedback = cd.m_FeedbackRecord->Resource.name; for(int i = 0; i < count; i++) { // use glTransformFeedbackBufferBase to ensure the feedback object is bound when we bind the // buffer USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glTransformFeedbackBufferBase); Serialise_glTransformFeedbackBufferBase(ser, feedback, first + i, buffers[i]); cd.m_FeedbackRecord->AddChunk(scope.Get()); } } // immediately consider buffers bound to transform feedbacks/SSBOs/atomic counters as dirty if(r && (target == eGL_TRANSFORM_FEEDBACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER || target == eGL_ATOMIC_COUNTER_BUFFER)) { if(IsBackgroundCapturing(m_State)) { for(int i = 0; i < count; i++) GetResourceManager()->MarkDirtyResource(BufferRes(GetCtx(), buffers[i])); } } if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glBindBuffersBase(ser, target, first, count, buffers); m_ContextRecord->AddChunk(scope.Get()); } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glBindBuffersRange(SerialiserType &ser, GLenum target, GLuint first, GLsizei count, const GLuint *bufferHandles, const GLintptr *offsetPtrs, const GLsizeiptr *sizePtrs) { // can't serialise arrays of GL handles since they're not wrapped or typed :(. // Likewise need to upcast the offsets and sizes to 64-bit instead of serialising as-is. std::vector<GLResource> buffers; std::vector<uint64_t> offsets; std::vector<uint64_t> sizes; if(ser.IsWriting() && bufferHandles) { buffers.reserve(count); for(GLsizei i = 0; i < count; i++) buffers.push_back(BufferRes(GetCtx(), bufferHandles[i])); } if(ser.IsWriting() && offsetPtrs) { offsets.reserve(count); for(GLsizei i = 0; i < count; i++) offsets.push_back((uint64_t)offsetPtrs[i]); } if(ser.IsWriting() && sizePtrs) { sizes.reserve(count); for(GLsizei i = 0; i < count; i++) sizes.push_back((uint64_t)sizePtrs[i]); } SERIALISE_ELEMENT(target); SERIALISE_ELEMENT(first); SERIALISE_ELEMENT(count); SERIALISE_ELEMENT(buffers); SERIALISE_ELEMENT(offsets); SERIALISE_ELEMENT(sizes); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { std::vector<GLuint> bufs; std::vector<GLintptr> offs; std::vector<GLsizeiptr> sz; if(!buffers.empty()) { bufs.reserve(count); for(GLsizei i = 0; i < count; i++) { bufs.push_back(buffers[i].name); AddResourceInitChunk(buffers[i]); } } if(!offsets.empty()) { offs.reserve(count); for(GLsizei i = 0; i < count; i++) offs.push_back((GLintptr)offsets[i]); } if(!sizes.empty()) { sz.reserve(count); for(GLsizei i = 0; i < count; i++) sz.push_back((GLintptr)sizes[i]); } m_Real.glBindBuffersRange(target, first, count, bufs.empty() ? NULL : bufs.data(), offs.empty() ? NULL : offs.data(), sz.empty() ? NULL : sz.data()); } return true; } void WrappedOpenGL::glBindBuffersRange(GLenum target, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizeiptr *sizes) { SERIALISE_TIME_CALL(m_Real.glBindBuffersRange(target, first, count, buffers, offsets, sizes)); if(IsCaptureMode(m_State) && buffers && count > 0) { ContextData &cd = GetCtxData(); size_t idx = BufferIdx(target); if(buffers[0] == 0) cd.m_BufferRecord[idx] = NULL; else cd.m_BufferRecord[idx] = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffers[0])); if(IsActiveCapturing(m_State)) { FrameRefType refType = eFrameRef_Read; // these targets write to the buffer if(target == eGL_ATOMIC_COUNTER_BUFFER || target == eGL_COPY_WRITE_BUFFER || target == eGL_PIXEL_PACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER || target == eGL_TRANSFORM_FEEDBACK_BUFFER) refType = eFrameRef_ReadBeforeWrite; for(GLsizei i = 0; i < count; i++) { if(buffers[i]) { ResourceId id = GetResourceManager()->GetID(BufferRes(GetCtx(), buffers[i])); GetResourceManager()->MarkResourceFrameReferenced(id, eFrameRef_ReadBeforeWrite); m_MissingTracks.insert(id); } } } else { for(int i = 0; i < count; i++) { GLResourceRecord *r = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffers[i])); // it's legal to re-type buffers, generate another BindBuffer chunk to rename if(r->datatype != target) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glBindBuffer); Serialise_glBindBuffer(ser, target, buffers[i]); chunk = scope.Get(); } r->datatype = target; r->AddChunk(chunk); } } } // store as transform feedback record state if(IsBackgroundCapturing(m_State) && target == eGL_TRANSFORM_FEEDBACK_BUFFER && RecordUpdateCheck(cd.m_FeedbackRecord)) { GLuint feedback = cd.m_FeedbackRecord->Resource.name; for(int i = 0; i < count; i++) { // use glTransformFeedbackBufferRange to ensure the feedback object is bound when we bind // the buffer USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glTransformFeedbackBufferRange); Serialise_glTransformFeedbackBufferRange(ser, feedback, first + i, buffers[i], offsets[i], (GLsizei)sizes[i]); cd.m_FeedbackRecord->AddChunk(scope.Get()); } } // immediately consider buffers bound to transform feedbacks/SSBOs/atomic counters as dirty if(target == eGL_TRANSFORM_FEEDBACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER || target == eGL_ATOMIC_COUNTER_BUFFER) { if(IsBackgroundCapturing(m_State)) { for(int i = 0; i < count; i++) GetResourceManager()->MarkDirtyResource(BufferRes(GetCtx(), buffers[i])); } } if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glBindBuffersRange(ser, target, first, count, buffers, offsets, sizes); m_ContextRecord->AddChunk(scope.Get()); } } } void WrappedOpenGL::glInvalidateBufferData(GLuint buffer) { m_Real.glInvalidateBufferData(buffer); if(IsBackgroundCapturing(m_State)) GetResourceManager()->MarkDirtyResource(BufferRes(GetCtx(), buffer)); else m_MissingTracks.insert(GetResourceManager()->GetID(BufferRes(GetCtx(), buffer))); } void WrappedOpenGL::glInvalidateBufferSubData(GLuint buffer, GLintptr offset, GLsizeiptr length) { m_Real.glInvalidateBufferSubData(buffer, offset, length); if(IsBackgroundCapturing(m_State)) GetResourceManager()->MarkDirtyResource(BufferRes(GetCtx(), buffer)); else m_MissingTracks.insert(GetResourceManager()->GetID(BufferRes(GetCtx(), buffer))); } #pragma endregion #pragma region Mapping /************************************************************************ * * Mapping tends to be the most complex/dense bit of the capturing process, as there are a lot of * carefully considered use cases and edge cases to be aware of. * * The primary motivation is, obviously, correctness - where we have to sacrifice performance, * clarity for correctness, we do. Second to that, we try and keep things simple/clear where the * performance sacrifice will be minimal, and generally we try to remove overhead entirely for * high-traffic maps, such that we only step in where necessary. * * We'll consider "normal" maps of buffers, and persistent maps, separately. Note that in all cases * we can guarantee that the buffer being mapped has correctly-sized backing store available, * created in the glBufferData or glBufferStorage call. We also only need to consider the case of * glMapNamedBufferRangeEXT, glUnmapNamedBufferEXT and glFlushMappedNamedBufferRange - all other * entry points are mapped to one of these in a fairly simple fashion. * * * glMapNamedBufferRangeEXT: * * For a normal map, we decide to either record/intercept it, or to step out of the way and allow * the application to map directly to the GL buffer. We can only map directly when idle capturing, * when capturing a frame we must capture all maps to be correct. Generally we perform a direct map * either if this resource is being mapped often and we want to remove overhead, or if the map * interception would be more complex than it's worth. * * The first checks are to see if we've already "given up" on a buffer, in which case we map * directly again. * * Next, if the map is for write and the buffer is not invalidated, we also map directly. * [NB: Since our buffer contents should be perfect at this point, we may not need to worry about * non-invalidating maps. Potential future improvement.] * * At this point, if the map is to be done directly, we pass the parameters onto GL and return * the result, marking the map with status GLResourceRecord::Mapped_Ignore_Real. Note that this * means we have no idea what happens with the map, and the buffer contents after that are to us * undefined. * * If not, we will be intercepting the map. If it's read-only this is relatively simple to satisfy, * as we just need to fetch the current buffer contents and return the appropriately offsetted * pointer. [NB: Again our buffer contents should still be perfect here, this fetch may be * redundant.] The map status is recorded as GLResourceRecord::Mapped_Read * * At this point we are intercepting a map for write, and it depends on whether or not we are * capturing a frame or just idle. * * If idle the handling is relatively simple, we just offset the pointer and return, marking the * map as GLResourceRecord::Mapped_Write. Note that here we also increment a counter, and if this * counter reaches a high enough number (arbitrary limit), we mark the buffer as high-traffic so * that we'll stop intercepting maps and reduce overhead on this buffer. * * If frame capturing it is more complex. The backing store of the buffer must be preserved as it * will contain the contents at the start of the frame. Instead we allocate two shadow storage * copies on first use. Shadow storage [1] contains the 'current' contents of the buffer - * when first allocated, if the map is non-invalidating, it will be filled with the buffer contents * at that point. If the map is invalidating, it will be reset to 0xcc to help find bugs caused by * leaving valid data behind in invalidated buffer memory. * * Shadow buffer [0] is the buffer that is returned to the user code. Every time it is updated * with the contents of [1]. This way both buffers are always identical and contain the latest * buffer contents. These buffers are used later in unmap, but Map() will return the appropriately * offsetted pointer, and mark the map as GLResourceRecord::Mapped_Write. * * * glUnmapNamedBufferEXT: * * The unmap becomes an actual chunk for serialisation when necessary, so we'll discuss the handling * of the unmap call, and then how it is serialised. * * Unmap's handling varies depending on the status of the map, as set above in * glMapNamedBufferRangeEXT. * * GLResourceRecord::Unmapped is an error case, indicating we haven't had a corresponding Map() * call. * * GLResourceRecord::Mapped_Read is a no-op as we can just discard it, the pointer we returned from * Map() was into our backing store. * * GLResourceRecord::Mapped_Ignore_Real is likewise a no-op as the GL pointer was updated directly * by user code, we weren't involved. However if we are now capturing a frame, it indicates a Map() * was made before this frame began, so this frame cannot be captured - we will need to try again * next frame, where a map will not be allowed to go into GLResourceRecord::Mapped_Ignore_Real. * * GLResourceRecord::Mapped_Write is the only case that will generate a serialised unmap chunk. If * we are idle, then all we need to do is map the 'real' GL buffer, copy across our backing store, * and unmap. We only map the range that was modified. Then everything is complete as the user code * updated our backing store. If we are capturing a frame, then we go into the serialise function * and serialise out a chunk. * * Finally we set the map status back to GLResourceRecord::Unmapped. * * When serialising out a map, we serialise the details of the map (which buffer, offset, length) * and then for non-invalidating maps of >512 byte buffers we perform a difference compare between * the two shadow storage buffers that were set up in glMapNamedBufferRangeEXT. We then serialise * out a buffer of the difference segment, and on replay we map and update this segment of the * buffer. * * The reason for finding the actual difference segment is that many maps will be of a large region * or even the whole buffer, but only update a small section, perhaps once per drawcall. So * serialising the entirety of a large buffer many many times can rapidly inflate the size of the * log. The savings from this can be many GBs as if a 4MB buffer is updated 1000 times, each time * only updating 1KB, this is a difference between 1MB and 4000MB in written data, most of which is * redundant in the last case. * * * glFlushMappedNamedBufferRangeEXT: * * Now consider the specialisation of the above, for maps that have GL_MAP_FLUSH_EXPLICIT_BIT * enabled. * * For the most part, these maps can be treated very similarly to normal maps, however in the case * of unmapping we will skip creating an unmap chunk and instead just allow the unmap to be * discarded. Instead we will serialise out a chunk for each glFlushMappedNamedBufferRangeEXT call. * We will also include flush explicit maps along with the others that we choose to map directly * when possible - so if we're capturing idle a flush explicit map will go straight to GL and be * handled as with GLResourceRecord::Mapped_Ignore_Real above. * * For this reason, if a map status is GLResourceRecord::Mapped_Ignore_Real then we simply pass the * flush range along to real GL. Again if we are capturing a frame now, this map has been 'missed' * and we must try again next frame to capture. Likewise as with Unmap GLResourceRecord::Unmapped is * an error, and for flushing we do not need to consider GLResourceRecord::Mapped_Read (it doesn't * make sense for this case). * * So we only serialise out a flush chunk if we are capturing a frame, and the map is correctly * GLResourceRecord::Mapped_Write. We clamp the flushed range to the size of the map (in case the * user code didn't do this). Unlike map we do not perform any difference compares, but rely on the * user to only flush the minimal range, and serialise the entire range out as a buffer. We also * update the shadow storage buffers so that if the buffer is subsequently mapped without flush * explicit, we have the 'current' contents to perform accurate compares with. * * * * * * Persistant maps: * * The above process handles "normal" maps that happen between other GL commands that use the buffer * contents. Maps that are persistent need to be handled carefully since there are other knock-ons * for correctness and proper tracking. They come in two major forms - coherent and non-coherent. * * Non-coherent maps are the 'easy' case, and in all cases should be recommended whenever users do * persistent mapping. Indeed because of the implementation details, coherent maps may come at a * performance penalty even when RenderDoc is not used and it is simply the user code using GL * directly. * * The important thing is that persistent maps *must always* be intercepted regardless of * circumstance, as in theory they may never be mapped again. We get hints to help us with these * maps, as the buffers must have been created with glBufferStorage and must have the matching * persistent and optionally coherent bits set in the flags bitfield. * * Note also that non-coherent maps tend to go hand in hand with flush explicit maps (although this * is not guaranteed, it is highly likely). * * Non-coherent mappable buffers are GL-mapped on creation, and remain GL-mapped until their * destruction regardless of what user code does. We keep this 'real' GL-mapped buffer around * permanently but it is never returned to user code. Instead we handle maps otherwise as above * (taking care to always intercept), and return the user a pointer to our backing store. Then every * time a map flush happens instead of temporarily mapping and unmapping the GL buffer, we copy into * the appropriate place in our persistent map pointer. If an unmap happens and the map wasn't * flush-explicit, we copy the mapped region then. In this way we maintain correctness - the copies * are "delayed" by the time between user code writing into our memory, and us copying into the real * memory. However this is valid as it happens synchronously with a flush, unmap or other event and * by definition non-coherent maps aren't visible to the GPU until after those operations. * * There is also the function glMemoryBarrier with bit GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT. This has * the effect of acting as if all currently persistent-mapped regions were simultaneously flushed. * This is exactly how we implement it - we store a list of all current user persistent maps and any * time this bit is passed to glMemoryBarrier, we manually call into * glFlushMappedNamedBufferRangeEXT() with the appropriate parameters and handling is otherwise * identical. * * The final piece of the puzzle is coherent mapped buffers. Since we must break the coherency * carefully (see below), we map coherent buffers as non-coherent at creation time, the same as * above. * * To satisfy the demands of being coherent, we need to transparently propogate any changes between * the user written data and the 'real' memory, without any call to intercept - there would be no * need to call glMemoryBarrier or glFlushMappedNamedBufferRangeEXT. To do this, we have shadow * storage allocated as in the "normal" mapping path all the time, and we insert a manual call to * essentially the same code as glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT) in every * intercepted function call that could depend on the results of the buffer. We then check if any * write/change has happened by comparing to the shadow storage, and if so we perform a manual flush * of that changed region and update the shadow storage for next time. * * This "fake coherency" is the reason we can map the buffer as non-coherent, since we will be * performing copies and flushes manually to emulate the coherency to allow our interception in the * middle. * * By definition, there will be *many* of these places where the buffer results could be used, not * least any buffer copy, any texture copy (since a texture buffer could be created), any draw or * dispatch, etc. At each of these points there will be a cost for each coherent map of checking for * changes and it will scale with the size of the buffers. This is a large performance penalty but * one that can't be easily avoided. This is another reason why coherent maps should be avoided. * * Note that this also involves a behaviour change that affects correctness - a user write to memory * is not visible as soon as the write happens, but only on the next api point where the write could * have an effect. In correct code this should not be a problem as relying on any other behaviour * would be impossible - if you wrote into memory expecting commands in flight to be affected you * could not ensure correct ordering. However, obvious from that description, this is precisely a * race condition bug if user code did do that - which means race condition bugs will be hidden by * the nature of this tracing. This is unavoidable without the extreme performance hit of making all * coherent maps read-write, and performing a read-back at every sync point to find every change. * Which by itself may also hide race conditions anyway. * * * Implementation notes: * * The record->Map.ptr is the *offsetted* pointer, ie. a pointer to the beginning of the mapped * region, at record->Map.offset bytes from the start of the buffer. * * record->Map.persistentPtr points to the *base* of the buffer, not offsetted by any current map. * * Likewise the shadow storage pointers point to the base of a buffer-sized allocation each. * ************************************************************************/ void *WrappedOpenGL::glMapNamedBufferRangeEXT(GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access) { // see above for high-level explanation of how mapping is handled if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); bool directMap = false; // first check if we've already given up on these buffers if(IsBackgroundCapturing(m_State) && m_HighTrafficResources.find(record->GetResourceID()) != m_HighTrafficResources.end()) directMap = true; if(!directMap && IsBackgroundCapturing(m_State) && GetResourceManager()->IsResourceDirty(record->GetResourceID())) directMap = true; bool invalidateMap = (access & (GL_MAP_INVALIDATE_BUFFER_BIT | GL_MAP_INVALIDATE_RANGE_BIT)) != 0; bool flushExplicitMap = (access & GL_MAP_FLUSH_EXPLICIT_BIT) != 0; // if this map is writing and doesn't invalidate, or is flush explicit, map directly if(!directMap && (!invalidateMap || flushExplicitMap) && (access & GL_MAP_WRITE_BIT) && IsBackgroundCapturing(m_State)) directMap = true; // persistent maps must ALWAYS be intercepted if((access & GL_MAP_PERSISTENT_BIT) || record->Map.persistentPtr) directMap = false; bool verifyWrite = (RenderDoc::Inst().GetCaptureOptions().verifyMapWrites != 0); // must also intercept to verify writes if(verifyWrite) directMap = false; if(directMap) { m_HighTrafficResources.insert(record->GetResourceID()); GetResourceManager()->MarkDirtyResource(record->GetResourceID()); } record->Map.offset = offset; record->Map.length = length; record->Map.access = access; record->Map.invalidate = invalidateMap; record->Map.verifyWrite = verifyWrite; // store a list of all persistent maps, and subset of all coherent maps if(access & GL_MAP_PERSISTENT_BIT) { Atomic::Inc64(&record->Map.persistentMaps); m_PersistentMaps.insert(record); if(record->Map.access & GL_MAP_COHERENT_BIT) m_CoherentMaps.insert(record); } // if we're doing a direct map, pass onto GL and return if(directMap) { record->Map.ptr = (byte *)m_Real.glMapNamedBufferRangeEXT(buffer, offset, length, access); record->Map.status = GLResourceRecord::Mapped_Ignore_Real; return record->Map.ptr; } // only squirrel away read-only maps, read-write can just be treated as write-only if((access & (GL_MAP_READ_BIT | GL_MAP_WRITE_BIT)) == GL_MAP_READ_BIT) { byte *ptr = record->GetDataPtr(); if(record->Map.persistentPtr) ptr = record->GetShadowPtr(0); RDCASSERT(ptr); ptr += offset; m_Real.glGetNamedBufferSubDataEXT(buffer, offset, length, ptr); record->Map.ptr = ptr; record->Map.status = GLResourceRecord::Mapped_Read; return ptr; } // below here, handle write maps to the backing store byte *ptr = record->GetDataPtr(); RDCASSERT(ptr); { // persistent maps get particular handling if(access & GL_MAP_PERSISTENT_BIT) { // persistent pointers are always into the shadow storage, this way we can use the backing // store for 'initial' buffer contents as with any other buffer. We also need to keep a // comparison & modified buffer in case the application calls glMemoryBarrier(..) at any // time. // if we're invalidating, mark the whole range as 0xcc if(invalidateMap) { memset(record->GetShadowPtr(0) + offset, 0xcc, length); memset(record->GetShadowPtr(1) + offset, 0xcc, length); } record->Map.ptr = ptr = record->GetShadowPtr(0) + offset; record->Map.status = GLResourceRecord::Mapped_Write; } else if(IsActiveCapturing(m_State)) { byte *shadow = (byte *)record->GetShadowPtr(0); // if we don't have a shadow pointer, need to allocate & initialise if(shadow == NULL) { GLint buflength; m_Real.glGetNamedBufferParameterivEXT(buffer, eGL_BUFFER_SIZE, &buflength); // allocate our shadow storage record->AllocShadowStorage(buflength); shadow = (byte *)record->GetShadowPtr(0); // if we're not invalidating, we need the existing contents if(!invalidateMap) { // need to fetch the whole buffer's contents, not just the mapped range, // as next time we won't re-fetch and might need the rest of the contents if(GetResourceManager()->IsResourceDirty(record->GetResourceID())) { // Perhaps we could get these contents from the frame initial state buffer? m_Real.glGetNamedBufferSubDataEXT(buffer, 0, buflength, shadow); } else { memcpy(shadow, record->GetDataPtr(), buflength); } } // copy into second shadow buffer ready for comparison later memcpy(record->GetShadowPtr(1), shadow, buflength); } // if we're invalidating, mark the whole range as 0xcc if(invalidateMap) { memset(shadow + offset, 0xcc, length); memset(record->GetShadowPtr(1) + offset, 0xcc, length); } record->Map.ptr = ptr = shadow + offset; record->Map.status = GLResourceRecord::Mapped_Write; } else if(IsBackgroundCapturing(m_State)) { if(verifyWrite) { byte *shadow = record->GetShadowPtr(0); GLint buflength; m_Real.glGetNamedBufferParameterivEXT(buffer, eGL_BUFFER_SIZE, &buflength); // if we don't have a shadow pointer, need to allocate & initialise if(shadow == NULL) { // allocate our shadow storage record->AllocShadowStorage(buflength); shadow = (byte *)record->GetShadowPtr(0); } // if we're not invalidating, we need the existing contents if(!invalidateMap) memcpy(shadow, record->GetDataPtr(), buflength); else memset(shadow + offset, 0xcc, length); ptr = shadow; } // return buffer backing store pointer, offsetted ptr += offset; record->Map.ptr = ptr; record->Map.status = GLResourceRecord::Mapped_Write; record->UpdateCount++; // mark as high-traffic if we update it often enough if(record->UpdateCount > 60) { m_HighTrafficResources.insert(record->GetResourceID()); GetResourceManager()->MarkDirtyResource(record->GetResourceID()); } } } return ptr; } return m_Real.glMapNamedBufferRangeEXT(buffer, offset, length, access); } void *WrappedOpenGL::glMapNamedBufferRange(GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access) { // only difference to EXT function is size parameter, so just upcast return glMapNamedBufferRangeEXT(buffer, offset, length, access); } void *WrappedOpenGL::glMapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access) { // see above glMapNamedBufferRangeEXT for high-level explanation of how mapping is handled if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetCtxData().m_BufferRecord[BufferIdx(target)]; RDCASSERTMSG("Couldn't identify implicit object at binding. Mismatched or bad GLuint?", record, target); if(record) return glMapNamedBufferRangeEXT(record->Resource.name, offset, length, access); RDCERR("glMapBufferRange: Couldn't get resource record for target %x - no buffer bound?", target); } return m_Real.glMapBufferRange(target, offset, length, access); } // the glMapBuffer functions are equivalent to glMapBufferRange - so we just pass through void *WrappedOpenGL::glMapNamedBufferEXT(GLuint buffer, GLenum access) { if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); RDCASSERTMSG("Couldn't identify object passed to function. Mismatched or bad GLuint?", record, buffer); if(record) { GLbitfield accessBits = 0; if(access == eGL_READ_ONLY) accessBits = eGL_MAP_READ_BIT; else if(access == eGL_WRITE_ONLY) accessBits = eGL_MAP_WRITE_BIT; else if(access == eGL_READ_WRITE) accessBits = eGL_MAP_READ_BIT | eGL_MAP_WRITE_BIT; return glMapNamedBufferRangeEXT(record->Resource.name, 0, (GLsizeiptr)record->Length, accessBits); } RDCERR("glMapNamedBufferEXT: Couldn't get resource record for buffer %x!", buffer); } return m_Real.glMapNamedBufferEXT(buffer, access); } void *WrappedOpenGL::glMapBuffer(GLenum target, GLenum access) { // see above glMapNamedBufferRangeEXT for high-level explanation of how mapping is handled if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetCtxData().m_BufferRecord[BufferIdx(target)]; if(record) { GLbitfield accessBits = 0; if(access == eGL_READ_ONLY) accessBits = eGL_MAP_READ_BIT; else if(access == eGL_WRITE_ONLY) accessBits = eGL_MAP_WRITE_BIT; else if(access == eGL_READ_WRITE) accessBits = eGL_MAP_READ_BIT | eGL_MAP_WRITE_BIT; return glMapNamedBufferRangeEXT(record->Resource.name, 0, (GLsizeiptr)record->Length, accessBits); } RDCERR("glMapBuffer: Couldn't get resource record for target %s - no buffer bound?", ToStr(target).c_str()); } return m_Real.glMapBuffer(target, access); } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glUnmapNamedBufferEXT(SerialiserType &ser, GLuint bufferHandle) { // see above glMapNamedBufferRangeEXT for high-level explanation of how mapping is handled GLResourceRecord *record = NULL; if(ser.IsWriting()) record = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)record->Map.offset); SERIALISE_ELEMENT_LOCAL(length, (uint64_t)record->Map.length); uint64_t diffStart = 0; uint64_t diffEnd = (size_t)length; byte *MapWrittenData = NULL; if(ser.IsWriting()) { MapWrittenData = record->Map.ptr; if(IsActiveCapturing(m_State) && // don't bother checking diff range for tiny buffers length > 512 && // if the map has a sub-range specified, trust the user to have specified // a minimal range, similar to glFlushMappedBufferRange, so don't find diff // range. record->Map.offset == 0 && length == record->Length && // similarly for invalidate maps, we want to update the whole buffer !record->Map.invalidate) { size_t s = (size_t)diffStart; size_t e = (size_t)diffEnd; bool found = FindDiffRange(record->Map.ptr, record->GetShadowPtr(1) + offset, (size_t)length, s, e); diffStart = (uint64_t)s; diffEnd = (uint64_t)e; if(found) { #if ENABLED(RDOC_DEVEL) static uint64_t saved = 0; saved += length - (diffEnd - diffStart); RDCDEBUG( "Mapped resource size %llu, difference: %llu -> %llu. Total bytes saved so far: %llu", length, diffStart, diffEnd, saved); #endif length = diffEnd - diffStart; } else { diffStart = 0; diffEnd = 0; length = 1; } // update the data pointer to be rebased to the start of the diff data. MapWrittenData += diffStart; } // update shadow stores for future diff'ing if(IsActiveCapturing(m_State) && record->GetShadowPtr(1)) { memcpy(record->GetShadowPtr(1) + (size_t)offset + (size_t)diffStart, MapWrittenData, size_t(diffEnd - diffStart)); } } SERIALISE_ELEMENT(diffStart); SERIALISE_ELEMENT(diffEnd); SERIALISE_ELEMENT_ARRAY(MapWrittenData, length); SERIALISE_CHECK_READ_ERRORS(); if(!IsStructuredExporting(m_State) && diffEnd > diffStart) { if(record && record->Map.persistentPtr) { // if we have a persistent mapped pointer, copy the range into the 'real' memory and // do a flush. Note the persistent pointer is always to the base of the buffer so we // need to account for the offset memcpy(record->Map.persistentPtr + (size_t)offset + (size_t)diffStart, record->Map.ptr + (size_t)diffStart, size_t(diffEnd - diffStart)); m_Real.glFlushMappedNamedBufferRangeEXT(buffer.name, GLintptr(offset + diffStart), GLsizeiptr(diffEnd - diffStart)); } else if(MapWrittenData && length > 0) { void *ptr = m_Real.glMapNamedBufferRangeEXT(buffer.name, (GLintptr)(offset + diffStart), GLsizeiptr(diffEnd - diffStart), GL_MAP_WRITE_BIT); memcpy(ptr, MapWrittenData, size_t(diffEnd - diffStart)); m_Real.glUnmapNamedBufferEXT(buffer.name); } } return true; } GLboolean WrappedOpenGL::glUnmapNamedBufferEXT(GLuint buffer) { // see above glMapNamedBufferRangeEXT for high-level explanation of how mapping is handled if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); auto status = record->Map.status; if(IsActiveCapturing(m_State)) { m_MissingTracks.insert(record->GetResourceID()); GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(), eFrameRef_ReadBeforeWrite); } GLboolean ret = GL_TRUE; switch(status) { case GLResourceRecord::Unmapped: RDCERR("Unmapped buffer being passed to glUnmapBuffer"); break; case GLResourceRecord::Mapped_Read: // can ignore break; case GLResourceRecord::Mapped_Ignore_Real: if(IsActiveCapturing(m_State)) { RDCERR( "Failed to cap frame - we saw an Unmap() that we didn't capture the corresponding " "Map() for"); m_SuccessfulCapture = false; m_FailureReason = CaptureFailed_UncappedUnmap; } // need to do the real unmap ret = m_Real.glUnmapNamedBufferEXT(buffer); break; case GLResourceRecord::Mapped_Write: { if(record->Map.verifyWrite) { if(!record->VerifyShadowStorage()) { string msg = StringFormat::Fmt( "Overwrite of %llu byte Map()'d buffer detected\n" "Breakpoint now to see callstack,\nor click 'Yes' to debugbreak.", record->Length); int res = tinyfd_messageBox("Map() overwrite detected!", msg.c_str(), "yesno", "error", 1); if(res == 1) { OS_DEBUG_BREAK(); } } // copy from shadow to backing store, so we're consistent memcpy(record->GetDataPtr() + record->Map.offset, record->Map.ptr, record->Map.length); } if(record->Map.access & GL_MAP_FLUSH_EXPLICIT_BIT) { // do nothing, any flushes that happened were handled, // and we won't do any other updates here or make a chunk. } else if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glUnmapNamedBufferEXT(ser, buffer); m_ContextRecord->AddChunk(scope.Get()); } else if(IsBackgroundCapturing(m_State)) { if(record->Map.persistentPtr) { // if we have a persistent mapped pointer, copy the range into the 'real' memory and // do a flush. Note the persistent pointer is always to the base of the buffer so we // need to account for the offset memcpy(record->Map.persistentPtr + record->Map.offset, record->Map.ptr, record->Map.length); m_Real.glFlushMappedNamedBufferRangeEXT(buffer, record->Map.offset, record->Map.length); // update shadow storage memcpy(record->GetShadowPtr(1) + record->Map.offset, record->Map.ptr, record->Map.length); GetResourceManager()->MarkDirtyResource(record->GetResourceID()); } else { // if we are here for background capturing, the app wrote directly into our backing // store memory. Just need to copy the data across to GL, no other work needed void *ptr = m_Real.glMapNamedBufferRangeEXT(buffer, (GLintptr)record->Map.offset, GLsizeiptr(record->Map.length), GL_MAP_WRITE_BIT); memcpy(ptr, record->Map.ptr, record->Map.length); m_Real.glUnmapNamedBufferEXT(buffer); } } break; } } // keep list of persistent & coherent maps up to date if we've // made the last unmap to a buffer if(record->Map.access & GL_MAP_PERSISTENT_BIT) { int64_t ref = Atomic::Dec64(&record->Map.persistentMaps); if(ref == 0) { m_PersistentMaps.erase(record); if(record->Map.access & GL_MAP_COHERENT_BIT) m_CoherentMaps.erase(record); } } record->Map.status = GLResourceRecord::Unmapped; return ret; } return m_Real.glUnmapNamedBufferEXT(buffer); } GLboolean WrappedOpenGL::glUnmapBuffer(GLenum target) { // see above glMapNamedBufferRangeEXT for high-level explanation of how mapping is handled if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetCtxData().m_BufferRecord[BufferIdx(target)]; if(record) return glUnmapNamedBufferEXT(record->Resource.name); RDCERR("glUnmapBuffer: Couldn't get resource record for target %s - no buffer bound?", ToStr(target).c_str()); } return m_Real.glUnmapBuffer(target); } // offsetPtr here is from the start of the buffer, not the mapped region template <typename SerialiserType> bool WrappedOpenGL::Serialise_glFlushMappedNamedBufferRangeEXT(SerialiserType &ser, GLuint bufferHandle, GLintptr offsetPtr, GLsizeiptr lengthPtr) { // see above glMapNamedBufferRangeEXT for high-level explanation of how mapping is handled SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr); SERIALISE_ELEMENT_LOCAL(length, (uint64_t)lengthPtr); GLResourceRecord *record = NULL; byte *FlushedData = NULL; if(ser.IsWriting()) { record = GetResourceManager()->GetResourceRecord(buffer); FlushedData = record->Map.ptr + offset - record->Map.offset; // update the comparison buffer in case this buffer is subsequently mapped and we want to find // the difference region if(IsActiveCapturing(m_State) && record->GetShadowPtr(1)) { memcpy(record->GetShadowPtr(1) + (size_t)offset, FlushedData, (size_t)length); } } SERIALISE_ELEMENT_ARRAY(FlushedData, length); SERIALISE_CHECK_READ_ERRORS(); if(record && record->Map.persistentPtr) { // if we have a persistent mapped pointer, copy the range into the 'real' memory and // do a flush. Note the persistent pointer is always to the base of the buffer so we // need to account for the offset memcpy(record->Map.persistentPtr + (size_t)offset, record->Map.ptr + (size_t)(offset - record->Map.offset), (size_t)length); m_Real.glFlushMappedNamedBufferRangeEXT(buffer.name, (GLintptr)offset, (GLsizeiptr)length); } else if(buffer.name && FlushedData && length > 0) { // perform a map of the range and copy the data, to emulate the modified region being flushed void *ptr = m_Real.glMapNamedBufferRangeEXT(buffer.name, (GLintptr)offset, (GLsizeiptr)length, GL_MAP_WRITE_BIT); memcpy(ptr, FlushedData, (size_t)length); m_Real.glUnmapNamedBufferEXT(buffer.name); } return true; } void WrappedOpenGL::glFlushMappedNamedBufferRangeEXT(GLuint buffer, GLintptr offset, GLsizeiptr length) { // see above glMapNamedBufferRangeEXT for high-level explanation of how mapping is handled GLResourceRecord *record = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); RDCASSERTMSG("Couldn't identify object passed to function. Mismatched or bad GLuint?", record, buffer); // only need to pay attention to flushes when in capframe. Otherwise (see above) we // treat the map as a normal map, and let ALL modified regions go through, flushed or not, // as this is legal - modified but unflushed regions are 'undefined' so we can just say // that modifications applying is our undefined behaviour. // note that we only want to flush the range with GL if we've actually // mapped it. Otherwise the map is 'virtual' and just pointing to our backing store data if(record && record->Map.status == GLResourceRecord::Mapped_Ignore_Real) { m_Real.glFlushMappedNamedBufferRangeEXT(buffer, offset, length); } if(IsActiveCapturing(m_State)) { if(record) { m_MissingTracks.insert(record->GetResourceID()); GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(), eFrameRef_ReadBeforeWrite); if(record->Map.status == GLResourceRecord::Unmapped) { RDCWARN("Unmapped buffer being flushed, ignoring"); } else if(record->Map.status == GLResourceRecord::Mapped_Ignore_Real) { RDCERR( "Failed to cap frame - we saw an FlushMappedBuffer() that we didn't capture the " "corresponding Map() for"); m_SuccessfulCapture = false; m_FailureReason = CaptureFailed_UncappedUnmap; } else if(record->Map.status == GLResourceRecord::Mapped_Write) { if(offset < 0 || offset + length > record->Map.length) { RDCWARN("Flushed buffer range is outside of mapped range, clamping"); // maintain the length/end boundary of the flushed range if the flushed offset // is below the mapped range if(offset < 0) { offset = 0; length += offset; } // clamp the length if it's beyond the mapped range. if(offset + length > record->Map.length) { length = (record->Map.length - offset); } } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glFlushMappedNamedBufferRangeEXT(ser, buffer, record->Map.offset + offset, length); m_ContextRecord->AddChunk(scope.Get()); } // other statuses is GLResourceRecord::Mapped_Read } } else if(IsBackgroundCapturing(m_State)) { // if this is a flush of a persistent map, we need to copy through to // the real pointer and perform a real flush. if(record && record->Map.persistentPtr) { memcpy(record->Map.persistentPtr + record->Map.offset + offset, record->Map.ptr + offset, length); m_Real.glFlushMappedNamedBufferRangeEXT(buffer, offset, length); GetResourceManager()->MarkDirtyResource(record->GetResourceID()); } } } void WrappedOpenGL::glFlushMappedNamedBufferRange(GLuint buffer, GLintptr offset, GLsizeiptr length) { // only difference to EXT function is size parameter, so just upcast glFlushMappedNamedBufferRangeEXT(buffer, offset, length); } void WrappedOpenGL::glFlushMappedBufferRange(GLenum target, GLintptr offset, GLsizeiptr length) { if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetCtxData().m_BufferRecord[BufferIdx(target)]; RDCASSERTMSG("Couldn't identify implicit object at binding. Mismatched or bad GLuint?", record, target); if(record) return glFlushMappedNamedBufferRangeEXT(record->Resource.name, offset, length); RDCERR( "glFlushMappedBufferRange: Couldn't get resource record for target %x - no buffer bound?", target); } return m_Real.glFlushMappedBufferRange(target, offset, length); } void WrappedOpenGL::PersistentMapMemoryBarrier(const set<GLResourceRecord *> &maps) { PUSH_CURRENT_CHUNK; // this function iterates over all the maps, checking for any changes between // the shadow pointers, and propogates that to 'real' GL for(set<GLResourceRecord *>::const_iterator it = maps.begin(); it != maps.end(); ++it) { GLResourceRecord *record = *it; RDCASSERT(record && record->Map.persistentPtr); size_t diffStart = 0, diffEnd = 0; bool found = FindDiffRange(record->GetShadowPtr(0), record->GetShadowPtr(1), (size_t)record->Length, diffStart, diffEnd); if(found) { // update the modified region in the 'comparison' shadow buffer for next check memcpy(record->GetShadowPtr(1) + diffStart, record->GetShadowPtr(0) + diffStart, diffEnd - diffStart); // we use our own flush function so it will serialise chunks when necessary, and it // also handles copying into the persistent mapped pointer and flushing the real GL // buffer gl_CurChunk = GLChunk::glFlushMappedNamedBufferRangeEXT; glFlushMappedNamedBufferRangeEXT(record->Resource.name, GLintptr(diffStart), GLsizeiptr(diffEnd - diffStart)); } } } #pragma endregion #pragma region Transform Feedback template <typename SerialiserType> bool WrappedOpenGL::Serialise_glGenTransformFeedbacks(SerialiserType &ser, GLsizei n, GLuint *ids) { SERIALISE_ELEMENT(n); SERIALISE_ELEMENT_LOCAL(feedback, GetResourceManager()->GetID(FeedbackRes(GetCtx(), *ids))) .TypedAs("GLResource"); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { GLuint real = 0; m_Real.glGenTransformFeedbacks(1, &real); m_Real.glBindTransformFeedback(eGL_TRANSFORM_FEEDBACK, real); m_Real.glBindTransformFeedback(eGL_TRANSFORM_FEEDBACK, 0); GLResource res = FeedbackRes(GetCtx(), real); m_ResourceManager->RegisterResource(res); GetResourceManager()->AddLiveResource(feedback, res); AddResource(feedback, ResourceType::StateObject, "Transform Feedback"); } return true; } void WrappedOpenGL::glGenTransformFeedbacks(GLsizei n, GLuint *ids) { SERIALISE_TIME_CALL(m_Real.glGenTransformFeedbacks(n, ids)); for(GLsizei i = 0; i < n; i++) { GLResource res = FeedbackRes(GetCtx(), ids[i]); ResourceId id = GetResourceManager()->RegisterResource(res); if(IsCaptureMode(m_State)) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glGenTransformFeedbacks(ser, 1, ids + i); chunk = scope.Get(); } GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id); RDCASSERT(record); record->AddChunk(chunk); } else { GetResourceManager()->AddLiveResource(id, res); } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glCreateTransformFeedbacks(SerialiserType &ser, GLsizei n, GLuint *ids) { SERIALISE_ELEMENT(n); SERIALISE_ELEMENT_LOCAL(feedback, GetResourceManager()->GetID(FeedbackRes(GetCtx(), *ids))) .TypedAs("GLResource"); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { GLuint real = 0; m_Real.glCreateTransformFeedbacks(1, &real); GLResource res = FeedbackRes(GetCtx(), real); m_ResourceManager->RegisterResource(res); GetResourceManager()->AddLiveResource(feedback, res); AddResource(feedback, ResourceType::StateObject, "Transform Feedback"); } return true; } void WrappedOpenGL::glCreateTransformFeedbacks(GLsizei n, GLuint *ids) { SERIALISE_TIME_CALL(m_Real.glCreateTransformFeedbacks(n, ids)); for(GLsizei i = 0; i < n; i++) { GLResource res = FeedbackRes(GetCtx(), ids[i]); ResourceId id = GetResourceManager()->RegisterResource(res); if(IsCaptureMode(m_State)) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glCreateTransformFeedbacks(ser, 1, ids + i); chunk = scope.Get(); } GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id); RDCASSERT(record); record->AddChunk(chunk); } else { GetResourceManager()->AddLiveResource(id, res); } } } void WrappedOpenGL::glDeleteTransformFeedbacks(GLsizei n, const GLuint *ids) { for(GLsizei i = 0; i < n; i++) { GLResource res = FeedbackRes(GetCtx(), ids[i]); if(GetResourceManager()->HasCurrentResource(res)) { GetResourceManager()->MarkCleanResource(res); if(GetResourceManager()->HasResourceRecord(res)) GetResourceManager()->GetResourceRecord(res)->Delete(GetResourceManager()); GetResourceManager()->UnregisterResource(res); } } m_Real.glDeleteTransformFeedbacks(n, ids); } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glTransformFeedbackBufferBase(SerialiserType &ser, GLuint xfbHandle, GLuint index, GLuint bufferHandle) { SERIALISE_ELEMENT_LOCAL(xfb, FeedbackRes(GetCtx(), xfbHandle)); SERIALISE_ELEMENT(index); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // use ARB_direct_state_access functions here as we use EXT_direct_state_access elsewhere. If // we are running without ARB_dsa support, these functions are emulated in the trivial way. This // is necessary since these functions can be serialised even if ARB_dsa was not used originally, // and we need to support this case. m_Real.glTransformFeedbackBufferBase(xfb.name, index, buffer.name); } return true; } void WrappedOpenGL::glTransformFeedbackBufferBase(GLuint xfb, GLuint index, GLuint buffer) { SERIALISE_TIME_CALL(m_Real.glTransformFeedbackBufferBase(xfb, index, buffer)); if(IsCaptureMode(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTransformFeedbackBufferBase(ser, xfb, index, buffer); if(IsActiveCapturing(m_State)) { m_ContextRecord->AddChunk(scope.Get()); GetResourceManager()->MarkResourceFrameReferenced(BufferRes(GetCtx(), buffer), eFrameRef_ReadBeforeWrite); } else if(xfb != 0) { GLResourceRecord *fbrecord = GetResourceManager()->GetResourceRecord(FeedbackRes(GetCtx(), xfb)); fbrecord->AddChunk(scope.Get()); if(buffer != 0) fbrecord->AddParent(GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer))); } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glTransformFeedbackBufferRange(SerialiserType &ser, GLuint xfbHandle, GLuint index, GLuint bufferHandle, GLintptr offsetPtr, GLsizeiptr sizePtr) { SERIALISE_ELEMENT_LOCAL(xfb, FeedbackRes(GetCtx(), xfbHandle)); SERIALISE_ELEMENT(index); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr); SERIALISE_ELEMENT_LOCAL(size, (uint64_t)sizePtr); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // use ARB_direct_state_access functions here as we use EXT_direct_state_access elsewhere. If // we are running without ARB_dsa support, these functions are emulated in the obvious way. This // is necessary since these functions can be serialised even if ARB_dsa was not used originally, // and we need to support this case. m_Real.glTransformFeedbackBufferRange(xfb.name, index, buffer.name, (GLintptr)offset, (GLsizei)size); } return true; } void WrappedOpenGL::glTransformFeedbackBufferRange(GLuint xfb, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size) { SERIALISE_TIME_CALL(m_Real.glTransformFeedbackBufferRange(xfb, index, buffer, offset, size)); if(IsCaptureMode(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTransformFeedbackBufferRange(ser, xfb, index, buffer, offset, size); if(IsActiveCapturing(m_State)) { m_ContextRecord->AddChunk(scope.Get()); GetResourceManager()->MarkResourceFrameReferenced(BufferRes(GetCtx(), buffer), eFrameRef_ReadBeforeWrite); } else if(xfb != 0) { GLResourceRecord *fbrecord = GetResourceManager()->GetResourceRecord(FeedbackRes(GetCtx(), xfb)); fbrecord->AddChunk(scope.Get()); if(buffer != 0) fbrecord->AddParent(GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer))); } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glBindTransformFeedback(SerialiserType &ser, GLenum target, GLuint xfbHandle) { SERIALISE_ELEMENT(target); SERIALISE_ELEMENT_LOCAL(xfb, FeedbackRes(GetCtx(), xfbHandle)); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { m_Real.glBindTransformFeedback(target, xfb.name); } return true; } void WrappedOpenGL::glBindTransformFeedback(GLenum target, GLuint id) { SERIALISE_TIME_CALL(m_Real.glBindTransformFeedback(target, id)); GLResourceRecord *record = NULL; if(IsCaptureMode(m_State)) { if(id == 0) { GetCtxData().m_FeedbackRecord = record = NULL; } else { GetCtxData().m_FeedbackRecord = record = GetResourceManager()->GetResourceRecord(FeedbackRes(GetCtx(), id)); } } if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glBindTransformFeedback(ser, target, id); m_ContextRecord->AddChunk(scope.Get()); if(record) GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(), eFrameRef_Read); } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glBeginTransformFeedback(SerialiserType &ser, GLenum primitiveMode) { SERIALISE_ELEMENT(primitiveMode); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { m_Real.glBeginTransformFeedback(primitiveMode); m_ActiveFeedback = true; } return true; } void WrappedOpenGL::glBeginTransformFeedback(GLenum primitiveMode) { SERIALISE_TIME_CALL(m_Real.glBeginTransformFeedback(primitiveMode)); m_ActiveFeedback = true; if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glBeginTransformFeedback(ser, primitiveMode); m_ContextRecord->AddChunk(scope.Get()); } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glPauseTransformFeedback(SerialiserType &ser) { if(IsReplayingAndReading()) { m_Real.glPauseTransformFeedback(); } return true; } void WrappedOpenGL::glPauseTransformFeedback() { SERIALISE_TIME_CALL(m_Real.glPauseTransformFeedback()); if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glPauseTransformFeedback(ser); m_ContextRecord->AddChunk(scope.Get()); } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glResumeTransformFeedback(SerialiserType &ser) { if(IsReplayingAndReading()) { m_Real.glResumeTransformFeedback(); } return true; } void WrappedOpenGL::glResumeTransformFeedback() { SERIALISE_TIME_CALL(m_Real.glResumeTransformFeedback()); if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glResumeTransformFeedback(ser); m_ContextRecord->AddChunk(scope.Get()); } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glEndTransformFeedback(SerialiserType &ser) { if(IsReplayingAndReading()) { m_Real.glEndTransformFeedback(); m_ActiveFeedback = false; } return true; } void WrappedOpenGL::glEndTransformFeedback() { SERIALISE_TIME_CALL(m_Real.glEndTransformFeedback()); m_ActiveFeedback = false; if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glEndTransformFeedback(ser); m_ContextRecord->AddChunk(scope.Get()); } } #pragma endregion #pragma region Vertex Arrays // NOTE: In each of the vertex array object functions below, we might not have the live buffer // resource if it's is a pre-capture chunk, and the buffer was never referenced at all in the actual // frame. // The reason for this is that the VAO record doesn't add a parent of the buffer record - because // that parent tracking quickly becomes stale with high traffic VAOs ignoring updates etc, so we // don't rely on the parent connection and manually reference the buffer wherever it is actually // used. template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribOffsetEXT( SerialiserType &ser, GLuint vaobjHandle, GLuint bufferHandle, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLintptr offsetPtr) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT(index); SERIALISE_ELEMENT(size); SERIALISE_ELEMENT(type); SERIALISE_ELEMENT_TYPED(bool, normalized); SERIALISE_ELEMENT(stride); SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; // some intel drivers don't properly update query states (like GL_VERTEX_ATTRIB_ARRAY_SIZE) // unless the VAO is also bound when performing EXT_dsa functions :( GLuint prevVAO = 0; m_Real.glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, (GLint *)&prevVAO); m_Real.glBindVertexArray(vaobj.name); // seems buggy when mixed and matched with new style vertex attrib binding, which we use for VAO // initial states. Since the spec defines how this function should work in terms of new style // bindings, just do that ourselves. // m_Real.glVertexArrayVertexAttribOffsetEXT(vaobj.name, buffer.name, index, size, type, // normalized, stride, (GLintptr)offset); m_Real.glVertexArrayVertexAttribFormatEXT(vaobj.name, index, size, type, normalized, 0); m_Real.glVertexArrayVertexAttribBindingEXT(vaobj.name, index, index); if(stride == 0) { GLenum SizeEnum = size == 1 ? eGL_RED : size == 2 ? eGL_RG : size == 3 ? eGL_RGB : eGL_RGBA; stride = (uint32_t)GetByteSize(1, 1, 1, SizeEnum, type); } if(buffer.name == 0) { // ES allows client-memory pointers, which we override with temp buffers during capture. // For replay, discard these pointers to prevent driver complaining about "negative offsets". offset = 0; } m_Real.glVertexArrayBindVertexBufferEXT(vaobj.name, index, buffer.name, (GLintptr)offset, stride); m_Real.glBindVertexArray(prevVAO); } return true; } void WrappedOpenGL::glVertexArrayVertexAttribOffsetEXT(GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLintptr offset) { SERIALISE_TIME_CALL(m_Real.glVertexArrayVertexAttribOffsetEXT(vaobj, buffer, index, size, type, normalized, stride, offset)); if(IsCaptureMode(m_State)) { GLResourceRecord *bufrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); if(IsActiveCapturing(m_State) && bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribOffsetEXT(ser, vaobj, buffer, index, size, type, normalized, stride, offset); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glVertexAttribPointer(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer) { SERIALISE_TIME_CALL(m_Real.glVertexAttribPointer(index, size, type, normalized, stride, pointer)); if(IsCaptureMode(m_State)) { ContextData &cd = GetCtxData(); GLResourceRecord *bufrecord = cd.m_BufferRecord[BufferIdx(eGL_ARRAY_BUFFER)]; GLResourceRecord *varecord = cd.m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); if(IsActiveCapturing(m_State) && bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribOffsetEXT( ser, varecord ? varecord->Resource.name : 0, bufrecord ? bufrecord->Resource.name : 0, index, size, type, normalized, stride, (GLintptr)pointer); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribIOffsetEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint bufferHandle, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offsetPtr) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT(index); SERIALISE_ELEMENT(size); SERIALISE_ELEMENT(type); SERIALISE_ELEMENT(stride); SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; // some intel drivers don't properly update query states (like GL_VERTEX_ATTRIB_ARRAY_SIZE) // unless the VAO is also bound when performing EXT_dsa functions :( GLuint prevVAO = 0; m_Real.glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, (GLint *)&prevVAO); m_Real.glBindVertexArray(vaobj.name); // seems buggy when mixed and matched with new style vertex attrib binding, which we use for VAO // initial states. Since the spec defines how this function should work in terms of new style // bindings, just do that ourselves. // m_Real.glVertexArrayVertexAttribIOffsetEXT(vaobj.name, buffer.name, index, size, type, // stride, (GLintptr)offset); m_Real.glVertexArrayVertexAttribIFormatEXT(vaobj.name, index, size, type, 0); m_Real.glVertexArrayVertexAttribBindingEXT(vaobj.name, index, index); if(stride == 0) { GLenum SizeEnum = size == 1 ? eGL_RED : size == 2 ? eGL_RG : size == 3 ? eGL_RGB : eGL_RGBA; stride = (uint32_t)GetByteSize(1, 1, 1, SizeEnum, type); } if(buffer.name == 0) { // ES allows client-memory pointers, which we override with temp buffers during capture. // For replay, discard these pointers to prevent driver complaining about "negative offsets". offset = 0; } m_Real.glVertexArrayBindVertexBufferEXT(vaobj.name, index, buffer.name, (GLintptr)offset, stride); m_Real.glBindVertexArray(prevVAO); } return true; } void WrappedOpenGL::glVertexArrayVertexAttribIOffsetEXT(GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset) { SERIALISE_TIME_CALL( m_Real.glVertexArrayVertexAttribIOffsetEXT(vaobj, buffer, index, size, type, stride, offset)); if(IsCaptureMode(m_State)) { GLResourceRecord *bufrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); if(IsActiveCapturing(m_State) && bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribIOffsetEXT(ser, vaobj, buffer, index, size, type, stride, offset); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glVertexAttribIPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer) { SERIALISE_TIME_CALL(m_Real.glVertexAttribIPointer(index, size, type, stride, pointer)); if(IsCaptureMode(m_State)) { ContextData &cd = GetCtxData(); GLResourceRecord *bufrecord = cd.m_BufferRecord[BufferIdx(eGL_ARRAY_BUFFER)]; GLResourceRecord *varecord = cd.m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); if(IsActiveCapturing(m_State) && bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribIOffsetEXT(ser, varecord ? varecord->Resource.name : 0, bufrecord ? bufrecord->Resource.name : 0, index, size, type, stride, (GLintptr)pointer); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribLOffsetEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint bufferHandle, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offsetPtr) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT(index); SERIALISE_ELEMENT(size); SERIALISE_ELEMENT(type); SERIALISE_ELEMENT(stride); SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; // some intel drivers don't properly update query states (like GL_VERTEX_ATTRIB_ARRAY_SIZE) // unless the VAO is also bound when performing EXT_dsa functions :( GLuint prevVAO = 0; m_Real.glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, (GLint *)&prevVAO); m_Real.glBindVertexArray(vaobj.name); // seems buggy when mixed and matched with new style vertex attrib binding, which we use for VAO // initial states. Since the spec defines how this function should work in terms of new style // bindings, just do that ourselves. // m_Real.glVertexArrayVertexAttribIOffsetEXT(vaobj.name, buffer.name, index, size, type, // stride, (GLintptr)offset); m_Real.glVertexArrayVertexAttribLFormatEXT(vaobj.name, index, size, type, 0); m_Real.glVertexArrayVertexAttribBindingEXT(vaobj.name, index, index); if(stride == 0) { GLenum SizeEnum = size == 1 ? eGL_RED : size == 2 ? eGL_RG : size == 3 ? eGL_RGB : eGL_RGBA; stride = (uint32_t)GetByteSize(1, 1, 1, SizeEnum, type); } if(buffer.name == 0) { // ES allows client-memory pointers, which we override with temp buffers during capture. // For replay, discard these pointers to prevent driver complaining about "negative offsets". offset = 0; } m_Real.glVertexArrayBindVertexBufferEXT(vaobj.name, index, buffer.name, (GLintptr)offset, stride); m_Real.glBindVertexArray(prevVAO); } return true; } void WrappedOpenGL::glVertexArrayVertexAttribLOffsetEXT(GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset) { SERIALISE_TIME_CALL( m_Real.glVertexArrayVertexAttribLOffsetEXT(vaobj, buffer, index, size, type, stride, offset)); if(IsCaptureMode(m_State)) { GLResourceRecord *bufrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); if(IsActiveCapturing(m_State) && bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribLOffsetEXT(ser, vaobj, buffer, index, size, type, stride, offset); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glVertexAttribLPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer) { SERIALISE_TIME_CALL(m_Real.glVertexAttribLPointer(index, size, type, stride, pointer)); if(IsCaptureMode(m_State)) { ContextData &cd = GetCtxData(); GLResourceRecord *bufrecord = cd.m_BufferRecord[BufferIdx(eGL_ARRAY_BUFFER)]; GLResourceRecord *varecord = cd.m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); if(IsActiveCapturing(m_State) && bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribLOffsetEXT(ser, varecord ? varecord->Resource.name : 0, bufrecord ? bufrecord->Resource.name : 0, index, size, type, stride, (GLintptr)pointer); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribBindingEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint attribindex, GLuint bindingindex) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT(attribindex); SERIALISE_ELEMENT(bindingindex); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; m_Real.glVertexArrayVertexAttribBindingEXT(vaobj.name, attribindex, bindingindex); } return true; } void WrappedOpenGL::glVertexArrayVertexAttribBindingEXT(GLuint vaobj, GLuint attribindex, GLuint bindingindex) { SERIALISE_TIME_CALL(m_Real.glVertexArrayVertexAttribBindingEXT(vaobj, attribindex, bindingindex)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribBindingEXT(ser, vaobj, attribindex, bindingindex); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glVertexAttribBinding(GLuint attribindex, GLuint bindingindex) { SERIALISE_TIME_CALL(m_Real.glVertexAttribBinding(attribindex, bindingindex)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribBindingEXT(ser, varecord ? varecord->Resource.name : 0, attribindex, bindingindex); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribFormatEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT(attribindex); SERIALISE_ELEMENT(size); SERIALISE_ELEMENT(type); SERIALISE_ELEMENT_TYPED(bool, normalized); SERIALISE_ELEMENT(relativeoffset); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; m_Real.glVertexArrayVertexAttribFormatEXT(vaobj.name, attribindex, size, type, normalized, relativeoffset); } return true; } void WrappedOpenGL::glVertexArrayVertexAttribFormatEXT(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset) { SERIALISE_TIME_CALL(m_Real.glVertexArrayVertexAttribFormatEXT(vaobj, attribindex, size, type, normalized, relativeoffset)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribFormatEXT(ser, vaobj, attribindex, size, type, normalized, relativeoffset); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glVertexAttribFormat(GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset) { SERIALISE_TIME_CALL( m_Real.glVertexAttribFormat(attribindex, size, type, normalized, relativeoffset)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribFormatEXT(ser, varecord ? varecord->Resource.name : 0, attribindex, size, type, normalized, relativeoffset); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribIFormatEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT(attribindex); SERIALISE_ELEMENT(size); SERIALISE_ELEMENT(type); SERIALISE_ELEMENT(relativeoffset); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; m_Real.glVertexArrayVertexAttribIFormatEXT(vaobj.name, attribindex, size, type, relativeoffset); } return true; } void WrappedOpenGL::glVertexArrayVertexAttribIFormatEXT(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset) { SERIALISE_TIME_CALL( m_Real.glVertexArrayVertexAttribIFormatEXT(vaobj, attribindex, size, type, relativeoffset)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribIFormatEXT(ser, vaobj, attribindex, size, type, relativeoffset); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glVertexAttribIFormat(GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset) { SERIALISE_TIME_CALL(m_Real.glVertexAttribIFormat(attribindex, size, type, relativeoffset)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribIFormatEXT(ser, varecord ? varecord->Resource.name : 0, attribindex, size, type, relativeoffset); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribLFormatEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT(attribindex); SERIALISE_ELEMENT(size); SERIALISE_ELEMENT(type); SERIALISE_ELEMENT(relativeoffset); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; m_Real.glVertexArrayVertexAttribLFormatEXT(vaobj.name, attribindex, size, type, relativeoffset); } return true; } void WrappedOpenGL::glVertexArrayVertexAttribLFormatEXT(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset) { SERIALISE_TIME_CALL( m_Real.glVertexArrayVertexAttribLFormatEXT(vaobj, attribindex, size, type, relativeoffset)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribLFormatEXT(ser, vaobj, attribindex, size, type, relativeoffset); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glVertexAttribLFormat(GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset) { SERIALISE_TIME_CALL(m_Real.glVertexAttribLFormat(attribindex, size, type, relativeoffset)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribLFormatEXT(ser, varecord ? varecord->Resource.name : 0, attribindex, size, type, relativeoffset); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribDivisorEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint index, GLuint divisor) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT(index); SERIALISE_ELEMENT(divisor); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; // at the time of writing, AMD driver seems to not have this entry point if(m_Real.glVertexArrayVertexAttribDivisorEXT) { m_Real.glVertexArrayVertexAttribDivisorEXT(vaobj.name, index, divisor); } else { GLuint VAO = 0; m_Real.glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, (GLint *)&VAO); m_Real.glBindVertexArray(vaobj.name); m_Real.glVertexAttribDivisor(index, divisor); m_Real.glBindVertexArray(VAO); } } return true; } void WrappedOpenGL::glVertexArrayVertexAttribDivisorEXT(GLuint vaobj, GLuint index, GLuint divisor) { SERIALISE_TIME_CALL(m_Real.glVertexArrayVertexAttribDivisorEXT(vaobj, index, divisor)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribDivisorEXT(ser, vaobj, index, divisor); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glVertexAttribDivisor(GLuint index, GLuint divisor) { SERIALISE_TIME_CALL(m_Real.glVertexAttribDivisor(index, divisor)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribDivisorEXT(ser, varecord ? varecord->Resource.name : 0, index, divisor); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glEnableVertexArrayAttribEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint index) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT(index); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; GLint prevVAO = 0; m_Real.glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, &prevVAO); m_Real.glEnableVertexArrayAttribEXT(vaobj.name, index); // nvidia bug seems to sometimes change VAO binding in glEnableVertexArrayAttribEXT, although it // seems like it only happens if GL_DEBUG_OUTPUT_SYNCHRONOUS is NOT enabled. m_Real.glBindVertexArray(prevVAO); } return true; } void WrappedOpenGL::glEnableVertexArrayAttribEXT(GLuint vaobj, GLuint index) { SERIALISE_TIME_CALL(m_Real.glEnableVertexArrayAttribEXT(vaobj, index)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glEnableVertexArrayAttribEXT(ser, vaobj, index); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glEnableVertexAttribArray(GLuint index) { SERIALISE_TIME_CALL(m_Real.glEnableVertexAttribArray(index)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glEnableVertexArrayAttribEXT(ser, varecord ? varecord->Resource.name : 0, index); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glDisableVertexArrayAttribEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint index) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT(index); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; GLint prevVAO = 0; m_Real.glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, &prevVAO); m_Real.glDisableVertexArrayAttribEXT(vaobj.name, index); // nvidia bug seems to sometimes change VAO binding in glEnableVertexArrayAttribEXT, although it // seems like it only happens if GL_DEBUG_OUTPUT_SYNCHRONOUS is NOT enabled. m_Real.glBindVertexArray(prevVAO); } return true; } void WrappedOpenGL::glDisableVertexArrayAttribEXT(GLuint vaobj, GLuint index) { SERIALISE_TIME_CALL(m_Real.glDisableVertexArrayAttribEXT(vaobj, index)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glDisableVertexArrayAttribEXT(ser, vaobj, index); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glDisableVertexAttribArray(GLuint index) { SERIALISE_TIME_CALL(m_Real.glDisableVertexAttribArray(index)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glDisableVertexArrayAttribEXT(ser, varecord ? varecord->Resource.name : 0, index); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glGenVertexArrays(SerialiserType &ser, GLsizei n, GLuint *arrays) { SERIALISE_ELEMENT(n); SERIALISE_ELEMENT_LOCAL(array, GetResourceManager()->GetID(VertexArrayRes(GetCtx(), *arrays))) .TypedAs("GLResource"); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { GLuint real = 0; m_Real.glGenVertexArrays(1, &real); m_Real.glBindVertexArray(real); m_Real.glBindVertexArray(0); GLResource res = VertexArrayRes(GetCtx(), real); m_ResourceManager->RegisterResource(res); GetResourceManager()->AddLiveResource(array, res); AddResource(array, ResourceType::StateObject, "Vertex Array"); } return true; } void WrappedOpenGL::glGenVertexArrays(GLsizei n, GLuint *arrays) { SERIALISE_TIME_CALL(m_Real.glGenVertexArrays(n, arrays)); for(GLsizei i = 0; i < n; i++) { GLResource res = VertexArrayRes(GetCtx(), arrays[i]); ResourceId id = GetResourceManager()->RegisterResource(res); if(IsCaptureMode(m_State)) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glGenVertexArrays(ser, 1, arrays + i); chunk = scope.Get(); } GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id); RDCASSERT(record); record->AddChunk(chunk); } else { GetResourceManager()->AddLiveResource(id, res); } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glCreateVertexArrays(SerialiserType &ser, GLsizei n, GLuint *arrays) { SERIALISE_ELEMENT(n); SERIALISE_ELEMENT_LOCAL(array, GetResourceManager()->GetID(VertexArrayRes(GetCtx(), *arrays))) .TypedAs("GLResource"); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { GLuint real = 0; m_Real.glCreateVertexArrays(1, &real); GLResource res = VertexArrayRes(GetCtx(), real); m_ResourceManager->RegisterResource(res); GetResourceManager()->AddLiveResource(array, res); AddResource(array, ResourceType::StateObject, "Vertex Array"); } return true; } void WrappedOpenGL::glCreateVertexArrays(GLsizei n, GLuint *arrays) { SERIALISE_TIME_CALL(m_Real.glCreateVertexArrays(n, arrays)); for(GLsizei i = 0; i < n; i++) { GLResource res = VertexArrayRes(GetCtx(), arrays[i]); ResourceId id = GetResourceManager()->RegisterResource(res); if(IsCaptureMode(m_State)) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glCreateVertexArrays(ser, 1, arrays + i); chunk = scope.Get(); } GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id); RDCASSERT(record); record->AddChunk(chunk); } else { GetResourceManager()->AddLiveResource(id, res); } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glBindVertexArray(SerialiserType &ser, GLuint vaobjHandle) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; m_Real.glBindVertexArray(vaobj.name); } return true; } void WrappedOpenGL::glBindVertexArray(GLuint array) { SERIALISE_TIME_CALL(m_Real.glBindVertexArray(array)); GLResourceRecord *record = NULL; if(IsCaptureMode(m_State)) { if(array == 0) { GetCtxData().m_VertexArrayRecord = record = NULL; } else { GetCtxData().m_VertexArrayRecord = record = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), array)); } } if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glBindVertexArray(ser, array); m_ContextRecord->AddChunk(scope.Get()); if(record) GetResourceManager()->MarkVAOReferenced(record->Resource, eFrameRef_ReadBeforeWrite); } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayElementBuffer(SerialiserType &ser, GLuint vaobjHandle, GLuint bufferHandle) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; // might not have the live resource if this is a pre-capture chunk, and the buffer was never // referenced at all in the actual frame if(buffer.name) { m_Buffers[GetResourceManager()->GetID(buffer)].curType = eGL_ELEMENT_ARRAY_BUFFER; m_Buffers[GetResourceManager()->GetID(buffer)].creationFlags |= BufferCategory::Index; } // use ARB_direct_state_access functions here as we use EXT_direct_state_access elsewhere. If // we are running without ARB_dsa support, these functions are emulated in the obvious way. This // is necessary since these functions can be serialised even if ARB_dsa was not used originally, // and we need to support this case. m_Real.glVertexArrayElementBuffer(vaobj.name, buffer.name); } return true; } void WrappedOpenGL::glVertexArrayElementBuffer(GLuint vaobj, GLuint buffer) { SERIALISE_TIME_CALL(m_Real.glVertexArrayElementBuffer(vaobj, buffer)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *bufrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); if(IsActiveCapturing(m_State) && bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayElementBuffer(ser, vaobj, buffer); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayBindVertexBufferEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint bindingindex, GLuint bufferHandle, GLintptr offsetPtr, GLsizei stride) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT(bindingindex); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr); SERIALISE_ELEMENT(stride); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; if(buffer.name) { m_Buffers[GetResourceManager()->GetID(buffer)].curType = eGL_ARRAY_BUFFER; m_Buffers[GetResourceManager()->GetID(buffer)].creationFlags |= BufferCategory::Vertex; } m_Real.glVertexArrayBindVertexBufferEXT(vaobj.name, bindingindex, buffer.name, (GLintptr)offset, (GLsizei)stride); } return true; } void WrappedOpenGL::glVertexArrayBindVertexBufferEXT(GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride) { SERIALISE_TIME_CALL( m_Real.glVertexArrayBindVertexBufferEXT(vaobj, bindingindex, buffer, offset, stride)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *bufrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); if(IsActiveCapturing(m_State) && bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayBindVertexBufferEXT(ser, vaobj, bindingindex, buffer, offset, stride); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glBindVertexBuffer(GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride) { SERIALISE_TIME_CALL(m_Real.glBindVertexBuffer(bindingindex, buffer, offset, stride)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord; GLResourceRecord *bufrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); if(IsActiveCapturing(m_State) && bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayBindVertexBufferEXT(ser, varecord ? varecord->Resource.name : 0, bindingindex, buffer, offset, stride); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayVertexBuffers(SerialiserType &ser, GLuint vaobjHandle, GLuint first, GLsizei count, const GLuint *bufferHandles, const GLintptr *offsetPtrs, const GLsizei *strides) { // can't serialise arrays of GL handles since they're not wrapped or typed :(. // Likewise need to upcast the offsets to 64-bit instead of serialising as-is. std::vector<GLResource> buffers; std::vector<uint64_t> offsets; if(ser.IsWriting() && bufferHandles) { buffers.reserve(count); for(GLsizei i = 0; i < count; i++) buffers.push_back(BufferRes(GetCtx(), bufferHandles[i])); } if(ser.IsWriting() && offsetPtrs) { offsets.reserve(count); for(GLsizei i = 0; i < count; i++) offsets.push_back((uint64_t)offsetPtrs[i]); } SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT(first); SERIALISE_ELEMENT(count); SERIALISE_ELEMENT(buffers); SERIALISE_ELEMENT(offsets); SERIALISE_ELEMENT_ARRAY(strides, count); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { std::vector<GLuint> bufs; std::vector<GLintptr> offs; if(!buffers.empty()) { bufs.reserve(count); for(GLsizei i = 0; i < count; i++) bufs.push_back(buffers[i].name); } if(!offsets.empty()) { offs.reserve(count); for(GLsizei i = 0; i < count; i++) offs.push_back((GLintptr)offsets[i]); } if(vaobj.name == 0) vaobj.name = m_FakeVAO; // use ARB_direct_state_access functions here as we use EXT_direct_state_access elsewhere. If // we are running without ARB_dsa support, these functions are emulated in the obvious way. This // is necessary since these functions can be serialised even if ARB_dsa was not used originally, // and we need to support this case. m_Real.glVertexArrayVertexBuffers(vaobj.name, first, count, bufs.empty() ? NULL : bufs.data(), offs.empty() ? NULL : offs.data(), strides); if(IsLoading(m_State)) { for(GLsizei i = 0; i < count; i++) { m_Buffers[GetResourceManager()->GetID(buffers[i])].curType = eGL_ARRAY_BUFFER; m_Buffers[GetResourceManager()->GetID(buffers[i])].creationFlags |= BufferCategory::Vertex; } } } return true; } void WrappedOpenGL::glVertexArrayVertexBuffers(GLuint vaobj, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides) { SERIALISE_TIME_CALL( m_Real.glVertexArrayVertexBuffers(vaobj, first, count, buffers, offsets, strides)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexBuffers(ser, vaobj, first, count, buffers, offsets, strides); r->AddChunk(scope.Get()); } if(IsActiveCapturing(m_State)) { for(GLsizei i = 0; i < count; i++) { if(buffers != NULL && buffers[i] != 0) { GLResourceRecord *bufrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffers[i])); if(bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); } } } } } } void WrappedOpenGL::glBindVertexBuffers(GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides) { SERIALISE_TIME_CALL(m_Real.glBindVertexBuffers(first, count, buffers, offsets, strides)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexBuffers(ser, varecord ? varecord->Resource.name : 0, first, count, buffers, offsets, strides); r->AddChunk(scope.Get()); } if(IsActiveCapturing(m_State)) { for(GLsizei i = 0; i < count; i++) { if(buffers != NULL && buffers[i] != 0) { GLResourceRecord *bufrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffers[i])); if(bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); } } } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayVertexBindingDivisorEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint bindingindex, GLuint divisor) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT(bindingindex); SERIALISE_ELEMENT(divisor); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; m_Real.glVertexArrayVertexBindingDivisorEXT(vaobj.name, bindingindex, divisor); } return true; } void WrappedOpenGL::glVertexArrayVertexBindingDivisorEXT(GLuint vaobj, GLuint bindingindex, GLuint divisor) { SERIALISE_TIME_CALL(m_Real.glVertexArrayVertexBindingDivisorEXT(vaobj, bindingindex, divisor)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexBindingDivisorEXT(ser, vaobj, bindingindex, divisor); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glVertexBindingDivisor(GLuint bindingindex, GLuint divisor) { SERIALISE_TIME_CALL(m_Real.glVertexBindingDivisor(bindingindex, divisor)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexBindingDivisorEXT(ser, varecord ? varecord->Resource.name : 0, bindingindex, divisor); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glDeleteBuffers(GLsizei n, const GLuint *buffers) { for(GLsizei i = 0; i < n; i++) { GLResource res = BufferRes(GetCtx(), buffers[i]); if(GetResourceManager()->HasCurrentResource(res)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(res); if(record) { // if we have a persistent pointer, make sure to unmap it if(record->Map.persistentPtr) { m_PersistentMaps.erase(record); if(record->Map.access & GL_MAP_COHERENT_BIT) m_CoherentMaps.erase(record); m_Real.glUnmapNamedBufferEXT(res.name); } // free any shadow storage record->FreeShadowStorage(); } GetResourceManager()->MarkCleanResource(res); if(GetResourceManager()->HasResourceRecord(res)) GetResourceManager()->GetResourceRecord(res)->Delete(GetResourceManager()); GetResourceManager()->UnregisterResource(res); } } m_Real.glDeleteBuffers(n, buffers); } void WrappedOpenGL::glDeleteVertexArrays(GLsizei n, const GLuint *arrays) { for(GLsizei i = 0; i < n; i++) { GLResource res = VertexArrayRes(GetCtx(), arrays[i]); if(GetResourceManager()->HasCurrentResource(res)) { GetResourceManager()->MarkCleanResource(res); if(GetResourceManager()->HasResourceRecord(res)) GetResourceManager()->GetResourceRecord(res)->Delete(GetResourceManager()); GetResourceManager()->UnregisterResource(res); } } m_Real.glDeleteVertexArrays(n, arrays); } #pragma endregion #pragma region Horrible glVertexAttrib variants template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexAttrib(SerialiserType &ser, GLuint index, int count, GLenum type, GLboolean normalized, const void *value, AttribType attribtype) { // this is used to share serialisation code amongst the brazillion variations SERIALISE_ELEMENT(attribtype).Hidden(); AttribType attr = AttribType(attribtype & Attrib_typemask); // this is the number of components in the attribute (1,2,3,4). We hide it because it's part of // the function signature SERIALISE_ELEMENT(count).Hidden(); SERIALISE_ELEMENT(index); // only serialise the type and normalized flags for packed commands if(attr == Attrib_packed) { SERIALISE_ELEMENT(type); SERIALISE_ELEMENT_TYPED(bool, normalized); } // create a union of all the value types - since we can only have up to 4, we can just make it // fixed size union { double d[4]; float f[4]; int32_t i32[4]; uint32_t u32[4]; int16_t i16[4]; uint16_t u16[4]; int8_t i8[4]; uint8_t u8[4]; } v; if(ser.IsWriting()) { uint32_t byteCount = count; if(attr == Attrib_GLbyte) byteCount *= sizeof(char); else if(attr == Attrib_GLshort) byteCount *= sizeof(int16_t); else if(attr == Attrib_GLint) byteCount *= sizeof(int32_t); else if(attr == Attrib_GLubyte) byteCount *= sizeof(unsigned char); else if(attr == Attrib_GLushort) byteCount *= sizeof(uint16_t); else if(attr == Attrib_GLuint || attr == Attrib_packed) byteCount *= sizeof(uint32_t); RDCEraseEl(v); memcpy(v.f, value, byteCount); } // Serialise the array with the right type. We don't want to allocate new storage switch(attr) { case Attrib_GLdouble: ser.Serialise("values", v.d, SerialiserFlags::NoFlags); break; case Attrib_GLfloat: ser.Serialise("values", v.f, SerialiserFlags::NoFlags); break; case Attrib_GLint: ser.Serialise("values", v.i32, SerialiserFlags::NoFlags); break; case Attrib_packed: case Attrib_GLuint: ser.Serialise("values", v.u32, SerialiserFlags::NoFlags); break; case Attrib_GLshort: ser.Serialise("values", v.i16, SerialiserFlags::NoFlags); break; case Attrib_GLushort: ser.Serialise("values", v.u16, SerialiserFlags::NoFlags); break; case Attrib_GLbyte: ser.Serialise("values", v.i8, SerialiserFlags::NoFlags); break; default: case Attrib_GLubyte: ser.Serialise("values", v.u8, SerialiserFlags::NoFlags); break; } SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(attr == Attrib_packed) { if(count == 1) m_Real.glVertexAttribP1uiv(index, type, normalized, v.u32); else if(count == 2) m_Real.glVertexAttribP2uiv(index, type, normalized, v.u32); else if(count == 3) m_Real.glVertexAttribP3uiv(index, type, normalized, v.u32); else if(count == 4) m_Real.glVertexAttribP4uiv(index, type, normalized, v.u32); } else if(attribtype & Attrib_I) { if(count == 1) { if(attr == Attrib_GLint) m_Real.glVertexAttribI1iv(index, v.i32); else if(attr == Attrib_GLuint) m_Real.glVertexAttribI1uiv(index, v.u32); } else if(count == 2) { if(attr == Attrib_GLint) m_Real.glVertexAttribI2iv(index, v.i32); else if(attr == Attrib_GLuint) m_Real.glVertexAttribI2uiv(index, v.u32); } else if(count == 3) { if(attr == Attrib_GLint) m_Real.glVertexAttribI3iv(index, v.i32); else if(attr == Attrib_GLuint) m_Real.glVertexAttribI3uiv(index, v.u32); } else { if(attr == Attrib_GLbyte) m_Real.glVertexAttribI4bv(index, v.i8); else if(attr == Attrib_GLshort) m_Real.glVertexAttribI4sv(index, v.i16); else if(attr == Attrib_GLint) m_Real.glVertexAttribI4iv(index, v.i32); else if(attr == Attrib_GLubyte) m_Real.glVertexAttribI4ubv(index, v.u8); else if(attr == Attrib_GLushort) m_Real.glVertexAttribI4usv(index, v.u16); else if(attr == Attrib_GLuint) m_Real.glVertexAttribI4uiv(index, v.u32); } } else if(attribtype & Attrib_L) { if(count == 1) m_Real.glVertexAttribL1dv(index, v.d); else if(count == 2) m_Real.glVertexAttribL2dv(index, v.d); else if(count == 3) m_Real.glVertexAttribL3dv(index, v.d); else if(count == 4) m_Real.glVertexAttribL4dv(index, v.d); } else if(attribtype & Attrib_N) { if(attr == Attrib_GLbyte) m_Real.glVertexAttrib4Nbv(index, v.i8); else if(attr == Attrib_GLshort) m_Real.glVertexAttrib4Nsv(index, v.i16); else if(attr == Attrib_GLint) m_Real.glVertexAttrib4Niv(index, v.i32); else if(attr == Attrib_GLubyte) m_Real.glVertexAttrib4Nubv(index, v.u8); else if(attr == Attrib_GLushort) m_Real.glVertexAttrib4Nusv(index, v.u16); else if(attr == Attrib_GLuint) m_Real.glVertexAttrib4Nuiv(index, v.u32); } else { if(count == 1) { if(attr == Attrib_GLdouble) m_Real.glVertexAttrib1dv(index, v.d); else if(attr == Attrib_GLfloat) m_Real.glVertexAttrib1fv(index, v.f); else if(attr == Attrib_GLshort) m_Real.glVertexAttrib1sv(index, v.i16); } else if(count == 2) { if(attr == Attrib_GLdouble) m_Real.glVertexAttrib2dv(index, v.d); else if(attr == Attrib_GLfloat) m_Real.glVertexAttrib2fv(index, v.f); else if(attr == Attrib_GLshort) m_Real.glVertexAttrib2sv(index, v.i16); } else if(count == 3) { if(attr == Attrib_GLdouble) m_Real.glVertexAttrib3dv(index, v.d); else if(attr == Attrib_GLfloat) m_Real.glVertexAttrib3fv(index, v.f); else if(attr == Attrib_GLshort) m_Real.glVertexAttrib3sv(index, v.i16); } else { if(attr == Attrib_GLdouble) m_Real.glVertexAttrib4dv(index, v.d); else if(attr == Attrib_GLfloat) m_Real.glVertexAttrib4fv(index, v.f); else if(attr == Attrib_GLbyte) m_Real.glVertexAttrib4bv(index, v.i8); else if(attr == Attrib_GLshort) m_Real.glVertexAttrib4sv(index, v.i16); else if(attr == Attrib_GLint) m_Real.glVertexAttrib4iv(index, v.i32); else if(attr == Attrib_GLubyte) m_Real.glVertexAttrib4ubv(index, v.u8); else if(attr == Attrib_GLushort) m_Real.glVertexAttrib4usv(index, v.u16); else if(attr == Attrib_GLuint) m_Real.glVertexAttrib4uiv(index, v.u32); } } } return true; } #define ATTRIB_FUNC(count, suffix, TypeOr, paramtype, ...) \ \ void WrappedOpenGL::CONCAT(glVertexAttrib, suffix)(GLuint index, __VA_ARGS__) \ \ { \ SERIALISE_TIME_CALL(m_Real.CONCAT(glVertexAttrib, suffix)(index, ARRAYLIST)); \ \ if(IsActiveCapturing(m_State)) \ { \ USE_SCRATCH_SERIALISER(); \ SCOPED_SERIALISE_CHUNK(gl_CurChunk); \ const paramtype vals[] = {ARRAYLIST}; \ Serialise_glVertexAttrib(ser, index, count, eGL_NONE, GL_FALSE, vals, \ AttribType(TypeOr | CONCAT(Attrib_, paramtype))); \ \ m_ContextRecord->AddChunk(scope.Get()); \ } \ } #define ARRAYLIST x ATTRIB_FUNC(1, 1f, 0, GLfloat, GLfloat x) ATTRIB_FUNC(1, 1s, 0, GLshort, GLshort x) ATTRIB_FUNC(1, 1d, 0, GLdouble, GLdouble x) ATTRIB_FUNC(1, L1d, Attrib_L, GLdouble, GLdouble x) ATTRIB_FUNC(1, I1i, Attrib_I, GLint, GLint x) ATTRIB_FUNC(1, I1ui, Attrib_I, GLuint, GLuint x) #undef ARRAYLIST #define ARRAYLIST x, y ATTRIB_FUNC(2, 2f, 0, GLfloat, GLfloat x, GLfloat y) ATTRIB_FUNC(2, 2s, 0, GLshort, GLshort x, GLshort y) ATTRIB_FUNC(2, 2d, 0, GLdouble, GLdouble x, GLdouble y) ATTRIB_FUNC(2, L2d, Attrib_L, GLdouble, GLdouble x, GLdouble y) ATTRIB_FUNC(2, I2i, Attrib_I, GLint, GLint x, GLint y) ATTRIB_FUNC(2, I2ui, Attrib_I, GLuint, GLuint x, GLuint y) #undef ARRAYLIST #define ARRAYLIST x, y, z ATTRIB_FUNC(3, 3f, 0, GLfloat, GLfloat x, GLfloat y, GLfloat z) ATTRIB_FUNC(3, 3s, 0, GLshort, GLshort x, GLshort y, GLshort z) ATTRIB_FUNC(3, 3d, 0, GLdouble, GLdouble x, GLdouble y, GLdouble z) ATTRIB_FUNC(3, L3d, Attrib_L, GLdouble, GLdouble x, GLdouble y, GLdouble z) ATTRIB_FUNC(3, I3i, Attrib_I, GLint, GLint x, GLint y, GLint z) ATTRIB_FUNC(3, I3ui, Attrib_I, GLuint, GLuint x, GLuint y, GLuint z) #undef ARRAYLIST #define ARRAYLIST x, y, z, w ATTRIB_FUNC(4, 4f, 0, GLfloat, GLfloat x, GLfloat y, GLfloat z, GLfloat w) ATTRIB_FUNC(4, 4s, 0, GLshort, GLshort x, GLshort y, GLshort z, GLshort w) ATTRIB_FUNC(4, 4d, 0, GLdouble, GLdouble x, GLdouble y, GLdouble z, GLdouble w) ATTRIB_FUNC(4, L4d, Attrib_L, GLdouble, GLdouble x, GLdouble y, GLdouble z, GLdouble w) ATTRIB_FUNC(4, I4i, Attrib_I, GLint, GLint x, GLint y, GLint z, GLint w) ATTRIB_FUNC(4, I4ui, Attrib_I, GLuint, GLuint x, GLuint y, GLuint z, GLuint w) ATTRIB_FUNC(4, 4Nub, Attrib_N, GLubyte, GLubyte x, GLubyte y, GLubyte z, GLubyte w) #undef ATTRIB_FUNC #define ATTRIB_FUNC(count, suffix, TypeOr, paramtype) \ \ void WrappedOpenGL::CONCAT(glVertexAttrib, suffix)(GLuint index, const paramtype *value) \ \ { \ m_Real.CONCAT(glVertexAttrib, suffix)(index, value); \ \ if(IsActiveCapturing(m_State)) \ { \ USE_SCRATCH_SERIALISER(); \ SCOPED_SERIALISE_CHUNK(gl_CurChunk); \ Serialise_glVertexAttrib(ser, index, count, eGL_NONE, GL_FALSE, value, \ AttribType(TypeOr | CONCAT(Attrib_, paramtype))); \ \ m_ContextRecord->AddChunk(scope.Get()); \ } \ } ATTRIB_FUNC(1, 1dv, 0, GLdouble) ATTRIB_FUNC(2, 2dv, 0, GLdouble) ATTRIB_FUNC(3, 3dv, 0, GLdouble) ATTRIB_FUNC(4, 4dv, 0, GLdouble) ATTRIB_FUNC(1, 1sv, 0, GLshort) ATTRIB_FUNC(2, 2sv, 0, GLshort) ATTRIB_FUNC(3, 3sv, 0, GLshort) ATTRIB_FUNC(4, 4sv, 0, GLshort) ATTRIB_FUNC(1, 1fv, 0, GLfloat) ATTRIB_FUNC(2, 2fv, 0, GLfloat) ATTRIB_FUNC(3, 3fv, 0, GLfloat) ATTRIB_FUNC(4, 4fv, 0, GLfloat) ATTRIB_FUNC(4, 4bv, 0, GLbyte) ATTRIB_FUNC(4, 4iv, 0, GLint) ATTRIB_FUNC(4, 4uiv, 0, GLuint) ATTRIB_FUNC(4, 4usv, 0, GLushort) ATTRIB_FUNC(4, 4ubv, 0, GLubyte) ATTRIB_FUNC(1, L1dv, Attrib_L, GLdouble) ATTRIB_FUNC(2, L2dv, Attrib_L, GLdouble) ATTRIB_FUNC(3, L3dv, Attrib_L, GLdouble) ATTRIB_FUNC(4, L4dv, Attrib_L, GLdouble) ATTRIB_FUNC(1, I1iv, Attrib_I, GLint) ATTRIB_FUNC(1, I1uiv, Attrib_I, GLuint) ATTRIB_FUNC(2, I2iv, Attrib_I, GLint) ATTRIB_FUNC(2, I2uiv, Attrib_I, GLuint) ATTRIB_FUNC(3, I3iv, Attrib_I, GLint) ATTRIB_FUNC(3, I3uiv, Attrib_I, GLuint) ATTRIB_FUNC(4, I4bv, Attrib_I, GLbyte) ATTRIB_FUNC(4, I4iv, Attrib_I, GLint) ATTRIB_FUNC(4, I4sv, Attrib_I, GLshort) ATTRIB_FUNC(4, I4ubv, Attrib_I, GLubyte) ATTRIB_FUNC(4, I4uiv, Attrib_I, GLuint) ATTRIB_FUNC(4, I4usv, Attrib_I, GLushort) ATTRIB_FUNC(4, 4Nbv, Attrib_N, GLbyte) ATTRIB_FUNC(4, 4Niv, Attrib_N, GLint) ATTRIB_FUNC(4, 4Nsv, Attrib_N, GLshort) ATTRIB_FUNC(4, 4Nubv, Attrib_N, GLubyte) ATTRIB_FUNC(4, 4Nuiv, Attrib_N, GLuint) ATTRIB_FUNC(4, 4Nusv, Attrib_N, GLushort) #undef ATTRIB_FUNC #define ATTRIB_FUNC(count, suffix, funcparam, passparam) \ \ void WrappedOpenGL::CONCAT(CONCAT(glVertexAttribP, count), suffix)( \ GLuint index, GLenum type, GLboolean normalized, funcparam) \ \ { \ m_Real.CONCAT(CONCAT(glVertexAttribP, count), suffix)(index, type, normalized, value); \ \ if(IsActiveCapturing(m_State)) \ { \ USE_SCRATCH_SERIALISER(); \ SCOPED_SERIALISE_CHUNK(gl_CurChunk); \ Serialise_glVertexAttrib(ser, index, count, type, normalized, passparam, Attrib_packed); \ \ m_ContextRecord->AddChunk(scope.Get()); \ } \ } ATTRIB_FUNC(1, ui, GLuint value, &value) ATTRIB_FUNC(2, ui, GLuint value, &value) ATTRIB_FUNC(3, ui, GLuint value, &value) ATTRIB_FUNC(4, ui, GLuint value, &value) ATTRIB_FUNC(1, uiv, const GLuint *value, value) ATTRIB_FUNC(2, uiv, const GLuint *value, value) ATTRIB_FUNC(3, uiv, const GLuint *value, value) ATTRIB_FUNC(4, uiv, const GLuint *value, value) #pragma endregion INSTANTIATE_FUNCTION_SERIALISED(void, glGenBuffers, GLsizei n, GLuint *buffers); INSTANTIATE_FUNCTION_SERIALISED(void, glCreateBuffers, GLsizei n, GLuint *buffers); INSTANTIATE_FUNCTION_SERIALISED(void, glBindBuffer, GLenum target, GLuint bufferHandle); INSTANTIATE_FUNCTION_SERIALISED(void, glNamedBufferStorageEXT, GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags); INSTANTIATE_FUNCTION_SERIALISED(void, glNamedBufferDataEXT, GLuint buffer, GLsizeiptr size, const void *data, GLenum usage); INSTANTIATE_FUNCTION_SERIALISED(void, glNamedBufferSubDataEXT, GLuint buffer, GLintptr offsetPtr, GLsizeiptr size, const void *data); INSTANTIATE_FUNCTION_SERIALISED(void, glNamedCopyBufferSubDataEXT, GLuint readBufferHandle, GLuint writeBufferHandle, GLintptr readOffsetPtr, GLintptr writeOffsetPtr, GLsizeiptr sizePtr); INSTANTIATE_FUNCTION_SERIALISED(void, glBindBufferBase, GLenum target, GLuint index, GLuint buffer); INSTANTIATE_FUNCTION_SERIALISED(void, glBindBufferRange, GLenum target, GLuint index, GLuint bufferHandle, GLintptr offsetPtr, GLsizeiptr sizePtr); INSTANTIATE_FUNCTION_SERIALISED(void, glBindBuffersBase, GLenum target, GLuint first, GLsizei count, const GLuint *bufferHandles); INSTANTIATE_FUNCTION_SERIALISED(void, glBindBuffersRange, GLenum target, GLuint first, GLsizei count, const GLuint *bufferHandles, const GLintptr *offsets, const GLsizeiptr *sizes); INSTANTIATE_FUNCTION_SERIALISED(void, glUnmapNamedBufferEXT, GLuint buffer); INSTANTIATE_FUNCTION_SERIALISED(void, glFlushMappedNamedBufferRangeEXT, GLuint buffer, GLintptr offset, GLsizeiptr length); INSTANTIATE_FUNCTION_SERIALISED(void, glGenTransformFeedbacks, GLsizei n, GLuint *ids); INSTANTIATE_FUNCTION_SERIALISED(void, glCreateTransformFeedbacks, GLsizei n, GLuint *ids); INSTANTIATE_FUNCTION_SERIALISED(void, glTransformFeedbackBufferBase, GLuint xfbHandle, GLuint index, GLuint bufferHandle); INSTANTIATE_FUNCTION_SERIALISED(void, glTransformFeedbackBufferRange, GLuint xfbHandle, GLuint index, GLuint bufferHandle, GLintptr offset, GLsizeiptr size); INSTANTIATE_FUNCTION_SERIALISED(void, glBindTransformFeedback, GLenum target, GLuint xfbHandle); INSTANTIATE_FUNCTION_SERIALISED(void, glBeginTransformFeedback, GLenum primitiveMode); INSTANTIATE_FUNCTION_SERIALISED(void, glPauseTransformFeedback); INSTANTIATE_FUNCTION_SERIALISED(void, glResumeTransformFeedback); INSTANTIATE_FUNCTION_SERIALISED(void, glEndTransformFeedback); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribOffsetEXT, GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLintptr offset); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribIOffsetEXT, GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribLOffsetEXT, GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr pointer); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribBindingEXT, GLuint vaobj, GLuint attribindex, GLuint bindingindex); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribFormatEXT, GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribIFormatEXT, GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribLFormatEXT, GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribDivisorEXT, GLuint vaobj, GLuint index, GLuint divisor); INSTANTIATE_FUNCTION_SERIALISED(void, glEnableVertexArrayAttribEXT, GLuint vaobj, GLuint index); INSTANTIATE_FUNCTION_SERIALISED(void, glDisableVertexArrayAttribEXT, GLuint vaobj, GLuint index); INSTANTIATE_FUNCTION_SERIALISED(void, glGenVertexArrays, GLsizei n, GLuint *arrays); INSTANTIATE_FUNCTION_SERIALISED(void, glCreateVertexArrays, GLsizei n, GLuint *arrays); INSTANTIATE_FUNCTION_SERIALISED(void, glBindVertexArray, GLuint arrayHandle); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayElementBuffer, GLuint vaobjHandle, GLuint bufferHandle); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayBindVertexBufferEXT, GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexBuffers, GLuint vaobjHandle, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexBindingDivisorEXT, GLuint vaobj, GLuint bindingindex, GLuint divisor); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexAttrib, GLuint index, int count, GLenum type, GLboolean normalized, const void *value, AttribType attribtype);
Java
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace PInvoke { using System; using System.Diagnostics.CodeAnalysis; using System.Text; using static Kernel32; /// <content> /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// </content> [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Functions are named like their native counterparts")] public static partial class Hid { public static Guid HidD_GetHidGuid() { Guid guid; HidD_GetHidGuid(out guid); return guid; } public static HiddAttributes HidD_GetAttributes(SafeObjectHandle hFile) { var result = HiddAttributes.Create(); if (!HidD_GetAttributes(hFile, ref result)) { throw new Win32Exception(); } return result; } public static SafePreparsedDataHandle HidD_GetPreparsedData(SafeObjectHandle hDevice) { SafePreparsedDataHandle preparsedDataHandle; if (!HidD_GetPreparsedData(hDevice, out preparsedDataHandle)) { throw new Win32Exception(); } return preparsedDataHandle; } public static HidpCaps HidP_GetCaps(SafePreparsedDataHandle preparsedData) { var hidCaps = default(HidpCaps); var result = HidP_GetCaps(preparsedData, ref hidCaps); switch (result.Value) { case NTSTATUS.Code.HIDP_STATUS_SUCCESS: return hidCaps; case NTSTATUS.Code.HIDP_STATUS_INVALID_PREPARSED_DATA: throw new ArgumentException("The specified preparsed data is invalid.", nameof(preparsedData)); default: result.ThrowOnError(); throw new InvalidOperationException("HidP_GetCaps returned an unexpected success value"); } } public static bool HidD_GetManufacturerString(SafeObjectHandle hidDeviceObject, out string result) { return GrowStringBuffer(sb => HidD_GetManufacturerString(hidDeviceObject, sb, sb.Capacity), out result); } public static bool HidD_GetProductString(SafeObjectHandle hidDeviceObject, out string result) { return GrowStringBuffer(sb => HidD_GetProductString(hidDeviceObject, sb, sb.Capacity), out result); } public static bool HidD_GetSerialNumberString(SafeObjectHandle hidDeviceObject, out string result) { return GrowStringBuffer(sb => HidD_GetSerialNumberString(hidDeviceObject, sb, sb.Capacity), out result); } public static string HidD_GetManufacturerString(SafeObjectHandle hidDeviceObject) { string result; if (!HidD_GetManufacturerString(hidDeviceObject, out result)) { throw new Win32Exception(); } return result; } public static string HidD_GetProductString(SafeObjectHandle hidDeviceObject) { string result; if (!HidD_GetProductString(hidDeviceObject, out result)) { throw new Win32Exception(); } return result; } public static string HidD_GetSerialNumberString(SafeObjectHandle hidDeviceObject) { string result; if (!HidD_GetSerialNumberString(hidDeviceObject, out result)) { throw new Win32Exception(); } return result; } private static bool GrowStringBuffer(Func<StringBuilder, bool> nativeMethod, out string result) { // USB Hid maximum size is 126 wide chars + '\0' = 254 bytes, allocating 256 bytes we should never grow // until another HID standard decide otherwise. var stringBuilder = new StringBuilder(256); // If we ever resize over this value something got really wrong const int maximumRealisticSize = 1 * 1024 * 2014; while (stringBuilder.Capacity < maximumRealisticSize) { if (nativeMethod(stringBuilder)) { result = stringBuilder.ToString(); return true; } if (GetLastError() != Win32ErrorCode.ERROR_INVALID_USER_BUFFER) { result = null; return false; } stringBuilder.Capacity = stringBuilder.Capacity * 2; } result = null; return false; } } }
Java
#!/bin/sh java -jar sprint0.jar
Java
var searchData= [ ['player',['player',['../classplayer.html#a4c43d838817775e2a2b0241d30de4abc',1,'player']]] ];
Java
// // Copyright (c) .NET Foundation and Contributors // See LICENSE file in the project root for full license information. // using System; namespace nanoFramework.Tools.Debugger.Usb { // This class is kept here for reference only. // It was to provide backwards compatibility with NETMF WinUSB devices of v4.4 // In the current nanoFramework implementation USB connection with devices is carried using USB CDC public class STM_Discovery4 { public const UInt16 DeviceVid = 0x0483; public const UInt16 DevicePid = 0xA08F; /// <summary> /// USB device interface class GUID. For NETMF debug capable devices this must be {D32D1D64-963D-463E-874A-8EC8C8082CBF}. /// </summary> public static Guid DeviceInterfaceClass = new Guid("{D32D1D64-963D-463E-874A-8EC8C8082CBF}"); /// <summary> /// ID string for the device /// </summary> public static String IDString { get { return String.Format("VID_{0:X4}&PID_{1:X4}", DeviceVid, DevicePid); } } public static new string ToString() { return "ST Discovery4"; } } }
Java
<?php return unserialize('a:1:{i:0;O:27:"Doctrine\\ORM\\Mapping\\Column":9:{s:4:"name";s:5:"parg4";s:4:"type";s:4:"text";s:6:"length";N;s:9:"precision";i:0;s:5:"scale";i:0;s:6:"unique";b:0;s:8:"nullable";b:1;s:7:"options";a:0:{}s:16:"columnDefinition";N;}}');
Java
Deprecated. Now with Docker-Compose, there is little reason for gobox. # gobox: Golang Process Boxer gobox manages your microservices for testing and production scenarios. ## Motivation **You**... - ...are building a large application with a service-oriented design. - ...have a variety of services that need to be running in order to execute integration tests. - ...really like docker, but due to frequent updates to your service layer, don't like the idea of having to constantly rebuild images. With gobox, you can define a set of processes *and* specify run commands that are to be used in `test` and `production` scenarios. Further, you can define the environment for each scenario at both the process- and global-level. ## Installation Use the Go tool: ``` go get github.com/tristanwietsma/gobox ``` ## Usage ```bash $ gobox -h Usage of gobox: -config=".gobox.toml": path to gobox config file -prod=false: run in production mode ``` ### Define a configuration file By default, gobox will look for a `.gobox.toml` file in the current working directory. Alternatively, you can specify the file location. ### Define global environment settings You can specify environment settings for both production and testing using the `prodenviron` and `testenviron` parameters. ``` prodenviron = ["VAR1=VAL1", "VAR2=VAL2"] testenviron = ["VAR1=X", "VAR2=Z"] ``` ### Define each processes For each process, define a `proc` block in the toml file. A `proc` definition looks like this: ``` [[proc]] name = "name of the process" priority = 1 prodcommand = "shell command for production use" prodenviron = ["NAME=prod1"] testcommand = "shell command for test use" testenviron = ["NAME=test1"] ``` #### Name `name` is purely for logging purposes. #### Priority `priority` is an integer the defines the order in which the process should be started relative to other processes in the configuration. Lower numbers have higher priority. ### Running Test Mode Test mode is the default. Assuming the config file is `.gobox.toml` in the current directory, ```bash $ gobox ``` ### Running Production Mode ```bash $ gobox -prod=true ``` ### Stopping gobox listens for kill signals and shuts down processes before exiting.
Java
/* dtpicker javascript jQuery */ (function($) { // 严格模式 'use strict'; // 控件类名 var pluginName = 'dtpicker'; var PluginClass=T.UI.Controls.DTPicker; var pluginRef = 't-plugin-ref'; // 胶水代码 $.fn[pluginName] = function(options) { if(typeof options === 'string'){ // 2. 调用API var plugin = this.data(pluginRef); if(!plugin || !plugin[options]){ throw '方法 ' + options + ' 不存在'; } var result = plugin[options].apply(plugin, Array.prototype.slice.call(arguments, 1)); if(options === 'destroy'){ jqElement.removeData(pluginRef); } return result; } this.each(function () { var jqElement=$(this); var plugin = jqElement.data(pluginRef); if(plugin === undefined){ // 1. 创建新对象 plugin=new PluginClass(this, $.extend(true, {}, options)); jqElement.data(pluginRef, plugin); } else{ // 3. 更新选项 plugin.updateOptions || plugin.updateOptions(options); } }); return this; }; })(jQuery); // (function($) { // // 'use strict'; // var dateTimePicker = function (element, options) { // /******************************************************************************** // * // * Public API functions // * ===================== // * // * Important: Do not expose direct references to private objects or the options // * object to the outer world. Always return a clone when returning values or make // * a clone when setting a private variable. // * // ********************************************************************************/ // picker.toggle = toggle; // picker.show = show; // picker.hide = hide; // picker.ignoreReadonly = function (ignoreReadonly) { // if (arguments.length === 0) { // return options.ignoreReadonly; // } // if (typeof ignoreReadonly !== 'boolean') { // throw new TypeError('ignoreReadonly () expects a boolean parameter'); // } // options.ignoreReadonly = ignoreReadonly; // return picker; // }; // picker.options = function (newOptions) { // if (arguments.length === 0) { // return $.extend(true, {}, options); // } // if (!(newOptions instanceof Object)) { // throw new TypeError('options() options parameter should be an object'); // } // $.extend(true, options, newOptions); // $.each(options, function (key, value) { // if (picker[key] !== undefined) { // picker[key](value); // } else { // throw new TypeError('option ' + key + ' is not recognized!'); // } // }); // return picker; // }; // picker.date = function (newDate) { // ///<signature helpKeyword="$.fn.datetimepicker.date"> // ///<summary>Returns the component's model current date, a moment object or null if not set.</summary> // ///<returns type="Moment">date.clone()</returns> // ///</signature> // ///<signature> // ///<summary>Sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration.</summary> // ///<param name="newDate" locid="$.fn.datetimepicker.date_p:newDate">Takes string, Date, moment, null parameter.</param> // ///</signature> // if (arguments.length === 0) { // if (unset) { // return null; // } // return date.clone(); // } // if (newDate !== null && typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) { // throw new TypeError('date() parameter must be one of [null, string, moment or Date]'); // } // setValue(newDate === null ? null : parseInputDate(newDate)); // return picker; // }; // picker.format = function (newFormat) { // ///<summary>test su</summary> // ///<param name="newFormat">info about para</param> // ///<returns type="string|boolean">returns foo</returns> // if (arguments.length === 0) { // return options.format; // } // if ((typeof newFormat !== 'string') && ((typeof newFormat !== 'boolean') || (newFormat !== false))) { // throw new TypeError('format() expects a sting or boolean:false parameter ' + newFormat); // } // options.format = newFormat; // if (actualFormat) { // initFormatting(); // reinit formatting // } // return picker; // }; // picker.timeZone = function (newZone) { // if (arguments.length === 0) { // return options.timeZone; // } // options.timeZone = newZone; // return picker; // }; // picker.dayViewHeaderFormat = function (newFormat) { // if (arguments.length === 0) { // return options.dayViewHeaderFormat; // } // if (typeof newFormat !== 'string') { // throw new TypeError('dayViewHeaderFormat() expects a string parameter'); // } // options.dayViewHeaderFormat = newFormat; // return picker; // }; // picker.extraFormats = function (formats) { // if (arguments.length === 0) { // return options.extraFormats; // } // if (formats !== false && !(formats instanceof Array)) { // throw new TypeError('extraFormats() expects an array or false parameter'); // } // options.extraFormats = formats; // if (parseFormats) { // initFormatting(); // reinit formatting // } // return picker; // }; // picker.disabledDates = function (dates) { // ///<signature helpKeyword="$.fn.datetimepicker.disabledDates"> // ///<summary>Returns an array with the currently set disabled dates on the component.</summary> // ///<returns type="array">options.disabledDates</returns> // ///</signature> // ///<signature> // ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of // ///options.enabledDates if such exist.</summary> // ///<param name="dates" locid="$.fn.datetimepicker.disabledDates_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param> // ///</signature> // if (arguments.length === 0) { // return (options.disabledDates ? $.extend({}, options.disabledDates) : options.disabledDates); // } // if (!dates) { // options.disabledDates = false; // update(); // return picker; // } // if (!(dates instanceof Array)) { // throw new TypeError('disabledDates() expects an array parameter'); // } // options.disabledDates = indexGivenDates(dates); // options.enabledDates = false; // update(); // return picker; // }; // picker.enabledDates = function (dates) { // ///<signature helpKeyword="$.fn.datetimepicker.enabledDates"> // ///<summary>Returns an array with the currently set enabled dates on the component.</summary> // ///<returns type="array">options.enabledDates</returns> // ///</signature> // ///<signature> // ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledDates if such exist.</summary> // ///<param name="dates" locid="$.fn.datetimepicker.enabledDates_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param> // ///</signature> // if (arguments.length === 0) { // return (options.enabledDates ? $.extend({}, options.enabledDates) : options.enabledDates); // } // if (!dates) { // options.enabledDates = false; // update(); // return picker; // } // if (!(dates instanceof Array)) { // throw new TypeError('enabledDates() expects an array parameter'); // } // options.enabledDates = indexGivenDates(dates); // options.disabledDates = false; // update(); // return picker; // }; // picker.daysOfWeekDisabled = function (daysOfWeekDisabled) { // if (arguments.length === 0) { // return options.daysOfWeekDisabled.splice(0); // } // if ((typeof daysOfWeekDisabled === 'boolean') && !daysOfWeekDisabled) { // options.daysOfWeekDisabled = false; // update(); // return picker; // } // if (!(daysOfWeekDisabled instanceof Array)) { // throw new TypeError('daysOfWeekDisabled() expects an array parameter'); // } // options.daysOfWeekDisabled = daysOfWeekDisabled.reduce(function (previousValue, currentValue) { // currentValue = parseInt(currentValue, 10); // if (currentValue > 6 || currentValue < 0 || isNaN(currentValue)) { // return previousValue; // } // if (previousValue.indexOf(currentValue) === -1) { // previousValue.push(currentValue); // } // return previousValue; // }, []).sort(); // if (options.useCurrent && !options.keepInvalid) { // var tries = 0; // while (!isValid(date, 'd')) { // date.add(1, 'd'); // if (tries === 7) { // throw 'Tried 7 times to find a valid date'; // } // tries++; // } // setValue(date); // } // update(); // return picker; // }; // picker.maxDate = function (maxDate) { // if (arguments.length === 0) { // return options.maxDate ? options.maxDate.clone() : options.maxDate; // } // if ((typeof maxDate === 'boolean') && maxDate === false) { // options.maxDate = false; // update(); // return picker; // } // if (typeof maxDate === 'string') { // if (maxDate === 'now' || maxDate === 'moment') { // maxDate = getMoment(); // } // } // var parsedDate = parseInputDate(maxDate); // if (!parsedDate.isValid()) { // throw new TypeError('maxDate() Could not parse date parameter: ' + maxDate); // } // if (options.minDate && parsedDate.isBefore(options.minDate)) { // throw new TypeError('maxDate() date parameter is before options.minDate: ' + parsedDate.format(actualFormat)); // } // options.maxDate = parsedDate; // if (options.useCurrent && !options.keepInvalid && date.isAfter(maxDate)) { // setValue(options.maxDate); // } // if (viewDate.isAfter(parsedDate)) { // viewDate = parsedDate.clone().subtract(options.stepping, 'm'); // } // update(); // return picker; // }; // picker.minDate = function (minDate) { // if (arguments.length === 0) { // return options.minDate ? options.minDate.clone() : options.minDate; // } // if ((typeof minDate === 'boolean') && minDate === false) { // options.minDate = false; // update(); // return picker; // } // if (typeof minDate === 'string') { // if (minDate === 'now' || minDate === 'moment') { // minDate = getMoment(); // } // } // var parsedDate = parseInputDate(minDate); // if (!parsedDate.isValid()) { // throw new TypeError('minDate() Could not parse date parameter: ' + minDate); // } // if (options.maxDate && parsedDate.isAfter(options.maxDate)) { // throw new TypeError('minDate() date parameter is after options.maxDate: ' + parsedDate.format(actualFormat)); // } // options.minDate = parsedDate; // if (options.useCurrent && !options.keepInvalid && date.isBefore(minDate)) { // setValue(options.minDate); // } // if (viewDate.isBefore(parsedDate)) { // viewDate = parsedDate.clone().add(options.stepping, 'm'); // } // update(); // return picker; // }; // picker.defaultDate = function (defaultDate) { // ///<signature helpKeyword="$.fn.datetimepicker.defaultDate"> // ///<summary>Returns a moment with the options.defaultDate option configuration or false if not set</summary> // ///<returns type="Moment">date.clone()</returns> // ///</signature> // ///<signature> // ///<summary>Will set the picker's inital date. If a boolean:false value is passed the options.defaultDate parameter is cleared.</summary> // ///<param name="defaultDate" locid="$.fn.datetimepicker.defaultDate_p:defaultDate">Takes a string, Date, moment, boolean:false</param> // ///</signature> // if (arguments.length === 0) { // return options.defaultDate ? options.defaultDate.clone() : options.defaultDate; // } // if (!defaultDate) { // options.defaultDate = false; // return picker; // } // if (typeof defaultDate === 'string') { // if (defaultDate === 'now' || defaultDate === 'moment') { // defaultDate = getMoment(); // } // } // var parsedDate = parseInputDate(defaultDate); // if (!parsedDate.isValid()) { // throw new TypeError('defaultDate() Could not parse date parameter: ' + defaultDate); // } // if (!isValid(parsedDate)) { // throw new TypeError('defaultDate() date passed is invalid according to component setup validations'); // } // options.defaultDate = parsedDate; // if ((options.defaultDate && options.inline) || input.val().trim() === '') { // setValue(options.defaultDate); // } // return picker; // }; // picker.locale = function (locale) { // if (arguments.length === 0) { // return options.locale; // } // if (!moment.localeData(locale)) { // throw new TypeError('locale() locale ' + locale + ' is not loaded from moment locales!'); // } // options.locale = locale; // date.locale(options.locale); // viewDate.locale(options.locale); // if (actualFormat) { // initFormatting(); // reinit formatting // } // if (widget) { // hide(); // show(); // } // return picker; // }; // picker.stepping = function (stepping) { // if (arguments.length === 0) { // return options.stepping; // } // stepping = parseInt(stepping, 10); // if (isNaN(stepping) || stepping < 1) { // stepping = 1; // } // options.stepping = stepping; // return picker; // }; // picker.useCurrent = function (useCurrent) { // var useCurrentOptions = ['year', 'month', 'day', 'hour', 'minute']; // if (arguments.length === 0) { // return options.useCurrent; // } // if ((typeof useCurrent !== 'boolean') && (typeof useCurrent !== 'string')) { // throw new TypeError('useCurrent() expects a boolean or string parameter'); // } // if (typeof useCurrent === 'string' && useCurrentOptions.indexOf(useCurrent.toLowerCase()) === -1) { // throw new TypeError('useCurrent() expects a string parameter of ' + useCurrentOptions.join(', ')); // } // options.useCurrent = useCurrent; // return picker; // }; // picker.collapse = function (collapse) { // if (arguments.length === 0) { // return options.collapse; // } // if (typeof collapse !== 'boolean') { // throw new TypeError('collapse() expects a boolean parameter'); // } // if (options.collapse === collapse) { // return picker; // } // options.collapse = collapse; // if (widget) { // hide(); // show(); // } // return picker; // }; // picker.icons = function (icons) { // if (arguments.length === 0) { // return $.extend({}, options.icons); // } // if (!(icons instanceof Object)) { // throw new TypeError('icons() expects parameter to be an Object'); // } // $.extend(options.icons, icons); // if (widget) { // hide(); // show(); // } // return picker; // }; // picker.tooltips = function (tooltips) { // if (arguments.length === 0) { // return $.extend({}, options.tooltips); // } // if (!(tooltips instanceof Object)) { // throw new TypeError('tooltips() expects parameter to be an Object'); // } // $.extend(options.tooltips, tooltips); // if (widget) { // hide(); // show(); // } // return picker; // }; // picker.useStrict = function (useStrict) { // if (arguments.length === 0) { // return options.useStrict; // } // if (typeof useStrict !== 'boolean') { // throw new TypeError('useStrict() expects a boolean parameter'); // } // options.useStrict = useStrict; // return picker; // }; // picker.sideBySide = function (sideBySide) { // if (arguments.length === 0) { // return options.sideBySide; // } // if (typeof sideBySide !== 'boolean') { // throw new TypeError('sideBySide() expects a boolean parameter'); // } // options.sideBySide = sideBySide; // if (widget) { // hide(); // show(); // } // return picker; // }; // picker.viewMode = function (viewMode) { // if (arguments.length === 0) { // return options.viewMode; // } // if (typeof viewMode !== 'string') { // throw new TypeError('viewMode() expects a string parameter'); // } // if (viewModes.indexOf(viewMode) === -1) { // throw new TypeError('viewMode() parameter must be one of (' + viewModes.join(', ') + ') value'); // } // options.viewMode = viewMode; // currentViewMode = Math.max(viewModes.indexOf(viewMode), minViewModeNumber); // showMode(); // return picker; // }; // picker.toolbarPlacement = function (toolbarPlacement) { // if (arguments.length === 0) { // return options.toolbarPlacement; // } // if (typeof toolbarPlacement !== 'string') { // throw new TypeError('toolbarPlacement() expects a string parameter'); // } // if (toolbarPlacements.indexOf(toolbarPlacement) === -1) { // throw new TypeError('toolbarPlacement() parameter must be one of (' + toolbarPlacements.join(', ') + ') value'); // } // options.toolbarPlacement = toolbarPlacement; // if (widget) { // hide(); // show(); // } // return picker; // }; // picker.widgetPositioning = function (widgetPositioning) { // if (arguments.length === 0) { // return $.extend({}, options.widgetPositioning); // } // if (({}).toString.call(widgetPositioning) !== '[object Object]') { // throw new TypeError('widgetPositioning() expects an object variable'); // } // if (widgetPositioning.horizontal) { // if (typeof widgetPositioning.horizontal !== 'string') { // throw new TypeError('widgetPositioning() horizontal variable must be a string'); // } // widgetPositioning.horizontal = widgetPositioning.horizontal.toLowerCase(); // if (horizontalModes.indexOf(widgetPositioning.horizontal) === -1) { // throw new TypeError('widgetPositioning() expects horizontal parameter to be one of (' + horizontalModes.join(', ') + ')'); // } // options.widgetPositioning.horizontal = widgetPositioning.horizontal; // } // if (widgetPositioning.vertical) { // if (typeof widgetPositioning.vertical !== 'string') { // throw new TypeError('widgetPositioning() vertical variable must be a string'); // } // widgetPositioning.vertical = widgetPositioning.vertical.toLowerCase(); // if (verticalModes.indexOf(widgetPositioning.vertical) === -1) { // throw new TypeError('widgetPositioning() expects vertical parameter to be one of (' + verticalModes.join(', ') + ')'); // } // options.widgetPositioning.vertical = widgetPositioning.vertical; // } // update(); // return picker; // }; // picker.calendarWeeks = function (calendarWeeks) { // if (arguments.length === 0) { // return options.calendarWeeks; // } // if (typeof calendarWeeks !== 'boolean') { // throw new TypeError('calendarWeeks() expects parameter to be a boolean value'); // } // options.calendarWeeks = calendarWeeks; // update(); // return picker; // }; // picker.showTodayButton = function (showTodayButton) { // if (arguments.length === 0) { // return options.showTodayButton; // } // if (typeof showTodayButton !== 'boolean') { // throw new TypeError('showTodayButton() expects a boolean parameter'); // } // options.showTodayButton = showTodayButton; // if (widget) { // hide(); // show(); // } // return picker; // }; // picker.showClear = function (showClear) { // if (arguments.length === 0) { // return options.showClear; // } // if (typeof showClear !== 'boolean') { // throw new TypeError('showClear() expects a boolean parameter'); // } // options.showClear = showClear; // if (widget) { // hide(); // show(); // } // return picker; // }; // picker.widgetParent = function (widgetParent) { // if (arguments.length === 0) { // return options.widgetParent; // } // if (typeof widgetParent === 'string') { // widgetParent = $(widgetParent); // } // if (widgetParent !== null && (typeof widgetParent !== 'string' && !(widgetParent instanceof $))) { // throw new TypeError('widgetParent() expects a string or a jQuery object parameter'); // } // options.widgetParent = widgetParent; // if (widget) { // hide(); // show(); // } // return picker; // }; // picker.keepOpen = function (keepOpen) { // if (arguments.length === 0) { // return options.keepOpen; // } // if (typeof keepOpen !== 'boolean') { // throw new TypeError('keepOpen() expects a boolean parameter'); // } // options.keepOpen = keepOpen; // return picker; // }; // picker.focusOnShow = function (focusOnShow) { // if (arguments.length === 0) { // return options.focusOnShow; // } // if (typeof focusOnShow !== 'boolean') { // throw new TypeError('focusOnShow() expects a boolean parameter'); // } // options.focusOnShow = focusOnShow; // return picker; // }; // picker.inline = function (inline) { // if (arguments.length === 0) { // return options.inline; // } // if (typeof inline !== 'boolean') { // throw new TypeError('inline() expects a boolean parameter'); // } // options.inline = inline; // return picker; // }; // picker.clear = function () { // clear(); // return picker; // }; // picker.keyBinds = function (keyBinds) { // options.keyBinds = keyBinds; // return picker; // }; // picker.getMoment = function (d) { // return this.getMoment(d); // }; // picker.debug = function (debug) { // if (typeof debug !== 'boolean') { // throw new TypeError('debug() expects a boolean parameter'); // } // options.debug = debug; // return picker; // }; // picker.allowInputToggle = function (allowInputToggle) { // if (arguments.length === 0) { // return options.allowInputToggle; // } // if (typeof allowInputToggle !== 'boolean') { // throw new TypeError('allowInputToggle() expects a boolean parameter'); // } // options.allowInputToggle = allowInputToggle; // return picker; // }; // picker.showClose = function (showClose) { // if (arguments.length === 0) { // return options.showClose; // } // if (typeof showClose !== 'boolean') { // throw new TypeError('showClose() expects a boolean parameter'); // } // options.showClose = showClose; // return picker; // }; // picker.keepInvalid = function (keepInvalid) { // if (arguments.length === 0) { // return options.keepInvalid; // } // if (typeof keepInvalid !== 'boolean') { // throw new TypeError('keepInvalid() expects a boolean parameter'); // } // options.keepInvalid = keepInvalid; // return picker; // }; // picker.datepickerInput = function (datepickerInput) { // if (arguments.length === 0) { // return options.datepickerInput; // } // if (typeof datepickerInput !== 'string') { // throw new TypeError('datepickerInput() expects a string parameter'); // } // options.datepickerInput = datepickerInput; // return picker; // }; // picker.parseInputDate = function (parseInputDate) { // if (arguments.length === 0) { // return options.parseInputDate; // } // if (typeof parseInputDate !== 'function') { // throw new TypeError('parseInputDate() sholud be as function'); // } // options.parseInputDate = parseInputDate; // return picker; // }; // picker.disabledTimeIntervals = function (disabledTimeIntervals) { // ///<signature helpKeyword="$.fn.datetimepicker.disabledTimeIntervals"> // ///<summary>Returns an array with the currently set disabled dates on the component.</summary> // ///<returns type="array">options.disabledTimeIntervals</returns> // ///</signature> // ///<signature> // ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of // ///options.enabledDates if such exist.</summary> // ///<param name="dates" locid="$.fn.datetimepicker.disabledTimeIntervals_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param> // ///</signature> // if (arguments.length === 0) { // return (options.disabledTimeIntervals ? $.extend({}, options.disabledTimeIntervals) : options.disabledTimeIntervals); // } // if (!disabledTimeIntervals) { // options.disabledTimeIntervals = false; // update(); // return picker; // } // if (!(disabledTimeIntervals instanceof Array)) { // throw new TypeError('disabledTimeIntervals() expects an array parameter'); // } // options.disabledTimeIntervals = disabledTimeIntervals; // update(); // return picker; // }; // picker.disabledHours = function (hours) { // ///<signature helpKeyword="$.fn.datetimepicker.disabledHours"> // ///<summary>Returns an array with the currently set disabled hours on the component.</summary> // ///<returns type="array">options.disabledHours</returns> // ///</signature> // ///<signature> // ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of // ///options.enabledHours if such exist.</summary> // ///<param name="hours" locid="$.fn.datetimepicker.disabledHours_p:hours">Takes an [ int ] of values and disallows the user to select only from those hours.</param> // ///</signature> // if (arguments.length === 0) { // return (options.disabledHours ? $.extend({}, options.disabledHours) : options.disabledHours); // } // if (!hours) { // options.disabledHours = false; // update(); // return picker; // } // if (!(hours instanceof Array)) { // throw new TypeError('disabledHours() expects an array parameter'); // } // options.disabledHours = indexGivenHours(hours); // options.enabledHours = false; // if (options.useCurrent && !options.keepInvalid) { // var tries = 0; // while (!isValid(date, 'h')) { // date.add(1, 'h'); // if (tries === 24) { // throw 'Tried 24 times to find a valid date'; // } // tries++; // } // setValue(date); // } // update(); // return picker; // }; // picker.enabledHours = function (hours) { // ///<signature helpKeyword="$.fn.datetimepicker.enabledHours"> // ///<summary>Returns an array with the currently set enabled hours on the component.</summary> // ///<returns type="array">options.enabledHours</returns> // ///</signature> // ///<signature> // ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledHours if such exist.</summary> // ///<param name="hours" locid="$.fn.datetimepicker.enabledHours_p:hours">Takes an [ int ] of values and allows the user to select only from those hours.</param> // ///</signature> // if (arguments.length === 0) { // return (options.enabledHours ? $.extend({}, options.enabledHours) : options.enabledHours); // } // if (!hours) { // options.enabledHours = false; // update(); // return picker; // } // if (!(hours instanceof Array)) { // throw new TypeError('enabledHours() expects an array parameter'); // } // options.enabledHours = indexGivenHours(hours); // options.disabledHours = false; // if (options.useCurrent && !options.keepInvalid) { // var tries = 0; // while (!isValid(date, 'h')) { // date.add(1, 'h'); // if (tries === 24) { // throw 'Tried 24 times to find a valid date'; // } // tries++; // } // setValue(date); // } // update(); // return picker; // }; // picker.viewDate = function (newDate) { // ///<signature helpKeyword="$.fn.datetimepicker.viewDate"> // ///<summary>Returns the component's model current viewDate, a moment object or null if not set.</summary> // ///<returns type="Moment">viewDate.clone()</returns> // ///</signature> // ///<signature> // ///<summary>Sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration.</summary> // ///<param name="newDate" locid="$.fn.datetimepicker.date_p:newDate">Takes string, viewDate, moment, null parameter.</param> // ///</signature> // if (arguments.length === 0) { // return viewDate.clone(); // } // if (!newDate) { // viewDate = date.clone(); // return picker; // } // if (typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) { // throw new TypeError('viewDate() parameter must be one of [string, moment or Date]'); // } // viewDate = parseInputDate(newDate); // viewUpdate(); // return picker; // }; // }; // })(jQuery);
Java
using RippleCommonUtilities; using RippleDictionary; using RippleScreenApp.Utilities; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.IO; using System.Linq; using System.Reflection; using System.Speech.Synthesis; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace RippleScreenApp { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class ScreenWindow : Window { internal static RippleDictionary.Ripple rippleData; private static TextBlock tbElement = new TextBlock(); private static TextBlock fullScreenTbElement = new TextBlock(); private static Image imgElement = new Image(); private static Image fullScreenImgElement = new Image(); private static String currentVideoURI = String.Empty; private static RippleDictionary.ContentType currentScreenContent = ContentType.Nothing; private static bool loopVideo = false; private BackgroundWorker myBackgroundWorker; private BackgroundWorker pptWorker; Utilities.ScriptingHelper helper; public System.Windows.Forms.Integration.WindowsFormsHost host; public System.Windows.Forms.WebBrowser browserElement; internal static String personName; private long prevRow; private Tile currentTile = null; private bool StartVideoPlayed = false; public static String sessionGuid = String.Empty; public ScreenWindow() { try { InitializeComponent(); LoadData(); SetObjectProperties(); //Start receiving messages Utilities.MessageReceiver.StartReceivingMessages(this); } catch (Exception ex) { //Exit and do nothing RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Screen {0}", ex.Message); } } private void Window_Loaded(object sender, RoutedEventArgs e) { try { this.WindowState = System.Windows.WindowState.Maximized; ResetUI(); } catch (Exception ex) { RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Window Loaded {0}", ex.Message); } } private void SetObjectProperties() { //Initialize video properties this.IntroVideoControl.Source = new Uri(Helper.GetAssetURI(rippleData.Screen.ScreenContents["IntroVideo"].Content)); this.IntroVideoControl.ScrubbingEnabled = true; //Set image elements properties imgElement.Stretch = Stretch.Fill; fullScreenImgElement.Stretch = Stretch.Fill; //Set text block properties tbElement.FontSize = 50; tbElement.Margin = new Thickness(120, 120, 120, 0); tbElement.TextWrapping = TextWrapping.Wrap; fullScreenTbElement.FontSize = 50; fullScreenTbElement.Margin = new Thickness(120, 120, 120, 0); fullScreenTbElement.TextWrapping = TextWrapping.Wrap; } /// <summary> /// Method that loads the configured data for the Screen, right now the Source is XML /// </summary> private void LoadData() { try { //Loads the local dictionary data from the configuration XML rippleData = RippleDictionary.Dictionary.GetRipple(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)); } catch (Exception ex) { RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Load Data for Screen {0}", ex.Message); throw; } } /// <summary> /// Resets the UI to System locked mode. /// </summary> private void ResetUI() { try { Globals.ResetGlobals(); currentVideoURI = String.Empty; currentScreenContent = ContentType.Nothing; loopVideo = false; StartVideoPlayed = false; sessionGuid = String.Empty; //Pick up content based on the "LockScreen" ID ProjectContent(rippleData.Screen.ScreenContents["LockScreen"]); //Commit the telemetry data Utilities.TelemetryWriter.CommitTelemetryAsync(); } catch (Exception ex) { //Do nothing RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Reset UI for Screen {0}", ex.Message); } } /// <summary> /// Code will receive messages from the floor /// Invoke appropriate content projection based on the tile ID passed /// </summary> /// <param name="val"></param> public void OnMessageReceived(string val) { try { //Check for reset if (val.Equals("Reset")) { //Update the previous entry Utilities.TelemetryWriter.UpdatePreviousEntry(); //Reset the system ResetUI(); } //Check for System start //Check for System start else if (val.StartsWith("System Start")) { //Load the telemetry Data Utilities.TelemetryWriter.RetrieveTelemetryData(); //The floor has asked the screen to start the system //Get the User Name Globals.UserName = val.Split(':')[1]; //Get the person identity for the session personName = String.IsNullOrEmpty(Globals.UserName) ? Convert.ToString(Guid.NewGuid()) : Globals.UserName; Utilities.TelemetryWriter.AddTelemetryRow(rippleData.Floor.SetupID, personName, "Unlock", val, "Unlock"); //Set the system state Globals.currentAppState = RippleSystemStates.UserDetected; //Play the Intro Content ProjectIntroContent(rippleData.Screen.ScreenContents["IntroVideo"]); } //Check for gestures else if (val.StartsWith("Gesture")) { OnGestureInput(val.Split(':')[1]); } //Check for HTMl messages else if (val.StartsWith("HTML")) { OnHTMLMessagesReceived(val.Split(':')[1]); } //Check for options- TODO need to figure out else if (val.StartsWith("Option")) { //Do nothing } //Check if a content - tile mapping or in general content tag exists else { if (rippleData.Screen.ScreenContents.ContainsKey(val) && rippleData.Screen.ScreenContents[val].Type != ContentType.Nothing) { //Set the system state Globals.currentAppState = RippleSystemStates.OptionSelected; ProjectContent(rippleData.Screen.ScreenContents[val]); RippleCommonUtilities.LoggingHelper.LogTrace(1, "In Message Received {0} {1}:{2}", Utilities.TelemetryWriter.telemetryData.Tables[0].Rows.Count, Utilities.TelemetryWriter.telemetryData.Tables[0].Rows[Utilities.TelemetryWriter.telemetryData.Tables[0].Rows.Count - 1].ItemArray[6], DateTime.Now); //Update the end time for the previous Utilities.TelemetryWriter.UpdatePreviousEntry(); //Insert the new entry Utilities.TelemetryWriter.AddTelemetryRow(rippleData.Floor.SetupID, personName, ((currentTile = GetFloorTileForID(val))==null)?"Unknown":currentTile.Name, val, (val == "Tile0") ? "Start" : "Option"); } else { //Stop any existing projections DocumentPresentation.HelperMethods.StopPresentation(); FullScreenContentGrid.Children.Clear(); ContentGrid.Children.Clear(); //Set focus for screen window also Utilities.Helper.ClickOnScreenToGetFocus(); //Stop any existing videos loopVideo = false; VideoControl.Source = null; FullScreenVideoControl.Source = null; //Clean the images fullScreenImgElement.Source = null; imgElement.Source = null; //Clear the header text TitleLabel.Text = ""; //Dispose the objects if(browserElement != null) browserElement.Dispose(); browserElement = null; if (host != null) host.Dispose(); host = null; if (helper != null) helper.PropertyChanged -= helper_PropertyChanged; helper = null; currentScreenContent = ContentType.Nothing; ShowText("No content available for this option, Please try some other tile option", "No Content"); } } } catch (Exception ex) { //Do nothing RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in On message received for Screen {0}", ex.Message); } } private void OnHTMLMessagesReceived(string p) { try { if(p.StartsWith("SessionID,")) { sessionGuid = p; return; } if (helper != null && currentScreenContent == ContentType.HTML) { helper.MessageReceived(p); } } catch (Exception ex) { //Do nothing RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in OnHTMLMessagesReceived received for Screen {0}", ex.Message); } } private void OnGestureInput(string inputGesture) { try { //PPT Mode - left and right swipe if (inputGesture == GestureTypes.LeftSwipe.ToString() && currentScreenContent == ContentType.PPT) { //Acts as previous DocumentPresentation.HelperMethods.GotoPrevious(); } else if (inputGesture == GestureTypes.RightSwipe.ToString() && currentScreenContent == ContentType.PPT) { //Check again, Means the presentation ended on clicking next if (!DocumentPresentation.HelperMethods.HasPresentationStarted()) { //Change the screen //ShowText("Your presentation has ended, Select some other option", "Select some other option"); ShowImage(@"\Assets\Images\pptend.png", "Presentation Ended"); //Set focus for screen window also Utilities.Helper.ClickOnScreenToGetFocus(); } //Acts as next DocumentPresentation.HelperMethods.GotoNext(); //Check again, Means the presentation ended on clicking next if (!DocumentPresentation.HelperMethods.HasPresentationStarted()) { //Change the screen text //ShowText("Your presentation has ended, Select some other option", "Select some other option"); ShowImage(@"\Assets\Images\pptend.png", "Presentation Ended"); //Set focus for screen window also Utilities.Helper.ClickOnScreenToGetFocus(); } } //Browser mode else if (currentScreenContent == ContentType.HTML) { OnHTMLMessagesReceived(inputGesture.ToString()); } //Set focus for screen window also //Utilities.Helper.ClickOnScreenToGetFocus(); } catch (Exception ex) { //Do nothing RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in OnGestureInput received for Screen {0}", ex.Message); } } #region Content Projection methods /// <summary> /// Identifies the content type and project accordingly /// </summary> /// <param name="screenContent"></param> private void ProjectContent(RippleDictionary.ScreenContent screenContent) { try { if (screenContent.Type == ContentType.HTMLMessage) { if (helper != null && currentScreenContent == ContentType.HTML) { helper.MessageReceived(screenContent.Content); return; } } //Stop any existing projections DocumentPresentation.HelperMethods.StopPresentation(); FullScreenContentGrid.Children.Clear(); ContentGrid.Children.Clear(); //Set focus for screen window also Utilities.Helper.ClickOnScreenToGetFocus(); //Stop any existing videos loopVideo = false; VideoControl.Source = null; FullScreenVideoControl.Source = null; //Clean the images fullScreenImgElement.Source = null; imgElement.Source = null; //Clear the header text TitleLabel.Text = ""; //Dispose the objects if (browserElement != null) browserElement.Dispose(); browserElement = null; if (host != null) host.Dispose(); host = null; if (helper != null) helper.PropertyChanged -= helper_PropertyChanged; helper = null; currentScreenContent = screenContent.Type; if (screenContent.Id == "Tile0" && StartVideoPlayed) { currentScreenContent = ContentType.Image; ShowImage("\\Assets\\Images\\default_start.png", screenContent.Header); return; } switch (screenContent.Type) { case RippleDictionary.ContentType.HTML: ShowBrowser(screenContent.Content, screenContent.Header); break; case RippleDictionary.ContentType.Image: ShowImage(screenContent.Content, screenContent.Header); break; case RippleDictionary.ContentType.PPT: ShowPPT(screenContent.Content, screenContent.Header); break; case RippleDictionary.ContentType.Text: ShowText(screenContent.Content, screenContent.Header); break; case RippleDictionary.ContentType.Video: loopVideo = (screenContent.LoopVideo == null) ? false : Convert.ToBoolean(screenContent.LoopVideo); if (screenContent.Id == "Tile0") StartVideoPlayed = true; ShowVideo(screenContent.Content, screenContent.Header); break; } } catch (Exception ex) { RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in ProjectContent Method for screen {0}", ex.Message); } } private void ProjectIntroContent(RippleDictionary.ScreenContent screenContent) { try { //Dispose the previous content //Stop any existing projections DocumentPresentation.HelperMethods.StopPresentation(); FullScreenContentGrid.Children.Clear(); ContentGrid.Children.Clear(); //Set focus for screen window also Utilities.Helper.ClickOnScreenToGetFocus(); //Stop any existing videos loopVideo = false; VideoControl.Source = null; FullScreenVideoControl.Source = null; //Clean the images fullScreenImgElement.Source = null; imgElement.Source = null; //Clear the header text TitleLabel.Text = ""; if (browserElement != null) browserElement.Dispose(); browserElement = null; if (host != null) host.Dispose(); host = null; if (helper != null) helper.PropertyChanged -= helper_PropertyChanged; helper = null; //Play the Intro video this.TitleLabel.Text = ""; ContentGrid.Visibility = Visibility.Collapsed; FullScreenContentGrid.Visibility = Visibility.Collapsed; FullScreenVideoGrid.Visibility = Visibility.Collapsed; IntroVideoControl.Visibility = Visibility.Visible; VideoControl.Visibility = Visibility.Collapsed; VideoGrid.Visibility = Visibility.Visible; IntroVideoControl.Play(); this.UpdateLayout(); myBackgroundWorker = new BackgroundWorker(); myBackgroundWorker.DoWork += myBackgroundWorker_DoWork; myBackgroundWorker.RunWorkerCompleted += myBackgroundWorker_RunWorkerCompleted; myBackgroundWorker.RunWorkerAsync(rippleData.Floor.Start.IntroVideoWaitPeriod); } catch (Exception ex) { RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in ProjectIntroContent Method for screen {0}", ex.Message); } } private void myBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //System has been started, it just finished playing the intro video if (Globals.currentAppState == RippleSystemStates.UserDetected) { this.IntroVideoControl.Stop(); //this.IntroVideoControl.Source = null; this.IntroVideoControl.Visibility = System.Windows.Visibility.Collapsed; ShowGotoStartContent(); } } private void myBackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { System.Threading.Thread.Sleep(Convert.ToInt16(e.Argument) * 1000); } /// <summary> /// Code to project a video /// If the Header value is not provided, the content is projected in full screen mode /// </summary> /// <param name="Content"></param> /// <param name="header"></param> private void ShowVideo(String Content, String header) { try { //Check if header is null //Null - Show full screen content if (String.IsNullOrEmpty(header)) { //Show the full screen video control currentVideoURI = Helper.GetAssetURI(Content); FullScreenVideoControl.Source = new Uri(currentVideoURI); FullScreenContentGrid.Visibility = Visibility.Collapsed; FullScreenVideoGrid.Visibility = Visibility.Visible; FullScreenVideoControl.Play(); } else { TitleLabel.Text = header; currentVideoURI = Helper.GetAssetURI(Content); VideoControl.Source = new Uri(currentVideoURI); ContentGrid.Visibility = Visibility.Collapsed; FullScreenContentGrid.Visibility = Visibility.Collapsed; FullScreenVideoGrid.Visibility = Visibility.Collapsed; VideoControl.Visibility = Visibility.Visible; VideoGrid.Visibility = Visibility.Visible; VideoControl.Play(); } this.UpdateLayout(); } catch (Exception ex) { RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Show Video method {0}", ex.Message); } } /// <summary> /// Code to display text /// If the Header value is not provided, the content is projected in full screen mode /// </summary> /// <param name="Content"></param> /// <param name="header"></param> private void ShowText(String Content, String header) { try { //Check if header is null //Null - Show full screen content if (String.IsNullOrEmpty(header)) { //Show the full screen control with text fullScreenTbElement.Text = Content; FullScreenContentGrid.Children.Clear(); FullScreenContentGrid.Children.Add(fullScreenTbElement); FullScreenContentGrid.Visibility = Visibility.Visible; FullScreenVideoGrid.Visibility = Visibility.Collapsed; } else { TitleLabel.Text = header; tbElement.Text = Content; ContentGrid.Children.Clear(); ContentGrid.Children.Add(tbElement); ContentGrid.Visibility = Visibility.Visible; FullScreenContentGrid.Visibility = Visibility.Collapsed; FullScreenVideoGrid.Visibility = Visibility.Collapsed; VideoGrid.Visibility = Visibility.Collapsed; } this.UpdateLayout(); } catch (Exception ex) { RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Show Text method {0}", ex.Message); } } /// <summary> /// Code to project a PPT /// If the Header value is not provided, the content is projected in full screen mode /// </summary> /// <param name="Content"></param> /// <param name="header"></param> private void ShowPPT(String Content, String header) { try { //Check if header is null //Null - Show full screen content if (String.IsNullOrEmpty(header)) { //Show the full screen video control FullScreenContentGrid.Visibility = Visibility.Visible; FullScreenVideoGrid.Visibility = Visibility.Collapsed; } else { TitleLabel.Text = header; ContentGrid.Visibility = Visibility.Visible; FullScreenContentGrid.Visibility = Visibility.Collapsed; FullScreenVideoGrid.Visibility = Visibility.Collapsed; VideoGrid.Visibility = Visibility.Collapsed; } this.UpdateLayout(); DocumentPresentation.HelperMethods.StartPresentation(Helper.GetAssetURI(Content)); //ShowText("Please wait while we load your presentation", header); //ShowImage(@"\Assets\Images\loading.png", header); //this.UpdateLayout(); //pptWorker = new BackgroundWorker(); //pptWorker.DoWork += pptWorker_DoWork; //pptWorker.RunWorkerAsync(Content); } catch (Exception ex) { RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Show PPT method {0}", ex.Message); } } void pptWorker_DoWork(object sender, DoWorkEventArgs e) { DocumentPresentation.HelperMethods.StartPresentation(Helper.GetAssetURI(e.Argument.ToString())); } /// <summary> /// Code to project an image /// If the Header value is not provided, the content is projected in full screen mode /// </summary> /// <param name="Content"></param> /// <param name="header"></param> private void ShowImage(String Content, String header) { try { //Check if header is null //Null - Show full screen content if (String.IsNullOrEmpty(header)) { //Show the full screen control with text fullScreenImgElement.Source = new BitmapImage(new Uri(Helper.GetAssetURI(Content))); FullScreenContentGrid.Children.Clear(); FullScreenContentGrid.Children.Add(fullScreenImgElement); FullScreenContentGrid.Visibility = Visibility.Visible; FullScreenVideoGrid.Visibility = Visibility.Collapsed; } else { TitleLabel.Text = header; imgElement.Source = new BitmapImage(new Uri(Helper.GetAssetURI(Content))); ContentGrid.Children.Clear(); ContentGrid.Children.Add(imgElement); ContentGrid.Visibility = Visibility.Visible; FullScreenContentGrid.Visibility = Visibility.Collapsed; FullScreenVideoGrid.Visibility = Visibility.Collapsed; VideoGrid.Visibility = Visibility.Collapsed; } this.UpdateLayout(); } catch (Exception ex) { RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Show Image {0}", ex.Message); } } /// <summary> /// Code to show browser based content, applicable for URL's /// If the Header value is not provided, the content is projected in full screen mode /// </summary> /// <param name="Content"></param> /// <param name="header"></param> private void ShowBrowser(String Content, String header) { try { //Check if header is null //Null - Show full screen content if (String.IsNullOrEmpty(header)) { //Show the full screen video control //Display HTML content host = new System.Windows.Forms.Integration.WindowsFormsHost(); browserElement = new System.Windows.Forms.WebBrowser(); browserElement.ScriptErrorsSuppressed = true; helper = new Utilities.ScriptingHelper(this); browserElement.ObjectForScripting = helper; host.Child = browserElement; helper.PropertyChanged += helper_PropertyChanged; FullScreenContentGrid.Children.Clear(); FullScreenContentGrid.Children.Add(host); FullScreenContentGrid.Visibility = Visibility.Visible; FullScreenVideoGrid.Visibility = Visibility.Collapsed; } else { TitleLabel.Text = header; host = new System.Windows.Forms.Integration.WindowsFormsHost(); browserElement = new System.Windows.Forms.WebBrowser(); browserElement.ScriptErrorsSuppressed = true; helper = new Utilities.ScriptingHelper(this); host.Child = browserElement; browserElement.ObjectForScripting = helper; helper.PropertyChanged += helper_PropertyChanged; ContentGrid.Children.Clear(); ContentGrid.Children.Add(host); ContentGrid.Visibility = Visibility.Visible; FullScreenContentGrid.Visibility = Visibility.Collapsed; FullScreenVideoGrid.Visibility = Visibility.Collapsed; VideoGrid.Visibility = Visibility.Collapsed; } String fileLocation = Helper.GetAssetURI(Content); String pageUri = String.Empty; //Local file if (File.Exists(fileLocation)) { String[] PathParts = fileLocation.Split(new char[] { ':' }); pageUri = "file://127.0.0.1/" + PathParts[0] + "$" + PathParts[1]; } //Web hosted file else { pageUri = Content; } browserElement.Navigate(pageUri); this.UpdateLayout(); } catch (Exception ex) { RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Show Browser {0}", ex.Message); } } #endregion #region Helpers private Tile GetFloorTileForID(string TileID) { Tile reqdTile = null; try { reqdTile = rippleData.Floor.Tiles[TileID]; } catch (Exception) { try { reqdTile = rippleData.Floor.Tiles[TileID.Substring(0, TileID.LastIndexOf("SubTile"))].SubTiles[TileID]; } catch (Exception) { return null; } } return reqdTile; } #endregion private void VideoControl_MediaEnded(object sender, RoutedEventArgs e) { if (currentScreenContent == ContentType.Video && loopVideo && (!String.IsNullOrEmpty(currentVideoURI))) { //Replay the video VideoControl.Source = new Uri(currentVideoURI); VideoControl.Play(); } } private void FullScreenVideoControl_MediaEnded(object sender, RoutedEventArgs e) { if (currentScreenContent == ContentType.Video && loopVideo && (!String.IsNullOrEmpty(currentVideoURI))) { //Replay the video FullScreenVideoControl.Source = new Uri(currentVideoURI); FullScreenVideoControl.Play(); } } private void ShowGotoStartContent() { //Set the system state Globals.currentAppState = RippleSystemStates.UserWaitToGoOnStart; ProjectContent(rippleData.Screen.ScreenContents["GotoStart"]); } private void IntroVideoControl_MediaEnded(object sender, RoutedEventArgs e) { //System has been started, it just finished playing the intro video //if (Globals.currentAppState == RippleSystemStates.UserDetected) //{ // this.IntroVideoControl.Stop(); // ShowGotoStartContent(); //} } private void Window_Closing_1(object sender, CancelEventArgs e) { RippleCommonUtilities.LoggingHelper.StopLogging(); } //Handles messages sent by HTML animations void helper_PropertyChanged(object sender, PropertyChangedEventArgs e) { try { var scriptingHelper = sender as Utilities.ScriptingHelper; if (scriptingHelper != null) { if (e.PropertyName == "SendMessage") { if ((!String.IsNullOrEmpty(scriptingHelper.SendMessage)) && currentScreenContent == ContentType.HTML) { //Send the screen a message for HTML parameter passing Utilities.MessageReceiver.SendMessage("HTML:" + scriptingHelper.SendMessage); } } } } catch (Exception ex) { RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in helper property changed event {0}", ex.Message); } } } }
Java
/** ****************************************************************************** * @file TIM/TIM_ParallelSynchro/stm32f4xx_conf.h * @author MCD Application Team * @version V1.3.0 * @date 13-November-2013 * @brief Library configuration file. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2013 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2 * * 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_CONF_H #define __STM32F4xx_CONF_H /* Includes ------------------------------------------------------------------*/ /* Uncomment the line below to enable peripheral header file inclusion */ #include "stm32f4xx_adc.h" #include "stm32f4xx_crc.h" #include "stm32f4xx_dbgmcu.h" #include "stm32f4xx_dma.h" #include "stm32f4xx_exti.h" #include "stm32f4xx_flash.h" #include "stm32f4xx_gpio.h" #include "stm32f4xx_i2c.h" #include "stm32f4xx_iwdg.h" #include "stm32f4xx_pwr.h" #include "stm32f4xx_rcc.h" #include "stm32f4xx_rtc.h" #include "stm32f4xx_sdio.h" #include "stm32f4xx_spi.h" #include "stm32f4xx_syscfg.h" #include "stm32f4xx_tim.h" #include "stm32f4xx_usart.h" #include "stm32f4xx_wwdg.h" #include "misc.h" /* High level functions for NVIC and SysTick (add-on to CMSIS functions) */ #if defined (STM32F429_439xx) #include "stm32f4xx_cryp.h" #include "stm32f4xx_hash.h" #include "stm32f4xx_rng.h" #include "stm32f4xx_can.h" #include "stm32f4xx_dac.h" #include "stm32f4xx_dcmi.h" #include "stm32f4xx_dma2d.h" #include "stm32f4xx_fmc.h" #include "stm32f4xx_ltdc.h" #include "stm32f4xx_sai.h" #endif /* STM32F429_439xx */ #if defined (STM32F427_437xx) #include "stm32f4xx_cryp.h" #include "stm32f4xx_hash.h" #include "stm32f4xx_rng.h" #include "stm32f4xx_can.h" #include "stm32f4xx_dac.h" #include "stm32f4xx_dcmi.h" #include "stm32f4xx_dma2d.h" #include "stm32f4xx_fmc.h" #include "stm32f4xx_sai.h" #endif /* STM32F427_437xx */ #if defined (STM32F40_41xxx) #include "stm32f4xx_cryp.h" #include "stm32f4xx_hash.h" #include "stm32f4xx_rng.h" #include "stm32f4xx_can.h" #include "stm32f4xx_dac.h" #include "stm32f4xx_dcmi.h" #include "stm32f4xx_fsmc.h" #endif /* STM32F40_41xxx */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* If an external clock source is used, then the value of the following define should be set to the value of the external clock source, else, if no external clock is used, keep this define commented */ /*#define I2S_EXTERNAL_CLOCK_VAL 12288000 */ /* Value of the external clock in Hz */ /* Uncomment the line below to expanse the "assert_param" macro in the Standard Peripheral Library drivers code */ /* #define USE_FULL_ASSERT 1 */ /* Exported macro ------------------------------------------------------------*/ #ifdef USE_FULL_ASSERT /** * @brief The assert_param macro is used for function's parameters check. * @param expr: If expr is false, it calls assert_failed function * which reports the name of the source file and the source * line number of the call that failed. * If expr is true, it returns no value. * @retval None */ #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__)) /* Exported functions ------------------------------------------------------- */ void assert_failed(uint8_t* file, uint32_t line); #else #define assert_param(expr) ((void)0) #endif /* USE_FULL_ASSERT */ #endif /* __STM32F4xx_CONF_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
Java
# Note that this is not a valid measurement of tail latency. This uses the execution times we measure because they're convenient, but this does not include queueing time inside BitFunnel nor does it include head-of-line blocking queue waiting time on the queue into BitFunnel. import csv filename = "/tmp/QueryPipelineStatistics.csv" times = [] with open(filename) as f: reader = csv.reader(f) header = next(reader) assert header == ['query', 'rows', 'matches', 'quadwords', 'cachelines', 'parse', 'plan', 'match'] for row in reader: total_time = float(row[-1]) + float(row[-2]) + float(row[-3]) times.append(total_time) times.sort(reverse=True) idx_max = len(times) - 1 idx = [round(idx_max / 2), round(idx_max / 10), round(idx_max / 100), round(idx_max / 1000), 0] tails = [times[x] for x in idx] print(tails)
Java
const assert = require('assert'); const md5 = require('blueimp-md5'); const createApp = require('../../lib'); describe('tokenize service', () => { it('tokenizes and stems', () => { const app = createApp(); const text = `what's the weather in vancouver`; const hash = md5(text); return app.service('tokenize').create({ text }).then(data => { assert.equal(data._id, hash, 'id is MD5 hash of the string'); assert.deepEqual(data, { _id: '873dd3d48eed1d576a4d5b1dcacd2348', text: 'what\'s the weather in vancouver', tokens: [ 'what', 's', 'the', 'weather', 'in', 'vancouver' ], stems: [ 'what', 's', 'the', 'weather', 'in', 'vancouv' ] }); }); }); });
Java
// AForge Kinect Video Library // AForge.NET framework // http://www.aforgenet.com/framework/ // // Copyright © AForge.NET, 2005-2011 // contacts@aforgenet.com // namespace AForge.Video.Kinect { using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; using AForge; using AForge.Imaging; using AForge.Video; /// <summary> /// Enumeration of video camera modes for the <see cref="KinectVideoCamera"/>. /// </summary> public enum VideoCameraMode { /// <summary> /// 24 bit per pixel RGB mode. /// </summary> Color, /// <summary> /// 8 bit per pixel Bayer mode. /// </summary> Bayer, /// <summary> /// 8 bit per pixel Infra Red mode. /// </summary> InfraRed } /// <summary> /// Video source for Microsoft Kinect's video camera. /// </summary> /// /// <remarks><para>The video source captures video data from Microsoft <a href="http://en.wikipedia.org/wiki/Kinect">Kinect</a> /// video camera, which is aimed originally as a gaming device for XBox 360 platform.</para> /// /// <para><note>Prior to using the class, make sure you've installed Kinect's drivers /// as described on <a href="http://openkinect.org/wiki/Getting_Started#Windows">Open Kinect</a> /// project's page.</note></para> /// /// <para><note>In order to run correctly the class requires <i>freenect.dll</i> library /// to be put into solution's output folder. This can be found within the AForge.NET framework's /// distribution in Externals folder.</note></para> /// /// <para>Sample usage:</para> /// <code> /// // create video source /// KinectVideoCamera videoSource = new KinectVideoCamera( 0 ); /// // set NewFrame event handler /// videoSource.NewFrame += new NewFrameEventHandler( video_NewFrame ); /// // start the video source /// videoSource.Start( ); /// // ... /// /// private void video_NewFrame( object sender, NewFrameEventArgs eventArgs ) /// { /// // get new frame /// Bitmap bitmap = eventArgs.Frame; /// // process the frame /// } /// </code> /// </remarks> /// public class KinectVideoCamera : IVideoSource { // Kinect's device ID private int deviceID; // received frames count private int framesReceived; // recieved byte count private long bytesReceived; // camera mode private VideoCameraMode cameraMode = VideoCameraMode.Color; // camera resolution to set private CameraResolution resolution = CameraResolution.Medium; // list of currently running cameras private static List<int> runningCameras = new List<int>( ); // dummy object to lock for synchronization private object sync = new object( ); /// <summary> /// New frame event. /// </summary> /// /// <remarks><para>Notifies clients about new available frames from the video source.</para> /// /// <para><note>Since video source may have multiple clients, each client is responsible for /// making a copy (cloning) of the passed video frame, because the video source disposes its /// own original copy after notifying of clients.</note></para> /// </remarks> /// public event NewFrameEventHandler NewFrame; /// <summary> /// Video source error event. /// </summary> /// /// <remarks>This event is used to notify clients about any type of errors occurred in /// video source object, for example internal exceptions.</remarks> /// public event VideoSourceErrorEventHandler VideoSourceError; /// <summary> /// Video playing finished event. /// </summary> /// /// <remarks><para>This event is used to notify clients that the video playing has finished.</para> /// </remarks> /// public event PlayingFinishedEventHandler PlayingFinished; /// <summary> /// Specifies video mode for the camera. /// </summary> /// /// <remarks> /// <para><note>The property must be set before running the video source to take effect.</note></para> /// /// <para>Default value of the property is set to <see cref="VideoCameraMode.Color"/>.</para> /// </remarks> /// public VideoCameraMode CameraMode { get { return cameraMode; } set { cameraMode = value; } } /// <summary> /// Resolution of video camera to set. /// </summary> /// /// <remarks><para><note>The property must be set before running the video source to take effect.</note></para> /// /// <para>Default value of the property is set to <see cref="CameraResolution.Medium"/>.</para> /// </remarks> /// public CameraResolution Resolution { get { return resolution; } set { resolution = value; } } /// <summary> /// A string identifying the video source. /// </summary> /// public virtual string Source { get { return "Kinect:VideoCamera:" + deviceID; } } /// <summary> /// State of the video source. /// </summary> /// /// <remarks>Current state of video source object - running or not.</remarks> /// public bool IsRunning { get { lock ( sync ) { return ( device != null ); } } } /// <summary> /// Received bytes count. /// </summary> /// /// <remarks>Number of bytes the video source provided from the moment of the last /// access to the property. /// </remarks> /// public long BytesReceived { get { long bytes = bytesReceived; bytesReceived = 0; return bytes; } } /// <summary> /// Received frames count. /// </summary> /// /// <remarks>Number of frames the video source provided from the moment of the last /// access to the property. /// </remarks> /// public int FramesReceived { get { int frames = framesReceived; framesReceived = 0; return frames; } } /// <summary> /// Initializes a new instance of the <see cref="KinectVideoCamera"/> class. /// </summary> /// /// <param name="deviceID">Kinect's device ID (index) to connect to.</param> /// public KinectVideoCamera( int deviceID ) { this.deviceID = deviceID; } /// <summary> /// Initializes a new instance of the <see cref="KinectVideoCamera"/> class. /// </summary> /// /// <param name="deviceID">Kinect's device ID (index) to connect to.</param> /// <param name="resolution">Resolution of video camera to set.</param> /// public KinectVideoCamera( int deviceID, CameraResolution resolution ) { this.deviceID = deviceID; this.resolution = resolution; } /// <summary> /// Initializes a new instance of the <see cref="KinectVideoCamera"/> class. /// </summary> /// /// <param name="deviceID">Kinect's device ID (index) to connect to.</param> /// <param name="resolution">Resolution of video camera to set.</param> /// <param name="cameraMode">Sets video camera mode.</param> /// public KinectVideoCamera( int deviceID, CameraResolution resolution, VideoCameraMode cameraMode ) { this.deviceID = deviceID; this.resolution = resolution; this.cameraMode = cameraMode; } private Kinect device = null; private IntPtr imageBuffer = IntPtr.Zero; private KinectNative.BitmapInfoHeader videoModeInfo; /// <summary> /// Start video source. /// </summary> /// /// <remarks>Starts video source and returns execution to caller. Video camera will be started /// and will provide new video frames through the <see cref="NewFrame"/> event.</remarks> /// /// <exception cref="ArgumentException">The specified resolution is not supported for the selected /// mode of the Kinect video camera.</exception> /// <exception cref="ConnectionFailedException">Could not connect to Kinect's video camera.</exception> /// <exception cref="DeviceBusyException">Another connection to the specified video camera is already running.</exception> /// public void Start( ) { lock ( sync ) { lock ( runningCameras ) { if ( device == null ) { bool success = false; try { if ( runningCameras.Contains( deviceID ) ) { throw new DeviceBusyException( "Another connection to the specified video camera is already running." ); } // get Kinect device device = Kinect.GetDevice( deviceID ); KinectNative.VideoCameraFormat dataFormat = KinectNative.VideoCameraFormat.RGB; if ( cameraMode == VideoCameraMode.Bayer ) { dataFormat = KinectNative.VideoCameraFormat.Bayer; } else if ( cameraMode == VideoCameraMode.InfraRed ) { dataFormat = KinectNative.VideoCameraFormat.IR8Bit; } // find video format parameters videoModeInfo = KinectNative.freenect_find_video_mode( resolution, dataFormat ); if ( videoModeInfo.IsValid == 0 ) { throw new ArgumentException( "The specified resolution is not supported for the selected mode of the Kinect video camera." ); } // set video format if ( KinectNative.freenect_set_video_mode( device.RawDevice, videoModeInfo ) != 0 ) { throw new VideoException( "Could not switch to the specified video format." ); } // allocate video buffer and provide it freenect imageBuffer = Marshal.AllocHGlobal( (int) videoModeInfo.Bytes ); KinectNative.freenect_set_video_buffer( device.RawDevice, imageBuffer ); // set video callback videoCallback = new KinectNative.FreenectVideoDataCallback( HandleDataReceived ); KinectNative.freenect_set_video_callback( device.RawDevice, videoCallback ); // start the camera if ( KinectNative.freenect_start_video( device.RawDevice ) != 0 ) { throw new ConnectionFailedException( "Could not start video stream." ); } success = true; runningCameras.Add( deviceID ); device.AddFailureHandler( deviceID, Stop ); } finally { if ( !success ) { if ( device != null ) { device.Dispose( ); device = null; } if ( imageBuffer != IntPtr.Zero ) { Marshal.FreeHGlobal( imageBuffer ); imageBuffer = IntPtr.Zero; } } } } } } } /// <summary> /// Signal video source to stop its work. /// </summary> /// /// <remarks><para><note>Calling this method is equivalent to calling <see cref="Stop"/> /// for Kinect video camera.</note></para></remarks> /// public void SignalToStop( ) { Stop( ); } /// <summary> /// Wait for video source has stopped. /// </summary> /// /// <remarks><para><note>Calling this method is equivalent to calling <see cref="Stop"/> /// for Kinect video camera.</note></para></remarks> /// public void WaitForStop( ) { Stop( ); } /// <summary> /// Stop video source. /// </summary> /// /// <remarks><para>The method stops the video source, so it no longer provides new video frames /// and does not consume any resources.</para> /// </remarks> /// public void Stop( ) { lock ( sync ) { lock ( runningCameras ) { if ( device != null ) { bool deviceFailed = device.IsDeviceFailed( deviceID ); if ( !deviceFailed ) { KinectNative.freenect_stop_video( device.RawDevice ); } device.Dispose( ); device = null; runningCameras.Remove( deviceID ); if ( PlayingFinished != null ) { PlayingFinished( this, ( !deviceFailed ) ? ReasonToFinishPlaying.StoppedByUser : ReasonToFinishPlaying.DeviceLost ); } } if ( imageBuffer != IntPtr.Zero ) { Marshal.FreeHGlobal( imageBuffer ); imageBuffer = IntPtr.Zero; } videoCallback = null; } } } // New video data event handler private KinectNative.FreenectVideoDataCallback videoCallback = null; private void HandleDataReceived( IntPtr device, IntPtr imageData, UInt32 timeStamp ) { int width = videoModeInfo.Width; int height = videoModeInfo.Height; Bitmap image = null; BitmapData data = null; try { image = ( cameraMode == VideoCameraMode.Color ) ? new Bitmap( width, height, PixelFormat.Format24bppRgb ) : AForge.Imaging.Image.CreateGrayscaleImage( width, height ); data = image.LockBits( new Rectangle( 0, 0, width, height ), ImageLockMode.ReadWrite, image.PixelFormat ); unsafe { byte* dst = (byte*) data.Scan0.ToPointer( ); byte* src = (byte*) imageBuffer.ToPointer( ); if ( cameraMode == VideoCameraMode.Color ) { // color RGB 24 mode int offset = data.Stride - width * 3; for ( int y = 0; y < height; y++ ) { for ( int x = 0; x < width; x++, src += 3, dst += 3 ) { dst[0] = src[2]; dst[1] = src[1]; dst[2] = src[0]; } dst += offset; } } else { // infra red mode - grayscale output int stride = data.Stride; if ( stride != width ) { for ( int y = 0; y < height; y++ ) { SystemTools.CopyUnmanagedMemory( dst, src, width ); dst += stride; src += width; } } else { SystemTools.CopyUnmanagedMemory( dst, src, width * height ); } } } image.UnlockBits( data ); framesReceived++; bytesReceived += width * height; } catch ( Exception ex ) { if ( VideoSourceError != null ) { VideoSourceError( this, new VideoSourceErrorEventArgs( ex.Message ) ); } if ( image != null ) { if ( data != null ) { image.UnlockBits( data ); } image.Dispose( ); image = null; } } if ( image != null ) { if ( NewFrame != null ) { NewFrame( this, new NewFrameEventArgs( image ) ); } image.Dispose( ); } } } }
Java
namespace DeviceHive.Data.EF.Migrations { using System.Data.Entity.Migrations; public partial class _91 : DbMigration { public override void Up() { CreateTable( "OAuthClient", c => new { ID = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 128), Domain = c.String(nullable: false, maxLength: 128), Subnet = c.String(maxLength: 128), RedirectUri = c.String(nullable: false, maxLength: 128), OAuthID = c.String(nullable: false, maxLength: 32), OAuthSecret = c.String(nullable: false, maxLength: 32), }) .PrimaryKey(t => t.ID) .Index(t => t.OAuthID, unique: true); CreateTable( "OAuthGrant", c => new { ID = c.Int(nullable: false, identity: true), Timestamp = c.DateTime(nullable: false, storeType: "datetime2"), AuthCode = c.Guid(), ClientID = c.Int(nullable: false), UserID = c.Int(nullable: false), AccessKeyID = c.Int(nullable: false), Type = c.Int(nullable: false), AccessType = c.Int(nullable: false), RedirectUri = c.String(maxLength: 128), Scope = c.String(nullable: false, maxLength: 256), NetworkList = c.String(maxLength: 128), }) .PrimaryKey(t => t.ID) .ForeignKey("OAuthClient", t => t.ClientID, cascadeDelete: true) .ForeignKey("User", t => t.UserID, cascadeDelete: true) .ForeignKey("AccessKey", t => t.AccessKeyID, cascadeDelete: false) .Index(t => t.ClientID) .Index(t => t.UserID) .Index(t => t.AccessKeyID); Sql("CREATE UNIQUE NONCLUSTERED INDEX [IX_AuthCode] ON [OAuthGrant] ( [AuthCode] ASC ) WHERE [AuthCode] IS NOT NULL"); } public override void Down() { DropIndex("OAuthGrant", new[] { "AccessKeyID" }); DropIndex("OAuthGrant", new[] { "UserID" }); DropIndex("OAuthGrant", new[] { "ClientID" }); DropIndex("OAuthGrant", new[] { "AuthCode" }); DropForeignKey("OAuthGrant", "AccessKeyID", "AccessKey"); DropForeignKey("OAuthGrant", "UserID", "User"); DropForeignKey("OAuthGrant", "ClientID", "OAuthClient"); DropTable("OAuthGrant"); DropIndex("OAuthClient", new[] { "OAuthID" }); DropTable("OAuthClient"); } } }
Java
require File.dirname(__FILE__) + '/../test_helper' require 'posts_controller' require 'mailing_list_mailer' # Re-raise errors caught by the controller. class PostsController def rescue_action(e) raise e end end # FIXME Navigation tests are weak. Need to do more than just not blow up class PostsControllerTest < ActiveSupport::TestCase def setup @controller = PostsController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new ActionMailer::Base.delivery_method = :test ActionMailer::Base.perform_deliveries = true ActionMailer::Base.deliveries = [] end def test_legacy_routing assert_recognizes( {:controller => "posts", :action => "show", :mailing_list_name => "obrarace", :id => "25621"}, "posts/show/obrarace/25621" ) assert_recognizes( {:controller => "posts", :action => "new", :mailing_list_name => "obra"}, "posts/new/obra" ) end def test_new obra_chat = mailing_lists(:obra_chat) get(:new, :mailing_list_name => obra_chat.name) assert_response(:success) assert_template("posts/new") assert_not_nil(assigns["mailing_list"], "Should assign mailing_list") assert_not_nil(assigns["mailing_list_post"], "Should assign mailing_list_post") mailing_list_post = assigns["mailing_list_post"] assert_equal(obra_chat, mailing_list_post.mailing_list, "Post's mailing list") assert_tag(:tag => "input", :attributes => {:type => "hidden", :name => "mailing_list_post[mailing_list_id]", :value => obra_chat.id}) assert_tag(:tag => "input", :attributes => {:type => "text", :name => "mailing_list_post[subject]"}) assert_tag(:tag => "input", :attributes => {:type => "text", :name => "mailing_list_post[from_email_address]"}) assert_tag(:tag => "input", :attributes => {:type => "text", :name => "mailing_list_post[from_name]"}) assert_tag(:tag => "textarea", :attributes => {:name => "mailing_list_post[body]"}) assert_tag(:tag => "input", :attributes => {:type => "submit", :name => "commit", :value => "Post"}) end def test_new_reply obra_race = mailing_lists(:obra_race) original_post = Post.create({ :mailing_list => obra_race, :subject => "Only OBRA Race Message", :date => Date.today, :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:new, :mailing_list_name => obra_race.name, :reply_to => original_post.id) assert_response(:success) assert_template("posts/new") assert_not_nil(assigns["mailing_list"], "Should assign mailing_list") mailing_list_post = assigns["mailing_list_post"] assert_not_nil(mailing_list_post, "Should assign mailing_list_post") assert_equal(original_post, assigns["reply_to"], "Should assign reply_to") assert_equal("Re: Only OBRA Race Message", mailing_list_post.subject, 'Prepopulated subject') assert_equal(obra_race, mailing_list_post.mailing_list, "Post's mailing list") assert_tag(:tag => "input", :attributes => {:type => "hidden", :name => "mailing_list_post[mailing_list_id]", :value => obra_race.id}) assert_tag(:tag => "input", :attributes => {:type => "text", :name => "mailing_list_post[subject]"}) assert_tag(:tag => "input", :attributes => {:type => "text", :name => "mailing_list_post[from_email_address]"}) assert_tag(:tag => "input", :attributes => {:type => "text", :name => "mailing_list_post[from_name]"}) assert_tag(:tag => "textarea", :attributes => {:name => "mailing_list_post[body]"}) assert_tag(:tag => "input", :attributes => {:type => "submit", :name => "commit", :value => "Send"}) end def test_index_routing obra_chat = mailing_lists(:obra_chat) opts = {:controller => "posts", :action => "index", :mailing_list_name => obra_chat.name} assert_routing("posts/obra", opts) end def test_index get(:index, :mailing_list_name => "obrarace") assert_response(:redirect) assert_redirected_to( :action => "list", :mailing_list_name => "obrarace", :month => Date.today.month, :year => Date.today.year ) end def test_list obra_chat = mailing_lists(:obra_chat) for index in 1..22 date = Time.now.beginning_of_month + index * 3600 * 24 Post.create({ :mailing_list => obra_chat, :subject => "Subject Test #{index}", :date => date, :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message #{index}" }) end obra_race = mailing_lists(:obra_race) Post.create({ :mailing_list => obra_race, :subject => "Only OBRA Race Message", :date => date, :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:list, :mailing_list_name => obra_chat.name, :month => Time.now.month, :year => Time.now.year) assert_response(:success) assert_not_nil(assigns["mailing_list"], "Should assign mailing_list") assert_not_nil(assigns["year"], "Should assign month") assert_not_nil(assigns["month"], "Should assign year") assert_not_nil(assigns["posts"], "Should assign posts") assert_equal(22, assigns["posts"].size, "Should show recent posts") assert_equal(Date.today.month, assigns["month"], "Assign month") assert_equal(Date.today.year, assigns["year"], "Assign year") assert_template("posts/list") get(:list, :mailing_list_name => obra_race.name, :month => Time.now.month, :year => Time.now.year) assert_response(:success) assert_not_nil(assigns["mailing_list"], "Should assign mailing_list") assert_not_nil(assigns["year"], "Should assign month") assert_not_nil(assigns["month"], "Should assign year") assert_not_nil(assigns["posts"], "Should assign posts") assert_equal(1, assigns["posts"].size, "Should show recent posts") assert_equal(Date.today.month, assigns["month"], "Assign month") assert_equal(Date.today.year, assigns["year"], "Assign year") assert_template("posts/list") end def test_list_with_date obra_race = mailing_lists(:obra_race) post_2004_12_01 = Post.create({ :mailing_list => obra_race, :subject => "BB 1 Race Results", :date => Date.new(2004, 12, 1), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) post_2004_11_31 = Post.create({ :mailing_list => obra_race, :subject => "Cherry Pie Race Results", :date => Date.new(2004, 11, 30), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) post_2004_12_31 = Post.create({ :mailing_list => obra_race, :subject => "Schedule Changes", :date => Time.local(2004, 12, 31, 23, 59, 59, 999999), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:list, :mailing_list_name => obra_race.name, :year => "2004", :month => "11") assert_response(:success) assert_not_nil(assigns["mailing_list"], "Should assign mailing_list") assert_not_nil(assigns["year"], "Should assign month") assert_not_nil(assigns["month"], "Should assign year") assert_not_nil(assigns["posts"], "Should assign posts") assert_equal(1, assigns["posts"].size, "Should show recent posts") assert_equal(11, assigns["month"], "Assign month") assert_equal(2004, assigns["year"], "Assign year") assert_equal(post_2004_11_31, assigns["posts"].first, "Post") assert_template("posts/list") get(:list, :mailing_list_name => obra_race.name, :year => "2004", :month => "12") assert_response(:success) assert_not_nil(assigns["mailing_list"], "Should assign mailing_list") assert_not_nil(assigns["year"], "Should assign month") assert_not_nil(assigns["month"], "Should assign year") assert_not_nil(assigns["posts"], "Should assign posts") assert_equal(2, assigns["posts"].size, "Should show recent posts") assert_equal(12, assigns["month"], "Assign month") assert_equal(2004, assigns["year"], "Assign year") assert_equal(post_2004_12_31, assigns["posts"].first, "Post") assert_equal(post_2004_12_01, assigns["posts"].last, "Post") assert_template("posts/list") get(:list, :mailing_list_name => obra_race.name, :year => "2004", :month => "10") assert_response(:success) assert_not_nil(assigns["mailing_list"], "Should assign mailing_list") assert_not_nil(assigns["year"], "Should assign month") assert_not_nil(assigns["month"], "Should assign year") assert_not_nil(assigns["posts"], "Should assign posts") assert_equal(10, assigns["month"], "Assign month") assert_equal(2004, assigns["year"], "Assign year") assert(assigns["posts"].empty?, "No posts") assert_template("posts/list") end def test_list_previous_next obra_race = mailing_lists(:obra_race) post_2004_12_01 = Post.create({ :mailing_list => obra_race, :subject => "BB 1 Race Results", :date => Date.new(2004, 12, 1), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) post_2004_11_31 = Post.create({ :mailing_list => obra_race, :subject => "Cherry Pie Race Results", :date => Date.new(2004, 11, 30), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) post_2004_12_31 = Post.create({ :mailing_list => obra_race, :subject => "Schedule Changes", :date => Time.local(2004, 12, 31, 23, 59, 59, 999999), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:list, :mailing_list_name => obra_race.name, :year => "2004", :month => "11", :next => "&gt;") assert_response(:redirect) assert_redirected_to(:month => 12, :year => 2004) get(:list, :mailing_list_name => obra_race.name, :year => "2004", :month => "12", :next => "&gt;") assert_response(:redirect) assert_redirected_to(:month => 1, :year => 2005) get(:list, :mailing_list_name => obra_race.name, :year => "2004", :month => "12", :previous => "&lt;") assert_response(:redirect) assert_redirected_to(:month => 11, :year => 2004) end def test_list_routing path = {:controller => "posts", :action => "list", :mailing_list_name => "obra", :year => "2003", :month => "8"} assert_routing("posts/obra/2003/8", path) end def test_post assert(MailingListMailer.deliveries.empty?, "Should have no email deliveries") obra_chat = mailing_lists(:obra_chat) subject = "Spynergy for Sale" from_name = "Tim Schauer" from_email_address = "tim.schauer@butlerpress.com" body = "Barely used" path = {:controller => "posts", :action => "post", :mailing_list_name => 'obra'} assert_routing("posts/obra/post", path) post(:post, :mailing_list_name => obra_chat.name, :reply_to => {:id => ''}, :mailing_list_post => { :mailing_list_id => obra_chat.id, :subject => subject, :from_name => from_name, :from_email_address => from_email_address, :body => body}, :commit => "Post" ) assert(flash.has_key?(:notice)) assert_response(:redirect) assert_redirected_to(:action => "confirm", :mailing_list_name => obra_chat.name) assert_equal(1, MailingListMailer.deliveries.size, "Should have one email delivery") delivered_mail = MailingListMailer.deliveries.first assert_equal(subject, delivered_mail.subject, "Subject") assert_equal([from_email_address], delivered_mail.from, "From email") assert_equal(from_name, delivered_mail.friendly_from, "From Name") assert_equal_dates(Date.today, delivered_mail.date, "Date") assert_equal([obra_chat.name], delivered_mail.to, "Recipient") end def test_post_reply assert(MailingListMailer.deliveries.empty?, "Should have no email deliveries") obra_chat = mailing_lists(:obra_chat) subject = "Spynergy for Sale" from_name = "Tim Schauer" from_email_address = "tim.schauer@butlerpress.com" body = "Barely used" reply_to_post = Post.create({ :mailing_list => obra_chat, :subject => "Schedule Changes", :date => Time.local(2004, 12, 31, 23, 59, 59, 999999), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) path = {:controller => "posts", :action => "post", :mailing_list_name => 'obra'} assert_routing("posts/obra/post", path) post(:post, :mailing_list_name => obra_chat.name, :mailing_list_post => { :mailing_list_id => obra_chat.id, :subject => subject, :from_name => from_name, :from_email_address => from_email_address, :body => body}, :reply_to => {:id => reply_to_post.id}, :commit => "Post" ) assert(flash.has_key?(:notice)) assert_response(:redirect) assert_redirected_to(:action => "confirm_private_reply", :mailing_list_name => obra_chat.name) assert_equal(1, MailingListMailer.deliveries.size, "Should have one email delivery") delivered_mail = MailingListMailer.deliveries.first assert_equal(subject, delivered_mail.subject, "Subject") assert_equal([from_email_address], delivered_mail.from, "From email") assert_equal(from_name, delivered_mail.friendly_from, "From Name") assert_equal_dates(Date.today, delivered_mail.date, "Date") assert_equal(['scout@obra.org'], delivered_mail.to, "Recipient") end def test_post_invalid_reply obra_chat = mailing_lists(:obra_chat) subject = "Spynergy for Sale" from_name = "Tim Schauer" from_email_address = "tim.schauer@butlerpress.com" body = "Barely used" reply_to_post = Post.create!( :mailing_list => obra_chat, :subject => "Schedule Changes", :date => Time.local(2004, 12, 31, 23, 59, 59, 999999), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." ) post(:post, :mailing_list_name => obra_chat.name, :mailing_list_post => { :mailing_list_id => obra_chat.id, :subject => "Re: #{subject}", :from_name => "", :from_email_address => "", :body => ""}, :reply_to => {:id => reply_to_post.id}, :commit => "Send" ) assert_template("posts/new") assert_not_nil(assigns["mailing_list"], "Should assign mailing_list") mailing_list_post = assigns["mailing_list_post"] assert_not_nil(mailing_list_post, "Should assign mailing_list_post") assert_equal(reply_to_post, assigns["reply_to"], "Should assign reply_to") assert_equal("Re: #{subject}", mailing_list_post.subject, 'Prepopulated subject') assert_equal(obra_chat, mailing_list_post.mailing_list, "Post's mailing list") end def test_confirm obra_race = mailing_lists(:obra_race) path = {:controller => "posts", :action => "confirm", :mailing_list_name => obra_race.name } assert_routing("posts/obrarace/confirm", path) get(:confirm, :mailing_list_name => obra_race.name) assert_response(:success) assert_template("posts/confirm") assert_equal(obra_race, assigns["mailing_list"], 'Should assign mailing list') end def test_confirm_private_reply obra_race = mailing_lists(:obra_race) path = {:controller => "posts", :action => "confirm_private_reply", :mailing_list_name => obra_race.name } assert_routing("posts/obrarace/confirm_private_reply", path) get(:confirm_private_reply, :mailing_list_name => obra_race.name) assert_response(:success) assert_template("posts/confirm_private_reply") assert_equal(obra_race, assigns["mailing_list"], 'Should assign mailing list') end def test_show obra_race = mailing_lists(:obra_race) new_post = Post.create({ :mailing_list => obra_race, :subject => "Only OBRA Race Message", :date => Time.now, :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) new_post.save! path = {:controller => "posts", :action => "show", :mailing_list_name => obra_race.name, :id => new_post.id.to_s } assert_routing("posts/obrarace/show/#{new_post.id}", path) get(:show, :mailing_list_name => obra_race.name, :id => new_post.id) assert_response(:success) assert_not_nil(assigns["post"], "Should assign post") assert_template("posts/show") end def test_archive_navigation # No posts get(:list, :mailing_list_name => "obrarace", :year => "2004", :month => "12") assert_tag(:tag => "div", :attributes => {:class => "archive_navigation"}) # One post obra_race = mailing_lists(:obra_race) new_post = Post.create({ :mailing_list => obra_race, :subject => "Only OBRA Race Message", :date => Time.local(2004, 12, 31, 12, 30), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:list, :mailing_list_name => "obrarace", :year => "2004", :month => "12") assert_tag(:tag => "div", :attributes => {:class => "archive_navigation"}) # Two months obra_race = mailing_lists(:obra_race) new_post = Post.create({ :mailing_list => obra_race, :subject => "Before OBRA Race Message", :date => Time.local(2004, 11, 7), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:list, :mailing_list_name => "obrarace", :year => "2004", :month => "11") assert_tag(:tag => "div", :attributes => {:class => "archive_navigation"}) end def test_post_navigation # One post obra_race = mailing_lists(:obra_race) post_2004_12_31 = Post.create({ :mailing_list => obra_race, :subject => "Only OBRA Race Message", :date => Time.local(2004, 12, 31, 12, 30), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:show, :mailing_list_name => obra_race.name, :id => post_2004_12_31.id) # Two months post_2004_11_07 = Post.create({ :mailing_list => obra_race, :subject => "Before OBRA Race Message", :date => Time.local(2004, 11, 7), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:show, :mailing_list_name => obra_race.name, :id => post_2004_12_31.id) # Three months post_2004_11_03 = Post.create({ :mailing_list => obra_race, :subject => "Before OBRA Race Message", :date => Time.local(2004, 11, 3, 8, 00, 00), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:show, :mailing_list_name => obra_race.name, :id => post_2004_11_07.id) # Another list obra_chat = mailing_lists(:obra_chat) post_other_list = Post.create({ :mailing_list => obra_chat, :subject => "OBRA Chat", :date => Time.local(2004, 11, 3, 21, 00, 00), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:show, :mailing_list_name => obra_race.name, :id => post_2004_11_07.id) assert_tag(:tag => "div", :attributes => {:class => "archive_navigation"}) end def test_post_previous_next obra_race = mailing_lists(:obra_race) post_2004_12_01 = Post.create({ :mailing_list => obra_race, :subject => "BB 1 Race Results", :date => Time.local(2004, 12, 1), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) post_2004_11_31 = Post.create({ :mailing_list => obra_race, :subject => "Cherry Pie Race Results", :date => Time.local(2004, 11, 30), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) post_2004_12_31 = Post.create({ :mailing_list => obra_race, :subject => "Schedule Changes", :date => Time.local(2004, 12, 31, 23, 59, 59, 999999), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:show, :mailing_list_name => obra_race.name, :next_id => post_2004_12_31.id, :next => "&gt;") assert_response(:redirect) assert_redirected_to(:id => post_2004_12_31.id.to_s) get(:show, :mailing_list_name => obra_race.name, :previous_id => post_2004_11_31.id, :previous => "&lt;") assert_response(:redirect) assert_redirected_to(:id => post_2004_11_31.id.to_s) # This part doesn't prove much obra_chat = mailing_lists(:obra_chat) post_other_list = Post.create({ :mailing_list => obra_chat, :subject => "OBRA Chat", :date => Time.local(2004, 12, 31, 12, 00, 00), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:show, :mailing_list_name => obra_race.name, :next_id => post_2004_12_31.id, :next => "&gt;") assert_response(:redirect) assert_redirected_to(:id => post_2004_12_31.id.to_s) end def test_list_with_no_lists MailingList.delete_all get(:list, :month => Date.today.month, :year => Date.today.year) assert_response(:success) assert_template('404') assert(!flash.empty?, "Should have flash") end def test_list_with_bad_name get(:list, :month => Date.today.month, :year => Date.today.year, :mailing_list_name => "Masters Racing") assert_response(:success) assert_template('404') assert(!flash.empty?, "Should have flash") end def test_list_with_bad_month get(:list, :month => 14, :year => Date.today.year, :mailing_list_name => mailing_lists(:obra_race).name) assert_redirected_to( :action => "list", :mailing_list_name => "obrarace", :month => Date.today.month, :year => Date.today.year ) end def test_list_with_bad_year get(:list, :month => 12, :year => 9_116_560, :mailing_list_name => mailing_lists(:obra_race).name) assert_redirected_to( :action => "list", :mailing_list_name => "obrarace", :month => Date.today.month, :year => Date.today.year ) end end
Java
class Views::Test::NeedsSubclass < Views::Test::Needs def content text "NeedsSubclass #{@foobar}" end end
Java
 namespace MonoGame.Extended.Collisions { public class CollisionGridCell : ICollidable { private readonly CollisionGrid _parentGrid; public CollisionGridCell(CollisionGrid parentGrid, int column, int row, int data) { _parentGrid = parentGrid; Column = column; Row = row; Data = data; Flag = data == 0 ? CollisionGridCellFlag.Empty : CollisionGridCellFlag.Solid; } public int Column { get; } public int Row { get; } public int Data { get; private set; } public object Tag { get; set; } public CollisionGridCellFlag Flag { get; set; } public RectangleF BoundingBox => _parentGrid.GetCellRectangle(Column, Row).ToRectangleF(); } }
Java
// // GPDownloader.h // test // // Created by mac on 15-2-3. // Copyright (c) 2015年 gpr. All rights reserved. // #import <Foundation/Foundation.h> @class GPDownloader; typedef NS_ENUM(NSUInteger, GPDownloaderStatus) { GPDownloaderStatusReady, GPDownloaderStatusDownLoading, GPDownloaderStatusPause, GPDownloaderStatusFinish, GPDownloaderStatusDestory, GPDownloaderStatusError }; // 这些block都不在主线程中执行 typedef void(^StartTaskBlock)(GPDownloader * downloader); typedef void(^ProgressBlock)(unsigned long long currDownloadSize); typedef void(^CompleteBlock)(GPDownloader *downloader); typedef void(^ErrorBlock)(GPDownloader *mdownloader,NSError *error); // 代理,注意代理方法运行在子线程中 @protocol GPDownloaderDelegate <NSObject> - (void)downloaderDidStart:(GPDownloader *) downloader; - (void)downloaderDidUpdateDataSize:(unsigned long long)currDownloadSize; - (void)downloaderDidComplete:(GPDownloader *) downloader; - (void)downloader:(GPDownloader *)downloader DidDownLoadFail:(NSError *)error; @end @interface GPDownloader : NSObject #pragma mark - 初始化 + (instancetype)downloaderWithURLString:(NSString *)urlString downloadRange:(NSRange)downloadRange fileName:(NSString *)fileName; - (instancetype)initWithURLString:(NSString *)urlString downloadRange:(NSRange)downloadRange fileName:(NSString *)fileName; + (instancetype)downloaderWithURLString:(NSString *)urlString downloadRange:(NSRange)downloadRange startBlock:(StartTaskBlock)startBlock progressBlock:(ProgressBlock)progressBlock completeBlock:(CompleteBlock)completeBlock errorBlock:(ErrorBlock)errorBlock fileName:(NSString *)fileName; - (instancetype)initWithURLString:(NSString *)urlString downloadRange:(NSRange)downloadRange startBlock:(StartTaskBlock)startBlock progressBlock:(ProgressBlock)progressBlock completeBlock:(CompleteBlock)completeBlock errorBlock:(ErrorBlock)errorBlock fileName:(NSString *)fileName; @property (nonatomic,copy) NSString *urlString; @property (nonatomic,assign) NSRange downloadRange; @property (nonatomic,strong) NSString *fileName; /** 用来标志下载文件的顺序,以便以后拼接文件方便 */ @property (nonatomic,assign) NSInteger fileIndex; /** 当连接失败的时候会尝试重新连接,默认重新尝试连接次数为3 */ @property (nonatomic,assign) NSInteger maxRestartCount; /** 已经下载的长度 */ @property (nonatomic,assign) unsigned long long currFileSize; /** 代理 */ @property (nonatomic,weak) id<GPDownloaderDelegate> delegate; /** 超时时间,默认为5秒*/ @property (nonatomic,assign) NSTimeInterval timeOut; /** 临时文件的名字,用于标识一个 GPDownloader 的唯一标识 */ @property (nonatomic,copy,readonly) NSString *tempFilePath; #pragma mark - 监听下载状态 //@property (nonatomic,assign) GPDownloaderStatus state; @property (nonatomic,copy) StartTaskBlock startBlock; @property (nonatomic,copy) ProgressBlock progressBlock; @property (nonatomic,copy) CompleteBlock completeBlock; @property (nonatomic,copy) ErrorBlock errorBlock; #pragma mark - 下载器状态管理 - (void)startDownloadTask; - (void)pause; - (void)resume; - (void)stop; - (void)destoryDownloader; @end
Java
/* Document : main Created on : Oct 12, 2013, 12:37:21 PM Author : Andres Description: Purpose of the stylesheet follows. */ .crud-table td{ padding-right: 10px; padding-bottom: 10px; padding-top: 0px; } /* ------ Mix ------ */ #Grid{ width: 398px; margin: 0px; padding: 0px; overflow: scroll; overflow-x: hidden; max-height: 500px; } #Grid:after{ content: ''; display: inline-block; width: 100%; } #Grid .mix{ display: none; opacity: 0; vertical-align: top; text-align: center; width: 100px; height: 160px; font-size: 10px; color: #000000; margin-bottom: 10px; margin-left: 18px; } #Grid .mix{ display: none; opacity: 0; vertical-align: top; text-align: center; width: 100px; height: 150px; font-size: 10px; color: #000000; margin-bottom: 10px; margin-left: 18px; } #Grid .mix a{ text-decoration: none; color: #000000; } #Grid .mix a span{ display: inline-block; height: 35px; } #Grid .mix.seleccionado{ background: #3297fd; color: #FFFFFF; outline: 5px solid #3297fd; font-weight: bold; } #Grid .mix.seleccionado a{ color: #FFFFFF; } #Grid .gap{ display: inline-block; width: 200px; } /* ------ Pedido producto -------*/ .pPedidoProducto{ width: 800px; } .tProductoPedido td{ vertical-align: top; padding-bottom: 20px; padding-right: 10px; } /* ------ Tabla colapse --------*/ .tColapse td{ padding: 1px !important; } .tColapse th{ padding: 1px !important; } /* .records_list td:last-child{ text-align: right; } */ .crud-table{ border: 10px solid #eeefff; background-color: #eeefff; } /* ------ Selecciones menu --------*/ .controlm.selected{ background: #39b3d7; } .cobrosm.selected{ background: #ed9c28; } .produccionm.selected{ background: #47a447; } .tareasm.selected{ background: #6f5499; } .tareasm.selected a, .produccionm.selected a, .cobrosm.selected a, .controlm.selected a{ color: #FFFFFF !important; } /*tr.odd td.highlighted { background-color: #D3D6FF; }*/ tr.even td.highlighted { background-color: #EAEBFF; } .t_control tr.even td, .t_control tr.odd td, table.t_control.dataTable tr.odd td.sorting_1, table.t_control.dataTable tr.even td.sorting_1{ background-color: #DBF7FF; } .t_cobros tr.even td, .t_cobros tr.odd td, table.t_cobros.dataTable tr.odd td.sorting_1, table.t_cobros.dataTable tr.even td.sorting_1{ background-color: #FFE9C9; } .t_produccion tr.even td, .t_produccion tr.odd td, table.t_produccion.dataTable tr.odd td.sorting_1, table.t_produccion.dataTable tr.even td.sorting_1{ background-color: #D6FFD6; } .t_tareas tr.even td, .t_tareas tr.odd td, table.t_tareas.dataTable tr.odd td.sorting_1, table.t_tareas.dataTable tr.even td.sorting_1{ background-color: #EEE3FF; }
Java
'use strict'; var getTemplatedStylesheet = require('./templatedStylesheet'), path = require('path'); module.exports = getTemplatedStylesheet(path.join(__dirname, '/templates/stylus.tpl'));
Java
import React from 'react' import Icon from 'react-icon-base' const MdTonality = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m32.9 23.4c0.1-0.6 0.2-1.2 0.3-1.8h-11.6v1.8h11.3z m-2.5 5c0.4-0.6 0.9-1.2 1.2-1.8h-10v1.8h8.8z m-8.8 4.8c1.8-0.2 3.4-0.8 4.9-1.6h-4.9v1.6z m0-16.6v1.8h11.6c-0.1-0.6-0.2-1.2-0.3-1.8h-11.3z m0-5v1.8h10c-0.4-0.6-0.8-1.2-1.2-1.8h-8.8z m0-4.8v1.6h4.9c-1.5-0.8-3.1-1.4-4.9-1.6z m-3.2 26.4v-26.4c-6.6 0.8-11.8 6.4-11.8 13.2s5.2 12.4 11.8 13.2z m1.6-29.8c9.2 0 16.6 7.4 16.6 16.6s-7.4 16.6-16.6 16.6-16.6-7.4-16.6-16.6 7.4-16.6 16.6-16.6z"/></g> </Icon> ) export default MdTonality
Java
--- title: "Ny fiarahan'Andriamanitra" date: 30/03/2021 --- Mariho ireo teny voalohany indrindra nataon'Andriamanitra tamin'ny olombelona, na farafaharatsiny araka izay fisehony voalohany ao amin'ny Soratra Masina. Nampahafantarin'Andriamanitra azy ireo ny fahafahany mamorona, miteraka olona tahaka azy ireo ihany. Nasehony azy koa ny tany, ny voary, ary nasaina nameno, nampanompo, sy nanjaka taminy izy ireo. Natorony azy ireo koa ireo zava-maniry azon'izy ireo ihinanana. Raha fintinina izany ny voalazan'ny Baiboly dia mikasika ny fifandraisan'izy ireo amin'ny tontolo mísy azy sy ny fampiasany izany no teny voalohany nataon'Andriamanitra ho an'ny lehilahy sy ny vehivavy. `Inona no ambaran'ny Gen. 1:28,29 antsika mikasika ny fomba fijerin'Andriamanitra ny tontolo hita maso sy azo-tsapain-tanana? Mampiseho ve ireo andininy ireo fa misy ratsy ao amin'ny zavatra ara-materialy na ny fisitrahantsika izany? Inona no lesona azontsika raisina avy amin'ireo toe-javatra voalohany teo amin'ny tantaran'ny taranak'olombelona ireo, mikasika ny tokony ho fifandraisantsika amin'ny voary?` Amin'ireo teny ireo ihany koa Andriamanitra dia manao dingana voalohany amin'ny fifandraisana amin'ny olombelona. Miresaka amin'izy ireo Izy; manome toromarika azy, milaza aminy ny tokony hataony. Misy andraikitra ihany koa ao ambadik'ireo teny ireo. Nasain'Andriamanitra nifehy io voary mahatalanjona noforonin'ny Tenany io izy ireo. `Milaza ny Gen. 1:28 fa nitso-drano an'i Adama sy Eva Andriamanitra. Inona no hevitr'izany? Karazam-pifandraisana inona eo amin'izy ireo sy ny Mpahary azy no asehon'izany?` Ny firesak’Andriamanitra tamin'i Adama sy Eva dia toy ny amin'ny voary manan-tsaina izay afaka hanisy setriny ny hatsaram-panahiny sy afaka hifandray am-po Aminy. I Adama sy Eva koa, amin'ny maha-voary zanaka azy ireo, dia niankina tamin'ny fitahiana sy ny fiahian'llay Rainy Mpahary azy. Tsy nisy na inona na inona naha-mendrika azy ireo hahazo izay nomen'ny Mpahary azy. Nandray maimaimpoana zavatra izay tsy nisasarany izy ireo. `Rehefa mamaky ny momba ny famoronana ny lehilahy sy ny vehivavy talohan'ny nisian'ny fahotana isika, dia mahita santionany amin'ilay karazam-pifandraisana tian'Andriamanitra ifandraisana amintsika ankehitriny, dia amin'izao fotoana efa isian'ny fahotana izao. Avereno jerena ity lesona androany ity. Inona ireo hevitra mifanindran-dalana ao ka afaka hanampy antsika hahatakatra ny fomba mety ifandraisantsika Aminy, na dia amin'izao fahalavoana misy antsika izao aza?`
Java
--- title: අනුවණකම සහ ඥානවන්තකම date: 02/12/2020 --- `හිතෝපදේශ 1 කියවන්න. සැබෑ ක්රිස්තියානි අධ්යාපනය කුමක් විය යුතුද යන්න පිළිබඳව මෙය අපට උගන්වන්නේ කුමක්ද?` අනුවණකම සහ ඥානවන්තකම අතර ස්ථිරවූ සංසන්දනයක් ශුද්ධ බයිබලය තුළින් පෙන්වා දෙයි. අනුවණ ලෙස හැසිරීම සහ අනුවණයන් සමඟ ඇසුරු කිරීම පිලිබඳ අන්තරායන් පිළිබඳව හිතෝපදේශ පොත අපට සිහිපත් කර දෙයි. වෙනස ඉතා පැහැදිලිය: දෙවියන්වහන්සේ ආශා කරන්නේ තම සෙනඟ ඥානය සොයමින්, එය අගය කරමින්, එය තුළ පූර්ණ වීමය. කලාව හා විද්යාව හදාරන ශිෂ්යයින් දැනුම වැඩි කරගැනීමට සහ ඔවුන්ගේ අධ්යයන කටයුතුවල විශිෂ්ටත්වය පසුපස යෑමට ඔවුන්ගේ හැකියාවන් භාවිතයේ යොදවති. මෙම ශික්ෂාවන්හි ගුරුවරුන්ද එළෙසම කරති. දැනුම සහ හැකියාව හේතුකොටගෙන අපට කලාත්මක සුවිශේෂී දස්කමක් හා විද්යානුකූල වූ විශාල ඉදිරි පියවරක් ගැනීමට හැකි වන්නට පුළුවන. ක්රිස්තියානි දෘෂ්ටි කෝණයකින් බලනා කල, කලාව හා විද්යාව තුළ දැනුම මඟින් හොඳ සහ නරක අතරද, යහපත සහ අයහපත අතරද, සත්යය සහ වරද අතරද ඇති වෙනස දැනගැනීම කෙරෙහි එය සම්බන්ධ කර නොගන්නේ නම් එයින් අදහස් කරන්නේ කුමක්ද? නිදසුනක් වශයෙන්, යමෙකු විසින් කළ යුතුව ඇති සියල්ල වන්නේ අපූර්ව වූ කුසලතා හා දක්ෂතා තිබීම සදාචාරාත්මක හෝ ඉතා අවංක වූ දැහැමි දිවියකට සමාන නොවන බව දැකීම සඳහා ලෝකයේ අග්රගණයේ කලාකරුවන් ලෙස සැලකෙන ඇතැම් අයගේ ජීවිත ගැන මඳක් කියවා බැලීම වේ. යමෙකු හට තර්ක කළ හැකි දෙයක් වන්නේ, සමූහ විනාශය සඳහා ජීව විද්යාත්මක හෝ රසායනික අවි නිර්මාණය කිරීමේ කාර්යයට සම්බන්ධිත ශ්රේෂ්ඨ විද්යාඥයින් උසස් අධ්යාපනය ලැබූ, සුවිශේෂී කුසලතාවයන්ගෙන් යුත් අය විය හැකි නමුත්, ඔවුන්ගේ කාර්යයේ ඵලය කුමක් වන්නේද? යන්නයි. පෙර සඳහන් කළ පරිදි, නියතවශයෙන්ම දැනුම, එය තුළම පැවතීම යහපත් වූ දෙයක් නොවෙයි. `හිතෝපදේශ 1: 7 කියවන්න. සැබෑ ක්රිස්තියානි අධ්යාපනයේ වැදගත් වන්නේ කුමක්ද යන්න ගැන මෙම පාඨයෙන් හෙළි වන්නේ කෙසේද?` `එක් නොබෙල් ත්යාගලාභියෙකුද, අදේවවාදියෙකුද වූ විශ්වය සහ එහි ඇති භෞතික බලයන් පිළිබඳව අධ්යයනය කරනා මිනිසෙක් විසින් මෙසේ ලියන්නට විය: “විශ්වය වඩා තේරුම් ගත හැකි ලෙස පෙනෙන තරමට එය වඩා අර්ථ විරහිත ලෙසද පෙනෙන්නට වෙයි.” දැනුම, එය තුළම පැවතීම මඟින් එය අර්ථ විරහිත වනවා පමණක් නොව, ඊටත් වඩා යහපත්ව හඳුනා නොගත් වැරදි වලටද තුඩු දෙන්නේ කෙසේද යන්න ගැන මින් අපට කිව යුත්තේ කුමක්ද?`
Java
<?php namespace Censo\CensoBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * TipoViviendas * * @ORM\Table(name="tipo_viviendas") * @ORM\Entity */ class TipoViviendas { /** * @var integer * * @ORM\Column(name="id", type="bigint", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") * @ORM\SequenceGenerator(sequenceName="tipo_viviendas_id_seq", allocationSize=1, initialValue=1) */ private $id; /** * @var string * * @ORM\Column(name="nombre", type="string", length=255, nullable=false) */ private $nombre; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set nombre * * @param string $nombre * @return TipoViviendas */ public function setNombre($nombre) { $this->nombre = $nombre; return $this; } /** * Get nombre * * @return string */ public function getNombre() { return $this->nombre; } public function __toString() { return $this->getNombre(); } }
Java
# school_shop 校园易购,本人于2015年4,5月份开发,后因产品策划的太臃肿,存在一定bug,并在忙其它事,没空修复, 现在将其开源,供大家参考学习 - 注:后台采用SpringMvc开发(Maven),部署在[Openshift](https://www.openshift.com/)服务器,由于是国外免费服务器,所以响应速度比较慢 # Screenshots ![Main screen](/screenshots/main.png) ![Main menu](/screenshots/main_menu.png) ![Market chat](/screenshots/market_chat.png) ![Market publish](/screenshots/market_publish.png) ![Message](/screenshots/message.jpg) # Third-party libraries used - [SystemBarTint](https://github.com/jgilfelt/SystemBarTint) - [Gson](https://github.com/google/gson) - [android-async-http](https://github.com/loopj/android-async-http) - [Emojiconlibrary](https://github.com/rockerhieu/emojicon) - [nineoldandroids](https://github.com/JakeWharton/NineOldAndroids) - [七牛] - [友盟] # License ``` Copyright 2015 Owater 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. ```
Java
/* Generated by CIL v. 1.7.0 */ /* print_CIL_Input is false */ struct _IO_FILE; struct timeval; extern float strtof(char const *str , char const *endptr ) ; extern void signal(int sig , void *func ) ; typedef struct _IO_FILE FILE; extern int atoi(char const *s ) ; extern double strtod(char const *str , char const *endptr ) ; extern int fclose(void *stream ) ; extern void *fopen(char const *filename , char const *mode ) ; extern void abort() ; extern void exit(int status ) ; extern int raise(int sig ) ; extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; extern int strcmp(char const *a , char const *b ) ; extern int rand() ; extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; void RandomFunc(unsigned int input[1] , unsigned int output[1] ) ; extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; extern int gettimeofday(struct timeval *tv , void *tz , ...) ; extern int printf(char const *format , ...) ; int main(int argc , char *argv[] ) ; void megaInit(void) ; extern unsigned long strlen(char const *s ) ; extern long strtol(char const *str , char const *endptr , int base ) ; extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; struct timeval { long tv_sec ; long tv_usec ; }; extern void *malloc(unsigned long size ) ; extern int scanf(char const *format , ...) ; void megaInit(void) { { } } void RandomFunc(unsigned int input[1] , unsigned int output[1] ) { unsigned int state[1] ; unsigned int local1 ; char copy11 ; unsigned short copy12 ; { state[0UL] = (input[0UL] + 914778474UL) ^ 3462201355U; local1 = 0UL; while (local1 < input[1UL]) { if (state[0UL] > local1) { copy11 = *((char *)(& state[local1]) + 0); *((char *)(& state[local1]) + 0) = *((char *)(& state[local1]) + 1); *((char *)(& state[local1]) + 1) = copy11; copy12 = *((unsigned short *)(& state[0UL]) + 1); *((unsigned short *)(& state[0UL]) + 1) = *((unsigned short *)(& state[0UL]) + 0); *((unsigned short *)(& state[0UL]) + 0) = copy12; } else { state[0UL] |= (state[0UL] & 31U) << 4UL; state[local1] *= state[local1]; } local1 ++; } output[0UL] = state[0UL] << 5U; } } int main(int argc , char *argv[] ) { unsigned int input[1] ; unsigned int output[1] ; int randomFuns_i5 ; unsigned int randomFuns_value6 ; int randomFuns_main_i7 ; { megaInit(); if (argc != 2) { printf("Call this program with %i arguments\n", 1); exit(-1); } else { } randomFuns_i5 = 0; while (randomFuns_i5 < 1) { randomFuns_value6 = (unsigned int )strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == 460535040U) { printf("You win!\n"); } else { } randomFuns_main_i7 = 0; while (randomFuns_main_i7 < 1) { printf("%u\n", output[randomFuns_main_i7]); randomFuns_main_i7 ++; } } }
Java
/* _______ ________ \ \ / _____/ ____ ___ / | \/ \ ____/ __ \ / \ / | \ \_\ \ ___/| | \ \____|__ /\______ /\___ >___| / \/ \/ \/ \/ The MIT License (MIT) COPYRIGHT (C) 2016 FIXCOM, LLC 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, sub-license, 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 __NGEN_CALLBACK_HPP #define __NGEN_CALLBACK_HPP #include "Ngen.Delegate.hpp" namespace Ngen { /** @brief A function-call provider primarily used to bind object instances to member delegates before invocation. */ class ngen_api Callback { public: /** @brief Constructor. Default. */ Callback() : mThis(0), mFunc(0) {} /** @brief Constructor. (unknown, Delegate*). */ Callback(unknown _this, Delegate* function) : mThis(_this), mFunc(function) {} /** @brief Constructor. (Delegate*). */ Callback(Delegate* function) : mThis(0), mFunc(function) {} /** @brief Constructor. Copy. */ Callback(const Callback& copy) : mThis(copy.mThis), mFunc(copy.mFunc) {} /** @brief De-constructor. */ ~Callback() { mThis = null; mFunc = null; } /** @brief Determines if the callback is properly configured for an invocation. */ bool IsValid() const { if(!isnull(mFunc)) { if(mFunc->IsMember()) { return !isnull(mThis); } return true; } return false; } /** @brief operator==(const Callback&) */ bool operator==(const Callback& rhs) const { if(!isnull(mThis) && mThis != rhs.mThis) { return false; } return rhs.mFunc->EqualTo(mFunc); } /** @brief operator!=(const Callback&) */ bool operator!=(const Callback& rhs) const { if(!isnull(mThis) && mThis != rhs.mThis) { return true; } return !rhs.mFunc->EqualTo(mFunc); } /** @brief Invokes the callback using the given unknown parameter set. */ unknown Call(unknown* params) { return mFunc->operator()(mThis, params); } void MakeValid(unknown pointer) { mThis = pointer; } Type* ReturnType() const { return mFunc->ReturnType(); } Delegate* Function() const { return mFunc; } protected: unknown mThis; Delegate* mFunc; }; } #endif // __NGEN_CALLBACK_HPP
Java
package logbook.server.proxy; /** * 動作に必要なデータのみ取得するためのフィルターです。 * */ public class Filter { /** フィルターするContent-Type */ public static final String CONTENT_TYPE_FILTER = "text/plain"; /** キャプチャーするリクエストのバイトサイズ上限 */ public static final int MAX_POST_FIELD_SIZE = 1024 * 1024; /** setAttribute用のキー(Response) */ public static final String RESPONSE_BODY = "res-body"; /** setAttribute用のキー(Request) */ public static final String REQUEST_BODY = "req-body"; private static String serverName; /** * 鎮守府サーバー名を設定する * @param name 鎮守府サーバー名 */ public static void setServerName(String name) { serverName = name; } /** * 鎮守府サーバー名を取得する * @param name 鎮守府サーバー名 */ public static String getServerName() { return serverName; } /** * 鎮守府サーバー名を検出した場合true * * @return 鎮守府サーバー名を検出した場合true */ public static boolean isServerDetected() { return serverName != null; } /** * <p> * 取得が必要なデータかを調べます<br> * 鎮守府サーバーが検出された場合はサーバー名から必要かどうかを判別します<br> * 鎮守府サーバーが検出できていない場合は常にtrue<br> * * @param name サーバー名 * @return 取得が必要なデータか */ public static boolean isNeed(String name) { if ((!isServerDetected() || (isServerDetected() && serverName.equals(name)))) { return true; } return false; } /** * <p> * 取得が必要なデータかを調べます<br> * 鎮守府サーバーが検出された場合はサーバー名とContent-Typeから必要かどうかを判別します<br> * 鎮守府サーバーが検出できていない場合はContent-Typeから必要かどうかを判別します<br> * * @param name サーバー名 * @param contentType Content-Type * @return 取得が必要なデータか */ public static boolean isNeed(String name, String contentType) { if ((!isServerDetected() || serverName.equals(name)) && CONTENT_TYPE_FILTER.equals(contentType)) { return true; } return false; } }
Java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: ForwardDocumentEvent.proto package Diadoc.Api.Proto; public final class ForwardDocumentEventProtos { private ForwardDocumentEventProtos() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } public interface ForwardDocumentEventOrBuilder extends // @@protoc_insertion_point(interface_extends:Diadoc.Api.Proto.ForwardDocumentEvent) com.google.protobuf.MessageOrBuilder { /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ boolean hasTimestamp(); /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ Diadoc.Api.Proto.TimestampProtos.Timestamp getTimestamp(); /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder getTimestampOrBuilder(); /** * <code>optional string ToBoxId = 2;</code> */ boolean hasToBoxId(); /** * <code>optional string ToBoxId = 2;</code> */ java.lang.String getToBoxId(); /** * <code>optional string ToBoxId = 2;</code> */ com.google.protobuf.ByteString getToBoxIdBytes(); } /** * Protobuf type {@code Diadoc.Api.Proto.ForwardDocumentEvent} */ public static final class ForwardDocumentEvent extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:Diadoc.Api.Proto.ForwardDocumentEvent) ForwardDocumentEventOrBuilder { // Use ForwardDocumentEvent.newBuilder() to construct. private ForwardDocumentEvent(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private ForwardDocumentEvent(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final ForwardDocumentEvent defaultInstance; public static ForwardDocumentEvent getDefaultInstance() { return defaultInstance; } public ForwardDocumentEvent getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ForwardDocumentEvent( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder subBuilder = null; if (((bitField0_ & 0x00000001) == 0x00000001)) { subBuilder = timestamp_.toBuilder(); } timestamp_ = input.readMessage(Diadoc.Api.Proto.TimestampProtos.Timestamp.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(timestamp_); timestamp_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000001; break; } case 18: { com.google.protobuf.ByteString bs = input.readBytes(); bitField0_ |= 0x00000002; toBoxId_ = bs; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return Diadoc.Api.Proto.ForwardDocumentEventProtos.internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return Diadoc.Api.Proto.ForwardDocumentEventProtos.internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_fieldAccessorTable .ensureFieldAccessorsInitialized( Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.class, Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.Builder.class); } public static com.google.protobuf.Parser<ForwardDocumentEvent> PARSER = new com.google.protobuf.AbstractParser<ForwardDocumentEvent>() { public ForwardDocumentEvent parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ForwardDocumentEvent(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<ForwardDocumentEvent> getParserForType() { return PARSER; } private int bitField0_; public static final int TIMESTAMP_FIELD_NUMBER = 1; private Diadoc.Api.Proto.TimestampProtos.Timestamp timestamp_; /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public boolean hasTimestamp() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public Diadoc.Api.Proto.TimestampProtos.Timestamp getTimestamp() { return timestamp_; } /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder getTimestampOrBuilder() { return timestamp_; } public static final int TOBOXID_FIELD_NUMBER = 2; private java.lang.Object toBoxId_; /** * <code>optional string ToBoxId = 2;</code> */ public boolean hasToBoxId() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional string ToBoxId = 2;</code> */ public java.lang.String getToBoxId() { java.lang.Object ref = toBoxId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { toBoxId_ = s; } return s; } } /** * <code>optional string ToBoxId = 2;</code> */ public com.google.protobuf.ByteString getToBoxIdBytes() { java.lang.Object ref = toBoxId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); toBoxId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private void initFields() { timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance(); toBoxId_ = ""; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; if (hasTimestamp()) { if (!getTimestamp().isInitialized()) { memoizedIsInitialized = 0; return false; } } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeMessage(1, timestamp_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeBytes(2, getToBoxIdBytes()); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, timestamp_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, getToBoxIdBytes()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code Diadoc.Api.Proto.ForwardDocumentEvent} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:Diadoc.Api.Proto.ForwardDocumentEvent) Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEventOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return Diadoc.Api.Proto.ForwardDocumentEventProtos.internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return Diadoc.Api.Proto.ForwardDocumentEventProtos.internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_fieldAccessorTable .ensureFieldAccessorsInitialized( Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.class, Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.Builder.class); } // Construct using Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getTimestampFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); if (timestampBuilder_ == null) { timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance(); } else { timestampBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); toBoxId_ = ""; bitField0_ = (bitField0_ & ~0x00000002); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return Diadoc.Api.Proto.ForwardDocumentEventProtos.internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor; } public Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent getDefaultInstanceForType() { return Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.getDefaultInstance(); } public Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent build() { Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent buildPartial() { Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent result = new Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } if (timestampBuilder_ == null) { result.timestamp_ = timestamp_; } else { result.timestamp_ = timestampBuilder_.build(); } if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.toBoxId_ = toBoxId_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent) { return mergeFrom((Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent other) { if (other == Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.getDefaultInstance()) return this; if (other.hasTimestamp()) { mergeTimestamp(other.getTimestamp()); } if (other.hasToBoxId()) { bitField0_ |= 0x00000002; toBoxId_ = other.toBoxId_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (hasTimestamp()) { if (!getTimestamp().isInitialized()) { return false; } } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private Diadoc.Api.Proto.TimestampProtos.Timestamp timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< Diadoc.Api.Proto.TimestampProtos.Timestamp, Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder, Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder> timestampBuilder_; /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public boolean hasTimestamp() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public Diadoc.Api.Proto.TimestampProtos.Timestamp getTimestamp() { if (timestampBuilder_ == null) { return timestamp_; } else { return timestampBuilder_.getMessage(); } } /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public Builder setTimestamp(Diadoc.Api.Proto.TimestampProtos.Timestamp value) { if (timestampBuilder_ == null) { if (value == null) { throw new NullPointerException(); } timestamp_ = value; onChanged(); } else { timestampBuilder_.setMessage(value); } bitField0_ |= 0x00000001; return this; } /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public Builder setTimestamp( Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder builderForValue) { if (timestampBuilder_ == null) { timestamp_ = builderForValue.build(); onChanged(); } else { timestampBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; return this; } /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public Builder mergeTimestamp(Diadoc.Api.Proto.TimestampProtos.Timestamp value) { if (timestampBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001) && timestamp_ != Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance()) { timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.newBuilder(timestamp_).mergeFrom(value).buildPartial(); } else { timestamp_ = value; } onChanged(); } else { timestampBuilder_.mergeFrom(value); } bitField0_ |= 0x00000001; return this; } /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public Builder clearTimestamp() { if (timestampBuilder_ == null) { timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance(); onChanged(); } else { timestampBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder getTimestampBuilder() { bitField0_ |= 0x00000001; onChanged(); return getTimestampFieldBuilder().getBuilder(); } /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder getTimestampOrBuilder() { if (timestampBuilder_ != null) { return timestampBuilder_.getMessageOrBuilder(); } else { return timestamp_; } } /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ private com.google.protobuf.SingleFieldBuilder< Diadoc.Api.Proto.TimestampProtos.Timestamp, Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder, Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder> getTimestampFieldBuilder() { if (timestampBuilder_ == null) { timestampBuilder_ = new com.google.protobuf.SingleFieldBuilder< Diadoc.Api.Proto.TimestampProtos.Timestamp, Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder, Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder>( getTimestamp(), getParentForChildren(), isClean()); timestamp_ = null; } return timestampBuilder_; } private java.lang.Object toBoxId_ = ""; /** * <code>optional string ToBoxId = 2;</code> */ public boolean hasToBoxId() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional string ToBoxId = 2;</code> */ public java.lang.String getToBoxId() { java.lang.Object ref = toBoxId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { toBoxId_ = s; } return s; } else { return (java.lang.String) ref; } } /** * <code>optional string ToBoxId = 2;</code> */ public com.google.protobuf.ByteString getToBoxIdBytes() { java.lang.Object ref = toBoxId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); toBoxId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>optional string ToBoxId = 2;</code> */ public Builder setToBoxId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; toBoxId_ = value; onChanged(); return this; } /** * <code>optional string ToBoxId = 2;</code> */ public Builder clearToBoxId() { bitField0_ = (bitField0_ & ~0x00000002); toBoxId_ = getDefaultInstance().getToBoxId(); onChanged(); return this; } /** * <code>optional string ToBoxId = 2;</code> */ public Builder setToBoxIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; toBoxId_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:Diadoc.Api.Proto.ForwardDocumentEvent) } static { defaultInstance = new ForwardDocumentEvent(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:Diadoc.Api.Proto.ForwardDocumentEvent) } private static final com.google.protobuf.Descriptors.Descriptor internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\032ForwardDocumentEvent.proto\022\020Diadoc.Api" + ".Proto\032\017Timestamp.proto\"W\n\024ForwardDocume" + "ntEvent\022.\n\tTimestamp\030\001 \001(\0132\033.Diadoc.Api." + "Proto.Timestamp\022\017\n\007ToBoxId\030\002 \001(\tB\034B\032Forw" + "ardDocumentEventProtos" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { Diadoc.Api.Proto.TimestampProtos.getDescriptor(), }, assigner); internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor, new java.lang.String[] { "Timestamp", "ToBoxId", }); Diadoc.Api.Proto.TimestampProtos.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
Java
<!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 (version 1.7.0_55) on Fri Jun 20 06:34:49 EDT 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title>Uses of Class org.apache.solr.handler.dataimport.BinContentStreamDataSource (Solr 4.9.0 API)</title> <meta name="date" content="2014-06-20"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.solr.handler.dataimport.BinContentStreamDataSource (Solr 4.9.0 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/solr/handler/dataimport/BinContentStreamDataSource.html" title="class in org.apache.solr.handler.dataimport">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/solr/handler/dataimport/class-use/BinContentStreamDataSource.html" target="_top">Frames</a></li> <li><a href="BinContentStreamDataSource.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></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> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.solr.handler.dataimport.BinContentStreamDataSource" class="title">Uses of Class<br>org.apache.solr.handler.dataimport.BinContentStreamDataSource</h2> </div> <div class="classUseContainer">No usage of org.apache.solr.handler.dataimport.BinContentStreamDataSource</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/solr/handler/dataimport/BinContentStreamDataSource.html" title="class in org.apache.solr.handler.dataimport">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/solr/handler/dataimport/class-use/BinContentStreamDataSource.html" target="_top">Frames</a></li> <li><a href="BinContentStreamDataSource.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All 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> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright &copy; 2000-2014 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
Java
package saberapplications.pawpads.databinding; import android.databinding.BaseObservable; import android.databinding.BindingAdapter; import android.databinding.BindingConversion; import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; import saberapplications.pawpads.R; /** * Created by Stanislav Volnjanskij on 25.08.16. */ public class BindableDouble extends BaseObservable { private Double value; private String format="%f"; public Double get() { return value; } public void set(double value) { if (this.value == null || !this.value.equals(value)) { this.value = value; notifyChange(); } } public void setSilent(double value) { if (this.value == null || !this.value.equals(value)) { this.value = value; } } public BindableDouble(double value) { super(); this.value = value; } public BindableDouble() { super(); } @BindingConversion public static String convertIntegerToString(BindableDouble value) { if (value != null && value.get()!=null) return String.format(value.getFormat(), value.get()); else { return null; } } @BindingAdapter({"binding2way"}) public static void bindEditText(EditText view, final BindableDouble bindableDouble) { if (view.getTag(R.id.BIND_ID) == null) { view.setTag(R.id.BIND_ID, true); view.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { try { bindableDouble.setSilent(Double.parseDouble(s.toString())); } catch (Exception e) { } } @Override public void afterTextChanged(Editable s) { } }); } //initial value if (bindableDouble == null) return; Double newValue = bindableDouble.get(); if (newValue == null) return; String strValue= String.format(bindableDouble.getFormat(),newValue); if (!view.getText().toString().equals(strValue) ) { view.setText(strValue); } } /** * Number format to display in text field * @return */ public String getFormat() { return format; } /** *Set number format to display in text field * @param format */ public void setFormat(String format) { this.format = format; } }
Java
using UnityEngine; using System.Collections; public class EnemyDeadInfo { public int score = 0; public Transform transform; public bool headShot = false; }
Java
<?php /** * Elgg cron library. * * @package Elgg * @subpackage Core * @author Curverider Ltd * @link http://elgg.org/ */ /** The cron exception. */ class CronException extends Exception {} /** * Initialisation * */ function cron_init() { // Register a pagehandler for cron register_page_handler('cron','cron_page_handler'); } /** * Cron handler for redirecting pages. * * @param unknown_type $page */ function cron_page_handler($page) { global $CONFIG; if ($page[0]) { switch (strtolower($page[0])) { case 'minute' : case 'fiveminute' : case 'fifteenmin' : case 'halfhour' : case 'hourly' : case 'daily' : case 'weekly' : case 'monthly': case 'yearly' : case 'reboot' : set_input('period', $page[0]); break; default : throw new CronException(sprintf(elgg_echo('CronException:unknownperiod'), $page[0])); } // Include cron handler include($CONFIG->path . "engine/handlers/cron_handler.php"); } else forward(); } // Register a startup event register_elgg_event_handler('init','system','cron_init'); ?>
Java
package types import "gopkg.in/pg.v4/internal/parser" func AppendJSONB(b, jsonb []byte, quote int) []byte { if quote == 1 { b = append(b, '\'') } p := parser.New(jsonb) for p.Valid() { c := p.Read() switch c { case '\'': if quote == 1 { b = append(b, '\'', '\'') } else { b = append(b, '\'') } case '\000': continue case '\\': if p.Got("u0000") { b = append(b, "\\\\u0000"...) } else { b = append(b, '\\') if p.Valid() { b = append(b, p.Read()) } } default: b = append(b, c) } } if quote == 1 { b = append(b, '\'') } return b }
Java
#include <stdio.h> #include <ruby.h> #include <ruby/thread.h> #include <v8.h> #include <libplatform/libplatform.h> #include <ruby/encoding.h> #include <pthread.h> #include <unistd.h> #include <mutex> #include <math.h> using namespace v8; class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator { public: virtual void* Allocate(size_t length) { void* data = AllocateUninitialized(length); return data == NULL ? data : memset(data, 0, length); } virtual void* AllocateUninitialized(size_t length) { return malloc(length); } virtual void Free(void* data, size_t) { free(data); } }; typedef struct { const char* data; int raw_size; } SnapshotInfo; typedef struct { Isolate* isolate; ArrayBufferAllocator* allocator; StartupData* startup_data; bool interrupted; pid_t pid; // how many references to this isolate exist // we can't rely on Ruby's GC for this, because when destroying // objects, Ruby will destroy ruby objects first, then call the // extenstion's deallocators. In this case, that means it would // call `deallocate_isolate` _before_ `deallocate`, causing a segfault int refs_count; } IsolateInfo; typedef struct { IsolateInfo* isolate_info; Persistent<Context>* context; } ContextInfo; typedef struct { bool parsed; bool executed; bool terminated; bool json; Persistent<Value>* value; Persistent<Value>* message; Persistent<Value>* backtrace; } EvalResult; typedef struct { ContextInfo* context_info; Local<String>* eval; useconds_t timeout; EvalResult* result; } EvalParams; static VALUE rb_eScriptTerminatedError; static VALUE rb_eParseError; static VALUE rb_eScriptRuntimeError; static VALUE rb_cJavaScriptFunction; static VALUE rb_eSnapshotError; static VALUE rb_ePlatformAlreadyInitializedError; static VALUE rb_mJSON; static VALUE rb_cFailedV8Conversion; static VALUE rb_cDateTime = Qnil; static Platform* current_platform = NULL; static std::mutex platform_lock; static VALUE rb_platform_set_flag_as_str(VALUE _klass, VALUE flag_as_str) { bool platform_already_initialized = false; platform_lock.lock(); if (current_platform == NULL) { V8::SetFlagsFromString(RSTRING_PTR(flag_as_str), (int)RSTRING_LEN(flag_as_str)); } else { platform_already_initialized = true; } platform_lock.unlock(); // important to raise outside of the lock if (platform_already_initialized) { rb_raise(rb_ePlatformAlreadyInitializedError, "The V8 platform is already initialized"); } return Qnil; } static void init_v8() { // no need to wait for the lock if already initialized if (current_platform != NULL) return; platform_lock.lock(); if (current_platform == NULL) { V8::InitializeICU(); current_platform = platform::CreateDefaultPlatform(); V8::InitializePlatform(current_platform); V8::Initialize(); } platform_lock.unlock(); } void* nogvl_context_eval(void* arg) { EvalParams* eval_params = (EvalParams*)arg; EvalResult* result = eval_params->result; Isolate* isolate = eval_params->context_info->isolate_info->isolate; Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); TryCatch trycatch(isolate); Local<Context> context = eval_params->context_info->context->Get(isolate); Context::Scope context_scope(context); // in gvl flag isolate->SetData(0, (void*)false); // terminate ASAP isolate->SetData(1, (void*)false); MaybeLocal<Script> parsed_script = Script::Compile(context, *eval_params->eval); result->parsed = !parsed_script.IsEmpty(); result->executed = false; result->terminated = false; result->json = false; result->value = NULL; if (!result->parsed) { result->message = new Persistent<Value>(); result->message->Reset(isolate, trycatch.Exception()); } else { MaybeLocal<Value> maybe_value = parsed_script.ToLocalChecked()->Run(context); result->executed = !maybe_value.IsEmpty(); if (result->executed) { // arrays and objects get converted to json Local<Value> local_value = maybe_value.ToLocalChecked(); if ((local_value->IsObject() || local_value->IsArray()) && !local_value->IsDate() && !local_value->IsFunction()) { Local<Object> JSON = context->Global()->Get( String::NewFromUtf8(isolate, "JSON"))->ToObject(); Local<Function> stringify = JSON->Get(v8::String::NewFromUtf8(isolate, "stringify")) .As<Function>(); Local<Object> object = local_value->ToObject(); const unsigned argc = 1; Local<Value> argv[argc] = { object }; MaybeLocal<Value> json = stringify->Call(JSON, argc, argv); if (json.IsEmpty()) { result->executed = false; } else { result->json = true; Persistent<Value>* persistent = new Persistent<Value>(); persistent->Reset(isolate, json.ToLocalChecked()); result->value = persistent; } } else { Persistent<Value>* persistent = new Persistent<Value>(); persistent->Reset(isolate, local_value); result->value = persistent; } } } if (!result->executed || !result->parsed) { if (trycatch.HasCaught()) { if (!trycatch.Exception()->IsNull()) { result->message = new Persistent<Value>(); Local<Message> message = trycatch.Message(); char buf[1000]; int len; len = snprintf(buf, sizeof(buf), "%s at %s:%i:%i", *String::Utf8Value(message->Get()), *String::Utf8Value(message->GetScriptResourceName()->ToString()), message->GetLineNumber(), message->GetStartColumn()); Local<String> v8_message = String::NewFromUtf8(isolate, buf, NewStringType::kNormal, (int)len).ToLocalChecked(); result->message->Reset(isolate, v8_message); } else if(trycatch.HasTerminated()) { result->terminated = true; result->message = new Persistent<Value>(); Local<String> tmp = String::NewFromUtf8(isolate, "JavaScript was terminated (either by timeout or explicitly)"); result->message->Reset(isolate, tmp); } if (!trycatch.StackTrace().IsEmpty()) { result->backtrace = new Persistent<Value>(); result->backtrace->Reset(isolate, trycatch.StackTrace()->ToString()); } } } isolate->SetData(0, (void*)true); return NULL; } static VALUE convert_v8_to_ruby(Isolate* isolate, Handle<Value> &value) { Isolate::Scope isolate_scope(isolate); HandleScope scope(isolate); if (value->IsNull() || value->IsUndefined()){ return Qnil; } if (value->IsInt32()) { return INT2FIX(value->Int32Value()); } if (value->IsNumber()) { return rb_float_new(value->NumberValue()); } if (value->IsTrue()) { return Qtrue; } if (value->IsFalse()) { return Qfalse; } if (value->IsArray()) { VALUE rb_array = rb_ary_new(); Local<Array> arr = Local<Array>::Cast(value); for(uint32_t i=0; i < arr->Length(); i++) { Local<Value> element = arr->Get(i); VALUE rb_elem = convert_v8_to_ruby(isolate, element); if (rb_funcall(rb_elem, rb_intern("class"), 0) == rb_cFailedV8Conversion) { return rb_elem; } rb_ary_push(rb_array, rb_elem); } return rb_array; } if (value->IsFunction()){ return rb_funcall(rb_cJavaScriptFunction, rb_intern("new"), 0); } if (value->IsDate()){ double ts = Local<Date>::Cast(value)->ValueOf(); double secs = ts/1000; long nanos = round((secs - floor(secs)) * 1000000); return rb_time_new(secs, nanos); } if (value->IsObject()) { VALUE rb_hash = rb_hash_new(); TryCatch trycatch(isolate); Local<Context> context = Context::New(isolate); Local<Object> object = value->ToObject(); MaybeLocal<Array> maybe_props = object->GetOwnPropertyNames(context); if (!maybe_props.IsEmpty()) { Local<Array> props = maybe_props.ToLocalChecked(); for(uint32_t i=0; i < props->Length(); i++) { Local<Value> key = props->Get(i); VALUE rb_key = convert_v8_to_ruby(isolate, key); Local<Value> value = object->Get(key); // this may have failed due to Get raising if (trycatch.HasCaught()) { // TODO isolate code that translates execption to ruby // exception so we can properly return it return rb_funcall(rb_cFailedV8Conversion, rb_intern("new"), 1, rb_str_new2("")); } VALUE rb_value = convert_v8_to_ruby(isolate, value); rb_hash_aset(rb_hash, rb_key, rb_value); } } return rb_hash; } Local<String> rstr = value->ToString(); return rb_enc_str_new(*String::Utf8Value(rstr), rstr->Utf8Length(), rb_enc_find("utf-8")); } static Handle<Value> convert_ruby_to_v8(Isolate* isolate, VALUE value) { EscapableHandleScope scope(isolate); Local<Array> array; Local<Object> object; VALUE hash_as_array; VALUE pair; int i; long length; long fixnum; VALUE klass; switch (TYPE(value)) { case T_FIXNUM: fixnum = NUM2LONG(value); if (fixnum > INT_MAX) { return scope.Escape(Number::New(isolate, (double)fixnum)); } return scope.Escape(Integer::New(isolate, (int)fixnum)); case T_FLOAT: return scope.Escape(Number::New(isolate, NUM2DBL(value))); case T_STRING: return scope.Escape(String::NewFromUtf8(isolate, RSTRING_PTR(value), NewStringType::kNormal, (int)RSTRING_LEN(value)).ToLocalChecked()); case T_NIL: return scope.Escape(Null(isolate)); case T_TRUE: return scope.Escape(True(isolate)); case T_FALSE: return scope.Escape(False(isolate)); case T_ARRAY: length = RARRAY_LEN(value); array = Array::New(isolate, (int)length); for(i=0; i<length; i++) { array->Set(i, convert_ruby_to_v8(isolate, rb_ary_entry(value, i))); } return scope.Escape(array); case T_HASH: object = Object::New(isolate); hash_as_array = rb_funcall(value, rb_intern("to_a"), 0); length = RARRAY_LEN(hash_as_array); for(i=0; i<length; i++) { pair = rb_ary_entry(hash_as_array, i); object->Set(convert_ruby_to_v8(isolate, rb_ary_entry(pair, 0)), convert_ruby_to_v8(isolate, rb_ary_entry(pair, 1))); } return scope.Escape(object); case T_SYMBOL: value = rb_funcall(value, rb_intern("to_s"), 0); return scope.Escape(String::NewFromUtf8(isolate, RSTRING_PTR(value), NewStringType::kNormal, (int)RSTRING_LEN(value)).ToLocalChecked()); case T_DATA: klass = rb_funcall(value, rb_intern("class"), 0); if (klass == rb_cTime || klass == rb_cDateTime) { if (klass == rb_cDateTime) { value = rb_funcall(value, rb_intern("to_time"), 0); } value = rb_funcall(value, rb_intern("to_f"), 0); return scope.Escape(Date::New(isolate, NUM2DBL(value) * 1000)); } case T_OBJECT: case T_CLASS: case T_ICLASS: case T_MODULE: case T_REGEXP: case T_MATCH: case T_STRUCT: case T_BIGNUM: case T_FILE: case T_UNDEF: case T_NODE: default: return scope.Escape(String::NewFromUtf8(isolate, "Undefined Conversion")); } } static void unblock_eval(void *ptr) { EvalParams* eval = (EvalParams*)ptr; eval->context_info->isolate_info->interrupted = true; } static VALUE rb_snapshot_size(VALUE self, VALUE str) { SnapshotInfo* snapshot_info; Data_Get_Struct(self, SnapshotInfo, snapshot_info); return INT2NUM(snapshot_info->raw_size); } static VALUE rb_snapshot_load(VALUE self, VALUE str) { SnapshotInfo* snapshot_info; Data_Get_Struct(self, SnapshotInfo, snapshot_info); init_v8(); StartupData startup_data = V8::CreateSnapshotDataBlob(RSTRING_PTR(str)); if (startup_data.data == NULL && startup_data.raw_size == 0) { rb_raise(rb_eSnapshotError, "Could not create snapshot, most likely the source is incorrect"); } snapshot_info->data = startup_data.data; snapshot_info->raw_size = startup_data.raw_size; return Qnil; } static VALUE rb_snapshot_warmup(VALUE self, VALUE str) { SnapshotInfo* snapshot_info; Data_Get_Struct(self, SnapshotInfo, snapshot_info); init_v8(); StartupData cold_startup_data = {snapshot_info->data, snapshot_info->raw_size}; StartupData warm_startup_data = V8::WarmUpSnapshotDataBlob(cold_startup_data, RSTRING_PTR(str)); if (warm_startup_data.data == NULL && warm_startup_data.raw_size == 0) { rb_raise(rb_eSnapshotError, "Could not warm up snapshot, most likely the source is incorrect"); } else { delete[] snapshot_info->data; snapshot_info->data = warm_startup_data.data; snapshot_info->raw_size = warm_startup_data.raw_size; } return self; } static VALUE rb_isolate_init_with_snapshot(VALUE self, VALUE snapshot) { IsolateInfo* isolate_info; Data_Get_Struct(self, IsolateInfo, isolate_info); init_v8(); isolate_info->allocator = new ArrayBufferAllocator(); isolate_info->interrupted = false; isolate_info->refs_count = 1; Isolate::CreateParams create_params; create_params.array_buffer_allocator = isolate_info->allocator; StartupData* startup_data = NULL; if (!NIL_P(snapshot)) { SnapshotInfo* snapshot_info; Data_Get_Struct(snapshot, SnapshotInfo, snapshot_info); int raw_size = snapshot_info->raw_size; char* data = new char[raw_size]; memcpy(data, snapshot_info->data, sizeof(char) * raw_size); startup_data = new StartupData; startup_data->data = data; startup_data->raw_size = raw_size; create_params.snapshot_blob = startup_data; } isolate_info->startup_data = startup_data; isolate_info->isolate = Isolate::New(create_params); return Qnil; } static VALUE rb_isolate_idle_notification(VALUE self, VALUE idle_time_in_ms) { IsolateInfo* isolate_info; Data_Get_Struct(self, IsolateInfo, isolate_info); return isolate_info->isolate->IdleNotification(NUM2INT(idle_time_in_ms)) ? Qtrue : Qfalse; } static VALUE rb_context_init_with_isolate(VALUE self, VALUE isolate) { ContextInfo* context_info; Data_Get_Struct(self, ContextInfo, context_info); init_v8(); IsolateInfo* isolate_info; Data_Get_Struct(isolate, IsolateInfo, isolate_info); context_info->isolate_info = isolate_info; isolate_info->refs_count++; { Locker lock(isolate_info->isolate); Isolate::Scope isolate_scope(isolate_info->isolate); HandleScope handle_scope(isolate_info->isolate); Local<Context> context = Context::New(isolate_info->isolate); context_info->context = new Persistent<Context>(); context_info->context->Reset(isolate_info->isolate, context); } if (Qnil == rb_cDateTime && rb_funcall(rb_cObject, rb_intern("const_defined?"), 1, rb_str_new2("DateTime")) == Qtrue) { rb_cDateTime = rb_const_get(rb_cObject, rb_intern("DateTime")); } return Qnil; } static VALUE rb_context_eval_unsafe(VALUE self, VALUE str) { EvalParams eval_params; EvalResult eval_result; ContextInfo* context_info; VALUE result; VALUE message = Qnil; VALUE backtrace = Qnil; Data_Get_Struct(self, ContextInfo, context_info); Isolate* isolate = context_info->isolate_info->isolate; { Locker lock(isolate); Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); Local<String> eval = String::NewFromUtf8(isolate, RSTRING_PTR(str), NewStringType::kNormal, (int)RSTRING_LEN(str)).ToLocalChecked(); eval_params.context_info = context_info; eval_params.eval = &eval; eval_params.result = &eval_result; eval_params.timeout = 0; VALUE timeout = rb_iv_get(self, "@timeout"); if (timeout != Qnil) { eval_params.timeout = (useconds_t)NUM2LONG(timeout); } eval_result.message = NULL; eval_result.backtrace = NULL; rb_thread_call_without_gvl(nogvl_context_eval, &eval_params, unblock_eval, &eval_params); if (eval_result.message != NULL) { Local<Value> tmp = Local<Value>::New(isolate, *eval_result.message); message = convert_v8_to_ruby(isolate, tmp); eval_result.message->Reset(); delete eval_result.message; } if (eval_result.backtrace != NULL) { Local<Value> tmp = Local<Value>::New(isolate, *eval_result.backtrace); backtrace = convert_v8_to_ruby(isolate, tmp); eval_result.backtrace->Reset(); delete eval_result.backtrace; } } // NOTE: this is very important, we can not do an rb_raise from within // a v8 scope, if we do the scope is never cleaned up properly and we leak if (!eval_result.parsed) { if(TYPE(message) == T_STRING) { rb_raise(rb_eParseError, "%s", RSTRING_PTR(message)); } else { rb_raise(rb_eParseError, "Unknown JavaScript Error during parse"); } } if (!eval_result.executed) { VALUE ruby_exception = rb_iv_get(self, "@current_exception"); if (ruby_exception == Qnil) { ruby_exception = eval_result.terminated ? rb_eScriptTerminatedError : rb_eScriptRuntimeError; // exception report about what happened if(TYPE(backtrace) == T_STRING) { rb_raise(ruby_exception, "%s", RSTRING_PTR(backtrace)); } else if(TYPE(message) == T_STRING) { rb_raise(ruby_exception, "%s", RSTRING_PTR(message)); } else { rb_raise(ruby_exception, "Unknown JavaScript Error during execution"); } } else { VALUE rb_str = rb_funcall(ruby_exception, rb_intern("to_s"), 0); rb_raise(CLASS_OF(ruby_exception), "%s", RSTRING_PTR(rb_str)); } } // New scope for return value { Locker lock(isolate); Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); Local<Value> tmp = Local<Value>::New(isolate, *eval_result.value); if (eval_result.json) { Local<String> rstr = tmp->ToString(); VALUE json_string = rb_enc_str_new(*String::Utf8Value(rstr), rstr->Utf8Length(), rb_enc_find("utf-8")); result = rb_funcall(rb_mJSON, rb_intern("parse"), 1, json_string); } else { result = convert_v8_to_ruby(isolate, tmp); } eval_result.value->Reset(); delete eval_result.value; } if (rb_funcall(result, rb_intern("class"), 0) == rb_cFailedV8Conversion) { // TODO try to recover stack trace from the conversion error rb_raise(rb_eScriptRuntimeError, "Error converting JS object to Ruby object"); } return result; } typedef struct { VALUE callback; int length; VALUE* args; bool failed; } protected_callback_data; static VALUE protected_callback(VALUE rdata) { protected_callback_data* data = (protected_callback_data*)rdata; VALUE result; if (data->length > 0) { result = rb_funcall2(data->callback, rb_intern("call"), data->length, data->args); } else { result = rb_funcall(data->callback, rb_intern("call"), 0); } return result; } static VALUE rescue_callback(VALUE rdata, VALUE exception) { protected_callback_data* data = (protected_callback_data*)rdata; data->failed = true; return exception; } void* gvl_ruby_callback(void* data) { FunctionCallbackInfo<Value>* args = (FunctionCallbackInfo<Value>*)data; VALUE* ruby_args = NULL; int length = args->Length(); VALUE callback; VALUE result; VALUE self; { HandleScope scope(args->GetIsolate()); Handle<External> external = Handle<External>::Cast(args->Data()); VALUE* self_pointer = (VALUE*)(external->Value()); self = *self_pointer; callback = rb_iv_get(self, "@callback"); if (length > 0) { ruby_args = ALLOC_N(VALUE, length); } for (int i = 0; i < length; i++) { Local<Value> value = ((*args)[i]).As<Value>(); ruby_args[i] = convert_v8_to_ruby(args->GetIsolate(), value); } } // may raise exception stay clear of handle scope protected_callback_data callback_data; callback_data.length = length; callback_data.callback = callback; callback_data.args = ruby_args; callback_data.failed = false; if ((bool)args->GetIsolate()->GetData(1) == true) { args->GetIsolate()->ThrowException(String::NewFromUtf8(args->GetIsolate(), "Terminated execution during tansition from Ruby to JS")); V8::TerminateExecution(args->GetIsolate()); return NULL; } result = rb_rescue2((VALUE(*)(...))&protected_callback, (VALUE)(&callback_data), (VALUE(*)(...))&rescue_callback, (VALUE)(&callback_data), rb_eException, (VALUE)0); if(callback_data.failed) { VALUE parent = rb_iv_get(self, "@parent"); rb_iv_set(parent, "@current_exception", result); args->GetIsolate()->ThrowException(String::NewFromUtf8(args->GetIsolate(), "Ruby exception")); } else { HandleScope scope(args->GetIsolate()); Handle<Value> v8_result = convert_ruby_to_v8(args->GetIsolate(), result); args->GetReturnValue().Set(v8_result); } if (length > 0) { xfree(ruby_args); } if ((bool)args->GetIsolate()->GetData(1) == true) { Isolate* isolate = args->GetIsolate(); V8::TerminateExecution(isolate); } return NULL; } static void ruby_callback(const FunctionCallbackInfo<Value>& args) { bool has_gvl = (bool)args.GetIsolate()->GetData(0); if(has_gvl) { gvl_ruby_callback((void*)&args); } else { rb_thread_call_with_gvl(gvl_ruby_callback, (void*)(&args)); } } static VALUE rb_external_function_notify_v8(VALUE self) { ContextInfo* context_info; VALUE parent = rb_iv_get(self, "@parent"); VALUE name = rb_iv_get(self, "@name"); VALUE parent_object = rb_iv_get(self, "@parent_object"); VALUE parent_object_eval = rb_iv_get(self, "@parent_object_eval"); bool parse_error = false; bool attach_error = false; Data_Get_Struct(parent, ContextInfo, context_info); Isolate* isolate = context_info->isolate_info->isolate; { Locker lock(isolate); Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); Local<Context> context = context_info->context->Get(isolate); Context::Scope context_scope(context); Local<String> v8_str = String::NewFromUtf8(isolate, RSTRING_PTR(name), NewStringType::kNormal, (int)RSTRING_LEN(name)).ToLocalChecked(); // copy self so we can access from v8 external VALUE* self_copy; Data_Get_Struct(self, VALUE, self_copy); *self_copy = self; Local<Value> external = External::New(isolate, self_copy); if (parent_object == Qnil) { context->Global()->Set(v8_str, FunctionTemplate::New(isolate, ruby_callback, external)->GetFunction()); } else { Local<String> eval = String::NewFromUtf8(isolate, RSTRING_PTR(parent_object_eval), NewStringType::kNormal, (int)RSTRING_LEN(parent_object_eval)).ToLocalChecked(); MaybeLocal<Script> parsed_script = Script::Compile(context, eval); if (parsed_script.IsEmpty()) { parse_error = true; } else { MaybeLocal<Value> maybe_value = parsed_script.ToLocalChecked()->Run(context); attach_error = true; if (!maybe_value.IsEmpty()) { Local<Value> value = maybe_value.ToLocalChecked(); if (value->IsObject()){ value.As<Object>()->Set(v8_str, FunctionTemplate::New(isolate, ruby_callback, external)->GetFunction()); attach_error = false; } } } } } // always raise out of V8 context if (parse_error) { rb_raise(rb_eParseError, "Invalid object %s", RSTRING_PTR(parent_object)); } if (attach_error) { rb_raise(rb_eParseError, "Was expecting %s to be an object", RSTRING_PTR(parent_object)); } return Qnil; } void maybe_free_isolate_info(IsolateInfo* isolate_info) { // an isolate can only be freed if no Isolate or Context (ruby) object // still need it if (isolate_info == NULL || isolate_info->refs_count > 0) { return; } if (isolate_info->isolate) { Locker lock(isolate_info->isolate); } if (isolate_info->isolate) { if (isolate_info->interrupted) { fprintf(stderr, "WARNING: V8 isolate was interrupted by Ruby, it can not be disposed and memory will not be reclaimed till the Ruby process exits.\n"); } else { if (isolate_info->pid != getpid()) { fprintf(stderr, "WARNING: V8 isolate was forked, it can not be disposed and memory will not be reclaimed till the Ruby process exits.\n"); } else { isolate_info->isolate->Dispose(); } } isolate_info->isolate = NULL; } if (isolate_info->startup_data) { delete[] isolate_info->startup_data->data; delete isolate_info->startup_data; } delete isolate_info->allocator; xfree(isolate_info); } void deallocate_isolate(void* data) { IsolateInfo* isolate_info = (IsolateInfo*) data; isolate_info->refs_count--; maybe_free_isolate_info(isolate_info); } void deallocate(void* data) { ContextInfo* context_info = (ContextInfo*)data; IsolateInfo* isolate_info = context_info->isolate_info; if (context_info->context && isolate_info && isolate_info->isolate) { Locker lock(isolate_info->isolate); v8::Isolate::Scope isolate_scope(isolate_info->isolate); context_info->context->Reset(); delete context_info->context; } if (isolate_info) { isolate_info->refs_count--; maybe_free_isolate_info(isolate_info); } } void deallocate_external_function(void * data) { xfree(data); } void deallocate_snapshot(void * data) { SnapshotInfo* snapshot_info = (SnapshotInfo*)data; delete[] snapshot_info->data; xfree(snapshot_info); } VALUE allocate_external_function(VALUE klass) { VALUE* self = ALLOC(VALUE); return Data_Wrap_Struct(klass, NULL, deallocate_external_function, (void*)self); } VALUE allocate(VALUE klass) { ContextInfo* context_info = ALLOC(ContextInfo); context_info->isolate_info = NULL; context_info->context = NULL; return Data_Wrap_Struct(klass, NULL, deallocate, (void*)context_info); } VALUE allocate_snapshot(VALUE klass) { SnapshotInfo* snapshot_info = ALLOC(SnapshotInfo); snapshot_info->data = NULL; snapshot_info->raw_size = 0; return Data_Wrap_Struct(klass, NULL, deallocate_snapshot, (void*)snapshot_info); } VALUE allocate_isolate(VALUE klass) { IsolateInfo* isolate_info = ALLOC(IsolateInfo); isolate_info->isolate = NULL; isolate_info->allocator = NULL; isolate_info->startup_data = NULL; isolate_info->interrupted = false; isolate_info->refs_count = 0; isolate_info->pid = getpid(); return Data_Wrap_Struct(klass, NULL, deallocate_isolate, (void*)isolate_info); } static VALUE rb_context_stop(VALUE self) { ContextInfo* context_info; Data_Get_Struct(self, ContextInfo, context_info); Isolate* isolate = context_info->isolate_info->isolate; // flag for termination isolate->SetData(1, (void*)true); V8::TerminateExecution(isolate); rb_funcall(self, rb_intern("stop_attached"), 0); return Qnil; } extern "C" { void Init_mini_racer_extension ( void ) { VALUE rb_mMiniRacer = rb_define_module("MiniRacer"); VALUE rb_cContext = rb_define_class_under(rb_mMiniRacer, "Context", rb_cObject); VALUE rb_cSnapshot = rb_define_class_under(rb_mMiniRacer, "Snapshot", rb_cObject); VALUE rb_cIsolate = rb_define_class_under(rb_mMiniRacer, "Isolate", rb_cObject); VALUE rb_cPlatform = rb_define_class_under(rb_mMiniRacer, "Platform", rb_cObject); VALUE rb_eEvalError = rb_define_class_under(rb_mMiniRacer, "EvalError", rb_eStandardError); rb_eScriptTerminatedError = rb_define_class_under(rb_mMiniRacer, "ScriptTerminatedError", rb_eEvalError); rb_eParseError = rb_define_class_under(rb_mMiniRacer, "ParseError", rb_eEvalError); rb_eScriptRuntimeError = rb_define_class_under(rb_mMiniRacer, "RuntimeError", rb_eEvalError); rb_cJavaScriptFunction = rb_define_class_under(rb_mMiniRacer, "JavaScriptFunction", rb_cObject); rb_eSnapshotError = rb_define_class_under(rb_mMiniRacer, "SnapshotError", rb_eStandardError); rb_ePlatformAlreadyInitializedError = rb_define_class_under(rb_mMiniRacer, "PlatformAlreadyInitialized", rb_eStandardError); rb_cFailedV8Conversion = rb_define_class_under(rb_mMiniRacer, "FailedV8Conversion", rb_cObject); rb_mJSON = rb_define_module("JSON"); VALUE rb_cExternalFunction = rb_define_class_under(rb_cContext, "ExternalFunction", rb_cObject); rb_define_method(rb_cContext, "stop", (VALUE(*)(...))&rb_context_stop, 0); rb_define_alloc_func(rb_cContext, allocate); rb_define_alloc_func(rb_cSnapshot, allocate_snapshot); rb_define_alloc_func(rb_cIsolate, allocate_isolate); rb_define_private_method(rb_cContext, "eval_unsafe",(VALUE(*)(...))&rb_context_eval_unsafe, 1); rb_define_private_method(rb_cContext, "init_with_isolate",(VALUE(*)(...))&rb_context_init_with_isolate, 1); rb_define_private_method(rb_cExternalFunction, "notify_v8", (VALUE(*)(...))&rb_external_function_notify_v8, 0); rb_define_alloc_func(rb_cExternalFunction, allocate_external_function); rb_define_method(rb_cSnapshot, "size", (VALUE(*)(...))&rb_snapshot_size, 0); rb_define_method(rb_cSnapshot, "warmup!", (VALUE(*)(...))&rb_snapshot_warmup, 1); rb_define_private_method(rb_cSnapshot, "load", (VALUE(*)(...))&rb_snapshot_load, 1); rb_define_method(rb_cIsolate, "idle_notification", (VALUE(*)(...))&rb_isolate_idle_notification, 1); rb_define_private_method(rb_cIsolate, "init_with_snapshot",(VALUE(*)(...))&rb_isolate_init_with_snapshot, 1); rb_define_singleton_method(rb_cPlatform, "set_flag_as_str!", (VALUE(*)(...))&rb_platform_set_flag_as_str, 1); } }
Java
// This source code is dual-licensed under the Apache License, version // 2.0, and the Mozilla Public License, version 1.1. // // The APL v2.0: // //--------------------------------------------------------------------------- // Copyright (C) 2007-2014 GoPivotal, 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. //--------------------------------------------------------------------------- // // The MPL v1.1: // //--------------------------------------------------------------------------- // The contents of this file are subject to the Mozilla Public License // Version 1.1 (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.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See // the License for the specific language governing rights and // limitations under the License. // // The Original Code is RabbitMQ. // // The Initial Developer of the Original Code is GoPivotal, Inc. // Copyright (c) 2007-2014 GoPivotal, Inc. All rights reserved. //--------------------------------------------------------------------------- using System; using System.Collections.Generic; namespace RabbitMQ.Client.Impl { public abstract class StreamProperties : ContentHeaderBase, IStreamProperties { public abstract string ContentType { get; set; } public abstract string ContentEncoding { get; set; } public abstract IDictionary<string, object> Headers { get; set; } public abstract byte Priority { get; set; } public abstract AmqpTimestamp Timestamp { get; set; } public abstract void ClearContentType(); public abstract void ClearContentEncoding(); public abstract void ClearHeaders(); public abstract void ClearPriority(); public abstract void ClearTimestamp(); public abstract bool IsContentTypePresent(); public abstract bool IsContentEncodingPresent(); public abstract bool IsHeadersPresent(); public abstract bool IsPriorityPresent(); public abstract bool IsTimestampPresent(); public override object Clone() { StreamProperties clone = MemberwiseClone() as StreamProperties; if (IsHeadersPresent()) { clone.Headers = new Dictionary<string, object>(); foreach (KeyValuePair<string, object> entry in Headers) clone.Headers[entry.Key] = entry.Value; } return clone; } } }
Java
# Slither.io bot Just for fun and AI. Written in Javascript, this is a project which the aim is to make a computer play against humans inside a human-driven game, which is in this case Slither.io. The goal is simple - try and make the snake live and get as long as possible. [![Gitter](https://img.shields.io/gitter/room/nwjs/nw.js.svg?maxAge=2592000)](https://gitter.im/ErmiyaEskandary/Slither.io-bot?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) # Table of Contents - [Installation instructions](https://github.com/ErmiyaEskandary/Slither.io-bot#installation-instructions) - [Visual tutorial](https://github.com/ErmiyaEskandary/Slither.io-bot#visual-tutorial) - [Text tutorial](https://github.com/ErmiyaEskandary/Slither.io-bot#text-tutorial) - [Hotkeys](https://github.com/ErmiyaEskandary/Slither.io-bot#hotkeys) - [Contributing](https://github.com/ErmiyaEskandary/Slither.io-bot#contributing) - [Documentation](https://github.com/ErmiyaEskandary/Slither.io-bot#documentation) - [Authors](https://github.com/ErmiyaEskandary/Slither.io-bot#authors) - [License](https://github.com/ErmiyaEskandary/Slither.io-bot#license) # Installation instructions **NOTE: these instructions are for installing the bot at a production-ready, fully working and a fully tested state, which is recommended. For the latest bleeding edge code, which may not be fully tested, refer to the bot.user.js file in the current default develop branch as the instructions below refer the bot file in the master branch.** ## Interactive tutorial http://slither.jlynx.net/ ## Visual tutorial https://www.youtube.com/watch?v=d7mkAgQNuCA - Created by http://slither.jlynx.net/ https://youtu.be/mlEKp-ZAi7w - Created by http://slithere.com/ https://youtu.be/QF9JBMi-fLo?t=38s - Created by SeppeTutorials https://youtu.be/IpsAazbVIcw - Created by TheFlyingPlatypus ## Text tutorial If you are on chrome, download the [TamperMonkey](https://chrome.google.com/webstore/detail/tampermonkey/dhdgffkkebhmkfjojejmpbldmpobfkfo?hl=en) extension. On other browsers, use the [GreaseMonkey](https://addons.mozilla.org/en-GB/firefox/addon/greasemonkey/) extension. Once installed, click on [this](https://github.com/ErmiyaEskandary/slither.io-bot/raw/master/bot.user.js), and choose **Install**. Go to [slither.io](http://slither.io/), and enjoy ! # Hotkeys Key | Result ---|--- T / Right Click | Bot enabled/disabled **O** | **Mobile rendering - Try this if you experience lag** A/S | Radius multiplier D | Quick radius change - "approach" and "avoid" mode I | Auto respawn G | Leaderboard overlay Y | Visual debugging U | Log debugging H | Overlays B | Background Change Mouse wheel | Zoom in/out Z | Reset zoom ESC | Quick respawn Q | Quit to menu # Contributing Please refer to the [guidelines for contributing](https://github.com/ErmiyaEskandary/Slither.io-bot/blob/master/.github/CONTRIBUTING.md) for all the information you need. [Check the wiki for additional information](https://github.com/ErmiyaEskandary/Slither.io-bot/wiki) NOTE : For existing collaborators, please refer to the [DEVELOPER.md file.](https://github.com/ErmiyaEskandary/Slither.io-bot/blob/master/DEVELOPER.md) ## Documentation [![Documentation Status](https://readthedocs.org/projects/slitherio-bot/badge/?version=latest)](http://slitherio-bot.readthedocs.io/en/latest/?badge=latest) The [online documentation](http://slitherio-bot.readthedocs.io/en/master/) is maintained in the `/docs` directory. # Authors **Ermiya Eskandary & Théophile Cailliau (ErmiyaEskandary & FliiFe)** Started as a collaborative and fun project between me and FliiFe on 2016/04/20, with this : > Slither.io bot could be cool # License **Licensed under the Mozilla Public License, v. 2.0** Read LICENSE.md for more info.
Java
'use strict' const dotenv = require('dotenv') const ENV = process.env.NODE_ENV || 'development' if (ENV === 'development') dotenv.load() const config = { ENV: process.env.NODE_ENV, PORT: process.env.PORT, PROXY_URI: process.env.PROXY_URI, WEBHOOK_URL: process.env.WEBHOOK_URL, BATTLESHIP_COMMAND_TOKEN: process.env.BATTLESHIP_COMMAND_TOKEN, SLACK_TOKEN: process.env.SLACK_TOKEN, ICON_EMOJI: ':passenger_ship:', USERNAME: "Battleship" } module.exports = (key) => { if (!key) return config return config[key] }
Java
SET NOCOUNT ON; SELECT T1.Client_Version0 as VersionNumber, CASE WHEN T1.Client_Version0 = '5.00.7711.0000' THEN 'ConfigMgr 2012 RTM' WHEN T1.Client_Version0 = '5.00.7711.0200' THEN 'ConfigMgr 2012 RTM CU1' WHEN T1.Client_Version0 = '5.00.7711.0301' THEN 'ConfigMgr 2012 RTM CU2' WHEN T1.Client_Version0 = '5.00.7804.1000' THEN 'ConfigMgr 2012 SP1' WHEN T1.Client_Version0 = '5.00.7804.1202' THEN 'ConfigMgr 2012 SP1 CU1' WHEN T1.Client_Version0 = '5.00.7804.1300' THEN 'ConfigMgr 2012 SP1 CU2' WHEN T1.Client_Version0 = '5.00.7804.1400' THEN 'ConfigMgr 2012 SP1 CU3' WHEN T1.Client_Version0 = '5.00.7804.1500' THEN 'ConfigMgr 2012 SP1 CU4' WHEN T1.Client_Version0 = '5.00.7804.1600' THEN 'ConfigMgr 2012 SP1 CU5' WHEN T1.Client_Version0 = '5.00.7958.1000' THEN 'ConfigMgr 2012 R2' WHEN T1.Client_Version0 = '5.00.7958.1101' THEN 'ConfigMgr 2012 R2 with KB290500' WHEN T1.Client_Version0 = '5.00.7958.1203' THEN 'ConfigMgr 2012 R2 CU1' WHEN T1.Client_Version0 = '5.00.7958.1303' THEN 'ConfigMgr 2012 R2 CU2' WHEN T1.Client_Version0 = '5.00.7958.1401' THEN 'ConfigMgr 2012 R2 CU3' WHEN T1.Client_Version0 = '5.00.7958.1501' THEN 'ConfigMgr 2012 R2 CU4' WHEN T1.Client_Version0 = '5.00.7958.1601' THEN 'ConfigMgr 2012 R2 CU5' WHEN T1.Client_Version0 = '5.00.8239.1000' THEN 'ConfigMgr 2012 R2 SP1' WHEN T1.Client_Version0 = '5.00.8239.1203' THEN 'ConfigMgr 2012 R2 SP1 CU1' WHEN T1.Client_Version0 = '5.00.8239.1301' THEN 'ConfigMgr 2012 R2 SP1 CU2' WHEN T1.Client_Version0 = '5.00.8239.1403' THEN 'ConfigMgr 2012 R2 SP1 CU3' WHEN T1.Client_Version0 = '5.00.8325.1000' THEN 'ConfigMgr Update 1511' WHEN T1.Client_Version0 = '5.00.8355.1000' THEN 'ConfigMgr Update 1602' WHEN T1.Client_Version0 = '5.00.8355.1306' THEN 'ConfigMgr Update 1602 UR1' WHEN T1.Client_Version0 = '5.00.8412.1007' THEN 'ConfigMgr Update 1606' WHEN T1.Client_Version0 = '5.00.8412.1307' THEN 'ConfigMgr Update 1606 UR1' ELSE T1.Client_Version0 END as 'Description', COUNT(T1.ResourceID) as 'Total', T1.ResourceID MachineId FROM v_R_System_Valid T1 GROUP BY T1.Client_Version0, T1.ResourceID ORDER BY Total DESC
Java
/* MACHINE GENERATED FILE, DO NOT EDIT */ #include <jni.h> #include "extgl.h" typedef GL_APICALL void (GL_APIENTRY *glTexStorage1DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); typedef GL_APICALL void (GL_APIENTRY *glTexStorage2DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); typedef GL_APICALL void (GL_APIENTRY *glTexStorage3DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); typedef GL_APICALL void (GL_APIENTRY *glTextureStorage1DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); typedef GL_APICALL void (GL_APIENTRY *glTextureStorage2DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); typedef GL_APICALL void (GL_APIENTRY *glTextureStorage3DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); static glTexStorage1DEXTPROC glTexStorage1DEXT; static glTexStorage2DEXTPROC glTexStorage2DEXT; static glTexStorage3DEXTPROC glTexStorage3DEXT; static glTextureStorage1DEXTPROC glTextureStorage1DEXT; static glTextureStorage2DEXTPROC glTextureStorage2DEXT; static glTextureStorage3DEXTPROC glTextureStorage3DEXT; static void JNICALL Java_org_lwjgl_opengles_EXTTextureStorage_nglTexStorage1DEXT(JNIEnv *env, jclass clazz, jint target, jint levels, jint internalformat, jint width) { glTexStorage1DEXT(target, levels, internalformat, width); } static void JNICALL Java_org_lwjgl_opengles_EXTTextureStorage_nglTexStorage2DEXT(JNIEnv *env, jclass clazz, jint target, jint levels, jint internalformat, jint width, jint height) { glTexStorage2DEXT(target, levels, internalformat, width, height); } static void JNICALL Java_org_lwjgl_opengles_EXTTextureStorage_nglTexStorage3DEXT(JNIEnv *env, jclass clazz, jint target, jint levels, jint internalformat, jint width, jint height, jint depth) { glTexStorage3DEXT(target, levels, internalformat, width, height, depth); } static void JNICALL Java_org_lwjgl_opengles_EXTTextureStorage_nglTextureStorage1DEXT(JNIEnv *env, jclass clazz, jint texture, jint target, jint levels, jint internalformat, jint width) { glTextureStorage1DEXT(texture, target, levels, internalformat, width); } static void JNICALL Java_org_lwjgl_opengles_EXTTextureStorage_nglTextureStorage2DEXT(JNIEnv *env, jclass clazz, jint texture, jint target, jint levels, jint internalformat, jint width, jint height) { glTextureStorage2DEXT(texture, target, levels, internalformat, width, height); } static void JNICALL Java_org_lwjgl_opengles_EXTTextureStorage_nglTextureStorage3DEXT(JNIEnv *env, jclass clazz, jint texture, jint target, jint levels, jint internalformat, jint width, jint height, jint depth) { glTextureStorage3DEXT(texture, target, levels, internalformat, width, height, depth); } JNIEXPORT void JNICALL Java_org_lwjgl_opengles_EXTTextureStorage_initNativeStubs(JNIEnv *env, jclass clazz) { JavaMethodAndExtFunction functions[] = { {"nglTexStorage1DEXT", "(IIII)V", (void *)&Java_org_lwjgl_opengles_EXTTextureStorage_nglTexStorage1DEXT, "glTexStorage1DEXT", (void *)&glTexStorage1DEXT, false}, {"nglTexStorage2DEXT", "(IIIII)V", (void *)&Java_org_lwjgl_opengles_EXTTextureStorage_nglTexStorage2DEXT, "glTexStorage2DEXT", (void *)&glTexStorage2DEXT, false}, {"nglTexStorage3DEXT", "(IIIIII)V", (void *)&Java_org_lwjgl_opengles_EXTTextureStorage_nglTexStorage3DEXT, "glTexStorage3DEXT", (void *)&glTexStorage3DEXT, false}, {"nglTextureStorage1DEXT", "(IIIII)V", (void *)&Java_org_lwjgl_opengles_EXTTextureStorage_nglTextureStorage1DEXT, "glTextureStorage1DEXT", (void *)&glTextureStorage1DEXT, false}, {"nglTextureStorage2DEXT", "(IIIIII)V", (void *)&Java_org_lwjgl_opengles_EXTTextureStorage_nglTextureStorage2DEXT, "glTextureStorage2DEXT", (void *)&glTextureStorage2DEXT, false}, {"nglTextureStorage3DEXT", "(IIIIIII)V", (void *)&Java_org_lwjgl_opengles_EXTTextureStorage_nglTextureStorage3DEXT, "glTextureStorage3DEXT", (void *)&glTextureStorage3DEXT, false} }; int num_functions = NUMFUNCTIONS(functions); extgl_InitializeClass(env, clazz, num_functions, functions); }
Java
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ package im.actor.core.entity; import com.google.j2objc.annotations.Property; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.ArrayList; import java.util.List; import im.actor.core.api.ApiAvatar; import im.actor.core.api.ApiBotCommand; import im.actor.core.api.ApiContactRecord; import im.actor.core.api.ApiContactType; import im.actor.core.api.ApiFullUser; import im.actor.core.api.ApiInt32Value; import im.actor.core.api.ApiMapValue; import im.actor.core.api.ApiMapValueItem; import im.actor.core.api.ApiUser; import im.actor.runtime.bser.BserCreator; import im.actor.runtime.bser.BserValues; import im.actor.runtime.bser.BserWriter; import im.actor.runtime.storage.KeyValueItem; // Disabling Bounds checks for speeding up calculations /*-[ #define J2OBJC_DISABLE_ARRAY_BOUND_CHECKS 1 ]-*/ public class User extends WrapperExtEntity<ApiFullUser, ApiUser> implements KeyValueItem { private static final int RECORD_ID = 10; private static final int RECORD_FULL_ID = 20; public static BserCreator<User> CREATOR = User::new; @Property("readonly, nonatomic") private int uid; @Property("readonly, nonatomic") private long accessHash; @NotNull @Property("readonly, nonatomic") @SuppressWarnings("NullableProblems") private String name; @Nullable @Property("readonly, nonatomic") private String localName; @Nullable @Property("readonly, nonatomic") private String username; @Nullable @Property("readonly, nonatomic") private String about; @Nullable @Property("readonly, nonatomic") private Avatar avatar; @NotNull @Property("readonly, nonatomic") @SuppressWarnings("NullableProblems") private Sex sex; @Property("readonly, nonatomic") private boolean isBot; @NotNull @Property("readonly, nonatomic") @SuppressWarnings("NullableProblems") private List<ContactRecord> records; @Property("readonly, nonatomic") private boolean isBlocked; @Nullable @Property("readonly, nonatomic") private String timeZone; @Property("readonly, nonatomic") private boolean isVerified; @Property("readonly, nonatomic") private List<BotCommand> commands; @NotNull @Property("readonly, nonatomic") private boolean haveExtension; public User(@NotNull ApiUser wrappedUser, @Nullable ApiFullUser ext) { super(RECORD_ID, RECORD_FULL_ID, wrappedUser, ext); } public User(@NotNull byte[] data) throws IOException { super(RECORD_ID, RECORD_FULL_ID, data); } private User() { super(RECORD_ID, RECORD_FULL_ID); } @NotNull public Peer peer() { return new Peer(PeerType.PRIVATE, uid); } public int getUid() { return uid; } public long getAccessHash() { return accessHash; } @NotNull public String getServerName() { return name; } @Nullable public String getLocalName() { return localName; } @NotNull public String getName() { if (localName == null) { return name; } else { return localName; } } @Nullable public String getNick() { return username; } @Nullable public String getAbout() { return about; } @Nullable public Avatar getAvatar() { return avatar; } @NotNull public Sex getSex() { return sex; } public boolean isHaveExtension() { return haveExtension; } @NotNull public List<ContactRecord> getRecords() { return records; } public boolean isBot() { return isBot; } public List<BotCommand> getCommands() { return commands; } public boolean isBlocked() { return isBlocked; } @Nullable public String getTimeZone() { return timeZone; } public boolean isVerified() { return isVerified; } public User editName(@NotNull String name) { ApiUser w = getWrapped(); ApiUser res = new ApiUser( w.getId(), w.getAccessHash(), name, w.getLocalName(), w.getNick(), w.getSex(), w.getAvatar(), w.isBot(), w.getExt()); res.setUnmappedObjects(w.getUnmappedObjects()); return new User(res, getWrappedExt()); } public User editLocalName(@NotNull String localName) { ApiUser w = getWrapped(); ApiUser res = new ApiUser( w.getId(), w.getAccessHash(), w.getName(), localName, w.getNick(), w.getSex(), w.getAvatar(), w.isBot(), w.getExt()); res.setUnmappedObjects(w.getUnmappedObjects()); return new User(res, getWrappedExt()); } public User editNick(@Nullable String nick) { ApiUser w = getWrapped(); ApiUser res = new ApiUser( w.getId(), w.getAccessHash(), w.getName(), w.getLocalName(), nick, w.getSex(), w.getAvatar(), w.isBot(), w.getExt()); res.setUnmappedObjects(w.getUnmappedObjects()); return new User(res, getWrappedExt()); } public User editExt(@Nullable ApiMapValue ext) { ApiUser w = getWrapped(); ApiUser res = new ApiUser( w.getId(), w.getAccessHash(), w.getName(), w.getLocalName(), w.getNick(), w.getSex(), w.getAvatar(), w.isBot(), ext); res.setUnmappedObjects(w.getUnmappedObjects()); return new User(res, getWrappedExt()); } public User editAvatar(@Nullable ApiAvatar avatar) { ApiUser w = getWrapped(); ApiUser res = new ApiUser( w.getId(), w.getAccessHash(), w.getName(), w.getLocalName(), w.getNick(), w.getSex(), avatar, w.isBot(), w.getExt()); res.setUnmappedObjects(w.getUnmappedObjects()); return new User(res, getWrappedExt()); } public User updateExt(@Nullable ApiFullUser ext) { return new User(getWrapped(), ext); } public User editAbout(@Nullable String about) { ApiFullUser ext = getWrappedExt(); if (ext != null) { ApiFullUser upd = new ApiFullUser( ext.getId(), ext.getContactInfo(), about, ext.getPreferredLanguages(), ext.getTimeZone(), ext.getBotCommands(), ext.getExt(), ext.isBlocked() ); return new User(getWrapped(), upd); } else { return this; } } public User editPreferredLanguages(List<String> preferredLanguages) { ApiFullUser ext = getWrappedExt(); if (ext != null) { ApiFullUser upd = new ApiFullUser( ext.getId(), ext.getContactInfo(), ext.getAbout(), preferredLanguages, ext.getTimeZone(), ext.getBotCommands(), ext.getExt(), ext.isBlocked() ); return new User(getWrapped(), upd); } else { return this; } } public User editTimeZone(String timeZone) { ApiFullUser ext = getWrappedExt(); if (ext != null) { ApiFullUser upd = new ApiFullUser( ext.getId(), ext.getContactInfo(), ext.getAbout(), ext.getPreferredLanguages(), timeZone, ext.getBotCommands(), ext.getExt(), ext.isBlocked() ); return new User(getWrapped(), upd); } else { return this; } } public User editContacts(List<ApiContactRecord> contacts) { ApiFullUser ext = getWrappedExt(); if (ext != null) { ApiFullUser upd = new ApiFullUser( ext.getId(), contacts, ext.getAbout(), ext.getPreferredLanguages(), ext.getTimeZone(), ext.getBotCommands(), ext.getExt(), ext.isBlocked() ); return new User(getWrapped(), upd); } else { return this; } } public User editBotCommands(List<ApiBotCommand> commands) { ApiFullUser ext = getWrappedExt(); if (ext != null) { ApiFullUser upd = new ApiFullUser( ext.getId(), ext.getContactInfo(), ext.getAbout(), ext.getPreferredLanguages(), ext.getTimeZone(), commands, ext.getExt(), ext.isBlocked() ); return new User(getWrapped(), upd); } else { return this; } } public User editFullExt(ApiMapValue extv) { ApiFullUser ext = getWrappedExt(); if (ext != null) { ApiFullUser upd = new ApiFullUser( ext.getId(), ext.getContactInfo(), ext.getAbout(), ext.getPreferredLanguages(), ext.getTimeZone(), ext.getBotCommands(), extv, ext.isBlocked() ); return new User(getWrapped(), upd); } else { return this; } } public User editBlocked(boolean isBlocked) { ApiFullUser ext = getWrappedExt(); if (ext != null) { ApiFullUser upd = new ApiFullUser( ext.getId(), ext.getContactInfo(), ext.getAbout(), ext.getPreferredLanguages(), ext.getTimeZone(), ext.getBotCommands(), ext.getExt(), isBlocked ); return new User(getWrapped(), upd); } else { return this; } } @Override protected void applyWrapped(@NotNull ApiUser wrapped, @Nullable ApiFullUser ext) { this.uid = wrapped.getId(); this.accessHash = wrapped.getAccessHash(); this.name = wrapped.getName(); this.localName = wrapped.getLocalName(); if (wrapped.getNick() != null && wrapped.getNick().length() > 0) { this.username = wrapped.getNick(); } else { this.username = null; } if (wrapped.getAvatar() != null) { this.avatar = new Avatar(wrapped.getAvatar()); } this.isBot = false; if (wrapped.isBot() != null) { this.isBot = wrapped.isBot(); } this.sex = Sex.UNKNOWN; if (wrapped.getSex() != null) { switch (wrapped.getSex()) { case FEMALE: this.sex = Sex.FEMALE; break; case MALE: this.sex = Sex.MALE; break; } } if (wrapped.getExt() != null) { this.isVerified = true; for (ApiMapValueItem i : wrapped.getExt().getItems()) { if ("is_verified".equals(i.getKey())) { if (i.getValue() instanceof ApiInt32Value) { this.isVerified = ((ApiInt32Value) i.getValue()).getValue() > 0; } } } } // Extension if (ext != null) { this.haveExtension = true; this.records = new ArrayList<>(); this.commands = new ArrayList<BotCommand>(); if (ext.isBlocked() != null) { this.isBlocked = ext.isBlocked(); } else { this.isBlocked = false; } this.timeZone = ext.getTimeZone(); for (ApiContactRecord record : ext.getContactInfo()) { if (record.getType() == ApiContactType.PHONE) { this.records.add(new ContactRecord(ContactRecordType.PHONE, record.getTypeSpec(), "" + record.getLongValue(), record.getTitle(), record.getSubtitle())); } else if (record.getType() == ApiContactType.EMAIL) { this.records.add(new ContactRecord(ContactRecordType.EMAIL, record.getTypeSpec(), record.getStringValue(), record.getTitle(), record.getSubtitle())); } else if (record.getType() == ApiContactType.WEB) { this.records.add(new ContactRecord(ContactRecordType.WEB, record.getTypeSpec(), record.getStringValue(), record.getTitle(), record.getSubtitle())); } else if (record.getType() == ApiContactType.SOCIAL) { this.records.add(new ContactRecord(ContactRecordType.SOCIAL, record.getTypeSpec(), record.getStringValue(), record.getTitle(), record.getSubtitle())); } } //Bot commands for (ApiBotCommand command : ext.getBotCommands()) { commands.add(new BotCommand(command.getSlashCommand(), command.getDescription(), command.getLocKey())); } this.about = ext.getAbout(); } else { this.isBlocked = false; this.haveExtension = false; this.records = new ArrayList<>(); this.commands = new ArrayList<BotCommand>(); this.about = null; this.timeZone = null; } } @Override public void parse(BserValues values) throws IOException { // Is Wrapper Layout if (values.getBool(8, false)) { // Parse wrapper layout super.parse(values); } else { // Convert old layout throw new IOException("Unsupported obsolete format"); } } @Override public void serialize(BserWriter writer) throws IOException { // Mark as wrapper layout writer.writeBool(8, true); // Serialize wrapper layout super.serialize(writer); } @Override public long getEngineId() { return getUid(); } @Override @NotNull protected ApiUser createInstance() { return new ApiUser(); } @Override protected ApiFullUser createExtInstance() { return new ApiFullUser(); } }
Java
<?xml version="1.0" encoding="UTF-8"?> <tileset name="Canalave Gym Set" firstgid="1" tilewidth="16" tileheight="16"> <image source="Canalave Gym Set.png" trans="000000"/> </tileset>
Java
/* * Copyright (c) 2011-2015 NinevehGL. More information at: http://nineveh.gl * * 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. */ #import "NGLRuntime.h" #import "NGLError.h" #import "NGLIterator.h" /*! * <strong>(Internal only)</strong> An object that holds the array values. * * This structure is used as a fixed pointer to preserve the necessary information/memory * to the array values. * * @var NGLArrayValues::pointers * The pointers array. * * @var NGLArrayValues::count * The count/length of the array. * * @var NGLArrayValues::retainOption * The retain option. This value can't be changed outside the initialization. * * @var NGLArrayValues::iterator * The iterator pointer. * * @var NGLArrayValues::i * The iterator index. */ typedef struct { void **pointers; unsigned int count; unsigned int capacity; BOOL retainOption; void **iterator; unsigned int i; } NGLArrayValues; /*! * Extremelly fast loop to work with NGLArray. This loop is slower than NSFastEnumeration, * about 50% slower. However it accepts mutations during the loop and can work with * any kind of data type (Objective-C or standard C). * * The syntax is a little bit different than the traditional forin loop: * * <pre> * * id variable; * * nglFor (variable, myNGLArray) * { * // Do something... * } * * </pre> * * @param p * A pointer that will receive the values. * * @param a * The NGLArray instance to loop through. */ #define nglFor(p, a)\ for(NGLArrayValues *v = [(((a) != nil) ? (a) : [NGLArray array]) forLoop:(void **)&(p)];\ (*v).i < (*v).count;\ (*v).i++, (p) = *(*v).iterator++) /*! * Checks if a pointer is valid or not, that means, if a pointer is really pointing to * a valid object (not released nor deallocated). * * @param pointer * A C pointer to check. * * @result A BOOL indicating if the pointer is valid or not. */ NGL_API BOOL nglPointerIsValid(void *pointer); /*! * Checks if a pointer is valid for a specific kind of class. * * To check the validation against any kind of classes, use the #nglPointerIsValid#. * * @param pointer * A C pointer to check. * * @param aClass * An Objective-C class. * * @result A BOOL indicating if the pointer is valid or not. */ NGL_API BOOL nglPointerIsValidToClass(void *pointer, Class aClass); /*! * Checks if a pointer is valid for a specific protocol. * * This function will return NO if the pointer is released, deallocated, or just doesn't * conform to the informed protocol. * * @param pointer * A C pointer to check. * * @param aProtocol * An Objective-C class. * * @result A BOOL indicating if the pointer is valid or not. */ NGL_API BOOL nglPointerIsValidToProtocol(void *pointer, Protocol *aProtocol); /*! * Checks if a pointer is valid and responds to a selector. * * This function will return NO if the pointer is released, deallocated, or just doesn't * conform to the informed protocol. * * @param pointer * A C pointer to check. * * @param selector * An Objective-C selector. * * @result A BOOL indicating if the pointer is valid or not. */ NGL_API BOOL nglPointerIsValidToSelector(void *pointer, SEL selector); /*! * This class is a collection that works just like an array, however it's generic for * any kind of data type, including basic C types. NGLArray does not retain * the object. * * This class is faster than the traditional NSArray. Depending on the tasks, NGLArray * can be 50% faster than NSArray, the most expensive task of NGLArray is at least * 15% faster than NSArray, which is "removeAll". Actually, this class is more like a * NSMutableArray, because you can change its collection at any time. This one also has * a "hint" property called capacity, if you already know the maximum number of elements * you can set this property to boost the performance a little bit more. * * By default, every time you try to insert an item in this array and it's capacity is * full, a new block of 10 items will be allocated into this array. * * The reasons that cause this one to be faster than NSArray are: * * - It basically work with pointers and dereference, instead of indices. * - It has an internal iterator loop that manages the enumerations. * - It doesn't have many too checks. NGLArray assumes you know what you're doing. * * The achieve the best performance and still flexible, the NGLArray offers three kind * of loops. Each one has its own cost and benefits: * * - <b>NGLIterator</b>: <i>Loops through 100 millions in 1.5 seg</i>.<br /> * Uses NGLIterator protocol. This loop is good for small array in which you * need to change it's content during the loop or even from another thread. * This routine offers a way to reset the loop at any time by calling the * <code>resetIterator</code> method. * The disadvantage of this routine is that it makes a Objective-C message call * at each loop cycle, so it's a little expensive compared to the other ones. * Its syntax is: * * <pre> * * id variable; * while ((variable = [myNGLArray nextIterator])) * { * // Do something... * } * * </pre> * * - <b>NGLFor</b>: <i>Loops through 100 millions in 0.45 seg</i>.<br /> * Very fast loop using the iterator properties. Can deal with changes during * the loop or even from another thread. * Its disadvantage is that it has a special syntax and just resets the iterator * loop at the beginning. So if you're planning to use the <b>NGLIterator</b> after * use this one, you must call <code>resetIterator</code> before start the * <b>NGLIterator</b>. Its syntax is: * * <pre> * * id variable; * nglFor (variable, myNGLArray) * { * // Do something... * } * * </pre> * * - <b>ForEach</b>: <i>Loops through 100 millions in 0.3 seg</i>.<br /> * Uses NSFastEnumeration protocol (the Cocoa "for in" loop). This loop is the * fastest one. However it's be used only in few situations. * Its disadvantage is that it only work with Objective-C objects and the array * can't be changed during the loop (changing the array during the loop will * result in runtime error). * Its syntax is: * * <pre> * * id variable; * for (variable in myNGLArray) * { * // Do something... * } * * </pre> * * The NGLArray class also provides a pointer to the items and a pointer to the * mutations property. You can use them to implement your own NSFastEnumeration. */ @interface NGLArray : NSObject <NGLIterator, NSFastEnumeration> { @private NGLArrayValues _values; } /*! * The capacity property is not the size/count of the array, it's just a "hint" to optimize * the array manipulation spped. This "hint" is useful for large array (above 10 items). * * The NGLArray will allocate the memory in sets/packages using this "hint" property. */ @property (nonatomic) unsigned int capacity; /*! * Indicates if this array will retain or not the objects in it. This property can't be * changed to ensure the integrity of the items and must be set when initializing this * array. Only Objective-C objects can receive retain messages. */ @property (nonatomic, readonly) BOOL retainOption; /*! * Returns the items pointer. This property is useful if you want to create your own * implementation of NSFastEnumeration but keep using NGLArray as your collection. * * Remember that NSFastEnumeration is exclusive for Objective-C objects. */ @property (nonatomic, readonly) NGL_ARC_ASSIGN id *itemsPointer; /*! * Returns the mutations pointer. This property is useful if you want to create your own * implementation of NSFastEnumeration but keep using NGLArray as your collection. * * Remember that NSFastEnumeration is exclusive for Objective-C objects. */ @property (nonatomic, readonly) unsigned long *mutationsPointer; /*! * <strong>(Internal only)</strong> Returns a pointer to the array values. * You should not call this method directly. */ @property (nonatomic, readonly) NGLArrayValues *values; /*! * Initiates a NGLArray making it a safe collection, that means, it will retain every * pointer that will be added to it. In this case, all pointer must be a subclass * of NSObject. * * The retained objects will receive a release message when they are removed or this * instance of NGLArray is released. * * @result A NGLArray instance. */ - (id) initWithRetainOption; /*! * Initiates a NGLArray instance based on another NGLArray. * * This method copies all objects/instances inside the informed NGLArray. * * @param pointers * A NGLArray to serve as base to the new NGLArray. * * @result A NGLArray instance. */ - (id) initWithNGLArray:(NGLArray *)pointers; /*! * Initiates a NGLArray instance based on many object/instances. * * This method doesn't make use of addPointerOnce, that means if a target is informed * more than one time, it will remain duplicated inside this collection. * * @param first * The first object/instance to be added. * * @param ... * A sequence of objects/instances separated by commas. This method must end with * a <code>nil</code> element. * * @result A NGLArray instance. */ - (id) initWithPointers:(void *)first, ... NS_REQUIRES_NIL_TERMINATION; /*! * Adds a new object/instance to this collection. If the target already exist in this * collection, it will be added again, resulting in a duplication. * * @param pointer * The target it self. */ - (void) addPointer:(void *)pointer; /*! * Adds a new object/instance to this collection only if the target is not already inside * this collection. If the target already exist, nothing will happen. * * @param pointer * The target it self. */ - (void) addPointerOnce:(void *)pointer; /*! * Adds all object/instance to this collection from another NGLArray. * This method copies all objects/instances inside the informed NGLArray. * * @param pointers * The NGLArray instance to copy pointers from. */ - (void) addPointersFromNGLArray:(NGLArray *)pointers; /*! * Returns the index of a target inside this collection. * * @param pointer * The target it self. * * @result Returns the index of the target or NGL_NOT_FOUND if the target was not found. */ - (unsigned int) indexOfPointer:(void *)pointer; /*! * Checks if a target is inside this collection. * * @param pointer * The target it self. * * @result Returns YES (1) if the target is found, otherwise NO (0) will be returned. */ - (BOOL) hasPointer:(void *)pointer; /*! * Removes an object/instance inside this collection. * * @param pointer * The target it self. */ - (void) removePointer:(void *)pointer; /*! * Removes an object/instance in a specific position inside this collection. * * @param index * The index of the target. If the index is out of bounds, nothing will happen. */ - (void) removePointerAtIndex:(unsigned int)index; /*! * Removes the very first object/instance in this collection. */ - (void) removeFirst; /*! * Removes the very last object/instance in this collection. */ - (void) removeLast; /*! * Removes all the instances inside this library. * * This method makes a clean up inside this library, freeing all allocated * memories to the instances in it. */ - (void) removeAll; /*! * Returns an object/instance in a specific position inside this collection. * * @param index * The index of the target. If the index is out of bounds, NULL will be returned. * * @result A pointer or NULL if no result was found. */ - (void *) pointerAtIndex:(unsigned int)index; /*! * Returns the number of instances in this library at the moment. * * @result An int data type. */ - (unsigned int) count; /*! * <strong>(Internal only)</strong> Prepares this array to work with "nglFor" loop. * You should not call this method directly. * * @param target * A pointer to the target that will receive the items of this array. Inside this * method the target will receive the first item. * * @result A pointer to the values of this array. */ - (NGLArrayValues *) forLoop:(void **)target; /*! * Returns an autoreleased instance of NGLArray. * * @result A NGLArray autoreleased instance. */ + (id) array; @end /*! * A category that extends the default behavior to perform some convenience method which * could help when other classes makes use of this one. */ @interface NGLArray(NGLArrayExtended) - (NSArray *) allPointers; /*! * A convenience method that loops through all objects making them perform a selector. * * IMPORTANT: This method assumes you're sure about this task and no additional check * will be made to identify if the objects can receive such message. So, make sure all * the objects are Objective-C instances and can receive the informed message. * * @param selector * The selector which will be performed on all objects. */ - (void) makeAllPointersPerformSelector:(SEL)selector; @end
Java
package api import ( "errors" "io/ioutil" "log" "net/http" "github.com/bitly/go-simplejson" ) func Request(req *http.Request) (*simplejson.Json, error) { resp, err := http.DefaultClient.Do(req) if err != nil { return nil, err } body, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { return nil, err } if resp.StatusCode != 200 { log.Printf("got response code %d - %s", resp.StatusCode, body) return nil, errors.New("api request returned non 200 status code") } data, err := simplejson.NewJson(body) if err != nil { return nil, err } return data, nil } func RequestUnparsedResponse(url string, header http.Header) ( response *http.Response, err error) { req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, errors.New("failed building request for " + url + ": " + err.Error()) } req.Header = header httpclient := &http.Client{} if response, err = httpclient.Do(req); err != nil { return nil, errors.New("request failed for " + url + ": " + err.Error()) } return }
Java
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.0-master-ce33beb */ md-radio-button.md-THEME_NAME-theme .md-off { border-color: '{{foreground-2}}'; } md-radio-button.md-THEME_NAME-theme .md-on { background-color: '{{accent-color-0.87}}'; } md-radio-button.md-THEME_NAME-theme.md-checked .md-off { border-color: '{{accent-color-0.87}}'; } md-radio-button.md-THEME_NAME-theme.md-checked .md-ink-ripple { color: '{{accent-color-0.87}}'; } md-radio-button.md-THEME_NAME-theme .md-container .md-ripple { color: '{{accent-A700}}'; } md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary .md-on, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary .md-on, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary .md-on, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary .md-on { background-color: '{{primary-color-0.87}}'; } md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary .md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary.md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary .md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary.md-checked .md-off, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary .md-checked .md-off, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary.md-checked .md-off, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary .md-checked .md-off, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary.md-checked .md-off { border-color: '{{primary-color-0.87}}'; } md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary .md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary.md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary .md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary.md-checked .md-ink-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary .md-checked .md-ink-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary.md-checked .md-ink-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary .md-checked .md-ink-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary.md-checked .md-ink-ripple { color: '{{primary-color-0.87}}'; } md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary .md-container .md-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary .md-container .md-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary .md-container .md-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary .md-container .md-ripple { color: '{{primary-600}}'; } md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn .md-on, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn .md-on, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn .md-on, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn .md-on { background-color: '{{warn-color-0.87}}'; } md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn .md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn.md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn .md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn.md-checked .md-off, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn .md-checked .md-off, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn.md-checked .md-off, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn .md-checked .md-off, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn.md-checked .md-off { border-color: '{{warn-color-0.87}}'; } md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn .md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn.md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn .md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn.md-checked .md-ink-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn .md-checked .md-ink-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn.md-checked .md-ink-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn .md-checked .md-ink-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn.md-checked .md-ink-ripple { color: '{{warn-color-0.87}}'; } md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn .md-container .md-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn .md-container .md-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn .md-container .md-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn .md-container .md-ripple { color: '{{warn-600}}'; } md-radio-group.md-THEME_NAME-theme[disabled], md-radio-button.md-THEME_NAME-theme[disabled] { color: '{{foreground-3}}'; } md-radio-group.md-THEME_NAME-theme[disabled] .md-container .md-off, md-radio-button.md-THEME_NAME-theme[disabled] .md-container .md-off { border-color: '{{foreground-3}}'; } md-radio-group.md-THEME_NAME-theme[disabled] .md-container .md-on, md-radio-button.md-THEME_NAME-theme[disabled] .md-container .md-on { border-color: '{{foreground-3}}'; } md-radio-group.md-THEME_NAME-theme .md-checked .md-ink-ripple { color: '{{accent-color-0.26}}'; } md-radio-group.md-THEME_NAME-theme.md-primary .md-checked:not([disabled]) .md-ink-ripple, md-radio-group.md-THEME_NAME-theme .md-checked:not([disabled]).md-primary .md-ink-ripple { color: '{{primary-color-0.26}}'; } md-radio-group.md-THEME_NAME-theme .md-checked.md-primary .md-ink-ripple { color: '{{warn-color-0.26}}'; } md-radio-group.md-THEME_NAME-theme.md-focused:not(:empty) .md-checked .md-container:before { background-color: '{{accent-color-0.26}}'; } md-radio-group.md-THEME_NAME-theme.md-focused:not(:empty).md-primary .md-checked .md-container:before, md-radio-group.md-THEME_NAME-theme.md-focused:not(:empty) .md-checked.md-primary .md-container:before { background-color: '{{primary-color-0.26}}'; } md-radio-group.md-THEME_NAME-theme.md-focused:not(:empty).md-warn .md-checked .md-container:before, md-radio-group.md-THEME_NAME-theme.md-focused:not(:empty) .md-checked.md-warn .md-container:before { background-color: '{{warn-color-0.26}}'; }
Java
require 'net/http' ## monkey-patch Net::HTTP # # Certain apple endpoints return 415 responses if a Content-Type is supplied. # Net::HTTP will default a content-type if none is provided by faraday # This monkey-patch allows us to leave out the content-type if we do not specify one. class Net::HTTPGenericRequest def supply_default_content_type return if content_type() end end
Java
<?php namespace spec\SensioLabs\Behat\PageObjectExtension\PageObject\Factory; require_once __DIR__.'/Fixtures/ArticleList.php'; use PhpSpec\ObjectBehavior; use Prophecy\Argument; use ProxyManager\Factory\LazyLoadingValueHolderFactory; use ProxyManager\Proxy\LazyLoadingInterface; use SensioLabs\Behat\PageObjectExtension\PageObject\Element; use SensioLabs\Behat\PageObjectExtension\PageObject\Factory; use SensioLabs\Behat\PageObjectExtension\PageObject\InlineElement; use SensioLabs\Behat\PageObjectExtension\PageObject\Page; use SensioLabs\Behat\PageObjectExtension\PageObject\PageObject; class LazyFactorySpec extends ObjectBehavior { function let(Factory $decoratedFactory) { $this->beConstructedWith($decoratedFactory, new LazyLoadingValueHolderFactory()); } function it_is_a_page_object_factory() { $this->shouldHaveType('SensioLabs\Behat\PageObjectExtension\PageObject\Factory'); } function it_delegates_create_page_calls_to_the_decorated_factory(Factory $decoratedFactory, Page $page) { $decoratedFactory->createPage('ArticleList')->willReturn($page); $this->createPage('ArticleList')->shouldReturn($page); } function it_delegates_create_element_calls_to_the_decorated_factory(Factory $decoratedFactory, Element $element) { $decoratedFactory->createElement('Foo')->willReturn($element); $this->createElement('Foo')->shouldReturn($element); } function it_delegates_create_inline_element_calls_to_the_decorated_factory(Factory $decoratedFactory, InlineElement $element) { $decoratedFactory->createInlineElement('.foo')->willReturn($element); $this->createInlineElement('.foo')->shouldReturn($element); } function it_creates_a_proxy_instead_of_instantiating_a_page_object_right_away() { $this->create('ArticleList')->shouldReturnAnInstanceOf('ProxyManager\Proxy\LazyLoadingInterface'); } function it_delegates_instantiation_to_the_decorated_factory(PageObject $pageObject, Factory $decoratedFactory) { $decoratedFactory->create('ArticleList')->willReturn($pageObject); $this->create('ArticleList')->shouldReturnAnInstanceOf('ProxyManager\Proxy\ProxyInterface'); } }
Java
{{ define "main" }} {{ partial "breadcrumbs" . }} <section class="resume-section p-3 p-lg-5 d-flex d-column content"> <div class="my-auto"> <h2 class="mb-0"><span class="text-primary">{{ .Title }}</span></h2> <p><a href="{{ .Params.link }}">Link to full {{ .Params.pubtype }}</a></p> {{ with .Params.image }}<img src="{{ . }}" style="max-height:300px;max-width:30%;" align="right"/>{{ end }} {{ .Content }} <p class="mt-3"> {{ partial "techtags" . }} </p> </div> </section> {{ end }}
Java
{{diagnostic}} <div class="aw-ui-callout aw-ui-callout-info"> <span>Please see below all the price set for various Asha Payment Activities.</span> </div> <form class="form-horizontal" #rulesForm="ngForm" (ngSubmit)="onSubmit(ruleForm.value)" method="POST"> <div> <h2>Maternal Health</h2> <h3>ANC Checkups</h3> <div class="form-group"> <label for="101" class="col-sm-4 control-label">No. of Registration during the first trimester of pregnancy at</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-101-R"><i class="fa fa-inr"></i></span> <input id="101_R" class="form-control" type="text" aria-describedby="addon-101-R" [(ngModel)]="model.R_101" name="R_101" #name="ngModel"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-101-U"><i class="fa fa-inr"></i></span> <input id="101_U" class="form-control" type="text" aria-describedby="addon-101-U" [(ngModel)]="model.U_101" name="U_101" #name="ngModel"> </div> </div> <div class="col-sm-2"> <textarea id="101_H" class="form-control" row="1" [(ngModel)]="model.H_101" name="H_101" #name="ngModel"></textarea> </div> </div> <div class="form-group"> <label for="102" class="col-sm-4 control-label">No. of 1st check up</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-102-R"><i class="fa fa-inr"></i></span> <input id="102_R" class="form-control" type="" aria-describedby="addon-102-R" [(ngModel)]="model.R_102" name="R_102" #name="ngModel"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-102-U"><i class="fa fa-inr"></i></span> <input id="102_U" class="form-control" type="" aria-describedby="addon-102-U" [(ngModel)]="model.U_102" name="U_102" #name="ngModel"> </div> </div> <div class="col-sm-2"> <textarea id="102_H" class="form-control" row="1" [(ngModel)]="model.H_102" name="H_102" #name="ngModel"></textarea> </div> </div> <div class="form-group"> <label for="103" class="col-sm-4 control-label">No. of 2 nd check up </label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-103-R"><i class="fa fa-inr"></i></span> <input id="103_R" class="form-control" type="" aria-describedby="addon-103-R" [(ngModel)]="model.R_103" name="R_103" #name="ngModel"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-103-U"><i class="fa fa-inr"></i></span> <input id="103_U" class="form-control" type="" aria-describedby="addon-103-U" [(ngModel)]="model.U_103" name="U_103" #name="ngModel"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1" [(ngModel)]="model.H_103" name="R_102" #name="ngModel"></textarea> </div> </div> <div class="form-group"> <label for="104" class="col-sm-4 control-label">No. of 3 rd check up</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-104-R"><i class="fa fa-inr"></i></span> <input id="104_R" class="form-control" type="" aria-describedby="addon-104-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-104-U"><i class="fa fa-inr"></i></span> <input id="104_U" class="form-control" type="" aria-describedby="addon-104-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="105" class="col-sm-4 control-label">No. of 4 th check up by M.O</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-105-R"><i class="fa fa-inr"></i></span> <input id="105_R" class="form-control" type="" aria-describedby="addon-105-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-105-U"><i class="fa fa-inr"></i></span> <input id="105_U" class="form-control" type="" aria-describedby="addon-105-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="106" class="col-sm-4 control-label">No. of Deliveres conducted in PHC/Institutons</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-106-R"><i class="fa fa-inr"></i></span> <input id="106_R" class="form-control" type="" aria-describedby="addon-106-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-106-U"><i class="fa fa-inr"></i></span> <input id="106_U" class="form-control" type="" aria-describedby="addon-106-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="107" class="col-sm-4 control-label">No. of Maternal Death reported to Sub Centre</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-107-R"><i class="fa fa-inr"></i></span> <input id="107_R" class="form-control" type="" aria-describedby="addon-107-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-107-U"><i class="fa fa-inr"></i></span> <input id="107_U" class="form-control" type="" aria-describedby="addon-107-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> </div> <div> <h2>Child Health</h2> <div class="form-group"> <label for="108" class="col-sm-4 control-label">Postnatal Visits (HBNC) (6 visits in Institutional Delivery, 7 Visits in Home Delivery)</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-108-R"><i class="fa fa-inr"></i></span> <input id="108_R" class="form-control" type="" aria-describedby="addon-108-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-108-U"><i class="fa fa-inr"></i></span> <input id="108_U" class="form-control" type="" aria-describedby="addon-108-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="109" class="col-sm-4 control-label">Rreferral & Follow up of SAM Cases to NRC</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-109-R"><i class="fa fa-inr"></i></span> <input id="109_R" class="form-control" type="" aria-describedby="addon-109-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-109-U"><i class="fa fa-inr"></i></span> <input id="109_U" class="form-control" type="" aria-describedby="addon-109-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="110" class="col-sm-4 control-label">Follow up of LBW babies (LBW Low Birth Weight Babies)</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-110-R"><i class="fa fa-inr"></i></span> <input id="110_R" class="form-control" type="" aria-describedby="addon-110-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-110-U"><i class="fa fa-inr"></i></span> <input id="110_U" class="form-control" type="" aria-describedby="addon-110-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="111" class="col-sm-4 control-label">Follow up of SNCU discharge babies</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-111-R"><i class="fa fa-inr"></i></span> <input id="111_R" class="form-control" type="" aria-describedby="addon-111-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-111-U"><i class="fa fa-inr"></i></span> <input id="111_U" class="form-control" type="" aria-describedby="addon-111-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="112" class="col-sm-4 control-label">Infant death reporting to Sub-centre and PHC</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-112-R"><i class="fa fa-inr"></i></span> <input id="112_R" class="form-control" type="" aria-describedby="addon-112-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-112-U"><i class="fa fa-inr"></i></span> <input id="112_U" class="form-control" type="" aria-describedby="addon-112-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="113" class="col-sm-4 control-label">Intesive Diarrhoea Control Programme</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-113-R"><i class="fa fa-inr"></i></span> <input id="113_R" class="form-control" type="" aria-describedby="addon-113-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-113-U"><i class="fa fa-inr"></i></span> <input id="113_U" class="form-control" type="" aria-describedby="addon-113-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> </div> <div> <h2>Immunization</h2> <div class="form-group"> <label for="114" class="col-sm-4 control-label">Pulse Polio Booth Mobilization</label> <div class="col-sm-2"> <div class="input-group disabled"> <span class="input-group-addon" id="addon-114-R"><i class="fa fa-inr"></i></span> <input id="114_R" class="form-control" type="" aria-describedby="addon-114-R" disabled> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-114-U"><i class="fa fa-inr"></i></span> <input id="114_U" class="form-control" type="" aria-describedby="addon-114-U" disabled> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <h3>Full Immunization</h3> <div class="form-group"> <label for="115" class="col-sm-4 control-label">Complete Immunization in 1st year of age</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-115-R"><i class="fa fa-inr"></i></span> <input id="115_R" class="form-control" type="" aria-describedby="addon-115-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-115-U"><i class="fa fa-inr"></i></span> <input id="115U" class="form-control" type="" aria-describedby="addon-115-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="116" class="col-sm-4 control-label">Full Immunization of 2nd year of age</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-116-R"><i class="fa fa-inr"></i></span> <input id="116" class="form-control" type="" aria-describedby="addon-116-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-116-U"><i class="fa fa-inr"></i></span> <input id="116" class="form-control" type="" aria-describedby="addon-116-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> </div> <div> <h2>Family Planning</h2> <div class="form-group"> <label for="117" class="col-sm-4 control-label">No. of Counseling & Motivation of women for Tubectomy</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-117-R"><i class="fa fa-inr"></i></span> <input id="117" class="form-control" type="" aria-describedby="addon-117-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-117-U"><i class="fa fa-inr"></i></span> <input id="117" class="form-control" type="" aria-describedby="addon-117-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="118" class="col-sm-4 control-label">No. of Counseling & Motivation for men of Vasectomy</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-118-R"><i class="fa fa-inr"></i></span> <input id="118" class="form-control" type="" aria-describedby="addon-118-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-118-U"><i class="fa fa-inr"></i></span> <input id="118" class="form-control" type="" aria-describedby="addon-118-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="119" class="col-sm-4 control-label">Accompanying the beneficiary for PPIUCD</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-119-R"><i class="fa fa-inr"></i></span> <input id="119" class="form-control" type="" aria-describedby="addon-119-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-119-U"><i class="fa fa-inr"></i></span> <input id="119" class="form-control" type="" aria-describedby="addon-119-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> </div> <div> <h2>RKSK (only for HPDs)</h2> <div class="form-group"> <label for="120" class="col-sm-4 control-label">Support to Peer Educator</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-120-R"><i class="fa fa-inr"></i></span> <input id="120" class="form-control" type="" aria-describedby="addon-120-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-120-U"><i class="fa fa-inr"></i></span> <input id="120" class="form-control" type="" aria-describedby="addon-120-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="121" class="col-sm-4 control-label">Mobilizing Adolescents for AHD</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-121-R"><i class="fa fa-inr"></i></span> <input id="121" class="form-control" type="" aria-describedby="addon-121-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-121-U"><i class="fa fa-inr"></i></span> <input id="121" class="form-control" type="" aria-describedby="addon-121-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> </div> <div> <h2>RNTCP</h2> <div class="form-group"> <label for="122" class="col-sm-4 control-label">New TB case Catg.I TB (42 contacts 6-7 months treatment)</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-122-R"><i class="fa fa-inr"></i></span> <input id="122" class="form-control" type="" aria-describedby="addon-122-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-122-U"><i class="fa fa-inr"></i></span> <input id="122" class="form-control" type="" aria-describedby="addon-122-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="123" class="col-sm-4 control-label">Previous treated TB case (57 contacts, catg.II TB 8-9 months treatment</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-123-R"><i class="fa fa-inr"></i></span> <input id="123" class="form-control" type="" aria-describedby="addon-123-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-123-U"><i class="fa fa-inr"></i></span> <input id="123" class="form-control" type="" aria-describedby="addon-123-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="124" class="col-sm-4 control-label">Providing treatment and support to Drug resistant TB patient (MDR)</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-124-R"><i class="fa fa-inr"></i></span> <input id="124" class="form-control" type="" aria-describedby="addon-124-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-124-U"><i class="fa fa-inr"></i></span> <input id="124" class="form-control" type="" aria-describedby="addon-124-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="125" class="col-sm-4 control-label">Identification & Successful completion of DOTS for TB</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-125-R"><i class="fa fa-inr"></i></span> <input id="125" class="form-control" type="" aria-describedby="addon-125-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-125-U"><i class="fa fa-inr"></i></span> <input id="125" class="form-control" type="" aria-describedby="addon-125-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> </div> <div> <h2>NLEP</h2> <div class="form-group"> <label for="126" class="col-sm-4 control-label">PB - Referring for Diagnostics + Complete treatment</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-126-R"><i class="fa fa-inr"></i></span> <input id="126" class="form-control" type="" aria-describedby="addon-126-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-126-U"><i class="fa fa-inr"></i></span> <input id="126" class="form-control" type="" aria-describedby="addon-126-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="127" class="col-sm-4 control-label">MB - Dsetection + complete treatment</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-127-R"><i class="fa fa-inr"></i></span> <input id="127" class="form-control" type="" aria-describedby="addon-127-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-127-U"><i class="fa fa-inr"></i></span> <input id="127" class="form-control" type="" aria-describedby="addon-127-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> </div> <div> <h2>NVBDC Programme (Srikakulam, Vizianagaram, East Godavari)</h2> <div class="form-group"> <label for="128" class="col-sm-4 control-label">Preparation of Blood Slide </label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-128-R"><i class="fa fa-inr"></i></span> <input id="128" class="form-control" type="" aria-describedby="addon-128-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-128-U"><i class="fa fa-inr"></i></span> <input id="128" class="form-control" type="" aria-describedby="addon-128-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="129" class="col-sm-4 control-label">Complete treatment for RDT +ve PF case & complete Radical treatment to +ve PF & PC cases</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-129-R"><i class="fa fa-inr"></i></span> <input id="129" class="form-control" type="" aria-describedby="addon-129-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-129-U"><i class="fa fa-inr"></i></span> <input id="129" class="form-control" type="" aria-describedby="addon-129-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="130" class="col-sm-4 control-label">Lymphatic Filariasis – for One time Line listing of Lymphoedema and Hydrocele cases in non-endemic dist</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-130-R"><i class="fa fa-inr"></i></span> <input id="130" class="form-control" type="" aria-describedby="addon-130-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-130-U"><i class="fa fa-inr"></i></span> <input id="130" class="form-control" type="" aria-describedby="addon-130-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="131" class="col-sm-4 control-label">Line listing of Lymphatic Filariasis</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-131-R"><i class="fa fa-inr"></i></span> <input id="131" class="form-control" type="" aria-describedby="addon-131-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-131-U"><i class="fa fa-inr"></i></span> <input id="131" class="form-control" type="" aria-describedby="addon-131-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="132" class="col-sm-4 control-label">Referral of AES / JE cases to the nearest CHC / DH / Medical College</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-132-R"><i class="fa fa-inr"></i></span> <input id="132" class="form-control" type="" aria-describedby="addon-132-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-132-U"><i class="fa fa-inr"></i></span> <input id="132" class="form-control" type="" aria-describedby="addon-132-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> </div> <div> <h2>Routine & Recurrent activities</h2> <div class="form-group"> <label for="133" class="col-sm-4 control-label">Mobilizing & attending VHND in the month</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-133-R"><i class="fa fa-inr"></i></span> <input id="133" class="form-control" type="" aria-describedby="addon-133-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-133-U"><i class="fa fa-inr"></i></span> <input id="133" class="form-control" type="" aria-describedby="addon-133-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="134" class="col-sm-4 control-label">Attending VHSNC meeting</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-134-R"><i class="fa fa-inr"></i></span> <input id="134" class="form-control" type="" aria-describedby="addon-134-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-134-U"><i class="fa fa-inr"></i></span> <input id="134" class="form-control" type="" aria-describedby="addon-134-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="135" class="col-sm-4 control-label">Atttending ASHA Day Meeting</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-135-R"><i class="fa fa-inr"></i></span> <input id="135" class="form-control" type="" aria-describedby="addon-135-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-135-U"><i class="fa fa-inr"></i></span> <input id="135" class="form-control" type="" aria-describedby="addon-135-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="136" class="col-sm-4 control-label">Line listing of households done at beginning of the year and updated after six months</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-136-R"><i class="fa fa-inr"></i></span> <input id="136" class="form-control" type="" aria-describedby="addon-136-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-136-U"><i class="fa fa-inr"></i></span> <input id="136" class="form-control" type="" aria-describedby="addon-136-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="137" class="col-sm-4 control-label">Maintaining village health register and supporting universal registration of births and deaths</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-137-R"><i class="fa fa-inr"></i></span> <input id="137" class="form-control" type="" aria-describedby="addon-137-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-137-U"><i class="fa fa-inr"></i></span> <input id="137" class="form-control" type="" aria-describedby="addon-137-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="138" class="col-sm-4 control-label">Preparation of due list of children to be immunized updated on monthly basis</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-138-R"><i class="fa fa-inr"></i></span> <input id="138" class="form-control" type="" aria-describedby="addon-138-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-138-U"><i class="fa fa-inr"></i></span> <input id="138" class="form-control" type="" aria-describedby="addon-138-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="139" class="col-sm-4 control-label">Preparation of list of ANC beneficiaries to be updated on monthly basis</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-139-R"><i class="fa fa-inr"></i></span> <input id="139" class="form-control" type="" aria-describedby="addon-139-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-139-U"><i class="fa fa-inr"></i></span> <input id="139" class="form-control" type="" aria-describedby="addon-139-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="140" class="col-sm-4 control-label">Preparation of list of eligible couples updated on monthly basis</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-140-R"><i class="fa fa-inr"></i></span> <input id="140" class="form-control" type="" aria-describedby="addon-140-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-140-U"><i class="fa fa-inr"></i></span> <input id="140" class="form-control" type="" aria-describedby="addon-140-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> </div> <div> <h2>104 (by state budget)</h2> <div class="form-group"> <label for="141" class="col-sm-4 control-label">No.of ASHA attended 104 Fixed day health services in villages </label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-141-R"><i class="fa fa-inr"></i></span> <input id="141" class="form-control" type="" aria-describedby="addon-141-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-141-U"><i class="fa fa-inr"></i></span> <input id="141" class="form-control" type="" aria-describedby="addon-141-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> </div> <div> <button type="submit" class="btn btn-primary">Save</button> </div> </form>
Java
// // IMRoomCreateViewController.h // Pods // // Created by FUNTEK Inc. on 2016/5/16. // // #import "IMInviteClient.h" #import "IMRoomInviteViewController.h" #import "IMViewController.h" @protocol IMRoomCreateDelegate; @interface IMRoomCreateViewController : IMViewController @property (weak, nonatomic) id <IMRoomCreateDelegate> delegate; @end @protocol IMRoomCreateDelegate <NSObject> @end
Java
#include "overlapping.hpp" /* TODO: * grow seeds from edges, not nodes. * Why are the results changing? * Then, speed up delV * ZEntropy shouldn't consider the number of groups, that should be taken out to another function. * That factorial expression would be better * Write down some of the stats, and be sure they're correct. * unordered_map for efficiency more often? * a big vector for the comm_count_per_edge? * keep track of frontier properly in growingSeed * type tags for the multi_index_container, instead of get<1> * random tie-breaking in frontier * update _p_in also. * * PLAN: * Fully abstract interface to grouping * Track count of types of edges. * Varying p_in and p_out * Each edge to know how many communities it's in. * Calculate global objective function every now and then. * More efficient finding of seeds * Random tie breaking * Stop seed growing at first positive? */ /* * Sources of randomness: * 246: Choice of initial edge seed * 249: (arbitrary, not random) Randomized p_in * 459: (arbitrary, not random) Tie breaker in seed expansion */ #include <list> #include <map> #include <algorithm> #include <functional> #include <math.h> #include <string.h> #include <fstream> #include <sstream> #include <float.h> #include <boost/multi_index_container.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/hashed_index.hpp> //#include <boost/multi_index/identity.hpp> #include <boost/multi_index/indexed_by.hpp> #include <boost/multi_index/member.hpp> #include <boost/unordered_map.hpp> #include <boost/unordered_set.hpp> #include "iterative.hpp" #include "options.hpp" #include "Range.hpp" #include "grouping.hpp" #include <set> using namespace std; using namespace std::tr1 ; using namespace grouping; char option_saveMOSESscores[1000] = ""; long option_seed = 0; int flag_justCalcObjective = 0; static void runMutual(void) { //system("echo;echo -n \" >> ;${x};${gt};${me}; \" ; bash -c '~/Code/Mutual3/mutual3/mutual \"${x}\"{\"${me}\",\"${gt}\"}' 1>&2 "); } namespace overlapping { bool flag_save_group_id_in_output = true; template <class N> static void overlappingT(bloomGraph<N> &g); void overlapping(SimpleIntGraph &g) { overlappingT(g); } void overlapping(SimpleStringGraph &g) { overlappingT(g); } void addSeed(Grouping &ging, const set<V> &nodes, bool randomized_p_in); static pair<long double, set<V> > growThisEdge(Grouping &ging, V edgeNumber, const long double &boost, bool randomized_p_in); static void update_p_out(Grouping &ging); static void estimate_p_in_and_p_out(Grouping &ging); long double MOSES_objective(const Grouping &ging); void addSeed(Grouping &ging, const set<V> &nodes, bool randomized_p_in) { assert(nodes.size()>0); Group *g = ging.newG(randomized_p_in); ForeachContainer(V v, nodes) { ging.addV(g, v); } } void seedGroupingWithPartition(Grouping &ging, const iterative::Partition &p); template <class N> static void useOneNodeSeeds(Grouping &ging, bloomGraph<N> &g, bool randomize_p_in); template <class N> static void groupStats(const Grouping &ging, bloomGraph<N> &g); template <class N> static void save(Grouping &ging, bloomGraph<N> &g); template <class N> static void louvainStyle(Grouping &ging, bloomGraph<N> &g); static void tryMerges(Grouping &ging); static void tryDeletions(Grouping &ging, bool SaveScores = false); static bool tryAndApplyThisOne(Grouping &ging, V e, bool randomized_p_in); template <class N> static void overlappingT(bloomGraph<N> &g) { printf("env: ALLOW_BOOST000 %s\n", getenv("ALLOW_BOOST000")); printf("env: Lookahead %s\n", getenv("Lookahead")); printf("env: MaxCommSize %s\n", getenv("MaxCommSize")); printf("env: OUTER_ITERS %s\n", getenv("OUTER_ITERS")); printf("env: LOUVAIN_ITERS %s\n", getenv("LOUVAIN_ITERS")); printf("NoBroken\n"); srand48(option_seed); // default seed. Will be changeable by command line arg. /* iterative::Partition p(g); iterative::findPartition(p, g); assert(option_planted[0]==0); strcpy(option_planted, option_overlapping); strcat(option_planted, "_partition"); savePartition(g, p, -1); long double p_in = (long double) p.m_i / p.a; long double p_out; { int64 b = p.N * (p.N-1L) / 2L; int64 m_e = p.m-p.m_i; p_out = (long double) (m_e) / (b - p.a); } PP(p_in); PP(p_out); //Grouping ging(g, p_in, p_out); //seedGroupingWithPartition(ging, p); */ Grouping ging(g, option_p_in, option_p_out); estimate_p_in_and_p_out(ging); ging.value_of_objective_with_no_communities = MOSES_objective(ging); //PP(ging._p_in); //PP(ging._p_out); if(option_loadOverlapping[0]) { // load preexisting grouping Pn("Preloading grouping '%s'", option_loadOverlapping); ifstream inFile(option_loadOverlapping); //for (int i=0; i<5; ++i) int lineNo=0; while(inFile.peek()!=EOF) { lineNo ++; string line; getline(inFile, line); if(line.length()==0) break; Group *grp = ging.newG(); istringstream linestream(line); //PP(line);// if(linestream.peek()=='"') { char ch; linestream >> ch; while(linestream.peek() != EOF) { linestream >> ch; if(ch=='"') break; } if(linestream.peek()!='\t') Die("grouping file should have a tab after any \" \". line %d {%d '%c'}", lineNo, (int) ch, ch); } while(linestream >> ws, linestream.peek() != EOF) { N n; linestream >> n; V v = g.key_for_vertexName(n); assert(v>=0); assert(v<g.vcount()); ging.addV(grp, v); } } save(ging, g); } estimate_p_in_and_p_out(ging); groupStats(ging, g); MOSES_objective(ging); if(flag_justCalcObjective) exit(0); const int max_OuterIters = atoi(getenv("OUTER_ITERS") ? : "20"); PP(max_OuterIters); for (int k=0; k<max_OuterIters; k++) { MOSES_objective(ging); const size_t num_groups_before = ging.groups.size(); ostringstream s; s << "Whole outer iter " << k << "/" << max_OuterIters; Timer timer(s.str()); Pn("\ngrow seeds %d/%d", k, max_OuterIters); bool randomize_p_in; if(k < max_OuterIters / 2) { randomize_p_in = true; Pn("Random p_i for each edge that we try"); estimate_p_in_and_p_out(ging); // this is just to estimate p_out useOneNodeSeeds(ging, g, true); estimate_p_in_and_p_out(ging); tryDeletions(ging); } else { randomize_p_in = false; useOneNodeSeeds(ging, g, false); tryDeletions(ging); } groupStats(ging, g); save(ging, g); estimate_p_in_and_p_out(ging); //tryDeletions(ging); //save(ging, g); const size_t num_groups_after = ging.groups.size(); if(!randomize_p_in && /*num_groups_after > 1000 && */ 0.99L * num_groups_after <= num_groups_before) { Pn("breaking after %d growing passes, as VERY FEW more have been found among the most recent subset", k+1); break; } } int louvainStyle_iter=0; const int max_louvainStyleIters = atoi(getenv("LOUVAIN_ITERS") ? : "10"); PP(max_louvainStyleIters); while(louvainStyle_iter != max_louvainStyleIters) { MOSES_objective(ging); Timer timer("Whole Louvain iter"); Pn("\nLouvain-style iteration %d/%d", louvainStyle_iter++, max_louvainStyleIters); louvainStyle(ging, g); tryDeletions(ging, louvainStyle_iter==max_louvainStyleIters); estimate_p_in_and_p_out(ging); groupStats(ging, g); save(ging, g); } if(0) { tryMerges(ging); save(ging, g); groupStats(ging, g); } Pn("\n\nFINAL Grouping"); groupStats(ging, g); estimate_p_in_and_p_out(ging); MOSES_objective(ging); } static bool tryAndApplyThisOne(Grouping &ging, V e, bool randomized_p_in) { static long double boost = 0.0L; if(!getenv("ALLOW_BOOST000")) boost=0.0L; // reset it back to zero unless ALLOW_BOOST000 is defined in the environment pair<long double, set<V> > bestSeed = growThisEdge(ging, e, boost, randomized_p_in); if(bestSeed.first + boost> 0.0L && bestSeed.second.size()>0 ) { addSeed(ging, bestSeed.second, randomized_p_in); boost /= 2.0; // if(boost<0.0L) boost=0.0L; return true; //Pn("Applied best 1-seed. Now returning. %zd nodes (+%Lg). Now there are %zd communities", bestSeed.second.size(), bestSeed.first, ging.groups.size()); // if(bestSeed.second.size() < 20) ForeachContainer (V v, bestSeed.second) { cout << "|" << g.name(v); } P("\n"); } boost += 0.1; return false; } template <class N> static void useOneNodeSeeds(Grouping &ging, bloomGraph<N> &g, bool randomize_p_in) { Timer timer(__FUNCTION__); const int numTries = g.ecount()/5; P(" \n Now just use one-EDGE seeds at a time. Try %d edges\n", numTries); // groupStats(ging, g); for(int x=0; x<numTries; ++x) { if(x && numTries>5 && x%(numTries/5)==0) { PP(x); PP(ging.groups.size()); } // choose an edge at random, but prefer to use it iff it's sharedCommunities score is low. V e = V(drand48() * (2*ging._g.ecount())); assert(e >= 0); assert(e < 2*ging._g.ecount()); if(randomize_p_in) { ging._p_in = 0.01L + 0.98L*drand48(); assert(ging._p_in < 1.0L); } tryAndApplyThisOne(ging, e, randomize_p_in); #if 0 int sharedCommunities = ging.comm_count_per_edge(ging._g.neighbours(0).first[e], &(ging._g.neighbours(0).first[e])); // a little time in here //PP(sharedCommunities); if( (double(rand())/RAND_MAX) < powl(0.5, sharedCommunities)) { //Pn(" X %d", sharedCommunities); tryAndApplyThisOne(ging, e); } else { //Pn(" %d", sharedCommunities); } #endif } } template <class N> static void groupStats(const Grouping &ging, bloomGraph<N> &g) { map<size_t, int> group_sizes_of_the_randomized; map<size_t, int> group_sizes; int64 totalAssignments = 0; // to help calculate average communities per node. ForeachContainer(Group *group, ging.groups) { DYINGWORDS(group->vs.size()>0) { PP(group->vs.size()); } group_sizes[group->vs.size()]++; totalAssignments += group->vs.size(); if(group->_randomized_p_in) group_sizes_of_the_randomized[group->vs.size()]++; } //Perror(" %zd\n", ging.groups.size()); Pn("#groups=%zd. %zd nodes, out of %d, are in at least one community. avgs grps/node=%g", ging.groups.size(), ging.vgroups_size(), g.vcount(), (double) totalAssignments / g.vcount()); pair<size_t, int> group_size; size_t max_group_size = group_sizes.size()==0 ? 0 : group_sizes.rbegin()->first; int entries_per_row = 15; int number_of_rows = (max_group_size / entries_per_row) + 1; for(int r = 0; r<number_of_rows ; r++) { for(size_t c = r; c <= max_group_size; c+=number_of_rows) { if(group_sizes[c]>0) P("%6d{%3zd}", group_sizes[c], c); else P(" "); } P("\n"); } { // now, just the randomized ones size_t max_group_size = group_sizes_of_the_randomized.size()==0 ? 0 : group_sizes_of_the_randomized.rbegin()->first; int entries_per_row = 15; int number_of_rows = (max_group_size / entries_per_row) + 1; for(int r = 0; r<number_of_rows ; r++) { for(size_t c = r; c <= max_group_size; c+=number_of_rows) { if(group_sizes_of_the_randomized[c]>0) P("%6d{%3zd}", group_sizes_of_the_randomized[c], c); else P(" "); } P("\n"); } } #if 0 set<V> lonelyNodesInLargestGroup; Group *largestGroup = NULL; ForeachContainer(Group *group, ging.groups) { if(group->vs.size() == max_group_size) { ForeachContainer(V v, group->vs) { P("(%zd)", ging.vgroups(v).size()); if(1 == ging.vgroups(v).size() && 0 == rand()%2) lonelyNodesInLargestGroup.insert(v); } P("\n"); largestGroup = group; break; } } #endif { int print_count = 0; for(map<int, V>::const_iterator it = ging.global_edge_counts.begin(); it!=ging.global_edge_counts.end(); ++it) { P("%6d(%3d)", (int) it->second ,(int) it->first); print_count++; if(print_count%15==0) P("\n"); } P("\n"); //if(0) update_p_out(ging); //PP(ging._p_in); //PP(ging._p_out); } } void seedGroupingWithPartition(Grouping &ging, const iterative::Partition &p) { for(V c=0; c<p.g.vcount(); ++c) { if(p.p[c].c == c) { // we're at the head node //Pn(" order %d", p.p[c].order); Group *grp = ging.newG(); V v = c; do { assert(c == p.p[v].c); ging.addV(grp, v); //Pn ("%d is in %d", v ,c); v = p.p[v].next; } while (v != c); } } } template <class It> static size_t count_intersection(It it1b, It it1e, It it2b, It it2e) { vector< typename It::value_type > is; set_intersection(it1b, it1e, it2b, it2e, back_inserter(is)); return is.size(); } template <class Container> static size_t count_intersection(const Container &container1, const Container &container2) { return count_intersection( container1.begin() , container1.end() , container2.begin() , container2.end() ); } struct DeltaSeed { const V _v; // for this node const int _group_size_smaller; // ...and this group (which v is NOT currently in) const Grouping &_ging; // what'd be the change in entropy (edge+Z+Q) from joining it? long double _deltadeltaEdgeEntropy; int count_edges_back_into_this_group; long double deltadeltaPairEntropy() const { return _deltadeltaEdgeEntropy + log2l(1.0L - _ging._p_in) * (_group_size_smaller - count_edges_back_into_this_group); } explicit DeltaSeed(V v, int group_size_smaller, Grouping &ging) : _v(v), _group_size_smaller(group_size_smaller), _ging(ging), _deltadeltaEdgeEntropy(0.0L), count_edges_back_into_this_group(0) { //assert(_grp.vs.count(v)==0); } void addEdge2(V n, const V* edgeVN_ptr) { // n is connected to _v assert(*edgeVN_ptr == n); this->addEdge(n, _ging.comm_count_per_edge(n, edgeVN_ptr)); } void addEdge(V , int sharedCommunities) { // n is connected to _v // TODO: might be quicker to pass in the count of sharedCommunities too //assert(_ging._g.are_connected(_v, n)); // TODO: remove these assertions //assert(_grp.vs.count(n) == 1); //assert(_grp.vs.count(_v) == 0); count_edges_back_into_this_group ++; _deltadeltaEdgeEntropy += log2l(1.0L - (1.0L-_ging._p_out)*powl(1.0L - _ging._p_in, 1+sharedCommunities)) - log2l(1.0L - (1.0L-_ging._p_out)*powl(1.0L - _ging._p_in, sharedCommunities)); } void redoEdge(V , int previous_sharedCommunities) { // n is connected to _v // TODO: might be quicker to pass in the count of sharedCommunities too _deltadeltaEdgeEntropy -=(log2l(1.0L - (1.0L-_ging._p_out)*powl(1.0L - _ging._p_in, 1+previous_sharedCommunities)) - log2l(1.0L - (1.0L-_ging._p_out)*powl(1.0L - _ging._p_in, previous_sharedCommunities))); _deltadeltaEdgeEntropy += log2l(1.0L - (1.0L-_ging._p_out)*powl(1.0L - _ging._p_in, 2+previous_sharedCommunities)) - log2l(1.0L - (1.0L-_ging._p_out)*powl(1.0L - _ging._p_in, 1+previous_sharedCommunities)); } long double _deltaZentropy() const { const size_t N = _ging._g.vcount(); const size_t x = _group_size_smaller; const size_t x2 = 1+x; return( x2 * log2l(x2) + (N-x2) * log2l(N-x2) -x * log2l(x) - (N-x ) * log2l(N-x ) ); /* (x2 * (log2l(x2)-log2l(N)) + (N-x2) * (log2l(N-x2)-log2l(N)) + log2l(1+ging.groups.size()) - log2l(N)) -(x * (log2l(x) -log2l(N)) + (N-x ) * (log2l(N-x )-log2l(N)) + log2l(1+ging.groups.size()) - log2l(N)) = (x2 * (log2l(x2)-log2l(N)) + (N-x2) * (log2l(N-x2)-log2l(N)) ) -(x * (log2l(x) -log2l(N)) + (N-x ) * (log2l(N-x )-log2l(N)) ) = (x2 * (log2l(x2) ) + (N-x2) * (log2l(N-x2) ) ) -(x * (log2l(x) ) + (N-x ) * (log2l(N-x ) ) ) = x2 * log2l(x2) + (N-x2) * log2l(N-x2) -x * log2l(x) - (N-x ) * log2l(N-x ) */ } long double _deltaTotalentropy() const { return this->deltadeltaPairEntropy() + this->_deltaZentropy(); } }; struct FrontierNode { FrontierNode(long double &score, V v) : _score(score), _v(v) {} long double _score; V _v; struct Incrementer { long double _x; Incrementer(long double &x) : _x(x) {} void operator() (FrontierNode &fn) const { fn._score += _x; } }; }; using namespace boost::multi_index; struct VertexTag {}; struct Frontier : private multi_index_container < // TODO: Some sort of binary tree sometime? FrontierNode, indexed_by< ordered_non_unique< member<FrontierNode,long double,&FrontierNode::_score>, greater<long double> >, hashed_unique< tag<VertexTag>, member<FrontierNode,V,&FrontierNode::_v> > > > { // vertices, and their scores. // easy removal of the highest-score vertices. // easy increase of score of arbitrary members, adding them if they don't exist already. public: static long double __attribute__ ((noinline)) calcddEE(const Grouping &ging, int sharedCommunities) { return log2l(1.0L - (1.0L-ging._p_out) * powl(1.0L - ging._p_in, 1+sharedCommunities)) - log2l(1.0L - (1.0L-ging._p_out) * powl(1.0L - ging._p_in, sharedCommunities)) - log2l(1.0L - ging._p_in) + 1e-20L * drand48() // random tie breaking ; } void addNode(const Grouping &ging, V to, const V *edgeFT_ptr) { // to is being added to the frontier, BUT it may already be in the frontier. // from is in the seed. //assert(*edgeFT_ptr == to); int sharedCommunities = ging.comm_count_per_edge(to, edgeFT_ptr); // a little time in here long double deltadeltaEdgeEntropy = calcddEE(ging, sharedCommunities /*, to*/); // a little time in here Frontier::nth_index<1>::type::iterator addOrModifyThis = this->get<1>().find(to); if(addOrModifyThis==this->get<1>().end()) { // TODO: faster if search for to is done just once? this->insert(FrontierNode(deltadeltaEdgeEntropy, to)); } else { this->get<1>().modify(addOrModifyThis, FrontierNode::Incrementer(deltadeltaEdgeEntropy)); } } void erase_best_node() { Frontier::iterator best_node = this->get<0>().begin(); this->erase(best_node); } int erase_this_node(V to) { return this->get<1>().erase(to); } long double best_node_score() const { Frontier::iterator best_node = this->get<0>().begin(); return best_node -> _score; } V best_node_v() const { Frontier::iterator best_node = this->get<0>().begin(); return best_node -> _v; } bool Empty() const { return this->empty(); } }; static long double logNchoose(int64 N, int64 n_c) { if(n_c==N) return 0; static vector<long double> logNchoose_vector; // static int64 usedN; assert(n_c>0); assert(n_c<=N); if (logNchoose_vector.size()==0) { Timer t("logNchoose Initialization"); logNchoose_vector.resize(N+1); // usedN = N; long double lN = 0.0L; for(int64 x1=1; x1<=N; x1++) { if(x1>1) { int64 i = x1-1; lN += log2l(i) - log2l(N-i); } logNchoose_vector.at(x1) = lN; } } assert(logNchoose_vector.at(0) == 0); // DYINGWORDS(logNchoose_vector.at(N) == 0) { // will never be exactly zero, but it should be, in theory assert(logNchoose_vector.size()>0); // assert(usedN == N); assert( size_t(N+1) == logNchoose_vector.size()); assert( size_t(n_c) < logNchoose_vector.size()); return logNchoose_vector.at(n_c); } pair<long double, set<V> > growingSeed(Grouping &ging, int lookahead , set<V> &seed , pair<long double, set<V> > bestSoFar , long double seedEdgeEntropy , int seed_size , Frontier &frontier , int edges_in_seed , const long double &boost // to allow some negative communities to persist. The deletion phase will fix them later. This is to ensure that we have the best chance of filling the graph up quickly. , bool randomized_p_in ) // Find the expansion among the frontier that best improves the score. Then recurse to it. // Stop growing if dead end is reached (empty frontier) or the seed isn't increasing and we already have at least 5 nodes. // Return the best set of nodes // TODO: Profile, then make this damn efficient { assert((int) seed.size() == seed_size); if(frontier.Empty()) return bestSoFar; const V best_v = frontier.best_node_v(); #if 0 { IteratorRange<const V *> ns(ging._g.neighbours(best_v)); Foreach(V n, ns) { if(1==seed.count(n)) { // This neighbour is already in the seed. That means the count of edges within the seed is about to be increased. Should update randomized p_in in light of this. ++edges_in_seed; } } int64 pairsInSeed = seed_size * (1+seed_size) / 2; long double new_p_in = 1.0L * (2*edges_in_seed+1) / (2 * pairsInSeed + 2) ; if(randomized_p_in) ging._p_in = new_p_in; /* cout << edges_in_seed << "/" << (1+seed_size) << "\t" << 100.0 * edges_in_seed / (seed_size * (1+seed_size) / 2) // << "\t" << ging._p_in << "\t" << randomized_p_in << "\t" << new_p_in << endl; */ assert(edges_in_seed <= (seed_size * (1+seed_size) / 2)); } #endif const long double newseedEdgeEntropy = seedEdgeEntropy + frontier.best_node_score() + log2l(1.0L-ging._p_in) * seed_size; const int N = ging._g.vcount(); //const int x = seed_size; const int x1= 1+seed_size; //long double seed_totalDeltaEntropy = seedEdgeEntropy + x * (log2l(x)-log2l(N)) + (N-x) * (log2l(N-x)-log2l(N)) + log2l(1+ging.groups.size())/*equivalent groupings*/ - log2l(N)/*encoding of size of the group*/; UNUSED int64 q = ging.groups.size(); if (q==0) q=1; UNUSED const int64 q_= 1 + q; const long double logNchoosen = logNchoose(N,x1); const long double newseed_totalDeltaEntropy = newseedEdgeEntropy //+ x1 * (log2l(x1)-log2l(N)) + (N-x1) * (log2l(N-x1)-log2l(N)) + logNchoosen - log2l(N+1)/*encoding of size of the group*/ + log2l(1+ging.groups.size())/*equivalent groupings*/ //+ (getenv("UseBroken") ? ( ( q_ * (log2l(q_) - log2l(exp(1))) + log2l(N+1) - log2l(N+1-q_) ) - ( q * (log2l(q ) - log2l(exp(1))) + log2l(N+1) - log2l(N+1-q ) ) ) : 0) ; if(bestSoFar.first < newseed_totalDeltaEntropy) { bestSoFar.first = newseed_totalDeltaEntropy; bestSoFar.second = seed; bestSoFar.second.insert(best_v); } if( (size_t) seed_size >= lookahead +bestSoFar.second.size() ) // lookahead return bestSoFar; const size_t max_commsize = atoi(getenv("MaxCommSize") ? : "10000000"); if( (size_t) seed_size >= max_commsize ) { // max comm size bestSoFar.first = -10000000; return bestSoFar; } //if( bestSoFar.first > 0.0L) // once positive, return immediately!!!!!!!!!!!!! //return bestSoFar; if( (size_t) seed_size > bestSoFar.second.size() && bestSoFar.first + boost > 0.0L) // once positive, return immediately if it drops. return bestSoFar; //if(bestSoFar.first > 0.0L) //return bestSoFar; // This isn't working so well. Too many communities (I think), and no faster (for Oklahoma at least) frontier.erase_best_node(); IteratorRange<const V *> ns(ging._g.neighbours(best_v)); const V *edgeVN_offset = ging._g.neighbours(best_v).first; Foreach(V n, ns) { assert( *edgeVN_offset == n); //assert(ging._g.neighbours(0).first[ging._comm_count_per_edge2[edgeVN_offset].other_index] == best_v); if(0==seed.count(n)) frontier.addNode(ging, n , edgeVN_offset ); ++edgeVN_offset; } seed.insert(best_v); return growingSeed(ging , lookahead , seed , bestSoFar , newseedEdgeEntropy , 1 + seed_size , frontier , edges_in_seed , boost , randomized_p_in ); } struct ThrowingIterator { struct Dereferenced {}; V & operator *() { throw Dereferenced(); } void operator ++() { throw Dereferenced(); } }; bool emptyIntersection(const pair<const V*, const V*> &l, const pair<const V*, const V*> &r) { try { set_intersection( l.first ,l.second ,r.first ,r.second ,ThrowingIterator() ); } catch (ThrowingIterator::Dereferenced &) { return false; } return true; //inter.empty(); } static pair<long double, set<V> > growThisEdge(Grouping &ging, const V edgeNumber, const long double &boost, bool randomized_p_in) { assert(edgeNumber < 2*ging._g.ecount()); V r = ging._g.neighbours(0).first[edgeNumber]; V l = ging._g.neighbours(0).first[ging.comm_count_per_edge2[edgeNumber].other_index]; // there must be a triangle available if(emptyIntersection(ging._g.neighbours(l),ging._g.neighbours(r))) return make_pair(-1.0L, set<V>()); Frontier frontier; { IteratorRange<const V *> ns(ging._g.neighbours(l)); const V *edgeIN_ptr = ging._g.neighbours(l).first; Foreach(V n, ns) { frontier.addNode(ging, n, edgeIN_ptr); ++edgeIN_ptr; } } //PP(frontier.size()); const int erased = frontier.erase_this_node(r); DYINGWORDS(erased==1) { PP(erased); PP(l); PP(r); //PP(frontier.size()); PP(ging._g.degree(l)); PP(ging._g.degree(r)); IteratorRange<const V *> ns(ging._g.neighbours(l)); Foreach(V n, ns) { PP(n); } } assert(erased==1); { IteratorRange<const V *> ns(ging._g.neighbours(r)); const V *edgeIN_ptr = ging._g.neighbours(r).first; Foreach(V n, ns) { if(n!=l) frontier.addNode(ging, n, edgeIN_ptr); ++edgeIN_ptr; } } set<V> seed; seed.insert(l); seed.insert(r); int sharedCommunities = ging.comm_count_per_edge(r, &(ging._g.neighbours(0).first[edgeNumber])); // a little time in here pair<long double, set<V> > grownSeed = growingSeed(ging , atoi(getenv("Lookahead") ? : "2") , seed , make_pair(-10000000.0L, seed) // This score is too low, but then we don't expect a singleton community to come out best anyway! Only positive scores are used. , log2l(1.0L - (1.0L-ging._p_out) * powl(1.0L - ging._p_in, 1+sharedCommunities)) - log2l(1.0L - (1.0L-ging._p_out) * powl(1.0L - ging._p_in, sharedCommunities)) , 2 , frontier , 1 , boost , randomized_p_in ); return grownSeed; } template <class N> static void save(Grouping &ging, bloomGraph<N> &g) { ofstream saveFile(option_overlapping); ForeachContainer(Group *grp, ging.groups) { bool firstLine = true; if(flag_save_group_id_in_output) saveFile << '\"' << grp->_id << "\"\t"; ForeachContainer(V v, grp->vs) { saveFile << (firstLine?"":" ") << g.name(v); firstLine = false; } saveFile << endl; } runMutual(); } struct hashGroup { int operator() (Group *grp) const { return grp->_id; } }; typedef boost::unordered_map<Group *, DeltaSeed, hashGroup> SeedDeltasT; template <class N> static void louvainStyle(Grouping &ging, bloomGraph<N> &g) { Timer t(__FUNCTION__); // find a node, isolate it from its communities, Add back one at a time if appropriate. const bool DEBUG_louvainStyle = 0; for(V v=0; v<g.vcount(); v++) { if(0) update_p_out(ging); // if(v%(g.vcount()/20)==0) PP(v); if(DEBUG_louvainStyle) groupStats(ging, g); if(DEBUG_louvainStyle) cout << "removing node in these many groups: " << ging.vgroups(v).size() << endl; ging.isolate(v); SeedDeltasT _seedDeltas; IteratorRange<const V *> ns(ging._g.neighbours(v)); { const V * edgeVN_ptr = ging._g.neighbours(v).first; Foreach(V n, ns) { int sharedCommunities = ging.comm_count_per_edge(n,edgeVN_ptr); // TODO: Could prepare the results for addEdge of v<>n ForeachContainer(Group *grp, ging.vgroups(n)) { _seedDeltas.insert(make_pair(grp, DeltaSeed(v, grp->vs.size(), ging))).first->second.addEdge(n, sharedCommunities); //_seedDeltas.find(grp)->second.addEdge(n, sharedCommunities); } ++edgeVN_ptr; } } for(int addedBack = 0; _seedDeltas.size()>0 ; addedBack++) { // for each neighbouring group, calculate the delta-entropy of expanding back in here. pair<long double, Group *> bestGroup(-LDBL_MAX, (Group*) NULL); int num_positive = 0; for(SeedDeltasT::iterator i = _seedDeltas.begin(); i!=_seedDeltas.end(); ) { if(i->second._deltaTotalentropy()<=0.0L) { i = _seedDeltas.erase(i); continue; } else { long double delta2 = i->second._deltaTotalentropy(); // TODO: Count the positive scores. No point proceeding if there aren't any more positive scores, as they can only decrease if(bestGroup.first < delta2) bestGroup = make_pair(delta2, i->first); if(delta2>0.0L) ++num_positive; } ++i; } if(bestGroup.first > 0.0L) { assert(num_positive>=1); ging.addV(bestGroup.second, v); if(num_positive==1) { // if just one was positive, then there's no point continuing, as the rest will only lose more score. break; } _seedDeltas.erase(bestGroup.second); // the other potential groups on the end of this edge need to have their addEdge undone const V * edgeVN_ptr = ging._g.neighbours(v).first; IteratorRange<const V*> ns(ging._g.neighbours(v)); Foreach(V n, ns) { assert(*edgeVN_ptr == n); if(bestGroup.second->vs.count(n)) { int previous_sharedCommunities = ging.comm_count_per_edge(n, edgeVN_ptr) - 1; ForeachContainer(Group *grp, ging.vgroups(n)) { SeedDeltasT::iterator grpInSeed =_seedDeltas.find(grp); if(grpInSeed != _seedDeltas.end()) { const long double before = grpInSeed->second._deltaTotalentropy(); grpInSeed->second.redoEdge(n, previous_sharedCommunities); const long double after = grpInSeed->second._deltaTotalentropy(); if(after > before) { Perror("%s:%d _deltaTotalentropy %Lg -> %Lg\n", __FILE__, __LINE__, before, after); } } } } ++edgeVN_ptr; } } else break; } } } static void update_p_out(Grouping &ging) { long double new_p_out = 2.0L * ging.global_edge_counts[0] / ging._g.vcount() / (ging._g.vcount()-1) ; if(new_p_out > 0.1L) ging._p_out = 0.1L; else ging._p_out = new_p_out; } struct PairGroupHash { int operator() (const pair<Group*,Group*> &pg) const { return pg.first->_id + pg.second->_id; } }; static void tryMerges(Grouping &ging) { Timer timer(__FUNCTION__); typedef boost::unordered_map< pair<Group*,Group*> , long double, PairGroupHash> MergesT; MergesT proposed_merges; size_t counter=0; for(V e = 0; e < /*100000 */ 2*ging._g.ecount() ; e++) { //if(e % (2*ging._g.ecount()/10) ==0) { PP(e); } V e2 = ging.comm_count_per_edge2[e].other_index; V l = ging._g.neighbours(0).first[e2]; V r = ging._g.neighbours(0).first[e]; if(r<l) continue; // no point considering each edge twice V sharedCommunities = ging.comm_count_per_edge2[e].shared_comms; assert(sharedCommunities == ging.comm_count_per_edge2[e2].shared_comms); //Pn("%d\t%d", l, r); counter++; const set<Group *> &lgrps = ging.vgroups(l); const set<Group *> &rgrps = ging.vgroups(r); //PP(lgrps.size()); //PP(rgrps.size()); vector<Group *> lonly, ronly; set_difference(lgrps.begin(),lgrps.end(),rgrps.begin(),rgrps.end(),back_inserter(lonly)); set_difference(rgrps.begin(),rgrps.end(),lgrps.begin(),lgrps.end(),back_inserter(ronly)); //Pn("# unmatched %zd,%zd", lonly.size(), ronly.size()); ForeachContainer(Group *lg, lonly) { ForeachContainer(Group *rg, ronly) { long double qi = 1.0L - ging._p_in; long double qo = 1.0L - ging._p_out; //const int64 oldQz = ging.groups.size(); Group * lg1 = lg; Group * rg1 = rg; if(lg1 > rg1) swap(lg1, rg1); MergesT::key_type key = make_pair(lg1, rg1); MergesT::iterator pm = proposed_merges.find(key); if(pm == proposed_merges.end()) { const int64 s1 = lg1->vs.size(); const int64 s2 = rg1->vs.size(); vector<V> Union; set_union(lg1->vs.begin(),lg1->vs.end(),rg1->vs.begin(),rg1->vs.end(),back_inserter(Union)); const int64 N = ging._g.vcount(); pm = proposed_merges.insert(make_pair(key, log2l(qi)*0.5L* (long double)( Union.size() * (Union.size()-1) - s1*(s1-1) - s2*(s2-1) ) // + ( (oldQz) *log2l(oldQz-1) + log2l(exp(1)) - log2l(oldQz-2-N) ) // - ( (oldQz+1)*log2l(oldQz ) - log2l(oldQz-1-N) ) + (s1+s2) * (log2l(s1+s2) /*- log2l(N)*/) - (s1 ) * (log2l(s1 ) /*- log2l(N)*/) - (s2 ) * (log2l(s2 ) /*- log2l(N)*/) + log2l(N) // one fewer community whose pi has to be encoded )).first; } pm -> second+= log2l(1.0L - qo * powl(qi, 1+sharedCommunities)) - log2l(1.0L - qo * powl(qi, sharedCommunities)) - log2l(qi) // for a given member of the map, each edge will be found exactly once. So here we cancel the affect of assuming it was disconnected ; } } } for(V e = 0; e < /*100000 */ 2*ging._g.ecount() ; e++) { if(e % (2*ging._g.ecount()/10) ==0) { PP(e); } V e2 = ging.comm_count_per_edge2[e].other_index; V l = ging._g.neighbours(0).first[e2]; V r = ging._g.neighbours(0).first[e]; if(r<l) continue; // no point considering each edge twice V sharedCommunities = ging.comm_count_per_edge2[e].shared_comms; assert(sharedCommunities == ging.comm_count_per_edge2[e2].shared_comms); //Pn("%d\t%d", l, r); counter++; const set<Group *> &lgrps = ging.vgroups(l); const set<Group *> &rgrps = ging.vgroups(r); //PP(lgrps.size()); //PP(rgrps.size()); vector<Group *> inter; set_intersection(lgrps.begin(),lgrps.end(),rgrps.begin(),rgrps.end(),back_inserter(inter)); //Pn("# unmatched %zd,%zd", lonly.size(), ronly.size()); ForeachContainer(Group *lg, inter) { ForeachContainer(Group *rg, inter) { if(lg < rg) { // no point proposing a merge between a group and itself long double qi = 1.0L - ging._p_in; long double qo = 1.0L - ging._p_out; Group * lg1 = lg; Group * rg1 = rg; if(lg1 > rg1) swap(lg1, rg1); MergesT::key_type key = make_pair(lg1, rg1); MergesT::iterator pm = proposed_merges.find(key); if(pm != proposed_merges.end()) pm -> second+= log2l(1.0L - qo * powl(qi, sharedCommunities-1)) - log2l(1.0L - qo * powl(qi, sharedCommunities)) + log2l(qi) // for a given member of the map, each edge will be found exactly once. So here we cancel the affect of assuming it was disconnected ; } } } } int64 merges_accepted = 0; int64 merges_applied = 0; for(MergesT::const_iterator pm = proposed_merges.begin(); pm != proposed_merges.end(); ++pm) { const long double score = pm->second; //const int64 N = ging._g.vcount(); boost::unordered_set<Group *> already_merged; if(score >0.0) { //PP(scoreEdges); //PP(scoreZ); merges_accepted++; MergesT::key_type merge_these = pm->first; if(already_merged.count(merge_these.first)==0 && already_merged.count(merge_these.second)==0) { Group * l = merge_these.first; Group * r = merge_these.second; const set<V> these_nodes(l->vs); // copy them, so as to iterate properly over them. //P(" "); PP(ging.groups.size()); ForeachContainer(V v, these_nodes) { if(r->vs.count(v)==0) { ging.addV(r,v); } assert(r->vs.count(v)==1); //ging.delV(l,v); } //PP(ging.groups.size()); already_merged.insert(merge_these.first); already_merged.insert(merge_these.second); merges_applied++; } } //if(score > -25.0) { printf("merge: %-11.2Lf\n", score); } } PP(proposed_merges.size()); PP(merges_accepted); PP(merges_applied); } static void tryDeletions(Grouping &ging, bool SaveScores /*= true*/) { // delete groups which aren't making a positive contribution any more. Timer timer(__FUNCTION__); typedef boost::unordered_map< Group* , long double, hashGroup> DeletionsT; DeletionsT proposed_deletions; const int64 N = ging._g.vcount(); ForeachContainer(Group *grp, ging.groups) { // preseed with all groups, because we want the groups even that don't have an edge in them! const int64 sz = grp->vs.size(); //int64 q = ging.groups.size() -1; if (q<=0) q=1; //const int64 q_= 1 + q; const long double logNchoosen = logNchoose(N,sz); proposed_deletions.insert(make_pair(grp, log2l(1.0L - ging._p_in)*(sz*(sz-1)/2) + logNchoosen - log2l(N+1)/*encoding of size of the group*/ + log2l(1+ging.groups.size())/*equivalent groupings*/ //+ (getenv("UseBroken") ? ( ( q_ * (log2l(q_) - log2l(exp(1))) + log2l(N+1) - log2l(N+1-q_) ) - ( q * (log2l(q ) - log2l(exp(1))) + log2l(N+1) - log2l(N+1-q ) ) ) : 0) )); } for(V e = 0; e < /*100000 */ 2*ging._g.ecount() ; e++) { /* if(e % (2*ging._g.ecount()/10) ==0) { PP(e); } */ V e2 = ging.comm_count_per_edge2[e].other_index; V sharedCommunities = ging.comm_count_per_edge2[e].shared_comms; assert(sharedCommunities == ging.comm_count_per_edge2[e2].shared_comms); V l = ging._g.neighbours(0).first[e2]; V r = ging._g.neighbours(0).first[e]; if(r<l) continue; // no point considering each edge twice const set<Group *> &lgrps = ging.vgroups(l); const set<Group *> &rgrps = ging.vgroups(r); vector<Group *> sharedComms; set_intersection(lgrps.begin(),lgrps.end(),rgrps.begin(),rgrps.end(),back_inserter(sharedComms)); assert((size_t)sharedCommunities == sharedComms.size()); ForeachContainer(Group *grp, sharedComms) { DeletionsT::iterator pm = proposed_deletions.find(grp); assert(pm != proposed_deletions.end()); pm -> second+= log2l(1.0L - (1.0L-ging._p_out) * powl(1.0L - ging._p_in, sharedCommunities)) - log2l(1.0L - (1.0L-ging._p_out) * powl(1.0L - ging._p_in, sharedCommunities-1)) - log2l(1.0L - ging._p_in) ; } } assert(proposed_deletions.size() <= ging.groups.size()); // maybe some communities didn't have an edge in them V deletions_accepted = 0; map<V, int> deletions_sizes; PP(ging.groups.size()); for(DeletionsT::const_iterator pm = proposed_deletions.begin(); pm != proposed_deletions.end(); ++pm) { const long double score = pm->second; //const int64 N = ging._g.vcount(); if(score < 0.0) { //PP(scoreEdges); //PP(scoreZ); deletions_accepted++; deletions_sizes[pm->first->vs.size()]++; { // delete the group set<V> vs = pm->first->vs; // COPY the vertices in ForeachContainer(V v, vs) { ging.delV(pm->first, v); } // By now, pm->first will be an invalid pointer, as it will be been delete'd } } } P("deletions_accepted: %d\t", deletions_accepted); pair<V, int> delete_size; ForeachContainer(delete_size, deletions_sizes) { P("%d{%d} ", delete_size.second, delete_size.first); } P("\n"); PP(ging.groups.size()); //if(SaveScores && option_saveMOSESscores[0]) Pn("NOT Saving the delta-scores for each comm"); if(SaveScores && option_saveMOSESscores[0]) { Pn("Saving the MOSES delta-score for each community as per the --saveMOSESscores option"); ofstream saveFile(option_saveMOSESscores); ForeachContainer(Group *grp, ging.groups) { // preseed with all groups, because we want the groups even that don't have an edge in them! saveFile << proposed_deletions[grp] << '\t' << grp->vs.size() << endl; } } } long double P_x_given_z(const Grouping &ging, long double p_o, long double p_i, int sigma_shared_Xis1) { const int64 N = ging._g.vcount(); const int64 m = ging._g.ecount() / 2L; long double logP_XgivenZ = 0.0; logP_XgivenZ += log2l(1.0L - p_o) * (N * (N-1) / 2 - m); logP_XgivenZ += log2l(1.0L - p_i) * (ging._sigma_shared - sigma_shared_Xis1); typedef pair <int,V> edge_countT; ForeachContainer(const edge_countT &edge_count, ging.global_edge_counts) { const int64 s = edge_count.first; const int64 m_s = edge_count.second; logP_XgivenZ += log2l(1.0L - (1.0L - p_o)*powl(1.0L - p_i, s)) * m_s; } return logP_XgivenZ; } long double MOSES_objective(const Grouping &ging) { Timer t(__FUNCTION__); // Three components // P(x|z) // Qz! // product of binomial/N+1 int64 sigma_shared_Xis1 = 0; pair <int,V> edge_count; ForeachContainer(edge_count, ging.global_edge_counts) { sigma_shared_Xis1 += edge_count.first * edge_count.second; } long double Pxz = P_x_given_z(ging, ging._p_out, ging._p_in, sigma_shared_Xis1); long double Pz = 0.0; for (size_t i = 1; i<=ging.groups.size(); i++) { Pz += log2l(i); //+ log2l(1+ging.groups.size())/*equivalent groupings*/ //P(Pz); } // PP(Pz); int64 N = ging._g.vcount(); ForeachContainer(const Group *grp, ging.groups) { long double logNchoosen = logNchoose(N,grp->vs.size()); DYINGWORDS(logNchoosen <= 0.0) { PP(logNchoosen); } assert(logNchoosen <= 0.0); Pz += logNchoosen - log2l(N+1) ; } // PP(Pxz); // PP(Pz); // PP(Pxz + Pz); // PP(ging.value_of_objective_with_no_communities); if(ging.value_of_objective_with_no_communities==1.0) Pn("Compression:\t%Lf\t%Lg\t%Lg", 1.0L ,Pz ,Pxz ); else Pn("Compression:\t%Lf\t%Lg\t%Lg", (Pxz + Pz) / ging.value_of_objective_with_no_communities ,Pz ,Pxz ); return Pxz + Pz; } static void estimate_p_in_and_p_out(Grouping &ging) { Timer t(__FUNCTION__); //PP(ging._sigma_shared); /* int64 _sigma_shared2 = 0; ForeachContainer(const Group *grp, ging.groups) { _sigma_shared2 += int64(grp->vs.size()) * int64(grp->vs.size()-1); } PP(_sigma_shared2/2); assert(_sigma_shared2 = 2 * ging._sigma_shared); */ const int64 N = ging._g.vcount(); const int64 m = ging._g.ecount() / 2L; int64 sigma_shared_Xis1 = 0; pair <int,V> edge_count; ForeachContainer(edge_count, ging.global_edge_counts) { sigma_shared_Xis1 += edge_count.first * edge_count.second; } //PP(sigma_shared_Xis1); map<long double, pair<long double, long double>, greater<long double> > ALLlogP_XgivenZ; for(long double p_i = 0.0L; (p_i+=0.001L) < 1.0L; ) { for(long double p_o = 1e-11L; (p_o*=1.1L) < 1.0L; ) { long double logP_XgivenZ = 0.0; logP_XgivenZ += log2l(1.0L - p_o) * (N * (N-1) / 2 - m); logP_XgivenZ += log2l(1.0L - p_i) * (ging._sigma_shared - sigma_shared_Xis1); ForeachContainer(edge_count, ging.global_edge_counts) { const int64 s = edge_count.first; const int64 m_s = edge_count.second; logP_XgivenZ += log2l(1.0L - (1.0L - p_o)*powl(1.0L - p_i, s)) * m_s; } assert(logP_XgivenZ == P_x_given_z(ging ,p_o ,p_i ,sigma_shared_Xis1)); ALLlogP_XgivenZ[logP_XgivenZ] = make_pair(p_i, p_o); } } pair<long double, pair<long double, long double> > best; ForeachContainer(best, ALLlogP_XgivenZ) { Pn("BEST: %Lg,%Lg -> %9.0Lf ", best.second.first, best.second.second, best.first); ging._p_in = best.second.first; ging._p_out= best.second.second; break; } } } // namespace overlapping
Java