code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
line_mean
float64
0.5
100
line_max
int64
1
1k
alpha_frac
float64
0.25
1
autogenerated
bool
1 class
--- layout: post title: "Vim实用技巧进阶(第10章:复制和粘贴) - Practical.Vim.2nd.Edition" keywords: "vim,practical-vim,copy,paste,register,clipboard,实用技巧" description: "Practical.Vim.2nd.Edition 实用技巧进阶 第10章:复制和粘贴" tagline: "Tip 60~64" date: '2018-11-01 09:44:57 +0800' category: linux tags: vim practical-vim linux --- > {{ page.description }} # 第10章 复制和粘贴 > Copy and Paste ## Tip 60 匿名寄存器的使用 {: #tip60} > Delete, Yank, and Put with Vim's Unnamed Register *Vim* 的 删除, 拷贝, 放置(delete, yank, put) 命令在日常使用中被设计得简单易用. *匿名寄存器* 就是使用频率最高的寄存器 通常, 我们提到的 *剪切*, *拷贝* 和 *粘贴* 都是将文本放在剪贴板上. 而在 *Vim* 术语中, 我们不说 *剪贴板*, 而是 `寄存器` #### 互换字符 Keystrokes | Buffer Contents ---- | ---- {start} | Practica lvi<code class="cursor">m</code> `F␣` | Practica<code class="cursor">&nbsp;</code>lvim `x` | Practica<code class="cursor">l</code>vim `p` | Practical<code class="cursor">&nbsp;</code>vim {: .table-multi-text} - `F␣` - 往前搜索 *空格* 字符, 并定位到匹配的位置 - `x` - 删除光标处的 *空格* 字符, 并把删除的字符存入到 *匿名寄存器* - `p` - 粘贴刚刚删除掉的 *空格* 综合起来: `xp` 这2个命令就相当于把光标处的2个字符互换了位置 #### 互换行 Keystrokes | Buffer Contents ---- | ---- {start} | <code class="cursor">2</code>) line two <br>1) line one <br>3) line three `dd` | <code class="cursor">1</code>) line one <br>3) line three `p` | 1) line one <br><code class="cursor">2</code>) line two <br>3) line three {: .table-multi-text} - `dd` - 删除光标处的行内容, 并把内容存入到 *匿名寄存器* - `p` - *vim* 这次知道粘贴的内容是行(line-wise), 所以把 *匿名寄存器* 的内容粘贴到了当前行下面 (注意前面的 `xp` 是粘贴在字符后面) 所以 `ddp` 就相当于当前行和下一行的互换位置 #### 复制行 Keystrokes | Buffer Contents ---- | ---- {start} | 1) line one <br><code class="cursor">2</code>) line two `yyp` | 1) line one <br>2) line two <br><code class="cursor">2</code>) line two {: .table-multi-text} `yyp` 和 `ddp` 类似, 都是面向行的; `yyp` 进行了行的复制, 并放到了 *匿名寄存器*, 然后按行的形式粘贴出来, 达到复制行的效果 #### 拷贝撞车 前面 *Vim* 的 *删除*, *拷贝* 和 *放置* 操作看起来都是非常直观的; 那么且看下面的示例 <pre> collection = getCollection(); process(somethingInTheWay, target); </pre> 现在我们想将 *somethingInTheWay* 替换为 *collection*, 看看我们如何操作: Keystrokes | Buffer Contents ---- | ---- `yiw` | <code class="cursor">c</code>ollection = getCollection();<br> process(somethingInTheWay, target); `jww` | collection = getCollection();<br> process(<code class="cursor">s</code>omethingInTheWay, target); `diw` | collection = getCollection();<br> process(<code class="cursor">,</code> target); `P` | collection = getCollection();<br> process(somethingInTheWa<code class="cursor">y</code>, target); {: .table-multi-text} 一套操作下来, 跟预想的不一样啊??? `yiw` 把 *collection* 存到了 *匿名寄存器* 里, 但是后面的 `diw` 删除 *somethingInTheWay* 的同时, 把 *匿名寄存器* 给覆盖了, 所以粘贴出来却不是我们想要的 为了解决这一问题, 我们需要了解 *vim* 的 *寄存器* 是如何工作的 ## Tip 61 寄存器一览 {: #tip61} > Grok Vim's Registers *Vim* 不是使用单个剪贴板进行所有剪切, 复制和粘贴(cut, copy, paste)操作, 而是提供多个寄存器. 当我们使用删除, 拉取和放置(delete, yank, put)命令时,我们可以指定我们想要与之交互的寄存器 **Vim 术语差别**: `cut,copy,paste` 和 `delete,yank,put` <pre> cut, copy, paste 术语是普片理解的, 并且这些操作可用于大多数桌面软件程序和操作系统. Vim 也提供这些功能, 但它使用不同的术语: delete, yank, put. Vim的 put 命令实际上与粘贴操作相同. 幸运的是, 这两个单词都以字母 <code class="highlighter-rouge">p</code> 开头, 因此可以认为就是粘贴命令了. Vim 的 yank 命令相当于复制操作. 从历史上看, <code class="highlighter-rouge">c</code>命令已经分配给了更改操作, 因此vi的作者被给出了另一个名称. <code class="highlighter-rouge">y</code> 键可用, 因此复制操作变为 yank 命令. Vim 的 delete 命令相当于标准剪切操作. 也就是说, 它将指定的文本复制到寄存器中, 然后将其从文档中删除. 如果想真正的删除文本而不存入寄存器呢? Vim 提供一个特殊的寄存器: 黑洞(black hole). 东西存进去就相当于丢弃了, 黑洞寄存器 寻址符号为:<code class="highlighter-rouge">_</code> 所以真正的删除为: <code class="highlighter-rouge">"_{motion}</code> </pre> 所以, <span class="red">除非特殊说明, *Vim* 里说的 剪切, 复制, 粘贴操作, 通常上是指 delete, yank, put 操作</span>; 而 *Vim* 里的 剪切 和 复制 是不能在其他程序里进行粘贴的; 后面会介绍特殊的寄存器与剪贴板进行交互, 就可以在其他程序里进行粘贴操作了. #### 寄存器访问 语法 `"{register}` - `"ayiw` - 复制当前的词, 并存到寄存器 *a* 里, 可使用 `"ap` 粘贴出来 - `"bdd` - 删除当前行, 并存到寄存器 *b* 里, 可使用 `"bp` 粘贴出来 - `:delete c` - Ex命令, 删除当前行并存到寄存器 c, 粘贴删除的行可以使用 `:put c` #### 匿名寄存器(\"\") 匿名寄存器 寻址符号为: `"` 例如要粘贴命令为: `""p` 可简写为 `p` `x`, `s`, `d{motion}`, `c{motion}`, `y{motion}` 等命令(大写亦可)都会把内容另存一份到 *匿名寄存器*; 如果想指定放到某个寄存器里, 可以指定前缀: `"{register}`, 不指定就是默认的 *匿名寄存器* *匿名寄存器* 的内容很容易被覆盖掉, 所以某些时候要注意一下 #### yank寄存器(\"0) 但使用 `y{motion}` 命令时, 会把文本存到 *匿名寄存器* 同时也会存一份到 yank寄存器, 寻址符号为: `0` 顾名思义, yank寄存器 仅只对 `y{motion}` 拉取操作生效, 而其他的 `x`, `s`, `c{motion}`, `d{motion}` 等命令不行 我们回到上个小节的: [拷贝撞车](#拷贝撞车) 的示例 Keystrokes | Buffer Contents ---- | ---- `yiw` | <code class="cursor">c</code>ollection = getCollection();<br> process(somethingInTheWay, target); `jww` | collection = getCollection();<br> process(<code class="cursor">s</code>omethingInTheWay, target); `diw` | collection = getCollection();<br> process(<code class="cursor">,</code> target); `"0P` | collection = getCollection();<br> process(collectio<code class="cursor">n</code>, target); {: .table-multi-text} - `diw` - 删除当前词, 并覆盖掉 *匿名寄存器* 里的内容; 但是 yank寄存器 的是没变的 - `"0P` - 把 yank寄存器 的内容粘贴出来, 正好就是我们想要的 查看 *匿名寄存器* 和 *yank寄存器* 的内容: <pre> ➾ :reg "0 ❮ --- Registers --- "" somethingInTheWay "0 collection </pre> #### 字母寄存器(\"a-\"z) *Vim* 提供了一组以26个小写字母(a-z)命名的寄存器 - `"ad{motion}` - 删除(剪切)并存入寄存器 *a* - `"ay{motion}` - 拉取(拷贝)并存入寄存器 *a* - `"ap` - 粘贴(放置)寄存器 *a* 的内容 Keystrokes | Buffer Contents ---- | ---- `"ayiw` | <code class="cursor">c</code>ollection = getCollection();<br> process(somethingInTheWay, target); `jww` | collection = getCollection();<br> process(<code class="cursor">s</code>omethingInTheWay, target); `diw` | collection = getCollection();<br> process(<code class="cursor">,</code> target); `"aP` | collection = getCollection();<br> process(collectio<code class="cursor">n</code>, target); {: .table-multi-text} 但我们有多个想要粘贴的文本时, 字母命名的寄存器就很有用了 #### 黑洞寄存器(\"_) *黑洞寄存器* 就是一个丢弃内容的地方, 删除内容不会影响到 *匿名寄存器* Keystrokes | Buffer Contents ---- | ---- `yiw` | <code class="cursor">c</code>ollection = getCollection();<br> process(somethingInTheWay, target); `jww` | collection = getCollection();<br> process(<code class="cursor">s</code>omethingInTheWay, target); `"_diw` | collection = getCollection();<br> process(<code class="cursor">,</code> target); `P` | collection = getCollection();<br> process(collectio<code class="cursor">n</code>, target); {: .table-multi-text} 删除的时候指定了 黑洞寄存器, 所以不会覆盖 匿名寄存器 的内容, 粘贴的文本就是之前拷贝的 #### 剪贴板寄存器(\"+ 和 \"*) 目前为止, 前面提到的寄存器都是Vim的内部寄存器. 如果我们想在Vim里进行拷贝, 然后在外部其他程序里粘贴呢? 这个时候就需要用到系统剪贴板了 系统剪贴板寄存器 寻址符号为: `+` 如果我们从外部程序剪切或者拷贝了文本, 那么在 Vim 里可以使用 `"+p` 来进行粘贴 (插入模式下可使用 `<C-r>+`); 相反, 如果我们在 Vim 里使用 `"+` 对文本进行拉取(yank)或删除, 那么文本就会存到 *系统剪贴板* 里, 外部程序就可以直接粘贴使用 *X11* 窗口系统有第二种称为主剪贴板. 是鼠标最近的选择的文本, 我们可以使用鼠标中键来粘贴 首要剪贴板的寻址符号: `*` Keystrokes | Buffer Contents ---- | ---- `"+` | X11 剪贴板, 用于 剪切, 复制和粘贴 `"*` | X11 主剪贴板, 选中的文本被拷贝, 用鼠标中键粘贴 {: .table-multi-text} `Windows`{: .red} 和 `Mac OS X`{: .red} 系统没有 *主剪贴板*, 所以 `"+` 和 `"*` 都表示 *系统剪贴板* 是否支持 *X11剪贴板* 可以使用 `:version` 来查看版本信息 - *+xterm_clipboard* 表示支持 - *-xterm_clipboard* 表示不支持 #### 表达式寄存器(\"=) Vim 寄存器可以简单的被认为是容纳一块文本的容器. 而 表达式寄存器 是个例外, 寻址符号为 `=` 但我们在插入模式或命令模式按下 `<C-r>=`, 然后命令行就会有 `=` 字符提示, 输入一个数字表达式(如:*1+2+3*)并按回车即可计算出结果, 并把结果回填到之前的位置 (见 Tip 16) #### 更多的寄存器 我们可以使用 delete 和 yank 命令显式设置 字母, 匿名和yank 等寄存器来存放内容. 此外, Vim提供了一些寄存器, 其值是隐式设置的. 这里统称为 只读寄存器 Keystrokes | Buffer Contents ---- | ---- `"%` | 当前文件名 `"#` | 候选文件名(缓存列表的候选文件) `".` | 最后插入的文本 `":` | 最后执行的Ex命令 `"/` | 最后的搜索 pattern {: .table-multi-text} 严格的说 `"/` 不是只读的, 因为可以通过 `:let` 进行设置, 不过这里也放到表格里了 **手册**: - *:h quote_quote* 匿名寄存器 - *:h quote0* yank寄存器 - *:h quote_alpha* 字母(a-z)寄存器 - *:h quote_* 黑洞寄存器 - *:h quote+* 剪贴板寄存器 - *:h quotestar* 主剪贴板寄存器 - *:h quote=* 表达式寄存器 - *:h quote.* 最后插入文本寄存器 - *:h quote/* 最后搜索模式寄存器 - *:h registers* 查看所有寄存器列表 ## Tip 62 寄存器替换选中的文本 {: #tip62} > Replace a Visual Selection with a Register 在可视化模式下使用 `p` 命令替换文本的同时, Vim 会把被替换的文本存入匿名寄存器中 Keystrokes | Buffer Contents ---- | ---- `yiw` | <code class="cursor">c</code>ollection = getCollection();<br> process(somethingInTheWay, target); `jww` | collection = getCollection();<br> process(<code class="cursor">s</code>omethingInTheWay, target); `ve` | collection = getCollection();<br> process(<code class="visual">somethingInTheWa<code class="cursor">y</code></code>, target); `p` | collection = getCollection();<br> process(collectio<code class="cursor">n</code>, target); {: .table-multi-text} 这应该是最直观和简洁的方式了, 省去了一个删除的步骤 (多一个选中的步骤, 不过更加直观一点) 上面示例, 再尝试一下按 `u` 撤销替换, 然后 `gv` 重新选中之前被替换的文本, 然后按 `p` 会怎样? 答案是什么都没变! 因为按 `u` 之前, 匿名寄存器已经被覆盖为替换前选中的文本了 (Feature or Bug?) #### 2个词互换 Keystrokes | Buffer Contents ---- | ---- {start} | <code class="cursor">I</code> like chips and fish. `fc` | I like <code class="cursor">c</code>hips and fish. `de` | I like <code class="cursor">&nbsp;</code>and fish. `mm` | I like <code class="cursor">&nbsp;</code>and fish. `ww` | I like and <code class="cursor">f</code>ish. `ve` | I like chips and <code class="visual">fis<code class="cursor">h</code></code>. `p` | I like and chip<code class="cursor">s</code>. <code class="highlighter-rouge">`m</code> | I like <code class="cursor">&nbsp;</code>and chips. `P` | I like fis<code class="cursor">h</code> and chips. {: .table-multi-text} - `de` - 删除 *chips* (并存入匿名寄存器中) - `mm` - 在光标处做了一个 *m* 标记, 方便一会儿跳转回来的 - `ve` - 选中 *fish* - `p` - 把选中的 *fish* 替换为匿名寄存器中的 *chips* 文本 (被替换的 *fish* 存入匿名寄存器中) - <code class="highlighter-rouge">`m</code> - 跳转回之前标记 *m* 的位置 (Tip 54) - `P` - 把匿名寄存器中的 *fish* 粘贴到光标位置之前 (大写的p) **手册**: - *:h v_p* ## Tip 63 寄存器粘贴 {: #tip63} > Paste from a Register 常规模式下的 放置(put) 命令的行为不一样, 这个取决于插入的文本是 面向字符(character-wise) 或 面向行(line-wise) 的 粘贴行为差异: 2种模式 | `p` | `P` | 存入 匿名寄存器 ---- | ---- | ---- | ---- 面向字符 | 光标之后 | 光标之前 | `x` `diw` `das` `yw` 等 面向行 | 光标下一行 | 光标上一行 | `dd` `yy` `dap` 等 {: .table-multi-text} 寄存器列表中带有 <span class="red">^J</span> 字符的就是换行, 试了一下出现在末尾会被认定为: 面向行 <pre> :reg --- Registers --- "" #### 字符模式粘贴<span class="red">^J</span> "0 粘贴行为差异 "1 #### 字符模式粘贴<span class="red">^J</span> "2 粘贴<span class="red">^J</span> 粘贴 </pre> #### 面向字符区域粘贴 假如我们的 匿名寄存器 已经存在了 *collection* 文本, 那么对比一下什么时候用: `p` 和 `P` 呢? 对比一下: <code class="highlighter-rouge">process<code class="cursor">(</code>, target);</code> 和 <code class="highlighter-rouge">process(<code class="cursor">,</code> target);</code> 第一种情况明显是 `p`, 后面是 `P`; 实时上错了之后经常按 `puP` 和 `Pup` 来形成肌肉记忆后就好了 上面小节介绍了直接替换选中的文本的粘贴[Tip 60](#tip60), 这里介绍插入模式下如何粘贴: - `<C-r>"` - 插入 匿名寄存器 里的内容 - `<C-r>0` - 插入 yank寄存器 里的内容 Keystrokes | Buffer Contents ---- | ---- `yiw` | <code class="cursor">c</code>ollection = getCollection();<br> process(somethingInTheWay, target); `jww` | collection = getCollection();<br> process(<code class="cursor">s</code>omethingInTheWay, target); `ciw<C-r>0<Esc>` | collection = getCollection();<br> process(collectio<code class="cursor">n</code>, target); {: .table-multi-text} 使用 `ciw` 命令可以带来额外的好处: 可以使用 `.` 命令进行当前词的替换! #### 面向行区域粘贴 前面我们说了, 面向行的 `p` 和 `P` 命令会将 匿名寄存器 的内容放置到 下一行/上一行 这里值得注意的是, Vim 还提供 `gp` 和 `gP` 命令. 不同的点在于:光标最后停留的位置是在粘贴内容之前和之后 演示文本: ```html <table> <tr> <td>Symbol</td> <td>Name</td> </tr> </table> ``` ![gP命令粘贴效果](/assets/archives/20181103122707_vim-gP-command.png) 多行文本复制时, `gP` 命令非常好用; 虽然 `P` 和 `gP` 命令都能达到预期的复制文本效果, 不过最后光标停留的位置还是 `gP` 更实用一点(修改更方便点) `p` 和 `P` 命令都能在多行文本进行粘贴时处理得很好. 不过在处理 面向字符区域文本时, `<C-r>{register}` 会更加直观一点 **手册**: - *:h p* - *:h linewise-register* ## Tip 64 系统剪贴板交互 {: #tip64} > Interact with the System Clipboard 除了 Vim 的内置粘贴(put)命令, 我们有时可以使用系统粘贴命令. 但是, 在终端内运行 Vim 时, 使用此功能偶尔会产生意外结果. 我们可以在使用系统粘贴命令之前启用 'paste' 选项来避免这些问题. #### 准备 禁用插件启动 vim <pre> $ vim -u NONE -N </pre> 启用自动缩进功能 <pre> :set autoindent </pre> 然后把下面这段 ruby 代码拷贝到系统剪贴板里: <pre> [1,2,3,4,5,6,7,8,9,10].each do |n| if n%5==0 puts "fizz" else puts n end end </pre> #### 系统粘贴快捷键 *Mac* 系统默认的粘贴快捷键为 <kbd>Cmd</kbd>+<kbd>v</kbd> 而 *Linux* 和 *Windows* 就没那么舒适了, 其系统默认的粘贴快捷键为 <kbd>Ctrl</kbd>+<kbd>v</kbd> 这个和 *Vim* 里的快捷键正好冲突: - 常规模式下 - `<C-v>` 是启用可视化模式 (Tip 21) - 插入模式下 - `<C-v>` 是插入特殊字符 (Tip 17) 一些 *Linux* 终端提供了另一套粘贴的快捷键: <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>v</kbd> 或 <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>v</kbd> 别忘了还有我们的剪贴板寄存器 `"+{regiester}` 和 `"*{register}` #### 插入模式下粘贴 当我们切换到 *插入模式* 下, 然后使用系统快捷键进行粘贴时, 我们会得到如下结果:(缩进可能太一样) <pre> [1,2,3,4,5,6,7,8,9,10].each do |n| if n%5==0 puts "fizz" else puts n end end </pre> 这个缩进并没有达到我们的预期. 当我们在插入模式下使用系统粘贴快捷键时, *Vim* 会以手动输入的字符来对待. 当 *autoindent* 选项开启后, 每次创建新行时, *Vim* 会保留同级别的缩进. 而剪贴板中每行前面的空格都被添加到了自动缩进的前面, 导致每一行都向右越走越远 这个时候, 我们可以手动开启 `:set paste` 选项, 告知 *Vim* 我们要使用系统的粘贴命令. 插入模式下, 在进行系统粘贴, 就会得到我们想要的结果了. 而当我们使用完之后, 可以关闭 `:set paste!` 选项, 回到之前的状态. 在插入模式下如何切换 *paste* 选项呢? 我们可以设置 *pastetoggle* 选项 `:set pastetoggle=<f5>` 这样就可以同时在 *插入模式* 和 *常规模式* 下快速切换了. 如果觉得实用, 可以加到 *~/.vimrc* 文件里 #### 用系统剪贴板寄存器粘贴 如果 *Vim* 支持 *+clipboard* 功能的话, 可以直接使用剪贴板寄存器, 而不用来回的切换 *paste* 选项了. [Tip 61 剪贴板寄存器](#%E5%89%AA%E8%B4%B4%E6%9D%BF%E5%AF%84%E5%AD%98%E5%99%A8-%E5%92%8C-) 使用 `"+p` 或 `"*p` 的系统剪贴板粘贴 (会忽略 *paste* 和 *autoindent* 选项) **手册**: - *:h 'paste'* - *:h 'pastetoggle'*
xu3352/xu3352.github.io
_posts/2018-11-01-practical-vim-skills-chapter-10.md
Markdown
mit
19,962
28.630769
163
0.628393
false
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Department extends Model { protected $fillable =['name']; }
mucyomiller/workloads
app/Department.php
PHP
mit
134
12.4
39
0.723881
false
# (c) Liviu Balan <liv_romania@yahoo.com> # http://www.liviubalan.com/ # # For the full copyright and license information, please view the LICENSE # file that was distributed with this source code. LIV_TUT_META_URL='http://www.liviubalan.com/git-log-command'
liviubalan/liviubalan.com-vagrant-ubuntu
provision-shell/tutorials/000/069/meta.sh
Shell
mit
260
36.142857
73
0.75
false
module Fae module BaseModelConcern extend ActiveSupport::Concern require 'csv' attr_accessor :filter included do include Fae::Trackable if Fae.track_changes include Fae::Sortable end def fae_display_field # override this method in your model end def fae_nested_parent # override this method in your model end def fae_tracker_parent # override this method in your model end def fae_nested_foreign_key return if fae_nested_parent.blank? "#{fae_nested_parent}_id" end def fae_form_manager_model_name return 'Fae::StaticPage' if self.class.name.constantize.superclass.name == 'Fae::StaticPage' self.class.name end def fae_form_manager_model_id self.id end module ClassMethods def for_fae_index order(order_method) end def order_method klass = name.constantize if klass.column_names.include? 'position' return :position elsif klass.column_names.include? 'name' return :name elsif klass.column_names.include? 'title' return :title else raise "No order_method found, please define for_fae_index as a #{name} class method to set a custom scope." end end def filter(params) # override this method in your model for_fae_index end def fae_search(query) all.to_a.keep_if { |i| i.fae_display_field.present? && i.fae_display_field.to_s.downcase.include?(query.downcase) } end def to_csv CSV.generate do |csv| csv << column_names all.each do |item| csv << item.attributes.values_at(*column_names) end end end def fae_translate(*attributes) attributes.each do |attribute| define_method attribute.to_s do self.send "#{attribute}_#{I18n.locale}" end define_singleton_method "find_by_#{attribute}" do |val| self.send("find_by_#{attribute}_#{I18n.locale}", val) end end end def has_fae_image(image_name_symbol) has_one image_name_symbol, -> { where(attached_as: image_name_symbol.to_s) }, as: :imageable, class_name: '::Fae::Image', dependent: :destroy accepts_nested_attributes_for image_name_symbol, allow_destroy: true end def has_fae_file(file_name_symbol) has_one file_name_symbol, -> { where(attached_as: file_name_symbol.to_s) }, as: :fileable, class_name: '::Fae::File', dependent: :destroy accepts_nested_attributes_for file_name_symbol, allow_destroy: true end end private def fae_bust_navigation_caches Fae::Role.all.each do |role| Rails.cache.delete("fae_navigation_#{role.id}") end end end end
wearefine/fae
app/models/concerns/fae/base_model_concern.rb
Ruby
mit
2,926
24.666667
123
0.597403
false
#pragma once #include <boost/uuid/random_generator.hpp> #include <boost/uuid/uuid_io.hpp> #include "util/util.h" #include "util/stl_ext.h" namespace collections { extern boost::optional<std::vector<std::string>> wrap_string(const char *csource, int charsPerLine); class tes_string : public reflection::class_meta_mixin_t<tes_string> { public: tes_string() { metaInfo._className = "JString"; metaInfo.comment = "various string utility methods"; } static object_base * wrap(tes_context& ctx, const char* source, SInt32 charsPerLine) { auto strings = wrap_string(source, charsPerLine); if (!strings) { return nullptr; } return &array::objectWithInitializer([&](array &obj) { for (auto& str : *strings) { obj.u_container().emplace_back(std::move(str)); } }, ctx); } REGISTERF2(wrap, "sourceText charactersPerLine=60", "Breaks source text onto set of lines of almost equal size.\n\ Returns JArray object containing lines.\n\ Accepts ASCII and UTF-8 encoded strings only"); static UInt32 decodeFormStringToFormId(const char* form_string) { return util::to_integral(decodeFormStringToForm(form_string)); } static FormId decodeFormStringToForm(const char* form_string) { return boost::get_optional_value_or(forms::from_string(form_string), FormId::Zero); } static skse::string_ref encodeFormToString(FormId id) { return skse::string_ref{ boost::get_optional_value_or(forms::to_string(id), "") }; } static skse::string_ref encodeFormIdToString(UInt32 id) { return encodeFormToString( util::to_enum<FormId>(id) ); } REGISTERF2_STATELESS(decodeFormStringToFormId, "formString", "FormId|Form <-> \"__formData|<pluginName>|<lowFormId>\"-string converisons"); REGISTERF2_STATELESS(decodeFormStringToForm, "formString", ""); REGISTERF2_STATELESS(encodeFormToString, "value", ""); REGISTERF2_STATELESS(encodeFormIdToString, "formId", ""); private: static boost::uuids::random_generator generateUUID_gen; static util::spinlock generateUUID_lock; public: static std::string generateUUID() { return boost::uuids::to_string( util::perform_while_locked(generateUUID_lock, [](){ return generateUUID_gen(); }) ); } REGISTERF2_STATELESS(generateUUID, "", "Generates random uuid-string like 2e80251a-ab22-4ad8-928c-2d1c9561270e"); }; boost::uuids::random_generator tes_string::generateUUID_gen; util::spinlock tes_string::generateUUID_lock; TES_META_INFO(tes_string); TEST(tes_string, wrap) { tes_context_standalone ctx; auto testData = json_deserializer::json_from_file( util::relative_to_dll_path("test_data/tes_string/string_wrap.json").generic_string().c_str() ); EXPECT_TRUE( json_is_array(testData.get()) ); auto testWrap = [&](const char *string, int linesCount, int charsPerLine) { auto obj = tes_string::wrap(ctx, string, charsPerLine); if (linesCount == -1) { EXPECT_NIL(obj); } else { EXPECT_NOT_NIL(obj); EXPECT_TRUE(obj->s_count() >= linesCount); } }; size_t index = 0; json_t *value = nullptr; json_array_foreach(testData.get(), index, value) { int charsPerLine = -1; json_t *jtext = nullptr; int linesCountMinimum = -1; json_error_t error; int succeed = json_unpack_ex(value, &error, 0, "{s:i, s:o, s:i}", "charsPerLine", &charsPerLine, "text", &jtext, "linesCountMinimum", &linesCountMinimum); EXPECT_TRUE(succeed == 0); testWrap(json_string_value(jtext), linesCountMinimum, charsPerLine); } } TEST(tes_string, generateUUID) { auto uidString = tes_string::generateUUID(); EXPECT_FALSE(uidString.empty()); auto uidString2 = tes_string::generateUUID(); EXPECT_NE(uidString, uidString2); } }
SilverIce/JContainers
JContainers/src/api_3/tes_string.h
C
mit
4,327
34.170732
147
0.599306
false
package biz.golek.whattodofordinner.business.contract.presenters; import biz.golek.whattodofordinner.business.contract.entities.Dinner; /** * Created by Bartosz Gołek on 2016-02-10. */ public interface EditDinnerPresenter { void Show(Dinner dinner); }
bartoszgolek/whattodofordinner
app/src/main/java/biz/golek/whattodofordinner/business/contract/presenters/EditDinnerPresenter.java
Java
mit
261
25
69
0.784615
false
<!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/html; charset=UTF-8" /> <title>Robber frog factsheet on ARKive - Eleutherodactylus simulans</title> <link rel="canonical" href="http://www.arkive.org/robber-frog/eleutherodactylus-simulans/" /> <link rel="stylesheet" type="text/css" media="screen,print" href="/rcss/factsheet.css" /> <link rel="icon" href="/favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /> </head> <body> <!-- onload="window.print()">--> <div id="container"> <div id="header"><a href="/"><img src="/rimg/factsheet/header_left.png" alt="" border="0" /><img src="/rimg/factsheet/header_logo.png" alt="" border="0" /><img src="/rimg/factsheet/header_right.png" alt="" border="0" /></a></div> <div id="content"> <h1>Robber frog (<i>Eleutherodactylus simulans</i>)</h1> <img alt="" src="/media/17/17E2922C-0DA3-4615-B79D-A1E11785D359/Presentation.Large/Eleutherodactylus-simulans.jpg"/> <table cellspacing="0" cellpadding="0" id="factList"> <tbody> <tr class="kingdom"><th align="left">Kingdom</th><td align="left">Animalia</td></tr> <tr class="phylum"><th align="left">Phylum</th><td align="left">Chordata</td></tr> <tr class="class"><th align="left">Class</th><td align="left">Amphibia</td></tr> <tr class="order"><th align="left">Order</th><td align="left">Anura</td></tr> <tr class="family"><th align="left">Family</th><td align="left">Eleutherodactylidae</td></tr> <tr class="genus"><th align="left">Genus</th><td align="left"><em>Eleutherodactylus (1)</em></td></tr> </tbody> </table> <h2><img src="/rimg/factsheet/Status.png" class="heading" /></h2><p class="Status"><p>Classified as Endangered (EN) on the IUCN Red List (1).</p></p><h2><img src="/rimg/factsheet/Description.png" class="heading" /></h2><p class="Description"><p>Information on <em>Eleutherodactylus simulans </em>is currently being researched and written and will appear here shortly.</p></p><h2><img src="/rimg/factsheet/Authentication.png" class="heading" /></h2><p class="AuthenticatioModel"><p>This information is awaiting authentication by a species expert, and will be updated as soon as possible. If you are able to help please contact: <br/><a href="mailto:arkive@wildscreen.org.uk">arkive@wildscreen.org.uk</a></p></p><h2><img src="/rimg/factsheet/References.png" class="heading" /></h2> <ol id="references"> <li id="ref1"> <a id="reference_1" name="reference_1"></a> IUCN Red List (July, 2010) <br/><a href="http://www.iucnredlist.org" target="_blank">http://www.iucnredlist.org</a></li> </ol> </div> </div> </body> </html>
andrewedstrom/cs638project
raw_data/arkive-endangered-html/eleutherodactylus-simulans.html
HTML
mit
2,866
68.902439
787
0.666085
false
\chapter{Constanten} \section{Globale Constanten} Dikwijls gebruik je bepaalde waarden doorheen je hele programma. Zo zou je, in een programma dat veel berekeningen met circels moet doen, vaak het getal pi nodig hebben. Dat getal kan je elke keer opnieuw berekenen, maar dat is niet zo'n goed idee omdat de uitkomst van je berekening steeds hetzelfde is. Je zou daarom een globale variabele pi kunnen declareren: \begin{code} int pi = 3.1415926; \end{code} Nu kan je overal de waarde van pi gebruiken in je berekeningen. Maar stel je voor dat je ergens vergist: \begin{code} int value = 1; // ... more code ... if(pi = value) { // do something } \end{code} Je wil in de bovenstaande code controleren of `value' gelijk is aan pi. Maar je schrijft een enkele in plaats van een dubbele =. Zo'n fout is snel gemaakt en valt op het eerste zicht niet zo op. Het gevolg is dat na de uitvoering van die code het getal pi niet meer gelijk is aan zijn oorspronkelijke waarde. Al je berekeningen zullen dus fout zijn! Om dit soort fouten te voorkomen voorzien de meeste programmeertalen in een mogelijkheid om een variabele `constant' te maken. Dat wil zeggen dat ze na hun declaratie niet meer aangepast mogen worden. Om dat duidelijk te maken bestaat de afspraak om die variabelen steeds met hoofdletters te schrijven. Hoe schrijf je zo'n variabele? In C++ doe je dat door voor het type \verb|const| toe te voegen. Esenthel geeft je daarnaast de mogelijkheid om dat af te korten tot \verb|C|. (Net zoals je \verb|this| kan afkorten tot \verb|T|). Je schrijft dus: \begin{code} C PI = 3.1415926; \end{code} Dit heeft twee voordelen: \begin{enumerate} \item Je kan de waarde van PI niet langer per vergissing aanpassen. \item Als je het getal PI in je code wil aanpassen, dan moet je dat maar op \'e\'en plaats doen. \textsl{(In het geval van PI is dat wel h\'e\'el onwaarschijnlijk, maar bij andere constanten kan dat dikwijls wel. Als je bijvoorbeeld een constante variabele ATTACK\_RANGE gebruikt, dan kan je misschien later beslissen dat die toch iets te groot is.)} \end{enumerate} \begin{note} Omdat PI een nummer is dat alle programmeurs vaak nodig hebben, bestaat er al een constante PI in Esenthel. Niet enkel dat, er zijn ook al varianten voorzien, zoals PI\_2 (de helft van PI) en PI2 (twee maal PI). \end{note} \begin{exercise} Maak een programma met de volgende constanten: playerColor, playerSize, enemyColor en enemySize. De player is een rechthoek en de enemies zijn cirkels. \textit{(Het is een erg abstract spel.)} Toon een speler en verschillende enemies op het scherm. \end{exercise} \section{Const Argumenten} Er bestaat nog een andere situatie waarin je constanten gebruikt. Bekijk even de volgende functie: \begin{code} float calculateDistance(Vec2 & pos1, Vec2 & pos2); \end{code} Je kan deze functie gebruiken om de afstand tussen twee posities te berekenen. Je leerde al in hoofdstuk \ref{chapter:references} dat we de argumenten van die functie by reference doorgeven om het programma sneller te maken. Dat heeft \'e\'en nadeel. Je zou in principe de waarden van pos1 en pos2 kunnen aanpassen in de functie. En dan zijn ook de originele waarden in je programma aangepast. De naam van de functie laat in dit geval vermoeden dat dat niet zal gebeuren. Maar je weet nooit zeker of de progammeur van die functie zich niet vergist heeft. Als er dus ergens iets fout gaat met de variabele \verb|pos1| in je programma, dan kan je niet anders dan ook de code van de functie \eeFunc{calculateDistance} nakijken. En misschien gebruikt die functie intern nog een andere functie die eveneens pass by reference argumenten heeft. Dat zou betekenen dat je echt alle onderliggende functies moet nakijken om uit te sluiten dat de fout daar zit. Zoiets is in grote projecten niet werkbaar. En daarom kunnen we ook een functie argument constant maken, net zoals een globale variabele. Je schrijft de functie dan zo: \begin{code} float calculateDistance(C Vec2 & pos1, C Vec2 & pos2); \end{code} De gevolgen zijn dat: \begin{enumerate} \item je tijdens het maken van de functie een foutmelding krijgt wanneer je toch zou proberen pos1 of pos2 aan te passen; \item de gebruiker van je functie zeker weet dat de waarde nooit aangepast kan zijn in de functie; \item je bijna zeker weet dat een functie waar de argumenten \textbf{niet} constant zijn, die argumenten zal aanpassen. \end{enumerate} Vanaf nu volg je dus de regel dat je alle functie argumenten als een const reference doorgeeft, tenzij het de bedoeling is dat de aangepaste waarde in het oorspronkelijke programma terecht komt. Wat is nu een goede reden om een argument aan te passen? Kijk even naar de Esenthel functie: \begin{code} void Clamp(Vec2 & value, C Vec2 & min, C Vec2 & max); \end{code} Het is de bedoeling dat deze functie de eerste waarde binnen het gevraagde minimum en maximum houdt. Je gebruikt de functie op deze manier: \begin{code} Vec2 pos = Ms.pos(); Clamp(pos, Vec2(-0.4,-0.4), Vec2(0.4,0.4)); pos.draw(RED); \end{code} Het tweede en derde argument zijn constant. De functie \eeFunc{Clamp} kan dus niet het minimum of maximum aanpassen. Maar \eeFunc{pos} willen we natuurlijk net wel aanpassen. Hier gebruik je dus geen const reference. \begin{exercise} \begin{itemize} \item Doorzoek de Engine code naar meer functies die geen const reference gebruiken. Probeer te verklaren waarom ze dat niet doen. \item Schrijf een functie `ClampToScreen' die een gegeven coordinaat aanpast wanneer het buiten het scherm zou vallen. Test de functie met een eenvoudig programma. Gebruik je een const reference of niet? \item Schrijf een functie met een string argument die die string op het scherm plaatst. Je maakt een versie met een const reference en een versie met een gewone reference. Test beide versies met bestaande strings en met string literals. Waarom werkt de niet-const versie enkel met strings en niet met literals? \end{itemize} \end{exercise}
yvanvds/EsenthelCourse
course/nl/basics/constants.tex
TeX
mit
5,959
63.782609
554
0.779493
false
package main import ( "github.com/weynsee/go-phrase/cli" "log" "os" ) func main() { args := os.Args[1:] c := cli.NewCLI("1.0.0", args) exitStatus, err := c.Run() if err != nil { log.Println(err) } os.Exit(exitStatus) }
weynsee/go-phrase
main.go
GO
mit
234
11.315789
35
0.594017
false
version https://git-lfs.github.com/spec/v1 oid sha256:2e4cfe75feb71c39771595f8dea4f59e216650e0454f3f56a2a5b38a062b94cf size 1360
yogeshsaroya/new-cdnjs
ajax/libs/openlayers/2.12/lib/OpenLayers/Format/XLS/v1_1_0.js
JavaScript
mit
129
42
75
0.883721
false
require 'spec_helper' describe ZK::Threadpool do before do @threadpool = ZK::Threadpool.new end after do @threadpool.shutdown end describe :new do it %[should be running] do @threadpool.should be_running end it %[should use the default size] do @threadpool.size.should == ZK::Threadpool.default_size end end describe :defer do it %[should run the given block on a thread in the threadpool] do @th = nil @threadpool.defer { @th = Thread.current } wait_until(2) { @th } @th.should_not == Thread.current end it %[should barf if the argument is not callable] do bad_obj = flexmock(:not_callable) bad_obj.should_not respond_to(:call) lambda { @threadpool.defer(bad_obj) }.should raise_error(ArgumentError) end it %[should not barf if the threadpool is not running] do @threadpool.shutdown lambda { @threadpool.defer { "hai!" } }.should_not raise_error end end describe :on_exception do it %[should register a callback that will be called if an exception is raised on the threadpool] do @ary = [] @threadpool.on_exception { |exc| @ary << exc } @threadpool.defer { raise "ZOMG!" } wait_while(2) { @ary.empty? } @ary.length.should == 1 e = @ary.shift e.should be_kind_of(RuntimeError) e.message.should == 'ZOMG!' end end describe :shutdown do it %[should set running to false] do @threadpool.shutdown @threadpool.should_not be_running end end describe :start! do it %[should be able to start a threadpool that had previously been shutdown (reuse)] do @threadpool.shutdown @threadpool.start!.should be_true @threadpool.should be_running @rval = nil @threadpool.defer do @rval = true end wait_until(2) { @rval } @rval.should be_true end end describe :on_threadpool? do it %[should return true if we're currently executing on one of the threadpool threads] do @a = [] @threadpool.defer { @a << @threadpool.on_threadpool? } wait_while(2) { @a.empty? } @a.should_not be_empty @a.first.should be_true end end describe :pause_before_fork_in_parent do it %[should stop all running threads] do @threadpool.should be_running @threadpool.should be_alive @threadpool.pause_before_fork_in_parent @threadpool.should_not be_alive end it %[should raise InvalidStateError if already paused] do @threadpool.pause_before_fork_in_parent lambda { @threadpool.pause_before_fork_in_parent }.should raise_error(ZK::Exceptions::InvalidStateError) end end describe :resume_after_fork_in_parent do before do @threadpool.pause_before_fork_in_parent end it %[should start all threads running again] do @threadpool.resume_after_fork_in_parent @threadpool.should be_alive end it %[should raise InvalidStateError if not in paused state] do @threadpool.shutdown lambda { @threadpool.resume_after_fork_in_parent }.should raise_error(ZK::Exceptions::InvalidStateError) end it %[should run callbacks deferred while paused] do calls = [] num = 5 latch = Latch.new(num) num.times do |n| @threadpool.defer do calls << n latch.release end end @threadpool.resume_after_fork_in_parent latch.await(2) calls.should_not be_empty end end end
rickypai/zk
spec/zk/threadpool_spec.rb
Ruby
mit
3,568
22.168831
110
0.63509
false
<div class="col-xs-7"> <div class="box"> <div class="box-header"> <h3 class="box-title">Order Table</h3> <div class="box-tools"> <div class="input-group input-group-sm" style="width: 150px;"> <input type="search" class="light-table-filter form-control pull-right" data-table="order-table" placeholder="Search"> <div class="input-group-btn"> <button type="submit" class="btn btn-default"><i class="fa fa-search"></i></button> </div> </div> </div> </div> <!-- /.box-header --> <div class="box-body table-responsive no-padding"> <table class="table table-hover order-table"> <thead> <tr> <th>Product</th> <th>Customer</th> <th>Date</th> <th>Status</th> <th>Price</th> <th>Phone</th> <th></th> </tr> </thead> <tbody> <?php foreach ($order as $item): if($item->status == 0){ ?> <tr> <td><?php echo $item->product; ?></td> <td><?php echo $item->username; ?></td> <td><?php echo $item->datereceive; ?></td> <td><?php if($item->status == 0){ echo "Watting access..."; } else{ echo "Ok"; } ?></td> <td><?php echo $item->price ?></td> <td><?php echo $item->phone ?></td> <td> <?php echo Html::anchor('admin/order/'.$item->id, 'Click to Complete', array('onclick' => "return confirm('Are you sure?')")); ?> </td> </tr> <?php } endforeach; ?> </tbody> </table> </div> <!-- /.box-body --> </div> <!-- /.box --> </div> <div class="col-xs-1"></div> <div class="col-xs-4"> <div class="box"> <div class="box-header"> <h3 class="box-title">Order Sussess</h3> </div> <!-- /.box-header --> <div class="box-body table-responsive no-padding"> <?php if ($order): ?> <table class="table table-hover"> <tbody><tr> <th>Product</th> <th>Date</th> <th>Status</th> <th>Customer</th> </tr> <?php foreach ($order as $item): if($item->status == 1){ ?> <tr> <td><?php echo $item->product; ?></td> <td><?php echo $item->datereceive; ?></td> <td><?php echo $item->username; ?></td> <td><?php if($item->status == 0){ echo "Watting access..."; } else{ echo "Ok"; } ?></td> </tr> <?php } ?> <?php endforeach; ?> </tbody> </table> <?php endif; ?> </div> <!-- /.box-body --> </div> </div>
NamBker/web_laptop
fuel/app/views/admin/order/index.php
PHP
mit
2,776
25.701923
139
0.443804
false
// // UIFont+PongMadness.h // Pong Madness // // Created by Ludovic Landry on 2/27/13. // Copyright (c) 2013 MirageTeam. All rights reserved. // #import <UIKit/UIKit.h> @interface UIFont (PongMadness) + (UIFont *)brothersBoldFontOfSize:(CGFloat)pointSize; + (void)printAvailableFonts; @end
little-green-men/Pong-Madness-iOS
Pong Madness/UIFont+PongMadness.h
C
mit
298
17.625
55
0.711409
false
// // #ifndef _Rectangle_h #define _Rectangle_h // Includes #include <Engine/Core/Shape.h> #include <Engine/Core/Vector.h> //============================================================================== namespace ptc { class Ray; class Rectangle : public Shape { public: Rectangle(); Rectangle( const Vector& center, const Vector& right, const Vector& normal, float width, //< in right dir float height ); //< in cross( right, normal ) dir void setIsDoubleSided( bool new_value ); bool getIsDoubleSided() const; IntersectDescr intersect( const Ray& ray ) override; private: Vector center_; Vector right_; Vector up_; Vector normal_; float width_; float height_; bool is_double_sided_; }; } // namespace ptc #endif // Include guard
asplendidday/ptchan
Engine/Shapes/Rectangle.h
C
mit
785
15.354167
80
0.603822
false
package multiwallet import ( "errors" "strings" "time" eth "github.com/OpenBazaar/go-ethwallet/wallet" "github.com/OpenBazaar/multiwallet/bitcoin" "github.com/OpenBazaar/multiwallet/bitcoincash" "github.com/OpenBazaar/multiwallet/client/blockbook" "github.com/OpenBazaar/multiwallet/config" "github.com/OpenBazaar/multiwallet/litecoin" "github.com/OpenBazaar/multiwallet/service" "github.com/OpenBazaar/multiwallet/zcash" "github.com/OpenBazaar/wallet-interface" "github.com/btcsuite/btcd/chaincfg" "github.com/op/go-logging" "github.com/tyler-smith/go-bip39" ) var log = logging.MustGetLogger("multiwallet") var UnsuppertedCoinError = errors.New("multiwallet does not contain an implementation for the given coin") type MultiWallet map[wallet.CoinType]wallet.Wallet func NewMultiWallet(cfg *config.Config) (MultiWallet, error) { log.SetBackend(logging.AddModuleLevel(cfg.Logger)) service.Log = log blockbook.Log = log if cfg.Mnemonic == "" { ent, err := bip39.NewEntropy(128) if err != nil { return nil, err } mnemonic, err := bip39.NewMnemonic(ent) if err != nil { return nil, err } cfg.Mnemonic = mnemonic cfg.CreationDate = time.Now() } multiwallet := make(MultiWallet) var err error for _, coin := range cfg.Coins { var w wallet.Wallet switch coin.CoinType { case wallet.Bitcoin: w, err = bitcoin.NewBitcoinWallet(coin, cfg.Mnemonic, cfg.Params, cfg.Proxy, cfg.Cache, cfg.DisableExchangeRates) if err != nil { return nil, err } if cfg.Params.Name == chaincfg.MainNetParams.Name { multiwallet[wallet.Bitcoin] = w } else { multiwallet[wallet.TestnetBitcoin] = w } case wallet.BitcoinCash: w, err = bitcoincash.NewBitcoinCashWallet(coin, cfg.Mnemonic, cfg.Params, cfg.Proxy, cfg.Cache, cfg.DisableExchangeRates) if err != nil { return nil, err } if cfg.Params.Name == chaincfg.MainNetParams.Name { multiwallet[wallet.BitcoinCash] = w } else { multiwallet[wallet.TestnetBitcoinCash] = w } case wallet.Zcash: w, err = zcash.NewZCashWallet(coin, cfg.Mnemonic, cfg.Params, cfg.Proxy, cfg.Cache, cfg.DisableExchangeRates) if err != nil { return nil, err } if cfg.Params.Name == chaincfg.MainNetParams.Name { multiwallet[wallet.Zcash] = w } else { multiwallet[wallet.TestnetZcash] = w } case wallet.Litecoin: w, err = litecoin.NewLitecoinWallet(coin, cfg.Mnemonic, cfg.Params, cfg.Proxy, cfg.Cache, cfg.DisableExchangeRates) if err != nil { return nil, err } if cfg.Params.Name == chaincfg.MainNetParams.Name { multiwallet[wallet.Litecoin] = w } else { multiwallet[wallet.TestnetLitecoin] = w } case wallet.Ethereum: w, err = eth.NewEthereumWallet(coin, cfg.Params, cfg.Mnemonic, cfg.Proxy) if err != nil { return nil, err } if cfg.Params.Name == chaincfg.MainNetParams.Name { multiwallet[wallet.Ethereum] = w } else { multiwallet[wallet.TestnetEthereum] = w } } } return multiwallet, nil } func (w *MultiWallet) Start() { for _, wallet := range *w { wallet.Start() } } func (w *MultiWallet) Close() { for _, wallet := range *w { wallet.Close() } } func (w *MultiWallet) WalletForCurrencyCode(currencyCode string) (wallet.Wallet, error) { for _, wl := range *w { if strings.EqualFold(wl.CurrencyCode(), currencyCode) || strings.EqualFold(wl.CurrencyCode(), "T"+currencyCode) { return wl, nil } } return nil, UnsuppertedCoinError }
OpenBazaar/openbazaar-go
vendor/github.com/OpenBazaar/multiwallet/multiwallet.go
GO
mit
3,469
26.752
124
0.701643
false
// Copyright (c) 2012 Pieter Wuille // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "addrman.h" #include "hash.h" #include "serialize.h" #include "streams.h" int CAddrInfo::GetTriedBucket(const uint256& nKey) const { uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetKey()).GetHash().GetCheapHash(); uint64_t hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << (hash1 % ADDRMAN_TRIED_BUCKETS_PER_GROUP)).GetHash().GetCheapHash(); return hash2 % ADDRMAN_TRIED_BUCKET_COUNT; } int CAddrInfo::GetNewBucket(const uint256& nKey, const CNetAddr& src) const { std::vector<unsigned char> vchSourceGroupKey = src.GetGroup(); uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << vchSourceGroupKey).GetHash().GetCheapHash(); uint64_t hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << vchSourceGroupKey << (hash1 % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP)).GetHash().GetCheapHash(); return hash2 % ADDRMAN_NEW_BUCKET_COUNT; } int CAddrInfo::GetBucketPosition(const uint256 &nKey, bool fNew, int nBucket) const { uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << (fNew ? 'N' : 'K') << nBucket << GetKey()).GetHash().GetCheapHash(); return hash1 % ADDRMAN_BUCKET_SIZE; } bool CAddrInfo::IsTerrible(int64_t nNow) const { if (nLastTry && nLastTry >= nNow - 60) // never remove things tried in the last minute return false; if (nTime > nNow + 10 * 60) // came in a flying DeLorean return true; if (nTime == 0 || nNow - nTime > ADDRMAN_HORIZON_DAYS * 24 * 60 * 60) // not seen in recent history return true; if (nLastSuccess == 0 && nAttempts >= ADDRMAN_RETRIES) // tried N times and never a success return true; if (nNow - nLastSuccess > ADDRMAN_MIN_FAIL_DAYS * 24 * 60 * 60 && nAttempts >= ADDRMAN_MAX_FAILURES) // N successive failures in the last week return true; return false; } double CAddrInfo::GetChance(int64_t nNow) const { double fChance = 1.0; int64_t nSinceLastSeen = nNow - nTime; int64_t nSinceLastTry = nNow - nLastTry; if (nSinceLastSeen < 0) nSinceLastSeen = 0; if (nSinceLastTry < 0) nSinceLastTry = 0; // deprioritize very recent attempts away if (nSinceLastTry < 60 * 10) fChance *= 0.01; // deprioritize 66% after each failed attempt, but at most 1/28th to avoid the search taking forever or overly penalizing outages. fChance *= pow(0.66, std::min(nAttempts, 8)); return fChance; } CAddrInfo* CAddrMan::Find(const CNetAddr& addr, int* pnId) { std::map<CNetAddr, int>::iterator it = mapAddr.find(addr); if (it == mapAddr.end()) return NULL; if (pnId) *pnId = (*it).second; std::map<int, CAddrInfo>::iterator it2 = mapInfo.find((*it).second); if (it2 != mapInfo.end()) return &(*it2).second; return NULL; } CAddrInfo* CAddrMan::Create(const CAddress& addr, const CNetAddr& addrSource, int* pnId) { int nId = nIdCount++; mapInfo[nId] = CAddrInfo(addr, addrSource); mapAddr[addr] = nId; mapInfo[nId].nRandomPos = vRandom.size(); vRandom.push_back(nId); if (pnId) *pnId = nId; return &mapInfo[nId]; } void CAddrMan::SwapRandom(unsigned int nRndPos1, unsigned int nRndPos2) { if (nRndPos1 == nRndPos2) return; assert(nRndPos1 < vRandom.size() && nRndPos2 < vRandom.size()); int nId1 = vRandom[nRndPos1]; int nId2 = vRandom[nRndPos2]; assert(mapInfo.count(nId1) == 1); assert(mapInfo.count(nId2) == 1); mapInfo[nId1].nRandomPos = nRndPos2; mapInfo[nId2].nRandomPos = nRndPos1; vRandom[nRndPos1] = nId2; vRandom[nRndPos2] = nId1; } void CAddrMan::Delete(int nId) { assert(mapInfo.count(nId) != 0); CAddrInfo& info = mapInfo[nId]; assert(!info.fInTried); assert(info.nRefCount == 0); SwapRandom(info.nRandomPos, vRandom.size() - 1); vRandom.pop_back(); mapAddr.erase(info); mapInfo.erase(nId); nNew--; } void CAddrMan::ClearNew(int nUBucket, int nUBucketPos) { // if there is an entry in the specified bucket, delete it. if (vvNew[nUBucket][nUBucketPos] != -1) { int nIdDelete = vvNew[nUBucket][nUBucketPos]; CAddrInfo& infoDelete = mapInfo[nIdDelete]; assert(infoDelete.nRefCount > 0); infoDelete.nRefCount--; vvNew[nUBucket][nUBucketPos] = -1; if (infoDelete.nRefCount == 0) { Delete(nIdDelete); } } } void CAddrMan::MakeTried(CAddrInfo& info, int nId) { // remove the entry from all new buckets for (int bucket = 0; bucket < ADDRMAN_NEW_BUCKET_COUNT; bucket++) { int pos = info.GetBucketPosition(nKey, true, bucket); if (vvNew[bucket][pos] == nId) { vvNew[bucket][pos] = -1; info.nRefCount--; } } nNew--; assert(info.nRefCount == 0); // which tried bucket to move the entry to int nKBucket = info.GetTriedBucket(nKey); int nKBucketPos = info.GetBucketPosition(nKey, false, nKBucket); // first make space to add it (the existing tried entry there is moved to new, deleting whatever is there). if (vvTried[nKBucket][nKBucketPos] != -1) { // find an item to evict int nIdEvict = vvTried[nKBucket][nKBucketPos]; assert(mapInfo.count(nIdEvict) == 1); CAddrInfo& infoOld = mapInfo[nIdEvict]; // Remove the to-be-evicted item from the tried set. infoOld.fInTried = false; vvTried[nKBucket][nKBucketPos] = -1; nTried--; // find which new bucket it belongs to int nUBucket = infoOld.GetNewBucket(nKey); int nUBucketPos = infoOld.GetBucketPosition(nKey, true, nUBucket); ClearNew(nUBucket, nUBucketPos); assert(vvNew[nUBucket][nUBucketPos] == -1); // Enter it into the new set again. infoOld.nRefCount = 1; vvNew[nUBucket][nUBucketPos] = nIdEvict; nNew++; } assert(vvTried[nKBucket][nKBucketPos] == -1); vvTried[nKBucket][nKBucketPos] = nId; nTried++; info.fInTried = true; } void CAddrMan::Good_(const CService& addr, int64_t nTime) { int nId; CAddrInfo* pinfo = Find(addr, &nId); // if not found, bail out if (!pinfo) return; CAddrInfo& info = *pinfo; // check whether we are talking about the exact same CService (including same port) if (info != addr) return; // update info info.nLastSuccess = nTime; info.nLastTry = nTime; info.nAttempts = 0; // nTime is not updated here, to avoid leaking information about // currently-connected peers. // if it is already in the tried set, don't do anything else if (info.fInTried) return; // find a bucket it is in now int nRnd = RandomInt(ADDRMAN_NEW_BUCKET_COUNT); int nUBucket = -1; for (unsigned int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) { int nB = (n + nRnd) % ADDRMAN_NEW_BUCKET_COUNT; int nBpos = info.GetBucketPosition(nKey, true, nB); if (vvNew[nB][nBpos] == nId) { nUBucket = nB; break; } } // if no bucket is found, something bad happened; // TODO: maybe re-add the node, but for now, just bail out if (nUBucket == -1) return; LogPrint("addrman", "Moving %s to tried\n", addr.ToString()); // move nId to the tried tables MakeTried(info, nId); } bool CAddrMan::Add_(const CAddress& addr, const CNetAddr& source, int64_t nTimePenalty) { if (!addr.IsRoutable()) return false; bool fNew = false; int nId; CAddrInfo* pinfo = Find(addr, &nId); if (pinfo) { // periodically update nTime bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < 24 * 60 * 60); int64_t nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60); if (addr.nTime && (!pinfo->nTime || pinfo->nTime < addr.nTime - nUpdateInterval - nTimePenalty)) pinfo->nTime = std::max((int64_t)0, addr.nTime - nTimePenalty); // add services pinfo->nServices |= addr.nServices; // do not update if no new information is present if (!addr.nTime || (pinfo->nTime && addr.nTime <= pinfo->nTime)) return false; // do not update if the entry was already in the "tried" table if (pinfo->fInTried) return false; // do not update if the max reference count is reached if (pinfo->nRefCount == ADDRMAN_NEW_BUCKETS_PER_ADDRESS) return false; // stochastic test: previous nRefCount == N: 2^N times harder to increase it int nFactor = 1; for (int n = 0; n < pinfo->nRefCount; n++) nFactor *= 2; if (nFactor > 1 && (RandomInt(nFactor) != 0)) return false; } else { pinfo = Create(addr, source, &nId); pinfo->nTime = std::max((int64_t)0, (int64_t)pinfo->nTime - nTimePenalty); nNew++; fNew = true; } int nUBucket = pinfo->GetNewBucket(nKey, source); int nUBucketPos = pinfo->GetBucketPosition(nKey, true, nUBucket); if (vvNew[nUBucket][nUBucketPos] != nId) { bool fInsert = vvNew[nUBucket][nUBucketPos] == -1; if (!fInsert) { CAddrInfo& infoExisting = mapInfo[vvNew[nUBucket][nUBucketPos]]; if (infoExisting.IsTerrible() || (infoExisting.nRefCount > 1 && pinfo->nRefCount == 0)) { // Overwrite the existing new table entry. fInsert = true; } } if (fInsert) { ClearNew(nUBucket, nUBucketPos); pinfo->nRefCount++; vvNew[nUBucket][nUBucketPos] = nId; } else { if (pinfo->nRefCount == 0) { Delete(nId); } } } return fNew; } void CAddrMan::Attempt_(const CService& addr, int64_t nTime) { CAddrInfo* pinfo = Find(addr); // if not found, bail out if (!pinfo) return; CAddrInfo& info = *pinfo; // check whether we are talking about the exact same CService (including same port) if (info != addr) return; // update info info.nLastTry = nTime; info.nAttempts++; } CAddrInfo CAddrMan::Select_(bool newOnly) { if (size() == 0) return CAddrInfo(); if (newOnly && nNew == 0) return CAddrInfo(); // Use a 50% chance for choosing between tried and new table entries. if (!newOnly && (nTried > 0 && (nNew == 0 || RandomInt(2) == 0))) { // use a tried node double fChanceFactor = 1.0; while (1) { int nKBucket = RandomInt(ADDRMAN_TRIED_BUCKET_COUNT); int nKBucketPos = RandomInt(ADDRMAN_BUCKET_SIZE); while (vvTried[nKBucket][nKBucketPos] == -1) { nKBucket = (nKBucket + insecure_rand()) % ADDRMAN_TRIED_BUCKET_COUNT; nKBucketPos = (nKBucketPos + insecure_rand()) % ADDRMAN_BUCKET_SIZE; } int nId = vvTried[nKBucket][nKBucketPos]; assert(mapInfo.count(nId) == 1); CAddrInfo& info = mapInfo[nId]; if (RandomInt(1 << 30) < fChanceFactor * info.GetChance() * (1 << 30)) return info; fChanceFactor *= 1.2; } } else { // use a new node double fChanceFactor = 1.0; while (1) { int nUBucket = RandomInt(ADDRMAN_NEW_BUCKET_COUNT); int nUBucketPos = RandomInt(ADDRMAN_BUCKET_SIZE); while (vvNew[nUBucket][nUBucketPos] == -1) { nUBucket = (nUBucket + insecure_rand()) % ADDRMAN_NEW_BUCKET_COUNT; nUBucketPos = (nUBucketPos + insecure_rand()) % ADDRMAN_BUCKET_SIZE; } int nId = vvNew[nUBucket][nUBucketPos]; assert(mapInfo.count(nId) == 1); CAddrInfo& info = mapInfo[nId]; if (RandomInt(1 << 30) < fChanceFactor * info.GetChance() * (1 << 30)) return info; fChanceFactor *= 1.2; } } } #ifdef DEBUG_ADDRMAN int CAddrMan::Check_() { std::set<int> setTried; std::map<int, int> mapNew; if (vRandom.size() != nTried + nNew) return -7; for (std::map<int, CAddrInfo>::iterator it = mapInfo.begin(); it != mapInfo.end(); it++) { int n = (*it).first; CAddrInfo& info = (*it).second; if (info.fInTried) { if (!info.nLastSuccess) return -1; if (info.nRefCount) return -2; setTried.insert(n); } else { if (info.nRefCount < 0 || info.nRefCount > ADDRMAN_NEW_BUCKETS_PER_ADDRESS) return -3; if (!info.nRefCount) return -4; mapNew[n] = info.nRefCount; } if (mapAddr[info] != n) return -5; if (info.nRandomPos < 0 || info.nRandomPos >= vRandom.size() || vRandom[info.nRandomPos] != n) return -14; if (info.nLastTry < 0) return -6; if (info.nLastSuccess < 0) return -8; } if (setTried.size() != nTried) return -9; if (mapNew.size() != nNew) return -10; for (int n = 0; n < ADDRMAN_TRIED_BUCKET_COUNT; n++) { for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) { if (vvTried[n][i] != -1) { if (!setTried.count(vvTried[n][i])) return -11; if (mapInfo[vvTried[n][i]].GetTriedBucket(nKey) != n) return -17; if (mapInfo[vvTried[n][i]].GetBucketPosition(nKey, false, n) != i) return -18; setTried.erase(vvTried[n][i]); } } } for (int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) { for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) { if (vvNew[n][i] != -1) { if (!mapNew.count(vvNew[n][i])) return -12; if (mapInfo[vvNew[n][i]].GetBucketPosition(nKey, true, n) != i) return -19; if (--mapNew[vvNew[n][i]] == 0) mapNew.erase(vvNew[n][i]); } } } if (setTried.size()) return -13; if (mapNew.size()) return -15; if (nKey.IsNull()) return -16; return 0; } #endif void CAddrMan::GetAddr_(std::vector<CAddress>& vAddr) { unsigned int nNodes = ADDRMAN_GETADDR_MAX_PCT * vRandom.size() / 100; if (nNodes > ADDRMAN_GETADDR_MAX) nNodes = ADDRMAN_GETADDR_MAX; // gather a list of random nodes, skipping those of low quality for (unsigned int n = 0; n < vRandom.size(); n++) { if (vAddr.size() >= nNodes) break; int nRndPos = RandomInt(vRandom.size() - n) + n; SwapRandom(n, nRndPos); assert(mapInfo.count(vRandom[n]) == 1); const CAddrInfo& ai = mapInfo[vRandom[n]]; if (!ai.IsTerrible()) vAddr.push_back(ai); } } void CAddrMan::Connected_(const CService& addr, int64_t nTime) { CAddrInfo* pinfo = Find(addr); // if not found, bail out if (!pinfo) return; CAddrInfo& info = *pinfo; // check whether we are talking about the exact same CService (including same port) if (info != addr) return; // update info int64_t nUpdateInterval = 20 * 60; if (nTime - info.nTime > nUpdateInterval) info.nTime = nTime; } int CAddrMan::RandomInt(int nMax){ return GetRandInt(nMax); }
BlockchainTechLLC/3dcoin
src/addrman.cpp
C++
mit
15,655
30.312
155
0.57892
false
import asyncio import discord import datetime import pytz from discord.ext import commands from Cogs import FuzzySearch from Cogs import Settings from Cogs import DisplayName from Cogs import Message from Cogs import Nullify class Time: # Init with the bot reference, and a reference to the settings var def __init__(self, bot, settings): self.bot = bot self.settings = settings @commands.command(pass_context=True) async def settz(self, ctx, *, tz : str = None): """Sets your TimeZone - Overrides your UTC offset - and accounts for DST.""" usage = 'Usage: `{}settz [Region/City]`\nYou can get a list of available TimeZones with `{}listtz`'.format(ctx.prefix, ctx.prefix) if not tz: self.settings.setGlobalUserStat(ctx.author, "TimeZone", None) await ctx.channel.send("*{}*, your TimeZone has been removed!".format(DisplayName.name(ctx.author))) return # Let's get the timezone list tz_list = FuzzySearch.search(tz, pytz.all_timezones, None, 3) if not tz_list[0]['Ratio'] == 1: # We didn't find a complete match msg = "I couldn't find that TimeZone!\n\nMaybe you meant one of the following?\n```" for tz in tz_list: msg += tz['Item'] + "\n" msg += '```' await ctx.channel.send(msg) return # We got a time zone self.settings.setGlobalUserStat(ctx.author, "TimeZone", tz_list[0]['Item']) await ctx.channel.send("TimeZone set to *{}!*".format(tz_list[0]['Item'])) @commands.command(pass_context=True) async def listtz(self, ctx, *, tz_search = None): """List all the supported TimeZones in PM.""" if not tz_search: msg = "__Available TimeZones:__\n\n" for tz in pytz.all_timezones: msg += tz + "\n" else: tz_list = FuzzySearch.search(tz_search, pytz.all_timezones) msg = "__Top 3 TimeZone Matches:__\n\n" for tz in tz_list: msg += tz['Item'] + "\n" await Message.say(self.bot, msg, ctx.channel, ctx.author, 1) @commands.command(pass_context=True) async def tz(self, ctx, *, member = None): """See a member's TimeZone.""" # Check if we're suppressing @here and @everyone mentions if self.settings.getServerStat(ctx.message.guild, "SuppressMentions").lower() == "yes": suppress = True else: suppress = False if member == None: member = ctx.message.author if type(member) == str: # Try to get a user first memberName = member member = DisplayName.memberForName(memberName, ctx.message.guild) if not member: msg = 'Couldn\'t find user *{}*.'.format(memberName) # Check for suppress if suppress: msg = Nullify.clean(msg) await ctx.channel.send(msg) return # We got one timezone = self.settings.getGlobalUserStat(member, "TimeZone") if timezone == None: msg = '*{}* hasn\'t set their TimeZone yet - they can do so with the `{}settz [Region/City]` command.'.format(DisplayName.name(member), ctx.prefix) await ctx.channel.send(msg) return msg = '*{}\'s* TimeZone is *{}*'.format(DisplayName.name(member), timezone) await ctx.channel.send(msg) @commands.command(pass_context=True) async def setoffset(self, ctx, *, offset : str = None): """Set your UTC offset.""" if offset == None: self.settings.setGlobalUserStat(ctx.message.author, "UTCOffset", None) msg = '*{}*, your UTC offset has been removed!'.format(DisplayName.name(ctx.message.author)) await ctx.channel.send(msg) return offset = offset.replace('+', '') # Split time string by : and get hour/minute values try: hours, minutes = map(int, offset.split(':')) except Exception: try: hours = int(offset) minutes = 0 except Exception: await ctx.channel.send('Offset has to be in +-H:M!') return off = "{}:{}".format(hours, minutes) self.settings.setGlobalUserStat(ctx.message.author, "UTCOffset", off) msg = '*{}*, your UTC offset has been set to *{}!*'.format(DisplayName.name(ctx.message.author), off) await ctx.channel.send(msg) @commands.command(pass_context=True) async def offset(self, ctx, *, member = None): """See a member's UTC offset.""" # Check if we're suppressing @here and @everyone mentions if self.settings.getServerStat(ctx.message.guild, "SuppressMentions").lower() == "yes": suppress = True else: suppress = False if member == None: member = ctx.message.author if type(member) == str: # Try to get a user first memberName = member member = DisplayName.memberForName(memberName, ctx.message.guild) if not member: msg = 'Couldn\'t find user *{}*.'.format(memberName) # Check for suppress if suppress: msg = Nullify.clean(msg) await ctx.channel.send(msg) return # We got one offset = self.settings.getGlobalUserStat(member, "UTCOffset") if offset == None: msg = '*{}* hasn\'t set their offset yet - they can do so with the `{}setoffset [+-offset]` command.'.format(DisplayName.name(member), ctx.prefix) await ctx.channel.send(msg) return # Split time string by : and get hour/minute values try: hours, minutes = map(int, offset.split(':')) except Exception: try: hours = int(offset) minutes = 0 except Exception: await ctx.channel.send('Offset has to be in +-H:M!') return msg = 'UTC' # Apply offset if hours > 0: # Apply positive offset msg += '+{}'.format(offset) elif hours < 0: # Apply negative offset msg += '{}'.format(offset) msg = '*{}\'s* offset is *{}*'.format(DisplayName.name(member), msg) await ctx.channel.send(msg) @commands.command(pass_context=True) async def time(self, ctx, *, offset : str = None): """Get UTC time +- an offset.""" timezone = None if offset == None: member = ctx.message.author else: # Try to get a user first member = DisplayName.memberForName(offset, ctx.message.guild) if member: # We got one # Check for timezone first offset = self.settings.getGlobalUserStat(member, "TimeZone") if offset == None: offset = self.settings.getGlobalUserStat(member, "UTCOffset") if offset == None: msg = '*{}* hasn\'t set their TimeZone or offset yet - they can do so with the `{}setoffset [+-offset]` or `{}settz [Region/City]` command.\nThe current UTC time is *{}*.'.format(DisplayName.name(member), ctx.prefix, ctx.prefix, datetime.datetime.utcnow().strftime("%I:%M %p")) await ctx.channel.send(msg) return # At this point - we need to determine if we have an offset - or possibly a timezone passed t = self.getTimeFromTZ(offset) if t == None: # We did not get an offset t = self.getTimeFromOffset(offset) if t == None: await ctx.channel.send("I couldn't find that TimeZone or offset!") return if member: msg = '{}; where *{}* is, it\'s currently *{}*'.format(t["zone"], DisplayName.name(member), t["time"]) else: msg = '{} is currently *{}*'.format(t["zone"], t["time"]) # Say message await ctx.channel.send(msg) def getTimeFromOffset(self, offset): offset = offset.replace('+', '') # Split time string by : and get hour/minute values try: hours, minutes = map(int, offset.split(':')) except Exception: try: hours = int(offset) minutes = 0 except Exception: return None # await ctx.channel.send('Offset has to be in +-H:M!') # return msg = 'UTC' # Get the time t = datetime.datetime.utcnow() # Apply offset if hours > 0: # Apply positive offset msg += '+{}'.format(offset) td = datetime.timedelta(hours=hours, minutes=minutes) newTime = t + td elif hours < 0: # Apply negative offset msg += '{}'.format(offset) td = datetime.timedelta(hours=(-1*hours), minutes=(-1*minutes)) newTime = t - td else: # No offset newTime = t return { "zone" : msg, "time" : newTime.strftime("%I:%M %p") } def getTimeFromTZ(self, tz): # Assume sanitized zones - as they're pulled from pytz # Let's get the timezone list tz_list = FuzzySearch.search(tz, pytz.all_timezones, None, 3) if not tz_list[0]['Ratio'] == 1: # We didn't find a complete match return None zone = pytz.timezone(tz_list[0]['Item']) zone_now = datetime.datetime.now(zone) return { "zone" : tz_list[0]['Item'], "time" : zone_now.strftime("%I:%M %p") }
TheMasterGhost/CorpBot
Cogs/Time.py
Python
mit
8,457
30.28626
280
0.637342
false
/* * @param parseObject [ParseObject] * @return [Object] * */ export const convertBrand = (parseObject) => { const ret = {}; const object = parseObject.toJSON(); ret.id = object.objectId; ret.name = object.name; ret.description = object.description; ret.images = (object.images || []).map(image => ({ id: image.objectId, url: image.file.url })); return ret; }; /* * @param parseObject [ParseObject] * @return [Object] * */ export const convertProduct = (parseObject) => { const ret = {}; const object = parseObject.toJSON(); ret.id = object.objectId; ret.brand_id = object.brand.objectId; ret.name = object.name; ret.description = object.description; ret.images = object.images.map(image => ({ id: image.objectId, url: image.file.url })); ret.size = object.size; ret.color = object.color; ret.cost = object.cost; ret.price = object.price; ret.quantity = object.quantity; return ret; };
ihenvyr/react-parse
src/utils.js
JavaScript
mit
934
24.243243
97
0.659529
false
#include <iostream> using namespace std; int main() { int a,b,c,d; int sum=1080; while(cin>>a>>b>>c>>d) { if(a==0&&b==0&&c==0&&d==0) break; if(a>b) { sum=(a-b)*9+sum; } else if(a<b) { sum=((40-b)+a)*9+sum; } if(c>b) { sum=(c-b)*9+sum; } else if(c<b) { sum=((40-b)+c)*9+sum; } if(c>d) { sum=(c-d)*9+sum; } else if(c<d) { sum=((40-d)+c)*9+sum; } cout<<sum<<endl; sum=1080; } return 0; }
w181496/OJ
Zerojudge/c006.cpp
C++
mit
711
14.181818
34
0.28692
false
--- layout: page title: Donald Singh's 31st Birthday date: 2016-05-24 author: Teresa Mcdaniel tags: weekly links, java status: published summary: Nam finibus mollis massa eget venenatis. Maecenas suscipit cursus. banner: images/banner/leisure-01.jpg booking: startDate: 10/08/2018 endDate: 10/13/2018 ctyhocn: TCCHHHX groupCode: DS3B published: true --- Pellentesque lacinia, tellus id ornare luctus, nunc libero pellentesque mi, lobortis tincidunt lectus libero vel tellus. Quisque tincidunt erat eget odio viverra congue. Sed eu ipsum nec tortor aliquet dapibus id id eros. Aliquam non cursus justo. Suspendisse faucibus arcu in sapien ullamcorper, eget sollicitudin quam euismod. Nulla venenatis purus sit amet volutpat volutpat. Sed felis ante, placerat id congue vel, suscipit volutpat enim. Curabitur fermentum scelerisque luctus. Morbi convallis risus vel ornare ullamcorper. Nulla facilisi. Sed malesuada faucibus varius. Nulla scelerisque eros at nisi imperdiet elementum. Vivamus fringilla ligula non pulvinar sollicitudin. Praesent sit amet hendrerit metus. Proin vel tristique erat. Integer neque sem, gravida posuere lacus et, commodo ullamcorper eros. Pellentesque at euismod libero. In hac habitasse platea dictumst. 1 Pellentesque accumsan risus ut nisi convallis rutrum 1 Pellentesque vel eros at nisi tempus vehicula 1 Nam eget tellus eu est mattis iaculis vel quis leo 1 Mauris et nisl non orci consectetur feugiat 1 Donec eget massa ac justo malesuada pellentesque ut egestas tortor. Donec velit urna, lacinia nec laoreet sed, semper a lacus. In fermentum congue turpis vitae faucibus. Nulla semper felis id ultricies cursus. Nulla vel nulla tincidunt, blandit eros ultrices, eleifend risus. Integer maximus neque at magna finibus varius. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus quis velit eu odio sagittis commodo ut sollicitudin dui. Praesent id libero ac eros consectetur faucibus. Fusce mattis id sem vitae ornare. Quisque a ipsum vel elit interdum auctor sit amet ut ante.
KlishGroup/prose-pogs
pogs/T/TCCHHHX/DS3B/index.md
Markdown
mit
2,064
78.384615
575
0.815891
false
--- layout: page title: Spring International Conference date: 2016-05-24 author: Helen Kline tags: weekly links, java status: published summary: Vivamus euismod, ipsum at eleifend porttitor, ligula neque accumsan. banner: images/banner/office-01.jpg booking: startDate: 10/10/2019 endDate: 10/15/2019 ctyhocn: RICMDHX groupCode: SIC published: true --- Donec pulvinar massa vel leo aliquet condimentum. Nullam tempor, erat nec varius posuere, nulla nisi bibendum ligula, nec accumsan sapien massa ac tortor. Fusce eleifend commodo velit sit amet mollis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec pretium, velit in commodo mattis, risus odio convallis massa, in ultricies elit libero ut lectus. Nunc vel malesuada arcu. Mauris molestie justo a magna volutpat, eget auctor metus pellentesque. Vivamus venenatis nibh nec eleifend ullamcorper. Proin efficitur a ex eu bibendum. * In non nibh pulvinar urna elementum scelerisque * Aenean vel nulla eget purus dignissim condimentum vitae sollicitudin arcu * Integer varius lectus a risus ultrices, nec mollis tortor faucibus. Vestibulum ultricies auctor porttitor. Ut aliquam lacus ut rutrum condimentum. Proin finibus placerat dui id suscipit. Proin ligula arcu, egestas eu leo eu, fringilla maximus libero. Proin ut odio tempor, aliquam orci ac, laoreet sapien. In congue ipsum at purus imperdiet, eget ultricies diam congue. Morbi accumsan velit velit, sit amet aliquet magna luctus sed. Aliquam cursus diam mauris, sed condimentum enim ultricies ac. Nulla ut ligula sagittis, vulputate libero ut, placerat massa. Donec eget mauris vel justo ornare euismod nec a ligula. Etiam at dolor posuere, elementum enim eget, lacinia purus. Sed id tellus dui. Curabitur dictum tincidunt massa, vitae pharetra ligula ullamcorper in. Sed sit amet quam dignissim, tempus nibh at, euismod libero. Mauris placerat urna egestas molestie suscipit. Nullam non sem ipsum. Duis sapien risus, consectetur ac justo non, ultricies suscipit libero. Mauris felis felis, ultricies vel finibus eu, rhoncus accumsan erat. Morbi hendrerit eros venenatis tortor varius, nec mattis mauris malesuada. Curabitur a lacus sed dui cursus viverra quis vitae sapien.
KlishGroup/prose-pogs
pogs/R/RICMDHX/SIC/index.md
Markdown
mit
2,238
92.25
572
0.809651
false
--- layout: page title: Webb Basic Financial Party date: 2016-05-24 author: Kenneth Schroeder tags: weekly links, java status: published summary: Aliquam erat volutpat. Pellentesque tincidunt luctus neque, ac. banner: images/banner/leisure-02.jpg booking: startDate: 01/03/2017 endDate: 01/07/2017 ctyhocn: MGMDNHX groupCode: WBFP published: true --- Maecenas semper augue vel velit volutpat, eu tempor mi volutpat. Curabitur sed lobortis justo. Ut diam turpis, efficitur eu est in, malesuada faucibus orci. Suspendisse eget lacinia tellus. In malesuada enim mi, ac convallis mi placerat ac. Nunc laoreet, leo ut vestibulum mollis, nisi leo volutpat lorem, lacinia condimentum tortor nisl vitae ligula. Mauris vitae leo porttitor, porta nunc nec, rutrum nulla. Proin maximus ullamcorper risus, non sodales eros viverra eu. Nam tempus consequat sem, eu porttitor nisl egestas at. In eget efficitur felis. Duis eu vulputate ligula. Phasellus vel augue eget urna imperdiet cursus et sed risus. Integer dignissim imperdiet diam, id feugiat leo. Mauris id leo nunc. Suspendisse potenti. Sed vel dolor diam. Ut eget ornare mauris. Phasellus porta tortor vel sapien dignissim feugiat. Pellentesque vel imperdiet tellus. * Praesent eu nibh vel eros convallis eleifend eget eu tortor * Aenean nec neque eu felis efficitur interdum nec nec arcu. Integer ac eleifend risus, eget finibus erat. Ut sollicitudin pellentesque ipsum id pellentesque. Phasellus condimentum congue porttitor. Vestibulum neque nisl, ultricies at aliquet a, efficitur non felis. Quisque ut rutrum magna. Integer semper pretium nibh, in suscipit tortor ornare vel. Integer egestas feugiat blandit. Sed non consequat magna. Cras scelerisque tristique neque nec hendrerit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Cras gravida ligula non aliquet lacinia. Maecenas eu ipsum sapien. Suspendisse quis ornare tortor. Interdum et malesuada fames ac ante ipsum primis in faucibus. Etiam ac vulputate ipsum. Etiam scelerisque lacinia lacus id pretium. Phasellus ultrices condimentum ex.
KlishGroup/prose-pogs
pogs/M/MGMDNHX/WBFP/index.md
Markdown
mit
2,097
86.375
451
0.810205
false
#ifndef COLLISIONALGORITHMB #define COLLISIONALGORITHMB #include "CollisionAlgorithm.h" class CollisionAlgorithmB : public CollisionAlgorithm { public: CollisionAlgorithmB(); ~CollisionAlgorithmB(); public: Tuple4f computeRayTriangleIntersection(Ray3D *ray, const Tuple3f &p0, const Tuple3f &p1, const Tuple3f &p2); }; #endif
hyperiris/praetoriansmapeditor
source/Math/CollisionAlgorithmB.h
C
mit
366
20.875
112
0.726776
false
/* */ "format cjs"; /*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.1-master-342ee53 */ (function( window, angular, undefined ){ "use strict"; /** * @ngdoc module * @name material.components.toast * @description * Toast */ MdToastDirective['$inject'] = ["$mdToast"]; MdToastProvider['$inject'] = ["$$interimElementProvider"]; angular.module('material.components.toast', [ 'material.core', 'material.components.button' ]) .directive('mdToast', MdToastDirective) .provider('$mdToast', MdToastProvider); /* ngInject */ function MdToastDirective($mdToast) { return { restrict: 'E', link: function postLink(scope, element) { element.addClass('_md'); // private md component indicator for styling // When navigation force destroys an interimElement, then // listen and $destroy() that interim instance... scope.$on('$destroy', function() { $mdToast.destroy(); }); } }; } /** * @ngdoc service * @name $mdToast * @module material.components.toast * * @description * `$mdToast` is a service to build a toast notification on any position * on the screen with an optional duration, and provides a simple promise API. * * The toast will be always positioned at the `bottom`, when the screen size is * between `600px` and `959px` (`sm` breakpoint) * * ## Restrictions on custom toasts * - The toast's template must have an outer `<md-toast>` element. * - For a toast action, use element with class `md-action`. * - Add the class `md-capsule` for curved corners. * * ### Custom Presets * Developers are also able to create their own preset, which can be easily used without repeating * their options each time. * * <hljs lang="js"> * $mdToastProvider.addPreset('testPreset', { * options: function() { * return { * template: * '<md-toast>' + * '<div class="md-toast-content">' + * 'This is a custom preset' + * '</div>' + * '</md-toast>', * controllerAs: 'toast', * bindToController: true * }; * } * }); * </hljs> * * After you created your preset at config phase, you can easily access it. * * <hljs lang="js"> * $mdToast.show( * $mdToast.testPreset() * ); * </hljs> * * ## Parent container notes * * The toast is positioned using absolute positioning relative to its first non-static parent * container. Thus, if the requested parent container uses static positioning, we will temporarily * set its positioning to `relative` while the toast is visible and reset it when the toast is * hidden. * * Because of this, it is usually best to ensure that the parent container has a fixed height and * prevents scrolling by setting the `overflow: hidden;` style. Since the position is based off of * the parent's height, the toast may be mispositioned if you allow the parent to scroll. * * You can, however, have a scrollable element inside of the container; just make sure the * container itself does not scroll. * * <hljs lang="html"> * <div layout-fill id="toast-container"> * <md-content> * I can have lots of content and scroll! * </md-content> * </div> * </hljs> * * @usage * <hljs lang="html"> * <div ng-controller="MyController"> * <md-button ng-click="openToast()"> * Open a Toast! * </md-button> * </div> * </hljs> * * <hljs lang="js"> * var app = angular.module('app', ['ngMaterial']); * app.controller('MyController', function($scope, $mdToast) { * $scope.openToast = function($event) { * $mdToast.show($mdToast.simple().textContent('Hello!')); * // Could also do $mdToast.showSimple('Hello'); * }; * }); * </hljs> */ /** * @ngdoc method * @name $mdToast#showSimple * * @param {string} message The message to display inside the toast * @description * Convenience method which builds and shows a simple toast. * * @returns {promise} A promise that can be resolved with `$mdToast.hide()` or * rejected with `$mdToast.cancel()`. * */ /** * @ngdoc method * @name $mdToast#simple * * @description * Builds a preconfigured toast. * * @returns {obj} a `$mdToastPreset` with the following chainable configuration methods. * * _**Note:** These configuration methods are provided in addition to the methods provided by * the `build()` and `show()` methods below._ * * <table class="md-api-table methods"> * <thead> * <tr> * <th>Method</th> * <th>Description</th> * </tr> * </thead> * <tbody> * <tr> * <td>`.textContent(string)`</td> * <td>Sets the toast content to the specified string</td> * </tr> * <tr> * <td>`.action(string)`</td> * <td> * Adds an action button. <br/> * If clicked, the promise (returned from `show()`) * will resolve with the value `'ok'`; otherwise, it is resolved with `true` after a `hideDelay` * timeout * </td> * </tr> * <tr> * <td>`.highlightAction(boolean)`</td> * <td> * Whether or not the action button will have an additional highlight class.<br/> * By default the `accent` color will be applied to the action button. * </td> * </tr> * <tr> * <td>`.highlightClass(string)`</td> * <td> * If set, the given class will be applied to the highlighted action button.<br/> * This allows you to specify the highlight color easily. Highlight classes are `md-primary`, `md-warn` * and `md-accent` * </td> * </tr> * <tr> * <td>`.capsule(boolean)`</td> * <td>Whether or not to add the `md-capsule` class to the toast to provide rounded corners</td> * </tr> * <tr> * <td>`.theme(string)`</td> * <td>Sets the theme on the toast to the requested theme. Default is `$mdThemingProvider`'s default.</td> * </tr> * <tr> * <td>`.toastClass(string)`</td> * <td>Sets a class on the toast element</td> * </tr> * </tbody> * </table> * */ /** * @ngdoc method * @name $mdToast#updateTextContent * * @description * Updates the content of an existing toast. Useful for updating things like counts, etc. * */ /** * @ngdoc method * @name $mdToast#build * * @description * Creates a custom `$mdToastPreset` that you can configure. * * @returns {obj} a `$mdToastPreset` with the chainable configuration methods for shows' options (see below). */ /** * @ngdoc method * @name $mdToast#show * * @description Shows the toast. * * @param {object} optionsOrPreset Either provide an `$mdToastPreset` returned from `simple()` * and `build()`, or an options object with the following properties: * * - `templateUrl` - `{string=}`: The url of an html template file that will * be used as the content of the toast. Restrictions: the template must * have an outer `md-toast` element. * - `template` - `{string=}`: Same as templateUrl, except this is an actual * template string. * - `autoWrap` - `{boolean=}`: Whether or not to automatically wrap the template content with a * `<div class="md-toast-content">` if one is not provided. Defaults to true. Can be disabled if you provide a * custom toast directive. * - `scope` - `{object=}`: the scope to link the template / controller to. If none is specified, it will create a new child scope. * This scope will be destroyed when the toast is removed unless `preserveScope` is set to true. * - `preserveScope` - `{boolean=}`: whether to preserve the scope when the element is removed. Default is false * - `hideDelay` - `{number=}`: How many milliseconds the toast should stay * active before automatically closing. Set to 0 or false to have the toast stay open until * closed manually. Default: 3000. * - `position` - `{string=}`: Sets the position of the toast. <br/> * Available: any combination of `'bottom'`, `'left'`, `'top'`, `'right'`, `'end'` and `'start'`. * The properties `'end'` and `'start'` are dynamic and can be used for RTL support.<br/> * Default combination: `'bottom left'`. * - `toastClass` - `{string=}`: A class to set on the toast element. * - `controller` - `{string=}`: The controller to associate with this toast. * The controller will be injected the local `$mdToast.hide( )`, which is a function * used to hide the toast. * - `locals` - `{string=}`: An object containing key/value pairs. The keys will * be used as names of values to inject into the controller. For example, * `locals: {three: 3}` would inject `three` into the controller with the value * of 3. * - `bindToController` - `bool`: bind the locals to the controller, instead of passing them in. * - `resolve` - `{object=}`: Similar to locals, except it takes promises as values * and the toast will not open until the promises resolve. * - `controllerAs` - `{string=}`: An alias to assign the controller to on the scope. * - `parent` - `{element=}`: The element to append the toast to. Defaults to appending * to the root element of the application. * * @returns {promise} A promise that can be resolved with `$mdToast.hide()` or * rejected with `$mdToast.cancel()`. `$mdToast.hide()` will resolve either with a Boolean * value == 'true' or the value passed as an argument to `$mdToast.hide()`. * And `$mdToast.cancel()` will resolve the promise with a Boolean value == 'false' */ /** * @ngdoc method * @name $mdToast#hide * * @description * Hide an existing toast and resolve the promise returned from `$mdToast.show()`. * * @param {*=} response An argument for the resolved promise. * * @returns {promise} a promise that is called when the existing element is removed from the DOM. * The promise is resolved with either a Boolean value == 'true' or the value passed as the * argument to `.hide()`. * */ /** * @ngdoc method * @name $mdToast#cancel * * @description * `DEPRECATED` - The promise returned from opening a toast is used only to notify about the closing of the toast. * As such, there isn't any reason to also allow that promise to be rejected, * since it's not clear what the difference between resolve and reject would be. * * Hide the existing toast and reject the promise returned from * `$mdToast.show()`. * * @param {*=} response An argument for the rejected promise. * * @returns {promise} a promise that is called when the existing element is removed from the DOM * The promise is resolved with a Boolean value == 'false'. * */ function MdToastProvider($$interimElementProvider) { // Differentiate promise resolves: hide timeout (value == true) and hide action clicks (value == ok). toastDefaultOptions['$inject'] = ["$animate", "$mdToast", "$mdUtil", "$mdMedia"]; var ACTION_RESOLVE = 'ok'; var activeToastContent; var $mdToast = $$interimElementProvider('$mdToast') .setDefaults({ methods: ['position', 'hideDelay', 'capsule', 'parent', 'position', 'toastClass'], options: toastDefaultOptions }) .addPreset('simple', { argOption: 'textContent', methods: ['textContent', 'content', 'action', 'highlightAction', 'highlightClass', 'theme', 'parent' ], options: /* ngInject */ ["$mdToast", "$mdTheming", function($mdToast, $mdTheming) { return { template: '<md-toast md-theme="{{ toast.theme }}" ng-class="{\'md-capsule\': toast.capsule}">' + ' <div class="md-toast-content">' + ' <span class="md-toast-text" role="alert" aria-relevant="all" aria-atomic="true">' + ' {{ toast.content }}' + ' </span>' + ' <md-button class="md-action" ng-if="toast.action" ng-click="toast.resolve()" ' + ' ng-class="highlightClasses">' + ' {{ toast.action }}' + ' </md-button>' + ' </div>' + '</md-toast>', controller: /* ngInject */ ["$scope", function mdToastCtrl($scope) { var self = this; if (self.highlightAction) { $scope.highlightClasses = [ 'md-highlight', self.highlightClass ] } $scope.$watch(function() { return activeToastContent; }, function() { self.content = activeToastContent; }); this.resolve = function() { $mdToast.hide( ACTION_RESOLVE ); }; }], theme: $mdTheming.defaultTheme(), controllerAs: 'toast', bindToController: true }; }] }) .addMethod('updateTextContent', updateTextContent) .addMethod('updateContent', updateTextContent); function updateTextContent(newContent) { activeToastContent = newContent; } return $mdToast; /* ngInject */ function toastDefaultOptions($animate, $mdToast, $mdUtil, $mdMedia) { var SWIPE_EVENTS = '$md.swipeleft $md.swiperight $md.swipeup $md.swipedown'; return { onShow: onShow, onRemove: onRemove, toastClass: '', position: 'bottom left', themable: true, hideDelay: 3000, autoWrap: true, transformTemplate: function(template, options) { var shouldAddWrapper = options.autoWrap && template && !/md-toast-content/g.test(template); if (shouldAddWrapper) { // Root element of template will be <md-toast>. We need to wrap all of its content inside of // of <div class="md-toast-content">. All templates provided here should be static, developer-controlled // content (meaning we're not attempting to guard against XSS). var templateRoot = document.createElement('md-template'); templateRoot.innerHTML = template; // Iterate through all root children, to detect possible md-toast directives. for (var i = 0; i < templateRoot.children.length; i++) { if (templateRoot.children[i].nodeName === 'MD-TOAST') { var wrapper = angular.element('<div class="md-toast-content">'); // Wrap the children of the `md-toast` directive in jqLite, to be able to append multiple // nodes with the same execution. wrapper.append(angular.element(templateRoot.children[i].childNodes)); // Append the new wrapped element to the `md-toast` directive. templateRoot.children[i].appendChild(wrapper[0]); } } // We have to return the innerHTMl, because we do not want to have the `md-template` element to be // the root element of our interimElement. return templateRoot.innerHTML; } return template || ''; } }; function onShow(scope, element, options) { activeToastContent = options.textContent || options.content; // support deprecated #content method var isSmScreen = !$mdMedia('gt-sm'); element = $mdUtil.extractElementByName(element, 'md-toast', true); options.element = element; options.onSwipe = function(ev, gesture) { //Add the relevant swipe class to the element so it can animate correctly var swipe = ev.type.replace('$md.',''); var direction = swipe.replace('swipe', ''); // If the swipe direction is down/up but the toast came from top/bottom don't fade away // Unless the screen is small, then the toast always on bottom if ((direction === 'down' && options.position.indexOf('top') != -1 && !isSmScreen) || (direction === 'up' && (options.position.indexOf('bottom') != -1 || isSmScreen))) { return; } if ((direction === 'left' || direction === 'right') && isSmScreen) { return; } element.addClass('md-' + swipe); $mdUtil.nextTick($mdToast.cancel); }; options.openClass = toastOpenClass(options.position); element.addClass(options.toastClass); // 'top left' -> 'md-top md-left' options.parent.addClass(options.openClass); // static is the default position if ($mdUtil.hasComputedStyle(options.parent, 'position', 'static')) { options.parent.css('position', 'relative'); } element.on(SWIPE_EVENTS, options.onSwipe); element.addClass(isSmScreen ? 'md-bottom' : options.position.split(' ').map(function(pos) { return 'md-' + pos; }).join(' ')); if (options.parent) options.parent.addClass('md-toast-animating'); return $animate.enter(element, options.parent).then(function() { if (options.parent) options.parent.removeClass('md-toast-animating'); }); } function onRemove(scope, element, options) { element.off(SWIPE_EVENTS, options.onSwipe); if (options.parent) options.parent.addClass('md-toast-animating'); if (options.openClass) options.parent.removeClass(options.openClass); return ((options.$destroy == true) ? element.remove() : $animate.leave(element)) .then(function () { if (options.parent) options.parent.removeClass('md-toast-animating'); if ($mdUtil.hasComputedStyle(options.parent, 'position', 'static')) { options.parent.css('position', ''); } }); } function toastOpenClass(position) { // For mobile, always open full-width on bottom if (!$mdMedia('gt-xs')) { return 'md-toast-open-bottom'; } return 'md-toast-open-' + (position.indexOf('top') > -1 ? 'top' : 'bottom'); } } } })(window, window.angular);
andream91/fusion-form
app/jspm_packages/github/angular/bower-material@master/modules/js/toast/toast.js
JavaScript
mit
18,003
35.593496
134
0.609398
false
<?php namespace Dvsa\Mot\Frontend\SecurityCardModule\CardOrder\Controller; use Core\Controller\AbstractDvsaActionController; use Dvsa\Mot\Frontend\AuthenticationModule\Model\Identity; use Dvsa\Mot\Frontend\SecurityCardModule\CardOrder\Service\OrderNewSecurityCardSessionService; use DvsaCommon\Constants\FeatureToggle; use DvsaFeature\FeatureToggles; use Zend\Http\Response; use Zend\View\Model\ViewModel; class CardOrderConfirmationController extends AbstractDvsaActionController { /** @var OrderNewSecurityCardSessionService $session */ protected $session; /** @var Identity $identity */ private $identity; /** @var FeatureToggles */ private $featureToggles; public function __construct( OrderNewSecurityCardSessionService $securityCardSessionService, Identity $identity, FeatureToggles $featureToggles ) { $this->session = $securityCardSessionService; $this->identity = $identity; $this->featureToggles = $featureToggles; } /** * @return ViewModel */ public function indexAction(): ViewModel { $userId = $this->params()->fromRoute('userId', $this->identity->getUserId()); if (false === $this->checkValidSession()) { $this->redirectToStart($userId); } if ($this->featureToggles->isEnabled(FeatureToggle::TWO_FA_GRACE_PERIOD) && $this->identity->isAuthenticatedWithSecurityQAndAs()) { $this->identity->setAuthenticatedWith2FA(true); } if (!$this->identity->isAuthenticatedWithSecurityQAndAs()) { $this->buildBreadcrumbs(); } // As this is the last page of the journey clear the session $this->session->clearByGuid($userId); return (new ViewModel())->setTemplate('2fa/card-order/confirmation'); } /** * If there is no valid session, we should go to the journey start. * * @return bool */ protected function checkValidSession(): bool { $values = $this->session->toArray(); return !(is_array($values) && count($values) === 0); } /** * @param int $userId * * @return Response */ protected function redirectToStart($userId): Response { return $this->redirect()->toRoute('security-card-order/new', ['userId' => $userId]); } protected function buildBreadcrumbs() { $this->getBreadcrumbBuilder() ->simple('Your profile', 'newProfile') ->simple('Order a security card') ->build(); } }
dvsa/mot
mot-web-frontend/module/SecurityCardModule/src/CardOrder/Controller/CardOrderConfirmationController.php
PHP
mit
2,570
28.54023
139
0.645525
false
/* SaveFileController * * Version 1.0 * * November 13, 2017 * * Copyright (c) 2017 Cup Of Java. All rights reserved. */ package com.cmput301f17t11.cupofjava.Controllers; import android.content.Context; import com.cmput301f17t11.cupofjava.Models.Habit; import com.cmput301f17t11.cupofjava.Models.HabitEvent; import com.cmput301f17t11.cupofjava.Models.HabitList; import com.cmput301f17t11.cupofjava.Models.User; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.lang.reflect.Type; import java.util.ArrayList; /** * Implements the file to save data to. * * @version 1.0 */ public class SaveFileController { private ArrayList<User> allUsers; //private String username; private String saveFile = "test_save_file4.sav"; public SaveFileController(){ this.allUsers = new ArrayList<User>(); } /** * Loads data from file. * * @param context instance of Context */ private void loadFromFile(Context context){ try{ FileInputStream ifStream = context.openFileInput(saveFile); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ifStream)); Gson gson = new Gson(); Type userArrayListType = new TypeToken<ArrayList<User>>(){}.getType(); this.allUsers = gson.fromJson(bufferedReader, userArrayListType); ifStream.close(); } //create a new array list if a file does not already exist catch (FileNotFoundException e){ this.allUsers = new ArrayList<User>(); saveToFile(context); } catch (IOException e){ throw new RuntimeException(); } } /** * Saves current ArrayList contents in file. * * @param context instance of Context */ private void saveToFile(Context context){ try{ FileOutputStream ofStream = context.openFileOutput(saveFile, Context.MODE_PRIVATE); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(ofStream)); Gson gson = new Gson(); gson.toJson(this.allUsers, bufferedWriter); bufferedWriter.flush(); ofStream.close(); } catch (FileNotFoundException e){ //shouldn't really happen, since a file not found would create a new file. throw new RuntimeException("Laws of nature defied!"); } catch (IOException e){ throw new RuntimeException(); } } /** * Adds new user and saves to file. * * @param context instance of Context * @param user instance of User * @see User */ public void addNewUser(Context context, User user){ loadFromFile(context); this.allUsers.add(user); saveToFile(context); } /** * Deletes all user from file. * * @param context instance of Context */ public void deleteAllUsers(Context context){ this.allUsers = new ArrayList<>(); saveToFile(context); } /** * Gets user index. * * @param context instance of Context * @param username string username * @return integer user index if username matches, -1 otherwise */ public int getUserIndex(Context context, String username){ loadFromFile(context); for (int i = 0; i < this.allUsers.size(); i++){ if (this.allUsers.get(i).getUsername().equals(username)){ return i; } } return -1; } /** * Gets HabitList instance. * * @param context instance of Context * @param userIndex integer user index * @return HabitList * @see HabitList */ public HabitList getHabitList(Context context, int userIndex){ loadFromFile(context); return this.allUsers.get(userIndex).getHabitList(); } /** * Gets ArrayList of type Habit. * * @param context instance of Context * @param userIndex integer user index * @return list */ public ArrayList<Habit> getHabitListAsArray(Context context, int userIndex){ loadFromFile(context); ArrayList<Habit> list = this.allUsers.get(userIndex).getHabitListAsArray(); return list; } /** * Adds a habit to a particular user's habit list. * * @param context instance of Context * @param userIndex integer user index * @param habit instance of Habit * @see Habit */ public void addHabit(Context context, int userIndex, Habit habit){ loadFromFile(context); this.allUsers.get(userIndex).getHabitList().addHabit(habit); saveToFile(context); } /** * Gets habit from a particular user's habit list. * * @param context instance of Context * @param userIndex integer user index * @param habitIndex integer index of habit * @return instance of Habit * @see Habit */ public Habit getHabit(Context context, int userIndex, int habitIndex){ loadFromFile(context); return this.allUsers.get(userIndex).getHabitListAsArray().get(habitIndex); } /** * Deletes habit from a certain user's habit list. * * @param context instance of Context * @param userIndex integer user index * @param habitIndex integer index of habit */ public void deleteHabit(Context context, int userIndex, int habitIndex){ loadFromFile(context); this.allUsers.get(userIndex).getHabitListAsArray().remove(habitIndex); saveToFile(context); } /** * Adds habit event to a particular user's habit event list. * * @param context instance of Context * @param userIndex integer user index * @param habitIndex integer index of habit * @param habitEvent instance of HabitEvent * @see HabitEvent */ public void addHabitEvent(Context context, int userIndex, int habitIndex, HabitEvent habitEvent){ loadFromFile(context); this.allUsers.get(userIndex).getHabitList().getHabit(habitIndex).addHabitEvent(habitEvent); saveToFile(context); } /** * Removes a habit event from a particular user's habit event list. * * @param context instance of Context * @param userIndex integer user index * @param habitIndex integer index of habit * @param habitEventIndex integer index of habit event */ public void removeHabitEvent(Context context, int userIndex, int habitIndex, int habitEventIndex){ loadFromFile(context); this.allUsers.get(userIndex).getHabitList().getHabit(habitIndex) .getHabitEventHistory().getHabitEvents().remove(habitEventIndex); saveToFile(context); } /** * For use in timeline view. * * @param context instance of Context * @param userIndex integer user index * @return ArrayList of HabitEvent type * @see HabitEvent */ public ArrayList<HabitEvent> getAllHabitEvents(Context context, int userIndex){ loadFromFile(context); ArrayList<HabitEvent> habitEvents = new ArrayList<>(); User user = this.allUsers.get(userIndex); ArrayList<Habit> habitList = user.getHabitListAsArray(); Habit currentHabit; ArrayList<HabitEvent> currentHabitEvents; for (int i = 0; i < habitList.size(); i++){ currentHabit = habitList.get(i); currentHabitEvents = currentHabit.getHabitEventHistory().getHabitEvents(); for (int j = 0; j < currentHabitEvents.size() ; j++){ habitEvents.add(user.getHabitListAsArray().get(i) .getHabitEventHistory().getHabitEvents().get(j)); } } return habitEvents; } }
CMPUT301F17T11/CupOfJava
app/src/main/java/com/cmput301f17t11/cupofjava/Controllers/SaveFileController.java
Java
mit
8,104
30.533074
102
0.640548
false
import unittest from katas.beta.what_color_is_your_name import string_color class StringColorTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(string_color('Jack'), '79CAE5') def test_equal_2(self): self.assertEqual(string_color('Joshua'), '6A10D6') def test_equal_3(self): self.assertEqual(string_color('Joshua Smith'), '8F00FB') def test_equal_4(self): self.assertEqual(string_color('Hayden Smith'), '7E00EE') def test_equal_5(self): self.assertEqual(string_color('Mathew Smith'), '8B00F1') def test_is_none_1(self): self.assertIsNone(string_color('a'))
the-zebulan/CodeWars
tests/beta_tests/test_what_color_is_your_name.py
Python
mit
656
27.521739
64
0.666159
false
<?php namespace BoomCMS\Settings; use BoomCMS\Support\Facades\Settings; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Lang; abstract class Manager { public static function options() { $options = []; foreach (Config::get('boomcms.settingsManagerOptions') as $name => $type) { $langPrefix = "boomcms::settings-manager.$name."; $options[] = [ 'name' => $name, 'label' => Lang::get("{$langPrefix}_label"), 'type' => $type, 'value' => Settings::get($name), 'info' => Lang::has("{$langPrefix}_info") ? Lang::get("{$langPrefix}_info") : '', ]; } usort($options, function ($a, $b) { return ($a['label'] < $b['label']) ? -1 : 1; }); return $options; } }
boomcms/boom-core
src/BoomCMS/Settings/Manager.php
PHP
mit
907
24.914286
83
0.484013
false
package endpoints.algebra.circe import io.circe.{Decoder => CirceDecoder, Encoder => CirceEncoder} /** * Combines both an [[io.circe.Encoder]] and a [[io.circe.Decoder]] into a single type class. * * You don’t need to define instances by yourself as they can be derived from an existing pair * of an [[io.circe.Encoder]] and a [[io.circe.Decoder]]. * * @see https://github.com/travisbrown/circe/issues/301 */ trait CirceCodec[A] { def encoder: CirceEncoder[A] def decoder: CirceDecoder[A] } object CirceCodec { @inline def apply[A](implicit codec: CirceCodec[A]): CirceCodec[A] = codec implicit def fromEncoderAndDecoder[A](implicit enc: CirceEncoder[A], dec: CirceDecoder[A]): CirceCodec[A] = new CirceCodec[A] { val decoder = dec val encoder = enc } }
Krever/endpoints
algebras/algebra-circe/src/main/scala/endpoints/algebra/circe/CirceCodec.scala
Scala
mit
805
26.689655
109
0.689913
false
# go-miner # Data Mining Algorithms in GoLang. ## Installation $ go get github.com/ozzie80/go-miner ## Algorithms ### k-means Description From [Wikipedia](https://en.wikipedia.org/wiki/K-means_clustering): > k-means clustering aims to partition n observations into k clusters in which each observation belongs to the cluster with the nearest mean, serving as a prototype of the cluster. This results in a partitioning of the data space into Voronoi cells. The k-means implementation of go-miner uses the [k-means++](https://en.wikipedia.org/wiki/K-means%2B%2B "k-means++") algorithm for choosing the initial cluster centroids. The implementation provides internal quality indexes, [Dunn Index](https://en.wikipedia.org/wiki/Dunn_index) and [Davies-Bouldin Index](https://en.wikipedia.org/wiki/Davies%E2%80%93Bouldin_index), for evaluating clustering results. Usage Example // Create points or read from a .csv file points := []dt.Vector{{1.0, 2.0, 3.0}, {5.1, 6.2, 7.3}, {2.0, 3.5, 5.0}} // Specify Parameters: K, Points, MaxIter (optional) params := kmeans.Params{2, points, math.MaxInt64} // Run k-means clusters, err := kmeans.Run(params) // Get quality index score index := kmeans.DunnIndex{} // DaviesBouldinIndex{} score := index.GetScore(clusters) To Do - Concurrent version - Cuda/GPU version ### To Be Added - Apriori - *K*NN - Naive Bayes - PageRank - SVM - ... ## License go-miner is MIT License.
ozzie80/go-miner
README.md
Markdown
mit
1,453
29.93617
403
0.717825
false
namespace UCloudSDK.Models { /// <summary> /// 获取流量信息 /// <para> /// http://docs.ucloud.cn/api/ucdn/get_ucdn_traffic.html /// </para> /// </summary> public partial class GetUcdnTrafficRequest { /// <summary> /// 默认Action名称 /// </summary> private string _action = "GetUcdnTraffic"; /// <summary> /// API名称 /// <para> /// GetUcdnTraffic /// </para> /// </summary> public string Action { get { return _action; } set { _action = value; } } /// <summary> /// None /// </summary> public string 不需要提供参数 { get; set; } } }
icyflash/ucloud-csharp-sdk
UCloudSDK/Models/UCDN/GetUcdnTrafficRequest.cs
C#
mit
808
21.647059
64
0.415584
false
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Progress extends CI_Controller { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome * - or - * http://example.com/index.php/welcome/index * - or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore will * map to /index.php/welcome/<method_name> * @see http://codeigniter.com/user_guide/general/urls.html */ function __construct() { parent::__construct(); date_default_timezone_set("Asia/Jakarta"); $this->load->model('M_progress'); if (empty($this->session->userdata('session'))) { redirect('login'); } } public function index() { $result['data'] = $this->M_progress->getAll(); $this->load->view('backend/header'); $this->load->view('backend/navbar'); $this->load->view('backend/sidenav'); $this->load->view('backend/list_progress',$result); $this->load->view('backend/footer'); } public function tambah() { $this->load->view('backend/header'); $this->load->view('backend/navbar'); $this->load->view('backend/sidenav'); $this->load->view('backend/add_progress'); $this->load->view('backend/footer'); } public function add() { $tanggal1 = substr($this->input->post('tanggal1'), 6,4)."-".substr($this->input->post('tanggal1'), 0,2)."-".substr($this->input->post('tanggal1'), 3,2); if (empty($this->input->post('tanggal2')) || empty($this->input->post('jam2'))) { $tanggal2 = substr($this->input->post('tanggal1'), 6,4)."-".substr($this->input->post('tanggal1'), 0,2)."-".substr($this->input->post('tanggal1'), 3,2); }else{ $tanggal2 = substr($this->input->post('tanggal2'), 6,4)."-".substr($this->input->post('tanggal2'), 0,2)."-".substr($this->input->post('tanggal2'), 3,2); } //die(); switch ($this->input->post('deputi')) { case 'asdep1': $created_by = 2; $url_back ='asdep1'; break; case 'asdep2': $created_by = 3; $url_back ='asdep2'; break; case 'asdep3': $created_by = 4; $url_back ='asdep3'; break; case 'asdep4': $created_by = 5; $url_back ='asdep4'; break; default: # code... break; } $dokumentasi1 = $this->uploadImage($_FILES['foto1'],'foto1'); $dokumentasi2 = $this->uploadImage($_FILES['foto2'],'foto2'); $data = array('narasiKebijakan'=>$this->input->post('narasiKebijakan'),'uraian'=>$this->input->post('uraian'), 'tanggal1'=>$tanggal1,'tanggal2'=>$tanggal2,'lokasi'=>$this->input->post('lokasi'),'hasil'=>$this->input->post('hasil'), 'tindak_ljt'=>$this->input->post('tindak_ljt'),'arahan'=>$this->input->post('arahan'),'masalah'=>$this->input->post('masalah'), 'dokumentasi1'=>$dokumentasi1,'dokumentasi2'=>$dokumentasi2,'created_by'=>$created_by, 'updated_by'=>$this->session->userdata('session')[0]->no); //print_r($data);die(); $this->M_progress->insert($data); redirect('Beranda/view/'.$url_back); } public function uploadImage($image,$name) { //print_r($image);die(); if ($image) { $file_name = 'file_'.time(); $config['upload_path'] = './assets/images/uploads/'; $config['allowed_types'] = 'jpg|png|JPG|PNG|JPEG|jpeg'; $config['max_size'] = 20480; $config['max_width'] = 5120; $config['max_height'] = 3840; $config['file_name'] = $file_name; $this->upload->initialize($config); if ($this->upload->do_upload($name)) { $img = $this->upload->data(); return $img['file_name']; }else{ return ""; //echo $this->upload->display_errors('<p>', '</p>'); } //redirect('Foto'); } } public function config() { $result['data'] = $this->M_progress->getAll(); $this->load->view('backend/header'); $this->load->view('backend/navbar'); $this->load->view('backend/sidenav'); $this->load->view('backend/list_progress',$result); $this->load->view('backend/footer'); } public function update($value) { $result = $this->M_progress->getId($value); $doc1 = $_FILES['foto1']; $doc2 = $_FILES['foto2']; $tanggal1 = substr($this->input->post('tanggal1'), 6,4)."-".substr($this->input->post('tanggal1'), 0,2)."-".substr($this->input->post('tanggal1'), 3,2); if (empty($this->input->post('tanggal2')) || empty($this->input->post('jam2'))) { $tanggal2 = substr($this->input->post('tanggal1'), 6,4)."-".substr($this->input->post('tanggal1'), 0,2)."-".substr($this->input->post('tanggal1'), 3,2); }else{ $tanggal2 = substr($this->input->post('tanggal2'), 6,4)."-".substr($this->input->post('tanggal2'), 0,2)."-".substr($this->input->post('tanggal2'), 3,2); } if ($doc1['size'] != 0) { $dokumentasi1 = $this->uploadImage($_FILES['foto1'],'foto1'); }else{ $dokumentasi1 = $result[0]->dokumentasi1; } if ($doc2['size'] != 0) { $dokumentasi2 = $this->uploadImage($_FILES['foto2'],'foto2'); }else{ $dokumentasi2 = $result[0]->dokumentasi2; } $data = array('narasiKebijakan'=>$this->input->post('narasiKebijakan'),'uraian'=>$this->input->post('uraian'),'tanggal1'=>$tanggal1,'tanggal2'=>$tanggal2,'lokasi'=>$this->input->post('lokasi'),'hasil'=>$this->input->post('hasil'),'arahan'=>$this->input->post('arahan'),'tindak_ljt'=>$this->input->post('tindak_ljt'),'masalah'=>$this->input->post('masalah'),'dokumentasi1'=>$dokumentasi1,'dokumentasi2'=>$dokumentasi2,'updated_by'=>$this->session->userdata('session')[0]->no,'updated_at'=>date("Y-m-d H:i:s")); //print_r($data);die(); $this->M_progress->updateId($data,$value); $data = $this->M_progress->getId($value); redirect('Beranda/view/'.$data[0]->role); } public function delete($value) { $this->M_progress->deleteId($value); $data = $this->M_kebijakan->getId($value); redirect('Beranda/view/'.$data[0]->role); } public function edit($value) { $result['data'] = $this->M_progress->getId($value); $this->load->view('backend/header'); $this->load->view('backend/navbar'); $this->load->view('backend/sidenav'); $this->load->view('backend/edit_progress',$result); $this->load->view('backend/footer'); } }
primasalama/simoniks2
application/controllers/Progress.php
PHP
mit
6,302
37.901235
511
0.605046
false
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Andersc.CodeLib.Tester.Helpers { public class Book { public string Title { get; set; } public string Publisher { get; set; } public int Year { get; set; } } }
anderscui/cslib
Andersc.CodeLib.Test/Helpers/Book.cs
C#
mit
295
19.928571
45
0.648464
false
import test from 'ava'; import { spawn } from 'child_process'; test.cb('app should boot without exiting', (t) => { const cli = spawn('node', [ './cli' ]); cli.stderr.on('data', (param) => { console.log(param.toString()); }); cli.on('close', (code) => { t.fail(`app failed to boot ${code}`); }); setTimeout(() => { t.pass(); t.end(); cli.kill(); }, 500); });
thomasmeadows/citibank-van
test/cli/boot.js
JavaScript
mit
396
18.8
51
0.525253
false
--- layout: post title: Mughal Empire categories: - Learning --- [Mughal Empire](http://en.wikipedia.org/wiki/Mughal_Empire) (1526 – 1857) rulers... - 1526-1530 [Babur ](http://en.wikipedia.org/wiki/Babur) - 1530–1539 and after restoration 1555–1556 [Humayun ](http://en.wikipedia.org/wiki/Humayun) - 1556–1605 [Akbar ](http://en.wikipedia.org/wiki/Akbar) - 1605–1627 [Jahangir ](http://en.wikipedia.org/wiki/Jahangir) - 1628–1658 [Shah Jahan ](http://en.wikipedia.org/wiki/Shah_Jahan) - 1659–1707   [Aurangzeb ](http://en.wikipedia.org/wiki/Aurangzeb) - Later Emperors = 1707-1857
sayanee/archives
_posts/2008-01-13-mughal-empire.md
Markdown
mit
601
33.411765
92
0.716239
false
require "spec_helper" module Smsru describe API do shared_context "shared configuration", need_values: 'configuration' do before :each do Smsru.configure do |conf| conf.api_id = 'your-api-id' conf.from = 'sender-name' conf.test = test conf.format = format end end subject { Smsru::API } end shared_examples 'send_sms' do it { expect(VCR.use_cassette(cassette) { subject.send_sms(phone, text) }).to eq(response) } end shared_examples 'send_group_sms' do it { expect(VCR.use_cassette(cassette) { subject.group_send(phone, text) }).to eq(response) } end let(:text) { 'Sample of text that will have sended inside sms.' } let(:phone) { '+79050000000' } context 'test', need_values: 'configuration' do let(:test) { true } describe 'format = false' do it_behaves_like "send_sms" do let(:response) { "100\n000-00000" } let(:cassette) { 'api/send_sms' } let(:format) { false } end end describe 'error message' do let(:phone) { '0000' } let(:raw_response) { "202\n0000" } it_behaves_like "send_sms" do let(:response) { raw_response } let(:cassette) { 'api/error_sms' } let(:format) { false } end it_behaves_like "send_sms" do let(:response) { Smsru::Response.new(phone, raw_response) } let(:cassette) { 'api/error_sms' } let(:format) { true } end end describe 'group send sms' do let(:raw_response) { "100\n000-00000\n000-00000" } let(:phone) { ['+79050000000', '+79060000000'] } let(:cassette) { 'api/group_sms' } describe 'format = true' do it_behaves_like "send_group_sms" do let(:response_phone) { '+79050000000,+79060000000' } let(:response) { [Smsru::Response.new(response_phone, raw_response)] } let(:format) { true } end end describe 'format = false' do it_behaves_like "send_group_sms" do let(:response) { [raw_response] } let(:format) { false } end end end end context 'production', need_values: 'configuration' do let(:test) { false } describe 'send sms' do let(:raw_response) { "100\n000-00000\nbalance=1000" } let(:cassette) { 'api/send_sms_production' } describe 'format = false' do it_behaves_like "send_sms" do let(:response) { raw_response } let(:format) { false } end end describe 'format = true' do it_behaves_like "send_sms" do let(:response) { Smsru::Response.new(phone, raw_response) } let(:format) { true } end end end describe 'group send sms' do let(:raw_response) { "100\n000-00000\n000-00000\nbalance=1000" } let(:cassette) { 'api/group_sms_production' } let(:phone) { ['+79050000000', '+79060000000'] } let(:response_phone) { '+79050000000,+79060000000' } describe 'format = true' do it_behaves_like "send_group_sms" do let(:response) { [Smsru::Response.new(response_phone, raw_response)] } let(:format) { true } end end describe 'format = false' do it_behaves_like "send_group_sms" do let(:response) { [raw_response] } let(:format) { false } end end end end end end
alekseenkoss77/smsru
spec/lib/smsru/api_spec.rb
Ruby
mit
3,612
28.373984
99
0.540144
false
import { expect } from 'chai'; import buildUriTemplate from '../src/uri-template'; describe('URI Template Handler', () => { context('when there are path object parameters', () => { context('when the path object parameters are not query parameters', () => { const basePath = '/api'; const href = '/pet/findByTags'; const pathObjectParams = [ { in: 'path', description: 'Path parameter from path object', name: 'fromPath', required: true, type: 'string', }, ]; const queryParams = [ { in: 'query', description: 'Tags to filter by', name: 'tags', required: true, type: 'string', }, { in: 'query', description: 'For tests. Unknown type of query parameter.', name: 'unknown', required: true, type: 'unknown', }, ]; it('returns the correct URI', () => { const hrefForResource = buildUriTemplate(basePath, href, pathObjectParams, queryParams); expect(hrefForResource).to.equal('/api/pet/findByTags{?tags,unknown}'); }); }); context('when there are no query parameters but have one path object parameter', () => { const basePath = '/api'; const href = '/pet/{id}'; const pathObjectParams = [ { in: 'path', description: 'Pet\'s identifier', name: 'id', required: true, type: 'number', }, ]; const queryParams = []; it('returns the correct URI', () => { const hrefForResource = buildUriTemplate(basePath, href, pathObjectParams, queryParams); expect(hrefForResource).to.equal('/api/pet/{id}'); }); }); context('when there are query parameters defined', () => { const basePath = '/api'; const href = '/pet/findByTags'; const pathObjectParams = [ { in: 'query', description: 'Query parameter from path object', name: 'fromPath', required: true, type: 'string', }, ]; const queryParams = [ { in: 'query', description: 'Tags to filter by', name: 'tags', required: true, type: 'string', }, { in: 'query', description: 'For tests. Unknown type of query parameter.', name: 'unknown', required: true, type: 'unknown', }, ]; it('returns the correct URI', () => { const hrefForResource = buildUriTemplate(basePath, href, pathObjectParams, queryParams); expect(hrefForResource).to.equal('/api/pet/findByTags{?fromPath,tags,unknown}'); }); }); context('when there are parameters with reserved characters', () => { const basePath = '/my-api'; const href = '/pet/{unique%2did}'; const queryParams = [ { in: 'query', description: 'Tags to filter by', name: 'tag-names[]', required: true, type: 'string', }, ]; it('returns the correct URI', () => { const hrefForResource = buildUriTemplate(basePath, href, [], queryParams); expect(hrefForResource).to.equal('/my-api/pet/{unique%2did}{?tag%2dnames%5B%5D}'); }); }); context('when there is a conflict in parameter names', () => { const basePath = '/api'; const href = '/pet/findByTags'; const pathObjectParams = [ { in: 'query', description: 'Tags to filter by', name: 'tags', required: true, type: 'string', }, ]; const queryParams = [ { in: 'query', description: 'Tags to filter by', name: 'tags', required: true, type: 'string', }, ]; it('only adds one to the query parameters', () => { const hrefForResource = buildUriTemplate(basePath, href, pathObjectParams, queryParams); expect(hrefForResource).to.equal('/api/pet/findByTags{?tags}'); }); }); context('when there are no query parameters defined', () => { const basePath = '/api'; const href = '/pet/findByTags'; const pathObjectParams = [ { in: 'query', description: 'Query parameter from path object', name: 'fromPath', required: true, type: 'string', }, ]; const queryParams = []; it('returns the correct URI', () => { const hrefForResource = buildUriTemplate(basePath, href, pathObjectParams, queryParams); expect(hrefForResource).to.equal('/api/pet/findByTags{?fromPath}'); }); }); }); context('when there are query parameters but no path object parameters', () => { const basePath = '/api'; const href = '/pet/findByTags'; const pathObjectParams = []; const queryParams = [ { in: 'query', description: 'Tags to filter by', name: 'tags', required: true, type: 'string', }, { in: 'query', description: 'For tests. Unknown type of query parameter.', name: 'unknown', required: true, type: 'unknown', }, ]; it('returns the correct URI', () => { const hrefForResource = buildUriTemplate(basePath, href, pathObjectParams, queryParams); expect(hrefForResource).to.equal('/api/pet/findByTags{?tags,unknown}'); }); }); context('when there are no query or path object parameters', () => { const basePath = '/api'; const href = '/pet/findByTags'; const pathObjectParams = []; const queryParams = []; it('returns the correct URI', () => { const hrefForResource = buildUriTemplate(basePath, href, pathObjectParams, queryParams); expect(hrefForResource).to.equal('/api/pet/findByTags'); }); }); describe('array parameters with collectionFormat', () => { it('returns a template with default format', () => { const parameter = { in: 'query', name: 'tags', type: 'array', }; const hrefForResource = buildUriTemplate('', '/example', [parameter]); expect(hrefForResource).to.equal('/example{?tags}'); }); it('returns a template with csv format', () => { const parameter = { in: 'query', name: 'tags', type: 'array', collectionFormat: 'csv', }; const hrefForResource = buildUriTemplate('', '/example', [parameter]); expect(hrefForResource).to.equal('/example{?tags}'); }); it('returns an exploded template with multi format', () => { const parameter = { in: 'query', name: 'tags', type: 'array', collectionFormat: 'multi', }; const hrefForResource = buildUriTemplate('', '/example', [parameter]); expect(hrefForResource).to.equal('/example{?tags*}'); }); }); });
apiaryio/fury-adapter-swagger
test/uri-template.js
JavaScript
mit
7,065
28.4375
96
0.537721
false
let Demo1 = require('./components/demo1.js'); document.body.appendChild(Demo1());
zjx1195688876/learn-react
src/webapp/main.js
JavaScript
mit
82
26.666667
45
0.731707
false
<!-- Author: Ray-Eldath refer to: - http://docs.mathjax.org/en/latest/options/index.html --> {% if site.mathjax %} <script type="text/javascript" async src="https://cdnjs.loli.net/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_CHTML"></script> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ jax: ["input/TeX", "output/HTML-CSS"], tex2jax: { inlineMath: [ ["$", "$"] ], displayMath: [ ["$$", "$$"] ], skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'] }, "HTML-CSS": { preferredFont: "TeX", availableFonts: ["STIX","TeX"] } }); </script> {% endif %}
gyje/gyje.github.io
_includes/mathjax.html
HTML
mit
625
30.3
135
0.5936
false
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Demo05")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Demo05")] [assembly: AssemblyCopyright("Copyright © Microsoft 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] //若要开始生成可本地化的应用程序,请在 //<PropertyGroup> 中的 .csproj 文件中 //设置 <UICulture>CultureYouAreCodingWith</UICulture>。例如,如果您在源文件中 //使用的是美国英语,请将 <UICulture> 设置为 en-US。然后取消 //对以下 NeutralResourceLanguage 特性的注释。更新 //以下行中的“en-US”以匹配项目文件中的 UICulture 设置。 //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //主题特定资源词典所处位置 //(在页面或应用程序资源词典中 // 未找到某个资源的情况下使用) ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置 //(在页面、应用程序或任何主题特定资源词典中 // 未找到某个资源的情况下使用) )] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 内部版本号 // 修订号 // // 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
HungryAnt/AntWpfDemos
AntWpfDemos/Demo05/Properties/AssemblyInfo.cs
C#
mit
2,195
25.818182
91
0.710458
false
# safe_projects Project management with git ## Configuration Create a file named `~/.projects` with the path where you'd like your repositories to be stored. This should ideally be a location that is backed up regularly. ```bash vim ~/.projects ``` An example file looks like this: ```bash export REPOSITORY_ROOT=/net/eichler/vol4/home/jlhudd/projects/repositories ``` Clone safe projects code and add scripts to `$PATH`. ```bash mkdir -p ~/src cd ~/src git clone https://github.com/huddlej/safe_projects.git PATH=$PATH:$HOME/src/safe_projects export PATH ``` ## Usage Create a new project. ```bash create_project.sh 2015-05-23-analyze_copy_number_distributions ``` Change into new project directory. ```bash cd 2015-05-23-analyze_copy_number_distributions ``` Add environmental configuration to `config.sh`. Add rules for your analyses to `Snakefile`. Add configuration parameters for [snakemake](https://bitbucket.org/johanneskoester/snakemake/wiki/Home) to `config.json`. Run your analysis. ```bash snakemake ``` Add your changes to the repository and commit them. ```bash git add Snakefile config.json config.sh git commit -m "added initial rules and configuration" ``` Save your changes to the repository root (i.e., your backed up path from the configuration section above). ```bash git push origin master ``` If your current working directory is already a git repository without a remote, you can quickly initialize a remote repository and push all your changes there by running the following command from the top-level of the working directory. ```bash initialize_project.sh ```
huddlej/safe_projects
README.md
Markdown
mit
1,608
20.44
79
0.75995
false
<div id="container" class="container-fluid" ng-controller="cloudAppController"> <div class="table"> <div class="col-lg-2"> <label for="teamDD">Team:</label> <select id="teamDD" class="form-control headerSelectWidth" ng-model="filteredTeam" ng-change="onTeamChange()" ng-options="team.id as team.name for team in teamsOnly"></select> </div> <!--<div class="col-lg-2"> <label for="moduleSearch">Module:</label> <input id="moduleSearch" class="form-control headerSelectWidth" ng-model="search.moduleName"/> </div>--> <div class="col-lg-2"> <label for="cloudAppSearch">CloudApp:</label> <input id="cloudAppSearch" class="form-control headerSelectWidth" ng-model="search.appName"/> </div> <div class="col-lg-1"> <div class="spinner" ng-show="isLoading"></div> </div> </div> <div ng-repeat = "module in cloudAddData.modules"> <div class="col-lg-12"> <table class="table"> <thead> <tr> <th> <span >{{module.moduleName}}</span> </th> </tr> <tr> <th> <span tooltip-placement="top">CloudApp</span> </th> <th> <span tooltip-placement="top">Page</span> </th> <th>StoryPoints</th> <th>Stream</th> <th>TaskStatus</th> <th>Blockers</th> </tr> </thead> <tbody> <tr ng-repeat = "cloudApp in module.cloudApps | filter:search:strict | orderBy:['appName','pageName']:reverse"> <!-- <td class="table_cell_border" ng-if="showCloud(cloudApp.appName)">{{cloudApp.appName}}</td> <td class="" ng-if="previousCloudSkipped"></td> rowspan="{{module.}}" --> <td class="table_cell_border" style="vertical-align: middle;" rowspan="{{getSpan(cloudApp.appName, module.cloudAppRowspans)}}" ng-if="showCloud(cloudApp.appName)" >{{cloudApp.appName}}</td> <td class="table_cell_border">{{cloudApp.pageName}}</td> <td class="table_cell_border">{{cloudApp.storyPoints}}</td> <td class="table_cell_border">{{cloudApp.stream}}</td> <td class="table_cell_border">{{cloudApp.taskStatus}}</td> <td class="table_cell_border"> <span ng-repeat="blocker in cloudApp.blockers" > <a ng-if="blocker.status!='Closed'" class="btn btn-primary blocker_style" ng-style={'background-color':stringToColorCode(blocker.key)} href="{{blocker.uri}}" target="_blank"> {{blocker.key}} <span class="badge">{{blocker.pagesInvolved}}</span> </a> <a ng-if="blocker.status=='Closed'" class="btn btn-primary blocker_style blocker_status_{{blocker.status}}" href="{{blocker.uri}}" target="_blank"> {{blocker.key}} <span class="badge">{{blocker.pagesInvolved}}</span> </a> </span> </td> </tr> </tbody> </table> </div> </div> </div>
ZloiBubr/ReportTool
public/pages/cloudappBlocker.html
HTML
mit
3,587
46.210526
209
0.477837
false
package doit.study.droid.fragments; import android.app.Activity; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import doit.study.droid.R; public class DislikeDialogFragment extends DialogFragment { public static final String EXTRA_CAUSE = "doit.study.droid.extra_cause"; private static final String QUESTION_TEXT_KEY = "doit.study.droid.question_text_key"; private Activity mHostActivity; private View mView; private int[] mCauseIds = {R.id.question_incorrect, R.id.answer_incorrect, R.id.documentation_irrelevant}; public static DislikeDialogFragment newInstance(String questionText) { DislikeDialogFragment dislikeDialog = new DislikeDialogFragment(); Bundle arg = new Bundle(); arg.putString(QUESTION_TEXT_KEY, questionText); dislikeDialog.setArguments(arg); return dislikeDialog; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { mHostActivity = getActivity(); LayoutInflater inflater = mHostActivity.getLayoutInflater(); mView = inflater.inflate(R.layout.fragment_dialog_dislike, null); AlertDialog.Builder builder = new AlertDialog.Builder(mHostActivity); builder.setMessage(getString(R.string.report_because)) .setView(mView) .setPositiveButton(mHostActivity.getString(R.string.report), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Fragment fr = getTargetFragment(); if (fr != null) { Intent intent = new Intent(); intent.putExtra(EXTRA_CAUSE, formReport()); fr.onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent); } } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); // Create the AlertDialog object and return it return builder.create(); } private String formReport() { EditText editText = (EditText) mView.findViewById(R.id.comment); StringBuilder result = new StringBuilder(" Cause:"); for (int id : mCauseIds) { CheckBox checkBox = (CheckBox) mView.findViewById(id); if (checkBox.isChecked()) result.append(checkBox.getText()) .append(","); } result.append(" Comment:"); result.append(editText.getText()); return result.toString(); } }
JaeW/dodroid
app/src/main/java/doit/study/droid/fragments/DislikeDialogFragment.java
Java
mit
3,105
40.413333
116
0.639614
false
<?php namespace Zycon42\Security\Application; use Nette; use Nette\Application\Request; use Nette\Reflection\ClassType; use Nette\Reflection\Method; use Symfony\Component\ExpressionLanguage\Expression; class PresenterRequirementsChecker extends Nette\Object { /** * @var ExpressionEvaluator */ private $expressionEvaluator; private $failedExpression; public function __construct(ExpressionEvaluator $expressionEvaluator) { $this->expressionEvaluator = $expressionEvaluator; } /** * @param ClassType|Method $element * @param Request $request * @return bool * @throws \InvalidArgumentException */ public function checkRequirement($element, Request $request) { if ($element instanceof ClassType) { $expressions = $this->getClassExpressionsToEvaluate($element); } else if ($element instanceof Method) { $expressions = $this->getMethodExpressionsToEvaluate($element); } else throw new \InvalidArgumentException("Argument 'element' must be instanceof Nette\\Reflection\\ClassType or Nette\\Reflection\\Method"); if (!empty($expressions)) { foreach ($expressions as $expression) { $result = $this->expressionEvaluator->evaluate($expression, $request); if (!$result) { $this->failedExpression = $expression; return false; } } } return true; } public function getFailedExpression() { return $this->failedExpression; } private function getClassExpressionsToEvaluate(ClassType $classType) { $expressions = []; $this->walkClassHierarchy($classType, $expressions); return $expressions; } private function walkClassHierarchy(ClassType $classType, &$expressions) { $parentClass = $classType->getParentClass(); if ($parentClass) $this->walkClassHierarchy($parentClass, $expressions); $annotation = $classType->getAnnotation('Security'); if ($annotation) { if (!is_string($annotation)) { throw new \InvalidArgumentException('Security annotation must be simple string with expression.'); } $expressions[] = new Expression($annotation); } } private function getMethodExpressionsToEvaluate(Method $method) { $annotation = $method->getAnnotation('Security'); if ($annotation) { if (!is_string($annotation)) { throw new \InvalidArgumentException('Security annotation must be simple string with expression.'); } return [new Expression($annotation)]; } return []; } }
Zycon42/Security
lib/Zycon42/Security/Application/PresenterRequirementsChecker.php
PHP
mit
2,781
31.717647
147
0.626393
false
<?php namespace App\Http\Middleware; use Input, Closure, Response, User; class CheckClientKey { public function handle($request, Closure $next) { $input = Input::all(); $output = array(); if(!isset($input['key'])){ $output['error'] = 'API key required'; return Response::json($output, 403); } $findUser = User::where('api_key', '=', $input['key'])->first(); if(!$findUser){ $output['error'] = 'Invalid API key'; return Response::json($output, 400); } if($findUser->activated == 0){ $output['error'] = 'Account not activated'; return Response::json($output, 403); } User::$api_user = $findUser; return $next($request); } }
tokenly/token-slot
app/Http/Middleware/CheckClientKey.php
PHP
mit
696
23.857143
66
0.594828
false
/*! NSURL extension YSCategorys Copyright (c) 2013-2014 YoungShook https://github.com/youngshook/YSCategorys The MIT License (MIT) http://www.opensource.org/licenses/mit-license.php */ #import <Foundation/Foundation.h> @interface NSURL (YSKit) /** Cover query string into NSDictionary */ - (NSDictionary *)ys_queryDictionary; + (NSURL *)ys_appStoreURLforApplicationIdentifier:(NSString *)identifier; + (NSURL *)ys_appStoreReviewURLForApplicationIdentifier:(NSString *)identifier; @end
youngshook/YSCategorys
Categorys/Foundation/NSURL+YSKit.h
C
mit
519
20.625
79
0.734104
false
--- permalink: /en/getting-startedLearn redirect: /en/getting-started/ layout: redirect sitemap: false ---
sunnankar/wucorg
redirects/redirects4/en-getting-startedLearn.html
HTML
mit
106
16.833333
35
0.754717
false
#region References using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using Speedy; #endregion namespace Scribe.Data.Entities { public class Page : ModifiableEntity { #region Constructors [SuppressMessage("ReSharper", "VirtualMemberCallInContructor")] public Page() { Versions = new Collection<PageVersion>(); } #endregion #region Properties public virtual PageVersion ApprovedVersion { get; set; } public virtual int? ApprovedVersionId { get; set; } public virtual PageVersion CurrentVersion { get; set; } public virtual int? CurrentVersionId { get; set; } /// <summary> /// Gets or sets a flag to indicated this pages has been "soft" deleted. /// </summary> public bool IsDeleted { get; set; } public virtual ICollection<PageVersion> Versions { get; set; } #endregion } }
BobbyCannon/Scribe
Scribe.Data/Entities/Page.cs
C#
mit
889
19.651163
74
0.726043
false
#pragma config(Sensor, in1, linefollower, sensorLineFollower) #pragma config(Sensor, dgtl5, OutputBeltSonar, sensorSONAR_mm) #pragma config(Motor, port6, WhipCreamMotor, tmotorVex393, openLoop) #pragma config(Motor, port7, InputBeltMotor, tmotorServoContinuousRotation, openLoop) #pragma config(Motor, port8, ElevatorMotor, tmotorServoContinuousRotation, openLoop) #pragma config(Motor, port9, OutputBeltMotor, tmotorServoContinuousRotation, openLoop) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// /* Project Title: Cookie Maker Team Members: Patrick Kubiak Date: Section: Task Description: Control cookie maker machine Pseudocode: Move input conveior belt set distance Move elevator set distance Move output conveior belt until whip cream Press whip cream Reset whip cream Move output conveior belt to end Reset elevator */ task main() { //Program begins, insert code within curly braces while (true) { //Input Conveior Belt startMotor(InputBeltMotor, 127); wait(2.5); stopMotor(InputBeltMotor); //Elevator startMotor(ElevatorMotor, 127); wait(1.5); stopMotor(ElevatorMotor); //Move Cookie To line follower do { startMotor(OutputBeltMotor, -127); } while(SensorValue(linefollower) > 2900); stopMotor(OutputBeltMotor); //Reset Elevator startMotor(ElevatorMotor, -127); wait(2); stopMotor(ElevatorMotor); //Move Cookie To Whip Cream startMotor(OutputBeltMotor, -127); wait(0.4); stopMotor(OutputBeltMotor); //Whip Cream Press startMotor(WhipCreamMotor, -127); wait(1); stopMotor(WhipCreamMotor); //Whip Cream Reset startMotor(WhipCreamMotor, 127); wait(0.9); stopMotor(WhipCreamMotor); //Output Conveior Belt startMotor(OutputBeltMotor, -127); wait(2); } }
patkub/pltw-vex-robotc
CookieMaker_Sensor.c
C
mit
1,901
24.346667
97
0.701736
false
# 弃用通知 此项目已不再维护,所有内容已经移至[magpie](https://github.com/haifenghuang/magpie)。 # Monkey程序语言 Table of Contents ================= * [Monkey程序语言](#monkey%E7%A8%8B%E5%BA%8F%E8%AF%AD%E8%A8%80) * [主页](#%E4%B8%BB%E9%A1%B5) * [概述](#%E6%A6%82%E8%BF%B0) * [总览](#%E6%80%BB%E8%A7%88) * [安装](#%E5%AE%89%E8%A3%85) * [基本用法](#%E5%9F%BA%E6%9C%AC%E7%94%A8%E6%B3%95) * [语言之旅](#%E8%AF%AD%E8%A8%80%E4%B9%8B%E6%97%85) * [注释](#%E6%B3%A8%E9%87%8A) * [数据类型](#%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B) * [常量(字面值)](#%E5%B8%B8%E9%87%8F%E5%AD%97%E9%9D%A2%E5%80%BC) * [变量](#%E5%8F%98%E9%87%8F) * [保留字](#%E4%BF%9D%E7%95%99%E5%AD%97) * [类型转换](#%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2) * [qw(Quote word)关键字](#qwquote-word%E5%85%B3%E9%94%AE%E5%AD%97) * [enum关键字](#enum%E5%85%B3%E9%94%AE%E5%AD%97) * [元操作符(Meta\-Operators)](#%E5%85%83%E6%93%8D%E4%BD%9C%E7%AC%A6meta-operators) * [控制流程](#%E6%8E%A7%E5%88%B6%E6%B5%81%E7%A8%8B) * [using语句](#using%E8%AF%AD%E5%8F%A5) * [用户自定义操作符](#%E7%94%A8%E6%88%B7%E8%87%AA%E5%AE%9A%E4%B9%89%E6%93%8D%E4%BD%9C%E7%AC%A6) * [整型(Integer)](#%E6%95%B4%E5%9E%8Binteger) * [浮点型(Float)](#%E6%B5%AE%E7%82%B9%E5%9E%8Bfloat) * [Decimal类型](#decimal%E7%B1%BB%E5%9E%8B) * [数组(Array)](#%E6%95%B0%E7%BB%84array) * [字符串(String)](#%E5%AD%97%E7%AC%A6%E4%B8%B2string) * [哈希(Hash)](#%E5%93%88%E5%B8%8Chash) * [元祖(Tuple)](#%E5%85%83%E7%A5%96tuple) * [类](#%E7%B1%BB) * [继承和多态](#%E7%BB%A7%E6%89%BF%E5%92%8C%E5%A4%9A%E6%80%81) * [操作符重载](#%E6%93%8D%E4%BD%9C%E7%AC%A6%E9%87%8D%E8%BD%BD) * [属性(类似C\#)](#%E5%B1%9E%E6%80%A7%E7%B1%BB%E4%BC%BCc) * [索引器](#%E7%B4%A2%E5%BC%95%E5%99%A8) * [静态变量/方法/属性](#%E9%9D%99%E6%80%81%E5%8F%98%E9%87%8F%E6%96%B9%E6%B3%95%E5%B1%9E%E6%80%A7) * [类类别(class category)](#%E7%B1%BB%E7%B1%BB%E5%88%ABclass-category) * [注解](#%E6%B3%A8%E8%A7%A3) * [标准输入/输出/错误](#%E6%A0%87%E5%87%86%E8%BE%93%E5%85%A5%E8%BE%93%E5%87%BA%E9%94%99%E8%AF%AF) * [标准库中的错误处理](#%E6%A0%87%E5%87%86%E5%BA%93%E4%B8%AD%E7%9A%84%E9%94%99%E8%AF%AF%E5%A4%84%E7%90%86) * [关于defer关键字](#%E5%85%B3%E4%BA%8Edefer%E5%85%B3%E9%94%AE%E5%AD%97) * [不同类型的联接](#%E4%B8%8D%E5%90%8C%E7%B1%BB%E5%9E%8B%E7%9A%84%E8%81%94%E6%8E%A5) * [列表推导(Comprehensions)](#%E5%88%97%E8%A1%A8%E6%8E%A8%E5%AF%BCcomprehensions) * [Grep和map](#grep%E5%92%8Cmap) * [函数](#%E5%87%BD%E6%95%B0) * [Pipe操作符](#pipe%E6%93%8D%E4%BD%9C%E7%AC%A6) * [Spawn 和 channel](#spawn-%E5%92%8C-channel) * [使用go语言模块](#%E4%BD%BF%E7%94%A8go%E8%AF%AD%E8%A8%80%E6%A8%A1%E5%9D%97) * [标准模块介绍](#%E6%A0%87%E5%87%86%E6%A8%A1%E5%9D%97%E4%BB%8B%E7%BB%8D) * [fmt 模块](#fmt-%E6%A8%A1%E5%9D%97) * [time 模块](#time-%E6%A8%A1%E5%9D%97) * [logger 模块](#logger-%E6%A8%A1%E5%9D%97) * [flag 模块(处理命令行选项)](#flag-%E6%A8%A1%E5%9D%97%E5%A4%84%E7%90%86%E5%91%BD%E4%BB%A4%E8%A1%8C%E9%80%89%E9%A1%B9) * [json 模块( json序列化(marshal)和反序列化(unmarshal) )](#json-%E6%A8%A1%E5%9D%97-json%E5%BA%8F%E5%88%97%E5%8C%96marshal%E5%92%8C%E5%8F%8D%E5%BA%8F%E5%88%97%E5%8C%96unmarshal-) * [net 模块](#net-%E6%A8%A1%E5%9D%97) * [linq 模块](#linq-%E6%A8%A1%E5%9D%97) * [Linq for file支持](#linq-for-file%E6%94%AF%E6%8C%81) * [csv 模块](#csv-%E6%A8%A1%E5%9D%97) * [template 模块](#template-%E6%A8%A1%E5%9D%97) * [sql 模块](#sql-%E6%A8%A1%E5%9D%97) * [实用工具](#%E5%AE%9E%E7%94%A8%E5%B7%A5%E5%85%B7) * [文档生成](#%E6%96%87%E6%A1%A3%E7%94%9F%E6%88%90) * [语法高亮](#%E8%AF%AD%E6%B3%95%E9%AB%98%E4%BA%AE) * [未来计划](#%E6%9C%AA%E6%9D%A5%E8%AE%A1%E5%88%92) * [许可证](#%E8%AE%B8%E5%8F%AF%E8%AF%81) * [备注](#%E5%A4%87%E6%B3%A8) ## 主页 [monkey](https://github.com/haifenghuang/monkey) ## 概述 Monkey是一个用go语言写的解析器. 语法借鉴了C, Ruby, Python, Perl和C#. 支持常用的控制流程,函数式编程和面向对象编程。 同时它还包括一个实时语法高亮的REPL。 下面是一个使用monkey语言的示例程序: ```swift //声明注解,注解的body中必须是属性,不能是方法 class @MinMaxValidator { property MinLength property MaxLength default 10 //Same as 'property MaxLength = 10' } //Marker annotation class @NoSpaceValidator {} class @DepartmentValidator { property Department } //这个是请求类,我们对这个类使用注解 class Request { @MinMaxValidator(MinLength=1) property FirstName; //这种方式声明的属性,默认为可读可写。等价于'property FirstName { get; set; }' @NoSpaceValidator property LastName; @DepartmentValidator(Department=["Department of Education", "Department of Labors"]) property Dept; } //处理注解的类 class RequestHandler { static fn handle(o) { props = o.getProperties() for p in props { annos = p.getAnnotations() for anno in annos { if anno.instanceOf(MinMaxValidator) { //p.value表示属性的值 if len(p.value) > anno.MaxLength || len(p.value) < anno.MinLength { printf("Property '%s' is not valid!\n", p.name) } } elseif anno.instanceOf(NoSpaceValidator) { for c in p.value { if c == " " || c == "\t" { printf("Property '%s' is not valid!\n", p.name) break } } } elseif anno.instanceOf(DepartmentValidator) { found = false for d in anno.Department { if p.value == d { found = true } } if !found { printf("Property '%s' is not valid!\n", p.name) } } } } } } class RequestMain { static fn main() { request = new Request(); request.FirstName = "Haifeng123456789" request.LastName = "Huang " request.Dept = "Department of Labors" RequestHandler.handle(request); } } RequestMain.main() ``` 下面是处理结果: ``` Property 'FirstName' is not valid! Property 'LastName' is not valid! ``` 下面是一个实时语法高亮REPL: ![REPL](REPL.gif) 下面是使用mdoc生成的html文档: ![HTML DOC](doc.png) ## 总览 此项目是基于mayoms的项目 [monkey](https://github.com/mayoms/monkey),修改了其中的一些bug,同时增加了许多语言特性: * 增加了简单面向对象(oop)支持(索引器,操作符重载,属性,static方法,注解) * 更改了`string`模块(能够正确处理utf8字符编码) * 修改了`file`模块(包含一些新方法). * 增加了`math`,`time`, `sort`, `os`, `log`, `net`, `http`, `filepath`, `fmt`, `sync`, `list`, `csv`, `regexp`, `template`, 模块等 * `sql(db)`模块(能够正确的处理`null`值) * `flag`模块(用来处理命令行参数) * `json`模块(json序列化和反序列化) * `linq`模块(代码来自[linq](https://github.com/ahmetb/go-linq)并进行了相应的更改) * 增加了`decimal`模块(代码来自[decimal](https://github.com/shopspring/decimal)并进行了相应的小幅度更改) * 正则表达式支持(部分类似于perl) * 管道(channel)(基于go语言的channel) * 更多的操作符支持(&&, ||, &, |, ^, +=, -=, ?:, ??等等) * utf8支持(例如,你可以使用utf8字符作为变量名) * 更多的流程控制支持(例如: try/catch/finally, for-in, case-in, 类似c语言的for循环) * defer支持 * spawn支持(goroutine) * enum支持 * `using`支持(类似C#的using) * pipe操作符支持 * 支持可变参数和缺省参数的函数 * 支持列表推导(list comprehension)和哈希推导(hash comprehension) * 支持用户自定义操作符 * 使用Go Package的方法(`RegisterFunctions`和`RegisterVars`) 这个项目的目的主要有以下几点: * 自学go语言 * 了解解析器的工作原理 但是,解析器的速度并不是这个项目考虑的因素 ## 安装 下载本项目,运行`./run.sh` ## 基本用法 你可以如下方式使用REPL: ```sh ~ » monkey Monkey programming language REPL >> ``` 或者运行一个monkey文件: ```sh monkey path/to/file ``` ## 语言之旅 ### 注释 Monkey支持两种形式的单行注释和块注释: ```swift // a single line comment # another single line comment /* This is a block comment. */ ``` 同时也支持块注释 ### 数据类型 Monkey支持9种基本类型: `String`, `Int`, `UInt`, `Float`, `Bool`, `Array`, `Hash`, `Tuple`和`Nil` ```swift s1 = "hello, 黄" # strings are UTF-8 encoded s2 = `hello, "world"` # raw string i = 10 # int u = 10u # uint f = 10.0 # float b = true # bool a = [1, "2"] # array h = {"a": 1, "b": 2} # hash t = (1,2,3) # tuple n = nil ``` ### 常量(字面值) Monkey中,主要有11种类型的常量(字面量). * Integer * UInteger * Float * String * 正则表达式 * Array * Hash * Tuple * Nil * Boolean * Function ```swift // Integer literals i1 = 10 i2 = 20_000_000 i3 = 0x80 // hex i4 = 0b10101 // binary i5 = 0o127 // octal // Unsigned Integer literals ui1 = 10u ui2 = 20_000_000u //for more readable ui3 = 0x80u // hex ui4 = 0b10101u // binary ui5 = 0o127u // octal // Float literals f1 = 10.25 f2 = 1.02E3 f3 = 123_456.789_012 // String literals s1 = "123" s2 = "Hello world" // Regular expression literals r = /\d+/.match("12") if (r) { prinln("regex matched!") } // Array literals a = [1+2, 3, 4, "5", 3] // Hash literals h = { "a": 1, "b": 2, "c": 2} //Tuple literals t = (1, 2+3, "Hello", 5) // Nil literal n = nil // Boolean literals t = true f = false // Function literals let f1 = add(x, y) { return x + y } println(f1(1,2)) //fat-arrow function literals let f2 = (x, y) => x + y println(f2(1,2)) ``` ### 变量 你可以使用`let`来声明一个变量,或直接使用赋值的方式来声明并赋值一个变量:`variable=value`. ```swift let a, b, c = 1, "hello world", [1,2,3] d = 4 e = 5 姓="黄" ``` 你还可以使用`解构赋值`(Destructuring assignment), 当使用这种方法的时候,等号左边的变量必须用‘()’包起来: ```swift //等号右边为数组 let (d,e,f) = [1,5,8] //d=1, e=5, f=8 //等号右边为元祖 let (g, h, i) = (10, 20, "hhf") //g=10, h=20, i=hhf //等号右边为哈希 let (j, k, l) = {"j": 50, "l": "good"} //j=50, k=nil, l=good ``` 如果你不使用`let`来给变量赋值,那么你将不能使用多变量赋值。下面的语句是错误的: ```swift //错误,多变量赋值必须使用let关键字 a, b, c = 1, "hello world", [1,2,3] ``` 注:从Monkey 5.0开始,`let`的含义有所变化,如果声明的变量已经存在,给变量赋值的时候就会覆盖原来的值: ```swift let x, y = 10, 20; let x, y = y, x //交换两个变量的值 printf("x=%v, y=%v\n", x, y) //结果:x=20, y=10 ``` `let`还支持使用占位符(_), 如果给占位符赋了一个值,占位符会忽略这个值: ```swift let x, _, y = 10, 20, 30 printf("x=%d, y=%d\n", x, y) //结果:x=10, y=30 ``` ### 保留字 下面列出了monkey语言的保留字: * fn * let * true false nil * if elsif elseif elif else * unless * return * include * and or * enum * struct # 保留,暂时没使用 * do while for break continue where * grep map * case is in * try catch finally throw * defer * spawn * qw * using * class new property set get static default * interface public private protected #保留,暂时没使用 ### 类型转换 你可以使用内置的方法:`int()`, `uint()`, `float()`, `str()`, `array()`, `tuple`, `hash`, `decimal`来进行不同类型之间的转换. ```swift let i = 0xa let u = uint(i) // result: 10 let s = str(i) // result: "10" let f = float(i) // result: 10 let a = array(i) // result: [10] let t = tuple(i) // result: (10,) let h = hash(("key", "value")) // result: {"key": "value} let d = decimal("123.45634567") // result: 123.45634567 ``` 你可以从一个数组创建一个tuple: ```swift let t = tuple([10, 20]) //result:(10,20) ``` 同样的, 你也可以从一个tuple创建一个数组: ```swift let arr = array((10,20)) //result:[10,20] ``` 你只能从数组或者tuple来创建一个hash: ```swift //创建一个空的哈希 let h1 = hash() //same as h1 = {} //从数组创建哈希 let h1 = hash([10, 20]) //result: {10 : 20} let h2 = hash([10,20,30]) //result: {10 : 20, 30 : nil} //从tuple创建哈希 let h3 = hash((10, 20)) //result: {10 : 20} let h4 = hash((10,20,30)) //result: {10 : 20, 30 : nil} ``` ### `qw`(Quote word)关键字 `qw`关键字类似perl的`qw`关键字. 当你想使用很多的双引号字符串时,`qw`就是一个好帮手. ```swift for str in qw<abc, def, ghi, jkl, mno> { //允许的成对操作符:'{}', '<>', '()' println('str={str}') } newArr = qw(1,2,3.5) //注:这里的newArr是一个字符串数组,不是一个整形数组. fmt.printf("newArr=%v\n", newArr) ``` ### `enum`关键字 在mokey中,你可以使用`enum`来定义常量. ```swift LogOption = enum { Ldate = 1 << 0, Ltime = 1 << 1, Lmicroseconds = 1 << 2, Llongfile = 1 << 3, Lshortfile = 1 << 4, LUTC = 1 << 5, LstdFlags = 1 << 4 | 1 << 5 } opt = LogOption.LstdFlags println(opt) //得到`enum`的所有名称 for s in LogOption.getNames() { //非排序(non-ordered) println(s) } //得到`enum`的所有值 for s in LogOption.getValues() { //非排序(non-ordered) println(s) } // 得到`enum`的一个特定的名字 println(LogOption.getName(LogOption.Lshortfile)) ``` ### 元操作符(Meta-Operators) Monkey内嵌了一些类似Perl6的元操作符。 但是对于元操作符有严格的限制: * 元操作符只能针对数组进行操作 * 元操作符操作的数组中的所有元素必须是数字(uint, int, float)或者字符串 * 元操作符是中缀元操作符的时候,如果两边都是数组的话,数组元素必须相等 ```swift let arr1 = [1,2,3] ~* [4,5,6] let arr2 = [1,2,3] ~* 4 let arr3 = [1,2,"HELLO"] ~* 2 let value1 = ~*[10,2,2] let value2 = ~+[2,"HELLO",2] println(arr1) //结果:[4, 10, 18] println(arr2) //结果:[4, 8, 12] println(arr3) //结果:[2,4,"HELLOHELLO"] println(value1) //结果:40 println(value2) //结果:2HELLO2 ``` 目前为止,Monkey中有六个元操作符: * <p>~+</p> * <p>~-</p> * <p>~*</p> * <p>~/</p> * <p>~%</p> * <p>~^</p> 这六个元操作符既可以作为中缀表达式,也可以作为前缀表达式。 元操作符作为中缀表达式返回的结果为数组类型。 元操作符作为前缀表达式返回的结果为值类型(uint, int, float, string)。 下面的表格列出了相关的元操作符及其含义(只列出了`~+`): <table> <tr> <th>元操作符</td> <th>表达式</td> <th>举例</td> <th>结果</td> </tr> <tr> <td>~+</td> <td>中缀表达式</td> <td>[x1, y1, z1] ~+ [x2, y2, z2]</td> <td>[x1+x2, y1+y2, z1+z2] (数组)</td> </tr> <tr> <td>~+</td> <td>中缀表达式</td> <td>[x1, y1, z1] ~+ 4</td> <td>[x1+4, y1+4, z1+4] (数组)</td> </tr> <tr> <td>~+</td> <td>前缀表达式</td> <td>~+[x1, y1, z1]</td> <td>x1+y1+z1 (注:数值, 非数组)</td> </tr> </table> ### 控制流程 * if/if-else/if-elif-else/if-elsif-else/if-elseif-else/if-else if-else * unless/unless-else * for/for-in * while * do * try-catch-finally * case-in/case-is ```swift // if-else let a, b = 10, 5 if (a > b) { println("a > b") } elseif a == b { // 也可以使用'elsif', 'elseif'和'elif' println("a = b") } else { println("a < b") } //unless-else unless b > a { println("a >= b") } else { println("b > a") } // for i = 9 for { // 无限循环 i = i + 2 if (i > 20) { break } println('i = {i}') } i = 0 for (i = 0; i < 5; i++) { // 类似c语言的for循环, '()'必须要有 if (i > 4) { break } if (i == 2) { continue } println('i is {i}') } i = 0 for (; i < 5; i++) { // 无初期化语句 if (i > 4) { break } if (i == 2) { continue } println('i is {i}') } i = 0 for (; i < 5;;) { // 无初期化和更新语句 if (i > 4) { break } if (i == 2) { continue } println('i is {i}') i++ //更新语句 } i = 0 for (;;;) { // 等价于'for { block }'语句 if (i > 4) { break } println('i is {i}') i++ //更新语句 } for i in range(10) { println('i = {i}') } a = [1,2,3,4] for i in a where i % 2 != 0 { println(i) } hs = {"a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7} for k, v in hs where v % 2 == 0 { println('{k} : {v}') } for i in 1..5 { println('i={i}') } for item in 10..20 where $_ % 2 == 0 { // $_ is the index printf("idx=%d, item=%d\n", $_, item) } for c in "m".."a" { println('c={c}') } for idx, v in "abcd" { printf("idx=%d, v=%s\n", idx, v) } for idx, v in ["a", "b", "c", "d"] { printf("idx=%d, v=%s\n", idx, v) } for item in ["a", "b", "c", "d"] where $_ % 2 == 0 { // $_ 是索引 printf("idx=%d, item=%s\n", $_, v) } //for循环是个表达式(expression),而不是一个语句(statement), 因此它能够被赋值给一个变量 let plus_one = for i in [1,2,3,4] { i + 1 } fmt.println(plus_one) // while i = 10 while (i>3) { i-- println('i={i}') } // do i = 10 do { i-- if (i==3) { break } } // try-catch-finally(仅支持throw一个string类型的变量) let exceptStr = "SUMERROR" try { let th = 1 + 2 if (th == 3) { throw exceptStr } } catch "OTHERERROR" { println("Catched OTHERERROR") } catch exceptStr { println("Catched is SUMERROR") } catch { println("Catched ALL") } finally { println("finally running") } // case-in/case-is let testStr = "123" case testStr in { // in(完全或部分匹配), is(完全匹配) "abc", "mno" { println("testStr is 'abc' or 'mno'") } "def" { println("testStr is 'def'") } `\d+` { println("testStr contains digit") } else { println("testStr not matched") } } let i = [{"a":1, "b":2}, 10] let x = [{"a":1, "b":2},10] case i in { 1, 2 { println("i matched 1, 2") } 3 { println("i matched 3") } x { println("i matched x") } else { println("i not matched anything")} } ``` ### `using`语句 在Monkey中,如果你有一些资源需要释放(release/free/close),例如关闭文件,释放网络连接等等, 你可以使用类似`c#`的`using`语句。 ```swift // 这里,我们使用'using'语句,因此你不必显示调用infile.close()。 // 当'using'语句执行完后,Monkey解析器会隐式调用infile.close()。 using (infile = newFile("./file.demo", "r")) { if (infile == nil) { println("opening 'file.demo' for reading failed, error:", infile.message()) os.exit(1) } let line; let num = 0 //Read file by using extraction operator(">>") while (infile>>line != nil) { num++ printf("%d %s\n", num, line) } } ``` ### 用户自定义操作符 在Monkey中, 你可以自定义一些操作符, 但是你不能覆盖Monkey内置的操作符。 > 注: 并不是所有的操作符都可以自定义。 下面的例子展示了如何使用自定义操作符: ```swift //中缀运算符'=@'接受两个参数 fn =@(x, y) { return x + y * y } //前缀运算符'=^'仅接受一个参数 fn =^(x) { return -x } let pp = 10 =@ 5 // 使用用户自定义的中缀运算符'=@' printf("pp=%d\n", pp) // 结果: pp=35 let hh = =^10 // 使用用户自定义的前缀运算符'=^' printf("hh=%d\n", hh) // 结果: hh=-10 ``` ```swift fn .^(x, y) { arr = [] while x <= y { arr += x x += 2 } return arr } let pp = 10.^20 printf("pp=%v\n", pp) // result: pp=[10, 12, 14, 16, 18, 20] ``` 下面的表格列出了Monkey内置的运算符和用户可以自定义的运算符: <table> <tr> <th>内置运算符</td> <th>用户自定义运算符</td> </tr> <tr> <td>==<br/>=~<br/>=></td> <td>=X</td> </tr> <tr> <td>++<br/>+=</td> <td>+X</td> </tr> <tr> <td>--<br/>-=<br/>-></td> <td>-X</td> </tr> <tr> <td>&gt;=<br/>&lt;&gt;</td> <td>&gt;X</td> </tr> <tr> <td>&lt;=<br/>&lt;&lt;</td> <td>&lt;X</td> </tr> <tr> <td>!=<br/>!~</td> <td>!X</td> </tr> <tr> <td>*=<br/>**</td> <td>*X</td> </tr> <tr> <td>..<br/>..</td> <td>.X</td> </tr> <tr> <td>&amp;=<br/>&amp;&amp;</td> <td>&amp;X</td> </tr> <tr> <td>|=<br/>||</td> <td>|X</td> </tr> <tr> <td>^=</td> <td>^X</td> </tr> </table> > 在上面的表格中,`X`可以是`.=+-*/%&,|^~<,>},!?@#$`。 ### 整型(Integer) 在Monkey中,整型也是一个对象。因此,你可以调用这个对象的方法。请看下面的例子: ```swift x = (-1).next() println(x) //0 x = -1.next() //equals 'x = -(1.next()) println(x) //-2 x = (-1).prev() println(x) //-2 x = -1.prev() //equals 'x = -(1.prev()) println(x) //0 x = [i for i in 10.upto(15)] println(x) //[10, 11, 12, 13, 14, 15] for i in 10.downto(5) { print(i, "") //10 9 8 7 6 5 } println() if 10.isEven() { println("10 is even") } if 9.isOdd() { println("9 is odd") } ``` ### 浮点型(Float) 在Monkey中,浮点型也是一个对象。因此,你可以调用这个对象的方法。请看下面的例子: ```swift f0 = 15.20 println(f0) f1 = 15.20.ceil() println(f1) f2 = 15.20.floor() println(f2) ``` ### Decimal类型 在Monkey中,Decimal类型表示一个任意精度固定位数的十进数(Arbitrary-precision fixed-point decimal numbers). 这个类型的代码主要是基于[decimal](https://github.com/shopspring/decimal). 请看下面的例子: ```swift d1 = decimal.fromString("123.45678901234567") //从字符串创建Decimal类型 d2 = decimal.fromFloat(3) //从浮点型创建Decimal类型 //设置除法精度(division precision). //注意: 这个操作将会影响所有后续对Decimal类型的运算 decimal.setDivisionPrecision(50) fmt.println("123.45678901234567/3 = ", d1.div(d2)) //打印 d1/d2 fmt.println(d1.div(d2)) //效果同上 fmt.println(decimal.fromString("123.456").trunc(2)) //将字符串转换为decimal d3=decimal("123.45678901234567") fmt.println(d3) fmt.println("123.45678901234567/3 = ", d3.div(d2)) ``` ### 数组(Array) 在Monkey中, 你可以使用[]来初始化一个空的数组: ```swift emptyArr = [] emptyArr[3] = 3 //将会自动扩容 println(emptyArr) ``` 你可以使用两种方式来创建一个给定长度的数组: ```swift //创建一个有10个元素的数组(默认值为nil) //Note: this only support integer literal. let arr = []10 println(arr) //使用内置'newArray'方法. let anotherArr = newArray(len(arr)) println(anotherArr) println(anotherArr) //结果: [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil] let arr1 = ["1","a5","5", "5b","4","cc", "7", "dd", "9"] let arr2 = newArray(6, arr1, 10, 11, 12) //第一个参数为数组size println(arr2) //结果: ["1", "a5", "5", "5b", "4", "cc", "7", "dd", "9", 10, 11, 12] let arr3 = newArray(20, arr1, 10, 11, 12) println(arr3) //结果 : ["1", "a5", "5", "5b", "4", "cc", "7", "dd", "9", 10, 11, 12, nil, nil, nil, nil, nil, nil, nil, nil] ``` 数组可以包含任意数据类型的元素。 ```swift mixedArr = [1, 2.5, "Hello", ["Another", "Array"], {"Name":"HHF", "SEX":"Male"}] ``` 注: 最后关闭方括弧(']')前的逗号(',’)是可以省略的。 你可以使用索引来访问数组元素。 ```swift println('mixedArr[2]={mixedArr[2]}') println(["a", "b", "c", "d"][2]) ``` 因为数组是一个对象, 因此你可以使用对象方法来操作它。 ```swift if ([].empty()) { println("array is empty") } emptyArr.push("Hello") println(emptyArr) //你可以使用'加算(+=)'的方式来向数组中添加一个元素: emptyArr += 2 println(emptyArr) //你还可以使用`<<(插入操作符)`的方式来向数组中添加一个元素,插入操作符支持链式操作。 emptyArr << 2 << 3 println(emptyArr) ``` 可以使用`for`循环来遍历一个数组。 ```swift numArr = [1,3,5,2,4,6,7,8,9] for item in numArr where item % 2 == 0 { println(item) } let strArr = ["1","a5","5", "5b","4","cc", "7", "dd", "9"] for item in strArr where /^\d+/.match(item) { println(item) } for item in ["a", "b", "c", "d"] where $_ % 2 == 0 { //$_是索引 printf("idx=%d, v=%s\n", $_, item) } ``` 你可以使用内置函数`reverse`来反转数组元素: ```swift let arr = [1,3,5,2,4,6,7,8,9] println("Source Array =", arr) revArr = reverse(arr) println("Reverse Array =", revArr) ``` 数组还支持使用`数组乘法运算符`(*): ```swift let arr = [3,4] * 3 println(arr) // 结果: [3,4,3,4,3,4] ``` ### 字符串(String) 在monkey中, 有三种类型的`string`: * 原生字符串(可包含`\n`) * 双引号字符串(不可包含`\n`) * 单引号字符串(可解析字符串) 原生字符串是一系列字符序列。使用反引号(``)来表示. 在原生字符串中,除了不能使用反引号外,你可以使用其它的任意字符。 请看下面的例子: ```swift normalStr = "Hello " + "world!" println(normalStr) println("123456"[2]) rawStr = `Welcome to visit us!` println(rawStr) //当你希望一个变量在字符串中也能够被解析时,你可以使用单引号。 //需要被解析的字符串放在花括号('{}')中: str = "Hello world" println('str={str}') //输出: "Hello world" str[6]="W" println('str={str}') //输出: "Hello World" ``` 在monkey中, 字符串是utf8编码的, 这说明你可以使用utf8编码的字符作为变量名: ```swift 三 = 3 五 = 5 println(三 + 五) //输出 : 8 ``` 字符串也是对象,你可以使用`strings`模块中的方法来操作字符串: ```swift upperStr = "hello world".upper() println(upperStr) //输出 : HELLO WORLD ``` 字符串也可以被遍历: ```swift for idx, v in "abcd" { printf("idx=%d, v=%s\n", idx, v) } for v in "Hello World" { printf("idx=%d, v=%s\n", $_, v) //$_是索引 } ``` 你可以连接一个对象到字符串: ```swift joinedStr = "Hello " + "World" joinedStr += "!" println(joinedStr) ``` 你还可以使用内置函数`reverse`来反转字符串: ```swift let str = "Hello world!" println("Source Str =", str) revStr = reverse(str) println("Reverse str =", revStr) ``` 如果你希望将一个包含数字的字符串转换为数字,你可以在字符串之前加入"+“号,将此字符串转换为数字: ```swift a = +"121314" // a是一个整数 println(a) // 结果:121314 // 整数支持"0x"(十六进制), "0b"(二进制), "0o"(八进制)前缀 a = +"0x10" // a是一个整数 println(a) // 结果:16 a = +"121314.6789" // a是一个浮点数 println(a) // 结果:121314.6789 ``` ### 哈希(Hash) 在monkey中,哈希默认会保持Key的插入顺序,类似Python的orderedDict. 你可以使用{}来创建一个空的哈希: ```swift emptyHash = {} emptyHash["key1"] = "value1" println(emptyHash) ``` 哈希的键(key)可以是字符串(string),整型(int)或布尔型(boolean): ```swift hashObj = { 12 : "twelve", true : 1, "Name" : "HHF" } hash["age"] = 12 // same as hash.age = 12 println(hashObj) ``` 注: 最后关闭花括弧('}')前的逗号(',’)是可以省略的。 你还可以使用'+'或'-'来从一个哈希中增加或者删除一个元素: ```swift hashObj += {"key1" : "value1"} hashObj += {"key2" : "value2"} hashObj += {5 : "five"} hashObj -= "key2" hashObj -= 5 println(hash) ``` 哈希也是一个对象,你可以使用`hash`模块中的方法来操作哈希: ```swift hashObj.push(15, "fifteen") //第一个参数是键,第二个参数是值 hashObj.pop(15) keys = hashObj.keys() println(keys) values = hashObj.values() println(values) ``` 你还可以使用内置函数`reverse`来反转哈希的key和value: ```swift let hs = {"key1":12, "key2":"HHF", "key3":false} println("Source Hash =", hs) revHash = reverse(hs) println("Reverse Hash =", revHash) ``` ### 元祖(Tuple) 在Monkey中, `tuple`与数组非常类似, 但一旦你创建了一个元祖,你就不能够更改它。 Tuples使用括号来创建: ```swift //创建一个空元祖 let t1 = tuple() //效果同上 let t2 = () // 创建仅有一个元素的元祖. // 注意: 结尾的","是必须的,否则将会被解析为(1), 而不是元祖 let t3 = (1,) //创建有两个元素的元祖 let t4 = (2,3) ``` 你可以使用内置函数`tuple`,将任何类型的对象装换为元祖。 ```swift let t = tuple("hello") println(t) // 结果: ("hello") ``` 类似于数组, 元祖也可以被索引(indexed),或切片(sliced)。 索引表达式`tuple[i]`返回第i个索引位置的元祖元素, 切片表达式 tuple[i:j]返回一个子元祖. ```swift let t = (1,2,3)[2] print(t) // result:3 ``` 元祖还可以被遍历(类似数组),所以元祖可以使用在for循环中,用在 列表推导中。 ```swift //for循环 for i in (1,2,3) { println(i) } //元祖推导(comprehension) let t1 = [x+1 for x in (2,4,6)] println(t1) //result: [3, 5, 7]. 注意: 结果是数组,不是元祖 ``` 与数组不同,元祖不能够被修改。但是元祖内部的可变元素是可以被修改的. ```swift arr1 = [1,2,3] t = (0, arr1, 5, 6) println(t) // 结果: (0, [1, 2, 3], 5, 6) arr1.push(4) println(t) //结果: (0, [1, 2, 3, 4], 5, 6) ``` 元祖也可以用作哈希的键。 ```swift key1=(1,2,3) key2=(2,3,4) let ht = {key1 : 10, key2 : 20} println(ht[key1]) // result: 10 println(ht[key2]) // result: 20 ``` 元祖可以使用`+`来连接,它会创建一个新的元祖。 ```swift let t = (1, 2) + (3, 4) println(t) // 结果: (1, 2, 3, 4) ``` 如果将元祖用在布尔环境中,那么如果元祖的元素数量大于0, 那么返回结果是true。 ```swift let t = (1,) if t { println("t is not empty!") } else { println("t is empty!") } //结果 : "t is not empty!" ``` 元祖的json序列化(反序列化)的结果都为数组,而不是元祖 ```swift let tupleJson = ("key1","key2") let tupleStr = json.marshal(tupleJson) //结果: [ // "key1", // "key2", // ] println(json.indent(tupleStr, " ")) let tupleJson1 = json.unmarshal(tupleStr) println(tupleJson1) //结果: ["key1", "key2"] ``` 元祖与一个数组相加,返回结果为一个数组,而不是元祖. ```swift t2 = (1,2,3) + [4,5,6] println(t2) // 结果: [(1, 2, 3), 4, 5, 6] ``` 你也可以使用内置函数`reverse`来反转元祖中的元素: ```swift let tp = (1,3,5,2,4,6,7,8,9) println(tp) //结果: (1, 3, 5, 2, 4, 6, 7, 8, 9) revTuple = reverse(tp) println(revTuple) //结果: (9, 8, 7, 6, 4, 2, 5, 3, 1) ``` ### 类 Monkey支持简单的面向对象编程, 下面列出了Mokey支持的特性: * 继承和多态 * 操作符重载 * 属性(getter和setter) * 静态变量/方法/属性 * 索引器 * 类类别(类似Objective-c的Category) * 注解(类似java的annotation) * 类的构造器方法和类的普通方法支持多参数和默认参数 monkey解析器(parser)能够正确的处理关键字`public`, `private`, `protected`, 但是解释器(evaluator)会忽略这些。 也就是说,monkey现在暂时不支持访问限定。 你可以使用`class`关键字来声明一个类,使用`new Class(xxx)`来创建一个类的实例。 ```swift class Animal { let name = "" fn init(name) { //'init'是构造方法 //do somthing } } ``` 在monkey中,所有的类都继承于`object`根类。`object`根类包含几个所有类的共通方法。比如`toString()`, `instanceOf()`, `is_a()`, `classOf()`, `hashCode`。 `instanceOf()`等价于`is_a()` 下面的代码和上面的代码等价: ```swift class Animal : object { let name = "" fn init(name) { //'init'是构造方法 //do somthing } } ``` #### 继承和多态 你使用`:`来表示继承关系: ```swift class Dog : Animal { //Dog类继承于Animal类 } ``` 在子类中,你可以使用`parent`来访问基类的方法和字段。 请看下面的例子: ```swift class Animal { let Name; fn MakeNoise() { println("generic noise") } fn ToString() { return "oooooooo" } } class Cat : Animal { fn init(name) { this.Name = name } fn MakeNoise() { println("Meow") } fn ToString() { return Name + " cat" } } class Dog : Animal { fn init(name) { this.Name = name } fn MakeNoise() { println("Woof!") } fn ToString() { return Name + " dog" } fn OnlyDogMethod() { println("secret dog only method") } } cat = new Cat("pearl") dog = new Dog("cole") randomAnimal = new Animal() animals = [cat, dog, randomAnimal] for animal in animals { println("Animal name: " + animal.Name) animal.MakeNoise() println(animal.ToString()) if is_a(animal, "Dog") { animal.OnlyDogMethod() } } ``` 运行结果如下: ``` Animal name: pearl Meow pearl cat Animal name: cole Woof! cole dog secret dog only method Animal name: nil generic noise oooooooo ``` #### 操作符重载 ```swift class Vector { let x = 0; let y = 0; // 构造函数 fn init (a, b, c) { if (!a) { a = 0;} if (!b) {b = 0;} x = a; y = b } fn +(v) { //重载'+' if (type(v) == "INTEGER" { return new Vector(x + v, y + v); } elseif v.is_a(Vector) { return new Vector(x + v.x, y + v.y); } return nil; } fn String() { return fmt.sprintf("(%v),(%v)", this.x, this.y); } } fn Vectormain() { v1 = new Vector(1,2); v2 = new Vector(4,5); // 下面的代码会调用Vector对象的'+'方法 v3 = v1 + v2 //等价于'v3 = v1.+(v2)' // 返回"(5),(7)" println(v3.String()); v4 = v1 + 10 //等价于v4 = v1.+(10); //返回"(11),(12)" println(v4.String()); } Vectormain() ``` #### 属性(类似C#) ```swift class Date { let month = 7; // Backing store property Month { get { return month } set { if ((value > 0) && (value < 13)) { month = value } else { println("BAD, month is invalid") } } } property Year; //与'property Year { get; set;}'等价 property Day { get; } property OtherInfo1 { get; } property OtherInfo2 { set; } fn init(year, month, day) { this.Year = year this.Month = month this.Day = day } fn getDateInfo() { printf("Year:%v, Month:%v, Day:%v\n", this.Year, this.Month, this.Day) //note here, you need to use 'this.Property', not 'Property' } } dateObj = new Date(2000, 5, 11) //printf("Calling Date's getter, month=%d\n", dateObj.Month) dateObj.getDateInfo() println() dateObj.Month = 10 printf("dateObj.Month=%d\n", dateObj.Month) dateObj.Year = 2018 println() dateObj.getDateInfo() //下面的代码会报错,因为OtherInfo1是个只读属性 //dateObj.OtherInfo1 = "Other Date Info" //println(dateObj.OtherInfo1) //下面的代码会报错,因为OtherInfo2是个只写属性 //dateObj.OtherInfo2 = "Other Date Info2" //println(dateObj.OtherInfo2) //下面的代码会报错,因为Day属性是个只读属性 //dateObj.Day = 18 ``` #### 索引器 Monkey还支持类似C#的索引器(`Indexer`)。 索引器能够让你像访问数组一样访问对象。 索引器使用如下的方式声明: 使用`property this[parameter]`方式来声明一个索引器。 ```swift property this[index] { get { xxx } set { xxx } } ``` 请看下面的代码: ```swift class IndexedNames { let namelist = [] let size = 10 fn init() { let i = 0 for (i = 0; i < size; i++) { namelist[i] = "N. A." } } fn getNameList() { println(namelist) } property this[index] { get { let tmp; if ( index >= 0 && index <= size - 1 ) { tmp = namelist[index] } else { tmp = "" } return tmp } set { if ( index >= 0 && index <= size-1 ) { namelist[index] = value } } } } fn Main() { namesObj = new IndexedNames() //下面的代码会调用索引器的setter方法 namesObj[0] = "Zara" namesObj[1] = "Riz" namesObj[2] = "Nuha" namesObj[3] = "Asif" namesObj[4] = "Davinder" namesObj[5] = "Sunil" namesObj[6] = "Rubic" namesObj.getNameList() for (i = 0; i < namesObj.size; i++) { println(namesObj[i]) //调用索引器的getter方法 } } Main() ``` #### 静态变量/方法/属性 ```swift class Test { static let x = 0; static let y = 5; static fn Main() { println(Test.x); println(Test.y); Test.x = 99; println(Test.x); } } Test.Main() ``` 注:非静态变量/方法/属性可以访问静态变量/方法/属性。 但是反过来不行。 #### 类类别(class category) Monkey支持类似objective-c的类别(C#中称为extension methods)。 ```swift class Animal { fn Walk() { println("Animal Walk!") } } //类类别 like objective-c class Animal (Run) { //建立一个Animal的Run类别. fn Run() { println("Animal Run!") this.Walk() //可以调用Animal类的Walk()方法. } } animal = new Animal() animal.Walk() println() animal.Run() ``` #### 注解 Monkey也支持非常简单的“注解”: * 仅支持类的属性和方法的注解(不支持类自身的注解,也不支持普通方法的注解) * 注解类的声明中,仅支持属性,不支持方法 * 使用注解时,你必须创建一个相应的对象 使用`class @annotationName {}`的方式来声明一个注解。 Monkey同时包含几个内置的注解: * @Override(作用类似于java的@Override)。 * @NotNull * @NotEmpty 请看下面的例子: ```swift //声明注解,注解的body中必须是属性,不能是方法 class @MinMaxValidator { property MinLength property MaxLength default 10 //Same as 'property MaxLength = 10' } //Marker annotation class @NoSpaceValidator {} class @DepartmentValidator { property Department } //这个是请求类,我们对这个类使用注解 class Request { @MinMaxValidator(MinLength=1) property FirstName; //默认可读可写(getter和setter),等价于'property FirstName {get; set;}' @NoSpaceValidator property LastName; @DepartmentValidator(Department=["Department of Education", "Department of Labors", "Department of Justice"]) property Dept; } //处理注解的类 class RequestHandler { static fn handle(o) { props = o.getProperties() for p in props { annos = p.getAnnotations() for anno in annos { if anno.instanceOf(MinMaxValidator) { //p.value表示属性的值 if len(p.value) > anno.MaxLength || len(p.value) < anno.MinLength { printf("Property '%s' is not valid!\n", p.name) } } elseif anno.instanceOf(NoSpaceValidator) { for c in p.value { if c == " " || c == "\t" { printf("Property '%s' is not valid!\n", p.name) break } } } elseif anno.instanceOf(DepartmentValidator) { found = false for d in anno.Department { if p.value == d { found = true } } if !found { printf("Property '%s' is not valid!\n", p.name) } } } } } } class RequestMain { static fn main() { request = new Request(); request.FirstName = "Haifeng123456789" request.LastName = "Huang " request.Dept = "Department of Justice" RequestHandler.handle(request); } } RequestMain.main() ``` 下面是处理结果: ``` Property 'FirstName' not valid! Property 'LastName' not valid! ``` ### 标准输入/输出/错误 Monkey中预定义了下面三个对象: `stdin`, `stdout`, `stderr`。分别代表标准输入,标准输出,标准错误。 ```swift stdout.writeLine("Hello world") //和上面效果一样 fmt.fprintf(stdout, "Hello world\n") print("Please type your name:") name = stdin.read(1024) //从标准输入读最多1024字节 println("Your name is " + name) ``` 你还可以使用类似C++的插入操作符(`<<`)和提取操作符(`>>`)来操作标准输入和输出。 ```swift // Output to stdout by using insertion operator("<<") // 'endl' is a predefined object, which is "\n". stdout << "hello " << "world!" << " How are you?" << endl; // Read from stdin by using extraction operator(">>") let name; stdout << "Your name please: "; stdin >> name; printf("Welcome, name=%v\n", name) ``` 插入操作符(`<<`)和提取操作符(`>>`)同样适用于文件操作。 ```swift //Read file by using extraction operator(">>") infile = newFile("./file.demo", "r") if (infile == nil) { println("opening 'file.demo' for reading failed, error:", infile.message()) os.exit(1) } let line; let num = 0 while ( infile>>line != nil) { num++ printf("%d %s\n", num, line) } infile.close() //Writing to file by using inserttion operator("<<") outfile = newFile("./outfile.demo", "w") if (outfile == nil) { println("opening 'outfile.demo' for writing failed, error:", outfile.message()) os.exit(1) } outfile << "Hello" << endl outfile << "world" << endl outfile.close() ``` ### 标准库中的错误处理 当标准库中的函数返回`nil`或者`false`的时候,你可以使用它们的`message()`方法类获取错误信息: ```swift file = newFile(filename, "r") if (file == nil) { println("opening ", filename, "for reading failed, error:", file.message()) } //操作文件 //... //关闭文件 file.close() let ret = http.listenAndServe("127.0.0.1:9090") if (ret == false) { println("listenAndServe failed, error:", ret.message()) } ``` 也许你会觉得奇怪,为什么`nil`或`false`有`message()`方法? 因为在monkey中, `nil`和`false`两个都是对象,因此它们都有方法。 ### 关于`defer`关键字 `defer`语句推迟(defer)某个函数的执行直到函数返回。 ```swift let add = fn(x,y){ defer println("I'm defer1") println("I'm in add") defer println("I'm defer2") return x + y } println(add(2,2)) ``` 结果如下: ```sh I'm in add I'm defer2 I'm defer1 4 ``` ### 不同类型的联接 Monkey中,你可以联接不同的类型。请看下面的例子: ```swift // Number plus assignment num = 10 num += 10 + 15.6 num += 20 println(num) // String plus assignment str = "Hello " str += "world! " str += [1, 2, 3] println(str) // Array plus assignment arr = [] arr += 1 arr += 10.5 arr += [1, 2, 3] arr += {"key":"value"} println(arr) // Array compare arr1 = [1, 10.5, [1, 2, 3], {"key" : "value"}] println(arr1) if arr == arr1 { //support ARRAY compare println("arr1 = arr") } else { println("arr1 != arr") } // Hash assignment("+=", "-=") hash = {} hash += {"key1" : "value1"} hash += {"key2" : "value2"} hash += {5 : "five"} println(hash) hash -= "key2" hash -= 5 println(hash) ``` ### 列表推导(Comprehensions) Monkey支持列表推导(列表可以为数组,字符串,Range,Tuple, 哈希)。 列表推导的返回值均为数组。请看下面的例子: ```swift //数组 x = [[word.upper(), word.lower(), word.title()] for word in ["hello", "world", "good", "morning"]] println(x) //结果:[["HELLO", "hello", "Hello"], ["WORLD", "world", "World"], ["GOOD", "good", "Good"], ["MORNING", "morning", "Morning"]] //字符串 y = [ c.upper() for c in "huanghaifeng" where $_ % 2 != 0] //$_ is the index println(y) //结果:["U", "N", "H", "I", "E", "G"] //范围 w = [i + 1 for i in 1..10] println(w) //结果:[2, 3, 4, 5, 6, 7, 8, 9, 10, 11] //tuple v = [x+1 for x in (12,34,56)] println(v) //结果:[13, 35, 57] //哈希 z = [v * 10 for k,v in {"key1":10, "key2":20, "key3":30}] println(z) //结果:[100, 200, 300] ``` Monkey同时也支持哈希推导。 哈希推导的返回值均为哈希。请看下面的例子: ```swift //哈希推导 (from hash) z1 = { v:k for k,v in {"key1":10, "key2":20, "key3":30}} //reverse key-value pair println(z1) // 结果: {10 : "key1", 20 : "key2", 30 : "key3"}, 顺序可能不同 //哈希推导 (from array) z2 = {x:x**2 for x in [1,2,3]} println(z2) // 结果: {1 : 1, 2 : 4, 3 : 9}, 顺序可能不同 //哈希推导 (from .. range) z3 = {x:x**2 for x in 5..7} println(z3) // 结果: {5 : 25, 6 : 36, 7 : 49}, 顺序可能不同 //哈希推导 (from string) z4 = {x:x.upper() for x in "hi"} println(z4) // 结果: {"h" : "H", "i" : "I"}, 顺序可能不同 //哈希推导 (from tuple) z5 = {x+1:x+2 for x in (1,2,3)} println(z5) // 结果: {4 : 5, 2 : 3, 3 : 4}, 顺序可能不同 ``` ### Grep和map `grep`和`map`类似于perl的`grep`和`map`. ```swift let sourceArr = [2,4,6,8,10,12] //$_表示每次循环取得的值 let m = grep $_ > 5, sourceArr //对每一个sourceArr中的元素,仅返回">5"的元素 println('m is {m}') let cp = map $_ * 2 , sourceArr //将每个元素乘以2 println('cp is {cp}') //一个复杂一点的例子 let fields = { "animal" : "dog", "building" : "house", "colour" : "red", "fruit" : "apple" } let pattern = `animal|fruit` // =~(匹配), !~(不匹配) let values = map { fields[$_] } grep { $_ =~ pattern } fields.keys() println(values) ``` ### 函数 在Monkey中,函数和别的基础类型一样,能够作为函数的参数,作为函数的返回值 函数还可以有缺省参数和可变参数。 ```swift //define a function let add = fn() { [5,6] } let n = [1, 2] + [3, 4] + add() println(n) let complex = { "add" : fn(x, y) { return fn(z) {x + y + z } }, //function with closure "sub" : fn(x, y) { x - y }, "other" : [1,2,3,4] } println(complex["add"](1, 2)(3)) println(complex["sub"](10, 2)) println(complex["other"][2]) let warr = [1+1, 3, fn(x) { x + 1}(2),"abc","def"] println(warr) println("\nfor i in 5..1 where i > 2 :") for i in fn(x){ x+1 }(4)..fn(x){ x+1 }(0) where i > 2 { if (i == 3) { continue } println('i={i}') } // 缺省参数和可变参数 add = fn (x, y=5, z=7, args...) { w = x + y + z for i in args { w += i } return w } w = add(2,3,4,5,6,7) println(w) ``` 你也可以像下面这样创建一个命名函数: ```swift fn sub(x,y=2) { return x - y } println(sub(10)) //结果 : 8 ``` 你还可以使用`胖箭头(fat arraw)`语法来创建一个匿名函数: ```swift let x = () => 5 + 5 println(x()) //结果: 10 let y = (x) => x * 5 println(y(2)) //结果: 10 let z = (x,y) => x * y + 5 println(z(3,4)) //结果 :17 let add = fn (x, factor) { x + factor(x) } result = add(5, (x) => x * 2) println(result) //结果 : 15 ``` 如果函数没有参数,你可以省略()。例如 ```swift println("hhf".upper) //结果: "HHF" //和上面结果一样 println("hhf".upper()) ``` Monkey5.0之前,函数不支持多个返回值, 但有很多方法可以达到目的. 下面是其中的一种实现方式: ```swift fn div(x, y) { if y == 0 { return [nil, "y could not be zero"] } return [x/y, ""] } ret = div(10,5) if ret[1] != "" { println(ret[1]) } else { println(ret[0]) } ``` 从版本5.0开始,Monkey可以使用let语句支持函数返回多个值。 返回的多个值被包装为一个元祖(tuple)。 ```swift fn testReturn(a, b, c, d=40) { return a, b, c, d } let (x, y, c, d) = testReturn(10, 20, 30) // let x, y, c, d = testReturn(10, 20, 30) same as above printf("x=%v, y=%v, c=%v, d=%v\n", x, y, c, d) //Result: x=10, y=20, c=30, d=40 ``` 注:必须使用`let`才能够支持支持函数的多个返回值,下面的语句无法通过编译。 ```swift (x, y, c, d) = testReturn(10, 20, 30) // no 'let', compile error x, y, c, d = testReturn(10, 20, 30) // no 'let', compile error ``` ### Pipe操作符 `pipe`操作符来自[Elixir](https://elixir-lang.org/). ```swift # Test pipe operator(|>) x = ["hello", "world"] |> strings.join(" ") |> strings.upper() |> strings.lower() |> strings.title() printf("x=<%s>\n", x) let add = fn(x,y) { return x + y } let pow = fn(x) { return x ** 2} let subtract = fn(x) { return x - 1} let mm = add(1,2) |> pow() |> subtract() printf("mm=%d\n", mm) "Hello %s!\n" |> fmt.printf("world") ``` ### Spawn 和 channel 你可以使用`spawn`来创建一个新的线程, `chan`来和这个线程进行交互. ```swift let aChan = chan() spawn fn() { let message = aChan.recv() println('channel received message=<{message}>') }() //发送信息到线程 aChan.send("Hello Channel!") ``` 使用channel和spawn的组合,你可以实现lazy evaluation(延迟执行): ```swift // XRange is an iterator over all the numbers from 0 to the limit. fn XRange(limit) { ch = chan() spawn fn() { //for (i = 0; i <= limit; i++) // 警告: 务必不要使用此种类型的for循环,否则得到的结果不会是你希望的 for i in 0..limit { ch.send(i) } // 确保循环终了的时候,channel被正常关闭! ch.close() }() return ch } for i in XRange(10) { fmt.println(i) } ``` ## 使用`go`语言模块 Monkey提供了引入`go`语言模块的功能(实验性)。 如果你需要使用`go`语言的package函数或类型,你首先需要使用`RegisterFunctions'或`RegisterVars` 来注册`go`语言的方法或类型到Monkey语言中。 下面是`main.go`中的例子(节选): ```swift // 因为Monkey语言中,已经提供了内置模块`fmt`, 因此这里我们使用`gfmt`作为名字。 eval.RegisterFunctions("gfmt", []interface{}{ fmt.Errorf, fmt.Println, fmt.Print, fmt.Printf, fmt.Fprint, fmt.Fprint, fmt.Fprintln, fmt.Fscan, fmt.Fscanf, fmt.Fscanln, fmt.Scan, fmt.Scanf, fmt.Scanln, fmt.Sscan, fmt.Sscanf, fmt.Sscanln, fmt.Sprint, fmt.Sprintf, fmt.Sprintln, }) eval.RegisterFunctions("io/ioutil", []interface{}{ ioutil.WriteFile, ioutil.ReadFile, ioutil.TempDir, ioutil.TempFile, ioutil.ReadAll, ioutil.ReadDir, ioutil.NopCloser, }) eval.Eval(program, scope) ``` 接下来, 在你的Monkey文件中,像下面这样使用导入的方法: ```swift gfmt.Printf("Hello %s!\n", "go function"); //注意: 这里需要使用'io_ioutil', 而不是'io/ioutil'。 let files, err = io_ioutil.ReadDir(".") if err != nil { gfmt.Println(err) } for file in files { if file.Name() == ".git" { continue } gfmt.Printf("Name=%s, Size=%d\n", file.Name(), file.Size()) } ``` 更详细的例子请参照`goObj.my`。 ## 标准模块介绍 Monkey中,预定义了一些标准模块,例如:json, sql, sort, fmt, os, logger, time, flag, net, http等等。 下面是对monkey的标准模块的一个简短的描述。 ### fmt 模块 ```swift let i, f, b, s, aArr, aHash = 108, 25.383, true, "Hello, world", [1, 2, 3, 4, "a", "b"], { "key1" : 1, "key2" : 2, "key3" : "abc"} //使用 '%v (value)' 来打印变量值, '%_' 来打印变量类型 fmt.printf("i=[%05d, %X], b=[%t], f=[%.5f], s=[%-15s], aArr=%v, aHash=%v\n", i, i, b, f, s, aArr, aHash) fmt.printf("i=[%_], b=[%t], f=[%f], aArr=%_, aHash=%_, s=[%s] \n", i, b, f, aArr, aHash, s) sp = fmt.sprintf("i=[%05d, %X], b=[%t], f=[%.5f], s=[%-15s]\n", i, i, b, f, s) fmt.printf("sp=%s", sp) fmt.fprintf(stdout, "Hello %s\n", "world") ``` ### time 模块 ```swift t1 = newTime() format = t1.strftime("%F %R") println(t1.toStr(format)) Epoch = t1.toEpoch() println(Epoch) t2 = t1.fromEpoch(Epoch) println(t2.toStr(format)) ``` ### logger 模块 ```swift #输出到标准输出(stdout) log = newLogger(stdout, "LOGGER-", logger.LSTDFLAGS | logger.LMICROSECONDS) log.printf("Hello, %s\n", "logger") fmt.printf("Logger: flags =<%d>, prefix=<%s>\n", log.flags(), log.prefix()) //输出到文件 file = newFile("./logger.log", "a+") log.setOutput(file) for i in 1..5 { log.printf("This is <%d>\n", i) } file.close() //别忘记关闭文件 ``` ### flag 模块(处理命令行选项) ```swift let verV = flag.bool("version", false, "0.1") let ageV = flag.int("age", 40, "an int") let heightV = flag.float("height", 120.5, "a float") let nameV = flag.string("name", "HuangHaiFeng", "a string") let hobbiesV = flag.string("hobbies", "1,2,3", "a comma-delimited string") flag.parse() println("verV = ", verV) println("ageV = ", ageV) println("heightV = ", heightV) println("nameV = ", nameV) println("hobbies = ", hobbiesV.split(",")) if (flag.isSet("age")) { println("age is set") } else { println("age is not set") } ``` ### json 模块( json序列化(marshal)和反序列化(unmarshal) ) ```swift let hsJson = {"key1" : 10, "key2" : "Hello Json %s %s Module", "key3" : 15.8912, "key4" : [1,2,3.5, "Hello"], "key5" : true, "key6" : {"subkey1":12, "subkey2":"Json"}, "key7" : fn(x,y){x+y}(1,2) } let hashStr = json.marshal(hsJson) //也可以使用 `json.toJson(hsJson)` println(json.indent(hashStr, " ")) let hsJson1 = json.unmarshal(hashStr) println(hsJson1) let arrJson = [1,2.3,"HHF",[],{ "key" :10, "key1" :11}] let arrStr = json.marshal(arrJson) println(json.indent(arrStr)) let arr1Json = json.unmarshal(arrStr) //也可以使用 `json.fromJson(arrStr)` println(arr1Json) ``` ### net 模块 ```swift //简单的TCP客户端 let conn = dialTCP("tcp", "127.0.0.1:9090") if (conn == nil) { println("dailTCP failed, error:", conn.message()) os.exit(1) } let n = conn.write("Hello server, I'm client") if (n == nil) { println("conn write failed, error:", n.message()) os.exit(1) } let ret = conn.close() if (ret == false) { println("Server close failed, error:", ret.message()) } //一个简单的TCP服务端 let ln = listenTCP("tcp", ":9090") for { let conn = ln.acceptTCP() if (conn == nil) { println(conn.message()) } else { printf("Accepted client, Address=%s\n", conn.addr()) } spawn fn(conn) { //spawn a thread to handle the connection println(conn.read()) }(conn) } //end for let ret = ln.close() if (ret == false) { println("Server close failed, error:", ret.message()) } ``` ### linq 模块 在Monkey中, `linq`模块支持下面的其中类型的对象: * File对象 (使用内置函数`newFile`创建) * Csv reader对象(使用内置函数`newCsvReader`创建) * String对象 * Array对象 * Tuple对象 * Hash对象 * Channel对象(使用内置函数`chan`创建) ```swift let mm = [1,2,3,4,5,6,7,8,9,10] println('before mm={mm}') result = linq.from(mm).where(fn(x) { x % 2 == 0 }).select(fn(x) { x = x + 2 }).toSlice() println('after result={result}') result = linq.from(mm).where(fn(x) { x % 2 == 0 }).select(fn(x) { x = x + 2 }).last() println('after result={result}') let sortArr = [1,2,3,4,5,6,7,8,9,10] result = linq.from(sortArr).sort(fn(x,y){ return x > y }) println('[1,2,3,4,5,6,7,8,9,10] sort(x>y)={result}') result = linq.from(sortArr).sort(fn(x,y){ return x < y }) println('[1,2,3,4,5,6,7,8,9,10] sort(x<y)={result}') thenByDescendingArr = [ {"Owner" : "Google", "Name" : "Chrome"}, {"Owner" : "Microsoft", "Name" : "Windows"}, {"Owner" : "Google", "Name" : "GMail"}, {"Owner" : "Microsoft", "Name" : "VisualStudio"}, {"Owner" : "Google", "Name" : "GMail"}, {"Owner" : "Microsoft", "Name" : "XBox"}, {"Owner" : "Google", "Name" : "GMail"}, {"Owner" : "Google", "Name" : "AppEngine"}, {"Owner" : "Intel", "Name" : "ParallelStudio"}, {"Owner" : "Intel", "Name" : "VTune"}, {"Owner" : "Microsoft", "Name" : "Office"}, {"Owner" : "Intel", "Name" : "Edison"}, {"Owner" : "Google", "Name" : "GMail"}, {"Owner" : "Microsoft", "Name" : "PowerShell"}, {"Owner" : "Google", "Name" : "GMail"}, {"Owner" : "Google", "Name" : "GDrive"} ] result = linq.from(thenByDescendingArr).orderBy(fn(x) { return x["Owner"] }).thenByDescending(fn(x){ return x["Name"] }).toOrderedSlice() //Note: You need to use toOrderedSlice //use json.indent() for formatting the output let thenByDescendingArrStr = json.marshal(result) println(json.indent(thenByDescendingArrStr, " ")) //测试 'selectManyByIndexed' println() let selectManyByIndexedArr1 = [[1, 2, 3], [4, 5, 6, 7]] result = linq.from(selectManyByIndexedArr1).selectManyByIndexed( fn(idx, x){ if idx == 0 { return linq.from([10, 20, 30]) } return linq.from(x) }, fn(x,y){ return x + 1 }) println('[[1, 2, 3], [4, 5, 6, 7]] selectManyByIndexed() = {result}') let selectManyByIndexedArr2 = ["st", "ng"] result = linq.from(selectManyByIndexedArr2).selectManyByIndexed( fn(idx,x){ if idx == 0 { return linq.from(x + "r") } return linq.from("i" + x) },fn(x,y){ return x + "_" }) println('["st", "ng"] selectManyByIndexed() = {result}') ``` ### Linq for file支持 现在,monkey有了一个支持`linq for file`的功能。这个功能类似awk。 请看下面的代码: ```swift //test: linq for "file" file = newFile("./examples/linqSample.csv", "r") //以读取方式打开linqSample.csv result = linq.from(file,",",fn(line){ //第二个参数为字段分隔符, 第三个参数为注释函数(comment function) if line.trim().hasPrefix("#") { //如果行以'#'开头 return true //返回'true'表示忽略这一行 } else { return false } }).where(fn(fields) { //'fields'是一个哈希数组: // fields = [ // {"line" : LineNo1, "nf" : line1's number of fields, 0 : line1, 1 : field1, 2 : field2, ...}, // {"line" : LineNo2, "nf" : line2's number of fields, 0 : line2, 1 : field1, 2 : field2, ...} // ] int(fields[1]) > 300000 //仅选取第一个字段的值 > 300000 }).sort(fn(field1,field2){ return int(field1[1]) > int(field2[1]) //第一个字段按照降序排列 }).select(fn(fields) { fields[5] //仅输出第五个字段 }) println(result) file.close() //别忘记关闭文件 //another test: linq for "file" file = newFile("./examples/linqSample.csv", "r") //以读取方式打开linqSample.csv result = linq.from(file,",",fn(line){ //第二个参数为字段分隔符, 第三个参数为注释函数(comment function) if line.trim().hasPrefix("#") { //如果行以'#'开头 return true //返回'true'表示忽略这一行 } else { return false } }).where(fn(fields) { int(fields[1]) > 300000 //仅选取第一个字段的值 > 300000 }).sort(fn(field1,field2){ return int(field1[1]) > int(field2[1]) //第一个字段按照降序排列 }).selectMany(fn(fields) { row = [[fields[0]]] //fields[0]为整行数据。 注意:我们需要使用两个[], 否则selectMany()将会flatten输出结果 linq.from(row) //输出整行数据 }) println(result) file.close() //别忘记关闭文件 //test: linq for "csv" r = newCsvReader("./examples/test.csv") //以读取方式打开test.csv r.setOptions({"Comma":";", "Comment":"#"}) result = linq.from(r).where(fn(x) { //The 'x' is an array of hashes, like below: // x = [ // {"nf": line1's number of fields, 1: field1, 2: field2, ...}, // {"nf": line2's number of fields, 1: field1, 2: field2, ...} // ] x[2] == "Pike"//仅选取第二个字段 = "Pike" }).sort(fn(x,y){ return len(x[1]) > len(y[1]) //以第一个字段的长度排序 }) println(result) r.close() //别忘记关闭Reader ``` ### csv 模块 ```swift //测试 csv reader let r = newCsvReader("./examples/test.csv") if r == nil { printf("newCsv returns err, message:%s\n", r.message()) } r.setOptions({"Comma": ";", "Comment": "#"}) ra = r.readAll() if (ra == nil) { printf("readAll returns err, message:%s\n", ra.message()) } for line in ra { println(line) for record in line { println(" ", record) } } r.close() //do not to forget to close the reader //测试 csv writer let ofile = newFile("./examples/demo.csv", "a+") let w = newCsvWriter(ofile) w.setOptions({"Comma": " "}) w.write(["1", "2", "3"]) w.writeAll([["4", "5", "6"],["7", "8", "9"],["10", "11", "12"]]) w.flush() ofile.close() //do not to forget to close the file ``` ### template 模块 `template` 模块包含'text'和'html'模版处理. 使用 `newText(...)` 或者 `parseTextFiles(...)` 来创建一个新的'text'模版。 使用 `newHtml(...)` 或者`parseHtmlFiles(...)` 来创建一个新的'html'模版。 ```swift arr = [ { "key" : "key1", "value" : "value1" }, { "key" : "key2", "value" : "value2" }, { "key" : "key3", "value" : "value3" } ] //使用parseTextFiles(), 来写入一个字符串 template.parseTextFiles("./examples/looping.tmpl").execute(resultValue, arr) println('{resultValue}') //使用parseTextFiles()来写入一个文件 file = newFile("./examples/outTemplate.log", "a+") template.parseTextFiles("./examples/looping.tmpl").execute(file, arr) file.close() //do not to forget to close the file //使用 parse() //注: 我们需要使用"{{-" and "-}}"来移除输出中的回车换行(newline) template.newText("array").parse(`Looping {{- range . }} key={{ .key }}, value={{ .value -}} {{- end }} `).execute(resultValue, arr) println('{resultValue}') ``` ### sql 模块 `sql` 模块提供了一个底层封装来操作数据库。 它可以正确的处理数据库中的null值,虽然没有经过完全的测试。 为了测试`sql`模块, 你需要做以下几个步骤: 1. 下载sql驱动器(sql driver)代码. 2. 将驱动器的包包含到'sql.go'文件中: ```go _ "github.com/mattn/go-sqlite3" ``` 3. 重新编译monkey源码. 下面是一个完整的使用数据库的例子(`examples/db.my`): ```swift let dbOp = fn() { os.remove("./foo.db") //delete `foo.db` file let db = dbOpen("sqlite3", "./foo.db") if (db == nil) { println("DB open failed, error:", db.message()) return false } defer db.close() let sqlStmt = `create table foo (id integer not null primary key, name text);delete from foo;` let exec_ret = db.exec(sqlStmt) if (exec_ret == nil) { println("DB exec failed! error:", exec_ret.message()) return false } let tx = db.begin() if (tx == nil) { println("db.Begin failed!, error:", tx.message()) return false } let stmt = tx.prepare(`insert into foo(id, name) values(?, ?)`) if (stmt == nil) { println("tx.Prepare failed!, error:", stmt.message()) return false } defer stmt.close() let i = 0 for (i = 0; i < 105; i++) { let name = "您好" + i if (i>100) { //插入`null`值. 有七个预定义的null常量:INT_NULL,UINT_NULL,FLOAT_NULL,STRING_NULL,BOOL_NULL,TIME_NULL, DECIMAL_NULL. let rs = stmt.exec(i, sql.STRING_NULL) } else { let rs = stmt.exec(i, name) } if (rs == nil) { println("statement exec failed, error:", rs.message()) return false } } //end for tx.commit() let id, name = 0, "" let rows = db.query("select id, name from foo") if (rows == nil) { println("db queue failed, error:", rows.message()) return false } defer rows.close() while (rows.next()) { rows.scan(id, name) if (name.valid()) { //检查是否为`null` println(id, "|", name) } else { println(id, "|", "null") } } return true } let ret = dbOp() if (ret == nil) { os.exit(1) } os.exit() ``` ## 实用工具 项目还包含了一些使用的工具:`formatter`和`highlighter`。 formatter工具能够格式化monkey语言。 highlighter工具能够语法高亮monkey语言(提供两种输出:命令行和html)。 你也可以将它们合起来使用: ```sh ./fmt xx.my | ./highlight //输出到屏幕(命令行高亮不只是windows) ``` ## 文档生成 Monkey还包含一个命令行工具`mdoc`,可以从Monkey文件的注释生成markdown类型的文档或者HTML文档。 目前仅仅支持以下语句的注释生成: * let语句 * enum语句 * function语句 * class语句 * let语句 * function语句 * property语句 ```sh //生成markdown文件, 生成的文件名为'doc.md' ./mdoc examples/doc.my //生成html文件, 生成的文件名为'doc.html' ./mdoc -html examples/doc.my //生成html文件, 同时生成函数和类的代码,生成的文件名为'doc.html' ./mdoc -html -showsource examples/doc.my //使用内置的css格式修饰html文档 // 0 - GitHub // 1 - Zenburn // 2 - Lake // 3 - Sea Side // 4 - Kimbie Light // 5 - Light Blue // 6 - Atom Dark // 7 - Forgotten Light ./mdoc -html -showsource -css 1 examples/doc.my //使用外部css文件来修饰html文档(优先级高于'-css'选项) //'-cssfile'选项的优先级高于'-css'选项 //如果提供的css文件不存在或者文件读取错误,则使用'-css'选项 ./mdoc -html -showsource -css 1 -cssfile ./examples/github-markdown.css examples/doc.my //遍历examples目录下的所有'.my'的文件,生成html ./mdoc -html examples ``` HTML文档的生成是调用github的REST API,因此必须在网络连接正常的情况下才能够生成HTML文档。 同时,你可能需要设置代理(环境变量:HTTP_PROXY)。 关于生成文档的示例,请参照: * [markdown.md](examples/markdown.md) * [markdown.html](examples/markdown.html) 由于github不能够直接浏览html文档,你可以使用(http://htmlpreview.github.io/)来浏览html文档。 ## 语法高亮 目前,monkey支持以下几种编辑器的语法高亮: 1. vim [vim](misc/vim) 2. emeditor [emeditor](misc/emeditor) 3. notepad++ [notepad++](misc/notepad%2B%2B) 4. Visual Studio Code [VSC](misc/vscode) 5. Sublime Text 3 [Sublime Text 3](misc/SublimeText3) ## 未来计划 下面是对项目的未来计划的描述: * 改进标准库并增加更多的函数. * 写更多的测试代码! ## 许可证 MIT ## 备注 如果你喜欢此项目,请点击下面的链接,多多star,fork。谢谢! [monkey](https://github.com/haifenghuang/monkey)
haifenghuang/monkey
README_cn.md
Markdown
mit
67,164
18.633286
171
0.575139
false
<?php use League\Flysystem\Adapter\Local; use League\Flysystem\Filesystem; use Spatie\Backup\FileHelpers\FileSelector; class FileSelectorTest extends Orchestra\Testbench\TestCase { protected $path; protected $disk; protected $root; protected $testFilesPath; protected $fileSelector; public function setUp() { parent::setUp(); $this->root = realpath('tests/_data/disk/root'); $this->path = 'backups'; $this->testFilesPath = realpath($this->root.'/'.$this->path); //make sure all files in our testdirectory are 5 days old foreach (scandir($this->testFilesPath) as $file) { touch($this->testFilesPath.'/'.$file, time() - (60 * 60 * 24 * 5)); } $this->disk = new Illuminate\Filesystem\FilesystemAdapter(new Filesystem(new Local($this->root))); $this->fileSelector = new FileSelector($this->disk, $this->path); } /** * @test */ public function it_returns_only_files_with_the_specified_extensions() { $oldFiles = $this->fileSelector->getFilesOlderThan(new DateTime(), ['zip']); $this->assertNotEmpty($oldFiles); $this->assertFalse(in_array('MariahCarey.php', $oldFiles)); } /** * @test */ public function it_returns_an_empty_array_if_no_extensions_are_specified() { $oldFiles = $this->fileSelector->getFilesOlderThan(new DateTime(), ['']); $this->assertEmpty($oldFiles); } /** * @test */ public function it_gets_files_older_than_the_given_date() { $testFileName = 'test_it_gets_files_older_than_the_given_date.zip'; touch($this->testFilesPath.'/'.$testFileName, time() - (60 * 60 * 24 * 10) + 60); //create a file that is 10 days and a minute old $oldFiles = $this->fileSelector->getFilesOlderThan((new DateTime())->sub(new DateInterval('P9D')), ['zip']); $this->assertTrue(in_array($this->path.'/'.$testFileName, $oldFiles)); $oldFiles = $this->fileSelector->getFilesOlderThan((new DateTime())->sub(new DateInterval('P10D')), ['zip']); $this->assertFalse(in_array($this->path.'/'.$testFileName, $oldFiles)); $oldFiles = $this->fileSelector->getFilesOlderThan((new DateTime())->sub(new DateInterval('P11D')), ['zip']); $this->assertFalse(in_array($this->path.'/'.$testFileName, $oldFiles)); } /** * @test */ public function it_excludes_files_outside_given_path() { $files = $this->fileSelector->getFilesOlderThan(new DateTime(), ['zip']); touch(realpath('tests/_data/disk/root/TomJones.zip'), time() - (60 * 60 * 24 * 10) + 60); $this->assertFalse(in_array($this->path.'/'.'TomJones.zip', $files)); $this->assertTrue(in_array($this->path.'/'.'test.zip', $files)); } /** * Call artisan command and return code. * * @param string $command * @param array $parameters * * @return int */ public function artisan($command, $parameters = []) { } }
emayk/laravel-backup
tests/fileSelector/FileSelectorTest.php
PHP
mit
3,070
28.519231
138
0.601629
false
var Handler, MiniEventEmitter; Handler = require("./handler"); MiniEventEmitter = (function() { function MiniEventEmitter(obj) { var handler; handler = new Handler(this, obj); this.on = handler.on; this.off = handler.off; this.emit = handler.emit; this.emitIf = handler.emitIf; this.trigger = handler.emit; this.triggerIf = handler.emitIf; } MiniEventEmitter.prototype.listen = function(type, event, args) {}; return MiniEventEmitter; })(); module.exports = MiniEventEmitter;
hawkerboy7/mini-event-emitter
build/js/app.js
JavaScript
mit
522
21.695652
69
0.683908
false
#!/usr/bin/bash # Hard variables # Directory containing Snakemake and cluster.json files snakefile_dir='/nas/longleaf/home/sfrenk/pipelines/snakemake' usage="\nCreate directory with Snakemake files required for pipeline \n\n setup_dir -p <pipeline> -d <directory> \n\n pipelines: bowtie_srna, hisat2_rna, srna_telo\n\n" pipeline="" if [ -z "$1" ]; then printf "$usage" exit fi while [[ $# > 0 ]] do key="$1" case $key in -p|--pipeline) pipeline="$2" shift ;; -d|--dir) dir="$2" shift ;; -h|--help) printf "$usage" exit ;; esac shift done if [[ ! -d $dir ]]; then echo "ERROR: Invalid directory" exit 1 fi if [[ $pipeline == "" ]]; then echo "ERROR: Please select pipeline: bowtie_srna or hisat2_rna" exit 1 fi # Determine pipeline file case $pipeline in "bowtie_srna"|"bowtie_sRNA") snakefile="bowtie_srna.Snakefile" ;; "hisat2_rna"|"hisat2_RNA") snakefile='hisat2_rna.Snakefile' ;; "srna_telo") snakefile="srna_telo.Snakefile" ;; *) echo "ERROR: Invalid pipeline. Please select one of the following: bowtie_srna, hisat2_rna or srna_telo" exit 1 ;; esac # Copy over the snakefile cp ${snakefile_dir}/${snakefile} ./${snakefile} # Edit base directory in Snakefile # Remove trailing "/" from dir if it's there input_dir="$(echo $dir |sed -r 's/\/$//')" input_dir=\"${input_dir}\" sed -i -e "s|^BASEDIR.*|BASEDIR = ${input_dir}|" $snakefile # Determine file extension extension="$(ls $dir | grep -Eo "\.[^/]+(\.gz)?$" | sort | uniq)" # Check if there are multiple file extensions in the same directory ext_count="$(ls $dir | grep -Eo "\.[^/]+(\.gz)?$" | sort | uniq | wc -l)" if [[ $ext_count == 0 ]]; then echo "ERROR: Directory is empty!" elif [[ $ext_count != 1 ]]; then echo "WARNING: Multiple file extensions found: using .fastq.gz" extension=".fastq.gz" fi # Edit extension and utils_dir in Snakefile extension="\"${extension}\"" sed -i -e "s|^EXTENSION.*|EXTENSION = ${extension}|g" $snakefile utils_dir="${snakefile_dir%/snakemake}/utils" utils_dir="\"${utils_dir}\"" sed -i -e "s|^UTILS_DIR.*|UTILS_DIR = ${utils_dir}|g" $snakefile # Create Snakmake command script printf "#!/usr/bin/bash\n" > "run_snakemake.sh" printf "#SBATCH -t 2-0\n\n" >> "run_snakemake.sh" printf "module add python\n\n" >> "run_snakemake.sh" printf "snakemake -s $snakefile --keep-going --rerun-incomplete --cluster-config ${snakefile_dir}/cluster.json -j 100 --cluster \"sbatch -n {cluster.n} -N {cluster.N} -t {cluster.time}\"\n" >> run_snakemake.sh
sfrenk/rna-seq_pipelines
utils/setup_dir.sh
Shell
mit
2,550
25.28866
209
0.644706
false
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import {connect} from 'react-redux'; import StringList from './StringList/StringList' import TwitterSelector from './DomainSelector/TwitterSelector' import TweetFilter from './TweetFilter/TweetFilter' class Search extends React.Component { constructor(props) { super(props); this.state = { includedWords: [] }; this.getWords = this.getWords.bind(this); } getWords(words) { this.setState({ includedWords: words }); } render() { const styles = { fontFamily: 'Helvetica Neue', fontSize: 14, lineHeight: '10px', color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', } return ( <div> <TweetFilter /> </div> ); } } export default Search;
hmeinertrita/MyPlanetGirlGuides
src/routes/search/Search.js
JavaScript
mit
1,083
20.64
66
0.638632
false
// // YZAlertView.h // AlertViewDemo // // Created by yangyongzheng on 2017/8/17. // Copyright © 2017年 yangyongzheng. All rights reserved. // #import <UIKit/UIKit.h> typedef void(^YYZAlertViewActionHandler)(UIAlertAction *action); NS_CLASS_AVAILABLE_IOS(8_0) @interface YYZAlertView : NSObject + (void)yyz_alertViewWithTitle:(NSString *)title message:(NSString *)message cancelActionTitle:(NSString *)cancelActionTitle; + (void)yyz_alertViewWithTitle:(NSString *)title message:(NSString *)message actionTitle:(NSString *)actionTitle actionHandler:(YYZAlertViewActionHandler)actionHandler; + (void)yyz_alertViewWithTitle:(NSString *)title message:(NSString *)message cancelActionTitle:(NSString *)cancelActionTitle otherActionTitle:(NSString *)otherActionTitle actionHandler:(YYZAlertViewActionHandler)actionHandler; @end
yangyongzheng/YZLottery
YZKit/Utility/YYZAlertView.h
C
mit
997
32.133333
72
0.66499
false
{% extends "layout_unbranded.html" %} {% block page_title %} GOV.UK prototype kit {% endblock %} {% block content %} <main id="content" role="main"> <div class="grid-row"> <div class="column-full"> <div id="global-breadcrumb" class="breadcrumb"> <a class="link-back" href="results_confirm2?search=QQ123456C">Back</a> </div> <h1 class="heading-large">QQ123456C</h1> <div class="tab-content"> <div class="js-tabs nav-tabs"> <ul class="tabs-nav" role="tablist"> <li class="active"><a href="#current-sp-value" id="tab-overview">Overview</a></li> <li><a href="#options-sp-value" id="tab-options">Filling gaps</a></li> <li><a href="#improve-sp-value" id="tab-contracting-out">Starting amount</a></li> <li><a href="#contracted-out" id="tab-ni-record">National Insurance summary</a></li> </ul> </div> </div> </div> <div id="forecast" class="tab-pane"> <div class="column-half"> <div class="forecast-wrapper2"> <span class="forecast-label2">State Pension date</span> <span class="forecast-data-bold2">4 May 2034</span> </div> <div class="forecast-wrapper2"> <span class="forecast-label2">Final relevant year (FRY)</span> <span class="forecast-data-bold2">2033-34</span> <span class="forecast-label2">&nbsp;</span><span class="forecast-data-bold2 forecast-label2-inline">18 years to FRY </span> </div> <div class="forecast-wrapper2"> <span class="forecast-label2">COPE estimate</span> <span class="forecast-data-bold2">£18.84 a week</span> <span class="forecast-no-data forecast-header forecast-label2-inline">Was contracted out</span> </div> </div> <div class="column-half"> <div class="forecast-wrapper2"> <span class="forecast-label2">Estimate up to 5 April 2016 </span> <span class="forecast-data-bold2">£120.10 a week</span> <span class="forecast-label2 forecast-label2-inline">Qualifying years</span> <span class="forecast-data-bold2 forecast-label2-inline">28</span> </div> <div class="forecast-wrapper2"> <span class="forecast-label2">Forecast contributing future years</span> <span class="forecast-data-bold2">£159.55 a week</span> <span class="forecast-label2 forecast-label2-inline">Future years needed</span> <span class="forecast-data-bold2 forecast-label2-inline">9</span> </div> <div class="forecast-wrapper2"> <span class="forecast-label2">Most they can get</span> <span class="forecast-data-bold2">£159.55 a week</span> </div> </div> </div> <div id="options" class="tab-pane"> <div class="column-two-thirds"> <h3 class="heading-small">Improve by filling gaps</h3> <table class="vnics"><tr><th>Gaps filled</th><th>Old rules</th><th>New rules</th></tr> <tr><td>Estimate 05 April 2016</td><td class="vnics_bold">£120.10 a week</td><td>£108.33 a week</td></tr> <tr><td>1</td><td class="vnics_bold">£124.17 a week</td><td>£112.89 a week</td></tr> <tr><td>2</td><td class="vnics_bold">£128.24 a week<td>£117.45 a week</td></tr> <tr><td>3</td><td><td>£122.00 a week</td></tr> <tr><td>4</td><td><td>£126.56 a week</td></tr> <tr><td>5</td><td><td class="vnics_bold">£131.12 a week</td></tr> </table> </div> </div> <div id="contracting-out" class="tab-pane"> <div class="column-two-thirds"> <h3 class="heading-small">Starting amount at April 2016 is £117.16 a week</h3> </div> <div class="column-one-half column-half-left"> <div class="forecast-wrapper2"> <p class="heading-small">Old rules</p> <span class="forecast-label2">Basic</span> <span class="forecast-data2">£111.35 a week</span> <span class="forecast-label2 forecast-label2-inline">Additional Pension and Grad</span> <span class="forecast-data2 forecast-label2-inline">£5.81 a week</span> <span class="forecast-label2 forecast-label2-inline">Total</span> <span class="forecast-data-bold2 forecast-label2-inline">£117.16 a week </span> </div> </div> <div class="column-one-half column-half-right"> <div class="forecast-wrapper2"> <p class="heading-small">New rules</p> <span class="forecast-label2">New State Pension</span> <span class="forecast-data2">£124.52 a week</span> <span class="forecast-label2 forecast-label2-inline">RDA</span> <span class="forecast-data2 forecast-label2-inline">£18.84 a week</span> <span class="forecast-label2 forecast-label2-inline">Total</span> <span class="forecast-data-bold2 forecast-label2-inline">£105.68 a week</span> </div> </div> </div> <div id="ni-record" class="tab-pane"> <div class="column-two-thirds"> <h2 class="heading-small">Shortfalls in record</h2> <p>5 years can be filled</p> <dl class="accordion2"> <dt> <div class="ni-wrapper"> <div class="ni-years2">2016-17</div> <div class="ni-notfull">This year is not available yet</div> </div> </dt> <dt> <div class="ni-wrapper"> <div class="ni-years2">2015-16</div> <div class="ni-notfull">£733.20 shortfall</div> </div> </dt> <dt> <div class="ni-wrapper"> <div class="ni-years2">2014-15</div> <div class="ni-notfull">£722.80 shortfall</div> </div> </dt> <dt> <div class="ni-wrapper"> <div class="ni-years2">2013-14</div> <div class="ni-notfull">£704.60 shortfall</div> </div> </dt> <dt> <div class="ni-wrapper"> <div class="ni-years2">2012-13</div> <div class="ni-notfull">£689.00 shortfall</div> </div> </dt> <dt> <div class="ni-wrapper"> <div class="ni-years2">2011-12</div> <div class="ni-notfull">£289.80 shortfall</div> </div> </dt> </dl> </div> <div class="column-one-third"> <aside class="govuk-related-items dwp-related-items" role="complementary"> <h2 class="heading-small" id="subsection-title">Full years and shortfalls</h2> <nav role="navigation" aria-labelledby="subsection-title"> <ul class="font-xsmall"> <nav role="navigation" aria-labelledby="parent-subsection"> <ul class="list-bullets"> <li><span style="font-size: 16px"><span style="font-weight: 700">28</span> qualifying years </span> </li> <li><span style="font-size: 16px"><span style="font-weight: 700">18</span> years to contribute before 05 April 2034</span> </li> <li><span style="font-size: 16px"><span style="font-weight: 700">5</span> years with a shortfall</span> </li> </ul> </ul> </nav> </aside> </div> </div> </div> </main> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script type="text/javascript"> // function show(elementId) { // document.getElementById("id1").style.display = "none"; // document.getElementById("id2").style.display = "block"; // document.getElementById(elementId).style.display = "block"; // } jQuery(document).ready(function($){ $("a#tab-overview").click(function() { $(".tabs-nav li").removeClass("active"); $(this).parent().addClass("active"); $("#forecast").show(); $("#ni-record").hide(); $("#contracting-out").hide(); $("#contracting-out").hide(); $("#options").hide(); window.location.hash = "#lie-forecast"; return false; }); $("a#tab-options").click(function() { $(".tabs-nav li").removeClass("active"); $(this).parent().addClass("active"); $("#options").show(); $("#forecast").hide(); $("#ni-record").hide(); $("#contracting-out").hide(); window.location.hash = "#lie-options"; return false; }); $("a#tab-ni-record").click(function() { $(".tabs-nav li").removeClass("active"); $(this).parent().addClass("active"); $("#ni-record").show(); $("#contracting-out").hide(); $("#forecast").hide(); $("#options").hide(); window.location.hash = "#lie-ni-record"; return false; }); $("a#tab-contracting-out").click(function() { $(".tabs-nav li").removeClass("active"); $(this).parent().addClass("active"); $("#contracting-out").show(); $("#ni-record").hide(); $("#forecast").hide(); $("#options").hide(); window.location.hash = "#lie-contracting-out"; return false; }); if(window.location.hash === "#lie-forecast") { $("a#tab-overview").trigger('click'); } else if (window.location.hash === "#lie-ni-record") { $("a#tab-ni-record").trigger('click'); } else if (window.location.hash === "#lie-contracting-out") { $("a#tab-contracting-out").trigger('click'); } else if (window.location.hash === "#lie-optionst") { $("a#tab-options").trigger('click'); } }); </script> </div> </main> <script type="text/javascript"> function removeWhitespaces() { var txtbox = document.getElementById('search-main'); txtbox.value = txtbox.value.replace(/\s/g, ""); } </script> {% endblock %}
steven-borthwick/check-support
app/views/volnicsv1a/forecast_QQ123456C.html
HTML
mit
9,847
36.204545
155
0.563531
false
<div id="maxoptions_example"></div>
oakmac/autocompletejs
examples/4008.html
HTML
mit
35
35
35
0.714286
false
Given(/^I have an Auton that has two steps, first step scheduling the next step$/) do class ScheduleSecondStepAuton < Nestene::Auton def first context.schedule_step(:second) end def second 'ok' end attr_accessor :context attribute foo: Fixnum end @auton_type="ScheduleSecondStepAuton" @auton_id = Celluloid::Actor[:nestene_core].create_auton(@auton_type) end When(/^I schedule the first step that returns the uuid of the second scheduled step$/) do @step_execution_id = Celluloid::Actor[:nestene_core].schedule_step @auton_id, :first @step_execution_id = Celluloid::Actor[:nestene_core].wait_for_execution_result(@auton_id, @step_execution_id) end When(/^I wait for the second step to finish$/) do @execution_result = Celluloid::Actor[:nestene_core].wait_for_execution_result(@auton_id, @step_execution_id) end Given(/^I have two autons where first auton schedules step on the other auton$/) do class StepSchedulingAuton < Nestene::Auton def schedule_step self.step_id = context.schedule_step_on_auton('step_executor', :step) end attr_accessor :context attribute step_id: Fixnum end class StepExecutorAuton < Nestene::Auton def step context.schedule_step(:second) end attr_accessor :context attribute foo: Fixnum end @first_auton_id = Celluloid::Actor[:nestene_core].create_auton('StepSchedulingAuton') @second_auton_id = Celluloid::Actor[:nestene_core].create_auton('StepExecutorAuton','step_executor') end When(/^I schedule the step on the first auton and wait for it's execution$/) do step_id = Celluloid::Actor[:nestene_core].schedule_step @first_auton_id, :schedule_step @second_auton_step_id = Celluloid::Actor[:nestene_core].wait_for_execution_result @first_auton_id, step_id end Then(/^second auton should either have scheduled or executed step$/) do Celluloid::Actor[:nestene_core].wait_for_execution_result @second_auton_id, @second_auton_step_id end
draganm/nestene
features/step_definitions/schedule_steps_steps.rb
Ruby
mit
1,992
29.646154
111
0.722892
false
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>ergo: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.10.2 / ergo - 8.6.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> ergo <small> 8.6.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-01-18 13:05:13 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-01-18 13:05:13 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils coq 8.10.2 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.07.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.07.1 Official release 4.07.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/ergo&quot; license: &quot;Unknown&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Ergo&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} &quot;coq-counting&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} &quot;coq-nfix&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} &quot;coq-containers&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} ] tags: [ &quot;keyword: reflexive decision procedure&quot; &quot;keyword: satisfiability modulo theories&quot; &quot;category: Computer Science/Decision Procedures and Certified Algorithms/Decision procedures&quot; ] authors: [ &quot;Stéphane Lescuyer&quot; ] bug-reports: &quot;https://github.com/coq-contribs/ergo/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/ergo.git&quot; synopsis: &quot;Ergo: a Coq plugin for reification of term with arbitrary signature&quot; description: &quot;This library provides a tactic that performs SMT solving (SAT + congruence closure + arithmetic).&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/ergo/archive/v8.6.0.tar.gz&quot; checksum: &quot;md5=5995e362eac7d51d1d6339ab417d518e&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-ergo.8.6.0 coq.8.10.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.10.2). The following dependencies couldn&#39;t be met: - coq-ergo -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-ergo.8.6.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.07.1-2.0.6/released/8.10.2/ergo/8.6.0.html
HTML
mit
6,970
41.341463
215
0.540179
false
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>finger-tree: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.12.1 / finger-tree - 8.7.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> finger-tree <small> 8.7.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-01-11 21:45:50 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-01-11 21:45:50 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils coq 8.12.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.09.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.09.1 Official release 4.09.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/finger-tree&quot; license: &quot;LGPL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/FingerTree&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.7&quot; &amp; &lt; &quot;8.8~&quot;} ] tags: [ &quot;keyword: data structures&quot; &quot;keyword: dependent types&quot; &quot;keyword: Finger Trees&quot; &quot;category: Computer Science/Data Types and Data Structures&quot; &quot;date: 2009-02&quot; ] authors: [ &quot;Matthieu Sozeau &lt;mattam@mattam.org&gt; [http://mattam.org]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/finger-tree/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/finger-tree.git&quot; synopsis: &quot;Dependent Finger Trees&quot; description: &quot;&quot;&quot; http://mattam.org/research/russell/fingertrees.en.html A verified generic implementation of Finger Trees&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/finger-tree/archive/v8.7.0.tar.gz&quot; checksum: &quot;md5=65bc1765ca51e147bcbd410b0f4c88b0&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-finger-tree.8.7.0 coq.8.12.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.12.1). The following dependencies couldn&#39;t be met: - coq-finger-tree -&gt; coq &lt; 8.8~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-finger-tree.8.7.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.09.1-2.0.6/released/8.12.1/finger-tree/8.7.0.html
HTML
mit
6,929
41.097561
213
0.544322
false
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>paramcoq: Not compatible</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.10.0 / paramcoq - 1.1.1+coq8.7</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> paramcoq <small> 1.1.1+coq8.7 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-07-16 08:04:26 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-16 08:04:26 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.10.0 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; synopsis: &quot;Paramcoq&quot; name: &quot;coq-paramcoq&quot; version: &quot;1.1.1+coq8.7&quot; maintainer: &quot;Pierre Roux &lt;pierre.roux@onera.fr&gt;&quot; homepage: &quot;https://github.com/coq-community/paramcoq&quot; dev-repo: &quot;git+https://github.com/coq-community/paramcoq.git&quot; bug-reports: &quot;https://github.com/coq-community/paramcoq/issues&quot; license: &quot;MIT&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Param&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.7.2&quot; &amp; &lt; &quot;8.8~&quot;} ] tags: [ &quot;keyword:paramcoq&quot; &quot;keyword:parametricity&quot; &quot;keyword:ocaml module&quot; &quot;category:paramcoq&quot; &quot;category:Miscellaneous/Coq Extensions&quot; &quot;logpath:Param&quot; ] authors: [ &quot;Chantal Keller (Inria, École polytechnique)&quot; &quot;Marc Lasson (ÉNS de Lyon)&quot; &quot;Abhishek Anand&quot; &quot;Pierre Roux&quot; &quot;Emilio Jesús Gallego Arias&quot; &quot;Cyril Cohen&quot; &quot;Matthieu Sozeau&quot; ] flags: light-uninstall url { src: &quot;https://github.com/coq-community/paramcoq/releases/download/v1.1.1+coq8.7/coq-paramcoq.1.1.1+coq8.7.tgz&quot; checksum: &quot;md5=3eb94ccdb53e6dfc7f0d74b3cd1a5db5&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-paramcoq.1.1.1+coq8.7 coq.8.10.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.10.0). The following dependencies couldn&#39;t be met: - coq-paramcoq -&gt; coq &lt; 8.8~ -&gt; ocaml &lt; 4.03.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-paramcoq.1.1.1+coq8.7</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.05.0-2.0.6/released/8.10.0/paramcoq/1.1.1+coq8.7.html
HTML
mit
7,188
38.685083
157
0.546986
false
using MineLib.Core; using MineLib.Core.Data; using MineLib.Core.IO; using ProtocolClassic.Data; namespace ProtocolClassic.Packets.Server { public struct LevelFinalizePacket : IPacketWithSize { public Position Coordinates; public byte ID { get { return 0x04; } } public short Size { get { return 7; } } public IPacketWithSize ReadPacket(IProtocolDataReader reader) { Coordinates = Position.FromReaderShort(reader); return this; } IPacket IPacket.ReadPacket(IProtocolDataReader reader) { return ReadPacket(reader); } public IPacket WritePacket(IProtocolStream stream) { Coordinates.ToStreamShort(stream); return this; } } }
MineLib/ProtocolClassic
Packets/Server/LevelFinalize.cs
C#
mit
812
22.823529
69
0.614815
false
#ifndef IDUCK_HPP_124b1b04_74d3_41ae_b7ce_2a0bea79f1c7 #define IDUCK_HPP_124b1b04_74d3_41ae_b7ce_2a0bea79f1c7 #include "../strategy/IFly.hpp" /** \interface IDuck Interface for duck. It can fly, quack and rotate right. */ class IDuck { public: virtual Course getCourse() const = 0; virtual int getDistance(Course course) const = 0; virtual void fly() = 0; virtual void quack() = 0; virtual void right() = 0; virtual void left() = 0; virtual ~IDuck() { } }; #endif // IDUCK_HPP_124b1b04_74d3_41ae_b7ce_2a0bea79f1c7
PS-Group/compiler-theory-samples
interpreter/IDuckPro_AST/src/duck/IDuck.hpp
C++
mit
553
22.041667
57
0.679928
false
require 'cred_hubble/resources/credential' module CredHubble module Resources class UserValue include Virtus.model attribute :username, String attribute :password, String attribute :password_hash, String def to_json(options = {}) attributes.to_json(options) end def attributes_for_put attributes.delete_if { |k, _| immutable_attributes.include?(k) } end private def immutable_attributes [:password_hash] end end class UserCredential < Credential attribute :value, UserValue def type Credential::USER_TYPE end def attributes_for_put super.merge(value: value && value.attributes_for_put) end end end end
tcdowney/cred_hubble
lib/cred_hubble/resources/user_credential.rb
Ruby
mit
767
18.666667
72
0.627119
false
# encoding: utf-8 require 'spec_helper' describe Optimizer::Algebra::Projection::ExtensionOperand, '#optimizable?' do subject { object.optimizable? } let(:header) { Relation::Header.coerce([[:id, Integer], [:name, String], [:age, Integer]]) } let(:base) { Relation.new(header, LazyEnumerable.new([[1, 'Dan Kubb', 35]])) } let(:relation) { operand.project([:id, :name]) } let(:object) { described_class.new(relation) } before do expect(object.operation).to be_kind_of(Algebra::Projection) end context 'when the operand is an extension, and the extended attribtue is removed ' do let(:operand) { base.extend { |r| r.add(:active, true) } } it { should be(true) } end context 'when the operand is an extension, and the extended attribtue is not removed ' do let(:operand) { base.extend { |r| r.add(:active, true) } } let(:relation) { operand.project([:id, :name, :active]) } it { should be(false) } end context 'when the operand is not an extension' do let(:operand) { base } it { should be(false) } end end
dkubb/axiom-optimizer
spec/unit/axiom/optimizer/algebra/projection/extension_operand/optimizable_predicate_spec.rb
Ruby
mit
1,187
32.914286
96
0.593092
false
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Rendering; namespace ASP.NET_Core_Email.Models.ManageViewModels { public class ConfigureTwoFactorViewModel { public string SelectedProvider { get; set; } public ICollection<SelectListItem> Providers { get; set; } } }
elanderson/ASP.NET-Core-Email
ASP.NET-Core-Email/src/ASP.NET-Core-Email/Models/ManageViewModels/ConfigureTwoFactorViewModel.cs
C#
mit
378
24.066667
66
0.744681
false
#include <stdio.h> #include "list.h" #define N 10 link reverse(link); int main(void) { int i; link head, x; // Population head = new_link(0); x = head; for (i = 1; i < N; ++i) { x = insert_after(x, new_link(i)); } // Reversal head = reverse(head); // Traversal x = head; do { printf("%i\n", x->item); x = x->next; } while (x != head); return 0; } link reverse(link x) { link t; link y = x; link r = NULL; do { t = y->next; y->next = r; r = y; y = t; } while (y != x); x->next = r; return r; }
bartobri/data-structures-c
linked-lists/circular-reversal/main.c
C
mit
546
10.617021
35
0.509158
false
-- service script, define some stuuf for use with main build config self=loader.extra[1] profile=loader.extra[2] prefix=loader.extra[3] config=loader.extra[4] prefix_addon=string.format('--prefix="%s"', prefix)
DarkCaster/Linux-Helper-Tools
WineLauncher/build.pre.lua
Lua
mit
214
22.777778
67
0.747664
false
import { get } from "ember-metal/property_get"; import { set } from "ember-metal/property_set"; import Ember from "ember-metal/core"; // Ember.assert import EmberError from "ember-metal/error"; import { Descriptor, defineProperty } from "ember-metal/properties"; import { ComputedProperty } from "ember-metal/computed"; import create from "ember-metal/platform/create"; import { meta, inspect } from "ember-metal/utils"; import { addDependentKeys, removeDependentKeys } from "ember-metal/dependent_keys"; export default function alias(altKey) { return new AliasedProperty(altKey); } export function AliasedProperty(altKey) { this.altKey = altKey; this._dependentKeys = [altKey]; } AliasedProperty.prototype = create(Descriptor.prototype); AliasedProperty.prototype.get = function AliasedProperty_get(obj, keyName) { return get(obj, this.altKey); }; AliasedProperty.prototype.set = function AliasedProperty_set(obj, keyName, value) { return set(obj, this.altKey, value); }; AliasedProperty.prototype.willWatch = function(obj, keyName) { addDependentKeys(this, obj, keyName, meta(obj)); }; AliasedProperty.prototype.didUnwatch = function(obj, keyName) { removeDependentKeys(this, obj, keyName, meta(obj)); }; AliasedProperty.prototype.setup = function(obj, keyName) { Ember.assert("Setting alias '" + keyName + "' on self", this.altKey !== keyName); var m = meta(obj); if (m.watching[keyName]) { addDependentKeys(this, obj, keyName, m); } }; AliasedProperty.prototype.teardown = function(obj, keyName) { var m = meta(obj); if (m.watching[keyName]) { removeDependentKeys(this, obj, keyName, m); } }; AliasedProperty.prototype.readOnly = function() { this.set = AliasedProperty_readOnlySet; return this; }; function AliasedProperty_readOnlySet(obj, keyName, value) { throw new EmberError('Cannot set read-only property "' + keyName + '" on object: ' + inspect(obj)); } AliasedProperty.prototype.oneWay = function() { this.set = AliasedProperty_oneWaySet; return this; }; function AliasedProperty_oneWaySet(obj, keyName, value) { defineProperty(obj, keyName, null); return set(obj, keyName, value); } // Backwards compatibility with Ember Data AliasedProperty.prototype._meta = undefined; AliasedProperty.prototype.meta = ComputedProperty.prototype.meta;
gdi2290/ember.js
packages/ember-metal/lib/alias.js
JavaScript
mit
2,326
27.024096
101
0.735168
false
# Alt Three Storage A cached secure storage provider for Laravel 5. ## Installation This version requires [PHP](https://php.net) 7.1 or 7.2, and supports Laravel 5.5 - 5.7 only. To get the latest version, simply require the project using [Composer](https://getcomposer.org): ```bash $ composer require alt-three/storage ``` Once installed, if you are not using automatic package discovery, then you need to register the `AltThree\Storage\StorageServiceProvider` service provider in your `config/app.php`. ## Configuration Alt Three Storage requires configuration. To get started, you'll need to publish all vendor assets: ```bash $ php artisan vendor:publish ``` This will create a `config/login.php` file in your app that you can modify to set your configuration. Also, make sure you check for changes to the original config file in this package between releases. ## Security If you discover a security vulnerability within this package, please e-mail us at support@alt-three.com. All security vulnerabilities will be promptly addressed. ## License Alt Three Storage is licensed under [The MIT License (MIT)](LICENSE).
AltThree/Storage
README.md
Markdown
mit
1,139
28.205128
201
0.766462
false
<!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_65) on Sat Dec 27 23:31:06 CST 2014 --> <TITLE> Uses of Class pages.MarkovTable </TITLE> <META NAME="date" CONTENT="2014-12-27"> <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="Uses of Class pages.MarkovTable"; } } </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="../../pages/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../pages/MarkovTable.html" title="class in pages"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&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-files/index-1.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;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html?pages//class-useMarkovTable.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="MarkovTable.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> <B>Uses of Class<br>pages.MarkovTable</B></H2> </CENTER> <A NAME="pages"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../pages/MarkovTable.html" title="class in pages">MarkovTable</A> in <A HREF="../../pages/package-summary.html">pages</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../pages/package-summary.html">pages</A> declared as <A HREF="../../pages/MarkovTable.html" title="class in pages">MarkovTable</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>(package private) &nbsp;<A HREF="../../pages/MarkovTable.html" title="class in pages">MarkovTable</A></CODE></FONT></TD> <TD><CODE><B>Model.</B><B><A HREF="../../pages/Model.html#markov">markov</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>private &nbsp;<A HREF="../../pages/MarkovTable.html" title="class in pages">MarkovTable</A></CODE></FONT></TD> <TD><CODE><B>ClassifyingThread.</B><B><A HREF="../../pages/ClassifyingThread.html#markov">markov</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>private &nbsp;<A HREF="../../pages/MarkovTable.html" title="class in pages">MarkovTable</A></CODE></FONT></TD> <TD><CODE><B>ClassifyingExecutor.</B><B><A HREF="../../pages/ClassifyingExecutor.html#markov">markov</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../pages/package-summary.html">pages</A> that return <A HREF="../../pages/MarkovTable.html" title="class in pages">MarkovTable</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../pages/MarkovTable.html" title="class in pages">MarkovTable</A></CODE></FONT></TD> <TD><CODE><B>Corpus.</B><B><A HREF="../../pages/Corpus.html#makeMarkovTable(java.util.ArrayList, double)">makeMarkovTable</A></B>(java.util.ArrayList&lt;java.lang.String&gt;&nbsp;volumesToUse, double&nbsp;alpha)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../pages/package-summary.html">pages</A> with parameters of type <A HREF="../../pages/MarkovTable.html" title="class in pages">MarkovTable</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B>GenrePredictorMulticlass.</B><B><A HREF="../../pages/GenrePredictorMulticlass.html#classify(java.lang.String, java.lang.String, java.lang.String, pages.MarkovTable, java.util.ArrayList, pages.Vocabulary, pages.FeatureNormalizer, boolean)">classify</A></B>(java.lang.String&nbsp;thisFile, java.lang.String&nbsp;inputDir, java.lang.String&nbsp;outputDir, <A HREF="../../pages/MarkovTable.html" title="class in pages">MarkovTable</A>&nbsp;markov, java.util.ArrayList&lt;java.lang.String&gt;&nbsp;genres, <A HREF="../../pages/Vocabulary.html" title="class in pages">Vocabulary</A>&nbsp;vocabulary, <A HREF="../../pages/FeatureNormalizer.html" title="class in pages">FeatureNormalizer</A>&nbsp;normalizer, boolean&nbsp;isPairtree)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B>GenrePredictor.</B><B><A HREF="../../pages/GenrePredictor.html#classify(java.lang.String, java.lang.String, java.lang.String, pages.MarkovTable, java.util.ArrayList, pages.Vocabulary, pages.FeatureNormalizer, boolean)">classify</A></B>(java.lang.String&nbsp;thisFile, java.lang.String&nbsp;inputDir, java.lang.String&nbsp;outputDir, <A HREF="../../pages/MarkovTable.html" title="class in pages">MarkovTable</A>&nbsp;markov, java.util.ArrayList&lt;java.lang.String&gt;&nbsp;genres, <A HREF="../../pages/Vocabulary.html" title="class in pages">Vocabulary</A>&nbsp;vocabulary, <A HREF="../../pages/FeatureNormalizer.html" title="class in pages">FeatureNormalizer</A>&nbsp;normalizer, boolean&nbsp;isPairtree)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.util.ArrayList&lt;double[]&gt;</CODE></FONT></TD> <TD><CODE><B>ForwardBackward.</B><B><A HREF="../../pages/ForwardBackward.html#smooth(java.util.ArrayList, pages.MarkovTable, double[])">smooth</A></B>(java.util.ArrayList&lt;double[]&gt;&nbsp;evidenceVectors, <A HREF="../../pages/MarkovTable.html" title="class in pages">MarkovTable</A>&nbsp;markov, double[]&nbsp;wordLengths)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Constructors in <A HREF="../../pages/package-summary.html">pages</A> with parameters of type <A HREF="../../pages/MarkovTable.html" title="class in pages">MarkovTable</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../pages/ClassifyingThread.html#ClassifyingThread(java.lang.String, java.lang.String, java.lang.String, int, java.util.ArrayList, pages.MarkovTable, java.util.ArrayList, pages.Vocabulary, pages.FeatureNormalizer, boolean, java.lang.String)">ClassifyingThread</A></B>(java.lang.String&nbsp;thisFile, java.lang.String&nbsp;inputDir, java.lang.String&nbsp;outputDir, int&nbsp;numGenres, java.util.ArrayList&lt;<A HREF="../../pages/GenrePredictor.html" title="class in pages">GenrePredictor</A>&gt;&nbsp;classifiers, <A HREF="../../pages/MarkovTable.html" title="class in pages">MarkovTable</A>&nbsp;markov, java.util.ArrayList&lt;java.lang.String&gt;&nbsp;genres, <A HREF="../../pages/Vocabulary.html" title="class in pages">Vocabulary</A>&nbsp;vocabulary, <A HREF="../../pages/FeatureNormalizer.html" title="class in pages">FeatureNormalizer</A>&nbsp;normalizer, boolean&nbsp;isPairtree, java.lang.String&nbsp;modelLabel)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../pages/Model.html#Model(pages.Vocabulary, pages.FeatureNormalizer, pages.GenreList, java.util.ArrayList, pages.MarkovTable)">Model</A></B>(<A HREF="../../pages/Vocabulary.html" title="class in pages">Vocabulary</A>&nbsp;vocabulary, <A HREF="../../pages/FeatureNormalizer.html" title="class in pages">FeatureNormalizer</A>&nbsp;normalizer, <A HREF="../../pages/GenreList.html" title="class in pages">GenreList</A>&nbsp;genreList, java.util.ArrayList&lt;<A HREF="../../pages/GenrePredictor.html" title="class in pages">GenrePredictor</A>&gt;&nbsp;classifiers, <A HREF="../../pages/MarkovTable.html" title="class in pages">MarkovTable</A>&nbsp;markov)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <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="../../pages/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../pages/MarkovTable.html" title="class in pages"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&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-files/index-1.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;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html?pages//class-useMarkovTable.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="MarkovTable.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>
tedunderwood/genre
pages/doc/pages/class-use/MarkovTable.html
HTML
mit
13,555
47.410714
323
0.649354
false
/* * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. * * author: emicklei */ V8D.receiveCallback = function(msg) { var obj = JSON.parse(msg); var context = this; if (obj.receiver != "this") { var namespaces = obj.receiver.split("."); for (var i = 0; i < namespaces.length; i++) { context = context[namespaces[i]]; } } var func = context[obj.selector]; if (func != null) { return JSON.stringify(func.apply(context, obj.args)); } else { // try reporting the error if (console != null) { console.log("[JS] unable to perform", msg); } // TODO return error? return "null"; } } // This callback is set for handling function calls from Go transferred as JSON. // It is called from Go using "worker.Send(...)". // Throws a SyntaxError exception if the string to parse is not valid JSON. // $recv(V8D.receiveCallback); // This callback is set for handling function calls from Go transferred as JSON that expect a return value. // It is called from Go using "worker.SendSync(...)". // Throws a SyntaxError exception if the string to parse is not valid JSON. // Returns the JSON representation of the return value of the handling function. // $recvSync(V8D.receiveCallback); // callDispatch is used from Go to call a callback function that was registered. // V8D.callDispatch = function(functionRef /*, arguments */ ) { var jsonArgs = [].slice.call(arguments).splice(1); var callback = V8D.function_registry.take(functionRef) if (V8D.function_registry.none == callback) { $print("[JS] no function for reference:" + functionRef); return; } callback.apply(this, jsonArgs.map(function(each){ return JSON.parse(each); })); } // MessageSend is a constructor. // V8D.MessageSend = function MessageSend(receiver, selector, onReturn) { this.data = { "receiver": receiver, "selector": selector, "callback": onReturn, "args": [].slice.call(arguments).splice(3) }; } // MessageSend toJSON returns the JSON representation. // V8D.MessageSend.prototype = { toJSON: function() { return JSON.stringify(this.data); } } // callReturn performs a MessageSend in Go and returns the value from that result // V8D.callReturn = function(receiver, selector /*, arguments */ ) { var msg = { "receiver": receiver, "selector": selector, "args": [].slice.call(arguments).splice(2) }; return JSON.parse($sendSync(JSON.stringify(msg))); } // call performs a MessageSend in Go and does NOT return a value. // V8D.call = function(receiver, selector /*, arguments */ ) { var msg = { "receiver": receiver, "selector": selector, "args": [].slice.call(arguments).splice(2) }; $send(JSON.stringify(msg)); } // callThen performs a MessageSend in Go which can call the onReturn function. // It does not return the value of the perform. // V8D.callThen = function(receiver, selector, onReturnFunction /*, arguments */ ) { var msg = { "receiver": receiver, "selector": selector, "callback": V8D.function_registry.put(onReturnFunction), "args": [].slice.call(arguments).splice(3) }; $send(JSON.stringify(msg)); } // set adds/replaces the value for a variable in the global scope. // V8D.set = function(variableName,itsValue) { V8D.outerThis[variableName] = itsValue; } // get returns the value for a variable in the global scope. // V8D.get = function(variableName) { return V8D.outerThis[variableName]; }
emicklei/v8dispatcher
js/setup.js
JavaScript
mit
3,684
29.966387
107
0.649294
false
#!/usr/bin/env bash GEM_BIN=$1/ruby/bin/gem export GEM_HOME=/usr/local/kidsruby/ruby/lib/ruby/gems/1.9.1 install_gems() { echo $KIDSRUBY_INSTALLING_GEMS ${GEM_BIN} install htmlentities-4.3.0.gem --no-ri --no-rdoc 2>&1 ${GEM_BIN} install rubywarrior-i18n-0.0.3.gem --no-ri --no-rdoc 2>&1 ${GEM_BIN} install serialport-1.1.1-universal.x86_64-darwin-10.gem --no-ri --no-rdoc 2>&1 ${GEM_BIN} install hybridgroup-sphero-1.0.1.gem --no-ri --no-rdoc 2>&1 } install_qtbindings() { echo $KIDSRUBY_INSTALLING_QTBINDINGS ${GEM_BIN} install qtbindings-4.7.3-universal-darwin-10.gem --no-ri --no-rdoc 2>&1 } install_gosu() { echo $KIDSRUBY_INSTALLING_GOSU ${GEM_BIN} install gosu-0.7.36.2-universal-darwin.gem --no-ri --no-rdoc 2>&1 } install_gems install_qtbindings install_gosu
hybridgroup/kidsrubyinstaller-osx
install_gems.sh
Shell
mit
784
30.36
91
0.700255
false
require File.join(File.dirname(__FILE__), 'test_helper') require 'activesupport' class SplamTest < Test::Unit::TestCase class FixedRule < Splam::Rule def run add_score 25, "The force is strong with this one" end end # It should not be in the default set Splam::Rule.default_rules.delete SplamTest::FixedRule class Foo include ::Splam splammable :body attr_accessor :body def body @body || "This is body\320\224 \320\199" end end class FooReq include ::Splam splammable :body do |s| s.rules = [ Splam::Rules::Keyhits, Splam::Rules::True ] end attr_accessor :body attr_accessor :request def request(obj) @request end end class FooCond include ::Splam splammable :body, 0, lambda { |s| false } attr_accessor :body end class PickyFoo include ::Splam splammable :body do |s| s.rules = [:fixed_rule, FixedRule] end def body 'lol wut' end end class HeavyFoo include ::Splam splammable :body do |s| s.rules = {:fixed_rule => 3} end def body 'lol wut' end end def test_runs_plugins f = Foo.new assert ! f.splam? assert_equal 10, f.splam_score end def test_runs_plugins_with_specified_rules f = PickyFoo.new assert ! f.splam? assert_equal 25, f.splam_score end def test_runs_plugins_with_specified_weighted_rules f = HeavyFoo.new assert ! f.splam? assert_equal 75, f.splam_score end def test_runs_conditions f = FooCond.new assert f.splam? # it IS spam, coz threshold is 0 end def test_scores_spam_really_high Dir.glob(File.join(File.dirname(__FILE__), "fixtures", "comment", "spam", "*.txt")).each do |f| comment = Foo.new spam = File.open(f).read comment.body = spam # some spam have a lower threshold denoted by their filename # trickier to detect if f =~ /\/(\d+)_.*\.txt/ Foo.splam_suite.threshold = $1.to_i else Foo.splam_suite.threshold = 180 end spam = comment.splam? score = comment.splam_score #$stderr.puts "#{f} score: #{score}\n#{comment.splam_reasons.inspect}" #$stderr.puts "=====================" assert spam, "Comment #{f} was not spam, score was #{score} but threshold was #{Foo.splam_suite.threshold}\nReasons were #{comment.splam_reasons.inspect}" end end def test_scores_ham_low Dir.glob(File.join(File.dirname(__FILE__), "fixtures", "comment", "ham", "*.txt")).each do |f| comment = Foo.new comment.body = File.open(f).read spam = comment.splam? score = comment.splam_score #$stderr.puts "#{f} score: #{score}" #$stderr.puts "=====================" assert !spam, "File #{f} should be marked ham < #{Foo.splam_suite.threshold}, but was marked with score #{score}\nReasons were #{comment.splam_reasons.inspect}\n\n#{comment.body}" end end def test_keyhits_with_true f = FooReq.new f.body = "true" f.request = {:counter => "", :time => 3, :remote_ip => "1.2.3.4"} assert f.splam? assert_equal 300, f.splam_score end def test_keyhits_with_word f = FooReq.new f.body = "8趷" f.request = {:counter => "", :time => 3, :remote_ip => "1.2.3.4"} assert f.splam? assert_equal 300, f.splam_score end end
courtenay/splam
test/splam_test.rb
Ruby
mit
3,384
24.238806
185
0.604672
false
<?php namespace Symfony\Component\Serializer; use Symfony\Component\Serializer\SerializerInterface; /* * This file is part of the Symfony framework. * * (c) Fabien Potencier <fabien@symfony.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ /** * Defines the interface of encoders * * @author Jordi Boggiano <j.boggiano@seld.be> */ interface SerializerAwareInterface { /** * Sets the owning Serializer object * * @param SerializerInterface $serializer */ function setSerializer(SerializerInterface $serializer); }
flyingfeet/FlyingFeet
vendor/symfony/src/Symfony/Component/Serializer/SerializerAwareInterface.php
PHP
mit
608
20.714286
65
0.735197
false
// ƒwƒbƒ_ƒtƒ@ƒCƒ‹‚̃Cƒ“ƒNƒ‹[ƒh #include <windows.h> // •W€WindowsAPI #include <tchar.h> // TCHARŒ^ #include <string.h> // C•¶Žš—ñˆ— // ŠÖ”‚̃vƒƒgƒ^ƒCƒvéŒ¾ LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); // ƒEƒBƒ“ƒhƒEƒƒbƒZ[ƒW‚ɑ΂µ‚Ä“ÆŽ©‚̏ˆ—‚ð‚·‚é‚悤‚É’è‹`‚µ‚½ƒR[ƒ‹ƒoƒbƒNŠÖ”WindowProc. // _tWinMainŠÖ”‚Ì’è‹` int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nShowCmd) { // •Ï”‚̐錾 HWND hWnd; // CreateWindow‚ō쐬‚µ‚½ƒEƒBƒ“ƒhƒE‚̃EƒBƒ“ƒhƒEƒnƒ“ƒhƒ‹‚ðŠi”[‚·‚éHWNDŒ^•Ï”hWnd. MSG msg; // ƒEƒBƒ“ƒhƒEƒƒbƒZ[ƒWî•ñ‚ðŠi”[‚·‚éMSG\‘¢‘ÌŒ^•Ï”msg. WNDCLASS wc; // ƒEƒBƒ“ƒhƒEƒNƒ‰ƒXî•ñ‚ð‚à‚ÂWNDCLASS\‘¢‘ÌŒ^•Ï”wc. // ƒEƒBƒ“ƒhƒEƒNƒ‰ƒX‚̐ݒè wc.lpszClassName = _T("SetBkColor"); // ƒEƒBƒ“ƒhƒEƒNƒ‰ƒX–¼‚Í"SetBkColor". wc.style = CS_HREDRAW | CS_VREDRAW; // ƒXƒ^ƒCƒ‹‚ÍCS_HREDRAW | CS_VREDRAW. wc.lpfnWndProc = WindowProc; // ƒEƒBƒ“ƒhƒEƒvƒƒV[ƒWƒƒ‚Í“ÆŽ©‚̏ˆ—‚ð’è‹`‚µ‚½WindowProc. wc.hInstance = hInstance; // ƒCƒ“ƒXƒ^ƒ“ƒXƒnƒ“ƒhƒ‹‚Í_tWinMain‚̈ø”. wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); // ƒAƒCƒRƒ“‚̓AƒvƒŠƒP[ƒVƒ‡ƒ“Šù’è‚Ì‚à‚Ì. wc.hCursor = LoadCursor(NULL, IDC_ARROW); // ƒJ[ƒ\ƒ‹‚Í–îˆó. wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); // ”wŒi‚Í”’ƒuƒ‰ƒV. wc.lpszMenuName = NULL; // ƒƒjƒ…[‚Í‚È‚µ. wc.cbClsExtra = 0; // 0‚Å‚¢‚¢. wc.cbWndExtra = 0; // 0‚Å‚¢‚¢. // ƒEƒBƒ“ƒhƒEƒNƒ‰ƒX‚Ì“o˜^ if (!RegisterClass(&wc)) { // RegisterClass‚ŃEƒBƒ“ƒhƒEƒNƒ‰ƒX‚ð“o˜^‚µ, 0‚ª•Ô‚Á‚½‚çƒGƒ‰[. // ƒGƒ‰[ˆ— MessageBox(NULL, _T("RegisterClass failed!"), _T("SetBkColor"), MB_OK | MB_ICONHAND); // MessageBox‚Å"RegisterClass failed!"‚ƃGƒ‰[ƒƒbƒZ[ƒW‚ð•\Ž¦. return -1; // ˆÙíI—¹(1) } // ƒEƒBƒ“ƒhƒE‚̍쐬 hWnd = CreateWindow(_T("SetBkColor"), _T("SetBkColor"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL); // CreateWindow‚Å, ã‚Å“o˜^‚µ‚½"SetBkColor"ƒEƒBƒ“ƒhƒEƒNƒ‰ƒX‚̃EƒBƒ“ƒhƒE‚ðì¬. if (hWnd == NULL) { // ƒEƒBƒ“ƒhƒE‚̍쐬‚ÉŽ¸”s‚µ‚½‚Æ‚«. // ƒGƒ‰[ˆ— MessageBox(NULL, _T("CreateWindow failed!"), _T("SetBkColor"), MB_OK | MB_ICONHAND); // MessageBox‚Å"CreateWindow failed!"‚ƃGƒ‰[ƒƒbƒZ[ƒW‚ð•\Ž¦. return -2; // ˆÙíI—¹(2) } // ƒEƒBƒ“ƒhƒE‚Ì•\Ž¦ ShowWindow(hWnd, SW_SHOW); // ShowWindow‚ÅSW_SHOW‚ðŽw’肵‚ăEƒBƒ“ƒhƒE‚Ì•\Ž¦. // ƒƒbƒZ[ƒWƒ‹[ƒv while (GetMessage(&msg, NULL, 0, 0) > 0) { // GetMessage‚сƒbƒZ[ƒW‚ðŽæ“¾, –ß‚è’l‚ª0‚æ‚è‘å‚«‚¢ŠÔ‚̓‹[ƒv‚µ‘±‚¯‚é. // ƒEƒBƒ“ƒhƒEƒƒbƒZ[ƒW‚Ì‘—o DispatchMessage(&msg); // DispatchMessage‚Ŏ󂯎æ‚Á‚½ƒƒbƒZ[ƒW‚ðƒEƒBƒ“ƒhƒEƒvƒƒV[ƒWƒƒ(‚±‚̏ꍇ‚Í“ÆŽ©‚É’è‹`‚µ‚½WindowProc)‚É‘—o. } // ƒvƒƒOƒ‰ƒ€‚̏I—¹ return (int)msg.wParam; // I—¹ƒR[ƒh(msg.wParam)‚ð–ß‚è’l‚Æ‚µ‚Ä•Ô‚·. } // WindowProcŠÖ”‚Ì’è‹` LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { // ƒEƒBƒ“ƒhƒEƒƒbƒZ[ƒW‚ɑ΂µ‚Ä“ÆŽ©‚̏ˆ—‚ð‚·‚é‚悤‚É’è‹`‚µ‚½ƒEƒBƒ“ƒhƒEƒvƒƒV[ƒWƒƒ. // ƒEƒBƒ“ƒhƒEƒƒbƒZ[ƒW‚ɑ΂·‚鏈—. switch (uMsg) { // switch-casa•¶‚ÅuMsg‚Ì’l‚²‚Ƃɏˆ—‚ðU‚蕪‚¯‚é. // ƒEƒBƒ“ƒhƒE‚̍쐬‚ªŠJŽn‚³‚ꂽŽž. case WM_CREATE: // ƒEƒBƒ“ƒhƒE‚̍쐬‚ªŠJŽn‚³‚ꂽŽž.(uMsg‚ªWM_CREATE‚ÌŽž.) // WM_CREATEƒuƒƒbƒN { // ƒEƒBƒ“ƒhƒEì¬¬Œ÷ return 0; // return•¶‚Å0‚ð•Ô‚µ‚Ä, ƒEƒBƒ“ƒhƒEì¬¬Œ÷‚Æ‚·‚é. } // Šù’è‚̏ˆ—‚ÖŒü‚©‚¤. break; // break‚Å”²‚¯‚Ä, Šù’è‚̏ˆ—(DefWindowProc)‚ÖŒü‚©‚¤. // ƒEƒBƒ“ƒhƒE‚ª”jŠü‚³‚ꂽŽž. case WM_DESTROY: // ƒEƒBƒ“ƒhƒE‚ª”jŠü‚³‚ꂽŽž.(uMsg‚ªWM_DESTROY‚ÌŽž.) // WM_DESTROYƒuƒƒbƒN { // I—¹ƒƒbƒZ[ƒW‚Ì‘—M. PostQuitMessage(0); // PostQuitMessage‚ŏI—¹ƒR[ƒh‚ð0‚Æ‚µ‚ÄWM_QUITƒƒbƒZ[ƒW‚𑗐M.(‚·‚é‚ƃƒbƒZ[ƒWƒ‹[ƒv‚ÌGetMessage‚Ì–ß‚è’l‚ª0‚É‚È‚é‚Ì‚Å, ƒƒbƒZ[ƒWƒ‹[ƒv‚©‚甲‚¯‚é.) } // Šù’è‚̏ˆ—‚ÖŒü‚©‚¤. break; // break‚Å”²‚¯‚Ä, Šù’è‚̏ˆ—(DefWindowProc)‚ÖŒü‚©‚¤. // ‰æ–Ê‚Ì•`‰æ‚ð—v‹‚³‚ꂽŽž. case WM_PAINT: // ‰æ–Ê‚Ì•`‰æ‚ð—v‹‚³‚ꂽŽž.(uMsg‚ªWM_PAINT‚ÌŽž.) // WM_PAINTƒuƒƒbƒN { // ‚±‚̃uƒƒbƒN‚̃[ƒJƒ‹•Ï”E”z—ñ‚̐錾‚Ə‰Šú‰». HDC hDC; // ƒfƒoƒCƒXƒRƒ“ƒeƒLƒXƒgƒnƒ“ƒhƒ‹‚ðŠi”[‚·‚éHDCŒ^•Ï”hDC. PAINTSTRUCT ps; // ƒyƒCƒ“ƒgî•ñ‚ðŠÇ—‚·‚éPAINTSTRUCT\‘¢‘ÌŒ^‚̕ϐ”ps. TCHAR tszText[] = _T("ABCDE"); // TCHARŒ^”z—ñtszText‚ð"ABCDE"‚ŏ‰Šú‰». size_t uiLen = 0; // tszText‚Ì’·‚³‚ðŠi”[‚·‚邽‚ß‚Ìsize_tŒ^•Ï”uiLen‚ð0‚ɏ‰Šú‰». // ƒEƒBƒ“ƒhƒE‚Ì•`‰æŠJŽn hDC = BeginPaint(hwnd, &ps); // BeginPaint‚Å‚±‚̃EƒBƒ“ƒhƒE‚Ì•`‰æ‚̏€”õ‚ð‚·‚é. –ß‚è’l‚ɂ̓fƒoƒCƒXƒRƒ“ƒeƒLƒXƒgƒnƒ“ƒhƒ‹‚ª•Ô‚é‚Ì‚Å, hDC‚ÉŠi”[. // ”wŒiF‚̐ݒè SetBkColor(hDC, RGB(0x00, 0x00, 0xff)); // SetBkColor‚ՂðƒZƒbƒg. // •`‰æF‚̐ݒè SetTextColor(hDC, RGB(0xff, 0x00, 0x00)); // SetTextColor‚ŐԂðƒZƒbƒg. // •¶Žš—ñ‚Ì•`‰æ uiLen = _tcslen(tszText); // _tcslen‚ÅtszText‚Ì’·‚³‚ðŽæ“¾‚µ, uiLen‚ÉŠi”[. TextOut(hDC, 50, 50, tszText, (int)uiLen); // TextOut‚ŃEƒBƒ“ƒhƒEhwnd‚̍À•W(50, 50)‚̈ʒu‚ÉtszText‚ð•`‰æ. // ƒEƒBƒ“ƒhƒE‚Ì•`‰æI—¹ EndPaint(hwnd, &ps); // EndPaint‚Å‚±‚̃EƒBƒ“ƒhƒE‚Ì•`‰æˆ—‚ðI—¹‚·‚é. } // Šù’è‚̏ˆ—‚ÖŒü‚©‚¤. break; // break‚Å”²‚¯‚Ä, Šù’è‚̏ˆ—(DefWindowProc)‚ÖŒü‚©‚¤. // ã‹LˆÈŠO‚ÌŽž. default: // ã‹LˆÈŠO‚Ì’l‚ÌŽž‚ÌŠù’菈—. // Šù’è‚̏ˆ—‚ÖŒü‚©‚¤. break; // break‚Å”²‚¯‚Ä, Šù’è‚̏ˆ—(DefWindowProc)‚ÖŒü‚©‚¤. } // ‚ ‚Æ‚ÍŠù’è‚̏ˆ—‚É”C‚¹‚é. return DefWindowProc(hwnd, uMsg, wParam, lParam); // –ß‚è’l‚àŠÜ‚ßDefWindowProc‚ÉŠù’è‚̏ˆ—‚ð”C‚¹‚é. }
bg1bgst333/Sample
winapi/SetBkColor/SetBkColor/src/SetBkColor/SetBkColor/SetBkColor.cpp
C++
mit
5,385
36.664336
246
0.486908
false
/** * * Modelo de Login usando MCV * Desenvolvido por Ricardo Hirashiki * Publicado em: http://www.sitedoricardo.com.br * Data: Ago/2011 * * Baseado na extensao criada por Wemerson Januario * http://code.google.com/p/login-window/ * */ Ext.define('Siccad.view.authentication.CapsWarningTooltip', { extend : 'Ext.tip.QuickTip', alias : 'widget.capswarningtooltip', target : 'authentication-login', id : 'toolcaps', anchor : 'left', anchorOffset : 60, width : 305, dismissDelay : 0, autoHide : false, disabled : false, title : '<b>Caps Lock est&aacute; ativada</b>', html : '<div>Se Caps lock estiver ativado, isso pode fazer com que voc&ecirc;</div>' + '<div>digite a senha incorretamente.</div><br/>' + '<div>Voc&ecirc; deve pressionar a tecla Caps lock para desativ&aacute;-la</div>' + '<div>antes de digitar a senha.</div>' });
romeugodoi/demo_sf2
src/Sicoob/SiccadBundle/Resources/public/js/siccad/view/authentication/CapsWarningTooltip.js
JavaScript
mit
1,010
32.896552
100
0.584158
false
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Rotate : MonoBehaviour { public Vector3 m_rotate; public float m_speed; void Start() { transform.rotation = Random.rotation; } // Update is called once per frame void Update () { transform.Rotate(m_rotate*Time.deltaTime* m_speed); } }
a172862967/ProceduralSphere
KGProceduralSphere/Assets/Demo/Rotate.cs
C#
mit
373
18.526316
59
0.67655
false
package slacknotifications.teamcity.payload; import jetbrains.buildServer.messages.Status; import jetbrains.buildServer.responsibility.ResponsibilityEntry; import jetbrains.buildServer.responsibility.TestNameResponsibilityEntry; import jetbrains.buildServer.serverSide.*; import jetbrains.buildServer.tests.TestName; import slacknotifications.teamcity.BuildStateEnum; import slacknotifications.teamcity.Loggers; import slacknotifications.teamcity.payload.content.SlackNotificationPayloadContent; import java.util.Collection; public class SlackNotificationPayloadManager { SBuildServer server; public SlackNotificationPayloadManager(SBuildServer server){ this.server = server; Loggers.SERVER.info("SlackNotificationPayloadManager :: Starting"); } public SlackNotificationPayloadContent beforeBuildFinish(SRunningBuild runningBuild, SFinishedBuild previousBuild) { SlackNotificationPayloadContent content = new SlackNotificationPayloadContent(server, runningBuild, previousBuild, BuildStateEnum.BEFORE_BUILD_FINISHED); return content; } public SlackNotificationPayloadContent buildFinished(SRunningBuild runningBuild, SFinishedBuild previousBuild) { SlackNotificationPayloadContent content = new SlackNotificationPayloadContent(server, runningBuild, previousBuild, BuildStateEnum.BUILD_FINISHED); return content; } public SlackNotificationPayloadContent buildInterrupted(SRunningBuild runningBuild, SFinishedBuild previousBuild) { SlackNotificationPayloadContent content = new SlackNotificationPayloadContent(server, runningBuild, previousBuild, BuildStateEnum.BUILD_INTERRUPTED); return content; } public SlackNotificationPayloadContent buildStarted(SRunningBuild runningBuild, SFinishedBuild previousBuild) { SlackNotificationPayloadContent content = new SlackNotificationPayloadContent(server, runningBuild, previousBuild, BuildStateEnum.BUILD_STARTED); return content; } /** Used by versions of TeamCity less than 7.0 */ public SlackNotificationPayloadContent responsibleChanged(SBuildType buildType, ResponsibilityInfo responsibilityInfoOld, ResponsibilityInfo responsibilityInfoNew, boolean isUserAction) { SlackNotificationPayloadContent content = new SlackNotificationPayloadContent(server, buildType, BuildStateEnum.RESPONSIBILITY_CHANGED); String oldUser = "Nobody"; String newUser = "Nobody"; try { oldUser = responsibilityInfoOld.getResponsibleUser().getDescriptiveName(); } catch (Exception e) {} try { newUser = responsibilityInfoNew.getResponsibleUser().getDescriptiveName(); } catch (Exception e) {} content.setText(buildType.getFullName().toString() + " changed responsibility from " + oldUser + " to " + newUser + " with comment '" + responsibilityInfoNew.getComment().toString().trim() + "'" ); return content; } /** Used by versions of TeamCity 7.0 and above */ public SlackNotificationPayloadContent responsibleChanged(SBuildType buildType, ResponsibilityEntry responsibilityEntryOld, ResponsibilityEntry responsibilityEntryNew) { SlackNotificationPayloadContent content = new SlackNotificationPayloadContent(server, buildType, BuildStateEnum.RESPONSIBILITY_CHANGED); String oldUser = "Nobody"; String newUser = "Nobody"; if (responsibilityEntryOld.getState() != ResponsibilityEntry.State.NONE) { oldUser = responsibilityEntryOld.getResponsibleUser().getDescriptiveName(); } if (responsibilityEntryNew.getState() != ResponsibilityEntry.State.NONE) { newUser = responsibilityEntryNew.getResponsibleUser().getDescriptiveName(); } content.setText(buildType.getFullName().toString().toString().trim() + " changed responsibility from " + oldUser + " to " + newUser + " with comment '" + responsibilityEntryNew.getComment().toString().trim() + "'" ); return content; } public SlackNotificationPayloadContent responsibleChanged(SProject project, TestNameResponsibilityEntry oldTestNameResponsibilityEntry, TestNameResponsibilityEntry newTestNameResponsibilityEntry, boolean isUserAction) { // TODO Auto-generated method stub return null; } public SlackNotificationPayloadContent responsibleChanged(SProject project, Collection<TestName> testNames, ResponsibilityEntry entry, boolean isUserAction) { // TODO Auto-generated method stub return null; } /* HashMap<String, SlackNotificationPayload> formats = new HashMap<String,SlackNotificationPayload>(); Comparator<SlackNotificationPayload> rankComparator = new SlackNotificationPayloadRankingComparator(); List<SlackNotificationPayload> orderedFormatCollection = new ArrayList<SlackNotificationPayload>(); SBuildServer server; public SlackNotificationPayloadManager(SBuildServer server){ this.server = server; Loggers.SERVER.info("SlackNotificationPayloadManager :: Starting"); } public void registerPayloadFormat(SlackNotificationPayload payloadFormat){ Loggers.SERVER.info(this.getClass().getSimpleName() + " :: Registering payload " + payloadFormat.getFormatShortName() + " with rank of " + payloadFormat.getRank()); formats.put(payloadFormat.getFormatShortName(),payloadFormat); this.orderedFormatCollection.add(payloadFormat); Collections.sort(this.orderedFormatCollection, rankComparator); Loggers.SERVER.debug(this.getClass().getSimpleName() + " :: Payloads list is " + this.orderedFormatCollection.size() + " items long. Payloads are ranked in the following order.."); for (SlackNotificationPayload pl : this.orderedFormatCollection){ Loggers.SERVER.debug(this.getClass().getSimpleName() + " :: Payload Name: " + pl.getFormatShortName() + " Rank: " + pl.getRank()); } } public SlackNotificationPayload getFormat(String formatShortname){ if (formats.containsKey(formatShortname)){ return formats.get(formatShortname); } return null; } public Boolean isRegisteredFormat(String format){ return formats.containsKey(format); } public Set<String> getRegisteredFormats(){ return formats.keySet(); } public Collection<SlackNotificationPayload> getRegisteredFormatsAsCollection(){ return orderedFormatCollection; } public SBuildServer getServer() { return server; } */ }
jeanregisser/tcSlackBuildNotifier
tcslackbuildnotifier-core/src/main/java/slacknotifications/teamcity/payload/SlackNotificationPayloadManager.java
Java
mit
7,122
41.142012
182
0.693064
false
<?php /* SRVDVServerBundle:Registration:email.txt.twig */ class __TwigTemplate_d9fb642ef38579dd6542f4eacc9668ce91ac497e0fd5b3f1b1ca25429847bdfe extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( 'subject' => array($this, 'block_subject'), 'body_text' => array($this, 'block_body_text'), 'body_html' => array($this, 'block_body_html'), ); } protected function doDisplay(array $context, array $blocks = array()) { $__internal_7a96ebd63b4296612d33f1d823c5023a1e83652097ab3b2f83bcd80ebfe28389 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"); $__internal_7a96ebd63b4296612d33f1d823c5023a1e83652097ab3b2f83bcd80ebfe28389->enter($__internal_7a96ebd63b4296612d33f1d823c5023a1e83652097ab3b2f83bcd80ebfe28389_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "SRVDVServerBundle:Registration:email.txt.twig")); // line 2 echo " "; // line 3 $this->displayBlock('subject', $context, $blocks); // line 8 $this->displayBlock('body_text', $context, $blocks); // line 13 $this->displayBlock('body_html', $context, $blocks); $__internal_7a96ebd63b4296612d33f1d823c5023a1e83652097ab3b2f83bcd80ebfe28389->leave($__internal_7a96ebd63b4296612d33f1d823c5023a1e83652097ab3b2f83bcd80ebfe28389_prof); } // line 3 public function block_subject($context, array $blocks = array()) { $__internal_8dec34524e53ef6eb9823b0097df011468b0fef15fddadcedc50239d971a3cfe = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"); $__internal_8dec34524e53ef6eb9823b0097df011468b0fef15fddadcedc50239d971a3cfe->enter($__internal_8dec34524e53ef6eb9823b0097df011468b0fef15fddadcedc50239d971a3cfe_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "subject")); // line 4 echo " "; // line 5 echo " "; echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\TranslationExtension')->trans("registration.email.subject", array("%username%" => $this->getAttribute((isset($context["user"]) ? $context["user"] : $this->getContext($context, "user")), "username", array()), "%confirmationUrl%" => (isset($context["confirmationUrl"]) ? $context["confirmationUrl"] : $this->getContext($context, "confirmationUrl"))), "FOSUserBundle"); echo " "; $__internal_8dec34524e53ef6eb9823b0097df011468b0fef15fddadcedc50239d971a3cfe->leave($__internal_8dec34524e53ef6eb9823b0097df011468b0fef15fddadcedc50239d971a3cfe_prof); } // line 8 public function block_body_text($context, array $blocks = array()) { $__internal_7131087c60e816b15fc165bd85f50803d3ee0c35a7e40bf98ad739acaf455904 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"); $__internal_7131087c60e816b15fc165bd85f50803d3ee0c35a7e40bf98ad739acaf455904->enter($__internal_7131087c60e816b15fc165bd85f50803d3ee0c35a7e40bf98ad739acaf455904_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "body_text")); // line 9 echo " "; // line 10 echo " "; echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\TranslationExtension')->trans("registration.email.message", array("%username%" => $this->getAttribute((isset($context["user"]) ? $context["user"] : $this->getContext($context, "user")), "username", array()), "%confirmationUrl%" => (isset($context["confirmationUrl"]) ? $context["confirmationUrl"] : $this->getContext($context, "confirmationUrl"))), "FOSUserBundle"); echo " "; $__internal_7131087c60e816b15fc165bd85f50803d3ee0c35a7e40bf98ad739acaf455904->leave($__internal_7131087c60e816b15fc165bd85f50803d3ee0c35a7e40bf98ad739acaf455904_prof); } // line 13 public function block_body_html($context, array $blocks = array()) { $__internal_35b67ba0a150c9c6c2bdcba437c30bb455fcc764d18c8bc8364adeec347d24a3 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"); $__internal_35b67ba0a150c9c6c2bdcba437c30bb455fcc764d18c8bc8364adeec347d24a3->enter($__internal_35b67ba0a150c9c6c2bdcba437c30bb455fcc764d18c8bc8364adeec347d24a3_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "body_html")); $__internal_35b67ba0a150c9c6c2bdcba437c30bb455fcc764d18c8bc8364adeec347d24a3->leave($__internal_35b67ba0a150c9c6c2bdcba437c30bb455fcc764d18c8bc8364adeec347d24a3_prof); } public function getTemplateName() { return "SRVDVServerBundle:Registration:email.txt.twig"; } public function getDebugInfo() { return array ( 75 => 13, 65 => 10, 63 => 9, 57 => 8, 47 => 5, 45 => 4, 39 => 3, 32 => 13, 30 => 8, 28 => 3, 25 => 2,); } /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */ public function getSource() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); return $this->getSourceContext()->getCode(); } public function getSourceContext() { return new Twig_Source("{% trans_default_domain 'FOSUserBundle' %} {% block subject %} {% autoescape false %} {{ 'registration.email.subject'|trans({'%username%': user.username, '%confirmationUrl%': confirmationUrl}) }} {% endautoescape %} {% endblock %} {% block body_text %} {% autoescape false %} {{ 'registration.email.message'|trans({'%username%': user.username, '%confirmationUrl%': confirmationUrl}) }} {% endautoescape %} {% endblock %} {% block body_html %}{% endblock %} ", "SRVDVServerBundle:Registration:email.txt.twig", "C:\\wamp64\\www\\serveurDeVoeux\\src\\SRVDV\\ServerBundle/Resources/views/Registration/email.txt.twig"); } }
youcefboukersi/serveurdevoeux
app/cache/dev/twig/a4/a4d5e331da6ebdf63a769ec513a07ed062a09e096299142f0540503ab3951bbb.php
PHP
mit
6,108
49.9
435
0.687459
false
using Portal.CMS.Entities.Enumerators; using Portal.CMS.Services.Generic; using Portal.CMS.Services.PageBuilder; using Portal.CMS.Web.Architecture.ActionFilters; using Portal.CMS.Web.Architecture.Extensions; using Portal.CMS.Web.Areas.PageBuilder.ViewModels.Component; using Portal.CMS.Web.ViewModels.Shared; using System; using System.Linq; using System.Threading.Tasks; using System.Web.Mvc; using System.Web.SessionState; namespace Portal.CMS.Web.Areas.PageBuilder.Controllers { [AdminFilter(ActionFilterResponseType.Modal)] [SessionState(SessionStateBehavior.ReadOnly)] public class ComponentController : Controller { private readonly IPageSectionService _pageSectionService; private readonly IPageComponentService _pageComponentService; private readonly IImageService _imageService; public ComponentController(IPageSectionService pageSectionService, IPageComponentService pageComponentService, IImageService imageService) { _pageSectionService = pageSectionService; _pageComponentService = pageComponentService; _imageService = imageService; } [HttpGet] [OutputCache(Duration = 86400)] public async Task<ActionResult> Add() { var model = new AddViewModel { PageComponentTypeList = await _pageComponentService.GetComponentTypesAsync() }; return View("_Add", model); } [HttpPost] [ValidateInput(false)] public async Task<JsonResult> Add(int pageSectionId, string containerElementId, string elementBody) { elementBody = elementBody.Replace("animated bounce", string.Empty); await _pageComponentService.AddAsync(pageSectionId, containerElementId, elementBody); return Json(new { State = true }); } [HttpPost] public async Task<ActionResult> Delete(int pageSectionId, string elementId) { try { await _pageComponentService.DeleteAsync(pageSectionId, elementId); return Json(new { State = true }); } catch (Exception ex) { return Json(new { State = false, Message = ex.InnerException }); } } [HttpPost] [ValidateInput(false)] public async Task<ActionResult> Edit(int pageSectionId, string elementId, string elementHtml) { await _pageComponentService.EditElementAsync(pageSectionId, elementId, elementHtml); return Content("Refresh"); } [HttpGet] public async Task<ActionResult> EditImage(int pageSectionId, string elementId, string elementType) { var imageList = await _imageService.GetAsync(); var model = new ImageViewModel { SectionId = pageSectionId, ElementType = elementType, ElementId = elementId, GeneralImages = new PaginationViewModel { PaginationType = "general", TargetInputField = "SelectedImageId", ImageList = imageList.Where(x => x.ImageCategory == ImageCategory.General) }, IconImages = new PaginationViewModel { PaginationType = "icon", TargetInputField = "SelectedImageId", ImageList = imageList.Where(x => x.ImageCategory == ImageCategory.Icon) }, ScreenshotImages = new PaginationViewModel { PaginationType = "screenshot", TargetInputField = "SelectedImageId", ImageList = imageList.Where(x => x.ImageCategory == ImageCategory.Screenshot) }, TextureImages = new PaginationViewModel { PaginationType = "texture", TargetInputField = "SelectedImageId", ImageList = imageList.Where(x => x.ImageCategory == ImageCategory.Texture) } }; return View("_EditImage", model); } [HttpPost] public async Task<JsonResult> EditImage(ImageViewModel model) { try { var selectedImage = await _imageService.GetAsync(model.SelectedImageId); await _pageComponentService.EditImageAsync(model.SectionId, model.ElementType, model.ElementId, selectedImage.CDNImagePath()); return Json(new { State = true, Source = selectedImage.CDNImagePath() }); } catch (Exception) { return Json(new { State = false }); } } [HttpGet] public ActionResult EditVideo(int pageSectionId, string widgetWrapperElementId, string videoPlayerElementId) { var model = new VideoViewModel { SectionId = pageSectionId, WidgetWrapperElementId = widgetWrapperElementId, VideoPlayerElementId = videoPlayerElementId, VideoUrl = string.Empty }; return View("_EditVideo", model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> EditVideo(VideoViewModel model) { try { await _pageComponentService.EditSourceAsync(model.SectionId, model.VideoPlayerElementId, model.VideoUrl); return Json(new { State = true }); } catch (Exception) { return Json(new { State = false }); } } [HttpGet] public ActionResult EditContainer(int pageSectionId, string elementId) { var model = new ContainerViewModel { SectionId = pageSectionId, ElementId = elementId }; return View("_EditContainer", model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> EditContainer(ContainerViewModel model) { await _pageSectionService.EditAnimationAsync(model.SectionId, model.ElementId, model.Animation.ToString()); return Content("Refresh"); } [HttpPost] [ValidateInput(false)] public async Task<ActionResult> Link(int pageSectionId, string elementId, string elementHtml, string elementHref, string elementTarget) { await _pageComponentService.EditAnchorAsync(pageSectionId, elementId, elementHtml, elementHref, elementTarget); return Content("Refresh"); } [HttpPost] public async Task<JsonResult> Clone(int pageSectionId, string elementId, string componentStamp) { await _pageComponentService.CloneElementAsync(pageSectionId, elementId, componentStamp); return Json(new { State = true }); } } }
tommcclean/PortalCMS
Portal.CMS.Web/Areas/PageBuilder/Controllers/ComponentController.cs
C#
mit
7,137
34.326733
146
0.592432
false
<?php /** * Created by PhpStorm. * User: robert * Date: 1/14/15 * Time: 3:06 PM */ namespace Skema\Directive; class Binding extends Base { }
Skema/Skema
Skema/Directive/Binding.php
PHP
mit
149
9.714286
28
0.630872
false
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ActionOnDispose.cs // // // Implemention of IDisposable that runs a delegate on Dispose. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Threading.Tasks.Dataflow.Internal { /// <summary>Provider of disposables that run actions.</summary> internal sealed class Disposables { /// <summary>An IDisposable that does nothing.</summary> internal readonly static IDisposable Nop = new NopDisposable(); /// <summary>Creates an IDisposable that runs an action when disposed.</summary> /// <typeparam name="T1">Specifies the type of the first argument.</typeparam> /// <typeparam name="T2">Specifies the type of the second argument.</typeparam> /// <param name="action">The action to invoke.</param> /// <param name="arg1">The first argument.</param> /// <param name="arg2">The second argument.</param> /// <returns>The created disposable.</returns> internal static IDisposable Create<T1, T2>(Action<T1, T2> action, T1 arg1, T2 arg2) { Contract.Requires(action != null, "Non-null disposer action required."); return new Disposable<T1, T2>(action, arg1, arg2); } /// <summary>Creates an IDisposable that runs an action when disposed.</summary> /// <typeparam name="T1">Specifies the type of the first argument.</typeparam> /// <typeparam name="T2">Specifies the type of the second argument.</typeparam> /// <typeparam name="T3">Specifies the type of the third argument.</typeparam> /// <param name="action">The action to invoke.</param> /// <param name="arg1">The first argument.</param> /// <param name="arg2">The second argument.</param> /// <param name="arg3">The third argument.</param> /// <returns>The created disposable.</returns> internal static IDisposable Create<T1, T2, T3>(Action<T1, T2, T3> action, T1 arg1, T2 arg2, T3 arg3) { Contract.Requires(action != null, "Non-null disposer action required."); return new Disposable<T1, T2, T3>(action, arg1, arg2, arg3); } /// <summary>A disposable that's a nop.</summary> [DebuggerDisplay("Disposed = true")] private sealed class NopDisposable : IDisposable { void IDisposable.Dispose() { } } /// <summary>An IDisposable that will run a delegate when disposed.</summary> [DebuggerDisplay("Disposed = {Disposed}")] private sealed class Disposable<T1, T2> : IDisposable { /// <summary>First state argument.</summary> private readonly T1 _arg1; /// <summary>Second state argument.</summary> private readonly T2 _arg2; /// <summary>The action to run when disposed. Null if disposed.</summary> private Action<T1, T2> _action; /// <summary>Initializes the ActionOnDispose.</summary> /// <param name="action">The action to run when disposed.</param> /// <param name="arg1">The first argument.</param> /// <param name="arg2">The second argument.</param> internal Disposable(Action<T1, T2> action, T1 arg1, T2 arg2) { Contract.Requires(action != null, "Non-null action needed for disposable"); _action = action; _arg1 = arg1; _arg2 = arg2; } /// <summary>Gets whether the IDisposable has been disposed.</summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private bool Disposed { get { return _action == null; } } /// <summary>Invoke the action.</summary> void IDisposable.Dispose() { Action<T1, T2> toRun = _action; if (toRun != null && Interlocked.CompareExchange(ref _action, null, toRun) == toRun) { toRun(_arg1, _arg2); } } } /// <summary>An IDisposable that will run a delegate when disposed.</summary> [DebuggerDisplay("Disposed = {Disposed}")] private sealed class Disposable<T1, T2, T3> : IDisposable { /// <summary>First state argument.</summary> private readonly T1 _arg1; /// <summary>Second state argument.</summary> private readonly T2 _arg2; /// <summary>Third state argument.</summary> private readonly T3 _arg3; /// <summary>The action to run when disposed. Null if disposed.</summary> private Action<T1, T2, T3> _action; /// <summary>Initializes the ActionOnDispose.</summary> /// <param name="action">The action to run when disposed.</param> /// <param name="arg1">The first argument.</param> /// <param name="arg2">The second argument.</param> /// <param name="arg3">The third argument.</param> internal Disposable(Action<T1, T2, T3> action, T1 arg1, T2 arg2, T3 arg3) { Contract.Requires(action != null, "Non-null action needed for disposable"); _action = action; _arg1 = arg1; _arg2 = arg2; _arg3 = arg3; } /// <summary>Gets whether the IDisposable has been disposed.</summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private bool Disposed { get { return _action == null; } } /// <summary>Invoke the action.</summary> void IDisposable.Dispose() { Action<T1, T2, T3> toRun = _action; if (toRun != null && Interlocked.CompareExchange(ref _action, null, toRun) == toRun) { toRun(_arg1, _arg2, _arg3); } } } } }
cuteant/dotnet-tpl-dataflow
source/Internal/ActionOnDispose.cs
C#
mit
5,481
37.584507
102
0.657419
false
using System; using System.Collections.Generic; using Esb.Transport; namespace Esb.Message { public interface IMessageQueue { void Add(Envelope message); IEnumerable<Envelope> Messages { get; } Envelope GetNextMessage(); void SuspendMessages(Type messageType); void ResumeMessages(Type messageType); void RerouteMessages(Type messageType); void RemoveMessages(Type messageType); event EventHandler<EventArgs> OnMessageArived; IRouter Router { get; set; } } }
Xynratron/WorkingCluster
Esb/Message/IMessageQueue.cs
C#
mit
548
25.047619
54
0.681319
false
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <CRealMoveRequestDelayCheckerDetail.hpp> #include <common/ATFCore.hpp> START_ATF_NAMESPACE namespace Register { class CRealMoveRequestDelayCheckerRegister : public IRegister { public: void Register() override { auto& hook_core = CATFCore::get_instance(); for (auto& r : Detail::CRealMoveRequestDelayChecker_functions) hook_core.reg_wrapper(r.pBind, r); } }; }; // end namespace Register END_ATF_NAMESPACE
goodwinxp/Yorozuya
library/ATF/CRealMoveRequestDelayCheckerRegister.hpp
C++
mit
727
30.608696
108
0.605227
false
title: 会声会影安装与激活 date: 2016-06-05 22:58:54 tags: --- ## 资源 * [会声会影下载](http://www.huishenghuiying.com.cn/xiazai.html#selctbuy) * [会声会影注册机下载](https://hostr.co/file/FDp8MOYlRuHv/AppNee.com.Corel.X5-X9.All.Products.Universal.Keygen.7z?warning=on) * 转载:[会声会影安装与激活](https://luoyefe.com/blog/2016/06/05/%E4%BC%9A%E5%A3%B0%E4%BC%9A%E5%BD%B1%E5%AE%89%E8%A3%85%E4%B8%8E%E6%BF%80%E6%B4%BB/) @[Github](https://github.com/luoye-fe/hexo-blog/tree/master/source/_posts) ## 安装(x8版本) #### 1、找到下载好的以 `.exe` 为结尾的安装文件,将后缀名改为 `.rar`,然后打开此压缩包(不是解压,用360压缩等工具打开) #### 2、打开压缩包中的 `setup.xml` * 搜索 `SHOWSERIALDIALOG`,将其 `value` 改为 `true` * 搜索 `SERIALNUMBER`,将其 `value` 删除 > 修改前 ![](https://github.com/luoye-fe/hexo-blog/blob/master/source/_posts/会声会影安装与激活/1.png) > 修改后 ![](https://github.com/luoye-fe/hexo-blog/blob/master/source/_posts/会声会影安装与激活/2.png) 然后将 `.rar` 改回 `.exe` #### 3、断开网络链接 #### 4、打开注册机,选择产品为 `Corel VideoStudio Pro/Ulitime X8` ![](https://github.com/luoye-fe/hexo-blog/blob/master/source/_posts/会声会影安装与激活/3.png) #### 5、双击打开安装包 * 勾选接受协议,下一步 ![](https://github.com/luoye-fe/hexo-blog/blob/master/source/_posts/会声会影安装与激活/4.png) * 要求输入序列号 ![](https://github.com/luoye-fe/hexo-blog/blob/master/source/_posts/会声会影安装与激活/5.png) * 拷贝注册机中生成的序列号 ![](https://github.com/luoye-fe/hexo-blog/blob/master/source/_posts/会声会影安装与激活/6.png) * 粘贴在输入框内,点击下一步 ![](https://github.com/luoye-fe/hexo-blog/blob/master/source/_posts/会声会影安装与激活/7.png) * 位置默认,视频标准默认,安装位置自定义,点击立即安装,等待安装完成 ![](https://github.com/luoye-fe/hexo-blog/blob/master/source/_posts/会声会影安装与激活/8.png) #### 6、打开会声会影主程序,第一次打开会提示为试用版30天,有功能限制,无视。待程序打开后,关闭程序 > 这个地方有可能出现打开主程序提示试用版然后打不开软件的情况,此时,链接上网络,双击 `Corel FastFlick X8`,会出现提示注册的界面,输入邮箱进行注册,如下 ![](https://github.com/luoye-fe/hexo-blog/blob/master/source/_posts/会声会影安装与激活/9.png) ![](https://github.com/luoye-fe/hexo-blog/blob/master/source/_posts/会声会影安装与激活/10.png) > 点击下一步,完成后关闭页面 * 出现如下界面时,断开网络链接,根据箭头指示点击 ![](https://github.com/luoye-fe/hexo-blog/blob/master/source/_posts/会声会影安装与激活/11.png) ![](https://github.com/luoye-fe/hexo-blog/blob/master/source/_posts/会声会影安装与激活/12.png) * 在注册机中输入安装码(只能手工输入,注意连字符) ![](https://github.com/luoye-fe/hexo-blog/blob/master/source/_posts/会声会影安装与激活/13.png) ![](https://github.com/luoye-fe/hexo-blog/blob/master/source/_posts/会声会影安装与激活/14.png) * 点击 `Generate Activation Code` 生成激活码 ![](https://github.com/luoye-fe/hexo-blog/blob/master/source/_posts/会声会影安装与激活/15.png) * 复制生成好的激活码 ![](https://github.com/luoye-fe/hexo-blog/blob/master/source/_posts/会声会影安装与激活/16.png) * 粘贴在安装程序激活码位置 ![](https://github.com/luoye-fe/hexo-blog/blob/master/source/_posts/会声会影安装与激活/17.png) * 点击下一步完成激活 ![](https://github.com/luoye-fe/hexo-blog/blob/master/source/_posts/会声会影安装与激活/18.png) * 链接网络,打开主程序,已成功激活 ![](https://github.com/luoye-fe/hexo-blog/blob/master/source/_posts/会声会影安装与激活/19.png)
taoste/taoste.github.io
intl/Tool/会声会影安装与激活/会声会影安装与激活.md
Markdown
mit
4,053
33.728395
212
0.727337
false
// generates an interface file given an eni file // you can generate an eni file using the aws-cli // example: // aws ec2 describe-network-interfaces --network-interface-ids eni-2492676c > eni-7290653a.json var ENI_FILE = "json/eni-651e2c2c.json"; // the interface you want to configure var INTERFACE = "eth1"; // port you want squid proxy to start at; doesn't matter if you're not using squid var PORT = 3188; // get the gateway ip by running `route -n` var GATEWAYIP = "172.31.16.1"; // number to start with in RT TABLES var RT_TABLES = 2; fs = require('fs'); fs.readFile(ENI_FILE, function (err, data) { if (!err) { var eni = JSON.parse(data).NetworkInterfaces[0]; var netConfig = "auto " + INTERFACE + "\niface " + INTERFACE + " inet dhcp\n\n"; var squidConfig = ""; var rtTables = ""; for (var i = 0; i < eni.PrivateIpAddresses.length; i++) { var addressObject = eni.PrivateIpAddresses[i]; // construct string // current subinterface var subinterface = INTERFACE + ":" + i; netConfig += "auto " + subinterface + "\n"; netConfig += "iface "+ subinterface + " inet static\n"; netConfig += "address " + addressObject.PrivateIpAddress + "\n"; // this IP is the gateway IP netConfig += "up ip route add default via " + GATEWAYIP + " dev " + subinterface + " table " + subinterface + "\n" netConfig += "up ip rule add from " + addressObject.PrivateIpAddress + " lookup " + subinterface + "\n\n"; squidConfig += "http_port localhost:" + PORT + " name="+ PORT + "\nacl a" + PORT + " myportname " + PORT + " src localhost\nhttp_access allow a" + PORT + "\ntcp_outgoing_address " + addressObject.PrivateIpAddress + " a" + PORT + "\n\n"; rtTables += RT_TABLES + " " + subinterface + "\n"; PORT++; RT_TABLES++; }; // trim newlines netConfig = netConfig.replace(/^\s+|\s+$/g, ''); squidConfig = squidConfig.replace(/^\s+|\s+$/g, ''); rtTables = rtTables.replace(/^\s+|\s+$/g, ''); fs.writeFile("./cfg/" + INTERFACE + ".cfg", netConfig, function(err) { if(err) { console.log(err); } else { console.log("Generated networking config and saved it to " + INTERFACE + ".cfg."); } }); fs.writeFile("./cfg/" + INTERFACE + "-squid.cfg", squidConfig, function(err) { if(err) { console.log(err); } else { console.log("Generated squid config and saved it to " + INTERFACE + ".cfg."); } }); fs.writeFile("./cfg/" + INTERFACE + "-rt_tables.cfg", rtTables, function(err) { if(err) { console.log(err); } else { console.log("Generated rt_tables and saved it to " + INTERFACE + ".cfg."); } }); } if (err) { console.log("Error! Make sure you're running this in the config-utils directory and that the JSON file + the cfg directory are both there."); } });
lukemiles/aws-eni-configutil
interface-gen.js
JavaScript
mit
2,829
36.236842
239
0.618593
false
# nodejs-boilerplate ## About A boilerplate for a developer environment pre-built for a nodejs project using expressjs for the backend and angularjs for the front end. This boilerplate also comes with a built in logger for requests as well as a Gruntfile with my favorite addons for developing nodejs projects. :godmode: ## Dependencies **AngularJS** Using the Browserify addon in grunt, I've created a folder structure for organizing angular projects into smaller components within the *public/js/modules* folder. While running grunt watch, all of these files are included in *public/js/main.js* and will continue to be compressed into *public/js/bundle.min.js*. I have set AngularJS html5Mode option to true and have made the server configurations necessary to remove the hashtag from urls. Strict mode has been added to each module to ensure proper javascript is being used. **bower** Using a .bowerrc file, I have set it so running *bower install* will install packages directly into the *public/js/bower_components* folder. This is intended to keep frontend libraries and frameworks seperate from backend node_modules and Gruntfile addons. **SASS and Compass** This boilerplate comes with the SASS precompiler and I have decided to go with SCSS because I enjoy curly brackets. **Grunt** Be sure to keep the grunt watch task running during development. I've set jshint to all javascript files including those found in the backend. Thank you and have a nice day :)
typicalmike002/nodejs-boilerplate
README.md
Markdown
mit
1,485
52.035714
313
0.791919
false
//----------------------------------------------------------------------- // <copyright file="LocalizableFormBase.cs" company="Hyperar"> // Copyright (c) Hyperar. All rights reserved. // </copyright> // <author>Matías Ezequiel Sánchez</author> //----------------------------------------------------------------------- namespace Hyperar.HattrickUltimate.UserInterface { using System; using System.Windows.Forms; using Interface; /// <summary> /// ILocalizableForm base implementation. /// </summary> public partial class LocalizableFormBase : Form, ILocalizableForm { #region Public Methods /// <summary> /// Populates controls' properties with the corresponding localized string. /// </summary> public virtual void PopulateLanguage() { } #endregion Public Methods #region Protected Methods /// <summary> /// Raises the System.Windows.Forms.Form.Load event. /// </summary> /// <param name="e">An System.EventArgs that contains the event data.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); this.PopulateLanguage(); } #endregion Protected Methods } }
hyperar/Hattrick-Ultimate
Hyperar.HattrickUltimate.UserInterface/LocalizableFormBase.cs
C#
mit
1,283
28.090909
85
0.544957
false
var width = window.innerWidth, height = window.innerHeight, boids = [], destination, canvas, context; const MAX_NUMBER = 100; const MAX_SPEED = 1; const radius = 5; init(); animation(); function init(){ canvas = document.getElementById('canvas'), context = canvas.getContext( "2d" ); canvas.width = width; canvas.height = height; destination = { x:Math.random()*width, y:Math.random()*height }; for (var i = 0; i <MAX_NUMBER; i++) { boids[i] = new Boid(); }; } var _animation; function animation(){ _animation = requestAnimationFrame(animation); context.clearRect(0,0,width,height); for (var i = 0; i < boids.length; i++) { boids[i].rule1(); boids[i].rule2(); boids[i].rule3(); boids[i].rule4(); boids[i].rule5(); boids[i].rule6(); var nowSpeed = Math.sqrt(boids[i].vx * boids[i].vx + boids[i].vy * boids[i].vy ); if(nowSpeed > MAX_SPEED){ boids[i].vx *= MAX_SPEED / nowSpeed; boids[i].vy *= MAX_SPEED / nowSpeed; } boids[i].x += boids[i].vx; boids[i].y += boids[i].vy; drawCircle(boids[i].x,boids[i].y); drawVector(boids[i].x,boids[i].y,boids[i].vx,boids[i].vy); }; } /* //mouseEvent document.onmousemove = function (event){ destination ={ x:event.screenX, y:event.screenY } }; */ function Boid(){ this.x = Math.random()*width; this.y = Math.random()*height; this.vx = 0.0; this.vy = 0.0; this.dx = Math.random()*width; this.dy = Math.random()*height; //群れの中心に向かう this.rule1 = function(){ var centerx = 0, centery = 0; for (var i = 0; i < boids.length; i++) { if (boids[i] != this) { centerx += boids[i].x; centery += boids[i].y; }; }; centerx /= MAX_NUMBER-1; centery /= MAX_NUMBER-1; this.vx += (centerx-this.x)/1000; this.vy += (centery-this.y)/1000; } //他の個体と離れるように動く this.rule2 = function(){ var _vx = 0, _vy = 0; for (var i = 0; i < boids.length; i++) { if(this != boids[i]){ var distance = distanceTo(this.x,boids[i].x,this.y,boids[i].y); if(distance<25){ distance += 0.001; _vx -= (boids[i].x - this.x)/distance; _vy -= (boids[i].y - this.y)/distance; //this.dx = -boids[i].x; //this.dy = -boids[i].y; } } }; this.vx += _vx; this.vy += _vy; } //他の個体と同じ速度で動こうとする this.rule3 = function(){ var _pvx = 0, _pvy = 0; for (var i = 0; i < boids.length; i++) { if (boids[i] != this) { _pvx += boids[i].vx; _pvy += boids[i].vy; } }; _pvx /= MAX_NUMBER-1; _pvy /= MAX_NUMBER-1; this.vx += (_pvx - this.vx)/10; this.vy += (_pvy - this.vy)/10; }; //壁側の時の振る舞い this.rule4 = function(){ if(this.x < 10 && this.vx < 0)this.vx += 10/(Math.abs( this.x ) + 1 ); if(this.x > width && this.vx > 0)this.vx -= 10/(Math.abs( width - this.x ) + 1 ); if (this.y < 10 && this.vy < 0)this.vy += 10/(Math.abs( this.y ) + 1 ); if(this.y > height && this.vy > 0)this.vy -= 10/(Math.abs( height - this.y ) + 1 ); }; //目的地に行く this.rule5 = function(){ var _dx = this.dx - this.x, _dy = this.dy - this.y; this.vx += (this.dx - this.x)/500; this.vy += (this.dy - this.y)/500; } //捕食する this.rule6 = function(){ var _vx = Math.random()-0.5, _vy = Math.random()-0.5; for (var i = 0; i < boids.length; i++) { if(this != boids[i] && this.dx != boids[i].dx && this.dy != boids[i].dy){ var distance = distanceTo(this.x,boids[i].x,this.y,boids[i].y); if(distance<20 && distance>15){ console.log(distance); distance += 0.001; _vx += (boids[i].x - this.x)/distance; _vy += (boids[i].y - this.y)/distance; drawLine(this.x,this.y,boids[i].x,boids[i].y); this.dx = boids[i].dx; this.dy = boids[i].dy; } } }; this.vx += _vx; this.vy += _vy; } } function distanceTo(x1,x2,y1,y2){ var dx = x2-x1, dy = y2-y1; return Math.sqrt(dx*dx+dy*dy); } function drawCircle(x,y){ context.beginPath(); context.strokeStyle = "#fff"; context.arc(x,y,radius,0,Math.PI*2,false); context.stroke(); } const VectorLong = 10; function drawVector(x,y,vx,vy){ context.beginPath(); var pointx = x+vx*VectorLong; var pointy = y+vy*VectorLong; context.moveTo(x,y); context.lineTo(pointx,pointy); context.stroke(); } function drawLine(x1,y1,x2,y2){ context.beginPath(); context.moveTo(x1,y1); context.lineTo(x2,y2); context.stroke(); }
yuuki2006628/boid
boid.js
JavaScript
mit
4,749
23.015544
87
0.536785
false
package com.facetime.spring.support; import java.util.ArrayList; import java.util.List; import com.facetime.core.conf.ConfigUtils; import com.facetime.core.utils.StringUtils; /** * 分页类 * * @author yufei * @param <T> */ public class Page<T> { private static int BEGIN_PAGE_SIZE = 20; /** 下拉分页列表的递增数量级 */ private static int ADD_PAGE_SIZE_RATIO = 10; public static int DEFAULT_PAGE_SIZE = 10; private static int MAX_PAGE_SIZE = 200; private QueryInfo<T> queryInfo = null; private List<T> queryResult = null; public Page() { this(new QueryInfo<T>()); } public Page(QueryInfo<T> queryInfo) { this.queryInfo = queryInfo; this.queryResult = new ArrayList<T>(15); } /** * @return 下拉分页列表的递增数量级 */ public final static int getAddPageSize() { String addPageSizeRatio = ConfigUtils.getProperty("add_page_size_ratio"); if (StringUtils.isValid(addPageSizeRatio)) ADD_PAGE_SIZE_RATIO = Integer.parseInt(addPageSizeRatio); return ADD_PAGE_SIZE_RATIO; } /** * @return 默认分页下拉列表的开始值 */ public final static int getBeginPageSize() { String beginPageSize = ConfigUtils.getProperty("begin_page_size"); if (StringUtils.isValid(beginPageSize)) BEGIN_PAGE_SIZE = Integer.parseInt(beginPageSize); return BEGIN_PAGE_SIZE; } /** * 默认列表记录显示条数 */ public static final int getDefaultPageSize() { String defaultPageSize = ConfigUtils.getProperty("default_page_size"); if (StringUtils.isValid(defaultPageSize)) DEFAULT_PAGE_SIZE = Integer.parseInt(defaultPageSize); return DEFAULT_PAGE_SIZE; } /** * 默认分页列表显示的最大记录条数 */ public static final int getMaxPageSize() { String maxPageSize = ConfigUtils.getProperty("max_page_size"); if (StringUtils.isValid(maxPageSize)) { MAX_PAGE_SIZE = Integer.parseInt(maxPageSize); } return MAX_PAGE_SIZE; } public String getBeanName() { return this.queryInfo.getBeanName(); } public int getCurrentPageNo() { return this.queryInfo.getCurrentPageNo(); } public String getKey() { return this.queryInfo.getKey(); } public Integer getNeedRowNum() { return this.getPageSize() - this.getQueryResult().size(); } public long getNextPage() { return this.queryInfo.getNextPage(); } public int getPageCount() { return this.queryInfo.getPageCount(); } public int getPageSize() { return this.queryInfo.getPageSize(); } public List<T> getParams() { return this.queryInfo.getParams(); } public int getPreviousPage() { return this.queryInfo.getPreviousPage(); } public String[] getProperties() { return this.queryInfo.getProperties(); } public List<T> getQueryResult() { return this.queryResult; } public int getRecordCount() { return this.queryInfo.getRecordCount(); } public String getSql() { return this.queryInfo.getSql(); } public boolean isHasResult() { return this.queryResult != null && this.queryResult.size() > 0; } public void setBeanName(String beanNameValue) { this.queryInfo.setBeanName(beanNameValue); } public void setCurrentPageNo(int currentPageNo) { this.queryInfo.setCurrentPageNo(currentPageNo); } public void setKey(String keyValue) { this.queryInfo.setKey(keyValue); } public void setPageCount(int pageCount) { this.queryInfo.setPageCount(pageCount); } public void setPageSize(int pageSize) { this.queryInfo.setPageSize(pageSize); } public void setParams(List<T> paramsValue) { this.queryInfo.setParams(paramsValue); } public void setProperties(String[] propertiesValue) { this.queryInfo.setProperties(propertiesValue); } public void setQueryResult(List<T> list) { this.queryResult = list; } public void setRecordCount(int count) { this.queryInfo.setRecordCount(count); } public void setSql(String sql) { this.queryInfo.setSql(sql); } }
allanfish/facetime
facetime-spring/src/main/java/com/facetime/spring/support/Page.java
Java
mit
3,885
21.1
75
0.722651
false
--- layout: post title: Mancester 6/26 --- ### Screened today, imaged 6/22 growth exp. & screened larvae; cleaned broodstock, yada yada yada... #### Imaged 6/22 SN growth experiment larvae Grace imaged the well plate, taking photos of first the well #, then larvae, not capturing the same larvae more than once. She imaged a ruler whenever it was necessary to adjust the zoom. Images will named and uploaded to my [O.lurida repo images folder](https://github.com/laurahspencer/O.lurida_Stress/tree/master/Images) using the following well plate map: ![file_000 8](https://user-images.githubusercontent.com/17264765/27980511-534852be-6334-11e7-9249-69d9f0de8dba.jpeg) #### Screening data ![snip20170707_48](https://user-images.githubusercontent.com/17264765/27980434-79d1d1ea-6333-11e7-8c35-bf04684e528d.png) ![snip20170707_46](https://user-images.githubusercontent.com/17264765/27980433-79d01ac6-6333-11e7-8c2c-1a7b3af70e77.png) TB Continued.... need to reference notebook entry left @ home
laurahspencer/LabNotebook
_posts/2017-06-26-Manchester6-26.md
Markdown
mit
994
61.125
359
0.779678
false
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL'; -- ---------------------------------------------------------------------------------------------------------- -- TABLES -- ---------------------------------------------------------------------------------------------------------- -- ----------------------------------------------------- -- Table `gene` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `gene` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `hgnc_id` int(10) unsigned NOT NULL, `symbol` varchar(40) NOT NULL, `name` TEXT NOT NULL, `type` enum('protein-coding gene','pseudogene','non-coding RNA','other') NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `hgnc_id` (`hgnc_id`), UNIQUE KEY `symbol` (`symbol`), KEY `type` (`type`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Genes from HGNC'; -- ----------------------------------------------------- -- Table `gene_alias` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `gene_alias` ( `gene_id` int(10) unsigned NOT NULL, `symbol` varchar(40) NOT NULL, `type` enum('synonym','previous') NOT NULL, KEY `fk_gene_id1` (`gene_id` ASC) , CONSTRAINT `fk_gene_id1` FOREIGN KEY (`gene_id` ) REFERENCES `gene` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, KEY `symbol` (`symbol`), KEY `type` (`type`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Alternative symbols of genes'; -- ----------------------------------------------------- -- Table `gene_transcript` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `gene_transcript` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `gene_id` int(10) unsigned NOT NULL, `name` varchar(40) NOT NULL, `source` enum('ccds', 'ensembl') NOT NULL, `chromosome` enum('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','X','Y','MT') NOT NULL, `start_coding` int(10) unsigned NULL, `end_coding` int(10) unsigned NULL, `strand` enum('+', '-') NOT NULL, PRIMARY KEY (`id`), CONSTRAINT `fk_gene_id3` FOREIGN KEY (`gene_id` ) REFERENCES `gene` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, UNIQUE KEY `gene_name_unique` (`gene_id`, `name`), UNIQUE KEY `name` (`name`) , KEY `source` (`source`), KEY `chromosome` (`chromosome`), KEY `start_coding` (`start_coding`), KEY `end_coding` (`end_coding`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Gene transcipts'; -- ----------------------------------------------------- -- Table `gene_exon` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `gene_exon` ( `transcript_id` int(10) unsigned NOT NULL, `start` int(10) unsigned NOT NULL, `end` int(10) unsigned NOT NULL, KEY `fk_transcript_id2` (`transcript_id` ASC) , CONSTRAINT `fk_transcript_id2` FOREIGN KEY (`transcript_id` ) REFERENCES `gene_transcript` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, KEY `start` (`start`), KEY `end` (`end`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Transcript exons'; -- ----------------------------------------------------- -- Table `geneinfo_germline` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `geneinfo_germline` ( `symbol` VARCHAR(40) NOT NULL, `inheritance` ENUM('AR','AD','AR+AD','XLR','XLD','XLR+XLD','MT','MU','n/a') NOT NULL, `gnomad_oe_syn` FLOAT NULL, `gnomad_oe_mis` FLOAT NULL, `gnomad_oe_lof` FLOAT NULL, `comments` text NOT NULL, PRIMARY KEY `symbol` (`symbol`) ) ENGINE=InnoDB CHARSET=utf8; -- ----------------------------------------------------- -- Table `mid` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `mid` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) NOT NULL, `sequence` VARCHAR(45) NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `genome` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `genome` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `build` VARCHAR(45) NOT NULL, `comment` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `build_UNIQUE` (`build` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `processing_system` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `processing_system` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name_short` VARCHAR(50) NOT NULL, `name_manufacturer` VARCHAR(100) NOT NULL, `adapter1_p5` VARCHAR(45) NULL DEFAULT NULL, `adapter2_p7` VARCHAR(45) NULL DEFAULT NULL, `type` ENUM('WGS','WGS (shallow)','WES','Panel','Panel Haloplex','Panel MIPs','RNA','ChIP-Seq', 'cfDNA (patient-specific)', 'cfDNA') NOT NULL, `shotgun` TINYINT(1) NOT NULL, `umi_type` ENUM('n/a','HaloPlex HS','SureSelect HS','ThruPLEX','Safe-SeqS','MIPs','QIAseq','IDT-UDI-UMI','IDT-xGen-Prism') NOT NULL DEFAULT 'n/a', `target_file` VARCHAR(255) NULL DEFAULT NULL COMMENT 'filename of sub-panel BED file relative to the megSAP enrichment folder.', `genome_id` INT(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `name_short` (`name_short` ASC), UNIQUE INDEX `name_manufacturer` (`name_manufacturer` ASC), INDEX `fk_processing_system_genome1` (`genome_id` ASC), CONSTRAINT `fk_processing_system_genome1` FOREIGN KEY (`genome_id`) REFERENCES `genome` (`id`) ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `device` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `device` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `type` ENUM('GAIIx','MiSeq','HiSeq2500','NextSeq500','NovaSeq5000','NovaSeq6000','MGI-2000','SequelII','PromethION') NOT NULL, `name` VARCHAR(45) NOT NULL, `comment` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `sequencing_run` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sequencing_run` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NOT NULL, `fcid` VARCHAR(45) NULL DEFAULT NULL, `flowcell_type` ENUM('Illumina MiSeq v2','Illumina MiSeq v2 Micro','Illumina MiSeq v2 Nano','Illumina MiSeq v3','Illumina NextSeq High Output','Illumina NextSeq Mid Output','Illumina NovaSeq SP','Illumina NovaSeq S1','Illumina NovaSeq S2','Illumina NovaSeq S4','PromethION FLO-PRO002','SMRTCell 8M','n/a') NOT NULL DEFAULT 'n/a', `start_date` DATE NULL DEFAULT NULL, `end_date` DATE NULL DEFAULT NULL, `device_id` INT(11) NOT NULL, `recipe` VARCHAR(45) NOT NULL COMMENT 'Read length for reads and index reads separated by \'+\'', `pool_molarity` float DEFAULT NULL, `pool_quantification_method` enum('n/a','Tapestation','Bioanalyzer','qPCR','Tapestation & Qubit','Bioanalyzer & Qubit','Bioanalyzer & Tecan Infinite','Fragment Analyzer & Qubit','Fragment Analyzer & Tecan Infinite','Illumina 450bp & Qubit ssDNA','PCR Size & ssDNA') NOT NULL DEFAULT 'n/a', `comment` TEXT NULL DEFAULT NULL, `quality` ENUM('n/a','good','medium','bad') NOT NULL DEFAULT 'n/a', `status` ENUM('n/a','run_started','run_finished','run_aborted','demultiplexing_started','analysis_started','analysis_finished','analysis_not_possible','analysis_and_backup_not_required') NOT NULL DEFAULT 'n/a', `backup_done` TINYINT(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name` ASC), UNIQUE INDEX `fcid_UNIQUE` (`fcid` ASC), INDEX `fk_run_device1` (`device_id` ASC), CONSTRAINT `fk_run_device1` FOREIGN KEY (`device_id`) REFERENCES `device` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `runqc_read` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `runqc_read` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `read_num` INT NOT NULL, `cycles` INT NOT NULL, `is_index` BOOLEAN NOT NULL, `q30_perc` FLOAT NOT NULL, `error_rate` FLOAT DEFAULT NULL, `sequencing_run_id` INT(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE (`sequencing_run_id`, `read_num`), INDEX `fk_sequencing_run_id` (`sequencing_run_id` ASC), CONSTRAINT `fk_sequencing_run_id` FOREIGN KEY (`sequencing_run_id`) REFERENCES `sequencing_run` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `runqc_lane` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `runqc_lane` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `lane_num` INT NOT NULL, `cluster_density` FLOAT NOT NULL, `cluster_density_pf` FLOAT NOT NULL, `yield` FLOAT NOT NULL, `error_rate` FLOAT DEFAULT NULL, `q30_perc` FLOAT NOT NULL, `occupied_perc` FLOAT DEFAULT NULL, `runqc_read_id` INT(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE (`runqc_read_id`, `lane_num`), INDEX `fk_runqc_read_id` (`runqc_read_id` ASC), CONSTRAINT `fk_runqc_read_id` FOREIGN KEY (`runqc_read_id`) REFERENCES `runqc_read` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `species` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `species` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `sender` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sender` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NOT NULL, `phone` VARCHAR(45) NULL DEFAULT NULL, `email` VARCHAR(45) NULL DEFAULT NULL, `affiliation` VARCHAR(100) NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `user` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `user` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `user_id` VARCHAR(45) NOT NULL COMMENT 'Use the lower-case Windows domain name!', `password` VARCHAR(64) NOT NULL, `user_role` ENUM('user','admin','special') NOT NULL, `name` VARCHAR(45) NOT NULL, `email` VARCHAR(100) NOT NULL, `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `last_login` DATETIME NULL DEFAULT NULL, `active` TINYINT(1) DEFAULT 1 NOT NULL, `salt` VARCHAR(40) NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`user_id` ASC), UNIQUE INDEX `email_UNIQUE` (`email` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `sample` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sample` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(20) NOT NULL, `name_external` VARCHAR(255) NULL DEFAULT NULL COMMENT 'External names.<br>If several, separate by comma!<br>Always enter full names, no short forms!', `received` DATE NULL DEFAULT NULL, `receiver_id` INT(11) NULL DEFAULT NULL, `sample_type` ENUM('DNA','DNA (amplicon)','DNA (native)','RNA','cfDNA') NOT NULL, `species_id` INT(11) NOT NULL, `concentration` FLOAT NULL DEFAULT NULL, `volume` FLOAT NULL DEFAULT NULL, `od_260_280` FLOAT NULL DEFAULT NULL, `gender` ENUM('male','female','n/a') NOT NULL, `comment` TEXT NULL DEFAULT NULL, `quality` ENUM('n/a','good','medium','bad') NOT NULL DEFAULT 'n/a', `od_260_230` FLOAT NULL DEFAULT NULL, `integrity_number` FLOAT NULL DEFAULT NULL, `tumor` TINYINT(1) NOT NULL, `ffpe` TINYINT(1) NOT NULL, `sender_id` INT(11) NOT NULL, `disease_group` ENUM('n/a','Neoplasms','Diseases of the blood or blood-forming organs','Diseases of the immune system','Endocrine, nutritional or metabolic diseases','Mental, behavioural or neurodevelopmental disorders','Sleep-wake disorders','Diseases of the nervous system','Diseases of the visual system','Diseases of the ear or mastoid process','Diseases of the circulatory system','Diseases of the respiratory system','Diseases of the digestive system','Diseases of the skin','Diseases of the musculoskeletal system or connective tissue','Diseases of the genitourinary system','Developmental anomalies','Other diseases') NOT NULL DEFAULT 'n/a', `disease_status` ENUM('n/a','Affected','Unaffected','Unclear') NOT NULL DEFAULT 'n/a', `tissue` ENUM('n/a','Blood','Buccal mucosa','Skin') NOT NULL DEFAULT 'n/a', PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name` ASC), INDEX `fk_samples_species1` (`species_id` ASC), INDEX `sender_id` (`sender_id` ASC), INDEX `receiver_id` (`receiver_id` ASC), INDEX `name_external` (`name_external` ASC), INDEX `tumor` (`tumor` ASC), INDEX `quality` (`quality` ASC), INDEX `disease_group` (`disease_group`), INDEX `disease_status` (`disease_status`), CONSTRAINT `fk_samples_species1` FOREIGN KEY (`species_id`) REFERENCES `species` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `sample_ibfk_1` FOREIGN KEY (`sender_id`) REFERENCES `sender` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `sample_ibfk_2` FOREIGN KEY (`receiver_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `sample_disease_info` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sample_disease_info` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `sample_id` INT(11) NOT NULL, `disease_info` TEXT NOT NULL, `type` ENUM('HPO term id', 'ICD10 code', 'OMIM disease/phenotype identifier', 'Orpha number', 'CGI cancer type', 'tumor fraction', 'age of onset', 'clinical phenotype (free text)', 'RNA reference tissue') NOT NULL, `user_id` int(11) DEFAULT NULL, `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), CONSTRAINT `fk_sample_id` FOREIGN KEY (`sample_id`) REFERENCES `sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_user` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `sample_relations` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sample_relations` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `sample1_id` INT(11) NOT NULL, `relation` ENUM('parent-child', 'tumor-normal', 'siblings', 'same sample', 'tumor-cfDNA', 'same patient', 'cousins', 'twins', 'twins (monozygotic)') NOT NULL, `sample2_id` INT(11) NOT NULL, `user_id` int(11) DEFAULT NULL, `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE INDEX `relation_unique` (`sample1_id` ASC, `relation` ASC, `sample2_id` ASC), CONSTRAINT `fk_sample1_id` FOREIGN KEY (`sample1_id`) REFERENCES `sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_sample2_id` FOREIGN KEY (`sample2_id`) REFERENCES `sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_user2` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `project` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `project` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NOT NULL, `aliases` TEXT DEFAULT NULL, `type` ENUM('diagnostic','research','test','external') NOT NULL, `internal_coordinator_id` INT(11) NOT NULL COMMENT 'Person who is responsible for this project.<br>The person will be notified when new samples are available.', `comment` TEXT NULL DEFAULT NULL, `analysis` ENUM('fastq','mapping','variants') NOT NULL DEFAULT 'variants' COMMENT 'Bioinformatics analysis to be done for non-tumor germline samples in this project.<br>"fastq" skips the complete analysis.<br>"mapping" creates the BAM file but calls no variants.<br>"variants" performs the full analysis.', `preserve_fastqs` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Prevents FASTQ files from being deleted after mapping in this project.<br>Has no effect if megSAP is not configured to delete FASTQs automatically.<br>For diagnostics, do not check. For other project types ask the bioinformatician in charge.', `email_notification` varchar(200) DEFAULT NULL COMMENT 'List of email addresses (separated by semicolon) that are notified in addition to the project coordinator when new samples are available.', PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name` ASC), INDEX `internal_coordinator_id` (`internal_coordinator_id` ASC), CONSTRAINT `project_ibfk_1` FOREIGN KEY (`internal_coordinator_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `processed_sample` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `processed_sample` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `sample_id` INT(11) NOT NULL, `process_id` INT(2) NOT NULL, `sequencing_run_id` INT(11) NULL DEFAULT NULL, `lane` varchar(15) NOT NULL COMMENT 'Comma-separated lane list (1-8)', `mid1_i7` INT(11) NULL DEFAULT NULL, `mid2_i5` INT(11) NULL DEFAULT NULL, `operator_id` INT(11) NULL DEFAULT NULL, `processing_system_id` INT(11) NOT NULL, `comment` TEXT NULL DEFAULT NULL, `project_id` INT(11) NOT NULL, `processing_input` FLOAT NULL DEFAULT NULL, `molarity` FLOAT NULL DEFAULT NULL, `normal_id` INT(11) NULL DEFAULT NULL COMMENT 'For tumor samples, a normal sample can be given here which is used as reference sample during the data analysis.', `quality` ENUM('n/a','good','medium','bad') NOT NULL DEFAULT 'n/a', PRIMARY KEY (`id`), UNIQUE INDEX `sample_psid_unique` (`sample_id` ASC, `process_id` ASC), INDEX `fk_processed_sample_samples1` (`sample_id` ASC), INDEX `fk_processed_sample_mid1` (`mid1_i7` ASC), INDEX `fk_processed_sample_processing_system1` (`processing_system_id` ASC), INDEX `fk_processed_sample_run1` (`sequencing_run_id` ASC), INDEX `fk_processed_sample_mid2` (`mid2_i5` ASC), INDEX `project_id` (`project_id` ASC), INDEX `operator_id` (`operator_id` ASC), INDEX `normal_id_INDEX` (`normal_id` ASC), INDEX `quality` (`quality` ASC), CONSTRAINT `fk_processed_sample_mid1` FOREIGN KEY (`mid1_i7`) REFERENCES `mid` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_processed_sample_mid2` FOREIGN KEY (`mid2_i5`) REFERENCES `mid` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_processed_sample_processing_system1` FOREIGN KEY (`processing_system_id`) REFERENCES `processing_system` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_processed_sample_run1` FOREIGN KEY (`sequencing_run_id`) REFERENCES `sequencing_run` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_processed_sample_sample2` FOREIGN KEY (`normal_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_processed_sample_samples1` FOREIGN KEY (`sample_id`) REFERENCES `sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `processed_sample_ibfk_1` FOREIGN KEY (`project_id`) REFERENCES `project` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `processed_sample_ibfk_2` FOREIGN KEY (`operator_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `variant` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `variant` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `chr` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `start` INT(11) NOT NULL, `end` INT(11) NOT NULL, `ref` TEXT NOT NULL, `obs` TEXT NOT NULL, `1000g` FLOAT NULL DEFAULT NULL, `gnomad` FLOAT NULL DEFAULT NULL, `coding` TEXT NULL DEFAULT NULL, `comment` TEXT NULL DEFAULT NULL, `cadd` FLOAT NULL DEFAULT NULL, `spliceai` FLOAT NULL DEFAULT NULL, `germline_het` INT(11) NOT NULL DEFAULT '0', `germline_hom` INT(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE INDEX `variant_UNIQUE` (`chr` ASC, `start` ASC, `end` ASC, `ref`(255) ASC, `obs`(255) ASC), INDEX `1000g` (`1000g` ASC), INDEX `gnomad` (`gnomad` ASC), INDEX `comment` (`comment`(50) ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `variant_publication` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `variant_publication` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `sample_id` INT(11) NOT NULL, `variant_id` INT(11) NOT NULL, `db` ENUM('LOVD','ClinVar') NOT NULL, `class` ENUM('1','2','3','4','5', 'M') NOT NULL, `details` TEXT NOT NULL, `user_id` INT(11) NOT NULL, `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `result` TEXT DEFAULT NULL, `replaced` BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (`id`), CONSTRAINT `fk_variant_publication_has_user` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_variant_publication_has_sample` FOREIGN KEY (`sample_id`) REFERENCES `sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_variant_publication_has_variant` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `variant_classification` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `variant_classification` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `variant_id` INT(11) NOT NULL, `class` ENUM('n/a','1','2','3','4','5','M') NOT NULL, `comment` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `fk_variant_classification_has_variant` (`variant_id`), CONSTRAINT `fk_variant_classification_has_variant` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, INDEX `class` (`class` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `somatic_variant_classification` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `somatic_variant_classification` ( `id` int(11) NOT NULL AUTO_INCREMENT, `variant_id` int(11) NOT NULL, `class` ENUM('n/a','activating','likely_activating','inactivating','likely_inactivating','unclear','test_dependent') NOT NULL, `comment` TEXT, PRIMARY KEY (`id`), UNIQUE KEY `somatic_variant_classification_has_variant` (`variant_id`), CONSTRAINT `somatic_variant_classification_has_variant` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `somatic_vicc_interpretation` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `somatic_vicc_interpretation` ( `id` int(11) NOT NULL AUTO_INCREMENT, `variant_id` int(11) NOT NULL, `null_mutation_in_tsg` BOOLEAN NULL DEFAULT NULL, `known_oncogenic_aa` BOOLEAN NULL DEFAULT NULL, `oncogenic_funtional_studies` BOOLEAN NULL DEFAULT NULL, `strong_cancerhotspot` BOOLEAN NULL DEFAULT NULL, `located_in_canerhotspot` BOOLEAN NULL DEFAULT NULL, `absent_from_controls` BOOLEAN NULL DEFAULT NULL, `protein_length_change` BOOLEAN NULL DEFAULT NULL, `other_aa_known_oncogenic` BOOLEAN NULL DEFAULT NULL, `weak_cancerhotspot` BOOLEAN NULL DEFAULT NULL, `computational_evidence` BOOLEAN NULL DEFAULT NULL, `mutation_in_gene_with_etiology` BOOLEAN NULL DEFAULT NULL, `very_weak_cancerhotspot` BOOLEAN NULL DEFAULT NULL, `very_high_maf` BOOLEAN NULL DEFAULT NULL, `benign_functional_studies` BOOLEAN NULL DEFAULT NULL, `high_maf` BOOLEAN NULL DEFAULT NULL, `benign_computational_evidence` BOOLEAN NULL DEFAULT NULL, `synonymous_mutation` BOOLEAN NULL DEFAULT NULL, `comment` TEXT NULL DEFAULT NULL, `created_by` int(11) DEFAULT NULL, `created_date` DATETIME NOT NULL, `last_edit_by` int(11) DEFAULT NULL, `last_edit_date` TIMESTAMP NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `somatic_vicc_interpretation_has_variant` (`variant_id`), CONSTRAINT `somatic_vicc_interpretation_has_variant` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `somatic_vicc_interpretation_created_by_user` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `somatic_vicc_interpretation_last_edit_by_user` FOREIGN KEY (`last_edit_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `somatic_gene_role` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `somatic_gene_role` ( `id` int(11) NOT NULL AUTO_INCREMENT, `symbol` VARCHAR(40) NOT NULL, `gene_role` ENUM('activating','loss_of_function', 'ambiguous') NOT NULL, `high_evidence` BOOLEAN DEFAULT FALSE, `comment` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY (`symbol`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `detected_variant` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `detected_variant` ( `processed_sample_id` INT(11) NOT NULL, `variant_id` INT(11) NOT NULL, `genotype` ENUM('hom','het') NOT NULL, PRIMARY KEY (`processed_sample_id`, `variant_id`), INDEX `fk_detected_variant_variant1` (`variant_id` ASC), CONSTRAINT `fk_processed_sample_has_variant_processed_sample1` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_processed_sample_has_variant_variant1` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `qc_terms` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `qc_terms` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `qcml_id` VARCHAR(10) NULL DEFAULT NULL, `name` VARCHAR(45) NOT NULL, `description` TEXT NOT NULL, `type` ENUM('float', 'int', 'string') NOT NULL, `obsolete` TINYINT(1) NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name` ASC), UNIQUE INDEX `qcml_id_UNIQUE` (`qcml_id` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `processed_sample_qc` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `processed_sample_qc` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `processed_sample_id` INT(11) NOT NULL, `qc_terms_id` INT(11) NOT NULL, `value` TEXT NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `c_processing_id_qc_terms_id` (`processed_sample_id` ASC, `qc_terms_id` ASC), INDEX `fk_qcvalues_processing1` (`processed_sample_id` ASC), INDEX `fk_processed_sample_annotaiton_qcml1` (`qc_terms_id` ASC), CONSTRAINT `fk_processed_sample_annotaiton_qcml1` FOREIGN KEY (`qc_terms_id`) REFERENCES `qc_terms` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_qcvalues_processing1` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `sample_group` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sample_group` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NOT NULL, `comment` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `nm_sample_sample_group` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `nm_sample_sample_group` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `sample_group_id` INT(11) NOT NULL, `sample_id` INT(11) NOT NULL, PRIMARY KEY (`id`), INDEX `fk_sample_group_has_sample_sample1` (`sample_id` ASC), INDEX `fk_sample_group_has_sample_sample_group1` (`sample_group_id` ASC), CONSTRAINT `fk_sample_group_has_sample_sample1` FOREIGN KEY (`sample_id`) REFERENCES `sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_sample_group_has_sample_sample_group1` FOREIGN KEY (`sample_group_id`) REFERENCES `sample_group` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `detected_somatic_variant` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `detected_somatic_variant` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `processed_sample_id_tumor` INT(11) NOT NULL, `processed_sample_id_normal` INT(11) NULL DEFAULT NULL, `variant_id` INT(11) NOT NULL, `variant_frequency` FLOAT NOT NULL, `depth` INT(11) NOT NULL, `quality_snp` FLOAT NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `detected_somatic_variant_UNIQUE` (`processed_sample_id_tumor` ASC, `processed_sample_id_normal` ASC, `variant_id` ASC), INDEX `variant_id_INDEX` (`variant_id` ASC), INDEX `processed_sample_id_tumor_INDEX` (`processed_sample_id_tumor` ASC), INDEX `processed_sample_id_normal_INDEX` (`processed_sample_id_normal` ASC), INDEX `fk_dsv_has_ps1` (`processed_sample_id_tumor` ASC), INDEX `fk_dsv_has_ps2` (`processed_sample_id_normal` ASC), CONSTRAINT `fk_dsv_has_ps1` FOREIGN KEY (`processed_sample_id_tumor`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_dsv_has_ps2` FOREIGN KEY (`processed_sample_id_normal`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_dsv_has_v` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `diag_status` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `diag_status` ( `processed_sample_id` INT(11) NOT NULL, `status` ENUM('pending','in progress','done','done - follow up pending','cancelled','not usable because of data quality') NOT NULL, `user_id` INT(11) NOT NULL, `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `outcome` ENUM('n/a','no significant findings','uncertain','significant findings','significant findings - second method', 'significant findings - non-genetic', 'candidate gene') NOT NULL DEFAULT 'n/a', `comment` TEXT NULL DEFAULT NULL, PRIMARY KEY (`processed_sample_id`), INDEX `user_id` (`user_id` ASC), CONSTRAINT `diag_status_ibfk_1` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `diag_status_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `kasp_status` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `kasp_status` ( `processed_sample_id` INT(11) NOT NULL, `random_error_prob` FLOAT UNSIGNED NOT NULL, `snps_evaluated` INT(10) UNSIGNED NOT NULL, `snps_match` INT(10) UNSIGNED NOT NULL, PRIMARY KEY (`processed_sample_id`), CONSTRAINT `processed_sample0` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `hpo_term` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `hpo_term` ( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `hpo_id` VARCHAR(10) NOT NULL, `name` TEXT NOT NULL, `definition` TEXT NOT NULL, `synonyms` TEXT NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `hpo_id` (`hpo_id` ASC), INDEX `name` (`name`(100) ASC), INDEX `synonyms` (`synonyms`(100) ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `hpo_genes` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `hpo_genes` ( `hpo_term_id` INT(10) UNSIGNED NOT NULL, `gene` VARCHAR(40) CHARACTER SET 'utf8' NOT NULL, `details` TEXT COMMENT 'Semicolon seperated pairs of database sources with evidences of where the connection was found (Source, Original Evidence, Evidence translated; Source2, ....)', `evidence` ENUM('n/a','low','medium','high') NOT NULL DEFAULT 'n/a', PRIMARY KEY (`hpo_term_id`, `gene`), CONSTRAINT `hpo_genes_ibfk_1` FOREIGN KEY (`hpo_term_id`) REFERENCES `hpo_term` (`id`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `hpo_parent` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `hpo_parent` ( `parent` INT(10) UNSIGNED NOT NULL, `child` INT(10) UNSIGNED NOT NULL, PRIMARY KEY (`parent`, `child`), INDEX `child` (`child` ASC), CONSTRAINT `hpo_parent_ibfk_2` FOREIGN KEY (`child`) REFERENCES `hpo_term` (`id`), CONSTRAINT `hpo_parent_ibfk_1` FOREIGN KEY (`parent`) REFERENCES `hpo_term` (`id`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `analysis_job` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `analysis_job` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `type` enum('single sample','multi sample','trio','somatic') NOT NULL, `high_priority` TINYINT(1) NOT NULL, `args` text NOT NULL, `sge_id` varchar(10) DEFAULT NULL, `sge_queue` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ----------------------------------------------------- -- Table `analysis_job_sample` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `analysis_job_sample` ( `id` int(11) NOT NULL AUTO_INCREMENT, `analysis_job_id` int(11) NOT NULL, `processed_sample_id` int(11) NOT NULL, `info` text NOT NULL, PRIMARY KEY (`id`), CONSTRAINT `fk_analysis_job_id` FOREIGN KEY (`analysis_job_id` ) REFERENCES `analysis_job` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_processed_sample_id` FOREIGN KEY (`processed_sample_id` ) REFERENCES `processed_sample` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ----------------------------------------------------- -- Table `analysis_job_history` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `analysis_job_history` ( `id` int(11) NOT NULL AUTO_INCREMENT, `analysis_job_id` int(11) NOT NULL, `time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `user_id` int(11) DEFAULT NULL, `status` enum('queued','started','finished','cancel','canceled','error') NOT NULL, `output` text DEFAULT NULL, PRIMARY KEY (`id`), CONSTRAINT `fk_analysis_job_id2` FOREIGN KEY (`analysis_job_id` ) REFERENCES `analysis_job` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_user_id2` FOREIGN KEY (`user_id` ) REFERENCES `user` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ----------------------------------------------------- -- Table `omim_gene` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `omim_gene` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `gene` VARCHAR(40) CHARACTER SET 'utf8' NOT NULL, `mim` VARCHAR(10) CHARACTER SET 'utf8' NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `mim_unique` (`mim`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `omim_phenotype` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `omim_phenotype` ( `omim_gene_id` INT(11) UNSIGNED NOT NULL, `phenotype` VARCHAR(255) CHARACTER SET 'utf8' NOT NULL, PRIMARY KEY (`omim_gene_id`, `phenotype`), CONSTRAINT `omim_gene_id_FK` FOREIGN KEY (`omim_gene_id` ) REFERENCES `omim_gene` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `omim_preferred_phenotype` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `omim_preferred_phenotype` ( `gene` VARCHAR(40) CHARACTER SET 'utf8' NOT NULL, `disease_group` ENUM('Neoplasms','Diseases of the blood or blood-forming organs','Diseases of the immune system','Endocrine, nutritional or metabolic diseases','Mental, behavioural or neurodevelopmental disorders','Sleep-wake disorders','Diseases of the nervous system','Diseases of the visual system','Diseases of the ear or mastoid process','Diseases of the circulatory system','Diseases of the respiratory system','Diseases of the digestive system','Diseases of the skin','Diseases of the musculoskeletal system or connective tissue','Diseases of the genitourinary system','Developmental anomalies','Other diseases') NOT NULL, `phenotype_accession` VARCHAR(6) CHARACTER SET 'utf8' NOT NULL, PRIMARY KEY (`gene`,`disease_group`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `merged_processed_samples` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `merged_processed_samples` ( `processed_sample_id` INT(11) NOT NULL, `merged_into` INT(11) NOT NULL, PRIMARY KEY (`processed_sample_id`), CONSTRAINT `merged_processed_samples_ps_id` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `merged_processed_samples_merged_into` FOREIGN KEY (`merged_into`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `somatic_report_configuration` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `somatic_report_configuration` ( `id` int(11) NOT NULL AUTO_INCREMENT, `ps_tumor_id` int(11) NOT NULL, `ps_normal_id` int(11) NOT NULL, `created_by` int(11) NOT NULL, `created_date` DATETIME NOT NULL, `last_edit_by` int(11) DEFAULT NULL, `last_edit_date` timestamp NULL DEFAULT NULL, `mtb_xml_upload_date` timestamp NULL DEFAULT NULL, `target_file` VARCHAR(255) NULL DEFAULT NULL COMMENT 'filename of sub-panel BED file without path', `tum_content_max_af` BOOLEAN NOT NULL DEFAULT FALSE COMMENT 'include tumor content calculated by median value maximum allele frequency', `tum_content_max_clonality` BOOLEAN NOT NULL DEFAULT FALSE COMMENT 'include tumor content calculated by maximum CNV clonality', `tum_content_hist` BOOLEAN NOT NULL DEFAULT FALSE COMMENT 'include histological tumor content estimate ', `msi_status` BOOLEAN NOT NULL DEFAULT FALSE COMMENT 'include microsatellite instability status', `cnv_burden` BOOLEAN NOT NULL DEFAULT FALSE, `hrd_score` TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'homologous recombination deficiency score, determined manually by user', `hrd_statement` ENUM('no proof', 'proof', 'undeterminable') NULL DEFAULT NULL COMMENT 'comment to be shown in somatic report about HRD score', `cnv_loh_count` INT(11) NULL DEFAULT NULL COMMENT 'number of somatic LOH events, determined from CNV file', `cnv_tai_count` INT(11) NULL DEFAULT NULL COMMENT 'number of somatic telomer allelic imbalance events, determined from CNV file', `cnv_lst_count` INT(11) NULL DEFAULT NULL COMMENT 'number of somatic long state transitions events, determined from CNV file', `tmb_ref_text` VARCHAR(200) NULL DEFAULT NULL COMMENT 'reference data as free text for tumor mutation burden', `quality` ENUM('no abnormalities','tumor cell content too low', 'quality of tumor DNA too low', 'DNA quantity too low', 'heterogeneous sample') NULL DEFAULT NULL COMMENT 'user comment on the quality of the DNA', `fusions_detected` BOOLEAN NOT NULL DEFAULT FALSE COMMENT 'fusions or other SVs were detected. Cannot be determined automatically, because manta files contain too many false positives', `cin_chr` TEXT NULL DEFAULT NULL COMMENT 'comma separated list of instable chromosomes', `limitations` TEXT NULL DEFAULT NULL COMMENT 'manually created text if the analysis has special limitations', `filter` VARCHAR(255) NULL DEFAULT NULL COMMENT 'name of the variant filter', PRIMARY KEY (`id`), UNIQUE INDEX `combo_som_rep_conf_ids` (`ps_tumor_id` ASC, `ps_normal_id` ASC), CONSTRAINT `somatic_report_config_created_by_user` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `somatic_report_config_last_edit_by_user` FOREIGN KEY (`last_edit_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `somatic_report_config_ps_normal_id` FOREIGN KEY (`ps_normal_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `somatic_report_config_ps_tumor_id` FOREIGN KEY (`ps_tumor_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARSET = utf8; -- ----------------------------------------------------- -- Table `somatic_report_configuration_variant` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `somatic_report_configuration_variant` ( `id` int(11) NOT NULL AUTO_INCREMENT, `somatic_report_configuration_id` int(11) NOT NULL, `variant_id` int(11) NOT NULL, `exclude_artefact` BOOLEAN NOT NULL, `exclude_low_tumor_content` BOOLEAN NOT NULL, `exclude_low_copy_number` BOOLEAN NOT NULL, `exclude_high_baf_deviation` BOOLEAN NOT NULL, `exclude_other_reason` BOOLEAN NOT NULL, `include_variant_alteration` text DEFAULT NULL, `include_variant_description` text DEFAULT NULL, `comment` text NOT NULL, PRIMARY KEY (`id`), CONSTRAINT `som_rep_conf_var_has_som_rep_conf_id` FOREIGN KEY (`somatic_report_configuration_id`) REFERENCES `somatic_report_configuration` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `somatic_report_configuration_variant_has_variant_id` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, UNIQUE INDEX `som_conf_var_combo_uniq_index` (`somatic_report_configuration_id` ASC, `variant_id` ASC) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ----------------------------------------------------- -- Table `somatic_report_configuration_germl_snv` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `somatic_report_configuration_germl_var` ( `id` int(11) NOT NULL AUTO_INCREMENT, `somatic_report_configuration_id` int(11) NOT NULL, `variant_id` int(11) NOT NULL, `tum_freq` FLOAT UNSIGNED NULL DEFAULT NULL COMMENT 'frequency of this variant in the tumor sample.', `tum_depth` int(11) UNSIGNED NULL DEFAULT NULL COMMENT 'depth of this variant in the tumor sample.', PRIMARY KEY (`id`), CONSTRAINT `som_rep_conf_germl_var_has_rep_conf_id` FOREIGN KEY (`somatic_report_configuration_id`) REFERENCES `somatic_report_configuration` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `som_rep_germl_var_has_var_id` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, UNIQUE INDEX `som_conf_germl_var_combo_uni_idx` (`somatic_report_configuration_id` ASC, `variant_id` ASC) ) COMMENT='variants detected in control tissue that are marked as tumor related by the user' ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ----------------------------------------------------- -- Table `somatic_cnv_callset` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `somatic_cnv_callset` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `ps_tumor_id` INT(11) NOT NULL, `ps_normal_id` INT(11) NOT NULL, `caller` ENUM('ClinCNV') NOT NULL, `caller_version` varchar(25) NOT NULL, `call_date` DATETIME NOT NULL, `quality_metrics` TEXT DEFAULT NULL COMMENT 'quality metrics as JSON key-value array', `quality` ENUM('n/a','good','medium','bad') NOT NULL DEFAULT 'n/a', PRIMARY KEY (`id`), INDEX `caller` (`caller` ASC), INDEX `call_date` (`call_date` ASC), INDEX `quality` (`quality` ASC), UNIQUE INDEX `combo_ids` (`ps_tumor_id` ASC, `ps_normal_id` ASC), CONSTRAINT `som_cnv_callset_ps_normal_id` FOREIGN KEY (`ps_normal_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `som_cnv_callset_ps_tumor_id` FOREIGN KEY (`ps_tumor_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COMMENT='somatic CNV call set'; -- ----------------------------------------------------- -- Table `somatic_cnv` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `somatic_cnv` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `somatic_cnv_callset_id` INT(11) UNSIGNED NOT NULL, `chr` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `start` INT(11) UNSIGNED NOT NULL, `end` INT(11) UNSIGNED NOT NULL, `cn` FLOAT UNSIGNED NOT NULL COMMENT 'copy-number change in whole sample, including normal parts', `tumor_cn` INT(11) UNSIGNED NOT NULL COMMENT 'copy-number change normalized to tumor tissue only', `tumor_clonality` FLOAT NOT NULL COMMENT 'tumor clonality, i.e. fraction of tumor cells', `quality_metrics` TEXT DEFAULT NULL COMMENT 'quality metrics as JSON key-value array', PRIMARY KEY (`id`), CONSTRAINT `som_cnv_references_cnv_callset` FOREIGN KEY (`somatic_cnv_callset_id`) REFERENCES `somatic_cnv_callset` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `unique_callset_cnv_pair` UNIQUE(`somatic_cnv_callset_id`,`chr`,`start`,`end`), INDEX `chr` (`chr` ASC), INDEX `start` (`start` ASC), INDEX `end` (`end` ASC), INDEX `tumor_cn` (`tumor_cn` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COMMENT='somatic CNV'; -- ----------------------------------------------------- -- Table `somatic_report_configuration_cnv` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `somatic_report_configuration_cnv` ( `id` int(11) NOT NULL AUTO_INCREMENT, `somatic_report_configuration_id` int(11) NOT NULL, `somatic_cnv_id` int(11) UNSIGNED NOT NULL, `exclude_artefact` BOOLEAN NOT NULL, `exclude_low_tumor_content` BOOLEAN NOT NULL, `exclude_low_copy_number` BOOLEAN NOT NULL, `exclude_high_baf_deviation` BOOLEAN NOT NULL, `exclude_other_reason` BOOLEAN NOT NULL, `comment` text NOT NULL, PRIMARY KEY (`id`), CONSTRAINT `som_rep_conf_cnv_has_som_rep_conf_id` FOREIGN KEY (`somatic_report_configuration_id`) REFERENCES `somatic_report_configuration` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `som_report_conf_cnv_has_som_cnv_id` FOREIGN KEY (`somatic_cnv_id`) REFERENCES `somatic_cnv` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, UNIQUE INDEX `som_conf_cnv_combo_uniq_index` (`somatic_report_configuration_id` ASC, `somatic_cnv_id` ASC) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ----------------------------------------------------- -- Table `report_configuration` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `report_configuration` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `processed_sample_id` INT(11) NOT NULL, `created_by` int(11) NOT NULL, `created_date` DATETIME NOT NULL, `last_edit_by` int(11) DEFAULT NULL, `last_edit_date` TIMESTAMP NULL DEFAULT NULL, `finalized_by` int(11) DEFAULT NULL, `finalized_date` TIMESTAMP NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `processed_sample_id_unique` (`processed_sample_id`), CONSTRAINT `fk_processed_sample_id2` FOREIGN KEY (`processed_sample_id` ) REFERENCES `processed_sample` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `report_configuration_created_by` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `report_configuration_last_edit_by` FOREIGN KEY (`last_edit_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `report_configuration_finalized_by` FOREIGN KEY (`finalized_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `report_configuration_variant` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `report_configuration_variant` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `report_configuration_id` INT(11) NOT NULL, `variant_id` INT(11) NOT NULL, `type` ENUM('diagnostic variant', 'candidate variant', 'incidental finding') NOT NULL, `causal` BOOLEAN NOT NULL, `inheritance` ENUM('n/a', 'AR','AD','XLR','XLD','MT') NOT NULL, `de_novo` BOOLEAN NOT NULL, `mosaic` BOOLEAN NOT NULL, `compound_heterozygous` BOOLEAN NOT NULL, `exclude_artefact` BOOLEAN NOT NULL, `exclude_frequency` BOOLEAN NOT NULL, `exclude_phenotype` BOOLEAN NOT NULL, `exclude_mechanism` BOOLEAN NOT NULL, `exclude_other` BOOLEAN NOT NULL, `comments` text NOT NULL, `comments2` text NOT NULL, PRIMARY KEY (`id`), CONSTRAINT `fk_report_configuration` FOREIGN KEY (`report_configuration_id` ) REFERENCES `report_configuration` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_report_configuration_variant_has_variant` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, UNIQUE INDEX `config_variant_combo_uniq` (`report_configuration_id` ASC, `variant_id` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `disease_term` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `disease_term` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `source` ENUM('OrphaNet') NOT NULL, `identifier` VARCHAR(40) CHARACTER SET 'utf8' NOT NULL, `name` TEXT CHARACTER SET 'utf8' NOT NULL, `synonyms` TEXT CHARACTER SET 'utf8' DEFAULT NULL, PRIMARY KEY (`id`), INDEX `disease_source` (`source` ASC), UNIQUE KEY `disease_id` (`identifier`), INDEX `disease_name` (`name`(50) ASC), INDEX `disease_synonyms` (`synonyms`(50) ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `disease_gene` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `disease_gene` ( `disease_term_id` INT(11) UNSIGNED NOT NULL, `gene` VARCHAR(40) CHARACTER SET 'utf8' NOT NULL, PRIMARY KEY (`disease_term_id`, `gene`), CONSTRAINT `disease_genes_ibfk_1` FOREIGN KEY (`disease_term_id`) REFERENCES `disease_term` (`id`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `cnv_callset` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `cnv_callset` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `processed_sample_id` INT(11) NOT NULL, `caller` ENUM('CnvHunter', 'ClinCNV') NOT NULL, `caller_version` varchar(25) NOT NULL, `call_date` DATETIME DEFAULT NULL, `quality_metrics` TEXT DEFAULT NULL COMMENT 'quality metrics as JSON key-value array', `quality` ENUM('n/a','good','medium','bad') NOT NULL DEFAULT 'n/a', PRIMARY KEY (`id`), INDEX `caller` (`quality` ASC), INDEX `call_date` (`call_date` ASC), INDEX `quality` (`quality` ASC), UNIQUE KEY `cnv_callset_references_processed_sample` (`processed_sample_id`), CONSTRAINT `cnv_callset_references_processed_sample` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COMMENT='germline CNV call set'; -- ----------------------------------------------------- -- Table `cnv` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `cnv` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `cnv_callset_id` INT(11) UNSIGNED NOT NULL, `chr` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `start` INT(11) UNSIGNED NOT NULL, `end` INT(11) UNSIGNED NOT NULL, `cn` INT(11) UNSIGNED NOT NULL COMMENT 'copy-number', `quality_metrics` TEXT DEFAULT NULL COMMENT 'quality metrics as JSON key-value array', PRIMARY KEY (`id`), CONSTRAINT `cnv_references_cnv_callset` FOREIGN KEY (`cnv_callset_id`) REFERENCES `cnv_callset` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, INDEX `chr` (`chr` ASC), INDEX `start` (`start` ASC), INDEX `end` (`end` ASC), INDEX `cn` (`cn` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COMMENT='germline CNV'; -- ----------------------------------------------------- -- Table `report_configuration_cnv` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `report_configuration_cnv` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `report_configuration_id` INT(11) NOT NULL, `cnv_id` INT(11) UNSIGNED NOT NULL, `type` ENUM('diagnostic variant', 'candidate variant', 'incidental finding') NOT NULL, `causal` BOOLEAN NOT NULL, `class` ENUM('n/a','1','2','3','4','5','M') NOT NULL, `inheritance` ENUM('n/a', 'AR','AD','XLR','XLD','MT') NOT NULL, `de_novo` BOOLEAN NOT NULL, `mosaic` BOOLEAN NOT NULL, `compound_heterozygous` BOOLEAN NOT NULL, `exclude_artefact` BOOLEAN NOT NULL, `exclude_frequency` BOOLEAN NOT NULL, `exclude_phenotype` BOOLEAN NOT NULL, `exclude_mechanism` BOOLEAN NOT NULL, `exclude_other` BOOLEAN NOT NULL, `comments` text NOT NULL, `comments2` text NOT NULL, PRIMARY KEY (`id`), CONSTRAINT `fk_report_configuration2` FOREIGN KEY (`report_configuration_id` ) REFERENCES `report_configuration` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_report_configuration_cnv_has_cnv` FOREIGN KEY (`cnv_id`) REFERENCES `cnv` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, UNIQUE INDEX `config_variant_combo_uniq` (`report_configuration_id` ASC, `cnv_id` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `sv_callset` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sv_callset` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `processed_sample_id` INT(11) NOT NULL, `caller` ENUM('Manta') NOT NULL, `caller_version` varchar(25) NOT NULL, `call_date` DATETIME DEFAULT NULL, PRIMARY KEY (`id`), INDEX `call_date` (`call_date` ASC), UNIQUE KEY `sv_callset_references_processed_sample` (`processed_sample_id`), CONSTRAINT `sv_callset_references_processed_sample` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COMMENT='SV call set'; -- ----------------------------------------------------- -- Table `sv_deletion` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sv_deletion` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `sv_callset_id` INT(11) UNSIGNED NOT NULL, `chr` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `start_min` INT(11) UNSIGNED NOT NULL, `start_max` INT(11) UNSIGNED NOT NULL, `end_min` INT(11) UNSIGNED NOT NULL, `end_max` INT(11) UNSIGNED NOT NULL, `quality_metrics` TEXT DEFAULT NULL COMMENT 'quality metrics as JSON key-value array', PRIMARY KEY (`id`), CONSTRAINT `sv_del_references_sv_callset` FOREIGN KEY (`sv_callset_id`) REFERENCES `sv_callset` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, INDEX `exact_match` (`chr`, `start_min`, `start_max`, `end_min`, `end_max`), INDEX `overlap_match` (`chr`, `start_min`, `end_max`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COMMENT='SV deletion'; -- ----------------------------------------------------- -- Table `sv_duplication` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sv_duplication` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `sv_callset_id` INT(11) UNSIGNED NOT NULL, `chr` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `start_min` INT(11) UNSIGNED NOT NULL, `start_max` INT(11) UNSIGNED NOT NULL, `end_min` INT(11) UNSIGNED NOT NULL, `end_max` INT(11) UNSIGNED NOT NULL, `quality_metrics` TEXT DEFAULT NULL COMMENT 'quality metrics as JSON key-value array', PRIMARY KEY (`id`), CONSTRAINT `sv_dup_references_sv_callset` FOREIGN KEY (`sv_callset_id`) REFERENCES `sv_callset` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, INDEX `exact_match` (`chr`, `start_min`, `start_max`, `end_min`, `end_max`), INDEX `overlap_match` (`chr`, `start_min`, `end_max`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COMMENT='SV duplication'; -- ----------------------------------------------------- -- Table `sv_insertion` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sv_insertion` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `sv_callset_id` INT(11) UNSIGNED NOT NULL, `chr` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `pos`INT(11) UNSIGNED NOT NULL, `ci_lower` INT(5) UNSIGNED NOT NULL DEFAULT 0, `ci_upper` INT(5) UNSIGNED NOT NULL, `inserted_sequence` TEXT DEFAULT NULL, `known_left` TEXT DEFAULT NULL, `known_right` TEXT DEFAULT NULL, `quality_metrics` TEXT DEFAULT NULL COMMENT 'quality metrics as JSON key-value array', PRIMARY KEY (`id`), CONSTRAINT `sv_ins_references_sv_callset` FOREIGN KEY (`sv_callset_id`) REFERENCES `sv_callset` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, INDEX `match` (`chr`, `pos`, `ci_upper`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COMMENT='SV insertion'; -- ----------------------------------------------------- -- Table `sv_inversion` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sv_inversion` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `sv_callset_id` INT(11) UNSIGNED NOT NULL, `chr` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `start_min` INT(11) UNSIGNED NOT NULL, `start_max` INT(11) UNSIGNED NOT NULL, `end_min` INT(11) UNSIGNED NOT NULL, `end_max` INT(11) UNSIGNED NOT NULL, `quality_metrics` TEXT DEFAULT NULL COMMENT 'quality metrics as JSON key-value array', PRIMARY KEY (`id`), CONSTRAINT `sv_inv_references_sv_callset` FOREIGN KEY (`sv_callset_id`) REFERENCES `sv_callset` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, INDEX `exact_match` (`chr`, `start_min`, `start_max`, `end_min`, `end_max`), INDEX `overlap_match` (`chr`, `start_min`, `end_max`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COMMENT='SV inversion'; -- ----------------------------------------------------- -- Table `sv_translocation` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sv_translocation` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `sv_callset_id` INT(11) UNSIGNED NOT NULL, `chr1` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `start1` INT(11) UNSIGNED NOT NULL, `end1` INT(11) UNSIGNED NOT NULL, `chr2` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `start2` INT(11) UNSIGNED NOT NULL, `end2` INT(11) UNSIGNED NOT NULL, `quality_metrics` TEXT DEFAULT NULL COMMENT 'quality metrics as JSON key-value array', PRIMARY KEY (`id`), CONSTRAINT `sv_bnd_references_sv_callset` FOREIGN KEY (`sv_callset_id`) REFERENCES `sv_callset` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, INDEX `match` (`chr1`, `start1`, `end1`, `chr2`, `start2`, `end2`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COMMENT='SV translocation'; -- ----------------------------------------------------- -- Table `report_configuration_sv` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `report_configuration_sv` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `report_configuration_id` INT(11) NOT NULL, `sv_deletion_id` INT(11) UNSIGNED DEFAULT NULL, `sv_duplication_id` INT(11) UNSIGNED DEFAULT NULL, `sv_insertion_id` INT(11) UNSIGNED DEFAULT NULL, `sv_inversion_id` INT(11) UNSIGNED DEFAULT NULL, `sv_translocation_id` INT(11) UNSIGNED DEFAULT NULL, `type` ENUM('diagnostic variant', 'candidate variant', 'incidental finding') NOT NULL, `causal` BOOLEAN NOT NULL, `class` ENUM('n/a','1','2','3','4','5','M') NOT NULL, `inheritance` ENUM('n/a', 'AR','AD','XLR','XLD','MT') NOT NULL, `de_novo` BOOLEAN NOT NULL, `mosaic` BOOLEAN NOT NULL, `compound_heterozygous` BOOLEAN NOT NULL, `exclude_artefact` BOOLEAN NOT NULL, `exclude_frequency` BOOLEAN NOT NULL, `exclude_phenotype` BOOLEAN NOT NULL, `exclude_mechanism` BOOLEAN NOT NULL, `exclude_other` BOOLEAN NOT NULL, `comments` text NOT NULL, `comments2` text NOT NULL, PRIMARY KEY (`id`), CONSTRAINT `fk_report_configuration3` FOREIGN KEY (`report_configuration_id` ) REFERENCES `report_configuration` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_report_configuration_sv_has_sv_deletion` FOREIGN KEY (`sv_deletion_id`) REFERENCES `sv_deletion` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_report_configuration_sv_has_sv_duplication` FOREIGN KEY (`sv_duplication_id`) REFERENCES `sv_duplication` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_report_configuration_sv_has_sv_insertion` FOREIGN KEY (`sv_insertion_id`) REFERENCES `sv_insertion` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_report_configuration_sv_has_sv_inversion` FOREIGN KEY (`sv_inversion_id`) REFERENCES `sv_inversion` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_report_configuration_sv_has_sv_translocation` FOREIGN KEY (`sv_translocation_id`) REFERENCES `sv_translocation` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, UNIQUE INDEX `config_variant_combo_uniq` (`report_configuration_id` ASC, `sv_deletion_id` ASC, `sv_duplication_id` ASC, `sv_insertion_id` ASC, `sv_inversion_id` ASC, `sv_translocation_id` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `evaluation_sheet_data` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `evaluation_sheet_data` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `processed_sample_id` INT(11) NOT NULL, `dna_rna_id` TEXT CHARACTER SET 'utf8' DEFAULT NULL, `reviewer1` INT NOT NULL, `review_date1` DATE NOT NULL, `reviewer2` INT NOT NULL, `review_date2` DATE NOT NULL, `analysis_scope` TEXT CHARACTER SET 'utf8' DEFAULT NULL, `acmg_requested` BOOLEAN DEFAULT FALSE NOT NULL, `acmg_analyzed` BOOLEAN DEFAULT FALSE NOT NULL, `acmg_noticeable` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_freq_based_dominant` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_freq_based_recessive` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_mito` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_x_chr` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_cnv` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_svs` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_res` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_mosaic` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_phenotype` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_multisample` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_trio_stringent` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_trio_relaxed` BOOLEAN DEFAULT FALSE NOT NULL, PRIMARY KEY (`id`), INDEX `processed_sample_id` (`processed_sample_id` ASC), UNIQUE KEY `evaluation_sheet_data_references_processed_sample` (`processed_sample_id`), CONSTRAINT `evaluation_sheet_data_references_processed_sample` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `evaluation_sheet_data_references_user1` FOREIGN KEY (`reviewer1`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `evaluation_sheet_data_references_user2` FOREIGN KEY (`reviewer2`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `preferred_transcripts` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `preferred_transcripts` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` varchar(40) NOT NULL, `added_by` INT(11) NOT NULL, `added_date` timestamp NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `combo_som_rep_conf_ids` (`name` ASC), CONSTRAINT `preferred_transcriptsg_created_by_user` FOREIGN KEY (`added_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; -- ----------------------------------------------------- -- Table `variant_validation` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `variant_validation` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `user_id` INT(11) NOT NULL, `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `sample_id` INT(11) NOT NULL, `variant_type` ENUM('SNV_INDEL', 'CNV', 'SV') NOT NULL, `variant_id` INT(11) DEFAULT NULL, `cnv_id` INT(11) UNSIGNED DEFAULT NULL, `sv_deletion_id` INT(11) UNSIGNED DEFAULT NULL, `sv_duplication_id` INT(11) UNSIGNED DEFAULT NULL, `sv_insertion_id` INT(11) UNSIGNED DEFAULT NULL, `sv_inversion_id` INT(11) UNSIGNED DEFAULT NULL, `sv_translocation_id` INT(11) UNSIGNED DEFAULT NULL, `genotype` ENUM('hom','het') DEFAULT NULL, `validation_method` ENUM('Sanger sequencing', 'breakpoint PCR', 'qPCR', 'MLPA', 'Array', 'shallow WGS', 'fragment length analysis', 'n/a') NOT NULL DEFAULT 'n/a', `status` ENUM('n/a','to validate','to segregate','for reporting','true positive','false positive','wrong genotype') NOT NULL DEFAULT 'n/a', `comment` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`), INDEX `fk_user_id` (`user_id` ASC), CONSTRAINT `vv_user` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_variant_validation_has_sample` FOREIGN KEY (`sample_id`) REFERENCES `sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_variant_validation_has_variant` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_variant_validation_has_cnv` FOREIGN KEY (`cnv_id`) REFERENCES `cnv` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_variant_validation_has_sv_deletion` FOREIGN KEY (`sv_deletion_id`) REFERENCES `sv_deletion` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_variant_validation_has_sv_duplication` FOREIGN KEY (`sv_duplication_id`) REFERENCES `sv_duplication` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_variant_validation_has_sv_insertion` FOREIGN KEY (`sv_insertion_id`) REFERENCES `sv_insertion` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_variant_validation_has_sv_inversion` FOREIGN KEY (`sv_inversion_id`) REFERENCES `sv_inversion` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_variant_validation_has_sv_translocation` FOREIGN KEY (`sv_translocation_id`) REFERENCES `sv_translocation` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, UNIQUE INDEX `variant_validation_unique_var` (`sample_id`, `variant_id`, `cnv_id`, `sv_deletion_id`, `sv_duplication_id`, `sv_insertion_id`, `sv_inversion_id`, `sv_translocation_id`), INDEX `status` (`status` ASC), INDEX `variant_type` (`variant_type` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `study` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `study` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, `description` TEXT NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `study_sample` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `study_sample` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `study_id` INT(11) NOT NULL, `processed_sample_id` INT(11) NOT NULL, `study_sample_idendifier` VARCHAR(50) DEFAULT NULL, PRIMARY KEY (`id`), CONSTRAINT `fk_study_sample_has_study` FOREIGN KEY (`study_id`) REFERENCES `study` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_study_sample_has_ps` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, UNIQUE INDEX `unique_sample_ps` (`study_id`, `processed_sample_id`), INDEX `i_study_sample_idendifier` (`study_sample_idendifier` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `secondary_analysis` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `secondary_analysis` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `type` enum('multi sample','trio','somatic') NOT NULL, `gsvar_file` VARCHAR(1000) NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `unique_gsvar` (`gsvar_file`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `gaps` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `gaps` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `chr` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `start` INT(11) UNSIGNED NOT NULL, `end` INT(11) UNSIGNED NOT NULL, `processed_sample_id` INT(11) NOT NULL, `status` enum('checked visually','to close','in progress','closed','canceled') NOT NULL, `history` TEXT, PRIMARY KEY (`id`), INDEX `gap_index` (`chr` ASC, `start` ASC, `end` ASC), INDEX `processed_sample_id` (`processed_sample_id` ASC), INDEX `status` (`status` ASC), CONSTRAINT `fk_gap_has_processed_sample1` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `gene_pseudogene_relation` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `gene_pseudogene_relation` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `parent_gene_id` int(10) unsigned NOT NULL, `pseudogene_gene_id` int(10) unsigned DEFAULT NULL, `gene_name` varchar(40) DEFAULT NULL, PRIMARY KEY (`id`), CONSTRAINT `fk_parent_gene_id` FOREIGN KEY (`parent_gene_id` ) REFERENCES `gene` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_pseudogene_gene_id` FOREIGN KEY (`pseudogene_gene_id` ) REFERENCES `gene` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, UNIQUE KEY `pseudo_gene_relation` (`parent_gene_id`, `pseudogene_gene_id`, `gene_name`), INDEX `parent_gene_id` (`parent_gene_id` ASC), INDEX `pseudogene_gene_id` (`pseudogene_gene_id` ASC) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Gene-Pseudogene relation'; -- ----------------------------------------------------- -- Table `processed_sample_ancestry` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `processed_sample_ancestry` ( `processed_sample_id` INT(11) NOT NULL, `num_snps` INT(11) NOT NULL, `score_afr` FLOAT NOT NULL, `score_eur` FLOAT NOT NULL, `score_sas` FLOAT NOT NULL, `score_eas` FLOAT NOT NULL, `population` enum('AFR','EUR','SAS','EAS','ADMIXED/UNKNOWN') NOT NULL, PRIMARY KEY (`processed_sample_id`), CONSTRAINT `fk_processed_sample_ancestry_has_processed_sample` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `subpanels` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `subpanels` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` varchar(200) NOT NULL, `created_by` int(11) DEFAULT NULL, `created_date` DATE NOT NULL, `mode` ENUM('exon', 'gene') NOT NULL, `extend` INT(11) NOT NULL, `genes` MEDIUMTEXT NOT NULL, `roi` MEDIUMTEXT NOT NULL, `archived` TINYINT(1) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`), INDEX(`created_by`), INDEX(`created_date`), INDEX(`archived`), CONSTRAINT `subpanels_created_by_user` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `cfdna_panels` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `cfdna_panels` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `tumor_id` INT(11) NOT NULL, `cfdna_id` INT(11) DEFAULT NULL, `created_by` INT(11) DEFAULT NULL, `created_date` DATE NOT NULL, `processing_system_id` INT(11) NOT NULL, `bed` MEDIUMTEXT NOT NULL, `vcf` MEDIUMTEXT NOT NULL, `excluded_regions` MEDIUMTEXT DEFAULT NULL, PRIMARY KEY (`id`), INDEX(`created_by`), INDEX(`created_date`), INDEX(`tumor_id`), UNIQUE `unique_cfdna_panel`(`tumor_id`, `processing_system_id`), CONSTRAINT `cfdna_panels_tumor_id` FOREIGN KEY (`tumor_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `cfdna_panels_cfdna_id` FOREIGN KEY (`cfdna_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `cfdna_panels_created_by_user` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `cfdna_panels_processing_system_id` FOREIGN KEY (`processing_system_id`) REFERENCES `processing_system` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `cfdna_panel_genes` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `cfdna_panel_genes` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `gene_name` VARCHAR(40) CHARACTER SET 'utf8' NOT NULL, `chr` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `start` INT(11) UNSIGNED NOT NULL, `end` INT(11) UNSIGNED NOT NULL, `date` DATE NOT NULL, `bed` MEDIUMTEXT NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX(`gene_name`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `variant_literature` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `variant_literature` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `variant_id` INT(11) NOT NULL, `pubmed` VARCHAR(12) CHARACTER SET 'utf8' NOT NULL, PRIMARY KEY (`id`), INDEX(`variant_id`), UNIQUE INDEX `variant_literature_UNIQUE` (`variant_id` ASC, `pubmed` ASC), CONSTRAINT `variant_literature_variant_id` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8;
imgag/ngs-bits
src/cppNGSD/resources/NGSD_schema.sql
SQL
mit
79,928
36.524883
651
0.617431
false
#ifndef ABSTRACTTRANSFORM_H #define ABSTRACTTRANSFORM_H #include <new> #include <mfapi.h> #include <mftransform.h> #include <mfidl.h> #include <mferror.h> #include <strsafe.h> #include <assert.h> // Note: The Direct2D helper library is included for its 2D matrix operations. #include <D2d1helper.h> #include <wrl\implements.h> #include <wrl\module.h> #include <windows.media.h> #include <INITGUID.H> #include "Common.h" #include "Interop\MessengerInterface.h" // Forward declaration class ImageAnalyzer; class ImageProcessingUtils; class Settings; class CAbstractTransform : public Microsoft::WRL::RuntimeClass< Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::RuntimeClassType::WinRtClassicComMix>, ABI::Windows::Media::IMediaExtension, IMFTransform> { public: CAbstractTransform(); virtual ~CAbstractTransform(); STDMETHOD(RuntimeClassInitialize)(); // IMediaExtension virtual STDMETHODIMP SetProperties(ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration); // IMFTransform STDMETHODIMP GetStreamLimits( DWORD *pdwInputMinimum, DWORD *pdwInputMaximum, DWORD *pdwOutputMinimum, DWORD *pdwOutputMaximum ); STDMETHODIMP GetStreamCount( DWORD *pcInputStreams, DWORD *pcOutputStreams ); STDMETHODIMP GetStreamIDs( DWORD dwInputIDArraySize, DWORD *pdwInputIDs, DWORD dwOutputIDArraySize, DWORD *pdwOutputIDs ); STDMETHODIMP GetInputStreamInfo( DWORD dwInputStreamID, MFT_INPUT_STREAM_INFO * pStreamInfo ); STDMETHODIMP GetOutputStreamInfo( DWORD dwOutputStreamID, MFT_OUTPUT_STREAM_INFO * pStreamInfo ); STDMETHODIMP GetAttributes(IMFAttributes** pAttributes); STDMETHODIMP GetInputStreamAttributes( DWORD dwInputStreamID, IMFAttributes **ppAttributes ); STDMETHODIMP GetOutputStreamAttributes( DWORD dwOutputStreamID, IMFAttributes **ppAttributes ); STDMETHODIMP DeleteInputStream(DWORD dwStreamID); STDMETHODIMP AddInputStreams( DWORD cStreams, DWORD *adwStreamIDs ); STDMETHODIMP GetInputAvailableType( DWORD dwInputStreamID, DWORD dwTypeIndex, // 0-based IMFMediaType **ppType ); STDMETHODIMP GetOutputAvailableType( DWORD dwOutputStreamID, DWORD dwTypeIndex, // 0-based IMFMediaType **ppType ); STDMETHODIMP SetInputType( DWORD dwInputStreamID, IMFMediaType *pType, DWORD dwFlags ); STDMETHODIMP SetOutputType( DWORD dwOutputStreamID, IMFMediaType *pType, DWORD dwFlags ); STDMETHODIMP GetInputCurrentType( DWORD dwInputStreamID, IMFMediaType **ppType ); STDMETHODIMP GetOutputCurrentType( DWORD dwOutputStreamID, IMFMediaType **ppType ); STDMETHODIMP GetInputStatus( DWORD dwInputStreamID, DWORD *pdwFlags ); STDMETHODIMP GetOutputStatus(DWORD *pdwFlags); STDMETHODIMP SetOutputBounds( LONGLONG hnsLowerBound, LONGLONG hnsUpperBound ); STDMETHODIMP ProcessEvent( DWORD dwInputStreamID, IMFMediaEvent *pEvent ); STDMETHODIMP ProcessMessage( MFT_MESSAGE_TYPE eMessage, ULONG_PTR ulParam ); virtual STDMETHODIMP ProcessInput( DWORD dwInputStreamID, IMFSample *pSample, DWORD dwFlags ); virtual STDMETHODIMP ProcessOutput( DWORD dwFlags, DWORD cOutputBufferCount, MFT_OUTPUT_DATA_BUFFER *pOutputSamples, // one per stream DWORD *pdwStatus ); protected: // HasPendingOutput: Returns TRUE if the MFT is holding an input sample. BOOL HasPendingOutput() const { return m_pSample != NULL; } // IsValidInputStream: Returns TRUE if dwInputStreamID is a valid input stream identifier. BOOL IsValidInputStream(DWORD dwInputStreamID) const { return dwInputStreamID == 0; } // IsValidOutputStream: Returns TRUE if dwOutputStreamID is a valid output stream identifier. BOOL IsValidOutputStream(DWORD dwOutputStreamID) const { return dwOutputStreamID == 0; } HRESULT OnGetPartialType(DWORD dwTypeIndex, IMFMediaType **ppmt); HRESULT OnCheckInputType(IMFMediaType *pmt); HRESULT OnCheckOutputType(IMFMediaType *pmt); HRESULT OnCheckMediaType(IMFMediaType *pmt); void OnSetInputType(IMFMediaType *pmt); void OnSetOutputType(IMFMediaType *pmt); HRESULT OnFlush(); virtual HRESULT UpdateFormatInfo(); virtual HRESULT BeginStreaming(); virtual HRESULT EndStreaming(); virtual HRESULT OnProcessOutput(IMFMediaBuffer *pIn, IMFMediaBuffer *pOut) = 0; virtual void OnMfMtSubtypeResolved(const GUID subtype); protected: // Members CRITICAL_SECTION m_critSec; D2D_RECT_U m_rcDest; // Destination rectangle for the effect. // Streaming bool m_bStreamingInitialized; IMFSample *m_pSample; // Input sample. IMFMediaType *m_pInputType; // Input media type. IMFMediaType *m_pOutputType; // Output media type. // Fomat information UINT32 m_imageWidthInPixels; UINT32 m_imageHeightInPixels; DWORD m_cbImageSize; // Image size, in bytes. IMFAttributes *m_pAttributes; VideoEffect::MessengerInterface ^m_messenger; ImageAnalyzer *m_imageAnalyzer; ImageProcessingUtils *m_imageProcessingUtils; Settings *m_settings; GUID m_videoFormatSubtype; }; #endif // ABSTRACTTRANSFORM_H
tompaana/object-tracking-demo
VideoEffect/VideoEffect.Shared/Transforms/AbstractTransform.h
C
mit
6,350
27.348214
108
0.612126
false
package com.cnpc.framework.base.service.impl; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON; import com.cnpc.framework.base.entity.Dict; import com.cnpc.framework.base.pojo.TreeNode; import com.cnpc.framework.base.service.DictService; import com.cnpc.framework.constant.RedisConstant; import com.cnpc.framework.utils.StrUtil; import com.cnpc.framework.utils.TreeUtil; @Service("dictService") public class DictServiceImpl extends BaseServiceImpl implements DictService { @Override public List<TreeNode> getTreeData() { // 获取数据 String key = RedisConstant.DICT_PRE+"tree"; List<TreeNode> tnlist = null; String tnStr = redisDao.get(key); if(!StrUtil.isEmpty(key)) { tnlist = JSON.parseArray(tnStr,TreeNode.class); } if (tnlist != null) { return tnlist; } else { String hql = "from Dict order by levelCode asc"; List<Dict> dicts = this.find(hql); Map<String, TreeNode> nodelist = new LinkedHashMap<String, TreeNode>(); for (Dict dict : dicts) { TreeNode node = new TreeNode(); node.setText(dict.getName()); node.setId(dict.getId()); node.setParentId(dict.getParentId()); node.setLevelCode(dict.getLevelCode()); nodelist.put(node.getId(), node); } // 构造树形结构 tnlist = TreeUtil.getNodeList(nodelist); redisDao.save(key, tnlist); return tnlist; } } public List<Dict> getDictsByCode(String code) { String key = RedisConstant.DICT_PRE+ code; List dicts = redisDao.get(key, List.class); if (dicts == null) { String hql = "from Dict where code='" + code + "'"; Dict dict = this.get(hql); dicts = this.find("from Dict where parentId='" + dict.getId() + "' order by levelCode"); redisDao.add(key, dicts); return dicts; } else { return dicts; } } @Override public List<TreeNode> getTreeDataByCode(String code) { // 获取数据 String key = RedisConstant.DICT_PRE + code + "s"; List<TreeNode> tnlist = null; String tnStr = redisDao.get(key); if(!StrUtil.isEmpty(key)) { tnlist = JSON.parseArray(tnStr,TreeNode.class); } if (tnlist != null) { return tnlist; } else { String hql = "from Dict where code='" + code + "' order by levelCode asc"; List<Dict> dicts = this.find(hql); hql = "from Dict where code='" + code + "' or parent_id = '" +dicts.get(0).getId()+ "' order by levelCode asc"; dicts = this.find(hql); Map<String, TreeNode> nodelist = new LinkedHashMap<String, TreeNode>(); for (Dict dict : dicts) { TreeNode node = new TreeNode(); node.setText(dict.getName()); node.setId(dict.getId()); node.setParentId(dict.getParentId()); node.setLevelCode(dict.getLevelCode()); nodelist.put(node.getId(), node); } // 构造树形结构 tnlist = TreeUtil.getNodeList(nodelist); redisDao.save(key, tnlist); return tnlist; } } @Override public List<TreeNode> getMeasureTreeData() { // 获取数据 String hql = "from Dict WHERE (levelCode LIKE '000026%' OR levelCode LIKE '000027%') order by levelCode asc"; List<Dict> funcs = this.find(hql); Map<String, TreeNode> nodelist = new LinkedHashMap<String, TreeNode>(); for (Dict dict : funcs) { TreeNode node = new TreeNode(); node.setText(dict.getName()); node.setId(dict.getId()); node.setParentId(dict.getParentId()); node.setLevelCode(dict.getLevelCode()); nodelist.put(node.getId(), node); } // 构造树形结构 return TreeUtil.getNodeList(nodelist); } }
Squama/Master
AdminEAP-framework/src/main/java/com/cnpc/framework/base/service/impl/DictServiceImpl.java
Java
mit
4,363
35.417391
123
0.556124
false
#include "unicorn/format.hpp" #include <cmath> #include <cstdio> using namespace RS::Unicorn::Literals; using namespace std::chrono; using namespace std::literals; namespace RS::Unicorn { namespace UnicornDetail { namespace { // These will always be called with x>=0 and prec>=0 Ustring float_print(long double x, int prec, bool exp) { std::vector<char> buf(32); int len = 0; for (;;) { if (exp) len = snprintf(buf.data(), buf.size(), "%.*Le", prec, x); else len = snprintf(buf.data(), buf.size(), "%.*Lf", prec, x); if (len < int(buf.size())) return buf.data(); buf.resize(2 * buf.size()); } } void float_strip(Ustring& str) { static const Regex pattern("(.*)(\\.(?:\\d*[1-9])?)(0+)(e.*)?", Regex::full); auto match = pattern(str); if (match) { Ustring result(match[1]); if (match.count(2) != 1) result += match[2]; result += match[4]; str.swap(result); } } Ustring float_digits(long double x, int prec) { prec = std::max(prec, 1); auto result = float_print(x, prec - 1, true); auto epos = result.find_first_of("Ee"); auto exponent = strtol(result.data() + epos + 1, nullptr, 10); result.resize(epos); if (exponent < 0) { if (prec > 1) result.erase(1, 1); result.insert(0, 1 - exponent, '0'); result[1] = '.'; } else if (exponent >= prec - 1) { if (prec > 1) result.erase(1, 1); result.insert(result.end(), exponent - prec + 1, '0'); } else if (exponent > 0) { result.erase(1, 1); result.insert(exponent + 1, 1, '.'); } return result; } Ustring float_exp(long double x, int prec) { prec = std::max(prec, 1); auto result = float_print(x, prec - 1, true); auto epos = result.find_first_of("Ee"); char esign = 0; if (result[epos + 1] == '-') esign = '-'; auto epos2 = result.find_first_not_of("+-0", epos + 1); Ustring exponent; if (epos2 < result.size()) exponent = result.substr(epos2); result.resize(epos); result += 'e'; if (esign) result += esign; if (exponent.empty()) result += '0'; else result += exponent; return result; } Ustring float_fixed(long double x, int prec) { return float_print(x, prec, false); } Ustring float_general(long double x, int prec) { using std::floor; using std::log10; if (x == 0) return float_digits(x, prec); auto exp = int(floor(log10(x))); auto d_estimate = exp < 0 ? prec + 1 - exp : exp < prec - 1 ? prec + 1 : exp + 1; auto e_estimate = exp < 0 ? prec + 4 : prec + 3; auto e_vs_d = e_estimate - d_estimate; if (e_vs_d <= -2) return float_exp(x, prec); if (e_vs_d >= 2) return float_digits(x, prec); auto dform = float_digits(x, prec); auto eform = float_exp(x, prec); return dform.size() <= eform.size() ? dform : eform; } Ustring string_escape(const Ustring& s, uint64_t mode) { Ustring result; result.reserve(s.size() + 2); if (mode & Format::quote) result += '\"'; for (auto i = utf_begin(s), e = utf_end(s); i != e; ++i) { switch (*i) { case U'\0': result += "\\0"; break; case U'\t': result += "\\t"; break; case U'\n': result += "\\n"; break; case U'\f': result += "\\f"; break; case U'\r': result += "\\r"; break; case U'\\': result += "\\\\"; break; case U'\"': if (mode & Format::quote) result += '\\'; result += '\"'; break; default: if (*i >= 32 && *i <= 126) { result += char(*i); } else if (*i >= 0xa0 && ! (mode & Format::ascii)) { result.append(s, i.offset(), i.count()); } else if (*i <= 0xff) { result += "\\x"; result += format_radix(*i, 16, 2); } else { result += "\\x{"; result += format_radix(*i, 16, 1); result += '}'; } break; } } if (mode & Format::quote) result += '\"'; return result; } template <typename Range> Ustring string_values(const Range& s, int base, int prec, int defprec) { if (prec < 0) prec = defprec; Ustring result; for (auto c: s) { result += format_radix(char_to_uint(c), base, prec); result += ' '; } if (! result.empty()) result.pop_back(); return result; } } // Formatting for specific types void translate_flags(const Ustring& str, uint64_t& flags, int& prec, size_t& width, char32_t& pad) { flags = 0; prec = -1; width = 0; pad = U' '; auto i = utf_begin(str), end = utf_end(str); while (i != end) { if (*i == U'<' || *i == U'=' || *i == U'>') { if (*i == U'<') flags |= Format::left; else if (*i == U'=') flags |= Format::centre; else flags |= Format::right; ++i; if (i != end && ! char_is_digit(*i)) pad = *i++; if (i != end && char_is_digit(*i)) i = str_to_int<size_t>(width, i); } else if (char_is_ascii(*i) && ascii_isalpha(char(*i))) { flags |= letter_to_mask(char(*i++)); } else if (char_is_digit(*i)) { i = str_to_int<int>(prec, i); } else { ++i; } } } Ustring format_ldouble(long double t, uint64_t flags, int prec) { using std::fabs; static constexpr auto format_flags = Format::digits | Format::exp | Format::fixed | Format::general; static constexpr auto sign_flags = Format::sign | Format::signz; if (popcount(flags & format_flags) > 1 || popcount(flags & sign_flags) > 1) throw std::invalid_argument("Inconsistent formatting flags"); if (prec < 0) prec = 6; auto mag = fabs(t); Ustring s; if (flags & Format::digits) s = float_digits(mag, prec); else if (flags & Format::exp) s = float_exp(mag, prec); else if (flags & Format::fixed) s = float_fixed(mag, prec); else s = float_general(mag, prec); if (flags & Format::stripz) float_strip(s); if (t < 0 || (flags & Format::sign) || (t > 0 && (flags & Format::signz))) s.insert(s.begin(), t < 0 ? '-' : '+'); return s; } // Alignment and padding Ustring format_align(Ustring src, uint64_t flags, size_t width, char32_t pad) { if (popcount(flags & (Format::left | Format::centre | Format::right)) > 1) throw std::invalid_argument("Inconsistent formatting alignment flags"); if (popcount(flags & (Format::lower | Format::title | Format::upper)) > 1) throw std::invalid_argument("Inconsistent formatting case conversion flags"); if (flags & Format::lower) str_lowercase_in(src); else if (flags & Format::title) str_titlecase_in(src); else if (flags & Format::upper) str_uppercase_in(src); size_t len = str_length(src, flags & format_length_flags); if (width <= len) return src; size_t extra = width - len; Ustring dst; if (flags & Format::right) str_append_chars(dst, extra, pad); else if (flags & Format::centre) str_append_chars(dst, extra / 2, pad); dst += src; if (flags & Format::left) str_append_chars(dst, extra, pad); else if (flags & Format::centre) str_append_chars(dst, (extra + 1) / 2, pad); return dst; } } // Basic formattng functions Ustring format_type(bool t, uint64_t flags, int /*prec*/) { static constexpr auto format_flags = Format::binary | Format::tf | Format::yesno; if (popcount(flags & format_flags) > 1) throw std::invalid_argument("Inconsistent formatting flags"); if (flags & Format::binary) return t ? "1" : "0"; else if (flags & Format::yesno) return t ? "yes" : "no"; else return t ? "true" : "false"; } Ustring format_type(const Ustring& t, uint64_t flags, int prec) { using namespace UnicornDetail; static constexpr auto format_flags = Format::ascii | Format::ascquote | Format::escape | Format::decimal | Format::hex | Format::hex8 | Format::hex16 | Format::quote; if (popcount(flags & format_flags) > 1) throw std::invalid_argument("Inconsistent formatting flags"); if (flags & Format::quote) return string_escape(t, Format::quote); else if (flags & Format::ascquote) return string_escape(t, Format::quote | Format::ascii); else if (flags & Format::escape) return string_escape(t, 0); else if (flags & Format::ascii) return string_escape(t, Format::ascii); else if (flags & Format::decimal) return string_values(utf_range(t), 10, prec, 1); else if (flags & Format::hex8) return string_values(t, 16, prec, 2); else if (flags & Format::hex16) return string_values(to_utf16(t), 16, prec, 4); else if (flags & Format::hex) return string_values(utf_range(t), 16, prec, 1); else return t; } Ustring format_type(system_clock::time_point t, uint64_t flags, int prec) { static constexpr auto format_flags = Format::iso | Format::common; if (popcount(flags & format_flags) > 1) throw std::invalid_argument("Inconsistent formatting flags"); auto zone = flags & Format::local ? local_zone : utc_zone; if (flags & Format::common) return format_date(t, "%c"s, zone); auto result = format_date(t, prec, zone); if (flags & Format::iso) { auto pos = result.find(' '); if (pos != npos) result[pos] = 'T'; } return result; } // Formatter class Format::Format(const Ustring& format): fmt(format), seq() { auto i = utf_begin(format), end = utf_end(format); while (i != end) { auto j = std::find(i, end, U'$'); add_literal(u_str(i, j)); i = std::next(j); if (i == end) break; Ustring prefix, suffix; if (char_is_digit(*i)) { auto k = std::find_if_not(i, end, char_is_digit); j = std::find_if_not(k, end, char_is_alphanumeric); prefix = u_str(i, k); suffix = u_str(k, j); } else if (*i == U'{') { auto k = std::next(i); if (char_is_digit(*k)) { auto l = std::find_if_not(k, end, char_is_digit); j = std::find(l, end, U'}'); if (j != end) { prefix = u_str(k, l); suffix = u_str(l, j); ++j; } } } if (prefix.empty()) { add_literal(i.str()); ++i; } else { add_index(str_to_int<unsigned>(prefix), suffix); i = j; } } } void Format::add_index(unsigned index, const Ustring& flags) { using namespace UnicornDetail; element elem; elem.index = index; translate_flags(to_utf8(flags), elem.flags, elem.prec, elem.width, elem.pad); seq.push_back(elem); if (index > 0 && index > num) num = index; } void Format::add_literal(const Ustring& text) { if (! text.empty()) { if (seq.empty() || seq.back().index != 0) seq.push_back({0, text, 0, 0, 0, 0}); else seq.back().text += text; } } }
CaptainCrowbar/unicorn-lib
unicorn/format.cpp
C++
mit
14,380
38.39726
174
0.42121
false
#!/bin/bash DATESTR=$(date +"%Y%m%d%H%M%S") LOCAL_BACKUP_DIR=/home/rails/db_backups/dsi function fetch_ntriples() { FILE_NAME="$LOCAL_BACKUP_DIR/$1" GRAPH_URI=$2 SOURCE_URI=http://46.4.78.148/dsi/data?graph=$GRAPH_URI curl -s -H "Accept:text/plain" -f -o $FILE_NAME $SOURCE_URI CURL_STATUS=$? if [ $CURL_STATUS -ne 0 ]; then echo "Failed to fetch URL with curl: $SOURCE_URI" echo "Backup Failed to Complete." exit 1 fi gzip $FILE_NAME echo "Downloaded & Gzipped triples to $FILE_NAME" } function upload_to_s3() { FNAME=$1 FILE_NAME="$LOCAL_BACKUP_DIR/$FNAME.gz" s3cmd put -P $FILE_NAME s3://digitalsocial-dumps S3_STATUS=$? if [ $S3_STATUS -ne 0 ]; then echo "Failed to put backup on S3" echo "Backup Failed to Complete." exit 2 fi echo "Copied $FILE_NAME to S3" } # For backup purposes function set_modified_date() { query=`printf 'WITH <http://data.digitalsocial.eu/graph/organizations-and-activities/metadata> DELETE {?ds <http://purl.org/dc/terms/modified> ?mod} INSERT {?ds <http://purl.org/dc/terms/modified> "%s"^^<http://www.w3.org/2001/XMLSchema#dateTime>} WHERE { GRAPH <http://data.digitalsocial.eu/graph/organizations-and-activities/metadata> { ?ds a <http://publishmydata.com/def/dataset#Dataset> . OPTIONAL {?ds <http://purl.org/dc/terms/modified> ?mod} } }' $DATESTR` curl -s -f -d "request=$query" http://46.4.78.148/dsi/update > /dev/null CURL_STATUS=$? if [ $CURL_STATUS -ne 0 ]; then echo "Failed to update modified date" echo "Backup Failed to Complete." exit 3 fi echo "Modification Date Set" } function remove_dsi_backup() { FNAME=$1 rm $FNAME echo "Removed old local backup: $FNAME" } export -f remove_dsi_backup # export the function so we can use it with find function remove_old_backups() { # NOTE the crazy syntax for calling an exported function and # passing an arg to find -exec. find $LOCAL_BACKUP_DIR -mtime +14 -exec bash -c 'remove_dsi_backup "$0"' {} \; } MAIN_DATA_SET="dataset_data_organizations-and-activities_$DATESTR.nt" ACTIVITY_TYPES="concept-scheme_activity_types_$DATESTR.nt" ACTIVITY_TECHNOLOGY_METHODS="concept-scheme_activity-technology-methods_$DATESTR.nt" AREA_OF_SOCIETY="concept-scheme_area-of-society_$DATESTR.nt" fetch_ntriples $MAIN_DATA_SET "http%3A%2F%2Fdata.digitalsocial.eu%2Fgraph%2Forganizations-and-activities" fetch_ntriples $ACTIVITY_TYPES "http%3A%2F%2Fdata.digitalsocial.eu%2Fgraph%2Fconcept-scheme%2Factivity-type" fetch_ntriples $ACTIVITY_TECHNOLOGY_METHODS "http%3A%2F%2Fdata.digitalsocial.eu%2Fgraph%2Fconcept-scheme%2Ftechnology-method" fetch_ntriples $AREA_OF_SOCIETY "http%3A%2F%2Fdata.digitalsocial.eu%2Fgraph%2Fconcept-scheme%2Farea-of-society" upload_to_s3 $MAIN_DATA_SET upload_to_s3 $ACTIVITY_TYPES upload_to_s3 $ACTIVITY_TECHNOLOGY_METHODS upload_to_s3 $AREA_OF_SOCIETY set_modified_date remove_old_backups echo "$DATESTR Backup Complete."
Swirrl/digitalsocial
backup_data_graph.sh
Shell
mit
3,022
32.577778
145
0.698213
false
// // IOService.cpp // Firedrake // // Created by Sidney Just // Copyright (c) 2015 by Sidney Just // 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 "IOService.h" namespace IO { IODefineMeta(Service, RegistryEntry) String *kServiceProviderMatchKey; String *kServiceClassMatchKey; String *kServicePropertiesMatchKey; extern void RegisterClass(MetaClass *meta, Dictionary *properties); extern void RegisterProvider(Service *provider); extern void EnumerateClassesForProvider(Service *provider, const Function<bool (MetaClass *meta, Dictionary *properties)> &callback); void Service::InitialWakeUp(MetaClass *meta) { if(meta == Service::GetMetaClass()) { kServiceProviderMatchKey = String::Alloc()->InitWithCString("kServiceProviderMatchKey"); kServiceClassMatchKey = String::Alloc()->InitWithCString("kServiceClassMatchKey"); kServicePropertiesMatchKey = String::Alloc()->InitWithCString("kServicePropertiesMatchKey"); } RegistryEntry::InitialWakeUp(meta); } void Service::RegisterService(MetaClass *meta, Dictionary *properties) { RegisterClass(meta, properties); } Service *Service::InitWithProperties(Dictionary *properties) { if(!RegistryEntry::Init()) return nullptr; _started = false; _properties = properties->Retain(); return this; } Dictionary *Service::GetProperties() const { return _properties; } void Service::Start() { _started = true; } void Service::Stop() {} // Matching void Service::RegisterProvider() { IO::RegisterProvider(this); } bool Service::MatchProperties(__unused Dictionary *properties) { return true; } void Service::StartMatching() { DoMatch(); } void Service::DoMatch() { EnumerateClassesForProvider(this, [this](MetaClass *meta, Dictionary *properties) { if(MatchProperties(properties)) { Service *service = static_cast<Service *>(meta->Alloc()); service = service->InitWithProperties(properties); if(service) { PublishService(service); return true; } } return false; }); } void Service::PublishService(Service *service) { AttachChild(service); } void Service::AttachToParent(RegistryEntry *parent) { RegistryEntry::AttachToParent(parent); Start(); } }
JustSid/Firedrake
slib/libio/service/IOService.cpp
C++
mit
3,272
25.387097
134
0.73533
false
# Toady 1.0 Wickedly extensible IRC bot written in Node.js. Load and reload mods without reconnecting. ## Please pay attention: This master branch is merged with version 1.x from Toady and got extended afterwards! ## Download. Install. Fly. If you don't already have Node.js, [get it](http://nodejs.org). It's awesome. And also required. Then, grab Toady from Github by using the [download link](https://github.com/TomFrost/Toady/archive/master.zip), or if you're dev-minded and like to stay updated, clone it on the command line: git clone git@github.com:TomFrost/Toady.git Get into that folder on the command line and install: npm install ## Configure it. Just a little bit. Copy config/default.yaml.sample to config/default.yaml. Enter your server settings, change Toady's name, and pay extra careful attention to the section marked with ## !!IMPORTANT!! ## Because four exclamation points means business, son. ## You turn Toady on. To launch (from the Toady directory) on any non-Windows machine, or Cygwin: ./ribbit start If you're on Windows, it's: ribbit.cmd start Need to launch it on more than one server? Just copy config/default.yaml to config/myotherserver.yaml, edit it for the new server, and launch Toady like this: ./ribbit start myotherserver When he's in your channel, do this in IRC for more info: /msg Toady help ## Teach Toady new tricks. Toady can be extended through simple mods, and mods can make Toady do practially anything. Mods can be searched for, installed, and uninstalled through ribbit. **IMPORTANT NOTE: This section shows you how to install third-party mods. These are not moderated, maintained, guaranteed, or otherwise vetted by Toady's author. Install at your own risk, as mods are capable of anything!** List all Toady mods: ./ribbit search # Or in IRC: /msg Toady ribbit search List only mods that deal with typos: ./ribbit search typo # Or in IRC: /msg Toady ribbit search typo Install a mod: ./ribbit install typofix # Or in IRC, just say: !ribbit install typofix Uninstall a mod: ./ribbit uninstall typofix # Or in IRC, just say: !ribbit uninstall typofix Did I mention you can search, download, and install mods into a running Toady instance directly from IRC? Yeah. Toady's like that. ## Write your own mods! (It's easy) Mods for Toady are standard Node.js modules. They can have their own node_modules folder with dependencies set up in a package.json, they can require() whatever they need, they can open new ports, and they can interact with the entire Toady framework including other mods. Toady mods have no limitations. ### Make a basic mod For your first mod, make a folder in Toady's 'mods' folder called 'test'. That makes 'test' your mod's 'id' -- no other mod can be loaded with the same id. Inside of mods/test, create index.js and paste in the following. This is the most basic form of a mod: /** * Creates a new Test mod * * @param {Object} config Contains config fields specific to this mod * @param {Object} client The connected IRC client powering the bot * @param {Object} modMan A reference to the ModManager object, * responsible for loading/unloading mods and commands. * @returns {Object} The new Test mod */ module.exports = function(config, client, modMan) { return { name: "My Test Mod", version: "0.1.0", author: "Me, Myself, and I", desc: "I just made this to screw around", commands: { greet: { handler: function(from, to, target, args) { client.say(target, "Hi " + from + "!"); }, desc: "Makes the bot say Hi to you.", help: [ "Format: {cmd} [#channel]", "Examples:", " /msg {nick} {cmd} #room", " {!}{cmd}", " {!}{cmd} #otherRoomImIn", " ", "If this is said in a channel, I'll greet you on the" + "same channel if no other is specified." ], targetChannel: true } } }; }; If Toady isn't running yet, this mod will be loaded automatically when you start him up. If he *is* currently running, just say this: !loadmod test And now you can try out your new `!greet` command. Any time you make a change to this mod and want Toady to update to the latest version, just say: !reloadmod test For a list of these and other mod-related commands, type !viewmod modcontrol ### Structure of a mod The object literal that the exported function returns has the following properties: #### name: string The name given to your mod when it's listed with `!help` or `!viewmod`. #### version: string The version of your mod. This should follow the semantic versioning guidelines at [semver.org](http://semver.org). **You can omit this if your mod has a package.json file with a version! Toady will pull it from there instead.** #### author: string Your name! You can optionally specify your E-mail address, in the format `Your Name <your@email.com>`. **You can omit this if your mod has a package.json file with an author! Toady will pull it from there instead.** #### desc: string A very brief, one-liner description of what your mod does. This will show up in the `!viewmod` output. **You can omit this if your mod has a package.json file with a description! Toady will pull it from there instead.** #### unload: function() *(optional)* A function that will be called immediately before unloading this module in the ModManager. **If any event listeners have been placed on the ModManager or the IRC client object, they MUST BE REMOVED by this function!** Toady cannot enforce this, so it is up to you, the mod author, to make sure. Toady will have unexpected and unstable behavior if this function does not remove all the mod's listeners. #### configItems: object *(optional)* A mapping of configuration keys to objects defining that key. The object has the following properties, all of which are optional: { desc: "Describe what this option means in a one-liner", type: "number", // Either string, boolean, or number. validate: function(value) { return true; } } These items will be made available to be changed by the 'config' core module. If a type is specified, the user input will be cast to that type. If validate is specified, the value will be passed to it and the function can return one of three things: - {Error} If validation failed and an error message should be provided to the user - {boolean} false if validation failed and a generic error message should be provided to the user - {boolean} true if validation passed #### blockReload: boolean *(optional, default false)* If true, this will stop your mod from being reloaded with the `!reloadmod` command. While this can be convenient to stop the mod's "memory" from being wiped by an unsuspecting Owner or SuperUser, this is *extremely bad practice*. Use the config object to save changes rather than blocking your mod from being reloaded. #### blockUnload: boolean *(optional, default false)* If true, this will stop your mod from being unloaded with the `!unloadmod` command, but *not* through the `!reloadmod` command. **This should only ever be used for mods that are core to the function of the bot** #### commands An object literal that maps command names (whatever you would msg Toady or say in a room with the fantasy char) to command objects. Those are defined below. *This field is optional; not all mods have user-callabe commands.* ### Structure of a Command Commands are managed by the Toady framework to prevent name overlaps, ensure users have the appropriate permissions, etc. If your mod just needs to listen for IRC events and react to them, no commands are necessary. But if you want someone to be able to say `!somecommand`, here's how: #### handler: function(from, to, target, args, inChan) The function that executes when the function is called. The arguments are: - *from* - The nick of the user calling the command - *to* - The bot's name if this was sent in a private message, or the channel the command was spoken in if not. - *target* - The channel or nick targeted for the command. This is configured below. - *args* - An array containing the arguments to this command. If no *pattern* is specified below, this will have just one element: The entire string following the command or target. - *inChan* - True if the command was said in a channel (and thus 'to' is a channel name); false if the command was messaged privately (and this 'to' is the bot's nick). #### desc: string A brief one-liner description of what the command does. Shown in `!help`. #### help: array An array of strings to be sent in the `!help` command. Each string will be sent in its own IRC NOTICE, so this can be utilized to control line breaks. The following placeholders will be automatically replaced with the appropriate contents: - **{!}** - The configured fantasy character - **{cmd}** - The name of the command - **{mod}** - The name of the mod (specified in the mod's `name` field) - **{modId}** - The id of the mod (usually, its folder name in the mods folder) - **{nick}** - The nickname of the bot - **{version}** - The version number of the mod #### minPermission: string *(optional)* The permission character of the lowest permission allowed to call this command. If omitted, the command won't be restricted by permission. Toady recognizes the following permissions, in order from most to least privileged: - **O** - Owner. Full access to all commands, cannot be revoked. - **S** - SuperUser. Full access to all commands, except those which may impact other Owners or SuperUsers. - **P** - PowerUser. Limited access to global command set. - **~** - Channel founder - **&** - Channel admin - **@** - Channel op - **%** - Channel half-op - **+** - Voice - **''** - (Empty string) A user in a channel The **O**, **S**, and **P** permissions are Toady-specfic and can be set with the `!adduser` and `!updateuser` commands. All others come directly from IRC. #### pattern: RexExp *(optional)* The regex pattern that the command arguments must match in order for the function to be called. If specified, the `args` argument in the handler function will be the result of the match -- so index 0 will be the entire string, 1 will be the first paranthetical match, 2 will be the second, and so on. If targetChannel or targetNick is specified as described below, this pattern will *NOT* be applied to the target argument. #### targetChannel: boolean *(optional, default false)* Setting this to `true` will require that the first argument to the command is a channel name, prefixed with `#` or `&`. If the command is said in a channel using the fantasy char, the channel can be omitted and it will be assumed that the target is the same channel. This value will be passed in the handler's `target` argument. #### targetNick: boolean *(optional, default false)* Setting this to `true` will require that the first argument to the command is a user's nick. **Note that this will *not* ensure that the nick is real or connected -- it just assumes the first argument is the target nick**. This value will be passed in the handler's `target` argument. #### hidden: boolean *(optional, default false)* Setting this to `true` will cause this command to be omitted from `!help`. This can be useful in games where certain commands would only make sense to users if the game is currently running. The "hidden" flag can be turned on and off dynamically as needed. It should **never** be used to exercise any form of security through obscurity. Use *minPermission* to restrict access to commands. ### Config The `config` argument passed to each mod is an object literal containing configuration fields. The fields are loaded in the following order, with each step overwriting any existing fields from previous steps: - The mod's own module.exports.configDefaults object, if one exists - The mod_MODNAME-HERE section from the .yaml config file currently in use, if it exists - The config/CONFNAME-mod_MODNAME.json file, if it exists So if a mod named "test" is written with this at the bottom: module.exports.configDefaults = { delay: 12, message: 'Hello!', name: 'Ted' }; And **config/default.yaml** contains this block: mod_test: delay: 5 And the file **config/default-mod_test.json** contains this: { "message": "Yo!" } Then the config object passed into the 'test' mod when it's loaded will be: { delay: 5, message: "Yo!", name: "Ted" } Why the complexity? - module.exports.configDefaults allows you to define the default values your mod will be instantiated with, so that no error checking for nonexistant config values is necessary - The block in the .yaml file allows the bot owner to easily specify new config options - The .json file is what the config object itself saves when config.save() is called. Note that any mod can access any other mod's config object to read, write, and save with the following call. This should be used sparingly and only when absolutely necessary, as the target mod may not be prepared to handle dynamic changes in its config: var otherModConfig = modMan.getMod('otherModId').config; #### config.save(_\[{Array} properties\]_, _\[{Function} callback\]_) The 'save' function is the only value that Toady itself adds to your config object, and it is non-enumable -- so iterating over your config values will not show 'save' as a property. It's there, though, and calling it will write the file config/default-mod_MODNAME.json, where "default" is the name of the .yaml file currently in use. Any saved config will be provided back to the mod if it's reloaded, or the bot is restarted. If _properties_ is omitted, all enumerable properties on the config object will be saved. But _properties_ can be set to an array of strings representing the only config keys that should be saved in the resulting file. The optional callback function will be called with an Error object from _fs.writeFile_ if the write fails, or with no error upon success. ### Client The IRC client provided to each mod is an instance of martynsmith's fantastic [node-irc](https://github.com/martynsmith/node-irc) client, unaltered in any way except for configuring and connecting it according to the options defined in the configuration yaml file. The client object allows the bot to send messages, join, part, quit, change nicks, etc -- anything you would expect an IRC client to do. It also tracks the bot's nick as well as the users and their permissions in the channels the bot is in, and exposes many events you can hook to be notified of new messages, nick changes, parts, and more. Just skim [the node-irc documentation site](https://node-irc.readthedocs.org/en/latest/API.html) for details. Here are a few examples of how easy the client is to use: client.say('#myChan', "HI GUYS! MY NAME IS " + client.nick + "!!!"); function nickHandler(oldnick, newnick, channels) { channels.forEach(function(channel) { client.say(channel, "Stop changing your name, " + newnick); }); } client.on('nick', nickHandler); // And your mod's 'unload' function MUST contain this line // if you do the above: // client.removeListener('nick', nickHandler); ### ModManager The ModManager instance that gets passed to each mod on load is a singleton responsible for loading/unloading all mods, collecting command objects, and providing all of these things to other mods on request. In addition to returning official mod properties in the resulting object literal, arbitrary properties can be added for other mods to take advantage of. For example, the 'users' mod includes functions for finding and checking user permissions. If your mod needs to do that, you could call: var usersMod = modMan.getMod('users'); client.say(channel, "You have the permission: " + usersMod.getPermission(nick)); The ModManager also emits events for when mods and commands are loaded/unloaded, so if your mod needs to modify all new commands as they load (maybe your mod's goal is to remove permission requirements from all comamnds?), listening for those events is extremely easy. Since the use cases for accessing the ModManager are fairly rare, I'll refer to the very thorough in-code documentation in app/modmanager/ModManager.js to guide you to the different events and function calls. ### Mod Metadata Toady mods all assign module.exports to a function. However, some features can be impacted before the mod is fully loaded by assigning other properties to module.exports as well. #### module.exports.configDefaults = {Object} A mapping of config keys to their default value, which will be passed in the module's _'config'_ argument at load time unless a key or keys have been overridden through other means. See **Config** above for details. #### module.exports.minToadyVersion = {String} The minimum version of Toady with which this mod is compatible. Toady will refuse to load the mod if this value is greater than Toady's own version. ### Examples Learn faster from looking at code than reading docs? Nearly all of Toady's functionality happens in mods -- from the help commands, to finding and verifying user permissions, to even detecting and executing commands themselves. All of these core mods are very thoroughly documented in the app/coremods folder. ## Distribute your mods on ribbit To get your mods on ribbit, all you need to do is publish your mod to NPM under the following name: toady-mod_name_here So if your mod is named 'typofix', your mod's package.json should contain this line: "name": "toady-typofix" Don't have a package.json yet? Just type `npm init` in your mod's directory and follow the prompts, giving it the "toady-" prefixed name when it asks. If you haven't already done it, run `npm adduser` to log in (or make an account) on NPM, and then run `npm publish` to give your mod to the world. It should show up in ribbit searches within a few minutes. ## Toady has a lawyer Toady is distributed under the BSD license. See the 'LICENSE.txt' file for the legalese. It's friendly and open, I promise. ## Toady has a purpose in life I wrote Toady in 2013 to help manage my dev team's IRC room. There are other bots, but this is the magical mix of features that few of the others had: - Written in Javascript, so practically anyone can extend it - Dead-simple command framework, so new commands are no more than a few lines of code away - Can develop on it and test mods without restarting (/msg Toady viewmod modcontrol) - Can restrict its commands by its own global permissions as well as channel and NickServ permissions on the IRC server itself - Since it's Node.js, making mods do crazy stuff like hosting websites to view channel logs right within Toady is as simple as `npm install express` ## Obligatory Copyright Toady is Copyright ©2013 Tom Frost.
tomhatzer/Toady
README.md
Markdown
mit
19,090
41.514477
182
0.734035
false
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Pelasoft.AspNet.Mvc.Slack.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Pelasoft.AspNet.Mvc.Slack.Tests")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("75d28683-1b61-4d8d-87c7-89d8d199d752")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
peterlanoie/aspnet-mvc-slack
src/Pelasoft.AspNet.Mvc.Slack.Tests/Properties/AssemblyInfo.cs
C#
mit
1,398
38.857143
84
0.749821
false