text
stringlengths 2
100k
| meta
dict |
---|---|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_202) on Fri Jul 24 11:53:31 GMT 2020 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ReadWriteLockManager (Eclipse RDF4J 3.3.0 API)</title>
<meta name="date" content="2020-07-24">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ReadWriteLockManager (Eclipse RDF4J 3.3.0 API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":6,"i1":6,"i2":6,"i3":6};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ReadWriteLockManager.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/eclipse/rdf4j/common/concurrent/locks/ReadPrefReadWriteLockManager.html" title="class in org.eclipse.rdf4j.common.concurrent.locks"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../org/eclipse/rdf4j/common/concurrent/locks/WritePrefReadWriteLockManager.html" title="class in org.eclipse.rdf4j.common.concurrent.locks"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/eclipse/rdf4j/common/concurrent/locks/ReadWriteLockManager.html" target="_top">Frames</a></li>
<li><a href="ReadWriteLockManager.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.eclipse.rdf4j.common.concurrent.locks</div>
<h2 title="Interface ReadWriteLockManager" class="title">Interface ReadWriteLockManager</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Known Implementing Classes:</dt>
<dd><a href="../../../../../../org/eclipse/rdf4j/common/concurrent/locks/AbstractReadWriteLockManager.html" title="class in org.eclipse.rdf4j.common.concurrent.locks">AbstractReadWriteLockManager</a>, <a href="../../../../../../org/eclipse/rdf4j/common/concurrent/locks/ReadPrefReadWriteLockManager.html" title="class in org.eclipse.rdf4j.common.concurrent.locks">ReadPrefReadWriteLockManager</a>, <a href="../../../../../../org/eclipse/rdf4j/common/concurrent/locks/WritePrefReadWriteLockManager.html" title="class in org.eclipse.rdf4j.common.concurrent.locks">WritePrefReadWriteLockManager</a></dd>
</dl>
<hr>
<br>
<pre>public interface <span class="typeNameLabel">ReadWriteLockManager</span></pre>
<div class="block">A lock manager that manages a multi-read, single-write lock. This lock manager allows multiple read locks to be
active at the same time. The write lock is exclusive, meaning that no other read- or write locks may be active at the
same time.</div>
<dl>
<dt><span class="simpleTagLabel">Author:</span></dt>
<dd>Arjohn Kampman</dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/eclipse/rdf4j/common/concurrent/locks/Lock.html" title="interface in org.eclipse.rdf4j.common.concurrent.locks">Lock</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/eclipse/rdf4j/common/concurrent/locks/ReadWriteLockManager.html#getReadLock--">getReadLock</a></span>()</code>
<div class="block">Gets a read lock.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code><a href="../../../../../../org/eclipse/rdf4j/common/concurrent/locks/Lock.html" title="interface in org.eclipse.rdf4j.common.concurrent.locks">Lock</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/eclipse/rdf4j/common/concurrent/locks/ReadWriteLockManager.html#getWriteLock--">getWriteLock</a></span>()</code>
<div class="block">Gets an exclusive write lock.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/eclipse/rdf4j/common/concurrent/locks/Lock.html" title="interface in org.eclipse.rdf4j.common.concurrent.locks">Lock</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/eclipse/rdf4j/common/concurrent/locks/ReadWriteLockManager.html#tryReadLock--">tryReadLock</a></span>()</code>
<div class="block">Gets a read lock, if available.</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code><a href="../../../../../../org/eclipse/rdf4j/common/concurrent/locks/Lock.html" title="interface in org.eclipse.rdf4j.common.concurrent.locks">Lock</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/eclipse/rdf4j/common/concurrent/locks/ReadWriteLockManager.html#tryWriteLock--">tryWriteLock</a></span>()</code>
<div class="block">Gets an exclusive write lock, if available.</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="tryReadLock--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>tryReadLock</h4>
<pre><a href="../../../../../../org/eclipse/rdf4j/common/concurrent/locks/Lock.html" title="interface in org.eclipse.rdf4j.common.concurrent.locks">Lock</a> tryReadLock()</pre>
<div class="block">Gets a read lock, if available. This method will return <tt>null</tt> if the read lock is not immediately
available.</div>
</li>
</ul>
<a name="getReadLock--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getReadLock</h4>
<pre><a href="../../../../../../org/eclipse/rdf4j/common/concurrent/locks/Lock.html" title="interface in org.eclipse.rdf4j.common.concurrent.locks">Lock</a> getReadLock()
throws <a href="http://download.oracle.com/javase/7/docs/api/java/lang/InterruptedException.html?is-external=true" title="class or interface in java.lang">InterruptedException</a></pre>
<div class="block">Gets a read lock. This method blocks until the read lock is available.</div>
<dl>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code><a href="http://download.oracle.com/javase/7/docs/api/java/lang/InterruptedException.html?is-external=true" title="class or interface in java.lang">InterruptedException</a></code> - In case the thread requesting the lock was <a href="http://download.oracle.com/javase/7/docs/api/java/lang/Thread.html?is-external=true#interrupt--" title="class or interface in java.lang"><code>interrupted</code></a>.</dd>
</dl>
</li>
</ul>
<a name="tryWriteLock--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>tryWriteLock</h4>
<pre><a href="../../../../../../org/eclipse/rdf4j/common/concurrent/locks/Lock.html" title="interface in org.eclipse.rdf4j.common.concurrent.locks">Lock</a> tryWriteLock()</pre>
<div class="block">Gets an exclusive write lock, if available. This method will return <tt>null</tt> if the write lock is not
immediately available.</div>
</li>
</ul>
<a name="getWriteLock--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getWriteLock</h4>
<pre><a href="../../../../../../org/eclipse/rdf4j/common/concurrent/locks/Lock.html" title="interface in org.eclipse.rdf4j.common.concurrent.locks">Lock</a> getWriteLock()
throws <a href="http://download.oracle.com/javase/7/docs/api/java/lang/InterruptedException.html?is-external=true" title="class or interface in java.lang">InterruptedException</a></pre>
<div class="block">Gets an exclusive write lock. This method blocks until the write lock is available.</div>
<dl>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code><a href="http://download.oracle.com/javase/7/docs/api/java/lang/InterruptedException.html?is-external=true" title="class or interface in java.lang">InterruptedException</a></code> - In case the thread requesting the lock was <a href="http://download.oracle.com/javase/7/docs/api/java/lang/Thread.html?is-external=true#interrupt--" title="class or interface in java.lang"><code>interrupted</code></a>.</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ReadWriteLockManager.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/eclipse/rdf4j/common/concurrent/locks/ReadPrefReadWriteLockManager.html" title="class in org.eclipse.rdf4j.common.concurrent.locks"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../org/eclipse/rdf4j/common/concurrent/locks/WritePrefReadWriteLockManager.html" title="class in org.eclipse.rdf4j.common.concurrent.locks"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/eclipse/rdf4j/common/concurrent/locks/ReadWriteLockManager.html" target="_top">Frames</a></li>
<li><a href="ReadWriteLockManager.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2015-2020 <a href="https://www.eclipse.org/">Eclipse Foundation</a>. All Rights Reserved.</small></p>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2013-2018 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if ENABLE(ASSEMBLER) && (CPU(X86) || CPU(X86_64))
#include "MacroAssembler.h"
#include "ProbeContext.h"
#include <wtf/InlineASM.h>
#if COMPILER(MSVC)
#include <intrin.h>
#endif
namespace JSC {
#if ENABLE(MASM_PROBE)
extern "C" void ctiMasmProbeTrampoline();
// The following are offsets for Probe::State fields accessed by the ctiMasmProbeTrampoline stub.
#if CPU(X86)
#define PTR_SIZE 4
#else // CPU(X86_64)
#define PTR_SIZE 8
#endif
#define PROBE_PROBE_FUNCTION_OFFSET (0 * PTR_SIZE)
#define PROBE_ARG_OFFSET (1 * PTR_SIZE)
#define PROBE_INIT_STACK_FUNCTION_OFFSET (2 * PTR_SIZE)
#define PROBE_INIT_STACK_ARG_OFFSET (3 * PTR_SIZE)
#define PROBE_FIRST_GPR_OFFSET (4 * PTR_SIZE)
#define PROBE_CPU_EAX_OFFSET (PROBE_FIRST_GPR_OFFSET + (0 * PTR_SIZE))
#define PROBE_CPU_ECX_OFFSET (PROBE_FIRST_GPR_OFFSET + (1 * PTR_SIZE))
#define PROBE_CPU_EDX_OFFSET (PROBE_FIRST_GPR_OFFSET + (2 * PTR_SIZE))
#define PROBE_CPU_EBX_OFFSET (PROBE_FIRST_GPR_OFFSET + (3 * PTR_SIZE))
#define PROBE_CPU_ESP_OFFSET (PROBE_FIRST_GPR_OFFSET + (4 * PTR_SIZE))
#define PROBE_CPU_EBP_OFFSET (PROBE_FIRST_GPR_OFFSET + (5 * PTR_SIZE))
#define PROBE_CPU_ESI_OFFSET (PROBE_FIRST_GPR_OFFSET + (6 * PTR_SIZE))
#define PROBE_CPU_EDI_OFFSET (PROBE_FIRST_GPR_OFFSET + (7 * PTR_SIZE))
#if CPU(X86)
#define PROBE_FIRST_SPR_OFFSET (PROBE_FIRST_GPR_OFFSET + (8 * PTR_SIZE))
#else // CPU(X86_64)
#define PROBE_CPU_R8_OFFSET (PROBE_FIRST_GPR_OFFSET + (8 * PTR_SIZE))
#define PROBE_CPU_R9_OFFSET (PROBE_FIRST_GPR_OFFSET + (9 * PTR_SIZE))
#define PROBE_CPU_R10_OFFSET (PROBE_FIRST_GPR_OFFSET + (10 * PTR_SIZE))
#define PROBE_CPU_R11_OFFSET (PROBE_FIRST_GPR_OFFSET + (11 * PTR_SIZE))
#define PROBE_CPU_R12_OFFSET (PROBE_FIRST_GPR_OFFSET + (12 * PTR_SIZE))
#define PROBE_CPU_R13_OFFSET (PROBE_FIRST_GPR_OFFSET + (13 * PTR_SIZE))
#define PROBE_CPU_R14_OFFSET (PROBE_FIRST_GPR_OFFSET + (14 * PTR_SIZE))
#define PROBE_CPU_R15_OFFSET (PROBE_FIRST_GPR_OFFSET + (15 * PTR_SIZE))
#define PROBE_FIRST_SPR_OFFSET (PROBE_FIRST_GPR_OFFSET + (16 * PTR_SIZE))
#endif // CPU(X86_64)
#define PROBE_CPU_EIP_OFFSET (PROBE_FIRST_SPR_OFFSET + (0 * PTR_SIZE))
#define PROBE_CPU_EFLAGS_OFFSET (PROBE_FIRST_SPR_OFFSET + (1 * PTR_SIZE))
#define PROBE_FIRST_XMM_OFFSET (PROBE_FIRST_SPR_OFFSET + (2 * PTR_SIZE))
#define XMM_SIZE 8
#define PROBE_CPU_XMM0_OFFSET (PROBE_FIRST_XMM_OFFSET + (0 * XMM_SIZE))
#define PROBE_CPU_XMM1_OFFSET (PROBE_FIRST_XMM_OFFSET + (1 * XMM_SIZE))
#define PROBE_CPU_XMM2_OFFSET (PROBE_FIRST_XMM_OFFSET + (2 * XMM_SIZE))
#define PROBE_CPU_XMM3_OFFSET (PROBE_FIRST_XMM_OFFSET + (3 * XMM_SIZE))
#define PROBE_CPU_XMM4_OFFSET (PROBE_FIRST_XMM_OFFSET + (4 * XMM_SIZE))
#define PROBE_CPU_XMM5_OFFSET (PROBE_FIRST_XMM_OFFSET + (5 * XMM_SIZE))
#define PROBE_CPU_XMM6_OFFSET (PROBE_FIRST_XMM_OFFSET + (6 * XMM_SIZE))
#define PROBE_CPU_XMM7_OFFSET (PROBE_FIRST_XMM_OFFSET + (7 * XMM_SIZE))
#if CPU(X86)
#define PROBE_SIZE (PROBE_CPU_XMM7_OFFSET + XMM_SIZE)
#else // CPU(X86_64)
#define PROBE_CPU_XMM8_OFFSET (PROBE_FIRST_XMM_OFFSET + (8 * XMM_SIZE))
#define PROBE_CPU_XMM9_OFFSET (PROBE_FIRST_XMM_OFFSET + (9 * XMM_SIZE))
#define PROBE_CPU_XMM10_OFFSET (PROBE_FIRST_XMM_OFFSET + (10 * XMM_SIZE))
#define PROBE_CPU_XMM11_OFFSET (PROBE_FIRST_XMM_OFFSET + (11 * XMM_SIZE))
#define PROBE_CPU_XMM12_OFFSET (PROBE_FIRST_XMM_OFFSET + (12 * XMM_SIZE))
#define PROBE_CPU_XMM13_OFFSET (PROBE_FIRST_XMM_OFFSET + (13 * XMM_SIZE))
#define PROBE_CPU_XMM14_OFFSET (PROBE_FIRST_XMM_OFFSET + (14 * XMM_SIZE))
#define PROBE_CPU_XMM15_OFFSET (PROBE_FIRST_XMM_OFFSET + (15 * XMM_SIZE))
#define PROBE_SIZE (PROBE_CPU_XMM15_OFFSET + XMM_SIZE)
#endif // CPU(X86_64)
#define PROBE_EXECUTOR_OFFSET PROBE_SIZE // Stash the executeProbe function pointer at the end of the ProbeContext.
// The outgoing record to be popped off the stack at the end consists of:
// eflags, eax, ecx, ebp, eip.
#define OUT_SIZE (5 * PTR_SIZE)
// These ASSERTs remind you that if you change the layout of Probe::State,
// you need to change ctiMasmProbeTrampoline offsets above to match.
#define PROBE_OFFSETOF(x) offsetof(struct Probe::State, x)
#define PROBE_OFFSETOF_REG(x, reg) offsetof(struct Probe::State, x) + reg * sizeof((reinterpret_cast<Probe::State*>(0))->x[reg])
static_assert(PROBE_OFFSETOF(probeFunction) == PROBE_PROBE_FUNCTION_OFFSET, "Probe::State::probeFunction's offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF(arg) == PROBE_ARG_OFFSET, "Probe::State::arg's offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF(initializeStackFunction) == PROBE_INIT_STACK_FUNCTION_OFFSET, "Probe::State::initializeStackFunction's offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF(initializeStackArg) == PROBE_INIT_STACK_ARG_OFFSET, "Probe::State::initializeStackArg's offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.gprs, X86Registers::eax) == PROBE_CPU_EAX_OFFSET, "Probe::State::cpu.gprs[eax]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.gprs, X86Registers::ecx) == PROBE_CPU_ECX_OFFSET, "Probe::State::cpu.gprs[ecx]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.gprs, X86Registers::edx) == PROBE_CPU_EDX_OFFSET, "Probe::State::cpu.gprs[edx]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.gprs, X86Registers::ebx) == PROBE_CPU_EBX_OFFSET, "Probe::State::cpu.gprs[ebx]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.gprs, X86Registers::esp) == PROBE_CPU_ESP_OFFSET, "Probe::State::cpu.gprs[esp]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.gprs, X86Registers::ebp) == PROBE_CPU_EBP_OFFSET, "Probe::State::cpu.gprs[ebp]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.gprs, X86Registers::esi) == PROBE_CPU_ESI_OFFSET, "Probe::State::cpu.gprs[esi]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.gprs, X86Registers::edi) == PROBE_CPU_EDI_OFFSET, "Probe::State::cpu.gprs[edi]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.sprs, X86Registers::eip) == PROBE_CPU_EIP_OFFSET, "Probe::State::cpu.gprs[eip]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.sprs, X86Registers::eflags) == PROBE_CPU_EFLAGS_OFFSET, "Probe::State::cpu.sprs[eflags]'s offset matches ctiMasmProbeTrampoline");
#if CPU(X86_64)
static_assert(PROBE_OFFSETOF_REG(cpu.gprs, X86Registers::r8) == PROBE_CPU_R8_OFFSET, "Probe::State::cpu.gprs[r8]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.gprs, X86Registers::r9) == PROBE_CPU_R9_OFFSET, "Probe::State::cpu.gprs[r9]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.gprs, X86Registers::r10) == PROBE_CPU_R10_OFFSET, "Probe::State::cpu.gprs[r10]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.gprs, X86Registers::r11) == PROBE_CPU_R11_OFFSET, "Probe::State::cpu.gprs[r11]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.gprs, X86Registers::r12) == PROBE_CPU_R12_OFFSET, "Probe::State::cpu.gprs[r12]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.gprs, X86Registers::r13) == PROBE_CPU_R13_OFFSET, "Probe::State::cpu.gprs[r13]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.gprs, X86Registers::r14) == PROBE_CPU_R14_OFFSET, "Probe::State::cpu.gprs[r14]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.gprs, X86Registers::r15) == PROBE_CPU_R15_OFFSET, "Probe::State::cpu.gprs[r15]'s offset matches ctiMasmProbeTrampoline");
#endif // CPU(X86_64)
static_assert(!(PROBE_CPU_XMM0_OFFSET & 0x7), "Probe::State::cpu.fprs[xmm0]'s offset should be 8 byte aligned");
static_assert(PROBE_OFFSETOF_REG(cpu.fprs, X86Registers::xmm0) == PROBE_CPU_XMM0_OFFSET, "Probe::State::cpu.fprs[xmm0]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.fprs, X86Registers::xmm1) == PROBE_CPU_XMM1_OFFSET, "Probe::State::cpu.fprs[xmm1]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.fprs, X86Registers::xmm2) == PROBE_CPU_XMM2_OFFSET, "Probe::State::cpu.fprs[xmm2]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.fprs, X86Registers::xmm3) == PROBE_CPU_XMM3_OFFSET, "Probe::State::cpu.fprs[xmm3]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.fprs, X86Registers::xmm4) == PROBE_CPU_XMM4_OFFSET, "Probe::State::cpu.fprs[xmm4]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.fprs, X86Registers::xmm5) == PROBE_CPU_XMM5_OFFSET, "Probe::State::cpu.fprs[xmm5]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.fprs, X86Registers::xmm6) == PROBE_CPU_XMM6_OFFSET, "Probe::State::cpu.fprs[xmm6]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.fprs, X86Registers::xmm7) == PROBE_CPU_XMM7_OFFSET, "Probe::State::cpu.fprs[xmm7]'s offset matches ctiMasmProbeTrampoline");
#if CPU(X86_64)
static_assert(PROBE_OFFSETOF_REG(cpu.fprs, X86Registers::xmm8) == PROBE_CPU_XMM8_OFFSET, "Probe::State::cpu.fprs[xmm8]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.fprs, X86Registers::xmm9) == PROBE_CPU_XMM9_OFFSET, "Probe::State::cpu.fprs[xmm9]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.fprs, X86Registers::xmm10) == PROBE_CPU_XMM10_OFFSET, "Probe::State::cpu.fprs[xmm10]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.fprs, X86Registers::xmm11) == PROBE_CPU_XMM11_OFFSET, "Probe::State::cpu.fprs[xmm11]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.fprs, X86Registers::xmm12) == PROBE_CPU_XMM12_OFFSET, "Probe::State::cpu.fprs[xmm12]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.fprs, X86Registers::xmm13) == PROBE_CPU_XMM13_OFFSET, "Probe::State::cpu.fprs[xmm13]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.fprs, X86Registers::xmm14) == PROBE_CPU_XMM14_OFFSET, "Probe::State::cpu.fprs[xmm14]'s offset matches ctiMasmProbeTrampoline");
static_assert(PROBE_OFFSETOF_REG(cpu.fprs, X86Registers::xmm15) == PROBE_CPU_XMM15_OFFSET, "Probe::State::cpu.fprs[xmm15]'s offset matches ctiMasmProbeTrampoline");
#endif // CPU(X86_64)
static_assert(sizeof(Probe::State) == PROBE_SIZE, "Probe::State::size's matches ctiMasmProbeTrampoline");
static_assert((PROBE_EXECUTOR_OFFSET + PTR_SIZE) <= (PROBE_SIZE + OUT_SIZE), "Must have room after ProbeContext to stash the probe handler");
#undef PROBE_OFFSETOF
#if CPU(X86)
#if COMPILER(GCC_COMPATIBLE)
asm (
".globl " SYMBOL_STRING(ctiMasmProbeTrampoline) "\n"
HIDE_SYMBOL(ctiMasmProbeTrampoline) "\n"
SYMBOL_STRING(ctiMasmProbeTrampoline) ":" "\n"
"pushfl" "\n"
// MacroAssemblerX86Common::probe() has already generated code to store some values.
// Together with the eflags pushed above, the top of stack now looks like
// this:
// esp[0 * ptrSize]: eflags
// esp[1 * ptrSize]: return address / saved eip
// esp[2 * ptrSize]: saved ebx
// esp[3 * ptrSize]: saved edx
// esp[4 * ptrSize]: saved ecx
// esp[5 * ptrSize]: saved eax
//
// Incoming registers contain:
// ecx: Probe::executeProbe
// edx: probe function
// ebx: probe arg
// eax: scratch (was ctiMasmProbeTrampoline)
"movl %esp, %eax" "\n"
"subl $" STRINGIZE_VALUE_OF(PROBE_SIZE + OUT_SIZE) ", %esp" "\n"
// The X86_64 ABI specifies that the worse case stack alignment requirement is 32 bytes.
"andl $~0x1f, %esp" "\n"
"movl %ebp, " STRINGIZE_VALUE_OF(PROBE_CPU_EBP_OFFSET) "(%esp)" "\n"
"movl %esp, %ebp" "\n" // Save the Probe::State*.
"movl %ecx, " STRINGIZE_VALUE_OF(PROBE_EXECUTOR_OFFSET) "(%ebp)" "\n"
"movl %edx, " STRINGIZE_VALUE_OF(PROBE_PROBE_FUNCTION_OFFSET) "(%ebp)" "\n"
"movl %ebx, " STRINGIZE_VALUE_OF(PROBE_ARG_OFFSET) "(%ebp)" "\n"
"movl %esi, " STRINGIZE_VALUE_OF(PROBE_CPU_ESI_OFFSET) "(%ebp)" "\n"
"movl %edi, " STRINGIZE_VALUE_OF(PROBE_CPU_EDI_OFFSET) "(%ebp)" "\n"
"movl 0 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%eax), %ecx" "\n"
"movl %ecx, " STRINGIZE_VALUE_OF(PROBE_CPU_EFLAGS_OFFSET) "(%ebp)" "\n"
"movl 1 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%eax), %ecx" "\n"
"movl %ecx, " STRINGIZE_VALUE_OF(PROBE_CPU_EIP_OFFSET) "(%ebp)" "\n"
"movl 2 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%eax), %ecx" "\n"
"movl %ecx, " STRINGIZE_VALUE_OF(PROBE_CPU_EBX_OFFSET) "(%ebp)" "\n"
"movl 3 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%eax), %ecx" "\n"
"movl %ecx, " STRINGIZE_VALUE_OF(PROBE_CPU_EDX_OFFSET) "(%ebp)" "\n"
"movl 4 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%eax), %ecx" "\n"
"movl %ecx, " STRINGIZE_VALUE_OF(PROBE_CPU_ECX_OFFSET) "(%ebp)" "\n"
"movl 5 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%eax), %ecx" "\n"
"movl %ecx, " STRINGIZE_VALUE_OF(PROBE_CPU_EAX_OFFSET) "(%ebp)" "\n"
"movl %eax, %ecx" "\n"
"addl $" STRINGIZE_VALUE_OF(6 * PTR_SIZE) ", %ecx" "\n"
"movl %ecx, " STRINGIZE_VALUE_OF(PROBE_CPU_ESP_OFFSET) "(%ebp)" "\n"
"movq %xmm0, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM0_OFFSET) "(%ebp)" "\n"
"movq %xmm1, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM1_OFFSET) "(%ebp)" "\n"
"movq %xmm2, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM2_OFFSET) "(%ebp)" "\n"
"movq %xmm3, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM3_OFFSET) "(%ebp)" "\n"
"movq %xmm4, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM4_OFFSET) "(%ebp)" "\n"
"movq %xmm5, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM5_OFFSET) "(%ebp)" "\n"
"movq %xmm6, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM6_OFFSET) "(%ebp)" "\n"
"movq %xmm7, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM7_OFFSET) "(%ebp)" "\n"
// Reserve stack space for the arg while maintaining the required stack
// pointer 32 byte alignment:
"subl $0x20, %esp" "\n"
"movl %ebp, 0(%esp)" "\n" // the Probe::State* arg.
"call *" STRINGIZE_VALUE_OF(PROBE_EXECUTOR_OFFSET) "(%ebp)" "\n"
// Make sure the Probe::State is entirely below the result stack pointer so
// that register values are still preserved when we call the initializeStack
// function.
"movl $" STRINGIZE_VALUE_OF(PROBE_SIZE + OUT_SIZE) ", %ecx" "\n"
"movl %ebp, %eax" "\n"
"movl " STRINGIZE_VALUE_OF(PROBE_CPU_ESP_OFFSET) "(%ebp), %edx" "\n"
"addl %ecx, %eax" "\n"
"cmpl %eax, %edx" "\n"
"jge " LOCAL_LABEL_STRING(ctiMasmProbeTrampolineProbeStateIsSafe) "\n"
// Allocate a safe place on the stack below the result stack pointer to stash the Probe::State.
"subl %ecx, %edx" "\n"
"andl $~0x1f, %edx" "\n" // Keep the stack pointer 32 bytes aligned.
"xorl %eax, %eax" "\n"
"movl %edx, %esp" "\n"
"movl $" STRINGIZE_VALUE_OF(PROBE_SIZE) ", %ecx" "\n"
// Copy the Probe::State to the safe place.
LOCAL_LABEL_STRING(ctiMasmProbeTrampolineCopyLoop) ":" "\n"
"movl (%ebp, %eax), %edx" "\n"
"movl %edx, (%esp, %eax)" "\n"
"addl $" STRINGIZE_VALUE_OF(PTR_SIZE) ", %eax" "\n"
"cmpl %eax, %ecx" "\n"
"jg " LOCAL_LABEL_STRING(ctiMasmProbeTrampolineCopyLoop) "\n"
"movl %esp, %ebp" "\n"
// Call initializeStackFunction if present.
LOCAL_LABEL_STRING(ctiMasmProbeTrampolineProbeStateIsSafe) ":" "\n"
"xorl %ecx, %ecx" "\n"
"addl " STRINGIZE_VALUE_OF(PROBE_INIT_STACK_FUNCTION_OFFSET) "(%ebp), %ecx" "\n"
"je " LOCAL_LABEL_STRING(ctiMasmProbeTrampolineRestoreRegisters) "\n"
// Reserve stack space for the arg while maintaining the required stack
// pointer 32 byte alignment:
"subl $0x20, %esp" "\n"
"movl %ebp, 0(%esp)" "\n" // the Probe::State* arg.
"call *%ecx" "\n"
LOCAL_LABEL_STRING(ctiMasmProbeTrampolineRestoreRegisters) ":" "\n"
// To enable probes to modify register state, we copy all registers
// out of the Probe::State before returning.
"movl " STRINGIZE_VALUE_OF(PROBE_CPU_EDX_OFFSET) "(%ebp), %edx" "\n"
"movl " STRINGIZE_VALUE_OF(PROBE_CPU_EBX_OFFSET) "(%ebp), %ebx" "\n"
"movl " STRINGIZE_VALUE_OF(PROBE_CPU_ESI_OFFSET) "(%ebp), %esi" "\n"
"movl " STRINGIZE_VALUE_OF(PROBE_CPU_EDI_OFFSET) "(%ebp), %edi" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM0_OFFSET) "(%ebp), %xmm0" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM1_OFFSET) "(%ebp), %xmm1" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM2_OFFSET) "(%ebp), %xmm2" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM3_OFFSET) "(%ebp), %xmm3" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM4_OFFSET) "(%ebp), %xmm4" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM5_OFFSET) "(%ebp), %xmm5" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM6_OFFSET) "(%ebp), %xmm6" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM7_OFFSET) "(%ebp), %xmm7" "\n"
// There are 6 more registers left to restore:
// eax, ecx, ebp, esp, eip, and eflags.
// The restoration process at ctiMasmProbeTrampolineEnd below works by popping
// 5 words off the stack into eflags, eax, ecx, ebp, and eip. These 5 words need
// to be pushed on top of the final esp value so that just by popping the 5 words,
// we'll get the esp that the probe wants to set. Let's call this area (for storing
// these 5 words) the restore area.
"movl " STRINGIZE_VALUE_OF(PROBE_CPU_ESP_OFFSET) "(%ebp), %ecx" "\n"
"subl $5 * " STRINGIZE_VALUE_OF(PTR_SIZE) ", %ecx" "\n"
// ecx now points to the restore area.
// Copy remaining restore values from the Probe::State to the restore area.
// Note: We already ensured above that the Probe::State is in a safe location before
// calling the initializeStackFunction. The initializeStackFunction is not allowed to
// change the stack pointer again.
"movl " STRINGIZE_VALUE_OF(PROBE_CPU_EFLAGS_OFFSET) "(%ebp), %eax" "\n"
"movl %eax, 0 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%ecx)" "\n"
"movl " STRINGIZE_VALUE_OF(PROBE_CPU_EAX_OFFSET) "(%ebp), %eax" "\n"
"movl %eax, 1 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%ecx)" "\n"
"movl " STRINGIZE_VALUE_OF(PROBE_CPU_ECX_OFFSET) "(%ebp), %eax" "\n"
"movl %eax, 2 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%ecx)" "\n"
"movl " STRINGIZE_VALUE_OF(PROBE_CPU_EBP_OFFSET) "(%ebp), %eax" "\n"
"movl %eax, 3 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%ecx)" "\n"
"movl " STRINGIZE_VALUE_OF(PROBE_CPU_EIP_OFFSET) "(%ebp), %eax" "\n"
"movl %eax, 4 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%ecx)" "\n"
"movl %ecx, %esp" "\n"
// Do the remaining restoration by popping off the restore area.
"popfl" "\n"
"popl %eax" "\n"
"popl %ecx" "\n"
"popl %ebp" "\n"
"ret" "\n"
);
#endif
#if COMPILER(MSVC)
extern "C" __declspec(naked) void ctiMasmProbeTrampoline()
{
__asm {
pushfd;
// MacroAssemblerX86Common::probe() has already generated code to store some values.
// Together with the eflags pushed above, the top of stack now looks like
// this:
// esp[0 * ptrSize]: eflags
// esp[1 * ptrSize]: return address / saved eip
// esp[2 * ptrSize]: saved ebx
// esp[3 * ptrSize]: saved edx
// esp[4 * ptrSize]: saved ecx
// esp[5 * ptrSize]: saved eax
//
// Incoming registers contain:
// ecx: Probe::executeProbe
// edx: probe function
// ebx: probe arg
// eax: scratch (was ctiMasmProbeTrampoline)
mov eax, esp
sub esp, PROBE_SIZE + OUT_SIZE
// The X86_64 ABI specifies that the worse case stack alignment requirement is 32 bytes.
and esp, ~0x1f
mov [PROBE_CPU_EBP_OFFSET + esp], ebp
mov ebp, esp // Save the ProbeContext*.
mov [PROBE_EXECUTOR_OFFSET + ebp], ecx
mov [PROBE_PROBE_FUNCTION_OFFSET + ebp], edx
mov [PROBE_ARG_OFFSET + ebp], ebx
mov [PROBE_CPU_ESI_OFFSET + ebp], esi
mov [PROBE_CPU_EDI_OFFSET + ebp], edi
mov ecx, [0 * PTR_SIZE + eax]
mov [PROBE_CPU_EFLAGS_OFFSET + ebp], ecx
mov ecx, [1 * PTR_SIZE + eax]
mov [PROBE_CPU_EIP_OFFSET + ebp], ecx
mov ecx, [2 * PTR_SIZE + eax]
mov [PROBE_CPU_EBX_OFFSET + ebp], ecx
mov ecx, [3 * PTR_SIZE + eax]
mov [PROBE_CPU_EDX_OFFSET + ebp], ecx
mov ecx, [4 * PTR_SIZE + eax]
mov [PROBE_CPU_ECX_OFFSET + ebp], ecx
mov ecx, [5 * PTR_SIZE + eax]
mov [PROBE_CPU_EAX_OFFSET + ebp], ecx
mov ecx, eax
add ecx, 6 * PTR_SIZE
mov [PROBE_CPU_ESP_OFFSET + ebp], ecx
movq qword ptr[PROBE_CPU_XMM0_OFFSET + ebp], xmm0
movq qword ptr[PROBE_CPU_XMM1_OFFSET + ebp], xmm1
movq qword ptr[PROBE_CPU_XMM2_OFFSET + ebp], xmm2
movq qword ptr[PROBE_CPU_XMM3_OFFSET + ebp], xmm3
movq qword ptr[PROBE_CPU_XMM4_OFFSET + ebp], xmm4
movq qword ptr[PROBE_CPU_XMM5_OFFSET + ebp], xmm5
movq qword ptr[PROBE_CPU_XMM6_OFFSET + ebp], xmm6
movq qword ptr[PROBE_CPU_XMM7_OFFSET + ebp], xmm7
// Reserve stack space for the arg while maintaining the required stack
// pointer 32 byte alignment:
sub esp, 0x20
mov [0 + esp], ebp // the ProbeContext* arg.
call [PROBE_EXECUTOR_OFFSET + ebp]
// Make sure the ProbeContext is entirely below the result stack pointer so
// that register values are still preserved when we call the initializeStack
// function.
mov ecx, PROBE_SIZE + OUT_SIZE
mov eax, ebp
mov edx, [PROBE_CPU_ESP_OFFSET + ebp]
add eax, ecx
cmp edx, eax
jge ctiMasmProbeTrampolineProbeContextIsSafe
// Allocate a safe place on the stack below the result stack pointer to stash the ProbeContext.
sub edx, ecx
and edx, ~0x1f // Keep the stack pointer 32 bytes aligned.
xor eax, eax
mov esp, edx
mov ecx, PROBE_SIZE
// Copy the ProbeContext to the safe place.
ctiMasmProbeTrampolineCopyLoop :
mov edx, [ebp + eax]
mov [esp + eax], edx
add eax, PTR_SIZE
cmp ecx, eax
jg ctiMasmProbeTrampolineCopyLoop
mov ebp, esp
// Call initializeStackFunction if present.
ctiMasmProbeTrampolineProbeContextIsSafe :
xor ecx, ecx
add ecx, [PROBE_INIT_STACK_FUNCTION_OFFSET + ebp]
je ctiMasmProbeTrampolineRestoreRegisters
// Reserve stack space for the arg while maintaining the required stack
// pointer 32 byte alignment:
sub esp, 0x20
mov [0 + esp], ebp // the ProbeContext* arg.
call ecx
ctiMasmProbeTrampolineRestoreRegisters :
// To enable probes to modify register state, we copy all registers
// out of the ProbeContext before returning.
mov edx, [PROBE_CPU_EDX_OFFSET + ebp]
mov ebx, [PROBE_CPU_EBX_OFFSET + ebp]
mov esi, [PROBE_CPU_ESI_OFFSET + ebp]
mov edi, [PROBE_CPU_EDI_OFFSET + ebp]
movq xmm0, qword ptr[PROBE_CPU_XMM0_OFFSET + ebp]
movq xmm1, qword ptr[PROBE_CPU_XMM1_OFFSET + ebp]
movq xmm2, qword ptr[PROBE_CPU_XMM2_OFFSET + ebp]
movq xmm3, qword ptr[PROBE_CPU_XMM3_OFFSET + ebp]
movq xmm4, qword ptr[PROBE_CPU_XMM4_OFFSET + ebp]
movq xmm5, qword ptr[PROBE_CPU_XMM5_OFFSET + ebp]
movq xmm6, qword ptr[PROBE_CPU_XMM6_OFFSET + ebp]
movq xmm7, qword ptr[PROBE_CPU_XMM7_OFFSET + ebp]
// There are 6 more registers left to restore:
// eax, ecx, ebp, esp, eip, and eflags.
// The restoration process at ctiMasmProbeTrampolineEnd below works by popping
// 5 words off the stack into eflags, eax, ecx, ebp, and eip. These 5 words need
// to be pushed on top of the final esp value so that just by popping the 5 words,
// we'll get the esp that the probe wants to set. Let's call this area (for storing
// these 5 words) the restore area.
mov ecx, [PROBE_CPU_ESP_OFFSET + ebp]
sub ecx, 5 * PTR_SIZE
// ecx now points to the restore area.
// Copy remaining restore values from the ProbeContext to the restore area.
// Note: We already ensured above that the ProbeContext is in a safe location before
// calling the initializeStackFunction. The initializeStackFunction is not allowed to
// change the stack pointer again.
mov eax, [PROBE_CPU_EFLAGS_OFFSET + ebp]
mov [0 * PTR_SIZE + ecx], eax
mov eax, [PROBE_CPU_EAX_OFFSET + ebp]
mov [1 * PTR_SIZE + ecx], eax
mov eax, [PROBE_CPU_ECX_OFFSET + ebp]
mov [2 * PTR_SIZE + ecx], eax
mov eax, [PROBE_CPU_EBP_OFFSET + ebp]
mov [3 * PTR_SIZE + ecx], eax
mov eax, [PROBE_CPU_EIP_OFFSET + ebp]
mov [4 * PTR_SIZE + ecx], eax
mov esp, ecx
// Do the remaining restoration by popping off the restore area.
popfd
pop eax
pop ecx
pop ebp
ret
}
}
#endif // COMPILER(MSVC)
#endif // CPU(X86)
#if CPU(X86_64)
#if COMPILER(GCC_COMPATIBLE)
asm (
".globl " SYMBOL_STRING(ctiMasmProbeTrampoline) "\n"
HIDE_SYMBOL(ctiMasmProbeTrampoline) "\n"
SYMBOL_STRING(ctiMasmProbeTrampoline) ":" "\n"
"pushfq" "\n"
// MacroAssemblerX86Common::probe() has already generated code to store some values.
// Together with the rflags pushed above, the top of stack now looks like this:
// rsp[0 * ptrSize]: rflags
// rsp[1 * ptrSize]: return address / saved rip
// rsp[2 * ptrSize]: saved rbx
// rsp[3 * ptrSize]: saved rdx
// rsp[4 * ptrSize]: saved rcx
// rsp[5 * ptrSize]: saved rax
//
// Incoming registers contain:
// rcx: Probe::executeProbe
// rdx: probe function
// rbx: probe arg
// rax: scratch (was ctiMasmProbeTrampoline)
"movq %rsp, %rax" "\n"
"subq $" STRINGIZE_VALUE_OF(PROBE_SIZE + OUT_SIZE) ", %rsp" "\n"
// The X86_64 ABI specifies that the worse case stack alignment requirement is 32 bytes.
"andq $~0x1f, %rsp" "\n"
// Since sp points to the Probe::State, we've ensured that it's protected from interrupts before we initialize it.
"movq %rbp, " STRINGIZE_VALUE_OF(PROBE_CPU_EBP_OFFSET) "(%rsp)" "\n"
"movq %rsp, %rbp" "\n" // Save the Probe::State*.
"movq %rcx, " STRINGIZE_VALUE_OF(PROBE_EXECUTOR_OFFSET) "(%rbp)" "\n"
"movq %rdx, " STRINGIZE_VALUE_OF(PROBE_PROBE_FUNCTION_OFFSET) "(%rbp)" "\n"
"movq %rbx, " STRINGIZE_VALUE_OF(PROBE_ARG_OFFSET) "(%rbp)" "\n"
"movq %rsi, " STRINGIZE_VALUE_OF(PROBE_CPU_ESI_OFFSET) "(%rbp)" "\n"
"movq %rdi, " STRINGIZE_VALUE_OF(PROBE_CPU_EDI_OFFSET) "(%rbp)" "\n"
"movq 0 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rax), %rcx" "\n"
"movq %rcx, " STRINGIZE_VALUE_OF(PROBE_CPU_EFLAGS_OFFSET) "(%rbp)" "\n"
"movq 1 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rax), %rcx" "\n"
"movq %rcx, " STRINGIZE_VALUE_OF(PROBE_CPU_EIP_OFFSET) "(%rbp)" "\n"
"movq 2 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rax), %rcx" "\n"
"movq %rcx, " STRINGIZE_VALUE_OF(PROBE_CPU_EBX_OFFSET) "(%rbp)" "\n"
"movq 3 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rax), %rcx" "\n"
"movq %rcx, " STRINGIZE_VALUE_OF(PROBE_CPU_EDX_OFFSET) "(%rbp)" "\n"
"movq 4 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rax), %rcx" "\n"
"movq %rcx, " STRINGIZE_VALUE_OF(PROBE_CPU_ECX_OFFSET) "(%rbp)" "\n"
"movq 5 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rax), %rcx" "\n"
"movq %rcx, " STRINGIZE_VALUE_OF(PROBE_CPU_EAX_OFFSET) "(%rbp)" "\n"
"movq %rax, %rcx" "\n"
"addq $" STRINGIZE_VALUE_OF(6 * PTR_SIZE) ", %rcx" "\n"
"movq %rcx, " STRINGIZE_VALUE_OF(PROBE_CPU_ESP_OFFSET) "(%rbp)" "\n"
"movq %r8, " STRINGIZE_VALUE_OF(PROBE_CPU_R8_OFFSET) "(%rbp)" "\n"
"movq %r9, " STRINGIZE_VALUE_OF(PROBE_CPU_R9_OFFSET) "(%rbp)" "\n"
"movq %r10, " STRINGIZE_VALUE_OF(PROBE_CPU_R10_OFFSET) "(%rbp)" "\n"
"movq %r11, " STRINGIZE_VALUE_OF(PROBE_CPU_R11_OFFSET) "(%rbp)" "\n"
"movq %r12, " STRINGIZE_VALUE_OF(PROBE_CPU_R12_OFFSET) "(%rbp)" "\n"
"movq %r13, " STRINGIZE_VALUE_OF(PROBE_CPU_R13_OFFSET) "(%rbp)" "\n"
"movq %r14, " STRINGIZE_VALUE_OF(PROBE_CPU_R14_OFFSET) "(%rbp)" "\n"
"movq %r15, " STRINGIZE_VALUE_OF(PROBE_CPU_R15_OFFSET) "(%rbp)" "\n"
"movq %xmm0, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM0_OFFSET) "(%rbp)" "\n"
"movq %xmm1, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM1_OFFSET) "(%rbp)" "\n"
"movq %xmm2, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM2_OFFSET) "(%rbp)" "\n"
"movq %xmm3, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM3_OFFSET) "(%rbp)" "\n"
"movq %xmm4, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM4_OFFSET) "(%rbp)" "\n"
"movq %xmm5, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM5_OFFSET) "(%rbp)" "\n"
"movq %xmm6, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM6_OFFSET) "(%rbp)" "\n"
"movq %xmm7, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM7_OFFSET) "(%rbp)" "\n"
"movq %xmm8, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM8_OFFSET) "(%rbp)" "\n"
"movq %xmm9, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM9_OFFSET) "(%rbp)" "\n"
"movq %xmm10, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM10_OFFSET) "(%rbp)" "\n"
"movq %xmm11, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM11_OFFSET) "(%rbp)" "\n"
"movq %xmm12, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM12_OFFSET) "(%rbp)" "\n"
"movq %xmm13, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM13_OFFSET) "(%rbp)" "\n"
"movq %xmm14, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM14_OFFSET) "(%rbp)" "\n"
"movq %xmm15, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM15_OFFSET) "(%rbp)" "\n"
"movq %rbp, %rdi" "\n" // the Probe::State* arg.
"call *" STRINGIZE_VALUE_OF(PROBE_EXECUTOR_OFFSET) "(%rbp)" "\n"
// Make sure the Probe::State is entirely below the result stack pointer so
// that register values are still preserved when we call the initializeStack
// function.
"movq $" STRINGIZE_VALUE_OF(PROBE_SIZE + OUT_SIZE) ", %rcx" "\n"
"movq %rbp, %rax" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_ESP_OFFSET) "(%rbp), %rdx" "\n"
"addq %rcx, %rax" "\n"
"cmpq %rax, %rdx" "\n"
"jge " LOCAL_LABEL_STRING(ctiMasmProbeTrampolineProbeStateIsSafe) "\n"
// Allocate a safe place on the stack below the result stack pointer to stash the Probe::State.
"subq %rcx, %rdx" "\n"
"andq $~0x1f, %rdx" "\n" // Keep the stack pointer 32 bytes aligned.
"xorq %rax, %rax" "\n"
"movq %rdx, %rsp" "\n"
"movq $" STRINGIZE_VALUE_OF(PROBE_SIZE) ", %rcx" "\n"
// Copy the Probe::State to the safe place.
LOCAL_LABEL_STRING(ctiMasmProbeTrampolineCopyLoop) ":" "\n"
"movq (%rbp, %rax), %rdx" "\n"
"movq %rdx, (%rsp, %rax)" "\n"
"addq $" STRINGIZE_VALUE_OF(PTR_SIZE) ", %rax" "\n"
"cmpq %rax, %rcx" "\n"
"jg " LOCAL_LABEL_STRING(ctiMasmProbeTrampolineCopyLoop) "\n"
"movq %rsp, %rbp" "\n"
// Call initializeStackFunction if present.
LOCAL_LABEL_STRING(ctiMasmProbeTrampolineProbeStateIsSafe) ":" "\n"
"xorq %rcx, %rcx" "\n"
"addq " STRINGIZE_VALUE_OF(PROBE_INIT_STACK_FUNCTION_OFFSET) "(%rbp), %rcx" "\n"
"je " LOCAL_LABEL_STRING(ctiMasmProbeTrampolineRestoreRegisters) "\n"
"movq %rbp, %rdi" "\n" // the Probe::State* arg.
"call *%rcx" "\n"
LOCAL_LABEL_STRING(ctiMasmProbeTrampolineRestoreRegisters) ":" "\n"
// To enable probes to modify register state, we copy all registers
// out of the Probe::State before returning.
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_EDX_OFFSET) "(%rbp), %rdx" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_EBX_OFFSET) "(%rbp), %rbx" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_ESI_OFFSET) "(%rbp), %rsi" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_EDI_OFFSET) "(%rbp), %rdi" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_R8_OFFSET) "(%rbp), %r8" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_R9_OFFSET) "(%rbp), %r9" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_R10_OFFSET) "(%rbp), %r10" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_R11_OFFSET) "(%rbp), %r11" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_R12_OFFSET) "(%rbp), %r12" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_R13_OFFSET) "(%rbp), %r13" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_R14_OFFSET) "(%rbp), %r14" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_R15_OFFSET) "(%rbp), %r15" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM0_OFFSET) "(%rbp), %xmm0" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM1_OFFSET) "(%rbp), %xmm1" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM2_OFFSET) "(%rbp), %xmm2" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM3_OFFSET) "(%rbp), %xmm3" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM4_OFFSET) "(%rbp), %xmm4" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM5_OFFSET) "(%rbp), %xmm5" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM6_OFFSET) "(%rbp), %xmm6" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM7_OFFSET) "(%rbp), %xmm7" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM8_OFFSET) "(%rbp), %xmm8" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM9_OFFSET) "(%rbp), %xmm9" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM10_OFFSET) "(%rbp), %xmm10" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM11_OFFSET) "(%rbp), %xmm11" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM12_OFFSET) "(%rbp), %xmm12" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM13_OFFSET) "(%rbp), %xmm13" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM14_OFFSET) "(%rbp), %xmm14" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_XMM15_OFFSET) "(%rbp), %xmm15" "\n"
// There are 6 more registers left to restore:
// rax, rcx, rbp, rsp, rip, and rflags.
// The restoration process at ctiMasmProbeTrampolineEnd below works by popping
// 5 words off the stack into rflags, rax, rcx, rbp, and rip. These 5 words need
// to be pushed on top of the final esp value so that just by popping the 5 words,
// we'll get the esp that the probe wants to set. Let's call this area (for storing
// these 5 words) the restore area.
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_ESP_OFFSET) "(%rbp), %rcx" "\n"
"subq $5 * " STRINGIZE_VALUE_OF(PTR_SIZE) ", %rcx" "\n"
// rcx now points to the restore area.
// Copy remaining restore values from the Probe::State to the restore area.
// Note: We already ensured above that the Probe::State is in a safe location before
// calling the initializeStackFunction. The initializeStackFunction is not allowed to
// change the stack pointer again.
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_EFLAGS_OFFSET) "(%rbp), %rax" "\n"
"movq %rax, 0 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rcx)" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_EAX_OFFSET) "(%rbp), %rax" "\n"
"movq %rax, 1 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rcx)" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_ECX_OFFSET) "(%rbp), %rax" "\n"
"movq %rax, 2 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rcx)" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_EBP_OFFSET) "(%rbp), %rax" "\n"
"movq %rax, 3 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rcx)" "\n"
"movq " STRINGIZE_VALUE_OF(PROBE_CPU_EIP_OFFSET) "(%rbp), %rax" "\n"
"movq %rax, 4 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rcx)" "\n"
"movq %rcx, %rsp" "\n"
// Do the remaining restoration by popping off the restore area.
"popfq" "\n"
"popq %rax" "\n"
"popq %rcx" "\n"
"popq %rbp" "\n"
"ret" "\n"
);
#endif // COMPILER(GCC_COMPATIBLE)
#endif // CPU(X86_64)
// What code is emitted for the probe?
// ==================================
// We want to keep the size of the emitted probe invocation code as compact as
// possible to minimize the perturbation to the JIT generated code. However,
// we also need to preserve the CPU registers and set up the Probe::State to be
// passed to the user probe function.
//
// Hence, we do only the minimum here to preserve a scratch register (i.e. rax
// in this case) and the stack pointer (i.e. rsp), and pass the probe arguments.
// We'll let the ctiMasmProbeTrampoline handle the rest of the probe invocation
// work i.e. saving the CPUState (and setting up the Probe::State), calling the
// user probe function, and restoring the CPUState before returning to JIT
// generated code.
//
// What registers need to be saved?
// ===============================
// The registers are saved for 2 reasons:
// 1. To preserve their state in the JITted code. This means that all registers
// that are not callee saved needs to be saved. We also need to save the
// condition code registers because the probe can be inserted between a test
// and a branch.
// 2. To allow the probe to inspect the values of the registers for debugging
// purposes. This means all registers need to be saved.
//
// In summary, save everything. But for reasons stated above, we should do the
// minimum here and let ctiMasmProbeTrampoline do the heavy lifting to save the
// full set.
//
// What values are in the saved registers?
// ======================================
// Conceptually, the saved registers should contain values as if the probe
// is not present in the JIT generated code. Hence, they should contain values
// that are expected at the start of the instruction immediately following the
// probe.
//
// Specifically, the saved stack pointer register will point to the stack
// position before we push the Probe::State frame. The saved rip will point to
// the address of the instruction immediately following the probe.
void MacroAssembler::probe(Probe::Function function, void* arg)
{
push(RegisterID::eax);
move(TrustedImmPtr(reinterpret_cast<void*>(ctiMasmProbeTrampoline)), RegisterID::eax);
push(RegisterID::ecx);
move(TrustedImmPtr(reinterpret_cast<void*>(Probe::executeProbe)), RegisterID::ecx);
push(RegisterID::edx);
move(TrustedImmPtr(reinterpret_cast<void*>(function)), RegisterID::edx);
push(RegisterID::ebx);
move(TrustedImmPtr(arg), RegisterID::ebx);
call(RegisterID::eax, CFunctionPtrTag);
}
#endif // ENABLE(MASM_PROBE)
MacroAssemblerX86Common::CPUID MacroAssemblerX86Common::getCPUID(unsigned level)
{
return getCPUIDEx(level, 0);
}
MacroAssemblerX86Common::CPUID MacroAssemblerX86Common::getCPUIDEx(unsigned level, unsigned count)
{
CPUID result { };
#if COMPILER(MSVC)
__cpuidex(bitwise_cast<int*>(result.data()), level, count);
#else
__asm__ (
"cpuid\n"
: "=a"(result[0]), "=b"(result[1]), "=c"(result[2]), "=d"(result[3])
: "0"(level), "2"(count)
);
#endif
return result;
}
void MacroAssemblerX86Common::collectCPUFeatures()
{
static std::once_flag onceKey;
std::call_once(onceKey, [] {
{
CPUID cpuid = getCPUID(0x1);
s_sse4_1CheckState = (cpuid[2] & (1 << 19)) ? CPUIDCheckState::Set : CPUIDCheckState::Clear;
s_sse4_2CheckState = (cpuid[2] & (1 << 20)) ? CPUIDCheckState::Set : CPUIDCheckState::Clear;
s_popcntCheckState = (cpuid[2] & (1 << 23)) ? CPUIDCheckState::Set : CPUIDCheckState::Clear;
s_avxCheckState = (cpuid[2] & (1 << 28)) ? CPUIDCheckState::Set : CPUIDCheckState::Clear;
}
{
CPUID cpuid = getCPUID(0x7);
s_bmi1CheckState = (cpuid[2] & (1 << 3)) ? CPUIDCheckState::Set : CPUIDCheckState::Clear;
}
{
CPUID cpuid = getCPUID(0x80000001);
s_lzcntCheckState = (cpuid[2] & (1 << 5)) ? CPUIDCheckState::Set : CPUIDCheckState::Clear;
}
});
}
MacroAssemblerX86Common::CPUIDCheckState MacroAssemblerX86Common::s_sse4_1CheckState = CPUIDCheckState::NotChecked;
MacroAssemblerX86Common::CPUIDCheckState MacroAssemblerX86Common::s_sse4_2CheckState = CPUIDCheckState::NotChecked;
MacroAssemblerX86Common::CPUIDCheckState MacroAssemblerX86Common::s_avxCheckState = CPUIDCheckState::NotChecked;
MacroAssemblerX86Common::CPUIDCheckState MacroAssemblerX86Common::s_lzcntCheckState = CPUIDCheckState::NotChecked;
MacroAssemblerX86Common::CPUIDCheckState MacroAssemblerX86Common::s_bmi1CheckState = CPUIDCheckState::NotChecked;
MacroAssemblerX86Common::CPUIDCheckState MacroAssemblerX86Common::s_popcntCheckState = CPUIDCheckState::NotChecked;
} // namespace JSC
#endif // ENABLE(ASSEMBLER) && (CPU(X86) || CPU(X86_64))
| {
"pile_set_name": "Github"
} |
/**
* Autogenerated by Thrift Compiler (0.9.3)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package org.apache.sentry.api.service.thrift;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.3)")
public class TSentrySyncIDResponse implements org.apache.thrift.TBase<TSentrySyncIDResponse, TSentrySyncIDResponse._Fields>, java.io.Serializable, Cloneable, Comparable<TSentrySyncIDResponse> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("TSentrySyncIDResponse");
private static final org.apache.thrift.protocol.TField STATUS_FIELD_DESC = new org.apache.thrift.protocol.TField("status", org.apache.thrift.protocol.TType.STRUCT, (short)1);
private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.I64, (short)2);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new TSentrySyncIDResponseStandardSchemeFactory());
schemes.put(TupleScheme.class, new TSentrySyncIDResponseTupleSchemeFactory());
}
private org.apache.sentry.service.thrift.TSentryResponseStatus status; // required
private long id; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
STATUS((short)1, "status"),
ID((short)2, "id");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // STATUS
return STATUS;
case 2: // ID
return ID;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __ID_ISSET_ID = 0;
private byte __isset_bitfield = 0;
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.STATUS, new org.apache.thrift.meta_data.FieldMetaData("status", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, org.apache.sentry.service.thrift.TSentryResponseStatus.class)));
tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(TSentrySyncIDResponse.class, metaDataMap);
}
public TSentrySyncIDResponse() {
}
public TSentrySyncIDResponse(
org.apache.sentry.service.thrift.TSentryResponseStatus status,
long id)
{
this();
this.status = status;
this.id = id;
setIdIsSet(true);
}
/**
* Performs a deep copy on <i>other</i>.
*/
public TSentrySyncIDResponse(TSentrySyncIDResponse other) {
__isset_bitfield = other.__isset_bitfield;
if (other.isSetStatus()) {
this.status = new org.apache.sentry.service.thrift.TSentryResponseStatus(other.status);
}
this.id = other.id;
}
public TSentrySyncIDResponse deepCopy() {
return new TSentrySyncIDResponse(this);
}
@Override
public void clear() {
this.status = null;
setIdIsSet(false);
this.id = 0;
}
public org.apache.sentry.service.thrift.TSentryResponseStatus getStatus() {
return this.status;
}
public void setStatus(org.apache.sentry.service.thrift.TSentryResponseStatus status) {
this.status = status;
}
public void unsetStatus() {
this.status = null;
}
/** Returns true if field status is set (has been assigned a value) and false otherwise */
public boolean isSetStatus() {
return this.status != null;
}
public void setStatusIsSet(boolean value) {
if (!value) {
this.status = null;
}
}
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
setIdIsSet(true);
}
public void unsetId() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __ID_ISSET_ID);
}
/** Returns true if field id is set (has been assigned a value) and false otherwise */
public boolean isSetId() {
return EncodingUtils.testBit(__isset_bitfield, __ID_ISSET_ID);
}
public void setIdIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __ID_ISSET_ID, value);
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case STATUS:
if (value == null) {
unsetStatus();
} else {
setStatus((org.apache.sentry.service.thrift.TSentryResponseStatus)value);
}
break;
case ID:
if (value == null) {
unsetId();
} else {
setId((Long)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case STATUS:
return getStatus();
case ID:
return getId();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case STATUS:
return isSetStatus();
case ID:
return isSetId();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof TSentrySyncIDResponse)
return this.equals((TSentrySyncIDResponse)that);
return false;
}
public boolean equals(TSentrySyncIDResponse that) {
if (that == null)
return false;
boolean this_present_status = true && this.isSetStatus();
boolean that_present_status = true && that.isSetStatus();
if (this_present_status || that_present_status) {
if (!(this_present_status && that_present_status))
return false;
if (!this.status.equals(that.status))
return false;
}
boolean this_present_id = true;
boolean that_present_id = true;
if (this_present_id || that_present_id) {
if (!(this_present_id && that_present_id))
return false;
if (this.id != that.id)
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_status = true && (isSetStatus());
list.add(present_status);
if (present_status)
list.add(status);
boolean present_id = true;
list.add(present_id);
if (present_id)
list.add(id);
return list.hashCode();
}
@Override
public int compareTo(TSentrySyncIDResponse other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetStatus()).compareTo(other.isSetStatus());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetStatus()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.status, other.status);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetId()).compareTo(other.isSetId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("TSentrySyncIDResponse(");
boolean first = true;
sb.append("status:");
if (this.status == null) {
sb.append("null");
} else {
sb.append(this.status);
}
first = false;
if (!first) sb.append(", ");
sb.append("id:");
sb.append(this.id);
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
if (!isSetStatus()) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'status' is unset! Struct:" + toString());
}
if (!isSetId()) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'id' is unset! Struct:" + toString());
}
// check for sub-struct validity
if (status != null) {
status.validate();
}
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class TSentrySyncIDResponseStandardSchemeFactory implements SchemeFactory {
public TSentrySyncIDResponseStandardScheme getScheme() {
return new TSentrySyncIDResponseStandardScheme();
}
}
private static class TSentrySyncIDResponseStandardScheme extends StandardScheme<TSentrySyncIDResponse> {
public void read(org.apache.thrift.protocol.TProtocol iprot, TSentrySyncIDResponse struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // STATUS
if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
struct.status = new org.apache.sentry.service.thrift.TSentryResponseStatus();
struct.status.read(iprot);
struct.setStatusIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // ID
if (schemeField.type == org.apache.thrift.protocol.TType.I64) {
struct.id = iprot.readI64();
struct.setIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, TSentrySyncIDResponse struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.status != null) {
oprot.writeFieldBegin(STATUS_FIELD_DESC);
struct.status.write(oprot);
oprot.writeFieldEnd();
}
oprot.writeFieldBegin(ID_FIELD_DESC);
oprot.writeI64(struct.id);
oprot.writeFieldEnd();
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class TSentrySyncIDResponseTupleSchemeFactory implements SchemeFactory {
public TSentrySyncIDResponseTupleScheme getScheme() {
return new TSentrySyncIDResponseTupleScheme();
}
}
private static class TSentrySyncIDResponseTupleScheme extends TupleScheme<TSentrySyncIDResponse> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, TSentrySyncIDResponse struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
struct.status.write(oprot);
oprot.writeI64(struct.id);
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, TSentrySyncIDResponse struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
struct.status = new org.apache.sentry.service.thrift.TSentryResponseStatus();
struct.status.read(iprot);
struct.setStatusIsSet(true);
struct.id = iprot.readI64();
struct.setIdIsSet(true);
}
}
}
| {
"pile_set_name": "Github"
} |
SINGLE=Archivo
LIST=Archivos
EXCEL=Excel
PDF=Pdf
CSV=Csv
IMPORT_FILE=Importar
EXPORT_FILE=Exportar
ATTACH_FILES=Adjuntar Archivo(s)
NOT_ATTACH_FILE_WARNING=Parece que no ha adjuntado ningún archivo
IMPORT_FILE_SUCCESS=Importación exitosa
CHOOSE_SUPPORT_FILE_TYPES_WARNING=El tipo de archivo no es soportado
OPT_MY_DOCUMENTS=Mis Documentos
OPT_FAVICON_FORMAT_DESCRIPTION=Favicon aparece en la barra de direcciones del navegador y favoritos. El ícono debe ser formato png o jpg y debe tener un tamaño de 32x32 pixeles
OPT_SIZE=Tamaño
OPT_SIZE_VALUE=Tamaño: {0}
OPT_DRAG_OR_CLICK_TO_UPLOAD=Adjunte archivos soltándolos aquí o clickeando en esta barra para subirlos
OPT_DELETE_RESOURCES_SUCCESSFULLY=Recursos eliminados correctamente
OPT_EDIT_FOLDER_FILE_NAME=Editar carpeta/nombre de archivo
OPT_UPLOAD_FILE_SUCCESSFULLY=Subida exitosa
OPT_MOVE_ASSETS_SUCCESSFULLY=Movida de recurso(s) exitosa
ACTION_CHANGE_LOGO=Cambiar Logo
ACTION_NEW_FOLDER=Nueva Carpeta
ACTION_MOVE_ASSETS=Mover Recurso
ERROR_FILE_IS_EXISTED=El archivo {0} ya existe.
ERROR_INVALID_SUPPORTED_IMAGE_FORMAT=Formato de imágen no soportado
ERROR_UPLOAD_INVALID_SUPPORTED_IMAGE_FORMAT=El archivo subido no tiene un formato válido de imágen. Los formatos soportados son jpg/png
ERROR_NO_SELECTED_FILE_TO_DOWNLOAD=No se ha seleccionado ningún archivo para descargar
ERROR_INVALID_FILE_NAME=Por favor suba un nombre de archivo válido a excepción de los siguientes caracteres : <>:&/\|?*&
ERROR_SOME_FILES_MOVING_ERROR=La acción de mover recursos ha finalizado, algunos items no se pudieron mover al destino. Por favor verifique que no haya nombre de archivos duplicados e intente nuevamente
| {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.commonsware.android.headerdetail" android:versionCode="1" android:versionName="1.0">
<supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:smallScreens="true"/>
<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="4"/>
<application android:icon="@drawable/ic_launcher">
<activity android:name="HeaderDetailListDemo" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
| {
"pile_set_name": "Github"
} |
#!/bin/sh
command -v getarg >/dev/null || . /lib/dracut-lib.sh
OLDIFS="${IFS}"
NEWLINE="
"
ZPOOL_IMPORT_OPTS=""
if getargbool 0 zfs_force -y zfs.force -y zfsforce ; then
warn "ZFS: Will force-import pools if necessary."
ZPOOL_IMPORT_OPTS="${ZPOOL_IMPORT_OPTS} -f"
fi
# find_bootfs
# returns the first dataset with the bootfs attribute.
find_bootfs() {
IFS="${NEWLINE}"
for dataset in $(zpool list -H -o bootfs); do
case "${dataset}" in
"" | "-")
continue
;;
"no pools available")
IFS="${OLDIFS}"
return 1
;;
*)
IFS="${OLDIFS}"
echo "${dataset}"
return 0
;;
esac
done
IFS="${OLDIFS}"
return 1
}
# import_pool POOL
# imports the given zfs pool if it isn't imported already.
import_pool() {
local pool="${1}"
if ! zpool list -H "${pool}" 2>&1 > /dev/null ; then
info "ZFS: Importing pool ${pool}..."
if ! zpool import -N ${ZPOOL_IMPORT_OPTS} "${pool}" ; then
warn "ZFS: Unable to import pool ${pool}"
return 1
fi
fi
return 0
}
# mount_dataset DATASET
# mounts the given zfs dataset.
mount_dataset() {
local dataset="${1}"
local mountpoint="$(zfs get -H -o value mountpoint "${dataset}")"
# We need zfsutil for non-legacy mounts and not for legacy mounts.
if [ "${mountpoint}" = "legacy" ] ; then
mount -t zfs "${dataset}" "${NEWROOT}"
else
mount -o zfsutil -t zfs "${dataset}" "${NEWROOT}"
fi
return $?
}
# export_all OPTS
# exports all imported zfs pools.
export_all() {
local opts="${1}"
local ret=0
IFS="${NEWLINE}"
for pool in `zpool list -H -o name` ; do
if zpool list -H "${pool}" 2>&1 > /dev/null ; then
zpool export "${pool}" ${opts} || ret=$?
fi
done
IFS="${OLDIFS}"
return ${ret}
}
| {
"pile_set_name": "Github"
} |
const path = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'development',
entry: {
app: ['./app/index.js']
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './dist'),
publicPath: '/'
},
module: {
rules: [{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-env',
'@babel/preset-react',
]
}
}
}, {
test: /\.css$/i,
use: [
'style-loader',
'css-loader',
],
},
{
test: /\.s[ac]ss$/i,
use: [
'style-loader',
'css-loader',
'sass-loader',
],
},
{
test: /\.(png|jpg|jpeg|gif|svg)$/,
use: 'file-loader?limit=8192&name=assets/[name].[ext]?[hash]'
}, {
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
use: 'url-loader?limit=100000'
}]
},
resolve: {
extensions: ['.js', '.scss']
},
plugins: [
new HtmlWebpackPlugin({
template: './app/index.ejs'
}),
new CopyWebpackPlugin([
{ from: './app/favicon.ico' },
{ from: './app/assets', to: 'assets' }
]),
],
devtool: 'inline-source-map'
}
| {
"pile_set_name": "Github"
} |
var WebSocketServer = require('../../').Server
, express = require('express')
, fs = require('fs')
, http = require('http')
, util = require('util')
, path = require('path')
, app = express.createServer()
, events = require('events')
, ansi = require('ansi')
, cursor = ansi(process.stdout);
function BandwidthSampler(ws, interval) {
interval = interval || 2000;
var previousByteCount = 0;
var self = this;
var intervalId = setInterval(function() {
var byteCount = ws.bytesReceived;
var bytesPerSec = (byteCount - previousByteCount) / (interval / 1000);
previousByteCount = byteCount;
self.emit('sample', bytesPerSec);
}, interval);
ws.on('close', function() {
clearInterval(intervalId);
});
}
util.inherits(BandwidthSampler, events.EventEmitter);
function makePathForFile(filePath, prefix, cb) {
if (typeof cb !== 'function') throw new Error('callback is required');
filePath = path.dirname(path.normalize(filePath)).replace(/^(\/|\\)+/, '');
var pieces = filePath.split(/(\\|\/)/);
var incrementalPath = prefix;
function step(error) {
if (error) return cb(error);
if (pieces.length == 0) return cb(null, incrementalPath);
incrementalPath += '/' + pieces.shift();
fs.exists(incrementalPath, function(exists) {
if (!exists) fs.mkdir(incrementalPath, step);
else process.nextTick(step);
});
}
step();
}
cursor.eraseData(2).goto(1, 1);
app.use(express.static(__dirname + '/public'));
var clientId = 0;
var wss = new WebSocketServer({server: app});
wss.on('connection', function(ws) {
var thisId = ++clientId;
cursor.goto(1, 4 + thisId).eraseLine();
console.log('Client #%d connected', thisId);
var sampler = new BandwidthSampler(ws);
sampler.on('sample', function(bps) {
cursor.goto(1, 4 + thisId).eraseLine();
console.log('WebSocket #%d incoming bandwidth: %d MB/s', thisId, Math.round(bps / (1024*1024)));
});
var filesReceived = 0;
var currentFile = null;
ws.on('message', function(data, flags) {
if (!flags.binary) {
currentFile = JSON.parse(data);
// note: a real-world app would want to sanity check the data
}
else {
if (currentFile == null) return;
makePathForFile(currentFile.path, __dirname + '/uploaded', function(error, path) {
if (error) {
console.log(error);
ws.send(JSON.stringify({event: 'error', path: currentFile.path, message: error.message}));
return;
}
fs.writeFile(path + '/' + currentFile.name, data, function(error) {
++filesReceived;
// console.log('received %d bytes long file, %s', data.length, currentFile.path);
ws.send(JSON.stringify({event: 'complete', path: currentFile.path}));
currentFile = null;
});
});
}
});
ws.on('close', function() {
cursor.goto(1, 4 + thisId).eraseLine();
console.log('Client #%d disconnected. %d files received.', thisId, filesReceived);
});
ws.on('error', function(e) {
cursor.goto(1, 4 + thisId).eraseLine();
console.log('Client #%d error: %s', thisId, e.message);
});
});
fs.mkdir(__dirname + '/uploaded', function(error) {
// ignore errors, most likely means directory exists
console.log('Uploaded files will be saved to %s/uploaded.', __dirname);
console.log('Remember to wipe this directory if you upload lots and lots.');
app.listen(8080);
console.log('Listening on http://localhost:8080');
});
| {
"pile_set_name": "Github"
} |
#include "qtestelementattribute.h"
| {
"pile_set_name": "Github"
} |
# 2018 May 19
#
# The author disclaims copyright to this source code. In place of
# a legal notice, here is a blessing:
#
# May you do good and not evil.
# May you find forgiveness for yourself and forgive others.
# May you share freely, never taking more than you give.
#
#***********************************************************************
#
source [file join [file dirname $argv0] pg_common.tcl]
#=========================================================================
start_test window7 "2019 March 01"
ifcapable !windowfunc
execsql_test 1.0 {
DROP TABLE IF EXISTS t3;
CREATE TABLE t3(a INTEGER, b INTEGER);
INSERT INTO t3 VALUES
(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8),
(9, 9), (0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16),
(7, 17), (8, 18), (9, 19), (0, 20), (1, 21), (2, 22), (3, 23), (4, 24),
(5, 25), (6, 26), (7, 27), (8, 28), (9, 29), (0, 30), (1, 31), (2, 32),
(3, 33), (4, 34), (5, 35), (6, 36), (7, 37), (8, 38), (9, 39), (0, 40),
(1, 41), (2, 42), (3, 43), (4, 44), (5, 45), (6, 46), (7, 47), (8, 48),
(9, 49), (0, 50), (1, 51), (2, 52), (3, 53), (4, 54), (5, 55), (6, 56),
(7, 57), (8, 58), (9, 59), (0, 60), (1, 61), (2, 62), (3, 63), (4, 64),
(5, 65), (6, 66), (7, 67), (8, 68), (9, 69), (0, 70), (1, 71), (2, 72),
(3, 73), (4, 74), (5, 75), (6, 76), (7, 77), (8, 78), (9, 79), (0, 80),
(1, 81), (2, 82), (3, 83), (4, 84), (5, 85), (6, 86), (7, 87), (8, 88),
(9, 89), (0, 90), (1, 91), (2, 92), (3, 93), (4, 94), (5, 95), (6, 96),
(7, 97), (8, 98), (9, 99), (0, 100);
}
execsql_test 1.1 {
SELECT a, sum(b) FROM t3 GROUP BY a ORDER BY 1;
}
execsql_test 1.2 {
SELECT a, sum(b) OVER (
ORDER BY a GROUPS BETWEEN CURRENT ROW AND CURRENT ROW
) FROM t3 ORDER BY 1;
}
execsql_test 1.3 {
SELECT a, sum(b) OVER (
ORDER BY a GROUPS BETWEEN 0 PRECEDING AND 0 FOLLOWING
) FROM t3 ORDER BY 1;
}
execsql_test 1.4 {
SELECT a, sum(b) OVER (
ORDER BY a GROUPS BETWEEN 2 PRECEDING AND 2 FOLLOWING
) FROM t3 ORDER BY 1;
}
execsql_test 1.5 {
SELECT a, sum(b) OVER (
ORDER BY a RANGE BETWEEN 0 PRECEDING AND 0 FOLLOWING
) FROM t3 ORDER BY 1;
}
execsql_test 1.6 {
SELECT a, sum(b) OVER (
ORDER BY a RANGE BETWEEN 2 PRECEDING AND 2 FOLLOWING
) FROM t3 ORDER BY 1;
}
execsql_test 1.7 {
SELECT a, sum(b) OVER (
ORDER BY a RANGE BETWEEN 2 PRECEDING AND 1 FOLLOWING
) FROM t3 ORDER BY 1;
}
execsql_test 1.8.1 {
SELECT a, sum(b) OVER (
ORDER BY a RANGE BETWEEN 0 PRECEDING AND 1 FOLLOWING
) FROM t3 ORDER BY 1;
}
execsql_test 1.8.2 {
SELECT a, sum(b) OVER (
ORDER BY a DESC RANGE BETWEEN 0 PRECEDING AND 1 FOLLOWING
) FROM t3 ORDER BY 1;
}
finish_test
| {
"pile_set_name": "Github"
} |
package cms.bean;
import java.io.Serializable;
/**
* 媒体信息
* @author Gao
*
*/
public class MediaInfo implements Serializable{
private static final long serialVersionUID = -4032600666415370715L;
/** 媒体文件URL **/
private String mediaUrl;
/** 封面文件 **/
private String cover;
/** 缩略图文件 **/
private String thumbnail;
public String getMediaUrl() {
return mediaUrl;
}
public void setMediaUrl(String mediaUrl) {
this.mediaUrl = mediaUrl;
}
public String getCover() {
return cover;
}
public void setCover(String cover) {
this.cover = cover;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
}
| {
"pile_set_name": "Github"
} |
<?hh // strict
<<file:__EnableUnstableFeatures(
'pocket_universes',
)>>
class C {
enum E {
case reify type T;
}
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html><html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml"><head xmlns:wcag="https://www.w3.org/WAI/GL/"><title>Using null alt text and no title attribute on img elements for images that AT
should ignore</title><link rel="stylesheet" type="text/css" href="../../css/sources.css" class="remove"></link></head><body xmlns:wcag="https://www.w3.org/WAI/GL/"><h1>Using null alt text and no title attribute on img elements for images that AT
should ignore</h1><section class="meta"><p class="id">ID: H67</p><p class="technology">Technology: html</p><p class="type">Type: Technique</p></section><section class="applicability"><h2>When to Use</h2>
<p>HTML and XHTML documents that load images. </p>
</section><section class="description"><h2>Description</h2>
<p> The purpose of this technique is to show how images can be marked so that they can be
ignored by Assistive Technology. </p>
<p> If no title attribute is used, and the alt text is set to null (i.e.
alt="") it indicates to assistive technology that the image can be safely
ignored. </p>
<div class="note">
<p>Have a "null" alt attribute is not the same as having no alt attribute. </p>
</div>
</section><section class="examples"><h2>Examples</h2>
<section class="example">
<section class="description"><h2>Description</h2>
<p>The following image is used to insert a decorative image on a Web page.</p>
</section>
<pre xml:space="preserve">
<img src="squiggle.gif" width="20" height="20" alt="" />
</pre>
</section>
</section><section class="tests"><h2>Tests</h2>
<section class="procedure"><h3>Procedure</h3>
<p> For each image that should be ignored:</p>
<ol>
<li> Check that title attribute is either absent or empty. </li>
<li> Check that alt attribute is present and empty.</li>
</ol>
</section>
<section class="results"><h3>Expected Results</h3>
<ul>
<li> #1 and #2 are true </li>
</ul>
</section>
</section><section class="related"><h2>Related Techniques</h2></section><section class="resources"><h2>Resources</h2></section></body></html> | {
"pile_set_name": "Github"
} |
<?php
/**
* This is the model class for table "vehicle_details".
*
* The followings are the available columns in table 'vehicle_details':
* @property integer $id
* @property string $vehicle_no
* @property string $vehicle_code
* @property string $no_of_seats
* @property string $maximum_capacity
* @property string $vehicle_type
* @property string $address
* @property string $city
* @property string $state
* @property string $phone
* @property string $insurance
* @property string $tax_remitted
* @property string $permit
*/
class VehicleDetails extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @return VehicleDetails the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'vehicle_details';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('vehicle_no, vehicle_code, no_of_seats, maximum_capacity, insurance', 'required'),
array('no_of_seats, maximum_capacity', 'numerical', 'integerOnly'=>true),
array('maximum_capacity','check'),
array('maximum_capacity','checkinteger'),
array('no_of_seats','checkint'),
array('vehicle_no, vehicle_code, no_of_seats, maximum_capacity, vehicle_type, address, city, state, phone, insurance, tax_remitted, permit,status', 'length', 'max'=>120),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, vehicle_no, vehicle_code, no_of_seats, maximum_capacity, vehicle_type, address, city, state, phone, insurance, tax_remitted, permit, status', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'vehicle_no' => Yii::t('app','Vehicle No'),
'vehicle_code' => Yii::t('app','Vehicle Code'),
'no_of_seats' => Yii::t('app','No Of Seats'),
'maximum_capacity' => Yii::t('app','Maximum Capacity'),
'vehicle_type' => Yii::t('app','Vehicle Type'),
'address' => Yii::t('app','Address'),
'city' => Yii::t('app','City'),
'state' => Yii::t('app','State'),
'phone' => Yii::t('app','Phone'),
'insurance' => Yii::t('app','Insurance'),
'tax_remitted' => Yii::t('app','Tax Remitted'),
'permit' => Yii::t('app','Permit'),
'status' => Yii::t('app','Status'),
);
}
public function check($attribute,$params)
{
if ($this->$attribute > $this->no_of_seats)
$this->addError($attribute, 'vehicle capacity is due to no of seat');
}
public function checkinteger($attribute,$params)
{
if ($this->$attribute < 1)
$this->addError($attribute, 'Maximum Capacity must be an integer');
}
public function checkint($attribute,$params)
{
if ($this->$attribute < 1)
$this->addError($attribute, 'No of Seats must be an integer');
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('vehicle_no',$this->vehicle_no,true);
$criteria->compare('vehicle_code',$this->vehicle_code,true);
$criteria->compare('no_of_seats',$this->no_of_seats,true);
$criteria->compare('maximum_capacity',$this->maximum_capacity,true);
$criteria->compare('vehicle_type',$this->vehicle_type,true);
$criteria->compare('address',$this->address,true);
$criteria->compare('city',$this->city,true);
$criteria->compare('state',$this->state,true);
$criteria->compare('phone',$this->phone,true);
$criteria->compare('insurance',$this->insurance,true);
$criteria->compare('tax_remitted',$this->tax_remitted,true);
$criteria->compare('permit',$this->permit,true);
$criteria->compare('status',$this->status,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
} | {
"pile_set_name": "Github"
} |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import random
import math
import json
import threading
import numpy as np
import tensorflow as tf
import util
import coref_ops
import conll
import metrics
import optimization
from bert import tokenization
from bert import modeling
from pytorch_to_tf import load_from_pytorch_checkpoint
class CorefModel(object):
def __init__(self, config):
self.config = config
self.subtoken_maps = {}
self.max_segment_len = config['max_segment_len']
self.max_span_width = config["max_span_width"]
self.genres = { g:i for i,g in enumerate(config["genres"]) }
self.eval_data = None # Load eval data lazily.
self.bert_config = modeling.BertConfig.from_json_file(config["bert_config_file"])
self.sep = 102
self.cls = 101
self.tokenizer = tokenization.FullTokenizer(
vocab_file=config['vocab_file'], do_lower_case=False)
input_props = []
input_props.append((tf.int32, [None, None])) # input_ids.
input_props.append((tf.int32, [None, None])) # input_mask
input_props.append((tf.int32, [None, None])) # input_ids.
input_props.append((tf.int32, [None, None])) # input_mask
input_props.append((tf.int32, [None])) # Text lengths.
input_props.append((tf.int32, [None, None])) # Speaker IDs.
input_props.append((tf.int32, [])) # Genre.
input_props.append((tf.bool, [])) # Is training.
input_props.append((tf.int32, [None])) # Gold starts.
input_props.append((tf.int32, [None])) # Gold ends.
input_props.append((tf.int32, [None])) # Cluster ids.
input_props.append((tf.int32, [None])) # Sentence Map
self.queue_input_tensors = [tf.placeholder(dtype, shape) for dtype, shape in input_props]
dtypes, shapes = zip(*input_props)
queue = tf.PaddingFIFOQueue(capacity=10, dtypes=dtypes, shapes=shapes)
self.enqueue_op = queue.enqueue(self.queue_input_tensors)
self.input_tensors = queue.dequeue()
self.predictions, self.loss = self.get_predictions_and_loss(*self.input_tensors)
# bert stuff
tvars = tf.trainable_variables()
assignment_map, initialized_variable_names = modeling.get_assignment_map_from_checkpoint(tvars, config['tf_checkpoint'])
init_from_checkpoint = tf.train.init_from_checkpoint if config['init_checkpoint'].endswith('ckpt') else load_from_pytorch_checkpoint
init_from_checkpoint(config['init_checkpoint'], assignment_map)
print("**** Trainable Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
# tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
# init_string)
print(" name = %s, shape = %s%s" % (var.name, var.shape, init_string))
num_train_steps = int(
self.config['num_docs'] * self.config['num_epochs'])
num_warmup_steps = int(num_train_steps * 0.1)
self.global_step = tf.train.get_or_create_global_step()
self.train_op = optimization.create_custom_optimizer(tvars,
self.loss, self.config['bert_learning_rate'], self.config['task_learning_rate'],
num_train_steps, num_warmup_steps, False, self.global_step, freeze=-1)
def start_enqueue_thread(self, session):
with open(self.config["train_path"]) as f:
train_examples = [json.loads(jsonline) for jsonline in f.readlines()]
def _enqueue_loop():
while True:
random.shuffle(train_examples)
if self.config['single_example']:
for example in train_examples:
tensorized_example = self.tensorize_example(example, is_training=True)
feed_dict = dict(zip(self.queue_input_tensors, tensorized_example))
session.run(self.enqueue_op, feed_dict=feed_dict)
else:
examples = []
for example in train_examples:
tensorized = self.tensorize_example(example, is_training=True)
if type(tensorized) is not list:
tensorized = [tensorized]
examples += tensorized
random.shuffle(examples)
print('num examples', len(examples))
for example in examples:
feed_dict = dict(zip(self.queue_input_tensors, example))
session.run(self.enqueue_op, feed_dict=feed_dict)
enqueue_thread = threading.Thread(target=_enqueue_loop)
enqueue_thread.daemon = True
enqueue_thread.start()
def restore(self, session):
# Don't try to restore unused variables from the TF-Hub ELMo module.
vars_to_restore = [v for v in tf.global_variables() ]
saver = tf.train.Saver(vars_to_restore)
checkpoint_path = os.path.join(self.config["log_dir"], "model.max.ckpt")
print("Restoring from {}".format(checkpoint_path))
session.run(tf.global_variables_initializer())
saver.restore(session, checkpoint_path)
def tensorize_mentions(self, mentions):
if len(mentions) > 0:
starts, ends = zip(*mentions)
else:
starts, ends = [], []
return np.array(starts), np.array(ends)
def tensorize_span_labels(self, tuples, label_dict):
if len(tuples) > 0:
starts, ends, labels = zip(*tuples)
else:
starts, ends, labels = [], [], []
return np.array(starts), np.array(ends), np.array([label_dict[c] for c in labels])
def get_speaker_dict(self, speakers):
speaker_dict = {'UNK': 0, '[SPL]': 1}
for s in speakers:
if s not in speaker_dict and len(speaker_dict) < self.config['max_num_speakers']:
speaker_dict[s] = len(speaker_dict)
return speaker_dict
def tensorize_example(self, example, is_training):
clusters = example["clusters"]
gold_mentions = sorted(tuple(m) for m in util.flatten(clusters))
gold_mention_map = {m:i for i,m in enumerate(gold_mentions)}
cluster_ids = np.zeros(len(gold_mentions))
for cluster_id, cluster in enumerate(clusters):
for mention in cluster:
cluster_ids[gold_mention_map[tuple(mention)]] = cluster_id + 1
sentences = example["sentences"]
num_words = sum(len(s) for s in sentences)
speakers = example["speakers"]
# assert num_words == len(speakers), (num_words, len(speakers))
speaker_dict = self.get_speaker_dict(util.flatten(speakers))
sentence_map = example['sentence_map']
max_sentence_length = self.max_segment_len #270 #max(len(s) for s in sentences)
text_len = np.array([len(s) for s in sentences])
input_ids, input_mask, speaker_ids, prev_overlap = [], [], [], []
overlap_ids, overlap_mask = [], []
half = self.max_segment_len // 2
prev_tokens_per_seg = []
for i, (sentence, speaker) in enumerate(zip(sentences, speakers)):
prev_tokens_per_seg += [len(prev_overlap)]
overlap_words = ['[CLS]'] + prev_overlap + sentence[:half] + ['[SEP]']
prev_overlap = sentence[half:]
sentence = ['[CLS]'] + sentence + ['[SEP]']
sent_input_ids = self.tokenizer.convert_tokens_to_ids(sentence)
sent_input_mask = [1] * len(sent_input_ids)
sent_speaker_ids = [speaker_dict.get(s, 0) for s in ['##'] + speaker + ['##']]
while len(sent_input_ids) < max_sentence_length:
sent_input_ids.append(0)
sent_input_mask.append(0)
sent_speaker_ids.append(0)
overlap_input_ids = self.tokenizer.convert_tokens_to_ids(overlap_words)
overlap_input_mask = [1] * len(overlap_input_ids)
while len(overlap_input_ids) < max_sentence_length:
overlap_input_ids.append(0)
overlap_input_mask.append(0)
input_ids.append(sent_input_ids)
speaker_ids.append(sent_speaker_ids)
input_mask.append(sent_input_mask)
overlap_ids.append(overlap_input_ids)
overlap_mask.append(overlap_input_mask)
overlap_words = ['[CLS]'] + prev_overlap + ['[SEP]']
overlap_input_ids = self.tokenizer.convert_tokens_to_ids(overlap_words)
overlap_input_mask = [1] * len(overlap_input_ids)
prev_tokens_per_seg += [len(prev_overlap)]
while len(overlap_input_ids) < max_sentence_length:
overlap_input_ids.append(0)
overlap_input_mask.append(0)
overlap_ids.append(overlap_input_ids)
overlap_mask.append(overlap_input_mask)
input_ids = np.array(input_ids)
input_mask = np.array(input_mask)
speaker_ids = np.array(speaker_ids)
overlap_ids = np.array(overlap_ids)
overlap_mask = np.array(overlap_mask)
assert num_words == (np.sum(input_mask) - 2*np.shape(input_mask)[0]), (num_words, np.sum(input_mask))
assert num_words == (np.sum(overlap_mask) - 2*np.shape(overlap_mask)[0]), (num_words, np.sum(overlap_mask), np.shape(overlap_mask))
doc_key = example["doc_key"]
self.subtoken_maps[doc_key] = example["subtoken_map"]
genre = self.genres[doc_key[:2]]
gold_starts, gold_ends = self.tensorize_mentions(gold_mentions)
example_tensors = (input_ids, input_mask, overlap_ids, overlap_mask, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids, sentence_map)
if is_training and len(sentences) > self.config["max_training_sentences"]:
return self.truncate_example(* (example_tensors + (prev_tokens_per_seg, )))
else:
return example_tensors
def truncate_example(self, input_ids, input_mask, overlap_ids, overlap_mask, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids, sentence_map, prev_tokens_per_seg, sentence_offset=None):
max_training_sentences = self.config["max_training_sentences"]
num_sentences = input_ids.shape[0]
assert num_sentences > max_training_sentences
sentence_offset = random.randint(0, num_sentences - max_training_sentences) if sentence_offset is None else sentence_offset
word_offset = text_len[:sentence_offset].sum()
num_words = text_len[sentence_offset:sentence_offset + max_training_sentences].sum()
input_ids = input_ids[sentence_offset:sentence_offset + max_training_sentences, :]
input_mask = input_mask[sentence_offset:sentence_offset + max_training_sentences, :]
overlap_ids = overlap_ids[sentence_offset:sentence_offset + max_training_sentences + 1, :]
overlap_mask = overlap_mask[sentence_offset:sentence_offset + max_training_sentences + 1, :]
overlap_ids[-1, 1 + prev_tokens_per_seg[sentence_offset + max_training_sentences]] = self.sep
overlap_ids[-1, 2 + prev_tokens_per_seg[sentence_offset + max_training_sentences]:] = 0
overlap_mask[-1, 2 + prev_tokens_per_seg[sentence_offset + max_training_sentences]:] = 0
overlap_mask[0, 1: 1 + prev_tokens_per_seg[sentence_offset ]] = 0
assert num_words == overlap_mask.sum() - 2 * np.shape(overlap_ids)[0], (num_words, overlap_mask.sum(), text_len)
speaker_ids = speaker_ids[sentence_offset:sentence_offset + max_training_sentences, :]
text_len = text_len[sentence_offset:sentence_offset + max_training_sentences]
sentence_map = sentence_map[word_offset: word_offset + num_words]
gold_spans = np.logical_and(gold_ends >= word_offset, gold_starts < word_offset + num_words)
gold_starts = gold_starts[gold_spans] - word_offset
gold_ends = gold_ends[gold_spans] - word_offset
cluster_ids = cluster_ids[gold_spans]
return input_ids, input_mask, overlap_ids, overlap_mask, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids, sentence_map
def get_candidate_labels(self, candidate_starts, candidate_ends, labeled_starts, labeled_ends, labels):
same_start = tf.equal(tf.expand_dims(labeled_starts, 1), tf.expand_dims(candidate_starts, 0)) # [num_labeled, num_candidates]
same_end = tf.equal(tf.expand_dims(labeled_ends, 1), tf.expand_dims(candidate_ends, 0)) # [num_labeled, num_candidates]
same_span = tf.logical_and(same_start, same_end) # [num_labeled, num_candidates]
candidate_labels = tf.matmul(tf.expand_dims(labels, 0), tf.to_int32(same_span)) # [1, num_candidates]
candidate_labels = tf.squeeze(candidate_labels, 0) # [num_candidates]
return candidate_labels
def get_dropout(self, dropout_rate, is_training):
return 1 - (tf.to_float(is_training) * dropout_rate)
def coarse_to_fine_pruning(self, top_span_emb, top_span_mention_scores, c):
k = util.shape(top_span_emb, 0)
top_span_range = tf.range(k) # [k]
antecedent_offsets = tf.expand_dims(top_span_range, 1) - tf.expand_dims(top_span_range, 0) # [k, k]
antecedents_mask = antecedent_offsets >= 1 # [k, k]
fast_antecedent_scores = tf.expand_dims(top_span_mention_scores, 1) + tf.expand_dims(top_span_mention_scores, 0) # [k, k]
fast_antecedent_scores += tf.log(tf.to_float(antecedents_mask)) # [k, k]
fast_antecedent_scores += self.get_fast_antecedent_scores(top_span_emb) # [k, k]
if self.config['use_prior']:
antecedent_distance_buckets = self.bucket_distance(antecedent_offsets) # [k, c]
distance_scores = util.projection(tf.nn.dropout(tf.get_variable("antecedent_distance_emb", [10, self.config["feature_size"]]), self.dropout), 1, initializer=tf.truncated_normal_initializer(stddev=0.02)) #[10, 1]
antecedent_distance_scores = tf.gather(tf.squeeze(distance_scores, 1), antecedent_distance_buckets) # [k, c]
fast_antecedent_scores += antecedent_distance_scores
_, top_antecedents = tf.nn.top_k(fast_antecedent_scores, c, sorted=False) # [k, c]
top_antecedents_mask = util.batch_gather(antecedents_mask, top_antecedents) # [k, c]
top_fast_antecedent_scores = util.batch_gather(fast_antecedent_scores, top_antecedents) # [k, c]
top_antecedent_offsets = util.batch_gather(antecedent_offsets, top_antecedents) # [k, c]
return top_antecedents, top_antecedents_mask, top_fast_antecedent_scores, top_antecedent_offsets
def combine_passes(self, original_doc, input_ids, input_mask, overlap_doc, overlap_ids, overlap_mask):
overlap_mask, input_mask = tf.equal(overlap_mask, 1), tf.equal(input_mask, 1)
org_content_mask = tf.logical_and(input_mask, tf.logical_and(tf.not_equal(input_ids, self.cls), tf.not_equal(input_ids, self.sep)))
overlap_content_mask = tf.logical_and(overlap_mask, tf.logical_and(tf.not_equal(overlap_ids, self.cls), tf.not_equal(overlap_ids, self.sep)))
flat_org_doc = self.flatten_emb_by_sentence(original_doc, org_content_mask)
flat_overlap_doc = self.flatten_emb_by_sentence(overlap_doc, overlap_content_mask)
with tf.variable_scope("combo"):
f = tf.sigmoid(util.projection(tf.concat([flat_org_doc, flat_overlap_doc], -1), util.shape(flat_org_doc, -1))) # [n, emb]
combo = f * flat_org_doc + (1 - f) * flat_overlap_doc
return combo, org_content_mask
def get_predictions_and_loss(self, input_ids, input_mask, overlap_ids, overlap_mask, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids, sentence_map):
model = modeling.BertModel(
config=self.bert_config,
is_training=is_training,
input_ids=input_ids,
input_mask=input_mask,
use_one_hot_embeddings=False,
scope='bert')
original_doc = model.get_sequence_output()
model = modeling.BertModel(
config=self.bert_config,
is_training=is_training,
input_ids=overlap_ids,
input_mask=overlap_mask,
use_one_hot_embeddings=False,
scope='bert')
overlap_doc = model.get_sequence_output()
self.dropout = self.get_dropout(self.config["dropout_rate"], is_training)
num_sentences = tf.shape(input_ids)[0]
max_sentence_length = tf.shape(input_mask)[1] - 2
mention_doc, org_content_mask = self.combine_passes(original_doc, input_ids, input_mask, overlap_doc, overlap_ids, overlap_mask)
num_words = util.shape(mention_doc, 0)
antecedent_doc = mention_doc
# mask out cross-sentence candidates
flattened_sentence_indices = sentence_map
candidate_starts = tf.tile(tf.expand_dims(tf.range(num_words), 1), [1, self.max_span_width]) # [num_words, max_span_width]
candidate_ends = candidate_starts + tf.expand_dims(tf.range(self.max_span_width), 0) # [num_words, max_span_width]
candidate_start_sentence_indices = tf.gather(flattened_sentence_indices, candidate_starts) # [num_words, max_span_width]
candidate_end_sentence_indices = tf.gather(flattened_sentence_indices, tf.minimum(candidate_ends, num_words - 1)) # [num_words, max_span_width]
candidate_mask = tf.logical_and(candidate_ends < num_words, tf.equal(candidate_start_sentence_indices, candidate_end_sentence_indices)) # [num_words, max_span_width]
flattened_candidate_mask = tf.reshape(candidate_mask, [-1]) # [num_words * max_span_width]
candidate_starts = tf.boolean_mask(tf.reshape(candidate_starts, [-1]), flattened_candidate_mask) # [num_candidates]
candidate_ends = tf.boolean_mask(tf.reshape(candidate_ends, [-1]), flattened_candidate_mask) # [num_candidates]
candidate_sentence_indices = tf.boolean_mask(tf.reshape(candidate_start_sentence_indices, [-1]), flattened_candidate_mask) # [num_candidates]
candidate_cluster_ids = self.get_candidate_labels(candidate_starts, candidate_ends, gold_starts, gold_ends, cluster_ids) # [num_candidates]
candidate_span_emb = self.get_span_emb(mention_doc, mention_doc, candidate_starts, candidate_ends) # [num_candidates, emb]
candidate_mention_scores = self.get_mention_scores(candidate_span_emb, candidate_starts, candidate_ends)
candidate_mention_scores = tf.squeeze(candidate_mention_scores, 1) # [k]
# beam size
k = tf.minimum(3900, tf.to_int32(tf.floor(tf.to_float(num_words) * self.config["top_span_ratio"])))
c = tf.minimum(self.config["max_top_antecedents"], k)
# pull from beam
top_span_indices = coref_ops.extract_spans(tf.expand_dims(candidate_mention_scores, 0),
tf.expand_dims(candidate_starts, 0),
tf.expand_dims(candidate_ends, 0),
tf.expand_dims(k, 0),
num_words,
True) # [1, k]
top_span_indices.set_shape([1, None])
top_span_indices = tf.squeeze(top_span_indices, 0) # [k]
top_span_starts = tf.gather(candidate_starts, top_span_indices) # [k]
top_span_ends = tf.gather(candidate_ends, top_span_indices) # [k]
# don't need this
top_span_emb = tf.gather(candidate_span_emb, top_span_indices) # [k, emb]
top_span_cluster_ids = tf.gather(candidate_cluster_ids, top_span_indices) # [k]
top_span_mention_scores = tf.gather(candidate_mention_scores, top_span_indices) # [k]
genre_emb = tf.gather(tf.get_variable("genre_embeddings", [len(self.genres), self.config["feature_size"]]), genre) # [emb]
if self.config['use_metadata']:
speaker_ids = self.flatten_emb_by_sentence(speaker_ids, org_content_mask)
top_span_speaker_ids = tf.gather(speaker_ids, top_span_starts) # [k]i
else:
top_span_speaker_ids = None
# antecedent scores -- change this
dummy_scores = tf.zeros([k, 1]) # [k, 1]
top_antecedents, top_antecedents_mask, top_fast_antecedent_scores, top_antecedent_offsets = self.coarse_to_fine_pruning(top_span_emb, top_span_mention_scores, c)
num_segs, seg_len = util.shape(org_content_mask, 0), util.shape(org_content_mask, 1)
word_segments = tf.reshape(tf.tile(tf.expand_dims(tf.range(0, num_segs), 1), [1, seg_len]), [-1])
flat_word_segments = tf.boolean_mask(word_segments, tf.reshape(org_content_mask, [-1]))
mention_segments = tf.expand_dims(tf.gather(flat_word_segments, top_span_starts), 1) # [k, 1]
antecedent_segments = tf.gather(flat_word_segments, tf.gather(top_span_starts, top_antecedents)) #[k, c]
segment_distance = tf.clip_by_value(mention_segments - antecedent_segments, 0, self.config['max_training_sentences'] - 1) if self.config['use_segment_distance'] else None #[k, c]
if self.config['fine_grained']:
for i in range(self.config["coref_depth"]):
with tf.variable_scope("coref_layer", reuse=(i > 0)):
top_antecedent_emb = tf.gather(top_span_emb, top_antecedents) # [k, c, emb]
top_antecedent_scores = top_fast_antecedent_scores + self.get_slow_antecedent_scores(top_span_emb, top_antecedents, top_antecedent_emb, top_antecedent_offsets, top_span_speaker_ids, genre_emb, segment_distance) # [k, c]
top_antecedent_weights = tf.nn.softmax(tf.concat([dummy_scores, top_antecedent_scores], 1)) # [k, c + 1]
top_antecedent_emb = tf.concat([tf.expand_dims(top_span_emb, 1), top_antecedent_emb], 1) # [k, c + 1, emb]
attended_span_emb = tf.reduce_sum(tf.expand_dims(top_antecedent_weights, 2) * top_antecedent_emb, 1) # [k, emb]
with tf.variable_scope("f"):
f = tf.sigmoid(util.projection(tf.concat([top_span_emb, attended_span_emb], 1), util.shape(top_span_emb, -1))) # [k, emb]
top_span_emb = f * attended_span_emb + (1 - f) * top_span_emb # [k, emb]
else:
top_antecedent_scores = top_fast_antecedent_scores
top_antecedent_scores = tf.concat([dummy_scores, top_antecedent_scores], 1) # [k, c + 1]
# top_antecedent_scores = tf.Print(top_antecedent_scores, [tf.shape(context_outputs), tf.shape(candidate_ends), top_antecedent_scores, tf.shape(top_antecedent_scores)], 'top_antecedent_scores')
top_antecedent_cluster_ids = tf.gather(top_span_cluster_ids, top_antecedents) # [k, c]
# top_antecedents_mask = tf.Print(top_antecedents_mask, [top_antecedents_mask, tf.reduce_sum(tf.to_int32(top_antecedents_mask))], 'top ante amsk')
top_antecedent_cluster_ids += tf.to_int32(tf.log(tf.to_float(top_antecedents_mask))) # [k, c]
same_cluster_indicator = tf.equal(top_antecedent_cluster_ids, tf.expand_dims(top_span_cluster_ids, 1)) # [k, c]
non_dummy_indicator = tf.expand_dims(top_span_cluster_ids > 0, 1) # [k, 1]
pairwise_labels = tf.logical_and(same_cluster_indicator, non_dummy_indicator) # [k, c]
dummy_labels = tf.logical_not(tf.reduce_any(pairwise_labels, 1, keepdims=True)) # [k, 1]
top_antecedent_labels = tf.concat([dummy_labels, pairwise_labels], 1) # [k, c + 1]
loss = self.softmax_loss(top_antecedent_scores, top_antecedent_labels) # [k]
loss = tf.reduce_sum(loss) # []
return [candidate_starts, candidate_ends, candidate_mention_scores, top_span_starts, top_span_ends, top_antecedents, top_antecedent_scores], loss
def get_span_emb(self, head_emb, context_outputs, span_starts, span_ends):
span_emb_list = []
span_start_emb = tf.gather(context_outputs, span_starts) # [k, emb]
span_emb_list.append(span_start_emb)
span_end_emb = tf.gather(context_outputs, span_ends) # [k, emb]
span_emb_list.append(span_end_emb)
span_width = 1 + span_ends - span_starts # [k]
if self.config["use_features"]:
span_width_index = span_width - 1 # [k]
span_width_emb = tf.gather(tf.get_variable("span_width_embeddings", [self.config["max_span_width"], self.config["feature_size"]]), span_width_index) # [k, emb]
span_width_emb = tf.nn.dropout(span_width_emb, self.dropout)
span_emb_list.append(span_width_emb)
if self.config["model_heads"]:
mention_word_scores = self.get_masked_mention_word_scores(context_outputs, span_starts, span_ends)
head_attn_reps = tf.matmul(mention_word_scores, context_outputs) # [K, T]
span_emb_list.append(head_attn_reps)
span_emb = tf.concat(span_emb_list, 1) # [k, emb]
return span_emb # [k, emb]
def get_mention_scores(self, span_emb, span_starts, span_ends):
with tf.variable_scope("mention_scores"):
span_scores = util.ffnn(span_emb, self.config["ffnn_depth"], self.config["ffnn_size"], 1, self.dropout) # [k, 1]
if self.config['use_prior']:
span_width_emb = tf.get_variable("span_width_prior_embeddings", [self.config["max_span_width"], self.config["feature_size"]]) # [W, emb]
span_width_index = span_ends - span_starts # [NC]
with tf.variable_scope("width_scores"):
width_scores = util.ffnn(span_width_emb, self.config["ffnn_depth"], self.config["ffnn_size"], 1, self.dropout) # [W, 1]
width_scores = tf.gather(width_scores, span_width_index)
span_scores += width_scores
return span_scores
def get_width_scores(self, doc, starts, ends):
distance = ends - starts
span_start_emb = tf.gather(doc, starts)
hidden = util.shape(doc, 1)
with tf.variable_scope('span_width'):
span_width_emb = tf.gather(tf.get_variable("start_width_embeddings", [self.config["max_span_width"], hidden], initializer=tf.truncated_normal_initializer(stddev=0.02)), distance) # [W, emb]
scores = tf.reduce_sum(span_start_emb * span_width_emb, axis=1)
return scores
def get_masked_mention_word_scores(self, encoded_doc, span_starts, span_ends):
num_words = util.shape(encoded_doc, 0) # T
num_c = util.shape(span_starts, 0) # NC
doc_range = tf.tile(tf.expand_dims(tf.range(0, num_words), 0), [num_c, 1]) # [K, T]
mention_mask = tf.logical_and(doc_range >= tf.expand_dims(span_starts, 1), doc_range <= tf.expand_dims(span_ends, 1)) #[K, T]
with tf.variable_scope("mention_word_attn"):
word_attn = tf.squeeze(util.projection(encoded_doc, 1, initializer=tf.truncated_normal_initializer(stddev=0.02)), 1)
mention_word_attn = tf.nn.softmax(tf.log(tf.to_float(mention_mask)) + tf.expand_dims(word_attn, 0))
return mention_word_attn
def softmax_loss(self, antecedent_scores, antecedent_labels):
gold_scores = antecedent_scores + tf.log(tf.to_float(antecedent_labels)) # [k, max_ant + 1]
marginalized_gold_scores = tf.reduce_logsumexp(gold_scores, [1]) # [k]
log_norm = tf.reduce_logsumexp(antecedent_scores, [1]) # [k]
return log_norm - marginalized_gold_scores # [k]
def bucket_distance(self, distances):
"""
Places the given values (designed for distances) into 10 semi-logscale buckets:
[0, 1, 2, 3, 4, 5-7, 8-15, 16-31, 32-63, 64+].
"""
logspace_idx = tf.to_int32(tf.floor(tf.log(tf.to_float(distances))/math.log(2))) + 3
use_identity = tf.to_int32(distances <= 4)
combined_idx = use_identity * distances + (1 - use_identity) * logspace_idx
return tf.clip_by_value(combined_idx, 0, 9)
def get_slow_antecedent_scores(self, top_span_emb, top_antecedents, top_antecedent_emb, top_antecedent_offsets, top_span_speaker_ids, genre_emb, segment_distance=None):
k = util.shape(top_span_emb, 0)
c = util.shape(top_antecedents, 1)
feature_emb_list = []
if self.config["use_metadata"]:
top_antecedent_speaker_ids = tf.gather(top_span_speaker_ids, top_antecedents) # [k, c]
same_speaker = tf.equal(tf.expand_dims(top_span_speaker_ids, 1), top_antecedent_speaker_ids) # [k, c]
speaker_pair_emb = tf.gather(tf.get_variable("same_speaker_emb", [2, self.config["feature_size"]]), tf.to_int32(same_speaker)) # [k, c, emb]
feature_emb_list.append(speaker_pair_emb)
tiled_genre_emb = tf.tile(tf.expand_dims(tf.expand_dims(genre_emb, 0), 0), [k, c, 1]) # [k, c, emb]
feature_emb_list.append(tiled_genre_emb)
if self.config["use_features"]:
antecedent_distance_buckets = self.bucket_distance(top_antecedent_offsets) # [k, c]
antecedent_distance_emb = tf.gather(tf.get_variable("antecedent_distance_emb", [10, self.config["feature_size"]]), antecedent_distance_buckets) # [k, c]
feature_emb_list.append(antecedent_distance_emb)
if segment_distance is not None:
with tf.variable_scope('segment_distance', reuse=tf.AUTO_REUSE):
segment_distance_emb = tf.gather(tf.get_variable("segment_distance_embeddings", [self.config['max_training_sentences'], self.config["feature_size"]]), segment_distance) # [k, emb]
span_width_emb = tf.nn.dropout(segment_distance_emb, self.dropout)
feature_emb_list.append(segment_distance_emb)
feature_emb = tf.concat(feature_emb_list, 2) # [k, c, emb]
feature_emb = tf.nn.dropout(feature_emb, self.dropout) # [k, c, emb]
target_emb = tf.expand_dims(top_span_emb, 1) # [k, 1, emb]
similarity_emb = top_antecedent_emb * target_emb # [k, c, emb]
target_emb = tf.tile(target_emb, [1, c, 1]) # [k, c, emb]
pair_emb = tf.concat([target_emb, top_antecedent_emb, similarity_emb, feature_emb], 2) # [k, c, emb]
with tf.variable_scope("slow_antecedent_scores"):
slow_antecedent_scores = util.ffnn(pair_emb, self.config["ffnn_depth"], self.config["ffnn_size"], 1, self.dropout) # [k, c, 1]
slow_antecedent_scores = tf.squeeze(slow_antecedent_scores, 2) # [k, c]
return slow_antecedent_scores # [k, c]
def get_fast_antecedent_scores(self, top_span_emb):
with tf.variable_scope("src_projection"):
source_top_span_emb = tf.nn.dropout(util.projection(top_span_emb, util.shape(top_span_emb, -1)), self.dropout) # [k, emb]
target_top_span_emb = tf.nn.dropout(top_span_emb, self.dropout) # [k, emb]
return tf.matmul(source_top_span_emb, target_top_span_emb, transpose_b=True) # [k, k]
def flatten_emb_by_sentence(self, emb, text_len_mask):
num_sentences = tf.shape(emb)[0]
max_sentence_length = tf.shape(emb)[1]
emb_rank = len(emb.get_shape())
if emb_rank == 2:
flattened_emb = tf.reshape(emb, [num_sentences * max_sentence_length])
elif emb_rank == 3:
flattened_emb = tf.reshape(emb, [num_sentences * max_sentence_length, util.shape(emb, 2)])
else:
raise ValueError("Unsupported rank: {}".format(emb_rank))
return tf.boolean_mask(flattened_emb, tf.reshape(text_len_mask, [num_sentences * max_sentence_length]))
def get_predicted_antecedents(self, antecedents, antecedent_scores):
predicted_antecedents = []
for i, index in enumerate(np.argmax(antecedent_scores, axis=1) - 1):
if index < 0:
predicted_antecedents.append(-1)
else:
predicted_antecedents.append(antecedents[i, index])
return predicted_antecedents
def get_predicted_clusters(self, top_span_starts, top_span_ends, predicted_antecedents):
mention_to_predicted = {}
predicted_clusters = []
for i, predicted_index in enumerate(predicted_antecedents):
if predicted_index < 0:
continue
assert i > predicted_index, (i, predicted_index)
predicted_antecedent = (int(top_span_starts[predicted_index]), int(top_span_ends[predicted_index]))
if predicted_antecedent in mention_to_predicted:
predicted_cluster = mention_to_predicted[predicted_antecedent]
else:
predicted_cluster = len(predicted_clusters)
predicted_clusters.append([predicted_antecedent])
mention_to_predicted[predicted_antecedent] = predicted_cluster
mention = (int(top_span_starts[i]), int(top_span_ends[i]))
predicted_clusters[predicted_cluster].append(mention)
mention_to_predicted[mention] = predicted_cluster
predicted_clusters = [tuple(pc) for pc in predicted_clusters]
mention_to_predicted = { m:predicted_clusters[i] for m,i in mention_to_predicted.items() }
return predicted_clusters, mention_to_predicted
def evaluate_coref(self, top_span_starts, top_span_ends, predicted_antecedents, gold_clusters, evaluator):
gold_clusters = [tuple(tuple(m) for m in gc) for gc in gold_clusters]
mention_to_gold = {}
for gc in gold_clusters:
for mention in gc:
mention_to_gold[mention] = gc
predicted_clusters, mention_to_predicted = self.get_predicted_clusters(top_span_starts, top_span_ends, predicted_antecedents)
evaluator.update(predicted_clusters, gold_clusters, mention_to_predicted, mention_to_gold)
return predicted_clusters
def load_eval_data(self):
if self.eval_data is None:
def load_line(line):
example = json.loads(line)
return self.tensorize_example(example, is_training=False), example
with open(self.config["eval_path"]) as f:
self.eval_data = [load_line(l) for l in f.readlines()]
num_words = sum(tensorized_example[2].sum() for tensorized_example, _ in self.eval_data)
print("Loaded {} eval examples.".format(len(self.eval_data)))
def evaluate(self, session, global_step=None, official_stdout=False, keys=None, eval_mode=False):
self.load_eval_data()
coref_predictions = {}
coref_evaluator = metrics.CorefEvaluator()
losses = []
doc_keys = []
num_evaluated= 0
for example_num, (tensorized_example, example) in enumerate(self.eval_data):
_, _, _, _, _, _, _, _, gold_starts, gold_ends, _, _ = tensorized_example
feed_dict = {i:t for i,t in zip(self.input_tensors, tensorized_example)}
# if tensorized_example[0].shape[0] <= 9:
# if keys is not None and example['doc_key'] in keys:
# print('Skipping...', example['doc_key'], tensorized_example[0].shape)
# continue
doc_keys.append(example['doc_key'])
loss, (candidate_starts, candidate_ends, candidate_mention_scores, top_span_starts, top_span_ends, top_antecedents, top_antecedent_scores) = session.run([self.loss, self.predictions], feed_dict=feed_dict)
# losses.append(session.run(self.loss, feed_dict=feed_dict))
losses.append(loss)
predicted_antecedents = self.get_predicted_antecedents(top_antecedents, top_antecedent_scores)
coref_predictions[example["doc_key"]] = self.evaluate_coref(top_span_starts, top_span_ends, predicted_antecedents, example["clusters"], coref_evaluator)
if example_num % 10 == 0:
print("Evaluated {}/{} examples.".format(example_num + 1, len(self.eval_data)))
summary_dict = {}
# with open('doc_keys_512.txt', 'w') as f:
# for key in doc_keys:
# f.write(key + '\n')
if eval_mode:
conll_results = conll.evaluate_conll(self.config["conll_eval_path"], coref_predictions, self.subtoken_maps, official_stdout )
average_f1 = sum(results["f"] for results in conll_results.values()) / len(conll_results)
summary_dict["Average F1 (conll)"] = average_f1
print("Average F1 (conll): {:.2f}%".format(average_f1))
p,r,f = coref_evaluator.get_prf()
summary_dict["Average F1 (py)"] = f
print("Average F1 (py): {:.2f}% on {} docs".format(f * 100, len(doc_keys)))
summary_dict["Average precision (py)"] = p
print("Average precision (py): {:.2f}%".format(p * 100))
summary_dict["Average recall (py)"] = r
print("Average recall (py): {:.2f}%".format(r * 100))
return util.make_summary(summary_dict), f
| {
"pile_set_name": "Github"
} |
{
"network": [
[
"probeNetwork - default - end",
1,
84942
],
[
"probeNetwork - default - start",
0,
0
]
],
"gfx": [
[
"probeGFX - default - end",
1,
4,
9,
1,
[
35777,
35777
],
[
142,
142
],
[
1664,
1664
]
]
]
} | {
"pile_set_name": "Github"
} |
#include <u.h>
#include <libc.h>
#include <fcall.h>
#include <thread.h>
#include <9p.h>
#include "dat.h"
#include "fns.h"
#define thdr r->ifcall
#define rhdr r->ofcall
extern int errno;
static void
response(Req *r)
{
char *err;
if (errno) {
err = xerrstr(errno);
chat("%s\n", err);
respond(r, err);
} else {
chat("OK\n");
respond(r, nil);
}
}
static void
rattach(Req *r)
{
Xfs *xf;
Xfile *root;
chat("attach(fid=%d,uname=\"%s\",aname=\"%s\",afid=\"%d\")...",
thdr.fid, thdr.uname, thdr.aname, thdr.afid);
errno = 0;
root = xfile(r->fid, Clean);
if(!root){
errno = Enomem;
goto error;
}
root->xf = xf = getxfs(thdr.aname);
if(!xf)
goto error;
/* now attach root inode */
if( get_inode(root, EXT2_ROOT_INODE) < 0 )
goto error;
r->fid->qid.type = QTDIR;
r->fid->qid.vers = 0;
root->xf->rootqid = r->fid->qid;
root->pinbr = EXT2_ROOT_INODE;
root->root = 1;
rhdr.qid = r->fid->qid;
error:
response(r);
}
static char *
rclone(Fid *fid, Fid *newfid)
{
Xfile *of = xfile(fid, Asis);
Xfile *nf = xfile(newfid, Clean);
chat("clone(fid=%d,newfid=%d)...", fid->fid, newfid->fid);
errno = 0;
if(!of)
errno = Eio;
else if(!nf)
errno = Enomem;
else{
Xfile *next = nf->next;
*nf = *of;
nf->next = next;
nf->fid = newfid->fid;
nf->root = 0;
}
chat("%s\n", errno? xerrstr(errno) : "OK");
return errno ? xerrstr(errno) : 0;
}
static char *
rwalk1(Fid *fid, char *name, Qid *qid)
{
Xfile *f=xfile(fid, Asis);
int nr, sinbr = 0;
chat("walk1(fid=%d,name=\"%s\")...", fid->fid, name);
errno = 0;
if( !f ){
chat("no xfile...");
goto error;
}
if( !(fid->qid.type & QTDIR) ){
chat("qid.type=0x%x...", fid->qid.type);
goto error;
}
sinbr = f->pinbr;
if( name == 0 || name[0] == 0 || !strcmp(name, ".") ){
*qid = fid->qid;
goto ok;
}else if( !strcmp(name, "..") ){
if( fid->qid.path == f->xf->rootqid.path ){
chat("walkup from root...");
*qid = fid->qid;
goto ok;
}
if( get_inode(f, f->pinbr) < 0 )
goto error;
if( f->pinbr == EXT2_ROOT_INODE ){
*qid = f->xf->rootqid;
f->pinbr = EXT2_ROOT_INODE;
} else {
*qid = (Qid){f->pinbr,0,QTDIR};
f->inbr = f->pinbr;
if( (nr = get_file(f, "..")) < 0 )
goto error;
f->pinbr = nr;
}
}else{
f->pinbr = f->inbr;
if( (nr = get_file(f, name)) < 0 )
goto error;
if( get_inode(f, nr) < 0 )
goto error;
*qid = (Qid){nr,0,0};
if( nr == EXT2_ROOT_INODE )
*qid = f->xf->rootqid;
else if( S_ISDIR(getmode(f)) )
qid->type = QTDIR;
/*strcpy(f->name, thdr.name);*/
}
ok:
chat("OK\n");
return 0;
error:
f->pinbr = sinbr;
chat("%s\n", xerrstr(Enonexist));
return xerrstr(Enonexist);
}
static void
rstat(Req *r)
{
Xfile *f=xfile(r->fid, Asis);
chat("stat(fid=%d)...", thdr.fid);
errno = 0;
if( !f )
errno = Eio;
else{
dostat(r->fid->qid, f, &r->d);
}
response(r);
}
static void
rwstat(Req *r)
{
Xfile *f=xfile(r->fid, Asis);
chat("wstat(fid=%d)...", thdr.fid);
errno = 0;
if( !f )
errno = Eio;
else
dowstat(f, &r->d);
response(r);
}
static void
rread(Req *r)
{
Xfile *f;
int nr;
chat("read(fid=%d,offset=%lld,count=%d)...",
thdr.fid, thdr.offset, thdr.count);
errno = 0;
if ( !(f=xfile(r->fid, Asis)) )
goto error;
if( r->fid->qid.type & QTDIR ){
nr = readdir(f, r->rbuf, thdr.offset, thdr.count);
}else
nr = readfile(f, r->rbuf, thdr.offset, thdr.count);
if(nr >= 0){
rhdr.count = nr;
chat("rcnt=%d...OK\n", nr);
respond(r, nil);
return;
}
error:
errno = Eio;
response(r);
}
static void
rwrite(Req *r)
{
Xfile *f; int nr;
chat("write(fid=%d,offset=%lld,count=%d)...",
thdr.fid, thdr.offset, thdr.count);
errno = 0;
if (!(f=xfile(r->fid, Asis)) ){
errno = Eio;
goto error;
}
if( !S_ISREG(getmode(f)) ){
errno = Elink;
goto error;
}
nr = writefile(f, thdr.data, thdr.offset, thdr.count);
if(nr >= 0){
rhdr.count = nr;
chat("rcnt=%d...OK\n", nr);
respond(r, nil);
return;
}
errno = Eio;
error:
response(r);
}
static void
destroyfid(Fid *fid)
{
chat("destroy(fid=%d)\n", fid->fid);
xfile(fid, Clunk);
/*syncbuf(xf);*/
}
static void
ropen(Req *r)
{
Xfile *f;
chat("open(fid=%d,mode=%d)...", thdr.fid, thdr.mode);
errno = 0;
f = xfile(r->fid, Asis);
if( !f ){
errno = Eio;
goto error;
}
if(thdr.mode & OTRUNC){
if( !S_ISREG(getmode(f)) ){
errno = Eperm;
goto error;
}
if(truncfile(f) < 0){
goto error;
}
}
chat("f->qid=0x%8.8lux...", r->fid->qid.path);
rhdr.qid = r->fid->qid;
error:
response(r);
}
static void
rcreate(Req *r)
{
Xfile *f;
int inr, perm;
chat("create(fid=%d,name=\"%s\",perm=%uo,mode=%d)...",
thdr.fid, thdr.name, thdr.perm, thdr.mode);
errno = 0;
if(strcmp(thdr.name, ".") == 0 || strcmp(thdr.name, "..") == 0){
errno = Eperm;
goto error;
}
f = xfile(r->fid, Asis);
if( !f ){
errno = Eio;
goto error;
}
if( strlen(thdr.name) > EXT2_NAME_LEN ){
chat("name too long ...");
errno = Elongname;
goto error;
}
/* create */
errno = 0;
if( thdr.perm & DMDIR ){
perm = (thdr.perm & ~0777) |
(getmode(f) & thdr.perm & 0777);
perm |= S_IFDIR;
inr = create_dir(f, thdr.name, perm);
}else{
perm = (thdr.perm & (~0777|0111)) |
(getmode(f) & thdr.perm & 0666);
perm |= S_IFREG;
inr = create_file(f, thdr.name, perm);
}
if( inr < 0 )
goto error;
/* fill with new inode */
f->pinbr = f->inbr;
if( get_inode(f, inr) < 0 ){
errno = Eio;
goto error;
}
r->fid->qid = (Qid){inr, 0, 0};
if( S_ISDIR(getmode(f)) )
r->fid->qid.type |= QTDIR;
chat("f->qid=0x%8.8lux...", r->fid->qid.path);
rhdr.qid = r->fid->qid;
error:
response(r);
}
static void
rremove(Req *r)
{
Xfile *f=xfile(r->fid, Asis);
chat("remove(fid=%d) ...", thdr.fid);
errno = 0;
if(!f){
errno = Eio;
goto error;
}
/* check permission here !!!!*/
unlink(f);
error:
response(r);
}
Srv ext2srv = {
.destroyfid = destroyfid,
.attach = rattach,
.stat = rstat,
.wstat = rwstat,
.clone = rclone,
.walk1 = rwalk1,
.open = ropen,
.read = rread,
.write = rwrite,
.create = rcreate,
.remove = rremove,
};
| {
"pile_set_name": "Github"
} |
---
title: 'Removing a datastore'
slug: remove-data-store
excerpt: 'Find out how to remove a datastore from your Private Cloud'
legacy_guide_number: '7766789'
section: 'OVH Features'
---
**Last updated 24th July 2020**
## Objective
In certain cases — like replacing a datastore or scaling it up to a higher capacity, for example — it may be useful to remove a datastore from your cluster.
**This guide will show you how to securely remove a datastore from your infrastructure.**
## Requirements
* an [OVHcloud Hosted Private Cloud](https://www.ovhcloud.com/en-sg/enterprise/products/hosted-private-cloud/){.external} solution
* access to the vSphere management interface
## Instructions
> [!warning]
>
> Please note that you cannot remove the **two 300 GB or 1.2 TB datastores** included in your pack. For security reasons, the removal request will also be blocked if you have virtual machines (VMs) on the datastore concerned (they will be listed in the confirmation window).
>
To remove a datastore, right-click on the resource concerned. Then select `OVHcloud`{.action}, and `Remove this Storage`{.action}.
{.thumbnail}
A confirmation window will pop up. Confirm by clicking `Next`{.action}.
{.thumbnail}
The removal request will then be processed.
{.thumbnail}
You can also monitor the progress of the datastore removal in `Recent Tasks`{.action}.
{.thumbnail}
## Go further
Join our community of users on <https://community.ovh.com/en/>.
| {
"pile_set_name": "Github"
} |
SUMMARY="A tool to play back online videos in MediaPlayer"
DESCRIPTION="
UberTuber grabs clips from various sites and opens them in your media player \
while they're being downloaded. The Python script youtube-dl downloads the \
video file to the temporary folder. From there it is eitherplayed back while \
it gets downloaded or moved to another location determined in a file dialog.
UberTuber monitors the system clipboard for URLs pointing to the supported \
websites and automatically inserts them into its URL text field.
At this moment there is support for clips from:
YouTube, Google video, MetaCafe, DailyMotion, Yahoo video, Photobucket, \
DepositFiles, Vimeo.com, blip.tv, Facebook video and Escapist magazine.
For a complete list, check http://rg3.github.io/youtube-dl/supportedsites.html
"
HOMEPAGE="https://sourceforge.net/projects/ubertuber/"
COPYRIGHT="2013 Humdinger"
LICENSE="MIT"
REVISION="3"
SOURCE_URI="git://git.code.sf.net/p/ubertuber/code#12bc4486522dab6255f95c5a041674cd8b2cde2c"
ARCHITECTURES="x86_gcc2 x86"
USER_SETTINGS_FILES="settings/UberTuber_settings"
PROVIDES="
ubertuber = $portVersion
app:ubertuber = $portVersion
"
REQUIRES="
haiku
cmd:youtube_dl
"
BUILD_REQUIRES="
haiku_devel
"
BUILD_PREREQUIRES="
makefile_engine
cmd:gcc
cmd:make
"
BUILD()
{
make $jobArgs
}
INSTALL()
{
ubertuberDir=$appsDir/UberTuber
mkdir -p $ubertuberDir
ARCH=$(echo $buildArchitecture | sed 's/_/-/g')
cp -af objects.$ARCH-release/UberTuber $ubertuberDir
cp -af ReadMe.html $ubertuberDir
cp -r images $ubertuberDir
addAppDeskbarSymlink $ubertuberDir/UberTuber
}
| {
"pile_set_name": "Github"
} |
<component name="MarkdownNavigator.ProfileManager">
<settings default="" pdf-export="" />
</component> | {
"pile_set_name": "Github"
} |
<?php
namespace Robo\Task\Archive;
use Robo\Result;
use Robo\Task\BaseTask;
use Robo\Task\Filesystem\FilesystemStack;
use Robo\Task\Filesystem\DeleteDir;
use Robo\Contract\BuilderAwareInterface;
use Robo\Common\BuilderAwareTrait;
/**
* Extracts an archive.
*
* Note that often, distributions are packaged in tar or zip archives
* where the topmost folder may contain variable information, such as
* the release date, or the version of the package. This information
* is very useful when unpacking by hand, but arbitrarily-named directories
* are much less useful to scripts. Therefore, by default, Extract will
* remove the top-level directory, and instead store all extracted files
* into the directory specified by $archivePath.
*
* To keep the top-level directory when extracting, use
* `preserveTopDirectory(true)`.
*
* ``` php
* <?php
* $this->taskExtract($archivePath)
* ->to($destination)
* ->preserveTopDirectory(false) // the default
* ->run();
* ?>
* ```
*/
class Extract extends BaseTask implements BuilderAwareInterface
{
use BuilderAwareTrait;
/**
* @var string
*/
protected $filename;
/**
* @var string
*/
protected $to;
/**
* @var bool
*/
private $preserveTopDirectory = false;
/**
* @param string $filename
*/
public function __construct($filename)
{
$this->filename = $filename;
}
/**
* Location to store extracted files.
*
* @param string $to
*
* @return $this
*/
public function to($to)
{
$this->to = $to;
return $this;
}
/**
* @param bool $preserve
*
* @return $this
*/
public function preserveTopDirectory($preserve = true)
{
$this->preserveTopDirectory = $preserve;
return $this;
}
/**
* {@inheritdoc}
*/
public function run()
{
if (!file_exists($this->filename)) {
$this->printTaskError("File {filename} does not exist", ['filename' => $this->filename]);
return false;
}
if (!($mimetype = static::archiveType($this->filename))) {
$this->printTaskError("Could not determine type of archive for {filename}", ['filename' => $this->filename]);
return false;
}
// We will first extract to $extractLocation and then move to $this->to
$extractLocation = static::getTmpDir();
@mkdir($extractLocation);
@mkdir(dirname($this->to));
$this->startTimer();
$this->printTaskInfo("Extracting {filename}", ['filename' => $this->filename]);
$result = $this->extractAppropriateType($mimetype, $extractLocation);
if ($result->wasSuccessful()) {
$this->printTaskInfo("{filename} extracted", ['filename' => $this->filename]);
// Now, we want to move the extracted files to $this->to. There
// are two possibilities that we must consider:
//
// (1) Archived files were encapsulated in a folder with an arbitrary name
// (2) There was no encapsulating folder, and all the files in the archive
// were extracted into $extractLocation
//
// In the case of (1), we want to move and rename the encapsulating folder
// to $this->to.
//
// In the case of (2), we will just move and rename $extractLocation.
$filesInExtractLocation = glob("$extractLocation/*");
$hasEncapsulatingFolder = ((count($filesInExtractLocation) == 1) && is_dir($filesInExtractLocation[0]));
if ($hasEncapsulatingFolder && !$this->preserveTopDirectory) {
$result = (new FilesystemStack())
->inflect($this)
->rename($filesInExtractLocation[0], $this->to)
->run();
(new DeleteDir($extractLocation))
->inflect($this)
->run();
} else {
$result = (new FilesystemStack())
->inflect($this)
->rename($extractLocation, $this->to)
->run();
}
}
$this->stopTimer();
$result['time'] = $this->getExecutionTime();
return $result;
}
/**
* @param string $mimetype
* @param string $extractLocation
*
* @return \Robo\Result
*/
protected function extractAppropriateType($mimetype, $extractLocation)
{
// Perform the extraction of a zip file.
if (($mimetype == 'application/zip') || ($mimetype == 'application/x-zip')) {
return $this->extractZip($extractLocation);
}
return $this->extractTar($extractLocation);
}
/**
* @param string $extractLocation
*
* @return \Robo\Result
*/
protected function extractZip($extractLocation)
{
if (!extension_loaded('zlib')) {
return Result::errorMissingExtension($this, 'zlib', 'zip extracting');
}
$zip = new \ZipArchive();
if (($status = $zip->open($this->filename)) !== true) {
return Result::error($this, "Could not open zip archive {$this->filename}");
}
if (!$zip->extractTo($extractLocation)) {
return Result::error($this, "Could not extract zip archive {$this->filename}");
}
$zip->close();
return Result::success($this);
}
/**
* @param string $extractLocation
*
* @return \Robo\Result
*/
protected function extractTar($extractLocation)
{
if (!class_exists('Archive_Tar')) {
return Result::errorMissingPackage($this, 'Archive_Tar', 'pear/archive_tar');
}
$tar_object = new \Archive_Tar($this->filename);
if (!$tar_object->extract($extractLocation)) {
return Result::error($this, "Could not extract tar archive {$this->filename}");
}
return Result::success($this);
}
/**
* @param string $filename
*
* @return bool|string
*/
protected static function archiveType($filename)
{
$content_type = false;
if (class_exists('finfo')) {
$finfo = new \finfo(FILEINFO_MIME_TYPE);
$content_type = $finfo->file($filename);
// If finfo cannot determine the content type, then we will try other methods
if ($content_type == 'application/octet-stream') {
$content_type = false;
}
}
// Examing the file's magic header bytes.
if (!$content_type) {
if ($file = fopen($filename, 'rb')) {
$first = fread($file, 2);
fclose($file);
if ($first !== false) {
// Interpret the two bytes as a little endian 16-bit unsigned int.
$data = unpack('v', $first);
switch ($data[1]) {
case 0x8b1f:
// First two bytes of gzip files are 0x1f, 0x8b (little-endian).
// See http://www.gzip.org/zlib/rfc-gzip.html#header-trailer
$content_type = 'application/x-gzip';
break;
case 0x4b50:
// First two bytes of zip files are 0x50, 0x4b ('PK') (little-endian).
// See http://en.wikipedia.org/wiki/Zip_(file_format)#File_headers
$content_type = 'application/zip';
break;
case 0x5a42:
// First two bytes of bzip2 files are 0x5a, 0x42 ('BZ') (big-endian).
// See http://en.wikipedia.org/wiki/Bzip2#File_format
$content_type = 'application/x-bzip2';
break;
}
}
}
}
// 3. Lastly if above methods didn't work, try to guess the mime type from
// the file extension. This is useful if the file has no identificable magic
// header bytes (for example tarballs).
if (!$content_type) {
// Remove querystring from the filename, if present.
$filename = basename(current(explode('?', $filename, 2)));
$extension_mimetype = array(
'.tar.gz' => 'application/x-gzip',
'.tgz' => 'application/x-gzip',
'.tar' => 'application/x-tar',
);
foreach ($extension_mimetype as $extension => $ct) {
if (substr($filename, -strlen($extension)) === $extension) {
$content_type = $ct;
break;
}
}
}
return $content_type;
}
/**
* @return string
*/
protected static function getTmpDir()
{
return getcwd() . '/tmp' . rand() . time();
}
}
| {
"pile_set_name": "Github"
} |
FROM tensorflow/tensorflow:1.8.0-gpu-py3
RUN apt-get update
RUN apt-get install -y \
build-essential \
cmake \
git \
wget \
unzip \
yasm \
pkg-config \
libswscale-dev \
libtbb2 \
libtbb-dev \
libjpeg-dev \
libpng-dev \
libtiff-dev \
# libjasper-dev \ this library seems to not be installable at the moment
libavformat-dev \
libhdf5-dev \
libpq-dev
WORKDIR /
RUN apt-get update && apt-get install -y wget && wget https://github.com/opencv/opencv/archive/3.4.1.zip \
&& unzip 3.4.1.zip \
&& mkdir /opencv-3.4.1/cmake_binary \
&& cd /opencv-3.4.1/cmake_binary \
&& cmake -DBUILD_TIFF=ON \
-DBUILD_opencv_java=OFF \
-DWITH_CUDA=OFF \
-DENABLE_AVX=ON \
-DWITH_OPENGL=ON \
-DWITH_OPENCL=ON \
-DWITH_IPP=ON \
-DWITH_TBB=ON \
-DWITH_EIGEN=ON \
-DWITH_V4L=ON \
-DBUILD_TESTS=OFF \
-DBUILD_PERF_TESTS=OFF \
-DCMAKE_BUILD_TYPE=RELEASE \
-DCMAKE_INSTALL_PREFIX=$(python3 -c "import sys; print(sys.prefix)") \
-DPYTHON_EXECUTABLE=$(which python3) \
-DPYTHON_INCLUDE_DIR=$(python3 -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())") \
-DPYTHON_PACKAGES_PATH=$(python3 -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())") .. \
&& make install \
&& rm /3.4.1.zip \
&& rm -r /opencv-3.4.1
RUN pip3 install --upgrade cython
RUN wget https://s3.amazonaws.com/vision4j/problems/external_models/mask-rcnn-segmentation/requirements.txt -O /tmp/requirements.txt
RUN pip3 install -r /tmp/requirements.txt
RUN mkdir -p /app
RUN wget https://github.com/matterport/Mask_RCNN/releases/download/v2.0/mask_rcnn_coco.h5 -O /app/mask_rcnn_coco.h5
RUN mkdir -p /app/proto
COPY segmentation.proto /app/proto
COPY *.py /app/
RUN python -m grpc_tools.protoc -I/app/proto --python_out=/app --grpc_python_out=/app /app/proto/segmentation.proto
CMD ["python", "/app/segmentation_server.py"]
| {
"pile_set_name": "Github"
} |
/**
* @file
*
* @author CCHyper
* @author OmniBlade
*
* @brief Class for handling TARGA images.
*
* @copyright Thyme is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version
* 2 of the License, or (at your option) any later version.
* A full copy of the GNU General Public License can be found in
* LICENSE
*/
#include "targa.h"
#include "ffactory.h"
#include <captainslog.h>
#include <cstring>
#include <malloc.h>
#ifdef GAME_DLL
#include "hookcrt.h"
#endif
using std::memcpy;
using std::memset;
TargaImage::TargaImage() : m_TGAFile(nullptr), m_access(0), m_flags(0), m_image(nullptr), m_palette(nullptr)
{
memset(&m_header, 0, sizeof(m_header));
memset(&m_extension, 0, sizeof(m_extension));
}
TargaImage::~TargaImage()
{
Close();
if (m_palette != nullptr && m_flags & 2) {
free(m_palette);
m_palette = nullptr;
}
if (m_image != nullptr && m_flags & 1) {
free(m_image);
m_image = nullptr;
}
}
int TargaImage::Open(const char *name, int mode)
{
if (Is_File_Open() && m_access == mode) {
return 0;
}
Close();
m_flags &= ~8;
m_access = mode;
TGA2Footer footer;
switch (mode) {
case TARGA_READ:
if (!File_Open_Read(name)) {
Close();
return TGA_RET_UNABLE_TO_LOAD;
}
// If we can't read enough data for a footer, not a TGA file.
if (File_Seek(-((int)sizeof(footer)), FileSeekType::FS_SEEK_END) == -1
|| File_Read(&footer, sizeof(footer)) != sizeof(footer)) {
Close();
return TGA_RET_NOT_TGA;
}
// If we don't have the correct footer info, not a TGA file.
if (strncasecmp(footer.signature, "TRUEVISION-XFILE", sizeof(footer.signature)) == 0 && footer.extension != 0) {
m_flags |= 8;
}
footer.extension = le32toh(footer.extension);
// If we can't seek to the extension offset or we can't read enough data,
// not a TGA file.
if ((m_flags & 8) != 0
&& (File_Seek(footer.extension, FileSeekType::FS_SEEK_START) != -1
|| File_Read(&m_extension, sizeof(m_extension) != sizeof(m_extension)))) {
Close();
return TGA_RET_NOT_TGA;
} else if (File_Seek(0, FileSeekType::FS_SEEK_START) == -1) {
Close();
return TGA_RET_NOT_TGA;
}
// Convert endian if needed.
Extension_To_Host(m_extension);
// If file is shorter than header then its not a TGA.
if (File_Read(&m_header, sizeof(m_header)) != sizeof(m_header)) {
Close();
return TGA_RET_NOT_TGA;
}
// Convert endian if needed.
Header_To_Host(m_header);
// If file seek past ID fails, then not a TGA.
if (m_header.id_length != 0 && File_Seek(m_header.id_length, FileSeekType::FS_SEEK_CURRENT) == -1) {
Close();
return TGA_RET_NOT_TGA;
}
break;
case TARGA_WRITE:
if (!File_Open_Write(name)) {
Close();
return TGA_RET_UNABLE_TO_LOAD;
}
break;
case TARGA_READWRITE:
if (!File_Open_ReadWrite(name)) {
Close();
return TGA_RET_UNABLE_TO_LOAD;
}
// If file is shorter than header then its not a TGA.
if (File_Read(&m_header, sizeof(m_header)) != sizeof(m_header)) {
Close();
return TGA_RET_NOT_TGA;
}
Header_To_Host(m_header);
// If file seek past ID fails, then not a TGA.
if (m_header.id_length != 0 && File_Seek(m_header.id_length, FileSeekType::FS_SEEK_CURRENT) == -1) {
Close();
return TGA_RET_NOT_TGA;
}
break;
default:
break;
}
return TGA_RET_OK;
}
void TargaImage::Close()
{
if (m_TGAFile != nullptr) {
m_TGAFile->Close();
g_theFileFactory->Return_File(m_TGAFile);
Clear_File();
}
}
int TargaImage::Load(const char *name, int flags, bool invert_image)
{
if (Open(name, TARGA_READ) != TGA_RET_OK) {
return TGA_RET_UNABLE_TO_LOAD;
}
if ((flags & TGA_FLAG_PAL_ALLOC) != 0 && m_header.cmap_type == 1) {
if (m_palette != nullptr && (m_flags & TGA_FLAG_PAL_ALLOC) == 0) {
free(m_palette);
m_palette = nullptr;
m_flags &= ~TGA_FLAG_PAL_ALLOC;
}
if (m_palette == nullptr && (m_flags & TGA_FLAG_PAL_ALLOC) == 0) {
if ((m_header.cmap_length * (m_header.cmap_depth / 8)) > 0) {
m_palette = (char *)malloc(m_header.cmap_length * (m_header.cmap_depth / 8));
}
if (m_palette == nullptr) {
Close();
return TGA_RET_OUT_OF_MEMORY;
}
m_flags |= 2;
}
}
if ((flags & TGA_FLAG_IMAGE_ALLOC) != 0) {
if (m_image != nullptr && (m_flags & TGA_FLAG_IMAGE_ALLOC) == 0) {
free(m_image);
m_image = nullptr;
m_flags &= ~TGA_FLAG_IMAGE_ALLOC;
}
if (m_image == nullptr && (m_flags & TGA_FLAG_IMAGE_ALLOC) == 0) {
if ((m_header.width * m_header.height * ((m_header.pixel_depth + 7) / 8)) > 0) {
m_image = (char *)malloc(m_header.width * m_header.height * ((m_header.pixel_depth + 7) / 8));
}
if (m_image == nullptr) {
Close();
return TGA_RET_OUT_OF_MEMORY;
}
m_flags |= 1;
}
}
int ret = Load(name, m_palette, m_image, invert_image);
Close();
return ret;
}
int TargaImage::Load(const char *name, char *palette, char *image, bool invert_image)
{
if (Open(name, TARGA_READ) != TGA_RET_OK) {
return TGA_RET_UNABLE_TO_LOAD;
}
if (m_header.cmap_type == 1) {
int pixel_bytes = m_header.cmap_depth / 8;
if (palette != nullptr && m_header.cmap_length > 0) {
int read_bytes = File_Read(&palette[pixel_bytes * m_header.cmap_start], pixel_bytes * m_header.cmap_length);
if (read_bytes != pixel_bytes * m_header.cmap_length) {
Close();
return TGA_RET_NOT_TGA;
}
} else if (File_Seek(pixel_bytes * m_header.cmap_length, FileSeekType::FS_SEEK_CURRENT) == -1) {
Close();
return TGA_RET_NOT_TGA;
}
}
if (image != nullptr) {
int total_bytes = m_header.width * m_header.height * ((m_header.pixel_depth + 7) / 8);
switch (m_header.image_type) {
case TGA_TYPE_MAPPED:
case TGA_TYPE_COLOR:
case TGA_TYPE_GREY:
if (File_Read(image, total_bytes) != total_bytes) {
Close();
return TGA_RET_NOT_TGA;
}
break;
case TGA_TYPE_RLE_MAPPED:
case TGA_TYPE_RLE_COLOR: {
int ret = Decode_Image();
if (ret != TGA_RET_OK) {
return ret;
}
} break;
default:
Close();
return TGA_RET_UNSUPPORTED;
}
if (invert_image) {
Invert_Image();
}
if ((m_header.image_descriptor & 0x10) != 0) {
X_Flip();
m_header.image_descriptor &= ~0x10;
}
if ((m_header.image_descriptor & 0x20) != 0) {
Y_Flip();
m_header.image_descriptor &= ~0x20;
}
}
Close();
return TGA_RET_OK;
}
int TargaImage::Save(const char *name, int flags, bool add_extension)
{
if (Open(name, TARGA_WRITE) != TGA_RET_OK) {
return TGA_RET_UNABLE_TO_LOAD;
}
m_header.id_length = 0;
// Flag can force compression even if its not currently set.
if ((flags & TGA_FLAG_COMPRESS) != 0) {
switch (m_header.image_type) {
case TGA_TYPE_MAPPED:
case TGA_TYPE_COLOR:
case TGA_TYPE_GREY:
m_header.image_type += 8; // Convert to RLE type then fall through
case TGA_TYPE_RLE_MAPPED:
case TGA_TYPE_RLE_COLOR:
case TGA_TYPE_RLE_GREY:
break;
default:
flags &= ~TGA_FLAG_COMPRESS;
break;
}
}
if (File_Write(&m_header, sizeof(m_header)) != sizeof(m_header)) {
Close();
return TGA_RET_UNABLE_TO_SAVE;
}
// Write palette if we have one.
if ((flags & TGA_FLAG_PAL_ALLOC) != 0) {
if (m_palette != nullptr && m_header.cmap_length > 0) {
int pal_depth = m_header.cmap_depth / 8;
int pal_size = pal_depth * m_header.cmap_length;
if (File_Write(&m_palette[pal_depth * m_header.cmap_start], pal_size) != pal_size) {
Close();
return TGA_RET_UNABLE_TO_SAVE;
}
}
}
// Write the image, flipping if color and flipping back afterward, compressing if required
if ((flags & TGA_FLAG_IMAGE_ALLOC) != 0 && m_image != nullptr) {
bool inverted = false;
if (m_header.image_type == TGA_TYPE_COLOR || m_header.image_type == TGA_TYPE_RLE_COLOR) {
Invert_Image();
inverted = true;
}
if ((flags & TGA_FLAG_COMPRESS) != 0) {
Encode_Image();
} else {
int img_size = m_header.width * m_header.height * ((m_header.pixel_depth + 7) / 8);
if (File_Write(m_image, img_size) != img_size) {
Close();
return TGA_RET_UNABLE_TO_SAVE;
}
}
if (inverted) {
Invert_Image();
}
}
TGA2Footer footer;
// Write the extension if required, if not just write the footer.
if (add_extension) {
m_extension.ext_size = sizeof(m_extension);
strlcpy(m_extension.software_id, "Thyme Game Engine", sizeof(m_extension.software_id));
m_extension.software_vers.number = 1;
m_extension.software_vers.letter = '\0';
footer.extension = File_Seek(0, FileSeekType::FS_SEEK_CURRENT);
if (footer.extension == -1 || File_Write(&m_extension, sizeof(m_extension)) != sizeof(m_extension)) {
Close();
return TGA_RET_UNABLE_TO_SAVE;
}
} else {
footer.extension = 0;
}
strlcpy(footer.signature, "TRUEVISION-XFILE", sizeof(footer.signature));
footer.dot_char = '.';
footer.null_char = '\0';
if (File_Write(&footer, sizeof(footer)) != sizeof(footer)) {
Close();
return TGA_RET_UNABLE_TO_SAVE;
}
Close();
return TGA_RET_OK;
}
void TargaImage::X_Flip()
{
int pixel_size = (m_header.pixel_depth + 7) / 8;
// Must have at least one row of pixels.
if (m_header.height <= 0) {
captainslog_dbgassert(false, "Image has no pixels.");
return;
}
// Iterate over the image and move bytes from start of a row to the
// end and vice versa, keeping the order of bytes within the pixel.
for (int y = 0; y < m_header.height; ++y) {
char *startp = &m_image[y * m_header.width * pixel_size];
char *endp = &startp[pixel_size * (m_header.width - 1)];
for (int x = 0; x < (m_header.width / 2); ++x) {
if (pixel_size > 0) {
char *modp = endp;
ptrdiff_t diff = startp - endp;
for (int i = pixel_size; i > 0; --i) {
char tmp = modp[diff];
modp[diff] = modp[0];
modp[0] = tmp;
++modp;
}
}
startp += pixel_size;
endp -= pixel_size;
}
}
}
void TargaImage::Y_Flip()
{
int pixel_size = (m_header.pixel_depth + 7) / 8;
for (int y = 0; y < (m_header.height / 2); ++y) {
// Set pointers to the start and end rows.
char *startp = &m_image[m_header.width * pixel_size * y];
char *endp = &m_image[m_header.width * pixel_size * (m_header.height - 1)] - (m_header.width * pixel_size * y);
// Iterate over the rows, swapping bytes between them.
for (int x = 0; x < (pixel_size * m_header.width); ++x) {
char tmp = startp[x];
startp[x] = endp[x];
endp[x] = tmp;
}
}
}
char *TargaImage::Set_Image(char *buffer)
{
if (m_image != nullptr && (m_flags & TGA_FLAG_IMAGE_ALLOC) == 0) {
free(m_image);
m_image = nullptr;
m_flags &= ~TGA_FLAG_IMAGE_ALLOC;
}
char *old_image = m_image;
m_image = buffer;
return old_image;
}
char *TargaImage::Set_Palette(char *buffer)
{
if (m_palette != nullptr && (m_flags & TGA_FLAG_PAL_ALLOC) == 0) {
free(m_palette);
m_palette = nullptr;
m_flags &= ~TGA_FLAG_PAL_ALLOC;
}
char *old_pal = m_palette;
m_palette = buffer;
return old_pal;
}
int TargaImage::Decode_Image()
{
int pixel_bytes = (m_header.pixel_depth + 7) / 8;
int pixel_count = m_header.width * m_header.height;
char *putp = m_image;
while (pixel_count) {
uint8_t count;
if (File_Read(&count, sizeof(count)) != sizeof(count)) {
return TGA_RET_NOT_TGA;
}
if ((count & 0x80) != 0) {
count = (count & 0x7F) + 1;
char *getp = putp;
if (File_Read(getp, pixel_bytes) != pixel_bytes) {
return TGA_RET_NOT_TGA;
}
putp += pixel_bytes;
for (int i = 1; i < count; ++i) {
memcpy(putp, getp, pixel_bytes);
putp += pixel_bytes;
}
} else {
++count;
int read_size = pixel_bytes * count;
if (File_Read(putp, read_size) != read_size) {
return TGA_RET_NOT_TGA;
}
putp += read_size;
}
pixel_count -= count;
}
return TGA_RET_OK;
}
int TargaImage::Encode_Image()
{
// TODO
return 0;
}
void TargaImage::Invert_Image()
{
int pixel_bytes = (m_header.pixel_depth + 7) / 8;
int pixel_count = m_header.width * m_header.height;
if (pixel_bytes <= 2) {
return;
}
int half_pixel = pixel_bytes / 2;
char *curr_pixel = m_image;
while (pixel_count--) {
for (int i = 0; i < half_pixel; ++i) {
char tmp = curr_pixel[i];
curr_pixel[i] = curr_pixel[pixel_bytes - 1 - i];
curr_pixel[pixel_bytes - 1 - i] = tmp;
}
curr_pixel += pixel_bytes;
}
}
void TargaImage::Clear_File()
{
m_TGAFile = nullptr;
}
bool TargaImage::Is_File_Open()
{
return m_TGAFile != nullptr;
}
bool TargaImage::File_Open_Read(const char *name)
{
m_TGAFile = g_theFileFactory->Get_File(name);
if (m_TGAFile != nullptr && m_TGAFile->Is_Available()) {
return m_TGAFile->Open(FM_READ);
}
return false;
}
bool TargaImage::File_Open_Write(const char *name)
{
m_TGAFile = g_theWritingFileFactory->Get_File(name);
if (m_TGAFile != nullptr && m_TGAFile->Is_Available()) {
return m_TGAFile->Open(FM_WRITE);
}
return false;
}
bool TargaImage::File_Open_ReadWrite(const char *name)
{
m_TGAFile = g_theWritingFileFactory->Get_File(name);
if (m_TGAFile != nullptr && m_TGAFile->Is_Available()) {
return m_TGAFile->Open(FM_READ_WRITE);
}
return false;
}
int TargaImage::Error_Handler(int load_err, const char *filename)
{
switch (load_err) {
case TGA_RET_OK:
return load_err;
case TGA_RET_UNABLE_TO_LOAD:
captainslog_error("Targa: Failed to open file \"%s\"", filename);
return load_err;
case TGA_RET_NOT_TGA:
captainslog_error("Targa: Failed to read file \"%s\"", filename);
return load_err;
case TGA_RET_UNSUPPORTED:
captainslog_error("Targa: File \"%s\" is an unsupported Targa type", filename);
return load_err;
case TGA_RET_OUT_OF_MEMORY:
captainslog_error("Targa: Failed to allocate memory for file \"%s\"", filename);
return load_err;
default:
captainslog_error("Targa: Unknown error when loading file '%s'", filename);
return load_err;
}
}
| {
"pile_set_name": "Github"
} |
/* gerdes_amd7930.c,v 0.99 2001/10/02
*
* gerdes_amd7930.c Amd 79C30A and 79C32A specific routines
* (based on HiSax driver by Karsten Keil)
*
* Author Christoph Ersfeld <[email protected]>
* Formula-n Europe AG (www.formula-n.com)
* previously Gerdes AG
*
*
* This file is (c) under GNU PUBLIC LICENSE
*
*
* Notes:
* Version 0.99 is the first release of this driver and there are
* certainly a few bugs.
*
* Please don't report any malfunction to me without sending
* (compressed) debug-logs.
* It would be nearly impossible to retrace it.
*
* Log D-channel-processing as follows:
*
* 1. Load hisax with card-specific parameters, this example ist for
* Formula-n enter:now ISDN PCI and compatible
* (f.e. Gerdes Power ISDN PCI)
*
* modprobe hisax type=41 protocol=2 id=gerdes
*
* if you chose an other value for id, you need to modify the
* code below, too.
*
* 2. set debug-level
*
* hisaxctrl gerdes 1 0x3ff
* hisaxctrl gerdes 11 0x4f
* cat /dev/isdnctrl >> ~/log &
*
* Please take also a look into /var/log/messages if there is
* anything importand concerning HISAX.
*
*
* Credits:
* Programming the driver for Formula-n enter:now ISDN PCI and
* necessary this driver for the used Amd 7930 D-channel-controller
* was spnsored by Formula-n Europe AG.
* Thanks to Karsten Keil and Petr Novak, who gave me support in
* Hisax-specific questions.
* I want so say special thanks to Carl-Friedrich Braun, who had to
* answer a lot of questions about generally ISDN and about handling
* of the Amd-Chip.
*
*/
#include "hisax.h"
#include "isdnl1.h"
#include "isac.h"
#include "amd7930_fn.h"
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/gfp.h>
static void Amd7930_new_ph(struct IsdnCardState *cs);
static WORD initAMD[] = {
0x0100,
0x00A5, 3, 0x01, 0x40, 0x58, // LPR, LMR1, LMR2
0x0086, 1, 0x0B, // DMR1 (D-Buffer TH-Interrupts on)
0x0087, 1, 0xFF, // DMR2
0x0092, 1, 0x03, // EFCR (extended mode d-channel-fifo on)
0x0090, 4, 0xFE, 0xFF, 0x02, 0x0F, // FRAR4, SRAR4, DMR3, DMR4 (address recognition )
0x0084, 2, 0x80, 0x00, // DRLR
0x00C0, 1, 0x47, // PPCR1
0x00C8, 1, 0x01, // PPCR2
0x0102,
0x0107,
0x01A1, 1,
0x0121, 1,
0x0189, 2,
0x0045, 4, 0x61, 0x72, 0x00, 0x00, // MCR1, MCR2, MCR3, MCR4
0x0063, 2, 0x08, 0x08, // GX
0x0064, 2, 0x08, 0x08, // GR
0x0065, 2, 0x99, 0x00, // GER
0x0066, 2, 0x7C, 0x8B, // STG
0x0067, 2, 0x00, 0x00, // FTGR1, FTGR2
0x0068, 2, 0x20, 0x20, // ATGR1, ATGR2
0x0069, 1, 0x4F, // MMR1
0x006A, 1, 0x00, // MMR2
0x006C, 1, 0x40, // MMR3
0x0021, 1, 0x02, // INIT
0x00A3, 1, 0x40, // LMR1
0xFFFF
};
static void /* macro wWordAMD */
WriteWordAmd7930(struct IsdnCardState *cs, BYTE reg, WORD val)
{
wByteAMD(cs, 0x00, reg);
wByteAMD(cs, 0x01, LOBYTE(val));
wByteAMD(cs, 0x01, HIBYTE(val));
}
static WORD /* macro rWordAMD */
ReadWordAmd7930(struct IsdnCardState *cs, BYTE reg)
{
WORD res;
/* direct access register */
if (reg < 8) {
res = rByteAMD(cs, reg);
res += 256 * rByteAMD(cs, reg);
}
/* indirect access register */
else {
wByteAMD(cs, 0x00, reg);
res = rByteAMD(cs, 0x01);
res += 256 * rByteAMD(cs, 0x01);
}
return (res);
}
static void
Amd7930_ph_command(struct IsdnCardState *cs, u_char command, char *s)
{
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "AMD7930: %s: ph_command 0x%02X", s, command);
cs->dc.amd7930.lmr1 = command;
wByteAMD(cs, 0xA3, command);
}
static BYTE i430States[] = {
// to reset F3 F4 F5 F6 F7 F8 AR from
0x01, 0x02, 0x00, 0x00, 0x00, 0x07, 0x05, 0x00, // init
0x01, 0x02, 0x00, 0x00, 0x00, 0x07, 0x05, 0x00, // reset
0x01, 0x02, 0x00, 0x00, 0x00, 0x09, 0x05, 0x04, // F3
0x01, 0x02, 0x00, 0x00, 0x1B, 0x00, 0x00, 0x00, // F4
0x01, 0x02, 0x00, 0x00, 0x1B, 0x00, 0x00, 0x00, // F5
0x01, 0x03, 0x00, 0x00, 0x00, 0x06, 0x05, 0x00, // F6
0x11, 0x13, 0x00, 0x00, 0x1B, 0x00, 0x15, 0x00, // F7
0x01, 0x03, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, // F8
0x01, 0x03, 0x00, 0x00, 0x00, 0x09, 0x00, 0x0A}; // AR
/* Row init - reset F3 F4 F5 F6 F7 F8 AR */
static BYTE stateHelper[] = { 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
static void
Amd7930_get_state(struct IsdnCardState *cs) {
BYTE lsr = rByteAMD(cs, 0xA1);
cs->dc.amd7930.ph_state = (lsr & 0x7) + 2;
Amd7930_new_ph(cs);
}
static void
Amd7930_new_ph(struct IsdnCardState *cs)
{
u_char index = stateHelper[cs->dc.amd7930.old_state] * 8 + stateHelper[cs->dc.amd7930.ph_state] - 1;
u_char message = i430States[index];
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "AMD7930: new_ph %d, old_ph %d, message %d, index %d",
cs->dc.amd7930.ph_state, cs->dc.amd7930.old_state, message & 0x0f, index);
cs->dc.amd7930.old_state = cs->dc.amd7930.ph_state;
/* abort transmit if nessesary */
if ((message & 0xf0) && (cs->tx_skb)) {
wByteAMD(cs, 0x21, 0xC2);
wByteAMD(cs, 0x21, 0x02);
}
switch (message & 0x0f) {
case (1):
l1_msg(cs, HW_RESET | INDICATION, NULL);
Amd7930_get_state(cs);
break;
case (2): /* init, Card starts in F3 */
l1_msg(cs, HW_DEACTIVATE | CONFIRM, NULL);
break;
case (3):
l1_msg(cs, HW_DEACTIVATE | INDICATION, NULL);
break;
case (4):
l1_msg(cs, HW_POWERUP | CONFIRM, NULL);
Amd7930_ph_command(cs, 0x50, "HW_ENABLE REQUEST");
break;
case (5):
l1_msg(cs, HW_RSYNC | INDICATION, NULL);
break;
case (6):
l1_msg(cs, HW_INFO4_P8 | INDICATION, NULL);
break;
case (7): /* init, Card starts in F7 */
l1_msg(cs, HW_RSYNC | INDICATION, NULL);
l1_msg(cs, HW_INFO4_P8 | INDICATION, NULL);
break;
case (8):
l1_msg(cs, HW_POWERUP | CONFIRM, NULL);
/* fall through */
case (9):
Amd7930_ph_command(cs, 0x40, "HW_ENABLE REQ cleared if set");
l1_msg(cs, HW_RSYNC | INDICATION, NULL);
l1_msg(cs, HW_INFO2 | INDICATION, NULL);
l1_msg(cs, HW_INFO4_P8 | INDICATION, NULL);
break;
case (10):
Amd7930_ph_command(cs, 0x40, "T3 expired, HW_ENABLE REQ cleared");
cs->dc.amd7930.old_state = 3;
break;
case (11):
l1_msg(cs, HW_INFO2 | INDICATION, NULL);
break;
default:
break;
}
}
static void
Amd7930_bh(struct work_struct *work)
{
struct IsdnCardState *cs =
container_of(work, struct IsdnCardState, tqueue);
struct PStack *stptr;
if (test_and_clear_bit(D_CLEARBUSY, &cs->event)) {
if (cs->debug)
debugl1(cs, "Amd7930: bh, D-Channel Busy cleared");
stptr = cs->stlist;
while (stptr != NULL) {
stptr->l1.l1l2(stptr, PH_PAUSE | CONFIRM, NULL);
stptr = stptr->next;
}
}
if (test_and_clear_bit(D_L1STATECHANGE, &cs->event)) {
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "AMD7930: bh, D_L1STATECHANGE");
Amd7930_new_ph(cs);
}
if (test_and_clear_bit(D_RCVBUFREADY, &cs->event)) {
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "AMD7930: bh, D_RCVBUFREADY");
DChannel_proc_rcv(cs);
}
if (test_and_clear_bit(D_XMTBUFREADY, &cs->event)) {
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "AMD7930: bh, D_XMTBUFREADY");
DChannel_proc_xmt(cs);
}
}
static void
Amd7930_empty_Dfifo(struct IsdnCardState *cs, int flag)
{
BYTE stat, der;
BYTE *ptr;
struct sk_buff *skb;
if ((cs->debug & L1_DEB_ISAC) && !(cs->debug & L1_DEB_ISAC_FIFO))
debugl1(cs, "Amd7930: empty_Dfifo");
ptr = cs->rcvbuf + cs->rcvidx;
/* AMD interrupts off */
AmdIrqOff(cs);
/* read D-Channel-Fifo*/
stat = rByteAMD(cs, 0x07); // DSR2
/* while Data in Fifo ... */
while ((stat & 2) && ((ptr-cs->rcvbuf) < MAX_DFRAME_LEN_L1)) {
*ptr = rByteAMD(cs, 0x04); // DCRB
ptr++;
stat = rByteAMD(cs, 0x07); // DSR2
cs->rcvidx = ptr - cs->rcvbuf;
/* Paket ready? */
if (stat & 1) {
der = rWordAMD(cs, 0x03);
/* no errors, packet ok */
if (!der && !flag) {
rWordAMD(cs, 0x89); // clear DRCR
if ((cs->rcvidx) > 0) {
if (!(skb = alloc_skb(cs->rcvidx, GFP_ATOMIC)))
printk(KERN_WARNING "HiSax: Amd7930: empty_Dfifo, D receive out of memory!\n");
else {
/* Debugging */
if (cs->debug & L1_DEB_ISAC_FIFO) {
char *t = cs->dlog;
t += sprintf(t, "Amd7930: empty_Dfifo cnt: %d |", cs->rcvidx);
QuickHex(t, cs->rcvbuf, cs->rcvidx);
debugl1(cs, cs->dlog);
}
/* moves received data in sk-buffer */
memcpy(skb_put(skb, cs->rcvidx), cs->rcvbuf, cs->rcvidx);
skb_queue_tail(&cs->rq, skb);
}
}
}
/* throw damaged packets away, reset receive-buffer, indicate RX */
ptr = cs->rcvbuf;
cs->rcvidx = 0;
schedule_event(cs, D_RCVBUFREADY);
}
}
/* Packet to long, overflow */
if (cs->rcvidx >= MAX_DFRAME_LEN_L1) {
if (cs->debug & L1_DEB_WARN)
debugl1(cs, "AMD7930: empty_Dfifo L2-Framelength overrun");
cs->rcvidx = 0;
return;
}
/* AMD interrupts on */
AmdIrqOn(cs);
}
static void
Amd7930_fill_Dfifo(struct IsdnCardState *cs)
{
WORD dtcrr, dtcrw, len, count;
BYTE txstat, dmr3;
BYTE *ptr, *deb_ptr;
if ((cs->debug & L1_DEB_ISAC) && !(cs->debug & L1_DEB_ISAC_FIFO))
debugl1(cs, "Amd7930: fill_Dfifo");
if ((!cs->tx_skb) || (cs->tx_skb->len <= 0))
return;
dtcrw = 0;
if (!cs->dc.amd7930.tx_xmtlen)
/* new Frame */
len = dtcrw = cs->tx_skb->len;
/* continue frame */
else len = cs->dc.amd7930.tx_xmtlen;
/* AMD interrupts off */
AmdIrqOff(cs);
deb_ptr = ptr = cs->tx_skb->data;
/* while free place in tx-fifo available and data in sk-buffer */
txstat = 0x10;
while ((txstat & 0x10) && (cs->tx_cnt < len)) {
wByteAMD(cs, 0x04, *ptr);
ptr++;
cs->tx_cnt++;
txstat = rByteAMD(cs, 0x07);
}
count = ptr - cs->tx_skb->data;
skb_pull(cs->tx_skb, count);
dtcrr = rWordAMD(cs, 0x85); // DTCR
dmr3 = rByteAMD(cs, 0x8E);
if (cs->debug & L1_DEB_ISAC) {
debugl1(cs, "Amd7930: fill_Dfifo, DMR3: 0x%02X, DTCR read: 0x%04X write: 0x%02X 0x%02X", dmr3, dtcrr, LOBYTE(dtcrw), HIBYTE(dtcrw));
}
/* writeing of dtcrw starts transmit */
if (!cs->dc.amd7930.tx_xmtlen) {
wWordAMD(cs, 0x85, dtcrw);
cs->dc.amd7930.tx_xmtlen = dtcrw;
}
if (test_and_set_bit(FLG_DBUSY_TIMER, &cs->HW_Flags)) {
debugl1(cs, "Amd7930: fill_Dfifo dbusytimer running");
del_timer(&cs->dbusytimer);
}
init_timer(&cs->dbusytimer);
cs->dbusytimer.expires = jiffies + ((DBUSY_TIMER_VALUE * HZ) / 1000);
add_timer(&cs->dbusytimer);
if (cs->debug & L1_DEB_ISAC_FIFO) {
char *t = cs->dlog;
t += sprintf(t, "Amd7930: fill_Dfifo cnt: %d |", count);
QuickHex(t, deb_ptr, count);
debugl1(cs, cs->dlog);
}
/* AMD interrupts on */
AmdIrqOn(cs);
}
void Amd7930_interrupt(struct IsdnCardState *cs, BYTE irflags)
{
BYTE dsr1, dsr2, lsr;
WORD der;
while (irflags)
{
dsr1 = rByteAMD(cs, 0x02);
der = rWordAMD(cs, 0x03);
dsr2 = rByteAMD(cs, 0x07);
lsr = rByteAMD(cs, 0xA1);
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "Amd7930: interrupt: flags: 0x%02X, DSR1: 0x%02X, DSR2: 0x%02X, LSR: 0x%02X, DER=0x%04X", irflags, dsr1, dsr2, lsr, der);
/* D error -> read DER and DSR2 bit 2 */
if (der || (dsr2 & 4)) {
if (cs->debug & L1_DEB_WARN)
debugl1(cs, "Amd7930: interrupt: D error DER=0x%04X", der);
/* RX, TX abort if collision detected */
if (der & 2) {
wByteAMD(cs, 0x21, 0xC2);
wByteAMD(cs, 0x21, 0x02);
if (test_and_clear_bit(FLG_DBUSY_TIMER, &cs->HW_Flags))
del_timer(&cs->dbusytimer);
if (test_and_clear_bit(FLG_L1_DBUSY, &cs->HW_Flags))
schedule_event(cs, D_CLEARBUSY);
/* restart frame */
if (cs->tx_skb) {
skb_push(cs->tx_skb, cs->tx_cnt);
cs->tx_cnt = 0;
cs->dc.amd7930.tx_xmtlen = 0;
Amd7930_fill_Dfifo(cs);
} else {
printk(KERN_WARNING "HiSax: Amd7930 D-Collision, no skb\n");
debugl1(cs, "Amd7930: interrupt: D-Collision, no skb");
}
}
/* remove damaged data from fifo */
Amd7930_empty_Dfifo(cs, 1);
if (test_and_clear_bit(FLG_DBUSY_TIMER, &cs->HW_Flags))
del_timer(&cs->dbusytimer);
if (test_and_clear_bit(FLG_L1_DBUSY, &cs->HW_Flags))
schedule_event(cs, D_CLEARBUSY);
/* restart TX-Frame */
if (cs->tx_skb) {
skb_push(cs->tx_skb, cs->tx_cnt);
cs->tx_cnt = 0;
cs->dc.amd7930.tx_xmtlen = 0;
Amd7930_fill_Dfifo(cs);
}
}
/* D TX FIFO empty -> fill */
if (irflags & 1) {
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "Amd7930: interrupt: clear Timer and fill D-TX-FIFO if data");
/* AMD interrupts off */
AmdIrqOff(cs);
if (test_and_clear_bit(FLG_DBUSY_TIMER, &cs->HW_Flags))
del_timer(&cs->dbusytimer);
if (test_and_clear_bit(FLG_L1_DBUSY, &cs->HW_Flags))
schedule_event(cs, D_CLEARBUSY);
if (cs->tx_skb) {
if (cs->tx_skb->len)
Amd7930_fill_Dfifo(cs);
}
/* AMD interrupts on */
AmdIrqOn(cs);
}
/* D RX FIFO full or tiny packet in Fifo -> empty */
if ((irflags & 2) || (dsr1 & 2)) {
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "Amd7930: interrupt: empty D-FIFO");
Amd7930_empty_Dfifo(cs, 0);
}
/* D-Frame transmit complete */
if (dsr1 & 64) {
if (cs->debug & L1_DEB_ISAC) {
debugl1(cs, "Amd7930: interrupt: transmit packet ready");
}
/* AMD interrupts off */
AmdIrqOff(cs);
if (test_and_clear_bit(FLG_DBUSY_TIMER, &cs->HW_Flags))
del_timer(&cs->dbusytimer);
if (test_and_clear_bit(FLG_L1_DBUSY, &cs->HW_Flags))
schedule_event(cs, D_CLEARBUSY);
if (cs->tx_skb) {
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "Amd7930: interrupt: TX-Packet ready, freeing skb");
dev_kfree_skb_irq(cs->tx_skb);
cs->tx_cnt = 0;
cs->dc.amd7930.tx_xmtlen = 0;
cs->tx_skb = NULL;
}
if ((cs->tx_skb = skb_dequeue(&cs->sq))) {
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "Amd7930: interrupt: TX-Packet ready, next packet dequeued");
cs->tx_cnt = 0;
cs->dc.amd7930.tx_xmtlen = 0;
Amd7930_fill_Dfifo(cs);
}
else
schedule_event(cs, D_XMTBUFREADY);
/* AMD interrupts on */
AmdIrqOn(cs);
}
/* LIU status interrupt -> read LSR, check statechanges */
if (lsr & 0x38) {
/* AMD interrupts off */
AmdIrqOff(cs);
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "Amd: interrupt: LSR=0x%02X, LIU is in state %d", lsr, ((lsr & 0x7) + 2));
cs->dc.amd7930.ph_state = (lsr & 0x7) + 2;
schedule_event(cs, D_L1STATECHANGE);
/* AMD interrupts on */
AmdIrqOn(cs);
}
/* reads Interrupt-Register again. If there is a new interrupt-flag: restart handler */
irflags = rByteAMD(cs, 0x00);
}
}
static void
Amd7930_l1hw(struct PStack *st, int pr, void *arg)
{
struct IsdnCardState *cs = (struct IsdnCardState *) st->l1.hardware;
struct sk_buff *skb = arg;
u_long flags;
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "Amd7930: l1hw called, pr: 0x%04X", pr);
switch (pr) {
case (PH_DATA | REQUEST):
if (cs->debug & DEB_DLOG_HEX)
LogFrame(cs, skb->data, skb->len);
if (cs->debug & DEB_DLOG_VERBOSE)
dlogframe(cs, skb, 0);
spin_lock_irqsave(&cs->lock, flags);
if (cs->tx_skb) {
skb_queue_tail(&cs->sq, skb);
#ifdef L2FRAME_DEBUG /* psa */
if (cs->debug & L1_DEB_LAPD)
Logl2Frame(cs, skb, "Amd7930: l1hw: PH_DATA Queued", 0);
#endif
} else {
cs->tx_skb = skb;
cs->tx_cnt = 0;
cs->dc.amd7930.tx_xmtlen = 0;
#ifdef L2FRAME_DEBUG /* psa */
if (cs->debug & L1_DEB_LAPD)
Logl2Frame(cs, skb, "Amd7930: l1hw: PH_DATA", 0);
#endif
Amd7930_fill_Dfifo(cs);
}
spin_unlock_irqrestore(&cs->lock, flags);
break;
case (PH_PULL | INDICATION):
spin_lock_irqsave(&cs->lock, flags);
if (cs->tx_skb) {
if (cs->debug & L1_DEB_WARN)
debugl1(cs, "Amd7930: l1hw: l2l1 tx_skb exist this shouldn't happen");
skb_queue_tail(&cs->sq, skb);
spin_unlock_irqrestore(&cs->lock, flags);
break;
}
if (cs->debug & DEB_DLOG_HEX)
LogFrame(cs, skb->data, skb->len);
if (cs->debug & DEB_DLOG_VERBOSE)
dlogframe(cs, skb, 0);
cs->tx_skb = skb;
cs->tx_cnt = 0;
cs->dc.amd7930.tx_xmtlen = 0;
#ifdef L2FRAME_DEBUG /* psa */
if (cs->debug & L1_DEB_LAPD)
Logl2Frame(cs, skb, "Amd7930: l1hw: PH_DATA_PULLED", 0);
#endif
Amd7930_fill_Dfifo(cs);
spin_unlock_irqrestore(&cs->lock, flags);
break;
case (PH_PULL | REQUEST):
#ifdef L2FRAME_DEBUG /* psa */
if (cs->debug & L1_DEB_LAPD)
debugl1(cs, "Amd7930: l1hw: -> PH_REQUEST_PULL, skb: %s", (cs->tx_skb) ? "yes" : "no");
#endif
if (!cs->tx_skb) {
test_and_clear_bit(FLG_L1_PULL_REQ, &st->l1.Flags);
st->l1.l1l2(st, PH_PULL | CONFIRM, NULL);
} else
test_and_set_bit(FLG_L1_PULL_REQ, &st->l1.Flags);
break;
case (HW_RESET | REQUEST):
spin_lock_irqsave(&cs->lock, flags);
if ((cs->dc.amd7930.ph_state == 8)) {
/* b-channels off, PH-AR cleared
* change to F3 */
Amd7930_ph_command(cs, 0x20, "HW_RESET REQUEST"); //LMR1 bit 5
spin_unlock_irqrestore(&cs->lock, flags);
} else {
Amd7930_ph_command(cs, 0x40, "HW_RESET REQUEST");
cs->dc.amd7930.ph_state = 2;
spin_unlock_irqrestore(&cs->lock, flags);
Amd7930_new_ph(cs);
}
break;
case (HW_ENABLE | REQUEST):
cs->dc.amd7930.ph_state = 9;
Amd7930_new_ph(cs);
break;
case (HW_INFO3 | REQUEST):
// automatic
break;
case (HW_TESTLOOP | REQUEST):
/* not implemented yet */
break;
case (HW_DEACTIVATE | RESPONSE):
skb_queue_purge(&cs->rq);
skb_queue_purge(&cs->sq);
if (cs->tx_skb) {
dev_kfree_skb(cs->tx_skb);
cs->tx_skb = NULL;
}
if (test_and_clear_bit(FLG_DBUSY_TIMER, &cs->HW_Flags))
del_timer(&cs->dbusytimer);
if (test_and_clear_bit(FLG_L1_DBUSY, &cs->HW_Flags))
schedule_event(cs, D_CLEARBUSY);
break;
default:
if (cs->debug & L1_DEB_WARN)
debugl1(cs, "Amd7930: l1hw: unknown %04x", pr);
break;
}
}
static void
setstack_Amd7930(struct PStack *st, struct IsdnCardState *cs)
{
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "Amd7930: setstack called");
st->l1.l1hw = Amd7930_l1hw;
}
static void
DC_Close_Amd7930(struct IsdnCardState *cs) {
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "Amd7930: DC_Close called");
}
static void
dbusy_timer_handler(struct IsdnCardState *cs)
{
u_long flags;
struct PStack *stptr;
WORD dtcr, der;
BYTE dsr1, dsr2;
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "Amd7930: dbusy_timer expired!");
if (test_bit(FLG_DBUSY_TIMER, &cs->HW_Flags)) {
spin_lock_irqsave(&cs->lock, flags);
/* D Transmit Byte Count Register:
* Counts down packet's number of Bytes, 0 if packet ready */
dtcr = rWordAMD(cs, 0x85);
dsr1 = rByteAMD(cs, 0x02);
dsr2 = rByteAMD(cs, 0x07);
der = rWordAMD(cs, 0x03);
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "Amd7930: dbusy_timer_handler: DSR1=0x%02X, DSR2=0x%02X, DER=0x%04X, cs->tx_skb->len=%u, tx_stat=%u, dtcr=%u, cs->tx_cnt=%u", dsr1, dsr2, der, cs->tx_skb->len, cs->dc.amd7930.tx_xmtlen, dtcr, cs->tx_cnt);
if ((cs->dc.amd7930.tx_xmtlen - dtcr) < cs->tx_cnt) { /* D-Channel Busy */
test_and_set_bit(FLG_L1_DBUSY, &cs->HW_Flags);
stptr = cs->stlist;
spin_unlock_irqrestore(&cs->lock, flags);
while (stptr != NULL) {
stptr->l1.l1l2(stptr, PH_PAUSE | INDICATION, NULL);
stptr = stptr->next;
}
} else {
/* discard frame; reset transceiver */
test_and_clear_bit(FLG_DBUSY_TIMER, &cs->HW_Flags);
if (cs->tx_skb) {
dev_kfree_skb_any(cs->tx_skb);
cs->tx_cnt = 0;
cs->tx_skb = NULL;
cs->dc.amd7930.tx_xmtlen = 0;
} else {
printk(KERN_WARNING "HiSax: Amd7930: D-Channel Busy no skb\n");
debugl1(cs, "Amd7930: D-Channel Busy no skb");
}
/* Transmitter reset, abort transmit */
wByteAMD(cs, 0x21, 0x82);
wByteAMD(cs, 0x21, 0x02);
spin_unlock_irqrestore(&cs->lock, flags);
cs->irq_func(cs->irq, cs);
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "Amd7930: dbusy_timer_handler: Transmitter reset");
}
}
}
void Amd7930_init(struct IsdnCardState *cs)
{
WORD *ptr;
BYTE cmd, cnt;
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "Amd7930: initamd called");
cs->dc.amd7930.tx_xmtlen = 0;
cs->dc.amd7930.old_state = 0;
cs->dc.amd7930.lmr1 = 0x40;
cs->dc.amd7930.ph_command = Amd7930_ph_command;
cs->setstack_d = setstack_Amd7930;
cs->DC_Close = DC_Close_Amd7930;
/* AMD Initialisation */
for (ptr = initAMD; *ptr != 0xFFFF; ) {
cmd = LOBYTE(*ptr);
/* read */
if (*ptr++ >= 0x100) {
if (cmd < 8)
/* reset register */
rByteAMD(cs, cmd);
else {
wByteAMD(cs, 0x00, cmd);
for (cnt = *ptr++; cnt > 0; cnt--)
rByteAMD(cs, 0x01);
}
}
/* write */
else if (cmd < 8)
wByteAMD(cs, cmd, LOBYTE(*ptr++));
else {
wByteAMD(cs, 0x00, cmd);
for (cnt = *ptr++; cnt > 0; cnt--)
wByteAMD(cs, 0x01, LOBYTE(*ptr++));
}
}
}
void setup_Amd7930(struct IsdnCardState *cs)
{
INIT_WORK(&cs->tqueue, Amd7930_bh);
cs->dbusytimer.function = (void *) dbusy_timer_handler;
cs->dbusytimer.data = (long) cs;
init_timer(&cs->dbusytimer);
}
| {
"pile_set_name": "Github"
} |
package main
import (
"github.com/pquerna/otp"
"github.com/pquerna/otp/totp"
"bufio"
"bytes"
"encoding/base32"
"fmt"
"image/png"
"io/ioutil"
"os"
"time"
)
func display(key *otp.Key, data []byte) {
fmt.Printf("Issuer: %s\n", key.Issuer())
fmt.Printf("Account Name: %s\n", key.AccountName())
fmt.Printf("Secret: %s\n", key.Secret())
fmt.Println("Writing PNG to qr-code.png....")
ioutil.WriteFile("qr-code.png", data, 0644)
fmt.Println("")
fmt.Println("Please add your TOTP to your OTP Application now!")
fmt.Println("")
}
func promptForPasscode() string {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter Passcode: ")
text, _ := reader.ReadString('\n')
return text
}
// Demo function, not used in main
// Generates Passcode using a UTF-8 (not base32) secret and custom paramters
func GeneratePassCode(utf8string string) string{
secret := base32.StdEncoding.EncodeToString([]byte(utf8string))
passcode, err := totp.GenerateCodeCustom(secret, time.Now(), totp.ValidateOpts{
Period: 30,
Skew: 1,
Digits: otp.DigitsSix,
Algorithm: otp.AlgorithmSHA512,
})
if err != nil {
panic(err)
}
return passcode
}
func main() {
key, err := totp.Generate(totp.GenerateOpts{
Issuer: "Example.com",
AccountName: "[email protected]",
})
if err != nil {
panic(err)
}
// Convert TOTP key into a PNG
var buf bytes.Buffer
img, err := key.Image(200, 200)
if err != nil {
panic(err)
}
png.Encode(&buf, img)
// display the QR code to the user.
display(key, buf.Bytes())
// Now Validate that the user's successfully added the passcode.
fmt.Println("Validating TOTP...")
passcode := promptForPasscode()
valid := totp.Validate(passcode, key.Secret())
if valid {
println("Valid passcode!")
os.Exit(0)
} else {
println("Invalid passcode!")
os.Exit(1)
}
}
| {
"pile_set_name": "Github"
} |
'use strict'
var path = require('path')
var fs = require('graceful-fs')
var mkdirp = require('mkdirp')
var rimraf = require('rimraf')
var test = require('tap').test
var requireInject = require('require-inject')
require('../common-tap.js')
var base = path.join(__dirname, path.basename(__filename, '.js'))
var baseJSON = {
name: 'base',
version: '1.0.0',
repository: {
type: 'git',
url: 'http://example.com'
},
scripts: {
prepublish: 'false'
}
}
var lastOpened
var npm = requireInject.installGlobally('../../lib/npm.js', {
'../../lib/utils/lifecycle.js': function (pkg, stage, wd, moreOpts, cb) {
if (typeof moreOpts === 'function') {
cb = moreOpts
}
cb(new Error("Shouldn't be calling lifecycle scripts"))
},
opener: function (url, options, cb) {
lastOpened = {url: url, options: options}
cb()
}
})
test('setup', function (t) {
cleanup()
setup()
t.end()
})
test('repo', function (t) {
process.chdir(base)
npm.load({browser: 'echo'}, function () {
npm.commands.repo([], function (err) {
t.ifError(err, 'no errors')
t.match(lastOpened.url, baseJSON.repository.url, 'opened the right url')
t.is(lastOpened.options.command, 'echo', 'opened with a specified browser')
t.end()
})
})
})
test('cleanup', function (t) {
cleanup()
t.end()
})
function saveJson (pkgPath, json) {
mkdirp.sync(pkgPath)
fs.writeFileSync(path.join(pkgPath, 'package.json'), JSON.stringify(json, null, 2))
}
function setup () {
saveJson(base, baseJSON)
}
function cleanup () {
rimraf.sync(base)
}
| {
"pile_set_name": "Github"
} |
from Screens.Screen import Screen
from Components.ConfigList import ConfigListScreen
from Components.config import config, getConfigListEntry
from Components.Sources.StaticText import StaticText
class HdmiCECSetupScreen(Screen, ConfigListScreen):
skin = """
<screen position="c-300,c-250" size="600,500" title="HDMI-CEC setup">
<widget name="config" position="25,25" size="550,350" />
<widget source="current_address" render="Label" position="25,375" size="550,30" zPosition="10" font="Regular;21" halign="left" valign="center" />
<widget source="fixed_address" render="Label" position="25,405" size="550,30" zPosition="10" font="Regular;21" halign="left" valign="center" />
<ePixmap pixmap="buttons/red.png" position="20,e-45" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/green.png" position="160,e-45" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/yellow.png" position="300,e-45" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/blue.png" position="440,e-45" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="20,e-45" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="160,e-45" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget source="key_yellow" render="Label" position="300,e-45" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
<widget source="key_blue" render="Label" position="440,e-45" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
</screen>"""
def __init__(self, session):
self.skin = HdmiCECSetupScreen.skin
Screen.__init__(self, session)
self.setTitle(_("HDMI-CEC setup"))
from Components.ActionMap import ActionMap
from Components.Button import Button
self["key_red"] = StaticText(_("Cancel"))
self["key_green"] = StaticText(_("OK"))
self["key_yellow"] = StaticText(_("Set fixed"))
self["key_blue"] = StaticText(_("Clear fixed"))
self["current_address"] = StaticText()
self["fixed_address"] = StaticText()
self["actions"] = ActionMap(["SetupActions", "ColorActions", "MenuActions"],
{
"ok": self.keyOk,
"save": self.keyGo,
"cancel": self.keyCancel,
"green": self.keyGo,
"red": self.keyCancel,
"yellow": self.setFixedAddress,
"blue": self.clearFixedAddress,
"menu": self.closeRecursive,
}, -2)
self.list = []
self.logpath_entry = None
ConfigListScreen.__init__(self, self.list, session = self.session)
self.createSetup()
self.updateAddress()
def createSetup(self):
self.list = []
self.list.append(getConfigListEntry(_("Enabled"), config.hdmicec.enabled))
if config.hdmicec.enabled.value:
self.list.append(getConfigListEntry(_("Put TV in standby"), config.hdmicec.control_tv_standby))
self.list.append(getConfigListEntry(_("Wakeup TV from standby"), config.hdmicec.control_tv_wakeup))
self.list.append(getConfigListEntry(_("Regard deep standby as standby"), config.hdmicec.handle_deepstandby_events))
self.list.append(getConfigListEntry(_("Switch TV to correct input"), config.hdmicec.report_active_source))
self.list.append(getConfigListEntry(_("Use TV remote control"), config.hdmicec.report_active_menu))
self.list.append(getConfigListEntry(_("Handle standby from TV"), config.hdmicec.handle_tv_standby))
self.list.append(getConfigListEntry(_("Handle wakeup from TV"), config.hdmicec.handle_tv_wakeup))
self.list.append(getConfigListEntry(_("Wakeup signal from TV"), config.hdmicec.tv_wakeup_detection))
self.list.append(getConfigListEntry(_("Forward volume keys"), config.hdmicec.volume_forwarding))
self.list.append(getConfigListEntry(_("Put receiver in standby"), config.hdmicec.control_receiver_standby))
self.list.append(getConfigListEntry(_("Wakeup receiver from standby"), config.hdmicec.control_receiver_wakeup))
self.list.append(getConfigListEntry(_("Minimum send interval"), config.hdmicec.minimum_send_interval))
self.list.append(getConfigListEntry(_("Repeat leave standby messages"), config.hdmicec.repeat_wakeup_timer))
self.list.append(getConfigListEntry(_("Send 'sourceactive' before zap timers"), config.hdmicec.sourceactive_zaptimers))
self.list.append(getConfigListEntry(_("Detect next boxes before standby"), config.hdmicec.next_boxes_detect))
self.list.append(getConfigListEntry(_("Debug to file"), config.hdmicec.debug))
self.logpath_entry = getConfigListEntry(_("Select path for logfile"), config.hdmicec.log_path)
if config.hdmicec.debug.value != "0":
self.list.append(self.logpath_entry)
self["config"].list = self.list
self["config"].l.setList(self.list)
def keyLeft(self):
ConfigListScreen.keyLeft(self)
self.createSetup()
def keyRight(self):
ConfigListScreen.keyRight(self)
self.createSetup()
def keyGo(self):
for x in self["config"].list:
x[1].save()
self.close()
def keyCancel(self):
for x in self["config"].list:
x[1].cancel()
self.close()
def keyOk(self):
currentry = self["config"].getCurrent()
if currentry == self.logpath_entry:
self.set_path()
else:
self.keyGo()
def setFixedAddress(self):
import Components.HdmiCec
Components.HdmiCec.hdmi_cec.setFixedPhysicalAddress(Components.HdmiCec.hdmi_cec.getPhysicalAddress())
self.updateAddress()
def clearFixedAddress(self):
import Components.HdmiCec
Components.HdmiCec.hdmi_cec.setFixedPhysicalAddress("0.0.0.0")
self.updateAddress()
def updateAddress(self):
import Components.HdmiCec
self["current_address"].setText(_("Current CEC address") + ": " + Components.HdmiCec.hdmi_cec.getPhysicalAddress())
if config.hdmicec.fixed_physical_address.value == "0.0.0.0":
fixedaddresslabel = ""
else:
fixedaddresslabel = _("Using fixed address") + ": " + config.hdmicec.fixed_physical_address.value
self["fixed_address"].setText(fixedaddresslabel)
def logPath(self, res):
if res is not None:
config.hdmicec.log_path.value = res
def set_path(self):
inhibitDirs = ["/autofs", "/bin", "/boot", "/dev", "/etc", "/lib", "/proc", "/sbin", "/sys", "/tmp", "/usr"]
from Screens.LocationBox import LocationBox
txt = _("Select directory for logfile")
self.session.openWithCallback(self.logPath, LocationBox, text=txt, currDir=config.hdmicec.log_path.value,
bookmarks=config.hdmicec.bookmarks, autoAdd=False, editDir=True,
inhibitDirs=inhibitDirs, minFree=1
)
def main(session, **kwargs):
session.open(HdmiCECSetupScreen)
def startSetup(menuid):
# only show in the menu when set to intermediate or higher
if menuid == "video" and config.av.videoport.value == "DVI" and config.usage.setup_level.index >= 1:
return [(_("HDMI-CEC setup"), main, "hdmi_cec_setup", 0)]
return []
def Plugins(**kwargs):
from os import path
if path.exists("/dev/hdmi_cec") or path.exists("/dev/misc/hdmi_cec0"):
import Components.HdmiCec
from Plugins.Plugin import PluginDescriptor
return [PluginDescriptor(where = PluginDescriptor.WHERE_MENU, fnc = startSetup)]
return []
| {
"pile_set_name": "Github"
} |
#include <zookeeper.h>
#include <sys/fcntl.h>
#include <string>
#include "gtest/gtest.h"
#include "qconf_zoo.h"
#include "qconf_const.h"
#include "qconf_format.h"
using namespace std;
#define MAX_NODE_NUM 20
//unit test case for qconf_zk.cc
static int children_node_cmp(const void* p1, const void* p2);
static void zoo_create_or_set(zhandle_t *zh, const string path, const string value);
static void create_string_vector(string_vector_t *nodes, size_t count, bool serv_flg = false);
static void global_watcher(zhandle_t* zh, int type, int state, const char* path, void* context);
//Related test environment set up 1:
class Test_qconf_zk : public :: testing::Test
{
protected:
virtual void SetUp()
{
// init zookeeper handler
const char* host = "127.0.0.1:2181";
zh = zookeeper_init(host, global_watcher, QCONF_ZK_DEFAULT_RECV_TIMEOUT, NULL, NULL, 0);
zoo_create_or_set(zh, "/qconf", "qconf");
zoo_create_or_set(zh, "/qconf/__unit_test", "unit test");
}
virtual void TearDown()
{
zookeeper_close(zh);
}
zhandle_t *zh;
};
static void global_watcher(zhandle_t* zh, int type, int state, const char* path, void* context)
{
//to do something
}
/**
* ========================================================================================================
* Begin_Test_for function: int zk_get_chdnodes(zhandle_t *zh, const string &path, string_vector_t &nodes)
*/
// Test for zk_get_chdnodes : zh is null
TEST_F(Test_qconf_zk, zk_get_chdnodes_null_zh)
{
int ret = 0;
string path;
string_vector_t nodes;
ret = zk_get_chdnodes(NULL, path, nodes);
EXPECT_EQ(QCONF_ERR_PARAM, ret);
}
// Test for zk_get_chdnodes : path is empty
TEST_F(Test_qconf_zk, zk_get_chdnodes_empty_path)
{
int ret = 0;
string path;
string_vector_t nodes;
ret = zk_get_chdnodes(zh, path, nodes);
EXPECT_EQ(QCONF_ERR_PARAM, ret);
}
// Test for zk_get_chdnodes : path does not exist
TEST_F(Test_qconf_zk, zk_get_chdnodes_not_exist_path)
{
int ret = 0;
string path = "/qconf/__unit_test/not_exist_path";
string_vector_t nodes;
ret = zk_get_chdnodes(zh, path, nodes);
EXPECT_EQ(QCONF_NODE_NOT_EXIST, ret);
}
// Test for zk_get_chdnodes : path is illegal value
TEST_F(Test_qconf_zk, zk_get_chdnodes_illegal_path)
{
int ret = 0;
string path = "qconf/__unit_test/not_exist_path";
string_vector_t nodes;
ret = zk_get_chdnodes(zh, path, nodes);
EXPECT_EQ(QCONF_ERR_ZOO_FAILED, ret);
}
// Test for zk_get_chdnodes : zero child
TEST_F(Test_qconf_zk, zk_get_chdnodes_zero_child)
{
int ret = 0;
string path = "/qconf/__unit_test/zero_child";
string value("zero child");
string_vector_t nodes;
zoo_create(zh, path.c_str(), value.c_str(), value.size(), &ZOO_OPEN_ACL_UNSAFE, 0, NULL, 0);
ret = zk_get_chdnodes(zh, path, nodes);
EXPECT_EQ(QCONF_OK, ret);
EXPECT_EQ(0, nodes.count);
}
// Test for zk_get_chdnodes : 10 children
TEST_F(Test_qconf_zk, zk_get_chdnodes_10_children)
{
int ret = 0;
string path = "/qconf/__unit_test/10_child";
string value("10 child");
string_vector_t nodes;
string_vector_t ret_nodes;
size_t chd_count = 10;
create_string_vector(&nodes, chd_count);
zoo_create(zh, path.c_str(), value.c_str(), value.size(), &ZOO_OPEN_ACL_UNSAFE, 0, NULL, 0);
for (int i = 0; i < nodes.count; ++i)
{
string child_path = path + "/" + nodes.data[i];
zoo_create(zh, child_path.c_str(), value.c_str(), value.size(), &ZOO_OPEN_ACL_UNSAFE, 0, NULL, 0);
}
ret = zk_get_chdnodes(zh, path, ret_nodes);
EXPECT_EQ(QCONF_OK, ret);
EXPECT_EQ(nodes.count, ret_nodes.count);
for (int i = 0; i < ret_nodes.count; ++i)
{
EXPECT_STREQ(nodes.data[i], ret_nodes.data[i]);
}
free_string_vector(nodes, nodes.count);
free_string_vector(ret_nodes, ret_nodes.count);
}
// Test for zk_get_chdnodes : 100 children
TEST_F(Test_qconf_zk, zk_get_chdnodes_100_children)
{
int ret = 0;
string path = "/qconf/__unit_test/100_child";
string value("100 child");
string_vector_t nodes;
string_vector_t ret_nodes;
size_t chd_count = 100;
create_string_vector(&nodes, chd_count);
zoo_create(zh, path.c_str(), value.c_str(), value.size(), &ZOO_OPEN_ACL_UNSAFE, 0, NULL, 0);
for (int i = 0; i < nodes.count; ++i)
{
string child_path = path + "/" + nodes.data[i];
zoo_create(zh, child_path.c_str(), value.c_str(), value.size(), &ZOO_OPEN_ACL_UNSAFE, 0, NULL, 0);
}
ret = zk_get_chdnodes(zh, path, ret_nodes);
EXPECT_EQ(QCONF_OK, ret);
EXPECT_EQ(nodes.count, ret_nodes.count);
qsort(nodes.data, nodes.count, sizeof(char*), children_node_cmp);
for (int i = 0; i < ret_nodes.count; ++i)
{
EXPECT_STREQ(nodes.data[i], ret_nodes.data[i]);
}
free_string_vector(nodes, nodes.count);
free_string_vector(ret_nodes, ret_nodes.count);
}
static int children_node_cmp(const void* p1, const void* p2)
{
char **s1 = (char**)p1;
char **s2 = (char**)p2;
return strcmp(*s1, *s2);
}
static void create_string_vector(string_vector_t *nodes, size_t count, bool serv_flg)
{
char tmp[1024] = {0};
memset(nodes, 0, sizeof(string_vector_t));
nodes->data = (char**)malloc(sizeof(char*) * count);
assert(NULL != nodes->data);
nodes->count = count;
for (int i = 0; i < nodes->count; ++i)
{
ssize_t len = 0;
if (serv_flg)
{
len = snprintf(tmp, sizeof(tmp), "10.10.10.10:1%d", i);
}
else
{
len = snprintf(tmp, sizeof(tmp), "child_num_%d", i);
}
nodes->data[i] = (char*) calloc(len + 1, sizeof(char));
assert(NULL != nodes->data[i]);
memcpy(nodes->data[i], tmp, len);
}
}
/**
* End_Test_for function: int zk_get_chdnodes(zhandle_t *zh, const string &path, string_vector_t &nodes)
* =========================================================================================================
*/
/**
* ========================================================================================================
* Begin_Test_for function:
* int zk_get_chdnodes_with_status(zhandle_t *zh, const string &path, string_vector_t &nodes, vector<char> &status)
*/
// Test for zk_get_chdnodes_with_status : zh is null
TEST_F(Test_qconf_zk, zk_get_chdnodes_with_status_null_zh)
{
int ret = 0;
string path;
string_vector_t nodes;
vector<char> status;
ret = zk_get_chdnodes_with_status(NULL, path, nodes, status);
EXPECT_EQ(QCONF_ERR_PARAM, ret);
}
// Test for zk_get_chdnodes_with_status : path is empty
TEST_F(Test_qconf_zk, zk_get_chdnodes_with_status_empty_path)
{
int ret = 0;
string path;
string_vector_t nodes;
vector<char> status;
ret = zk_get_chdnodes_with_status(zh, path, nodes, status);
EXPECT_EQ(QCONF_ERR_PARAM, ret);
}
// Test for zk_get_chdnodes_with_status : path does not exist
TEST_F(Test_qconf_zk, zk_get_chdnodes_with_status_not_exist_path)
{
int ret = 0;
vector<char> status;
string_vector_t nodes;
string path = "/qconf/__unit_test/not_exist_path";
ret = zk_get_chdnodes_with_status(zh, path, nodes, status);
EXPECT_EQ(QCONF_NODE_NOT_EXIST, ret);
}
// Test for zk_get_chdnodes_with_status : path is illegal value
TEST_F(Test_qconf_zk, zk_get_chdnodes_with_status_illegal_path)
{
int ret = 0;
vector<char> status;
string_vector_t nodes;
string path = "qconf/__unit_test/not_exist_path";
ret = zk_get_chdnodes_with_status(zh, path, nodes, status);
EXPECT_EQ(QCONF_ERR_ZOO_FAILED, ret);
}
// Test for zk_get_chdnodes_with_status : zero servs
TEST_F(Test_qconf_zk, zk_get_chdnodes_with_status_zero_serv)
{
int ret = 0;
string_vector_t nodes;
string value("zero service");
string path = "/qconf/__unit_test/zero_service";
vector<char> status;
zoo_create(zh, path.c_str(), value.c_str(), value.size(), &ZOO_OPEN_ACL_UNSAFE, 0, NULL, 0);
ret = zk_get_chdnodes_with_status(zh, path, nodes, status);
EXPECT_EQ(QCONF_OK, ret);
EXPECT_EQ(0, nodes.count);
}
// Test for zk_get_chdnodes_with_status : 10 services with 10 down
TEST_F(Test_qconf_zk, zk_get_chdnodes_with_status_10_servs_all_down)
{
int ret = 0;
string_vector_t nodes;
size_t chd_count = 10;
string_vector_t ret_nodes;
string value("10 services");
string path = "/qconf/__unit_test/10_servs";
vector<char> status;
vector<char> ret_status;
create_string_vector(&nodes, chd_count, true);
for (int i = 0; i < nodes.count; ++i)
{
status.push_back(STATUS_DOWN);
}
zoo_create(zh, path.c_str(), value.c_str(), value.size(), &ZOO_OPEN_ACL_UNSAFE, 0, NULL, 0);
for (int i = 0; i < nodes.count; ++i)
{
string child_path = path + "/" + nodes.data[i];
zoo_create_or_set(zh, child_path, string(1, status[i] + '0'));
}
ret = zk_get_chdnodes_with_status(zh, path, ret_nodes, ret_status);
EXPECT_EQ(QCONF_OK, ret);
EXPECT_EQ(nodes.count, ret_nodes.count);
for (int i = 0; i < ret_nodes.count; ++i)
{
EXPECT_STREQ(nodes.data[i], ret_nodes.data[i]);
EXPECT_EQ(status[i], ret_status[i]);
}
free_string_vector(nodes, nodes.count);
free_string_vector(ret_nodes, ret_nodes.count);
}
// Test for zk_get_chdnodes_with_status : 10 services with 5 down and 5 up
TEST_F(Test_qconf_zk, zk_get_chdnodes_with_status_10_servs_half_down)
{
int ret = 0;
string_vector_t nodes;
size_t chd_count = 10;
string_vector_t ret_nodes;
string value("10 services");
string path = "/qconf/__unit_test/10_servs";
vector<char> status;
vector<char> ret_status;
create_string_vector(&nodes, chd_count, true);
for (int i = 0; i < nodes.count; ++i)
{
status.push_back(i % 2 == 0 ? STATUS_DOWN : STATUS_UP);
}
zoo_create(zh, path.c_str(), value.c_str(), value.size(), &ZOO_OPEN_ACL_UNSAFE, 0, NULL, 0);
for (int i = 0; i < nodes.count; ++i)
{
string child_path = path + "/" + nodes.data[i];
zoo_create_or_set(zh, child_path, string(1, status[i] + '0'));
}
ret = zk_get_chdnodes_with_status(zh, path, ret_nodes, ret_status);
EXPECT_EQ(QCONF_OK, ret);
EXPECT_EQ(nodes.count, ret_nodes.count);
for (int i = 0; i < ret_nodes.count; ++i)
{
EXPECT_STREQ(nodes.data[i], ret_nodes.data[i]);
EXPECT_EQ(status[i], ret_status[i]);
}
free_string_vector(nodes, nodes.count);
free_string_vector(ret_nodes, ret_nodes.count);
}
// Test for zk_get_chdnodes_with_status : 10 services with 5 offline and 5 up
TEST_F(Test_qconf_zk, zk_get_chdnodes_with_status_10_servs_half_offline)
{
int ret = 0;
string_vector_t nodes;
size_t chd_count = 10;
string_vector_t ret_nodes;
string value("10 services");
string path = "/qconf/__unit_test/10_servs";
vector<char> status;
vector<char> ret_status;
create_string_vector(&nodes, chd_count, true);
for (int i = 0; i < nodes.count; ++i)
{
status.push_back(i % 2 == 0 ? STATUS_UP : STATUS_OFFLINE);
}
zoo_create(zh, path.c_str(), value.c_str(), value.size(), &ZOO_OPEN_ACL_UNSAFE, 0, NULL, 0);
for (int i = 0; i < nodes.count; ++i)
{
string child_path = path + "/" + nodes.data[i];
zoo_create_or_set(zh, child_path, string(1, status[i] + '0'));
}
ret = zk_get_chdnodes_with_status(zh, path, ret_nodes, ret_status);
EXPECT_EQ(QCONF_OK, ret);
EXPECT_EQ(nodes.count, ret_nodes.count);
for (int i = 0; i < ret_nodes.count; ++i)
{
EXPECT_STREQ(nodes.data[i], ret_nodes.data[i]);
EXPECT_EQ(status[i], ret_status[i]);
}
free_string_vector(nodes, nodes.count);
free_string_vector(ret_nodes, ret_nodes.count);
}
// Test for zk_get_chdnodes_with_status : 10 services with 10 up
TEST_F(Test_qconf_zk, zk_get_chdnodes_with_status_10_servs_all_up)
{
int ret = 0;
string_vector_t nodes;
size_t chd_count = 10;
string_vector_t ret_nodes;
string value("10 services");
string path = "/qconf/__unit_test/10_servs";
vector<char> status;
vector<char> ret_status;
create_string_vector(&nodes, chd_count, true);
for (int i = 0; i < nodes.count; ++i)
{
status.push_back(STATUS_UP);
}
zoo_create(zh, path.c_str(), value.c_str(), value.size(), &ZOO_OPEN_ACL_UNSAFE, 0, NULL, 0);
for (int i = 0; i < nodes.count; ++i)
{
string child_path = path + "/" + nodes.data[i];
zoo_create_or_set(zh, child_path, string(1, status[i] + '0'));
}
ret = zk_get_chdnodes_with_status(zh, path, ret_nodes, ret_status);
EXPECT_EQ(QCONF_OK, ret);
EXPECT_EQ(nodes.count, ret_nodes.count);
for (int i = 0; i < ret_nodes.count; ++i)
{
EXPECT_STREQ(nodes.data[i], ret_nodes.data[i]);
EXPECT_EQ(status[i], ret_status[i]);
}
free_string_vector(nodes, nodes.count);
free_string_vector(ret_nodes, ret_nodes.count);
}
static void zoo_create_or_set(zhandle_t *zh, const string path, const string value)
{
int ret = zoo_exists(zh, path.c_str(), 0, NULL);
if (ZOK == ret)
{
zoo_set(zh, path.c_str(), value.c_str(), value.size(), -1);
}
else if (ZNONODE == ret)
{
zoo_create(zh, path.c_str(), value.c_str(), value.size(), &ZOO_OPEN_ACL_UNSAFE, 0, NULL, 0);
}
}
/**
* End_Test_for function:
* int zk_get_chdnodes_with_status(zhandle_t *zh, const string &path, string_vector_t &nodes, vector<char> &status)
* =========================================================================================================
*/
/**
* ========================================================================================================
* Begin_Test_for function:
* int zk_get_node(zhandle_t *zh, const string &path, string &buf)
*/
// Test for zk_get_node: node not exists
TEST_F(Test_qconf_zk, zk_get_node_not_exists)
{
int ret = 0;
string path = "/qconf/__unit_test/untest";
string buf;
ret = zk_get_node(zh, path, buf, 0);
EXPECT_EQ(QCONF_NODE_NOT_EXIST, ret);
}
// Test for zk_get_node: bad arguments
TEST_F(Test_qconf_zk, zk_get_node_bad_arguments)
{
int ret = 0;
string path = "test/bad/args";
string buf;
ret = zk_get_node(zh, path, buf, 0);
EXPECT_EQ(QCONF_ERR_ZOO_FAILED, ret);
}
// Test for zk_get_node: node exists
TEST_F(Test_qconf_zk, zk_get_node_exists)
{
int ret = 0;
string path = "/qconf/__unit_test/test";
string value = "hello good";
string buf;
zoo_create(zh, path.c_str(), value.c_str(), value.size(), &ZOO_OPEN_ACL_UNSAFE, 0, NULL, 0);
ret = zk_get_node(zh, path, buf, 0);
EXPECT_EQ(QCONF_OK, ret);
EXPECT_STREQ(value.c_str(), buf.c_str());
}
// Test for zk_get_node: node val = empty
TEST_F(Test_qconf_zk, zk_get_node_with_empty_val)
{
int ret = 0;
string path("/qconf/__unit_test/nullval");
string buf;
zoo_create(zh, path.c_str(), NULL, 0, &ZOO_OPEN_ACL_UNSAFE, 0, NULL, 0);
ret = zk_get_node(zh, path, buf, 0);
EXPECT_EQ(QCONF_OK, ret);
EXPECT_STREQ("", buf.c_str());
}
// Test for zk_get_node: length of node : 1K
TEST_F(Test_qconf_zk, zk_get_node_with_1k_val)
{
string buf;
int ret = 0;
string path("/qconf/__unit_test/1k");
string value(1024, 'a');
zoo_create(zh, path.c_str(), value.c_str(), value.size(), &ZOO_OPEN_ACL_UNSAFE, 0, NULL, 0);
ret = zk_get_node(zh, path, buf, 0);
EXPECT_EQ(QCONF_OK, ret);
EXPECT_STREQ(value.c_str(), buf.c_str());
}
// Test for zk_get_node: length of node : 10k
TEST_F(Test_qconf_zk, zk_get_node_with_10k_val)
{
string buf;
int ret = 0;
string path("/qconf/__unit_test/10k");
string value(10240, 'a');
zoo_create(zh, path.c_str(), value.c_str(), value.size(), &ZOO_OPEN_ACL_UNSAFE, 0, NULL, 0);
ret = zk_get_node(zh, path, buf, 0);
EXPECT_EQ(QCONF_OK, ret);
EXPECT_STREQ(value.c_str(), buf.c_str());
}
// Test for zk_get_node: length of node : 100k
TEST_F(Test_qconf_zk, zk_get_node_with_100k_val)
{
string buf;
int ret = 0;
string path("/qconf/__unit_test/100k");
string value(10240, 'a');
zoo_create(zh, path.c_str(), value.c_str(), value.size(), &ZOO_OPEN_ACL_UNSAFE, 0, NULL, 0);
ret = zk_get_node(zh, path, buf, 0);
EXPECT_EQ(QCONF_OK, ret);
EXPECT_STREQ(value.c_str(), buf.c_str());
}
// Test for zk_get_node: length of node : 1m
TEST_F(Test_qconf_zk, zk_get_node_with_1m_val)
{
string buf;
int ret = 0;
string path("/qconf/__unit_test/1m");
string value(1000000, 'a');
zoo_create(zh, path.c_str(), value.c_str(), value.size(), &ZOO_OPEN_ACL_UNSAFE, 0, NULL, 0);
ret = zk_get_node(zh, path, buf, 0);
EXPECT_EQ(QCONF_OK, ret);
EXPECT_STREQ(value.c_str(), buf.c_str());
}
/**
* End_Test_for function:
* int zk_get_node(zhandle_t *zh, const string &path, string &buf)
* =========================================================================================================
*/
/**
* ========================================================================================================
* Begin_Test_for function:
* int zk_create_node(zhandle_t *zh, const string &path, const string &value, int flags)
*/
// Test for zk_create_node: parent not exists
TEST_F(Test_qconf_zk, zk_create_node_parent_not_exists)
{
int ret = 0;
string path = "/qconf/111/tst_create_no";
string value("hello");
ret = zk_create_node(zh, path, value, 0);
EXPECT_EQ(QCONF_ERR_ZOO_FAILED, ret);
}
// Test for zk_create_node: node not exists
TEST_F(Test_qconf_zk, zk_create_node_not_exists)
{
int ret = 0;
string path = "/qconf/__unit_test/tst_create_no";
string buf;
string value("hello");
ret = zk_create_node(zh, path, value, 0);
EXPECT_EQ(QCONF_OK, ret);
ret = zk_get_node(zh, path, buf, 0);
EXPECT_EQ(QCONF_OK, ret);
EXPECT_STREQ(value.c_str(), buf.c_str());
ret = zoo_delete(zh, path.c_str(), -1);
EXPECT_EQ(ret, ZOK);
}
// Test for zk_create_node: node exists
TEST_F(Test_qconf_zk, zk_create_node_exists)
{
int ret = 0;
string path = "/qconf/__unit_test/tst_create";
string value = "hello good";
ret = zk_create_node(zh, path, value, 0);
EXPECT_EQ(QCONF_NODE_EXIST, ret);
}
// Test for zk_create_node: node val = empty
TEST_F(Test_qconf_zk, zk_create_node_with_empty_val)
{
int ret = 0;
string path("/qconf/__unit_test/tst_create_nullval");
string buf;
ret = zk_create_node(zh, path, "", 0);
EXPECT_EQ(QCONF_OK, ret);
ret = zk_get_node(zh, path, buf, 0);
EXPECT_EQ(QCONF_OK, ret);
EXPECT_STREQ("", buf.c_str());
ret = zoo_delete(zh, path.c_str(), -1);
EXPECT_EQ(ret, ZOK);
}
// Test for zk_create_node: length of node : 1K
TEST_F(Test_qconf_zk, zk_create_node_with_1k_val)
{
string buf;
int ret = 0;
string path("/qconf/__unit_test/test_create_1k");
string value(1024, 'a');
ret = zk_create_node(zh, path, value, 0);
EXPECT_EQ(QCONF_OK, ret);
ret = zk_get_node(zh, path, buf, 0);
EXPECT_EQ(QCONF_OK, ret);
EXPECT_STREQ(value.c_str(), buf.c_str());
ret = zoo_delete(zh, path.c_str(), -1);
EXPECT_EQ(ret, ZOK);
}
/**
* End_Test_for function:
* int zk_create_node(zhandle_t *zh, const string &path, string &buf)
* =========================================================================================================
*/
/**
* ===============================================================================================
* Begin_Test_for function:
* int zk_register_ephemeral(zhandle_t *zh, const string &path, const string &value)
*/
// Test for zk_register_ephemeral: zh=NULL
TEST_F(Test_qconf_zk, zk_register_ephemeral_null_zh)
{
int ret = 0;
string path = "/qconf/__unit_test/test";
const char* val = "hello";
ret = zk_register_ephemeral(NULL, path, val);
EXPECT_EQ(QCONF_ERR_PARAM, ret);
}
// Test for zk_register_ephemeral: path=NULL
TEST_F(Test_qconf_zk, zk_register_ephemeral_empty_path)
{
int ret = 0;
const char* val = "hello";
string path;
ret = zk_register_ephemeral(zh, path, val);
EXPECT_EQ(QCONF_ERR_PARAM, ret);
}
// Test for zk_register_ephemeral: value=NULL
TEST_F(Test_qconf_zk, zk_register_ephemeral_empty_value)
{
int ret = 0;
string path = "/qconf/test";
string value;
ret = zk_register_ephemeral(zh, path, value);
EXPECT_EQ(QCONF_ERR_PARAM, ret);
}
// Test for zk_register_ephemeral: invalid path
TEST_F(Test_qconf_zk, zk_register_ephemeral_invalid_path)
{
int ret = 0;
string path = "qconf/test";
const char* val = "hello";
ret = zk_register_ephemeral(zh, path, val);
EXPECT_EQ(QCONF_ERR_ZOO_FAILED, ret);
}
// Test for zk_register_ephemeral: path="/qconf"
TEST_F(Test_qconf_zk, zk_register_ephemeral_path_with_one_delim)
{
int ret = 0;
string path = "/qconf/__qconf_register_hosts";
const char* val = "hello";
string buf;
char hostname[256] = {0};
string path_buf;
ret = gethostname(hostname, sizeof(hostname));
EXPECT_EQ(0, ret);
path_buf = path + "/" + hostname + "-" + hostname;
ret = zk_register_ephemeral(zh, path_buf, val);
zk_get_node(zh, path_buf, buf, 0);
EXPECT_EQ(QCONF_OK, ret);
EXPECT_EQ(5, buf.size());
EXPECT_STREQ("hello", buf.c_str());
}
/**
* End_Test_for function:
* int zk_register_ephemeral(zhandle_t *zh, const string &path, const string &value)
* =========================================================================================================
*/
/**
* ========================================================================================================
* Begin_Test_for function:
* int qconf_init_zoo_log(const string &log_dir, const string &zoo_log)
*/
// Test for qconf_init_zoo_log: log_dir empty
TEST_F(Test_qconf_zk, qconf_init_zoo_log_empty_log_dir)
{
string log_dir;
string zoo_log;
int ret = qconf_init_zoo_log(log_dir, zoo_log);
EXPECT_EQ(QCONF_ERR_PARAM, ret);
}
// Test for qconf_init_zoo_log: zoo_log empty
TEST_F(Test_qconf_zk, qconf_init_zoo_log_empty_zoo_log)
{
string log_dir(".");
string zoo_log;
int ret = qconf_init_zoo_log(log_dir, zoo_log);
EXPECT_EQ(QCONF_ERR_PARAM, ret);
}
// Test for qconf_init_zoo_log: log dir not exist
TEST_F(Test_qconf_zk, qconf_init_zoo_log_unexist_log_dir)
{
string log_dir("/unexist_log_dir");
string zoo_log("zoo_err.log");
int ret = qconf_init_zoo_log(log_dir, zoo_log);
EXPECT_EQ(QCONF_ERR_FAILED_OPEN_FILE, ret);
}
// Test for qconf_init_zoo_log: zoo log not exist
TEST_F(Test_qconf_zk, qconf_init_zoo_log_unexist_zoo_log)
{
string log_dir("./logs");
string zoo_log("zoo_err.log");
mode_t mode = 0755;
mkdir(log_dir.c_str(), mode);
string path = log_dir + "/" + zoo_log;
unlink(path.c_str());
int ret = qconf_init_zoo_log(log_dir, zoo_log);
EXPECT_EQ(QCONF_OK, ret);
}
// Test for qconf_init_zoo_log: zoo log exist
TEST_F(Test_qconf_zk, qconf_init_zoo_log_exist_zoo_log)
{
string log_dir("./logs");
string zoo_log("zoo_err.log");
mode_t mode = 0755;
mkdir(log_dir.c_str(), mode);
string path = log_dir + "/" + zoo_log;
int fd = open(path.c_str(), O_RDWR | O_CREAT, mode);
assert(fd > 0);
close(fd);
int ret = qconf_init_zoo_log(log_dir, zoo_log);
EXPECT_EQ(QCONF_OK, ret);
}
/**
* End_Test_for function:
* int qconf_init_zoo_log(const string &log_dir, const string &zoo_log)
* =========================================================================================================
*/
//End_Test_for qconf_zk.c
| {
"pile_set_name": "Github"
} |
using Server.Network;
using System;
namespace Server.Items
{
public enum SawTrapType
{
WestWall,
NorthWall,
WestFloor,
NorthFloor
}
public class SawTrap : BaseTrap
{
[Constructable]
public SawTrap()
: this(SawTrapType.NorthFloor)
{
}
[Constructable]
public SawTrap(SawTrapType type)
: base(GetBaseID(type))
{
}
public SawTrap(Serial serial)
: base(serial)
{
}
[CommandProperty(AccessLevel.GameMaster)]
public SawTrapType Type
{
get
{
switch (ItemID)
{
case 0x1103:
return SawTrapType.NorthWall;
case 0x1116:
return SawTrapType.WestWall;
case 0x11AC:
return SawTrapType.NorthFloor;
case 0x11B1:
return SawTrapType.WestFloor;
}
return SawTrapType.NorthWall;
}
set
{
ItemID = GetBaseID(value);
}
}
public override bool PassivelyTriggered => false;
public override TimeSpan PassiveTriggerDelay => TimeSpan.Zero;
public override int PassiveTriggerRange => 0;
public override TimeSpan ResetDelay => TimeSpan.FromSeconds(0.0);
public static int GetBaseID(SawTrapType type)
{
switch (type)
{
case SawTrapType.NorthWall:
return 0x1103;
case SawTrapType.WestWall:
return 0x1116;
case SawTrapType.NorthFloor:
return 0x11AC;
case SawTrapType.WestFloor:
return 0x11B1;
}
return 0;
}
public override void OnTrigger(Mobile from)
{
if (!from.Alive || from.IsStaff())
return;
Effects.SendLocationEffect(Location, Map, GetBaseID(Type) + 1, 6, 3, GetEffectHue(), 0);
Effects.PlaySound(Location, Map, 0x21C);
Spells.SpellHelper.Damage(TimeSpan.FromTicks(1), from, from, Utility.RandomMinMax(5, 15));
from.LocalOverheadMessage(MessageType.Regular, 0x22, 500853); // You stepped onto a blade trap!
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write(0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
} | {
"pile_set_name": "Github"
} |
easyblock = "Toolchain"
name = 'iomkl'
version = '2015.03'
homepage = 'http://software.intel.com/en-us/intel-cluster-toolkit-compiler/'
description = """Intel Cluster Toolchain Compiler Edition provides Intel C/C++ and Fortran compilers, Intel MKL &
OpenMPI."""
toolchain = SYSTEM
compver = '2015.3.187-GNU-4.9.3-2.25'
dependencies = [
('icc', compver),
('ifort', compver),
('OpenMPI', '1.8.8', '', ('iccifort', compver)),
('imkl', '11.2.3.187', '', ('iompi', version)),
]
moduleclass = 'toolchain'
| {
"pile_set_name": "Github"
} |
// mksyscall.pl syscall_bsd.go syscall_darwin.go syscall_darwin_arm.go
// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
// +build arm,darwin
package unix
import (
"syscall"
"unsafe"
)
var _ syscall.Errno
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func setgroups(ngid int, gid *_Gid_t) (err error) {
_, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) {
r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0)
wpid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) {
r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
_, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
_, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func socket(domain int, typ int, proto int) (fd int, err error) {
r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) {
_, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) {
_, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) {
_, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) {
_, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Shutdown(s int, how int) (err error) {
_, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) {
_, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) {
r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) {
r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
var _p0 unsafe.Pointer
if len(mib) > 0 {
_p0 = unsafe.Pointer(&mib[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
use(_p0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func utimes(path string, timeval *[2]Timeval) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func futimes(fd int, timeval *[2]Timeval) (err error) {
_, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func fcntl(fd int, cmd int, arg int) (val int, err error) {
r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg))
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) {
_, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func pipe() (r int, w int, err error) {
r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0)
r = int(r0)
w = int(r1)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func kill(pid int, signum int, posix int) (err error) {
_, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), uintptr(posix))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Access(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
_, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chdir(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chflags(path string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chmod(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chown(path string, uid int, gid int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid))
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chroot(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Close(fd int) (err error) {
_, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Dup(fd int) (nfd int, err error) {
r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
nfd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Dup2(from int, to int) (err error) {
_, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Exchangedata(path1 string, path2 string, options int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path1)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(path2)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_EXCHANGEDATA, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options))
use(unsafe.Pointer(_p0))
use(unsafe.Pointer(_p1))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Exit(code int) {
Syscall(SYS_EXIT, uintptr(code), 0, 0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchdir(fd int) (err error) {
_, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchflags(fd int, flags int) (err error) {
_, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchmod(fd int, mode uint32) (err error) {
_, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchown(fd int, uid int, gid int) (err error) {
_, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Flock(fd int, how int) (err error) {
_, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fpathconf(fd int, name int) (val int, err error) {
r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fstat(fd int, stat *Stat_t) (err error) {
_, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fstatfs(fd int, stat *Statfs_t) (err error) {
_, _, e1 := Syscall(SYS_FSTATFS64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fsync(fd int) (err error) {
_, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Ftruncate(fd int, length int64) (err error) {
_, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_GETDIRENTRIES64, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getdtablesize() (size int) {
r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0)
size = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getegid() (egid int) {
r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0)
egid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Geteuid() (uid int) {
r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
uid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getgid() (gid int) {
r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0)
gid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpgid(pid int) (pgid int, err error) {
r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0)
pgid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpgrp() (pgrp int) {
r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
pgrp = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpid() (pid int) {
r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0)
pid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getppid() (ppid int) {
r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0)
ppid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpriority(which int, who int) (prio int, err error) {
r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0)
prio = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getrlimit(which int, lim *Rlimit) (err error) {
_, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getrusage(who int, rusage *Rusage) (err error) {
_, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getsid(pid int) (sid int, err error) {
r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0)
sid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getuid() (uid int) {
r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0)
uid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Issetugid() (tainted bool) {
r0, _, _ := RawSyscall(SYS_ISSETUGID, 0, 0, 0)
tainted = bool(r0 != 0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Kqueue() (fd int, err error) {
r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Lchown(path string, uid int, gid int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid))
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Link(path string, link string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(link)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
use(unsafe.Pointer(_p0))
use(unsafe.Pointer(_p1))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Listen(s int, backlog int) (err error) {
_, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Lstat(path string, stat *Stat_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdir(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkfifo(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mknod(path string, mode uint32, dev int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mlock(b []byte) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mlockall(flags int) (err error) {
_, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mprotect(b []byte, prot int) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Munlock(b []byte) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Munlockall() (err error) {
_, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Open(path string, mode int, perm uint32) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
use(unsafe.Pointer(_p0))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pathconf(path string, name int) (val int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
use(unsafe.Pointer(_p0))
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pread(fd int, p []byte, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pwrite(fd int, p []byte, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func read(fd int, p []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Readlink(path string, buf []byte) (n int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 unsafe.Pointer
if len(buf) > 0 {
_p1 = unsafe.Pointer(&buf[0])
} else {
_p1 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)))
use(unsafe.Pointer(_p0))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Rename(from string, to string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(from)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(to)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
use(unsafe.Pointer(_p0))
use(unsafe.Pointer(_p1))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Revoke(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Rmdir(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence))
newoffset = int64(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
_, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setegid(egid int) (err error) {
_, _, e1 := Syscall(SYS_SETEGID, uintptr(egid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Seteuid(euid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setgid(gid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setlogin(name string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(name)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setpgid(pid int, pgid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setpriority(which int, who int, prio int) (err error) {
_, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setprivexec(flag int) (err error) {
_, _, e1 := Syscall(SYS_SETPRIVEXEC, uintptr(flag), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setregid(rgid int, egid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setreuid(ruid int, euid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setrlimit(which int, lim *Rlimit) (err error) {
_, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setsid() (pid int, err error) {
r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0)
pid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Settimeofday(tp *Timeval) (err error) {
_, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setuid(uid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Stat(path string, stat *Stat_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Statfs(path string, stat *Statfs_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Symlink(path string, link string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(link)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
use(unsafe.Pointer(_p0))
use(unsafe.Pointer(_p1))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Sync() (err error) {
_, _, e1 := Syscall(SYS_SYNC, 0, 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Truncate(path string, length int64) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Umask(newmask int) (oldmask int) {
r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
oldmask = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Undelete(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Unlink(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Unmount(path string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func write(fd int, p []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos))
ret = uintptr(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func munmap(addr uintptr, length uintptr) (err error) {
_, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func readlen(fd int, buf *byte, nbuf int) (n int, err error) {
r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func writelen(fd int, buf *byte, nbuf int) (n int, err error) {
r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func gettimeofday(tp *Timeval) (sec int32, usec int32, err error) {
r0, r1, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
sec = int32(r0)
usec = int32(r1)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
| {
"pile_set_name": "Github"
} |
OpenSSL Native Nuget package
-------------------------
Uses [CoApp](http://coapp.org/) project to build the zlib package.
Prerequisites
-------------
Multiple versions of VS installed to be able to build all the targets:
* Visual Studio 2015
* Visual Studio 2013
* Visual Studio 2010 (you might need SP1 to prevent LNK1123 error)
ActivePerl
CoApp toolkit: http://downloads.coapp.org/files/CoApp.Tools.Powershell.msi
More details on installation: http://coapp.org/tutorials/installation.html
Building
--------
Build all flavors of openssl library using the provided batch file.
```
buildall.bat
```
Then, create NuGet package using powershell (you'll need the CoApp toolkit installed):
```
[THIS_DIRECTORY]> Write-NuGetPackage grpc.dependencies.openssl.autopkg
```
This will create three NuGet packages:
* the main dev package
* the redistributable package that contains just the binaries and no headers
* the symbols package (debug symbols)
Later, you can push the package to NuGet.org repo.
Attention: before pusing the resulting nuget package to public nuget repo, you have to be 100% sure it works correctly - there’s no way how to delete or update an already existing package. | {
"pile_set_name": "Github"
} |
.clearfix:before,
.clearfix:after,
.navbar:before,
.navbar:after,
.navbar-header:before,
.navbar-header:after {
content: " ";
display: table;
}
.clearfix:after,
.navbar:after,
.navbar-header:after {
clear: both;
}
.center-block {
display: block;
margin-left: auto;
margin-right: auto;
}
.pull-right {
float: right !important;
}
.pull-left {
float: left !important;
}
.hide {
display: none !important;
}
.show {
display: block !important;
}
.invisible {
visibility: hidden;
}
.text-hide {
font: 0/0 a;
color: transparent;
text-shadow: none;
background-color: transparent;
border: 0;
}
.hidden {
display: none !important;
visibility: hidden !important;
}
.affix {
position: fixed;
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
/* general styles */
a,
button {
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
}
a i.fa,
button i.fa {
margin: 0 5px;
}
.clickable {
cursor: pointer !important;
}
.required {
color: #955251;
}
.accent {
color: #955251;
}
.text-uppercase {
text-transform: uppercase;
letter-spacing: 0.08em;
}
@media (max-width: 991px) {
.text-center-sm {
text-align: center;
}
}
p.lead {
margin-bottom: 40px;
}
section,
div.section {
margin-bottom: 40px;
}
.no-mb {
margin-bottom: 0 !important;
}
.mb-small {
margin-bottom: 20px !important;
}
.heading {
margin-bottom: 40px;
}
.heading h1,
.heading h2,
.heading h3,
.heading h4,
.heading h5 {
display: inline-block;
border-bottom: solid 5px #955251;
line-height: 1.1;
margin-bottom: 0;
padding-bottom: 10px;
vertical-align: middle;
text-transform: uppercase;
letter-spacing: 0.06em;
}
.heading h1 i.fa,
.heading h2 i.fa,
.heading h3 i.fa,
.heading h4 i.fa,
.heading h5 i.fa {
display: inline-block;
background: #955251;
width: 30px;
height: 30px;
vertical-align: middle;
text-align: center;
color: #fff;
font-size: 12px;
line-height: 30px;
border-radius: 15px;
}
.icon {
display: inline-block;
width: 80px;
height: 80px;
color: #fff;
line-height: 80px;
border-radius: 40px;
border: solid 1px #fff;
font-size: 20px;
}
.icon.icon-lg {
font-size: 30px;
border-width: 2px;
}
.ul-icons {
padding-left: 10px;
}
.ul-icons li {
list-style-type: none;
line-height: 20px;
margin-bottom: 20px;
}
.ul-icons li i {
width: 20px;
height: 20px;
background: #955251;
color: #fff;
text-align: center;
border-radius: 10px;
line-height: 20px;
margin-right: 10px;
}
ul.list-style-none {
list-style: none;
}
#text-page h1,
#text-page h2,
#text-page h3 {
font-weight: 700;
}
#error-page {
text-align: center;
margin-top: 40px;
margin-bottom: 100px;
}
#error-page h4 {
margin-bottom: 40px;
}
#error-page p.buttons {
margin-top: 40px;
}
.pages-listing .item {
text-align: center;
}
.pages-listing .item h3 {
font-size: 18px;
text-transform: uppercase;
margin-bottom: 20px;
letter-spacing: 0.08em;
}
.pages-listing .item h3 a {
color: #555555;
}
.pages-listing .item .text {
margin-bottom: 20px;
}
.pages-listing .item .text p {
color: #999999;
font-size: 12px;
margin-bottom: 20px;
}
.banner {
margin-bottom: 30px;
text-align: center;
}
.banner img {
margin: 0 auto;
}
.banner a:hover img {
opacity: 0.8;
filter: alpha(opacity=80);
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
}
.pages {
text-align: center;
}
.pages .loadMore {
text-align: center;
}
.pages .pagination {
text-align: center;
}
.features-buttons button {
margin-bottom: 20px;
}
@media (min-width: 1300px) {
body.boxed {
background: url(http://subtlepatterns.com/patterns/subtle_zebra_3d.png);
}
body.boxed #all {
position: relative;
background: #fff;
width: 1200px;
margin: 0 auto;
overflow: hidden;
-webkit-box-shadow: 0 0 5px #cccccc;
box-shadow: 0 0 5px #cccccc;
}
}
#top {
background: #555555;
color: #eeeeee;
padding: 10px 0;
}
#top p {
margin: 0;
font-size: 12px;
}
#top .social {
float: right;
text-align: right;
}
#top .social a {
color: #999999;
display: inline-block;
width: 24px;
height: 24px;
border-radius: 12px;
line-height: 20px;
font-size: 12px;
text-align: center;
vertical-align: bottom;
}
#top .social a:hover {
color: #fff;
}
#top .social a:hover.facebook {
background-color: #4460ae;
}
#top .social a:hover.gplus {
background-color: #c21f25;
}
#top .social a:hover.twitter {
background-color: #3cf;
}
#top .social a:hover.instagram {
background-color: #cd4378;
}
#top .social a:hover.email {
background-color: #4a7f45;
}
#top .login {
float: right;
}
#top .login a {
font-size: 12px;
color: #eeeeee;
margin-right: 15px;
text-decoration: none;
text-transform: uppercase;
font-weight: 700;
letter-spacing: 0.10em;
}
@media (max-width: 767px) {
#top .login {
float: left;
}
}
#top.light {
background: #fff;
color: #999999;
border-bottom: solid 1px #eeeeee;
}
#top.light .login a {
color: #555555;
}
.navbar {
border: none;
}
.navbar ul.nav > li > a {
text-transform: uppercase;
text-decoration: underline;
font-weight: bold;
letter-spacing: 0.08em;
border-top: solid 5px transparent;
}
.navbar ul.nav > li > a:hover {
border-top: solid 5px #955251;
}
.navbar ul.nav > li.active > a,
.navbar ul.nav > li.open > a {
text-decoration: none !important;
border-top: solid 5px #532e2d;
}
@media (max-width: 768px) {
.navbar ul.nav > li.active > a,
.navbar ul.nav > li.open > a {
border-top-color: transparent;
}
.navbar ul.nav > li > a:hover {
border-top-color: transparent;
}
}
.navbar.navbar-light ul.nav > li.active > a {
border-top: solid 5px #532e2d;
background: #fff !important;
color: #555555 !important;
}
.navbar.navbar-light ul.nav > li.active > a:hover {
border-top: solid 5px #532e2d;
}
.navbar.navbar-light ul.nav > li > a:hover,
.navbar.navbar-light ul.nav > li.open > a:hover,
.navbar.navbar-light ul.nav > li > a:focus,
.navbar.navbar-light ul.nav > li.open > a:focus {
border-top: solid 5px #955251;
background: #fff !important;
color: #555555 !important;
}
.navbar ul.dropdown-menu {
margin: 0;
padding: 0;
}
.navbar ul.dropdown-menu li {
list-style-type: none;
border-bottom: solid 1px #eeeeee;
text-transform: uppercase;
letter-spacing: 0.08em;
padding: 4px 0;
}
.navbar ul.dropdown-menu li a {
position: relative;
color: #999999;
font-size: 12px;
display: block;
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
left: 0;
}
.navbar ul.dropdown-menu li a:hover {
color: #955251;
text-decoration: none;
background: none;
left: 2px;
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
}
@media (max-width: 767px) {
.navbar ul.dropdown-menu li a:hover {
left: 0;
}
}
.navbar .yamm-content h3 {
font-size: 18px;
text-transform: uppercase;
padding-bottom: 10px;
margin-top: 5px;
border-bottom: dotted 1px #555555;
letter-spacing: 0.08em;
}
@media (max-width: 767px) {
.navbar .yamm-content h3 {
font-size: 14px;
}
}
.navbar .yamm-content h5 {
text-transform: uppercase;
padding-bottom: 10px;
border-bottom: dotted 1px #555555;
letter-spacing: 0.08em;
}
.navbar .yamm-content ul {
margin: 0;
padding: 0;
}
.navbar .yamm-content ul li {
list-style-type: none;
border-bottom: solid 1px #eeeeee;
text-transform: uppercase;
padding: 4px 0;
}
.navbar .yamm-content ul li a {
position: relative;
color: #999999;
font-size: 12px;
display: block;
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
}
.navbar .yamm-content ul li a:hover {
color: #955251;
text-decoration: none;
padding-left: 2px;
}
.navbar .yamm-content .banner {
margin-bottom: 10px;
}
.navbar .yamm-fw .dropdown-menu {
padding: 0;
}
.navbar .navbar-buttons {
float: right;
}
.navbar .navbar-buttons button,
.navbar .navbar-buttons a.btn,
.navbar .navbar-buttons .btn-default.navbar-toggle {
margin-top: 11px;
margin-bottom: 11px;
margin-left: 0;
margin-right: 5px;
}
.navbar .btn-default,
.navbar .btn-default.navbar-toggle {
color: #999999;
background-color: #fff;
margin-left: 7px;
margin-right: 0;
}
.navbar .btn-default:hover,
.navbar .btn-default.navbar-toggle:hover,
.navbar .btn-default:focus,
.navbar .btn-default.navbar-toggle:focus {
background-color: #fff;
border-color: #955251;
color: #955251;
}
.navbar #search {
clear: both;
border-top: solid 1px #955251;
text-align: right;
}
.navbar #search form {
float: right;
}
.navbar #search form .input-group {
width: 500px;
}
@media (max-width: 768px) {
.navbar #search form .input-group {
width: 100%;
}
}
.navbar #basket-overview a {
margin-left: 7px;
}
.navbar-affixed-top {
top: -32px;
}
.navbar-affixed-top.affix-top {
-webkit-transition: all 0.5s ease-out;
-moz-transition: all 0.5s ease-out;
transition: all 0.5s ease-out;
}
.navbar-affixed-top.affix {
position: fixed;
width: 100%;
top: 0;
z-index: 1000;
-webkit-box-shadow: 0 0 5px #cccccc;
box-shadow: 0 0 5px #cccccc;
-webkit-transition: all 0.5s ease-out;
-moz-transition: all 0.5s ease-out;
transition: all 0.5s ease-out;
}
body.boxed .navbar-affixed-top.affix {
position: static;
}
#login-modal {
overflow: hidden;
}
#login-modal .modal-header h4 {
text-transform: uppercase;
}
#login-modal form {
margin-bottom: 20px;
}
#login-modal a {
color: #955251;
}
#login-modal p {
font-weight: 300;
margin-bottom: 20px;
font-size: 13px;
}
/* buttons */
.btn {
font-weight: 700;
font-family: "Roboto", Helvetica, Arial, sans-serif;
text-transform: uppercase;
letter-spacing: 0.08em;
padding: 6px 12px;
font-size: 13px;
line-height: 1.42857143;
border-radius: 0;
}
.input-group .btn {
font-size: 14px;
}
.btn-lg {
padding: 10px 16px;
font-size: 14px;
line-height: 1.33;
border-radius: 0;
}
.btn-sm {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 0;
}
.btn-xs {
padding: 1px 5px;
font-size: 12px;
line-height: 1.5;
border-radius: 0;
}
.btn-template-main {
color: #955251;
background-color: #ffffff;
border-color: #955251;
}
.btn-template-main:hover,
.btn-template-main:focus,
.btn-template-main:active,
.btn-template-main.active,
.open > .dropdown-toggle.btn-template-main {
color: #955251;
background-color: #e6e6e6;
border-color: #6d3c3b;
}
.btn-template-main:active,
.btn-template-main.active,
.open > .dropdown-toggle.btn-template-main {
background-image: none;
}
.btn-template-main.disabled,
.btn-template-main[disabled],
fieldset[disabled] .btn-template-main,
.btn-template-main.disabled:hover,
.btn-template-main[disabled]:hover,
fieldset[disabled] .btn-template-main:hover,
.btn-template-main.disabled:focus,
.btn-template-main[disabled]:focus,
fieldset[disabled] .btn-template-main:focus,
.btn-template-main.disabled:active,
.btn-template-main[disabled]:active,
fieldset[disabled] .btn-template-main:active,
.btn-template-main.disabled.active,
.btn-template-main[disabled].active,
fieldset[disabled] .btn-template-main.active {
background-color: #ffffff;
border-color: #955251;
}
.btn-template-main .badge {
color: #ffffff;
background-color: #955251;
}
.btn-template-main:hover,
.btn-template-main:focus,
.btn-template-main:active,
.btn-template-main.active {
background: #955251;
color: #ffffff;
border-color: #955251;
}
.btn-template-transparent-primary {
color: #ffffff;
background-color: transparent;
border-color: #ffffff;
}
.btn-template-transparent-primary:hover,
.btn-template-transparent-primary:focus,
.btn-template-transparent-primary:active,
.btn-template-transparent-primary.active,
.open > .dropdown-toggle.btn-template-transparent-primary {
color: #ffffff;
background-color: rgba(0, 0, 0, 0);
border-color: #e0e0e0;
}
.btn-template-transparent-primary:active,
.btn-template-transparent-primary.active,
.open > .dropdown-toggle.btn-template-transparent-primary {
background-image: none;
}
.btn-template-transparent-primary.disabled,
.btn-template-transparent-primary[disabled],
fieldset[disabled] .btn-template-transparent-primary,
.btn-template-transparent-primary.disabled:hover,
.btn-template-transparent-primary[disabled]:hover,
fieldset[disabled] .btn-template-transparent-primary:hover,
.btn-template-transparent-primary.disabled:focus,
.btn-template-transparent-primary[disabled]:focus,
fieldset[disabled] .btn-template-transparent-primary:focus,
.btn-template-transparent-primary.disabled:active,
.btn-template-transparent-primary[disabled]:active,
fieldset[disabled] .btn-template-transparent-primary:active,
.btn-template-transparent-primary.disabled.active,
.btn-template-transparent-primary[disabled].active,
fieldset[disabled] .btn-template-transparent-primary.active {
background-color: transparent;
border-color: #ffffff;
}
.btn-template-transparent-primary .badge {
color: transparent;
background-color: #ffffff;
}
.btn-template-transparent-primary:hover,
.btn-template-transparent-primary:focus,
.btn-template-transparent-primary:active,
.btn-template-transparent-primary.active {
background: #fff;
color: #955251;
border-color: #fff;
}
.btn-template-transparent-black {
color: #ffffff;
background-color: transparent;
border-color: #ffffff;
}
.btn-template-transparent-black:hover,
.btn-template-transparent-black:focus,
.btn-template-transparent-black:active,
.btn-template-transparent-black.active,
.open > .dropdown-toggle.btn-template-transparent-black {
color: #ffffff;
background-color: rgba(0, 0, 0, 0);
border-color: #e0e0e0;
}
.btn-template-transparent-black:active,
.btn-template-transparent-black.active,
.open > .dropdown-toggle.btn-template-transparent-black {
background-image: none;
}
.btn-template-transparent-black.disabled,
.btn-template-transparent-black[disabled],
fieldset[disabled] .btn-template-transparent-black,
.btn-template-transparent-black.disabled:hover,
.btn-template-transparent-black[disabled]:hover,
fieldset[disabled] .btn-template-transparent-black:hover,
.btn-template-transparent-black.disabled:focus,
.btn-template-transparent-black[disabled]:focus,
fieldset[disabled] .btn-template-transparent-black:focus,
.btn-template-transparent-black.disabled:active,
.btn-template-transparent-black[disabled]:active,
fieldset[disabled] .btn-template-transparent-black:active,
.btn-template-transparent-black.disabled.active,
.btn-template-transparent-black[disabled].active,
fieldset[disabled] .btn-template-transparent-black.active {
background-color: transparent;
border-color: #ffffff;
}
.btn-template-transparent-black .badge {
color: transparent;
background-color: #ffffff;
}
.btn-template-transparent-black:hover,
.btn-template-transparent-black:focus,
.btn-template-transparent-black:active,
.btn-template-transparent-black.active {
background: #fff;
color: #000;
border-color: #fff;
}
.btn-template-primary {
color: #ffffff;
background-color: #955251;
border-color: #955251;
}
.btn-template-primary:hover,
.btn-template-primary:focus,
.btn-template-primary:active,
.btn-template-primary.active,
.open > .dropdown-toggle.btn-template-primary {
color: #ffffff;
background-color: #74403f;
border-color: #6d3c3b;
}
.btn-template-primary:active,
.btn-template-primary.active,
.open > .dropdown-toggle.btn-template-primary {
background-image: none;
}
.btn-template-primary.disabled,
.btn-template-primary[disabled],
fieldset[disabled] .btn-template-primary,
.btn-template-primary.disabled:hover,
.btn-template-primary[disabled]:hover,
fieldset[disabled] .btn-template-primary:hover,
.btn-template-primary.disabled:focus,
.btn-template-primary[disabled]:focus,
fieldset[disabled] .btn-template-primary:focus,
.btn-template-primary.disabled:active,
.btn-template-primary[disabled]:active,
fieldset[disabled] .btn-template-primary:active,
.btn-template-primary.disabled.active,
.btn-template-primary[disabled].active,
fieldset[disabled] .btn-template-primary.active {
background-color: #955251;
border-color: #955251;
}
.btn-template-primary .badge {
color: #955251;
background-color: #ffffff;
}
#intro {
background: url('../img/home.jpg') no-repeat center top;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#intro .item {
font-family: "Roboto", Helvetica, Arial, sans-serif;
height: 100%;
}
#intro .item h1 {
text-transform: uppercase;
font-size: 50px;
color: #fff;
margin-bottom: 40px;
letter-spacing: 0.08em;
}
@media (max-width: 991px) {
#intro .item h1 {
font-size: 40px;
}
}
@media (max-width: 767px) {
#intro .item h1 {
font-size: 25px;
}
}
#intro .item h3 {
color: #fff;
margin-bottom: 40px;
}
@media (max-width: 767px) {
#intro .item h3 {
font-size: 15px;
margin-bottom: 20px;
}
}
#intro .item .btn {
text-transform: none;
}
@media (max-width: 991px) {
#intro .item .btn {
font-size: 14px;
}
}
@media (max-width: 991px) {
#intro .item .carousel-caption {
left: 10%;
right: 10%;
}
}
#intro .container,
#intro .row {
height: 100%;
position: relative;
}
.jumbotron {
padding: 30px;
margin-bottom: 0;
position: relative;
background: url('../img/photogrid.jpg') center center repeat;
background-size: cover;
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
}
.jumbotron .dark-mask {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #955251;
opacity: 0.9;
filter: alpha(opacity=90);
}
.jumbotron h1,
.jumbotron h2,
.jumbotron h3,
.jumbotron p,
.jumbotron ul {
color: #fff;
}
.jumbotron h1,
.jumbotron h2,
.jumbotron h3 {
color: #ffffff;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.jumbotron p {
margin-bottom: 20px;
font-size: 21px;
font-weight: 400;
}
.jumbotron p.text-uppercase {
font-weight: 700;
}
.jumbotron > hr {
border-top-color: #d5d5d5;
}
.container .jumbotron {
border-radius: 0;
}
.jumbotron .container {
max-width: 100%;
z-index: 2;
}
@media screen and (min-width: 768px) {
.jumbotron {
padding-top: 48px;
padding-bottom: 48px;
}
.container .jumbotron {
padding-left: 60px;
padding-right: 60px;
}
.jumbotron h1,
.jumbotron .h1 {
font-size: 46px;
}
}
#categoryMenu h3 {
padding: 20px;
background: #f7f7f7;
margin: 0;
border-bottom: solid 1px #eeeeee;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.panel.sidebar-menu h3 {
padding: 5px 0;
margin: 0;
}
.panel.sidebar-menu {
background: #fff;
margin: 0 0 20px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.panel.sidebar-menu .panel-heading {
text-transform: uppercase;
margin-bottom: 10px;
background: none;
padding: 0;
letter-spacing: 0.08em;
border-bottom: none;
}
.panel.sidebar-menu .panel-heading h1,
.panel.sidebar-menu .panel-heading h2,
.panel.sidebar-menu .panel-heading h3,
.panel.sidebar-menu .panel-heading h4,
.panel.sidebar-menu .panel-heading h5 {
display: inline-block;
border-bottom: solid 5px #955251;
line-height: 1.1;
margin-bottom: 0;
padding-bottom: 10px;
}
.panel.sidebar-menu .panel-heading .btn.btn-danger {
color: #fff;
margin-top: 5px;
}
.panel.sidebar-menu .panel-body {
padding: 0;
}
.panel.sidebar-menu .panel-body span.colour {
display: inline-block;
width: 15px;
height: 15px;
border: solid 1px #555555;
vertical-align: top;
margin-top: 2px;
margin-left: 5px;
}
.panel.sidebar-menu .panel-body span.colour.white {
background: #fff;
}
.panel.sidebar-menu .panel-body span.colour.red {
background: red;
}
.panel.sidebar-menu .panel-body span.colour.green {
background: green;
}
.panel.sidebar-menu .panel-body span.colour.blue {
background: blue;
}
.panel.sidebar-menu .panel-body span.colour.yellow {
background: yellow;
}
.panel.sidebar-menu .panel-body label {
color: #999999;
font-size: 12px;
}
.panel.sidebar-menu .panel-body label:hover {
color: #555555;
}
.panel.sidebar-menu ul.nav.category-menu {
margin-bottom: 20px;
text-transform: uppercase;
font-weight: 700;
letter-spacing: 0.08em;
}
.panel.sidebar-menu ul.nav.category-menu li a {
font-family: "Roboto", Helvetica, Arial, sans-serif;
}
.panel.sidebar-menu ul.nav ul {
list-style: none;
padding-left: 0;
}
.panel.sidebar-menu ul.nav ul li {
display: block;
}
.panel.sidebar-menu ul.nav ul li a {
position: relative;
font-family: "Times New Roman", Times, serif;
font-weight: normal;
text-transform: none !important;
display: block;
padding: 10px 15px;
padding-left: 30px;
font-size: 12px;
color: #999999;
}
.panel.sidebar-menu ul.nav ul li a:hover,
.panel.sidebar-menu ul.nav ul li a:focus {
text-decoration: none;
background-color: #eeeeee;
}
.panel.sidebar-menu ul.tag-cloud {
list-style: none;
padding-left: 0;
}
.panel.sidebar-menu ul.tag-cloud li {
display: inline-block;
}
.panel.sidebar-menu ul.tag-cloud li a {
display: inline-block;
padding: 5px;
border: solid 1px #eeeeee;
border-radius: 0;
color: #955251;
margin: 5px 5px 5px 0;
text-transform: uppercase;
letter-spacing: 0.08em;
font-weight: 700;
font-size: 12px;
}
.panel.sidebar-menu ul.tag-cloud li a:hover {
color: #955251;
text-decoration: none;
border-color: #955251;
}
.panel.sidebar-menu ul.popular,
.panel.sidebar-menu ul.recent {
list-style: none;
padding-left: 0;
padding: 20px 0;
}
.panel.sidebar-menu ul.popular li,
.panel.sidebar-menu ul.recent li {
margin-bottom: 10px;
padding: 5px 0;
border-bottom: dotted 1px #eeeeee;
}
.panel.sidebar-menu ul.popular li:before,
.panel.sidebar-menu ul.recent li:before,
.panel.sidebar-menu ul.popular li:after,
.panel.sidebar-menu ul.recent li:after {
content: " ";
display: table;
}
.panel.sidebar-menu ul.popular li:after,
.panel.sidebar-menu ul.recent li:after {
clear: both;
}
.panel.sidebar-menu ul.popular li:before,
.panel.sidebar-menu ul.recent li:before,
.panel.sidebar-menu ul.popular li:after,
.panel.sidebar-menu ul.recent li:after {
content: " ";
display: table;
}
.panel.sidebar-menu ul.popular li:after,
.panel.sidebar-menu ul.recent li:after {
clear: both;
}
.panel.sidebar-menu ul.popular li img,
.panel.sidebar-menu ul.recent li img {
width: 50px;
margin-right: 10px;
}
.panel.sidebar-menu ul.popular li h5,
.panel.sidebar-menu ul.recent li h5 {
margin: 0 0 10px;
}
.panel.sidebar-menu ul.popular li h5 a,
.panel.sidebar-menu ul.recent li h5 a {
font-weight: normal;
}
.panel.sidebar-menu ul.popular li p.date,
.panel.sidebar-menu ul.recent li p.date {
float: right;
font-size: 12px;
color: #999999;
}
.panel.sidebar-menu ul.popular li:last-child,
.panel.sidebar-menu ul.recent li:last-child {
border-bottom: none;
}
.panel.sidebar-menu .text-widget {
font-size: 12px;
}
.panel.sidebar-menu.with-icons ul.nav li a:after {
font-family: 'FontAwesome';
content: "\f105";
position: relative;
top: 0;
float: right;
}
/* ribbons for product sales etc. */
.ribbon {
position: absolute;
top: 50px;
padding-left: 51px;
font-weight: 700;
letter-spacing: 0.08em;
}
.ribbon .ribbon-background {
position: absolute;
top: 0;
right: 0;
}
.ribbon .theribbon {
position: relative;
width: 80px;
padding: 6px 20px 6px 20px;
margin: 30px 10px 10px -71px;
color: #fff;
background-color: #955251;
font-family: "Roboto", Helvetica, Arial, sans-serif;
}
.ribbon .theribbon:before,
.ribbon .theribbon:after {
content: ' ';
position: absolute;
width: 0;
height: 0;
}
.ribbon .theribbon:after {
left: 0px;
top: 100%;
border-width: 5px 10px;
border-style: solid;
border-color: #000000 #000000 transparent transparent;
}
.ribbon.sale {
top: 0;
}
.ribbon.new {
top: 50px;
}
.ribbon.new .theribbon {
background-color: #5bc0de;
text-shadow: 0px 1px 2px #bbb;
}
.ribbon.new .theribbon:after {
border-color: #2390b0 #2390b0 transparent transparent;
}
.ribbon.gift {
top: 100px;
}
.ribbon.gift .theribbon {
background-color: #5cb85c;
text-shadow: 0px 1px 2px #bbb;
}
.ribbon.gift .theribbon:after {
border-color: #357935 #357935 transparent transparent;
}
.owl-carousel .owl-controls .owl-page.active span,
.owl-theme .owl-controls .owl-page.active span,
.owl-carousel .owl-controls.clickable .owl-page:hover span,
.owl-theme .owl-controls.clickable .owl-page:hover span {
background: #955251;
}
.owl-carousel .owl-controls .owl-buttons,
.owl-theme .owl-controls .owl-buttons {
position: absolute;
top: 5px;
right: 0;
}
.owl-carousel .owl-controls .owl-buttons div,
.owl-theme .owl-controls .owl-buttons div {
width: 26px;
height: 26px;
line-height: 25px;
margin: 0 5px 0 0;
font-size: 18px;
color: #955251;
padding: 0;
background: #fff;
border-radius: 13px;
vertical-align: middle;
text-align: center;
opacity: 1;
filter: alpha(opacity=100);
}
.home-carousel {
position: relative;
background: url('../img/photogrid.jpg') center center repeat;
background-size: cover;
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
}
.home-carousel .dark-mask {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #955251;
opacity: 0.9;
filter: alpha(opacity=90);
}
.home-carousel .owl-carousel {
padding-top: 60px;
padding-bottom: 20px;
}
.home-carousel .owl-theme .owl-controls .owl-page span {
background: #666;
}
.home-carousel .owl-theme .owl-controls .owl-page.active span {
background: #fff;
}
.home-carousel .owl-theme .owl-controls .owl-page:hover span {
background: #fff;
}
@media (max-width: 767px) {
.home-carousel {
text-align: center !important;
}
}
@media (min-width: 992px) {
.home-carousel .right {
text-align: right;
}
}
.home-carousel h1,
.home-carousel h2,
.home-carousel h3,
.home-carousel p,
.home-carousel ul {
color: #fff;
}
.home-carousel h1 {
font-weight: 700;
text-transform: uppercase;
font-size: 46px;
letter-spacing: 0.08em;
}
@media (max-width: 991px) {
.home-carousel h1 {
font-size: 36px;
}
}
.home-carousel h2 {
font-weight: 700;
text-transform: uppercase;
font-size: 40px;
letter-spacing: 0.08em;
}
.home-carousel ul,
.home-carousel p {
font-size: 18px;
font-weight: 700;
padding: 0;
text-transform: uppercase;
letter-spacing: 0.10em;
}
@media (max-width: 991px) {
.home-carousel ul,
.home-carousel p {
font-size: 14px;
}
}
.home-carousel ul li {
margin-bottom: 10px;
}
.customers {
padding: 0;
margin-bottom: 40px;
}
.customers .item {
list-style-type: none;
text-align: center;
margin: 0 20px;
}
.customers .item img {
display: inline-block;
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
/* Firefox 10+, Firefox on Android */
filter: gray;
/* IE6-9 */
-webkit-filter: grayscale(100%);
/* Chrome 19+, Safari 6+, Safari 6+ iOS */
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
}
.customers .item img:hover {
max-width: auto;
filter: none;
-webkit-filter: none;
}
.testimonials {
padding: 0;
margin-bottom: 40px;
}
.testimonials .item {
list-style-type: none;
margin: 0 5px;
background: #fff;
padding-bottom: 60px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.testimonials .item .testimonial {
position: relative;
padding: 20px;
}
.testimonials .item .testimonial:before,
.testimonials .item .testimonial:after {
content: " ";
display: table;
}
.testimonials .item .testimonial:after {
clear: both;
}
.testimonials .item .testimonial:before,
.testimonials .item .testimonial:after {
content: " ";
display: table;
}
.testimonials .item .testimonial:after {
clear: both;
}
.testimonials .item .testimonial .text {
color: #999999;
margin-bottom: 40px;
}
.testimonials .item .testimonial .bottom {
position: absolute;
left: 0;
bottom: 0;
width: 100%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 20px;
height: 50px;
}
.testimonials .item .testimonial .bottom .icon {
color: #955251;
font-size: 30px;
float: left;
width: 20%;
}
.testimonials .item .testimonial .name-picture {
float: right;
width: 80%;
text-align: right;
}
.testimonials .item .testimonial .name-picture h5 {
font-size: 14px;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.testimonials .item .testimonial .name-picture p {
color: #999999;
margin: 0;
font-size: 12px;
}
.testimonials .item .testimonial .name-picture img {
float: right;
width: 60px;
border-radius: 30px;
margin-left: 10px;
}
.team-member {
text-align: center;
margin-bottom: 40px;
}
.team-member h3 {
font-size: 18px;
text-transform: uppercase;
margin-bottom: 5px;
letter-spacing: 0.08em;
}
.team-member h3 a {
color: #555555;
}
.team-member p.role {
color: #999999;
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.06em;
}
.team-member .social {
margin-bottom: 20px;
}
.team-member .social a {
margin: 0 10px 0 0;
color: #fff;
display: inline-block;
width: 26px;
height: 26px;
border-radius: 13px;
line-height: 26px;
font-size: 15px;
text-align: center;
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
vertical-align: bottom;
}
.team-member .social a i {
vertical-align: bottom;
line-height: 26px;
}
.team-member .social a.facebook {
background-color: #4460ae;
}
.team-member .social a.gplus {
background-color: #c21f25;
}
.team-member .social a.twitter {
background-color: #3cf;
}
.team-member .social a.instagram {
background-color: #cd4378;
}
.team-member .social a.email {
background-color: #4a7f45;
}
.team-member .text p {
color: #999999;
font-size: 12px;
}
.team-member .social,
.team-member-detail .social {
margin-bottom: 20px;
}
.team-member .social a,
.team-member-detail .social a {
margin: 0 10px 0 0;
color: #fff;
display: inline-block;
width: 26px;
height: 26px;
border-radius: 13px;
line-height: 26px;
font-size: 15px;
text-align: center;
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
vertical-align: bottom;
}
.team-member .social a i,
.team-member-detail .social a i {
vertical-align: bottom;
line-height: 26px;
}
.team-member .social a.facebook,
.team-member-detail .social a.facebook {
background-color: #4460ae;
}
.team-member .social a.gplus,
.team-member-detail .social a.gplus {
background-color: #c21f25;
}
.team-member .social a.twitter,
.team-member-detail .social a.twitter {
background-color: #3cf;
}
.team-member .social a.instagram,
.team-member-detail .social a.instagram {
background-color: #cd4378;
}
.team-member .social a.email,
.team-member-detail .social a.email {
background-color: #4a7f45;
}
.box-simple {
text-align: center;
margin-bottom: 40px;
}
.box-simple .icon {
color: #955251;
border-color: #955251;
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
}
.box-simple h3 {
font-weight: normal;
font-size: 18px;
text-transform: uppercase;
line-height: 1.5;
color: #555555;
font-weight: 800;
letter-spacing: 0.08em;
}
.box-simple h3 a {
color: #555555;
}
.box-simple p {
color: #999999;
}
.box-simple:hover .icon {
-webkit-transform: scale(1.1, 1.1);
-ms-transform: scale(1.1, 1.1);
-o-transform: scale(1.1, 1.1);
transform: scale(1.1, 1.1);
}
.box-simple:hover .icon i {
-webkit-transform: scale(1, 1);
-ms-transform: scale(1, 1);
-o-transform: scale(1, 1);
transform: scale(1, 1);
}
.box-simple.box-white {
padding: 20px;
border: dotted 1px #999999;
}
.box-simple.box-white .icon {
color: #555555;
border-color: transparent;
font-size: 70px;
}
.box-simple.box-dark {
padding: 20px;
border: dotted 1px #999999;
background: #555555;
color: #fff;
}
.box-simple.box-dark .icon {
color: #f7f7f7;
border-color: transparent;
font-size: 70px;
}
.box-simple.box-dark h3 {
color: #fff;
}
.box-simple.box-dark h3 a {
color: #fff;
}
.box-simple.box-dark p {
color: #fff;
}
.box-image {
position: relative;
overflow: hidden;
text-align: center;
margin: 15px 0;
}
.box-image .bg {
position: absolute;
top: auto;
bottom: 0;
width: 100%;
height: 100%;
opacity: 0;
filter: alpha(opacity=0);
background: #955251;
}
.box-image .name {
position: absolute;
width: 100%;
height: 50%;
bottom: 0;
-webkit-transform: translate(0, 100%);
-ms-transform: translate(0, 100%);
-o-transform: translate(0, 100%);
transform: translate(0, 100%);
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
color: #fff;
padding: 0 20px;
}
.box-image .name h3 {
color: #fff;
text-transform: uppercase;
font-size: 18px;
letter-spacing: 0.08em;
}
.box-image .name h3 a {
color: #fff;
text-decoration: none;
}
.box-image .text {
position: absolute;
width: 100%;
height: 50%;
top: 0;
-webkit-transform: translate(0, -150%);
-ms-transform: translate(0, -150%);
-o-transform: translate(0, -150%);
transform: translate(0, -150%);
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
color: #fff;
padding: 0 20px;
}
.box-image:hover .bg {
opacity: 0.7;
filter: alpha(opacity=70);
}
.box-image:hover .name {
position: absolute;
-webkit-transform: translate(0, -75%);
-ms-transform: translate(0, -75%);
-o-transform: translate(0, -75%);
transform: translate(0, -75%);
}
.box-image:hover .text {
position: absolute;
-webkit-transform: translate(0, 100%);
-ms-transform: translate(0, 100%);
-o-transform: translate(0, 100%);
transform: translate(0, 100%);
}
.box-image-text {
position: relative;
overflow: hidden;
text-align: center;
margin: 15px 0;
}
.box-image-text .top {
position: relative;
margin-bottom: 10px;
}
.box-image-text .top .bg {
position: absolute;
top: auto;
bottom: 0;
width: 100%;
height: 100%;
opacity: 0;
filter: alpha(opacity=0);
background: #955251;
}
.box-image-text .top .name {
position: absolute;
width: 100%;
height: 50%;
bottom: 0;
-webkit-transform: translate(0, 100%);
-ms-transform: translate(0, 100%);
-o-transform: translate(0, 100%);
transform: translate(0, 100%);
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
color: #fff;
padding: 0 20px;
}
.box-image-text .top .name h3 {
color: #fff;
text-transform: uppercase;
font-size: 18px;
letter-spacing: 0.08em;
}
.box-image-text .top .name h3 a {
color: #fff;
text-decoration: none;
}
.box-image-text .top .text {
position: absolute;
width: 100%;
height: 50%;
top: 0;
-webkit-transform: translate(0, -150%);
-ms-transform: translate(0, -150%);
-o-transform: translate(0, -150%);
transform: translate(0, -150%);
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
color: #fff;
padding: 0 20px;
}
.box-image-text .content h3,
.box-image-text .content h4 {
text-transform: uppercase;
line-height: 1.5;
color: #555555;
font-weight: 800;
letter-spacing: 0.08em;
}
.box-image-text .content p {
color: #999999;
}
.box-image-text:hover .bg {
opacity: 0.7;
filter: alpha(opacity=70);
}
.box-image-text:hover .name {
position: absolute;
-webkit-transform: translate(0, -75%);
-ms-transform: translate(0, -75%);
-o-transform: translate(0, -75%);
transform: translate(0, -75%);
}
.box-image-text:hover .text {
position: absolute;
-webkit-transform: translate(0, 100%);
-ms-transform: translate(0, 100%);
-o-transform: translate(0, 100%);
transform: translate(0, 100%);
}
/* universal box */
.box {
background: #fff;
margin: 0 0 30px;
border: solid 1px #ccc;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 20px 0;
border-left: none;
border-right: none;
}
.box .box-header {
background: #f7f7f7;
margin: -20px 0 20px;
padding: 20px;
border-bottom: solid 1px #eeeeee;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.box .box-header:before,
.box .box-header:after {
content: " ";
display: table;
}
.box .box-header:after {
clear: both;
}
.box .box-header:before,
.box .box-header:after {
content: " ";
display: table;
}
.box .box-header:after {
clear: both;
}
.box .box-footer {
background: #f7f7f7;
margin: 30px 0 -20px;
padding: 20px;
border-top: solid 1px #eeeeee;
}
.box .box-footer:before,
.box .box-footer:after {
content: " ";
display: table;
}
.box .box-footer:after {
clear: both;
}
.box .box-footer:before,
.box .box-footer:after {
content: " ";
display: table;
}
.box .box-footer:after {
clear: both;
}
@media (max-width: 991px) {
.box .box-footer .btn {
margin-bottom: 20px;
}
}
.box.no-border {
border: none;
}
#heading-breadcrumbs {
background: url('../img/texture-bw.png') center center repeat;
padding: 20px 0;
margin-bottom: 40px;
}
#heading-breadcrumbs.no-mb {
margin-bottom: 0;
}
#heading-breadcrumbs h1 {
color: #333333;
text-transform: uppercase;
font-size: 30px;
font-weight: 700;
letter-spacing: 0.08em;
}
@media (max-width: 991px) {
#heading-breadcrumbs h1 {
text-align: center;
}
}
#heading-breadcrumbs ul.breadcrumb {
margin-top: 5px;
margin-bottom: 0;
}
.bar {
position: relative;
background: #955251;
padding: 60px 0;
}
.bar.background-pentagon {
background: url('../img/texture-bw.png') center center repeat;
border-top: solid 1px #999999;
border-bottom: solid 1px #999999;
}
.bar.background-gray {
background: #eeeeee;
}
.bar.background-gray-dark {
background: #555555;
}
.bar.background-white {
background: #fff;
}
.bar.background-image-fixed-1 {
background: url('../img/fixed-background-1.jpg') center top no-repeat;
background-attachment: fixed;
background-size: cover;
}
.bar.background-image-fixed-2 {
background: url('../img/fixed-background-2.jpg') center top no-repeat;
background-attachment: fixed;
background-size: cover;
}
.bar.color-white h1,
.bar.color-white h2,
.bar.color-white h3,
.bar.color-white h4,
.bar.color-white h5,
.bar.color-white h6,
.bar.color-white p {
color: #fff;
}
.bar.padding-big {
padding: 50px 0;
}
.bar.padding-horizontal {
padding-left: 30px;
padding-right: 30px;
}
.bar.margin-vertical {
margin-top: 20px;
margin-bottom: 20px;
}
.bar .dark-mask {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #000;
opacity: 0.3;
filter: alpha(opacity=30);
}
.portfolio.no-space {
padding: 0 15px;
}
.portfolio.no-space .box-image {
margin: 0 -15px;
}
.portfolio-project .project-more h4 {
color: #555555;
text-transform: uppercase;
margin-bottom: 0;
text-align: left;
font-size: 14px;
letter-spacing: 0.08em;
}
.portfolio-project .project-more p {
color: #999999;
padding: 10px 0;
margin-bottom: 20px;
text-align: left;
}
.portfolio-showcase {
margin: 15px 0 60px;
}
.portfolio-showcase h3 a {
text-transform: uppercase;
line-height: 1.5;
letter-spacing: 0.08em;
}
.portfolio-showcase p.lead {
color: #555555;
margin-bottom: 20px;
}
.portfolio-showcase p {
color: #999999;
}
.portfolio-showcase p.buttons {
margin-top: 40px;
}
.see-more {
text-align: center;
margin-top: 20px;
padding-top: 20px;
}
.see-more p {
font-size: 28px;
font-weight: 100;
margin-bottom: 20px;
}
.showcase .item {
text-align: center;
}
.showcase .item .icon {
display: inline-block;
width: 50px;
height: 50px;
color: #555555;
line-height: 50px;
border-radius: 25px;
border: solid 1px #555555;
}
.showcase .item h4 {
color: #555555;
text-transform: uppercase;
letter-spacing: 0.08em;
line-height: 1.5;
font-size: 16px;
}
.showcase .item h4 span {
font-weight: bold;
font-size: 51px;
}
.packages .package {
background: #fff;
margin-top: 25px;
margin-bottom: 20px;
padding-bottom: 15px;
text-align: center;
border: solid 1px #955251;
overflow: hidden;
}
.packages .package .package-header {
height: 57px;
color: #fff;
line-height: 57px;
background: #955251;
}
.packages .package .package-header h5 {
color: #fff;
text-transform: uppercase;
font-weight: bold;
line-height: 57px;
margin: 0;
letter-spacing: 0.08em;
}
.packages .package .package-header.light-gray {
background: #eeeeee;
}
.packages .package .package-header.light-gray h5 {
color: #555555;
}
.packages .package .price {
line-height: 120px;
height: 100px;
color: #fff;
font-weight: 400;
}
.packages .package .price h4 {
display: inline;
font-size: 50px;
line-height: normal;
margin-bottom: 0;
}
.packages .package .price .period {
line-height: normal;
color: #999999;
}
.packages .package ul {
padding: 0;
}
.packages .package ul li {
list-style-type: none;
padding-top: 10px;
padding-bottom: 10px;
width: 80%;
margin: auto;
border-bottom: 1px dotted #ccc;
}
.packages .package ul li:last-child {
border-bottom: 0;
}
.packages .package ul li i {
font-size: 13px;
margin-right: 5px;
}
.packages .best-value .package {
margin-top: 0;
padding-bottom: 40px;
}
.packages .best-value .package .package-header {
height: 72px;
padding-top: 17px;
height: 82px !important;
}
.packages .best-value .package .package-header h5 {
font-weight: bold;
line-height: 29px;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.packages .best-value .package .package-header .meta-text {
font-size: 13px;
line-height: 15px;
}
#map {
height: 300px;
}
#map.with-border {
border-top: solid 1px #955251;
border-bottom: solid 1px #955251;
}
#blog-listing-big .post,
#blog-homepage .post {
margin-bottom: 60px;
}
#blog-listing-big .post h2,
#blog-homepage .post h2,
#blog-listing-big .post h4,
#blog-homepage .post h4 {
text-transform: uppercase;
letter-spacing: 0.08em;
}
#blog-listing-big .post h2 a,
#blog-homepage .post h2 a,
#blog-listing-big .post h4 a,
#blog-homepage .post h4 a {
color: #555555;
}
#blog-listing-big .post h2 a:hover,
#blog-homepage .post h2 a:hover,
#blog-listing-big .post h4 a:hover,
#blog-homepage .post h4 a:hover {
color: #955251;
}
#blog-listing-big .post .author-category,
#blog-homepage .post .author-category {
color: #999999;
text-transform: uppercase;
font-weight: 300;
letter-spacing: 0.08em;
}
#blog-listing-big .post .author-category a,
#blog-homepage .post .author-category a {
font-weight: 500;
}
#blog-listing-big .post .date-comments a,
#blog-homepage .post .date-comments a {
color: #999999;
margin-right: 20px;
}
#blog-listing-big .post .date-comments a:hover,
#blog-homepage .post .date-comments a:hover {
color: #955251;
}
@media (min-width: 768px) {
#blog-listing-big .post .date-comments,
#blog-homepage .post .date-comments {
text-align: right;
}
}
#blog-listing-big .post .intro,
#blog-homepage .post .intro {
text-align: left;
}
#blog-listing-big .post .image,
#blog-homepage .post .image {
margin-bottom: 10px;
overflow: hidden;
}
#blog-listing-big .post .image img,
#blog-homepage .post .image img {
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
}
@media (max-width: 767px) {
#blog-listing-big .post .image img.img-responsive,
#blog-homepage .post .image img.img-responsive {
min-width: 100%;
}
}
#blog-listing-big .post .video,
#blog-homepage .post .video {
margin-bottom: 10px;
}
#blog-listing-big .post .read-more,
#blog-homepage .post .read-more {
text-align: right;
}
#blog-listing-medium .post {
margin-bottom: 60px;
}
#blog-listing-medium .post h2 {
text-transform: uppercase;
margin: 0 0 10px;
font-size: 24px;
letter-spacing: 0.08em;
}
#blog-listing-medium .post h2 a {
color: #555555;
}
#blog-listing-medium .post h2 a:hover {
color: #955251;
}
#blog-listing-medium .post .author-category {
float: left;
color: #999999;
text-transform: uppercase;
font-weight: 300;
font-size: 12px;
letter-spacing: 0.08em;
}
#blog-listing-medium .post .author-category a {
font-weight: 500;
}
#blog-listing-medium .post .date-comments {
float: right;
font-size: 12px;
}
#blog-listing-medium .post .date-comments a {
color: #999999;
margin-right: 20px;
}
#blog-listing-medium .post .date-comments a:hover {
color: #955251;
}
@media (min-width: 768px) {
#blog-listing-medium .post .date-comments {
text-align: right;
}
}
#blog-listing-medium .post .intro {
text-align: left;
}
#blog-listing-medium .post .clearfix:before,
#blog-listing-medium .post .clearfix:after,
#blog-listing-medium .post .navbar:before,
#blog-listing-medium .post .navbar:after,
#blog-listing-medium .post .navbar-header:before,
#blog-listing-medium .post .navbar-header:after {
content: " ";
display: table;
}
#blog-listing-medium .post .clearfix:after,
#blog-listing-medium .post .navbar:after,
#blog-listing-medium .post .navbar-header:after {
clear: both;
}
#blog-listing-medium .post .clearfix:before,
#blog-listing-medium .post .clearfix:after,
#blog-listing-medium .post .navbar:before,
#blog-listing-medium .post .navbar:after,
#blog-listing-medium .post .navbar-header:before,
#blog-listing-medium .post .navbar-header:after {
content: " ";
display: table;
}
#blog-listing-medium .post .clearfix:after,
#blog-listing-medium .post .navbar:after,
#blog-listing-medium .post .navbar-header:after {
clear: both;
}
#blog-listing-medium .post .image {
margin-bottom: 10px;
overflow: hidden;
}
#blog-listing-medium .post .image img {
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
}
@media (max-width: 767px) {
#blog-listing-medium .post .image img.img-responsive {
min-width: 100%;
}
}
#blog-listing-medium .post .video {
margin-bottom: 10px;
}
#blog-listing-medium .post .read-more {
text-align: right;
}
.box-image-text.blog .author-category {
color: #999999;
text-transform: uppercase;
letter-spacing: 0.08em;
font-weight: 300;
font-size: 12px;
}
.box-image-text.blog .author-category a {
font-weight: 500;
}
.box-image-text.blog .intro {
text-align: left;
margin-bottom: 20px;
}
#blog-homepage .post {
margin-bottom: 30px;
}
#blog-homepage .post h2,
#blog-homepage .post h4,
#blog-homepage .post .author-category,
#blog-homepage .post .read-more {
text-align: center;
}
#blog-homepage .post .read-more {
margin-top: 20px;
}
#blog-post #post-content {
margin-bottom: 20px;
}
#blog-post .comment {
margin-bottom: 25px;
}
#blog-post .comment:before,
#blog-post .comment:after {
content: " ";
display: table;
}
#blog-post .comment:after {
clear: both;
}
#blog-post .comment:before,
#blog-post .comment:after {
content: " ";
display: table;
}
#blog-post .comment:after {
clear: both;
}
#blog-post .comment .posted {
color: #999999;
font-size: 12px;
}
#blog-post .comment .reply {
font-family: "Roboto", Helvetica, Arial, sans-serif;
}
#blog-post .comment.last {
margin-bottom: 0;
}
#blog-post #comments,
#blog-post #comment-form {
padding: 20px 0;
margin-top: 20px;
border-top: solid 1px #eeeeee;
}
#blog-post #comments:before,
#blog-post #comment-form:before,
#blog-post #comments:after,
#blog-post #comment-form:after {
content: " ";
display: table;
}
#blog-post #comments:after,
#blog-post #comment-form:after {
clear: both;
}
#blog-post #comments:before,
#blog-post #comment-form:before,
#blog-post #comments:after,
#blog-post #comment-form:after {
content: " ";
display: table;
}
#blog-post #comments:after,
#blog-post #comment-form:after {
clear: both;
}
#blog-post #comments h4,
#blog-post #comment-form h4 {
margin-bottom: 20px;
}
#blog-post #comment-form {
margin-bottom: 20px;
}
.product {
background: #fff;
border-bottom: solid 1px #e6e6e6;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
margin-bottom: 60px;
overflow: hidden;
text-align: center;
}
.product .image {
overflow: hidden;
}
.product .image img {
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
}
@media (max-width: 767px) {
.product .image img.img-responsive {
min-width: 100%;
}
}
.product .text {
padding: 10px;
}
.product .text h3 {
font-size: 14px;
font-weight: 700;
height: 39.6px;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.product .text h3 a {
color: #555555;
}
.product .text h3 a:hover {
text-decoration: none;
}
.product .text p.price {
font-size: 18px;
}
.product .text p.price del {
color: #999999;
}
.product .buttons {
clear: both;
position: absolute;
display: none;
bottom: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
width: 100%;
border: solid 1px transparent;
padding: 20px;
background: rgba(255, 255, 255, 0.9);
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
text-align: center;
}
.product .buttons .btn {
margin-bottom: 20px;
}
.product:hover {
border-bottom: solid 1px #808080;
top: 0;
}
.product:hover .buttons {
clear: both;
position: absolute;
top: 0;
background: rgba(255, 255, 255, 0.5);
}
.product:hover .image img {
-webkit-transform: scale(1.1, 1.1);
-ms-transform: scale(1.1, 1.1);
-o-transform: scale(1.1, 1.1);
transform: scale(1.1, 1.1);
}
.goToDescription {
font-size: 12px;
text-align: center;
margin-bottom: 40px;
}
.goToDescription a {
color: #999999;
text-decoration: underline;
}
#productMain {
margin-bottom: 30px;
}
#productMain .sizes {
text-align: center;
}
#productMain .sizes h3 {
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
margin-bottom: 40px;
}
#productMain .sizes a {
display: inline-block;
width: 40px;
height: 40px;
border-radius: 40px;
background: #ccc;
line-height: 40px;
color: #555555;
text-align: center;
text-decoration: none;
font-family: "Roboto", Helvetica, Arial, sans-serif;
}
#productMain .sizes a.active,
#productMain .sizes a:hover {
background: #955251;
color: #fff;
}
#productMain .sizes input {
display: none;
}
#productMain .price {
font-size: 40px;
text-align: center;
margin-top: 40px;
margin-bottom: 40px;
}
#thumbs a {
display: block;
border: solid 1px transparent;
}
#thumbs a.active {
border-color: #955251;
}
#product-social {
text-align: center;
}
#product-social h4 {
font-weight: 300;
margin-bottom: 10px;
}
#product-social p {
line-height: 26px;
}
#product-social p a {
margin: 0 10px 0 0;
color: #fff;
display: inline-block;
width: 26px;
height: 26px;
border-radius: 13px;
line-height: 26px;
font-size: 15px;
text-align: center;
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
vertical-align: bottom;
}
#product-social p a i {
vertical-align: bottom;
line-height: 26px;
}
#product-social p a.facebook {
background-color: #4460ae;
}
#product-social p a.gplus {
background-color: #c21f25;
}
#product-social p a.twitter {
background-color: #3cf;
}
#product-social p a.instagram {
background-color: #cd4378;
}
#product-social p a.email {
background-color: #4a7f45;
}
@media (max-width: 991px) {
#product-social {
text-align: center;
}
}
#checkout .nav {
margin-bottom: 20px;
border-bottom: solid 1px #955251;
}
#checkout .nav li {
height: 100%;
}
#checkout .nav li a {
display: block;
height: 100%;
}
#order-summary table {
margin-top: 20px;
}
#order-summary table td {
color: #999999;
}
#order-summary table tr.total td,
#order-summary table tr.total th {
font-size: 18px;
color: #555555;
font-weight: 700;
}
#checkout .table tbody tr td,
#basket .table tbody tr td,
#customer-order .table tbody tr td {
vertical-align: middle;
}
#checkout .table tbody tr td input,
#basket .table tbody tr td input,
#customer-order .table tbody tr td input {
width: 50px;
text-align: right;
}
#checkout .table tbody tr td img,
#basket .table tbody tr td img,
#customer-order .table tbody tr td img {
width: 50px;
}
#checkout .table tfoot,
#basket .table tfoot,
#customer-order .table tfoot {
font-size: 18px;
}
.shipping-method h4,
.payment-method h4 {
text-transform: uppercase;
letter-spacing: 0.08em;
}
#customer-orders table tr th,
#customer-orders table tr td {
vertical-align: baseline;
}
#customer-order .table tfoot th {
font-size: 18px;
font-weight: 300;
}
#customer-order .addresses {
text-align: right;
margin-bottom: 30px;
}
#customer-order .addresses p {
font-size: 18px;
font-weight: 300;
}
#customer-account {
margin-bottom: 30px;
}
#get-it {
background: #955251;
padding: 50px 0 30px;
color: #fff;
text-align: center;
}
#get-it h1,
#get-it h2,
#get-it h3,
#get-it h4,
#get-it h5,
#get-it h6 {
color: #fff;
text-transform: uppercase;
letter-spacing: 0.08em;
margin: 0 0 20px;
}
#get-it p {
margin: 0 0 20px;
}
#footer {
background: #555555;
padding: 50px 0;
color: #999999;
}
#footer h1,
#footer h2,
#footer h3,
#footer h4,
#footer h5,
#footer h6 {
color: #eeeeee;
}
#footer h4 {
font-size: 14px;
font-weight: 800;
text-transform: uppercase;
letter-spacing: 0.08em;
}
#footer ul {
padding-left: 0;
list-style: none;
}
#footer ul a {
color: #999999;
}
#footer ul a:hover {
color: #955251;
text-decoration: none;
}
#footer .photostream div {
float: left;
display: block;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
width: 33%;
padding: 7.5px;
overflow: hidden;
}
#footer .photostream div a {
border: solid 1 px #eeeeee;
}
#footer .photostream div img {
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
}
#footer .photostream div:hover img {
-webkit-transform: scale(1.1, 1.1);
-ms-transform: scale(1.1, 1.1);
-o-transform: scale(1.1, 1.1);
transform: scale(1.1, 1.1);
}
#footer .blog-entries .item {
clear: both;
padding: 5px 0;
margin-bottom: 10px;
border-bottom: solid 1px #555555;
}
#footer .blog-entries .item .image {
float: left;
width: 15%;
margin-right: 10px;
}
#footer .blog-entries .item .name {
width: 75%;
margin-left: 10px;
display: table-cell;
vertical-align: middle;
}
#footer .blog-entries .item .name h5 {
margin: 0;
text-transform: uppercase;
letter-spacing: 0.08em;
font-size: 12px;
}
#footer .blog-entries .item .name h5 a {
color: #eeeeee;
}
#footer .blog-entries .item .text {
width: 100%;
clear: both;
}
#footer .blog-entries .item:last-child {
border-bottom: none;
margin-bottom: 0;
}
#footer .social a {
color: #555555;
font-size: 25px;
margin: 0 10px 0 0;
}
#footer .social a:hover {
color: #955251;
}
#copyright {
background: #333;
color: #ccc;
padding: 50px 0;
font-size: 12px;
line-height: 28px;
}
#copyright p {
margin: 0;
}
@media (max-width: 991px) {
#copyright p {
float: none !important;
text-align: center;
margin-bottom: 10px;
}
}
[data-animate] {
opacity: 0;
filter: alpha(opacity=0);
}
#style-switch-button {
position: fixed;
top: 100px;
left: 0px;
border-radius: 0;
}
#style-switch {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
width: 300px;
padding: 20px;
position: fixed;
top: 140px;
left: 0;
background: #fff;
border: solid 1px #eeeeee;
}
@media (max-width: 991px) {
#style-switch-button {
display: none;
}
#style-switch {
display: none;
}
}
/* Original Boostrap template overwrite */
/* breadcrumbs */
.breadcrumb {
font-family: "Roboto", Helvetica, Arial, sans-serif;
text-transform: uppercase;
background-color: none;
letter-spacing: 0.08em;
}
/* nav */
.nav > li > a {
padding: 10px 15px;
}
.nav > li > a:hover,
.nav > li > a:focus {
background-color: #eeeeee;
}
.nav > li.disabled > a {
color: #999999;
}
.nav > li.disabled > a:hover,
.nav > li.disabled > a:focus {
color: #999999;
}
.nav .open > a,
.nav .open > a:hover,
.nav .open > a:focus {
background-color: #eeeeee;
border-color: #955251;
}
.nav-tabs {
border-bottom: 1px solid #955251;
}
.nav-tabs > li {
float: left;
margin-bottom: -1px;
}
.nav-tabs > li > a {
margin-right: 2px;
line-height: 1.42857143;
border: 1px solid transparent;
border-radius: 0 0 0 0;
}
.nav-tabs > li > a:hover {
border-color: #eeeeee #eeeeee #955251;
}
.nav-tabs > li.active > a,
.nav-tabs > li.active > a:hover,
.nav-tabs > li.active > a:focus {
color: #555555;
background-color: #ffffff;
border: 1px solid #955251;
border-bottom-color: transparent;
cursor: default;
}
.nav-tabs.nav-justified {
width: 100%;
border-bottom: solid 1px #955251;
border-bottom: 0;
}
.nav-tabs.nav-justified > li {
float: none;
}
.nav-tabs.nav-justified > li > a {
text-align: center;
/*margin-bottom: 5px;*/
}
.nav-tabs.nav-justified > .dropdown .dropdown-menu {
top: auto;
left: auto;
}
.nav-tabs.nav-justified > li > a {
margin-right: 0;
border-radius: 0;
}
.nav-tabs.nav-justified > .active > a,
.nav-tabs.nav-justified > .active > a:hover,
.nav-tabs.nav-justified > .active > a:focus {
border: 1px solid #955251;
}
@media (min-width: 768px) {
.nav-tabs.nav-justified > li > a {
border-bottom: 1px solid #955251;
border-radius: 0 0 0 0;
}
.nav-tabs.nav-justified > .active > a,
.nav-tabs.nav-justified > .active > a:hover,
.nav-tabs.nav-justified > .active > a:focus {
border-bottom-color: #ffffff;
}
}
.nav-pills > li {
float: left;
}
.nav-pills > li > a {
border-radius: 0;
}
.nav-pills > li + li {
margin-left: 2px;
}
.nav-pills > li.active > a,
.nav-pills > li.active > a:hover,
.nav-pills > li.active > a:focus {
color: #ffffff;
background-color: #955251;
}
.nav-stacked > li {
float: none;
}
.nav-stacked > li + li {
margin-top: 2px;
margin-left: 0;
}
.nav-justified {
width: 100%;
border-bottom: solid 1px #955251;
}
.nav-justified > li {
float: none;
}
.nav-justified > li > a {
text-align: center;
/*margin-bottom: 5px;*/
}
.nav-justified > .dropdown .dropdown-menu {
top: auto;
left: auto;
}
.nav-tabs-justified {
border-bottom: 0;
}
.nav-tabs-justified > li > a {
margin-right: 0;
border-radius: 0;
}
.nav-tabs-justified > .active > a,
.nav-tabs-justified > .active > a:hover,
.nav-tabs-justified > .active > a:focus {
border: 1px solid #955251;
}
@media (min-width: 768px) {
.nav-tabs-justified > li > a {
border-bottom: 1px solid #955251;
border-radius: 0 0 0 0;
}
.nav-tabs-justified > .active > a,
.nav-tabs-justified > .active > a:hover,
.nav-tabs-justified > .active > a:focus {
border-bottom-color: #ffffff;
}
}
.tab-content {
padding: 15px;
border: solid 1px #ddd;
border-top: none;
}
/* navbar */
.navbar {
position: relative;
min-height: 62px;
margin-bottom: 0;
border-bottom: 1px solid transparent;
}
@media (min-width: 768px) {
.navbar {
border-radius: 0px;
}
}
@media (min-width: 768px) {
.navbar-header {
float: left;
}
}
.navbar-collapse {
overflow-x: visible;
padding-right: 15px;
padding-left: 15px;
}
.navbar-collapse.in {
overflow-y: auto;
}
@media (min-width: 768px) {
.navbar-collapse {
width: auto;
border-top: 0;
box-shadow: none;
}
.navbar-collapse.collapse {
display: block !important;
height: auto !important;
padding-bottom: 0;
overflow: visible !important;
}
.navbar-collapse.in {
overflow-y: visible;
}
.navbar-fixed-top .navbar-collapse,
.navbar-static-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
padding-left: 0;
padding-right: 0;
}
}
.navbar-fixed-top .navbar-collapse,
.navbar-affixed-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
max-height: 340px;
}
@media (max-width: 480px) and (orientation: landscape) {
.navbar-fixed-top .navbar-collapse,
.navbar-affixed-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
max-height: 200px;
}
}
.container > .navbar-header,
.container-fluid > .navbar-header,
.container > .navbar-collapse,
.container-fluid > .navbar-collapse {
margin-right: -15px;
margin-left: -15px;
}
@media (min-width: 768px) {
.container > .navbar-header,
.container-fluid > .navbar-header,
.container > .navbar-collapse,
.container-fluid > .navbar-collapse {
margin-right: 0;
margin-left: 0;
}
}
.navbar-static-top {
z-index: 1000;
border-width: 0 0 1px;
}
@media (min-width: 768px) {
.navbar-static-top {
border-radius: 0;
}
}
.navbar-fixed-top,
.navbar-fixed-bottom {
position: fixed;
right: 0;
left: 0;
z-index: 1030;
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
@media (min-width: 768px) {
.navbar-fixed-top,
.navbar-fixed-bottom {
border-radius: 0;
}
}
.navbar-fixed-top {
top: 0;
border-width: 0 0 1px;
}
.navbar-fixed-bottom {
bottom: 0;
margin-bottom: 0;
border-width: 1px 0 0;
}
.navbar-brand {
float: left;
padding: 10px 15px;
font-size: 18px;
line-height: 20px;
height: 62px;
}
.navbar-brand:hover,
.navbar-brand:focus {
text-decoration: none;
}
@media (min-width: 768px) {
.navbar > .container .navbar-brand,
.navbar > .container-fluid .navbar-brand {
margin-left: -15px;
}
}
.navbar-toggle {
position: relative;
float: right;
margin-right: 15px;
padding: 9px 10px;
margin-top: 14px;
margin-bottom: 14px;
background-color: transparent;
background-image: none;
border: 1px solid transparent;
border-radius: 0;
}
.navbar-toggle:focus {
outline: 0;
}
.navbar-nav {
margin: 10.5px -15px;
}
.navbar-nav > li > a {
padding-top: 10px;
padding-bottom: 10px;
line-height: 20px;
}
@media (max-width: 767px) {
.navbar-nav .open .dropdown-menu > li > a,
.navbar-nav .open .dropdown-menu .dropdown-header {
padding: 5px 15px 5px 25px;
}
.navbar-nav .open .dropdown-menu > li > a {
line-height: 20px;
}
.navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-nav .open .dropdown-menu > li > a:focus {
background-image: none;
}
}
@media (min-width: 768px) {
.navbar-nav {
float: left;
margin: 0;
}
.navbar-nav > li {
float: left;
}
.navbar-nav > li > a {
padding-top: 21px;
padding-bottom: 21px;
}
.navbar-nav.navbar-right:last-child {
margin-right: -15px;
}
}
@media (min-width: 768px) {
.navbar-left {
float: left !important;
}
.navbar-right {
float: right !important;
}
}
.navbar-form {
margin-left: -15px;
margin-right: -15px;
padding: 10px 15px;
border-top: 1px solid transparent;
border-bottom: 1px solid transparent;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);
margin-top: 14px;
margin-bottom: 14px;
}
@media (max-width: 767px) {
.navbar-form .form-group {
margin-bottom: 5px;
}
}
@media (min-width: 768px) {
.navbar-form {
width: auto;
border: 0;
margin-left: 0;
margin-right: 0;
padding-top: 0;
padding-bottom: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.navbar-form.navbar-right:last-child {
margin-right: -15px;
}
}
.navbar-nav > li > .dropdown-menu {
margin-top: 0;
border-top-right-radius: 0;
border-top-left-radius: 0;
}
.navbar-fixed-bottom .navbar-nav > li > .dropdown-menu {
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.navbar-btn {
margin-top: 14px;
margin-bottom: 14px;
}
.navbar-btn.btn-sm {
margin-top: 16px;
margin-bottom: 16px;
}
.navbar-btn.btn-xs {
margin-top: 20px;
margin-bottom: 20px;
}
.navbar-text {
margin-top: 21px;
margin-bottom: 21px;
}
@media (min-width: 768px) {
.navbar-text {
float: left;
margin-left: 15px;
margin-right: 15px;
}
.navbar-text.navbar-right:last-child {
margin-right: 0;
}
}
.navbar-default {
background-color: #ffffff;
border-color: #cccccc;
border-bottom: none;
}
.navbar-default .navbar-brand {
color: #555555;
}
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus {
color: #3b3b3b;
background-color: transparent;
}
.navbar-default .navbar-text {
color: #777777;
}
.navbar-default .navbar-nav > li > a {
color: #555555;
}
.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
color: #555555;
background-color: #c08c8c;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
color: #ffffff;
background-color: #955251;
}
.navbar-default .navbar-nav > .disabled > a,
.navbar-default .navbar-nav > .disabled > a:hover,
.navbar-default .navbar-nav > .disabled > a:focus {
color: #cccccc;
background-color: transparent;
}
.navbar-default .navbar-toggle {
border-color: #dddddd;
}
.navbar-default .navbar-toggle:hover,
.navbar-default .navbar-toggle:focus {
background-color: #955251;
}
.navbar-default .navbar-toggle .icon-bar {
background-color: #888888;
}
.navbar-default .navbar-collapse,
.navbar-default .navbar-form {
border-color: #cccccc;
}
.navbar-default .navbar-nav > .open > a,
.navbar-default .navbar-nav > .open > a:hover,
.navbar-default .navbar-nav > .open > a:focus {
background-color: #955251;
color: #ffffff;
}
@media (max-width: 767px) {
.navbar-default .navbar-nav .open .dropdown-menu > li > a {
color: #555555;
}
.navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
color: #955251;
}
.navbar-default .navbar-nav .open .dropdown-menu > .active > a,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #ffffff;
background-color: #955251;
}
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus {
color: #cccccc;
background-color: transparent;
}
}
.navbar-default .navbar-link {
color: #555555;
}
.navbar-default .navbar-link:hover {
color: #555555;
}
.navbar-default .btn-link {
color: #555555;
}
.navbar-default .btn-link:hover,
.navbar-default .btn-link:focus {
color: #555555;
}
.navbar-default .btn-link[disabled]:hover,
fieldset[disabled] .navbar-default .btn-link:hover,
.navbar-default .btn-link[disabled]:focus,
fieldset[disabled] .navbar-default .btn-link:focus {
color: #cccccc;
}
/* scaffolding */
body {
font-family: "Roboto", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.42857143;
color: #555555;
}
a {
color: #955251;
text-decoration: none;
}
a:hover,
a:focus {
color: #633736;
text-decoration: underline;
}
a:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
.img-rounded {
border-radius: 0;
}
hr {
margin-top: 20px;
margin-bottom: 20px;
border: 0;
border-top: 1px solid #eeeeee;
}
/* breadcrumbs */
.breadcrumb {
padding: 20px 0;
margin-bottom: 20px;
background-color: transparent;
border-radius: 0;
text-align: right;
}
.breadcrumb > li + li:before {
content: ">\00a0";
color: #555555;
}
.breadcrumb > .active {
color: #999999;
}
@media (max-width: 991px) {
.breadcrumb {
padding: 20px 0;
text-align: center;
}
}
/* dropdowns */
.dropdown-menu {
z-index: 1000;
font-size: 14px;
background-color: #ffffff;
border: 1px solid #cccccc;
border: 1px solid rgba(0, 0, 0, 0.15);
border-radius: 0;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
}
.dropdown-menu.pull-right {
right: 0;
left: auto;
}
.dropdown-menu .divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
.dropdown-menu > li > a {
padding: 5px 20px;
line-height: 1.42857143;
color: #333333;
white-space: nowrap;
}
/* labels */
.label {
font-family: "Roboto", Helvetica, Arial, sans-serif;
font-weight: normal;
text-transform: uppercase;
letter-spacing: 0.08em;
}
/* forms.less */
label {
font-weight: normal;
}
.form-control {
-webkit-box-shadow: none;
box-shadow: none;
border-radius: 0;
}
.form-control:focus {
border-color: #955251;
outline: 0;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(149, 82, 81, 0.6);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(149, 82, 81, 0.6);
}
.form-group {
margin-bottom: 20px;
}
/* pager*/
.pager {
margin: 20px 0;
border-top: solid 1px #eeeeee;
padding-top: 20px;
text-transform: uppercase;
letter-spacing: 0.08em;
font-family: "Roboto", Helvetica, Arial, sans-serif;
}
.pager li {
display: inline;
}
.pager li > a,
.pager li > span {
background-color: #ffffff;
border: 1px solid #955251;
border-radius: 0;
}
.pager li > a:hover,
.pager li > a:focus {
text-decoration: none;
color: #fff;
background-color: #955251;
}
.pager .disabled > a,
.pager .disabled > a:hover,
.pager .disabled > a:focus,
.pager .disabled > span {
color: #999999;
background-color: #ffffff;
border-color: #ddd;
}
/* pagination */
.pagination {
margin: 20px 0;
font-family: "Roboto", Helvetica, Arial, sans-serif;
border-radius: 0;
}
.pagination > li > a,
.pagination > li > span {
padding: 6px 12px;
line-height: 1.42857143;
text-decoration: none;
color: #955251;
background-color: #ffffff;
border: 1px solid #dddddd;
}
.pagination > li > a:hover,
.pagination > li > span:hover,
.pagination > li > a:focus,
.pagination > li > span:focus {
color: #955251;
background-color: #d2adad;
border-color: #dddddd;
}
.pagination > .active > a,
.pagination > .active > span,
.pagination > .active > a:hover,
.pagination > .active > span:hover,
.pagination > .active > a:focus,
.pagination > .active > span:focus {
z-index: 2;
color: #ffffff;
background-color: #955251;
border-color: #955251;
}
.pagination > .disabled > span,
.pagination > .disabled > span:hover,
.pagination > .disabled > span:focus,
.pagination > .disabled > a,
.pagination > .disabled > a:hover,
.pagination > .disabled > a:focus {
color: #999999;
background-color: #ffffff;
border-color: #dddddd;
}
/* responsive utilities */
@media (max-width: 767px) {
.text-center-xs {
text-align: center !important;
}
.text-center-xs img {
display: block;
margin-left: auto;
margin-right: auto;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.text-center-sm {
text-align: center !important;
}
.text-center-sm img {
display: block;
margin-left: auto;
margin-right: auto;
}
}
/* type */
h1,
h2,
h3,
h4,
h5,
h6,
.h1,
.h2,
.h3,
.h4,
.h5,
.h6 {
font-family: "Roboto", Helvetica, Arial, sans-serif;
font-weight: 900;
line-height: 1.1;
color: #333333;
}
h1,
.h1,
h2,
.h2,
h3,
.h3 {
margin-top: 20px;
margin-bottom: 20px;
}
p {
margin: 0 0 10px;
}
.lead {
margin-bottom: 20px;
font-size: 18px;
}
@media (min-width: 768px) {
.lead {
font-size: 21px;
}
}
.text-small {
font-size: 12px;
}
.text-large {
font-size: 18px;
}
.text-italic {
font-style: italic;
}
.text-primary {
color: #955251;
}
a.text-primary:hover {
color: #74403f;
}
.bg-primary {
color: #fff;
background-color: #955251;
}
a.bg-primary:hover {
background-color: #74403f;
}
abbr[title],
abbr[data-original-title] {
border-bottom: 1px dotted #999999;
}
blockquote {
padding: 10px 20px;
margin: 0 0 20px;
font-size: 14px;
border-left: 5px solid #955251;
}
blockquote footer,
blockquote small,
blockquote .small {
display: block;
font-size: 80%;
line-height: 1.42857143;
color: #999999;
}
blockquote footer:before,
blockquote small:before,
blockquote .small:before {
content: '\2014 \00A0';
}
.blockquote-reverse,
blockquote.pull-right {
border-right: 5px solid #955251;
}
address {
margin-bottom: 20px;
line-height: 1.42857143;
}
.panel {
margin-bottom: 20px;
background-color: #ffffff;
border: 1px solid transparent;
border-radius: 0;
-webkit-box-shadow: 0 0 0;
box-shadow: 0 0 0;
}
.panel-heading {
border-top-right-radius: 0;
border-top-left-radius: 0;
text-transform: uppercase;
letter-spacing: 0.08em;
padding: 15px 15px;
}
.progress {
overflow: hidden;
height: 20px;
margin-bottom: 20px;
background-color: #f5f5f5;
border-radius: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.panel-group {
margin-bottom: 20px;
}
.panel-group .panel {
margin-bottom: 0;
border-radius: 0;
overflow: hidden;
}
.panel-group .panel + .panel {
margin-top: 5px;
}
.panel-group.accordion .panel {
border-color: #ccc;
}
.panel-primary {
border-color: #955251;
}
.panel-primary > .panel-heading {
color: #ffffff;
background-color: #955251;
border-color: #955251;
}
.panel-primary > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #955251;
}
.panel-primary > .panel-heading .badge {
color: #955251;
background-color: #ffffff;
}
.panel-primary > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #955251;
}
.panel-primary .panel-title {
font-weight: 300;
}
.panel-primary .panel-title a:hover {
color: #fff;
text-decoration: none;
}
a.badge:hover,
a.badge:focus {
color: #ffffff;
text-decoration: none;
cursor: pointer;
}
a.list-group-item.active > .badge,
.nav-pills > .active > a > .badge {
color: #955251;
background-color: #ffffff;
}
.nav-pills > li > a > .badge {
margin-left: 3px;
}
.progress-bar-primary {
background-color: #955251;
}
.progress-striped .progress-bar-primary {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
}
/*!
* Yamm!3 - Yet another megamenu for Bootstrap 3
* http://geedmo.github.com/yamm3
*
* @geedmo - Licensed under the MIT license
*/
.yamm .nav,
.yamm .collapse,
.yamm .dropup.use-yamm,
.yamm .dropdown.use-yamm {
position: static;
}
.yamm .container {
position: relative;
}
.yamm .dropdown-menu {
left: auto;
}
.yamm .nav.navbar-right .dropdown-menu {
left: auto;
right: 0;
}
.yamm .yamm-content {
padding: 20px 30px;
}
.yamm .dropdown.yamm-fw .dropdown-menu {
left: 15px;
right: 15px;
}
| {
"pile_set_name": "Github"
} |
# The gvim.desktop file is generated by src/po/Makefile, do NOT edit.
# Edit the src/po/gvim.desktop.in file instead.
[Desktop Entry]
# Translators: This is the Application Name used in the GVim desktop file
Name=GVim
# Translators: This is the Generic Application Name used in the Vim desktop file
GenericName=Text Editor
# Translators: This is the comment used in the Vim desktop file
Comment=Edit text files
# The translations should come from the po file. Leave them here for now, they will
# be overwritten by the po file when generating the desktop.file!
GenericName[da]=Teksteditor
GenericName[eo]=Tekstoredaktilo
GenericName[fr]=Éditeur de texte
GenericName[pl]=Edytor tekstu
GenericName[is]=Ritvinnsluforrit
Comment[af]=Redigeer tekslêers
Comment[am]=የጽሑፍ ፋይሎች ያስተካክሉ
Comment[ar]=حرّر ملفات نصية
Comment[az]=Mətn fayllarını redaktə edin
Comment[be]=Рэдагаваньне тэкставых файлаў
Comment[bg]=Редактиране на текстови файлове
Comment[bn]=টেক্স্ট ফাইল এডিট করুন
Comment[bs]=Izmijeni tekstualne datoteke
Comment[ca]=Edita fitxers de text
Comment[cs]=Úprava textových souborů
Comment[cy]=Golygu ffeiliau testun
Comment[da]=Rediger tekstfiler
Comment[el]=Επεξεργασία αρχείων κειμένου
Comment[en_CA]=Edit text files
Comment[en_GB]=Edit text files
Comment[eo]=Redakti tekstajn dosierojn
Comment[es]=Edita archivos de texto
Comment[et]=Redigeeri tekstifaile
Comment[eu]=Editatu testu-fitxategiak
Comment[fa]=ویرایش پروندههای متنی
Comment[fi]=Muokkaa tekstitiedostoja
Comment[fr]=Éditer des fichiers textes
Comment[ga]=Eagar comhad Téacs
Comment[gu]=લખાણ ફાઇલોમાં ફેરફાર કરો
Comment[he]=ערוך קבצי טקסט
Comment[hi]=पाठ फ़ाइलें संपादित करें
Comment[hr]=Uređivanje tekstualne datoteke
Comment[hu]=Szövegfájlok szerkesztése
Comment[id]=Edit file teks
Comment[is]=Vinna með textaskrár
Comment[it]=Modifica file di testo
Comment[kn]=ಪಠ್ಯ ಕಡತಗಳನ್ನು ಸಂಪಾದಿಸು
Comment[ko]=텍스트 파일을 편집합니다
Comment[lt]=Redaguoti tekstines bylas
Comment[lv]=Rediģēt teksta failus
Comment[mk]=Уреди текстуални фајлови
Comment[ml]=വാചക രചനകള് തിരുത്തുക
Comment[mn]=Текст файл боловсруулах
Comment[mr]=गद्य फाइल संपादित करा
Comment[ms]=Edit fail teks
Comment[nb]=Rediger tekstfiler
Comment[ne]=पाठ फाइललाई संशोधन गर्नुहोस्
Comment[nl]=Tekstbestanden bewerken
Comment[nn]=Rediger tekstfiler
Comment[no]=Rediger tekstfiler
Comment[or]=ପାଠ୍ଯ ଫାଇଲଗୁଡ଼ିକୁ ସମ୍ପାଦନ କରନ୍ତୁ
Comment[pa]=ਪਾਠ ਫਾਇਲਾਂ ਸੰਪਾਦਨ
Comment[pl]=Edytuj pliki tekstowe
Comment[pt]=Editar ficheiros de texto
Comment[pt_BR]=Edite arquivos de texto
Comment[ro]=Editare fişiere text
Comment[ru]=Редактор текстовых файлов
Comment[sk]=Úprava textových súborov
Comment[sl]=Urejanje datotek z besedili
Comment[sq]=Përpuno files teksti
Comment[sr]=Измени текстуалне датотеке
Comment[sr@Latn]=Izmeni tekstualne datoteke
Comment[sv]=Redigera textfiler
Comment[ta]=உரை கோப்புகளை தொகுக்கவும்
Comment[th]=แก้ไขแฟ้มข้อความ
Comment[tk]=Metin faýllary editle
Comment[tr]=Metin dosyalarını düzenle
Comment[uk]=Редактор текстових файлів
Comment[vi]=Soạn thảo tập tin văn bản
Comment[wa]=Asspougnî des fitchîs tecses
Comment[zh_CN]=编辑文本文件
Comment[zh_TW]=編輯文字檔
TryExec=gvim
Exec=gvim -f %F
Terminal=false
Type=Application
# Translators: Search terms to find this application. Do NOT change the semicolons! The list MUST also end with a semicolon!
Keywords=Text;editor;
# Translators: This is the Icon file name. Do NOT translate
Icon=gvim
Categories=Utility;TextEditor;
StartupNotify=true
MimeType=text/english;text/plain;text/x-makefile;text/x-c++hdr;text/x-c++src;text/x-chdr;text/x-csrc;text/x-java;text/x-moc;text/x-pascal;text/x-tcl;text/x-tex;application/x-shellscript;text/x-c;text/x-c++;
| {
"pile_set_name": "Github"
} |
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#ifndef COMPILER_VERSIONGLSL_H_
#define COMPILER_VERSIONGLSL_H_
#include "GLSLANG/ShaderLang.h"
#include "compiler/intermediate.h"
// Traverses the intermediate tree to return the minimum GLSL version
// required to legally access all built-in features used in the shader.
// GLSL 1.1 which is mandated by OpenGL 2.0 provides:
// - #version and #extension to declare version and extensions.
// - built-in functions refract, exp, and log.
// - updated step() to compare x < edge instead of x <= edge.
// GLSL 1.2 which is mandated by OpenGL 2.1 provides:
// - many changes to reduce differences when compared to the ES specification.
// - invariant keyword and its support.
// - c++ style name hiding rules.
// - built-in variable gl_PointCoord for fragment shaders.
// - matrix constructors taking matrix as argument.
// - array as "out" function parameters
//
class TVersionGLSL : public TIntermTraverser {
public:
TVersionGLSL(ShShaderType type);
// Returns 120 if the following is used the shader:
// - "invariant",
// - "gl_PointCoord",
// - matrix/matrix constructors
// - array "out" parameters
// Else 110 is returned.
int getVersion() { return mVersion; }
virtual void visitSymbol(TIntermSymbol*);
virtual void visitConstantUnion(TIntermConstantUnion*);
virtual bool visitBinary(Visit, TIntermBinary*);
virtual bool visitUnary(Visit, TIntermUnary*);
virtual bool visitSelection(Visit, TIntermSelection*);
virtual bool visitAggregate(Visit, TIntermAggregate*);
virtual bool visitLoop(Visit, TIntermLoop*);
virtual bool visitBranch(Visit, TIntermBranch*);
protected:
void updateVersion(int version);
private:
ShShaderType mShaderType;
int mVersion;
};
#endif // COMPILER_VERSIONGLSL_H_
| {
"pile_set_name": "Github"
} |
/*
* cx18 init/start/stop/exit stream functions
*
* Derived from ivtv-streams.h
*
* Copyright (C) 2007 Hans Verkuil <[email protected]>
* Copyright (C) 2008 Andy Walls <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
u32 cx18_find_handle(struct cx18 *cx);
struct cx18_stream *cx18_handle_to_stream(struct cx18 *cx, u32 handle);
int cx18_streams_setup(struct cx18 *cx);
int cx18_streams_register(struct cx18 *cx);
void cx18_streams_cleanup(struct cx18 *cx, int unregister);
#define CX18_ENC_STREAM_TYPE_IDX_FW_MDL_MIN (3)
void cx18_stream_rotate_idx_mdls(struct cx18 *cx);
static inline bool cx18_stream_enabled(struct cx18_stream *s)
{
return s->video_dev.v4l2_dev ||
(s->dvb && s->dvb->enabled) ||
(s->type == CX18_ENC_STREAM_TYPE_IDX &&
s->cx->stream_buffers[CX18_ENC_STREAM_TYPE_IDX] != 0);
}
/* Related to submission of mdls to firmware */
static inline void cx18_stream_load_fw_queue(struct cx18_stream *s)
{
schedule_work(&s->out_work_order);
}
static inline void cx18_stream_put_mdl_fw(struct cx18_stream *s,
struct cx18_mdl *mdl)
{
/* Put mdl on q_free; the out work handler will move mdl(s) to q_busy */
cx18_enqueue(s, mdl, &s->q_free);
cx18_stream_load_fw_queue(s);
}
void cx18_out_work_handler(struct work_struct *work);
/* Capture related */
int cx18_start_v4l2_encode_stream(struct cx18_stream *s);
int cx18_stop_v4l2_encode_stream(struct cx18_stream *s, int gop_end);
void cx18_stop_all_captures(struct cx18 *cx);
| {
"pile_set_name": "Github"
} |
/*!
* jQuery Password Strength plugin for Twitter Bootstrap
* Version: 2.0.0
*
* Copyright (c) 2008-2013 Tane Piper
* Copyright (c) 2013 Alejandro Blanco
* Dual licensed under the MIT and GPL licenses.
* https://github.com/ablanco/jquery.pwstrength.bootstrap
*/
(function (jQuery) {
// Source: src/i18n.js
var i18n = {};
(function (i18n, i18next) {
'use strict';
i18n.fallback = {
"wordLength": "Your password is too short",
"wordNotEmail": "Do not use your email as your password",
"wordSimilarToUsername": "Your password cannot contain your username",
"wordTwoCharacterClasses": "Use different character classes",
"wordRepetitions": "Too many repetitions",
"wordSequences": "Your password contains sequences",
"errorList": "Errors:",
"veryWeak": "Very Weak",
"weak": "Weak",
"normal": "Normal",
"medium": "Medium",
"strong": "Strong",
"veryStrong": "Very Strong"
};
i18n.t = function (key) {
var result = '';
// Try to use i18next.com
if (i18next) {
result = i18next.t(key);
} else {
// Fallback to english
result = i18n.fallback[key];
}
return result === key ? '' : result;
};
}(i18n, window.i18next));
// Source: src/rules.js
var rulesEngine = {};
try {
if (!jQuery && module && module.exports) {
var jQuery = require("jquery"),
jsdom = require("jsdom").jsdom;
jQuery = jQuery(jsdom().parentWindow);
}
} catch (ignore) {}
(function ($, rulesEngine) {
"use strict";
var validation = {};
rulesEngine.forbiddenSequences = [
"0123456789", "abcdefghijklmnopqrstuvwxyz", "qwertyuiop", "asdfghjkl",
"zxcvbnm", "!@#$%^&*()_+"
];
validation.wordNotEmail = function (options, word, score) {
if (word.match(/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i)) {
return score;
}
return 0;
};
validation.wordLength = function (options, word, score) {
var wordlen = word.length,
lenScore = Math.pow(wordlen, options.rules.raisePower);
if (wordlen < options.common.minChar) {
lenScore = (lenScore + score);
}
return lenScore;
};
validation.wordSimilarToUsername = function (options, word, score) {
var username = $(options.common.usernameField).val();
if (username && word.toLowerCase().match(username.replace(/[\-\[\]\/\{\}\(\)\*\+\=\?\:\.\\\^\$\|\!\,]/g, "\\$&").toLowerCase())) {
return score;
}
return 0;
};
validation.wordTwoCharacterClasses = function (options, word, score) {
if (word.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/) ||
(word.match(/([a-zA-Z])/) && word.match(/([0-9])/)) ||
(word.match(/(.[!,@,#,$,%,\^,&,*,?,_,~])/) && word.match(/[a-zA-Z0-9_]/))) {
return score;
}
return 0;
};
validation.wordRepetitions = function (options, word, score) {
if (word.match(/(.)\1\1/)) { return score; }
return 0;
};
validation.wordSequences = function (options, word, score) {
var found = false,
j;
if (word.length > 2) {
$.each(rulesEngine.forbiddenSequences, function (idx, seq) {
if (found) { return; }
var sequences = [seq, seq.split('').reverse().join('')];
$.each(sequences, function (idx, sequence) {
for (j = 0; j < (word.length - 2); j += 1) { // iterate the word trough a sliding window of size 3:
if (sequence.indexOf(word.toLowerCase().substring(j, j + 3)) > -1) {
found = true;
}
}
});
});
if (found) { return score; }
}
return 0;
};
validation.wordLowercase = function (options, word, score) {
return word.match(/[a-z]/) && score;
};
validation.wordUppercase = function (options, word, score) {
return word.match(/[A-Z]/) && score;
};
validation.wordOneNumber = function (options, word, score) {
return word.match(/\d+/) && score;
};
validation.wordThreeNumbers = function (options, word, score) {
return word.match(/(.*[0-9].*[0-9].*[0-9])/) && score;
};
validation.wordOneSpecialChar = function (options, word, score) {
return word.match(/[!,@,#,$,%,\^,&,*,?,_,~]/) && score;
};
validation.wordTwoSpecialChar = function (options, word, score) {
return word.match(/(.*[!,@,#,$,%,\^,&,*,?,_,~].*[!,@,#,$,%,\^,&,*,?,_,~])/) && score;
};
validation.wordUpperLowerCombo = function (options, word, score) {
return word.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/) && score;
};
validation.wordLetterNumberCombo = function (options, word, score) {
return word.match(/([a-zA-Z])/) && word.match(/([0-9])/) && score;
};
validation.wordLetterNumberCharCombo = function (options, word, score) {
return word.match(/([a-zA-Z0-9].*[!,@,#,$,%,\^,&,*,?,_,~])|([!,@,#,$,%,\^,&,*,?,_,~].*[a-zA-Z0-9])/) && score;
};
rulesEngine.validation = validation;
rulesEngine.executeRules = function (options, word) {
var totalScore = 0;
$.each(options.rules.activated, function (rule, active) {
if (active) {
var score = options.rules.scores[rule],
funct = rulesEngine.validation[rule],
result,
errorMessage;
if (!$.isFunction(funct)) {
funct = options.rules.extra[rule];
}
if ($.isFunction(funct)) {
result = funct(options, word, score);
if (result) {
totalScore += result;
}
if (result < 0 || (!$.isNumeric(result) && !result)) {
errorMessage = options.ui.spanError(options, rule);
if (errorMessage.length > 0) {
options.instances.errors.push(errorMessage);
}
}
}
}
});
return totalScore;
};
}(jQuery, rulesEngine));
try {
if (module && module.exports) {
module.exports = rulesEngine;
}
} catch (ignore) {}
// Source: src/options.js
var defaultOptions = {};
defaultOptions.common = {};
defaultOptions.common.minChar = 6;
defaultOptions.common.usernameField = "#username";
defaultOptions.common.userInputs = [
// Selectors for input fields with user input
];
defaultOptions.common.onLoad = undefined;
defaultOptions.common.onKeyUp = undefined;
defaultOptions.common.zxcvbn = false;
defaultOptions.common.zxcvbnTerms = [
// List of disrecommended words
];
defaultOptions.common.debug = false;
defaultOptions.rules = {};
defaultOptions.rules.extra = {};
defaultOptions.rules.scores = {
wordNotEmail: -100,
wordLength: -50,
wordSimilarToUsername: -100,
wordSequences: -20,
wordTwoCharacterClasses: 2,
wordRepetitions: -25,
wordLowercase: 1,
wordUppercase: 3,
wordOneNumber: 3,
wordThreeNumbers: 5,
wordOneSpecialChar: 3,
wordTwoSpecialChar: 5,
wordUpperLowerCombo: 2,
wordLetterNumberCombo: 2,
wordLetterNumberCharCombo: 2
};
defaultOptions.rules.activated = {
wordNotEmail: true,
wordLength: true,
wordSimilarToUsername: true,
wordSequences: true,
wordTwoCharacterClasses: false,
wordRepetitions: false,
wordLowercase: true,
wordUppercase: true,
wordOneNumber: true,
wordThreeNumbers: true,
wordOneSpecialChar: true,
wordTwoSpecialChar: true,
wordUpperLowerCombo: true,
wordLetterNumberCombo: true,
wordLetterNumberCharCombo: true
};
defaultOptions.rules.raisePower = 1.4;
defaultOptions.ui = {};
defaultOptions.ui.bootstrap2 = false;
defaultOptions.ui.bootstrap4 = false;
defaultOptions.ui.colorClasses = [
"danger", "danger", "danger", "warning", "warning", "success"
];
defaultOptions.ui.showProgressBar = true;
defaultOptions.ui.progressBarEmptyPercentage = 1;
defaultOptions.ui.progressBarMinPercentage = 1;
defaultOptions.ui.progressBarExtraCssClasses = '';
defaultOptions.ui.showPopover = false;
defaultOptions.ui.popoverPlacement = "bottom";
defaultOptions.ui.showStatus = false;
defaultOptions.ui.spanError = function (options, key) {
"use strict";
var text = options.i18n.t(key);
if (!text) { return ''; }
return '<span style="color: #d52929">' + text + '</span>';
};
defaultOptions.ui.popoverError = function (options) {
"use strict";
var errors = options.instances.errors,
errorsTitle = options.i18n.t("errorList"),
message = "<div>" + errorsTitle + "<ul class='error-list' style='margin-bottom: 0;'>";
jQuery.each(errors, function (idx, err) {
message += "<li>" + err + "</li>";
});
message += "</ul></div>";
return message;
};
defaultOptions.ui.showVerdicts = true;
defaultOptions.ui.showVerdictsInsideProgressBar = false;
defaultOptions.ui.useVerdictCssClass = false;
defaultOptions.ui.showErrors = false;
defaultOptions.ui.showScore = false;
defaultOptions.ui.container = undefined;
defaultOptions.ui.viewports = {
progress: undefined,
verdict: undefined,
errors: undefined,
score: undefined
};
defaultOptions.ui.scores = [0, 14, 26, 38, 50];
defaultOptions.i18n = {};
defaultOptions.i18n.t = i18n.t;
// Source: src/ui.js
var ui = {};
(function ($, ui) {
"use strict";
var statusClasses = ["error", "warning", "success"],
verdictKeys = [
"veryWeak", "weak", "normal", "medium", "strong", "veryStrong"
];
ui.getContainer = function (options, $el) {
var $container;
$container = $(options.ui.container);
if (!($container && $container.length === 1)) {
$container = $el.parent();
}
return $container;
};
ui.findElement = function ($container, viewport, cssSelector) {
if (viewport) {
return $container.find(viewport).find(cssSelector);
}
return $container.find(cssSelector);
};
ui.getUIElements = function (options, $el) {
var $container, selector, result;
if (options.instances.viewports) {
return options.instances.viewports;
}
$container = ui.getContainer(options, $el);
result = {};
if (options.ui.bootstrap4) {
selector = "progress.progress";
} else {
selector = "div.progress";
}
result.$progressbar = ui.findElement($container, options.ui.viewports.progress, selector);
if (options.ui.showVerdictsInsideProgressBar) {
result.$verdict = result.$progressbar.find("span.password-verdict");
}
if (!options.ui.showPopover) {
if (!options.ui.showVerdictsInsideProgressBar) {
result.$verdict = ui.findElement($container, options.ui.viewports.verdict, "span.password-verdict");
}
result.$errors = ui.findElement($container, options.ui.viewports.errors, "ul.error-list");
}
result.$score = ui.findElement($container, options.ui.viewports.score,
"span.password-score");
options.instances.viewports = result;
return result;
};
ui.initProgressBar = function (options, $el) {
var $container = ui.getContainer(options, $el),
progressbar = "<div class='progress ";
if (options.ui.bootstrap2) {
// Boostrap 2
progressbar += options.ui.progressBarExtraCssClasses +
"'><div class='";
} else if (!options.ui.bootstrap2 && !options.ui.bootstrap4) {
// Bootstrap 3
progressbar += "'><div class='" +
options.ui.progressBarExtraCssClasses + " progress-";
}
progressbar += "bar'>";
if (options.ui.bootstrap4) {
// Boostrap 4
progressbar = "<progress class='progress " +
options.ui.progressBarExtraCssClasses + "' value='0' max='100'>";
}
if (options.ui.showVerdictsInsideProgressBar) {
progressbar += "<span class='password-verdict'></span>";
}
if (options.ui.bootstrap4) {
progressbar += "</progress>";
} else {
progressbar += "</div></div>";
}
if (options.ui.viewports.progress) {
$container.find(options.ui.viewports.progress).append(progressbar);
} else {
$(progressbar).insertAfter($el);
}
};
ui.initHelper = function (options, $el, html, viewport) {
var $container = ui.getContainer(options, $el);
if (viewport) {
$container.find(viewport).append(html);
} else {
$(html).insertAfter($el);
}
};
ui.initVerdict = function (options, $el) {
ui.initHelper(options, $el, "<span class='password-verdict'></span>",
options.ui.viewports.verdict);
};
ui.initErrorList = function (options, $el) {
ui.initHelper(options, $el, "<ul class='error-list'></ul>",
options.ui.viewports.errors);
};
ui.initScore = function (options, $el) {
ui.initHelper(options, $el, "<span class='password-score'></span>",
options.ui.viewports.score);
};
ui.initPopover = function (options, $el) {
$el.popover("destroy");
$el.popover({
html: true,
placement: options.ui.popoverPlacement,
trigger: "manual",
content: " "
});
};
ui.initUI = function (options, $el) {
if (options.ui.showPopover) {
ui.initPopover(options, $el);
} else {
if (options.ui.showErrors) { ui.initErrorList(options, $el); }
if (options.ui.showVerdicts && !options.ui.showVerdictsInsideProgressBar) {
ui.initVerdict(options, $el);
}
}
if (options.ui.showProgressBar) {
ui.initProgressBar(options, $el);
}
if (options.ui.showScore) {
ui.initScore(options, $el);
}
};
ui.updateProgressBar = function (options, $el, cssClass, percentage) {
var $progressbar = ui.getUIElements(options, $el).$progressbar,
$bar = $progressbar.find(".progress-bar"),
cssPrefix = "progress-";
if (options.ui.bootstrap2) {
$bar = $progressbar.find(".bar");
cssPrefix = "";
}
$.each(options.ui.colorClasses, function (idx, value) {
if (options.ui.bootstrap4) {
$progressbar.removeClass(cssPrefix + value);
} else {
$bar.removeClass(cssPrefix + "bar-" + value);
}
});
if (options.ui.bootstrap4) {
$progressbar.addClass(cssPrefix + options.ui.colorClasses[cssClass]);
$progressbar.val(percentage);
} else {
$bar.addClass(cssPrefix + "bar-" + options.ui.colorClasses[cssClass]);
$bar.css("width", percentage + '%');
}
};
ui.updateVerdict = function (options, $el, cssClass, text) {
var $verdict = ui.getUIElements(options, $el).$verdict;
$verdict.removeClass(options.ui.colorClasses.join(' '));
if (cssClass > -1) {
$verdict.addClass(options.ui.colorClasses[cssClass]);
}
$verdict.html(text);
};
ui.updateErrors = function (options, $el, remove) {
var $errors = ui.getUIElements(options, $el).$errors,
html = "";
if (!remove) {
$.each(options.instances.errors, function (idx, err) {
html += "<li>" + err + "</li>";
});
}
$errors.html(html);
};
ui.updateScore = function (options, $el, score, remove) {
var $score = ui.getUIElements(options, $el).$score,
html = "";
if (!remove) { html = score.toFixed(2); }
$score.html(html);
};
ui.updatePopover = function (options, $el, verdictText, remove) {
var popover = $el.data("bs.popover"),
html = "",
hide = true;
if (options.ui.showVerdicts &&
!options.ui.showVerdictsInsideProgressBar &&
verdictText.length > 0) {
html = "<h5><span class='password-verdict'>" + verdictText +
"</span></h5>";
hide = false;
}
if (options.ui.showErrors) {
if (options.instances.errors.length > 0) {
hide = false;
}
html += options.ui.popoverError(options);
}
if (hide || remove) {
$el.popover("hide");
return;
}
if (options.ui.bootstrap2) { popover = $el.data("popover"); }
if (popover.$arrow && popover.$arrow.parents("body").length > 0) {
$el.find("+ .popover .popover-content").html(html);
} else {
// It's hidden
popover.options.content = html;
$el.popover("show");
}
};
ui.updateFieldStatus = function (options, $el, cssClass, remove) {
var targetClass = options.ui.bootstrap2 ? ".control-group" : ".form-group",
$container = $el.parents(targetClass).first();
$.each(statusClasses, function (idx, css) {
if (!options.ui.bootstrap2) { css = "has-" + css; }
$container.removeClass(css);
});
if (remove) { return; }
cssClass = statusClasses[cssClass];
if (!options.ui.bootstrap2) { cssClass = "has-" + cssClass; }
$container.addClass(cssClass);
};
ui.percentage = function (options, score, maximun) {
var result = Math.floor(100 * score / maximun),
min = options.ui.progressBarMinPercentage;
result = result <= min ? min : result;
result = result > 100 ? 100 : result;
return result;
};
ui.getVerdictAndCssClass = function (options, score) {
var level, verdict;
if (score === undefined) { return ['', 0]; }
if (score <= options.ui.scores[0]) {
level = 0;
} else if (score < options.ui.scores[1]) {
level = 1;
} else if (score < options.ui.scores[2]) {
level = 2;
} else if (score < options.ui.scores[3]) {
level = 3;
} else if (score < options.ui.scores[4]) {
level = 4;
} else {
level = 5;
}
verdict = verdictKeys[level];
return [options.i18n.t(verdict), level];
};
ui.updateUI = function (options, $el, score) {
var cssClass, barPercentage, verdictText, verdictCssClass;
cssClass = ui.getVerdictAndCssClass(options, score);
verdictText = score === 0 ? '' : cssClass[0];
cssClass = cssClass[1];
verdictCssClass = options.ui.useVerdictCssClass ? cssClass : -1;
if (options.ui.showProgressBar) {
if (score === undefined) {
barPercentage = options.ui.progressBarEmptyPercentage;
} else {
barPercentage = ui.percentage(options, score, options.ui.scores[4]);
}
ui.updateProgressBar(options, $el, cssClass, barPercentage);
if (options.ui.showVerdictsInsideProgressBar) {
ui.updateVerdict(options, $el, verdictCssClass, verdictText);
}
}
if (options.ui.showStatus) {
ui.updateFieldStatus(options, $el, cssClass, score === undefined);
}
if (options.ui.showPopover) {
ui.updatePopover(options, $el, verdictText, score === undefined);
} else {
if (options.ui.showVerdicts && !options.ui.showVerdictsInsideProgressBar) {
ui.updateVerdict(options, $el, verdictCssClass, verdictText);
}
if (options.ui.showErrors) {
ui.updateErrors(options, $el, score === undefined);
}
}
if (options.ui.showScore) {
ui.updateScore(options, $el, score, score === undefined);
}
};
}(jQuery, ui));
// Source: src/methods.js
var methods = {};
(function ($, methods) {
"use strict";
var onKeyUp, onPaste, applyToAll;
onKeyUp = function (event) {
var $el = $(event.target),
options = $el.data("pwstrength-bootstrap"),
word = $el.val(),
userInputs,
verdictText,
verdictLevel,
score;
if (options === undefined) { return; }
options.instances.errors = [];
if (word.length === 0) {
score = undefined;
} else {
if (options.common.zxcvbn) {
userInputs = [];
$.each(options.common.userInputs.concat([options.common.usernameField]), function (idx, selector) {
var value = $(selector).val();
if (value) { userInputs.push(value); }
});
userInputs = userInputs.concat(options.common.zxcvbnTerms);
score = Math.log2(zxcvbn(word, userInputs).guesses);
} else {
score = rulesEngine.executeRules(options, word);
}
}
ui.updateUI(options, $el, score);
verdictText = ui.getVerdictAndCssClass(options, score);
verdictLevel = verdictText[2];
verdictText = verdictText[0];
if (options.common.debug) { console.log(score + ' - ' + verdictText); }
if ($.isFunction(options.common.onKeyUp)) {
options.common.onKeyUp(event, {
score: score,
verdictText: verdictText,
verdictLevel: verdictLevel
});
}
};
onPaste = function (event) {
// This handler is necessary because the paste event fires before the
// content is actually in the input, so we cannot read its value right
// away. Therefore, the timeouts.
var $el = $(event.target),
word = $el.val(),
tries = 0,
callback;
callback = function () {
var newWord = $el.val();
if (newWord !== word) {
onKeyUp(event);
} else if (tries < 3) {
tries += 1;
setTimeout(callback, 100);
}
};
setTimeout(callback, 100);
};
methods.init = function (settings) {
this.each(function (idx, el) {
// Make it deep extend (first param) so it extends also the
// rules and other inside objects
var clonedDefaults = $.extend(true, {}, defaultOptions),
localOptions = $.extend(true, clonedDefaults, settings),
$el = $(el);
localOptions.instances = {};
$el.data("pwstrength-bootstrap", localOptions);
$el.on("keyup", onKeyUp);
$el.on("change", onKeyUp);
$el.on("paste", onPaste);
ui.initUI(localOptions, $el);
$el.trigger("keyup");
if ($.isFunction(localOptions.common.onLoad)) {
localOptions.common.onLoad();
}
});
return this;
};
methods.destroy = function () {
this.each(function (idx, el) {
var $el = $(el),
options = $el.data("pwstrength-bootstrap"),
elements = ui.getUIElements(options, $el);
elements.$progressbar.remove();
elements.$verdict.remove();
elements.$errors.remove();
$el.removeData("pwstrength-bootstrap");
});
};
methods.forceUpdate = function () {
this.each(function (idx, el) {
var event = { target: el };
onKeyUp(event);
});
};
methods.addRule = function (name, method, score, active) {
this.each(function (idx, el) {
var options = $(el).data("pwstrength-bootstrap");
options.rules.activated[name] = active;
options.rules.scores[name] = score;
options.rules.extra[name] = method;
});
};
applyToAll = function (rule, prop, value) {
this.each(function (idx, el) {
$(el).data("pwstrength-bootstrap").rules[prop][rule] = value;
});
};
methods.changeScore = function (rule, score) {
applyToAll.call(this, rule, "scores", score);
};
methods.ruleActive = function (rule, active) {
applyToAll.call(this, rule, "activated", active);
};
$.fn.pwstrength = function (method) {
var result;
if (methods[method]) {
result = methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === "object" || !method) {
result = methods.init.apply(this, arguments);
} else {
$.error("Method " + method + " does not exist on jQuery.pwstrength-bootstrap");
}
return result;
};
}(jQuery, methods));
}(jQuery)); | {
"pile_set_name": "Github"
} |
/*
DeaDBeeF -- the music player
Copyright (C) 2009-2015 Alexey Yakovenko and other contributors
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include <ctype.h>
#include "../../gettext.h"
#include "ddblistview.h"
#include "trkproperties.h"
#include "interface.h"
#include "support.h"
#include "../../deadbeef.h"
#include "gtkui.h"
#include "mainplaylist.h"
#include "search.h"
#include "ddbcellrenderertextmultiline.h"
#include "tagwritersettings.h"
#include "wingeom.h"
#include "callbacks.h"
#include "../../shared/trkproperties_shared.h"
//#define trace(...) { fprintf(stderr, __VA_ARGS__); }
#define trace(fmt,...)
#define min(x,y) ((x)<(y)?(x):(y))
static GtkWidget *trackproperties;
static GtkCellRenderer *rend_text2;
static GtkListStore *store;
static GtkListStore *propstore;
int trkproperties_modified;
static DB_playItem_t **tracks;
static int numtracks;
static GtkWidget *progressdlg;
static int progress_aborted;
static int last_ctx;
static ddb_playlist_t *last_plt;
// Max length of a string displayed in the TableView
// If a string is longer -- it gets clipped, and appended with " (…)", like with linebreaks
#define MAX_GUI_FIELD_LEN 500
static char *
clip_multiline_value (const char *v) {
char *clipped_val = NULL;
size_t l = strlen (v);
const char multiline_ellipsis[] = " (…)";
int i;
for (i = 0; i < l; i++) {
if (v[i] == '\r' || v[i] == '\n') {
break;
}
}
if (l >= MAX_GUI_FIELD_LEN && (i == l || i >= MAX_GUI_FIELD_LEN)) {
i = MAX_GUI_FIELD_LEN;
}
if (i != l) {
clipped_val = malloc (i + sizeof (multiline_ellipsis));
memcpy (clipped_val, v, i);
memcpy (clipped_val + i, multiline_ellipsis, sizeof (multiline_ellipsis));
}
return clipped_val;
}
gboolean
on_trackproperties_delete_event (GtkWidget *widget,
GdkEvent *event,
gpointer user_data)
{
if (trkproperties_modified) {
GtkWidget *dlg = gtk_message_dialog_new (GTK_WINDOW (trackproperties), GTK_DIALOG_MODAL, GTK_MESSAGE_WARNING, GTK_BUTTONS_YES_NO, _("You've modified data for this track."));
gtk_window_set_transient_for (GTK_WINDOW (dlg), GTK_WINDOW (trackproperties));
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dlg), _("Really close the window?"));
gtk_window_set_title (GTK_WINDOW (dlg), _("Warning"));
int response = gtk_dialog_run (GTK_DIALOG (dlg));
gtk_widget_destroy (dlg);
if (response != GTK_RESPONSE_YES) {
return TRUE;
}
}
gtk_widget_destroy (widget);
rend_text2 = NULL;
trackproperties = NULL;
if (tracks) {
for (int i = 0; i < numtracks; i++) {
deadbeef->pl_item_unref (tracks[i]);
}
free (tracks);
tracks = NULL;
numtracks = 0;
}
return TRUE;
}
int trkproperties_block_keyhandler = 0;
gboolean
on_trackproperties_key_press_event (GtkWidget *widget,
GdkEventKey *event,
gpointer user_data)
{
if (trkproperties_block_keyhandler) {
return FALSE;
}
if (event->keyval == GDK_Escape) {
on_trackproperties_delete_event (trackproperties, NULL, NULL);
return TRUE;
}
else if (event->keyval == GDK_Delete) {
on_trkproperties_remove_activate (NULL, NULL);
return TRUE;
}
else if (event->keyval == GDK_Insert) {
on_trkproperties_add_new_field_activate (NULL, NULL);
return TRUE;
}
return FALSE;
}
void
trkproperties_destroy (void) {
if (trackproperties) {
on_trackproperties_delete_event (trackproperties, NULL, NULL);
}
if (last_plt) {
deadbeef->plt_unref (last_plt);
last_plt = NULL;
}
last_ctx = -1;
}
void
on_closebtn_clicked (GtkButton *button,
gpointer user_data)
{
trkproperties_destroy ();
}
static void
update_meta_iter_with_edited_value (GtkTreeIter *iter, const char *new_text) {
char *clipped_val = clip_multiline_value (new_text);
if (!clipped_val) {
gtk_list_store_set (store, iter, 1, new_text, 3, 0, 4, new_text, -1);
}
else {
gtk_list_store_set (store, iter, 1, clipped_val, 3, 0, 4, new_text, -1);
free (clipped_val);
}
}
void
on_metadata_edited (GtkCellRendererText *renderer, gchar *path, gchar *new_text, gpointer user_data) {
GtkListStore *store = GTK_LIST_STORE (user_data);
GtkTreePath *treepath = gtk_tree_path_new_from_string (path);
GtkTreeIter iter;
if (!treepath) {
return;
}
gboolean valid = gtk_tree_model_get_iter (GTK_TREE_MODEL (store), &iter, treepath);
gtk_tree_path_free (treepath);
if (!valid) {
return;
}
GValue value = {0,};
GValue mult = {0,};
gtk_tree_model_get_value (GTK_TREE_MODEL (store), &iter, 4, &value);
gtk_tree_model_get_value (GTK_TREE_MODEL (store), &iter, 3, &mult);
const char *svalue = g_value_get_string (&value);
if (!svalue) {
svalue = "";
}
// The multiple values case gets cleared on attempt to edit,
// that's why the change gets applied unconditionally for multivalue case
int imult = g_value_get_int (&mult);
if (strcmp (svalue, new_text) || imult) {
update_meta_iter_with_edited_value (&iter, new_text);
trkproperties_modified = 1;
}
G_IS_VALUE (&value) ? (g_value_unset (&value), NULL) : NULL;
G_IS_VALUE (&mult) ? (g_value_unset (&mult), NULL) : NULL;
trkproperties_block_keyhandler = 0;
}
void
add_field (GtkListStore *store, const char *key, const char *title, int is_prop, DB_playItem_t **tracks, int numtracks) {
// get value to edit
const char *mult = is_prop ? "" : _("[Multiple values] ");
char val[5000];
size_t ml = strlen (mult);
memcpy (val, mult, ml+1);
int n = trkproperties_get_field_value (val + ml, sizeof (val) - ml, key, tracks, numtracks);
GtkTreeIter iter;
gtk_list_store_append (store, &iter);
if (!is_prop) {
if (n) {
char *clipped_val = clip_multiline_value (val);
if (!clipped_val) {
gtk_list_store_set (store, &iter, 0, title, 1, val, 2, key, 3, n ? 1 : 0, 4, val, -1);
}
else {
gtk_list_store_set (store, &iter, 0, title, 1, clipped_val, 2, key, 3, n ? 1 : 0, 4, val, -1);
free (clipped_val);
}
}
else {
char *v = val + ml;
char *clipped_val = clip_multiline_value (v);
if (!clipped_val) {
gtk_list_store_set (store, &iter, 0, title, 1, v, 2, key, 3, n ? 1 : 0, 4, v, -1);
}
else {
gtk_list_store_set (store, &iter, 0, title, 1, clipped_val, 2, key, 3, n ? 1 : 0, 4, v, -1);
free (clipped_val);
}
}
}
else {
gtk_list_store_set (store, &iter, 0, title, 1, n ? val : val + ml, -1);
}
}
void
trkproperties_fill_meta (GtkListStore *store, DB_playItem_t **tracks, int numtracks) {
gtk_list_store_clear (store);
if (!tracks) {
return;
}
const char **keys = NULL;
int nkeys = trkproperties_build_key_list (&keys, 0, tracks, numtracks);
// add "standard" fields
for (int i = 0; trkproperties_types[i]; i += 2) {
add_field (store, trkproperties_types[i], _(trkproperties_types[i+1]), 0, tracks, numtracks);
}
// add all other fields
for (int k = 0; k < nkeys; k++) {
int i;
for (i = 0; trkproperties_types[i]; i += 2) {
if (!strcasecmp (keys[k], trkproperties_types[i])) {
break;
}
}
if (trkproperties_types[i]) {
continue;
}
size_t l = strlen (keys[k]);
char title[l + 3];
snprintf (title, sizeof (title), "<%s>", keys[k]);
add_field (store, keys[k], title, 0, tracks, numtracks);
}
if (keys) {
free (keys);
}
}
void
trkproperties_fill_metadata (void) {
if (!trackproperties) {
return;
}
trkproperties_modified = 0;
deadbeef->pl_lock ();
trkproperties_fill_meta (store, tracks, numtracks);
gtk_list_store_clear (propstore);
// hardcoded properties
for (int i = 0; trkproperties_hc_props[i]; i += 2) {
add_field (propstore, trkproperties_hc_props[i], _(trkproperties_hc_props[i+1]), 1, tracks, numtracks);
}
// properties
const char **keys = NULL;
int nkeys = trkproperties_build_key_list (&keys, 1, tracks, numtracks);
for (int k = 0; k < nkeys; k++) {
int i;
for (i = 0; trkproperties_hc_props[i]; i += 2) {
if (!strcasecmp (keys[k], trkproperties_hc_props[i])) {
break;
}
}
if (trkproperties_hc_props[i]) {
continue;
}
size_t l = strlen (keys[k]);
char title[l + 3];
snprintf (title, sizeof (title), "<%s>", keys[k]+1);
add_field (propstore, keys[k], title, 1, tracks, numtracks);
}
if (keys) {
free (keys);
}
deadbeef->pl_unlock ();
}
void
meta_value_transform_func (GtkTreeViewColumn *tree_column,
GtkCellRenderer *cell,
GtkTreeModel *tree_model,
GtkTreeIter *iter,
gpointer data) {
}
void
show_track_properties_dlg (int ctx, ddb_playlist_t *plt) {
last_ctx = ctx;
deadbeef->plt_ref (plt);
if (last_plt) {
deadbeef->plt_unref (last_plt);
}
last_plt = plt;
trkproperties_free_track_list (&tracks, &numtracks);
trkproperties_build_track_list_for_ctx (plt, ctx, &tracks, &numtracks);
GtkTreeView *tree;
GtkTreeView *proptree;
if (!trackproperties) {
trackproperties = create_trackproperties ();
gtk_window_set_transient_for (GTK_WINDOW (trackproperties), GTK_WINDOW (mainwin));
wingeom_restore (trackproperties, "trkproperties", -1, -1, 300, 400, 0);
// metadata tree
tree = GTK_TREE_VIEW (lookup_widget (trackproperties, "metalist"));
store = gtk_list_store_new (5, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INT, G_TYPE_STRING);
gtk_tree_view_set_model (tree, GTK_TREE_MODEL (store));
GtkCellRenderer *rend_text = gtk_cell_renderer_text_new ();
rend_text2 = GTK_CELL_RENDERER (ddb_cell_renderer_text_multiline_new ());
g_signal_connect ((gpointer)rend_text2, "edited",
G_CALLBACK (on_metadata_edited),
store);
GtkTreeViewColumn *col1 = gtk_tree_view_column_new_with_attributes (_("Key"), rend_text, "text", 0, NULL);
GtkTreeViewColumn *col2 = gtk_tree_view_column_new_with_attributes (_("Value"), rend_text2, "text", 1, NULL);
//gtk_tree_view_column_set_cell_data_func (col2, rend_text2, meta_value_transform_func, NULL, NULL);
gtk_tree_view_append_column (tree, col1);
gtk_tree_view_append_column (tree, col2);
// properties tree
proptree = GTK_TREE_VIEW (lookup_widget (trackproperties, "properties"));
propstore = gtk_list_store_new (2, G_TYPE_STRING, G_TYPE_STRING);
gtk_tree_view_set_model (proptree, GTK_TREE_MODEL (propstore));
GtkCellRenderer *rend_propkey = gtk_cell_renderer_text_new ();
GtkCellRenderer *rend_propvalue = gtk_cell_renderer_text_new ();
g_object_set (G_OBJECT (rend_propvalue), "editable", TRUE, NULL);
col1 = gtk_tree_view_column_new_with_attributes (_("Key"), rend_propkey, "text", 0, NULL);
col2 = gtk_tree_view_column_new_with_attributes (_("Value"), rend_propvalue, "text", 1, NULL);
gtk_tree_view_append_column (proptree, col1);
gtk_tree_view_append_column (proptree, col2);
}
else {
tree = GTK_TREE_VIEW (lookup_widget (trackproperties, "metalist"));
store = GTK_LIST_STORE (gtk_tree_view_get_model (tree));
gtk_list_store_clear (store);
proptree = GTK_TREE_VIEW (lookup_widget (trackproperties, "properties"));
propstore = GTK_LIST_STORE (gtk_tree_view_get_model (proptree));
gtk_list_store_clear (propstore);
}
if (numtracks == 1) {
deadbeef->pl_lock ();
gtk_entry_set_text (GTK_ENTRY (lookup_widget (trackproperties, "filename")), deadbeef->pl_find_meta_raw (tracks[0], ":URI"));
deadbeef->pl_unlock ();
}
else {
gtk_entry_set_text (GTK_ENTRY (lookup_widget (trackproperties, "filename")), _("[Multiple values]"));
}
g_object_set (G_OBJECT (rend_text2), "editable", TRUE, NULL);
GtkWidget *widget = trackproperties;
trkproperties_fill_metadata ();
gtk_widget_set_sensitive (lookup_widget (widget, "write_tags"), TRUE);
gtk_widget_show (widget);
gtk_window_present (GTK_WINDOW (widget));
}
static gboolean
set_metadata_cb (GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter, gpointer data) {
GValue mult = {0,};
gtk_tree_model_get_value (model, iter, 3, &mult);
int smult = g_value_get_int (&mult);
if (!smult) {
GValue key = {0,}, value = {0,};
gtk_tree_model_get_value (model, iter, 2, &key);
gtk_tree_model_get_value (model, iter, 4, &value);
const char *skey = g_value_get_string (&key);
const char *svalue = g_value_get_string (&value);
int num_values = 1;
for (int i = 0; svalue[i]; i++) {
if (svalue[i] == ';') {
num_values++;
}
}
char **values = calloc (num_values, sizeof (char *));
const char *p = svalue;
const char *e = p;
int n = 0;
do {
while (*e && *e != ';') {
e++;
}
// trim
const char *rb = p;
const char *re = e-1;
while (rb <= re) {
if ((uint8_t)(*rb) > 0x20) {
break;
}
rb++;
}
while (re >= rb) {
if ((uint8_t)(*re) > 0x20) {
break;
}
re--;
}
if (rb <= re) {
re++;
char *v = malloc (re-rb+1);
memcpy (v, rb, re-rb);
v[re-rb] = 0;
values[n++] = v;
}
if (!*e) {
break;
}
p = ++e;
} while (*p);
for (int i = 0; i < numtracks; i++) {
deadbeef->pl_delete_meta (tracks[i], skey);
if (*svalue) {
for (int k = 0; k < n; k++) {
if (values[k] && *values[k]) {
deadbeef->pl_append_meta (tracks[i], skey, values[k]);
}
}
}
}
for (int k = 0; k < n; k++) {
if (values[k]) {
free (values[k]);
}
}
free (values);
}
return FALSE;
}
static gboolean
write_finished_cb (void *ctx) {
gtk_widget_destroy (progressdlg);
progressdlg = NULL;
trkproperties_modified = 0;
if (last_plt) {
deadbeef->plt_modified (last_plt);
show_track_properties_dlg (last_ctx, last_plt);
}
return FALSE;
}
static gboolean
set_progress_cb (void *ctx) {
DB_playItem_t *track = ctx;
GtkWidget *progressitem = lookup_widget (progressdlg, "progresstitle");
deadbeef->pl_lock ();
gtk_entry_set_text (GTK_ENTRY (progressitem), deadbeef->pl_find_meta_raw (track, ":URI"));
deadbeef->pl_unlock ();
deadbeef->pl_item_unref (track);
return FALSE;
}
static void
write_meta_worker (void *ctx) {
for (int t = 0; t < numtracks; t++) {
if (progress_aborted) {
break;
}
DB_playItem_t *track = tracks[t];
deadbeef->pl_lock ();
const char *dec = deadbeef->pl_find_meta_raw (track, ":DECODER");
char decoder_id[100];
if (dec) {
strncpy (decoder_id, dec, sizeof (decoder_id));
}
int match = track && dec;
deadbeef->pl_unlock ();
if (match) {
int is_subtrack = deadbeef->pl_get_item_flags (track) & DDB_IS_SUBTRACK;
if (is_subtrack) {
continue;
}
deadbeef->pl_item_ref (track);
g_idle_add (set_progress_cb, track);
// find decoder
DB_decoder_t *dec = NULL;
DB_decoder_t **decoders = deadbeef->plug_get_decoder_list ();
for (int i = 0; decoders[i]; i++) {
if (!strcmp (decoders[i]->plugin.id, decoder_id)) {
dec = decoders[i];
if (dec->write_metadata) {
dec->write_metadata (track);
}
break;
}
}
}
}
g_idle_add (write_finished_cb, ctx);
}
static gboolean
on_progress_delete_event (GtkWidget *widget,
GdkEvent *event,
gpointer user_data)
{
progress_aborted = 1;
return gtk_widget_hide_on_delete (widget);
}
static void
on_progress_abort (GtkButton *button,
gpointer user_data)
{
progress_aborted = 1;
}
void
on_write_tags_clicked (GtkButton *button,
gpointer user_data)
{
deadbeef->pl_lock ();
GtkTreeView *tree = GTK_TREE_VIEW (lookup_widget (trackproperties, "metalist"));
GtkTreeModel *model = GTK_TREE_MODEL (gtk_tree_view_get_model (tree));
// delete all metadata properties that are not in the listview
for (int i = 0; i < numtracks; i++) {
DB_metaInfo_t *meta = deadbeef->pl_get_metadata_head (tracks[i]);
while (meta) {
DB_metaInfo_t *next = meta->next;
if (meta->key[0] != ':' && meta->key[0] != '!' && meta->key[0] != '_') {
GtkTreeIter iter;
gboolean res = gtk_tree_model_get_iter_first (model, &iter);
while (res) {
GValue key = {0,};
gtk_tree_model_get_value (model, &iter, 2, &key);
const char *skey = g_value_get_string (&key);
if (!strcasecmp (skey, meta->key)) {
// field found, don't delete
break;
}
res = gtk_tree_model_iter_next (GTK_TREE_MODEL (store), &iter);
}
if (!res) {
// field not found, delete
deadbeef->pl_delete_metadata (tracks[i], meta);
}
}
meta = next;
}
}
// put all metainfo into track
gtk_tree_model_foreach (model, set_metadata_cb, NULL);
deadbeef->pl_unlock ();
if (numtracks > 25) {
deadbeef->sendmessage (DB_EV_PLAYLISTCHANGED, 0, DDB_PLAYLIST_CHANGE_CONTENT, 0);
}
else {
for (int i = 0; i < numtracks; i++) {
ddb_event_track_t *ev = (ddb_event_track_t *)deadbeef->event_alloc (DB_EV_TRACKINFOCHANGED);
ev->track = tracks[i];
deadbeef->pl_item_ref (ev->track);
deadbeef->event_send ((ddb_event_t*)ev, 0, 0);
}
}
progress_aborted = 0;
progressdlg = create_progressdlg ();
gtk_window_set_title (GTK_WINDOW (progressdlg), _("Writing tags..."));
g_signal_connect ((gpointer) progressdlg, "delete_event",
G_CALLBACK (on_progress_delete_event),
NULL);
GtkWidget *cancelbtn = lookup_widget (progressdlg, "cancelbtn");
g_signal_connect ((gpointer) cancelbtn, "clicked",
G_CALLBACK (on_progress_abort),
NULL);
gtk_widget_show_all (progressdlg);
gtk_window_present (GTK_WINDOW (progressdlg));
gtk_window_set_transient_for (GTK_WINDOW (progressdlg), GTK_WINDOW (trackproperties));
// start new thread for writing metadata
intptr_t tid = deadbeef->thread_start (write_meta_worker, NULL);
deadbeef->thread_detach (tid);
}
gboolean
on_metalist_button_press_event (GtkWidget *widget,
GdkEventButton *event,
gpointer user_data)
{
if (event->button == 3) {
GtkWidget *menu = create_trkproperties_popup_menu ();
if (numtracks != 1) {
gtk_widget_set_sensitive (lookup_widget (menu, "trkproperties_edit"), FALSE);
}
gtk_menu_attach_to_widget (GTK_MENU (menu), GTK_WIDGET (widget), NULL);
gtk_menu_popup (GTK_MENU (menu), NULL, NULL, NULL, NULL, event->button, gtk_get_current_event_time());
}
return FALSE;
}
void
on_tagwriter_settings_clicked (GtkButton *button,
gpointer user_data)
{
run_tagwriter_settings (trackproperties);
}
gboolean
on_trackproperties_configure_event (GtkWidget *widget,
GdkEventConfigure *event,
gpointer user_data)
{
wingeom_save (widget, "trkproperties");
return FALSE;
}
gboolean
on_trackproperties_window_state_event (GtkWidget *widget,
GdkEventWindowState *event,
gpointer user_data)
{
wingeom_save_max (event, widget, "trkproperties");
return FALSE;
}
void
on_trkproperties_edit_activate (GtkMenuItem *menuitem,
gpointer user_data)
{
if (numtracks != 1) {
return; // TODO: multiple track editing support
}
GtkTreeView *treeview = GTK_TREE_VIEW (lookup_widget (trackproperties, "metalist"));
GtkTreeSelection *sel = gtk_tree_view_get_selection (treeview);
int count = gtk_tree_selection_count_selected_rows (sel);
if (count != 1) {
return; // multiple fields can't be edited at the same time
}
GtkWidget *dlg = create_edit_tag_value_dlg ();
gtk_window_set_transient_for (GTK_WINDOW (dlg), GTK_WINDOW (trackproperties));
gtk_dialog_set_default_response (GTK_DIALOG (dlg), GTK_RESPONSE_OK);
GList *lst = gtk_tree_selection_get_selected_rows (sel, NULL);
GtkTreePath *path = lst->data;
GtkTreeIter iter;
gtk_tree_model_get_iter (GTK_TREE_MODEL (store), &iter, path);
GValue key = {0,};
gtk_tree_model_get_value (GTK_TREE_MODEL (store), &iter, 2, &key);
GValue value = {0,};
gtk_tree_model_get_value (GTK_TREE_MODEL (store), &iter, 4, &value);
const char *skey = g_value_get_string (&key);
const char *svalue = g_value_get_string (&value);
char *uppercase_key = strdup (skey);
for (char *p = uppercase_key; *p; p++) {
*p = toupper (*p);
}
gtk_entry_set_text (GTK_ENTRY (lookup_widget (dlg, "field_name")), uppercase_key);
free (uppercase_key);
GtkTextBuffer *buffer = gtk_text_buffer_new (NULL);
gtk_text_buffer_set_text (buffer, svalue, (gint)strlen (svalue));
gtk_text_view_set_buffer (GTK_TEXT_VIEW (lookup_widget (dlg, "field_value")), buffer);
g_value_unset (&key);
g_value_unset (&value);
for (GList *l = lst; l; l = l->next) {
gtk_tree_path_free (l->data);
}
g_list_free (lst);
int response = gtk_dialog_run (GTK_DIALOG (dlg));
if (response == GTK_RESPONSE_OK) {
GtkTextIter begin, end;
gtk_text_buffer_get_start_iter (buffer, &begin);
gtk_text_buffer_get_end_iter (buffer, &end);
char *new_text = gtk_text_buffer_get_text (buffer, &begin, &end, TRUE);
update_meta_iter_with_edited_value (&iter, new_text);
free (new_text);
trkproperties_modified = 1;
}
g_object_unref (buffer);
gtk_widget_destroy (dlg);
}
void
on_trkproperties_edit_in_place_activate
(GtkMenuItem *menuitem,
gpointer user_data)
{
GtkTreeView *treeview = GTK_TREE_VIEW (lookup_widget (trackproperties, "metalist"));
GtkTreePath *path;
gtk_tree_view_get_cursor (treeview, &path, NULL);
if (!path) {
return;
}
GtkTreeViewColumn *col = gtk_tree_view_get_column (treeview, 1);
gtk_tree_view_set_cursor (treeview, path, col, TRUE); // set cursor onto new field
gtk_tree_path_free(path);
}
void
on_trkproperties_remove_activate (GtkMenuItem *menuitem,
gpointer user_data)
{
GtkTreeView *treeview = GTK_TREE_VIEW (lookup_widget (trackproperties, "metalist"));
if (!gtk_widget_is_focus(GTK_WIDGET (treeview))) {
return; // do not remove field if Metadata tab is not focused
}
GtkTreePath *path;
GtkTreeViewColumn *col;
gtk_tree_view_get_cursor (treeview, &path, &col);
if (!path || !col) {
return;
}
GtkTreeIter iter;
gtk_tree_model_get_iter (GTK_TREE_MODEL (store), &iter, path);
GValue value = {0,};
gtk_tree_model_get_value (GTK_TREE_MODEL (store), &iter, 2, &value);
const char *svalue = g_value_get_string (&value);
// delete unknown fields completely; otherwise just clear
int i = 0;
for (; trkproperties_types[i]; i += 2) {
if (!strcasecmp (svalue, trkproperties_types[i])) {
break;
}
}
if (trkproperties_types[i]) { // known val, clear
gtk_list_store_set (store, &iter, 1, "", 3, 0, 4, "", -1);
}
else {
gtk_list_store_remove (store, &iter);
}
gtk_tree_view_set_cursor (treeview, path, NULL, FALSE); // restore cursor after deletion
gtk_tree_path_free (path);
trkproperties_modified = 1;
}
void
on_trkproperties_cut_activate (GtkMenuItem *menuitem,
gpointer user_data)
{
}
void
on_trkproperties_copy_activate (GtkMenuItem *menuitem,
gpointer user_data)
{
}
void
on_trkproperties_paste_activate (GtkMenuItem *menuitem,
gpointer user_data)
{
}
void
on_trkproperties_capitalize_activate (GtkMenuItem *menuitem,
gpointer user_data)
{
}
void
on_trkproperties_clean_up_activate (GtkMenuItem *menuitem,
gpointer user_data)
{
}
void
on_trkproperties_format_from_other_fields_activate
(GtkMenuItem *menuitem,
gpointer user_data)
{
}
void
on_trkproperties_add_new_field_activate
(GtkMenuItem *menuitem,
gpointer user_data)
{
GtkTreeView *treeview = GTK_TREE_VIEW (lookup_widget (trackproperties, "metalist"));
if (!gtk_widget_is_focus(GTK_WIDGET (treeview))) {
return; // do not add field if Metadata tab is not focused
}
GtkWidget *dlg = create_entrydialog ();
gtk_window_set_transient_for (GTK_WINDOW (dlg), GTK_WINDOW (trackproperties));
gtk_dialog_set_default_response (GTK_DIALOG (dlg), GTK_RESPONSE_OK);
gtk_window_set_title (GTK_WINDOW (dlg), _("Field name"));
GtkWidget *e;
e = lookup_widget (dlg, "title_label");
gtk_label_set_text (GTK_LABEL(e), _("Name:"));
for (;;) {
int res = gtk_dialog_run (GTK_DIALOG (dlg));
if (res == GTK_RESPONSE_OK) {
e = lookup_widget (dlg, "title");
const char *text = gtk_entry_get_text (GTK_ENTRY(e));
GtkTreeIter iter;
// check for _ and :
if (text[0] == '_' || text[0] == ':' || text[0] == '!') {
GtkWidget *d = gtk_message_dialog_new (GTK_WINDOW (dlg), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, _("Field names must not start with : or _"));
gtk_window_set_title (GTK_WINDOW (d), _("Cannot add field"));
gtk_dialog_run (GTK_DIALOG (d));
gtk_widget_destroy (d);
continue;
}
// check if a field with the same name already exists
int dup = 0;
gboolean res = gtk_tree_model_get_iter_first (GTK_TREE_MODEL (store), &iter);
while (res) {
GValue value = {0,};
gtk_tree_model_get_value (GTK_TREE_MODEL (store), &iter, 2, &value);
const char *svalue = g_value_get_string (&value);
if (!strcasecmp (svalue, text)) {
dup = 1;
break;
}
res = gtk_tree_model_iter_next (GTK_TREE_MODEL (store), &iter);
}
if (!dup) {
size_t l = strlen (text);
char title[l+3];
snprintf (title, sizeof (title), "<%s>", text);
const char *value = "";
const char *key = text;
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, 0, title, 1, value, 2, key, 3, 0, 4, value, -1);
GtkTreePath *path;
gint rows = gtk_tree_model_iter_n_children (GTK_TREE_MODEL (store), NULL);
path = gtk_tree_path_new_from_indices (rows - 1, -1);
gtk_tree_view_set_cursor (treeview, path, NULL, TRUE); // set cursor onto new field
gtk_tree_path_free(path);
trkproperties_modified = 1;
}
else {
GtkWidget *d = gtk_message_dialog_new (GTK_WINDOW (dlg), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, _("Field with such name already exists, please try different name."));
gtk_window_set_title (GTK_WINDOW (d), _("Cannot add field"));
gtk_dialog_run (GTK_DIALOG (d));
gtk_widget_destroy (d);
continue;
}
}
break;
}
gtk_widget_destroy (dlg);
gtk_window_present (GTK_WINDOW (trackproperties));
}
void
on_trkproperties_paste_fields_activate (GtkMenuItem *menuitem,
gpointer user_data)
{
}
void
on_trkproperties_automatically_fill_values_activate
(GtkMenuItem *menuitem,
gpointer user_data)
{
}
void
on_trkproperties_crop_activate (GtkMenuItem *menuitem,
gpointer user_data)
{
GtkTreeView *treeview = GTK_TREE_VIEW (lookup_widget (trackproperties, "metalist"));
if (!gtk_widget_is_focus(GTK_WIDGET (treeview))) {
return; // do not remove field if Metadata tab is not focused
}
GtkTreePath *path;
gtk_tree_view_get_cursor (treeview, &path, NULL);
if (!path) {
return;
}
GtkTreeIter iter_curr;
gtk_tree_model_get_iter (GTK_TREE_MODEL (store), &iter_curr, path);
GtkTreeModel *model = gtk_tree_view_get_model (treeview);
GtkTreeIter iter;
gboolean res = gtk_tree_model_get_iter_first (model, &iter);
while (res) {
int getnext = 1;
GtkTreePath *iter_path = gtk_tree_model_get_path (model, &iter);
if (gtk_tree_path_compare (path, iter_path)) {
GValue key = {0,};
gtk_tree_model_get_value (model, &iter, 2, &key);
GValue value = {0,};
gtk_tree_model_get_value (GTK_TREE_MODEL (store), &iter, 2, &value);
const char *svalue = g_value_get_string (&value);
// delete unknown fields completely; otherwise just clear
int i = 0;
for (; trkproperties_types[i]; i += 2) {
if (!strcasecmp (svalue, trkproperties_types[i])) {
break;
}
}
if (trkproperties_types[i]) { // known val, clear
gtk_list_store_set (store, &iter, 1, "", 3, 0, 4, "", -1);
}
else {
gtk_list_store_remove (store, &iter);
getnext = 0;
if (!gtk_list_store_iter_is_valid (GTK_LIST_STORE (model), &iter)) {
res = 0;
}
}
}
gtk_tree_path_free (iter_path);
if (getnext) {
res = gtk_tree_model_iter_next (GTK_TREE_MODEL (store), &iter);
}
}
gtk_tree_view_set_cursor (treeview, path, NULL, FALSE); // restore cursor after deletion
gtk_tree_path_free (path);
trkproperties_modified = 1;
}
| {
"pile_set_name": "Github"
} |
//
// MJRefreshNormalHeader.h
// MJRefreshExample
//
// Created by MJ Lee on 15/4/24.
// Copyright (c) 2015年 小码哥. All rights reserved.
//
#import "MJRefreshStateHeader.h"
@interface MJRefreshNormalHeader : MJRefreshStateHeader
@property (weak, nonatomic, readonly) UIImageView *arrowView;
/** 菊花的样式 */
@property (assign, nonatomic) UIActivityIndicatorViewStyle activityIndicatorViewStyle;
@end
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_144) on Wed Sep 06 08:23:33 PDT 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface javax.validation.metadata.ReturnValueDescriptor (Java(TM) EE 8 Specification APIs)</title>
<meta name="date" content="2017-09-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface javax.validation.metadata.ReturnValueDescriptor (Java(TM) EE 8 Specification APIs)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../javax/validation/metadata/ReturnValueDescriptor.html" title="interface in javax.validation.metadata">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?javax/validation/metadata/class-use/ReturnValueDescriptor.html" target="_top">Frames</a></li>
<li><a href="ReturnValueDescriptor.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface javax.validation.metadata.ReturnValueDescriptor" class="title">Uses of Interface<br>javax.validation.metadata.ReturnValueDescriptor</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../javax/validation/metadata/ReturnValueDescriptor.html" title="interface in javax.validation.metadata">ReturnValueDescriptor</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#javax.validation.metadata">javax.validation.metadata</a></td>
<td class="colLast">
<div class="block">Package containing all objects specifically used and returned by the
metadata API.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="javax.validation.metadata">
<!-- -->
</a>
<h3>Uses of <a href="../../../../javax/validation/metadata/ReturnValueDescriptor.html" title="interface in javax.validation.metadata">ReturnValueDescriptor</a> in <a href="../../../../javax/validation/metadata/package-summary.html">javax.validation.metadata</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../javax/validation/metadata/package-summary.html">javax.validation.metadata</a> that return <a href="../../../../javax/validation/metadata/ReturnValueDescriptor.html" title="interface in javax.validation.metadata">ReturnValueDescriptor</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../javax/validation/metadata/ReturnValueDescriptor.html" title="interface in javax.validation.metadata">ReturnValueDescriptor</a></code></td>
<td class="colLast"><span class="typeNameLabel">ExecutableDescriptor.</span><code><span class="memberNameLink"><a href="../../../../javax/validation/metadata/ExecutableDescriptor.html#getReturnValueDescriptor--">getReturnValueDescriptor</a></span>()</code>
<div class="block">Returns a descriptor for this executable's return value.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../javax/validation/metadata/ReturnValueDescriptor.html" title="interface in javax.validation.metadata">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?javax/validation/metadata/class-use/ReturnValueDescriptor.html" target="_top">Frames</a></li>
<li><a href="ReturnValueDescriptor.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 1996-2017, <a href="http://www.oracle.com">Oracle</a> and/or its affiliates. All Rights Reserved. Use is subject to <a href="../../../../doc-files/speclicense.html" target="_top">license terms</a>.</small></p>
</body>
</html>
| {
"pile_set_name": "Github"
} |
//
// BALoginViewModel.h
// BAQMUIDemo
//
// Created by boai on 2017/3/20.
// Copyright © 2017年 boaihome. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface BALoginViewModel : NSObject
@property (nonatomic, strong) NSString *user_name;
@property (nonatomic, strong) NSString *user_pwd;
@property (nonatomic, strong) RACSubject *success_object;
@property (nonatomic, strong) RACSubject *failure_object;
@property (nonatomic, strong) RACSubject *error_object;
- (id)ba_loginButtonIsValid;
- (void)ba_login;
@end
| {
"pile_set_name": "Github"
} |
Strptime
========
Simple C-style strptime wrappers for Go's `time.Parse`. Support is available
for the following subset of format strings (descriptions blatantly stolen from
python docs):
%d Day of the month as a zero-padded decimal number.
%b Month as locale’s abbreviated name.
%B Month as locale’s full name.
%m Month as a zero-padded decimal number.
%y Year without century as a zero-padded decimal number.
%Y Year with century as a decimal number.
%H Hour (24-hour clock) as a zero-padded decimal number.
%I Hour (12-hour clock) as a zero-padded decimal number.
%p Locale’s equivalent of either AM or PM.
%M Minute as a zero-padded decimal number.
%S Second as a zero-padded decimal number.
%f Microsecond as a decimal number, zero-padded on the left.
%z UTC offset in the form +HHMM or -HHMM.
%Z Time zone name. UTC, EST, CST
%% A literal '%' character.
A small test suite is included to test many common use cases. Code is available
under the MIT License in case anyone else has a need for it like I do.
| {
"pile_set_name": "Github"
} |
#pragma once
#include <memory>
#include "Runtime/Graphics/Shaders/CAABoxShader.hpp"
#include "Runtime/Weapon/CGunWeapon.hpp"
namespace urde {
class CPhazonBeam final : public CGunWeapon {
TCachedToken<CModel> x21c_phazonVeins;
std::unique_ptr<CModelData> x224_phazonVeinsData;
TCachedToken<CGenDescription> x228_phazon2nd1;
std::unique_ptr<CElementGen> x234_chargeFxGen;
zeus::CAABox x238_aaBoxScale;
zeus::CAABox x250_aaBoxTranslate;
float x268_clipWipeScale = 0.f;
float x26c_clipWipeTranslate = 0.f;
float x270_indirectAlpha = 1.f;
bool x274_24_loaded : 1 = false;
bool x274_25_clipWipeActive : 1 = true;
bool x274_26_veinsAlphaActive : 1 = false;
bool x274_27_phazonVeinsIdx : 1 = false;
float x278_fireTime = 1.f / 3.f;
CAABoxShader m_aaboxShaderScale{true};
CAABoxShader m_aaboxShaderTranslate{true};
void ReInitVariables();
void DrawClipScaleCube();
void DrawClipTranslateCube();
public:
CPhazonBeam(CAssetId characterId, EWeaponType type, TUniqueId playerId, EMaterialTypes playerMaterial,
const zeus::CVector3f& scale);
void AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId sender, CStateManager& mgr);
bool IsFiring() const { return x278_fireTime < 1.f / 6.f; }
void SetClipWipeActive(bool b) { x274_25_clipWipeActive = b; }
void SetVeinsAlphaActive(bool b) { x274_26_veinsAlphaActive = b; }
void StopBeam(CStateManager& mgr, bool b1);
void UpdateBeam(float dt, const zeus::CTransform& targetXf, const zeus::CVector3f& localBeamPos, CStateManager& mgr);
void CreateBeam(CStateManager& mgr);
void PreRenderGunFx(const CStateManager& mgr, const zeus::CTransform& xf) override;
void PostRenderGunFx(const CStateManager& mgr, const zeus::CTransform& xf) override;
void UpdateGunFx(bool shotSmoke, float dt, const CStateManager& mgr, const zeus::CTransform& xf) override;
void Fire(bool underwater, float dt, EChargeState chargeState, const zeus::CTransform& xf, CStateManager& mgr,
TUniqueId homingTarget, float chargeFactor1, float chargeFactor2) override;
void Update(float dt, CStateManager& mgr) override;
void Load(CStateManager& mgr, bool subtypeBasePose) override;
void Unload(CStateManager& mgr) override;
bool IsLoaded() const override;
void Draw(bool drawSuitArm, const CStateManager& mgr, const zeus::CTransform& xf, const CModelFlags& flags,
const CActorLights* lights) override;
void DrawMuzzleFx(const CStateManager& mgr) const override;
};
} // namespace urde
| {
"pile_set_name": "Github"
} |
JASC-PAL
0100
16
205 205 172
255 255 255
255 255 172
230 205 98
205 164 65
156 115 57
156 123 106
123 90 74
98 65 49
74 41 24
197 49 24
156 0 0
197 197 197
115 115 115
255 238 115
16 16 16
| {
"pile_set_name": "Github"
} |
// Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs defs_linux.go
package ipv4
const (
sysIP_TOS = 0x1
sysIP_TTL = 0x2
sysIP_HDRINCL = 0x3
sysIP_OPTIONS = 0x4
sysIP_ROUTER_ALERT = 0x5
sysIP_RECVOPTS = 0x6
sysIP_RETOPTS = 0x7
sysIP_PKTINFO = 0x8
sysIP_PKTOPTIONS = 0x9
sysIP_MTU_DISCOVER = 0xa
sysIP_RECVERR = 0xb
sysIP_RECVTTL = 0xc
sysIP_RECVTOS = 0xd
sysIP_MTU = 0xe
sysIP_FREEBIND = 0xf
sysIP_TRANSPARENT = 0x13
sysIP_RECVRETOPTS = 0x7
sysIP_ORIGDSTADDR = 0x14
sysIP_RECVORIGDSTADDR = 0x14
sysIP_MINTTL = 0x15
sysIP_NODEFRAG = 0x16
sysIP_UNICAST_IF = 0x32
sysIP_MULTICAST_IF = 0x20
sysIP_MULTICAST_TTL = 0x21
sysIP_MULTICAST_LOOP = 0x22
sysIP_ADD_MEMBERSHIP = 0x23
sysIP_DROP_MEMBERSHIP = 0x24
sysIP_UNBLOCK_SOURCE = 0x25
sysIP_BLOCK_SOURCE = 0x26
sysIP_ADD_SOURCE_MEMBERSHIP = 0x27
sysIP_DROP_SOURCE_MEMBERSHIP = 0x28
sysIP_MSFILTER = 0x29
sysMCAST_JOIN_GROUP = 0x2a
sysMCAST_LEAVE_GROUP = 0x2d
sysMCAST_JOIN_SOURCE_GROUP = 0x2e
sysMCAST_LEAVE_SOURCE_GROUP = 0x2f
sysMCAST_BLOCK_SOURCE = 0x2b
sysMCAST_UNBLOCK_SOURCE = 0x2c
sysMCAST_MSFILTER = 0x30
sysIP_MULTICAST_ALL = 0x31
sysICMP_FILTER = 0x1
sysSO_EE_ORIGIN_NONE = 0x0
sysSO_EE_ORIGIN_LOCAL = 0x1
sysSO_EE_ORIGIN_ICMP = 0x2
sysSO_EE_ORIGIN_ICMP6 = 0x3
sysSO_EE_ORIGIN_TXSTATUS = 0x4
sysSO_EE_ORIGIN_TIMESTAMPING = 0x4
sizeofKernelSockaddrStorage = 0x80
sizeofSockaddrInet = 0x10
sizeofInetPktinfo = 0xc
sizeofSockExtendedErr = 0x10
sizeofIPMreq = 0x8
sizeofIPMreqn = 0xc
sizeofIPMreqSource = 0xc
sizeofGroupReq = 0x84
sizeofGroupSourceReq = 0x104
sizeofICMPFilter = 0x4
)
type kernelSockaddrStorage struct {
Family uint16
X__data [126]int8
}
type sockaddrInet struct {
Family uint16
Port uint16
Addr [4]byte /* in_addr */
X__pad [8]uint8
}
type inetPktinfo struct {
Ifindex int32
Spec_dst [4]byte /* in_addr */
Addr [4]byte /* in_addr */
}
type sockExtendedErr struct {
Errno uint32
Origin uint8
Type uint8
Code uint8
Pad uint8
Info uint32
Data uint32
}
type ipMreq struct {
Multiaddr [4]byte /* in_addr */
Interface [4]byte /* in_addr */
}
type ipMreqn struct {
Multiaddr [4]byte /* in_addr */
Address [4]byte /* in_addr */
Ifindex int32
}
type ipMreqSource struct {
Multiaddr uint32
Interface uint32
Sourceaddr uint32
}
type groupReq struct {
Interface uint32
Group kernelSockaddrStorage
}
type groupSourceReq struct {
Interface uint32
Group kernelSockaddrStorage
Source kernelSockaddrStorage
}
type icmpFilter struct {
Data uint32
}
| {
"pile_set_name": "Github"
} |
package com.yan.refreshloadlayouttest.testactivity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.yan.pullrefreshlayout.PullRefreshLayout;
import com.yan.refreshloadlayouttest.R;
import com.yan.refreshloadlayouttest.widget.DiDiListHeader;
public class DiDiListViewFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_didi, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final PullRefreshLayout prl = (PullRefreshLayout) view.findViewById(R.id.prl);
prl.setHeaderView(new DiDiListHeader(getContext(), prl));
prl.setOnRefreshListener(new PullRefreshLayout.OnRefreshListenerAdapter() {
@Override
public void onRefresh() {
prl.postDelayed(new Runnable() {
@Override
public void run() {
prl.refreshComplete();
}
}, 3000);
}
});
RecyclerView rvData = (RecyclerView) view.findViewById(R.id.rv_data);
rvData.setLayoutManager(new LinearLayoutManager(getContext()));
rvData.setAdapter(new RecyclerView.Adapter() {
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new RecyclerView.ViewHolder(getLayoutInflater().inflate(R.layout.didi_item, parent, false)) {
};
}
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
public int getItemCount() {
return 2;
}
});
}
}
| {
"pile_set_name": "Github"
} |
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual C++ Express 2013
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TCPConnection", "TCPConnection-vc2013.vcxproj", "{4EBA0C76-44FB-4B5C-8CEF-54008DA70535}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4EBA0C76-44FB-4B5C-8CEF-54008DA70535}.Debug|Win32.ActiveCfg = Debug|Win32
{4EBA0C76-44FB-4B5C-8CEF-54008DA70535}.Debug|Win32.Build.0 = Debug|Win32
{4EBA0C76-44FB-4B5C-8CEF-54008DA70535}.Release|Win32.ActiveCfg = Release|Win32
{4EBA0C76-44FB-4B5C-8CEF-54008DA70535}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (9.0.4) on Sun Mar 29 20:19:04 CEST 2020 -->
<title>QuantityFormat (Units of Measurement API 2.0 API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="date" content="2020-03-29">
<meta name="keywords" content="javax.measure.format.QuantityFormat interface">
<meta name="keywords" content="format()">
<meta name="keywords" content="parse()">
<meta name="keywords" content="isLocaleSensitive()">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../jquery/jquery-ui.css" title="Style">
<script type="text/javascript" src="../../../script.js"></script>
<script type="text/javascript" src="../../../jquery/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script>
<![endif]-->
<script type="text/javascript" src="../../../jquery/jquery-1.10.2.js"></script>
<script type="text/javascript" src="../../../jquery/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="QuantityFormat (Units of Measurement API 2.0 API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":6,"i1":6,"i2":18,"i3":6,"i4":6};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"],16:["t5","Default Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
var pathtoroot = "../../../";loadScripts(document, 'script');</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="fixedNav">
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/QuantityFormat.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../javax/measure/format/ParserException.html" title="class in javax.measure.format"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../javax/measure/format/UnitFormat.html" title="interface in javax.measure.format"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?javax/measure/format/QuantityFormat.html" target="_top">Frames</a></li>
<li><a href="QuantityFormat.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<ul class="navListSearch">
<li><span>SEARCH: </span>
<input type="text" id="search" value=" " disabled="disabled">
<input type="reset" id="reset" value=" " disabled="disabled">
</li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
</div>
<div class="navPadding"> </div>
<script type="text/javascript"><!--
$('.navPadding').css('padding-top', $('.fixedNav').css("height"));
//-->
</script>
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle"><span class="packageLabelInType">Package</span> <a href="../../../javax/measure/format/package-summary.html">javax.measure.format</a></div>
<h2 title="Interface QuantityFormat" class="title">Interface QuantityFormat</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public interface <span class="typeNameLabel">QuantityFormat</span></pre>
<div class="block">Formats instances of <a href="../../../javax/measure/Quantity.html" title="interface in javax.measure"><code>Quantity</code></a>.
<h3><a id="synchronization">Synchronization</a></h3>
Instances of this class are not required to be thread-safe. It is recommended to use separate format instances for each thread. If multiple threads
access a format concurrently, it must be synchronized externally.</div>
<dl>
<dt><span class="simpleTagLabel">Since:</span></dt>
<dd>2.0</dd>
<dt><span class="simpleTagLabel">Version:</span></dt>
<dd>0.9, 22 Feb, 2019</dd>
<dt><span class="simpleTagLabel">Author:</span></dt>
<dd><a href="mailto:[email protected]">Werner Keil</a>, <a href="mailto:[email protected]">Thodoris Bais</a></dd>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../javax/measure/Quantity.html" title="interface in javax.measure"><code>Quantity</code></a></dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span><span id="t5" class="tableTab"><span><a href="javascript:show(16);">Default Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colSecond" scope="col">Method</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code><a href="https://docs.oracle.com/javase/9/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../javax/measure/format/QuantityFormat.html#format-javax.measure.Quantity-">format</a></span>​(<a href="../../../javax/measure/Quantity.html" title="interface in javax.measure">Quantity</a><?> quantity)</code></th>
<td class="colLast">
<div class="block">Formats the specified <a href="../../../javax/measure/Quantity.html" title="interface in javax.measure"><code>Quantity</code></a>.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code><a href="https://docs.oracle.com/javase/9/docs/api/java/lang/Appendable.html?is-external=true" title="class or interface in java.lang">Appendable</a></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../javax/measure/format/QuantityFormat.html#format-javax.measure.Quantity-java.lang.Appendable-">format</a></span>​(<a href="../../../javax/measure/Quantity.html" title="interface in javax.measure">Quantity</a><?> quantity,
<a href="https://docs.oracle.com/javase/9/docs/api/java/lang/Appendable.html?is-external=true" title="class or interface in java.lang">Appendable</a> destination)</code></th>
<td class="colLast">
<div class="block">Formats the specified quantity into an <code>Appendable</code>.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>default boolean</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../javax/measure/format/QuantityFormat.html#isLocaleSensitive--">isLocaleSensitive</a></span>​()</code></th>
<td class="colLast">
<div class="block">Returns <code>true</code> if this <a href="../../../javax/measure/format/QuantityFormat.html" title="interface in javax.measure.format"><code>QuantityFormat</code></a> depends on a <code>Locale</code> to perform its tasks.</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code><a href="../../../javax/measure/Quantity.html" title="interface in javax.measure">Quantity</a><?></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../javax/measure/format/QuantityFormat.html#parse-java.lang.CharSequence-">parse</a></span>​(<a href="https://docs.oracle.com/javase/9/docs/api/java/lang/CharSequence.html?is-external=true" title="class or interface in java.lang">CharSequence</a> csq)</code></th>
<td class="colLast">
<div class="block">Parses a portion of the specified <code>CharSequence</code> from the specified position to produce a <a href="../../../javax/measure/Quantity.html" title="interface in javax.measure"><code>Quantity</code></a>.</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code><a href="../../../javax/measure/Quantity.html" title="interface in javax.measure">Quantity</a><?></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../javax/measure/format/QuantityFormat.html#parse-java.lang.CharSequence-java.text.ParsePosition-">parse</a></span>​(<a href="https://docs.oracle.com/javase/9/docs/api/java/lang/CharSequence.html?is-external=true" title="class or interface in java.lang">CharSequence</a> csq,
<a href="https://docs.oracle.com/javase/9/docs/api/java/text/ParsePosition.html?is-external=true" title="class or interface in java.text">ParsePosition</a> pos)</code></th>
<td class="colLast">
<div class="block">Parses a portion of the specified <code>CharSequence</code> from the specified position to produce a <a href="../../../javax/measure/Quantity.html" title="interface in javax.measure"><code>Quantity</code></a>.</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="format-javax.measure.Quantity-java.lang.Appendable-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>format</h4>
<pre><a href="https://docs.oracle.com/javase/9/docs/api/java/lang/Appendable.html?is-external=true" title="class or interface in java.lang">Appendable</a> format​(<a href="../../../javax/measure/Quantity.html" title="interface in javax.measure">Quantity</a><?> quantity,
<a href="https://docs.oracle.com/javase/9/docs/api/java/lang/Appendable.html?is-external=true" title="class or interface in java.lang">Appendable</a> destination)
throws <a href="https://docs.oracle.com/javase/9/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a></pre>
<div class="block">Formats the specified quantity into an <code>Appendable</code>.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>quantity</code> - the quantity to format.</dd>
<dd><code>destination</code> - the appendable destination.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the specified <code>Appendable</code>.</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code><a href="https://docs.oracle.com/javase/9/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a></code> - if an I/O exception occurs.</dd>
</dl>
</li>
</ul>
<a name="format-javax.measure.Quantity-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>format</h4>
<pre><a href="https://docs.oracle.com/javase/9/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> format​(<a href="../../../javax/measure/Quantity.html" title="interface in javax.measure">Quantity</a><?> quantity)</pre>
<div class="block">Formats the specified <a href="../../../javax/measure/Quantity.html" title="interface in javax.measure"><code>Quantity</code></a>.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>quantity</code> - the <a href="../../../javax/measure/Quantity.html" title="interface in javax.measure"><code>Quantity</code></a> to format, not <code>null</code></dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the string representation using the settings of this <a href="../../../javax/measure/format/QuantityFormat.html" title="interface in javax.measure.format"><code>QuantityFormat</code></a>.</dd>
</dl>
</li>
</ul>
<a name="parse-java.lang.CharSequence-java.text.ParsePosition-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>parse</h4>
<pre><a href="../../../javax/measure/Quantity.html" title="interface in javax.measure">Quantity</a><?> parse​(<a href="https://docs.oracle.com/javase/9/docs/api/java/lang/CharSequence.html?is-external=true" title="class or interface in java.lang">CharSequence</a> csq,
<a href="https://docs.oracle.com/javase/9/docs/api/java/text/ParsePosition.html?is-external=true" title="class or interface in java.text">ParsePosition</a> pos)
throws <a href="https://docs.oracle.com/javase/9/docs/api/java/lang/IllegalArgumentException.html?is-external=true" title="class or interface in java.lang">IllegalArgumentException</a>,
<a href="../../../javax/measure/format/MeasurementParseException.html" title="class in javax.measure.format">MeasurementParseException</a></pre>
<div class="block">Parses a portion of the specified <code>CharSequence</code> from the specified position to produce a <a href="../../../javax/measure/Quantity.html" title="interface in javax.measure"><code>Quantity</code></a>.
If parsing succeeds, then the index of the <code>pos</code> argument is updated to the index after the last character used.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>csq</code> - the <code>CharSequence</code> to parse.</dd>
<dd><code>pos</code> - a ParsePosition object holding the current parsing index and error parsing index information as described above.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the quantity parsed from the specified character sub-sequence.</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code><a href="https://docs.oracle.com/javase/9/docs/api/java/lang/IllegalArgumentException.html?is-external=true" title="class or interface in java.lang">IllegalArgumentException</a></code> - if any problem occurs while parsing the specified character sequence (e.g. illegal syntax).</dd>
<dd><code><a href="../../../javax/measure/format/MeasurementParseException.html" title="class in javax.measure.format">MeasurementParseException</a></code></dd>
</dl>
</li>
</ul>
<a name="parse-java.lang.CharSequence-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>parse</h4>
<pre><a href="../../../javax/measure/Quantity.html" title="interface in javax.measure">Quantity</a><?> parse​(<a href="https://docs.oracle.com/javase/9/docs/api/java/lang/CharSequence.html?is-external=true" title="class or interface in java.lang">CharSequence</a> csq)
throws <a href="../../../javax/measure/format/MeasurementParseException.html" title="class in javax.measure.format">MeasurementParseException</a></pre>
<div class="block">Parses a portion of the specified <code>CharSequence</code> from the specified position to produce a <a href="../../../javax/measure/Quantity.html" title="interface in javax.measure"><code>Quantity</code></a>.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>csq</code> - the <code>CharSequence</code> to parse.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the quantity parsed from the specified character sub-sequence.</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code><a href="https://docs.oracle.com/javase/9/docs/api/java/lang/IllegalArgumentException.html?is-external=true" title="class or interface in java.lang">IllegalArgumentException</a></code> - if any problem occurs while parsing the specified character sequence (e.g. illegal syntax).</dd>
<dd><code><a href="../../../javax/measure/format/MeasurementParseException.html" title="class in javax.measure.format">MeasurementParseException</a></code></dd>
</dl>
</li>
</ul>
<a name="isLocaleSensitive--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>isLocaleSensitive</h4>
<pre>default boolean isLocaleSensitive​()</pre>
<div class="block">Returns <code>true</code> if this <a href="../../../javax/measure/format/QuantityFormat.html" title="interface in javax.measure.format"><code>QuantityFormat</code></a> depends on a <code>Locale</code> to perform its tasks.
<p>
In environments that do not support a <code>Locale</code>, e.g. Java ME, this usually returns <code>false</code>.
</p></div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>whether this format depends on the locale.</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/QuantityFormat.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../javax/measure/format/ParserException.html" title="class in javax.measure.format"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../javax/measure/format/UnitFormat.html" title="interface in javax.measure.format"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?javax/measure/format/QuantityFormat.html" target="_top">Frames</a></li>
<li><a href="QuantityFormat.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2014–2020 <a href="http://unitsofmeasurement.github.io">Jean-Marie Dautelle, Werner Keil, Otavio Santana</a>. All rights reserved.</small></p>
</body>
</html>
| {
"pile_set_name": "Github"
} |
using System.Web.Mvc;
using TwitterBootstrapMVC.ControlModels;
using TwitterBootstrapMVC.Controls;
using TwitterBootstrapMVC.Infrastructure.Enums;
using TwitterBootstrapMVC.TypeExtensions;
namespace TwitterBootstrapMVC.Renderers
{
internal static partial class Renderer
{
public static string RenderControlGroupSelectElement(HtmlHelper html, BootstrapSelectElementModel inputModel, BootstrapLabelModel labelModel, BootstrapInputType inputType)
{
string input = string.Empty;
if(inputType == BootstrapInputType.DropDownList)
input = Renderer.RenderSelectElement(html, inputModel, BootstrapInputType.DropDownList);
if (inputType == BootstrapInputType.ListBox)
input = Renderer.RenderSelectElement(html, inputModel, BootstrapInputType.ListBox);
string label = Renderer.RenderLabel(html, labelModel ?? new BootstrapLabelModel
{
htmlFieldName = inputModel.htmlFieldName,
metadata = inputModel.metadata,
htmlAttributes = new { @class = "control-label" }.ToDictionary()
});
bool fieldIsValid = true;
if(inputModel != null) fieldIsValid = html.ViewData.ModelState.IsValidField(inputModel.htmlFieldName);
return new BootstrapControlGroup(input, label, ControlGroupType.textboxLike, fieldIsValid).ToHtmlString();
}
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2019 Google LLC
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ https://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:immersive">true</item>
<item name="android:windowFullscreen">true</item>
</style>
</resources>
| {
"pile_set_name": "Github"
} |
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: [email protected] (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// This file intentionally left blank. (At one point this wouldn't compile
// correctly.)
| {
"pile_set_name": "Github"
} |
<?php
$comment = App\Comment::find($notification->data['id']);
$type = $notification->data['commentable_type'] === 'articles' ? lang('Article') : lang('Discussion');
$commentable_id = $notification->data['commentable_id'];
if ($comment && $comment->commentable) {
switch($comment->commentable_type) {
case 'articles':
$article = App\Article::find($commentable_id);
$url = url($article->slug);
break;
case 'discussions':
$discussion = App\Discussion::find($commentable_id);
$url = url('discussion', ['id' => $discussion->id]);
break;
}
} else {
$message = lang('Be Banned Comment');
}
?>
<li :class="'{{ empty($notification->read_at) }}' ? 'bold' : ''">
@if ($comment && $comment->commentable)
<a class="text-info" href="{{ url('user', ['username' => $comment->user->name]) }}">{{ $comment->user->name }}</a>
{{ lang('Mentioned') }} {{ lang('In') }}
<a class="text-info" href="{{ $url }}">{{ $comment->commentable->title }}</a>
@elseif ($comment && !$comment->commentable)
<s>{{ strtolower($type) }} {{ $message }}</s>
@else
<s>{{ strtolower($type) }} {{ lang('Deleted') }}</s>
@endif
</li>
| {
"pile_set_name": "Github"
} |
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package v1beta1
import (
v1beta1 "k8s.io/api/scheduling/v1beta1"
"k8s.io/client-go/kubernetes/scheme"
rest "k8s.io/client-go/rest"
)
type SchedulingV1beta1Interface interface {
RESTClient() rest.Interface
PriorityClassesGetter
}
// SchedulingV1beta1Client is used to interact with features provided by the scheduling.k8s.io group.
type SchedulingV1beta1Client struct {
restClient rest.Interface
}
func (c *SchedulingV1beta1Client) PriorityClasses() PriorityClassInterface {
return newPriorityClasses(c)
}
// NewForConfig creates a new SchedulingV1beta1Client for the given config.
func NewForConfig(c *rest.Config) (*SchedulingV1beta1Client, error) {
config := *c
if err := setConfigDefaults(&config); err != nil {
return nil, err
}
client, err := rest.RESTClientFor(&config)
if err != nil {
return nil, err
}
return &SchedulingV1beta1Client{client}, nil
}
// NewForConfigOrDie creates a new SchedulingV1beta1Client for the given config and
// panics if there is an error in the config.
func NewForConfigOrDie(c *rest.Config) *SchedulingV1beta1Client {
client, err := NewForConfig(c)
if err != nil {
panic(err)
}
return client
}
// New creates a new SchedulingV1beta1Client for the given RESTClient.
func New(c rest.Interface) *SchedulingV1beta1Client {
return &SchedulingV1beta1Client{c}
}
func setConfigDefaults(config *rest.Config) error {
gv := v1beta1.SchemeGroupVersion
config.GroupVersion = &gv
config.APIPath = "/apis"
config.NegotiatedSerializer = scheme.Codecs.WithoutConversion()
if config.UserAgent == "" {
config.UserAgent = rest.DefaultKubernetesUserAgent()
}
return nil
}
// RESTClient returns a RESTClient that is used to communicate
// with API server by this client implementation.
func (c *SchedulingV1beta1Client) RESTClient() rest.Interface {
if c == nil {
return nil
}
return c.restClient
}
| {
"pile_set_name": "Github"
} |
eclipse.preferences.version=1
encoding/<project>=UTF-8
| {
"pile_set_name": "Github"
} |
# ----------------------------------------------------------------------------------
# Electrum plugin for the Digital Bitbox hardware wallet by Shift Devices AG
# digitalbitbox.com
#
import base64
import binascii
import hashlib
import hmac
import json
import math
import os
import re
import struct
import sys
import time
from electrum_axe.crypto import sha256d, EncodeAES_base64, EncodeAES_bytes, DecodeAES_bytes, hmac_oneshot
from electrum_axe.bitcoin import (TYPE_ADDRESS, push_script, var_int, public_key_to_p2pkh,
is_address)
from electrum_axe.bip32 import BIP32Node
from electrum_axe import ecc
from electrum_axe.ecc import msg_magic
from electrum_axe.wallet import Standard_Wallet
from electrum_axe import constants
from electrum_axe.transaction import Transaction
from electrum_axe.i18n import _
from electrum_axe.keystore import Hardware_KeyStore
from ..hw_wallet import HW_PluginBase
from electrum_axe.util import to_string, UserCancelled, UserFacingException
from electrum_axe.base_wizard import ScriptTypeNotSupported, HWD_SETUP_NEW_WALLET
from electrum_axe.network import Network
from electrum_axe.logging import get_logger
_logger = get_logger(__name__)
try:
import hid
DIGIBOX = True
except ImportError as e:
DIGIBOX = False
# ----------------------------------------------------------------------------------
# USB HID interface
#
def to_hexstr(s):
return binascii.hexlify(s).decode('ascii')
def derive_keys(x):
h = sha256d(x)
h = hashlib.sha512(h).digest()
return (h[:32],h[32:])
MIN_MAJOR_VERSION = 5
ENCRYPTION_PRIVKEY_KEY = 'encryptionprivkey'
CHANNEL_ID_KEY = 'comserverchannelid'
class DigitalBitbox_Client():
def __init__(self, plugin, hidDevice):
self.plugin = plugin
self.dbb_hid = hidDevice
self.opened = True
self.password = None
self.isInitialized = False
self.setupRunning = False
self.usbReportSize = 64 # firmware > v2.0.0
def close(self):
if self.opened:
try:
self.dbb_hid.close()
except:
pass
self.opened = False
def timeout(self, cutoff):
pass
def label(self):
return " "
def is_pairable(self):
return True
def is_initialized(self):
return self.dbb_has_password()
def is_paired(self):
return self.password is not None
def has_usable_connection_with_device(self):
try:
self.dbb_has_password()
except BaseException:
return False
return True
def _get_xpub(self, bip32_path):
if self.check_device_dialog():
return self.hid_send_encrypt(('{"xpub": "%s"}' % bip32_path).encode('utf8'))
def get_xpub(self, bip32_path, xtype):
assert xtype in self.plugin.SUPPORTED_XTYPES
reply = self._get_xpub(bip32_path)
if reply:
xpub = reply['xpub']
# Change type of xpub to the requested type. The firmware
# only ever returns the mainnet standard type, but it is agnostic
# to the type when signing.
if xtype != 'standard' or constants.net.TESTNET:
node = BIP32Node.from_xkey(xpub, net=constants.BitcoinMainnet)
xpub = node._replace(xtype=xtype).to_xpub()
return xpub
else:
raise Exception('no reply')
def dbb_has_password(self):
reply = self.hid_send_plain(b'{"ping":""}')
if 'ping' not in reply:
raise UserFacingException(_('Device communication error. Please unplug and replug your Digital Bitbox.'))
if reply['ping'] == 'password':
return True
return False
def stretch_key(self, key: bytes):
return to_hexstr(hashlib.pbkdf2_hmac('sha512', key, b'Digital Bitbox', iterations = 20480))
def backup_password_dialog(self):
msg = _("Enter the password used when the backup was created:")
while True:
password = self.handler.get_passphrase(msg, False)
if password is None:
return None
if len(password) < 4:
msg = _("Password must have at least 4 characters.") \
+ "\n\n" + _("Enter password:")
elif len(password) > 64:
msg = _("Password must have less than 64 characters.") \
+ "\n\n" + _("Enter password:")
else:
return password.encode('utf8')
def password_dialog(self, msg):
while True:
password = self.handler.get_passphrase(msg, False)
if password is None:
return False
if len(password) < 4:
msg = _("Password must have at least 4 characters.") + \
"\n\n" + _("Enter password:")
elif len(password) > 64:
msg = _("Password must have less than 64 characters.") + \
"\n\n" + _("Enter password:")
else:
self.password = password.encode('utf8')
return True
def check_device_dialog(self):
match = re.search(r'v([0-9])+\.[0-9]+\.[0-9]+', self.dbb_hid.get_serial_number_string())
if match is None:
raise Exception("error detecting firmware version")
major_version = int(match.group(1))
if major_version < MIN_MAJOR_VERSION:
raise Exception("Please upgrade to the newest firmware using the BitBox Desktop app: https://shiftcrypto.ch/start")
# Set password if fresh device
if self.password is None and not self.dbb_has_password():
if not self.setupRunning:
return False # A fresh device cannot connect to an existing wallet
msg = _("An uninitialized Digital Bitbox is detected.") + " " + \
_("Enter a new password below.") + "\n\n" + \
_("REMEMBER THE PASSWORD!") + "\n\n" + \
_("You cannot access your coins or a backup without the password.") + "\n" + \
_("A backup is saved automatically when generating a new wallet.")
if self.password_dialog(msg):
reply = self.hid_send_plain(b'{"password":"' + self.password + b'"}')
else:
return False
# Get password from user if not yet set
msg = _("Enter your Digital Bitbox password:")
while self.password is None:
if not self.password_dialog(msg):
raise UserCancelled()
reply = self.hid_send_encrypt(b'{"led":"blink"}')
if 'error' in reply:
self.password = None
if reply['error']['code'] == 109:
msg = _("Incorrect password entered.") + "\n\n" + \
reply['error']['message'] + "\n\n" + \
_("Enter your Digital Bitbox password:")
else:
# Should never occur
msg = _("Unexpected error occurred.") + "\n\n" + \
reply['error']['message'] + "\n\n" + \
_("Enter your Digital Bitbox password:")
# Initialize device if not yet initialized
if not self.setupRunning:
self.isInitialized = True # Wallet exists. Electrum code later checks if the device matches the wallet
elif not self.isInitialized:
reply = self.hid_send_encrypt(b'{"device":"info"}')
if reply['device']['id'] != "":
self.recover_or_erase_dialog() # Already seeded
else:
self.seed_device_dialog() # Seed if not initialized
self.mobile_pairing_dialog()
return self.isInitialized
def recover_or_erase_dialog(self):
msg = _("The Digital Bitbox is already seeded. Choose an option:") + "\n"
choices = [
(_("Create a wallet using the current seed")),
(_("Load a wallet from the micro SD card (the current seed is overwritten)")),
(_("Erase the Digital Bitbox"))
]
try:
reply = self.handler.win.query_choice(msg, choices)
except Exception:
return # Back button pushed
if reply == 2:
self.dbb_erase()
elif reply == 1:
if not self.dbb_load_backup():
return
else:
if self.hid_send_encrypt(b'{"device":"info"}')['device']['lock']:
raise UserFacingException(_("Full 2FA enabled. This is not supported yet."))
# Use existing seed
self.isInitialized = True
def seed_device_dialog(self):
msg = _("Choose how to initialize your Digital Bitbox:") + "\n"
choices = [
(_("Generate a new random wallet")),
(_("Load a wallet from the micro SD card"))
]
try:
reply = self.handler.win.query_choice(msg, choices)
except Exception:
return # Back button pushed
if reply == 0:
self.dbb_generate_wallet()
else:
if not self.dbb_load_backup(show_msg=False):
return
self.isInitialized = True
def mobile_pairing_dialog(self):
dbb_user_dir = None
if sys.platform == 'darwin':
dbb_user_dir = os.path.join(os.environ.get("HOME", ""), "Library", "Application Support", "DBB")
elif sys.platform == 'win32':
dbb_user_dir = os.path.join(os.environ["APPDATA"], "DBB")
else:
dbb_user_dir = os.path.join(os.environ["HOME"], ".dbb")
if not dbb_user_dir:
return
try:
# Python 3.5+
jsonDecodeError = json.JSONDecodeError
except AttributeError:
jsonDecodeError = ValueError
try:
with open(os.path.join(dbb_user_dir, "config.dat")) as f:
dbb_config = json.load(f)
except (FileNotFoundError, jsonDecodeError):
return
if ENCRYPTION_PRIVKEY_KEY not in dbb_config or CHANNEL_ID_KEY not in dbb_config:
return
choices = [
_('Do not pair'),
_('Import pairing from the Digital Bitbox desktop app'),
]
try:
reply = self.handler.win.query_choice(_('Mobile pairing options'), choices)
except Exception:
return # Back button pushed
if reply == 0:
if self.plugin.is_mobile_paired():
del self.plugin.digitalbitbox_config[ENCRYPTION_PRIVKEY_KEY]
del self.plugin.digitalbitbox_config[CHANNEL_ID_KEY]
elif reply == 1:
# import pairing from dbb app
self.plugin.digitalbitbox_config[ENCRYPTION_PRIVKEY_KEY] = dbb_config[ENCRYPTION_PRIVKEY_KEY]
self.plugin.digitalbitbox_config[CHANNEL_ID_KEY] = dbb_config[CHANNEL_ID_KEY]
self.plugin.config.set_key('digitalbitbox', self.plugin.digitalbitbox_config)
def dbb_generate_wallet(self):
key = self.stretch_key(self.password)
filename = ("Axe-Electrum-" + time.strftime("%Y-%m-%d-%H-%M-%S") + ".pdf")
msg = ('{"seed":{"source": "create", "key": "%s", "filename": "%s", "entropy": "%s"}}' % (key, filename, to_hexstr(os.urandom(32)))).encode('utf8')
reply = self.hid_send_encrypt(msg)
if 'error' in reply:
raise UserFacingException(reply['error']['message'])
def dbb_erase(self):
self.handler.show_message(_("Are you sure you want to erase the Digital Bitbox?") + "\n\n" +
_("To continue, touch the Digital Bitbox's light for 3 seconds.") + "\n\n" +
_("To cancel, briefly touch the light or wait for the timeout."))
hid_reply = self.hid_send_encrypt(b'{"reset":"__ERASE__"}')
self.handler.finished()
if 'error' in hid_reply:
raise UserFacingException(hid_reply['error']['message'])
else:
self.password = None
raise UserFacingException('Device erased')
def dbb_load_backup(self, show_msg=True):
backups = self.hid_send_encrypt(b'{"backup":"list"}')
if 'error' in backups:
raise UserFacingException(backups['error']['message'])
try:
f = self.handler.win.query_choice(_("Choose a backup file:"), backups['backup'])
except Exception:
return False # Back button pushed
key = self.backup_password_dialog()
if key is None:
raise Exception('Canceled by user')
key = self.stretch_key(key)
if show_msg:
self.handler.show_message(_("Loading backup...") + "\n\n" +
_("To continue, touch the Digital Bitbox's light for 3 seconds.") + "\n\n" +
_("To cancel, briefly touch the light or wait for the timeout."))
msg = ('{"seed":{"source": "backup", "key": "%s", "filename": "%s"}}' % (key, backups['backup'][f])).encode('utf8')
hid_reply = self.hid_send_encrypt(msg)
self.handler.finished()
if 'error' in hid_reply:
raise UserFacingException(hid_reply['error']['message'])
return True
def hid_send_frame(self, data):
HWW_CID = 0xFF000000
HWW_CMD = 0x80 + 0x40 + 0x01
data_len = len(data)
seq = 0;
idx = 0;
write = []
while idx < data_len:
if idx == 0:
# INIT frame
write = data[idx : idx + min(data_len, self.usbReportSize - 7)]
self.dbb_hid.write(b'\0' + struct.pack(">IBH", HWW_CID, HWW_CMD, data_len & 0xFFFF) + write + b'\xEE' * (self.usbReportSize - 7 - len(write)))
else:
# CONT frame
write = data[idx : idx + min(data_len, self.usbReportSize - 5)]
self.dbb_hid.write(b'\0' + struct.pack(">IB", HWW_CID, seq) + write + b'\xEE' * (self.usbReportSize - 5 - len(write)))
seq += 1
idx += len(write)
def hid_read_frame(self):
# INIT response
read = bytearray(self.dbb_hid.read(self.usbReportSize))
cid = ((read[0] * 256 + read[1]) * 256 + read[2]) * 256 + read[3]
cmd = read[4]
data_len = read[5] * 256 + read[6]
data = read[7:]
idx = len(read) - 7;
while idx < data_len:
# CONT response
read = bytearray(self.dbb_hid.read(self.usbReportSize))
data += read[5:]
idx += len(read) - 5
return data
def hid_send_plain(self, msg):
reply = ""
try:
serial_number = self.dbb_hid.get_serial_number_string()
if "v2.0." in serial_number or "v1." in serial_number:
hidBufSize = 4096
self.dbb_hid.write('\0' + msg + '\0' * (hidBufSize - len(msg)))
r = bytearray()
while len(r) < hidBufSize:
r += bytearray(self.dbb_hid.read(hidBufSize))
else:
self.hid_send_frame(msg)
r = self.hid_read_frame()
r = r.rstrip(b' \t\r\n\0')
r = r.replace(b"\0", b'')
r = to_string(r, 'utf8')
reply = json.loads(r)
except Exception as e:
_logger.info(f'Exception caught {repr(e)}')
return reply
def hid_send_encrypt(self, msg):
sha256_byte_len = 32
reply = ""
try:
encryption_key, authentication_key = derive_keys(self.password)
msg = EncodeAES_bytes(encryption_key, msg)
hmac_digest = hmac_oneshot(authentication_key, msg, hashlib.sha256)
authenticated_msg = base64.b64encode(msg + hmac_digest)
reply = self.hid_send_plain(authenticated_msg)
if 'ciphertext' in reply:
b64_unencoded = bytes(base64.b64decode(''.join(reply["ciphertext"])))
reply_hmac = b64_unencoded[-sha256_byte_len:]
hmac_calculated = hmac_oneshot(authentication_key, b64_unencoded[:-sha256_byte_len], hashlib.sha256)
if not hmac.compare_digest(reply_hmac, hmac_calculated):
raise Exception("Failed to validate HMAC")
reply = DecodeAES_bytes(encryption_key, b64_unencoded[:-sha256_byte_len])
reply = to_string(reply, 'utf8')
reply = json.loads(reply)
if 'error' in reply:
self.password = None
except Exception as e:
_logger.info(f'Exception caught {repr(e)}')
return reply
# ----------------------------------------------------------------------------------
#
#
class DigitalBitbox_KeyStore(Hardware_KeyStore):
hw_type = 'digitalbitbox'
device = 'DigitalBitbox'
def __init__(self, d):
Hardware_KeyStore.__init__(self, d)
self.force_watching_only = False
self.maxInputs = 14 # maximum inputs per single sign command
def get_derivation(self):
return str(self.derivation)
def is_p2pkh(self):
return self.derivation.startswith("m/44'/")
def give_error(self, message, clear_client = False):
if clear_client:
self.client = None
raise Exception(message)
def decrypt_message(self, pubkey, message, password):
raise RuntimeError(_('Encryption and decryption are currently not supported for {}').format(self.device))
def sign_message(self, sequence, message, password):
sig = None
try:
message = message.encode('utf8')
inputPath = self.get_derivation() + "/%d/%d" % sequence
msg_hash = sha256d(msg_magic(message))
inputHash = to_hexstr(msg_hash)
hasharray = []
hasharray.append({'hash': inputHash, 'keypath': inputPath})
hasharray = json.dumps(hasharray)
msg = ('{"sign":{"meta":"sign message", "data":%s}}' % hasharray).encode('utf8')
dbb_client = self.plugin.get_client(self)
if not dbb_client.is_paired():
raise Exception(_("Could not sign message."))
reply = dbb_client.hid_send_encrypt(msg)
self.handler.show_message(_("Signing message ...") + "\n\n" +
_("To continue, touch the Digital Bitbox's blinking light for 3 seconds.") + "\n\n" +
_("To cancel, briefly touch the blinking light or wait for the timeout."))
reply = dbb_client.hid_send_encrypt(msg) # Send twice, first returns an echo for smart verification (not implemented)
self.handler.finished()
if 'error' in reply:
raise Exception(reply['error']['message'])
if 'sign' not in reply:
raise Exception(_("Could not sign message."))
if 'recid' in reply['sign'][0]:
# firmware > v2.1.1
sig_string = binascii.unhexlify(reply['sign'][0]['sig'])
recid = int(reply['sign'][0]['recid'], 16)
sig = ecc.construct_sig65(sig_string, recid, True)
pubkey, compressed = ecc.ECPubkey.from_signature65(sig, msg_hash)
addr = public_key_to_p2pkh(pubkey.get_public_key_bytes(compressed=compressed))
if ecc.verify_message_with_address(addr, sig, message) is False:
raise Exception(_("Could not sign message"))
elif 'pubkey' in reply['sign'][0]:
# firmware <= v2.1.1
for recid in range(4):
sig_string = binascii.unhexlify(reply['sign'][0]['sig'])
sig = ecc.construct_sig65(sig_string, recid, True)
try:
addr = public_key_to_p2pkh(binascii.unhexlify(reply['sign'][0]['pubkey']))
if ecc.verify_message_with_address(addr, sig, message):
break
except Exception:
continue
else:
raise Exception(_("Could not sign message"))
except BaseException as e:
self.give_error(e)
return sig
def sign_transaction(self, tx, password):
if tx.is_complete():
return
try:
p2pkhTransaction = True
derivations = self.get_tx_derivations(tx)
inputhasharray = []
hasharray = []
pubkeyarray = []
# Build hasharray from inputs
for i, txin in enumerate(tx.inputs()):
if txin['type'] == 'coinbase':
self.give_error("Coinbase not supported") # should never happen
if txin['type'] != 'p2pkh':
p2pkhTransaction = False
for x_pubkey in txin['x_pubkeys']:
if x_pubkey in derivations:
index = derivations.get(x_pubkey)
inputPath = "%s/%d/%d" % (self.get_derivation(), index[0], index[1])
inputHash = sha256d(binascii.unhexlify(tx.serialize_preimage(i)))
hasharray_i = {'hash': to_hexstr(inputHash), 'keypath': inputPath}
hasharray.append(hasharray_i)
inputhasharray.append(inputHash)
break
else:
self.give_error("No matching x_key for sign_transaction") # should never happen
# Build pubkeyarray from outputs
for o in tx.outputs():
assert o.type == TYPE_ADDRESS
info = tx.output_info.get(o.address)
if info is not None:
index = info.address_index
changePath = self.get_derivation() + "/%d/%d" % index
changePubkey = self.derive_pubkey(index[0], index[1])
pubkeyarray_i = {'pubkey': changePubkey, 'keypath': changePath}
pubkeyarray.append(pubkeyarray_i)
# Special serialization of the unsigned transaction for
# the mobile verification app.
# At the moment, verification only works for p2pkh transactions.
if p2pkhTransaction:
class CustomTXSerialization(Transaction):
@classmethod
def input_script(self, txin, estimate_size=False):
if txin['type'] == 'p2pkh':
return Transaction.get_preimage_script(txin)
if txin['type'] == 'p2sh':
# Multisig verification has partial support, but is disabled. This is the
# expected serialization though, so we leave it here until we activate it.
return '00' + push_script(Transaction.get_preimage_script(txin))
raise Exception("unsupported type %s" % txin['type'])
tx_dbb_serialized = CustomTXSerialization(tx.serialize()).serialize_to_network()
else:
# We only need this for the signing echo / verification.
tx_dbb_serialized = None
# Build sign command
dbb_signatures = []
steps = math.ceil(1.0 * len(hasharray) / self.maxInputs)
for step in range(int(steps)):
hashes = hasharray[step * self.maxInputs : (step + 1) * self.maxInputs]
msg = {
"sign": {
"data": hashes,
"checkpub": pubkeyarray,
},
}
if tx_dbb_serialized is not None:
msg["sign"]["meta"] = to_hexstr(sha256d(tx_dbb_serialized))
msg = json.dumps(msg).encode('ascii')
dbb_client = self.plugin.get_client(self)
if not dbb_client.is_paired():
raise Exception("Could not sign transaction.")
reply = dbb_client.hid_send_encrypt(msg)
if 'error' in reply:
raise Exception(reply['error']['message'])
if 'echo' not in reply:
raise Exception("Could not sign transaction.")
if self.plugin.is_mobile_paired() and tx_dbb_serialized is not None:
reply['tx'] = tx_dbb_serialized
self.plugin.comserver_post_notification(reply)
if steps > 1:
self.handler.show_message(_("Signing large transaction. Please be patient ...") + "\n\n" +
_("To continue, touch the Digital Bitbox's blinking light for 3 seconds.") + " " +
_("(Touch {} of {})").format((step + 1), steps) + "\n\n" +
_("To cancel, briefly touch the blinking light or wait for the timeout.") + "\n\n")
else:
self.handler.show_message(_("Signing transaction...") + "\n\n" +
_("To continue, touch the Digital Bitbox's blinking light for 3 seconds.") + "\n\n" +
_("To cancel, briefly touch the blinking light or wait for the timeout."))
# Send twice, first returns an echo for smart verification
reply = dbb_client.hid_send_encrypt(msg)
self.handler.finished()
if 'error' in reply:
if reply["error"].get('code') in (600, 601):
# aborted via LED short touch or timeout
raise UserCancelled()
raise Exception(reply['error']['message'])
if 'sign' not in reply:
raise Exception("Could not sign transaction.")
dbb_signatures.extend(reply['sign'])
# Fill signatures
if len(dbb_signatures) != len(tx.inputs()):
raise Exception("Incorrect number of transactions signed.") # Should never occur
for i, txin in enumerate(tx.inputs()):
num = txin['num_sig']
for pubkey in txin['pubkeys']:
signatures = list(filter(None, txin['signatures']))
if len(signatures) == num:
break # txin is complete
ii = txin['pubkeys'].index(pubkey)
signed = dbb_signatures[i]
if 'recid' in signed:
# firmware > v2.1.1
recid = int(signed['recid'], 16)
s = binascii.unhexlify(signed['sig'])
h = inputhasharray[i]
pk = ecc.ECPubkey.from_sig_string(s, recid, h)
pk = pk.get_public_key_hex(compressed=True)
elif 'pubkey' in signed:
# firmware <= v2.1.1
pk = signed['pubkey']
if pk != pubkey:
continue
sig_r = int(signed['sig'][:64], 16)
sig_s = int(signed['sig'][64:], 16)
sig = ecc.der_sig_from_r_and_s(sig_r, sig_s)
sig = to_hexstr(sig) + '01'
tx.add_signature_to_txin(i, ii, sig)
except UserCancelled:
raise
except BaseException as e:
self.give_error(e, True)
else:
_logger.info("Transaction is_complete {tx.is_complete()}")
tx.raw = tx.serialize()
class DigitalBitboxPlugin(HW_PluginBase):
libraries_available = DIGIBOX
keystore_class = DigitalBitbox_KeyStore
client = None
DEVICE_IDS = [
(0x03eb, 0x2402) # Digital Bitbox
]
SUPPORTED_XTYPES = ('standard', )
def __init__(self, parent, config, name):
HW_PluginBase.__init__(self, parent, config, name)
if self.libraries_available:
self.device_manager().register_devices(self.DEVICE_IDS)
self.digitalbitbox_config = self.config.get('digitalbitbox', {})
def get_dbb_device(self, device):
dev = hid.device()
dev.open_path(device.path)
return dev
def create_client(self, device, handler):
if device.interface_number == 0 or device.usage_page == 0xffff:
if handler:
self.handler = handler
client = self.get_dbb_device(device)
if client is not None:
client = DigitalBitbox_Client(self, client)
return client
else:
return None
def setup_device(self, device_info, wizard, purpose):
devmgr = self.device_manager()
device_id = device_info.device.id_
client = devmgr.client_by_id(device_id)
if client is None:
raise Exception(_('Failed to create a client for this device.') + '\n' +
_('Make sure it is in the correct state.'))
client.handler = self.create_handler(wizard)
if purpose == HWD_SETUP_NEW_WALLET:
client.setupRunning = True
client.get_xpub("m/44'/5'", 'standard')
def is_mobile_paired(self):
return ENCRYPTION_PRIVKEY_KEY in self.digitalbitbox_config
def comserver_post_notification(self, payload):
assert self.is_mobile_paired(), "unexpected mobile pairing error"
url = 'https://digitalbitbox.com/smartverification/index.php'
key_s = base64.b64decode(self.digitalbitbox_config[ENCRYPTION_PRIVKEY_KEY])
args = 'c=data&s=0&dt=0&uuid=%s&pl=%s' % (
self.digitalbitbox_config[CHANNEL_ID_KEY],
EncodeAES_base64(key_s, json.dumps(payload).encode('ascii')).decode('ascii'),
)
try:
text = Network.send_http_on_proxy('post', url, body=args.encode('ascii'), headers={'content-type': 'application/x-www-form-urlencoded'})
_logger.info(f'digitalbitbox reply from server {text}')
except Exception as e:
self.handler.show_error(repr(e)) # repr because str(Exception()) == ''
def get_xpub(self, device_id, derivation, xtype, wizard):
if xtype not in self.SUPPORTED_XTYPES:
raise ScriptTypeNotSupported(_('This type of script is not supported with {}.').format(self.device))
devmgr = self.device_manager()
client = devmgr.client_by_id(device_id)
client.handler = self.create_handler(wizard)
client.check_device_dialog()
xpub = client.get_xpub(derivation, xtype)
return xpub
def get_client(self, keystore, force_pair=True):
devmgr = self.device_manager()
handler = keystore.handler
with devmgr.hid_lock:
client = devmgr.client_for_keystore(self, handler, keystore, force_pair)
if client is not None:
client.check_device_dialog()
return client
def show_address(self, wallet, address, keystore=None):
if keystore is None:
keystore = wallet.get_keystore()
if not self.show_address_helper(wallet, address, keystore):
return
if type(wallet) is not Standard_Wallet:
keystore.handler.show_error(_('This function is only available for standard wallets when using {}.').format(self.device))
return
if not self.is_mobile_paired():
keystore.handler.show_error(_('This function is only available after pairing your {} with a mobile device.').format(self.device))
return
if not keystore.is_p2pkh():
keystore.handler.show_error(_('This function is only available for p2pkh keystores when using {}.').format(self.device))
return
change, index = wallet.get_address_index(address)
keypath = '%s/%d/%d' % (keystore.derivation, change, index)
xpub = self.get_client(keystore)._get_xpub(keypath)
verify_request_payload = {
"type": 'p2pkh',
"echo": xpub['echo'],
}
self.comserver_post_notification(verify_request_payload)
| {
"pile_set_name": "Github"
} |
; RUN: opt < %s -inline -S | grep "ret i32 1"
; ModuleID = 'short.opt.bc'
define i32 @testBool(i1 %X) {
%tmp = zext i1 %X to i32 ; <i32> [#uses=1]
ret i32 %tmp
}
define i32 @testByte(i8 %X) {
%tmp = icmp ne i8 %X, 0 ; <i1> [#uses=1]
%tmp.i = zext i1 %tmp to i32 ; <i32> [#uses=1]
ret i32 %tmp.i
}
define i32 @main() {
%rslt = call i32 @testByte( i8 123 ) ; <i32> [#uses=1]
ret i32 %rslt
}
| {
"pile_set_name": "Github"
} |
/* $OpenBSD: smult_curve25519_ref.c,v 1.2 2013/11/02 22:02:14 markus Exp $ */
/*
version 20081011
Matthew Dempsky
Public domain.
Derived from public domain code by D. J. Bernstein.
*/
int crypto_scalarmult_curve25519(unsigned char *, const unsigned char *, const unsigned char *);
static void add(unsigned int out[32],const unsigned int a[32],const unsigned int b[32])
{
unsigned int j;
unsigned int u;
u = 0;
for (j = 0;j < 31;++j) { u += a[j] + b[j]; out[j] = u & 255; u >>= 8; }
u += a[31] + b[31]; out[31] = u;
}
static void sub(unsigned int out[32],const unsigned int a[32],const unsigned int b[32])
{
unsigned int j;
unsigned int u;
u = 218;
for (j = 0;j < 31;++j) {
u += a[j] + 65280 - b[j];
out[j] = u & 255;
u >>= 8;
}
u += a[31] - b[31];
out[31] = u;
}
static void squeeze(unsigned int a[32])
{
unsigned int j;
unsigned int u;
u = 0;
for (j = 0;j < 31;++j) { u += a[j]; a[j] = u & 255; u >>= 8; }
u += a[31]; a[31] = u & 127;
u = 19 * (u >> 7);
for (j = 0;j < 31;++j) { u += a[j]; a[j] = u & 255; u >>= 8; }
u += a[31]; a[31] = u;
}
static const unsigned int minusp[32] = {
19, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128
} ;
static void freeze(unsigned int a[32])
{
unsigned int aorig[32];
unsigned int j;
unsigned int negative;
for (j = 0;j < 32;++j) aorig[j] = a[j];
add(a,a,minusp);
negative = -((a[31] >> 7) & 1);
for (j = 0;j < 32;++j) a[j] ^= negative & (aorig[j] ^ a[j]);
}
static void mult(unsigned int out[32],const unsigned int a[32],const unsigned int b[32])
{
unsigned int i;
unsigned int j;
unsigned int u;
for (i = 0;i < 32;++i) {
u = 0;
for (j = 0;j <= i;++j) u += a[j] * b[i - j];
for (j = i + 1;j < 32;++j) u += 38 * a[j] * b[i + 32 - j];
out[i] = u;
}
squeeze(out);
}
static void mult121665(unsigned int out[32],const unsigned int a[32])
{
unsigned int j;
unsigned int u;
u = 0;
for (j = 0;j < 31;++j) { u += 121665 * a[j]; out[j] = u & 255; u >>= 8; }
u += 121665 * a[31]; out[31] = u & 127;
u = 19 * (u >> 7);
for (j = 0;j < 31;++j) { u += out[j]; out[j] = u & 255; u >>= 8; }
u += out[j]; out[j] = u;
}
static void square(unsigned int out[32],const unsigned int a[32])
{
unsigned int i;
unsigned int j;
unsigned int u;
for (i = 0;i < 32;++i) {
u = 0;
for (j = 0;j < i - j;++j) u += a[j] * a[i - j];
for (j = i + 1;j < i + 32 - j;++j) u += 38 * a[j] * a[i + 32 - j];
u *= 2;
if ((i & 1) == 0) {
u += a[i / 2] * a[i / 2];
u += 38 * a[i / 2 + 16] * a[i / 2 + 16];
}
out[i] = u;
}
squeeze(out);
}
static void select(unsigned int p[64],unsigned int q[64],const unsigned int r[64],const unsigned int s[64],unsigned int b)
{
unsigned int j;
unsigned int t;
unsigned int bminus1;
bminus1 = b - 1;
for (j = 0;j < 64;++j) {
t = bminus1 & (r[j] ^ s[j]);
p[j] = s[j] ^ t;
q[j] = r[j] ^ t;
}
}
static void mainloop(unsigned int work[64],const unsigned char e[32])
{
unsigned int xzm1[64];
unsigned int xzm[64];
unsigned int xzmb[64];
unsigned int xzm1b[64];
unsigned int xznb[64];
unsigned int xzn1b[64];
unsigned int a0[64];
unsigned int a1[64];
unsigned int b0[64];
unsigned int b1[64];
unsigned int c1[64];
unsigned int r[32];
unsigned int s[32];
unsigned int t[32];
unsigned int u[32];
unsigned int j;
unsigned int b;
int pos;
for (j = 0;j < 32;++j) xzm1[j] = work[j];
xzm1[32] = 1;
for (j = 33;j < 64;++j) xzm1[j] = 0;
xzm[0] = 1;
for (j = 1;j < 64;++j) xzm[j] = 0;
for (pos = 254;pos >= 0;--pos) {
b = e[pos / 8] >> (pos & 7);
b &= 1;
select(xzmb,xzm1b,xzm,xzm1,b);
add(a0,xzmb,xzmb + 32);
sub(a0 + 32,xzmb,xzmb + 32);
add(a1,xzm1b,xzm1b + 32);
sub(a1 + 32,xzm1b,xzm1b + 32);
square(b0,a0);
square(b0 + 32,a0 + 32);
mult(b1,a1,a0 + 32);
mult(b1 + 32,a1 + 32,a0);
add(c1,b1,b1 + 32);
sub(c1 + 32,b1,b1 + 32);
square(r,c1 + 32);
sub(s,b0,b0 + 32);
mult121665(t,s);
add(u,t,b0);
mult(xznb,b0,b0 + 32);
mult(xznb + 32,s,u);
square(xzn1b,c1);
mult(xzn1b + 32,r,work);
select(xzm,xzm1,xznb,xzn1b,b);
}
for (j = 0;j < 64;++j) work[j] = xzm[j];
}
static void recip(unsigned int out[32],const unsigned int z[32])
{
unsigned int z2[32];
unsigned int z9[32];
unsigned int z11[32];
unsigned int z2_5_0[32];
unsigned int z2_10_0[32];
unsigned int z2_20_0[32];
unsigned int z2_50_0[32];
unsigned int z2_100_0[32];
unsigned int t0[32];
unsigned int t1[32];
int i;
/* 2 */ square(z2,z);
/* 4 */ square(t1,z2);
/* 8 */ square(t0,t1);
/* 9 */ mult(z9,t0,z);
/* 11 */ mult(z11,z9,z2);
/* 22 */ square(t0,z11);
/* 2^5 - 2^0 = 31 */ mult(z2_5_0,t0,z9);
/* 2^6 - 2^1 */ square(t0,z2_5_0);
/* 2^7 - 2^2 */ square(t1,t0);
/* 2^8 - 2^3 */ square(t0,t1);
/* 2^9 - 2^4 */ square(t1,t0);
/* 2^10 - 2^5 */ square(t0,t1);
/* 2^10 - 2^0 */ mult(z2_10_0,t0,z2_5_0);
/* 2^11 - 2^1 */ square(t0,z2_10_0);
/* 2^12 - 2^2 */ square(t1,t0);
/* 2^20 - 2^10 */ for (i = 2;i < 10;i += 2) { square(t0,t1); square(t1,t0); }
/* 2^20 - 2^0 */ mult(z2_20_0,t1,z2_10_0);
/* 2^21 - 2^1 */ square(t0,z2_20_0);
/* 2^22 - 2^2 */ square(t1,t0);
/* 2^40 - 2^20 */ for (i = 2;i < 20;i += 2) { square(t0,t1); square(t1,t0); }
/* 2^40 - 2^0 */ mult(t0,t1,z2_20_0);
/* 2^41 - 2^1 */ square(t1,t0);
/* 2^42 - 2^2 */ square(t0,t1);
/* 2^50 - 2^10 */ for (i = 2;i < 10;i += 2) { square(t1,t0); square(t0,t1); }
/* 2^50 - 2^0 */ mult(z2_50_0,t0,z2_10_0);
/* 2^51 - 2^1 */ square(t0,z2_50_0);
/* 2^52 - 2^2 */ square(t1,t0);
/* 2^100 - 2^50 */ for (i = 2;i < 50;i += 2) { square(t0,t1); square(t1,t0); }
/* 2^100 - 2^0 */ mult(z2_100_0,t1,z2_50_0);
/* 2^101 - 2^1 */ square(t1,z2_100_0);
/* 2^102 - 2^2 */ square(t0,t1);
/* 2^200 - 2^100 */ for (i = 2;i < 100;i += 2) { square(t1,t0); square(t0,t1); }
/* 2^200 - 2^0 */ mult(t1,t0,z2_100_0);
/* 2^201 - 2^1 */ square(t0,t1);
/* 2^202 - 2^2 */ square(t1,t0);
/* 2^250 - 2^50 */ for (i = 2;i < 50;i += 2) { square(t0,t1); square(t1,t0); }
/* 2^250 - 2^0 */ mult(t0,t1,z2_50_0);
/* 2^251 - 2^1 */ square(t1,t0);
/* 2^252 - 2^2 */ square(t0,t1);
/* 2^253 - 2^3 */ square(t1,t0);
/* 2^254 - 2^4 */ square(t0,t1);
/* 2^255 - 2^5 */ square(t1,t0);
/* 2^255 - 21 */ mult(out,t1,z11);
}
int crypto_scalarmult_curve25519(unsigned char *q,
const unsigned char *n,
const unsigned char *p)
{
unsigned int work[96];
unsigned char e[32];
unsigned int i;
for (i = 0;i < 32;++i) e[i] = n[i];
e[0] &= 248;
e[31] &= 127;
e[31] |= 64;
for (i = 0;i < 32;++i) work[i] = p[i];
mainloop(work,e);
recip(work + 32,work + 32);
mult(work + 64,work,work + 32);
freeze(work + 64);
for (i = 0;i < 32;++i) q[i] = work[64 + i];
return 0;
}
| {
"pile_set_name": "Github"
} |
(module mod-importforms)
(import enum)
(def fun (fn extern int (void) 100))
(def var (var extern int 1000))
(def str (struct extern ((a int) (b int))))
(def-enum enu extern int (a b c d))
| {
"pile_set_name": "Github"
} |
module Fog
module AWS
class Redshift
class Real
require 'fog/aws/parsers/redshift/create_cluster_security_group'
# ==== Parameters
#
# @param [Hash] options
# * :cluster_security_group_name - (String)
# The name of a cluster security group for which you are requesting details. You
# can specify either the Marker parameter or a ClusterSecurityGroupName parameter,
# but not both. Example: securitygroup1
# * :description - required - (String)
# A description for the security group.
#
# ==== See Also
# http://docs.aws.amazon.com/redshift/latest/APIReference/API_CreateClusterSecurityGroup.html
def create_cluster_security_group(options = {})
cluster_security_group_name = options[:cluster_security_group_name]
description = options[:description]
path = "/"
params = {
:headers => {},
:path => path,
:method => :put,
:query => {},
:parser => Fog::Parsers::Redshift::AWS::CreateClusterSecurityGroup.new
}
params[:query]['Action'] = 'CreateClusterSecurityGroup'
params[:query]['ClusterSecurityGroupName'] = cluster_security_group_name if cluster_security_group_name
params[:query]['Description'] = description if description
request(params)
end
end
end
end
end
| {
"pile_set_name": "Github"
} |
/*! Spectre.css v0.5.7 | MIT License | github.com/picturepan2/spectre */
/* Manually forked from Normalize.css */
/* normalize.css v5.0.0 | MIT License | github.com/necolas/normalize.css */
/** 1. Change the default font family in all browsers (opinionated). 2. Correct the line height in all browsers. 3. Prevent adjustments of font size after orientation changes in IE on Windows Phone and in iOS. */
/* Document ========================================================================== */
html {
font-family: sans-serif; /* 1 */
-webkit-text-size-adjust: 100%; /* 3 */
-ms-text-size-adjust: 100%; /* 3 */
}
/* Sections ========================================================================== */
/** Remove the margin in all browsers (opinionated). */
body {
margin: 0;
}
/** Add the correct display in IE 9-. */
article,
aside,
footer,
header,
nav,
section {
display: block;
}
/** Correct the font size and margin on `h1` elements within `section` and `article` contexts in Chrome, Firefox, and Safari. */
h1 {
font-size: 2em;
margin: .67em 0;
}
/* Grouping content ========================================================================== */
/** Add the correct display in IE 9-. 1. Add the correct display in IE. */
figcaption,
figure,
main {
/* 1 */ display: block;
}
/** Add the correct margin in IE 8 (removed). */
/** 1. Add the correct box sizing in Firefox. 2. Show the overflow in Edge and IE. */
hr {
box-sizing: content-box; /* 1 */
height: 0; /* 1 */
overflow: visible; /* 2 */
}
/** 1. Correct the inheritance and scaling of font size in all browsers. (removed) 2. Correct the odd `em` font sizing in all browsers. */
/* Text-level semantics ========================================================================== */
/** 1. Remove the gray background on active links in IE 10. 2. Remove gaps in links underline in iOS 8+ and Safari 8+. */
a {
background-color: transparent; /* 1 */
-webkit-text-decoration-skip: objects; /* 2 */
}
/** Remove the outline on focused links when they are also active or hovered in all browsers (opinionated). */
a:active,
a:hover {
outline-width: 0;
}
/** Modify default styling of address. */
address {
font-style: normal;
}
/** 1. Remove the bottom border in Firefox 39-. 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari. (removed) */
/** Prevent the duplicate application of `bolder` by the next rule in Safari 6. */
b,
strong {
font-weight: inherit;
}
/** Add the correct font weight in Chrome, Edge, and Safari. */
b,
strong {
font-weight: bolder;
}
/** 1. Correct the inheritance and scaling of font size in all browsers. 2. Correct the odd `em` font sizing in all browsers. */
code,
kbd,
pre,
samp {
font-family: "SF Mono", "Segoe UI Mono", "Roboto Mono", Menlo, Courier, monospace; /* 1 (changed) */
font-size: 1em; /* 2 */
}
/** Add the correct font style in Android 4.3-. */
dfn {
font-style: italic;
}
/** Add the correct background and color in IE 9-. (Removed) */
/** Add the correct font size in all browsers. */
small {
font-size: 80%;
font-weight: 400; /* (added) */
}
/** Prevent `sub` and `sup` elements from affecting the line height in all browsers. */
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -.25em;
}
sup {
top: -.5em;
}
/* Embedded content ========================================================================== */
/** Add the correct display in IE 9-. */
audio,
video {
display: inline-block;
}
/** Add the correct display in iOS 4-7. */
audio:not([controls]) {
display: none;
height: 0;
}
/** Remove the border on images inside links in IE 10-. */
img {
border-style: none;
}
/** Hide the overflow in IE. */
svg:not(:root) {
overflow: hidden;
}
/* Forms ========================================================================== */
/** 1. Change the font styles in all browsers (opinionated). 2. Remove the margin in Firefox and Safari. */
button,
input,
optgroup,
select,
textarea {
font-family: inherit; /* 1 (changed) */
font-size: inherit; /* 1 (changed) */
line-height: inherit; /* 1 (changed) */
margin: 0; /* 2 */
}
/** Show the overflow in IE. 1. Show the overflow in Edge. */
button,
input {
/* 1 */ overflow: visible;
}
/** Remove the inheritance of text transform in Edge, Firefox, and IE. 1. Remove the inheritance of text transform in Firefox. */
button,
select {
/* 1 */ text-transform: none;
}
/** 1. Prevent a WebKit bug where (2) destroys native `audio` and `video` controls in Android 4. 2. Correct the inability to style clickable types in iOS and Safari. */
button,
html [type="button"],
[type="reset"],
[type="submit"] {
-webkit-appearance: button; /* 2 */
}
/** Remove the inner border and padding in Firefox. */
button::-moz-focus-inner,
[type="button"]::-moz-focus-inner,
[type="reset"]::-moz-focus-inner,
[type="submit"]::-moz-focus-inner {
border-style: none;
padding: 0;
}
/** Restore the focus styles unset by the previous rule (removed). */
/** Change the border, margin, and padding in all browsers (opinionated) (changed). */
fieldset {
border: 0;
margin: 0;
padding: 0;
}
/** 1. Correct the text wrapping in Edge and IE. 2. Correct the color inheritance from `fieldset` elements in IE. 3. Remove the padding so developers are not caught out when they zero out `fieldset` elements in all browsers. */
legend {
box-sizing: border-box; /* 1 */
color: inherit; /* 2 */
display: table; /* 1 */
max-width: 100%; /* 1 */
padding: 0; /* 3 */
white-space: normal; /* 1 */
}
/** 1. Add the correct display in IE 9-. 2. Add the correct vertical alignment in Chrome, Firefox, and Opera. */
progress {
display: inline-block; /* 1 */
vertical-align: baseline; /* 2 */
}
/** Remove the default vertical scrollbar in IE. */
textarea {
overflow: auto;
}
/** 1. Add the correct box sizing in IE 10-. 2. Remove the padding in IE 10-. */
[type="checkbox"],
[type="radio"] {
box-sizing: border-box; /* 1 */
padding: 0; /* 2 */
}
/** Correct the cursor style of increment and decrement buttons in Chrome. */
[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
height: auto;
}
/** 1. Correct the odd appearance in Chrome and Safari. 2. Correct the outline style in Safari. */
[type="search"] {
-webkit-appearance: textfield; /* 1 */
outline-offset: -2px; /* 2 */
}
/** Remove the inner padding and cancel buttons in Chrome and Safari on macOS. */
[type="search"]::-webkit-search-cancel-button,
[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/** 1. Correct the inability to style clickable types in iOS and Safari. 2. Change font properties to `inherit` in Safari. */
::-webkit-file-upload-button {
-webkit-appearance: button; /* 1 */
font: inherit; /* 2 */
}
/* Interactive ========================================================================== */
/* Add the correct display in IE 9-. 1. Add the correct display in Edge, IE, and Firefox. */
details,
menu {
display: block;
}
/* Add the correct display in all browsers. */
summary {
display: list-item;
outline: none;
}
/* Scripting ========================================================================== */
/** Add the correct display in IE 9-. */
canvas {
display: inline-block;
}
/** Add the correct display in IE. */
template {
display: none;
}
/* Hidden ========================================================================== */
/** Add the correct display in IE 10-. */
[hidden] {
display: none;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
html {
box-sizing: border-box;
font-size: 20px;
line-height: 1.5;
-webkit-tap-highlight-color: transparent;
}
body {
background: #fff;
color: #3b4351;
font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;
font-size: .8rem;
overflow-x: hidden;
text-rendering: optimizeLegibility;
}
a {
color: #5755d9;
outline: none;
text-decoration: none;
}
a:focus {
box-shadow: 0 0 0 .1rem rgba(87, 85, 217, .2);
}
a:focus,
a:hover,
a:active,
a.active {
color: #302ecd;
text-decoration: underline;
}
a:visited {
color: #807fe2;
}
h1,
h2,
h3,
h4,
h5,
h6 {
color: inherit;
font-weight: 500;
line-height: 1.2;
margin-bottom: .5em;
margin-top: 0;
}
.h1,
.h2,
.h3,
.h4,
.h5,
.h6 {
font-weight: 500;
}
h1,
.h1 {
font-size: 2rem;
}
h2,
.h2 {
font-size: 1.6rem;
}
h3,
.h3 {
font-size: 1.4rem;
}
h4,
.h4 {
font-size: 1.2rem;
}
h5,
.h5 {
font-size: 1rem;
}
h6,
.h6 {
font-size: .8rem;
}
p {
margin: 0 0 1.2rem;
}
a,
ins,
u {
-webkit-text-decoration-skip: ink edges;
text-decoration-skip: ink edges;
}
abbr[title] {
border-bottom: .05rem dotted;
cursor: help;
text-decoration: none;
}
kbd {
background: #303742;
border-radius: .1rem;
color: #fff;
font-size: .7rem;
line-height: 1.2;
padding: .1rem .2rem;
}
mark {
background: #ffe9b3;
border-bottom: .05rem solid #ffd367;
border-radius: .1rem;
color: #3b4351;
padding: .05rem .1rem 0;
}
blockquote {
border-left: .1rem solid #dadee4;
margin-left: 0;
padding: .4rem .8rem;
}
blockquote p:last-child {
margin-bottom: 0;
}
ul,
ol {
margin: .8rem 0 .8rem .8rem;
padding: 0;
}
ul ul,
ul ol,
ol ul,
ol ol {
margin: .8rem 0 .8rem .8rem;
}
ul li,
ol li {
margin-top: .4rem;
}
ul {
list-style: disc inside;
}
ul ul {
list-style-type: circle;
}
ol {
list-style: decimal inside;
}
ol ol {
list-style-type: lower-alpha;
}
dl dt {
font-weight: bold;
}
dl dd {
margin: .4rem 0 .8rem 0;
}
html:lang(zh),
html:lang(zh-Hans),
.lang-zh,
.lang-zh-hans {
font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Helvetica Neue", sans-serif;
}
html:lang(zh-Hant),
.lang-zh-hant {
font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang TC", "Hiragino Sans CNS", "Microsoft JhengHei", "Helvetica Neue", sans-serif;
}
html:lang(ja),
.lang-ja {
font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, "Hiragino Sans", "Hiragino Kaku Gothic Pro", "Yu Gothic", YuGothic, Meiryo, "Helvetica Neue", sans-serif;
}
html:lang(ko),
.lang-ko {
font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, "Malgun Gothic", "Helvetica Neue", sans-serif;
}
:lang(zh) ins,
:lang(zh) u,
:lang(ja) ins,
:lang(ja) u,
.lang-cjk ins,
.lang-cjk u {
border-bottom: .05rem solid;
text-decoration: none;
}
:lang(zh) del + del,
:lang(zh) del + s,
:lang(zh) ins + ins,
:lang(zh) ins + u,
:lang(zh) s + del,
:lang(zh) s + s,
:lang(zh) u + ins,
:lang(zh) u + u,
:lang(ja) del + del,
:lang(ja) del + s,
:lang(ja) ins + ins,
:lang(ja) ins + u,
:lang(ja) s + del,
:lang(ja) s + s,
:lang(ja) u + ins,
:lang(ja) u + u,
.lang-cjk del + del,
.lang-cjk del + s,
.lang-cjk ins + ins,
.lang-cjk ins + u,
.lang-cjk s + del,
.lang-cjk s + s,
.lang-cjk u + ins,
.lang-cjk u + u {
margin-left: .125em;
}
.table {
border-collapse: collapse;
border-spacing: 0;
text-align: left;
width: 100%;
}
.table.table-striped tbody tr:nth-of-type(odd) {
background: #f7f8f9;
}
.table tbody tr.active,
.table.table-striped tbody tr.active {
background: #eef0f3;
}
.table.table-hover tbody tr:hover {
background: #eef0f3;
}
.table.table-scroll {
display: block;
overflow-x: auto;
padding-bottom: .75rem;
white-space: nowrap;
}
.table td,
.table th {
border-bottom: .05rem solid #dadee4;
padding: .6rem .4rem;
}
.table th {
border-bottom-width: .1rem;
}
.btn {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: #fff;
border: .05rem solid #5755d9;
border-radius: .1rem;
color: #5755d9;
cursor: pointer;
display: inline-block;
font-size: .8rem;
height: 1.8rem;
line-height: 1.2rem;
outline: none;
padding: .25rem .4rem;
text-align: center;
text-decoration: none;
transition: background .2s, border .2s, box-shadow .2s, color .2s;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
vertical-align: middle;
white-space: nowrap;
}
.btn:focus {
box-shadow: 0 0 0 .1rem rgba(87, 85, 217, .2);
}
.btn:focus,
.btn:hover {
background: #f1f1fc;
border-color: #4b48d6;
text-decoration: none;
}
.btn:active,
.btn.active {
background: #4b48d6;
border-color: #3634d2;
color: #fff;
text-decoration: none;
}
.btn:active.loading::after,
.btn.active.loading::after {
border-bottom-color: #fff;
border-left-color: #fff;
}
.btn[disabled],
.btn:disabled,
.btn.disabled {
cursor: default;
opacity: .5;
pointer-events: none;
}
.btn.btn-primary {
background: #5755d9;
border-color: #4b48d6;
color: #fff;
}
.btn.btn-primary:focus,
.btn.btn-primary:hover {
background: #4240d4;
border-color: #3634d2;
color: #fff;
}
.btn.btn-primary:active,
.btn.btn-primary.active {
background: #3a38d2;
border-color: #302ecd;
color: #fff;
}
.btn.btn-primary.loading::after {
border-bottom-color: #fff;
border-left-color: #fff;
}
.btn.btn-success {
background: #32b643;
border-color: #2faa3f;
color: #fff;
}
.btn.btn-success:focus {
box-shadow: 0 0 0 .1rem rgba(50, 182, 67, .2);
}
.btn.btn-success:focus,
.btn.btn-success:hover {
background: #30ae40;
border-color: #2da23c;
color: #fff;
}
.btn.btn-success:active,
.btn.btn-success.active {
background: #2a9a39;
border-color: #278e34;
color: #fff;
}
.btn.btn-success.loading::after {
border-bottom-color: #fff;
border-left-color: #fff;
}
.btn.btn-error {
background: #e85600;
border-color: #d95000;
color: #fff;
}
.btn.btn-error:focus {
box-shadow: 0 0 0 .1rem rgba(232, 86, 0, .2);
}
.btn.btn-error:focus,
.btn.btn-error:hover {
background: #de5200;
border-color: #cf4d00;
color: #fff;
}
.btn.btn-error:active,
.btn.btn-error.active {
background: #c44900;
border-color: #b54300;
color: #fff;
}
.btn.btn-error.loading::after {
border-bottom-color: #fff;
border-left-color: #fff;
}
.btn.btn-link {
background: transparent;
border-color: transparent;
color: #5755d9;
}
.btn.btn-link:focus,
.btn.btn-link:hover,
.btn.btn-link:active,
.btn.btn-link.active {
color: #302ecd;
}
.btn.btn-sm {
font-size: .7rem;
height: 1.4rem;
padding: .05rem .3rem;
}
.btn.btn-lg {
font-size: .9rem;
height: 2rem;
padding: .35rem .6rem;
}
.btn.btn-block {
display: block;
width: 100%;
}
.btn.btn-action {
padding-left: 0;
padding-right: 0;
width: 1.8rem;
}
.btn.btn-action.btn-sm {
width: 1.4rem;
}
.btn.btn-action.btn-lg {
width: 2rem;
}
.btn.btn-clear {
background: transparent;
border: 0;
color: currentColor;
height: 1rem;
line-height: .8rem;
margin-left: .2rem;
margin-right: -2px;
opacity: 1;
padding: .1rem;
text-decoration: none;
width: 1rem;
}
.btn.btn-clear:focus,
.btn.btn-clear:hover {
background: rgba(247, 248, 249, .5);
opacity: .95;
}
.btn.btn-clear::before {
content: "\2715";
}
.btn-group {
display: inline-flex;
display: -ms-inline-flexbox;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
}
.btn-group .btn {
-ms-flex: 1 0 auto;
flex: 1 0 auto;
}
.btn-group .btn:first-child:not(:last-child) {
border-bottom-right-radius: 0;
border-top-right-radius: 0;
}
.btn-group .btn:not(:first-child):not(:last-child) {
border-radius: 0;
margin-left: -.05rem;
}
.btn-group .btn:last-child:not(:first-child) {
border-bottom-left-radius: 0;
border-top-left-radius: 0;
margin-left: -.05rem;
}
.btn-group .btn:focus,
.btn-group .btn:hover,
.btn-group .btn:active,
.btn-group .btn.active {
z-index: 1;
}
.btn-group.btn-group-block {
display: flex;
display: -ms-flexbox;
}
.btn-group.btn-group-block .btn {
-ms-flex: 1 0 0;
flex: 1 0 0;
}
.form-group:not(:last-child) {
margin-bottom: .4rem;
}
fieldset {
margin-bottom: .8rem;
}
legend {
font-size: .9rem;
font-weight: 500;
margin-bottom: .8rem;
}
.form-label {
display: block;
line-height: 1.2rem;
padding: .3rem 0;
}
.form-label.label-sm {
font-size: .7rem;
padding: .1rem 0;
}
.form-label.label-lg {
font-size: .9rem;
padding: .4rem 0;
}
.form-input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: #fff;
background-image: none;
border: .05rem solid #bcc3ce;
border-radius: .1rem;
color: #3b4351;
display: block;
font-size: .8rem;
height: 1.8rem;
line-height: 1.2rem;
max-width: 100%;
outline: none;
padding: .25rem .4rem;
position: relative;
transition: background .2s, border .2s, box-shadow .2s, color .2s;
width: 100%;
}
.form-input:focus {
border-color: #5755d9;
box-shadow: 0 0 0 .1rem rgba(87, 85, 217, .2);
}
.form-input::-webkit-input-placeholder {
color: #bcc3ce;
}
.form-input:-ms-input-placeholder {
color: #bcc3ce;
}
.form-input::-ms-input-placeholder {
color: #bcc3ce;
}
.form-input::placeholder {
color: #bcc3ce;
}
.form-input.input-sm {
font-size: .7rem;
height: 1.4rem;
padding: .05rem .3rem;
}
.form-input.input-lg {
font-size: .9rem;
height: 2rem;
padding: .35rem .6rem;
}
.form-input.input-inline {
display: inline-block;
vertical-align: middle;
width: auto;
}
.form-input[type="file"] {
height: auto;
}
textarea.form-input,
textarea.form-input.input-lg,
textarea.form-input.input-sm {
height: auto;
}
.form-input-hint {
color: #bcc3ce;
font-size: .7rem;
margin-top: .2rem;
}
.has-success .form-input-hint,
.is-success + .form-input-hint {
color: #32b643;
}
.has-error .form-input-hint,
.is-error + .form-input-hint {
color: #e85600;
}
.form-select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: #fff;
border: .05rem solid #bcc3ce;
border-radius: .1rem;
color: inherit;
font-size: .8rem;
height: 1.8rem;
line-height: 1.2rem;
outline: none;
padding: .25rem .4rem;
vertical-align: middle;
width: 100%;
}
.form-select:focus {
border-color: #5755d9;
box-shadow: 0 0 0 .1rem rgba(87, 85, 217, .2);
}
.form-select::-ms-expand {
display: none;
}
.form-select.select-sm {
font-size: .7rem;
height: 1.4rem;
padding: .05rem 1.1rem .05rem .3rem;
}
.form-select.select-lg {
font-size: .9rem;
height: 2rem;
padding: .35rem 1.4rem .35rem .6rem;
}
.form-select[size],
.form-select[multiple] {
height: auto;
padding: .25rem .4rem;
}
.form-select[size] option,
.form-select[multiple] option {
padding: .1rem .2rem;
}
.form-select:not([multiple]):not([size]) {
background: #fff url("data:image/svg+xml;charset=utf8,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%204%205'%3E%3Cpath%20fill='%23667189'%20d='M2%200L0%202h4zm0%205L0%203h4z'/%3E%3C/svg%3E") no-repeat right .35rem center/.4rem .5rem;
padding-right: 1.2rem;
}
.has-icon-left,
.has-icon-right {
position: relative;
}
.has-icon-left .form-icon,
.has-icon-right .form-icon {
height: .8rem;
margin: 0 .25rem;
position: absolute;
top: 50%;
transform: translateY(-50%);
width: .8rem;
z-index: 2;
}
.has-icon-left .form-icon {
left: .05rem;
}
.has-icon-left .form-input {
padding-left: 1.3rem;
}
.has-icon-right .form-icon {
right: .05rem;
}
.has-icon-right .form-input {
padding-right: 1.3rem;
}
.form-checkbox,
.form-radio,
.form-switch {
display: block;
line-height: 1.2rem;
margin: .2rem 0;
min-height: 1.2rem;
padding: .1rem .4rem .1rem 1.2rem;
position: relative;
}
.form-checkbox input,
.form-radio input,
.form-switch input {
clip: rect(0, 0, 0, 0);
height: 1px;
margin: -1px;
overflow: hidden;
position: absolute;
width: 1px;
}
.form-checkbox input:focus + .form-icon,
.form-radio input:focus + .form-icon,
.form-switch input:focus + .form-icon {
border-color: #5755d9;
box-shadow: 0 0 0 .1rem rgba(87, 85, 217, .2);
}
.form-checkbox input:checked + .form-icon,
.form-radio input:checked + .form-icon,
.form-switch input:checked + .form-icon {
background: #5755d9;
border-color: #5755d9;
}
.form-checkbox .form-icon,
.form-radio .form-icon,
.form-switch .form-icon {
border: .05rem solid #bcc3ce;
cursor: pointer;
display: inline-block;
position: absolute;
transition: background .2s, border .2s, box-shadow .2s, color .2s;
}
.form-checkbox.input-sm,
.form-radio.input-sm,
.form-switch.input-sm {
font-size: .7rem;
margin: 0;
}
.form-checkbox.input-lg,
.form-radio.input-lg,
.form-switch.input-lg {
font-size: .9rem;
margin: .3rem 0;
}
.form-checkbox .form-icon,
.form-radio .form-icon {
background: #fff;
height: .8rem;
left: 0;
top: .3rem;
width: .8rem;
}
.form-checkbox input:active + .form-icon,
.form-radio input:active + .form-icon {
background: #eef0f3;
}
.form-checkbox .form-icon {
border-radius: .1rem;
}
.form-checkbox input:checked + .form-icon::before {
background-clip: padding-box;
border: .1rem solid #fff;
border-left-width: 0;
border-top-width: 0;
content: "";
height: 9px;
left: 50%;
margin-left: -3px;
margin-top: -6px;
position: absolute;
top: 50%;
transform: rotate(45deg);
width: 6px;
}
.form-checkbox input:indeterminate + .form-icon {
background: #5755d9;
border-color: #5755d9;
}
.form-checkbox input:indeterminate + .form-icon::before {
background: #fff;
content: "";
height: 2px;
left: 50%;
margin-left: -5px;
margin-top: -1px;
position: absolute;
top: 50%;
width: 10px;
}
.form-radio .form-icon {
border-radius: 50%;
}
.form-radio input:checked + .form-icon::before {
background: #fff;
border-radius: 50%;
content: "";
height: 6px;
left: 50%;
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
width: 6px;
}
.form-switch {
padding-left: 2rem;
}
.form-switch .form-icon {
background: #bcc3ce;
background-clip: padding-box;
border-radius: .45rem;
height: .9rem;
left: 0;
top: .25rem;
width: 1.6rem;
}
.form-switch .form-icon::before {
background: #fff;
border-radius: 50%;
content: "";
display: block;
height: .8rem;
left: 0;
position: absolute;
top: 0;
transition: background .2s, border .2s, box-shadow .2s, color .2s, left .2s;
width: .8rem;
}
.form-switch input:checked + .form-icon::before {
left: 14px;
}
.form-switch input:active + .form-icon::before {
background: #f7f8f9;
}
.input-group {
display: flex;
display: -ms-flexbox;
}
.input-group .input-group-addon {
background: #f7f8f9;
border: .05rem solid #bcc3ce;
border-radius: .1rem;
line-height: 1.2rem;
padding: .25rem .4rem;
white-space: nowrap;
}
.input-group .input-group-addon.addon-sm {
font-size: .7rem;
padding: .05rem .3rem;
}
.input-group .input-group-addon.addon-lg {
font-size: .9rem;
padding: .35rem .6rem;
}
.input-group .form-input,
.input-group .form-select {
-ms-flex: 1 1 auto;
flex: 1 1 auto;
width: 1%;
}
.input-group .input-group-btn {
z-index: 1;
}
.input-group .form-input:first-child:not(:last-child),
.input-group .form-select:first-child:not(:last-child),
.input-group .input-group-addon:first-child:not(:last-child),
.input-group .input-group-btn:first-child:not(:last-child) {
border-bottom-right-radius: 0;
border-top-right-radius: 0;
}
.input-group .form-input:not(:first-child):not(:last-child),
.input-group .form-select:not(:first-child):not(:last-child),
.input-group .input-group-addon:not(:first-child):not(:last-child),
.input-group .input-group-btn:not(:first-child):not(:last-child) {
border-radius: 0;
margin-left: -.05rem;
}
.input-group .form-input:last-child:not(:first-child),
.input-group .form-select:last-child:not(:first-child),
.input-group .input-group-addon:last-child:not(:first-child),
.input-group .input-group-btn:last-child:not(:first-child) {
border-bottom-left-radius: 0;
border-top-left-radius: 0;
margin-left: -.05rem;
}
.input-group .form-input:focus,
.input-group .form-select:focus,
.input-group .input-group-addon:focus,
.input-group .input-group-btn:focus {
z-index: 2;
}
.input-group .form-select {
width: auto;
}
.input-group.input-inline {
display: inline-flex;
display: -ms-inline-flexbox;
}
.has-success .form-input,
.form-input.is-success,
.has-success .form-select,
.form-select.is-success {
background: #f9fdfa;
border-color: #32b643;
}
.has-success .form-input:focus,
.form-input.is-success:focus,
.has-success .form-select:focus,
.form-select.is-success:focus {
box-shadow: 0 0 0 .1rem rgba(50, 182, 67, .2);
}
.has-error .form-input,
.form-input.is-error,
.has-error .form-select,
.form-select.is-error {
background: #fffaf7;
border-color: #e85600;
}
.has-error .form-input:focus,
.form-input.is-error:focus,
.has-error .form-select:focus,
.form-select.is-error:focus {
box-shadow: 0 0 0 .1rem rgba(232, 86, 0, .2);
}
.has-error .form-checkbox .form-icon,
.form-checkbox.is-error .form-icon,
.has-error .form-radio .form-icon,
.form-radio.is-error .form-icon,
.has-error .form-switch .form-icon,
.form-switch.is-error .form-icon {
border-color: #e85600;
}
.has-error .form-checkbox input:checked + .form-icon,
.form-checkbox.is-error input:checked + .form-icon,
.has-error .form-radio input:checked + .form-icon,
.form-radio.is-error input:checked + .form-icon,
.has-error .form-switch input:checked + .form-icon,
.form-switch.is-error input:checked + .form-icon {
background: #e85600;
border-color: #e85600;
}
.has-error .form-checkbox input:focus + .form-icon,
.form-checkbox.is-error input:focus + .form-icon,
.has-error .form-radio input:focus + .form-icon,
.form-radio.is-error input:focus + .form-icon,
.has-error .form-switch input:focus + .form-icon,
.form-switch.is-error input:focus + .form-icon {
border-color: #e85600;
box-shadow: 0 0 0 .1rem rgba(232, 86, 0, .2);
}
.has-error .form-checkbox input:indeterminate + .form-icon,
.form-checkbox.is-error input:indeterminate + .form-icon {
background: #e85600;
border-color: #e85600;
}
.form-input:not(:placeholder-shown):invalid {
border-color: #e85600;
}
.form-input:not(:placeholder-shown):invalid:focus {
background: #fffaf7;
box-shadow: 0 0 0 .1rem rgba(232, 86, 0, .2);
}
.form-input:not(:placeholder-shown):invalid + .form-input-hint {
color: #e85600;
}
.form-input:disabled,
.form-input.disabled,
.form-select:disabled,
.form-select.disabled {
background-color: #eef0f3;
cursor: not-allowed;
opacity: .5;
}
.form-input[readonly] {
background-color: #f7f8f9;
}
input:disabled + .form-icon,
input.disabled + .form-icon {
background: #eef0f3;
cursor: not-allowed;
opacity: .5;
}
.form-switch input:disabled + .form-icon::before,
.form-switch input.disabled + .form-icon::before {
background: #fff;
}
.form-horizontal {
padding: .4rem 0;
}
.form-horizontal .form-group {
display: flex;
display: -ms-flexbox;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
}
.form-inline {
display: inline-block;
}
.label {
background: #eef0f3;
border-radius: .1rem;
color: #455060;
display: inline-block;
line-height: 1.2;
padding: .1rem .2rem;
}
.label.label-rounded {
border-radius: 5rem;
padding-left: .4rem;
padding-right: .4rem;
}
.label.label-primary {
background: #5755d9;
color: #fff;
}
.label.label-secondary {
background: #f1f1fc;
color: #5755d9;
}
.label.label-success {
background: #32b643;
color: #fff;
}
.label.label-warning {
background: #ffb700;
color: #fff;
}
.label.label-error {
background: #e85600;
color: #fff;
}
code {
background: #fcf2f2;
border-radius: .1rem;
color: #d73e48;
font-size: 85%;
line-height: 1.2;
padding: .1rem .2rem;
}
.code {
border-radius: .1rem;
color: #3b4351;
position: relative;
}
.code::before {
color: #bcc3ce;
content: attr(data-lang);
font-size: .7rem;
position: absolute;
right: .4rem;
top: .1rem;
}
.code code {
background: #f7f8f9;
color: inherit;
display: block;
line-height: 1.5;
overflow-x: auto;
padding: 1rem;
width: 100%;
}
.img-responsive {
display: block;
height: auto;
max-width: 100%;
}
.img-fit-cover {
object-fit: cover;
}
.img-fit-contain {
object-fit: contain;
}
.video-responsive {
display: block;
overflow: hidden;
padding: 0;
position: relative;
width: 100%;
}
.video-responsive::before {
content: "";
display: block;
padding-bottom: 56.25%;
}
.video-responsive iframe,
.video-responsive object,
.video-responsive embed {
border: 0;
bottom: 0;
height: 100%;
left: 0;
position: absolute;
right: 0;
top: 0;
width: 100%;
}
video.video-responsive {
height: auto;
max-width: 100%;
}
video.video-responsive::before {
content: none;
}
.video-responsive-4-3::before {
padding-bottom: 75%;
}
.video-responsive-1-1::before {
padding-bottom: 100%;
}
.figure {
margin: 0 0 .4rem 0;
}
.figure .figure-caption {
color: #66758c;
margin-top: .4rem;
}
.container {
margin-left: auto;
margin-right: auto;
padding-left: .4rem;
padding-right: .4rem;
width: 100%;
}
.container.grid-xl {
max-width: 1296px;
}
.container.grid-lg {
max-width: 976px;
}
.container.grid-md {
max-width: 856px;
}
.container.grid-sm {
max-width: 616px;
}
.container.grid-xs {
max-width: 496px;
}
.show-xs,
.show-sm,
.show-md,
.show-lg,
.show-xl {
display: none !important;
}
.columns {
display: flex;
display: -ms-flexbox;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
margin-left: -.4rem;
margin-right: -.4rem;
}
.columns.col-gapless {
margin-left: 0;
margin-right: 0;
}
.columns.col-gapless > .column {
padding-left: 0;
padding-right: 0;
}
.columns.col-oneline {
-ms-flex-wrap: nowrap;
flex-wrap: nowrap;
overflow-x: auto;
}
.column {
-ms-flex: 1;
flex: 1;
max-width: 100%;
padding-left: .4rem;
padding-right: .4rem;
}
.column.col-12,
.column.col-11,
.column.col-10,
.column.col-9,
.column.col-8,
.column.col-7,
.column.col-6,
.column.col-5,
.column.col-4,
.column.col-3,
.column.col-2,
.column.col-1 {
-ms-flex: none;
flex: none;
}
.col-12 {
width: 100%;
}
.col-11 {
width: 91.66666667%;
}
.col-10 {
width: 83.33333333%;
}
.col-9 {
width: 75%;
}
.col-8 {
width: 66.66666667%;
}
.col-7 {
width: 58.33333333%;
}
.col-6 {
width: 50%;
}
.col-5 {
width: 41.66666667%;
}
.col-4 {
width: 33.33333333%;
}
.col-3 {
width: 25%;
}
.col-2 {
width: 16.66666667%;
}
.col-1 {
width: 8.33333333%;
}
.col-auto {
-ms-flex: 0 0 auto;
flex: 0 0 auto;
max-width: none;
width: auto;
}
.col-mx-auto {
margin-left: auto;
margin-right: auto;
}
.col-ml-auto {
margin-left: auto;
}
.col-mr-auto {
margin-right: auto;
}
@media (max-width: 1280px) {
.col-xl-12,
.col-xl-11,
.col-xl-10,
.col-xl-9,
.col-xl-8,
.col-xl-7,
.col-xl-6,
.col-xl-5,
.col-xl-4,
.col-xl-3,
.col-xl-2,
.col-xl-1 {
-ms-flex: none;
flex: none;
}
.col-xl-12 {
width: 100%;
}
.col-xl-11 {
width: 91.66666667%;
}
.col-xl-10 {
width: 83.33333333%;
}
.col-xl-9 {
width: 75%;
}
.col-xl-8 {
width: 66.66666667%;
}
.col-xl-7 {
width: 58.33333333%;
}
.col-xl-6 {
width: 50%;
}
.col-xl-5 {
width: 41.66666667%;
}
.col-xl-4 {
width: 33.33333333%;
}
.col-xl-3 {
width: 25%;
}
.col-xl-2 {
width: 16.66666667%;
}
.col-xl-1 {
width: 8.33333333%;
}
.hide-xl {
display: none !important;
}
.show-xl {
display: block !important;
}
}
@media (max-width: 960px) {
.col-lg-12,
.col-lg-11,
.col-lg-10,
.col-lg-9,
.col-lg-8,
.col-lg-7,
.col-lg-6,
.col-lg-5,
.col-lg-4,
.col-lg-3,
.col-lg-2,
.col-lg-1 {
-ms-flex: none;
flex: none;
}
.col-lg-12 {
width: 100%;
}
.col-lg-11 {
width: 91.66666667%;
}
.col-lg-10 {
width: 83.33333333%;
}
.col-lg-9 {
width: 75%;
}
.col-lg-8 {
width: 66.66666667%;
}
.col-lg-7 {
width: 58.33333333%;
}
.col-lg-6 {
width: 50%;
}
.col-lg-5 {
width: 41.66666667%;
}
.col-lg-4 {
width: 33.33333333%;
}
.col-lg-3 {
width: 25%;
}
.col-lg-2 {
width: 16.66666667%;
}
.col-lg-1 {
width: 8.33333333%;
}
.hide-lg {
display: none !important;
}
.show-lg {
display: block !important;
}
}
@media (max-width: 840px) {
.col-md-12,
.col-md-11,
.col-md-10,
.col-md-9,
.col-md-8,
.col-md-7,
.col-md-6,
.col-md-5,
.col-md-4,
.col-md-3,
.col-md-2,
.col-md-1 {
-ms-flex: none;
flex: none;
}
.col-md-12 {
width: 100%;
}
.col-md-11 {
width: 91.66666667%;
}
.col-md-10 {
width: 83.33333333%;
}
.col-md-9 {
width: 75%;
}
.col-md-8 {
width: 66.66666667%;
}
.col-md-7 {
width: 58.33333333%;
}
.col-md-6 {
width: 50%;
}
.col-md-5 {
width: 41.66666667%;
}
.col-md-4 {
width: 33.33333333%;
}
.col-md-3 {
width: 25%;
}
.col-md-2 {
width: 16.66666667%;
}
.col-md-1 {
width: 8.33333333%;
}
.hide-md {
display: none !important;
}
.show-md {
display: block !important;
}
}
@media (max-width: 600px) {
.col-sm-12,
.col-sm-11,
.col-sm-10,
.col-sm-9,
.col-sm-8,
.col-sm-7,
.col-sm-6,
.col-sm-5,
.col-sm-4,
.col-sm-3,
.col-sm-2,
.col-sm-1 {
-ms-flex: none;
flex: none;
}
.col-sm-12 {
width: 100%;
}
.col-sm-11 {
width: 91.66666667%;
}
.col-sm-10 {
width: 83.33333333%;
}
.col-sm-9 {
width: 75%;
}
.col-sm-8 {
width: 66.66666667%;
}
.col-sm-7 {
width: 58.33333333%;
}
.col-sm-6 {
width: 50%;
}
.col-sm-5 {
width: 41.66666667%;
}
.col-sm-4 {
width: 33.33333333%;
}
.col-sm-3 {
width: 25%;
}
.col-sm-2 {
width: 16.66666667%;
}
.col-sm-1 {
width: 8.33333333%;
}
.hide-sm {
display: none !important;
}
.show-sm {
display: block !important;
}
}
@media (max-width: 480px) {
.col-xs-12,
.col-xs-11,
.col-xs-10,
.col-xs-9,
.col-xs-8,
.col-xs-7,
.col-xs-6,
.col-xs-5,
.col-xs-4,
.col-xs-3,
.col-xs-2,
.col-xs-1 {
-ms-flex: none;
flex: none;
}
.col-xs-12 {
width: 100%;
}
.col-xs-11 {
width: 91.66666667%;
}
.col-xs-10 {
width: 83.33333333%;
}
.col-xs-9 {
width: 75%;
}
.col-xs-8 {
width: 66.66666667%;
}
.col-xs-7 {
width: 58.33333333%;
}
.col-xs-6 {
width: 50%;
}
.col-xs-5 {
width: 41.66666667%;
}
.col-xs-4 {
width: 33.33333333%;
}
.col-xs-3 {
width: 25%;
}
.col-xs-2 {
width: 16.66666667%;
}
.col-xs-1 {
width: 8.33333333%;
}
.hide-xs {
display: none !important;
}
.show-xs {
display: block !important;
}
}
.hero {
display: flex;
display: -ms-flexbox;
-ms-flex-direction: column;
flex-direction: column;
-ms-flex-pack: justify;
justify-content: space-between;
padding-bottom: 4rem;
padding-top: 4rem;
}
.hero.hero-sm {
padding-bottom: 2rem;
padding-top: 2rem;
}
.hero.hero-lg {
padding-bottom: 8rem;
padding-top: 8rem;
}
.hero .hero-body {
padding: .4rem;
}
.navbar {
align-items: stretch;
display: flex;
display: -ms-flexbox;
-ms-flex-align: stretch;
-ms-flex-pack: justify;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
justify-content: space-between;
}
.navbar .navbar-section {
align-items: center;
display: flex;
display: -ms-flexbox;
-ms-flex: 1 0 0;
flex: 1 0 0;
-ms-flex-align: center;
}
.navbar .navbar-section:not(:first-child):last-child {
-ms-flex-pack: end;
justify-content: flex-end;
}
.navbar .navbar-center {
align-items: center;
display: flex;
display: -ms-flexbox;
-ms-flex: 0 0 auto;
flex: 0 0 auto;
-ms-flex-align: center;
}
.navbar .navbar-brand {
font-size: .9rem;
text-decoration: none;
}
.accordion input:checked ~ .accordion-header .icon,
.accordion[open] .accordion-header .icon {
transform: rotate(90deg);
}
.accordion input:checked ~ .accordion-body,
.accordion[open] .accordion-body {
max-height: 50rem;
}
.accordion .accordion-header {
display: block;
padding: .2rem .4rem;
}
.accordion .accordion-header .icon {
transition: transform .25s;
}
.accordion .accordion-body {
margin-bottom: .4rem;
max-height: 0;
overflow: hidden;
transition: max-height .25s;
}
summary.accordion-header::-webkit-details-marker {
display: none;
}
.avatar {
background: #5755d9;
border-radius: 50%;
color: rgba(255, 255, 255, .85);
display: inline-block;
font-size: .8rem;
font-weight: 300;
height: 1.6rem;
line-height: 1.25;
margin: 0;
position: relative;
vertical-align: middle;
width: 1.6rem;
}
.avatar.avatar-xs {
font-size: .4rem;
height: .8rem;
width: .8rem;
}
.avatar.avatar-sm {
font-size: .6rem;
height: 1.2rem;
width: 1.2rem;
}
.avatar.avatar-lg {
font-size: 1.2rem;
height: 2.4rem;
width: 2.4rem;
}
.avatar.avatar-xl {
font-size: 1.6rem;
height: 3.2rem;
width: 3.2rem;
}
.avatar img {
border-radius: 50%;
height: 100%;
position: relative;
width: 100%;
z-index: 1;
}
.avatar .avatar-icon,
.avatar .avatar-presence {
background: #fff;
bottom: 14.64%;
height: 50%;
padding: .1rem;
position: absolute;
right: 14.64%;
transform: translate(50%, 50%);
width: 50%;
z-index: 2;
}
.avatar .avatar-presence {
background: #bcc3ce;
border-radius: 50%;
box-shadow: 0 0 0 .1rem #fff;
height: .5em;
width: .5em;
}
.avatar .avatar-presence.online {
background: #32b643;
}
.avatar .avatar-presence.busy {
background: #e85600;
}
.avatar .avatar-presence.away {
background: #ffb700;
}
.avatar[data-initial]::before {
color: currentColor;
content: attr(data-initial);
left: 50%;
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
z-index: 1;
}
.badge {
position: relative;
white-space: nowrap;
}
.badge[data-badge]::after,
.badge:not([data-badge])::after {
background: #5755d9;
background-clip: padding-box;
border-radius: .5rem;
box-shadow: 0 0 0 .1rem #fff;
color: #fff;
content: attr(data-badge);
display: inline-block;
transform: translate(-.05rem, -.5rem);
}
.badge[data-badge]::after {
font-size: .7rem;
height: .9rem;
line-height: 1;
min-width: .9rem;
padding: .1rem .2rem;
text-align: center;
white-space: nowrap;
}
.badge:not([data-badge])::after,
.badge[data-badge=""]::after {
height: 6px;
min-width: 6px;
padding: 0;
width: 6px;
}
.badge.btn::after {
position: absolute;
right: 0;
top: 0;
transform: translate(50%, -50%);
}
.badge.avatar::after {
position: absolute;
right: 14.64%;
top: 14.64%;
transform: translate(50%, -50%);
z-index: 100;
}
.breadcrumb {
list-style: none;
margin: .2rem 0;
padding: .2rem 0;
}
.breadcrumb .breadcrumb-item {
color: #66758c;
display: inline-block;
margin: 0;
padding: .2rem 0;
}
.breadcrumb .breadcrumb-item:not(:last-child) {
margin-right: .2rem;
}
.breadcrumb .breadcrumb-item:not(:last-child) a {
color: #66758c;
}
.breadcrumb .breadcrumb-item:not(:first-child)::before {
color: #66758c;
content: "/";
padding-right: .4rem;
}
.bar {
background: #eef0f3;
border-radius: .1rem;
display: flex;
display: -ms-flexbox;
-ms-flex-wrap: nowrap;
flex-wrap: nowrap;
height: .8rem;
width: 100%;
}
.bar.bar-sm {
height: .2rem;
}
.bar .bar-item {
background: #5755d9;
color: #fff;
display: block;
-ms-flex-negative: 0;
flex-shrink: 0;
font-size: .7rem;
height: 100%;
line-height: .8rem;
position: relative;
text-align: center;
width: 0;
}
.bar .bar-item:first-child {
border-bottom-left-radius: .1rem;
border-top-left-radius: .1rem;
}
.bar .bar-item:last-child {
border-bottom-right-radius: .1rem;
border-top-right-radius: .1rem;
-ms-flex-negative: 1;
flex-shrink: 1;
}
.bar-slider {
height: .1rem;
margin: .4rem 0;
position: relative;
}
.bar-slider .bar-item {
left: 0;
padding: 0;
position: absolute;
}
.bar-slider .bar-item:not(:last-child):first-child {
background: #eef0f3;
z-index: 1;
}
.bar-slider .bar-slider-btn {
background: #5755d9;
border: 0;
border-radius: 50%;
height: .6rem;
padding: 0;
position: absolute;
right: 0;
top: 50%;
transform: translate(50%, -50%);
width: .6rem;
}
.bar-slider .bar-slider-btn:active {
box-shadow: 0 0 0 .1rem #5755d9;
}
.card {
background: #fff;
border: .05rem solid #dadee4;
border-radius: .1rem;
display: flex;
display: -ms-flexbox;
-ms-flex-direction: column;
flex-direction: column;
}
.card .card-header,
.card .card-body,
.card .card-footer {
padding: .8rem;
padding-bottom: 0;
}
.card .card-header:last-child,
.card .card-body:last-child,
.card .card-footer:last-child {
padding-bottom: .8rem;
}
.card .card-body {
-ms-flex: 1 1 auto;
flex: 1 1 auto;
}
.card .card-image {
padding-top: .8rem;
}
.card .card-image:first-child {
padding-top: 0;
}
.card .card-image:first-child img {
border-top-left-radius: .1rem;
border-top-right-radius: .1rem;
}
.card .card-image:last-child img {
border-bottom-left-radius: .1rem;
border-bottom-right-radius: .1rem;
}
.chip {
align-items: center;
background: #eef0f3;
border-radius: 5rem;
display: inline-flex;
display: -ms-inline-flexbox;
-ms-flex-align: center;
font-size: 90%;
height: 1.2rem;
line-height: .8rem;
margin: .1rem;
max-width: 320px;
overflow: hidden;
padding: .2rem .4rem;
text-decoration: none;
text-overflow: ellipsis;
vertical-align: middle;
white-space: nowrap;
}
.chip.active {
background: #5755d9;
color: #fff;
}
.chip .avatar {
margin-left: -.4rem;
margin-right: .2rem;
}
.chip .btn-clear {
border-radius: 50%;
transform: scale(.75);
}
.dropdown {
display: inline-block;
position: relative;
}
.dropdown .menu {
animation: slide-down .15s ease 1;
display: none;
left: 0;
max-height: 50vh;
overflow-y: auto;
position: absolute;
top: 100%;
}
.dropdown.dropdown-right .menu {
left: auto;
right: 0;
}
.dropdown.active .menu,
.dropdown .dropdown-toggle:focus + .menu,
.dropdown .menu:hover {
display: block;
}
.dropdown .btn-group .dropdown-toggle:nth-last-child(2) {
border-bottom-right-radius: .1rem;
border-top-right-radius: .1rem;
}
.empty {
background: #f7f8f9;
border-radius: .1rem;
color: #66758c;
padding: 3.2rem 1.6rem;
text-align: center;
}
.empty .empty-icon {
margin-bottom: .8rem;
}
.empty .empty-title,
.empty .empty-subtitle {
margin: .4rem auto;
}
.empty .empty-action {
margin-top: .8rem;
}
.menu {
background: #fff;
border-radius: .1rem;
box-shadow: 0 .05rem .2rem rgba(48, 55, 66, .3);
list-style: none;
margin: 0;
min-width: 180px;
padding: .4rem;
transform: translateY(.2rem);
z-index: 300;
}
.menu.menu-nav {
background: transparent;
box-shadow: none;
}
.menu .menu-item {
margin-top: 0;
padding: 0 .4rem;
text-decoration: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.menu .menu-item > a {
border-radius: .1rem;
color: inherit;
display: block;
margin: 0 -.4rem;
padding: .2rem .4rem;
text-decoration: none;
}
.menu .menu-item > a:focus,
.menu .menu-item > a:hover {
background: #f1f1fc;
color: #5755d9;
}
.menu .menu-item > a:active,
.menu .menu-item > a.active {
background: #f1f1fc;
color: #5755d9;
}
.menu .menu-item .form-checkbox,
.menu .menu-item .form-radio,
.menu .menu-item .form-switch {
margin: .1rem 0;
}
.menu .menu-item + .menu-item {
margin-top: .2rem;
}
.menu .menu-badge {
float: right;
padding: .2rem 0;
}
.menu .menu-badge .btn {
margin-top: -.1rem;
}
.modal {
align-items: center;
bottom: 0;
display: none;
-ms-flex-align: center;
-ms-flex-pack: center;
justify-content: center;
left: 0;
opacity: 0;
overflow: hidden;
padding: .4rem;
position: fixed;
right: 0;
top: 0;
}
.modal:target,
.modal.active {
display: flex;
display: -ms-flexbox;
opacity: 1;
z-index: 400;
}
.modal:target .modal-overlay,
.modal.active .modal-overlay {
background: rgba(247, 248, 249, .75);
bottom: 0;
cursor: default;
display: block;
left: 0;
position: absolute;
right: 0;
top: 0;
}
.modal:target .modal-container,
.modal.active .modal-container {
animation: slide-down .2s ease 1;
z-index: 1;
}
.modal.modal-sm .modal-container {
max-width: 320px;
padding: 0 .4rem;
}
.modal.modal-lg .modal-overlay {
background: #fff;
}
.modal.modal-lg .modal-container {
box-shadow: none;
max-width: 960px;
}
.modal-container {
background: #fff;
border-radius: .1rem;
box-shadow: 0 .2rem .5rem rgba(48, 55, 66, .3);
display: flex;
display: -ms-flexbox;
-ms-flex-direction: column;
flex-direction: column;
max-height: 75vh;
max-width: 640px;
padding: 0 .8rem;
width: 100%;
}
.modal-container.modal-fullheight {
max-height: 100vh;
}
.modal-container .modal-header {
color: #303742;
padding: .8rem;
}
.modal-container .modal-body {
overflow-y: auto;
padding: .8rem;
position: relative;
}
.modal-container .modal-footer {
padding: .8rem;
text-align: right;
}
.nav {
display: flex;
display: -ms-flexbox;
-ms-flex-direction: column;
flex-direction: column;
list-style: none;
margin: .2rem 0;
}
.nav .nav-item a {
color: #66758c;
padding: .2rem .4rem;
text-decoration: none;
}
.nav .nav-item a:focus,
.nav .nav-item a:hover {
color: #5755d9;
}
.nav .nav-item.active > a {
color: #505c6e;
font-weight: bold;
}
.nav .nav-item.active > a:focus,
.nav .nav-item.active > a:hover {
color: #5755d9;
}
.nav .nav {
margin-bottom: .4rem;
margin-left: .8rem;
}
.pagination {
display: flex;
display: -ms-flexbox;
list-style: none;
margin: .2rem 0;
padding: .2rem 0;
}
.pagination .page-item {
margin: .2rem .05rem;
}
.pagination .page-item span {
display: inline-block;
padding: .2rem .2rem;
}
.pagination .page-item a {
border-radius: .1rem;
display: inline-block;
padding: .2rem .4rem;
text-decoration: none;
}
.pagination .page-item a:focus,
.pagination .page-item a:hover {
color: #5755d9;
}
.pagination .page-item.disabled a {
cursor: default;
opacity: .5;
pointer-events: none;
}
.pagination .page-item.active a {
background: #5755d9;
color: #fff;
}
.pagination .page-item.page-prev,
.pagination .page-item.page-next {
-ms-flex: 1 0 50%;
flex: 1 0 50%;
}
.pagination .page-item.page-next {
text-align: right;
}
.pagination .page-item .page-item-title {
margin: 0;
}
.pagination .page-item .page-item-subtitle {
margin: 0;
opacity: .5;
}
.panel {
border: .05rem solid #dadee4;
border-radius: .1rem;
display: flex;
display: -ms-flexbox;
-ms-flex-direction: column;
flex-direction: column;
}
.panel .panel-header,
.panel .panel-footer {
-ms-flex: 0 0 auto;
flex: 0 0 auto;
padding: .8rem;
}
.panel .panel-nav {
-ms-flex: 0 0 auto;
flex: 0 0 auto;
}
.panel .panel-body {
-ms-flex: 1 1 auto;
flex: 1 1 auto;
overflow-y: auto;
padding: 0 .8rem;
}
.popover {
display: inline-block;
position: relative;
}
.popover .popover-container {
left: 50%;
opacity: 0;
padding: .4rem;
position: absolute;
top: 0;
transform: translate(-50%, -50%) scale(0);
transition: transform .2s;
width: 320px;
z-index: 300;
}
.popover *:focus + .popover-container,
.popover:hover .popover-container {
display: block;
opacity: 1;
transform: translate(-50%, -100%) scale(1);
}
.popover.popover-right .popover-container {
left: 100%;
top: 50%;
}
.popover.popover-right *:focus + .popover-container,
.popover.popover-right:hover .popover-container {
transform: translate(0, -50%) scale(1);
}
.popover.popover-bottom .popover-container {
left: 50%;
top: 100%;
}
.popover.popover-bottom *:focus + .popover-container,
.popover.popover-bottom:hover .popover-container {
transform: translate(-50%, 0) scale(1);
}
.popover.popover-left .popover-container {
left: 0;
top: 50%;
}
.popover.popover-left *:focus + .popover-container,
.popover.popover-left:hover .popover-container {
transform: translate(-100%, -50%) scale(1);
}
.popover .card {
border: 0;
box-shadow: 0 .2rem .5rem rgba(48, 55, 66, .3);
}
.step {
display: flex;
display: -ms-flexbox;
-ms-flex-wrap: nowrap;
flex-wrap: nowrap;
list-style: none;
margin: .2rem 0;
width: 100%;
}
.step .step-item {
-ms-flex: 1 1 0;
flex: 1 1 0;
margin-top: 0;
min-height: 1rem;
position: relative;
text-align: center;
}
.step .step-item:not(:first-child)::before {
background: #5755d9;
content: "";
height: 2px;
left: -50%;
position: absolute;
top: 9px;
width: 100%;
}
.step .step-item a {
color: #5755d9;
display: inline-block;
padding: 20px 10px 0;
text-decoration: none;
}
.step .step-item a::before {
background: #5755d9;
border: .1rem solid #fff;
border-radius: 50%;
content: "";
display: block;
height: .6rem;
left: 50%;
position: absolute;
top: .2rem;
transform: translateX(-50%);
width: .6rem;
z-index: 1;
}
.step .step-item.active a::before {
background: #fff;
border: .1rem solid #5755d9;
}
.step .step-item.active ~ .step-item::before {
background: #dadee4;
}
.step .step-item.active ~ .step-item a {
color: #bcc3ce;
}
.step .step-item.active ~ .step-item a::before {
background: #dadee4;
}
.tab {
align-items: center;
border-bottom: .05rem solid #dadee4;
display: flex;
display: -ms-flexbox;
-ms-flex-align: center;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
list-style: none;
margin: .2rem 0 .15rem 0;
}
.tab .tab-item {
margin-top: 0;
}
.tab .tab-item a {
border-bottom: .1rem solid transparent;
color: inherit;
display: block;
margin: 0 .4rem 0 0;
padding: .4rem .2rem .3rem .2rem;
text-decoration: none;
}
.tab .tab-item a:focus,
.tab .tab-item a:hover {
color: #5755d9;
}
.tab .tab-item.active a,
.tab .tab-item a.active {
border-bottom-color: #5755d9;
color: #5755d9;
}
.tab .tab-item.tab-action {
-ms-flex: 1 0 auto;
flex: 1 0 auto;
text-align: right;
}
.tab .tab-item .btn-clear {
margin-top: -.2rem;
}
.tab.tab-block .tab-item {
-ms-flex: 1 0 0;
flex: 1 0 0;
text-align: center;
}
.tab.tab-block .tab-item a {
margin: 0;
}
.tab.tab-block .tab-item .badge[data-badge]::after {
position: absolute;
right: .1rem;
top: .1rem;
transform: translate(0, 0);
}
.tab:not(.tab-block) .badge {
padding-right: 0;
}
.tile {
align-content: space-between;
align-items: flex-start;
display: flex;
display: -ms-flexbox;
-ms-flex-align: start;
-ms-flex-line-pack: justify;
}
.tile .tile-icon,
.tile .tile-action {
-ms-flex: 0 0 auto;
flex: 0 0 auto;
}
.tile .tile-content {
-ms-flex: 1 1 auto;
flex: 1 1 auto;
}
.tile .tile-content:not(:first-child) {
padding-left: .4rem;
}
.tile .tile-content:not(:last-child) {
padding-right: .4rem;
}
.tile .tile-title,
.tile .tile-subtitle {
line-height: 1.2rem;
}
.tile.tile-centered {
align-items: center;
-ms-flex-align: center;
}
.tile.tile-centered .tile-content {
overflow: hidden;
}
.tile.tile-centered .tile-title,
.tile.tile-centered .tile-subtitle {
margin-bottom: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.toast {
background: rgba(48, 55, 66, .95);
border: .05rem solid #303742;
border-color: #303742;
border-radius: .1rem;
color: #fff;
display: block;
padding: .4rem;
width: 100%;
}
.toast.toast-primary {
background: rgba(87, 85, 217, .95);
border-color: #5755d9;
}
.toast.toast-success {
background: rgba(50, 182, 67, .95);
border-color: #32b643;
}
.toast.toast-warning {
background: rgba(255, 183, 0, .95);
border-color: #ffb700;
}
.toast.toast-error {
background: rgba(232, 86, 0, .95);
border-color: #e85600;
}
.toast a {
color: #fff;
text-decoration: underline;
}
.toast a:focus,
.toast a:hover,
.toast a:active,
.toast a.active {
opacity: .75;
}
.toast .btn-clear {
margin: .1rem;
}
.toast p:last-child {
margin-bottom: 0;
}
.tooltip {
position: relative;
}
.tooltip::after {
background: rgba(48, 55, 66, .95);
border-radius: .1rem;
bottom: 100%;
color: #fff;
content: attr(data-tooltip);
display: block;
font-size: .7rem;
left: 50%;
max-width: 320px;
opacity: 0;
overflow: hidden;
padding: .2rem .4rem;
pointer-events: none;
position: absolute;
text-overflow: ellipsis;
transform: translate(-50%, .4rem);
transition: opacity .2s, transform .2s;
white-space: pre;
z-index: 300;
}
.tooltip:focus::after,
.tooltip:hover::after {
opacity: 1;
transform: translate(-50%, -.2rem);
}
.tooltip[disabled],
.tooltip.disabled {
pointer-events: auto;
}
.tooltip.tooltip-right::after {
bottom: 50%;
left: 100%;
transform: translate(-.2rem, 50%);
}
.tooltip.tooltip-right:focus::after,
.tooltip.tooltip-right:hover::after {
transform: translate(.2rem, 50%);
}
.tooltip.tooltip-bottom::after {
bottom: auto;
top: 100%;
transform: translate(-50%, -.4rem);
}
.tooltip.tooltip-bottom:focus::after,
.tooltip.tooltip-bottom:hover::after {
transform: translate(-50%, .2rem);
}
.tooltip.tooltip-left::after {
bottom: 50%;
left: auto;
right: 100%;
transform: translate(.4rem, 50%);
}
.tooltip.tooltip-left:focus::after,
.tooltip.tooltip-left:hover::after {
transform: translate(-.2rem, 50%);
}
@keyframes loading {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
@keyframes slide-down {
0% {
opacity: 0;
transform: translateY(-1.6rem);
}
100% {
opacity: 1;
transform: translateY(0);
}
}
.text-primary {
color: #5755d9 !important;
}
a.text-primary:focus,
a.text-primary:hover {
color: #4240d4;
}
a.text-primary:visited {
color: #6c6ade;
}
.text-secondary {
color: #e5e5f9 !important;
}
a.text-secondary:focus,
a.text-secondary:hover {
color: #d1d0f4;
}
a.text-secondary:visited {
color: #fafafe;
}
.text-gray {
color: #bcc3ce !important;
}
a.text-gray:focus,
a.text-gray:hover {
color: #adb6c4;
}
a.text-gray:visited {
color: #cbd0d9;
}
.text-light {
color: #fff !important;
}
a.text-light:focus,
a.text-light:hover {
color: #f2f2f2;
}
a.text-light:visited {
color: white;
}
.text-dark {
color: #3b4351 !important;
}
a.text-dark:focus,
a.text-dark:hover {
color: #303742;
}
a.text-dark:visited {
color: #455060;
}
.text-success {
color: #32b643 !important;
}
a.text-success:focus,
a.text-success:hover {
color: #2da23c;
}
a.text-success:visited {
color: #39c94b;
}
.text-warning {
color: #ffb700 !important;
}
a.text-warning:focus,
a.text-warning:hover {
color: #e6a500;
}
a.text-warning:visited {
color: #ffbe1a;
}
.text-error {
color: #e85600 !important;
}
a.text-error:focus,
a.text-error:hover {
color: #cf4d00;
}
a.text-error:visited {
color: #ff6003;
}
.bg-primary {
background: #5755d9 !important;
color: #fff;
}
.bg-secondary {
background: #f1f1fc !important;
}
.bg-dark {
background: #303742 !important;
color: #fff;
}
.bg-gray {
background: #f7f8f9 !important;
}
.bg-success {
background: #32b643 !important;
color: #fff;
}
.bg-warning {
background: #ffb700 !important;
color: #fff;
}
.bg-error {
background: #e85600 !important;
color: #fff;
}
.c-hand {
cursor: pointer;
}
.c-move {
cursor: move;
}
.c-zoom-in {
cursor: zoom-in;
}
.c-zoom-out {
cursor: zoom-out;
}
.c-not-allowed {
cursor: not-allowed;
}
.c-auto {
cursor: auto;
}
.d-block {
display: block;
}
.d-inline {
display: inline;
}
.d-inline-block {
display: inline-block;
}
.d-flex {
display: flex;
display: -ms-flexbox;
}
.d-inline-flex {
display: inline-flex;
display: -ms-inline-flexbox;
}
.d-none,
.d-hide {
display: none !important;
}
.d-visible {
visibility: visible;
}
.d-invisible {
visibility: hidden;
}
.text-hide {
background: transparent;
border: 0;
color: transparent;
font-size: 0;
line-height: 0;
text-shadow: none;
}
.text-assistive {
border: 0;
clip: rect(0, 0, 0, 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
.divider,
.divider-vert {
display: block;
position: relative;
}
.divider[data-content]::after,
.divider-vert[data-content]::after {
background: #fff;
color: #bcc3ce;
content: attr(data-content);
display: inline-block;
font-size: .7rem;
padding: 0 .4rem;
transform: translateY(-.65rem);
}
.divider {
border-top: .05rem solid #dadee4;
height: .05rem;
margin: .4rem 0;
}
.divider[data-content] {
margin: .8rem 0;
}
.divider-vert {
display: block;
padding: .8rem;
}
.divider-vert::before {
border-left: .05rem solid #dadee4;
bottom: .4rem;
content: "";
display: block;
left: 50%;
position: absolute;
top: .4rem;
transform: translateX(-50%);
}
.divider-vert[data-content]::after {
left: 50%;
padding: .2rem 0;
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
}
.loading {
color: transparent !important;
min-height: .8rem;
pointer-events: none;
position: relative;
}
.loading::after {
animation: loading 500ms infinite linear;
border: .1rem solid #5755d9;
border-radius: 50%;
border-right-color: transparent;
border-top-color: transparent;
content: "";
display: block;
height: .8rem;
left: 50%;
margin-left: -.4rem;
margin-top: -.4rem;
position: absolute;
top: 50%;
width: .8rem;
z-index: 1;
}
.loading.loading-lg {
min-height: 2rem;
}
.loading.loading-lg::after {
height: 1.6rem;
margin-left: -.8rem;
margin-top: -.8rem;
width: 1.6rem;
}
.clearfix::after {
clear: both;
content: "";
display: table;
}
.float-left {
float: left !important;
}
.float-right {
float: right !important;
}
.p-relative {
position: relative !important;
}
.p-absolute {
position: absolute !important;
}
.p-fixed {
position: fixed !important;
}
.p-sticky {
position: sticky !important;
position: -webkit-sticky !important;
}
.p-centered {
display: block;
float: none;
margin-left: auto;
margin-right: auto;
}
.flex-centered {
align-items: center;
display: flex;
display: -ms-flexbox;
-ms-flex-align: center;
-ms-flex-pack: center;
justify-content: center;
}
.m-0 {
margin: 0 !important;
}
.mb-0 {
margin-bottom: 0 !important;
}
.ml-0 {
margin-left: 0 !important;
}
.mr-0 {
margin-right: 0 !important;
}
.mt-0 {
margin-top: 0 !important;
}
.mx-0 {
margin-left: 0 !important;
margin-right: 0 !important;
}
.my-0 {
margin-bottom: 0 !important;
margin-top: 0 !important;
}
.m-1 {
margin: .2rem !important;
}
.mb-1 {
margin-bottom: .2rem !important;
}
.ml-1 {
margin-left: .2rem !important;
}
.mr-1 {
margin-right: .2rem !important;
}
.mt-1 {
margin-top: .2rem !important;
}
.mx-1 {
margin-left: .2rem !important;
margin-right: .2rem !important;
}
.my-1 {
margin-bottom: .2rem !important;
margin-top: .2rem !important;
}
.m-2 {
margin: .4rem !important;
}
.mb-2 {
margin-bottom: .4rem !important;
}
.ml-2 {
margin-left: .4rem !important;
}
.mr-2 {
margin-right: .4rem !important;
}
.mt-2 {
margin-top: .4rem !important;
}
.mx-2 {
margin-left: .4rem !important;
margin-right: .4rem !important;
}
.my-2 {
margin-bottom: .4rem !important;
margin-top: .4rem !important;
}
.p-0 {
padding: 0 !important;
}
.pb-0 {
padding-bottom: 0 !important;
}
.pl-0 {
padding-left: 0 !important;
}
.pr-0 {
padding-right: 0 !important;
}
.pt-0 {
padding-top: 0 !important;
}
.px-0 {
padding-left: 0 !important;
padding-right: 0 !important;
}
.py-0 {
padding-bottom: 0 !important;
padding-top: 0 !important;
}
.p-1 {
padding: .2rem !important;
}
.pb-1 {
padding-bottom: .2rem !important;
}
.pl-1 {
padding-left: .2rem !important;
}
.pr-1 {
padding-right: .2rem !important;
}
.pt-1 {
padding-top: .2rem !important;
}
.px-1 {
padding-left: .2rem !important;
padding-right: .2rem !important;
}
.py-1 {
padding-bottom: .2rem !important;
padding-top: .2rem !important;
}
.p-2 {
padding: .4rem !important;
}
.pb-2 {
padding-bottom: .4rem !important;
}
.pl-2 {
padding-left: .4rem !important;
}
.pr-2 {
padding-right: .4rem !important;
}
.pt-2 {
padding-top: .4rem !important;
}
.px-2 {
padding-left: .4rem !important;
padding-right: .4rem !important;
}
.py-2 {
padding-bottom: .4rem !important;
padding-top: .4rem !important;
}
.s-rounded {
border-radius: .1rem;
}
.s-circle {
border-radius: 50%;
}
.text-left {
text-align: left;
}
.text-right {
text-align: right;
}
.text-center {
text-align: center;
}
.text-justify {
text-align: justify;
}
.text-lowercase {
text-transform: lowercase;
}
.text-uppercase {
text-transform: uppercase;
}
.text-capitalize {
text-transform: capitalize;
}
.text-normal {
font-weight: normal;
}
.text-bold {
font-weight: bold;
}
.text-italic {
font-style: italic;
}
.text-large {
font-size: 1.2em;
}
.text-ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.text-clip {
overflow: hidden;
text-overflow: clip;
white-space: nowrap;
}
.text-break {
-webkit-hyphens: auto;
-ms-hyphens: auto;
hyphens: auto;
word-break: break-word;
word-wrap: break-word;
} | {
"pile_set_name": "Github"
} |
(VL2014::VL-PARSE-RANGE-FN
(66 1
(:REWRITE VL2014::VL-TOKENLIST-P-WHEN-NOT-CONSP))
(56 3 (:REWRITE VL2014::NTH-WHEN-TOO-BIG))
(40 40
(:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-CONS-LISTP))
(40 40
(:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-ATOM-LISTP))
(38
2
(:REWRITE VL2014::VL-PARSE-EXPRESSION-VAL-WHEN-ERROR-VL-PARSE-EXPRESSION))
(38 1 (:REWRITE CONSP-OF-CAR-WHEN-ALISTP))
(36 2
(:REWRITE VL2014::VL-PARSE-EXPRESSION-EOF-VL-PARSE-EXPRESSION))
(35 8 (:REWRITE LEN-WHEN-ATOM))
(18 1 (:REWRITE TRUE-LISTP-WHEN-ATOM))
(17 1
(:REWRITE TRUE-LISTP-WHEN-SYMBOL-LISTP-REWRITE))
(14 1
(:REWRITE TRUE-LISTP-WHEN-STRING-LISTP-REWRITE))
(13 2 (:REWRITE DEFAULT-CAR))
(12 1
(:REWRITE TRUE-LISTP-WHEN-CHARACTER-LISTP-REWRITE))
(12 1 (:LINEAR VL2014::LEN-OF-CDR-STRONG))
(11 1
(:REWRITE VL2014::VL-TOKENLIST-P-OF-CAR-WHEN-VL-TOKENLISTLIST-P))
(11 1
(:REWRITE VL2014::ALISTP-WHEN-VL-ATTS-P-REWRITE))
(9 1
(:REWRITE ALISTP-WHEN-HONS-DUPLICITY-ALIST-P))
(9 1
(:REWRITE VL2014::ALISTP-WHEN-ALL-HAVE-LEN))
(7 1 (:REWRITE |(< 0 (len x))|))
(6 6 (:REWRITE DEFAULT-CDR))
(6 1
(:REWRITE VL2014::VL-TOKENLISTLIST-P-WHEN-NOT-CONSP))
(6 1
(:REWRITE VL2014::VL-ATTS-P-WHEN-NOT-CONSP))
(6 1
(:REWRITE SET::SETS-ARE-TRUE-LISTS-CHEAP))
(6 1 (:REWRITE NTH-WHEN-ATOM))
(6 1 (:REWRITE VL2014::NTH-OF-ATOM))
(6 1
(:REWRITE HONS-DUPLICITY-ALIST-P-WHEN-NOT-CONSP))
(6 1
(:REWRITE VL2014::CONSP-OF-CAR-WHEN-VL-COMMENTMAP-P))
(6 1
(:REWRITE VL2014::ALL-HAVE-LEN-WHEN-NOT-CONSP))
(6 1 (:REWRITE ALISTP-WHEN-ATOM))
(4 4
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-USERTYPES-P
. 2))
(4 4
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-USERTYPES-P
. 1))
(4 4
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-GENCASELIST-P
. 2))
(4 4
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-GENCASELIST-P
. 1))
(4 4
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-COMMENTMAP-P
. 2))
(4 4
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-COMMENTMAP-P
. 1))
(4 4
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-CASELIST-P
. 2))
(4 4
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-CASELIST-P
. 1))
(4 4
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-ATTS-P
. 2))
(4 4
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-ATTS-P
. 1))
(4 4 (:REWRITE CONSP-BY-LEN))
(4 2
(:REWRITE SYMBOL-LISTP-WHEN-SUBSETP-EQUAL))
(4 1
(:REWRITE VL2014::STRING-LISTP-WHEN-NO-NILS-IN-VL-MAYBE-STRING-LISTP))
(3 1
(:REWRITE VL2014::SYMBOL-LISTP-WHEN-SUBSETP-EQUAL-OF-SYMBOL-LISTP
. 1))
(3 1 (:REWRITE NTH-WITH-LARGE-INDEX))
(3 1 (:REWRITE NTH-WHEN-TOO-LARGE-CHEAP))
(2 2
(:TYPE-PRESCRIPTION VL2014::VL-TOKENLISTLIST-P))
(2 2
(:TYPE-PRESCRIPTION VL2014::VL-COMMENTMAP-P))
(2 2
(:TYPE-PRESCRIPTION VL2014::VL-ATTS-P))
(2 2 (:TYPE-PRESCRIPTION SYMBOL-LISTP))
(2 2 (:TYPE-PRESCRIPTION SUBSETP-EQUAL))
(2 2 (:TYPE-PRESCRIPTION STRING-LISTP))
(2 2 (:TYPE-PRESCRIPTION SET::SETP-TYPE))
(2 2
(:TYPE-PRESCRIPTION HONS-DUPLICITY-ALIST-P))
(2 2 (:TYPE-PRESCRIPTION CHARACTER-LISTP))
(2 2
(:TYPE-PRESCRIPTION VL2014::ALL-HAVE-LEN))
(2 2 (:TYPE-PRESCRIPTION ALISTP))
(2 2
(:REWRITE VL2014::VL-TOKENLISTLIST-P-WHEN-SUBSETP-EQUAL))
(2 2
(:REWRITE VL2014::VL-TOKENLIST-P-WHEN-SUBSETP-EQUAL))
(2
2
(:REWRITE VL2014::VL-TOKENLIST-P-WHEN-MEMBER-EQUAL-OF-VL-TOKENLISTLIST-P))
(2 2
(:REWRITE VL2014::VL-COMMENTMAP-P-WHEN-SUBSETP-EQUAL))
(2 2
(:REWRITE VL2014::VL-ATTS-P-WHEN-SUBSETP-EQUAL))
(2 2
(:REWRITE VL2014::TRUE-LISTP-WHEN-MEMBER-EQUAL-OF-TRUE-LIST-LISTP))
(2 2
(:REWRITE VL2014::SYMBOL-LISTP-WHEN-MEMBER-EQUAL-OF-SYMBOL-LIST-LISTP))
(2 2
(:REWRITE VL2014::SYMBOL-LISTP-OF-ALIST-VALS-OF-VL-FULL-KEYWORD-TABLE))
(2 2
(:REWRITE STRING-LISTP-WHEN-SUBSETP-EQUAL))
(2 2
(:REWRITE VL2014::STRING-LISTP-WHEN-MEMBER-EQUAL-OF-STRING-LIST-LISTP))
(2 2
(:REWRITE CHARACTER-LISTP-WHEN-SUBSETP-EQUAL))
(2 2 (:REWRITE CAR-WHEN-ALL-EQUALP))
(2 2
(:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP))
(2 2
(:LINEAR LISTPOS-UPPER-BOUND-STRONG-2))
(2 2 (:LINEAR LEN-WHEN-PREFIXP))
(2 1
(:TYPE-PRESCRIPTION TRUE-LISTP-MEMBER-EQUAL))
(2 1
(:REWRITE SYMBOL-LISTP-WHEN-BOOLEAN-LISTP))
(2 1 (:REWRITE SET::NONEMPTY-MEANS-SET))
(2 1 (:REWRITE SET::DOUBLE-CONTAINMENT))
(2 1
(:REWRITE CONSP-OF-CAR-WHEN-CONS-LISTP))
(2 1
(:REWRITE CONSP-OF-CAR-WHEN-ATOM-LISTP))
(2 1
(:REWRITE STR::CHARACTER-LISTP-WHEN-OCTAL-DIGIT-LISTP))
(2 1
(:REWRITE STR::CHARACTER-LISTP-WHEN-HEX-DIGIT-LISTP))
(2 1
(:REWRITE STR::CHARACTER-LISTP-WHEN-DIGIT-LISTP))
(1 1
(:TYPE-PRESCRIPTION STR::OCTAL-DIGIT-LISTP))
(1 1
(:TYPE-PRESCRIPTION STR::HEX-DIGIT-LISTP))
(1 1 (:TYPE-PRESCRIPTION SET::EMPTY-TYPE))
(1 1 (:TYPE-PRESCRIPTION STR::DIGIT-LISTP))
(1 1
(:TYPE-PRESCRIPTION CONSP-MEMBER-EQUAL))
(1 1 (:TYPE-PRESCRIPTION CONS-LISTP))
(1 1 (:TYPE-PRESCRIPTION BOOLEAN-LISTP))
(1 1 (:TYPE-PRESCRIPTION ATOM-LISTP))
(1 1
(:REWRITE VL2014::VL-COMMENTMAP-P-WHEN-NOT-CONSP))
(1 1
(:REWRITE TRUE-LISTP-WHEN-UNSIGNED-BYTE-LISTP))
(1 1
(:REWRITE TRUE-LISTP-WHEN-SIGNED-BYTE-LISTP))
(1 1
(:REWRITE VL2014::SYMBOL-LISTP-WHEN-SUBSETP-EQUAL-OF-SYMBOL-LISTP
. 2))
(1 1
(:REWRITE SYMBOL-LISTP-WHEN-NOT-CONSP))
(1 1
(:REWRITE VL2014::STRING-LISTP-WHEN-SUBSETP-EQUAL-OF-STRING-LISTP
. 2))
(1 1
(:REWRITE VL2014::STRING-LISTP-WHEN-SUBSETP-EQUAL-OF-STRING-LISTP
. 1))
(1 1
(:REWRITE STRING-LISTP-WHEN-NOT-CONSP))
(1 1 (:REWRITE NTH-WHEN-ZP))
(1 1 (:REWRITE NTH-WHEN-PREFIXP))
(1 1 (:REWRITE SET::IN-SET))
(1 1 (:REWRITE FN-CHECK-DEF-FORMALS))
(1 1
(:REWRITE CHARACTER-LISTP-WHEN-NOT-CONSP))
(1 1 (:META CANCEL_TIMES-EQUAL-CORRECT))
(1 1 (:META CANCEL_PLUS-EQUAL-CORRECT))
(1 1 (:LINEAR LEQ-POSITION-EQUAL-LEN))
(1 1 (:LINEAR INDEX-OF-<-LEN))
(1 1
(:LINEAR STR::COUNT-LEADING-CHARSET-LEN)))
(VL2014::VL-PARSE-RANGE-FAILS-GRACEFULLY
(422 211
(:TYPE-PRESCRIPTION VL2014::VL-IS-TOKEN?-FN-WHEN-ATOM-OF-TOKENS))
(306 17
(:REWRITE VL2014::VL-PARSE-EXPRESSION-EOF-VL-PARSE-EXPRESSION))
(84 12
(:REWRITE VL2014::VL-MATCH-TOKEN-FAILS-GRACEFULLY))
(34 34
(:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-CONS-LISTP))
(34 34
(:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-ATOM-LISTP))
(34 17
(:REWRITE CONSP-UNDER-IFF-WHEN-TRUE-LISTP))
(17 17 (:TYPE-PRESCRIPTION TRUE-LISTP))
(17 17
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-USERTYPES-P
. 2))
(17 17
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-USERTYPES-P
. 1))
(17 17
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-GENCASELIST-P
. 2))
(17 17
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-GENCASELIST-P
. 1))
(17 17
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-COMMENTMAP-P
. 2))
(17 17
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-COMMENTMAP-P
. 1))
(17 17
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-CASELIST-P
. 2))
(17 17
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-CASELIST-P
. 1))
(17 17
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-ATTS-P
. 2))
(17 17
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-ATTS-P
. 1))
(17 17 (:REWRITE CONSP-BY-LEN))
(1 1
(:REWRITE VL2014::VL-RANGE-OF-VL-EXPR-FIX-MSB-NORMALIZE-CONST))
(1 1
(:REWRITE VL2014::VL-RANGE-OF-VL-EXPR-FIX-LSB-NORMALIZE-CONST)))
(VL2014::VL-WARNING-P-OF-VL-PARSE-RANGE
(114
6
(:REWRITE VL2014::VL-PARSE-EXPRESSION-VAL-WHEN-ERROR-VL-PARSE-EXPRESSION))
(108 6
(:REWRITE VL2014::VL-PARSE-EXPRESSION-EOF-VL-PARSE-EXPRESSION))
(63 9
(:REWRITE VL2014::VL-MATCH-TOKEN-FAILS-GRACEFULLY))
(36 18
(:TYPE-PRESCRIPTION VL2014::VL-IS-TOKEN?-FN-WHEN-ATOM-OF-TOKENS))
(18 18
(:TYPE-PRESCRIPTION VL2014::VL-IS-TOKEN?$INLINE))
(18 18 (:TYPE-PRESCRIPTION ATOM))
(12 12
(:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-CONS-LISTP))
(12 12
(:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-ATOM-LISTP))
(12 6
(:REWRITE CONSP-UNDER-IFF-WHEN-TRUE-LISTP))
(6 6 (:TYPE-PRESCRIPTION TRUE-LISTP))
(6 6
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-USERTYPES-P
. 2))
(6 6
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-USERTYPES-P
. 1))
(6 6
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-GENCASELIST-P
. 2))
(6 6
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-GENCASELIST-P
. 1))
(6 6
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-COMMENTMAP-P
. 2))
(6 6
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-COMMENTMAP-P
. 1))
(6 6
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-CASELIST-P
. 2))
(6 6
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-CASELIST-P
. 1))
(6 6
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-ATTS-P
. 2))
(6 6
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-ATTS-P
. 1))
(6 6 (:REWRITE CONSP-BY-LEN))
(3 3
(:REWRITE VL2014::VL-RANGE-OF-VL-EXPR-FIX-MSB-NORMALIZE-CONST))
(3 3
(:REWRITE VL2014::VL-RANGE-OF-VL-EXPR-FIX-LSB-NORMALIZE-CONST))
(2 2
(:REWRITE VL2014::VL-WARNING-P-WHEN-MEMBER-EQUAL-OF-VL-WARNINGLIST-P)))
(VL2014::VL-PARSE-RANGE-RESULT
(180 10
(:REWRITE VL2014::VL-PARSE-EXPRESSION-EOF-VL-PARSE-EXPRESSION))
(138 69
(:TYPE-PRESCRIPTION VL2014::VL-IS-TOKEN?-FN-WHEN-ATOM-OF-TOKENS))
(69 69 (:TYPE-PRESCRIPTION ATOM))
(20 20
(:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-CONS-LISTP))
(20 20
(:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-ATOM-LISTP))
(20 10
(:REWRITE CONSP-UNDER-IFF-WHEN-TRUE-LISTP))
(15 2 (:REWRITE SET::DOUBLE-CONTAINMENT))
(13 2
(:REWRITE VL2014::VL-RANGE-P-WHEN-VL-MAYBE-RANGE-P))
(10 10 (:TYPE-PRESCRIPTION TRUE-LISTP))
(10 10
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-USERTYPES-P
. 2))
(10 10
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-USERTYPES-P
. 1))
(10 10
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-GENCASELIST-P
. 2))
(10 10
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-GENCASELIST-P
. 1))
(10 10
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-COMMENTMAP-P
. 2))
(10 10
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-COMMENTMAP-P
. 1))
(10 10
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-CASELIST-P
. 2))
(10 10
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-CASELIST-P
. 1))
(10 10
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-ATTS-P
. 2))
(10 10
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-ATTS-P
. 1))
(10 10 (:REWRITE CONSP-BY-LEN))
(10 2
(:REWRITE VL2014::VL-RANGE-P-WHEN-VL-PACKEDDIMENSION-P))
(8 1
(:REWRITE VL2014::VL-MAYBE-RANGE-P-WHEN-VL-RANGE-P))
(4 4 (:TYPE-PRESCRIPTION SET::SETP-TYPE))
(4 4
(:REWRITE VL2014::VL-RANGE-P-WHEN-MEMBER-EQUAL-OF-VL-RANGELIST-P))
(4 2 (:REWRITE SET::NONEMPTY-MEANS-SET))
(3 3
(:TYPE-PRESCRIPTION VL2014::VL-MAYBE-RANGE-P))
(2 2 (:TYPE-PRESCRIPTION SET::EMPTY-TYPE))
(2 2
(:REWRITE VL2014::VL-RANGE-OF-VL-EXPR-FIX-MSB-NORMALIZE-CONST))
(2 2
(:REWRITE VL2014::VL-RANGE-OF-VL-EXPR-FIX-LSB-NORMALIZE-CONST))
(2
2
(:REWRITE
VL2014::VL-MAYBE-RANGE-P-WHEN-MEMBER-EQUAL-OF-VL-MAYBE-RANGE-LIST-P))
(2 2 (:REWRITE SET::IN-SET))
(2 2 (:META CANCEL_TIMES-EQUAL-CORRECT))
(2 2 (:META CANCEL_PLUS-EQUAL-CORRECT)))
(VL2014::VL-PARSE-RANGE-COUNT-STRONG
(1480 86 (:REWRITE LEN-WHEN-ATOM))
(921 2
(:REWRITE LOWER-BOUND-OF-LEN-WHEN-SUBLISTP))
(841 2 (:REWRITE SUBLISTP-WHEN-PREFIXP))
(751 4 (:REWRITE PREFIXP-WHEN-EQUAL-LENGTHS))
(188 188
(:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-CONS-LISTP))
(188 188
(:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-ATOM-LISTP))
(188 94
(:REWRITE CONSP-UNDER-IFF-WHEN-TRUE-LISTP))
(94 94 (:TYPE-PRESCRIPTION TRUE-LISTP))
(94 94
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-USERTYPES-P
. 2))
(94 94
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-USERTYPES-P
. 1))
(94 94
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-GENCASELIST-P
. 2))
(94 94
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-GENCASELIST-P
. 1))
(94 94
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-COMMENTMAP-P
. 2))
(94 94
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-COMMENTMAP-P
. 1))
(94 94
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-CASELIST-P
. 2))
(94 94
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-CASELIST-P
. 1))
(94 94
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-ATTS-P
. 2))
(94 94
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-ATTS-P
. 1))
(94 94 (:REWRITE CONSP-BY-LEN))
(78
6
(:REWRITE VL2014::VL-PARSE-EXPRESSION-VAL-WHEN-ERROR-VL-PARSE-EXPRESSION))
(72 4
(:REWRITE VL2014::VL-PARSE-EXPRESSION-EOF-VL-PARSE-EXPRESSION))
(70 35
(:TYPE-PRESCRIPTION VL2014::VL-IS-TOKEN?-FN-WHEN-ATOM-OF-TOKENS))
(68 17
(:REWRITE VL2014::VL-MATCH-TOKEN-UNDER-IFF))
(63 9
(:REWRITE VL2014::VL-MATCH-TOKEN-FAILS-GRACEFULLY))
(58 58
(:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP))
(58 58
(:LINEAR LISTPOS-UPPER-BOUND-STRONG-2))
(58 58 (:LINEAR LEN-WHEN-PREFIXP))
(38 4
(:REWRITE PREFIXP-WHEN-NOT-CONSP-RIGHT))
(38 4
(:REWRITE PREFIXP-WHEN-NOT-CONSP-LEFT))
(36 2 (:REWRITE SUBLISTP-WHEN-ATOM-RIGHT))
(36 2 (:REWRITE SUBLISTP-WHEN-ATOM-LEFT))
(35 35
(:TYPE-PRESCRIPTION VL2014::VL-IS-TOKEN?$INLINE))
(35 35 (:TYPE-PRESCRIPTION ATOM))
(35 35 (:LINEAR LEQ-POSITION-EQUAL-LEN))
(35 35 (:LINEAR INDEX-OF-<-LEN))
(29 29
(:LINEAR STR::COUNT-LEADING-CHARSET-LEN))
(26 2 (:REWRITE LEN-WHEN-PREFIXP))
(8 8 (:TYPE-PRESCRIPTION PREFIXP))
(8 8
(:REWRITE VL2014::PREFIXP-WHEN-MEMBER-EQUAL-OF-PREFIX-OF-EACHP))
(4 4 (:TYPE-PRESCRIPTION SUBLISTP))
(4 4
(:REWRITE VL2014::TRANSITIVITY-OF-PREFIXP))
(4 4 (:REWRITE PREFIXP-TRANSITIVE . 2))
(4 4 (:REWRITE PREFIXP-TRANSITIVE . 1))
(4 4
(:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 2))
(4 4
(:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 1))
(4 2 (:REWRITE SET::DOUBLE-CONTAINMENT))
(4 2 (:REWRITE DEFAULT-<-2))
(4 2 (:REWRITE DEFAULT-<-1))
(3 3
(:REWRITE VL2014::VL-RANGE-OF-VL-EXPR-FIX-MSB-NORMALIZE-CONST))
(3 3
(:REWRITE VL2014::VL-RANGE-OF-VL-EXPR-FIX-LSB-NORMALIZE-CONST))
(2 2 (:REWRITE SUBLISTP-COMPLETE))
(2 2 (:META CANCEL_TIMES-EQUAL-CORRECT))
(2 2 (:META CANCEL_PLUS-LESSP-CORRECT))
(2 2 (:META CANCEL_PLUS-EQUAL-CORRECT)))
(VL2014::VL-PARSE-0+-RANGES-FN
(70 43
(:TYPE-PRESCRIPTION VL2014::VL-IS-TOKEN?-FN-WHEN-ATOM-OF-TOKENS))
(36 2 (:REWRITE LEN-WHEN-ATOM))
(4 4
(:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-CONS-LISTP))
(4 4
(:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-ATOM-LISTP))
(4 2
(:REWRITE CONSP-UNDER-IFF-WHEN-TRUE-LISTP))
(2 2 (:TYPE-PRESCRIPTION TRUE-LISTP))
(2 2
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-USERTYPES-P
. 2))
(2 2
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-USERTYPES-P
. 1))
(2 2
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-GENCASELIST-P
. 2))
(2 2
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-GENCASELIST-P
. 1))
(2 2
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-COMMENTMAP-P
. 2))
(2 2
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-COMMENTMAP-P
. 1))
(2 2
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-CASELIST-P
. 2))
(2 2
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-CASELIST-P
. 1))
(2 2
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-ATTS-P
. 2))
(2 2
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-ATTS-P
. 1))
(2 2 (:REWRITE CONSP-BY-LEN)))
(VL2014::VL-PARSE-0+-RANGES-FAILS-GRACEFULLY
(164 82
(:TYPE-PRESCRIPTION VL2014::VL-IS-TOKEN?-FN-WHEN-ATOM-OF-TOKENS)))
(VL2014::VL-WARNING-P-OF-VL-PARSE-0+-RANGES
(156 78
(:TYPE-PRESCRIPTION VL2014::VL-IS-TOKEN?-FN-WHEN-ATOM-OF-TOKENS))
(6 6
(:REWRITE VL2014::VL-WARNING-P-WHEN-MEMBER-EQUAL-OF-VL-WARNINGLIST-P)))
(VL2014::VL-PARSE-0+-RANGES-RESULT
(156 78
(:TYPE-PRESCRIPTION VL2014::VL-IS-TOKEN?-FN-WHEN-ATOM-OF-TOKENS))
(31 1 (:REWRITE SUBSETP-OF-CONS))
(19 2
(:REWRITE VL2014::VL-RANGELIST-P-WHEN-NOT-CONSP))
(15 2
(:REWRITE VL2014::MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-UNDER-IFF))
(12 6
(:TYPE-PRESCRIPTION TRUE-LISTP-MEMBER-EQUAL))
(7 7 (:TYPE-PRESCRIPTION TRUE-LISTP))
(6 6
(:TYPE-PRESCRIPTION CONSP-MEMBER-EQUAL))
(6
6
(:REWRITE VL2014::VL-RANGELIST-P-WHEN-MEMBER-EQUAL-OF-VL-RANGELIST-LIST-P))
(3 3 (:REWRITE SUBSETP-TRANS2))
(3 3 (:REWRITE SUBSETP-TRANS))
(2 2 (:REWRITE SUBSETP-MEMBER . 2))
(2 2 (:REWRITE SUBSETP-MEMBER . 1))
(2 2
(:REWRITE MEMBER-EQUAL-WHEN-ALL-EQUALP))
(2 2
(:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-CONS-LISTP))
(2 2
(:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-ATOM-LISTP))
(2 1
(:REWRITE CONSP-UNDER-IFF-WHEN-TRUE-LISTP))
(1 1 (:REWRITE DEFAULT-CDR))
(1 1
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-USERTYPES-P
. 2))
(1 1
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-USERTYPES-P
. 1))
(1 1
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-GENCASELIST-P
. 2))
(1 1
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-GENCASELIST-P
. 1))
(1 1
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-COMMENTMAP-P
. 2))
(1 1
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-COMMENTMAP-P
. 1))
(1 1
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-CASELIST-P
. 2))
(1 1
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-CASELIST-P
. 1))
(1 1
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-ATTS-P
. 2))
(1 1
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-ATTS-P
. 1))
(1 1 (:REWRITE CONSP-BY-LEN)))
(VL2014::VL-PARSE-0+-RANGES-TRUE-LISTP
(116 58
(:TYPE-PRESCRIPTION VL2014::VL-IS-TOKEN?-FN-WHEN-ATOM-OF-TOKENS))
(18 1 (:REWRITE TRUE-LISTP-WHEN-ATOM))
(17 1
(:REWRITE TRUE-LISTP-WHEN-SYMBOL-LISTP-REWRITE))
(14 1
(:REWRITE TRUE-LISTP-WHEN-STRING-LISTP-REWRITE))
(12 1
(:REWRITE TRUE-LISTP-WHEN-CHARACTER-LISTP-REWRITE))
(6 1
(:REWRITE SET::SETS-ARE-TRUE-LISTS-CHEAP))
(4 2
(:REWRITE SYMBOL-LISTP-WHEN-SUBSETP-EQUAL))
(4 1
(:REWRITE VL2014::STRING-LISTP-WHEN-NO-NILS-IN-VL-MAYBE-STRING-LISTP))
(3 1
(:REWRITE VL2014::SYMBOL-LISTP-WHEN-SUBSETP-EQUAL-OF-SYMBOL-LISTP
. 1))
(2 2 (:TYPE-PRESCRIPTION SYMBOL-LISTP))
(2 2 (:TYPE-PRESCRIPTION SUBSETP-EQUAL))
(2 2 (:TYPE-PRESCRIPTION STRING-LISTP))
(2 2 (:TYPE-PRESCRIPTION SET::SETP-TYPE))
(2 2 (:TYPE-PRESCRIPTION CHARACTER-LISTP))
(2 2
(:REWRITE VL2014::TRUE-LISTP-WHEN-MEMBER-EQUAL-OF-TRUE-LIST-LISTP))
(2 2
(:REWRITE VL2014::SYMBOL-LISTP-WHEN-MEMBER-EQUAL-OF-SYMBOL-LIST-LISTP))
(2 2
(:REWRITE VL2014::SYMBOL-LISTP-OF-ALIST-VALS-OF-VL-FULL-KEYWORD-TABLE))
(2 2
(:REWRITE STRING-LISTP-WHEN-SUBSETP-EQUAL))
(2 2
(:REWRITE VL2014::STRING-LISTP-WHEN-MEMBER-EQUAL-OF-STRING-LIST-LISTP))
(2 2
(:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-CONS-LISTP))
(2 2
(:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-ATOM-LISTP))
(2 2
(:REWRITE CHARACTER-LISTP-WHEN-SUBSETP-EQUAL))
(2 1
(:TYPE-PRESCRIPTION TRUE-LISTP-MEMBER-EQUAL))
(2 1
(:REWRITE SYMBOL-LISTP-WHEN-BOOLEAN-LISTP))
(2 1 (:REWRITE SET::NONEMPTY-MEANS-SET))
(2 1
(:REWRITE CONSP-UNDER-IFF-WHEN-TRUE-LISTP))
(2 1
(:REWRITE STR::CHARACTER-LISTP-WHEN-OCTAL-DIGIT-LISTP))
(2 1
(:REWRITE STR::CHARACTER-LISTP-WHEN-HEX-DIGIT-LISTP))
(2 1
(:REWRITE STR::CHARACTER-LISTP-WHEN-DIGIT-LISTP))
(1 1
(:TYPE-PRESCRIPTION STR::OCTAL-DIGIT-LISTP))
(1 1
(:TYPE-PRESCRIPTION STR::HEX-DIGIT-LISTP))
(1 1 (:TYPE-PRESCRIPTION SET::EMPTY-TYPE))
(1 1 (:TYPE-PRESCRIPTION STR::DIGIT-LISTP))
(1 1
(:TYPE-PRESCRIPTION CONSP-MEMBER-EQUAL))
(1 1 (:TYPE-PRESCRIPTION BOOLEAN-LISTP))
(1 1
(:REWRITE TRUE-LISTP-WHEN-UNSIGNED-BYTE-LISTP))
(1 1
(:REWRITE TRUE-LISTP-WHEN-SIGNED-BYTE-LISTP))
(1 1
(:REWRITE VL2014::SYMBOL-LISTP-WHEN-SUBSETP-EQUAL-OF-SYMBOL-LISTP
. 2))
(1 1
(:REWRITE SYMBOL-LISTP-WHEN-NOT-CONSP))
(1 1
(:REWRITE VL2014::STRING-LISTP-WHEN-SUBSETP-EQUAL-OF-STRING-LISTP
. 2))
(1 1
(:REWRITE VL2014::STRING-LISTP-WHEN-SUBSETP-EQUAL-OF-STRING-LISTP
. 1))
(1 1
(:REWRITE STRING-LISTP-WHEN-NOT-CONSP))
(1 1 (:REWRITE SET::IN-SET))
(1 1 (:REWRITE FN-CHECK-DEF-FORMALS))
(1 1
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-USERTYPES-P
. 2))
(1 1
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-USERTYPES-P
. 1))
(1 1
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-GENCASELIST-P
. 2))
(1 1
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-GENCASELIST-P
. 1))
(1 1
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-COMMENTMAP-P
. 2))
(1 1
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-COMMENTMAP-P
. 1))
(1 1
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-CASELIST-P
. 2))
(1 1
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-CASELIST-P
. 1))
(1 1
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-ATTS-P
. 2))
(1 1
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-ATTS-P
. 1))
(1 1 (:REWRITE CONSP-BY-LEN))
(1 1
(:REWRITE CHARACTER-LISTP-WHEN-NOT-CONSP)))
(VL2014::VL-PARSE-0+-RANGES-COUNT-STRONG-ON-VALUE
(683 54 (:REWRITE LEN-WHEN-ATOM))
(218 109
(:TYPE-PRESCRIPTION VL2014::VL-IS-TOKEN?-FN-WHEN-ATOM-OF-TOKENS))
(152 16
(:REWRITE PREFIXP-WHEN-NOT-CONSP-RIGHT))
(152 16
(:REWRITE PREFIXP-WHEN-NOT-CONSP-LEFT))
(149 16
(:REWRITE PREFIXP-WHEN-EQUAL-LENGTHS))
(144 8 (:REWRITE SUBLISTP-WHEN-ATOM-RIGHT))
(144 8 (:REWRITE SUBLISTP-WHEN-ATOM-LEFT))
(138 138
(:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-CONS-LISTP))
(138 138
(:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-ATOM-LISTP))
(138 69
(:REWRITE CONSP-UNDER-IFF-WHEN-TRUE-LISTP))
(104 8 (:REWRITE LEN-WHEN-PREFIXP))
(69 69 (:TYPE-PRESCRIPTION TRUE-LISTP))
(69 69
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-USERTYPES-P
. 2))
(69 69
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-USERTYPES-P
. 1))
(69 69
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-GENCASELIST-P
. 2))
(69 69
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-GENCASELIST-P
. 1))
(69 69
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-COMMENTMAP-P
. 2))
(69 69
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-COMMENTMAP-P
. 1))
(69 69
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-CASELIST-P
. 2))
(69 69
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-CASELIST-P
. 1))
(69 69
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-ATTS-P
. 2))
(69 69
(:REWRITE VL2014::CONSP-WHEN-MEMBER-EQUAL-OF-VL-ATTS-P
. 1))
(69 69 (:REWRITE CONSP-BY-LEN))
(34 34
(:REWRITE VL2014::PREFIXP-WHEN-MEMBER-EQUAL-OF-PREFIX-OF-EACHP))
(17 17
(:REWRITE VL2014::TRANSITIVITY-OF-PREFIXP))
(16 16 (:REWRITE PREFIXP-TRANSITIVE . 2))
(16 16 (:REWRITE PREFIXP-TRANSITIVE . 1))
(16 16
(:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 2))
(16 16
(:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 1))
(16 8 (:REWRITE SET::DOUBLE-CONTAINMENT))
(16 8 (:REWRITE DEFAULT-<-2))
(16 8 (:REWRITE DEFAULT-<-1))
(12 12
(:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP))
(12 12
(:LINEAR LISTPOS-UPPER-BOUND-STRONG-2))
(12 12 (:LINEAR LEN-WHEN-PREFIXP))
(9 9 (:REWRITE SUBLISTP-COMPLETE))
(9 9 (:META CANCEL_PLUS-LESSP-CORRECT))
(8 8 (:META CANCEL_TIMES-EQUAL-CORRECT))
(8 8 (:META CANCEL_PLUS-EQUAL-CORRECT))
(6 6 (:LINEAR LEQ-POSITION-EQUAL-LEN))
(6 6 (:LINEAR INDEX-OF-<-LEN))
(6 6
(:LINEAR STR::COUNT-LEADING-CHARSET-LEN)))
| {
"pile_set_name": "Github"
} |
---
title: Reactive and nonreactive SharePoint web parts
description: Reactive web parts are client-side only; nonreactive web parts have elements that require a server to operate.
ms.date: 01/23/2018
localization_priority: Priority
---
# Reactive and nonreactive SharePoint web parts
Reactive web parts are client-side only; nonreactive web parts have elements that require a server to operate. We recommend that you build your SharePoint web parts to be reactive because that best fits the UX model and WYSIWYG principles for authoring. However, it might not be possible or cost-effective in all cases to build reactive web parts.
## Reactive web parts
Reactive web parts are fully client-side web parts. This means that each component configured in the property pane reflects the change made within the web part on the page. For example, for the To-Do List web part, unchecking “Completed Tasks” hides this view in the web part.
<img alt="A reactive web part" src="../images/design-reactive-01.png" width="850">
## Nonreactive web parts
Nonreactive web parts are not fully client-side; generally, one or more properties need to make a call to set/pull or store data on a server. For nonreactive web parts, you should enable the **Apply** button at the bottom of the property pane.
You can also customize the **Apply** button to be a more specific action. <!-- Is this a reference to an image? (design-wp-pp-non-reactive.png) -->
<img alt="A nonreactive web part with Apply and Cancel buttons" src="../images/design-reactive-02.png" width="850">
<br/>
The following examples show nonreactive web parts in the context of the [three property pane structures](design-a-web-part.md).
**Single pane example**
<img alt="A nonreactive web part with a single pane property structure" src="../images/design-reactive-03.png" width="850">
<br/>
**Accordion groups example**
<img alt="A nonreactive web part with an according groups pane property structure" src="../images/design-reactive-04.png" width="850">
<br/>
**Steps pane example**
<img alt="A nonreactive web part with a steps pane property structure" src="../images/design-reactive-05.png" width="850">
## See also
- [Designing great SharePoint experiences](design-guidance-overview.md)
| {
"pile_set_name": "Github"
} |
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Solutions component.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
** of its contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qtsingleapplication.h"
#include "qtlocalpeer.h"
#include <QWidget>
/*!
\class QtSingleApplication qtsingleapplication.h
\brief The QtSingleApplication class provides an API to detect and
communicate with running instances of an application.
This class allows you to create applications where only one
instance should be running at a time. I.e., if the user tries to
launch another instance, the already running instance will be
activated instead. Another usecase is a client-server system,
where the first started instance will assume the role of server,
and the later instances will act as clients of that server.
By default, the full path of the executable file is used to
determine whether two processes are instances of the same
application. You can also provide an explicit identifier string
that will be compared instead.
The application should create the QtSingleApplication object early
in the startup phase, and call isRunning() to find out if another
instance of this application is already running. If isRunning()
returns false, it means that no other instance is running, and
this instance has assumed the role as the running instance. In
this case, the application should continue with the initialization
of the application user interface before entering the event loop
with exec(), as normal.
The messageReceived() signal will be emitted when the running
application receives messages from another instance of the same
application. When a message is received it might be helpful to the
user to raise the application so that it becomes visible. To
facilitate this, QtSingleApplication provides the
setActivationWindow() function and the activateWindow() slot.
If isRunning() returns true, another instance is already
running. It may be alerted to the fact that another instance has
started by using the sendMessage() function. Also data such as
startup parameters (e.g. the name of the file the user wanted this
new instance to open) can be passed to the running instance with
this function. Then, the application should terminate (or enter
client mode).
If isRunning() returns true, but sendMessage() fails, that is an
indication that the running instance is frozen.
Here's an example that shows how to convert an existing
application to use QtSingleApplication. It is very simple and does
not make use of all QtSingleApplication's functionality (see the
examples for that).
\code
// Original
int main(int argc, char **argv)
{
QApplication app(argc, argv);
MyMainWidget mmw;
mmw.show();
return app.exec();
}
// Single instance
int main(int argc, char **argv)
{
QtSingleApplication app(argc, argv);
if (app.isRunning())
return !app.sendMessage(someDataString);
MyMainWidget mmw;
app.setActivationWindow(&mmw);
mmw.show();
return app.exec();
}
\endcode
Once this QtSingleApplication instance is destroyed (normally when
the process exits or crashes), when the user next attempts to run the
application this instance will not, of course, be encountered. The
next instance to call isRunning() or sendMessage() will assume the
role as the new running instance.
For console (non-GUI) applications, QtSingleCoreApplication may be
used instead of this class, to avoid the dependency on the QtGui
library.
\sa QtSingleCoreApplication
*/
void QtSingleApplication::sysInit(const QString &appId)
{
actWin = 0;
peer = new QtLocalPeer(this, appId);
connect(peer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::messageReceived);
}
/*!
Creates a QtSingleApplication object. The application identifier
will be QCoreApplication::applicationFilePath(). \a argc, \a
argv, and \a GUIenabled are passed on to the QAppliation constructor.
If you are creating a console application (i.e. setting \a
GUIenabled to false), you may consider using
QtSingleCoreApplication instead.
*/
QtSingleApplication::QtSingleApplication(int &argc, char **argv, bool GUIenabled)
: QApplication(argc, argv, GUIenabled)
{
sysInit();
}
/*!
Creates a QtSingleApplication object with the application
identifier \a appId. \a argc and \a argv are passed on to the
QAppliation constructor.
*/
QtSingleApplication::QtSingleApplication(const QString &appId, int &argc, char **argv)
: QApplication(argc, argv)
{
sysInit(appId);
}
#if QT_VERSION < 0x050000
/*!
Creates a QtSingleApplication object. The application identifier
will be QCoreApplication::applicationFilePath(). \a argc, \a
argv, and \a type are passed on to the QAppliation constructor.
*/
QtSingleApplication::QtSingleApplication(int &argc, char **argv, Type type)
: QApplication(argc, argv, type)
{
sysInit();
}
# if defined(Q_WS_X11)
/*!
Special constructor for X11, ref. the documentation of
QApplication's corresponding constructor. The application identifier
will be QCoreApplication::applicationFilePath(). \a dpy, \a visual,
and \a cmap are passed on to the QApplication constructor.
*/
QtSingleApplication::QtSingleApplication(Display* dpy, Qt::HANDLE visual, Qt::HANDLE cmap)
: QApplication(dpy, visual, cmap)
{
sysInit();
}
/*!
Special constructor for X11, ref. the documentation of
QApplication's corresponding constructor. The application identifier
will be QCoreApplication::applicationFilePath(). \a dpy, \a argc, \a
argv, \a visual, and \a cmap are passed on to the QApplication
constructor.
*/
QtSingleApplication::QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap)
: QApplication(dpy, argc, argv, visual, cmap)
{
sysInit();
}
/*!
Special constructor for X11, ref. the documentation of
QApplication's corresponding constructor. The application identifier
will be \a appId. \a dpy, \a argc, \a
argv, \a visual, and \a cmap are passed on to the QApplication
constructor.
*/
QtSingleApplication::QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap)
: QApplication(dpy, argc, argv, visual, cmap)
{
sysInit(appId);
}
# endif // Q_WS_X11
#endif // QT_VERSION < 0x050000
/*!
Returns true if another instance of this application is running;
otherwise false.
This function does not find instances of this application that are
being run by a different user (on Windows: that are running in
another session).
\sa sendMessage()
*/
bool QtSingleApplication::isRunning()
{
return peer->isClient();
}
/*!
Tries to send the text \a message to the currently running
instance. The QtSingleApplication object in the running instance
will emit the messageReceived() signal when it receives the
message.
This function returns true if the message has been sent to, and
processed by, the current instance. If there is no instance
currently running, or if the running instance fails to process the
message within \a timeout milliseconds, this function return false.
\sa isRunning(), messageReceived()
*/
bool QtSingleApplication::sendMessage(const QString &message, int timeout)
{
return peer->sendMessage(message, timeout);
}
/*!
Returns the application identifier. Two processes with the same
identifier will be regarded as instances of the same application.
*/
QString QtSingleApplication::id() const
{
return peer->applicationId();
}
/*!
Sets the activation window of this application to \a aw. The
activation window is the widget that will be activated by
activateWindow(). This is typically the application's main window.
If \a activateOnMessage is true (the default), the window will be
activated automatically every time a message is received, just prior
to the messageReceived() signal being emitted.
\sa activateWindow(), messageReceived()
*/
void QtSingleApplication::setActivationWindow(QWidget* aw, bool activateOnMessage)
{
actWin = aw;
if (activateOnMessage)
connect(peer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::activateWindow);
else
disconnect(peer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::activateWindow);
}
/*!
Returns the applications activation window if one has been set by
calling setActivationWindow(), otherwise returns 0.
\sa setActivationWindow()
*/
QWidget* QtSingleApplication::activationWindow() const
{
return actWin;
}
/*!
De-minimizes, raises, and activates this application's activation window.
This function does nothing if no activation window has been set.
This is a convenience function to show the user that this
application instance has been activated when he has tried to start
another instance.
This function should typically be called in response to the
messageReceived() signal. By default, that will happen
automatically, if an activation window has been set.
\sa setActivationWindow(), messageReceived(), initialize()
*/
void QtSingleApplication::activateWindow()
{
if (actWin) {
actWin->setWindowState(actWin->windowState() & ~Qt::WindowMinimized);
actWin->raise();
actWin->activateWindow();
}
}
/*!
\fn void QtSingleApplication::messageReceived(const QString& message)
This signal is emitted when the current instance receives a \a
message from another instance of this application.
\sa sendMessage(), setActivationWindow(), activateWindow()
*/
/*!
\fn void QtSingleApplication::initialize(bool dummy = true)
\obsolete
*/
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>HelloWorld.xcscheme</key>
<dict>
<key>orderHint</key>
<integer>0</integer>
</dict>
</dict>
<key>SuppressBuildableAutocreation</key>
<dict>
<key>HelloWorld.app</key>
<true/>
</dict>
</dict>
</plist>
| {
"pile_set_name": "Github"
} |
using System;
using System.Runtime.Serialization;
public partial class MAVLink
{
public class MAVLinkParam
{
/// <summary>
/// Paramater name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Value of paramter as a double
/// </summary>
public double Value
{
get
{
return GetValue();
}
set
{
SetValue(value);
}
}
/// <summary>
/// Over the wire storage format
/// </summary>
public MAV_PARAM_TYPE Type { get; set; }
private MAV_PARAM_TYPE _typeap = 0;
public MAV_PARAM_TYPE TypeAP {
get
{
if (_typeap != 0)
return _typeap;
return Type;
}
set
{
_typeap = value;
}
}
byte uint8_value { get { return data[0]; } }
sbyte int8_value { get { return (sbyte)data[0]; } }
ushort uint16_value { get { return BitConverter.ToUInt16(data, 0); } }
short int16_value { get { return BitConverter.ToInt16(data, 0); } }
UInt32 uint32_value { get { return BitConverter.ToUInt32(data, 0); } }
Int32 int32_value { get { return BitConverter.ToInt32(data, 0); } }
[IgnoreDataMember]
public float float_value { get { return BitConverter.ToSingle(data, 0); } }
byte[] _data = new byte[4];
[IgnoreDataMember]
public byte[] data
{
get { return _data; }
set
{
_data = value;
Array.Resize(ref _data, 4);
}
}
/// <summary>
/// used as a generic input to type the input data
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <param name="wiretype"></param>
public MAVLinkParam(string name, double value, MAV_PARAM_TYPE wiretype)
{
Name = name;
Type = wiretype;
Value = value;
}
/// <summary>
/// Used to set Ardupilot Params
/// </summary>
/// <param name="name"></param>
/// <param name="inputwire"></param>
/// <param name="wiretype"></param>
/// <param name="typeap"></param>
public MAVLinkParam(string name, byte[] inputwire, MAV_PARAM_TYPE wiretype, MAV_PARAM_TYPE typeap)
{
Name = name;
Type = wiretype;
TypeAP = typeap;
Array.Copy(inputwire, _data, 4);
}
public double GetValue()
{
switch (Type)
{
case MAV_PARAM_TYPE.UINT8:
return (double)uint8_value;
case MAV_PARAM_TYPE.INT8:
return (double)int8_value;
case MAV_PARAM_TYPE.UINT16:
return (double)uint16_value;
case MAV_PARAM_TYPE.INT16:
return (double)int16_value;
case MAV_PARAM_TYPE.UINT32:
return (double)uint32_value;
case MAV_PARAM_TYPE.INT32:
return (double)int32_value;
case MAV_PARAM_TYPE.REAL32:
return (double)float_value;
}
throw new FormatException("invalid type");
}
public void SetValue(double input)
{
switch (Type)
{
case MAV_PARAM_TYPE.UINT8:
data = BitConverter.GetBytes((byte)input);
Array.Resize(ref _data, 4);
break;
case MAV_PARAM_TYPE.INT8:
data = BitConverter.GetBytes((sbyte)input);
Array.Resize(ref _data, 4);
break;
case MAV_PARAM_TYPE.UINT16:
data = BitConverter.GetBytes((ushort)input);
Array.Resize(ref _data, 4);
break;
case MAV_PARAM_TYPE.INT16:
data = BitConverter.GetBytes((short)input);
Array.Resize(ref _data, 4);
break;
case MAV_PARAM_TYPE.UINT32:
data = BitConverter.GetBytes((UInt32)input);
break;
case MAV_PARAM_TYPE.INT32:
data = BitConverter.GetBytes((Int32)input);
break;
case MAV_PARAM_TYPE.REAL32:
data = BitConverter.GetBytes((float)input);
break;
}
}
public static explicit operator byte(MAVLinkParam v)
{
return (byte)v.Value;
}
public static explicit operator sbyte(MAVLinkParam v)
{
return (sbyte)v.Value;
}
public static explicit operator short(MAVLinkParam v)
{
return (short)v.Value;
}
public static explicit operator ushort(MAVLinkParam v)
{
return (ushort)v.Value;
}
public static explicit operator int(MAVLinkParam v)
{
return (int)v.Value;
}
public static explicit operator uint(MAVLinkParam v)
{
return (uint)v.Value;
}
public static explicit operator float (MAVLinkParam v)
{
return (float)v.Value;
}
public static explicit operator double(MAVLinkParam v)
{
return (double)v.Value;
}
public override string ToString()
{
if (Type == MAV_PARAM_TYPE.REAL32)
return ((float)this).ToString();
return Value.ToString();
}
}
}
| {
"pile_set_name": "Github"
} |
namespace WGestures.App.Gui.Windows
{
partial class ErrorForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ErrorForm));
this.lb_Message = new System.Windows.Forms.Label();
this.tb_Detail = new System.Windows.Forms.TextBox();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.btn_close = new System.Windows.Forms.Button();
this.flowLayoutPanel2 = new System.Windows.Forms.FlowLayoutPanel();
this.flowLayoutPanel4 = new System.Windows.Forms.FlowLayoutPanel();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.flowLayoutPanel3 = new System.Windows.Forms.FlowLayoutPanel();
this.label1 = new System.Windows.Forms.Label();
this.tb_mail = new System.Windows.Forms.TextBox();
this.flowLayoutPanel1.SuspendLayout();
this.flowLayoutPanel2.SuspendLayout();
this.flowLayoutPanel4.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.flowLayoutPanel3.SuspendLayout();
this.SuspendLayout();
//
// lb_Message
//
this.lb_Message.Font = new System.Drawing.Font("Microsoft YaHei", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.lb_Message.ForeColor = System.Drawing.Color.Red;
this.lb_Message.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.lb_Message.Location = new System.Drawing.Point(79, 0);
this.lb_Message.Margin = new System.Windows.Forms.Padding(8, 0, 1, 0);
this.lb_Message.Name = "lb_Message";
this.lb_Message.Size = new System.Drawing.Size(276, 55);
this.lb_Message.TabIndex = 0;
this.lb_Message.Text = "抱歉!WGesture遇到了一个意想不到的问题,因而无法继续运行。";
this.lb_Message.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// tb_Detail
//
this.tb_Detail.BackColor = System.Drawing.Color.White;
this.tb_Detail.HideSelection = false;
this.tb_Detail.Location = new System.Drawing.Point(4, 122);
this.tb_Detail.Margin = new System.Windows.Forms.Padding(1);
this.tb_Detail.Multiline = true;
this.tb_Detail.Name = "tb_Detail";
this.tb_Detail.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.tb_Detail.Size = new System.Drawing.Size(381, 174);
this.tb_Detail.TabIndex = 1;
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.flowLayoutPanel1.BackColor = System.Drawing.SystemColors.ButtonFace;
this.flowLayoutPanel1.Controls.Add(this.btn_close);
this.flowLayoutPanel1.FlowDirection = System.Windows.Forms.FlowDirection.RightToLeft;
this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 305);
this.flowLayoutPanel1.Margin = new System.Windows.Forms.Padding(0, 12, 0, 0);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Padding = new System.Windows.Forms.Padding(8);
this.flowLayoutPanel1.Size = new System.Drawing.Size(391, 50);
this.flowLayoutPanel1.TabIndex = 2;
//
// btn_close
//
this.btn_close.Location = new System.Drawing.Point(285, 9);
this.btn_close.Margin = new System.Windows.Forms.Padding(1);
this.btn_close.Name = "btn_close";
this.btn_close.Size = new System.Drawing.Size(89, 30);
this.btn_close.TabIndex = 0;
this.btn_close.Text = "退出";
this.btn_close.UseVisualStyleBackColor = true;
this.btn_close.Click += new System.EventHandler(this.btn_close_Click);
//
// flowLayoutPanel2
//
this.flowLayoutPanel2.AutoSize = true;
this.flowLayoutPanel2.BackColor = System.Drawing.Color.White;
this.flowLayoutPanel2.Controls.Add(this.flowLayoutPanel4);
this.flowLayoutPanel2.Controls.Add(this.flowLayoutPanel3);
this.flowLayoutPanel2.Controls.Add(this.tb_Detail);
this.flowLayoutPanel2.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.flowLayoutPanel2.Location = new System.Drawing.Point(0, 0);
this.flowLayoutPanel2.Margin = new System.Windows.Forms.Padding(2);
this.flowLayoutPanel2.Name = "flowLayoutPanel2";
this.flowLayoutPanel2.Padding = new System.Windows.Forms.Padding(3);
this.flowLayoutPanel2.Size = new System.Drawing.Size(391, 300);
this.flowLayoutPanel2.TabIndex = 3;
//
// flowLayoutPanel4
//
this.flowLayoutPanel4.Controls.Add(this.pictureBox1);
this.flowLayoutPanel4.Controls.Add(this.lb_Message);
this.flowLayoutPanel4.Location = new System.Drawing.Point(5, 5);
this.flowLayoutPanel4.Margin = new System.Windows.Forms.Padding(2);
this.flowLayoutPanel4.Name = "flowLayoutPanel4";
this.flowLayoutPanel4.Size = new System.Drawing.Size(379, 73);
this.flowLayoutPanel4.TabIndex = 4;
//
// pictureBox1
//
this.pictureBox1.Image = global::WGestures.App.Properties.Resources.logo_error;
this.pictureBox1.Location = new System.Drawing.Point(2, 2);
this.pictureBox1.Margin = new System.Windows.Forms.Padding(2);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(67, 65);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.pictureBox1.TabIndex = 3;
this.pictureBox1.TabStop = false;
//
// flowLayoutPanel3
//
this.flowLayoutPanel3.Controls.Add(this.label1);
this.flowLayoutPanel3.Controls.Add(this.tb_mail);
this.flowLayoutPanel3.Location = new System.Drawing.Point(5, 87);
this.flowLayoutPanel3.Margin = new System.Windows.Forms.Padding(2, 7, 2, 2);
this.flowLayoutPanel3.Name = "flowLayoutPanel3";
this.flowLayoutPanel3.Size = new System.Drawing.Size(379, 32);
this.flowLayoutPanel3.TabIndex = 2;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft YaHei", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.label1.ForeColor = System.Drawing.SystemColors.WindowFrame;
this.label1.Location = new System.Drawing.Point(1, 0);
this.label1.Margin = new System.Windows.Forms.Padding(1, 0, 1, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(180, 20);
this.label1.TabIndex = 0;
this.label1.Text = "请附上以下信息联系开发者:";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// tb_mail
//
this.tb_mail.BackColor = System.Drawing.SystemColors.ButtonHighlight;
this.tb_mail.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tb_mail.Font = new System.Drawing.Font("Microsoft YaHei", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.tb_mail.ForeColor = System.Drawing.Color.DodgerBlue;
this.tb_mail.HideSelection = false;
this.tb_mail.Location = new System.Drawing.Point(184, 2);
this.tb_mail.Margin = new System.Windows.Forms.Padding(2);
this.tb_mail.Name = "tb_mail";
this.tb_mail.ReadOnly = true;
this.tb_mail.Size = new System.Drawing.Size(193, 25);
this.tb_mail.TabIndex = 1;
this.tb_mail.Text = "[email protected]";
this.tb_mail.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// ErrorForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.AutoSize = true;
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(391, 353);
this.Controls.Add(this.flowLayoutPanel2);
this.Controls.Add(this.flowLayoutPanel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Margin = new System.Windows.Forms.Padding(1);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ErrorForm";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "WGestures错误";
this.TopMost = true;
this.flowLayoutPanel1.ResumeLayout(false);
this.flowLayoutPanel2.ResumeLayout(false);
this.flowLayoutPanel2.PerformLayout();
this.flowLayoutPanel4.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.flowLayoutPanel3.ResumeLayout(false);
this.flowLayoutPanel3.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lb_Message;
private System.Windows.Forms.TextBox tb_Detail;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private System.Windows.Forms.Button btn_close;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel2;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel3;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel4;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.TextBox tb_mail;
}
} | {
"pile_set_name": "Github"
} |
.class public final Lcom/google/android/gms/dynamic/zzm;
.super Lcom/google/android/gms/internal/zzed;
# interfaces
.implements Lcom/google/android/gms/dynamic/IObjectWrapper;
# direct methods
.method constructor <init>(Landroid/os/IBinder;)V
.locals 1
const-string/jumbo v0, "com.google.android.gms.dynamic.IObjectWrapper"
invoke-direct {p0, p1, v0}, Lcom/google/android/gms/internal/zzed;-><init>(Landroid/os/IBinder;Ljava/lang/String;)V
return-void
.end method
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/base/android/media_drm_bridge.h"
#include <stddef.h>
#include <algorithm>
#include <utility>
#include "base/android/build_info.h"
#include "base/android/jni_array.h"
#include "base/android/jni_string.h"
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/containers/hash_tables.h"
#include "base/lazy_instance.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/sys_byteorder.h"
#include "base/sys_info.h"
#include "base/threading/thread_task_runner_handle.h"
#include "jni/MediaDrmBridge_jni.h"
#include "media/base/android/media_client_android.h"
#include "media/base/android/media_codec_util.h"
#include "media/base/android/media_drm_bridge_delegate.h"
#include "media/base/android/provision_fetcher.h"
#include "media/base/cdm_key_information.h"
#include "widevine_cdm_version.h" // In SHARED_INTERMEDIATE_DIR.
using base::android::AttachCurrentThread;
using base::android::ConvertUTF8ToJavaString;
using base::android::ConvertJavaStringToUTF8;
using base::android::JavaByteArrayToByteVector;
using base::android::ScopedJavaGlobalRef;
using base::android::ScopedJavaLocalRef;
namespace media {
namespace {
// These must be in sync with Android MediaDrm REQUEST_TYPE_XXX constants!
// https://developer.android.com/reference/android/media/MediaDrm.KeyRequest.html
enum class RequestType {
REQUEST_TYPE_INITIAL = 0,
REQUEST_TYPE_RENEWAL = 1,
REQUEST_TYPE_RELEASE = 2,
};
// These must be in sync with Android MediaDrm KEY_STATUS_XXX constants:
// https://developer.android.com/reference/android/media/MediaDrm.KeyStatus.html
enum class KeyStatus {
KEY_STATUS_USABLE = 0,
KEY_STATUS_EXPIRED = 1,
KEY_STATUS_OUTPUT_NOT_ALLOWED = 2,
KEY_STATUS_PENDING = 3,
KEY_STATUS_INTERNAL_ERROR = 4,
};
// Converts jbyteArray (byte[] in Java) into std::string.
std::string AsString(JNIEnv* env, jbyteArray j_byte_array) {
std::vector<uint8_t> byte_vector;
JavaByteArrayToByteVector(env, j_byte_array, &byte_vector);
return std::string(byte_vector.begin(), byte_vector.end());
}
const uint8_t kWidevineUuid[16] = {
0xED, 0xEF, 0x8B, 0xA9, 0x79, 0xD6, 0x4A, 0xCE, //
0xA3, 0xC8, 0x27, 0xDC, 0xD5, 0x1D, 0x21, 0xED};
// Convert |init_data_type| to a string supported by MediaDRM.
// "audio"/"video" does not matter, so use "video".
std::string ConvertInitDataType(media::EmeInitDataType init_data_type) {
// TODO(jrummell/xhwang): EME init data types like "webm" and "cenc" are
// supported in API level >=21 for Widevine key system. Switch to use those
// strings when they are officially supported in Android for all key systems.
switch (init_data_type) {
case media::EmeInitDataType::WEBM:
return "video/webm";
case media::EmeInitDataType::CENC:
return "video/mp4";
case media::EmeInitDataType::KEYIDS:
return "keyids";
default:
NOTREACHED();
return "unknown";
}
}
MediaKeys::MessageType GetMessageType(RequestType request_type) {
switch (request_type) {
case RequestType::REQUEST_TYPE_INITIAL:
return MediaKeys::LICENSE_REQUEST;
case RequestType::REQUEST_TYPE_RENEWAL:
return MediaKeys::LICENSE_RENEWAL;
case RequestType::REQUEST_TYPE_RELEASE:
return MediaKeys::LICENSE_RELEASE;
}
NOTREACHED();
return MediaKeys::LICENSE_REQUEST;
}
CdmKeyInformation::KeyStatus ConvertKeyStatus(KeyStatus key_status) {
switch (key_status) {
case KeyStatus::KEY_STATUS_USABLE:
return CdmKeyInformation::USABLE;
case KeyStatus::KEY_STATUS_EXPIRED:
return CdmKeyInformation::EXPIRED;
case KeyStatus::KEY_STATUS_OUTPUT_NOT_ALLOWED:
return CdmKeyInformation::OUTPUT_RESTRICTED;
case KeyStatus::KEY_STATUS_PENDING:
// TODO(xhwang): This should probably be renamed to "PENDING".
return CdmKeyInformation::KEY_STATUS_PENDING;
case KeyStatus::KEY_STATUS_INTERNAL_ERROR:
return CdmKeyInformation::INTERNAL_ERROR;
}
NOTREACHED();
return CdmKeyInformation::INTERNAL_ERROR;
}
class KeySystemManager {
public:
KeySystemManager();
UUID GetUUID(const std::string& key_system);
std::vector<std::string> GetPlatformKeySystemNames();
private:
using KeySystemUuidMap = MediaClientAndroid::KeySystemUuidMap;
KeySystemUuidMap key_system_uuid_map_;
DISALLOW_COPY_AND_ASSIGN(KeySystemManager);
};
KeySystemManager::KeySystemManager() {
// Widevine is always supported in Android.
key_system_uuid_map_[kWidevineKeySystem] =
UUID(kWidevineUuid, kWidevineUuid + arraysize(kWidevineUuid));
MediaClientAndroid* client = GetMediaClientAndroid();
if (client)
client->AddKeySystemUUIDMappings(&key_system_uuid_map_);
}
UUID KeySystemManager::GetUUID(const std::string& key_system) {
KeySystemUuidMap::iterator it = key_system_uuid_map_.find(key_system);
if (it == key_system_uuid_map_.end())
return UUID();
return it->second;
}
std::vector<std::string> KeySystemManager::GetPlatformKeySystemNames() {
std::vector<std::string> key_systems;
for (KeySystemUuidMap::iterator it = key_system_uuid_map_.begin();
it != key_system_uuid_map_.end(); ++it) {
// Rule out the key system handled by Chrome explicitly.
if (it->first != kWidevineKeySystem)
key_systems.push_back(it->first);
}
return key_systems;
}
base::LazyInstance<KeySystemManager>::Leaky g_key_system_manager =
LAZY_INSTANCE_INITIALIZER;
// Checks whether |key_system| is supported with |container_mime_type|. Only
// checks |key_system| support if |container_mime_type| is empty.
// TODO(xhwang): The |container_mime_type| is not the same as contentType in
// the EME spec. Revisit this once the spec issue with initData type is
// resolved.
bool IsKeySystemSupportedWithTypeImpl(const std::string& key_system,
const std::string& container_mime_type) {
DCHECK(MediaDrmBridge::IsAvailable());
if (key_system.empty()) {
NOTREACHED();
return false;
}
UUID scheme_uuid = g_key_system_manager.Get().GetUUID(key_system);
if (scheme_uuid.empty())
return false;
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jbyteArray> j_scheme_uuid =
base::android::ToJavaByteArray(env, &scheme_uuid[0], scheme_uuid.size());
ScopedJavaLocalRef<jstring> j_container_mime_type =
ConvertUTF8ToJavaString(env, container_mime_type);
return Java_MediaDrmBridge_isCryptoSchemeSupported(
env, j_scheme_uuid.obj(), j_container_mime_type.obj());
}
MediaDrmBridge::SecurityLevel GetSecurityLevelFromString(
const std::string& security_level_str) {
if (0 == security_level_str.compare("L1"))
return MediaDrmBridge::SECURITY_LEVEL_1;
if (0 == security_level_str.compare("L3"))
return MediaDrmBridge::SECURITY_LEVEL_3;
DCHECK(security_level_str.empty());
return MediaDrmBridge::SECURITY_LEVEL_DEFAULT;
}
// Do not change the return values as they are part of Android MediaDrm API for
// Widevine.
std::string GetSecurityLevelString(
MediaDrmBridge::SecurityLevel security_level) {
switch (security_level) {
case MediaDrmBridge::SECURITY_LEVEL_DEFAULT:
return "";
case MediaDrmBridge::SECURITY_LEVEL_1:
return "L1";
case MediaDrmBridge::SECURITY_LEVEL_3:
return "L3";
}
return "";
}
bool AreMediaDrmApisAvailable() {
if (base::android::BuildInfo::GetInstance()->sdk_int() < 19)
return false;
int32_t os_major_version = 0;
int32_t os_minor_version = 0;
int32_t os_bugfix_version = 0;
base::SysInfo::OperatingSystemVersionNumbers(
&os_major_version, &os_minor_version, &os_bugfix_version);
if (os_major_version == 4 && os_minor_version == 4 && os_bugfix_version == 0)
return false;
return true;
}
} // namespace
// MediaDrm is not generally usable without MediaCodec. Thus, both the MediaDrm
// APIs and MediaCodec APIs must be enabled and not blacklisted.
// static
bool MediaDrmBridge::IsAvailable() {
return AreMediaDrmApisAvailable() && MediaCodecUtil::IsMediaCodecAvailable();
}
// static
bool MediaDrmBridge::RegisterMediaDrmBridge(JNIEnv* env) {
return RegisterNativesImpl(env);
}
// static
bool MediaDrmBridge::IsKeySystemSupported(const std::string& key_system) {
if (!MediaDrmBridge::IsAvailable())
return false;
return IsKeySystemSupportedWithTypeImpl(key_system, "");
}
// static
bool MediaDrmBridge::IsKeySystemSupportedWithType(
const std::string& key_system,
const std::string& container_mime_type) {
DCHECK(!container_mime_type.empty()) << "Call IsKeySystemSupported instead";
if (!MediaDrmBridge::IsAvailable())
return false;
return IsKeySystemSupportedWithTypeImpl(key_system, container_mime_type);
}
// static
std::vector<std::string> MediaDrmBridge::GetPlatformKeySystemNames() {
if (!MediaDrmBridge::IsAvailable())
return std::vector<std::string>();
return g_key_system_manager.Get().GetPlatformKeySystemNames();
}
// static
scoped_refptr<MediaDrmBridge> MediaDrmBridge::CreateInternal(
const std::string& key_system,
SecurityLevel security_level,
const CreateFetcherCB& create_fetcher_cb,
const SessionMessageCB& session_message_cb,
const SessionClosedCB& session_closed_cb,
const LegacySessionErrorCB& legacy_session_error_cb,
const SessionKeysChangeCB& session_keys_change_cb,
const SessionExpirationUpdateCB& session_expiration_update_cb) {
// All paths requires the MediaDrmApis.
DCHECK(AreMediaDrmApisAvailable());
UUID scheme_uuid = g_key_system_manager.Get().GetUUID(key_system);
if (scheme_uuid.empty())
return nullptr;
scoped_refptr<MediaDrmBridge> media_drm_bridge(new MediaDrmBridge(
scheme_uuid, security_level, create_fetcher_cb, session_message_cb,
session_closed_cb, legacy_session_error_cb, session_keys_change_cb,
session_expiration_update_cb));
if (media_drm_bridge->j_media_drm_.is_null())
media_drm_bridge = nullptr;
return media_drm_bridge;
}
// static
scoped_refptr<MediaDrmBridge> MediaDrmBridge::Create(
const std::string& key_system,
SecurityLevel security_level,
const CreateFetcherCB& create_fetcher_cb,
const SessionMessageCB& session_message_cb,
const SessionClosedCB& session_closed_cb,
const LegacySessionErrorCB& legacy_session_error_cb,
const SessionKeysChangeCB& session_keys_change_cb,
const SessionExpirationUpdateCB& session_expiration_update_cb) {
DVLOG(1) << __FUNCTION__;
if (!IsAvailable())
return nullptr;
return CreateInternal(key_system, security_level, create_fetcher_cb,
session_message_cb, session_closed_cb,
legacy_session_error_cb, session_keys_change_cb,
session_expiration_update_cb);
}
// static
scoped_refptr<MediaDrmBridge> MediaDrmBridge::CreateWithoutSessionSupport(
const std::string& key_system,
SecurityLevel security_level,
const CreateFetcherCB& create_fetcher_cb) {
DVLOG(1) << __FUNCTION__;
// Sessions won't be used so decoding capability is not required.
if (!AreMediaDrmApisAvailable())
return nullptr;
return MediaDrmBridge::Create(key_system, security_level, create_fetcher_cb,
SessionMessageCB(), SessionClosedCB(),
LegacySessionErrorCB(), SessionKeysChangeCB(),
SessionExpirationUpdateCB());
}
void MediaDrmBridge::SetServerCertificate(
const std::vector<uint8_t>& certificate,
std::unique_ptr<media::SimpleCdmPromise> promise) {
DCHECK(task_runner_->BelongsToCurrentThread());
DVLOG(2) << __FUNCTION__ << "(" << certificate.size() << " bytes)";
DCHECK(!certificate.empty());
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jbyteArray> j_certificate = base::android::ToJavaByteArray(
env, certificate.data(), certificate.size());
if (Java_MediaDrmBridge_setServerCertificate(env, j_media_drm_.obj(),
j_certificate.obj())) {
promise->resolve();
} else {
promise->reject(INVALID_ACCESS_ERROR, 0, "Set server certificate failed.");
}
}
void MediaDrmBridge::CreateSessionAndGenerateRequest(
SessionType session_type,
media::EmeInitDataType init_data_type,
const std::vector<uint8_t>& init_data,
std::unique_ptr<media::NewSessionCdmPromise> promise) {
DCHECK(task_runner_->BelongsToCurrentThread());
DVLOG(2) << __FUNCTION__;
if (session_type != media::MediaKeys::TEMPORARY_SESSION) {
NOTIMPLEMENTED() << "EME persistent sessions not yet supported on Android.";
promise->reject(NOT_SUPPORTED_ERROR, 0,
"Only the temporary session type is supported.");
return;
}
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jbyteArray> j_init_data;
ScopedJavaLocalRef<jobjectArray> j_optional_parameters;
MediaClientAndroid* client = GetMediaClientAndroid();
if (client) {
MediaDrmBridgeDelegate* delegate =
client->GetMediaDrmBridgeDelegate(scheme_uuid_);
if (delegate) {
std::vector<uint8_t> init_data_from_delegate;
std::vector<std::string> optional_parameters_from_delegate;
if (!delegate->OnCreateSession(init_data_type, init_data,
&init_data_from_delegate,
&optional_parameters_from_delegate)) {
promise->reject(INVALID_ACCESS_ERROR, 0, "Invalid init data.");
return;
}
if (!init_data_from_delegate.empty()) {
j_init_data =
base::android::ToJavaByteArray(env, init_data_from_delegate.data(),
init_data_from_delegate.size());
}
if (!optional_parameters_from_delegate.empty()) {
j_optional_parameters = base::android::ToJavaArrayOfStrings(
env, optional_parameters_from_delegate);
}
}
}
if (j_init_data.is_null()) {
j_init_data =
base::android::ToJavaByteArray(env, init_data.data(), init_data.size());
}
ScopedJavaLocalRef<jstring> j_mime =
ConvertUTF8ToJavaString(env, ConvertInitDataType(init_data_type));
uint32_t promise_id = cdm_promise_adapter_.SavePromise(std::move(promise));
Java_MediaDrmBridge_createSessionFromNative(
env, j_media_drm_.obj(), j_init_data.obj(), j_mime.obj(),
j_optional_parameters.obj(), promise_id);
}
void MediaDrmBridge::LoadSession(
SessionType session_type,
const std::string& session_id,
std::unique_ptr<media::NewSessionCdmPromise> promise) {
DCHECK(task_runner_->BelongsToCurrentThread());
DVLOG(2) << __FUNCTION__;
NOTIMPLEMENTED() << "EME persistent sessions not yet supported on Android.";
promise->reject(NOT_SUPPORTED_ERROR, 0, "LoadSession() is not supported.");
}
void MediaDrmBridge::UpdateSession(
const std::string& session_id,
const std::vector<uint8_t>& response,
std::unique_ptr<media::SimpleCdmPromise> promise) {
DCHECK(task_runner_->BelongsToCurrentThread());
DVLOG(2) << __FUNCTION__;
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jbyteArray> j_response =
base::android::ToJavaByteArray(env, response.data(), response.size());
ScopedJavaLocalRef<jbyteArray> j_session_id = base::android::ToJavaByteArray(
env, reinterpret_cast<const uint8_t*>(session_id.data()),
session_id.size());
uint32_t promise_id = cdm_promise_adapter_.SavePromise(std::move(promise));
Java_MediaDrmBridge_updateSession(env, j_media_drm_.obj(), j_session_id.obj(),
j_response.obj(), promise_id);
}
void MediaDrmBridge::CloseSession(
const std::string& session_id,
std::unique_ptr<media::SimpleCdmPromise> promise) {
DCHECK(task_runner_->BelongsToCurrentThread());
DVLOG(2) << __FUNCTION__;
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jbyteArray> j_session_id = base::android::ToJavaByteArray(
env, reinterpret_cast<const uint8_t*>(session_id.data()),
session_id.size());
uint32_t promise_id = cdm_promise_adapter_.SavePromise(std::move(promise));
Java_MediaDrmBridge_closeSession(env, j_media_drm_.obj(), j_session_id.obj(),
promise_id);
}
void MediaDrmBridge::RemoveSession(
const std::string& session_id,
std::unique_ptr<media::SimpleCdmPromise> promise) {
DCHECK(task_runner_->BelongsToCurrentThread());
DVLOG(2) << __FUNCTION__;
NOTIMPLEMENTED() << "EME persistent sessions not yet supported on Android.";
promise->reject(NOT_SUPPORTED_ERROR, 0, "RemoveSession() is not supported.");
}
CdmContext* MediaDrmBridge::GetCdmContext() {
DVLOG(2) << __FUNCTION__;
return &media_drm_bridge_cdm_context_;
}
void MediaDrmBridge::DeleteOnCorrectThread() const {
DVLOG(1) << __FUNCTION__;
if (!task_runner_->BelongsToCurrentThread()) {
// When DeleteSoon returns false, |this| will be leaked, which is okay.
task_runner_->DeleteSoon(FROM_HERE, this);
} else {
delete this;
}
}
int MediaDrmBridge::RegisterPlayer(const base::Closure& new_key_cb,
const base::Closure& cdm_unset_cb) {
// |player_tracker_| can be accessed from any thread.
return player_tracker_.RegisterPlayer(new_key_cb, cdm_unset_cb);
}
void MediaDrmBridge::UnregisterPlayer(int registration_id) {
// |player_tracker_| can be accessed from any thread.
player_tracker_.UnregisterPlayer(registration_id);
}
bool MediaDrmBridge::IsProtectedSurfaceRequired() {
// For Widevine, this depends on the security level.
if (std::equal(scheme_uuid_.begin(), scheme_uuid_.end(), kWidevineUuid))
return IsSecureDecoderRequired(GetSecurityLevel());
// For other key systems, assume true.
return true;
}
void MediaDrmBridge::ResetDeviceCredentials(
const ResetCredentialsCB& callback) {
DVLOG(1) << __FUNCTION__;
DCHECK(reset_credentials_cb_.is_null());
reset_credentials_cb_ = callback;
JNIEnv* env = AttachCurrentThread();
Java_MediaDrmBridge_resetDeviceCredentials(env, j_media_drm_.obj());
}
void MediaDrmBridge::ResolvePromise(uint32_t promise_id) {
DVLOG(2) << __FUNCTION__;
cdm_promise_adapter_.ResolvePromise(promise_id);
}
void MediaDrmBridge::ResolvePromiseWithSession(uint32_t promise_id,
const std::string& session_id) {
DVLOG(2) << __FUNCTION__;
cdm_promise_adapter_.ResolvePromise(promise_id, session_id);
}
void MediaDrmBridge::RejectPromise(uint32_t promise_id,
const std::string& error_message) {
DVLOG(2) << __FUNCTION__;
cdm_promise_adapter_.RejectPromise(promise_id, MediaKeys::UNKNOWN_ERROR, 0,
error_message);
}
jobject MediaDrmBridge::GetMediaCrypto() {
DCHECK(task_runner_->BelongsToCurrentThread());
return j_media_crypto_->obj();
}
void MediaDrmBridge::SetMediaCryptoReadyCB(
const MediaCryptoReadyCB& media_crypto_ready_cb) {
if (!task_runner_->BelongsToCurrentThread()) {
task_runner_->PostTask(
FROM_HERE,
base::Bind(&MediaDrmBridge::SetMediaCryptoReadyCB,
weak_factory_.GetWeakPtr(), media_crypto_ready_cb));
return;
}
DVLOG(1) << __FUNCTION__;
if (media_crypto_ready_cb.is_null()) {
media_crypto_ready_cb_.Reset();
return;
}
DCHECK(media_crypto_ready_cb_.is_null());
media_crypto_ready_cb_ = media_crypto_ready_cb;
if (!j_media_crypto_)
return;
base::ResetAndReturn(&media_crypto_ready_cb_)
.Run(CreateJavaObjectPtr(j_media_crypto_->obj()),
IsProtectedSurfaceRequired());
}
//------------------------------------------------------------------------------
// The following OnXxx functions are called from Java. The implementation must
// only do minimal work and then post tasks to avoid reentrancy issues.
void MediaDrmBridge::OnMediaCryptoReady(
JNIEnv* env,
const JavaParamRef<jobject>& j_media_drm,
const JavaParamRef<jobject>& j_media_crypto) {
DCHECK(task_runner_->BelongsToCurrentThread());
DVLOG(1) << __FUNCTION__;
task_runner_->PostTask(
FROM_HERE,
base::Bind(&MediaDrmBridge::NotifyMediaCryptoReady,
weak_factory_.GetWeakPtr(),
base::Passed(CreateJavaObjectPtr(j_media_crypto.obj()))));
}
void MediaDrmBridge::OnStartProvisioning(
JNIEnv* env,
const JavaParamRef<jobject>& j_media_drm,
const JavaParamRef<jstring>& j_default_url,
const JavaParamRef<jbyteArray>& j_request_data) {
DVLOG(1) << __FUNCTION__;
task_runner_->PostTask(FROM_HERE,
base::Bind(&MediaDrmBridge::SendProvisioningRequest,
weak_factory_.GetWeakPtr(),
ConvertJavaStringToUTF8(env, j_default_url),
AsString(env, j_request_data)));
}
void MediaDrmBridge::OnPromiseResolved(JNIEnv* env,
const JavaParamRef<jobject>& j_media_drm,
jint j_promise_id) {
task_runner_->PostTask(FROM_HERE,
base::Bind(&MediaDrmBridge::ResolvePromise,
weak_factory_.GetWeakPtr(), j_promise_id));
}
void MediaDrmBridge::OnPromiseResolvedWithSession(
JNIEnv* env,
const JavaParamRef<jobject>& j_media_drm,
jint j_promise_id,
const JavaParamRef<jbyteArray>& j_session_id) {
task_runner_->PostTask(FROM_HERE,
base::Bind(&MediaDrmBridge::ResolvePromiseWithSession,
weak_factory_.GetWeakPtr(), j_promise_id,
AsString(env, j_session_id)));
}
void MediaDrmBridge::OnPromiseRejected(
JNIEnv* env,
const JavaParamRef<jobject>& j_media_drm,
jint j_promise_id,
const JavaParamRef<jstring>& j_error_message) {
task_runner_->PostTask(
FROM_HERE,
base::Bind(&MediaDrmBridge::RejectPromise, weak_factory_.GetWeakPtr(),
j_promise_id, ConvertJavaStringToUTF8(env, j_error_message)));
}
void MediaDrmBridge::OnSessionMessage(
JNIEnv* env,
const JavaParamRef<jobject>& j_media_drm,
const JavaParamRef<jbyteArray>& j_session_id,
jint j_message_type,
const JavaParamRef<jbyteArray>& j_message,
const JavaParamRef<jstring>& j_legacy_destination_url) {
DVLOG(2) << __FUNCTION__;
std::vector<uint8_t> message;
JavaByteArrayToByteVector(env, j_message, &message);
GURL legacy_destination_url =
GURL(ConvertJavaStringToUTF8(env, j_legacy_destination_url));
MediaKeys::MessageType message_type =
GetMessageType(static_cast<RequestType>(j_message_type));
task_runner_->PostTask(
FROM_HERE, base::Bind(session_message_cb_, AsString(env, j_session_id),
message_type, message, legacy_destination_url));
}
void MediaDrmBridge::OnSessionClosed(
JNIEnv* env,
const JavaParamRef<jobject>& j_media_drm,
const JavaParamRef<jbyteArray>& j_session_id) {
DVLOG(2) << __FUNCTION__;
std::string session_id = AsString(env, j_session_id);
task_runner_->PostTask(FROM_HERE, base::Bind(session_closed_cb_, session_id));
}
void MediaDrmBridge::OnSessionKeysChange(
JNIEnv* env,
const JavaParamRef<jobject>& j_media_drm,
const JavaParamRef<jbyteArray>& j_session_id,
const JavaParamRef<jobjectArray>& j_keys_info,
bool has_additional_usable_key) {
DVLOG(2) << __FUNCTION__;
CdmKeysInfo cdm_keys_info;
size_t size = env->GetArrayLength(j_keys_info);
DCHECK_GT(size, 0u);
for (size_t i = 0; i < size; ++i) {
ScopedJavaLocalRef<jobject> j_key_status(
env, env->GetObjectArrayElement(j_keys_info, i));
ScopedJavaLocalRef<jbyteArray> j_key_id =
Java_KeyStatus_getKeyId(env, j_key_status.obj());
std::vector<uint8_t> key_id;
JavaByteArrayToByteVector(env, j_key_id.obj(), &key_id);
DCHECK(!key_id.empty());
jint j_status_code = Java_KeyStatus_getStatusCode(env, j_key_status.obj());
CdmKeyInformation::KeyStatus key_status =
ConvertKeyStatus(static_cast<KeyStatus>(j_status_code));
DVLOG(2) << __FUNCTION__ << "Key status change: "
<< base::HexEncode(&key_id[0], key_id.size()) << ", "
<< key_status;
cdm_keys_info.push_back(new CdmKeyInformation(key_id, key_status, 0));
}
task_runner_->PostTask(
FROM_HERE,
base::Bind(session_keys_change_cb_, AsString(env, j_session_id),
has_additional_usable_key, base::Passed(&cdm_keys_info)));
if (has_additional_usable_key) {
task_runner_->PostTask(FROM_HERE,
base::Bind(&MediaDrmBridge::OnHasAdditionalUsableKey,
weak_factory_.GetWeakPtr()));
}
}
// According to MeidaDrm documentation [1], zero |expiry_time_ms| means the keys
// will never expire. This will be translated into a NULL base::Time() [2],
// which will then be mapped to a zero Java time [3]. The zero Java time is
// passed to Blink which will then be translated to NaN [4], which is what the
// spec uses to indicate that the license will never expire [5].
// [1]
// http://developer.android.com/reference/android/media/MediaDrm.OnExpirationUpdateListener.html
// [2] See base::Time::FromDoubleT()
// [3] See base::Time::ToJavaTime()
// [4] See MediaKeySession::expirationChanged()
// [5] https://github.com/w3c/encrypted-media/issues/58
void MediaDrmBridge::OnSessionExpirationUpdate(
JNIEnv* env,
const JavaParamRef<jobject>& j_media_drm,
const JavaParamRef<jbyteArray>& j_session_id,
jlong expiry_time_ms) {
DVLOG(2) << __FUNCTION__ << ": " << expiry_time_ms << " ms";
task_runner_->PostTask(
FROM_HERE,
base::Bind(session_expiration_update_cb_, AsString(env, j_session_id),
base::Time::FromDoubleT(expiry_time_ms / 1000.0)));
}
void MediaDrmBridge::OnLegacySessionError(
JNIEnv* env,
const JavaParamRef<jobject>& j_media_drm,
const JavaParamRef<jbyteArray>& j_session_id,
const JavaParamRef<jstring>& j_error_message) {
std::string error_message = ConvertJavaStringToUTF8(env, j_error_message);
DVLOG(2) << __FUNCTION__ << ": " << error_message;
task_runner_->PostTask(
FROM_HERE,
base::Bind(legacy_session_error_cb_, AsString(env, j_session_id),
MediaKeys::UNKNOWN_ERROR, 0, error_message));
}
void MediaDrmBridge::OnResetDeviceCredentialsCompleted(
JNIEnv* env,
const JavaParamRef<jobject>&,
bool success) {
DVLOG(2) << __FUNCTION__ << ": success:" << success;
DCHECK(!reset_credentials_cb_.is_null());
task_runner_->PostTask(
FROM_HERE,
base::Bind(base::ResetAndReturn(&reset_credentials_cb_), success));
}
//------------------------------------------------------------------------------
// The following are private methods.
MediaDrmBridge::MediaDrmBridge(
const std::vector<uint8_t>& scheme_uuid,
SecurityLevel security_level,
const CreateFetcherCB& create_fetcher_cb,
const SessionMessageCB& session_message_cb,
const SessionClosedCB& session_closed_cb,
const LegacySessionErrorCB& legacy_session_error_cb,
const SessionKeysChangeCB& session_keys_change_cb,
const SessionExpirationUpdateCB& session_expiration_update_cb)
: scheme_uuid_(scheme_uuid),
create_fetcher_cb_(create_fetcher_cb),
session_message_cb_(session_message_cb),
session_closed_cb_(session_closed_cb),
legacy_session_error_cb_(legacy_session_error_cb),
session_keys_change_cb_(session_keys_change_cb),
session_expiration_update_cb_(session_expiration_update_cb),
task_runner_(base::ThreadTaskRunnerHandle::Get()),
media_drm_bridge_cdm_context_(this),
weak_factory_(this) {
DVLOG(1) << __FUNCTION__;
DCHECK(!create_fetcher_cb_.is_null());
JNIEnv* env = AttachCurrentThread();
CHECK(env);
ScopedJavaLocalRef<jbyteArray> j_scheme_uuid =
base::android::ToJavaByteArray(env, &scheme_uuid[0], scheme_uuid.size());
std::string security_level_str = GetSecurityLevelString(security_level);
ScopedJavaLocalRef<jstring> j_security_level =
ConvertUTF8ToJavaString(env, security_level_str);
// Note: OnMediaCryptoReady() could be called in this call.
j_media_drm_.Reset(Java_MediaDrmBridge_create(
env, j_scheme_uuid.obj(), j_security_level.obj(),
reinterpret_cast<intptr_t>(this)));
}
MediaDrmBridge::~MediaDrmBridge() {
DCHECK(task_runner_->BelongsToCurrentThread());
DVLOG(1) << __FUNCTION__;
JNIEnv* env = AttachCurrentThread();
// After the call to Java_MediaDrmBridge_destroy() Java won't call native
// methods anymore, this is ensured by MediaDrmBridge.java.
if (!j_media_drm_.is_null())
Java_MediaDrmBridge_destroy(env, j_media_drm_.obj());
player_tracker_.NotifyCdmUnset();
if (!media_crypto_ready_cb_.is_null()) {
base::ResetAndReturn(&media_crypto_ready_cb_)
.Run(CreateJavaObjectPtr(nullptr), IsProtectedSurfaceRequired());
}
// Rejects all pending promises.
cdm_promise_adapter_.Clear();
}
// TODO(ddorwin): This is specific to Widevine. http://crbug.com/459400
// static
bool MediaDrmBridge::IsSecureDecoderRequired(SecurityLevel security_level) {
DCHECK(IsAvailable());
return SECURITY_LEVEL_1 == security_level;
}
MediaDrmBridge::SecurityLevel MediaDrmBridge::GetSecurityLevel() {
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jstring> j_security_level =
Java_MediaDrmBridge_getSecurityLevel(env, j_media_drm_.obj());
std::string security_level_str =
ConvertJavaStringToUTF8(env, j_security_level.obj());
return GetSecurityLevelFromString(security_level_str);
}
// We have to use scoped_ptr to pass ScopedJavaGlobalRef with a callback.
// TODO(timav): Check whether we can simply pass j_media_crypto_->obj() in the
// callback.
MediaDrmBridge::JavaObjectPtr MediaDrmBridge::CreateJavaObjectPtr(
jobject object) {
JavaObjectPtr j_object_ptr(new ScopedJavaGlobalRef<jobject>());
j_object_ptr->Reset(AttachCurrentThread(), object);
return j_object_ptr;
}
void MediaDrmBridge::NotifyMediaCryptoReady(JavaObjectPtr j_media_crypto) {
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK(j_media_crypto);
DCHECK(!j_media_crypto_);
j_media_crypto_ = std::move(j_media_crypto);
if (media_crypto_ready_cb_.is_null())
return;
base::ResetAndReturn(&media_crypto_ready_cb_)
.Run(CreateJavaObjectPtr(j_media_crypto_->obj()),
IsProtectedSurfaceRequired());
}
void MediaDrmBridge::SendProvisioningRequest(const std::string& default_url,
const std::string& request_data) {
DCHECK(task_runner_->BelongsToCurrentThread());
DVLOG(1) << __FUNCTION__;
DCHECK(!provision_fetcher_) << "At most one provision request at any time.";
provision_fetcher_ = create_fetcher_cb_.Run();
provision_fetcher_->Retrieve(
default_url, request_data,
base::Bind(&MediaDrmBridge::ProcessProvisionResponse,
weak_factory_.GetWeakPtr()));
}
void MediaDrmBridge::ProcessProvisionResponse(bool success,
const std::string& response) {
DCHECK(task_runner_->BelongsToCurrentThread());
DVLOG(1) << __FUNCTION__;
DCHECK(provision_fetcher_) << "No provision request pending.";
provision_fetcher_.reset();
if (!success)
VLOG(1) << "Device provision failure: can't get server response";
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jbyteArray> j_response = base::android::ToJavaByteArray(
env, reinterpret_cast<const uint8_t*>(response.data()), response.size());
Java_MediaDrmBridge_processProvisionResponse(env, j_media_drm_.obj(), success,
j_response.obj());
}
void MediaDrmBridge::OnHasAdditionalUsableKey() {
DCHECK(task_runner_->BelongsToCurrentThread());
DVLOG(1) << __FUNCTION__;
player_tracker_.NotifyNewKey();
}
} // namespace media
| {
"pile_set_name": "Github"
} |
STATS SUMMARY
=============
General stats
--------------------
Sample time: 0.014 [Seconds]
Number of SSL packets: 401 [Packets]
Rate of SSL packets: 0.000 [Packets/sec]
Number of SSL flows: 20 [Flows]
Rate of SSL flows: 0.000 [Flows/sec]
Total SSL data: 284021 [Bytes]
Rate of SSL data: 0.000 [Bytes/sec]
Average packets per flow: 20.050 [Packets]
Average data per flow: 14201.050 [Bytes]
Client-hello message: 20 [Messages]
Server-hello message: 20 [Messages]
Number of SSL flows with successful handshake: 18 [Flows]
Number of SSL flows ended with alert: 5 [Flows]
SSL/TLS ports count
--------------------
-------------------------
| SSL/TLS ports | Count |
-------------------------
| 443 | 20 |
-------------------------
SSL versions count
--------------------
----------------------------------------
| SSL record version | Count |
----------------------------------------
| 771 | 20 |
----------------------------------------
Client-hello versions count
--------------------
----------------------------------------
| Client-hello version | Count |
----------------------------------------
| 769 | 20 |
----------------------------------------
Cipher-suite count
--------------------
--------------------------------------------------------------
| Cipher-suite | Count |
--------------------------------------------------------------
| TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 | 6 |
| TLS_DHE_RSA_WITH_AES_128_CBC_SHA | 6 |
| TLS_RSA_WITH_RC4_128_SHA | 4 |
| TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 | 3 |
| TLS_RSA_WITH_AES_128_CBC_SHA | 1 |
--------------------------------------------------------------
Server-name count
--------------------
----------------------------------------------------
| Hostname | Count |
----------------------------------------------------
| img.cybersear.ch | 6 |
| fbstatic-a.akamaihd.net | 3 |
| www.gstatic.com | 2 |
| apis.google.com | 2 |
| www.google.com | 1 |
| www.google.co.il | 1 |
| www.facebook.com | 1 |
| ssl.gstatic.com | 1 |
| ssl.bbc.co.uk | 1 |
| s-static.ak.facebook.com | 1 |
| id.google.co.il | 1 |
----------------------------------------------------
| {
"pile_set_name": "Github"
} |
;;; package.el --- Simple package system for Emacs
;; Copyright (C) 2007-2011 Free Software Foundation, Inc.
;; Author: Tom Tromey <[email protected]>
;; Created: 10 Mar 2007
;; Version: 0.9
;; Keywords: tools
;; This file is part of GNU Emacs.
;; GNU Emacs is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING. If not, write to the
;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
;;; Change Log:
;; 2 Apr 2007 - now using ChangeLog file
;; 15 Mar 2007 - updated documentation
;; 14 Mar 2007 - Changed how obsolete packages are handled
;; 13 Mar 2007 - Wrote package-install-from-buffer
;; 12 Mar 2007 - Wrote package-menu mode
;;; Commentary:
;; The idea behind package.el is to be able to download packages and
;; install them. Packages are versioned and have versioned
;; dependencies. Furthermore, this supports built-in packages which
;; may or may not be newer than user-specified packages. This makes
;; it possible to upgrade Emacs and automatically disable packages
;; which have moved from external to core. (Note though that we don't
;; currently register any of these, so this feature does not actually
;; work.)
;; A package is described by its name and version. The distribution
;; format is either a tar file or a single .el file.
;; A tar file should be named "NAME-VERSION.tar". The tar file must
;; unpack into a directory named after the package and version:
;; "NAME-VERSION". It must contain a file named "PACKAGE-pkg.el"
;; which consists of a call to define-package. It may also contain a
;; "dir" file and the info files it references.
;; A .el file is named "NAME-VERSION.el" in the remote archive, but is
;; installed as simply "NAME.el" in a directory named "NAME-VERSION".
;; The downloader downloads all dependent packages. By default,
;; packages come from the official GNU sources, but others may be
;; added by customizing the `package-archives' alist. Packages get
;; byte-compiled at install time.
;; At activation time we will set up the load-path and the info path,
;; and we will load the package's autoloads. If a package's
;; dependencies are not available, we will not activate that package.
;; Conceptually a package has multiple state transitions:
;;
;; * Download. Fetching the package from ELPA.
;; * Install. Untar the package, or write the .el file, into
;; ~/.emacs.d/elpa/ directory.
;; * Byte compile. Currently this phase is done during install,
;; but we may change this.
;; * Activate. Evaluate the autoloads for the package to make it
;; available to the user.
;; * Load. Actually load the package and run some code from it.
;; Other external functions you may want to use:
;;
;; M-x list-packages
;; Enters a mode similar to buffer-menu which lets you manage
;; packages. You can choose packages for install (mark with "i",
;; then "x" to execute) or deletion (not implemented yet), and you
;; can see what packages are available. This will automatically
;; fetch the latest list of packages from ELPA.
;;
;; M-x package-list-packages-no-fetch
;; Like package-list-packages, but does not automatically fetch the
;; new list of packages.
;;
;; M-x package-install-from-buffer
;; Install a package consisting of a single .el file that appears
;; in the current buffer. This only works for packages which
;; define a Version header properly; package.el also supports the
;; extension headers Package-Version (in case Version is an RCS id
;; or similar), and Package-Requires (if the package requires other
;; packages).
;;
;; M-x package-install-file
;; Install a package from the indicated file. The package can be
;; either a tar file or a .el file. A tar file must contain an
;; appropriately-named "-pkg.el" file; a .el file must be properly
;; formatted as with package-install-from-buffer.
;;; Thanks:
;;; (sorted by sort-lines):
;; Jim Blandy <[email protected]>
;; Karl Fogel <[email protected]>
;; Kevin Ryde <[email protected]>
;; Lawrence Mitchell
;; Michael Olson <[email protected]>
;; Sebastian Tennant <[email protected]>
;; Stefan Monnier <[email protected]>
;; Vinicius Jose Latorre <[email protected]>
;; Phil Hagelberg <[email protected]>
;;; ToDo:
;; - putting info dirs at the start of the info path means
;; users see a weird ordering of categories. OTOH we want to
;; override later entries. maybe emacs needs to enforce
;; the standard layout?
;; - put bytecode in a separate directory tree
;; - perhaps give users a way to recompile their bytecode
;; or do it automatically when emacs changes
;; - give users a way to know whether a package is installed ok
;; - give users a way to view a package's documentation when it
;; only appears in the .el
;; - use/extend checkdoc so people can tell if their package will work
;; - "installed" instead of a blank in the status column
;; - tramp needs its files to be compiled in a certain order.
;; how to handle this? fix tramp?
;; - on emacs 21 we don't kill the -autoloads.el buffer. what about 22?
;; - maybe we need separate .elc directories for various emacs versions
;; and also emacs-vs-xemacs. That way conditional compilation can
;; work. But would this break anything?
;; - should store the package's keywords in archive-contents, then
;; let the users filter the package-menu by keyword. See
;; finder-by-keyword. (We could also let people view the
;; Commentary, but it isn't clear how useful this is.)
;; - William Xu suggests being able to open a package file without
;; installing it
;; - Interface with desktop.el so that restarting after an install
;; works properly
;; - Implement M-x package-upgrade, to upgrade any/all existing packages
;; - Use hierarchical layout. PKG/etc PKG/lisp PKG/info
;; ... except maybe lisp?
;; - It may be nice to have a macro that expands to the package's
;; private data dir, aka ".../etc". Or, maybe data-directory
;; needs to be a list (though this would be less nice)
;; a few packages want this, eg sokoban
;; - package menu needs:
;; ability to know which packages are built-in & thus not deletable
;; it can sometimes print odd results, like 0.3 available but 0.4 active
;; why is that?
;; - Allow multiple versions on the server...?
;; [ why bother? ]
;; - Don't install a package which will invalidate dependencies overall
;; - Allow something like (or (>= emacs 21.0) (>= xemacs 21.5))
;; [ currently thinking, why bother.. KISS ]
;; - Allow optional package dependencies
;; then if we require 'bbdb', bbdb-specific lisp in lisp/bbdb
;; and just don't compile to add to load path ...?
;; - Have a list of archive URLs? [ maybe there's no point ]
;; - David Kastrup pointed out on the xemacs list that for GPL it
;; is friendlier to ship the source tree. We could "support" that
;; by just having a "src" subdir in the package. This isn't ideal
;; but it probably is not worth trying to support random source
;; tree layouts, build schemes, etc.
;; - Our treatment of the info path is somewhat bogus
;; - perhaps have an "unstable" tree in ELPA as well as a stable one
;;; Code:
(defgroup package nil
"Manager for Emacs Lisp packages."
:group 'applications
:version "24.1")
;;;###autoload
(defcustom package-enable-at-startup t
"Whether to activate installed packages when Emacs starts.
If non-nil, packages are activated after reading the init file
and before `after-init-hook'. Activation is not done if
`user-init-file' is nil (e.g. Emacs was started with \"-q\").
Even if the value is nil, you can type \\[package-initialize] to
activate the package system at any time."
:type 'boolean
:group 'package
:version "24.1")
(defcustom package-load-list '(all)
"List of packages for `package-initialize' to load.
Each element in this list should be a list (NAME VERSION), or the
symbol `all'. The symbol `all' says to load the latest installed
versions of all packages not specified by other elements.
For an element (NAME VERSION), NAME is a package name (a symbol).
VERSION should be t, a string, or nil.
If VERSION is t, all versions are loaded, though obsolete ones
will be put in `package-obsolete-alist' and not activated.
If VERSION is a string, only that version is ever loaded.
Any other version, even if newer, is silently ignored.
Hence, the package is \"held\" at that version.
If VERSION is nil, the package is not loaded (it is \"disabled\")."
:type '(repeat symbol)
:risky t
:group 'package
:version "24.1")
(defvar Info-directory-list)
(declare-function info-initialize "info" ())
(declare-function url-http-parse-response "url-http" ())
(declare-function lm-header "lisp-mnt" (header))
(declare-function lm-commentary "lisp-mnt" (&optional file))
(defvar url-http-end-of-headers)
(defcustom package-archives '(("gnu" . "https://elpa.gnu.org/packages/"))
"An alist of archives from which to fetch.
The default value points to the GNU Emacs package repository.
Each element has the form (ID . LOCATION).
ID is an archive name, as a string.
LOCATION specifies the base location for the archive.
If it starts with \"http:\", it is treated as a HTTP URL;
otherwise it should be an absolute directory name.
(Other types of URL are currently not supported.)"
:type '(alist :key-type (string :tag "Archive name")
:value-type (string :tag "URL or directory name"))
:risky t
:group 'package
:version "24.1")
(defconst package-archive-version 1
"Version number of the package archive understood by this file.
Lower version numbers than this will probably be understood as well.")
(defconst package-el-version "1.0"
"Version of package.el.")
;; We don't prime the cache since it tends to get out of date.
(defvar package-archive-contents nil
"Cache of the contents of the Emacs Lisp Package Archive.
This is an alist mapping package names (symbols) to package
descriptor vectors. These are like the vectors for `package-alist'
but have extra entries: one which is 'tar for tar packages and
'single for single-file packages, and one which is the name of
the archive from which it came.")
(put 'package-archive-contents 'risky-local-variable t)
(defcustom package-user-dir (locate-user-emacs-file "elpa")
"Directory containing the user's Emacs Lisp packages.
The directory name should be absolute.
Apart from this directory, Emacs also looks for system-wide
packages in `package-directory-list'."
:type 'directory
:risky t
:group 'package
:version "24.1")
(defcustom package-directory-list
;; Defaults are subdirs named "elpa" in the site-lisp dirs.
(let (result)
(dolist (f load-path)
(and (stringp f)
(equal (file-name-nondirectory f) "site-lisp")
(push (expand-file-name "elpa" f) result)))
(nreverse result))
"List of additional directories containing Emacs Lisp packages.
Each directory name should be absolute.
These directories contain packages intended for system-wide; in
contrast, `package-user-dir' contains packages for personal use."
:type '(repeat directory)
:risky t
:group 'package
:version "24.1")
;; The value is precomputed in finder-inf.el, but don't load that
;; until it's needed (i.e. when `package-intialize' is called).
(defvar package--builtins nil
"Alist of built-in packages.
The actual value is initialized by loading the library
`finder-inf'; this is not done until it is needed, e.g. by the
function `package-built-in-p'.
Each element has the form (PKG . DESC), where PKG is a package
name (a symbol) and DESC is a vector that describes the package.
The vector DESC has the form [VERSION REQS DOCSTRING].
VERSION is a version list.
REQS is a list of packages (symbols) required by the package.
DOCSTRING is a brief description of the package.")
(put 'package--builtins 'risky-local-variable t)
(defvar package-alist nil
"Alist of all packages available for activation.
Each element has the form (PKG . DESC), where PKG is a package
name (a symbol) and DESC is a vector that describes the package.
The vector DESC has the form [VERSION REQS DOCSTRING].
VERSION is a version list.
REQS is a list of packages (symbols) required by the package.
DOCSTRING is a brief description of the package.
This variable is set automatically by `package-load-descriptor',
called via `package-initialize'. To change which packages are
loaded and/or activated, customize `package-load-list'.")
(put 'package-archive-contents 'risky-local-variable t)
(defvar package-activated-list nil
"List of the names of currently activated packages.")
(put 'package-activated-list 'risky-local-variable t)
(defvar package-obsolete-alist nil
"Representation of obsolete packages.
Like `package-alist', but maps package name to a second alist.
The inner alist is keyed by version.")
(put 'package-obsolete-alist 'risky-local-variable t)
(defconst package-subdirectory-regexp
"\\`\\([^.].*?\\)-\\([0-9]+\\(?:[.][0-9]+\\|\\(?:pre\\|beta\\|alpha\\)[0-9]+\\)*\\)\\'"
"Regular expression matching the name of a package subdirectory.
The first subexpression is the package name.
The second subexpression is the version string.")
(defun package-version-join (vlist)
"Return the version string corresponding to the list VLIST.
This is, approximately, the inverse of `version-to-list'.
\(Actually, it returns only one of the possible inverses, since
`version-to-list' is a many-to-one operation.)"
(if (null vlist)
""
(let ((str-list (list "." (int-to-string (car vlist)))))
(dolist (num (cdr vlist))
(cond
((>= num 0)
(push (int-to-string num) str-list)
(push "." str-list))
((< num -3)
(error "Invalid version list `%s'" vlist))
(t
;; pre, or beta, or alpha
(cond ((equal "." (car str-list))
(pop str-list))
((not (string-match "[0-9]+" (car str-list)))
(error "Invalid version list `%s'" vlist)))
(push (cond ((= num -1) "pre")
((= num -2) "beta")
((= num -3) "alpha"))
str-list))))
(if (equal "." (car str-list))
(pop str-list))
(apply 'concat (nreverse str-list)))))
(defun package-strip-version (dirname)
"Strip the version from a combined package name and version.
E.g., if given \"quux-23.0\", will return \"quux\""
(if (string-match package-subdirectory-regexp dirname)
(match-string 1 dirname)))
(defun package-load-descriptor (dir package)
"Load the description file in directory DIR for package PACKAGE.
Here, PACKAGE is a string of the form NAME-VER, where NAME is the
package name and VER is its version."
(let* ((pkg-dir (expand-file-name package dir))
(pkg-file (expand-file-name
(concat (package-strip-version package) "-pkg")
pkg-dir)))
(when (and (file-directory-p pkg-dir)
(file-exists-p (concat pkg-file ".el")))
(load pkg-file nil t))))
(defun package-load-all-descriptors ()
"Load descriptors for installed Emacs Lisp packages.
This looks for package subdirectories in `package-user-dir' and
`package-directory-list'. The variable `package-load-list'
controls which package subdirectories may be loaded.
In each valid package subdirectory, this function loads the
description file containing a call to `define-package', which
updates `package-alist' and `package-obsolete-alist'."
(let ((all (memq 'all package-load-list))
name version force)
(dolist (dir (cons package-user-dir package-directory-list))
(when (file-directory-p dir)
(dolist (subdir (directory-files dir))
(when (and (file-directory-p (expand-file-name subdir dir))
(string-match package-subdirectory-regexp subdir))
(setq name (intern (match-string 1 subdir))
version (match-string 2 subdir)
force (assq name package-load-list))
(when (cond
((null force)
all) ; not in package-load-list
((null (setq force (cadr force)))
nil) ; disabled
((eq force t)
t)
((stringp force) ; held
(version-list-= (version-to-list version)
(version-to-list force)))
(t
(error "Invalid element in `package-load-list'")))
(package-load-descriptor dir subdir))))))))
(defsubst package-desc-vers (desc)
"Extract version from a package description vector."
(aref desc 0))
(defsubst package-desc-reqs (desc)
"Extract requirements from a package description vector."
(aref desc 1))
(defsubst package-desc-doc (desc)
"Extract doc string from a package description vector."
(aref desc 2))
(defsubst package-desc-kind (desc)
"Extract the kind of download from an archive package description vector."
(aref desc 3))
(defun package--dir (name version)
"Return the directory where a package is installed, or nil if none.
NAME and VERSION are both strings."
(let* ((subdir (concat name "-" version))
(dir-list (cons package-user-dir package-directory-list))
pkg-dir)
(while dir-list
(let ((subdir-full (expand-file-name subdir (car dir-list))))
(if (file-directory-p subdir-full)
(setq pkg-dir subdir-full
dir-list nil)
(setq dir-list (cdr dir-list)))))
pkg-dir))
(defun package-activate-1 (package pkg-vec)
(let* ((name (symbol-name package))
(version-str (package-version-join (package-desc-vers pkg-vec)))
(pkg-dir (package--dir name version-str)))
(unless pkg-dir
(error "Internal error: unable to find directory for `%s-%s'"
name version-str))
;; Add info node.
(when (file-exists-p (expand-file-name "dir" pkg-dir))
;; FIXME: not the friendliest, but simple.
(require 'info)
(info-initialize)
(push pkg-dir Info-directory-list))
;; Add to load path, add autoloads, and activate the package.
(push pkg-dir load-path)
(load (expand-file-name (concat name "-autoloads") pkg-dir) nil t)
(push package package-activated-list)
;; Don't return nil.
t))
(defun package-built-in-p (package &optional version)
"Return true if PACKAGE, of VERSION or newer, is built-in to Emacs."
(require 'finder-inf nil t) ; For `package--builtins'.
(let ((elt (assq package package--builtins)))
(and elt (version-list-<= version (package-desc-vers (cdr elt))))))
;; This function goes ahead and activates a newer version of a package
;; if an older one was already activated. This is not ideal; we'd at
;; least need to check to see if the package has actually been loaded,
;; and not merely activated.
(defun package-activate (package version)
"Activate package PACKAGE, of version VERSION or newer.
If PACKAGE has any dependencies, recursively activate them.
Return nil if the package could not be activated."
(let ((pkg-vec (cdr (assq package package-alist)))
available-version found)
;; Check if PACKAGE is available in `package-alist'.
(when pkg-vec
(setq available-version (package-desc-vers pkg-vec)
found (version-list-<= version available-version)))
(cond
;; If no such package is found, maybe it's built-in.
((null found)
(package-built-in-p package version))
;; If the package is already activated, just return t.
((memq package package-activated-list)
t)
;; Otherwise, proceed with activation.
(t
(let ((fail (catch 'dep-failure
;; Activate its dependencies recursively.
(dolist (req (package-desc-reqs pkg-vec))
(unless (package-activate (car req) (cadr req))
(throw 'dep-failure req))))))
(if fail
(warn "Unable to activate package `%s'.
Required package `%s-%s' is unavailable"
package (car fail) (package-version-join (cadr fail)))
;; If all goes well, activate the package itself.
(package-activate-1 package pkg-vec)))))))
(defun package-mark-obsolete (package pkg-vec)
"Put package on the obsolete list, if not already there."
(let ((elt (assq package package-obsolete-alist)))
(if elt
;; If this obsolete version does not exist in the list, update
;; it the list.
(unless (assoc (package-desc-vers pkg-vec) (cdr elt))
(setcdr elt (cons (cons (package-desc-vers pkg-vec) pkg-vec)
(cdr elt))))
;; Make a new association.
(push (cons package (list (cons (package-desc-vers pkg-vec)
pkg-vec)))
package-obsolete-alist))))
(defun define-package (name-string version-string
&optional docstring requirements
&rest extra-properties)
"Define a new package.
NAME-STRING is the name of the package, as a string.
VERSION-STRING is the version of the package, as a list of
integers of the form produced by `version-to-list'.
DOCSTRING is a short description of the package, a string.
REQUIREMENTS is a list of dependencies on other packages.
Each requirement is of the form (OTHER-PACKAGE \"VERSION\").
EXTRA-PROPERTIES is currently unused."
(let* ((name (intern name-string))
(version (version-to-list version-string))
(new-pkg-desc
(cons name
(vector version
(mapcar
(lambda (elt)
(list (car elt)
(version-to-list (car (cdr elt)))))
requirements)
docstring)))
(old-pkg (assq name package-alist)))
(cond
;; If there's no old package, just add this to `package-alist'.
((null old-pkg)
(push new-pkg-desc package-alist))
((version-list-< (package-desc-vers (cdr old-pkg)) version)
;; Remove the old package and declare it obsolete.
(package-mark-obsolete name (cdr old-pkg))
(setq package-alist (cons new-pkg-desc
(delq old-pkg package-alist))))
;; You can have two packages with the same version, e.g. one in
;; the system package directory and one in your private
;; directory. We just let the first one win.
((not (version-list-= (package-desc-vers (cdr old-pkg)) version))
;; The package is born obsolete.
(package-mark-obsolete name (cdr new-pkg-desc))))))
;; From Emacs 22.
(defun package-autoload-ensure-default-file (file)
"Make sure that the autoload file FILE exists and if not create it."
(unless (file-exists-p file)
(write-region
(concat ";;; " (file-name-nondirectory file)
" --- automatically extracted autoloads\n"
";;\n"
";;; Code:\n\n"
"\n;; Local Variables:\n"
";; version-control: never\n"
";; no-byte-compile: t\n"
";; no-update-autoloads: t\n"
";; End:\n"
";;; " (file-name-nondirectory file)
" ends here\n")
nil file))
file)
(defun package-generate-autoloads (name pkg-dir)
(let* ((auto-name (concat name "-autoloads.el"))
(ignore-name (concat name "-pkg.el"))
(generated-autoload-file (expand-file-name auto-name pkg-dir))
(version-control 'never))
(require 'autoload)
(unless (fboundp 'autoload-ensure-default-file)
(package-autoload-ensure-default-file generated-autoload-file))
(update-directory-autoloads pkg-dir)))
(defun package-untar-buffer ()
"Untar the current buffer.
This uses `tar-untar-buffer' if it is available.
Otherwise it uses an external `tar' program.
`default-directory' should be set by the caller."
(require 'tar-mode)
(if (fboundp 'tar-untar-buffer)
(progn
;; tar-mode messes with narrowing, so we just let it have the
;; whole buffer to play with.
(delete-region (point-min) (point))
(tar-mode)
(tar-untar-buffer))
;; FIXME: check the result.
(call-process-region (point) (point-max) "tar" nil '(nil nil) nil
"xf" "-")))
(defun package-unpack (name version)
(let ((pkg-dir (expand-file-name (concat (symbol-name name) "-" version)
package-user-dir)))
(make-directory package-user-dir t)
;; FIXME: should we delete PKG-DIR if it exists?
(let* ((default-directory (file-name-as-directory package-user-dir)))
(package-untar-buffer)
(package-generate-autoloads (symbol-name name) pkg-dir)
(let ((load-path (cons pkg-dir load-path)))
(byte-recompile-directory pkg-dir 0 t)))))
(defun package--write-file-no-coding (file-name)
(let ((buffer-file-coding-system 'no-conversion))
(write-region (point-min) (point-max) file-name)))
(defun package-unpack-single (file-name version desc requires)
"Install the contents of the current buffer as a package."
;; Special case "package".
(if (string= file-name "package")
(package--write-file-no-coding
(expand-file-name (concat file-name ".el") package-user-dir))
(let* ((pkg-dir (expand-file-name (concat file-name "-"
(package-version-join
(version-to-list version)))
package-user-dir))
(el-file (expand-file-name (concat file-name ".el") pkg-dir))
(pkg-file (expand-file-name (concat file-name "-pkg.el") pkg-dir)))
(make-directory pkg-dir t)
(package--write-file-no-coding el-file)
(let ((print-level nil)
(print-length nil))
(write-region
(concat
(prin1-to-string
(list 'define-package
file-name
version
desc
(list 'quote
;; Turn version lists into string form.
(mapcar
(lambda (elt)
(list (car elt)
(package-version-join (cadr elt))))
requires))))
"\n")
nil
pkg-file
nil nil nil 'excl))
(package-generate-autoloads file-name pkg-dir)
(let ((load-path (cons pkg-dir load-path)))
(byte-recompile-directory pkg-dir 0 t)))))
(defmacro package--with-work-buffer (location file &rest body)
"Run BODY in a buffer containing the contents of FILE at LOCATION.
LOCATION is the base location of a package archive, and should be
one of the URLs (or file names) specified in `package-archives'.
FILE is the name of a file relative to that base location.
This macro retrieves FILE from LOCATION into a temporary buffer,
and evaluates BODY while that buffer is current. This work
buffer is killed afterwards. Return the last value in BODY."
`(let* ((http (string-match "\\`http:" ,location))
(buffer
(if http
(url-retrieve-synchronously (concat ,location ,file))
(generate-new-buffer "*package work buffer*"))))
(prog1
(with-current-buffer buffer
(if http
(progn (package-handle-response)
(re-search-forward "^$" nil 'move)
(forward-char)
(delete-region (point-min) (point)))
(unless (file-name-absolute-p ,location)
(error "Archive location %s is not an absolute file name"
,location))
(insert-file-contents (expand-file-name ,file ,location)))
,@body)
(kill-buffer buffer))))
(defun package-handle-response ()
"Handle the response from a `url-retrieve-synchronously' call.
Parse the HTTP response and throw if an error occurred.
The url package seems to require extra processing for this.
This should be called in a `save-excursion', in the download buffer.
It will move point to somewhere in the headers."
;; We assume HTTP here.
(require 'url-http)
(let ((response (url-http-parse-response)))
(when (or (< response 200) (>= response 300))
(error "Error during download request:%s"
(buffer-substring-no-properties (point) (progn
(end-of-line)
(point)))))))
(defun package-download-single (name version desc requires)
"Download and install a single-file package."
(let ((location (package-archive-base name))
(file (concat (symbol-name name) "-" version ".el")))
(package--with-work-buffer location file
(package-unpack-single (symbol-name name) version desc requires))))
(defun package-download-tar (name version)
"Download and install a tar package."
(let ((location (package-archive-base name))
(file (concat (symbol-name name) "-" version ".tar")))
(package--with-work-buffer location file
(package-unpack name version))))
(defun package-installed-p (package &optional min-version)
"Return true if PACKAGE, of VERSION or newer, is installed.
Built-in packages also qualify."
(let ((pkg-desc (assq package package-alist)))
(if pkg-desc
(version-list-<= min-version
(package-desc-vers (cdr pkg-desc)))
;; Also check built-in packages.
(package-built-in-p package min-version))))
(defun package-compute-transaction (package-list requirements)
"Return a list of packages to be installed, including PACKAGE-LIST.
PACKAGE-LIST should be a list of package names (symbols).
REQUIREMENTS should be a list of additional requirements; each
element in this list should have the form (PACKAGE VERSION),
where PACKAGE is a package name and VERSION is the required
version of that package (as a list).
This function recursively computes the requirements of the
packages in REQUIREMENTS, and returns a list of all the packages
that must be installed. Packages that are already installed are
not included in this list."
(dolist (elt requirements)
(let* ((next-pkg (car elt))
(next-version (cadr elt)))
(unless (package-installed-p next-pkg next-version)
;; A package is required, but not installed. It might also be
;; blocked via `package-load-list'.
(let ((pkg-desc (assq next-pkg package-archive-contents))
hold)
(when (setq hold (assq next-pkg package-load-list))
(setq hold (cadr hold))
(cond ((eq hold nil)
(error "Required package '%s' is disabled"
(symbol-name next-pkg)))
((null (stringp hold))
(error "Invalid element in `package-load-list'"))
((version-list-< (version-to-list hold) next-version)
(error "Package `%s' held at version %s, \
but version %s required"
(symbol-name next-pkg) hold
(package-version-join next-version)))))
(unless pkg-desc
(error "Package `%s-%s' is unavailable"
(symbol-name next-pkg)
(package-version-join next-version)))
(unless (version-list-<= next-version
(package-desc-vers (cdr pkg-desc)))
(error
"Need package `%s-%s', but only %s is available"
(symbol-name next-pkg) (package-version-join next-version)
(package-version-join (package-desc-vers (cdr pkg-desc)))))
;; Only add to the transaction if we don't already have it.
(unless (memq next-pkg package-list)
(push next-pkg package-list))
(setq package-list
(package-compute-transaction package-list
(package-desc-reqs
(cdr pkg-desc))))))))
package-list)
(defun package-read-from-string (str)
"Read a Lisp expression from STR.
Signal an error if the entire string was not used."
(let* ((read-data (read-from-string str))
(more-left
(condition-case nil
;; The call to `ignore' suppresses a compiler warning.
(progn (ignore (read-from-string
(substring str (cdr read-data))))
t)
(end-of-file nil))))
(if more-left
(error "Can't read whole string")
(car read-data))))
(defun package--read-archive-file (file)
"Re-read archive file FILE, if it exists.
Will return the data from the file, or nil if the file does not exist.
Will throw an error if the archive version is too new."
(let ((filename (expand-file-name file package-user-dir)))
(when (file-exists-p filename)
(with-temp-buffer
(insert-file-contents-literally filename)
(let ((contents (read (current-buffer))))
(if (> (car contents) package-archive-version)
(error "Package archive version %d is higher than %d"
(car contents) package-archive-version))
(cdr contents))))))
(defun package-read-all-archive-contents ()
"Re-read `archive-contents', if it exists.
If successful, set `package-archive-contents'."
(setq package-archive-contents nil)
(dolist (archive package-archives)
(package-read-archive-contents (car archive))))
(defun package-read-archive-contents (archive)
"Re-read archive contents for ARCHIVE.
If successful, set the variable `package-archive-contents'.
If the archive version is too new, signal an error."
;; Version 1 of 'archive-contents' is identical to our internal
;; representation.
(let* ((dir (concat "archives/" archive))
(contents-file (concat dir "/archive-contents"))
contents)
(when (setq contents (package--read-archive-file contents-file))
(dolist (package contents)
(package--add-to-archive-contents package archive)))))
(defun package--add-to-archive-contents (package archive)
"Add the PACKAGE from the given ARCHIVE if necessary.
Also, add the originating archive to the end of the package vector."
(let* ((name (car package))
(version (aref (cdr package) 0))
(entry (cons (car package)
(vconcat (cdr package) (vector archive))))
(existing-package (cdr (assq name package-archive-contents))))
(when (or (not existing-package)
(version-list-< (aref existing-package 0) version))
(add-to-list 'package-archive-contents entry))))
(defun package-download-transaction (package-list)
"Download and install all the packages in PACKAGE-LIST.
PACKAGE-LIST should be a list of package names (symbols).
This function assumes that all package requirements in
PACKAGE-LIST are satisfied, i.e. that PACKAGE-LIST is computed
using `package-compute-transaction'."
(dolist (elt package-list)
(let* ((desc (cdr (assq elt package-archive-contents)))
;; As an exception, if package is "held" in
;; `package-load-list', download the held version.
(hold (cadr (assq elt package-load-list)))
(v-string (or (and (stringp hold) hold)
(package-version-join (package-desc-vers desc))))
(kind (package-desc-kind desc)))
(cond
((eq kind 'tar)
(package-download-tar elt v-string))
((eq kind 'single)
(package-download-single elt v-string
(package-desc-doc desc)
(package-desc-reqs desc)))
(t
(error "Unknown package kind: %s" (symbol-name kind)))))))
;;;###autoload
(defun package-install (name)
"Install the package named NAME.
Interactively, prompt for the package name.
The package is found on one of the archives in `package-archives'."
(interactive
(list (intern (completing-read "Install package: "
(mapcar (lambda (elt)
(cons (symbol-name (car elt))
nil))
package-archive-contents)
nil t))))
(let ((pkg-desc (assq name package-archive-contents)))
(unless pkg-desc
(error "Package `%s' is not available for installation"
(symbol-name name)))
(package-download-transaction
(package-compute-transaction (list name)
(package-desc-reqs (cdr pkg-desc)))))
;; Try to activate it.
(package-initialize))
(defun package-strip-rcs-id (str)
"Strip RCS version ID from the version string STR.
If the result looks like a dotted numeric version, return it.
Otherwise return nil."
(when str
(when (string-match "\\`[ \t]*[$]Revision:[ \t]+" str)
(setq str (substring str (match-end 0))))
(condition-case nil
(if (version-to-list str)
str)
(error nil))))
(defun package-buffer-info ()
"Return a vector describing the package in the current buffer.
The vector has the form
[FILENAME REQUIRES DESCRIPTION VERSION COMMENTARY]
FILENAME is the file name, a string, sans the \".el\" extension.
REQUIRES is a requires list, or nil.
DESCRIPTION is the package description, a string.
VERSION is the version, a string.
COMMENTARY is the commentary section, a string, or nil if none.
If the buffer does not contain a conforming package, signal an
error. If there is a package, narrow the buffer to the file's
boundaries."
(goto-char (point-min))
(unless (re-search-forward "^;;; \\([^ ]*\\)\\.el --- \\(.*\\)$" nil t)
(error "Packages lacks a file header"))
(let ((file-name (match-string-no-properties 1))
(desc (match-string-no-properties 2))
(start (line-beginning-position)))
(unless (search-forward (concat ";;; " file-name ".el ends here"))
(error "Package lacks a terminating comment"))
;; Try to include a trailing newline.
(forward-line)
(narrow-to-region start (point))
(require 'lisp-mnt)
;; Use some headers we've invented to drive the process.
(let* ((requires-str (lm-header "package-requires"))
(requires (if requires-str
(package-read-from-string requires-str)))
;; Prefer Package-Version; if defined, the package author
;; probably wants us to use it. Otherwise try Version.
(pkg-version
(or (package-strip-rcs-id (lm-header "package-version"))
(package-strip-rcs-id (lm-header "version"))))
(commentary (lm-commentary)))
(unless pkg-version
(error
"Package lacks a \"Version\" or \"Package-Version\" header"))
;; Turn string version numbers into list form.
(setq requires
(mapcar
(lambda (elt)
(list (car elt)
(version-to-list (car (cdr elt)))))
requires))
(vector file-name requires desc pkg-version commentary))))
(defun package-tar-file-info (file)
"Find package information for a tar file.
FILE is the name of the tar file to examine.
The return result is a vector like `package-buffer-info'."
(let ((default-directory (file-name-directory file))
(file (file-name-nondirectory file)))
(unless (string-match "^\\(.+\\)-\\([0-9.]+\\)\\.tar$" file)
(error "Invalid package name `%s'" file))
(let* ((pkg-name (match-string-no-properties 1 file))
(pkg-version (match-string-no-properties 2 file))
;; Extract the package descriptor.
(pkg-def-contents (shell-command-to-string
;; Requires GNU tar.
(concat "tar -xOf " file " "
pkg-name "-" pkg-version "/"
pkg-name "-pkg.el")))
(pkg-def-parsed (package-read-from-string pkg-def-contents)))
(unless (eq (car pkg-def-parsed) 'define-package)
(error "No `define-package' sexp is present in `%s-pkg.el'" pkg-name))
(let ((name-str (nth 1 pkg-def-parsed))
(version-string (nth 2 pkg-def-parsed))
(docstring (nth 3 pkg-def-parsed))
(requires (nth 4 pkg-def-parsed))
(readme (shell-command-to-string
;; Requires GNU tar.
(concat "tar -xOf " file " "
pkg-name "-" pkg-version "/README"))))
(unless (equal pkg-version version-string)
(error "Package has inconsistent versions"))
(unless (equal pkg-name name-str)
(error "Package has inconsistent names"))
;; Kind of a hack.
(if (string-match ": Not found in archive" readme)
(setq readme nil))
;; Turn string version numbers into list form.
(if (eq (car requires) 'quote)
(setq requires (car (cdr requires))))
(setq requires
(mapcar (lambda (elt)
(list (car elt)
(version-to-list (cadr elt))))
requires))
(vector pkg-name requires docstring version-string readme)))))
;;;###autoload
(defun package-install-from-buffer (pkg-info type)
"Install a package from the current buffer.
When called interactively, the current buffer is assumed to be a
single .el file that follows the packaging guidelines; see info
node `(elisp)Packaging'.
When called from Lisp, PKG-INFO is a vector describing the
information, of the type returned by `package-buffer-info'; and
TYPE is the package type (either `single' or `tar')."
(interactive (list (package-buffer-info) 'single))
(save-excursion
(save-restriction
(let* ((file-name (aref pkg-info 0))
(requires (aref pkg-info 1))
(desc (if (string= (aref pkg-info 2) "")
"No description available."
(aref pkg-info 2)))
(pkg-version (aref pkg-info 3)))
;; Download and install the dependencies.
(let ((transaction (package-compute-transaction nil requires)))
(package-download-transaction transaction))
;; Install the package itself.
(cond
((eq type 'single)
(package-unpack-single file-name pkg-version desc requires))
((eq type 'tar)
(package-unpack (intern file-name) pkg-version))
(t
(error "Unknown type: %s" (symbol-name type))))
;; Try to activate it.
(package-initialize)))))
;;;###autoload
(defun package-install-file (file)
"Install a package from a file.
The file can either be a tar file or an Emacs Lisp file."
(interactive "fPackage file name: ")
(with-temp-buffer
(insert-file-contents-literally file)
(cond
((string-match "\\.el$" file)
(package-install-from-buffer (package-buffer-info) 'single))
((string-match "\\.tar$" file)
(package-install-from-buffer (package-tar-file-info file) 'tar))
(t (error "Unrecognized extension `%s'" (file-name-extension file))))))
(defun package-delete (name version)
(let ((dir (package--dir name version)))
(if (string-equal (file-name-directory dir)
(file-name-as-directory
(expand-file-name package-user-dir)))
(progn
(delete-directory dir t)
(message "Package `%s-%s' deleted." name version))
;; Don't delete "system" packages
(error "Package `%s-%s' is a system package, not deleting"
name version))))
(defun package-archive-base (name)
"Return the archive containing the package NAME."
(let ((desc (cdr (assq (intern-soft name) package-archive-contents))))
(cdr (assoc (aref desc (- (length desc) 1)) package-archives))))
(defun package--download-one-archive (archive file)
"Retrieve an archive file FILE from ARCHIVE, and cache it.
ARCHIVE should be a cons cell of the form (NAME . LOCATION),
similar to an entry in `package-alist'. Save the cached copy to
\"archives/NAME/archive-contents\" in `package-user-dir'."
(let* ((dir (expand-file-name "archives" package-user-dir))
(dir (expand-file-name (car archive) dir)))
(package--with-work-buffer (cdr archive) file
;; Read the retrieved buffer to make sure it is valid (e.g. it
;; may fetch a URL redirect page).
(when (listp (read buffer))
(make-directory dir t)
(setq buffer-file-name (expand-file-name file dir))
(let ((version-control 'never))
(save-buffer))))))
(defun package-refresh-contents ()
"Download the ELPA archive description if needed.
This informs Emacs about the latest versions of all packages, and
makes them available for download."
(interactive)
(unless (file-exists-p package-user-dir)
(make-directory package-user-dir t))
(dolist (archive package-archives)
(condition-case-no-debug nil
(package--download-one-archive archive "archive-contents")
(error (message "Failed to download `%s' archive."
(car archive)))))
(package-read-all-archive-contents))
(defvar package--initialized nil)
;;;###autoload
(defun package-initialize (&optional no-activate)
"Load Emacs Lisp packages, and activate them.
The variable `package-load-list' controls which packages to load.
If optional arg NO-ACTIVATE is non-nil, don't activate packages."
(interactive)
(setq package-alist nil
package-obsolete-alist nil)
(package-load-all-descriptors)
(package-read-all-archive-contents)
(unless no-activate
(dolist (elt package-alist)
(package-activate (car elt) (package-desc-vers (cdr elt)))))
(setq package--initialized t))
;;;; Package description buffer.
;;;###autoload
(defun describe-package (package)
"Display the full documentation of PACKAGE (a symbol)."
(interactive
(let* ((guess (function-called-at-point))
packages val)
(require 'finder-inf nil t)
;; Load the package list if necessary (but don't activate them).
(unless package--initialized
(package-initialize t))
(setq packages (append (mapcar 'car package-alist)
(mapcar 'car package-archive-contents)
(mapcar 'car package--builtins)))
(unless (memq guess packages)
(setq guess nil))
(setq packages (mapcar 'symbol-name packages))
(setq val
(completing-read (if guess
(format "Describe package (default %s): "
guess)
"Describe package: ")
packages nil t nil nil guess))
(list (if (equal val "") guess (intern val)))))
(if (or (null package) (not (symbolp package)))
(message "No package specified")
(help-setup-xref (list #'describe-package package)
(called-interactively-p 'interactive))
(with-help-window (help-buffer)
(with-current-buffer standard-output
(describe-package-1 package)))))
(defun describe-package-1 (package)
(require 'lisp-mnt)
(let ((package-name (symbol-name package))
(built-in (assq package package--builtins))
desc pkg-dir reqs version installable)
(prin1 package)
(princ " is ")
(cond
;; Loaded packages are in `package-alist'.
((setq desc (cdr (assq package package-alist)))
(setq version (package-version-join (package-desc-vers desc)))
(if (setq pkg-dir (package--dir package-name version))
(insert "an installed package.\n\n")
;; This normally does not happen.
(insert "a deleted package.\n\n")))
;; Available packages are in `package-archive-contents'.
((setq desc (cdr (assq package package-archive-contents)))
(setq version (package-version-join (package-desc-vers desc))
installable t)
(if built-in
(insert "a built-in package.\n\n")
(insert "an uninstalled package.\n\n")))
(built-in
(setq desc (cdr built-in)
version (package-version-join (package-desc-vers desc)))
(insert "a built-in package.\n\n"))
(t
(insert "an orphan package.\n\n")))
(insert " " (propertize "Status" 'font-lock-face 'bold) ": ")
(cond (pkg-dir
(insert (propertize "Installed"
'font-lock-face 'font-lock-comment-face))
(insert " in `")
;; Todo: Add button for uninstalling.
(help-insert-xref-button (file-name-as-directory pkg-dir)
'help-package-def pkg-dir)
(if built-in
(insert "',\n shadowing a "
(propertize "built-in package"
'font-lock-face 'font-lock-builtin-face)
".")
(insert "'.")))
(installable
(if built-in
(insert (propertize "Built-in." 'font-lock-face 'font-lock-builtin-face)
" Alternate version available -- ")
(insert "Available -- "))
(let ((button-text (if (display-graphic-p) "Install" "[Install]"))
(button-face (if (display-graphic-p)
'(:box (:line-width 2 :color "dark grey")
:background "light grey"
:foreground "black")
'link)))
(insert-text-button button-text 'face button-face 'follow-link t
'package-symbol package
'action 'package-install-button-action)))
(built-in
(insert (propertize "Built-in." 'font-lock-face 'font-lock-builtin-face)))
(t (insert "Deleted.")))
(insert "\n")
(and version (> (length version) 0)
(insert " "
(propertize "Version" 'font-lock-face 'bold) ": " version "\n"))
(setq reqs (if desc (package-desc-reqs desc)))
(when reqs
(insert " " (propertize "Requires" 'font-lock-face 'bold) ": ")
(let ((first t)
name vers text)
(dolist (req reqs)
(setq name (car req)
vers (cadr req)
text (format "%s-%s" (symbol-name name)
(package-version-join vers)))
(cond (first (setq first nil))
((>= (+ 2 (current-column) (length text))
(window-width))
(insert ",\n "))
(t (insert ", ")))
(help-insert-xref-button text 'help-package name))
(insert "\n")))
(insert " " (propertize "Summary" 'font-lock-face 'bold)
": " (if desc (package-desc-doc desc)) "\n\n")
(if built-in
;; For built-in packages, insert the commentary.
(let ((fn (locate-file (concat package-name ".el") load-path
load-file-rep-suffixes))
(opoint (point)))
(insert (or (lm-commentary fn) ""))
(save-excursion
(goto-char opoint)
(when (re-search-forward "^;;; Commentary:\n" nil t)
(replace-match ""))
(while (re-search-forward "^\\(;+ ?\\)" nil t)
(replace-match ""))))
(let ((readme (expand-file-name (concat package-name "-readme.txt")
package-user-dir))
readme-string)
;; For elpa packages, try downloading the commentary. If that
;; fails, try an existing readme file in `package-user-dir'.
(cond ((condition-case nil
(package--with-work-buffer (package-archive-base package)
(concat package-name "-readme.txt")
(setq buffer-file-name
(expand-file-name readme package-user-dir))
(let ((version-control 'never))
(save-buffer))
(setq readme-string (buffer-string))
t)
(error nil))
(insert readme-string))
((file-readable-p readme)
(insert-file-contents readme)
(goto-char (point-max))))))))
(defun package-install-button-action (button)
(let ((package (button-get button 'package-symbol)))
(when (y-or-n-p (format "Install package `%s'? " package))
(package-install package)
(revert-buffer nil t)
(goto-char (point-min)))))
;;;; Package menu mode.
(defvar package-menu-mode-map
(let ((map (copy-keymap special-mode-map))
(menu-map (make-sparse-keymap "Package")))
(set-keymap-parent map button-buffer-map)
(define-key map "\C-m" 'package-menu-describe-package)
(define-key map "n" 'next-line)
(define-key map "p" 'previous-line)
(define-key map "u" 'package-menu-mark-unmark)
(define-key map "\177" 'package-menu-backup-unmark)
(define-key map "d" 'package-menu-mark-delete)
(define-key map "i" 'package-menu-mark-install)
(define-key map "r" 'package-menu-refresh)
(define-key map "~" 'package-menu-mark-obsolete-for-deletion)
(define-key map "x" 'package-menu-execute)
(define-key map "h" 'package-menu-quick-help)
(define-key map "?" 'package-menu-describe-package)
(define-key map [follow-link] 'mouse-face)
(define-key map [mouse-2] 'mouse-select-window)
(define-key map [menu-bar package-menu] (cons "Package" menu-map))
(define-key menu-map [mq]
'(menu-item "Quit" quit-window
:help "Quit package selection"))
(define-key menu-map [s1] '("--"))
(define-key menu-map [mn]
'(menu-item "Next" next-line
:help "Next Line"))
(define-key menu-map [mp]
'(menu-item "Previous" previous-line
:help "Previous Line"))
(define-key menu-map [s2] '("--"))
(define-key menu-map [mu]
'(menu-item "Unmark" package-menu-mark-unmark
:help "Clear any marks on a package and move to the next line"))
(define-key menu-map [munm]
'(menu-item "Unmark backwards" package-menu-backup-unmark
:help "Back up one line and clear any marks on that package"))
(define-key menu-map [md]
'(menu-item "Mark for deletion" package-menu-mark-delete
:help "Mark a package for deletion and move to the next line"))
(define-key menu-map [mi]
'(menu-item "Mark for install" package-menu-mark-install
:help "Mark a package for installation and move to the next line"))
(define-key menu-map [s3] '("--"))
(define-key menu-map [mg]
'(menu-item "Update package list" revert-buffer
:help "Update the list of packages"))
(define-key menu-map [mr]
'(menu-item "Refresh package list" package-menu-refresh
:help "Download the ELPA archive"))
(define-key menu-map [s4] '("--"))
(define-key menu-map [mt]
'(menu-item "Mark obsolete packages" package-menu-mark-obsolete-for-deletion
:help "Mark all obsolete packages for deletion"))
(define-key menu-map [mx]
'(menu-item "Execute actions" package-menu-execute
:help "Perform all the marked actions"))
(define-key menu-map [s5] '("--"))
(define-key menu-map [mh]
'(menu-item "Help" package-menu-quick-help
:help "Show short key binding help for package-menu-mode"))
(define-key menu-map [mc]
'(menu-item "View Commentary" package-menu-view-commentary
:help "Display information about this package"))
map)
"Local keymap for `package-menu-mode' buffers.")
(defvar package-menu-sort-button-map
(let ((map (make-sparse-keymap)))
(define-key map [header-line mouse-1] 'package-menu-sort-by-column)
(define-key map [header-line mouse-2] 'package-menu-sort-by-column)
(define-key map [follow-link] 'mouse-face)
map)
"Local keymap for package menu sort buttons.")
(put 'package-menu-mode 'mode-class 'special)
(define-derived-mode package-menu-mode special-mode "Package Menu"
"Major mode for browsing a list of packages.
Letters do not insert themselves; instead, they are commands.
\\<package-menu-mode-map>
\\{package-menu-mode-map}"
(setq truncate-lines t)
(setq buffer-read-only t)
(set (make-local-variable 'revert-buffer-function) 'package-menu-revert)
(setq header-line-format
(mapconcat
(lambda (pair)
(let ((column (car pair))
(name (cdr pair)))
(concat
;; Insert a space that aligns the button properly.
(propertize " " 'display (list 'space :align-to column)
'face 'fixed-pitch)
;; Set up the column button.
(propertize name
'column-name name
'help-echo "mouse-1: sort by column"
'mouse-face 'highlight
'keymap package-menu-sort-button-map))))
;; We take a trick from buff-menu and have a dummy leading
;; space to align the header line with the beginning of the
;; text. This doesn't really work properly on Emacs 21, but
;; it is close enough.
'((0 . "")
(2 . "Package")
(20 . "Version")
(32 . "Status")
(43 . "Description"))
"")))
(defun package-menu-refresh ()
"Download the Emacs Lisp package archive.
This fetches the contents of each archive specified in
`package-archives', and then refreshes the package menu."
(interactive)
(unless (eq major-mode 'package-menu-mode)
(error "The current buffer is not a Package Menu"))
(package-refresh-contents)
(package--generate-package-list))
(defun package-menu-revert (&optional arg noconfirm)
"Update the list of packages.
This function is the `revert-buffer-function' for Package Menu
buffers. The arguments are ignored."
(interactive)
(unless (eq major-mode 'package-menu-mode)
(error "The current buffer is not a Package Menu"))
(package--generate-package-list))
(defun package-menu-describe-package ()
"Describe the package in the current line."
(interactive)
(let ((name (package-menu-get-package)))
(if name
(describe-package (intern name))
(message "No package on this line"))))
(defun package-menu-mark-internal (what)
(unless (eobp)
(let ((buffer-read-only nil))
(beginning-of-line)
(delete-char 1)
(insert what)
(forward-line))))
;; fixme numeric argument
(defun package-menu-mark-delete (num)
"Mark a package for deletion and move to the next line."
(interactive "p")
(if (string-equal (package-menu-get-status) "installed")
(package-menu-mark-internal "D")
(forward-line)))
(defun package-menu-mark-install (num)
"Mark a package for installation and move to the next line."
(interactive "p")
(if (string-equal (package-menu-get-status) "available")
(package-menu-mark-internal "I")
(forward-line)))
(defun package-menu-mark-unmark (num)
"Clear any marks on a package and move to the next line."
(interactive "p")
(package-menu-mark-internal " "))
(defun package-menu-backup-unmark ()
"Back up one line and clear any marks on that package."
(interactive)
(forward-line -1)
(package-menu-mark-internal " ")
(forward-line -1))
(defun package-menu-mark-obsolete-for-deletion ()
"Mark all obsolete packages for deletion."
(interactive)
(save-excursion
(goto-char (point-min))
(forward-line 2)
(while (not (eobp))
(if (looking-at ".*\\s obsolete\\s ")
(package-menu-mark-internal "D")
(forward-line 1)))))
(defun package-menu-quick-help ()
"Show short key binding help for package-menu-mode."
(interactive)
(message "n-ext, i-nstall, d-elete, u-nmark, x-ecute, r-efresh, h-elp"))
(define-obsolete-function-alias
'package-menu-view-commentary 'package-menu-describe-package "24.1")
;; Return the name of the package on the current line.
(defun package-menu-get-package ()
(save-excursion
(beginning-of-line)
(if (looking-at ". \\([^ \t]*\\)")
(match-string-no-properties 1))))
;; Return the version of the package on the current line.
(defun package-menu-get-version ()
(save-excursion
(beginning-of-line)
(if (looking-at ". [^ \t]*[ \t]*\\([0-9.]*\\)")
(match-string 1))))
(defun package-menu-get-status ()
(save-excursion
(if (looking-at ". [^ \t]*[ \t]*[^ \t]*[ \t]*\\([^ \t]*\\)")
(match-string 1)
"")))
(defun package-menu-execute ()
"Perform marked Package Menu actions.
Packages marked for installation are downloaded and installed;
packages marked for deletion are removed."
(interactive)
(let (install-list delete-list cmd)
(save-excursion
(goto-char (point-min))
(while (not (eobp))
(setq cmd (char-after))
(cond
((eq cmd ?\s) t)
((eq cmd ?D)
(push (cons (package-menu-get-package)
(package-menu-get-version))
delete-list))
((eq cmd ?I)
(push (package-menu-get-package) install-list)))
(forward-line)))
;; Delete packages, prompting if necessary.
(when delete-list
(if (yes-or-no-p
(if (= (length delete-list) 1)
(format "Delete package `%s-%s'? "
(caar delete-list)
(cdr (car delete-list)))
(format "Delete these %d packages (%s)? "
(length delete-list)
(mapconcat (lambda (elt)
(concat (car elt) "-" (cdr elt)))
delete-list
", "))))
(dolist (elt delete-list)
(condition-case-no-debug err
(package-delete (car elt) (cdr elt))
(error (message (cadr err)))))
(error "Aborted")))
(when install-list
(if (yes-or-no-p
(if (= (length install-list) 1)
(format "Install package `%s'? " (car install-list))
(format "Install these %d packages (%s)? "
(length install-list)
(mapconcat 'identity install-list ", "))))
(dolist (elt install-list)
(package-install (intern elt)))))
;; If we deleted anything, regenerate `package-alist'. This is done
;; automatically if we installed a package.
(and delete-list (null install-list)
(package-initialize))
(if (or delete-list install-list)
(package-menu-revert)
(message "No operations specified."))))
(defun package-print-package (package version key desc)
(let ((face
(cond ((string= key "built-in") 'font-lock-builtin-face)
((string= key "available") 'default)
((string= key "held") 'font-lock-constant-face)
((string= key "disabled") 'font-lock-warning-face)
((string= key "installed") 'font-lock-comment-face)
(t ; obsolete, but also the default.
'font-lock-warning-face))))
(insert (propertize " " 'font-lock-face face))
(insert-text-button (symbol-name package)
'face 'link
'follow-link t
'package-symbol package
'action (lambda (button)
(describe-package
(button-get button 'package-symbol))))
(indent-to 20 1)
(insert (propertize (package-version-join version) 'font-lock-face face))
(indent-to 32 1)
(insert (propertize key 'font-lock-face face))
;; FIXME: this 'when' is bogus...
(when desc
(indent-to 43 1)
(let ((opoint (point)))
(insert (propertize desc 'font-lock-face face))
(upcase-region opoint (min (point) (1+ opoint)))))
(insert "\n")))
(defun package-list-maybe-add (package version status description result)
(unless (assoc (cons package version) result)
(push (list (cons package version) status description) result))
result)
(defvar package-menu-package-list nil
"List of packages to display in the Package Menu buffer.
A value of nil means to display all packages.")
(defvar package-menu-sort-key nil
"Sort key for the current Package Menu buffer.")
(defun package--generate-package-list ()
"Populate the current Package Menu buffer."
(let ((inhibit-read-only t)
info-list name desc hold builtin)
(erase-buffer)
;; List installed packages
(dolist (elt package-alist)
(setq name (car elt))
(when (or (null package-menu-package-list)
(memq name package-menu-package-list))
(setq desc (cdr elt)
hold (cadr (assq name package-load-list)))
(setq info-list
(package-list-maybe-add
name (package-desc-vers desc)
;; FIXME: it turns out to be tricky to see if this
;; package is presently activated.
(if (stringp hold) "held" "installed")
(package-desc-doc desc)
info-list))))
;; List built-in packages
(dolist (elt package--builtins)
(setq name (car elt))
(when (and (not (eq name 'emacs)) ; Hide the `emacs' package.
(or (null package-menu-package-list)
(memq name package-menu-package-list)))
(setq desc (cdr elt))
(setq info-list
(package-list-maybe-add
name (package-desc-vers desc)
"built-in"
(package-desc-doc desc)
info-list))))
;; List available and disabled packages
(dolist (elt package-archive-contents)
(setq name (car elt)
desc (cdr elt)
hold (assq name package-load-list))
(when (or (null package-menu-package-list)
(memq name package-menu-package-list))
(setq info-list
(package-list-maybe-add name
(package-desc-vers desc)
(if (and hold (null (cadr hold)))
"disabled"
"available")
(package-desc-doc (cdr elt))
info-list))))
;; List obsolete packages
(mapc (lambda (elt)
(mapc (lambda (inner-elt)
(setq info-list
(package-list-maybe-add (car elt)
(package-desc-vers
(cdr inner-elt))
"obsolete"
(package-desc-doc
(cdr inner-elt))
info-list)))
(cdr elt)))
package-obsolete-alist)
(setq info-list
(sort info-list
(cond ((string= package-menu-sort-key "Package")
'package-menu--name-predicate)
((string= package-menu-sort-key "Version")
'package-menu--version-predicate)
((string= package-menu-sort-key "Description")
'package-menu--description-predicate)
(t ; By default, sort by package status
'package-menu--status-predicate))))
(dolist (elt info-list)
(package-print-package (car (car elt))
(cdr (car elt))
(car (cdr elt))
(car (cdr (cdr elt)))))
(goto-char (point-min))
(set-buffer-modified-p nil)
(current-buffer)))
(defun package-menu--version-predicate (left right)
(let ((vleft (or (cdr (car left)) '(0)))
(vright (or (cdr (car right)) '(0))))
(if (version-list-= vleft vright)
(package-menu--name-predicate left right)
(version-list-< vleft vright))))
(defun package-menu--status-predicate (left right)
(let ((sleft (cadr left))
(sright (cadr right)))
(cond ((string= sleft sright)
(package-menu--name-predicate left right))
((string= sleft "available") t)
((string= sright "available") nil)
((string= sleft "installed") t)
((string= sright "installed") nil)
((string= sleft "held") t)
((string= sright "held") nil)
((string= sleft "built-in") t)
((string= sright "built-in") nil)
((string= sleft "obsolete") t)
((string= sright "obsolete") nil)
(t (string< sleft sright)))))
(defun package-menu--description-predicate (left right)
(let ((sleft (car (cddr left)))
(sright (car (cddr right))))
(if (string= sleft sright)
(package-menu--name-predicate left right)
(string< sleft sright))))
(defun package-menu--name-predicate (left right)
(string< (symbol-name (caar left))
(symbol-name (caar right))))
(defun package-menu-sort-by-column (&optional e)
"Sort the package menu by the column of the mouse click E."
(interactive "e")
(let* ((pos (event-start e))
(obj (posn-object pos))
(col (if obj
(get-text-property (cdr obj) 'column-name (car obj))
(get-text-property (posn-point pos) 'column-name)))
(buf (window-buffer (posn-window (event-start e)))))
(with-current-buffer buf
(when (eq major-mode 'package-menu-mode)
(setq package-menu-sort-key col)
(package--generate-package-list)))))
(defun package--list-packages (&optional packages)
"Generate and pop to the *Packages* buffer.
Optional PACKAGES is a list of names of packages (symbols) to
list; the default is to display everything in `package-alist'."
(require 'finder-inf nil t)
(let ((buf (get-buffer-create "*Packages*")))
(with-current-buffer buf
(package-menu-mode)
(set (make-local-variable 'package-menu-package-list) packages)
(set (make-local-variable 'package-menu-sort-key) nil)
(package--generate-package-list))
;; The package menu buffer has keybindings. If the user types
;; `M-x list-packages', that suggests it should become current.
(switch-to-buffer buf)))
;;;###autoload
(defun list-packages ()
"Display a list of packages.
Fetches the updated list of packages before displaying.
The list is displayed in a buffer named `*Packages*'."
(interactive)
;; Initialize the package system if necessary.
(unless package--initialized
(package-initialize t))
(package-refresh-contents)
(package--list-packages))
;;;###autoload
(defalias 'package-list-packages 'list-packages)
(defun package-list-packages-no-fetch ()
"Display a list of packages.
Does not fetch the updated list of packages before displaying.
The list is displayed in a buffer named `*Packages*'."
(interactive)
(package--list-packages))
(provide 'package)
;;; package.el ends here
| {
"pile_set_name": "Github"
} |
import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
export default new Router({
routes: [
//首页
{
path: "/",
redirect: "/index"
},
{
path: "/index",
name: "index",
component: r =>
require.ensure([], () => r(require("@/pages/home/index"), "index")),
meta: {
keepAlive: true
}
},
//登录页
{
path: "/login",
name: "login",
component: r =>
require.ensure([], () => r(require("@/pages/login/index"), "login"))
},
//用户信息
{
path: "/userInfo",
name: "userInfo",
component: r =>
require.ensure([], () =>
r(require("@/pages/userInfo/index"), "userInfo")
)
},
//私人Fm
{
path: "/personalFm",
name: "personalFm",
component: r =>
require.ensure([], () =>
r(require("@/pages/tabsPage/personalFm/index"), "personalFm")
),
meta: {
needLogin: true
}
},
//每日推荐
{
path: "/recomSong",
name: "recomSong",
component: r =>
require.ensure([], () =>
r(require("@/pages/tabsPage/recomSong/index"), "recomSong")
),
meta: {
needLogin: true
}
},
//我的音乐
{
path: "/myMusic/index",
name: "myMusic",
component: r =>
require.ensure([], () =>
r(require("@/pages/tabsPage/myMusic/index"), "myMusic")
),
meta: {
needLogin: true
}
},
//歌单详情歌曲列表
{
path: "/myMusic/playList",
name: "myMusicPlayList",
component: r =>
require.ensure([], () =>
r(require("@/pages/tabsPage/myMusic/musicDetail"), "myMusic")
),
meta: {
needLogin: true
}
},
//排行榜
{
path: "/topList",
name: "topList",
component: r =>
require.ensure([], () =>
r(require("@/pages/tabsPage/topList/index"), "topList")
),
meta: {
needLogin: true
}
},
{
path: "/detail",
name: "detail",
component: r =>
require.ensure([], () => r(require("@/pages/detail/index"), "detail"))
}
]
});
| {
"pile_set_name": "Github"
} |
#pragma once
#include <cstdint>
#include "PluginBase.h"
#include "eAudioFileType.h"
struct tUserTracksInfo
{
std::uint32_t startUfilesPath;
std::uint32_t pathLength;
eAudioFileType fileType;
};
VALIDATE_SIZE(tUserTracksInfo, 0xc);
| {
"pile_set_name": "Github"
} |
#include "../../src/gui/painting/qrgb.h"
| {
"pile_set_name": "Github"
} |
/*
* RapCAD - Rapid prototyping CAD IDE (www.rapcad.org)
* Copyright (C) 2010-2020 Giles Bathgate
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef NORMFUNCTION_H
#define NORMFUNCTION_H
#include "function.h"
class NormFunction : public Function
{
Q_DECLARE_TR_FUNCTIONS(NormFunction)
public:
NormFunction();
Value* evaluate(const Context&) const override;
};
#endif // NORMFUNCTION_H
| {
"pile_set_name": "Github"
} |
using System;
using RGB.NET.Core;
namespace RGB.NET.Devices.Razer
{
/// <inheritdoc />
/// <summary>
/// Represents a generic information for a <see cref="T:RGB.NET.Devices.Razer.RazerMousepadRGBDevice" />.
/// </summary>
public class RazerMousepadRGBDeviceInfo : RazerRGBDeviceInfo
{
#region Constructors
/// <inheritdoc />
/// <summary>
/// Internal constructor of managed <see cref="T:RGB.NET.Devices.Razer.RazerMousepadRGBDeviceInfo" />.
/// </summary>
/// <param name="deviceId">The Id of the <see cref="IRGBDevice"/>.</param>
/// <param name="model">The model of the <see cref="IRGBDevice"/>.</param>
internal RazerMousepadRGBDeviceInfo(Guid deviceId, string model)
: base(deviceId, RGBDeviceType.Mousepad, model)
{ }
#endregion
}
}
| {
"pile_set_name": "Github"
} |
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2014 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SPARSESPARSEPRODUCTWITHPRUNING_H
#define EIGEN_SPARSESPARSEPRODUCTWITHPRUNING_H
namespace Eigen {
namespace internal {
// perform a pseudo in-place sparse * sparse product assuming all matrices are col major
template<typename Lhs, typename Rhs, typename ResultType>
static void sparse_sparse_product_with_pruning_impl(const Lhs& lhs, const Rhs& rhs, ResultType& res, const typename ResultType::RealScalar& tolerance)
{
// return sparse_sparse_product_with_pruning_impl2(lhs,rhs,res);
typedef typename remove_all<Rhs>::type::Scalar RhsScalar;
typedef typename remove_all<ResultType>::type::Scalar ResScalar;
typedef typename remove_all<Lhs>::type::StorageIndex StorageIndex;
// make sure to call innerSize/outerSize since we fake the storage order.
Index rows = lhs.innerSize();
Index cols = rhs.outerSize();
//Index size = lhs.outerSize();
eigen_assert(lhs.outerSize() == rhs.innerSize());
// allocate a temporary buffer
AmbiVector<ResScalar,StorageIndex> tempVector(rows);
// mimics a resizeByInnerOuter:
if(ResultType::IsRowMajor)
res.resize(cols, rows);
else
res.resize(rows, cols);
evaluator<Lhs> lhsEval(lhs);
evaluator<Rhs> rhsEval(rhs);
// estimate the number of non zero entries
// given a rhs column containing Y non zeros, we assume that the respective Y columns
// of the lhs differs in average of one non zeros, thus the number of non zeros for
// the product of a rhs column with the lhs is X+Y where X is the average number of non zero
// per column of the lhs.
// Therefore, we have nnz(lhs*rhs) = nnz(lhs) + nnz(rhs)
Index estimated_nnz_prod = lhsEval.nonZerosEstimate() + rhsEval.nonZerosEstimate();
res.reserve(estimated_nnz_prod);
double ratioColRes = double(estimated_nnz_prod)/(double(lhs.rows())*double(rhs.cols()));
for (Index j=0; j<cols; ++j)
{
// FIXME:
//double ratioColRes = (double(rhs.innerVector(j).nonZeros()) + double(lhs.nonZeros())/double(lhs.cols()))/double(lhs.rows());
// let's do a more accurate determination of the nnz ratio for the current column j of res
tempVector.init(ratioColRes);
tempVector.setZero();
for (typename evaluator<Rhs>::InnerIterator rhsIt(rhsEval, j); rhsIt; ++rhsIt)
{
// FIXME should be written like this: tmp += rhsIt.value() * lhs.col(rhsIt.index())
tempVector.restart();
RhsScalar x = rhsIt.value();
for (typename evaluator<Lhs>::InnerIterator lhsIt(lhsEval, rhsIt.index()); lhsIt; ++lhsIt)
{
tempVector.coeffRef(lhsIt.index()) += lhsIt.value() * x;
}
}
res.startVec(j);
for (typename AmbiVector<ResScalar,StorageIndex>::Iterator it(tempVector,tolerance); it; ++it)
res.insertBackByOuterInner(j,it.index()) = it.value();
}
res.finalize();
}
template<typename Lhs, typename Rhs, typename ResultType,
int LhsStorageOrder = traits<Lhs>::Flags&RowMajorBit,
int RhsStorageOrder = traits<Rhs>::Flags&RowMajorBit,
int ResStorageOrder = traits<ResultType>::Flags&RowMajorBit>
struct sparse_sparse_product_with_pruning_selector;
template<typename Lhs, typename Rhs, typename ResultType>
struct sparse_sparse_product_with_pruning_selector<Lhs,Rhs,ResultType,ColMajor,ColMajor,ColMajor>
{
typedef typename ResultType::RealScalar RealScalar;
static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res, const RealScalar& tolerance)
{
typename remove_all<ResultType>::type _res(res.rows(), res.cols());
internal::sparse_sparse_product_with_pruning_impl<Lhs,Rhs,ResultType>(lhs, rhs, _res, tolerance);
res.swap(_res);
}
};
template<typename Lhs, typename Rhs, typename ResultType>
struct sparse_sparse_product_with_pruning_selector<Lhs,Rhs,ResultType,ColMajor,ColMajor,RowMajor>
{
typedef typename ResultType::RealScalar RealScalar;
static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res, const RealScalar& tolerance)
{
// we need a col-major matrix to hold the result
typedef SparseMatrix<typename ResultType::Scalar,ColMajor,typename ResultType::StorageIndex> SparseTemporaryType;
SparseTemporaryType _res(res.rows(), res.cols());
internal::sparse_sparse_product_with_pruning_impl<Lhs,Rhs,SparseTemporaryType>(lhs, rhs, _res, tolerance);
res = _res;
}
};
template<typename Lhs, typename Rhs, typename ResultType>
struct sparse_sparse_product_with_pruning_selector<Lhs,Rhs,ResultType,RowMajor,RowMajor,RowMajor>
{
typedef typename ResultType::RealScalar RealScalar;
static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res, const RealScalar& tolerance)
{
// let's transpose the product to get a column x column product
typename remove_all<ResultType>::type _res(res.rows(), res.cols());
internal::sparse_sparse_product_with_pruning_impl<Rhs,Lhs,ResultType>(rhs, lhs, _res, tolerance);
res.swap(_res);
}
};
template<typename Lhs, typename Rhs, typename ResultType>
struct sparse_sparse_product_with_pruning_selector<Lhs,Rhs,ResultType,RowMajor,RowMajor,ColMajor>
{
typedef typename ResultType::RealScalar RealScalar;
static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res, const RealScalar& tolerance)
{
typedef SparseMatrix<typename Lhs::Scalar,ColMajor,typename Lhs::StorageIndex> ColMajorMatrixLhs;
typedef SparseMatrix<typename Rhs::Scalar,ColMajor,typename Lhs::StorageIndex> ColMajorMatrixRhs;
ColMajorMatrixLhs colLhs(lhs);
ColMajorMatrixRhs colRhs(rhs);
internal::sparse_sparse_product_with_pruning_impl<ColMajorMatrixLhs,ColMajorMatrixRhs,ResultType>(colLhs, colRhs, res, tolerance);
// let's transpose the product to get a column x column product
// typedef SparseMatrix<typename ResultType::Scalar> SparseTemporaryType;
// SparseTemporaryType _res(res.cols(), res.rows());
// sparse_sparse_product_with_pruning_impl<Rhs,Lhs,SparseTemporaryType>(rhs, lhs, _res);
// res = _res.transpose();
}
};
template<typename Lhs, typename Rhs, typename ResultType>
struct sparse_sparse_product_with_pruning_selector<Lhs,Rhs,ResultType,ColMajor,RowMajor,RowMajor>
{
typedef typename ResultType::RealScalar RealScalar;
static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res, const RealScalar& tolerance)
{
typedef SparseMatrix<typename Lhs::Scalar,RowMajor,typename Lhs::StorageIndex> RowMajorMatrixLhs;
RowMajorMatrixLhs rowLhs(lhs);
sparse_sparse_product_with_pruning_selector<RowMajorMatrixLhs,Rhs,ResultType,RowMajor,RowMajor>(rowLhs,rhs,res,tolerance);
}
};
template<typename Lhs, typename Rhs, typename ResultType>
struct sparse_sparse_product_with_pruning_selector<Lhs,Rhs,ResultType,RowMajor,ColMajor,RowMajor>
{
typedef typename ResultType::RealScalar RealScalar;
static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res, const RealScalar& tolerance)
{
typedef SparseMatrix<typename Rhs::Scalar,RowMajor,typename Lhs::StorageIndex> RowMajorMatrixRhs;
RowMajorMatrixRhs rowRhs(rhs);
sparse_sparse_product_with_pruning_selector<Lhs,RowMajorMatrixRhs,ResultType,RowMajor,RowMajor,RowMajor>(lhs,rowRhs,res,tolerance);
}
};
template<typename Lhs, typename Rhs, typename ResultType>
struct sparse_sparse_product_with_pruning_selector<Lhs,Rhs,ResultType,ColMajor,RowMajor,ColMajor>
{
typedef typename ResultType::RealScalar RealScalar;
static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res, const RealScalar& tolerance)
{
typedef SparseMatrix<typename Rhs::Scalar,ColMajor,typename Lhs::StorageIndex> ColMajorMatrixRhs;
ColMajorMatrixRhs colRhs(rhs);
internal::sparse_sparse_product_with_pruning_impl<Lhs,ColMajorMatrixRhs,ResultType>(lhs, colRhs, res, tolerance);
}
};
template<typename Lhs, typename Rhs, typename ResultType>
struct sparse_sparse_product_with_pruning_selector<Lhs,Rhs,ResultType,RowMajor,ColMajor,ColMajor>
{
typedef typename ResultType::RealScalar RealScalar;
static void run(const Lhs& lhs, const Rhs& rhs, ResultType& res, const RealScalar& tolerance)
{
typedef SparseMatrix<typename Lhs::Scalar,ColMajor,typename Lhs::StorageIndex> ColMajorMatrixLhs;
ColMajorMatrixLhs colLhs(lhs);
internal::sparse_sparse_product_with_pruning_impl<ColMajorMatrixLhs,Rhs,ResultType>(colLhs, rhs, res, tolerance);
}
};
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_SPARSESPARSEPRODUCTWITHPRUNING_H
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
"""
pygments.styles.friendly
~~~~~~~~~~~~~~~~~~~~~~~~
A modern style based on the VIM pyte theme.
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Generic, Whitespace
class FriendlyStyle(Style):
"""
A modern style based on the VIM pyte theme.
"""
background_color = "#f0f0f0"
default_style = ""
styles = {
Whitespace: "#bbbbbb",
Comment: "italic #60a0b0",
Comment.Preproc: "noitalic #007020",
Comment.Special: "noitalic bg:#fff0f0",
Keyword: "bold #007020",
Keyword.Pseudo: "nobold",
Keyword.Type: "nobold #902000",
Operator: "#666666",
Operator.Word: "bold #007020",
Name.Builtin: "#007020",
Name.Function: "#06287e",
Name.Class: "bold #0e84b5",
Name.Namespace: "bold #0e84b5",
Name.Exception: "#007020",
Name.Variable: "#bb60d5",
Name.Constant: "#60add5",
Name.Label: "bold #002070",
Name.Entity: "bold #d55537",
Name.Attribute: "#4070a0",
Name.Tag: "bold #062873",
Name.Decorator: "bold #555555",
String: "#4070a0",
String.Doc: "italic",
String.Interpol: "italic #70a0d0",
String.Escape: "bold #4070a0",
String.Regex: "#235388",
String.Symbol: "#517918",
String.Other: "#c65d09",
Number: "#40a070",
Generic.Heading: "bold #000080",
Generic.Subheading: "bold #800080",
Generic.Deleted: "#A00000",
Generic.Inserted: "#00A000",
Generic.Error: "#FF0000",
Generic.Emph: "italic",
Generic.Strong: "bold",
Generic.Prompt: "bold #c65d09",
Generic.Output: "#888",
Generic.Traceback: "#04D",
Error: "border:#FF0000"
}
| {
"pile_set_name": "Github"
} |
=begin pod :kind("Type") :subkind("class") :category("exception")
=TITLE class X::Placeholder::Mainline
=SUBTITLE Compilation error due to a placeholder in the mainline
class X::Placeholder::Mainline is X::Placeholder::Block { }
Thrown when a placeholder variable is used in the mainline, i.e. outside of
any explicit block.
For example
=for code :skip-test<compile time error>
$^x;
dies with
=for code :lang<text>
===SORRY!===
Cannot use placeholder parameter $^x outside of a sub or block
Note that this error can also occur when you think something is a block,
but it really is a L«postcircumfix:<{ }>|/routine/{ }», for example
=for code :skip-test<compile time error>
my %h;
say %h{ $^x };
# ^^^^^^^ not a block, so $^x is part of the mainline
=end pod
| {
"pile_set_name": "Github"
} |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Requests\MethodRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The type WorkbookFunctionsExactRequest.
/// </summary>
public partial class WorkbookFunctionsExactRequest : BaseRequest, IWorkbookFunctionsExactRequest
{
/// <summary>
/// Constructs a new WorkbookFunctionsExactRequest.
/// </summary>
public WorkbookFunctionsExactRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
this.ContentType = "application/json";
this.RequestBody = new WorkbookFunctionsExactRequestBody();
}
/// <summary>
/// Gets the request body.
/// </summary>
public WorkbookFunctionsExactRequestBody RequestBody { get; private set; }
/// <summary>
/// Issues the POST request.
/// </summary>
public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync()
{
return this.PostAsync(CancellationToken.None);
}
/// <summary>
/// Issues the POST request.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync(
CancellationToken cancellationToken)
{
this.Method = "POST";
return this.SendAsync<WorkbookFunctionResult>(this.RequestBody, cancellationToken);
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookFunctionsExactRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookFunctionsExactRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is autogenerated by
// java_cpp_enum.py
// From
// ../../base/android/library_loader/library_load_from_apk_status_codes.h
package org.chromium.base.library_loader;
import android.support.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@IntDef({
LibraryLoadFromApkStatusCodes.UNKNOWN, LibraryLoadFromApkStatusCodes.NOT_SUPPORTED_OBSOLETE,
LibraryLoadFromApkStatusCodes.SUPPORTED_OBSOLETE, LibraryLoadFromApkStatusCodes.SUCCESSFUL,
LibraryLoadFromApkStatusCodes.USED_UNPACK_LIBRARY_FALLBACK,
LibraryLoadFromApkStatusCodes.USED_NO_MAP_EXEC_SUPPORT_FALLBACK_OBSOLETE,
LibraryLoadFromApkStatusCodes.MAX
})
@Retention(RetentionPolicy.SOURCE)
public @interface LibraryLoadFromApkStatusCodes {
/**
* The loader was unable to determine whether the functionality is supported.
*/
int UNKNOWN = 0;
/**
* The device does not support loading a library directly from the APK file (obsolete).
*/
int NOT_SUPPORTED_OBSOLETE = 1;
/**
* The device supports loading a library directly from the APK file. (obsolete).
*/
int SUPPORTED_OBSOLETE = 2;
/**
* The Chromium library was successfully loaded directly from the APK file.
*/
int SUCCESSFUL = 3;
/**
* The Chromium library was successfully loaded using the unpack library fallback because it was
* compressed or not page aligned in the APK file.
*/
int USED_UNPACK_LIBRARY_FALLBACK = 4;
/**
* The Chromium library was successfully loaded using the no map executable support fallback
* (obsolete).
*/
int USED_NO_MAP_EXEC_SUPPORT_FALLBACK_OBSOLETE = 5;
/**
* End sentinel.
*/
int MAX = 6;
}
| {
"pile_set_name": "Github"
} |
package pxb.android.axmlLP;
import com.googlecode.dex2jar.reader.io.ArrayDataIn;
import com.googlecode.dex2jar.reader.io.DataIn;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import pxb.android.axmlLP.AxmlVisitor.NodeVisitor;
public class AxmlReader {
static final int CHUNK_AXML_FILE = 524291;
static final int CHUNK_RESOURCEIDS = 524672;
static final int CHUNK_STRINGS = 1835009;
static final int CHUNK_XML_END_NAMESPACE = 1048833;
static final int CHUNK_XML_END_TAG = 1048835;
static final int CHUNK_XML_START_NAMESPACE = 1048832;
static final int CHUNK_XML_START_TAG = 1048834;
static final int CHUNK_XML_TEXT = 1048836;
public static final NodeVisitor EMPTY_VISITOR = new NodeVisitor() {
public NodeVisitor child(String ns, String name) {
return AxmlReader.EMPTY_VISITOR;
}
};
static final int UTF8_FLAG = 256;
private DataIn in;
private List<Integer> resourceIds;
private StringItems stringItems;
public AxmlReader(byte[] data) {
this(ArrayDataIn.le(data));
}
public AxmlReader(DataIn in) {
this.resourceIds = new ArrayList();
this.stringItems = new StringItems();
this.in = in;
}
public void accept(AxmlVisitor documentVisitor) throws IOException {
DataIn in = this.in;
if (in.readIntx() != CHUNK_AXML_FILE) {
throw new RuntimeException();
}
NodeVisitor root;
int fileSize = in.readIntx();
if (documentVisitor == null) {
root = EMPTY_VISITOR;
} else {
final AxmlVisitor axmlVisitor = documentVisitor;
NodeVisitor anonymousClass2 = new NodeVisitor() {
public NodeVisitor child(String ns, String name) {
return axmlVisitor.first(ns, name);
}
};
}
NodeVisitor tos = root;
Stack<NodeVisitor> nvs = new Stack();
nvs.push(root);
for (int p = in.getCurrentPosition(); p < fileSize; p = in.getCurrentPosition()) {
int type = in.readIntx();
int size = in.readIntx();
int i;
int lineNumber;
int nameIdx;
switch (type) {
case CHUNK_RESOURCEIDS /*524672*/:
int count = (size / 4) - 2;
for (i = 0; i < count; i++) {
this.resourceIds.add(Integer.valueOf(in.readIntx()));
}
break;
case CHUNK_XML_START_NAMESPACE /*1048832*/:
if (documentVisitor != null) {
lineNumber = in.readIntx();
in.skip(4);
documentVisitor.ns(((StringItem) this.stringItems.get(in.readIntx())).data, ((StringItem) this.stringItems.get(in.readIntx())).data, lineNumber);
break;
}
in.skip(16);
break;
case CHUNK_XML_END_NAMESPACE /*1048833*/:
in.skip(size - 8);
break;
case CHUNK_XML_START_TAG /*1048834*/:
lineNumber = in.readIntx();
in.skip(4);
int nsIdx = in.readIntx();
nameIdx = in.readIntx();
if (in.readIntx() == 1310740) {
tos = tos.child(nsIdx >= 0 ? ((StringItem) this.stringItems.get(nsIdx)).data : null, ((StringItem) this.stringItems.get(nameIdx)).data);
if (tos == null) {
tos = EMPTY_VISITOR;
}
nvs.push(tos);
tos.line(lineNumber);
int attributeCount = in.readUShortx();
in.skip(6);
if (tos == EMPTY_VISITOR) {
in.skip(20);
break;
}
for (i = 0; i < attributeCount; i++) {
Object value;
nsIdx = in.readIntx();
nameIdx = in.readIntx();
in.skip(4);
int aValueType = in.readIntx() >>> 24;
int aValue = in.readIntx();
String name = ((StringItem) this.stringItems.get(nameIdx)).data;
String ns = nsIdx >= 0 ? ((StringItem) this.stringItems.get(nsIdx)).data : null;
switch (aValueType) {
case AxmlVisitor.TYPE_STRING /*3*/:
value = ((StringItem) this.stringItems.get(aValue)).data;
break;
case AxmlVisitor.TYPE_INT_BOOLEAN /*18*/:
value = Boolean.valueOf(aValue != 0);
break;
default:
value = Integer.valueOf(aValue);
break;
}
tos.attr(ns, name, nameIdx < this.resourceIds.size() ? ((Integer) this.resourceIds.get(nameIdx)).intValue() : -1, aValueType, value);
}
break;
}
throw new RuntimeException();
case CHUNK_XML_END_TAG /*1048835*/:
in.skip(size - 8);
tos.end();
nvs.pop();
tos = (NodeVisitor) nvs.peek();
break;
case CHUNK_XML_TEXT /*1048836*/:
if (tos != EMPTY_VISITOR) {
lineNumber = in.readIntx();
in.skip(4);
nameIdx = in.readIntx();
in.skip(8);
tos.text(lineNumber, ((StringItem) this.stringItems.get(nameIdx)).data);
break;
}
in.skip(20);
break;
case CHUNK_STRINGS /*1835009*/:
this.stringItems.read(in, size);
break;
default:
throw new RuntimeException();
}
in.move(p + size);
}
}
}
| {
"pile_set_name": "Github"
} |
#include "depthwise_separable_convolution_kernels.hpp"
namespace uTensor {
namespace TFLM {
DEFINE_ERROR(qDwsMismatchedDimensionsError);
DEFINE_ERROR(InvalidQDwsActivationRangeError);
DEFINE_ERROR(InvalidQDwsOutputDepthError);
TfLitePaddingValues ComputePaddingHeightWidth(
int stride_height, int stride_width, int dilation_rate_height,
int dilation_rate_width, int in_height, int in_width, int filter_height,
int filter_width, TfLitePadding padding, int* out_height, int* out_width) {
*out_width = ComputeOutSize(padding, in_width, filter_width, stride_width,
dilation_rate_width);
*out_height = ComputeOutSize(padding, in_height, filter_height, stride_height,
dilation_rate_height);
TfLitePaddingValues padding_values;
int offset = 0;
padding_values.height =
ComputePaddingWithOffset(stride_height, dilation_rate_height, in_height,
filter_height, *out_height, &offset);
padding_values.height_offset = offset;
padding_values.width =
ComputePaddingWithOffset(stride_width, dilation_rate_width, in_width,
filter_width, *out_width, &offset);
padding_values.width_offset = offset;
return padding_values;
}
void ComputePaddingHeightWidth(int stride_height, int stride_width,
int dilation_rate_height,
int dilation_rate_width, int in_height,
int in_width, int filter_height,
int filter_width, int32_t* padding_height,
int32_t* padding_width, TfLitePadding padding,
int* out_height, int* out_width) {
*out_width = ComputeOutSize(padding, in_width, filter_width, stride_width,
dilation_rate_width);
*out_height = ComputeOutSize(padding, in_height, filter_height, stride_height,
dilation_rate_height);
TfLitePaddingValues padding_values;
int offset = 0;
*padding_height =
ComputePaddingWithOffset(stride_height, dilation_rate_height, in_height,
filter_height, *out_height, &offset);
// padding_values.height_offset = offset;
*padding_width =
ComputePaddingWithOffset(stride_width, dilation_rate_width, in_width,
filter_width, *out_width, &offset);
// padding_values.width_offset = offset;
// return padding_values;
}
uint16_t MatchingDim(TensorShape s0, uint8_t i0, TensorShape s1, uint8_t i1) {
if (!(s0[i0] == s1[i1])) {
Context::get_default_context()->throwError(
new qDwsMismatchedDimensionsError);
}
return s0[i0];
}
void DepthwiseConvPerChannel(const DepthwiseParams& params,
const int32_t* output_multiplier,
const int32_t* output_shift, Tensor& input,
Tensor& filter, Tensor& bias, Tensor& output) {
// Get parameters.
// TODO(b/141565753): Re-introduce ScopedProfilingLabel on Micro.
const int stride_width = params.stride_width;
const int stride_height = params.stride_height;
const int dilation_width_factor = params.dilation_width_factor;
const int dilation_height_factor = params.dilation_height_factor;
const int pad_width = params.padding_values.width;
const int pad_height = params.padding_values.height;
const int depth_multiplier = params.depth_multiplier;
const int32_t input_offset = params.input_offset;
const int32_t output_offset = params.output_offset;
const int32_t output_activation_min = params.quantized_activation_min;
const int32_t output_activation_max = params.quantized_activation_max;
// Check dimensions of the tensors.
TensorShape input_shape = input->get_shape();
TensorShape filter_shape = filter->get_shape();
TensorShape output_shape = output->get_shape();
if (!(input_shape.num_dims() == 4)) {
Context::get_default_context()->throwError(
new InvalidTensorDimensionsError);
}
if (!(filter_shape.num_dims() == 4)) {
Context::get_default_context()->throwError(
new InvalidTensorDimensionsError);
}
if (!(output_shape.num_dims() == 4)) {
Context::get_default_context()->throwError(
new InvalidTensorDimensionsError);
}
if (!(output_activation_min < output_activation_max)) {
Context::get_default_context()->throwError(
new InvalidQDwsActivationRangeError);
}
const int batches = MatchingDim(input_shape, 0, output_shape, 0);
const int output_depth = MatchingDim(filter_shape, 3, output_shape, 3);
const int input_height = input_shape[1];
const int input_width = input_shape[2];
const int input_depth = input_shape[3];
const int filter_height = filter_shape[1];
const int filter_width = filter_shape[2];
const int output_height = output_shape[1];
const int output_width = output_shape[2];
if (!(output_depth == input_depth * depth_multiplier)) {
Context::get_default_context()->throwError(new InvalidQDwsOutputDepthError);
}
if (!(bias->get_shape().get_linear_size() == (uint16_t)output_depth)) {
Context::get_default_context()->throwError(new InvalidQDwsOutputDepthError);
}
for (int batch = 0; batch < batches; ++batch) {
for (int out_y = 0; out_y < output_height; ++out_y) {
for (int out_x = 0; out_x < output_width; ++out_x) {
for (int in_channel = 0; in_channel < input_depth; ++in_channel) {
for (int m = 0; m < depth_multiplier; ++m) {
const int output_channel = m + in_channel * depth_multiplier;
const int in_x_origin = (out_x * stride_width) - pad_width;
const int in_y_origin = (out_y * stride_height) - pad_height;
int32_t acc = 0;
for (int filter_y = 0; filter_y < filter_height; ++filter_y) {
for (int filter_x = 0; filter_x < filter_width; ++filter_x) {
const int in_x = in_x_origin + dilation_width_factor * filter_x;
const int in_y =
in_y_origin + dilation_height_factor * filter_y;
// Zero padding by omitting the areas outside the image.
const bool is_point_inside_image =
(in_x >= 0) && (in_x < input_width) && (in_y >= 0) &&
(in_y < input_height);
if (is_point_inside_image) {
// int32_t input_val = input_data[Offset(input_shape, batch,
// in_y,
// in_x, in_channel)];
int32_t input_val =
static_cast<int8_t>(input(batch, in_y, in_x, in_channel));
// int32_t filter_val = filter_data[Offset(
// filter_shape, 0, filter_y, filter_x, output_channel)];
int32_t filter_val = static_cast<int8_t>(
filter(0, filter_y, filter_x, output_channel));
// Accumulate with 32 bits accumulator.
// In the nudging process during model quantization, we force
// real value of 0.0 be represented by a quantized value. This
// guarantees that the input_offset is a int8, even though it
// is represented using int32.
// int32 += int8 * (int8 - int8) so the highest value we can
// get from each accumulation is [-127, 127] * ([-128, 127] -
// [-128, 127]), which is [-32512, 32512]. log2(32512)
// = 14.98, which means we can accumulate at least 2^16
// multiplications without overflow. The accumulator is
// applied to a filter so the accumulation logic will hold as
// long as the filter size (filter_y * filter_x * in_channel)
// does not exceed 2^16, which is the case in all the models
// we have seen so far.
// TODO(jianlijianli): Add a check to make sure the
// accumulator depth is smaller than 2^16.
acc += filter_val * (input_val + input_offset);
}
}
}
// assuming bias data will always be provided
acc += static_cast<int32_t>(bias(output_channel));
acc = MultiplyByQuantizedMultiplier(
acc, output_multiplier[output_channel],
output_shift[output_channel]);
acc += output_offset;
acc = std::max(acc, output_activation_min);
acc = std::min(acc, output_activation_max);
output(batch, out_y, out_x, output_channel) =
static_cast<int8_t>(acc);
}
}
}
}
}
}
} // namespace TFLM
} // namespace uTensor
| {
"pile_set_name": "Github"
} |
<Application
xmlns="http://schemas.wsick.com/fayde"
xmlns:x="http://schemas.wsick.com/fayde/x"
ThemeName="Metro">
<Grid x:Name="LayoutRoot" ShowGridLines="true">
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="200" />
<RowDefinition Height="200" />
<RowDefinition Height="200" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150" />
<ColumnDefinition Width="300" />
<ColumnDefinition Width="300" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="Spread Method" HorizontalAlignment="Center" VerticalAlignment="Center" />
<TextBlock Grid.Column="1" Text="Linear" HorizontalAlignment="Center" VerticalAlignment="Center" />
<TextBlock Grid.Column="2" Text="Radial" HorizontalAlignment="Center" VerticalAlignment="Center" />
<TextBlock Grid.Row="1" Grid.Column="0" Text="Pad" VerticalAlignment="Center" />
<Grid Grid.Row="1" Grid.Column="1" Margin="4">
<Grid.Background>
<LinearGradientBrush SpreadMethod="Pad" StartPoint="0.25,0" EndPoint="0.75,0">
<GradientStop Offset="0.2" Color="Red" />
<GradientStop Offset="0.3" Color="Orange" />
<GradientStop Offset="0.4" Color="Yellow" />
<GradientStop Offset="0.5" Color="Green" />
<GradientStop Offset="0.6" Color="Blue" />
<GradientStop Offset="0.7" Color="Purple" />
</LinearGradientBrush>
</Grid.Background>
</Grid>
<Grid Grid.Row="1" Grid.Column="2" Margin="4">
<Grid.Background>
<RadialGradientBrush SpreadMethod="Pad" RadiusX="0.2" RadiusY="0.2" GradientOrigin="0.4,0.4">
<GradientStop Offset="0.2" Color="Red" />
<GradientStop Offset="0.3" Color="Orange" />
<GradientStop Offset="0.4" Color="Yellow" />
<GradientStop Offset="0.5" Color="Green" />
<GradientStop Offset="0.6" Color="Blue" />
<GradientStop Offset="0.7" Color="Purple" />
</RadialGradientBrush>
</Grid.Background>
</Grid>
<TextBlock Grid.Row="2" Grid.Column="0" Text="Repeat" VerticalAlignment="Center" />
<Grid Grid.Row="2" Grid.Column="1" Margin="4">
<Grid.Background>
<LinearGradientBrush SpreadMethod="Repeat" StartPoint="0.25,0" EndPoint="0.75,0">
<GradientStop Offset="0.2" Color="Red" />
<GradientStop Offset="0.3" Color="Orange" />
<GradientStop Offset="0.4" Color="Yellow" />
<GradientStop Offset="0.5" Color="Green" />
<GradientStop Offset="0.6" Color="Blue" />
<GradientStop Offset="0.7" Color="Purple" />
</LinearGradientBrush>
</Grid.Background>
</Grid>
<Grid Grid.Row="2" Grid.Column="2" Margin="4">
<Grid.Background>
<RadialGradientBrush SpreadMethod="Repeat" RadiusX="0.2" RadiusY="0.2" GradientOrigin="0.4,0.4">
<GradientStop Offset="0.2" Color="Red" />
<GradientStop Offset="0.3" Color="Orange" />
<GradientStop Offset="0.4" Color="Yellow" />
<GradientStop Offset="0.5" Color="Green" />
<GradientStop Offset="0.6" Color="Blue" />
<GradientStop Offset="0.7" Color="Purple" />
</RadialGradientBrush>
</Grid.Background>
</Grid>
<TextBlock Grid.Row="3" Grid.Column="0" Text="Reflect" VerticalAlignment="Center" />
<Grid Grid.Row="3" Grid.Column="1" Margin="4">
<Grid.Background>
<LinearGradientBrush SpreadMethod="Reflect" StartPoint="0.25,0" EndPoint="0.75,0">
<GradientStop Offset="0.2" Color="Red" />
<GradientStop Offset="0.3" Color="Orange" />
<GradientStop Offset="0.4" Color="Yellow" />
<GradientStop Offset="0.5" Color="Green" />
<GradientStop Offset="0.6" Color="Blue" />
<GradientStop Offset="0.7" Color="Purple" />
</LinearGradientBrush>
</Grid.Background>
</Grid>
<Grid Grid.Row="3" Grid.Column="2" Margin="4">
<Grid.Background>
<RadialGradientBrush SpreadMethod="Reflect" RadiusX="0.2" RadiusY="0.2" GradientOrigin="0.4,0.4">
<GradientStop Offset="0.2" Color="Red" />
<GradientStop Offset="0.3" Color="Orange" />
<GradientStop Offset="0.4" Color="Yellow" />
<GradientStop Offset="0.5" Color="Green" />
<GradientStop Offset="0.6" Color="Blue" />
<GradientStop Offset="0.7" Color="Purple" />
</RadialGradientBrush>
</Grid.Background>
</Grid>
</Grid>
</Application> | {
"pile_set_name": "Github"
} |
/*
* Conditions Of Use
*
* This software was developed by employees of the National Institute of
* Standards and Technology (NIST), an agency of the Federal Government.
* Pursuant to title 15 Untied States Code Section 105, works of NIST
* employees are not subject to copyright protection in the United States
* and are considered to be in the public domain. As a result, a formal
* license is not needed to use the software.
*
* This software is provided by NIST as a service and is expressly
* provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY. NIST does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
* Permission to use this software is contingent upon your acceptance
* of the terms of this agreement
*
* .
*
*/
/*******************************************
* PRODUCT OF PT INOVACAO - EST DEPARTMENT *
*******************************************/
package gov.nist.javax.sip.parser.ims;
import java.text.ParseException;
import gov.nist.javax.sip.parser.Lexer;
import gov.nist.javax.sip.parser.TokenTypes;
import gov.nist.javax.sip.header.SIPHeader;
import gov.nist.javax.sip.header.ims.PPreferredIdentity;
import gov.nist.javax.sip.parser.AddressParametersParser;
/**
* P-Preferred-Identity header parser.
*
* @author ALEXANDRE MIGUEL SILVA SANTOS
*/
public class PPreferredIdentityParser
//extends AddressHeaderParser
extends AddressParametersParser
implements TokenTypes {
public PPreferredIdentityParser(String preferredIdentity) {
super(preferredIdentity);
}
protected PPreferredIdentityParser(Lexer lexer) {
super(lexer);
}
public SIPHeader parse() throws ParseException {
if (debug)
dbg_enter("PreferredIdentityParser.parse");
try {
this.lexer.match(TokenTypes.P_PREFERRED_IDENTITY);
this.lexer.SPorHT();
this.lexer.match(':');
this.lexer.SPorHT();
PPreferredIdentity p = new PPreferredIdentity();
super.parse( p );
return p;
} finally {
if (debug)
dbg_leave("PreferredIdentityParser.parse");
}
}
}
| {
"pile_set_name": "Github"
} |
---
title: LSTM Layer
---
# LSTM Layer
* Layer type: `LSTM`
* [Doxygen Documentation](http://caffe.berkeleyvision.org/doxygen/classcaffe_1_1LSTMLayer.html)
* Header: [`./include/caffe/layers/lstm_layer.hpp`](https://github.com/BVLC/caffe/blob/master/include/caffe/layers/lstm_layer.hpp)
* CPU implementation: [`./src/caffe/layers/lstm_layer.cpp`](https://github.com/BVLC/caffe/blob/master/src/caffe/layers/lstm_layer.cpp)
* CPU implementation (helper): [`./src/caffe/layers/lstm_unit_layer.cpp`](https://github.com/BVLC/caffe/blob/master/src/caffe/layers/lstm_unit_layer.cpp)
* CUDA GPU implementation (helper): [`./src/caffe/layers/lstm_unit_layer.cu`](https://github.com/BVLC/caffe/blob/master/src/caffe/layers/lstm_unit_layer.cu)
## Parameters
* Parameters (`Parameter recurrent_param`)
* From [`./src/caffe/proto/caffe.proto`](https://github.com/BVLC/caffe/blob/master/src/caffe/proto/caffe.proto):
{% highlight Protobuf %}
{% include proto/RecurrentParameter.txt %}
{% endhighlight %}
| {
"pile_set_name": "Github"
} |
import { Selector } from 'testcafe'
import fetch from 'isomorphic-fetch'
import { expect } from 'chai'
const host = process.env.HOST || 'localhost'
const port = process.env.PORT || '3000'
const MAIN_PAGE = `http://${host}:${port}`
// eslint-disable-next-line no-unused-expressions, no-undef
fixture`Shopping List`.beforeEach(async (t) => {
await t.setNativeDialogHandler(() => true)
await t.navigateTo(MAIN_PAGE)
})
test('home page', async (t) => {
await t
.expect(await Selector('h1').withText('Shopping List').exists)
.eql(true)
})
test('createShoppingList', async () => {
const command = {
aggregateName: 'ShoppingList',
aggregateId: 'shopping-list-1',
type: 'createShoppingList',
payload: {
name: 'List 1',
},
}
const response = await fetch(`${MAIN_PAGE}/api/commands`, {
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify(command),
})
const event = await response.json()
expect(event).to.deep.include({
type: 'SHOPPING_LIST_CREATED',
payload: { name: 'List 1' },
aggregateId: 'shopping-list-1',
aggregateVersion: 1,
})
})
test('createShoppingItem', async () => {
const command = {
aggregateName: 'ShoppingList',
aggregateId: 'shopping-list-1',
type: 'createShoppingItem',
payload: {
id: '1',
text: 'Milk',
},
}
const response = await fetch(`${MAIN_PAGE}/api/commands`, {
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify(command),
})
const event = await response.json()
expect(event).to.deep.include({
type: 'SHOPPING_ITEM_CREATED',
payload: { id: '1', text: 'Milk' },
aggregateId: 'shopping-list-1',
aggregateVersion: 2,
})
})
test('createShoppingItems', async () => {
const matches = [
{
command: {
aggregateName: 'ShoppingList',
aggregateId: 'shopping-list-1',
type: 'createShoppingItem',
payload: {
id: '2',
text: 'Eggs',
},
},
event: {
type: 'SHOPPING_ITEM_CREATED',
payload: { id: '2', text: 'Eggs' },
aggregateId: 'shopping-list-1',
aggregateVersion: 3,
},
},
{
command: {
aggregateName: 'ShoppingList',
aggregateId: 'shopping-list-1',
type: 'createShoppingItem',
payload: {
id: '3',
text: 'Canned beans',
},
},
event: {
type: 'SHOPPING_ITEM_CREATED',
payload: { id: '3', text: 'Canned beans' },
aggregateId: 'shopping-list-1',
aggregateVersion: 4,
},
},
{
command: {
aggregateName: 'ShoppingList',
aggregateId: 'shopping-list-1',
type: 'createShoppingItem',
payload: {
id: '4',
text: 'Paper towels',
},
},
event: {
type: 'SHOPPING_ITEM_CREATED',
payload: { id: '4', text: 'Paper towels' },
aggregateId: 'shopping-list-1',
aggregateVersion: 5,
},
},
]
for (const match of matches) {
const response = await fetch(`${MAIN_PAGE}/api/commands`, {
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify(match.command),
})
const event = await response.json()
expect(event).to.deep.include(match.event)
}
})
test('validation should works correctly', async () => {
const matches = [
{
command: {
aggregateName: 'ShoppingList',
aggregateId: 'shopping-list-2',
type: 'createShoppingList',
payload: {},
},
error: 'name is required',
},
{
command: {
aggregateName: 'ShoppingList',
aggregateId: 'shopping-list-1',
type: 'createShoppingList',
payload: {
name: 'List 1',
},
},
error: 'shopping list already exists',
},
{
command: {
aggregateName: 'ShoppingList',
aggregateId: 'shopping-list-4000',
type: 'createShoppingItem',
payload: {
id: '5',
text: 'Bread',
},
},
error: 'shopping list does not exist',
},
]
for (const match of matches) {
const response = await fetch(`${MAIN_PAGE}/api/commands`, {
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify(match.command),
})
const event = await response.text()
expect(event).to.include(match.error)
}
})
test('query should works correctly', async () => {
const response = await fetch(
`${MAIN_PAGE}/api/query/shoppingList/shopping-list-1`,
{
headers: {
'Content-Type': 'application/json',
},
method: 'GET',
}
)
const result = await response.json()
expect(result.data).to.deep.equal({
id: 'shopping-list-1',
name: 'List 1',
list: [
{
id: '1',
text: 'Milk',
checked: false,
},
{
id: '2',
text: 'Eggs',
checked: false,
},
{
id: '3',
text: 'Canned beans',
checked: false,
},
{
id: '4',
text: 'Paper towels',
checked: false,
},
],
})
})
test('create items in second shopping list', async (t) => {
await t.typeText(Selector('input[type=text]'), 'Item 1')
await t.click(Selector('button').withText('Add Item'))
await t.typeText(Selector('input[type=text]'), 'Item 2')
await t.click(Selector('button').withText('Add Item'))
await t.typeText(Selector('input[type=text]'), 'Item 3')
await t.click(Selector('button').withText('Add Item'))
await t.expect(Selector('label').withText('Item 1').exists).eql(true)
await t.expect(Selector('label').withText('Item 2').exists).eql(true)
await t.expect(Selector('label').withText('Item 3').exists).eql(true)
})
test('toggle items in second shopping list', async (t) => {
await t.click(Selector('label').withText('Item 1'))
await t.click(Selector('label').withText('Item 2'))
await t.click(Selector('label').withText('Item 3'))
await t
.expect(Selector('label > input[type=checkbox]').nth(4).checked)
.eql(true)
await t
.expect(Selector('label > input[type=checkbox]').nth(5).checked)
.eql(true)
await t
.expect(Selector('label > input[type=checkbox]').nth(6).checked)
.eql(true)
})
| {
"pile_set_name": "Github"
} |
> * 原文地址:[The Details That Matter](https://uxplanet.org/the-details-that-matter-8b962ca58b49#.ypigeruoq)
> * 原文作者:[Nick Babich](https://uxplanet.org/@101?source=post_header_lockup)
> * 译文出自:[掘金翻译计划](https://github.com/xitu/gold-miner)
> * 译者:[ivyxuan](https://github.com/iloveivyxuan)
> * 校对者:[ylq167](http://www.11167.xyz)、[gaozp](https://github.com/gaozp)
<img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://cdn-images-1.medium.com/max/800/1*9QIpe-Mce0ltsgQ0f0lYWQ.png">
# 细节是产品设计的重中之重 #
一个产品的成功是由各种因素共同造就的,而其中最重要的因素,就是整体的用户体验。在设计一款新的应用或是网站的时候,坚持最佳的实践规范是一个可靠的方法,但是在创造宏伟蓝图的时候,人们很容易就会省略掉那些能让人有更好的体验但却并非必要的设计元素。然而,设计的优劣往往在于我们能设计出多么体贴的细节。
在这篇文章中,我将会重点关注**可视化反馈**、**小的文字信息**还有**留白**这几个方面,你将会发现为什么这些不起眼的细节和那些显眼的设计元素相比同样重要,而这些细节又是怎样决定你产品成败的。
### 可视化反馈 ###
可视化反馈在较大的设计方案里很容易就会被忽视掉,但它实际上贯穿整体的用户体验流程。可以说,如果没有反馈就没有所谓的交互,你能想象和一个人聊天,可他一点反应也不给你吗 —— 你根本就聊不下去。而对于你的应用也是同样的道理。
> **缺乏可视化的反馈会让用户感到困惑。**
你必须要确保对于用户的每个动作都有相应的反馈,因为这会让用户感觉应用运行一切正常。可视化反馈
- 首先表明这个应用接受到了用户的操作。
- 然后它通过一种可视化而且易于理解的方式告诉用户这次交互的结果是什么,通过给用户一个信号,来告诉用户自己对于这个任务的执行是成功还是失败。
#### 让按钮或是其他开关看起来是可触摸的 ####
在现实生活中,按钮、开关还有其他东西都会对我们的动作有所回应,人们觉得世界就是这样运转的。而同样,人们也会期待应用里的元素能有类似的回应。
<img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://cdn-images-1.medium.com/max/800/1*CJmWiRBN2cwd53TfcyTd8g.gif">
图片来源:[Ramotion](https://dribbble.com/shots/1749645-Contact-Sync)
#### 操作的结果 ####
当你需要告诉用户他的操作结果是什么的时候,可视化反馈就很有用了,你可以利用现有的元素去传递反馈信息。
<img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://cdn-images-1.medium.com/max/800/1*6YGP-5TxLJSuDwBYsKzREg.gif">
图片来源:[Colin Garven](https://dribbble.com/ColinGarven)
#### **系统需要告诉用户他当前的状态是什么** ####
在系统中,用户任何时候都会想知道他此刻的状态是什么,而这不应该让用户自己去猜 —— 所以系统应该通过恰当的可视化反馈告诉用户此刻正在发生什么。对于一些常见而且次要的操作,简单的反馈就可以了,而对于不寻常而且重要的操作,反馈就需要更明显一点。
- [动态提醒](https://uxplanet.org/3-key-uses-for-animation-in-mobile-ui-design-4d7c482dd84b#.x07lyyazb)可以让用户立刻明白此时的状态。
<img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://cdn-images-1.medium.com/max/800/1*wU-ATdbQDPg6MTYZtNfTxw.gif">
图片来源:[Eddy Gann](https://dribbble.com/SMSeddy)
- [加载动画](https://uxplanet.org/progress-indicators-in-mobile-ux-design-a141e22f3ea0#.etoavwmbw)是对于应用进程的实时提醒,可以让用户立刻明白现在加载到哪里了。
<img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://cdn-images-1.medium.com/max/800/1*cd858x6Yb2k7lountEkefA.gif">
应用加载信息的时候,进度条可以避免让用户感到困惑。图片来源:[Mark](https://dribbble.com/milkycookie)
### 少量的文字信息 ###
少量的文字信息是一些用来是指导用户行为的一点点文字。举一些例子就是,错误信息、按钮对应的标签、提示信息。乍看之下,这么少的文字和整个应用设计比起来一点也不重要,但出人意料的是,它们对转化率有着极为重要的影响。
> 在应用里写出好的文字信息,和让应用正常运行、用户界面易于使用一样重要。
#### 让应用看起来像是一个人 ####
有一个快速的方法能让你的 UI 变得温暖而不呆板,就是用人说话的口吻去描述内容。如果你的产品听起来好像是一个人,用户就会更加的信任你。
<img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://cdn-images-1.medium.com/max/800/1*r8YCZlga38mG_gX1JyLZWQ.png">
Yelp 表现得好像他们是真人在负责这件事情。
<img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://cdn-images-1.medium.com/max/800/1*BOI3X5Qe6tflo6yCDmNmoA.png">
Airbnb 的提示听起来像人说的话而且语气还很随和。
#### 报错的方式要友好而且有效 ####
表达错误信息的方式会严重影响产品的用户体验。通常来说,省略错误信息或是没有正确描述错误信息都会让用户受挫。
<img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://cdn-images-1.medium.com/max/800/1*1EESYQmM9pt_SScMmgQqEg.png">
**像“出错啦”这种警告对所有的用户都会造成困扰,而且还会惹恼专家级用户。** 但是,一个精心设计过的错误信息,会顿时化失望为欣喜。所以,把报错变得人性化、不用技术性的语言并且适合你的用户群体。
<img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://cdn-images-1.medium.com/max/800/1*gX0GBH3BM_d_yjhk8Yvlaw.png">
错误状态一定要具体、友好而且有用,要告诉用户下一步怎么做。
#### 减少用户的担忧 ####
这些少量的文字信息是很情景化的,这也是为什么它很重要的一个原因。它可以解答用户具体情况下的问题,并针对他们所担忧的事情进行直接地交流。举例来说,当用户选择订阅或是提供了具体信息的时候,一些文字信息对于消除用户担忧会起到相当关键的作用。对于优秀的营销人员来说,“不会有群发消息或是自动关注”是理所当然的事情,但用户自己会存疑。因此,当用户添加了他们的邮箱地址或者绑定了 Twitter 账号的时候,一定要明确表态“我们和你一样讨厌垃圾消息”。
<img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://cdn-images-1.medium.com/max/800/1*Cl0P6ebhZTDkCGAHGjLnhA.png">
这只是一小段紧凑的文字,却涵盖了用户所有潜在的担忧。
### 留白 ###
留白(或者说是负空间)是设计师没有摆放设计元素的地方。而设计元素间的留白是指处在图片间距、内边距、外边距、行间距和字间距的空白。虽然很多人觉得这些空白浪费了宝贵的界面位置,但其实,留白是用户界面设计的一个重要元素。
#### 让用户界面更容易理解 ####
**杂乱的堆砌是很糟糕的一件事情。** 在界面上杂乱堆砌元素会给用户带来过多的信息:每一个被添加的按钮、图片和文字都会让界面显得更加复杂。如果你不想你的设计有任何刻意的留白的话,下面这个例子就能很明白的告诉你,有太多东西一起吸引你的注意力是多么可怕的事情。
<img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://cdn-images-1.medium.com/max/800/1*nzZwU1-KnaFrSpzMl04dWg.png">
杂乱堆砌的 UI 尤其是没有视觉层次的 UI 会让用户没有一点想要审视的欲望。
留白之所以很重要,是因为用户的注意力还有记忆是很有限的。我们的短期记忆只可以在短时间内(通常来说是 10 到 15 秒钟、或者是 1 分钟以内)记住一点有效的既有信息(通常来说[是 7 个事物或者比这个更少](http://www.human-memory.net/types_short.html))。
> 用户的注意力是很珍贵的资源,所以必须合理的分配。
如果因为你界面上的胡乱堆砌使得用户接收过多的信息,那么减少一些杂物就能改善用户的理解。大方地使用留白可以让凌乱的界面变得简单而有吸引力,留白削减了用户乍看之下接收到的元素数量,这使得浏览信息变得更加容易。留白的使用技巧在于只给用户提供能让他消化的数量的内容([一定数量的内容](https://uxplanet.org/best-practices-for-cards-fa45e3ad94dd#.by8pzk56q)),然后去掉不必要的细节。
<img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://cdn-images-1.medium.com/max/800/1*cY8Jewt4J1xUKyt2rla9nQ.png">
Medium 是一个典型的例子,它善于使用留白来改善用户对内容和 UI 的理解。
#### 让元素更具有吸引力 ####
留白在设计中是通过在元素周围留出空白,以让元素更加突出或是和其他元素以进行区分。它可以告诉用户什么是最重要而且是需要格外注意的。
> 元素周围的留白越多,元素就会越引人注目。
谷歌搜索的首页就是一个使用留白的典型例子,它通过在正中央摆放其最重要的交互元素(搜索框),并且在周围留出足够的空白以凸显其重要性的布局,直接实现了用户目标。
<img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://cdn-images-1.medium.com/max/800/1*UbEexVXM8GYMNuwYNqd2PQ.png">
去掉其他的元素可以更加凸显留下来的元素。
#### 明确关系 ####
[接近法则](https://www.interaction-design.org/literature/article/laws-of-proximity-uniform-connectedness-and-continuation-gestalt-principles-2)描述了人的眼睛是如何划分视觉元素的,它阐述说距离更近的物体看起来更相似。我们可以利用留白,在不同的元素间产生视觉联系。你看下面这幅图片,几乎所有人都会说看到了两组点,而不是16个点。
<img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://cdn-images-1.medium.com/max/800/1*U_YCbTW_AEHSLMnLSqIlqQ.png">
将信息拆分成合适的组别可以让信息更好的被识别和阅读。右边的表单将 15 栏拆分成 3 组,这样填写表单也变得相对容易了。虽然内容的数量仍然相同,但是给用户的感觉却完全不同。
<img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://cdn-images-1.medium.com/max/800/1*xv6xhcRljayCKY15LDekfQ.png">
图片来源:NNGroup
### 总结 ###
**用心设计**,应用界面上的每一个小的细节都值得细心揣摩,因为用户体验就是由这些小的细节相互协调作用而成的:
> “细节不只是细节,细节成就了设计。” —— Charles Eames
谢谢!
**关注 UX Planet:** [*Twitter*](https://twitter.com/101babich) | [*Facebook*](https://www.facebook.com/uxplanet/)
---
> [掘金翻译计划](https://github.com/xitu/gold-miner) 是一个翻译优质互联网技术文章的社区,文章来源为 [掘金](https://juejin.im) 上的英文分享文章。内容覆盖 [Android](https://github.com/xitu/gold-miner#android)、[iOS](https://github.com/xitu/gold-miner#ios)、[React](https://github.com/xitu/gold-miner#react)、[前端](https://github.com/xitu/gold-miner#前端)、[后端](https://github.com/xitu/gold-miner#后端)、[产品](https://github.com/xitu/gold-miner#产品)、[设计](https://github.com/xitu/gold-miner#设计) 等领域,想要查看更多优质译文请持续关注 [掘金翻译计划](https://github.com/xitu/gold-miner)。
| {
"pile_set_name": "Github"
} |
iOS依赖注入
---
> * 原文链接 : [Dependency Injection: Give Your iOS Code a Shot in the Arm
June 05, 2015](https://corner.squareup.com/2015/06/dependency-injection-in-objc.html)
* 原文作者 : [Square Engineering Blog](https://corner.squareup.com)
* 译文出自 : [开发技术前线 www.devtf.cn](http://www.devtf.cn)
* 译者 : [HarriesChen](https://github.com/mrchenhao)
##什么是依赖注入呢?
依赖注入(DI)是一种非常流行的设计模式在许多的语言之中,比如说Java和C#,但是它似乎并没有在Objective-C广泛的被采用,这篇文章的目的就是简要的介绍一下在Objective-C中使用依赖注入的例子。虽然代码是用Objective-C写的,但是也可以应用到Swift。
依赖注入的概念很简单:一个对象应该被依赖而不是被创建。强烈建议阅读Martin Fowler的[excellent discussion on the subject](http://martinfowler.com/articles/injection.html)作为背景阅读。
注入可以通过对象的初始化(或者可以说构造器)或者通过特性(setter),这些就指的是构造器注入和setter方法注入。
##构造器注入
```
- (instancetype)initWithDependency1:(Dependency1 *)d1
dependency2:(Dependency2 *)d2;
```
##Setter 注入
```
@property (nonatomic, retain) Dependency1 *dependency1;
@property (nonatomic, retain) Dependency2 *dependency2;
```
根据福勒的描述,[首选构造器注入](http://martinfowler.com/articles/injection.html#ConstructorVersusSetterInjection),一般来说只有在构造器注入不可行的情况下才会选择settter注入。在构造器注入中,你可以还是会使用`@property`来定义这些依赖,但是在接口中你应该让他们为只读,
##为什么使用依赖注入
依赖注入提供了一系列的好处,其中重要的是一下几点:
* **依赖定义清晰** 可以很明显的看出对象需要什么来进行操作,从而可以避免依赖类似(dependencies—like),全部变量消失(globals—disappear)。
* **组合** 依赖注入提倡[组合而不是继承](https://en.wikipedia.org/wiki/Composition_over_inheritance), 提高代码的可重用性。
* **定制简单** 当创建一个对象的时候,可以轻松的定制对象的每一个部分来面对最糟糕的情况。
* **所有权清晰** 特别是当使用构造函数注入,严格执行对象的所有权规则,帮助建立一个[有向无循环对象图](https://en.wikipedia.org/wiki/Directed_acyclic_graph)。
* **可测试性** 更重要的是,依赖注入提高了你的对象的可测性。因为他们可以被非常简单的创建通过初始化方法,没有隐藏的依赖关系需要管理。此外,可以简单的模拟出依赖让你关注于被测试的对象。
##使用依赖注入
你的代码可能还没有使用依赖注入的设计模式来设计,但是很容易上手。依赖注入的一个很好的方面是,你不需要采用“全或无”。相反,你可以将它应用到代码的特定区域并从那里展开。
###类型注入
首先,让我们把类分成两种:基本类和复合类。基本类是没有依赖的,或只依赖于其他基础类。基本类被继承的可能性极低,因为它们的功能是明确的,不变的,不引用外部资源。Cocoa本身有很多的基本类,如`NSString` `NSArray`,`NSDictionary` `NSNumber`……。
复杂类则相反,他们有复杂的依赖关系,包括应用级别的逻辑(可能被改变),或者访问外部资源,比如磁盘,网络或者一些全局的服务。在你应用内的大多数类都是复杂的,包括大多数的控制器对象和模型对象。需要Cocoa类也食非常复杂的,比如说`NSURLConnection `或者`UIViewController `
判断这个的最简单方法就是拿起一个复杂类然后看它初始化其他复杂类的地方(搜索"alloc] init" or "new]"),介绍了类的依赖注入,改变这个实例化的对象是通过作为一个类的初始化参数而不是类的实例化对象本身。
###初始化中的依赖分配
让我们来看一个例子,一个子对象(依赖)被初始化作为父对象的一部分。一般代码如下:
```
@interface RCRaceCar ()
@property (nonatomic, readonly) RCEngine *engine;
@end
@implementation RCRaceCar
- (instancetype)init
{
...
// Create the engine. Note that it cannot be customized or
// mocked out without modifying the internals of RCRaceCar.
_engine = [[RCEngine alloc] init];
return self;
}
@end
```
依赖注入版本的有一些小小的不同
```
@interface RCRaceCar ()
@property (nonatomic, readonly) RCEngine *engine;
@end
@implementation RCRaceCar
// The engine is created before the race car and passed in
// as a parameter, and the caller can customize it if desired.
- (instancetype)initWithEngine:(RCEngine *)engine
{
...
_engine = engine;
return self;
}
@end
```
###依赖惰性初始化
一些对象有时会在很后面才会被用到,有时甚至在初始化之后不会被用到,举个例子(在依赖注入之前)也许看起来是这样子的:
```
@interface RCRaceCar ()
@property (nonatomic) RCEngine *engine;
@end
@implementation RCRaceCar
- (instancetype)initWithEngine:(RCEngine *)engine
{
...
_engine = engine;
return self;
}
- (void)recoverFromCrash
{
if (self.fire != nil) {
RCFireExtinguisher *fireExtinguisher = [[RCFireExtinguisher alloc] init];
[fireExtinguisher extinguishFire:self.fire];
}
}
@end
```
在这种情况下,赛车希望不会出事,而我们也不需要使用灭火器。由于需要该对象的机会很低,我们不想每一个赛车的创建的时候慢下来。另外,如果我们的赛车需要从多个事故恢复,就需要创建多个灭火器。针对这些情况,我们可以使用工厂。
工厂标准的Objective-C块不需要参数和返回一个对象的实例。一个对象可以控制当其依赖的是使用这些块而不需要详细了解如何创建。
这里是一个例子使用了依赖注入和工厂模式来创建灭火器。
```
typedef RCFireExtinguisher *(^RCFireExtinguisherFactory)();
@interface RCRaceCar ()
@property (nonatomic, readonly) RCEngine *engine;
@property (nonatomic, copy, readonly) RCFireExtinguisherFactory fireExtinguisherFactory;
@end
@implementation RCRaceCar
- (instancetype)initWithEngine:(RCEngine *)engine
fireExtinguisherFactory:(RCFireExtinguisherFactory)extFactory
{
...
_engine = engine;
_fireExtinguisherFactory = [extFactory copy];
return self;
}
- (void)recoverFromCrash
{
if (self.fire != nil) {
RCFireExtinguisher *fireExtinguisher = self.fireExtinguisherFactory();
[fireExtinguisher extinguishFire:self.fire];
}
}
@end
```
工厂模式在我们创建未知数量的依赖的时候也是非常有用的,即使是在初始化期间,例子如下:
```
@implementation RCRaceCar
- (instancetype)initWithEngine:(RCEngine *)engine
transmission:(RCTransmission *)transmission
wheelFactory:(RCWheel *(^)())wheelFactory;
{
self = [super init];
if (self == nil) {
return nil;
}
_engine = engine;
_transmission = transmission;
_leftFrontWheel = wheelFactory();
_leftRearWheel = wheelFactory();
_rightFrontWheel = wheelFactory();
_rightRearWheel = wheelFactory();
// Keep the wheel factory for later in case we need a spare.
_wheelFactory = [wheelFactory copy];
return self;
}
@end
```
##避免麻烦的配置
如果对象不应该在其他对象分配,他们在哪里分配?是不是所有的这些依赖关系很难配置?大多不都是一样的吗?这些问题的解决在于类方便的初始化(想一想+[NSDictionary dictionary])。我们会把我们的对象图的配置移出我们正常的对象,把他们抽象出来,测试,业务逻辑。
在我们添加简单初始化方法之前,先确认它是有必要的。如果一个对象只有少量的参数在初始化方法之中,这些参数没有规律,那么简单初始化方法是没有必要的。调用者应该使用标准初始化方法。
我们需要从四个地方搜集依赖来配置我们的对象:
* **没有明确默认值的变量** 这些包括布尔类型和数字类型的有可能在每个实例中是不同的。这些变量应该在简单初始化方法的参数中。
* **共享对象** 这些应该在简单初始化方法中作为参数(例如电台频率),这些对象先前可能被访问作为一个单例或者通过父指针。
* **新创建的对象** 如果我们的对象不与另一个对象分享这种依赖关系,合作者对象应该是新实例化的类中简单初始化。这些都是以前分配的对象直接在该对象的实现。
* **系统单例** Cocoa提供了很多单例可以直接被访问,例如`[NSFileManager defaultManager]`,那里有一个明确的目的只需要一个实例被使用在应用中,还有很多单例在系统中。
一个对于赛车的简单初始化看起来如下:
```
+ (instancetype)raceCarWithPitRadioFrequency:(RCRadioFrequency *)frequency;
{
RCEngine *engine = [[RCEngine alloc] init];
RCTransmission *transmission = [[RCTransmission alloc] init];
RCWheel *(^wheelFactory)() = ^{
return [[RCWheel alloc] init];
};
return [[self alloc] initWithEngine:engine
transmission:transmission
pitRadioFrequency:frequency
wheelFactory:wheelFactory];
}
```
你的类的简单初始化方法应该是最合适的。一个经常被用到的(可重用)的配置在一个.m文件中,而一个特定的配置文件应该在在`@interface RaceCar (FooConfiguration)`的类别文件中比如`fooRaceCar `。
##系统单例
在Cocoa的许多对象中,只有一种实例将一直存在。
例如`[UIApplication sharedApplication]`, `[NSFileManager defaultManager]`, `[NSUserDefaults standardUserDefaults]`, 和 `[UIDevice currentDevice]`,如果一个对象对他们存在依赖,那么应该在初始化的参数中包含他们,即使也许在你的代码中只有一个实例,你的测试可能要模拟实例或创建一个实例每个测试避免测试相互依存。
建议避免创建全局引用单例,而是创建一个对象的单个实例当它第一次被需要的时候并把它注入到所有依赖它的对象中去。
##不可变构造器
偶尔在某个类的构造器或者初始化方法不能被改变或者调用的时候,我们可以使用setter注入。例如:
```
// An example where we can't directly call the the initializer.
RCRaceTrack *raceTrack = [objectYouCantModify createRaceTrack];
// We can still use properties to configure our race track.
raceTrack.width = 10;
raceTrack.numberOfHairpinTurns = 2;
```
setter注入允许你配置对象,但是它也引入了易变性,你必须进行测试和处理,幸运的是,有两个场景导致初始化方法不能改变和调用,他们都是可以避免的。
###类注册
使用类注册的工厂模式意味着不能修改初始化方法。
```
NSArray *raceCarClasses = @[
[RCFastRaceCar class],
[RCSlowRaceCar class],
];
NSMutableArray *raceCars = [[NSMutableArray alloc] init];
for (Class raceCarClass in raceCarClasses) {
// All race cars must have the same initializer ("init" in this case).
// This means we can't customize different subclasses in different ways.
[raceCars addObject:[[raceCarClass alloc] init]];
}
```
一个简单的替代方法就是使用工厂块而不是类的声明列表。
```
typedef RCRaceCar *(^RCRaceCarFactory)();
NSArray *raceCarFactories = @[
^{ return [[RCFastRaceCar alloc] initWithTopSpeed:200]; },
^{ return [[RCSlowRaceCar alloc] initWithLeatherPlushiness:11]; }
];
NSMutableArray *raceCars = [[NSMutableArray alloc] init];
for (RCRaceCarFactory raceCarFactory in raceCarFactories) {
// We now no longer care which initializer is being called.
[raceCars addObject:raceCarFactory()];
}
```
###故事版
故事提供了一个方便的方式来设计你的用户界面,但也带来一些问题的时候。特别是依赖注入,实例化初始视图控制器在故事板中不允许你选择初始化方法。同样,当下面的事情就是在故事板中定义,目标视图控制器被实例化也不允许你指定的初始化方法。
解决这个问题的办法是避免使用故事板。这似乎是一个极端的解决方案,但是我们发现故事板有其他问题在大型团队的开发中。此外,没有必要失去大部分故事版的好处。xibs提供所有相同的好处和故事板,除了`segues`,但仍然让你自定义初始化。
##公共和私有
依赖注入鼓励你暴露更多的对象在你的公共接口。如前所述,这有许多好处。但当你构建框架,它会明显的膨胀公共API。使用依赖注入之前,公共对象A可能使用私有对象B(这反过来使用私有对象C),但对象B和C分别从未曝光的外部框架。使用依赖注入的对象A会使对象B暴露在公共初始化方法,对象B反过来将对象C暴露在公共初始化方法。。
```
// In public ObjectA.h.
@interface ObjectA
// Because the initializer uses a reference to ObjectB we need to
// make the Object B header public where we wouldn't have before.
- (instancetype)initWithObjectB:(ObjectB *)objectB;
@end
@interface ObjectB
// Same here: we need to expose ObjectC.h.
- (instancetype)initWithObjectC:(ObjectC *)objectC;
@end
@interface ObjectC
- (instancetype)init;
@end
```
对象B和对象C都是具体的实现,但你并不需要框架的使用者来担心他们,我们可以通过协议的方式来解决。
```
@interface ObjectA
- (instancetype)initWithObjectB:(id <ObjectB>)objectB;
@end
// This protocol exposes only the parts of the original ObjectB that
// are needed by ObjectA. We're not creating a hard dependency on
// our concrete ObjectB (or ObjectC) implementation.
@protocol ObjectB
- (void)methodNeededByObjectA;
@end
```
##结束语
依赖注入在 Objective-C(同样在Swift),合理的使用会使你的代码更加易读、易测试和易维护。
| {
"pile_set_name": "Github"
} |
<tr class="dijitReset" data-dojo-attach-point="focusNode" role="menuitem" tabIndex="-1">
<td class="dijitReset dijitMenuItemIconCell" role="presentation">
<span role="presentation" class="dijitInline dijitIcon dijitMenuItemIcon" data-dojo-attach-point="iconNode"></span>
</td>
<td class="dijitReset dijitMenuItemLabel" colspan="2" data-dojo-attach-point="containerNode,textDirNode"
role="presentation"></td>
<td class="dijitReset dijitMenuItemAccelKey" style="display: none" data-dojo-attach-point="accelKeyNode"></td>
<td class="dijitReset dijitMenuArrowCell" role="presentation">
<span data-dojo-attach-point="arrowWrapper" style="visibility: hidden">
<span class="dijitInline dijitIcon dijitMenuExpand"></span>
<span class="dijitMenuExpandA11y">+</span>
</span>
</td>
</tr>
| {
"pile_set_name": "Github"
} |
package com.lly835.bestpay.exception;
import com.lly835.bestpay.enums.BestPayResultEnum;
/**
* Created by null on 2017/2/23.
*/
public class BestPayException extends RuntimeException {
private Integer code;
public BestPayException(BestPayResultEnum resultEnum) {
super(resultEnum.getMsg());
code = resultEnum.getCode();
}
public Integer getCode() {
return code;
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2010 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<android.support.v7.internal.view.menu.ListMenuItemView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?attr/dropdownListPreferredItemHeight"
android:minWidth="196dip"
style="@style/RtlOverlay.Widget.AppCompat.PopupMenuItem">
<!-- Icon will be inserted here. -->
<!-- The title and summary have some gap between them, and this 'group' should be centered vertically. -->
<RelativeLayout
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:duplicateParentState="true"
style="@style/RtlOverlay.Widget.AppCompat.PopupMenuItem.InternalGroup">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:textAppearance="?attr/textAppearanceLargePopupMenu"
android:singleLine="true"
android:duplicateParentState="true"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
style="@style/RtlOverlay.Widget.AppCompat.PopupMenuItem.Text" />
<TextView
android:id="@+id/shortcut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/title"
android:textAppearance="?attr/textAppearanceSmallPopupMenu"
android:singleLine="true"
android:duplicateParentState="true"
style="@style/RtlOverlay.Widget.AppCompat.PopupMenuItem.Text" />
</RelativeLayout>
<!-- Checkbox, and/or radio button will be inserted here. -->
</android.support.v7.internal.view.menu.ListMenuItemView>
<!-- From: file:/usr/local/google/buildbot/repo_clients/https___googleplex-android.googlesource.com_a_platform_manifest.git/mnc-sdk-release/frameworks/support/v7/appcompat/res/layout/abc_popup_menu_item_layout.xml --> | {
"pile_set_name": "Github"
} |
import os
pwd=os.getcwd()
year_month=pwd.split('\\')[-1]
year=int(year_month[:4])
month=int(year_month[4:])
| {
"pile_set_name": "Github"
} |
% Copyright 2011 Zdenek Kalal
%
% This file is part of TLD.
%
% TLD is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% TLD is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with TLD. If not, see <http://www.gnu.org/licenses/>.
function idx_out = bb_isout(bb,imsize)
idx_out = bb(1,:) > imsize(2) | ...
bb(2,:) > imsize(1) | ...
bb(3,:) < 1 | ...
bb(4,:) < 1; | {
"pile_set_name": "Github"
} |
package net.ripe.db.whois.api.rest;
import net.ripe.db.whois.api.AbstractIntegrationTest;
import net.ripe.db.whois.api.RestTest;
import net.ripe.db.whois.api.rest.domain.Attribute;
import net.ripe.db.whois.api.rest.domain.WhoisResources;
import net.ripe.db.whois.api.rest.mapper.FormattedClientAttributeMapper;
import net.ripe.db.whois.api.rest.mapper.WhoisObjectMapper;
import net.ripe.db.whois.common.IntegrationTest;
import net.ripe.db.whois.common.MaintenanceMode;
import net.ripe.db.whois.common.TestDateTimeProvider;
import net.ripe.db.whois.common.domain.IpRanges;
import net.ripe.db.whois.common.rpsl.AttributeType;
import net.ripe.db.whois.common.rpsl.ObjectType;
import net.ripe.db.whois.common.rpsl.RpslAttribute;
import net.ripe.db.whois.common.rpsl.RpslObject;
import net.ripe.db.whois.common.rpsl.RpslObjectBuilder;
import org.glassfish.jersey.uri.UriComponent;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.springframework.beans.factory.annotation.Autowired;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.UUID;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
@Category(IntegrationTest.class)
public class UpdateMaintainerSS0TestIntegration extends AbstractIntegrationTest {
private static final RpslObject OWNER_MNT = RpslObject.parse("" +
"mntner: OWNER-MNT\n" +
"descr: Owner Maintainer\n" +
"admin-c: TP1-TEST\n" +
"upd-to: [email protected]\n" +
"auth: MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/ #test\n" +
"auth: SSO [email protected]\n" +
"mnt-by: OWNER-MNT\n" +
"source: TEST");
private static final RpslObject TEST_PERSON = RpslObject.parse("" +
"person: Test Person\n" +
"address: Singel 258\n" +
"phone: +31 6 12345678\n" +
"nic-hdl: TP1-TEST\n" +
"mnt-by: OWNER-MNT\n" +
"source: TEST\n");
private static final RpslObject TEST_ROLE = RpslObject.parse("" +
"role: Test Role\n" +
"address: Singel 258\n" +
"phone: +31 6 12345678\n" +
"nic-hdl: TR1-TEST\n" +
"admin-c: TR1-TEST\n" +
"abuse-mailbox: [email protected]\n" +
"mnt-by: OWNER-MNT\n" +
"source: TEST\n");
@Autowired private WhoisObjectMapper whoisObjectMapper;
@Autowired private MaintenanceMode maintenanceMode;
@Autowired private TestDateTimeProvider testDateTimeProvider;
@Autowired private IpRanges ipRanges;
@Before
public void setup() {
databaseHelper.addObject("person: Test Person\nnic-hdl: TP1-TEST");
databaseHelper.addObject("role: Test Role\nnic-hdl: TR1-TEST");
databaseHelper.addObject(OWNER_MNT);
databaseHelper.updateObject(TEST_PERSON);
databaseHelper.updateObject(TEST_ROLE);
maintenanceMode.set("FULL,FULL");
testDateTimeProvider.setTime(LocalDateTime.parse("2001-02-04T17:00:00"));
//add localhost as not trusted
ipRanges.setTrusted("::1");
}
@Test
public void update_maintainer_sso_with_sync_false_succeeds() {
insertSyncHistory("ORG-TEST","OWNER-MNT", 1000, false);
insertSyncHistory("ORG-TEST","OWNER-MNT", 2000, true);
insertSyncHistory("ORG-TEST","OWNER-MNT", 3000, false);
final RpslObject updatedObject = new RpslObjectBuilder(OWNER_MNT).append(new RpslAttribute(AttributeType.AUTH, "SSO [email protected]")).get();
final WhoisResources whoisResources = RestTest.target(getPort(), "whois/test/mntner/OWNER-MNT")
.request(MediaType.APPLICATION_XML)
.cookie("crowd.token_key", "valid-token")
.put(Entity.entity(map(updatedObject), MediaType.APPLICATION_XML), WhoisResources.class);
assertThat(whoisResources.getErrorMessages(), is(empty()));
assertThat(whoisResources.getWhoisObjects(), hasSize(1));
assertThat(whoisResources.getWhoisObjects().get(0).getAttributes(), hasItem(new Attribute("auth", "SSO [email protected]")));
assertThat(whoisResources.getWhoisObjects().get(0).getAttributes(), hasItem(new Attribute("auth", "SSO [email protected]")));
RpslObject rpslObject = databaseHelper.lookupObject(ObjectType.MNTNER, "OWNER-MNT");
assertThat(rpslObject.findAttributes(AttributeType.AUTH),
containsInAnyOrder(
new RpslAttribute(AttributeType.AUTH, "MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/ #test"),
new RpslAttribute(AttributeType.AUTH, "SSO 906635c2-0405-429a-800b-0602bd716124"),
new RpslAttribute(AttributeType.AUTH, "SSO 8ffe29be-89ef-41c8-ba7f-0e1553a623e5"))
);
}
@Test
public void update_maintainer_add_sso_with_sync_enabled_should_fail() {
insertSyncHistory("ORG-TEST","OWNER-MNT", 1000, false);
insertSyncHistory("ORG-TEST","OWNER-MNT", 2000, true);
final RpslObject updatedObject = new RpslObjectBuilder(OWNER_MNT).append(new RpslAttribute(AttributeType.AUTH, "SSO [email protected]")).get();
try {
RestTest.target(getPort(), "whois/test/mntner/OWNER-MNT")
.request(MediaType.APPLICATION_XML)
.cookie("crowd.token_key", "valid-token")
.put(Entity.entity(map(updatedObject), MediaType.APPLICATION_XML), WhoisResources.class);
fail();
} catch (BadRequestException e) {
RestTest.assertOnlyErrorMessage(e, "Error", "You cannot update SSO auth attribute(s), because the maintainer is synchronised from the LIR Portal");
}
}
@Test
public void update_maintainer_remove_sso_with_sync_enabled_should_fail() {
insertSyncHistory("ORG-TEST","OWNER-MNT", 1000, false);
insertSyncHistory("ORG-TEST","OWNER-MNT", 2000, true);
final RpslObject updatedObject = new RpslObjectBuilder(OWNER_MNT).removeAttribute(new RpslAttribute(AttributeType.AUTH, "SSO [email protected]")).get();
try {
RestTest.target(getPort(), "whois/test/mntner/OWNER-MNT")
.request(MediaType.APPLICATION_XML)
.cookie("crowd.token_key", "valid-token")
.put(Entity.entity(map(updatedObject), MediaType.APPLICATION_XML), WhoisResources.class);
fail();
} catch (BadRequestException e) {
RestTest.assertOnlyErrorMessage(e, "Error", "You cannot update SSO auth attribute(s), because the maintainer is synchronised from the LIR Portal");
}
}
@Test
public void update_maintainer_update_sso_with_sync_enabled_should_fail() {
insertSyncHistory("ORG-TEST","OWNER-MNT", 1000, false);
insertSyncHistory("ORG-TEST","OWNER-MNT", 2000, true);
final RpslObject updatedObject = new RpslObjectBuilder(OWNER_MNT).removeAttribute(new RpslAttribute(AttributeType.AUTH, "SSO [email protected]")).get();
try {
RestTest.target(getPort(), "whois/test/mntner/OWNER-MNT")
.request(MediaType.APPLICATION_XML)
.cookie("crowd.token_key", "valid-token")
.put(Entity.entity(map(updatedObject), MediaType.APPLICATION_XML), WhoisResources.class);
fail();
} catch (BadRequestException e) {
RestTest.assertOnlyErrorMessage(e, "Error", "You cannot update SSO auth attribute(s), because the maintainer is synchronised from the LIR Portal");
}
}
@Test
public void update_maintainer_succeeds_sync_enabled_no_sso() {
insertSyncHistory("ORG-TEST","OWNER-MNT-SYNC", 1000, true);
RpslObject MNT_SYNC = RpslObject.parse("" +
"mntner: OWNER-MNT-SYNC\n" +
"descr: Owner Maintainer\n" +
"admin-c: TP1-TEST\n" +
"upd-to: [email protected]\n" +
"auth: SSO [email protected]\n" +
"mnt-by: OWNER-MNT-SYNC\n" +
"source: TEST");
databaseHelper.addObject(MNT_SYNC);
final RpslObject updatedObject = new RpslObjectBuilder(MNT_SYNC).append(new RpslAttribute(AttributeType.AUTH, "MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/")).get();
final WhoisResources whoisResources = RestTest.target(getPort(), "whois/test/mntner/OWNER-MNT-SYNC")
.request(MediaType.APPLICATION_XML)
.cookie("crowd.token_key", "valid-token")
.put(Entity.entity(map(updatedObject), MediaType.APPLICATION_XML), WhoisResources.class);
assertThat(whoisResources.getErrorMessages(), is(empty()));
assertThat(whoisResources.getWhoisObjects(), hasSize(1));
assertThat(whoisResources.getWhoisObjects().get(0).getAttributes(), hasItem(new Attribute("auth", "MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/")));
assertThat(whoisResources.getWhoisObjects().get(0).getAttributes(), hasItem(new Attribute("auth", "SSO [email protected]")));
assertThat(databaseHelper.lookupObject(ObjectType.MNTNER, "OWNER-MNT-SYNC").findAttributes(AttributeType.AUTH),
containsInAnyOrder(
new RpslAttribute(AttributeType.AUTH, "MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/ #test"),
new RpslAttribute(AttributeType.AUTH, "SSO 906635c2-0405-429a-800b-0602bd716124"))
);
}
@Test
public void update_maintainer_sso_with_sync_true_trusted_source_succeeds() {
try {
ipRanges.setTrusted("127.0.0.1");
insertSyncHistory("ORG-TEST", "OWNER-MNT", 1000, false);
insertSyncHistory("ORG-TEST", "OWNER-MNT", 2000, true);
final RpslObject updatedObject = new RpslObjectBuilder(OWNER_MNT).append(new RpslAttribute(AttributeType.AUTH, "SSO [email protected]")).get();
final WhoisResources whoisResources = RestTest.target(getPort(), "whois/test/mntner/OWNER-MNT")
.request(MediaType.APPLICATION_XML)
.cookie("crowd.token_key", "valid-token")
.put(Entity.entity(map(updatedObject), MediaType.APPLICATION_XML), WhoisResources.class);
assertThat(whoisResources.getErrorMessages(), is(empty()));
assertThat(whoisResources.getWhoisObjects(), hasSize(1));
assertThat(whoisResources.getWhoisObjects().get(0).getAttributes(), hasItem(new Attribute("auth", "SSO [email protected]")));
assertThat(whoisResources.getWhoisObjects().get(0).getAttributes(), hasItem(new Attribute("auth", "SSO [email protected]")));
RpslObject rpslObject = databaseHelper.lookupObject(ObjectType.MNTNER, "OWNER-MNT");
assertThat(rpslObject.findAttributes(AttributeType.AUTH),
containsInAnyOrder(
new RpslAttribute(AttributeType.AUTH, "MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/ #test"),
new RpslAttribute(AttributeType.AUTH, "SSO 906635c2-0405-429a-800b-0602bd716124"),
new RpslAttribute(AttributeType.AUTH, "SSO 8ffe29be-89ef-41c8-ba7f-0e1553a623e5"))
);
} finally {
ipRanges.setTrusted("::1");
}
}
// helper methods
private void insertSyncHistory(final String org, final String mntnr, final long when, final Boolean syncState) {
final String email = UUID.randomUUID() + "@ripe.net";
final Timestamp timestamp = new Timestamp(when);
databaseHelper.getInternalsTemplate().update(
"INSERT INTO default_maintainer_sync_history (org, mntner, timestamp, email, is_synchronised) VALUES (?, ?, ?, ?, ?)",
org, mntnr, timestamp, email, syncState);
}
private String encode(final String input) {
// do not interpret template parameters
return UriComponent.encode(input, UriComponent.Type.QUERY_PARAM, false);
}
private WhoisResources map(final RpslObject ... rpslObjects) {
return whoisObjectMapper.mapRpslObjects(FormattedClientAttributeMapper.class, rpslObjects);
}
}
| {
"pile_set_name": "Github"
} |
AI 100 0 230 80 213 100 213
s 101
k_h 87
r 58
I 91 0 206 80 152 100 152
s 79
t_h 63
l 69 0 158 80 147 100 147
z 58
_ 203
_ 1
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save ( ) {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
| {
"pile_set_name": "Github"
} |
ego_left:
(510 1070) (540 1060) (550 1050) (560 1040) (570 1030) (580 1020) (590 1010) (600 1000) (600 990) (610 980) (620 970) (640 960) (640 950) (670 940)
ego_right:
(1470 1070) (1430 1060) (1420 1050) (1400 1040) (1390 1030) (1380 1020) (1370 1010) (1360 1000) (1350 990) (1340 980) (1330 970) (1320 960) (1300 950) (1290 940)
| {
"pile_set_name": "Github"
} |
{
"images" : [
{
"idiom" : "universal",
"filename" : "vc.pdf"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
},
"properties" : {
"preserves-vector-representation" : true
}
} | {
"pile_set_name": "Github"
} |
// Copyright 2017 Joyent, Inc.
module.exports = Key;
var assert = require('assert-plus');
var algs = require('./algs');
var crypto = require('crypto');
var Fingerprint = require('./fingerprint');
var Signature = require('./signature');
var DiffieHellman = require('./dhe').DiffieHellman;
var errs = require('./errors');
var utils = require('./utils');
var PrivateKey = require('./private-key');
var edCompat;
try {
edCompat = require('./ed-compat');
} catch (e) {
/* Just continue through, and bail out if we try to use it. */
}
var InvalidAlgorithmError = errs.InvalidAlgorithmError;
var KeyParseError = errs.KeyParseError;
var formats = {};
formats['auto'] = require('./formats/auto');
formats['pem'] = require('./formats/pem');
formats['pkcs1'] = require('./formats/pkcs1');
formats['pkcs8'] = require('./formats/pkcs8');
formats['rfc4253'] = require('./formats/rfc4253');
formats['ssh'] = require('./formats/ssh');
formats['ssh-private'] = require('./formats/ssh-private');
formats['openssh'] = formats['ssh-private'];
function Key(opts) {
assert.object(opts, 'options');
assert.arrayOfObject(opts.parts, 'options.parts');
assert.string(opts.type, 'options.type');
assert.optionalString(opts.comment, 'options.comment');
var algInfo = algs.info[opts.type];
if (typeof (algInfo) !== 'object')
throw (new InvalidAlgorithmError(opts.type));
var partLookup = {};
for (var i = 0; i < opts.parts.length; ++i) {
var part = opts.parts[i];
partLookup[part.name] = part;
}
this.type = opts.type;
this.parts = opts.parts;
this.part = partLookup;
this.comment = undefined;
this.source = opts.source;
/* for speeding up hashing/fingerprint operations */
this._rfc4253Cache = opts._rfc4253Cache;
this._hashCache = {};
var sz;
this.curve = undefined;
if (this.type === 'ecdsa') {
var curve = this.part.curve.data.toString();
this.curve = curve;
sz = algs.curves[curve].size;
} else if (this.type === 'ed25519' || this.type === 'curve25519') {
sz = 256;
this.curve = 'curve25519';
} else {
var szPart = this.part[algInfo.sizePart];
sz = szPart.data.length;
sz = sz * 8 - utils.countZeros(szPart.data);
}
this.size = sz;
}
Key.formats = formats;
Key.prototype.toBuffer = function (format, options) {
if (format === undefined)
format = 'ssh';
assert.string(format, 'format');
assert.object(formats[format], 'formats[format]');
assert.optionalObject(options, 'options');
if (format === 'rfc4253') {
if (this._rfc4253Cache === undefined)
this._rfc4253Cache = formats['rfc4253'].write(this);
return (this._rfc4253Cache);
}
return (formats[format].write(this, options));
};
Key.prototype.toString = function (format, options) {
return (this.toBuffer(format, options).toString());
};
Key.prototype.hash = function (algo) {
assert.string(algo, 'algorithm');
algo = algo.toLowerCase();
if (algs.hashAlgs[algo] === undefined)
throw (new InvalidAlgorithmError(algo));
if (this._hashCache[algo])
return (this._hashCache[algo]);
var hash = crypto.createHash(algo).
update(this.toBuffer('rfc4253')).digest();
this._hashCache[algo] = hash;
return (hash);
};
Key.prototype.fingerprint = function (algo) {
if (algo === undefined)
algo = 'sha256';
assert.string(algo, 'algorithm');
var opts = {
type: 'key',
hash: this.hash(algo),
algorithm: algo
};
return (new Fingerprint(opts));
};
Key.prototype.defaultHashAlgorithm = function () {
var hashAlgo = 'sha1';
if (this.type === 'rsa')
hashAlgo = 'sha256';
if (this.type === 'dsa' && this.size > 1024)
hashAlgo = 'sha256';
if (this.type === 'ed25519')
hashAlgo = 'sha512';
if (this.type === 'ecdsa') {
if (this.size <= 256)
hashAlgo = 'sha256';
else if (this.size <= 384)
hashAlgo = 'sha384';
else
hashAlgo = 'sha512';
}
return (hashAlgo);
};
Key.prototype.createVerify = function (hashAlgo) {
if (hashAlgo === undefined)
hashAlgo = this.defaultHashAlgorithm();
assert.string(hashAlgo, 'hash algorithm');
/* ED25519 is not supported by OpenSSL, use a javascript impl. */
if (this.type === 'ed25519' && edCompat !== undefined)
return (new edCompat.Verifier(this, hashAlgo));
if (this.type === 'curve25519')
throw (new Error('Curve25519 keys are not suitable for ' +
'signing or verification'));
var v, nm, err;
try {
nm = hashAlgo.toUpperCase();
v = crypto.createVerify(nm);
} catch (e) {
err = e;
}
if (v === undefined || (err instanceof Error &&
err.message.match(/Unknown message digest/))) {
nm = 'RSA-';
nm += hashAlgo.toUpperCase();
v = crypto.createVerify(nm);
}
assert.ok(v, 'failed to create verifier');
var oldVerify = v.verify.bind(v);
var key = this.toBuffer('pkcs8');
var curve = this.curve;
var self = this;
v.verify = function (signature, fmt) {
if (Signature.isSignature(signature, [2, 0])) {
if (signature.type !== self.type)
return (false);
if (signature.hashAlgorithm &&
signature.hashAlgorithm !== hashAlgo)
return (false);
if (signature.curve && self.type === 'ecdsa' &&
signature.curve !== curve)
return (false);
return (oldVerify(key, signature.toBuffer('asn1')));
} else if (typeof (signature) === 'string' ||
Buffer.isBuffer(signature)) {
return (oldVerify(key, signature, fmt));
/*
* Avoid doing this on valid arguments, walking the prototype
* chain can be quite slow.
*/
} else if (Signature.isSignature(signature, [1, 0])) {
throw (new Error('signature was created by too old ' +
'a version of sshpk and cannot be verified'));
} else {
throw (new TypeError('signature must be a string, ' +
'Buffer, or Signature object'));
}
};
return (v);
};
Key.prototype.createDiffieHellman = function () {
if (this.type === 'rsa')
throw (new Error('RSA keys do not support Diffie-Hellman'));
return (new DiffieHellman(this));
};
Key.prototype.createDH = Key.prototype.createDiffieHellman;
Key.parse = function (data, format, options) {
if (typeof (data) !== 'string')
assert.buffer(data, 'data');
if (format === undefined)
format = 'auto';
assert.string(format, 'format');
if (typeof (options) === 'string')
options = { filename: options };
assert.optionalObject(options, 'options');
if (options === undefined)
options = {};
assert.optionalString(options.filename, 'options.filename');
if (options.filename === undefined)
options.filename = '(unnamed)';
assert.object(formats[format], 'formats[format]');
try {
var k = formats[format].read(data, options);
if (k instanceof PrivateKey)
k = k.toPublic();
if (!k.comment)
k.comment = options.filename;
return (k);
} catch (e) {
if (e.name === 'KeyEncryptedError')
throw (e);
throw (new KeyParseError(options.filename, format, e));
}
};
Key.isKey = function (obj, ver) {
return (utils.isCompatible(obj, Key, ver));
};
/*
* API versions for Key:
* [1,0] -- initial ver, may take Signature for createVerify or may not
* [1,1] -- added pkcs1, pkcs8 formats
* [1,2] -- added auto, ssh-private, openssh formats
* [1,3] -- added defaultHashAlgorithm
* [1,4] -- added ed support, createDH
* [1,5] -- first explicitly tagged version
*/
Key.prototype._sshpkApiVersion = [1, 5];
Key._oldVersionDetect = function (obj) {
assert.func(obj.toBuffer);
assert.func(obj.fingerprint);
if (obj.createDH)
return ([1, 4]);
if (obj.defaultHashAlgorithm)
return ([1, 3]);
if (obj.formats['auto'])
return ([1, 2]);
if (obj.formats['pkcs1'])
return ([1, 1]);
return ([1, 0]);
};
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">{
"Info": [
{
"IsSuccess": "True",
"InAddress": "新北市板橋區館前西路132號(1樓)",
"InSRS": "EPSG:4326",
"InFuzzyType": "[單雙號機制]+[最近門牌號機制]",
"InFuzzyBuffer": "0",
"InIsOnlyFullMatch": "False",
"InIsLockCounty": "True",
"InIsLockTown": "False",
"InIsLockVillage": "False",
"InIsLockRoadSection": "False",
"InIsLockLane": "False",
"InIsLockAlley": "False",
"InIsLockArea": "False",
"InIsSameNumber_SubNumber": "True",
"InCanIgnoreVillage": "True",
"InCanIgnoreNeighborhood": "True",
"InReturnMaxCount": "0",
"OutTotal": "1",
"OutMatchType": "完全比對",
"OutMatchCode": "[新北市]\tFULL:1",
"OutTraceInfo": "[新北市]\t { 完全比對 } 找到符合的門牌地址"
}
],
"AddressList": [
{
"FULL_ADDR": "新北市板橋區流芳里8鄰館前西路132號",
"COUNTY": "新北市",
"TOWN": "板橋區",
"VILLAGE": "流芳里",
"NEIGHBORHOOD": "8鄰",
"ROAD": "館前西路",
"SECTION": "",
"LANE": "",
"ALLEY": "",
"SUB_ALLEY": "",
"TONG": "",
"NUMBER": "132號",
"X": 121.456502,
"Y": 25.007905
}
]
}</string> | {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.