answer stringlengths 15 1.25M |
|---|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<title>Units (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Units (POI API Documentation)";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar_top">
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Units.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/apache/poi/util/<API key>.html" title="interface in org.apache.poi.util"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/apache/poi/util/XMLHelper.html" title="class in org.apache.poi.util"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/poi/util/Units.html" target="_top">Frames</a></li>
<li><a href="Units.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
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><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<div class="subTitle">org.apache.poi.util</div>
<h2 title="Class Units" class="title">Class Units</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.apache.poi.util.Units</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="strong">Units</span>
extends java.lang.Object</pre>
<dl><dt><span class="strong">Author:</span></dt>
<dd>Yegor Kozlov</dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="field_summary">
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/poi/util/Units.html#EMU_PER_PIXEL">EMU_PER_PIXEL</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/poi/util/Units.html#EMU_PER_POINT">EMU_PER_POINT</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../org/apache/poi/util/Units.html#Units()">Units</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="method_summary">
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</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>
<tr class="altColor">
<td class="colFirst"><code>static double</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/poi/util/Units.html#fixedPointToDecimal(int)">fixedPointToDecimal</a></strong>(int fixedPoint)</code>
<div class="block">Converts a value of type FixedPoint to a decimal number</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/poi/util/Units.html#toEMU(double)">toEMU</a></strong>(double points)</code>
<div class="block">Converts points to EMUs</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static double</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/poi/util/Units.html#toPoints(long)">toPoints</a></strong>(long emu)</code>
<div class="block">Converts EMUs to points</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="<API key>.lang.Object">
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="field_detail">
</a>
<h3>Field Detail</h3>
<a name="EMU_PER_PIXEL">
</a>
<ul class="blockList">
<li class="blockList">
<h4>EMU_PER_PIXEL</h4>
<pre>public static final int EMU_PER_PIXEL</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../constant-values.html#org.apache.poi.util.Units.EMU_PER_PIXEL">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="EMU_PER_POINT">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>EMU_PER_POINT</h4>
<pre>public static final int EMU_PER_POINT</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../constant-values.html#org.apache.poi.util.Units.EMU_PER_POINT">Constant Field Values</a></dd></dl>
</li>
</ul>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
</a>
<h3>Constructor Detail</h3>
<a name="Units()">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>Units</h4>
<pre>public Units()</pre>
</li>
</ul>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="method_detail">
</a>
<h3>Method Detail</h3>
<a name="toEMU(double)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>toEMU</h4>
<pre>public static int toEMU(double points)</pre>
<div class="block">Converts points to EMUs</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>points</code> - points</dd>
<dt><span class="strong">Returns:</span></dt><dd>emus</dd></dl>
</li>
</ul>
<a name="toPoints(long)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>toPoints</h4>
<pre>public static double toPoints(long emu)</pre>
<div class="block">Converts EMUs to points</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>emu</code> - emu</dd>
<dt><span class="strong">Returns:</span></dt><dd>points</dd></dl>
</li>
</ul>
<a name="fixedPointToDecimal(int)">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>fixedPointToDecimal</h4>
<pre>public static double fixedPointToDecimal(int fixedPoint)</pre>
<div class="block">Converts a value of type FixedPoint to a decimal number</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>fixedPoint</code> - </dd>
<dt><span class="strong">Returns:</span></dt><dd>decimal number</dd><dt><span class="strong">See Also:</span></dt><dd><a href="http://msdn.microsoft.com/en-us/library/dd910765(v=office.12).aspx">[MS-OSHARED] - 2.2.1.6 FixedPoint</a></dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</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/Units.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/apache/poi/util/<API key>.html" title="interface in org.apache.poi.util"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/apache/poi/util/XMLHelper.html" title="class in org.apache.poi.util"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/poi/util/Units.html" target="_top">Frames</a></li>
<li><a href="Units.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
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><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
</a></div>
<p class="legalCopy"><small>
<i>Copyright 2015 The Apache Software Foundation or
its licensors, as applicable.</i>
</small></p>
</body>
</html> |
// This file was generated based on '(multiple files)'.
// WARNING: Changes might be lost if you edit this file directly.
#include <Android.android.net.Uri.h>
#include <Android.Base.<API key>.h>
#include <Android.Base.JNI.h>
#include <Android.Base.Primitives.jmethodID.h>
#include <Android.Base.Primitives.ujclass.h>
#include <Android.Base.Primitives.ujobject.h>
#include <Android.Base.Wrappers.JWrapper.h>
#include <Android.Fallbacks.<API key>.h>
#include <Android.java.lang.String.h>
#include <Uno.Bool.h>
#include <Uno.Exception.h>
#include <Uno.Int.h>
static uType* TYPES[2];
namespace g{
namespace Android{
namespace android{
namespace net{
// C:\ProgramData\Uno\Packages\Android\0.20.2\Android\android\net\$.uno(11)
// public abstract extern class Uri :11
::g::Android::java::lang::Object_type* Uri_typeof()
{
static uSStrong< ::g::Android::java::lang::Object_type*> type;
if (type != NULL) return type;
uTypeOptions options;
options.FieldCount = 8;
options.InterfaceCount = 2;
options.ObjectSize = sizeof(Uri);
options.TypeSize = sizeof(::g::Android::java::lang::Object_type);
type = (::g::Android::java::lang::Object_type*)uClassType::New("Android.android.net.Uri", options);
type->SetBase(::g::Android::java::lang::Object_typeof());
type->fp_hashCode1 = (void(*)(::g::Android::java::lang::Object*, int*))Uri__hashCode1_fn;
type->interface0.fp__GetJavaObject = (void(*)(uObject*, jobject*))::g::Android::Base::Wrappers::<API key>;
type->interface0.fp__IsSubclassed = (void(*)(uObject*, bool*))::g::Android::Base::Wrappers::<API key>;
type->interface1.fp_Dispose = (void(*)(uObject*))::g::Android::Base::Wrappers::<API key>;
::TYPES[0] = ::g::Android::Base::Wrappers::JWrapper_typeof();
::TYPES[1] = ::g::Android::Base::Wrappers::IJWrapper_typeof();
type->SetInterfaces(
::g::Android::Base::Wrappers::IJWrapper_typeof(), offsetof(::g::Android::java::lang::Object_type, interface0),
::g::Uno::IDisposable_typeof(), offsetof(::g::Android::java::lang::Object_type, interface1));
type->SetFields(5,
::g::Android::Base::Primitives::ujclass_typeof(), (uintptr_t)&::g::Android::android::net::Uri::_javaClass2_, uFieldFlagsStatic,
::g::Android::Base::Primitives::jmethodID_typeof(), (uintptr_t)&::g::Android::android::net::Uri::hashCode_10992_ID_, uFieldFlagsStatic,
::g::Android::Base::Primitives::jmethodID_typeof(), (uintptr_t)&::g::Android::android::net::Uri::parse_10996_ID_, uFieldFlagsStatic);
return type;
}
// public static extern new void _Init() :15
void Uri___Init2_fn()
{
Uri::_Init2();
}
// public override sealed int hashCode() :129
void Uri__hashCode1_fn(Uri* __this, int* __retval)
{
return *__retval = Uri::hashCode_IMPL_10992(__this->_subclassed, __this->_javaObject), void();
}
// public static extern int hashCode_IMPL_10992(bool arg0, Android.Base.Primitives.ujobject arg1) :247
void <API key>(bool* arg0_, jobject* arg1_, int* __retval)
{
*__retval = Uri::hashCode_IMPL_10992(*arg0_, *arg1_);
}
// public static Android.android.net.Uri parse(Android.java.lang.String arg0) :144
void Uri__parse_fn(::g::Android::java::lang::String* arg0, Uri** __retval)
{
*__retval = Uri::parse(arg0);
}
// public static extern Android.Base.Wrappers.IJWrapper parse_IMPL_10996(Android.Base.Wrappers.IJWrapper arg0) :253
void <API key>(uObject* arg0_, uObject** __retval)
{
*__retval = Uri::parse_IMPL_10996(arg0_);
}
jclass Uri::_javaClass2_;
jmethodID Uri::hashCode_10992_ID_;
jmethodID Uri::parse_10996_ID_;
// public static extern new void _Init() [static] :15
void Uri::_Init2()
{
if (Uri::_javaClass2()) { return; }
INIT_JNI;
Uri::_javaClass2() = NEW_GLOBAL_REF(jclass,LOAD_SYS_CLASS("android/net/Uri"));
::g::Android::Base::JNI::CheckException1(U_JNIVAR);
if (!Uri::_javaClass2()) { THROW_UNO_EXCEPTION("Unable to cache class 'android.net.Uri'", 39);; }
}
// public static extern int hashCode_IMPL_10992(bool arg0, Android.Base.Primitives.ujobject arg1) [static] :247
int Uri::hashCode_IMPL_10992(bool arg0_, jobject arg1_)
{
INIT_JNI;
CLASS_INIT(Uri::_javaClass2(),Uri::_Init2());
int result;
CACHE_METHOD(Uri::hashCode_10992_ID(),Uri::_javaClass2(),"hashCode","()I",GetMethodID,"Id for fallback method android.net.Uri.hashCode could not be cached",67);
if (arg0_) {
result = ((int)U_JNIVAR-><API key>(arg1_, Uri::_javaClass2(), Uri::hashCode_10992_ID()));
}
else
{
result = ((int)U_JNIVAR->CallIntMethod(arg1_, Uri::hashCode_10992_ID()));
}
::g::Android::Base::JNI::CheckException1(U_JNIVAR);
return result;
}
// public static Android.android.net.Uri parse(Android.java.lang.String arg0) [static] :144
Uri* Uri::parse(::g::Android::java::lang::String* arg0)
{
return uCast<Uri*>(Uri::parse_IMPL_10996((uObject*)arg0), Uri_typeof());
}
// public static extern Android.Base.Wrappers.IJWrapper parse_IMPL_10996(Android.Base.Wrappers.IJWrapper arg0) [static] :253
uObject* Uri::parse_IMPL_10996(uObject* arg0_)
{
INIT_JNI;
CLASS_INIT(Uri::_javaClass2(),Uri::_Init2());
jobject _obArg0 = ((!arg0_) ? NULL : ::g::Android::Base::Wrappers::IJWrapper::_GetJavaObject(uInterface(arg0_, ::g::Android::Base::Wrappers::IJWrapper_typeof())));
uObject* result;
CACHE_METHOD(Uri::parse_10996_ID(),Uri::_javaClass2(),"parse","(Ljava/lang/String;)Landroid/net/Uri;",GetStaticMethodID,"Id for fallback method android.net.Uri.parse could not be cached",64);
NEW_UNO(U_JNIVAR-><API key>(Uri::_javaClass2(), Uri::parse_10996_ID(), _obArg0),result,::g::Android::Fallbacks::<API key>(),Uri*,true,true);
::g::Android::Base::JNI::CheckException1(U_JNIVAR);
return result;
}
}}}} // ::g::Android::android::net |
sihugh.github.io
=============

Pages site. Have moved the hosting for this to Azure websites. Committing to this repo now kicks off a Travis CI build and commits a successful result to https://github.com/sihugh/alt-pgdn-release where Azure picks it up. |
#include "<API key>.h"
#include <stdio.h>
#include <stdlib.h>
#include "../NUS_log.h"
#include "../NUS_vulkan.h"
static void <API key>(<API key> *);
NUS_result <API key>
(VkDevice device, unsigned int family_index, unsigned int queue_index,
<API key> *p_submission_queue)
{
VkFenceCreateInfo fence_info = {
.sType = <API key>,
.pNext = NULL,
.flags = 0
};
if(vkCreateFence(device, &fence_info, NULL, &p_submission_queue->queue_finished) !=
VK_SUCCESS){
NUS_LOG_ERROR("failed to create submission_queue finished fence\n");
return NUS_FAILURE;
}
vkGetDeviceQueue(device, family_index, queue_index, &p_submission_queue->queue);
p_submission_queue->info = (VkSubmitInfo){
.sType = <API key>,
.pNext = NULL,
.waitSemaphoreCount = 0,
.pWaitSemaphores = p_submission_queue->wait_sem,
.pWaitDstStageMask = p_submission_queue->wait_dst_mask,
.commandBufferCount = 0,
.pCommandBuffers = p_submission_queue->buffer,
.<API key> = 0,
.pSignalSemaphores = p_submission_queue->signal_sem
};
return NUS_SUCCESS;
}
void <API key>
(<API key> *p_submission_queue, VkDevice logical_device)
{
vkQueueWaitIdle(p_submission_queue->queue);
vkDestroyFence(logical_device, p_submission_queue->queue_finished, NULL);
}
NUS_result <API key>
(<API key> *p_submission_queue, VkSemaphore wait_semaphore,
<API key> flags)
{
int semaphore_index = p_submission_queue->info.waitSemaphoreCount;
if(++p_submission_queue->info.waitSemaphoreCount >=
<API key>){
NUS_LOG_ERROR("failed to add wait semaphore to submission_queue\n");
return NUS_FAILURE;
}
p_submission_queue->wait_sem[semaphore_index] = wait_semaphore;
p_submission_queue->wait_dst_mask[semaphore_index] = flags;
return NUS_SUCCESS;
}
NUS_result <API key>
(<API key> *p_submission_queue, VkSemaphore signal_semaphore)
{
int semaphore_index = p_submission_queue->info.<API key>;
if(++p_submission_queue->info.<API key> >=
<API key>){
NUS_LOG_ERROR("failed to add signal semaphore to submission_queue\n");
return NUS_FAILURE;
}
p_submission_queue->signal_sem[semaphore_index] = signal_semaphore;
return NUS_SUCCESS;
}
NUS_result <API key>
(<API key> *p_submission_queue, VkCommandBuffer command_buffer)
{
int buffer_index = p_submission_queue->info.commandBufferCount;
if(++p_submission_queue->info.commandBufferCount >=
<API key>){
NUS_LOG_ERROR("failed to add command buffer to submission_queue\n");
return NUS_FAILURE;
}
p_submission_queue->buffer[buffer_index] = command_buffer;
return NUS_SUCCESS;
}
NUS_result <API key>
(<API key> *p_submission_queue, VkDevice logical_device)
{
if(p_submission_queue->info.commandBufferCount > 0){
// If there are command buffers to submit
vkQueueWaitIdle(p_submission_queue->queue);
vkResetFences(logical_device, 1, &p_submission_queue->queue_finished);
if(vkQueueSubmit(p_submission_queue->queue, 1, &p_submission_queue->info,
p_submission_queue->queue_finished) != VK_SUCCESS){
NUS_LOG_ERROR("failed queue submission_queue\n");
return NUS_FAILURE;
}
<API key>(p_submission_queue);
}
return NUS_SUCCESS;
}
NUS_result <API key>
(<API key> *p_submission_queue, VkDevice logical_device)
{
if(vkWaitForFences(logical_device, 1, &p_submission_queue->queue_finished,
VK_TRUE, <API key>) == VK_TIMEOUT){
// If the previous submission_queue is taking an extreme ammount of time
NUS_LOG_ERROR("submission_queue finished fence timeout\n");
return NUS_FAILURE;
}
return NUS_SUCCESS;
}
static void <API key>(<API key> *p_submission_queue)
{
p_submission_queue->info.waitSemaphoreCount = 0;
p_submission_queue->info.commandBufferCount = 0;
p_submission_queue->info.<API key> = 0;
} |
# Keystone Social Login
## v0.1.3 / 2015-02-23
* adding Node.js 0.12 to Travis-CI config
## v0.1.2 / 2015-02-23
* adding compatibility warning with [Keystone 0.3.x](http://keystonejs.com/)
* updated `less-middleware` to version `2.0.0`
* updated `chai` to version `2.0.0`
## v0.1.1 / 2015-01-25
* updated `less-middleware` to version `1.0.4`
* updated `passport` to version `0.2.1`
* updated `serve-static` to version `1.8.1`
* updated `underscore` to version `1.7.0`
* updated `chai` to version `1.10.0`
* updated `gulp` to version `3.8.10`
* updated `gulp-coverage` to version `0.3.32`
* updated `gulp-jshint` to version `1.9.0`
* updated `gulp-mocha` to version `2.0.0`
* updated `mocha` to version `2.1.0`
* updated `sinon` to version `1.12.2`
* updated `sinon-chai` to version `2.6.0`
## v0.1.0 / 2014-08-19
* includes support for [KeystoneJS 0.2.x](http://keystonejs.com/)
* includes support for Facebook OAuth 2.0 with [passport-facebook](https://github.com/jaredhanson/passport-facebook)
* includes support for Google OAuth 2.0 with [<API key>](https://github.com/jaredhanson/<API key>)
* includes support for GitHub OAuth 2.0 with [passport-github](https://github.com/jaredhanson/passport-github)
* includes support for Twitter OAuth with [passport-twitter](https://github.com/jaredhanson/passport-twitter)
* added unit tests for core functionality
* added initial api documenation |
#include "<API key>.h"
<API key>::<API key>(){
ofxAnimatable::setup(); //defaults to (0,0,0) >> (0,0,0)
}
void <API key>::update(float dt){
ofxAnimatable::update( dt );
}
void <API key>::draw(){
ofPushMatrix();
ofPoint p = getCurrentPosition();
ofTranslate(p.x, p.y, p.z);
float s = 10.0f;
ofRect( -s * 0.5f, -s * 0.5f, s, s );
ofPopMatrix();
}
void <API key>::setPosition( ofPoint newPos ){
ofxAnimatable::reset();
originalPoint_ = newPos;
targetPoint_ = newPos;
}
void <API key>::setPositionX( float newX ){
originalPoint_ = getCurrentPosition();
originalPoint_.x = newX;
targetPoint_ = originalPoint_;
ofxAnimatable::reset();
}
void <API key>::setPositionY( float newY ){
originalPoint_ = getCurrentPosition();
originalPoint_.y = newY;
targetPoint_ = originalPoint_;
ofxAnimatable::reset();
}
void <API key>::setPositionZ( float newZ ){
originalPoint_ = getCurrentPosition();
originalPoint_.z = newZ;
targetPoint_ = originalPoint_;
ofxAnimatable::reset();
}
void <API key>::reset(){
ofxAnimatable::reset();
targetPoint_ = originalPoint_;
}
void <API key>::animateTo( ofPoint where ){
originalPoint_ = getCurrentPosition();
targetPoint_ = where;
ofxAnimatable::startAnimation();
}
void <API key>::animateToAfterDelay( ofPoint where, float delay ){
if (delay <= 0.0f){
animateTo(where);
}else{
//originalTempPoint_ = getCurrentPosition();
targetTempPoint_ = where;
ofxAnimatable::<API key>(delay);
}
}
void <API key>::animateToIfFinished( ofPoint where ){
if (animating_ == false){
animateTo(where);
}
}
ofPoint <API key>::getCurrentPosition(){
float mappedDistribution = calcCurveAt(percentDone_); ///percentDone_ is [0..1] & tells me where we are between orig and target
return originalPoint_ + ( targetPoint_ - originalPoint_) * mappedDistribution ;
}
void <API key>::startAfterWait(){
animateTo(targetTempPoint_);
} |
require 'spec_helper'
# Snippet visibility scenarios are included in more details in spec/support/snippet_visibility.rb
describe <API key> do
let(:regular_user) { create(:user) }
let(:external_user) { create(:user, :external) }
let(:project) { create(:project, :public) }
let(:snippet) { create(:project_snippet, snippet_visibility, project: project) }
let(:author_permissions) do
[
:<API key>,
:<API key>
]
end
subject { described_class.new(current_user, snippet) }
context 'public snippet' do
let(:snippet_visibility) { :public }
context 'no user' do
let(:current_user) { nil }
it do
expect_allowed(:<API key>)
expect_disallowed(*author_permissions)
end
end
context 'regular user' do
let(:current_user) { regular_user }
it do
expect_allowed(:<API key>, :create_note)
expect_disallowed(*author_permissions)
end
end
context 'external user' do
let(:current_user) { external_user }
it do
expect_allowed(:<API key>, :create_note)
expect_disallowed(*author_permissions)
end
end
end
context 'internal snippet' do
let(:snippet_visibility) { :internal }
context 'no user' do
let(:current_user) { nil }
it do
expect_disallowed(:<API key>)
expect_disallowed(*author_permissions)
end
end
context 'regular user' do
let(:current_user) { regular_user }
it do
expect_allowed(:<API key>, :create_note)
expect_disallowed(*author_permissions)
end
end
context 'external user' do
let(:current_user) { external_user }
it do
expect_disallowed(:<API key>, :create_note)
expect_disallowed(*author_permissions)
end
context 'project team member' do
before do
project.add_developer(external_user)
end
it do
expect_allowed(:<API key>, :create_note)
expect_disallowed(*author_permissions)
end
end
end
end
context 'private snippet' do
let(:snippet_visibility) { :private }
context 'no user' do
let(:current_user) { nil }
it do
expect_disallowed(:<API key>)
expect_disallowed(*author_permissions)
end
end
context 'regular user' do
let(:current_user) { regular_user }
it do
expect_disallowed(:<API key>, :create_note)
expect_disallowed(*author_permissions)
end
context 'snippet author' do
let(:snippet) { create(:project_snippet, :private, author: regular_user, project: project) }
it do
expect_allowed(:<API key>, :create_note)
expect_allowed(*author_permissions)
end
end
context 'project team member normal user' do
before do
project.add_developer(regular_user)
end
it do
expect_allowed(:<API key>, :create_note)
expect_disallowed(*author_permissions)
end
end
end
context 'external user' do
context 'project team member' do
let(:current_user) { external_user }
before do
project.add_developer(external_user)
end
it do
expect_allowed(:<API key>, :create_note)
expect_disallowed(*author_permissions)
end
end
end
context 'admin user' do
let(:snippet_visibility) { :private }
let(:current_user) { create(:admin) }
it do
expect_allowed(:<API key>, :create_note)
expect_allowed(*author_permissions)
end
end
end
end |
<?php namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Foundation\Inspiring;
class Inspire extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'inspire';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Display an inspiring quote';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->comment(PHP_EOL.Inspiring::quote().PHP_EOL);
}
} |
import cv2
def outlineRect(image, rect, color):
if rect is None:
return
x, y, w, h = rect
cv2.rectangle(image, (x, y), (x+w, y+h), color)
def copyRect(src, dst, srcRect, dstRect,
interpolation = cv2.INTER_LINEAR):
"""Copy part of the source to part of the destination."""
x0, y0, w0, h0 = srcRect
x1, y1, w1, h1 = dstRect
# Resize the contents of the source sub-rectangle.
# Put the result in the destination sub-rectangle.
dst[y1:y1+h1, x1:x1+w1] = \
cv2.resize(src[y0:y0+h0, x0:x0+w0], (w1, h1),
interpolation = interpolation)
def swapRects(src, dst, rects,
interpolation = cv2.INTER_LINEAR):
"""Copy the source with two or more sub-rectangles swapped."""
if dst is not src:
dst[:] = src
numRects = len(rects)
if numRects < 2:
return
# Copy the contents of the last rectangle into temporary storage.
x, y, w, h = rects[numRects - 1]
temp = src[y:y+h, x:x+w].copy()
# Copy the contents of each rectangle into the next.
i = numRects - 2
while i >= 0:
copyRect(src, dst, rects[i], rects[i+1], interpolation)
i -= 1
# Copy the temporarily stored content into the first rectangle.
copyRect(temp, dst, (0, 0, w, h), rects[0], interpolation) |
require 'json'
require 'kitchen'
require 'chef/provisioning/vsphere_driver'
require 'chef/provisioning/machine_spec'
module Kitchen
module Driver
class Vsphere < Kitchen::Driver::Base
@@chef_zero_server = false
default_config :machine_options,
:start_timeout => 600,
:create_timeout => 600,
:stop_timeout => 600,
:ready_timeout => 90,
:bootstrap_options => {
:use_linked_clone => true,
:ssh => {
:user => 'root',
:paranoid => false,
:port => 22
},
:convergence_options => {},
:customization_spec => {
:domain => 'local'
}
}
default_config(:vsphere_name) do |driver|
"#{driver.instance.name}-#{SecureRandom.hex(4)}"
end
def create(state)
state[:vsphere_name] = config[:vsphere_name]
state[:username] = config[:machine_options][:bootstrap_options][:ssh][:user]
state[:password] = config[:machine_options][:bootstrap_options][:ssh][:password]
config[:server_name] = state[:vsphere_name]
machine = <API key>(state) do | action_handler, driver, machine_spec|
driver.allocate_machine(action_handler, machine_spec, config[:machine_options])
driver.ready_machine(action_handler, machine_spec, config[:machine_options])
state[:server_id] = machine_spec.location['server_id']
state[:hostname] = machine_spec.location['ipaddress']
machine_spec.save(action_handler)
end
end
def destroy(state)
return if state[:server_id].nil?
<API key>(state) do | action_handler, driver, machine_spec|
machine_spec.location = { 'driver_url' => driver.driver_url,
'server_id' => state[:server_id]}
driver.destroy_machine(action_handler, machine_spec, config[:machine_options])
end
state.delete(:server_id)
state.delete(:hostname)
state.delete(:vsphere_name)
end
def <API key>(state, &block)
config[:machine_options][:convergence_options] = {:chef_server => chef_server}
machine_spec = Chef::Provisioning.<API key>(chef_server).get(:machine, state[:vsphere_name])
if machine_spec.nil?
machine_spec = Chef::Provisioning.<API key>(chef_server)
.new_entry(:machine, state[:vsphere_name])
end
url = URI::VsphereUrl.from_config(@config[:driver_options]).to_s
driver = Chef::Provisioning.driver_for_url(url, config)
action_handler = Chef::Provisioning::ActionHandler.new
block.call(action_handler, driver, machine_spec)
end
def chef_server
if !@@chef_zero_server
vsphere_mutex.synchronize do
if !@@chef_zero_server
Chef::Config.local_mode = true
Chef::Config.chef_repo_path = Chef::Config.find_chef_repo_path(Dir.pwd)
require 'chef/local_mode'
Chef::LocalMode.<API key>
@@chef_zero_server = true
end
end
end
Cheffish.default_chef_server
end
def vsphere_mutex
@@vsphere_mutex ||= begin
Kitchen.mutex.synchronize do
instance.class.mutexes ||= Hash.new
instance.class.mutexes[self.class] = Mutex.new
end
instance.class.mutexes[self.class]
end
end
end
end
end |
require 'rails_helper'
describe FileUpload::Create do
before(:all) do
FileUpload.directory.files.each { |f| f.destroy }
end
let(:uploaded_file) do
ActionDispatch::Http::UploadedFile.new({
tempfile: File.open('spec/fixtures/images/avatar.jpg'),
filename: 'avatar.jpeg',
type: "image/jpeg"
})
end
let(:uploader) { create(:user) }
it "can store a file" do
upload = FileUpload::Create.run!({
file: uploaded_file,
uploadable: uploader,
uploader: uploader,
upload_type: :file,
is_public: false
})
uploaded_file.tempfile.rewind
original_data = uploaded_file.tempfile.read
expect(upload.read).to eq(original_data)
expect(upload.uploader).to eq(uploader)
expect(upload.uploadable).to eq(uploader)
expect(FileUpload.directory.files.get(upload.file_path).body).to_not eq(original_data)
end
end |
require File.dirname(__FILE__) + '/../lib/benchutils'
label = File.expand_path(__FILE__).sub(File.expand_path("..") + "/", "")
iterations = ARGV[-3].to_i
timeout = ARGV[-2].to_i
report = ARGV.last
BAILOUT = 16
MAX_ITERATIONS = 1000
class Mandelbrot
def initialize
puts "Rendering"
for y in -39...39 do
puts
for x in -39...39 do
i = iterate(x/40.0,y/40.0)
if (i == 0)
print "*"
else
print " "
end
end
end
end
def iterate(x,y)
cr = y-0.5
ci = x
zi = 0.0
zr = 0.0
i = 0
while(1)
i += 1
temp = zr * zi
zr2 = zr * zr
zi2 = zi * zi
zr = zr2 - zi2 + cr
zi = temp + temp + ci
return i if (zi2 + zr2 > BAILOUT)
return 0 if (i > MAX_ITERATIONS)
end
end
end
benchmark = BenchmarkRunner.new(label, iterations, timeout)
benchmark.run do
5.times do
Mandelbrot.new
end
end
File.open(report, "a") {|f| f.puts "#{benchmark.to_s},n/a" } |
package com.microsoft.azure.management.maintenance.v2018_06_01_preview.implementation;
import com.microsoft.azure.management.maintenance.v2018_06_01_preview.OperationInfo;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Represents an operation returned by the GetOperations request.
*/
public class OperationInner {
/**
* Name of the operation.
*/
@JsonProperty(value = "name")
private String name;
/**
* Display name of the operation.
*/
@JsonProperty(value = "display")
private OperationInfo display;
/**
* Origin of the operation.
*/
@JsonProperty(value = "origin")
private String origin;
/**
* Properties of the operation.
*/
@JsonProperty(value = "properties")
private Object properties;
/**
* Get name of the operation.
*
* @return the name value
*/
public String name() {
return this.name;
}
/**
* Set name of the operation.
*
* @param name the name value to set
* @return the OperationInner object itself.
*/
public OperationInner withName(String name) {
this.name = name;
return this;
}
/**
* Get display name of the operation.
*
* @return the display value
*/
public OperationInfo display() {
return this.display;
}
/**
* Set display name of the operation.
*
* @param display the display value to set
* @return the OperationInner object itself.
*/
public OperationInner withDisplay(OperationInfo display) {
this.display = display;
return this;
}
/**
* Get origin of the operation.
*
* @return the origin value
*/
public String origin() {
return this.origin;
}
/**
* Set origin of the operation.
*
* @param origin the origin value to set
* @return the OperationInner object itself.
*/
public OperationInner withOrigin(String origin) {
this.origin = origin;
return this;
}
/**
* Get properties of the operation.
*
* @return the properties value
*/
public Object properties() {
return this.properties;
}
/**
* Set properties of the operation.
*
* @param properties the properties value to set
* @return the OperationInner object itself.
*/
public OperationInner withProperties(Object properties) {
this.properties = properties;
return this;
}
} |
<?php
namespace PHPExiftool\Driver\Tag\ASF;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class ImageHeight extends AbstractTag
{
protected $Id = 58;
protected $Name = 'ImageHeight';
protected $FullName = 'ASF::StreamProperties';
protected $GroupName = 'ASF';
protected $g0 = 'ASF';
protected $g1 = 'ASF';
protected $g2 = 'Video';
protected $Type = 'int32u';
protected $Writable = false;
protected $Description = 'Image Height';
protected $Index = 1;
} |
# SwaggerYard #
The SwaggerYard gem is a Rails Engine designed to parse your Yardocs API controller.
It'll create a Swagger-UI complaint JSON to be served out through where you mount SwaggerYard.
You can mount this to the Rails app serving the REST API or you could mount it as a separate Rails app.
Parsing of the Yardocs happens during the server startup and the data will be subsequently cached to the Rails cache you have defined.
If your API is large expect a slow server start up time.
## Installation ##
Put SwaggerYard in your Gemfile:
gem 'swagger_yard'
Install the gem with Bunder:
bundle install
## Getting Started ##
Place your configuration in a your rails initializers
# config/initializers/swagger_yard.rb
SwaggerYard.configure do |config|
config.swagger_version = "1.2"
config.api_version = "1.0"
config.reload = Rails.env.development?
# where your swagger spec json will show up
config.<API key> = "http://localhost:3000/swagger/api"
# where your actual api is hosted from
config.api_base_path = "http://localhost:3000/api"
end
Mount your engine
# config/routes.rb
mount SwaggerYard::Engine, at: "/swagger"
## Example Documentation ##
Here is an example of how to use SwaggerYard in your Controller
**Note:** Model references should be Capitalized or CamelCased, basic types (integer, boolean, string, etc) should be lowercased everywhere.
ruby
# @resource Account ownership
# @resource_path /accounts/ownerships
# This document describes the API for creating, reading, and deleting account ownerships.
class Accounts::<API key> < ActionController::Base
# Returns a list of ownerships associated with the account.
# @notes Status can be -1(Deleted), 0(Inactive), 1(Active), 2(Expired) and 3(Cancelled).
# @path [GET] /accounts/ownerships.{format_type}
# @parameter offset [integer] Used for pagination of response data (default: 25 items per response). Specifies the offset of the next block of data to receive.
# @parameter status [array<string>] Filter by status. (e.g. status[]=1&status[]=2&status[]=3).
# @parameter_list [String] sort_order Orders response by fields. (e.g. sort_order=created_at).
# [List] id
# [List] begin_at
# [List] end_at
# [List] created_at
# @parameter sort_descending [boolean] Reverse order of sort_order sorting, make it descending.
# @parameter begin_at_greater [date] Filters response to include only items with begin_at >= specified timestamp (e.g. begin_at_greater=2012-02-15T02:06:56Z).
# @parameter begin_at_less [date] Filters response to include only items with begin_at <= specified timestamp (e.g. begin_at_less=2012-02-15T02:06:56Z).
# @parameter end_at_greater [date] Filters response to include only items with end_at >= specified timestamp (e.g. end_at_greater=2012-02-15T02:06:56Z).
# @parameter end_at_less [date] Filters response to include only items with end_at <= specified timestamp (e.g. end_at_less=2012-02-15T02:06:56Z).
def index
end
# Returns an ownership for an account by id
# @path [GET] /accounts/ownerships/{id}.{format_type}
# @response_type [Ownership]
# @error_message [EmptyOwnership] 404 Ownership not found
# @error_message 400 Invalid ID supplied
def show
end
end
Here is an example of how to use SwaggerYard in your Model
ruby
# @model Pet
# @property id(required) [integer] the identifier for the pet
# @property name [Array<string>] the names for the pet
# @property age [integer] the age of the pet
# @property relatives(required) [Array<Pet>] other Pets in its family
class Pet
end
To then use your `Model` in your `Controller` documentation, add `@parameter`s:
ruby
# @parameter [Pet] pet The pet object
## Authorization ##
Currently, SwaggerYard only supports API Key auth descriptions. Start by adding `@authorization` to your `<API key>`.
ruby
# @authorization [api_key] header <API key>
class <API key> < ActionController::Base
end
Then you can use these authorizations from your controller or actions in a controller. The name comes from either header or query plus the name of the key downcased/underscored.
ruby
# @authorize_with <API key>
class PetController < <API key>
end

## Seeing the Swagger JSON ##
You should now be able to start your application and visit `http://local-dev.domain:port/swagger/doc` (if the engine is mounted at `/swagger` as above). You should see the output list each of the controllers you documented, and the paths to see their specific APIs.
To see a specific controller visit `http://local-dev.domain:port/swagger/api/accounts/ownerships` as given in the `@resource_path` in the example above.
## Generators ##
There are two generators that you can use, if you need to customize the UI/JS (optional)
rails g swagger_yard:ui
rails g swagger_yard:js
They both copy over their respective files over to your Rails app to be customized.
See [rails engines overriding views](http://guides.rubyonrails.org/engines.html#overriding-views) for more info
Copying over JS requires that ActionDispatch::Static middleware be used (by default it should in use).
## Notes ##
By default SwaggerYard will use a slightly modify version of the swagger-ui. Changes to the JS code are indicated with "SwaggerYard changes" comments. The changes are mainly to support Rails way of supporting an array of parameters.
## More Information ##
* [Swagger-ui](https://github.com/wordnik/swagger-ui)
* [Yard](https://github.com/lsegal/yard)
* [Swagger-spec version 1.2](https://github.com/wordnik/swagger-spec/blob/master/versions/1.2.md) |
<?php
namespace Flarum\Flags;
use Flarum\Api\Controller;
use Flarum\Flags\Api\Controller\<API key>;
use Flarum\Http\RequestUtil;
use Illuminate\Database\Eloquent\Collection;
use Psr\Http\Message\<API key>;
class PrepareFlagsApiData
{
public function __invoke(Controller\<API key> $controller, $data, <API key> $request)
{
// For any API action that allows the 'flags' relationship to be
// included, we need to preload this relationship onto the data (Post
// models) so that we can selectively expose only the flags that the
if ($controller instanceof Controller\<API key>) {
if ($data->relationLoaded('posts')) {
$posts = $data->getRelation('posts');
}
}
if ($controller instanceof Controller\ListPostsController) {
$posts = $data->all();
}
if ($controller instanceof Controller\ShowPostController) {
$posts = [$data];
}
if ($controller instanceof <API key>) {
$posts = [$data->post];
}
if (isset($posts)) {
$actor = RequestUtil::getActor($request);
$postsWithPermission = [];
foreach ($posts as $post) {
if (is_object($post)) {
$post->setRelation('flags', null);
if ($actor->can('viewFlags', $post->discussion)) {
$postsWithPermission[] = $post;
}
}
}
if (count($postsWithPermission)) {
(new Collection($postsWithPermission))
->load('flags', 'flags.user');
}
}
}
} |
namespace Sitecore.FakeDb.Tasks
{
using Sitecore.Tasks;
public class <API key> : <API key><TaskDatabase>
{
public <API key>(TaskDatabase provider)
: base((<API key><TaskDatabase>)Globals.TaskDatabase, provider)
{
}
}
} |
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#pragma once
#include "Color.h"
#include <d3d9.h>
#include <SDL.h>
namespace Urho3D
{
%Graphics implementation. Holds API-specific objects.
class URHO3D_API GraphicsImpl
{
friend class Graphics;
public:
Construct.
GraphicsImpl();
Return Direct3D device.
IDirect3DDevice9* GetDevice() const { return device_; }
Return device capabilities.
const D3DCAPS9& GetDeviceCaps() const { return deviceCaps_; }
Return window.
SDL_Window* GetWindow() const { return window_; }
Return adapter identifier.
const <API key>& <API key>() const { return adapterIdentifier_; }
Return whether a texture format and usage is supported.
bool CheckFormatSupport(D3DFORMAT format, DWORD usage, D3DRESOURCETYPE type);
private:
SDL window.
SDL_Window* window_;
Direct3D interface.
IDirect3D9* interface_;
Direct3D device.
IDirect3DDevice9* device_;
Default color surface.
IDirect3DSurface9* <API key>;
Default depth-stencil surface.
IDirect3DSurface9* <API key>;
Frame query for flushing the GPU command queue.
IDirect3DQuery9* frameQuery_;
Adapter number.
DWORD adapter_;
Device type.
D3DDEVTYPE deviceType_;
Device capabilities.
D3DCAPS9 deviceCaps_;
Adapter identifier.
<API key> adapterIdentifier_;
Direct3D presentation parameters.
<API key> presentParams_;
Texture min/mag filter modes in use.
<API key> minMagFilters_[MAX_TEXTURE_UNITS];
Texture mip filter modes in use.
<API key> mipFilters_[MAX_TEXTURE_UNITS];
Texture U coordinate addressing modes in use.
D3DTEXTUREADDRESS uAddressModes_[MAX_TEXTURE_UNITS];
Texture V coordinate addressing modes in use.
D3DTEXTUREADDRESS vAddressModes_[MAX_TEXTURE_UNITS];
Texture W coordinate addressing modes in use.
D3DTEXTUREADDRESS wAddressModes_[MAX_TEXTURE_UNITS];
Texture border colors in use.
Color borderColors_[MAX_TEXTURE_UNITS];
sRGB mode in use.
bool sRGBModes_[MAX_TEXTURE_UNITS];
sRGB write flag.
bool sRGBWrite_;
Color surfaces in use.
IDirect3DSurface9* colorSurfaces_[MAX_RENDERTARGETS];
Depth-stencil surface in use.
IDirect3DSurface9* <API key>;
Blending enabled flag.
DWORD blendEnable_;
Source blend mode.
D3DBLEND srcBlend_;
Destination blend mode.
D3DBLEND destBlend_;
Blend operation.
D3DBLENDOP blendOp_;
};
} |
goog.provide('app.modifyrectangle');
goog.require('ngeo.interaction.ModifyRectangle');
/** @suppress {extraRequire} */
goog.require('ngeo.mapDirective');
goog.require('ol.Map');
goog.require('ol.View');
goog.require('ol.layer.Tile');
goog.require('ol.layer.Vector');
goog.require('ol.source.OSM');
goog.require('ol.source.Vector');
goog.require('ol.geom.Polygon');
goog.require('ol.Collection');
goog.require('ol.Feature');
goog.require('ol.style.Style');
goog.require('ol.style.Circle');
goog.require('ol.style.Fill');
goog.require('ol.style.Stroke');
/** @type {!angular.Module} **/
var module = angular.module('app', ['ngeo']);
/**
* @constructor
* @ngInject
*/
app.MainController = function() {
/**
* @type {ol.Map}
* @export
*/
this.map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: [-10997148, 4569099],
zoom: 4
})
});
var map = this.map;
var rectangle = new ol.geom.Polygon([[
[-9e6, 4e6], [-11e6, 4e6], [-11e6, 6e6], [-9e6, 6e6]
]]);
/**
* @type {ol.Collection.<ol.Feature>}
* @export
*/
this.features = new ol.Collection();
this.features.push(new ol.Feature({
geometry: rectangle,
'isRectangle': true
}));
var style = (function() {
var styles = {};
styles['Polygon'] = [
new ol.style.Style({
fill: new ol.style.Fill({
color: [255, 255, 255, 0.5]
})
}),
new ol.style.Style({
stroke: new ol.style.Stroke({
color: [255, 255, 255, 1],
width: 5
})
}),
new ol.style.Style({
stroke: new ol.style.Stroke({
color: [0, 153, 255, 1],
width: 3
})
})
];
styles['Point'] = [
new ol.style.Style({
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: [0, 153, 255, 1]
}),
stroke: new ol.style.Stroke({
color: [255, 255, 255, 0.75],
width: 1.5
})
}),
zIndex: 100000
})
];
styles['GeometryCollection'] = styles['Polygon'].concat(styles['Point']);
return function(feature, resolution) {
return styles[feature.getGeometry().getType()];
};
})();
var vectorSource = new ol.source.Vector({
features: this.features
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
// Use vectorLayer.setMap(map) rather than map.addLayer(vectorLayer). This
// makes the vector layer "unmanaged", meaning that it is always on top.
vectorLayer.setMap(map);
/**
* @type {ngeo.interaction.ModifyRectangle}
* @export
*/
this.interaction = new ngeo.interaction.ModifyRectangle(
/** @type {olx.interaction.ModifyOptions} */({
features: this.features,
style: style
}));
var interaction = this.interaction;
map.addInteraction(interaction);
interaction.setActive(true);
};
module.controller('MainController', app.MainController); |
<?php
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
namespace Twilio\Rest\Preview\Wireless;
use Twilio\Options;
use Twilio\Values;
/**
* PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com.
*/
abstract class SimOptions {
/**
* @param string $status The status
* @param string $iccid The iccid
* @param string $ratePlan The rate_plan
* @param string $eId The e_id
* @param string $simRegistrationCode The <API key>
* @return ReadSimOptions Options builder
*/
public static function read(string $status = Values::NONE, string $iccid = Values::NONE, string $ratePlan = Values::NONE, string $eId = Values::NONE, string $simRegistrationCode = Values::NONE): ReadSimOptions {
return new ReadSimOptions($status, $iccid, $ratePlan, $eId, $simRegistrationCode);
}
/**
* @param string $uniqueName The unique_name
* @param string $callbackMethod The callback_method
* @param string $callbackUrl The callback_url
* @param string $friendlyName The friendly_name
* @param string $ratePlan The rate_plan
* @param string $status The status
* @param string $<API key> The <API key>
* @param string $commandsCallbackUrl The <API key>
* @param string $smsFallbackMethod The sms_fallback_method
* @param string $smsFallbackUrl The sms_fallback_url
* @param string $smsMethod The sms_method
* @param string $smsUrl The sms_url
* @param string $voiceFallbackMethod The <API key>
* @param string $voiceFallbackUrl The voice_fallback_url
* @param string $voiceMethod The voice_method
* @param string $voiceUrl The voice_url
* @return UpdateSimOptions Options builder
*/
public static function update(string $uniqueName = Values::NONE, string $callbackMethod = Values::NONE, string $callbackUrl = Values::NONE, string $friendlyName = Values::NONE, string $ratePlan = Values::NONE, string $status = Values::NONE, string $<API key> = Values::NONE, string $commandsCallbackUrl = Values::NONE, string $smsFallbackMethod = Values::NONE, string $smsFallbackUrl = Values::NONE, string $smsMethod = Values::NONE, string $smsUrl = Values::NONE, string $voiceFallbackMethod = Values::NONE, string $voiceFallbackUrl = Values::NONE, string $voiceMethod = Values::NONE, string $voiceUrl = Values::NONE): UpdateSimOptions {
return new UpdateSimOptions($uniqueName, $callbackMethod, $callbackUrl, $friendlyName, $ratePlan, $status, $<API key>, $commandsCallbackUrl, $smsFallbackMethod, $smsFallbackUrl, $smsMethod, $smsUrl, $voiceFallbackMethod, $voiceFallbackUrl, $voiceMethod, $voiceUrl);
}
}
class ReadSimOptions extends Options {
/**
* @param string $status The status
* @param string $iccid The iccid
* @param string $ratePlan The rate_plan
* @param string $eId The e_id
* @param string $simRegistrationCode The <API key>
*/
public function __construct(string $status = Values::NONE, string $iccid = Values::NONE, string $ratePlan = Values::NONE, string $eId = Values::NONE, string $simRegistrationCode = Values::NONE) {
$this->options['status'] = $status;
$this->options['iccid'] = $iccid;
$this->options['ratePlan'] = $ratePlan;
$this->options['eId'] = $eId;
$this->options['simRegistrationCode'] = $simRegistrationCode;
}
/**
* The status
*
* @param string $status The status
* @return $this Fluent Builder
*/
public function setStatus(string $status): self {
$this->options['status'] = $status;
return $this;
}
/**
* The iccid
*
* @param string $iccid The iccid
* @return $this Fluent Builder
*/
public function setIccid(string $iccid): self {
$this->options['iccid'] = $iccid;
return $this;
}
/**
* The rate_plan
*
* @param string $ratePlan The rate_plan
* @return $this Fluent Builder
*/
public function setRatePlan(string $ratePlan): self {
$this->options['ratePlan'] = $ratePlan;
return $this;
}
/**
* The e_id
*
* @param string $eId The e_id
* @return $this Fluent Builder
*/
public function setEId(string $eId): self {
$this->options['eId'] = $eId;
return $this;
}
/**
* The <API key>
*
* @param string $simRegistrationCode The <API key>
* @return $this Fluent Builder
*/
public function <API key>(string $simRegistrationCode): self {
$this->options['simRegistrationCode'] = $simRegistrationCode;
return $this;
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string {
$options = \http_build_query(Values::of($this->options), '', ' ');
return '[Twilio.Preview.Wireless.ReadSimOptions ' . $options . ']';
}
}
class UpdateSimOptions extends Options {
/**
* @param string $uniqueName The unique_name
* @param string $callbackMethod The callback_method
* @param string $callbackUrl The callback_url
* @param string $friendlyName The friendly_name
* @param string $ratePlan The rate_plan
* @param string $status The status
* @param string $<API key> The <API key>
* @param string $commandsCallbackUrl The <API key>
* @param string $smsFallbackMethod The sms_fallback_method
* @param string $smsFallbackUrl The sms_fallback_url
* @param string $smsMethod The sms_method
* @param string $smsUrl The sms_url
* @param string $voiceFallbackMethod The <API key>
* @param string $voiceFallbackUrl The voice_fallback_url
* @param string $voiceMethod The voice_method
* @param string $voiceUrl The voice_url
*/
public function __construct(string $uniqueName = Values::NONE, string $callbackMethod = Values::NONE, string $callbackUrl = Values::NONE, string $friendlyName = Values::NONE, string $ratePlan = Values::NONE, string $status = Values::NONE, string $<API key> = Values::NONE, string $commandsCallbackUrl = Values::NONE, string $smsFallbackMethod = Values::NONE, string $smsFallbackUrl = Values::NONE, string $smsMethod = Values::NONE, string $smsUrl = Values::NONE, string $voiceFallbackMethod = Values::NONE, string $voiceFallbackUrl = Values::NONE, string $voiceMethod = Values::NONE, string $voiceUrl = Values::NONE) {
$this->options['uniqueName'] = $uniqueName;
$this->options['callbackMethod'] = $callbackMethod;
$this->options['callbackUrl'] = $callbackUrl;
$this->options['friendlyName'] = $friendlyName;
$this->options['ratePlan'] = $ratePlan;
$this->options['status'] = $status;
$this->options['<API key>'] = $<API key>;
$this->options['commandsCallbackUrl'] = $commandsCallbackUrl;
$this->options['smsFallbackMethod'] = $smsFallbackMethod;
$this->options['smsFallbackUrl'] = $smsFallbackUrl;
$this->options['smsMethod'] = $smsMethod;
$this->options['smsUrl'] = $smsUrl;
$this->options['voiceFallbackMethod'] = $voiceFallbackMethod;
$this->options['voiceFallbackUrl'] = $voiceFallbackUrl;
$this->options['voiceMethod'] = $voiceMethod;
$this->options['voiceUrl'] = $voiceUrl;
}
/**
* The unique_name
*
* @param string $uniqueName The unique_name
* @return $this Fluent Builder
*/
public function setUniqueName(string $uniqueName): self {
$this->options['uniqueName'] = $uniqueName;
return $this;
}
/**
* The callback_method
*
* @param string $callbackMethod The callback_method
* @return $this Fluent Builder
*/
public function setCallbackMethod(string $callbackMethod): self {
$this->options['callbackMethod'] = $callbackMethod;
return $this;
}
/**
* The callback_url
*
* @param string $callbackUrl The callback_url
* @return $this Fluent Builder
*/
public function setCallbackUrl(string $callbackUrl): self {
$this->options['callbackUrl'] = $callbackUrl;
return $this;
}
/**
* The friendly_name
*
* @param string $friendlyName The friendly_name
* @return $this Fluent Builder
*/
public function setFriendlyName(string $friendlyName): self {
$this->options['friendlyName'] = $friendlyName;
return $this;
}
/**
* The rate_plan
*
* @param string $ratePlan The rate_plan
* @return $this Fluent Builder
*/
public function setRatePlan(string $ratePlan): self {
$this->options['ratePlan'] = $ratePlan;
return $this;
}
/**
* The status
*
* @param string $status The status
* @return $this Fluent Builder
*/
public function setStatus(string $status): self {
$this->options['status'] = $status;
return $this;
}
/**
* The <API key>
*
* @param string $<API key> The <API key>
* @return $this Fluent Builder
*/
public function <API key>(string $<API key>): self {
$this->options['<API key>'] = $<API key>;
return $this;
}
/**
* The <API key>
*
* @param string $commandsCallbackUrl The <API key>
* @return $this Fluent Builder
*/
public function <API key>(string $commandsCallbackUrl): self {
$this->options['commandsCallbackUrl'] = $commandsCallbackUrl;
return $this;
}
/**
* The sms_fallback_method
*
* @param string $smsFallbackMethod The sms_fallback_method
* @return $this Fluent Builder
*/
public function <API key>(string $smsFallbackMethod): self {
$this->options['smsFallbackMethod'] = $smsFallbackMethod;
return $this;
}
/**
* The sms_fallback_url
*
* @param string $smsFallbackUrl The sms_fallback_url
* @return $this Fluent Builder
*/
public function setSmsFallbackUrl(string $smsFallbackUrl): self {
$this->options['smsFallbackUrl'] = $smsFallbackUrl;
return $this;
}
/**
* The sms_method
*
* @param string $smsMethod The sms_method
* @return $this Fluent Builder
*/
public function setSmsMethod(string $smsMethod): self {
$this->options['smsMethod'] = $smsMethod;
return $this;
}
/**
* The sms_url
*
* @param string $smsUrl The sms_url
* @return $this Fluent Builder
*/
public function setSmsUrl(string $smsUrl): self {
$this->options['smsUrl'] = $smsUrl;
return $this;
}
/**
* The <API key>
*
* @param string $voiceFallbackMethod The <API key>
* @return $this Fluent Builder
*/
public function <API key>(string $voiceFallbackMethod): self {
$this->options['voiceFallbackMethod'] = $voiceFallbackMethod;
return $this;
}
/**
* The voice_fallback_url
*
* @param string $voiceFallbackUrl The voice_fallback_url
* @return $this Fluent Builder
*/
public function setVoiceFallbackUrl(string $voiceFallbackUrl): self {
$this->options['voiceFallbackUrl'] = $voiceFallbackUrl;
return $this;
}
/**
* The voice_method
*
* @param string $voiceMethod The voice_method
* @return $this Fluent Builder
*/
public function setVoiceMethod(string $voiceMethod): self {
$this->options['voiceMethod'] = $voiceMethod;
return $this;
}
/**
* The voice_url
*
* @param string $voiceUrl The voice_url
* @return $this Fluent Builder
*/
public function setVoiceUrl(string $voiceUrl): self {
$this->options['voiceUrl'] = $voiceUrl;
return $this;
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string {
$options = \http_build_query(Values::of($this->options), '', ' ');
return '[Twilio.Preview.Wireless.UpdateSimOptions ' . $options . ']';
}
} |
# encoding: utf-8
require 'spec_helper'
describe Relation::Proxy, '#each' do
subject { object.each { |tuple| yields << tuple } }
let(:object) { described_class.new(relation) }
let(:described_class) { Class.new(Relation) }
let(:relation) { Relation.new([[:id, Integer]], body) }
let(:body) { [[1], [2]] }
let(:yields) { [] }
before do
described_class.class_eval do
include Relation::Proxy
def initialize(relation)
@relation = relation
end
end
end
<API key> 'an #each method'
it 'yields only tuples' do
subject
yields.each { |tuple| expect(tuple).to be_instance_of(Tuple) }
end
it 'yields only tuples with the expected header' do
subject
yields.each { |tuple| expect(tuple.header).to be(object.header) }
end
it 'yields only tuples with the expected data' do
expect { subject }.to change { yields.dup }
.from([])
.to(body)
end
end |
<html>
<head>
<title>Application</title>
<meta charset="utf-8">
</head>
<body>
<div id="application">
</div>
</body>
<script src="/bundle.js"></script>
</html> |
#ifndef <API key>
#define <API key>
// W A R N I N G
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
// We mean it.
#include <QtCore/qglobal.h>
#include <QtQml/qqmllist.h>
#include <QtCore/qvariant.h>
#include <private/qv4value_p.h>
#include <private/qv4object_p.h>
QT_BEGIN_NAMESPACE
namespace QV4 {
namespace Heap {
struct VariantObject : Object
{
void init();
void init(const QVariant &value);
void destroy() {
Q_ASSERT(scarceData);
if (isScarce())
<API key>();
delete scarceData;
Object::destroy();
}
bool isScarce() const;
int <API key>;
const QVariant &data() const { return scarceData->data; }
QVariant &data() { return scarceData->data; }
void <API key>() { scarceData->node.remove(); }
void <API key>() { internalClass->engine->scarceResources.insert(scarceData); }
private:
ExecutionEngine::ScarceResourceData *scarceData;
};
}
struct VariantObject : Object
{
V4_OBJECT2(VariantObject, Object)
V4_PROTOTYPE(variantPrototype)
V4_NEEDS_DESTROY
void <API key>();
void <API key>();
static bool isEqualTo(Managed *m, Managed *other);
};
struct VariantPrototype : VariantObject
{
public:
void init();
static ReturnedValue method_preserve(CallContext *ctx);
static ReturnedValue method_destroy(CallContext *ctx);
static ReturnedValue method_toString(CallContext *ctx);
static ReturnedValue method_valueOf(CallContext *ctx);
};
}
QT_END_NAMESPACE
#endif |
# Integrations
## Elasticsearch v2
- Updated the **URL** parameter description with the suggested default parameter. |
layout: default
lang: en
nav_link: Monitoring
nav_level: 2
nav_order: 300
# Monitoring the User Sync Process
[Previous Section](test_run.md) \| [Back to Contents](index.md) \| [Next Section](<API key>.md)
If you are using User Sync as an ongoing process, you’ll need to identify someone who can monitor and maintain the User Sync process. You'll also want to set up some automated monitoring mechanism to make it easy to see what is going on and determine if any errors have occurred.
There are several possible approaches to monitoring:
- Inspect log files from when User Sync runs
- Email latest run log summary to administrators who watch emails for errors (or non-delivery)
- Hook log files to a monitoring system and setup notifications for when errors occur
For this step, you need to identify who will be responsible for User Sync operation and identify how monitoring will be set up.
☐ Identify the person or team responsible for monitoring and make sure they are up to speed on User Sync and what it is doing.
☐ If you have a log analysis and alerting system available, arrange for the log from User Sync to be sent to the log analysis system and set up alerts if any Error or Critical messages appear in the log. You may also want to alert on Warning messages.
[Previous Section](test_run.md) \| [Back to Contents](index.md) \| [Next Section](<API key>.md) |
package debox.benchmark
import com.google.caliper.Param
import debox.Util.array
object <API key> extends MyRunner(classOf[<API key>])
class <API key> extends MyBenchmark {
def timeApply0(reps:Int) = run(reps)(Array[Int]().length)
def timeMacro0(reps:Int) = run(reps)(array[Int]().length)
def timeApply1(reps:Int) = run(reps)(Array(1).length)
def timeMacro1(reps:Int) = run(reps)(array(1).length)
def timeApply2(reps:Int) = run(reps)(Array(1,2).length)
def timeMacro2(reps:Int) = run(reps)(array(1,2).length)
def timeApply4(reps:Int) = run(reps)(Array(1,2,3,4).length)
def timeMacro4(reps:Int) = run(reps)(array(1,2,3,4).length)
def timeApply8(reps:Int) = run(reps)(Array(1,2,3,4,5,6,7,8).length)
def timeMacro8(reps:Int) = run(reps)(array(1,2,3,4,5,6,7,8).length)
def timeApply16(reps:Int) = run(reps)(Array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16).length)
def timeMacro16(reps:Int) = run(reps)(array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16).length)
def timeApply32(reps:Int) = run(reps)(Array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32).length)
def timeMacro32(reps:Int) = run(reps)(array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32).length)
def timeApply64(reps:Int) = run(reps)(Array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64).length)
def timeMacro64(reps:Int) = run(reps)(array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64).length)
def timeApply128(reps:Int) = run(reps)(Array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128).length)
def timeMacro128(reps:Int) = run(reps)(array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128).length)
} |
layout: post
title: poliCTF 2015 John the packer 350
category: [Reverse Engineering]
tags: [RE, poliCTF]
comments: true
**Points:** 350
**Solves:** 50
**Category:** Reverse Engineering
**Description:**
> John's greatest skill is to pack everything and everywhere with everyone. He doesn't want that someone reverse his super secret program. So he wrote a magic packing system. Can you show to John that his packing system is not a good anti-reversing solution? N.B. Unfortunately John The Packer has multiple solution, so if you have a solution that is not accepted by the scoreboard (but is accepted by the binary) please contact an OP on IRC
[john the packer]({{site.url}}/assets/topack)
## Write-up
Let's see what are we presented with here. 32-bit ELF stripped and we have to find the flag by passing it as an argument.
{% highlight bash %}
$ file topack
topack: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.32, BuildID[sha1]=<SHA1-like>, stripped
$ ./topack
Usage:
./topack flag{<key>}
$ ./topack AAAA
wrong Header for AAAA
wrong End for AAAA
Loser
$
{% endhighlight %}
Notice the 'wrong Header' and 'wrong End' warnings ? Let's try passing the right flag format as it tells us.
{% highlight bash %}
$ ./topack flag{AAAA}
Loser
$
{% endhighlight %}
This time no warnings...
Let's take a look at the main function.
{% highlight bash %}
(gdb) x/50i 0x8048bf2
=> 0x8048bf2: lea ecx,[esp+0x4]
0x8048bf6: and esp,0xfffffff0
0x8048bf9: push DWORD PTR [ecx-0x4]
0x8048bfc: push ebp
0x8048bfd: mov ebp,esp
0x8048bff: push ecx
0x8048c00: sub esp,0x4
0x8048c03: mov eax,ecx
0x8048c05: push DWORD PTR [eax+0x4]
0x8048c08: push DWORD PTR [eax]
0x8048c0a: push 0x53
0x8048c0f: push 0x8048aa5
0x8048c14: call 0x80485e0
0x8048c19: add esp,0x10
0x8048c1c: mov eax,0x0
0x8048c21: mov ecx,DWORD PTR [ebp-0x4]
0x8048c24: leave
{% endhighlight %}
Hm... this is a weird main function :). Anyway, let's continue with the next function, 0x80485e0.
{% highlight bash %}
(gdb) x/50i 0x80485e0
0x80485e0: push ebp
0x80485e1: mov ebp,esp
0x80485e3: sub esp,0x8
0x80485e6: mov eax,DWORD PTR [ebp+0x8]
0x80485e9: and eax,0xfffff000
0x80485ee: sub esp,0x4
0x80485f1: push 0x7
0x80485f3: push 0x1000
0x80485f8: push eax
0x80485f9: call 0x8048430 <mprotect@plt>
0x80485fe: add esp,0x10
0x8048601: mov ecx,DWORD PTR [ebp+0x8]
0x8048604: mov edx,0x66666667
0x8048609: mov eax,ecx
0x804860b: imul edx
0x804860d: sar edx,1
0x804860f: mov eax,ecx
0x8048611: sar eax,0x1f
0x8048614: sub edx,eax
0x8048616: mov eax,edx
0x8048618: mov edx,eax
0x804861a: shl edx,0x2
0x804861d: add edx,eax
0x804861f: mov eax,ecx
0x8048621: sub eax,edx
0x8048623: mov edx,DWORD PTR [eax*4+0x804a294]
0x804862a: mov eax,DWORD PTR [ebp+0x8]
0x804862d: mov ecx,DWORD PTR [ebp+0xc]
0x8048630: add esp,0x8
0x8048633: push eax
0x8048634: mov edx,DWORD PTR [edx]
0x8048636: xor DWORD PTR [eax],edx
0x8048638: add eax,0x4
0x804863b: dec ecx
0x804863c: jne 0x8048636
0x804863e: pop eax
0x804863f: call eax
0x8048641: sub esp,0x8
0x8048644: push DWORD PTR [ebp+0xc]
0x8048647: push DWORD PTR [ebp+0x8]
0x804864a: call 0x804859b
0x804864f: add esp,0x10
0x8048652: nop
0x8048653: leave
{% endhighlight %}
Aha, here comes the unpacking routine! First it modifies 0x08048000 section with size of 0x1000 is hex with READ, WRITE and EXEC permissions using mprotect().
Next it actually does the modification and almost to the end we see call EAX, if we add a breakpoint there we actually see that EAX is the address pushed before
we enter this unpacking function, '0x8048aa5'.
{% highlight bash %}
(gdb) b *0x804863f
Breakpoint 1 at 0x804863f
(gdb) run flag{AAAA}
Starting program: /home/user/ctfs/poliCTF/re350/topack flag{AAAA}
Breakpoint 1, 0x0804863f in ?? ()
(gdb) info reg
eax 0x8048aa5 134515365
ecx 0x0 0
edx 0x4030201 67305985
ebx 0xb7f76000 -1208524800
esp 0xbffff0b8 0xbffff0b8
ebp 0xbffff0b8 0xbffff0b8
esi 0x0 0
edi 0x0 0
eip 0x804863f 0x804863f
eflags 0x246 [ PF ZF IF ]
cs 0x73 115
ss 0x7b 123
ds 0x7b 123
es 0x7b 123
fs 0x0 0
gs 0x33 51
(gdb)
{% endhighlight %}
Let's step inside and see what's going on here.
It looks like we have arrived at the 'real' main function. However we can't dump the process just yet,
if we pay close attention, we are can recognize the 0x80485e0 function which unpacked 'main' and the address argument passed
to it.
{% highlight bash %}
(gdb) x/200i $eip
=> 0x8048aa5: push ebp
0x8048aa6: mov ebp,esp
0x8048aa8: sub esp,0x18
0x8048aab: cmp DWORD PTR [ebp+0x18],0x1
0x8048aaf: jg 0x8048ad1
0x8048ab1: mov eax,DWORD PTR [ebp+0x1c]
0x8048ab4: mov eax,DWORD PTR [eax]
0x8048ab6: sub esp,0x8
0x8048ab9: push eax
0x8048aba: push 0x8048db8
0x8048abf: call 0x8048440 <printf@plt>
0x8048ac4: add esp,0x10
0x8048ac7: sub esp,0xc
0x8048aca: push 0x0
0x8048acc: call 0x8048470 <exit@plt>
0x8048ad1: mov DWORD PTR [ebp-0xc],0x0
0x8048ad8: mov eax,DWORD PTR [ebp+0x1c]
0x8048adb: add eax,0x4
0x8048ade: mov eax,DWORD PTR [eax]
0x8048ae0: sub esp,0x4
0x8048ae3: push eax
0x8048ae4: push 0x11
0x8048ae9: push 0x8048655
0x8048aee: call 0x80485e0
0x8048af3: add esp,0x10
0x8048af6: add DWORD PTR [ebp-0xc],eax
0x8048af9: mov eax,DWORD PTR [ebp+0x1c]
0x8048afc: add eax,0x4
0x8048aff: mov eax,DWORD PTR [eax]
0x8048b01: sub esp,0x4
0x8048b04: push eax
0x8048b05: push 0x11
0x8048b0a: push 0x804869a
0x8048b0f: call 0x80485e0
0x8048b14: add esp,0x10
0x8048b17: add DWORD PTR [ebp-0xc],eax
0x8048b1a: mov eax,DWORD PTR [ebp+0x1c]
0x8048b1d: add eax,0x4
0x8048b20: mov eax,DWORD PTR [eax]
0x8048b22: sub esp,0x4
0x8048b25: push eax
0x8048b26: push 0x17
0x8048b2b: push 0x80486de
0x8048b30: call 0x80485e0
0x8048b35: add esp,0x10
0x8048b38: add DWORD PTR [ebp-0xc],eax
0x8048b3b: mov eax,DWORD PTR [ebp+0x1c]
0x8048b3e: add eax,0x4
0x8048b41: mov eax,DWORD PTR [eax]
0x8048b43: sub esp,0x4
0x8048b46: push eax
0x8048b47: push 0x18
0x8048b4c: push 0x8048a42
0x8048b51: call 0x80485e0
0x8048b56: add esp,0x10
0x8048b59: add DWORD PTR [ebp-0xc],eax
0x8048b5c: mov eax,DWORD PTR [ebp+0x1c]
0x8048b5f: add eax,0x4
0x8048b62: mov eax,DWORD PTR [eax]
0x8048b64: sub esp,0x4
0x8048b67: push eax
0x8048b68: push 0x26
0x8048b6d: push 0x80489a9
0x8048b72: call 0x80485e0
0x8048b77: add esp,0x10
0x8048b7a: add DWORD PTR [ebp-0xc],eax
0x8048b7d: mov eax,DWORD PTR [ebp+0x1c]
0x8048b80: add eax,0x4
0x8048b83: mov eax,DWORD PTR [eax]
0x8048b85: push 0x0
0x8048b87: push eax
0x8048b88: push 0x27
0x8048b8d: push 0x804890b
0x8048b92: call 0x80485e0
0x8048b97: add esp,0x10
0x8048b9a: add DWORD PTR [ebp-0xc],eax
0x8048b9d: mov eax,DWORD PTR [ebp+0x1c]
0x8048ba0: add eax,0x4
0x8048ba3: mov eax,DWORD PTR [eax]
0x8048ba5: sub esp,0x4
0x8048ba8: push eax
0x8048ba9: push 0x9
0x8048bae: push 0x80488e4
0x8048bb3: call 0x80485e0
0x8048bb8: add esp,0x10
0x8048bbb: add DWORD PTR [ebp-0xc],eax
0x8048bbe: cmp DWORD PTR [ebp-0xc],0x7
0x8048bc2: jne 0x8048bdf
0x8048bc4: mov eax,DWORD PTR [ebp+0x1c]
0x8048bc7: add eax,0x4
0x8048bca: mov eax,DWORD PTR [eax]
0x8048bcc: sub esp,0x8
0x8048bcf: push eax
0x8048bd0: push 0x8048dd0
0x8048bd5: call 0x8048440 <printf@plt>
0x8048bda: add esp,0x10
0x8048bdd: jmp 0x8048bef
0x8048bdf: sub esp,0xc
0x8048be2: push 0x8048df8
0x8048be7: call 0x8048440 <printf@plt>
0x8048bec: add esp,0x10
0x8048bef: nop
0x8048bf0: leave
0x8048bf1: ret
{% endhighlight %}
The way I organized the analysis was in sections. The unpacking routine was called 7 times with different address as argument.
That means we are going to have to complete 7 'levels' each one is being unpacked before execution reached there.
So let me split the main routine in 7 sections...
{% highlight bash %}
(gdb) x/200i $eip
=> 0x8048aa5: push ebp
0x8048aa6: mov ebp,esp
0x8048aa8: sub esp,0x18
0x8048aab: cmp DWORD PTR [ebp+0x18],0x1
0x8048aaf: jg 0x8048ad1
0x8048ab1: mov eax,DWORD PTR [ebp+0x1c]
0x8048ab4: mov eax,DWORD PTR [eax]
0x8048ab6: sub esp,0x8
0x8048ab9: push eax
0x8048aba: push 0x8048db8
0x8048abf: call 0x8048440 <printf@plt>
0x8048ac4: add esp,0x10
0x8048ac7: sub esp,0xc
0x8048aca: push 0x0
0x8048acc: call 0x8048470 <exit@plt>
0x8048ad1: mov DWORD PTR [ebp-0xc],0x0
0x8048ad8: mov eax,DWORD PTR [ebp+0x1c]
0x8048adb: add eax,0x4
0x8048ade: mov eax,DWORD PTR [eax]
0x8048ae0: sub esp,0x4
0x8048ae3: push eax
0x8048ae4: push 0x11
0x8048ae9: push 0x8048655
0x8048aee: call 0x80485e0
0x8048af3: add esp,0x10
0x8048af6: add DWORD PTR [ebp-0xc],eax
0x8048af9: mov eax,DWORD PTR [ebp+0x1c]
0x8048afc: add eax,0x4
0x8048aff: mov eax,DWORD PTR [eax]
0x8048b01: sub esp,0x4
0x8048b04: push eax
0x8048b05: push 0x11
0x8048b0a: push 0x804869a
0x8048b0f: call 0x80485e0
0x8048b14: add esp,0x10
0x8048b17: add DWORD PTR [ebp-0xc],eax
0x8048b1a: mov eax,DWORD PTR [ebp+0x1c]
0x8048b1d: add eax,0x4
0x8048b20: mov eax,DWORD PTR [eax]
0x8048b22: sub esp,0x4
0x8048b25: push eax
0x8048b26: push 0x17
0x8048b2b: push 0x80486de
0x8048b30: call 0x80485e0
0x8048b35: add esp,0x10
0x8048b38: add DWORD PTR [ebp-0xc],eax
0x8048b3b: mov eax,DWORD PTR [ebp+0x1c]
0x8048b3e: add eax,0x4
0x8048b41: mov eax,DWORD PTR [eax]
0x8048b43: sub esp,0x4
0x8048b46: push eax
0x8048b47: push 0x18
0x8048b4c: push 0x8048a42
0x8048b51: call 0x80485e0
0x8048b56: add esp,0x10
0x8048b59: add DWORD PTR [ebp-0xc],eax
0x8048b5c: mov eax,DWORD PTR [ebp+0x1c]
0x8048b5f: add eax,0x4
0x8048b62: mov eax,DWORD PTR [eax]
0x8048b64: sub esp,0x4
0x8048b67: push eax
0x8048b68: push 0x26
0x8048b6d: push 0x80489a9
0x8048b72: call 0x80485e0
0x8048b77: add esp,0x10
0x8048b7a: add DWORD PTR [ebp-0xc],eax
0x8048b7d: mov eax,DWORD PTR [ebp+0x1c]
0x8048b80: add eax,0x4
0x8048b83: mov eax,DWORD PTR [eax]
0x8048b85: push 0x0
0x8048b87: push eax
0x8048b88: push 0x27
0x8048b8d: push 0x804890b
0x8048b92: call 0x80485e0
0x8048b97: add esp,0x10
0x8048b9a: add DWORD PTR [ebp-0xc],eax
0x8048b9d: mov eax,DWORD PTR [ebp+0x1c]
0x8048ba0: add eax,0x4
0x8048ba3: mov eax,DWORD PTR [eax]
0x8048ba5: sub esp,0x4
0x8048ba8: push eax
0x8048ba9: push 0x9
0x8048bae: push 0x80488e4
0x8048bb3: call 0x80485e0
0x8048bb8: add esp,0x10
0x8048bbb: add DWORD PTR [ebp-0xc],eax
0x8048bbe: cmp DWORD PTR [ebp-0xc],0x7 <=== Compare if all sections returned '1'
0x8048bc2: jne 0x8048bdf
0x8048bc4: mov eax,DWORD PTR [ebp+0x1c]
0x8048bc7: add eax,0x4
0x8048bca: mov eax,DWORD PTR [eax]
0x8048bcc: sub esp,0x8
0x8048bcf: push eax
0x8048bd0: push 0x8048dd0 <===== Good Boy
0x8048bd5: call 0x8048440 <printf@plt>
0x8048bda: add esp,0x10
0x8048bdd: jmp 0x8048bef
0x8048bdf: sub esp,0xc
0x8048be2: push 0x8048df8 <===== Bad Boy
0x8048be7: call 0x8048440 <printf@plt>
0x8048bec: add esp,0x10
0x8048bef: nop
0x8048bf0: leave
0x8048bf1: ret
{% endhighlight %}
If you take a look at the end here, past section #7. You can see that the result of each return is compared to 0x7.
This means that each level needs to return '1' in order to reach the "Good Boy" statement. So let's continue and add a breakpoint
at each address passed to 0x80485e0, starting with section number 1 with address '0x8048655'.
# Section number 1
{% highlight bash %}
(gdb) b *0x8048655
Breakpoint 4 at 0x8048655
(gdb) c
Continuing.
Breakpoint 4, 0x08048655 in ?? ()
(gdb) x/50i $eip
=> 0x8048655: inc ebp
0x8048656: mov ebp,esp
0x8048658: sub esp,0x18
0x804865b: sub esp,0x8
0x804865e: push 0x8048cf9
0x8048663: push DWORD PTR [ebp+0x18]
0x8048666: call 0x8048420 <strstr@plt>
0x804866b: add esp,0x10
0x804866e: mov DWORD PTR [ebp-0xc],eax
0x8048671: mov eax,DWORD PTR [ebp-0xc]
0x8048674: cmp eax,DWORD PTR [ebp+0x18]
0x8048677: jne 0x8048680 <
0x8048679: mov eax,0x1 <
0x804867e: jmp 0x8048698
0x8048680: sub esp,0x8
0x8048683: push DWORD PTR [ebp+0x18]
0x8048686: push 0x8048cff
0x804868b: call 0x8048440 <printf@plt>
0x8048690: add esp,0x10
0x8048693: mov eax,0x0
0x8048698: leave
(gdb) x/s 0x8048cf9
0x8048cf9: "flag{"
(gdb) x/s 0x8048cff
0x8048cff: "wrong Header for %s\n"
(gdb)
{% endhighlight %}
It looks like strstr() is looking for string "flag{", if it's not present in our input "[ebp+0x18]", (remember throughout the entire
binary, each section will reference our input argument as [ebp+0x18]) it prints "wrong Header" and does not return the desired '1'.
Anyway, let's continue.
{% highlight bash %}
(gdb) c
Continuing.
wrong Header for [=sX
Program received signal SIGSEGV, Segmentation fault.
0xbffff0b0 in ?? ()
(gdb)
{% endhighlight %}
Oh-uh, what happened here ? I thought we had the right header, why we didn't continue to section number 2?
Well, it's because we used a software breakpoint, if the unpacking routine encounters a software breakpoint, which is a 0xCC byte,
it will unpack wrongfully. I think that's pretty cool ! So from now on we will only be using a Hardware Breakpoints, with the exception
of the __start because GDB can't add hardware breakpoints if the program is not running :(.
# Section number 2
{% highlight bash %}
user@ubuntu:~/ctfs/poliCTF/re350$ readelf --header topack | grep -i entry
Entry point address: 0x80484a0
user@ubuntu:~/ctfs/poliCTF/re350$ gdb -q ./topack
Reading symbols from ./topack...(no debugging symbols found)...done.
(gdb) b *0x80484a0
Breakpoint 1 at 0x80484a0
(gdb) run flag{AAAA}
Starting program: /home/user/ctfs/poliCTF/re350/topack flag{AAAA}
Breakpoint 1, 0x080484a0 in ?? ()
(gdb) hbreak *0x804869a
Hardware assisted breakpoint 2 at 0x804869a
(gdb) c
Continuing.
Breakpoint 2, 0x0804869a in ?? ()
(gdb) x/50i $eip
=> 0x804869a: push ebp
0x804869b: mov ebp,esp
0x804869d: sub esp,0x8
0x80486a0: sub esp,0xc
0x80486a3: push DWORD PTR [ebp+0x18]
0x80486a6: call 0x8048480 <strlen@plt>
0x80486ab: add esp,0x10
0x80486ae: lea edx,[eax-0x1] <--- strlen() - 1
0x80486b1: mov eax,DWORD PTR [ebp+0x18]
0x80486b4: add eax,edx
0x80486b6: movzx eax,BYTE PTR [eax] <--- last index char from input
0x80486b9: cmp al,0x7d <--- compare if input[-1:] == 0x7d, '}'
0x80486bb: jne 0x80486c4 <--- badboy
0x80486bd: mov eax,0x1
0x80486c2: jmp 0x80486dc
0x80486c4: sub esp,0x8
0x80486c7: push DWORD PTR [ebp+0x18]
0x80486ca: push 0x8048d14
0x80486cf: call 0x8048440 <printf@plt>
0x80486d4: add esp,0x10
0x80486d7: mov eax,0x0
0x80486dc: leave
0x80486dd: ret
(gdb) x/s 0x8048d14
0x8048d14: "wrong End for %s\n"
(gdb)
{% endhighlight %}
At section number 2 we see that the last character of our input is being compared with 0x7d, which is a closed-curly-brace.
If it's not, it prints "wrong End"...
# Section number 3
{% highlight bash %}
(gdb) hbreak *0x80486de
Hardware assisted breakpoint 3 at 0x80486de
(gdb) c
Continuing.
Breakpoint 3, 0x080486de in ?? ()
(gdb) x/50i $eip
=> 0x80486de: push ebp
0x80486df: mov ebp,esp
0x80486e1: sub esp,0x18
0x80486e4: sub esp,0xc
0x80486e7: push DWORD PTR [ebp+0x18]
0x80486ea: call 0x8048480 <strlen@plt>
0x80486ef: add esp,0x10
0x80486f2: mov DWORD PTR [ebp-0x10],eax
0x80486f5: mov DWORD PTR [ebp-0xc],0x0
0x80486fc: jmp 0x804872b
0x80486fe: mov edx,DWORD PTR [ebp-0xc]
0x8048701: mov eax,DWORD PTR [ebp+0x18]
0x8048704: add eax,edx
0x8048706: movzx eax,BYTE PTR [eax]
0x8048709: test al,al
0x804870b: jns 0x8048727
0x804870d: sub esp,0x8
0x8048710: push DWORD PTR [ebp+0x18]
0x8048713: push 0x8048d26
0x8048718: call 0x8048440 <printf@plt>
0x804871d: add esp,0x10
0x8048720: mov eax,0x0
0x8048725: jmp 0x8048738
0x8048727: add DWORD PTR [ebp-0xc],0x1
0x804872b: mov eax,DWORD PTR [ebp-0xc]
0x804872e: cmp eax,DWORD PTR [ebp-0x10]
0x8048731: jl 0x80486fe
0x8048733: mov eax,0x1
0x8048738: leave
0x8048739: ret
(gdb) x/s 0x8048d26
0x8048d26: "Not ascii character in %s\n"
(gdb)
{% endhighlight %}
Needless to say this section only checks if our input is composed of only printable characters.
# Section number 4
{% highlight bash %}
(gdb) hbreak *0x8048a42
Hardware assisted breakpoint 6 at 0x8048a42
(gdb) c
Continuing.
Breakpoint 6, 0x08048a42 in ?? ()
(gdb) x/100i $eip
=> 0x8048a42: push ebp
0x8048a43: mov ebp,esp
0x8048a45: push ebx
0x8048a46: sub esp,0x14
0x8048a49: mov DWORD PTR [ebp-0x10],0x6
0x8048a50: mov DWORD PTR [ebp-0xc],0x1
0x8048a57: jmp 0x8048a93
0x8048a59: mov eax,DWORD PTR [ebp-0xc]
0x8048a5c: add eax,0x4
0x8048a5f: mov edx,eax
0x8048a61: mov eax,DWORD PTR [ebp+0x18]
0x8048a64: add eax,edx
0x8048a66: movzx eax,BYTE PTR [eax]
0x8048a69: movsx ebx,al
0x8048a6c: sub esp,0x4
0x8048a6f: push DWORD PTR [ebp-0xc]
0x8048a72: push 0x36
0x8048a77: push 0x804873a
0x8048a7c: call 0x80485e0
0x8048a81: add esp,0x10
0x8048a84: cmp ebx,eax
0x8048a86: je 0x8048a8f
0x8048a88: mov eax,0x0
0x8048a8d: jmp 0x8048aa0
0x8048a8f: add DWORD PTR [ebp-0xc],0x1
0x8048a93: mov eax,DWORD PTR [ebp-0xc]
0x8048a96: cmp eax,DWORD PTR [ebp-0x10]
0x8048a99: jle 0x8048a59
0x8048a9b: mov eax,0x1
0x8048aa0: mov ebx,DWORD PTR [ebp-0x4]
0x8048aa3: leave
0x8048aa4: ret
{% endhighlight %}
Interesting... Here we see that it's calling the unpacking routine again... Well, we know the procedure, let's setup a hardware breakpoint
at 0x804873a. Don't forget to remove the previous hardware breakpoints for the sections we have already completed.
{% highlight bash %}
(gdb) hb *0x804873a
Hardware assisted breakpoint 7 at 0x804873a
(gdb) c
Continuing.
Breakpoint 7, 0x0804873a in ?? ()
(gdb) x/150i $eip
=> 0x804873a: push ebp
0x804873b: mov ebp,esp
0x804873d: sub esp,0x28
0x8048740: fild DWORD PTR [ebp+0x18]
0x8048743: fld QWORD PTR ds:0x8048e10
0x8048749: lea esp,[esp-0x8]
0x804874d: fstp QWORD PTR [esp]
0x8048750: lea esp,[esp-0x8]
0x8048754: fstp QWORD PTR [esp]
0x8048757: call 0x8048450 <pow@plt>
0x804875c: add esp,0x10
0x804875f: fld QWORD PTR ds:0x8048e18
0x8048765: fmulp st(1),st
0x8048767: fstp QWORD PTR [ebp-0x28]
0x804876a: fild DWORD PTR [ebp+0x18]
0x804876d: fld QWORD PTR ds:0x8048e20
0x8048773: lea esp,[esp-0x8]
0x8048777: fstp QWORD PTR [esp]
0x804877a: lea esp,[esp-0x8]
0x804877e: fstp QWORD PTR [esp]
0x8048781: call 0x8048450 <pow@plt>
0x8048786: add esp,0x10
0x8048789: fld QWORD PTR ds:0x8048e28
0x804878f: fmulp st(1),st
0x8048791: fsubr QWORD PTR [ebp-0x28]
0x8048794: fstp QWORD PTR [ebp-0x28]
0x8048797: fild DWORD PTR [ebp+0x18]
0x804879a: fld QWORD PTR ds:0x8048e30
0x80487a0: lea esp,[esp-0x8]
0x80487a4: fstp QWORD PTR [esp]
0x80487a7: lea esp,[esp-0x8]
0x80487ab: fstp QWORD PTR [esp]
0x80487ae: call 0x8048450 <pow@plt>
0x80487b3: add esp,0x10
0x80487b6: fld QWORD PTR ds:0x8048e38
0x80487bc: fmulp st(1),st
0x80487be: fadd QWORD PTR [ebp-0x28]
0x80487c1: fstp QWORD PTR [ebp-0x28]
0x80487c4: fild DWORD PTR [ebp+0x18]
0x80487c7: fld QWORD PTR ds:0x8048e40
0x80487cd: lea esp,[esp-0x8]
0x80487d1: fstp QWORD PTR [esp]
0x80487d4: lea esp,[esp-0x8]
0x80487d8: fstp QWORD PTR [esp]
0x80487db: call 0x8048450 <pow@plt>
0x80487e0: add esp,0x10
0x80487e3: fld QWORD PTR ds:0x8048e48
0x80487e9: fmulp st(1),st
0x80487eb: fld QWORD PTR [ebp-0x28]
0x80487ee: fsubp st(1),st
0x80487f0: fild DWORD PTR [ebp+0x18]
0x80487f3: fld QWORD PTR ds:0x8048e50
0x80487f9: fmulp st(1),st
0x80487fb: faddp st(1),st
0x80487fd: fld QWORD PTR ds:0x8048e58
0x8048803: faddp st(1),st
0x8048805: fstp DWORD PTR [ebp-0xc]
0x8048808: movss xmm0,DWORD PTR [ebp-0xc]
0x804880d: cvttss2si eax,xmm0
0x8048811: leave
0x8048812: ret
{% endhighlight %}
Oh my god ! Who would have time to reverse all this ? Having dealt with floating point number and double extended precisions in python before
I know that sometimes results are not the same as in C so I didn't even wasted any time putting this into script. Instead let's look
at it from a high-level. If we take a look at the section 4 function 0x8048a42, we can see that it actually loops 6 times through
the unpacking function, only if cmp ebx, eax at 0x8048a84 is equal. So let's setup a Hardware Breakpoint there and just print the
content of the registers.
{% highlight bash %}
(gdb) hb *0x8048a84
Hardware assisted breakpoint 8 at 0x8048a84
(gdb) c
Continuing.
Breakpoint 8, 0x08048a84 in ?? ()
(gdb) info reg
eax 0x70 112
ecx 0x0 0
edx 0x4030201 67305985
ebx 0x41 65
esp 0xbffff060 0xbffff060
ebp 0xbffff078 0xbffff078
esi 0x0 0
edi 0x0 0
eip 0x8048a84 0x8048a84
eflags 0x10286 [ PF SF IF RF ]
cs 0x73 115
ss 0x7b 123
ds 0x7b 123
es 0x7b 123
fs 0x0 0
gs 0x33 51
(gdb)
{% endhighlight %}
Ok, it looks like our first 'A' (0x41 in ebx) is compared with 0x70 ('p'). Cool, let's adjust our input and continue the loop.
{% highlight bash %}
eax 0x70 112
eax 0x61 97
eax 0x63 99
eax 0x6b 107
eax 0x65 101
eax 0x72 114
{% endhighlight %}
So the flag so far is flag{packer}...
# Section 5
{% highlight bash %}
(gdb) hb *0x80489a9
Hardware assisted breakpoint 9 at 0x80489a9
(gdb) c
Continuing.
Breakpoint 9, 0x080489a9 in ?? ()
(gdb) x/100i $eip
=> 0x80489a9: push ebp
0x80489aa: mov ebp,esp
0x80489ac: push edi
0x80489ad: push esi
0x80489ae: push ebx
0x80489af: sub esp,0x6c
0x80489b2: lea eax,[ebp-0x78]
0x80489b5: mov ebx,0x8048d60
0x80489ba: mov edx,0x16
0x80489bf: mov edi,eax
0x80489c1: mov esi,ebx
0x80489c3: mov ecx,edx
0x80489c5: rep movs DWORD PTR es:[edi],DWORD PTR ds:[esi]
0x80489c7: mov DWORD PTR [ebp-0x1c],0x0
0x80489ce: jmp 0x8048a2f
0x80489d0: mov eax,DWORD PTR [ebp-0x1c]
0x80489d3: mov edx,DWORD PTR [ebp+eax*8-0x74]
0x80489d7: mov eax,DWORD PTR [ebp+eax*8-0x78]
0x80489db: mov ecx,DWORD PTR [ebp-0x1c]
0x80489de: add ecx,0xb
0x80489e1: mov ebx,ecx
0x80489e3: mov ecx,DWORD PTR [ebp+0x18]
0x80489e6: add ecx,ebx
0x80489e8: movzx ecx,BYTE PTR [ecx]
0x80489eb: movsx ecx,cl
0x80489ee: sub esp,0xc
0x80489f1: push edx
0x80489f2: push eax
0x80489f3: push ecx
0x80489f4: push 0x34
0x80489f9: push 0x8048813
0x80489fe: call 0x80485e0
0x8048a03: add esp,0x20
0x8048a06: test eax,eax
0x8048a08: jne 0x8048a11
0x8048a0a: mov eax,0x0
0x8048a0f: jmp 0x8048a3a
0x8048a11: mov eax,DWORD PTR [ebp+0x18]
0x8048a14: add eax,0x11
0x8048a17: movzx eax,BYTE PTR [eax]
0x8048a1a: movsx eax,al
0x8048a1d: and eax,0x1
0x8048a20: test eax,eax
0x8048a22: jne 0x8048a2b
0x8048a24: mov eax,0x0
0x8048a29: jmp 0x8048a3a
0x8048a2b: add DWORD PTR [ebp-0x1c],0x1
0x8048a2f: cmp DWORD PTR [ebp-0x1c],0xa
0x8048a33: jle 0x80489d0
0x8048a35: mov eax,0x1
0x8048a3a: lea esp,[ebp-0xc]
0x8048a3d: pop ebx
0x8048a3e: pop esi
0x8048a3f: pop edi
0x8048a40: pop ebp
0x8048a41: ret
{% endhighlight %}
It's almost the same thing here except that on line 42, the code checks if the return from 0x8048813 is equal to 0 or not.
So this time we won't be given the values of the correct bytes. So let's see what's going on inside 0x8048813.
{% highlight bash %}
(gdb) hb *0x8048813
Hardware assisted breakpoint 10 at 0x8048813
(gdb) c
Continuing.
Breakpoint 10, 0x08048813 in ?? ()
(gdb) x/150i $eip
=> 0x8048813: push ebp
0x8048814: mov ebp,esp
0x8048816: push esi
0x8048817: push ebx
0x8048818: sub esp,0x30
0x804881b: mov eax,DWORD PTR [ebp+0x1c]
0x804881e: mov DWORD PTR [ebp-0x20],eax
0x8048821: mov eax,DWORD PTR [ebp+0x20]
0x8048824: mov DWORD PTR [ebp-0x1c],eax
0x8048827: fild DWORD PTR [ebp+0x18]
0x804882a: lea esp,[esp-0x8]
0x804882e: fstp QWORD PTR [esp]
0x8048831: fld QWORD PTR ds:0x8048e40
0x8048837: lea esp,[esp-0x8]
0x804883b: fstp QWORD PTR [esp]
0x804883e: call 0x8048450 <pow@plt>
0x8048843: add esp,0x10
0x8048846: fld QWORD PTR ds:0x8048e60
0x804884c: fxch st(1)
0x804884e: fucomi st,st(1)
0x8048850: fstp st(1)
0x8048852: jae 0x8048872
0x8048854: fnstcw WORD PTR [ebp-0x22]
0x8048857: movzx eax,WORD PTR [ebp-0x22]
0x804885b: mov ah,0xc
0x804885d: mov WORD PTR [ebp-0x24],ax
0x8048861: fldcw WORD PTR [ebp-0x24]
0x8048864: fistp QWORD PTR [ebp-0x30]
0x8048867: fldcw WORD PTR [ebp-0x22]
0x804886a: mov eax,DWORD PTR [ebp-0x30]
0x804886d: mov edx,DWORD PTR [ebp-0x2c]
0x8048870: jmp 0x80488ae
0x8048872: fld QWORD PTR ds:0x8048e60
0x8048878: fsubrp st(1),st
0x804887a: fnstcw WORD PTR [ebp-0x22]
0x804887d: movzx eax,WORD PTR [ebp-0x22]
0x8048881: mov ah,0xc
0x8048883: mov WORD PTR [ebp-0x24],ax
0x8048887: fldcw WORD PTR [ebp-0x24]
0x804888a: fistp QWORD PTR [ebp-0x30]
0x804888d: fldcw WORD PTR [ebp-0x22]
0x8048890: mov eax,DWORD PTR [ebp-0x30]
0x8048893: mov edx,DWORD PTR [ebp-0x2c]
0x8048896: mov ecx,eax
0x8048898: xor ch,0x0
0x804889b: mov DWORD PTR [ebp-0x38],ecx
0x804889e: mov eax,edx
0x80488a0: xor eax,0x80000000
0x80488a5: mov DWORD PTR [ebp-0x34],eax
0x80488a8: mov eax,DWORD PTR [ebp-0x38]
0x80488ab: mov edx,DWORD PTR [ebp-0x34]
0x80488ae: shld edx,eax,0x2
0x80488b2: shl eax,0x2
0x80488b5: add eax,0x15
0x80488b8: adc edx,0x0
0x80488bb: mov DWORD PTR [ebp-0x10],eax
0x80488be: mov DWORD PTR [ebp-0xc],edx
0x80488c1: mov eax,DWORD PTR [ebp-0x10]
0x80488c4: xor eax,DWORD PTR [ebp-0x20]
0x80488c7: mov ebx,eax
0x80488c9: mov eax,DWORD PTR [ebp-0xc]
0x80488cc: xor eax,DWORD PTR [ebp-0x1c]
0x80488cf: mov esi,eax
0x80488d1: mov eax,ebx
0x80488d3: or eax,esi
0x80488d5: test eax,eax
0x80488d7: sete al
0x80488da: movzx eax,al
0x80488dd: lea esp,[ebp-0x8]
0x80488e0: pop ebx
0x80488e1: pop esi
0x80488e2: pop ebp
0x80488e3: ret
{% endhighlight %}
I will be honest, I spend some here, actually most of my time on this single function. We see that it takes input for pow() from
the rest of my flag values and as well as the initialized values of section 4's main function at line 21. After that depending on the
result at line 27 (fucomi st,st(1)) with "jump if above or equal" at line 29 performs different actions. After some trial and error
I noticed that if the result always has to be below that comparison. Let me show you what that comparison looks like:
{% highlight bash %}
(gdb) hb *0x804884e
Hardware assisted breakpoint 11 at 0x804884e
(gdb) c
Continuing.
Breakpoint 11, 0x0804884e in ?? ()
(gdb) info all-registers
eax 0x1 1
ecx 0xbd2fffff -1120927745
edx 0x0 0
ebx 0xb 11
esp 0xbfffef88 0xbfffef88
ebp 0xbfffefc0 0xbfffefc0
esi 0x8048db8 134516152
edi 0xbffff048 -1073745848
eip 0x804884e 0x804884e
eflags 0x10286 [ PF SF IF RF ]
cs 0x73 115
ss 0x7b 123
ds 0x7b 123
es 0x7b 123
fs 0x0 0
gs 0x33 51
st0 <API key> (raw <API key>) <--- greater than st1, no good
st1 9223372036854775808 (raw <API key>)
{% endhighlight %}
So here, we are in violation. My input is "A" so let's try one character less..
{% highlight bash %}
(gdb) run flag{packer@AAAAAA}
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/user/ctfs/poliCTF/re350/topack flag{packer@AAAAAA}
Breakpoint 1, 0x080484a0 in ?? ()
(gdb) c
Continuing.
Breakpoint 9, 0x080489a9 in ?? ()
(gdb)
Continuing.
Breakpoint 10, 0x08048813 in ?? ()
(gdb)
Continuing.
Breakpoint 11, 0x0804884e in ?? ()
(gdb) info all-registers
eax 0x1 1
ecx 0xbbffffff -1140850689
edx 0x0 0
ebx 0xb 11
esp 0xbfffef88 0xbfffef88
ebp 0xbfffefc0 0xbfffefc0
esi 0x8048db8 134516152
edi 0xbffff048 -1073745848
eip 0x804884e 0x804884e
eflags 0x10286 [ PF SF IF RF ]
cs 0x73 115
ss 0x7b 123
ds 0x7b 123
es 0x7b 123
fs 0x0 0
gs 0x33 51
st0 <API key> (raw <API key>) <-- greater than st1, no good
st1 9223372036854775808 (raw <API key>)
{% endhighlight %}
Looks like we are still in violation. Let's try one less, which is an question mark.
{% highlight bash %}
(gdb) run flag{packer?AAAAAA}
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/user/ctfs/poliCTF/re350/topack flag{packer?AAAAAA}
Breakpoint 1, 0x080484a0 in ?? ()
(gdb) c
Continuing.
Breakpoint 9, 0x080489a9 in ?? ()
(gdb) c
Continuing.
Breakpoint 10, 0x08048813 in ?? ()
(gdb) c
Continuing.
Breakpoint 11, 0x0804884e in ?? ()
(gdb) info all-registers
eax 0x1 1
ecx 0xbc0fffff -1139802113
edx 0x0 0
ebx 0xb 11
esp 0xbfffef88 0xbfffef88
ebp 0xbfffefc0 0xbfffefc0
esi 0x8048db8 134516152
edi 0xbffff048 -1073745848
eip 0x804884e 0x804884e
eflags 0x10286 [ PF SF IF RF ]
cs 0x73 115
ss 0x7b 123
ds 0x7b 123
es 0x7b 123
fs 0x0 0
gs 0x33 51
st0 9223372036854775808 (raw <API key>) <--- equal, OK
st1 9223372036854775808 (raw <API key>)
{% endhighlight %}
Looks like we have a match. This means that our input needs to be computed from characters with value equal or less than the question mark, which is just some symbols and numbers.
We now know that the main function of section 5, checks for 11 characters and they all need to be numeric + some symbols.
Ok, but where does the real comparison is being worked at ? Well, it's outside this crazy looking floating numbers routine,
at line 42 address 0x8048a06 and also line number 51 address 0x8048a20. The first check at line 42, checks if the return of 0x8048813
different from 0. If it's a zero it's no good because it puts 0 in eax and exits and thus our section number 5 function will not
return the desired '1'. The check at line 51 address 0x8048a20 checks if all 11 characters past "flag{packer" has been evaluated.
The way I solved this is to add hardware breakpoints on those 2 locations and start brute-forcing my input.
After some tedious manual brute-forcing the input ended up being "flag{packer-15-4-?41="
# Section number 6
{% highlight bash %}
(gdb) hb *0x804890b
Hardware assisted breakpoint 12 at 0x804890b
(gdb) run flag{packer-15-4-?41=-AAAAAAAAA}
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/user/ctfs/poliCTF/re350/topack flag{packer-15-4-?41=AAAAAAAAA}
Breakpoint 1, 0x080484a0 in ?? ()
(gdb) c
Continuing.
Breakpoint 12, 0x0804890b in ?? ()
(gdb) x/100i $eip
=> 0x804890b: push ebp
0x804890c: mov ebp,esp
0x804890e: push ebx
0x804890f: sub esp,0x14
0x8048912: mov DWORD PTR [ebp-0xc],0x8048d41
0x8048919: mov eax,DWORD PTR [ebp+0x1c]
0x804891c: add eax,0x16
0x804891f: mov ebx,eax
0x8048921: sub esp,0xc
0x8048924: push DWORD PTR [ebp+0x18]
0x8048927: call 0x8048480 <strlen@plt>
0x804892c: add esp,0x10
0x804892f: cmp ebx,eax
0x8048931: jb 0x804893a
0x8048933: mov eax,0x1
0x8048938: jmp 0x80489a4
0x804893a: mov edx,DWORD PTR [ebp+0x1c]
0x804893d: mov eax,DWORD PTR [ebp-0xc]
0x8048940: add eax,edx
0x8048942: movzx ecx,BYTE PTR [eax]
0x8048945: mov eax,DWORD PTR [ebp+0x1c]
0x8048948: lea edx,[eax+0x14]
0x804894b: mov eax,DWORD PTR [ebp+0x18]
0x804894e: add eax,edx
0x8048950: movzx eax,BYTE PTR [eax]
0x8048953: xor eax,ecx
0x8048955: mov BYTE PTR [ebp-0xd],al
0x8048958: mov eax,DWORD PTR [ebp+0x1c]
0x804895b: add eax,0x15
0x804895e: mov edx,eax
0x8048960: mov eax,DWORD PTR [ebp+0x18]
0x8048963: add eax,edx
0x8048965: movzx eax,BYTE PTR [eax]
0x8048968: mov BYTE PTR [ebp-0xe],al
0x804896b: movzx eax,BYTE PTR [ebp-0xd]
0x804896f: cmp al,BYTE PTR [ebp-0xe]
0x8048972: je 0x804897b
0x8048974: mov eax,0x0
0x8048979: jmp 0x80489a4
0x804897b: mov eax,DWORD PTR [ebp+0x1c]
0x804897e: add eax,0x1
0x8048981: sub esp,0x8
0x8048984: push eax
0x8048985: push DWORD PTR [ebp+0x18]
0x8048988: push 0xdeadb00b
0x804898d: push 0xdeadb00b
0x8048992: push 0xdeadb00b
0x8048997: push 0xdeadb00b
0x804899c: call 0x804890b
0x80489a1: add esp,0x20
0x80489a4: mov ebx,DWORD PTR [ebp-0x4]
0x80489a7: leave
0x80489a8: ret
{% endhighlight %}
We can see that this is a recursive function, on lines 14-27 this function takes each character from our input starting from the 22nd byte until the end of the input and it calls itself at line 62.
At lines 49 and 50 it checks if the character currently being checks is correct or not, otherwise continues to line 51 where it fails.
So let's add a breakpoint at 0x804896f and check the compared values.
{% highlight bash %}
(gdb) hb *0x804896f
Hardware assisted breakpoint 13 at 0x804896f
(gdb) c
Continuing.
Breakpoint 13, 0x0804896f in ?? ()
(gdb) info reg
eax 0x2d 45
ecx 0x10 16
edx 0x15 21
ebx 0x16 22
esp 0xbffff040 0xbffff040
ebp 0xbffff058 0xbffff058
esi 0x0 0
edi 0x0 0
eip 0x804896f 0x804896f
eflags 0x10286 [ PF SF IF RF ]
cs 0x73 115
ss 0x7b 123
ds 0x7b 123
es 0x7b 123
fs 0x0 0
gs 0x33 51
(gdb) x/bx $ebp-0xe
0xbffff04a: 0x41
(gdb)
{% endhighlight %}
0x2d is a dash "-" and our value in [ebp-0xe] "A". Good, just an easy comparison, however I found that I needed to restart the process
after each time I find the correct next byte...
{% highlight bash %}
(gdb) x/bx $ebp-0xe
0xbffff04a: 0x2d
(gdb) x/bx $ebp-0xe
0xbffff00a: 0x69
(gdb) x/bx $ebp-0xe
0xbffff00a: 0x6e
(gdb) x/bx $ebp-0xe
0xbfffef8a: 0x2d
(gdb) x/bx $ebp-0xe
0xbfffef8a: 0x74
(gdb) x/bx $ebp-0xe
0xbfffef0a: 0x68
(gdb) x/bx $ebp-0xe
0xbfffef0a: 0x33
(gdb) x/bx $ebp-0xe
0xbfffee8a: 0x2d
(gdb) x/bx $ebp-0xe
0xbfffee8a: 0x34
(gdb) x/bx $ebp-0xe
0xbfffee0a: 0x73
(gdb) x/bx $ebp-0xe
0xbfffee0a: 0x73
{% endhighlight %}
So far the flag is "flag{packer-15-4-?41=-in-th3-4ss", of to the last section, Section number 7.
# Section number 7
{% highlight bash %}
(gdb) run flag{packer-15-4-?41=-<API key>
Starting program: /home/user/ctfs/poliCTF/re350/topack flag{packer-15-4-?41=-<API key>
Breakpoint 1, 0x080484a0 in ?? ()
(gdb) hb *0x80488e4
Hardware assisted breakpoint 14 at 0x80488e4
(gdb) c
Continuing.
wrong End for flag{packer-15-4-?41=-<API key>
Breakpoint 14, 0x080488e4 in ?? ()
(gdb) x/100i $eip
=> 0x80488e4: push ebp
0x80488e5: mov ebp,esp
0x80488e7: sub esp,0x8
0x80488ea: sub esp,0xc
0x80488ed: push DWORD PTR [ebp+0x18]
0x80488f0: call 0x8048480 <strlen@plt>
0x80488f5: add esp,0x10
0x80488f8: cmp eax,0x21
0x80488fb: jne 0x8048904
0x80488fd: mov eax,0x1
0x8048902: jmp 0x8048909
0x8048904: mov eax,0x0
0x8048909: leave
0x804890a: ret
{% endhighlight %}
Thank god this is a simple one, it just checks if the length of our input is equal 33 chars. So if the input of our flag so far
"flag{packer-15-4-?41=-in-th3-4ss" is 32 and we know it needs to end with "}", I think we have the flag.
{% highlight bash %}
user@ubuntu:~/ctfs/poliCTF/re350$ ./topack flag{packer-15-4-?41=-in-th3-4ss}
You got the flag: flag{packer-15-4-?41=-in-th3-4ss}
user@ubuntu:~/ctfs/poliCTF/re350$
{% endhighlight %}
Sorry for the lengthy write-up and thank you for reading.
## Links
* <http://polictf.it/> |
namespace ThinkingHome.NooLite.LibUsb.PR1132
{
public enum PR1132ChannelUiType
{
Switcher = 0,
Dimmer = 1,
RestoreState = 2,
LED = 3
}
} |
<?php
namespace ElfChat\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @property int $id
* @property \ElfChat\Entity\User $user
* @property string $ip
* @property int $howLong
* @property \DateTime $created
* @property \ElfChat\Entity\User $author
* @property string $reason
*
* @ORM\Entity
* @ORM\Table("elfchat_ban", indexes={
* @ORM\Index(name="ip_idx", columns={"ip"}),
* @ORM\Index(name="user_idx", columns={"user_id"})
* })
*/
class Ban extends Entity
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="ElfChat\Entity\User")
*/
protected $user;
/**
* @ORM\Column(type="string", length=45, nullable=true)
*/
protected $ip;
/**
* How long to bun in seconds.
* @ORM\Column(type="integer")
*/
protected $howLong;
/**
* @ORM\Column(type="integer")
*/
protected $created;
/**
* @ORM\ManyToOne(targetEntity="ElfChat\Entity\User")
*/
protected $author;
/**
* @ORM\Column(type="string", nullable=true)
*/
protected $reason;
public function __constructor()
{
$this->created = time();
}
public function isActive()
{
return time() - $this->created < $this->howLong;
}
/**
* @return mixed
*/
public function getCreated()
{
return \DateTime::createFromFormat('U', $this->created);
}
public function getHowLongString()
{
$ch = self::howLongChoices();
return $ch[$this->howLong];
}
public static function howLongChoices()
{
return array(
60 => 'One min',
60 * 5 => '5 min',
60 * 15 => '15 min',
60 * 60 => 'One hour',
60 * 60 * 12 => '12 hours',
60 * 60 * 24 => 'One day',
60 * 60 * 24 * 2 => '2 days',
60 * 60 * 24 * 7 => '7 days',
60 * 60 * 24 * 14 => '14 days',
60 * 60 * 24 * 31 => '31 days',
-1 => 'Forever',
);
}
public static function findAll()
{
$dql = "SELECT b FROM ElfChat\Entity\Ban b ORDER BY b.created DESC";
$query = self::entityManager()->createQuery($dql);
return $query->getResult();
}
public static function findActive($userId, $ip)
{
$dql = "
SELECT b FROM ElfChat\Entity\Ban b
WHERE (b.user = :userId OR b.ip = :ip) AND :now < b.created + b.howLong
";
$query = self::entityManager()->createQuery($dql);
$query->setParameter('userId', $userId);
$query->setParameter('ip', $ip);
$query->setParameter('now', time());
$query->setMaxResults(1);
return $query->getResult();
}
} |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# copies or substantial portions of the Software.
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import os
import subprocess
import logging
logger = logging.getLogger('sbpipe')
def which(cmd_name):
"""
Utility equivalent to `which` in GNU/Linux OS.
:param cmd_name: a command name
:return: return the command name with absolute path if this exists, or None
"""
for path in os.environ["PATH"].split(os.pathsep):
if os.path.exists(os.path.join(path, cmd_name)):
return os.path.join(path, cmd_name)
if os.path.exists(os.path.join(path, cmd_name + '.exe')):
return os.path.join(path, cmd_name + '.exe')
return None
def <API key>(package):
"""
Utility checking whether a Python package is installed.
:param package: a Python package name
:return: True if it is installed, false otherwise.
"""
try:
installed_packages = subprocess.Popen(['pip', 'list'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()[0]
if package in str(installed_packages):
return True
return False
except OSError as e:
logger.warning("pip is not installed")
return False
def <API key>(package):
"""
Utility checking whether a R package is installed.
:param package: an R package name
:return: True if it is installed, false otherwise.
"""
try:
output = subprocess.Popen(['Rscript',
os.path.join(os.path.dirname(__file__), os.pardir, "<API key>.r"),
package],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()[0]
logger.debug("is sbpiper installed? " + str(output))
if "TRUE" in str(output):
return True
return False
except OSError as e:
logger.error("R is not installed")
return False |
title: Collection utilities
sidebar_label: Collection utilities {}
hide_title: true
<script async type="text/javascript" src="//cdn.carbonads.com/carbon.js?serve=CEBD4KQ7&placement=mobxjsorg" id="_carbonads_js"></script>
# Collection utilities {}
They enable manipulating observable arrays, objects and Maps with the same generic API.
These APIs are fully reactive, which means that even [without `Proxy` support](configuration.md#<API key>) new property declarations can be detected by MobX if `set` is used to add them, and `values` or `keys` are used to iterate over them.
Another benefit of `values`, `keys` and `entries` is that they return arrays rather than iterators, which makes it possible to, for example, immediately call `.map(fn)` on the results.
All that being said, a typical project has little reason to use these APIs.
Access:
- `values(collection)` returns an array of all the values in the collection.
- `keys(collection)` returns an array of all the keys in the collection.
- `entries(collection)` returns an array of all the entries `[key, value]` pairs in the collection.
Mutation:
- `set(collection, key, value)` or `set(collection, { key: value })` update the given collection with the provided key / value pair(s).
- `remove(collection, key)` removes the specified child from the collection. Splicing is used for arrays.
- `has(collection, key)` returns _true_ if the collection has the specified _observable_ property.
- `get(collection, key)` returns the child under the specified key.
If you use the access APIs in an environment without `Proxy` support, then also use the mutation APIs so they can detect the changes.
javascript
import { get, set, observable, values } from "mobx"
const twitterUrls = observable.object({
Joe: "twitter.com/joey"
})
autorun(() => {
// Get can track not yet existing properties.
console.log(get(twitterUrls, "Sara"))
})
autorun(() => {
console.log("All urls: " + values(twitterUrls).join(", "))
})
set(twitterUrls, { Sara: "twitter.com/horsejs" }) |
import { moduleForComponent, test } from 'ember-qunit';
var component;
moduleForComponent('magma-button', 'Unit | Component | magma button', {
unit: true,
setup() {
component = this.subject({name: 'buttons', value: 'button1'});
},
teardown() {
component = null;
}
});
test('Component has correct initial value', function (assert) {
assert.expect(2);
assert.ok(component.get('name') !== null);
assert.ok(component.get('value') !== null);
}); |
import { Button } from '@rocket.chat/fuselage';
import React, { memo } from 'react';
import { <API key> } from '../../../../contexts/<API key>';
import { useMethod } from '../../../../contexts/ServerContext';
import { <API key> } from '../../../../contexts/<API key>';
import { useTranslation } from '../../../../contexts/TranslationContext';
import GroupPage from '../GroupPage';
import Section from '../Section';
function AssetsGroupPage({ _id, ...group }) {
const sections = <API key>(_id);
const solo = sections.length === 1;
const t = useTranslation();
const refreshClients = useMethod('refreshClients');
const <API key> = <API key>();
const <API key> = async () => {
try {
await refreshClients();
<API key>({
type: 'success',
message: t('<API key>'),
});
} catch (error) {
<API key>({ type: 'error', message: error });
}
};
return (
<GroupPage
_id={_id}
{...group}
headerButtons={
<>
<Button onClick={<API key>}>
{t('<API key>')}
</Button>
</>
}
>
{sections.map((sectionName) => (
<Section
key={sectionName}
groupId={_id}
hasReset={false}
sectionName={sectionName}
solo={solo}
/>
))}
</GroupPage>
);
}
export default memo(AssetsGroupPage); |
package au.edu.unimelb.csse.mugle.client.api;
import java.io.Serializable;
import com.google.gwt.user.client.rpc.AsyncCallback;
/**
* Developer async API for accessing the key/value store. This allows each game
* to associate arbitrary data with string keys, independently for each user.
*/
public interface <API key> {
/**
* Store an object in the key-value store. The value will be specific to the
* current user, and will only be able to be retrieved by the same user.
*
* @param gameToken
* The secret token for the current game.
* @param key
* The key to associate the object with.
* @param value
* The object to store.
* @param callback
* Called once the operation finishes.
*/
public void put(String gameToken, String key, Serializable value,
AsyncCallback<Void> callback);
/**
* Retrieve an object from the key-value store. The value will be the one
* stored by the current user.
*
* @param gameToken
* The secret token for the current game.
* @param key
* The key the object is associated with.
* @param callback
* Called once the operation finishes. On success, passes the
* object associated with the key. Fails (KeyError) if no object
* is associated with that key.
*/
public void get(String gameToken, String key,
AsyncCallback<Serializable> callback);
/**
* Test whether a key has an associated object for the current user.
*
* @param gameToken
* The secret token for the current game.
* @param key
* The key the object is associated with.
* @param callback
* Called once the operation finishes. On success, passes true if
* a value is associated with the key.
*/
public void containsKey(String gameToken, String key,
AsyncCallback<Boolean> callback);
} |
namespace NEventStore.Persistence.Sql.SqlDialects
{
using System;
using System.Data;
using System.Transactions;
using NEventStore.Persistence.Sql;
public abstract class CommonSqlDialect : ISqlDialect
{
public abstract string InitializeStorage { get; }
public virtual string PurgeStorage
{
get { return CommonSqlStatements.PurgeStorage; }
}
public string PurgeBucket
{
get { return CommonSqlStatements.PurgeBucket; }
}
public virtual string Drop
{
get { return CommonSqlStatements.DropTables; }
}
public virtual string DeleteStream
{
get { return CommonSqlStatements.DeleteStream; }
}
public virtual string <API key>
{
get { return CommonSqlStatements.<API key>; }
}
public virtual string <API key>
{
get { return CommonSqlStatements.<API key>; }
}
public virtual string <API key>
{
get { return CommonSqlStatements.<API key>; }
}
public abstract string PersistCommit { get; }
public virtual string DuplicateCommit
{
get { return CommonSqlStatements.DuplicateCommit; }
}
public virtual string <API key>
{
get { return CommonSqlStatements.<API key>; }
}
public virtual string GetSnapshot
{
get { return CommonSqlStatements.GetSnapshot; }
}
public virtual string <API key>
{
get { return CommonSqlStatements.<API key>; }
}
public virtual string <API key>
{
get { return CommonSqlStatements.<API key>; }
}
public virtual string <API key>
{
get { return CommonSqlStatements.<API key>; }
}
public virtual string BucketId
{
get { return "@BucketId"; }
}
public virtual string StreamId
{
get { return "@StreamId"; }
}
public virtual string StreamIdOriginal
{
get { return "@StreamIdOriginal"; }
}
public virtual string StreamRevision
{
get { return "@StreamRevision"; }
}
public virtual string MaxStreamRevision
{
get { return "@MaxStreamRevision"; }
}
public virtual string Items
{
get { return "@Items"; }
}
public virtual string CommitId
{
get { return "@CommitId"; }
}
public virtual string CommitSequence
{
get { return "@CommitSequence"; }
}
public virtual string CommitStamp
{
get { return "@CommitStamp"; }
}
public virtual string CommitStampStart
{
get { return "@CommitStampStart"; }
}
public virtual string CommitStampEnd
{
get { return "@CommitStampEnd"; }
}
public virtual string Headers
{
get { return "@Headers"; }
}
public virtual string Payload
{
get { return "@Payload"; }
}
public virtual string Threshold
{
get { return "@Threshold"; }
}
public virtual string Limit
{
get { return "@Limit"; }
}
public virtual string Skip
{
get { return "@Skip"; }
}
public virtual bool CanPage
{
get { return true; }
}
public virtual string CheckpointNumber
{
get { return "@CheckpointNumber"; }
}
public virtual string <API key>
{
get { return CommonSqlStatements.<API key>; }
}
public virtual string <API key>
{
get { return CommonSqlStatements.<API key>; }
}
public virtual object <API key>(object value)
{
return value;
}
public abstract bool IsDuplicate(Exception exception);
public virtual void AddPayloadParamater(IConnectionFactory connectionFactory, IDbConnection connection, IDbStatement cmd, byte[] payload)
{
cmd.AddParameter(Payload, payload);
}
public virtual DateTime ToDateTime(object value)
{
value = value is decimal ? (long) (decimal) value : value;
return value is long ? new DateTime((long) value) : DateTime.SpecifyKind((DateTime) value, DateTimeKind.Utc);
}
public virtual NextPageDelegate NextPageDelegate
{
get { return (q, r) => q.SetParameter(CommitSequence, r.CommitSequence()); }
}
public virtual IDbTransaction OpenTransaction(IDbConnection connection)
{
return null;
}
public virtual IDbStatement BuildStatement(
TransactionScope scope, IDbConnection connection, IDbTransaction transaction)
{
return new CommonDbStatement(this, scope, connection, transaction);
}
}
} |
<?php
namespace Unicodeveloper\Yearly;
use Illuminate\Support\Facades\Facade;
class YearlyFacade extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'laravel-yearly';
}
} |
<?php
namespace Oro\Bundle\UserBundle\Tests\Functional\Command;
use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit;
use Oro\Bundle\OrganizationBundle\Entity\Organization;
use Oro\Bundle\TestFrameworkBundle\Test\WebTestCase;
use Oro\Bundle\UserBundle\Command\CreateUserCommand;
use Oro\Bundle\UserBundle\Command\UpdateUserCommand;
use Oro\Bundle\UserBundle\Entity\User;
use Oro\Bundle\UserBundle\Entity\UserManager;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
class <API key> extends WebTestCase
{
/**
* @var Application
*/
protected $application;
/**
* @var BusinessUnit[]
*/
protected $businessUnits;
/**
* @var Organization[]
*/
protected $organizations;
/**
* @var UserManager
*/
protected $userManager;
protected function setUp()
{
$this->initClient();
$this->loadFixtures(['Oro\Bundle\UserBundle\Tests\Functional\DataFixtures\<API key>']);
$this->application = new Application($this->client->getKernel());
$this->application->setAutoExit(false);
$this->application->add(new CreateUserCommand());
$this->application->add(new UpdateUserCommand());
$this->businessUnits = ['bu1' => $this->getReference('bu1')];
$this->organizations = [
'org1' => $this->getReference('org1'),
'org2' => $this->getReference('org2'),
'org3' => $this->getReference('org3'),
];
$this->userManager = $this->getContainer()->get('oro_user.manager');
}
/**
* @dataProvider parametersProvider
*
* @param array $arguments
* @param string $result
*/
public function testParameters(array $arguments, $result)
{
$command = $this->application->find($arguments['command']);
$commandTester = new CommandTester($command);
$commandTester->execute($arguments);
$businessUnit =
isset($arguments['--user-business-unit']) &&
isset($this->businessUnits[$arguments['--user-business-unit']])
? $this->businessUnits[$arguments['--user-business-unit']]
: null;
if (!empty($result)) {
$this-><API key>($result, $commandTester->getDisplay());
return;
}
$this->assertEmpty($commandTester->getDisplay());
/** @var User $user */
$user = $this->userManager->findUserByUsername($arguments['--user-name']);
$this->assertNotEmpty($user);
if ($businessUnit) {
$this->assertSame($user->getOrganization(), $businessUnit->getOrganization());
$this->assertContains($businessUnit, $user->getBusinessUnits());
}
$this->assertTrue($user->isEnabled());
$this->assertEquals($arguments['--user-name'], $user->getUsername());
$this->assertEquals($arguments['--user-email'], $user->getEmail());
$this->assertEquals($arguments['--user-firstname'], $user->getFirstName());
$this->assertEquals($arguments['--user-lastname'], $user->getLastName());
$userOrganizations = $user->getOrganizations();
foreach ($arguments['--user-organizations'] as $organizationName) {
$this->assertContains($this->organizations[$organizationName], $userOrganizations);
}
}
/**
* @depends testParameters
*/
public function <API key>()
{
$arguments = [
'command' => 'oro:user:create',
'--user-business-unit' => 'bu1',
'--user-name' => 'test_user_main',
'--user-email' => 'test_user_main@example.com',
'--user-password' => 'admin',
];
$command = $this->application->find('oro:user:create');
$commandTester = new CommandTester($command);
$commandTester->execute($arguments);
$this-><API key>('User exists', $commandTester->getDisplay());
}
/**
* @return array
*/
public function parametersProvider()
{
return [
'create' => [
'arguments' => [
'command' => 'oro:user:create',
'--user-business-unit' => 'bu1',
'--user-name' => 'test_user_1',
'--user-email' => 'test_user_1@mailinator.com',
'--user-firstname' => 'User1F',
'--user-lastname' => 'User1L',
'--user-password' => 'admin',
'--user-organizations' => ['org2', 'org3'],
],
'result' => '',
],
'update' => [
'arguments' => [
'command' => 'oro:user:update',
'user-name' => 'test_user_1',
'--user-name' => 'test_user_2',
'--user-email' => 'test_user_2@mailinator.com',
'--user-firstname' => 'User2F',
'--user-lastname' => 'User2L',
'--user-organizations' => ['org1'],
],
'result' => '',
],
'invalid business unit' => [
'arguments' => [
'command' => 'oro:user:create',
'--user-business-unit' => '<API key>',
'--user-name' => 'new_user_1',
'--user-email' => 'test_user_2@mailinator.com',
'--user-password' => 'admin',
],
'result' => 'Invalid Business Unit',
],
'invalid organization' => [
'arguments' => [
'command' => 'oro:user:create',
'--user-organizations' => ['<API key>'],
'--user-business-unit' => 'bu1',
'--user-name' => 'new_user_2',
'--user-email' => 'test_user_2@mailinator.com',
'--user-password' => 'admin',
],
'result' => 'Invalid organization',
],
'invalid role' => [
'arguments' => [
'command' => 'oro:user:create',
'--user-role' => ['<API key>'],
'--user-business-unit' => 'bu1',
'--user-name' => 'new_user_3',
'--user-email' => 'test_user_2@mailinator.com',
'--user-password' => 'admin',
],
'result' => 'Invalid Role',
],
'business unit required' => [
'arguments' => [
'command' => 'oro:user:create',
'--user-name' => 'new_user_1',
'--user-email' => 'test_user_2@mailinator.com',
'--user-password' => 'admin',
],
'result' => '--user-business-unit option required',
],
'username required' => [
'arguments' => [
'command' => 'oro:user:create',
'--user-business-unit' => '<API key>',
'--user-email' => 'test_user_2@mailinator.com',
'--user-password' => 'admin',
],
'result' => '--user-name option required',
],
'user email required' => [
'arguments' => [
'command' => 'oro:user:create',
'--user-business-unit' => '<API key>',
'--user-name' => 'new_user_1',
'--user-password' => 'admin',
],
'result' => '--user-email option required',
],
'user password required' => [
'arguments' => [
'command' => 'oro:user:create',
'--user-business-unit' => '<API key>',
'--user-name' => 'new_user_1',
'--user-email' => 'test_user_2@mailinator.com',
],
'result' => '--user-password option required',
],
];
}
} |
# Supported Conversions
RCall supports conversions to and from most base Julia types and popular Statistics packages, e.g., `DataFrames`, `CategoricalArrays` and `AxisArrays`.
@setup 1
using Pkg
Pkg.add("DataFrames")
Pkg.add("AxisArrays")
using RCall
using Dates
using DataFrames
using AxisArrays
## Base Julia Types
@example 1
# Julia -> R
a = robject(1)
@example 1
# R -> Julia
rcopy(a)
@example 1
# Julia -> R
a = robject([1.0, 2.0])
@example 1
# R -> Julia
rcopy(a)
## Dictionaries
@example 1
# Julia -> R
d = Dict(:a => 1, :b => [4, 5, 3])
r = robject(d)
@example 1
# R -> Julia
rcopy(r)
## Date
@example 1
# Julia -> R
d = Date(2012, 12, 12)
r = robject(d)
@example 1
# R -> Julia
rcopy(r)
## DateTime
@example 1
# julia -> R
d = DateTime(2012, 12, 12, 12, 12, 12)
r = robject(d)
@example 1
# R -> Julia
rcopy(r)
## DataFrames
@example 1
d = DataFrame([[1.0, 4.5, 7.0]], [:x])
# Julia -> R
r = robject(d)
@example 1
# R -> Julia
rcopy(r)
In default, the column names of R data frames are normalized such that `foo.bar`
would be replaced by `foo_bar`.
@example 1
rcopy(R"data.frame(a.b = 1:3)")
To avoid the normalization, use `normalizenames` option.
@example 1
rcopy(R"data.frame(a.b = 1:10)"; normalizenames = false)
## AxisArrays
@example 1
# Julia -> R
aa = AxisArray([1,2,3], Axis{:id}(["a", "b", "c"]))
r = robject(aa)
@example 1
# R -> Julia
rcopy(AxisArray, r) |
<?php
namespace App\Http\Middleware;
use Bugsnag\BugsnagLaravel\Facades\Bugsnag;
use Closure;
use Exception;
class HandledMiddlewareEx
{
public function handle($request, Closure $next)
{
Bugsnag::notifyException(new Exception('Handled middleware exception'));
$next($request);
}
} |
#import <Foundation/NSObject.h>
@class NSNotification, <API key>, NSArray<ObjectType>, NSString;
<API key>
typedef NS_ENUM(NSUInteger, NSPostingStyle) {
NSPostWhenIdle = 1,
NSPostASAP = 2,
NSPostNow = 3
};
typedef NS_OPTIONS(NSUInteger, <API key>) {
<API key> = 0,
<API key> = 1,
<API key> = 2
};
@interface NSNotificationQueue : NSObject {
@private
id _notificationCenter;
id _asapQueue;
id _asapObs;
id _idleQueue;
id _idleObs;
}
+ (NSNotificationQueue *)defaultQueue;
- (instancetype)<API key>:(<API key> *)notificationCenter <API key>;
- (void)enqueueNotification:(NSNotification *)notification postingStyle:(NSPostingStyle)postingStyle;
- (void)enqueueNotification:(NSNotification *)notification postingStyle:(NSPostingStyle)postingStyle coalesceMask:(<API key>)coalesceMask forModes:(nullable NSArray<NSString *> *)modes;
- (void)<API key>:(NSNotification *)notification coalesceMask:(NSUInteger)coalesceMask;
@end
<API key> |
require "cp8_cli/github/api"
require "cp8_cli/github/parsed_url"
require "cp8_cli/story"
module Cp8Cli
module Github
class Issue < Story
include Api::Client
def initialize(number:, repo:, **attributes)
@number = number
@repo = repo
@attributes = attributes
end
def self.find_by_url(url)
url = ParsedUrl.new(url)
issue = client.issue(url.repo, url.number).to_h
new issue.merge(number: url.number, repo: url.repo)
end
def title
attributes[:title]
end
def summary
"Closes #{short_link}"
end
private
attr_reader :number, :repo, :attributes
def assign
client.add_assignees repo, number, [user.github_login]
end
def user
CurrentUser.new
end
def short_link
"#{repo}##{number}"
end
end
end
end |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Orleans.TestingHost;
using TestExtensions;
using UnitTests.GrainInterfaces;
using Xunit;
using Orleans.TestingHost.Utils;
using Orleans.Hosting;
using Orleans.Configuration;
using System.Diagnostics;
namespace Tester.Forwarding
{
public class ShutdownSiloTests : TestClusterPerTest
{
public const int NumberOfSilos = 2;
public static readonly TimeSpan DeactivationTimeout = TimeSpan.FromSeconds(10);
internal class <API key> : <API key>
{
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder.Configure<<API key>>(options =>
{
options.DeactivationTimeout = DeactivationTimeout;
}).<API key>(options => options.ConnectionString = <API key>.<API key>);
}
}
protected override void <API key>()
{
base.<API key>();
TestUtils.<API key>();
}
protected override void <API key>(TestClusterBuilder builder)
{
builder.Options.InitialSilosCount = NumberOfSilos;
builder.<API key><<API key>>();
builder.<API key>(legacy =>
{
legacy.<API key>.Globals.<API key> = "<API key>";
legacy.<API key>.Globals.<API key> = 1;
legacy.<API key>.Globals.<API key> = 1;
});
}
public ShutdownSiloTests()
{
this.<API key>();
}
[SkippableFact, TestCategory("Forward"), TestCategory("Functional")]
public async Task <API key>()
{
var grain = await <API key><bool>();
var tasks = new List<Task<string>>();
for (int i = 0; i < 100; i++)
{
tasks.Add(grain.<API key>(TimeSpan.FromMilliseconds(50)));
}
// Shutdown the silo where the grain is
await Task.Delay(500);
await HostedCluster.StopSiloAsync(HostedCluster.SecondarySilos.First());
var results = await Task.WhenAll(tasks);
Assert.Equal(results[99], HostedCluster.Primary.SiloAddress.ToLongString());
}
[SkippableFact, TestCategory("GracefulShutdown"), TestCategory("Functional")]
public async Task <API key>()
{
var grain = await <API key>();
var promise = grain.<API key>(TimeSpan.FromSeconds(10));
await Task.Delay(500);
await HostedCluster.StopSiloAsync(HostedCluster.SecondarySilos.First());
await promise;
}
[SkippableFact, TestCategory("GracefulShutdown"), TestCategory("Functional")]
public async Task <API key>()
{
var grain = await <API key>();
await grain.StartStuckTimer(TimeSpan.Zero);
await Task.Delay(TimeSpan.FromSeconds(1));
var stopwatch = Stopwatch.StartNew();
await HostedCluster.StopSiloAsync(HostedCluster.SecondarySilos.First());
stopwatch.Stop();
Assert.True(stopwatch.Elapsed > DeactivationTimeout);
}
[SkippableFact, TestCategory("GracefulShutdown"), TestCategory("Functional")]
public async Task <API key>()
{
var grain = await <API key>();
var promise = grain.<API key>(TimeSpan.FromMinutes(2));
await Task.Delay(500);
var stopwatch = Stopwatch.StartNew();
var cts = new <API key>(TimeSpan.FromSeconds(30));
await HostedCluster.SecondarySilos.First().StopSiloAsync(cts.Token);
stopwatch.Stop();
Assert.True(stopwatch.Elapsed < TimeSpan.FromMinutes(1));
}
private async Task<<API key><T>> <API key><T>()
{
while (true)
{
var grain = GrainFactory.GetGrain<<API key><T>>(Guid.NewGuid());
var instanceId = await grain.<API key>();
if (instanceId.Contains(HostedCluster.SecondarySilos[0].SiloAddress.Endpoint.ToString()))
{
return grain;
}
}
}
private async Task<ITimerRequestGrain> <API key>()
{
var i = 0;
while (true)
{
var grain = GrainFactory.GetGrain<ITimerRequestGrain>(i++);
var instanceId = await grain.<API key>();
if (instanceId.Contains(HostedCluster.SecondarySilos[0].SiloAddress.Endpoint.ToString()))
{
return grain;
}
}
}
}
} |
package jolokia2
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"path"
"time"
"github.com/influxdata/telegraf/plugins/common/tls"
)
type Client struct {
URL string
client *http.Client
config *ClientConfig
}
type ClientConfig struct {
ResponseTimeout time.Duration
Username string
Password string
ProxyConfig *ProxyConfig
tls.ClientConfig
}
type ProxyConfig struct {
<API key> string
<API key> string
Targets []ProxyTargetConfig
}
type ProxyTargetConfig struct {
Username string
Password string
URL string
}
type ReadRequest struct {
Mbean string
Attributes []string
Path string
}
type ReadResponse struct {
Status int
Value interface{}
RequestMbean string
RequestAttributes []string
RequestPath string
RequestTarget string
}
// Jolokia JSON request object. Example: {
// "type": "read",
// "mbean: "java.lang:type="Runtime",
// "attribute": "Uptime",
// "target": {
// "url: "service:jmx:rmi:///jndi/rmi://target:9010/jmxrmi"
type jolokiaRequest struct {
Type string `json:"type"`
Mbean string `json:"mbean"`
Attribute interface{} `json:"attribute,omitempty"`
Path string `json:"path,omitempty"`
Target *jolokiaTarget `json:"target,omitempty"`
}
type jolokiaTarget struct {
URL string `json:"url"`
User string `json:"user,omitempty"`
Password string `json:"password,omitempty"`
}
// Jolokia JSON response object. Example: {
// "request": {
// "type": "read"
// "mbean": "java.lang:type=Runtime",
// "attribute": "Uptime",
// "target": {
// "url": "service:jmx:rmi:///jndi/rmi://target:9010/jmxrmi"
// "value": 1214083,
// "timestamp": 1488059309,
// "status": 200
type jolokiaResponse struct {
Request jolokiaRequest `json:"request"`
Value interface{} `json:"value"`
Status int `json:"status"`
}
func NewClient(url string, config *ClientConfig) (*Client, error) {
tlsConfig, err := config.ClientConfig.TLSConfig()
if err != nil {
return nil, err
}
transport := &http.Transport{
<API key>: config.ResponseTimeout,
TLSClientConfig: tlsConfig,
}
client := &http.Client{
Transport: transport,
Timeout: config.ResponseTimeout,
}
return &Client{
URL: url,
config: config,
client: client,
}, nil
}
func (c *Client) read(requests []ReadRequest) ([]ReadResponse, error) {
jrequests := makeJolokiaRequests(requests, c.config.ProxyConfig)
requestBody, err := json.Marshal(jrequests)
if err != nil {
return nil, err
}
requestUrl, err := formatReadUrl(c.URL, c.config.Username, c.config.Password)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", requestUrl, bytes.NewBuffer(requestBody))
if err != nil {
return nil, fmt.Errorf("unable to create new request '%s': %s", requestUrl, err)
}
req.Header.Add("Content-type", "application/json")
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Response from url \"%s\" has status code %d (%s), expected %d (%s)",
c.URL, resp.StatusCode, http.StatusText(resp.StatusCode), http.StatusOK, http.StatusText(http.StatusOK))
}
responseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var jresponses []jolokiaResponse
if err = json.Unmarshal([]byte(responseBody), &jresponses); err != nil {
return nil, fmt.Errorf("Error decoding JSON response: %s: %s", err, responseBody)
}
return makeReadResponses(jresponses), nil
}
func makeJolokiaRequests(rrequests []ReadRequest, proxyConfig *ProxyConfig) []jolokiaRequest {
jrequests := make([]jolokiaRequest, 0)
if proxyConfig == nil {
for _, rr := range rrequests {
jrequests = append(jrequests, makeJolokiaRequest(rr, nil))
}
} else {
for _, t := range proxyConfig.Targets {
if t.Username == "" {
t.Username = proxyConfig.<API key>
}
if t.Password == "" {
t.Password = proxyConfig.<API key>
}
for _, rr := range rrequests {
jtarget := &jolokiaTarget{
URL: t.URL,
User: t.Username,
Password: t.Password,
}
jrequests = append(jrequests, makeJolokiaRequest(rr, jtarget))
}
}
}
return jrequests
}
func makeJolokiaRequest(rrequest ReadRequest, jtarget *jolokiaTarget) jolokiaRequest {
jrequest := jolokiaRequest{
Type: "read",
Mbean: rrequest.Mbean,
Path: rrequest.Path,
Target: jtarget,
}
if len(rrequest.Attributes) == 1 {
jrequest.Attribute = rrequest.Attributes[0]
}
if len(rrequest.Attributes) > 1 {
jrequest.Attribute = rrequest.Attributes
}
return jrequest
}
func makeReadResponses(jresponses []jolokiaResponse) []ReadResponse {
rresponses := make([]ReadResponse, 0)
for _, jr := range jresponses {
rrequest := ReadRequest{
Mbean: jr.Request.Mbean,
Path: jr.Request.Path,
Attributes: []string{},
}
attrValue := jr.Request.Attribute
if attrValue != nil {
attribute, ok := attrValue.(string)
if ok {
rrequest.Attributes = []string{attribute}
} else {
attributes, _ := attrValue.([]interface{})
rrequest.Attributes = make([]string, len(attributes))
for i, attr := range attributes {
rrequest.Attributes[i] = attr.(string)
}
}
}
rresponse := ReadResponse{
Value: jr.Value,
Status: jr.Status,
RequestMbean: rrequest.Mbean,
RequestAttributes: rrequest.Attributes,
RequestPath: rrequest.Path,
}
if jtarget := jr.Request.Target; jtarget != nil {
rresponse.RequestTarget = jtarget.URL
}
rresponses = append(rresponses, rresponse)
}
return rresponses
}
func formatReadUrl(configUrl, username, password string) (string, error) {
parsedUrl, err := url.Parse(configUrl)
if err != nil {
return "", err
}
readUrl := url.URL{
Host: parsedUrl.Host,
Scheme: parsedUrl.Scheme,
}
if username != "" || password != "" {
readUrl.User = url.UserPassword(username, password)
}
readUrl.Path = path.Join(parsedUrl.Path, "read")
readUrl.Query().Add("ignoreErrors", "true")
return readUrl.String(), nil
} |
#ifdef _MSC_VER
#define <API key>
#endif
#include "test.hpp"
#include <boost/multiprecision/mpfi.hpp>
#include <boost/multiprecision/random.hpp>
using namespace boost::multiprecision;
using namespace boost::random;
void test_exp()
{
std::cout << "Testing exp\n";
mpfr_float_50 val = 1.25;
for (unsigned i = 0; i < 2000; ++i)
{
mpfr_float_100 a(val);
mpfr_float_100 b = exp(a);
mpfi_float_50 in = val;
in = exp(in);
BOOST_CHECK((boost::math::isfinite)(in));
BOOST_CHECK(lower(in) <= b);
BOOST_CHECK(upper(in) >= b);
b = log(a);
in = val;
in = log(in);
BOOST_CHECK((boost::math::isfinite)(in));
BOOST_CHECK(lower(in) <= b);
BOOST_CHECK(upper(in) >= b);
val *= 1.01;
}
val = 1;
for (unsigned i = 0; i < 2000; ++i)
{
mpfr_float_100 a(val);
mpfr_float_100 b = exp(a);
mpfi_float_50 in = val;
in = exp(in);
BOOST_CHECK((boost::math::isfinite)(in));
BOOST_CHECK(lower(in) <= b);
BOOST_CHECK(upper(in) >= b);
b = log(a);
in = val;
in = log(in);
BOOST_CHECK((boost::math::isfinite)(in));
BOOST_CHECK(lower(in) <= b);
BOOST_CHECK(upper(in) >= b);
val /= 1.01;
}
}
void test_pow()
{
std::cout << "Testing pow function\n";
mt19937 gen;
<API key><mpfr_float_50> dist1(0, 400);
for (unsigned i = 0; i < 5000; ++i)
{
mpfr_float_50 base, p;
base = dist1(gen);
p = dist1(gen);
mpfr_float_100 a, b, r;
a = base;
b = p;
r = pow(a, b);
mpfi_float_50 ai, bi, ri;
ai = base;
bi = p;
ri = pow(ai, bi);
BOOST_CHECK((boost::math::isfinite)(ri));
BOOST_CHECK(lower(ri) <= r);
BOOST_CHECK(upper(ri) >= r);
}
}
void test_trig()
{
std::cout << "Testing trig functions\n";
mt19937 gen;
<API key><mpfr_float_50> dist1(-1.57079632679, 1.57079632679);
<API key><mpfr_float_50> dist2(-1, 1);
for (unsigned i = 0; i < 5000; ++i)
{
mpfr_float_50 val;
val = dist1(gen);
mpfr_float_100 a = val;
mpfr_float_100 b = sin(a);
mpfi_float_50 a2 = val;
mpfi_float_50 b2 = sin(a2);
BOOST_CHECK((boost::math::isfinite)(b2));
BOOST_CHECK(lower(b2) <= b);
BOOST_CHECK(upper(b2) >= b);
b = cos(a);
b2 = cos(a2);
BOOST_CHECK((boost::math::isfinite)(b2));
BOOST_CHECK(lower(b2) <= b);
BOOST_CHECK(upper(b2) >= b);
b = tan(a);
b2 = tan(a2);
BOOST_CHECK((boost::math::isfinite)(b2));
BOOST_CHECK(lower(b2) <= b);
BOOST_CHECK(upper(b2) >= b);
}
for (unsigned i = 0; i < 5000; ++i)
{
mpfr_float_50 val;
val = dist2(gen);
mpfr_float_100 a = val;
mpfr_float_100 b = asin(a);
mpfi_float_50 a2 = val;
mpfi_float_50 b2 = asin(a2);
BOOST_CHECK((boost::math::isfinite)(b2));
BOOST_CHECK(lower(b2) <= b);
BOOST_CHECK(upper(b2) >= b);
b = acos(a);
b2 = acos(a2);
BOOST_CHECK((boost::math::isfinite)(b2));
BOOST_CHECK(lower(b2) <= b);
BOOST_CHECK(upper(b2) >= b);
b = atan(a);
b2 = atan(a2);
BOOST_CHECK((boost::math::isfinite)(b2));
BOOST_CHECK(lower(b2) <= b);
BOOST_CHECK(upper(b2) >= b);
}
}
void test_hyp()
{
std::cout << "Testing hyperbolic trig functions\n";
mt19937 gen;
<API key><mpfr_float_50> dist1(-10, 10);
<API key><mpfr_float_50> dist2(-1, 1);
for (unsigned i = 0; i < 5000; ++i)
{
mpfr_float_50 val;
val = dist1(gen);
mpfr_float_100 a = val;
mpfr_float_100 b = sinh(a);
mpfi_float_50 a2 = val;
mpfi_float_50 b2 = sinh(a2);
BOOST_CHECK((boost::math::isfinite)(b2));
BOOST_CHECK(lower(b2) <= b);
BOOST_CHECK(upper(b2) >= b);
b = cosh(a);
b2 = cosh(a2);
BOOST_CHECK((boost::math::isfinite)(b2));
BOOST_CHECK(lower(b2) <= b);
BOOST_CHECK(upper(b2) >= b);
b = tanh(a);
b2 = tanh(a2);
BOOST_CHECK((boost::math::isfinite)(b2));
BOOST_CHECK(lower(b2) <= b);
BOOST_CHECK(upper(b2) >= b);
}
}
void test_intervals()
{
mpfi_float_50 a(1, 2);
mpfi_float_50 b(1.5, 2.5);
BOOST_CHECK_EQUAL(lower(a), 1);
BOOST_CHECK_EQUAL(upper(a), 2);
BOOST_CHECK_EQUAL(median(a), 1.5);
BOOST_CHECK_EQUAL(width(a), 1);
mpfi_float_50 r = intersect(a, b);
BOOST_CHECK_EQUAL(lower(r), 1.5);
BOOST_CHECK_EQUAL(upper(r), 2);
r = hull(a, b);
BOOST_CHECK_EQUAL(lower(r), 1);
BOOST_CHECK_EQUAL(upper(r), 2.5);
BOOST_CHECK(overlap(a, b));
BOOST_CHECK(in(mpfr_float_50(1.5), a));
BOOST_CHECK(in(mpfr_float_50(1), a));
BOOST_CHECK(in(mpfr_float_50(2), a));
BOOST_CHECK(!zero_in(a));
b = mpfi_float_50(1.5, 1.75);
BOOST_CHECK(subset(b, a));
BOOST_CHECK(proper_subset(b, a));
BOOST_CHECK(!empty(a));
BOOST_CHECK(!singleton(a));
b = mpfi_float_50(5, 6);
r = intersect(a, b);
BOOST_CHECK(empty(r));
}
#ifdef TEST_SPECIAL
#include "math/table_type.hpp"
#include <boost/math/special_functions.hpp>
#define T mpfi_float_50
typedef number<mpfi_float_backend<25> > mpfi_float_25;
void test_log1p_expm1()
{
#include "../../math/test/log1p_expm1_data.ipp"
std::cout << std::setprecision(std::numeric_limits<mpfi_float_25>::max_digits10);
std::cout << "Testing log1p and expm1\n";
for (unsigned i = 0; i < log1p_expm1_data.size(); ++i)
{
mpfi_float_25 in(log1p_expm1_data[i][0]);
mpfi_float_25 out = boost::math::log1p(in);
mpfi_float_25 expected(log1p_expm1_data[i][1]);
if (!subset(expected, out))
{
std::cout << in << std::endl;
std::cout << out << std::endl;
std::cout << expected << std::endl;
BOOST_CHECK(lower(out) <= lower(expected));
BOOST_CHECK(upper(out) >= upper(expected));
}
out = boost::math::expm1(in);
expected = mpfi_float_25(log1p_expm1_data[i][2]);
if (!subset(expected, out))
{
std::cout << in << std::endl;
std::cout << out << std::endl;
std::cout << expected << std::endl;
BOOST_CHECK(lower(out) <= lower(expected));
BOOST_CHECK(upper(out) >= upper(expected));
}
}
}
void test_bessel()
{
#include "../../math/test/bessel_i_int_data.ipp"
#include "../../math/test/bessel_i_data.ipp"
std::cout << std::setprecision(std::numeric_limits<mpfi_float_25>::max_digits10);
std::cout << "Testing Bessel Functions\n";
for (unsigned i = 0; i < bessel_i_int_data.size(); ++i)
{
int v = boost::lexical_cast<int>(static_cast<const char*>(bessel_i_int_data[i][0]));
mpfi_float_25 in(bessel_i_int_data[i][1]);
mpfi_float_25 out = boost::math::cyl_bessel_i(v, in);
mpfi_float_25 expected(bessel_i_int_data[i][2]);
if (!subset(expected, out))
{
std::cout << in << std::endl;
std::cout << out << std::endl;
std::cout << expected << std::endl;
BOOST_CHECK(lower(out) <= lower(expected));
BOOST_CHECK(upper(out) >= upper(expected));
}
}
}
#endif
int main()
{
#ifdef TEST_SPECIAL
test_log1p_expm1();
test_bessel();
#endif
test_intervals();
test_exp();
test_pow();
test_trig();
test_hyp();
return boost::report_errors();
} |
'use strict';
/**
* Creates a new `Juicy` object.
*
* @class Phaser.Plugin.Juicy
* @constructor
*
* @param {Phaser.Game} game Current game instance.
*/
Phaser.Plugin.Juicy = function (game) {
Phaser.Plugin.call(this, game);
/**
* @property {Phaser.Rectangle} _boundsCache - A reference to the current world bounds.
* @private
*/
this._boundsCache = Phaser.Utils.extend(false, {}, this.game.world.bounds);
/**
* @property {number} _shakeWorldMax - The maximum world shake radius
* @private
*/
this._shakeWorldMax = 20;
/**
* @property {number} _shakeWorldTime - The maximum world shake time
* @private
*/
this._shakeWorldTime = 0;
/**
* @property {number} _trailCounter - A count of how many trails we're tracking
* @private
*/
this._trailCounter = 0;
/**
* @property {object} _overScales - An object containing overscaling configurations
* @private
*/
this._overScales = {};
/**
* @property {number} _overScalesCounter - A count of how many overScales we're tracking
* @private
*/
this._overScalesCounter = 0;
};
Phaser.Plugin.Juicy.prototype = Object.create(Phaser.Plugin.prototype);
Phaser.Plugin.Juicy.prototype.constructor = Phaser.Plugin.Juicy;
/**
* Creates a new `Juicy.ScreenFlash` object.
*
* @class Phaser.Plugin.Juicy.ScreenFlash
* @constructor
*
* @param {Phaser.Game} game - Current game instance.
* @param {string} color='white' - The color to flash the screen.
* @memberof Phaser.Plugin.Juicy
*/
Phaser.Plugin.Juicy.ScreenFlash = function(game, color) {
color = color || 'white';
var bmd = game.add.bitmapData(game.width, game.height);
bmd.ctx.fillStyle = color;
bmd.ctx.fillRect(0,0, game.width, game.height);
Phaser.Sprite.call(this, game, 0,0, bmd);
this.alpha = 0;
};
Phaser.Plugin.Juicy.ScreenFlash.prototype = Object.create(Phaser.Sprite.prototype);
Phaser.Plugin.Juicy.ScreenFlash.prototype.constructor = Phaser.Plugin.Juicy.ScreenFlash;
/*
* Flashes the screen
*
* @param {number} [maxAlpha=1] - The maximum alpha to flash the screen to
* @param {number} [duration=100] - The duration of the flash in milliseconds
* @method Phaser.Plugin.Juicy.ScreenFlash.prototype.flash
* @memberof Phaser.Plugin.Juicy.ScreenFlash
*/
Phaser.Plugin.Juicy.ScreenFlash.prototype.flash = function(maxAlpha, duration) {
maxAlpha = maxAlpha || 1;
duration = duration || 100;
var flashTween = this.game.add.tween(this).to({alpha: maxAlpha}, 100, Phaser.Easing.Bounce.InOut, true,0, 0, true);
flashTween.onComplete.add(function() {
this.alpha = 0;
}, this);
};
/**
* Creates a new `Juicy.Trail` object.
*
* @class Phaser.Plugin.Juicy.Trail
* @constructor
*
* @param {Phaser.Game} game - Current game instance.
* @param {number} [trailLength=100] - The length of the trail
* @param {number} [color=0xFFFFFF] - The color of the trail
* @memberof Phaser.Plugin.Juicy
*/
Phaser.Plugin.Juicy.Trail = function(game, trailLength, color) {
Phaser.Graphics.call(this, game, 0,0);
/**
* @property {Phaser.Sprite} target - The target sprite whose movement we want to create the trail from
*/
this.target = null;
/**
* @property {number} trailLength - The number of segments to use to create the trail
*/
this.trailLength = trailLength || 100;
/**
* @property {number} trailWidth - The width of the trail
*/
this.trailWidth = 15.0;
/**
* @property {boolean} trailScale - Whether or not to taper the trail towards the end
*/
this.trailScaling = false;
/**
* @property {Phaser.Sprite} trailColor - The color of the trail
*/
this.trailColor = color || 0xFFFFFF;
/**
* @property {Array<Phaser.Point>} _segments - A historical collection of the previous position of the target
* @private
*/
this._segments = [];
/**
* @property {Array<number>} _verts - A collection of vertices created from _segments
* @private
*/
this._verts = [];
/**
* @property {Array<Phaser.Point>} _segments - A collection of indices created from _verts
* @private
*/
this._indices = [];
};
Phaser.Plugin.Juicy.Trail.prototype = Object.create(Phaser.Graphics.prototype);
Phaser.Plugin.Juicy.Trail.prototype.constructor = Phaser.Plugin.Juicy.Trail;
/**
* Updates the Trail if a target is set
*
* @method Phaser.Plugin.Juicy.Trail#update
* @memberof Phaser.Plugin.Juicy.Trail
*/
Phaser.Plugin.Juicy.Trail.prototype.update = function() {
if(this.target) {
this.x = this.target.x;
this.y = this.target.y;
this.addSegment(this.target.x, this.target.y);
this.redrawSegments(this.target.x, this.target.y);
}
};
/**
* Adds a segment to the segments list and culls the list if it is too long
*
* @param {number} [x] - The x position of the point
* @param {number} [y] - The y position of the point
*
* @method Phaser.Plugin.Juicy.Trail#addSegment
* @memberof Phaser.Plugin.Juicy.Trail
*/
Phaser.Plugin.Juicy.Trail.prototype.addSegment = function(x, y) {
var segment;
while(this._segments.length > this.trailLength) {
segment = this._segments.shift();
}
if(!segment) {
segment = new Phaser.Point();
}
segment.x = x;
segment.y = y;
this._segments.push(segment);
};
/**
* Creates and draws the triangle trail from segments
*
* @param {number} [offsetX] - The x position of the object
* @param {number} [offsetY] - The y position of the object
*
* @method Phaser.Plugin.Juicy.Trail#redrawSegment
* @memberof Phaser.Plugin.Juicy.Trail
*/
Phaser.Plugin.Juicy.Trail.prototype.redrawSegments = function(offsetX, offsetY) {
this.clear();
var s1, // current segment
s2, // previous segment
vertIndex = 0, // keeps track of which vertex index we're at
offset, // temporary storage for amount to extend line outwards, bigger = wider
ang, //temporary storage of the inter-segment angles
sin = 0, // as above
cos = 0; // again as above
// first we make sure that the vertice list is the same length as we we want
// each segment (except the first) will create to vertices with two values each
if (this._verts.length !== (this._segments.length -1) * 4) {
// if it's not correct, we clear the entire list
this._verts = [];
}
// now we loop over all the segments, the list has the "youngest" segment at the end
var prevAng = 0;
for(var j = 0; j < this._segments.length; ++j) {
// store the active segment for convenience
s1 = this._segments[j];
// if there's a previous segment, time to do some math
if(s2) {
// we calculate the angle between the two segments
// the result will be in radians, so adding half of pi will "turn" the angle 90 degrees
// that means we can use the sin and cos values to "expand" the line outwards
ang = Math.atan2(s1.y - s2.y, s1.x - s2.x) + Math.PI / 2;
sin = Math.sin(ang);
cos = Math.cos(ang);
// now it's time to creat ethe two vertices that will represent this pair of segments
// using a loop here is probably a bit overkill since it's only two iterations
for(var i = 0; i < 2; ++i) {
// this makes the first segment stand out to the "left" of the line
// annd the second to the right, changing that magic number at the end will alther the line width
offset = ( -0.5 + i / 1) * this.trailWidth;
// if trail scale effect is enabled, we scale down the offset as we move down the list
if(this.trailScaling) {
offset *= j / this._segments.length;
}
// finally we put to values in the vert list
// using the segment coordinates as a base we add the "extended" point
// offsetX and offsetY are used her to move the entire trail
this._verts[vertIndex++] = s1.x + cos * offset - offsetX;
this._verts[vertIndex++] = s1.y + sin * offset - offsetY;
}
}
// finally store the current segment as the previous segment and go for another round
s2 = s1.copyTo({});
}
// we need at least four vertices to draw something
if(this._verts.length >= 8) {
// now, we have a triangle "strip", but flash can't draw that without
// instructions for which vertices to connect, so it's time to make those
// here, we loop over all the vertices and pair them together in triangles
// each group of four vertices forms two triangles
for(var k = 0; k < this._verts.length; k++) {
this._indices[k * 6 + 0] = k * 2 + 0;
this._indices[k * 6 + 1] = k * 2 + 1;
this._indices[k * 6 + 2] = k * 2 + 2;
this._indices[k * 6 + 3] = k * 2 + 1;
this._indices[k * 6 + 4] = k * 2 + 2;
this._indices[k * 6 + 5] = k * 2 + 3;
}
this.beginFill(this.trailColor);
this.drawTriangles(this._verts, this._indices);
this.endFill();
}
};
/**
* Add a Sprite reference to this Plugin.
* All this plugin does is move the Sprite across the screen slowly.
* @type {Phaser.Sprite}
*/
/**
* Begins the screen shake effect
*
* @param {number} [duration=20] - The duration of the screen shake
* @param {number} [strength=20] - The strength of the screen shake
*
* @method Phaser.Plugin.Juicy#redrawSegment
* @memberof Phaser.Plugin.Juicy
*/
Phaser.Plugin.Juicy.prototype.shake = function (duration, strength) {
this._shakeWorldTime = duration || 20;
this._shakeWorldMax = strength || 20;
this.game.world.setBounds(this._boundsCache.x - this._shakeWorldMax, this._boundsCache.y - this._shakeWorldMax, this._boundsCache.width + this._shakeWorldMax, this._boundsCache.height + this._shakeWorldMax);
};
/**
* Creates a 'Juicy.ScreenFlash' object
*
* @param {string} color - The color of the screen flash
*
* @type {Phaser.Plugin.Juicy.ScreenFlash}
*/
Phaser.Plugin.Juicy.prototype.createScreenFlash = function(color) {
return new Phaser.Plugin.Juicy.ScreenFlash(this.game, color);
};
/**
* Creates a 'Juicy.Trail' object
*
* @param {number} length - The length of the trail
* @param {number} color - The color of the trail
*
* @type {Phaser.Plugin.Juicy.Trail}
*/
Phaser.Plugin.Juicy.prototype.createTrail = function(length, color) {
return new Phaser.Plugin.Juicy.Trail(this.game, length, color);
};
/**
* Creates the over scale effect on the given object
*
* @param {Phaser.Sprite} object - The object to over scale
* @param {number} [scale=1.5] - The scale amount to overscale by
* @param {Phaser.Point} [initialScale=new Phaser.Point(1,1)] - The initial scale of the object
*
*/
Phaser.Plugin.Juicy.prototype.overScale = function(object, scale, initialScale) {
scale = scale || 1.5;
var id = this._overScalesCounter++;
initialScale = initialScale || new Phaser.Point(1,1);
var scaleObj = this._overScales[id];
if(!scaleObj) {
scaleObj = {
object: object,
cache: initialScale.copyTo({})
};
}
scaleObj.scale = scale;
this._overScales[id] = scaleObj;
};
/**
* Creates the jelly effect on the given object
*
* @param {Phaser.Sprite} object - The object to gelatinize
* @param {number} [strength=0.2] - The strength of the effect
* @param {number} [delay=0] - The delay of the snap-back tween. 50ms are automaticallly added to whatever the delay amount is.
* @param {Phaser.Point} [initialScale=new Phaser.Point(1,1)] - The initial scale of the object
*
*/
Phaser.Plugin.Juicy.prototype.jelly = function(object, strength, delay, initialScale) {
strength = strength || 0.2;
delay = delay || 0;
initialScale = initialScale || new Phaser.Point(1, 1);
this.game.add.tween(object.scale).to({x: initialScale.x + (initialScale.x * strength)}, 50, Phaser.Easing.Quadratic.InOut, true, delay)
.to({x: initialScale.x}, 600, Phaser.Easing.Elastic.Out, true);
this.game.add.tween(object.scale).to({y: initialScale.y + (initialScale.y * strength)}, 50, Phaser.Easing.Quadratic.InOut, true, delay + 50)
.to({y: initialScale.y}, 600, Phaser.Easing.Elastic.Out, true);
};
/**
* Creates the mouse stretch effect on the given object
*
* @param {Phaser.Sprite} object - The object to mouse stretch
* @param {number} [strength=0.5] - The strength of the effect
* @param {Phaser.Point} [initialScale=new Phaser.Point(1,1)] - The initial scale of the object
*
*/
Phaser.Plugin.Juicy.prototype.mouseStretch = function(object, strength, initialScale) {
strength = strength || 0.5;
initialScale = initialScale || new Phaser.Point(1,1);
object.scale.x = initialScale.x + (Math.abs(object.x - this.game.input.activePointer.x) / 100) * strength;
object.scale.y = initialScale.y + (initialScale.y * strength) - (object.scale.x * strength);
};
/**
* Runs the core update function and causes screen shake and overscaling effects to occur if they are queued to do so.
*
* @method Phaser.Plugin.Juicy#update
* @memberof Phaser.Plugin.Juicy
*/
Phaser.Plugin.Juicy.prototype.update = function () {
var scaleObj;
// Screen Shake
if(this._shakeWorldTime > 0) {
var magnitude = (this._shakeWorldTime / this._shakeWorldMax) * this._shakeWorldMax;
var x = this.game.rnd.integerInRange(-magnitude, magnitude);
var y = this.game.rnd.integerInRange(-magnitude, magnitude);
this.game.camera.x = x;
this.game.camera.y = y;
this._shakeWorldTime
if(this._shakeWorldTime <= 0) {
this.game.world.setBounds(this._boundsCache.x, this._boundsCache.x, this._boundsCache.width, this._boundsCache.height);
}
}
// over scales
for(var s in this._overScales) {
if(this._overScales.hasOwnProperty(s)) {
scaleObj = this._overScales[s];
if(scaleObj.scale > 0.01) {
scaleObj.object.scale.x = scaleObj.scale * scaleObj.cache.x;
scaleObj.object.scale.y = scaleObj.scale * scaleObj.cache.y;
scaleObj.scale -= this.game.time.elapsed * scaleObj.scale * 0.35;
} else {
scaleObj.object.scale.x = scaleObj.cache.x;
scaleObj.object.scale.y = scaleObj.cache.y;
delete this._overScales[s];
}
}
}
};
// for browserify compatibility
//if(module && module.exports) {
// module.exports = Phaser.Plugin.Juicy;
// Draw Triangles Polyfill for back compatibility
if(!Phaser.Graphics.prototype.drawTriangle) {
Phaser.Graphics.prototype.drawTriangle = function(points, cull) {
var triangle = new Phaser.Polygon(points);
if (cull) {
var cameraToFace = new Phaser.Point(this.game.camera.x - points[0].x, this.game.camera.y - points[0].y);
var ab = new Phaser.Point(points[1].x - points[0].x, points[1].y - points[0].y);
var cb = new Phaser.Point(points[1].x - points[2].x, points[1].y - points[2].y);
var faceNormal = cb.cross(ab);
if (cameraToFace.dot(faceNormal) > 0) {
this.drawPolygon(triangle);
}
} else {
this.drawPolygon(triangle);
}
return;
};
/*
* Draws {Phaser.Polygon} triangles
*
* @param {Array<Phaser.Point>|Array<number>} vertices - An array of Phaser.Points or numbers that make up the vertices of the triangles
* @param {Array<number>} {indices=null} - An array of numbers that describe what order to draw the vertices in
* @param {boolean} [cull=false] - Should we check if the triangle is back-facing
* @method Phaser.Graphics.prototype.drawTriangles
*/
Phaser.Graphics.prototype.drawTriangles = function(vertices, indices, cull) {
var point1 = new Phaser.Point(),
point2 = new Phaser.Point(),
point3 = new Phaser.Point(),
points = [],
i;
if (!indices) {
if(vertices[0] instanceof Phaser.Point) {
for(i = 0; i < vertices.length / 3; i++) {
this.drawTriangle([vertices[i * 3], vertices[i * 3 + 1], vertices[i * 3 + 2]], cull);
}
} else {
for (i = 0; i < vertices.length / 6; i++) {
point1.x = vertices[i * 6 + 0];
point1.y = vertices[i * 6 + 1];
point2.x = vertices[i * 6 + 2];
point2.y = vertices[i * 6 + 3];
point3.x = vertices[i * 6 + 4];
point3.y = vertices[i * 6 + 5];
this.drawTriangle([point1, point2, point3], cull);
}
}
} else {
if(vertices[0] instanceof Phaser.Point) {
for(i = 0; i < indices.length /3; i++) {
points.push(vertices[indices[i * 3 ]]);
points.push(vertices[indices[i * 3 + 1]]);
points.push(vertices[indices[i * 3 + 2]]);
if(points.length === 3) {
this.drawTriangle(points, cull);
points = [];
}
}
} else {
for (i = 0; i < indices.length; i++) {
point1.x = vertices[indices[i] * 2];
point1.y = vertices[indices[i] * 2 + 1];
points.push(point1.copyTo({}));
if (points.length === 3) {
this.drawTriangle(points, cull);
points = [];
}
}
}
}
};
} |
// CLUSTER VIEW
bv.views.cluster = {
name: "cluster",
description: "Projection View",
plots: {}
};
bv.views.cluster.create = function() {
var view = Object.create(bv.views.cluster);
view.resourcesRequested = [
bv.ui.request("runs", "runs.json"),
bv.ui.request("solvers", "solvers.json"),
bv.ui.request("instances", "instances.json"),
bv.ui.request("membership", "membership.json"),
bv.ui.request("projection", "projection.json")
];
view.resources = {};
view.selections = bv.list.create();
view.drag = null;
return view;
};
bv.views.cluster.load = function() {
var this_ = this;
$(this).bind("resources-loaded", function() { this_.initialize(); });
bv.load(this);
return this;
};
bv.views.cluster.initialize = function() {
var this_ = this;
var $this = $(this);
// instances
var instancesByName = {};
this.instances = this.resources.instances.map(function(name, i) {
var instance = {
name: name,
x: this_.resources.projection[i][0],
y: this_.resources.projection[i][1],
membership: this_.resources.membership[i],
dominant: 0,
bars: {}
};
for(var j = 0; j < instance.membership.length; j += 1) {
if(instance.membership[j] > instance.membership[instance.dominant]) {
instance.dominant = j;
}
}
instancesByName[name] = instance;
return instance;
});
this.resources.runs.forEach(function(runsOn) {
var instance = instancesByName[runsOn.instance];
instance.runs = runsOn.runs;
for(var i = 0; i < runsOn.runs.length; i += 1) {
if(runsOn.runs[i].answer !== null) {
instance.answer = runsOn.runs[i].answer;
break;
}
}
});
// miscellaneous data
this.nodes = {
configuration: $("#configuration-div").get(0)
};
// start things moving
this.prepareProjection();
bv.later(this, function() {
this.prepareSelections();
this.preparePlot();
bv.later(this, function() {
this.updateProjection();
this.updateSelections();
this.updatePlot();
});
});
bv.later(this, function() {
var $container = $(this.nodes.container);
this.nodes.projectionBorder =
d3.select(this.nodes.projection)
.append("svg:rect")
.attr("id", "<API key>")
.attr("x", 1)
.attr("y", 1)
.attr("height", $container.innerHeight() - 2)
.attr("width", $container.innerWidth() - 2)
.style("stroke", this.selection.colors.range()[0])
.node();
});
};
bv.views.cluster.prepareProjection = function() {
// prepare projection area
var markup = [
'<section id="<API key>">',
'<div id="bv-projection-title">Problem Instances (MDS Projection)</div>',
'</section>'
];
var $container = $(markup.join("\n")).appendTo("body");
this.nodes.container = $container.get(0);
this.nodes.projection = d3.select(this.nodes.container).append("svg:svg").node();
};
bv.views.cluster.updateProjection = function() {
// prepare scales
var $container = $(this.nodes.container);
var xScale =
d3.scale.linear()
.domain([
d3.min(this.instances, function(d) { return d.x; }),
d3.max(this.instances, function(d) { return d.x; })
])
.rangeRound([16, $container.innerWidth() - 16]);
var yScale =
d3.scale.linear()
.domain([
d3.min(this.instances, function(d) { return d.y; }),
d3.max(this.instances, function(d) { return d.y; })
])
.rangeRound([16, $container.innerHeight() - 16]);
// add instance nodes
var denter =
d3.select(this.nodes.projection)
.selectAll(".instance-point-g")
.data(this.instances)
.enter();
var dpoints = denter.append("svg:g");
dpoints
.filter(function(d) { return d.answer === false; })
.append("svg:rect")
.attr("class", "instance-point")
.attr("x", function(d) { return xScale(d.x) - 7.5; })
.attr("y", function(d) { return yScale(d.y) - 7.5; })
.attr("height", 17)
.attr("width", 17)
.attr("transform", function(d) {
return "rotate(45 %s,%s)".format(xScale(d.x), yScale(d.y));
})
.each(function(d) { d.node = this; })
dpoints
.filter(function(d) { return d.answer === true; })
.append("svg:circle")
.attr("class", "instance-point")
.attr("cx", function(d) { return xScale(d.x) + 0.5; })
.attr("cy", function(d) { return yScale(d.y) + 0.5; })
.attr("r", 10)
.each(function(d) { d.node = this; })
dpoints
.filter(function(d) { return d.answer === undefined; })
.append("svg:rect")
.attr("class", "instance-point")
.attr("x", function(d) { return xScale(d.x) - 9.5; })
.attr("y", function(d) { return yScale(d.y) - 9.5; })
.attr("height", 20)
.attr("width", 20)
.each(function(d) { d.node = this; });
dpoints
.selectAll(".instance-point")
.each(function(d) {
var domain = xScale.domain();
d.cx = xScale(d.x);
d.cy = yScale(d.y);
d.rightSide = d.x > domain[0] + (domain[1] - domain[0]) / 2;
})
.on("mouseover", function(d) {
d3.select(this).classed("highlighted", true);
d3.select(d.label).attr("visibility", "visible");
})
.on("mouseout", function(d) {
d3.select(this).classed("highlighted", false);
d3.select(d.label).attr("visibility", "hidden");
});
dpoints
.append("svg:text")
.attr("class", "bv-instance-number")
.attr("x", function(d) { return xScale(d.x); })
.attr("y", function(d) { return yScale(d.y); })
.attr("dy", "0.5ex")
.text(function(d) { return d.dominant; });
// add instance node labels
var dlabels =
denter
.append("svg:g")
.classed("instance-label", true)
.attr("class", function() {
// XXX force Safari to pay attention
return d3.select(this).attr("class");
})
.attr("visibility", "hidden")
.each(function(d) { d.label = this; });
dlabels
.append("svg:text")
.attr("x", function(d) { return xScale(d.x) + (d.rightSide ? -12.5 : 12.5); })
.attr("y", function(d) { return yScale(d.y) + 0.5; })
.style("text-anchor", function(d) { return d.rightSide ? "end" : "start"; })
.text(function(d) { return d.name; })
.each(function(d) { return d.labelText = this; });
bv.later(this, function() {
dlabels
.insert("svg:rect", "text")
.attr("x", function(d) { return d.labelText.getBBox().x - 2; })
.attr("y", function(d) { return d.labelText.getBBox().y - 2; })
.attr("height", function(d) { return d.labelText.getBBox().height + 4; })
.attr("width", function(d) { return d.labelText.getBBox().width + 4; });
});
};
bv.views.cluster.prepareSelections = function() {
// prepare the selection list
var this_ = this;
this.nodes.selectionsDiv =
$("<p>Selections:</p>")
.appendTo(this.nodes.configuration)
.append('<ul id="selections-list"></ul>')
.get(0);
// the current selection, if any
var selection = null;
var count = 0;
var finished = function() {
if(selection !== null) {
selection.ready = true;
selection = null;
$(this_.selections).trigger("changed");
}
else if(this_.drag !== null) {
this_.drag = null;
$(this_.selections).trigger("changed");
}
};
$(this.nodes.container)
.mousedown(function(event) {
if(event.which === 1) {
if(this_.drag === null) {
if(selection === null) {
selection = this_.selection.create(this_, {x: event.layerX, y: event.layerY});
}
else {
finished();
}
}
}
})
.mousemove(function(event) {
if(selection !== null) {
selection.update({x: event.layerX, y: event.layerY});
if(selection.number === undefined && selection.area() >= 25) {
selection.reify(count += 1);
this_.selections.add(selection);
}
}
else if(this_.drag !== null) {
var q = {
x: event.layerX - this_.drag.startX,
y: event.layerY - this_.drag.startY
};
this_.drag.startX = event.layerX;
this_.drag.startY = event.layerY;
this_.drag.selection.translate(q);
}
})
.mouseup(function(event) {
if(event.which === 1) {
finished();
}
});
// add the initial "everything" selection
var everything = this.selection.create(this).reify(0, "All Instances");
everything.ready = true;
$(everything).bind("highlighted", function(event, state) {
d3.select(this_.nodes.projectionBorder).classed("highlighted", state);
});
this.selections.add(everything);
// update on changes
$(this.selections).bind("changed", function() { this_.updateSelections(); });
};
bv.views.cluster.updateSelections = function() {
var this_ = this;
// update selection list
var ditems =
d3.select("#selections-list")
.selectAll("li")
.data(this.selections.get(), function(d) { return d.number; });
var added =
ditems
.enter()
.append("li")
.each(function(d) {
var $d = $(d);
$(this)
.mouseenter(function() { $d.trigger("highlighted", [true]); })
.mouseleave(function() { $d.trigger("highlighted", [false]); });
});
ditems.exit().remove();
added
.append("span")
.attr("title", "Toggle")
.attr("class", "ui-icon ui-icon-pause")
.on("click", function(d) {
// switch the icon and text
$(this)
.toggleClass("ui-icon-pause")
.toggleClass("ui-icon-play")
.parent()
.toggleClass("hidden");
// hide the region
d.toggleVisible();
$(this_.selections).trigger("changed");
});
added
.append("span")
.filter(function(d) { return d.number > 0; })
.attr("title", "Remove")
.attr("class", "ui-icon ui-icon-close")
.on("click", function(d) { this_.selections.remove(d); });
added
.append("span")
.classed("bv-selection-name", true)
.style("color", function(d) { return d.color; })
.html(function(d) { return d.titleMarkup; })
.on("click", function(d) {
var instances = d.instances().map(function(v) { return v.name; });
var state = bv.ui.state.withView(bv.views.table, {instances: instances});
bv.ui.change(state);
});
// update selection rectangles
var visible = this.selections.get().filter(function(d) { return d.visible && d.p2 !== undefined; });
var dboxes =
d3.select(this.nodes.projection)
.selectAll(".selection-region")
.data(visible, function(d) { return d.number; });
dboxes
.enter()
.append("svg:rect")
.attr("class", "selection-region")
.attr("x", function(d) { return d.p1.x; })
.attr("y", function(d) { return d.p1.y; })
.attr("height", function(d) { return d.p2.y - d.p1.y; })
.attr("width", function(d) { return d.p2.x - d.p1.x; })
.style("fill", function(d) { return d.color; })
.style("stroke", function(d) { return d.color; })
.on("mouseover", function(d) {
if(d.ready && this_.drag === null) {
$(d).trigger("highlighted", [true]);
}
})
.on("mouseout", function(d) {
if(this_.drag === null) {
$(d).trigger("highlighted", [false]);
}
})
.on("mousedown", function(d) {
this_.drag = {
selection: d,
startX: d3.event.layerX,
startY: d3.event.layerY
};
})
.each(function(d) {
var dthis = d3.select(this);
this.highlighted = function(e, state) {
dthis.classed("highlighted", state);
};
this.moved = function() {
dthis
.attr("x", d.p1.x)
.attr("y", d.p1.y)
.attr("height", d.p2.y - d.p1.y)
.attr("width", d.p2.x - d.p1.x);
};
$(d)
.bind("highlighted", this.highlighted)
.bind("moved", this.moved);
});
dboxes
.exit()
.each(function(d) {
$(d)
.unbind("highlighted", this.highlighted)
.unbind("moved", this.moved);
})
.remove();
};
bv.views.cluster.preparePlot = function() {
// mise en place
var this_ = this;
// set up DOM
this.nodes.pickSelect =
$('<p>Chart:<select></select></p>')
.appendTo(this.nodes.configuration)
.find("select")
.attr("id", "<API key>")
.get(0);
this.nodes.plotControlsDiv =
$("<div></div>")
.appendTo(this.nodes.configuration)
.get(0);
this.nodes.chartDiv =
d3.select("body")
.append("div")
.attr("id", "bv-chart-container")
.node();
this.nodes.chartSVG =
d3.select(this.nodes.chartDiv)
.append("svg:svg")
.node();
// plot selection
d3.select(this.nodes.pickSelect)
.selectAll("option")
.data(Object.keys(this.plots))
.enter()
.append("option")
.sort(function(c, d) { return d3.ascending(this_.plots[c].order, this_.plots[d].order); })
.attr("value", function(d) { return d; })
.text(function(d) { return this_.plots[d].title; });
$(this.nodes.pickSelect)
.selectmenu({style: "dropdown"})
.change(function(event) { this_.updatePlot(); });
};
bv.views.cluster.updatePlot = function() {
if(this.plot !== undefined) {
this.plot.destroy();
}
var plotNodes = {
controlsDiv: this.nodes.plotControlsDiv,
chartDiv: this.nodes.chartDiv,
chartSVG: this.nodes.chartSVG
};
var plotType = this.plots[$(this.nodes.pickSelect).val()];
this.plot = plotType.create(this, plotNodes);
};
bv.views.cluster.destroy = function() {
this.plot.destroy();
$(this.nodes.configuration).empty();
$(this.nodes.container).remove();
$(this.nodes.chartDiv).remove();
};
{% include "borgexplorer/views/cluster/selection.js" %}
{% include "borgexplorer/views/cluster/cost_plot.js" %}
{% include "borgexplorer/views/cluster/success_plot.js" %} |
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Turno_model extends Model {
protected $table = 'turno';
protected $fillable = ['nome_turno'];
public function horarios() {
return $this->belongsToMany(Horario_model::class, 'turno_horario',
'turno_id','horario_id')->orderBy('horario.inicio', 'asc');
}
public function getNomeAttribute(){ return $this->attributes['nome_turno']; }
public function setNomeAttribute($nome){ $this->attributes['nome_turno'] = $nome; }
/**
* Retorna todos as turmas linkadas com o turno ordenadas pelo turno;
* @author Lucas Leonel
* @since 2017/08/19
*/
public function turmas() {
return $this->hasMany(Turma::class, 'turno_id')->orderBy('turno_id', 'asc');
}
public function qtd_horarios(){
return $this->horarios()->count();
}
} |
require 'net/ftp'
require 'ptools'
module Middleman
module Deploy
module Methods
class Ftp < Base
attr_reader :host, :port, :pass, :path, :user
def initialize(server_instance, options = {})
super(server_instance, options)
@host = self.options.host
@user = self.options.user
@pass = self.options.password
@path = self.options.path
@port = self.options.port
end
def process
puts "## Deploying via ftp to #{user}@#{host}:#{path}"
ftp = open_connection
Dir.chdir(build_dir) do
filtered_files.each do |filename|
if File.directory?(filename)
upload_directory(ftp, filename)
else
upload_binary(ftp, filename)
end
end
end
ftp.close
end
protected
def filtered_files
files = Dir.glob('**/*', File::FNM_DOTMATCH)
files.reject { |filename| filename =~ Regexp.new('\.$') }
end
def handle_exception(exception, ftp, filename)
reply = exception.message
err_code = reply[0, 3].to_i
if err_code == 550
if File.binary?(filename)
ftp.putbinaryfile(filename, filename)
else
ftp.puttextfile(filename, filename)
end
end
end
def open_connection
ftp = Net::FTP.new(host)
ftp.login(user, pass)
ftp.chdir(path)
ftp.passive = true
ftp
end
def upload_binary(ftp, filename)
begin
ftp.putbinaryfile(filename, filename)
rescue Exception => exception
handle_exception(exception, ftp, filename)
end
puts "Copied #{filename}"
end
def upload_directory(ftp, filename)
ftp.mkdir(filename)
puts "Created directory #{filename}"
rescue
end
end
end
end
end |
<div class="d-flex <API key> flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
<h1 class="h2">Gerenciador de Tags</h1>
<!--div class="btn-toolbar mb-2 mb-md-0">
<button class="btn btn-sm <API key>">
<i class="fa fa-plus-circle" aria-hidden="true"></i>
Cadastrar Nova
</button>
</div
</div>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<table class="table table-hover">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Tag</th>
<th scope="col">Ações</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>tag1</td>
<td>
<a class="" href="
<i class="fa fa-pencil-square-o" aria-hidden="true"></i>
Editar
</a>
<!-- spacer -->
<span style="display:inline-block; width: 20px;"></span>
<a class="" href="
<i class="fa fa-times-circle-o" aria-hidden="true"></i>
Excluir
</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div> |
# Specify gemfile Location and general variables
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
# Perform requiring gem that we need
# basic
require 'rubygems'
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
require 'pathname'
# database
require 'pg'
require 'active_record'
require 'logger'
# sinatra
require 'sinatra'
require "sinatra/reloader" if development?
# embedded ruby
require 'erb'
require 'uri'
require 'byebug'
# System Setup
# Setup app root folder and name
APP_ROOT = Pathname.new(File.expand_path('../../../', __FILE__))
APP_NAME = APP_ROOT.basename.to_s
# Setup sessions, logging and dump_errors
use Rack::Session::Cookie, expire_after: ENV['SESSION_EXPIRE'] || 2592000, # seconds
secret: ENV['SESSION_SECRET'] || 'this is a secret shhhhh'
set :logging, true
set :dump_errors, false
set :app_file, __FILE__
enable :sessions
# Setup Models (M) and its database
require APP_ROOT.join('config', 'database')
# Setup views (V)
set :views, File.join(APP_ROOT, "app", "views")
Dir[APP_ROOT.join('app', 'controllers', '*.rb')].each { |file| require file } |
export default () => (
<div className="card">
<div className="card__item soft">
<div className="soft-half-top one-fifth push-bottom <API key>" />
<div className="soft-half-top four-fifths push-half-bottom <API key>" />
<div className="soft-half-top one-half push-bottom <API key>" />
<div className="soft-half-top one-quarter <API key>" />
</div>
</div>
); |
using System;
using System.Collections.Generic;
using System.Text;
namespace SharpLua.AST
{
[Serializable()]
public partial class ElseifBlock
{
public Expr Condition;
public Chunk ThenBlock;
}
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/><!-- using block title in layout.dt--><!-- using block ddox.defs in ddox.layout.dt--><!-- using block ddox.title in ddox.layout.dt-->
<title>Function Sfxr.opAssign</title>
<link rel="stylesheet" type="text/css" href="../../../styles/ddox.css"/>
<link rel="stylesheet" href="../../../prettify/prettify.css" type="text/css"/>
<script type="text/javascript" src="../../../scripts/jquery.js"></script>
<script type="text/javascript" src="../../../prettify/prettify.js"></script>
<script type="text/javascript" src="../../../scripts/ddox.js"></script>
</head>
<body onload="prettyPrint(); setupDdox();">
<nav id="main-nav"><!-- using block navigation in layout.dt-->
<ul class="tree-view">
<li class=" tree-view">
<a href="#" class="package">dash</a>
<ul class="tree-view">
<li class="collapsed tree-view">
<a href="#" class="package">components</a>
<ul class="tree-view">
<li>
<a href="../../../dash/components/animation.html" class=" module">animation</a>
</li>
<li>
<a href="../../../dash/components/assets.html" class=" module">assets</a>
</li>
<li>
<a href="../../../dash/components/camera.html" class=" module">camera</a>
</li>
<li>
<a href="../../../dash/components/component.html" class=" module">component</a>
</li>
<li>
<a href="../../../dash/components/lights.html" class=" module">lights</a>
</li>
<li>
<a href="../../../dash/components/material.html" class=" module">material</a>
</li>
<li>
<a href="../../../dash/components/mesh.html" class=" module">mesh</a>
</li>
<li>
<a href="../../../dash/components/userinterface.html" class=" module">userinterface</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">core</a>
<ul class="tree-view">
<li>
<a href="../../../dash/core/dgame.html" class=" module">dgame</a>
</li>
<li>
<a href="../../../dash/core/gameobject.html" class=" module">gameobject</a>
</li>
<li>
<a href="../../../dash/core/prefabs.html" class=" module">prefabs</a>
</li>
<li>
<a href="../../../dash/core/properties.html" class=" module">properties</a>
</li>
<li>
<a href="../../../dash/core/scene.html" class=" module">scene</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">editor</a>
<ul class="tree-view">
<li>
<a href="../../../dash/editor/editor.html" class=" module">editor</a>
</li>
<li>
<a href="../../../dash/editor/websockets.html" class=" module">websockets</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">graphics</a>
<ul class="tree-view">
<li class="collapsed tree-view">
<a href="#" class="package">adapters</a>
<ul class="tree-view">
<li>
<a href="../../../dash/graphics/adapters/adapter.html" class=" module">adapter</a>
</li>
<li>
<a href="../../../dash/graphics/adapters/gl.html" class=" module">gl</a>
</li>
<li>
<a href="../../../dash/graphics/adapters/linux.html" class=" module">linux</a>
</li>
<li>
<a href="../../../dash/graphics/adapters/win32gl.html" class=" module">win32gl</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">shaders</a>
<ul class="tree-view">
<li class="collapsed tree-view">
<a href="#" class="package">glsl</a>
<ul class="tree-view">
<li>
<a href="../../../dash/graphics/shaders/glsl/ambientlight.html" class=" module">ambientlight</a>
</li>
<li>
<a href="../../../dash/graphics/shaders/glsl/animatedgeometry.html" class=" module">animatedgeometry</a>
</li>
<li>
<a href="../../../dash/graphics/shaders/glsl/directionallight.html" class=" module">directionallight</a>
</li>
<li>
<a href="../../../dash/graphics/shaders/glsl/geometry.html" class=" module">geometry</a>
</li>
<li>
<a href="../../../dash/graphics/shaders/glsl/pointlight.html" class=" module">pointlight</a>
</li>
<li>
<a href="../../../dash/graphics/shaders/glsl/shadowmap.html" class=" module">shadowmap</a>
</li>
<li>
<a href="../../../dash/graphics/shaders/glsl/userinterface.html" class=" module">userinterface</a>
</li>
</ul>
</li>
<li>
<a href="../../../dash/graphics/shaders/glsl.html" class=" module">glsl</a>
</li>
<li>
<a href="../../../dash/graphics/shaders/shaders.html" class=" module">shaders</a>
</li>
</ul>
</li>
<li>
<a href="../../../dash/graphics/adapters.html" class=" module">adapters</a>
</li>
<li>
<a href="../../../dash/graphics/graphics.html" class=" module">graphics</a>
</li>
<li>
<a href="../../../dash/graphics/shaders.html" class=" module">shaders</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">net</a>
<ul class="tree-view">
<li>
<a href="../../../dash/net/connection.html" class=" module">connection</a>
</li>
<li>
<a href="../../../dash/net/connectionmanager.html" class=" module">connectionmanager</a>
</li>
<li>
<a href="../../../dash/net/packets.html" class=" module">packets</a>
</li>
<li>
<a href="../../../dash/net/webconnection.html" class=" module">webconnection</a>
</li>
</ul>
</li>
<li class=" tree-view">
<a href="#" class="package">utility</a>
<ul class="tree-view">
<li>
<a href="../../../dash/utility/awesomium.html" class=" module">awesomium</a>
</li>
<li>
<a href="../../../dash/utility/concurrency.html" class=" module">concurrency</a>
</li>
<li>
<a href="../../../dash/utility/config.html" class=" module">config</a>
</li>
<li>
<a href="../../../dash/utility/input.html" class=" module">input</a>
</li>
<li>
<a href="../../../dash/utility/output.html" class=" module">output</a>
</li>
<li>
<a href="../../../dash/utility/resources.html" class=" module">resources</a>
</li>
<li>
<a href="../../../dash/utility/soloud.html" class="selected module">soloud</a>
</li>
<li>
<a href="../../../dash/utility/string.html" class=" module">string</a>
</li>
<li>
<a href="../../../dash/utility/tasks.html" class=" module">tasks</a>
</li>
<li>
<a href="../../../dash/utility/time.html" class=" module">time</a>
</li>
</ul>
</li>
<li>
<a href="../../../dash/components.html" class=" module">components</a>
</li>
<li>
<a href="../../../dash/core.html" class=" module">core</a>
</li>
<li>
<a href="../../../dash/editor.html" class=" module">editor</a>
</li>
<li>
<a href="../../../dash/graphics.html" class=" module">graphics</a>
</li>
<li>
<a href="../../../dash/net.html" class=" module">net</a>
</li>
<li>
<a href="../../../dash/utility.html" class=" module">utility</a>
</li>
</ul>
</li>
<li>
<a href="../../../dash.html" class=" module">dash</a>
</li>
</ul>
<noscript>
<p style="color: red">The search functionality needs JavaScript enabled</p>
</noscript>
<div id="symbolSearchPane" style="display: none">
<p>
<input id="symbolSearch" type="text" placeholder="Search for symbols" onchange="performSymbolSearch(24);" onkeypress="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();"/>
</p>
<ul id="symbolSearchResults" style="display: none"></ul>
<script type="application/javascript" src="../../../symbols.js"></script>
<script type="application/javascript">
//<![CDATA[
var symbolSearchRootDir = "../../../"; $('#symbolSearchPane').show();
</script>
</div>
<script type="text/javascript" src="../../../scripts/mousetrap.js"></script>
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
Mousetrap.bind('s', function(e) {
$("#symbolSearch").focus();
return false;
});
});
</script>
</nav>
<div id="main-contents">
<h1>Function Sfxr.opAssign</h1><!-- using block body in layout.dt--><!-- Default block ddox.description in ddox.layout.dt--><!-- Default block ddox.sections in ddox.layout.dt--><!-- using block ddox.members in ddox.layout.dt-->
<section>
<p></p>
<section>
<h3>Prototype</h3>
<pre class="code prettyprint lang-d prototype">
{null} opAssign();</pre>
</section>
</section>
<section>
<h2>Authors</h2><!-- using block ddox.authors in ddox.layout.dt-->
</section>
<section>
<h2>Copyright</h2>
</section>
<section>
<h2>License</h2>
</section>
</div>
</body>
</html> |
<?php
$aConfig = array(
/**
* Main Section.
*/
'type' => <API key>,
'name' => 'bx_snipcart',
'title' => 'Snipcart',
'note' => 'Snipcart shopping module.',
'version' => '9.0.6',
'vendor' => 'BoonEx',
'help_url' => 'http://feed.una.io/?section={module_name}',
'compatible_with' => array(
'9.0.0-RC10'
),
/**
* 'home_dir' and 'home_uri' - should be unique. Don't use spaces in 'home_uri' and the other special chars.
*/
'home_dir' => 'boonex/snipcart/',
'home_uri' => 'snipcart',
'db_prefix' => 'bx_snipcart_',
'class_prefix' => 'BxSnipcart',
/**
* Category for language keys.
*/
'language_category' => 'Snipcart',
/**
* List of page triggers.
*/
'page_triggers' => array (
'<API key>',
),
/**
* Menu triggers.
*/
'menu_triggers' => array(
'<API key>',
'<API key>'
),
/**
* Storage objects to automatically delete files from upon module uninstallation.
* Note. Don't add storage objects used in transcoder objects.
*/
'storages' => array(
'bx_snipcart_files'
),
/**
* Transcoders.
*/
'transcoders' => array(
'bx_snipcart_preview',
'bx_snipcart_gallery',
'bx_snipcart_cover'
),
/**
* Extended Search Forms.
*/
'esearches' => array(
'bx_snipcart',
'bx_snipcart_cmts',
),
/**
* Installation/Uninstallation Section.
*/
'install' => array(
'execute_sql' => 1,
'update_languages' => 1,
'clear_db_cache' => 1,
),
'uninstall' => array (
'process_esearches' => 1,
'execute_sql' => 1,
'update_languages' => 1,
'update_relations' => 1,
'clear_db_cache' => 1,
),
'enable' => array(
'execute_sql' => 1,
'update_relations' => 1,
'clear_db_cache' => 1,
),
'enable_success' => array(
'<API key>' => 1,
'<API key>' => 1,
'process_esearches' => 1,
'<API key>' => 1,
'clear_db_cache' => 1,
),
'disable' => array (
'execute_sql' => 1,
'update_relations' => 1,
'<API key>' => 1,
'clear_db_cache' => 1,
),
'disable_failed' => array (
'<API key>' => 1,
'clear_db_cache' => 1,
),
/**
* Dependencies Section
*/
'dependencies' => array(),
/**
* Relations Section
*/
'relations' => array(
'bx_timeline',
'bx_notifications'
),
); |
module Sorcery
module Model
module Submodules
# This submodule helps you login users from external providers such as Twitter.
# This is the model part which handles finding the user using access tokens.
# For the controller options see Sorcery::Controller::External.
# Socery assumes (read: requires) you will create external users in the same table where
# you keep your regular users,
# but that you will have a separate table for keeping their external authentication data,
# and that that separate table has a few rows for each user, facebook and twitter
# for example (a one-to-many relationship).
# External users will have a null crypted_password field, since we do not hold their password.
# They will not be sent activation emails on creation.
module External
def self.included(base)
base.sorcery_config.class_eval do
attr_accessor :<API key>,
:<API key>,
:<API key>,
:<API key>
end
base.sorcery_config.instance_eval do
@defaults.merge!(:@<API key> => nil,
:@<API key> => :user_id,
:@<API key> => :provider,
:@<API key> => :uid)
reset!
end
base.send(:include, InstanceMethods)
base.extend(ClassMethods)
end
module ClassMethods
# takes a provider and uid and finds a user by them.
def load_from_provider(provider, uid)
config = sorcery_config
authentication = config.<API key>.sorcery_adapter.<API key>(provider, uid)
# Return user if matching authentication found
sorcery_adapter.find_by_id(authentication.send(config.<API key>)) if authentication
end
def <API key>(provider, uid, attrs)
user = new(attrs)
user.send(sorcery_config.<API key>.name.demodulize.underscore.pluralize).build(
sorcery_config.<API key> => uid,
sorcery_config.<API key> => provider
)
saved = user.sorcery_adapter.save
[user, saved]
end
def <API key>(provider, uid, attrs)
user = new
attrs.each do |k, v|
user.send(:"#{k}=", v)
end
if block_given?
return false unless yield user
end
sorcery_adapter.transaction do
user.sorcery_adapter.save(validate: false)
sorcery_config.<API key>.create!(
sorcery_config.<API key> => user.id,
sorcery_config.<API key> => provider,
sorcery_config.<API key> => uid
)
end
user
end
# NOTE: Should this build the authentication as well and return [user, auth]?
# Currently, users call this function for the user and call <API key> after saving
def build_from_provider(attrs)
user = new
attrs.each do |k, v|
user.send(:"#{k}=", v)
end
if block_given?
return false unless yield user
end
user
end
end
module InstanceMethods
def <API key>(provider, uid)
authentications = sorcery_config.<API key>.name.demodulize.underscore.pluralize
# first check to see if user has a particular authentication already
if sorcery_adapter.find_<API key>(authentications, provider, uid).nil?
user = send(authentications).build(sorcery_config.<API key> => uid,
sorcery_config.<API key> => provider)
user.sorcery_adapter.save(validate: false)
else
user = false
end
user
end
end
end
end
end
end |
<!-- Top Navbar-->
<div class="navbar">
<div class="navbar-inner">
<div class="left"><a href="#" class="back link"> <i class="icon icon-back"></i><span>Back</span></a></div>
<div class="center sliding"></div>
<div class="right">
</div>
</div>
</div>
<div class="pages">
<div class="page" data-page="userentrydone">
<div class="page-content">
<div class="content-block">
{{query}}
</div>
</div>
</div>
</div> |
// Last.Fm Records 3.1
// Jeroen Smeets
// If you release this code as part of your own package,
// you have to change the API key. For more info, see
var lastFmRecords = (function() {
// private, reachable through public setters
var _user;
var _period = 'recenttracks';
var _count = 6;
var _styletype = ''; // can be highslide, lightbox
var _refreshmin = 3;
var _placeholder = 'lastfmrecords';
var _defaultthumb = 'http://cdn.last.fm/depth/catalogue/noimage/cover_85px.gif';
var _debug = false;
var _gmt_offset = '+1';
var _linknewscreen = 0;
// private //
var _imgs_found = [];
// capitals to pretend these are constant
var _LASTFM_<API key>;
var _LASTFM_WS_URL = 'http://ws.audioscrobbler.com/2.0/';
// last.fm added a default album image, and I don't like it
var _LASTFM_DEFAULTIMG = 'http://cdn.last.fm/flatness/catalogue/noimage/2/<API key>.png';
function _logStatus(text) {
if (_debug)
if ('undefined' != typeof console)
if ('function' == typeof console.log)
if ('object' == typeof text)
console.log(text);
else
console.log('last.fm.records: ' + text);
};
function _getLastFMData() {
var _method = false;
switch(_period) {
case 'lovedtracks':
_method = 'user.getlovedtracks';
break;
case 'topalbums':
_method = 'user.gettopalbums';
break;
case 'overall':
case '7day':
case '3month':
case '6month':
case '12month':
_method = 'user.gettopalbums&period=' + _period;
break;
default:
_method = 'user.getrecenttracks';
}
jQuery.getJSON(
_LASTFM_WS_URL + '?method=' + _method + '&user=' + _user + '&api_key=' + _LASTFM_APIKEY + '&limit=50&format=json&callback=?',
lastFmRecords.processLastFmData
);
};
function _getArtistData(_artistmbid) {
jQuery.getJSON(
_LASTFM_WS_URL
+ '?method=artist.getinfo&mbid=' + _artistmbid + '&api_key=' + _LASTFM_APIKEY + '&format=json&callback=?',
lastFmRecords.processArtistData
);
};
function <API key>(data) {
var _errorfound = false;
var _errormsg;
jQuery.each(data, function(tag, val) {
if ('error' == tag) {
_errorfound = true;
_errormsg = ' (' + val + ')';
}
if (_errorfound && ('message' == tag)) {
_errormsg = val + _errormsg;
}
});
if (_errorfound) {
_logStatus('last.fm reported error: ' + _errormsg);
}
return _errorfound;
}
function _findLargestImage(_imgarray) {
// _imgarray is an array returned by last.fm that looks like
// "image":[{"#text":"http:\/\/images.amazon.com\/images\/P\/B00004YYTW.02._SCMZZZZZZZ_.jpg","size":"small"},
// {"#text":"http:\/\/images.amazon.com\/images\/P\/B00004YYTW.02._SCMZZZZZZZ_.jpg","size":"medium"},
// {"#text":"http:\/\/images.amazon.com\/images\/P\/B00004YYTW.02._SCMZZZZZZZ_.jpg","size":"large"}
_biggestYet = false;
jQuery.each(_imgarray, function(j, _img) {
if ('large' == _img.size) {
_biggestYet = _img['#text'];
// biggest found, get out of this loop
return false;
} else if ('medium' == _img.size) {
_biggestYet = _img['#text'];
} else if (('small' == _img.size) && ('' == _biggestYet)) {
_biggestYet = _img['#text'];
}
});
return (_LASTFM_DEFAULTIMG == _biggestYet) ? false : _biggestYet;
}
function _processLastFmData(data) {
// error in response?
if (<API key>(data)) {
return false;
}
// get the cd data from the json
switch(_period) {
case 'recenttracks':
data = data.recenttracks.track;
break;
case 'lovedtracks':
data = data.lovedtracks.track;
break;
default:
data = data.topalbums.album;
}
if (!data) {
_logStatus('No return data from Last.fm');
return false;
}
// JNS 2009-07-30
// thanks to my friend xample who only listened to 1 album last week,
// i was able to fix this bug:
// if only one result is found, data is not an array of albums/tracks but just one album/track.
if (data.name && 'string' == typeof data.name) {
data = [data];
}
jQuery.each(data, function(i, _json) {
if (i > _count) {
return false;
}
var track = [];
track.cdcover = _json.image ? _findLargestImage(_json.image) : false;
track.artistname = _json.artist['#text'] || _json.artist.name;
track.artistmbid = _json.artist['mbid'];
track.name = _json.name;
track.mbid = _json.mbid;
track.url = ('http://' == _json.url.substr(0, 7).toLowerCase())
? _json.url
: 'http://' + _json.url;
if ('recenttracks' == _period) {
// aaargh! json has changed!
if (_json['@attr'] && ('true' == _json['@attr'].nowplaying)) {
track.time = 'listening now';
} else {
track.time = ('undefined' == typeof _json.date)
? 'some time'
: _getTimeAgo(_json.date['#text'], _gmt_offset);
}
} else {
track.time = '';
}
_showCover(i, track);
});
if (_refreshmin > 0) {
setTimeout('lastFmRecords.refreshCovers();', _refreshmin * 60000);
}
};
function _showCover(_id, _track) {
// store last.fm data about this track in (well, near, thanks to jQuery) the image
jQuery.each(_track, function(tag, val) {
jQuery('#lastfmcover' + _id).data(tag, val);
});
// always set title of image
var _title = _track.name + ' by ' + _track.artistname;
if ('' != _track.time) {
_title += ' (' + _track.time + ')';
}
jQuery('#lastfmcover' + _id).attr('title', _title);
if ('' == _track.cdcover) {
// no cover for cd, do we have an image for the artist?
if (_imgs_found[_track.artistmbid] && ('*' != _imgs_found[_track.artistmbid])) {
// yes, use that url
jQuery('#lastfmcover' + _id).attr('src', _imgs_found[_track.artistmbid]);
} else {
// nope, let's ask last.fm.
if ('*' != _imgs_found[_track.artistmbid]) {
if (_track.artistmbid) {
_logStatus('cover for ' + _track.name + ' not found, trying to find image of artist ' + _track.artistname);
// Setting a star to know we're already looking for this one
_imgs_found[_track.artistmbid] = '*';
_getArtistData(_track.artistmbid);
} else {
// TODO find image for artist
_logStatus('no last.fm data found for artist ' + _track.artistname);
}
}
jQuery('#lastfmcover' + _id).attr('src', _defaultthumb);
jQuery('#lastfmcover' + _id).addClass(_track.artistmbid);
}
} else {
// point src and href of parent a to the image
// and make link clickable
jQuery('#lastfmcover' + _id).attr('src', _track.cdcover).parent('a').attr('href', _track.url).unbind('click', lastFmRecords.dontFollowLink);
}
};
function _processArtistData(data) {
// error in response?
if (<API key>(data)) {
return false;
}
// data = data.artist;
jQuery.each(data, function(i, _json) {
_imgurl = _findLargestImage(_json.image);
_mbid = _json.mbid;
// find images that need to be changed
jQuery('.' + _mbid).each( function() {
// point src and href of parent a to the image and make link clickable
jQuery(this).attr('src', _imgurl).removeClass(_mbid).parent('a').attr('href', _json.url).unbind('click', lastFmRecords.dontFollowLink);
});
// remember we have an url for this artist
_imgs_found[_mbid] = _imgurl;
// stop looping
return false;
});
};
// this code is just too complex, I know. Suggestions?
function _getTimeAgo(_t, gmt_offset) {
// _logStatus('trying to figure out how long ago ' + _t + ' is, in your timezone ' + gmt_offset);
// difference between then and now
var _diff = new Date() - new Date(_t);
// take into account the timezone difference
_diff = _diff - (gmt_offset * 60000 * 60);
var _d = [];
// how many years in the difference? not many, I hope ;-)
_d.ye = parseInt(_diff / (1000 * 60 * 60 * 24 * 365));
_d.da = parseInt(_diff / (1000 * 60 * 60 * 24)) - (_d.ye * 365);
_d.ho = parseInt(_diff / (1000 * 60 * 60)) - (_d.ye * 365 * 24) - (_d.da * 24);
_d.mi = parseInt(_diff / (1000 * 60)) - (_d.ye * 365 * 24 * 60) - (_d.da * 24 * 60) - (_d.ho * 60);
var _meantime = [];
if (_d.ye > 0) { _meantime.push(_d.ye + ' year' + _getPluralS(_d.ye)); }
if (_d.da > 0) { _meantime.push(_d.da + ' day' + _getPluralS(_d.da)); }
if (_d.ho > 0) { _meantime.push(_d.ho + ' hour' + _getPluralS(_d.ho)); }
if (_d.mi > 0) { _meantime.push(_d.mi + ' minute' + _getPluralS(_d.mi)) };
// TODO: replace last comma with 'and'
return _meantime.join(', ') + ' ago';
};
function _getPluralS(_c) {
return (1 == _c) ? '' : 's';
};
function _handleError(_msg, _url, _linenumber) {
var _err = [];
_err.msg = _msg;
_err.url = _url;
_err.line = _linenumber;
_err.ref = document.location.href;
_logStatus(_err);
// returning false means javascript won't stop when it finds an error
return false;
};
// public //
return {
addStyle: function(styletype) {
_logStatus('function addStyle not supported yet');
},
setUser: function(orUsername) {
// TODO: validation
_user = orUsername;
},
setPeriod: function(orPeriod) {
// TODO: just todo ;-)
_period = orPeriod;
},
setCount: function(orCount) {
var _pI = parseInt(orCount);
if (_pI > 0) {
_count = _pI;
}
},
setStyle: function(orStyle) {
// TODO: validation
_styletype = orStyle;
},
setPlaceholder: function(orPlaceholder) {
// TODO: validate
_placeholder = orPlaceholder;
},
setDefaultThumb: function(orDefaultThumb) {
// TODO: validate
_defaultthumb = orDefaultThumb;
},
setRefreshMinutes: function(orRefresh) {
var _pI = parseInt(orRefresh);
if (_pI > 0) {
_refreshmin = _pI;
}
},
setTimeOffset: function(orOffset) {
_gmt_offset = parseInt(orOffset);
},
setLinkNewScreen: function(orLinkNewScreen) {
_linknewscreen = ('1' == orLinkNewScreen);
},
debug: function() {
_debug = true;
},
err: function(msg, url, linenumber) {
_handleError(msg, url, linenumber);
},
dontFollowLink: function() {
// made it a function so I can unbind it
return false;
},
init: function(_settings) {
_logStatus('initializing');
// send javascript errors to error handler
// to catch javascript errors that could make js stop
jQuery(window).bind('error', lastFmRecords.err);
_logStatus('registering error handler');
if (_settings.placeholder) {
this.setPlaceholder(_settings.placeholder);
}
// is a string [lastfmrecords|period|count] found on the page?
var _regex = /\[lastfmrecords\|[a-z]+\|[0-9]+\]/;
// get the strings in it
var _match = document.body.innerHTML.match(_regex);
_logStatus(_match);
if (_match) {
// and put the div where the cd covers should be
document.body.innerHTML = document.body.innerHTML.replace(_regex, '<div id=' + _placeholder + '></div>');
// change settings based on _match
_match = _match[0].replace('[', '').replace(']', '').split('|');
_logStatus('Hey, that\'s nice, this site is using the [lastfmrecords|period|count] way of showing covers.');
if (_match[1]) {
_settings.period = _match[1];
_logStatus('Changing period to ' + _match[1]);
}
if (_match[2]) {
_settings.count = _match[2];
_logStatus('Changing number of covers to ' + _match[2]);
}
}
if (jQuery("div#" + _placeholder).length < 1) {
_logStatus('error: placeholder for cd covers not found');
return false;
}
if (_settings.username) { this.setUser(_settings.username) }
if (_settings.period) { this.setPeriod(_settings.period); }
if (_settings.defaultthumb) { this.setDefaultThumb(_settings.defaultthumb); }
if (_settings.count) { this.setCount(_settings.count); }
if (_settings.refresh) { this.setRefreshMinutes(_settings.refresh); }
if (_settings.offset) { this.setTimeOffset(_settings.offset); }
if (_settings.styletype) { this.setStyle(_settings.styletype); }
if (_settings.linknewscreen) { this.setLinkNewScreen(_settings.linknewscreen); }
if ('1' == _settings.debug) { this.debug(); }
_logStatus(_user);
if (!_user) {
_logStatus('No last.fm username available. Impossible to fetch listening habits. Goodbye.');
return false;
}
// no need to refresh when period isn't Recent tracks
if ('recenttracks' != _period) {
_refreshmin = 0;
}
// add an ul to placeholder div
var _ol = jQuery("<ol></ol>").appendTo("div#" + _placeholder);
if (!_ol) {
_logStatus('error: placeholder for cd covers not found');
}
// add temporary cd covers
_logStatus('adding temporary cd covers');
var _img, _li;
for (var i = 0; i < _count; i++) {
_li = jQuery('<li></li>').attr('style', 'display: inline;');
_a = jQuery('<a></a>').bind('click', lastFmRecords.dontFollowLink).attr('href', '').appendTo(_li);
// highslide
if ('highslide' == _styletype) {
_a.click( function() { return hs.expand(this); });
}
// lightbox
else if ('lightbox' == _styletype) {
_a.attr('rel', 'lightbox');
}
// add target=_blank to link
else if ('1' == _linknewscreen) {
_a.attr('target', '_blank');
}
_img = jQuery('<img></img>')
.attr('src', _defaultthumb)
.attr('id', 'lastfmcover' + i)
.error(
function() {
jQuery(this).attr("src", _defaultthumb);
})
.appendTo(_a);
_li.appendTo(_ol);
}
_getLastFMData();
},
refreshCovers: function() {
_getLastFMData();
},
processLastFmData: function(data) {
// handle it internally
_processLastFmData(data);
},
processArtistData: function(data) {
// handle it internally
_processArtistData(data);
}
};
})(); |
import Ember from 'ember';
export default Ember.Controller.extend({
activeProjects: Ember.computed("model.[]", function() {
return this.get("model").filterBy("state", "active");
}),
completedProjects: Ember.computed("model.[]", function() {
return this.get("model").filterBy("state", "completed");
}),
upcomingProjects: Ember.computed("model.[]", function() {
return this.get("model").filterBy("state", "upcoming");
}),
}); |
package com.fteams.siftrain.util.random;
import com.badlogic.gdx.utils.Array;
import com.fteams.siftrain.objects.CircleMark;
import java.util.HashMap;
import java.util.Map;
public class ExtremeRandomizer extends Randomizer {
private Map<Integer, Double> noteToReleaseTime = new HashMap<>();
/*
* Info: this is the only randomizer which works with ANY BEATMAP (even those with more than 2 notes at the same time!)
*/
public void randomize(Array<CircleMark> marks) {
// sort marks by timing
marks.sort();
double threshold = marks.get(0).speed / 32.0;
for (int i = 0 ; i < marks.size; i++)
{
CircleMark mark = marks.get(i);
Integer pos = getFreePosition(mark.getNote().timing_sec);
noteToReleaseTime.put(pos, mark.getNote().timing_sec + (mark.hold ? mark.getNote().effect_value : 0) + threshold);
mark.updateDestination(pos);
}
}
private Integer getFreePosition(Double timing_sec) {
Integer position = (int)(Math.random() * 100) % 9;
while (noteToReleaseTime.get(position) != null && noteToReleaseTime.get(position) >= timing_sec )
{
position = (int)(Math.random() * 100) % 9;
}
return position;
}
} |
@charset "UTF-8";
/**
* sass
* rem 100px
* @version 1.0.0
* @author bigfact
* @date 2016.06.16
*/
.pop .mask {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.6);
}
.dialog {
position: fixed;
top: 30%;
background: #FFF;
width: 80%;
margin: 0 10%;
font-size: .14rem;
-moz-border-radius: 2px;
-<API key>: 2px;
border-radius: 2px;
}
.dialog .title {
text-align: center;
padding: .15rem 0 .1rem;
font-size: .16rem;
}
.dialog .content {
padding: 0 .15rem .15rem;
}
.dialog .footer {
position: relative;
height: .4rem;
line-height: .4rem;
text-align: center;
}
.dialog .footer::before {
content: " ";
position: absolute;
right: 0;
top: 0;
width: 100%;
border-top: 1px solid #D9D9D9;
}
.dialog .footer > * {
height: 100%;
float: left;
width: 49%;
}
.dialog .footer > *:first-of-type {
border-right: 1px solid #D9D9D9;
}
.dialog .footer > *:only-of-type {
width: 100%;
border: none;
}
/**
* loading
*/
.loading {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
height: .3rem;
text-align: center;
}
.loading > * {
width: .3rem;
height: .3rem;
background-color: #FFF;
-moz-border-radius: 100%;
-<API key>: 100%;
border-radius: 100%;
display: inline-block;
-moz-animation: "kfs-loading" 1.4s infinite ease-in-out;
-webkit-animation: "kfs-loading" 1.4s infinite ease-in-out;
animation: "kfs-loading" 1.4s infinite ease-in-out;
-<API key>: both;
-<API key>: both;
animation-fill-mode: both;
}
.loading > *:first-of-type {
-moz-animation-delay: -0.16s;
-<API key>: -0.16s;
animation-delay: -0.16s;
}
.loading > *:last-of-type {
-moz-animation-delay: 0.16s;
-<API key>: 0.16s;
animation-delay: 0.16s;
}
@-moz-keyframes kfs-loading {
0%, 80%, 100% {
-moz-transform: scale(0);
transform: scale(0);
}
40% {
-moz-transform: scale(1);
transform: scale(1);
}
}
@-webkit-keyframes kfs-loading {
0%, 80%, 100% {
-webkit-transform: scale(0);
transform: scale(0);
}
40% {
-webkit-transform: scale(1);
transform: scale(1);
}
}
@keyframes kfs-loading {
0%, 80%, 100% {
-moz-transform: scale(0);
-ms-transform: scale(0);
-webkit-transform: scale(0);
transform: scale(0);
}
40% {
-moz-transform: scale(1);
-ms-transform: scale(1);
-webkit-transform: scale(1);
transform: scale(1);
}
} |
// Purpose: A simple application demonstrating the HL2 demo file format ( subject to change!!! )
// $NoKeywords: $
#include <windows.h>
#include "tier0/dbg.h"
#include "FileSystem.h"
#include "FileSystem_Tools.h"
#include "cmdlib.h"
#include "tooldemofile.h"
static bool uselogfile = false;
static bool spewed = false;
#define LOGFILE_NAME "log.txt"
#define COM_COPY_CHUNK_SIZE 8192
// Purpose: Prints to stdout and to the developer console and optionally to a log file
// Input : depth -
// *fmt -
void vprint( int depth, const char *fmt, ... )
{
char string[ 8192 ];
va_list va;
va_start( va, fmt );
vsprintf( string, fmt, va );
va_end( va );
FILE *fp = NULL;
if ( uselogfile )
{
fp = fopen( LOGFILE_NAME, "ab" );
}
while ( depth
{
printf( " " );
OutputDebugString( " " );
if ( fp )
{
fprintf( fp, " " );
}
}
::printf( string );
OutputDebugString( string );
if ( fp )
{
char *p = string;
while ( *p )
{
if ( *p == '\n' )
{
fputc( '\r', fp );
}
fputc( *p, fp );
p++;
}
fclose( fp );
}
}
// Purpose: Warning/Msg call back through this API
// Input : type -
// *pMsg -
// Output : SpewRetval_t
SpewRetval_t SpewFunc( SpewType_t type, char const *pMsg )
{
spewed = true;
switch ( type )
{
default:
case SPEW_MESSAGE:
case SPEW_ASSERT:
case SPEW_LOG:
vprint( 0, "%s", pMsg );
break;
case SPEW_WARNING:
if ( verbose )
{
vprint( 0, "%s", pMsg );
}
break;
case SPEW_ERROR:
vprint( 0, "%s\n", pMsg );
break;
}
return SPEW_CONTINUE;
}
// Purpose: Shows usage information
void printusage( void )
{
vprint( 0, "usage: demoinfo <.dem file>\n\
\t-v = verbose output\n\
\t-l = log to file log.txt\n\
\ne.g.: demoinfo -v u:/hl2/hl2/foo.dem\n" );
// Exit app
exit( 1 );
}
// Purpose: Removes previous log file
void CheckLogFile( void )
{
if ( uselogfile )
{
_unlink( LOGFILE_NAME );
vprint( 0, " Outputting to log.txt\n" );
}
}
// Purpose: Prints banner
void PrintHeader()
{
vprint( 0, "Valve Software - demoinfo.exe (%s)\n", __DATE__ );
vprint( 0, "
}
// Purpose: Parses all "smoothing" info from .dem file
// Input : &demoFile -
// smooth -
void ParseSmoothingInfo( CToolDemoFile &demoFile, CUtlVector< demosmoothing_t >& smooth )
{
democmdinfo_t info;
int dummy;
bool demofinished = false;
while ( !demofinished )
{
int tick = 0;
byte cmd;
bool swallowmessages = true;
do
{
demoFile.ReadCmdHeader( cmd, tick );
// COMMAND HANDLERS
switch ( cmd )
{
case dem_synctick:
break;
case dem_stop:
{
swallowmessages = false;
demofinished = true;
}
break;
case dem_consolecmd:
{
demoFile.ReadConsoleCommand();
}
break;
case dem_datatables:
{
demoFile.<API key>( NULL );
}
break;
case dem_usercmd:
{
demoFile.ReadUserCmd( NULL, dummy );
}
break;
default:
{
swallowmessages = false;
}
break;
}
}
while ( swallowmessages );
if ( demofinished )
{
// StopPlayback();
return;
}
int curpos = demoFile.GetCurPos();
demoFile.ReadCmdInfo( info );
demoFile.ReadSequenceInfo( dummy, dummy );
demoFile.ReadRawData( NULL, 0 );
demosmoothing_t smoothing_entry;
smoothing_entry.file_offset = curpos;
smoothing_entry.frametick = tick;
smoothing_entry.info = info;
smoothing_entry.samplepoint = false;
smoothing_entry.vecmoved = info.GetViewOrigin();
smoothing_entry.angmoved = info.GetViewAngles();
smoothing_entry.targetpoint = false;
smoothing_entry.vectarget = info.GetViewOrigin();
// Add to end of list
smooth.AddToTail( smoothing_entry );
}
}
// Purpose: Resets all smoothing data back to original values
// Input : smoothing -
void ClearSmoothingInfo( CSmoothingContext& smoothing )
{
int c = smoothing.smooth.Count();
int i;
for ( i = 0; i < c; i++ )
{
demosmoothing_t *p = &smoothing.smooth[ i ];
p->info.Reset();
p->vecmoved = p->info.GetViewOrigin();
p->angmoved = p->info.GetViewAngles();
p->samplepoint = false;
p->vectarget = p->info.GetViewOrigin();
p->targetpoint = false;
}
}
// Purpose: Helper for copying sub-chunk of file
// Input : dst -
// src -
// nSize -
void COM_CopyFileChunk( FileHandle_t dst, FileHandle_t src, int nSize )
{
int copysize = nSize;
char copybuf[COM_COPY_CHUNK_SIZE];
while (copysize > COM_COPY_CHUNK_SIZE)
{
g_pFileSystem->Read ( copybuf, COM_COPY_CHUNK_SIZE, src );
g_pFileSystem->Write( copybuf, COM_COPY_CHUNK_SIZE, dst );
copysize -= COM_COPY_CHUNK_SIZE;
}
g_pFileSystem->Read ( copybuf, copysize, src );
g_pFileSystem->Write( copybuf, copysize, dst );
g_pFileSystem->Flush ( src );
g_pFileSystem->Flush ( dst );
}
// Purpose: Writes out a new .dem file based on the existing dem file with new camera positions saved into the dem file
// Note: The new file is named filename_smooth.dem
// Input : *filename -
// smoothing -
void SaveSmoothingInfo( char const *filename, CSmoothingContext& smoothing )
{
// Nothing to do
int c = smoothing.smooth.Count();
if ( !c )
return;
IBaseFileSystem *fs = g_pFileSystem;
FileHandle_t infile, outfile;
infile = fs->Open( filename, "rb", "GAME" );
if ( infile == <API key> )
return;
int filesize = fs->Size( infile );
char outfilename[ 512 ];
Q_StripExtension( filename, outfilename, sizeof( outfilename ) );
Q_strncat( outfilename, "_smooth", sizeof(outfilename), COPY_ALL_CHARACTERS );
Q_DefaultExtension( outfilename, ".dem", sizeof( outfilename ) );
outfile = fs->Open( outfilename, "wb", "GAME" );
if ( outfile == <API key> )
{
fs->Close( infile );
return;
}
int i;
// The basic algorithm is to seek to each sample and "overwrite" it during copy with the new data...
int lastwritepos = 0;
for ( i = 0; i < c; i++ )
{
demosmoothing_t *p = &smoothing.smooth[ i ];
int copyamount = p->file_offset - lastwritepos;
COM_CopyFileChunk( outfile, infile, copyamount );
fs->Seek( infile, p->file_offset, <API key> );
// wacky hacky overwriting
fs->Write( &p->info, sizeof( democmdinfo_t ), outfile );
lastwritepos = fs->Tell( outfile );
fs->Seek( infile, p->file_offset + sizeof( democmdinfo_t ), <API key> );
}
// Copy the final bit of data, if any...
int final = filesize - lastwritepos;
COM_CopyFileChunk( outfile, infile, final );
fs->Close( outfile );
fs->Close( infile );
}
// Purpose: Helper for spewing verbose sample information
// Input : flags -
// Output : char const
char const *DescribeFlags( int flags )
{
static char outbuf[ 256 ];
outbuf[ 0 ] = 0;
if ( flags & FDEMO_USE_ORIGIN2 )
{
Q_strncat( outbuf, "USE_ORIGIN2, ", sizeof( outbuf ), COPY_ALL_CHARACTERS );
}
if ( flags & FDEMO_USE_ANGLES2 )
{
Q_strncat( outbuf, "USE_ANGLES2, ", sizeof( outbuf ), COPY_ALL_CHARACTERS );
}
if ( flags & FDEMO_NOINTERP )
{
Q_strncat( outbuf, "NOINTERP, ", sizeof( outbuf ), COPY_ALL_CHARACTERS );
}
int len = Q_strlen( outbuf );
if ( len > 2 )
{
outbuf[ len - 2 ] = 0;
}
else
{
Q_strncpy( outbuf, "N/A", sizeof( outbuf ) );
}
return outbuf;
}
// Purpose: Loads up all camera samples from a .dem file into the passed in context.
// Input : *filename -
// smoothing -
void LoadSmoothingInfo( const char *filename, CSmoothingContext& smoothing )
{
char name[ MAX_OSPATH ];
Q_strncpy (name, filename, sizeof(name) );
Q_DefaultExtension( name, ".dem", sizeof( name ) );
CToolDemoFile demoFile;
if ( !demoFile.Open( filename, true ) )
{
Warning( "ERROR: couldn't open %s.\n", name );
return;
}
demoheader_t * header = demoFile.ReadDemoHeader();
if ( !header )
{
demoFile.Close();
return;
}
Msg( "\n\n" );
Msg( "
Msg( "demofilestamp: '%s'\n", header->demofilestamp );
Msg( "demoprotocol: %i\n", header->demoprotocol );
Msg( "networkprotocol: %i\n", header->networkprotocol );
Msg( "servername: '%s'\n", header->servername );
Msg( "clientname: '%s'\n", header->clientname );
Msg( "mapname: '%s'\n", header->mapname );
Msg( "gamedirectory: '%s'\n", header->gamedirectory );
Msg( "playback_time: %f seconds\n", header->playback_time );
Msg( "playback_ticks: %i ticks\n", header->playback_ticks );
Msg( "playback_frames: %i frames\n", header->playback_frames );
Msg( "signonlength: %s\n", Q_pretifymem( header->signonlength ) );
smoothing.active = true;
Q_strncpy( smoothing.filename, name, sizeof(smoothing.filename) );
smoothing.smooth.RemoveAll();
ClearSmoothingInfo( smoothing );
ParseSmoothingInfo( demoFile, smoothing.smooth );
Msg( "
Msg( "smoothing data: %i samples\n", smoothing.smooth.Count() );
if ( verbose )
{
int c = smoothing.smooth.Count();
for ( int i = 0; i < c; ++i )
{
demosmoothing_t& sample = smoothing.smooth[ i ];
Msg( "Sample %i:\n", i );
Msg( " file pos: %i\n", sample.file_offset );
Msg( " tick: %i\n", sample.frametick );
Msg( " flags: %s\n", DescribeFlags( sample.info.flags ) );
Msg( " Original Data:\n" );
Msg( " origin: %.4f %.4f %.4f\n", sample.info.viewOrigin.x, sample.info.viewOrigin.y, sample.info.viewOrigin.z );
Msg( " viewangles: %.4f %.4f %.4f\n", sample.info.viewAngles.x, sample.info.viewAngles.y, sample.info.viewAngles.z );
Msg( " localviewangles: %.4f %.4f %.4f\n", sample.info.localViewAngles.x, sample.info.localViewAngles.y, sample.info.localViewAngles.z );
Msg( " Resampled Data:\n" );
Msg( " origin: %.4f %.4f %.4f\n", sample.info.viewOrigin2.x, sample.info.viewOrigin2.y, sample.info.viewOrigin2.z );
Msg( " viewangles: %.4f %.4f %.4f\n", sample.info.viewAngles2.x, sample.info.viewAngles2.y, sample.info.viewAngles2.z );
Msg( " localviewangles: %.4f %.4f %.4f\n", sample.info.localViewAngles2.x, sample.info.localViewAngles2.y, sample.info.localViewAngles2.z );
Msg( "\n" );
}
}
demoFile.Close();
}
// Purpose:
// Input : argc -
// argv[] -
// Output : int
int main( int argc, char* argv[] )
{
SpewOutputFunc( SpewFunc );
SpewActivate( "demoinfo", 2 );
int i;
for ( i=1 ; i<argc ; i++)
{
if ( argv[ i ][ 0 ] == '-' )
{
switch( argv[ i ][ 1 ] )
{
case 'l':
uselogfile = true;
break;
case 'v':
verbose = true;
break;
case 'g':
++i;
break;
default:
printusage();
break;
}
}
}
if ( argc < 2 || ( i != argc ) )
{
PrintHeader();
printusage();
}
CheckLogFile();
PrintHeader();
vprint( 0, " Info for %s..\n", argv[ i - 1 ] );
char workingdir[ 256 ];
workingdir[0] = 0;
Q_getwd( workingdir, sizeof( workingdir ) );
if ( !FileSystem_Init( NULL, 0, FS_INIT_FULL ) )
return 1;
// Add this so relative filenames work.
g_pFullFileSystem->AddSearchPath( workingdir, "game", PATH_ADD_TO_HEAD );
// Load the demo
CSmoothingContext context;
LoadSmoothingInfo( argv[ i - 1 ], context );
// Note to tool makers:
// Do your work here!!!
//Performsmoothing( context );
// Save out updated .dem file
// UNCOMMENT THIS TO ENABLE OUTPUTTING NEW .DEM FILES!!!
// SaveSmoothingInfo( argv[ i - 1 ], context );
FileSystem_Term();
return 0;
} |
#!/bin/bash
# Sets up various stuff in Docker Container: database and Plugins
echo "START /configure.sh"
source /venv/bin/activate .
# Make sure PYTHONPATH includes GeoHealthCheck
export PYTHONPATH=/GeoHealthCheck/GeoHealthCheck:$PYTHONPATH
# Determine database type from DB URI
DB_TYPE=$(echo ${<API key>} | cut -f1 -d:)
echo "Using DB_TYPE=${DB_TYPE}"
# Create DB shorthand
function create_db() {
pushd /GeoHealthCheck/
paver create -u ${ADMIN_NAME} -p ${ADMIN_PWD} -e ${ADMIN_EMAIL}
popd
}
# Init actions per DB type
case ${DB_TYPE} in
sqlite)
if [ ! -f /GeoHealthCheck/DB/data.db ]
then
echo "Creating SQLite DB tables..."
create_db
else
echo "NOT creating SQLite DB tables..."
fi
;;
postgresql)
# format: postgresql://user:pw@host:5432/db
# Bit tricky, may use awk, but cut out DB elements from URI
DB_NAME=$(echo ${<API key>} | cut -f4 -d/)
DB_PASSWD_HOST=$(echo ${<API key>} | cut -f3 -d:)
DB_HOST=$(echo ${DB_PASSWD_HOST} | cut -f2 -d@)
DB_PASSWD=$(echo ${DB_PASSWD_HOST} | cut -f1 -d@)
DB_USER_SLASH=$(echo ${<API key>} | cut -f2 -d:)
DB_USER=$(echo ${DB_USER_SLASH} | cut -f3 -d/)
export PGPASSWORD=${DB_PASSWD}
# We need to wait until PG Container available
echo "Check if Postgres is avail/ready..."
until pg_isready -h "${DB_HOST}"; do
echo "Exit code=$? - Postgres not ready - sleeping"
sleep 1
done
# Check if we need to create DB tables
echo "Postgres is up - check if DB populated"
if ! psql -h "${DB_HOST}" -U "${DB_USER}" -c 'SELECT COUNT(*) FROM resource' ${DB_NAME}
then
echo "Creating Postgres DB tables..."
create_db
else
echo "Postgres DB already populated"
fi
;;
*)
echo "Unknown database type ${DB_TYPE}, exiting"
exit -1
;;
esac
# Copy possible mounted Plugins into app tree
if [ -d /plugins ]
then |
<html>
<head>
<link rel="stylesheet" href="style.css" />
<!-- To successful run the demo in Mainland China, use `gulp chinaCDN` to
replace fonts.usesoso.com with fonts.googleapis.com and replcace
maxcdn.bootstrapcdn.com with maxcdn.bootstrapcdn.com.
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css">
</head>
<body>
<div class="btn-share">
<a class="btn-share-brand btn-share-twitter" href="#"><i class="fa fa-twitter"></i></a>
<a class="btn-share-brand btn-share-facebook" href="#"><i class="fa fa-facebook"></i></a>
<a class="btn-share-brand <API key>" href="#"><i class="fa fa-google-plus"></i></a>
<span class="btn-share-text"><i>SHARE</i></span>
<svg class="btn-share-sign" width="1792" height="1792" viewBox="0 0 1792 1792" xmlns="http:
<path d="M1344 1024q133 0 226.5 93.5t93.5 226.5-93.5 226.5-226.5 93.5-226.5-93.5-93.5-226.5q0-12 2-34l-360-180q-92 86-218 86-133 0-226.5-93.5t-93.5-226.5 93.5-226.5 226.5-93.5q126 0 218 <API key> 0-133 93.5-226.5t226.5-93.5 226.5 93.5 93.5 226.5-93.5 226.5-226.5 93.5q-126 0-218-86l-360 180q2 22 2 34t-2 34l360 180q92-86 218-86z"
fill="#fff" />
</svg>
</div>
</body>
</htm> |
// NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT
// IT'S ALL JUST JUNK FOR OUR DOCS!
/* global Clipboard, anchors */
!(function($) {
'use strict';
$(function() {
// Disable empty links in docs examples
$('.page-content [href="#"]').click(function(e) {
e.preventDefault();
});
// Insert copy to clipboard button before .highlight
$('pre > code').each(function() {
var btnHtml = '<div class="bd-clipboard"><span class="btn-clipboard" title="Copy to clipboard">Copy</span></div>';
$(this).parent().before(btnHtml);
$('.btn-clipboard').tooltip();
});
var clipboard = new Clipboard('.btn-clipboard', {
target: function(trigger) {
return trigger.parentNode.nextElementSibling;
},
text: function(trigger) {
var sib = trigger.parentNode.nextElementSibling;
var val = $(sib).text();
return val.replace(/^\s*\$ +/, '');
}
});
clipboard.on('success', function(e) {
$(e.trigger)
.attr('title', 'Copied!')
.tooltip('_fixTitle')
.tooltip('show')
.attr('title', 'Copy to clipboard')
.tooltip('_fixTitle');
e.clearSelection();
});
clipboard.on('error', function(e) {
var modifierKey = /Mac/i.test(navigator.userAgent) ? '\u2318' : 'Ctrl-';
var fallbackMsg = 'Press ' + modifierKey + 'C to copy';
$(e.trigger)
.attr('title', fallbackMsg)
.tooltip('_fixTitle')
.tooltip('show')
.attr('title', 'Copy to clipboard')
.tooltip('_fixTitle');
});
// IE10 viewport hack for Surface/desktop Windows 8 bug
// See Getting Started docs for more information
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
var msViewportStyle = document.createElement('style');
msViewportStyle.appendChild(
document.createTextNode('@-ms-viewport{width:auto!important}')
);
document.querySelector('head').appendChild(msViewportStyle);
}
var $window = $(window);
var $body = $(document.body);
$body.scrollspy({
target: '.sidebar'
});
$window.on('load', function() {
$body.scrollspy('refresh');
});
// Keep popovers open when hovered
$('.source-link').popover({
trigger: 'manual',
container: 'body',
placement: 'left',
toggle: 'popover',
template: '<div class="popover popover-source"> <div class="arrow"></div> <div class="popover-inner"> <h3 class="popover-title"></h3> <div class="popover-content"> <p></p> </div> </div> </div>',
html: true,
delay: {show: 50, hide: 750}
}).on('mouseenter', function() {
var self = this;
$(this).popover('show');
$(this).addClass('active');
$('.popover').on('mouseleave', function() {
$(self).popover('hide');
$(self).removeClass('active');
});
}).on('mouseleave', function() {
var self = this;
setTimeout(function() {
if (!$('.popover:hover').length) {
$(self).popover('hide');
$(self).removeClass('active');
}
}, 100);
});
// back to top
setTimeout(function() {
var $sideBar = $('.sidebar');
$sideBar.affix({
offset: {
top: function() {
var offsetTop = $sideBar.offset().top;
var sideBarMargin = parseInt($sideBar.children(0).css('margin-top'), 10);
var navOuterHeight = $('.site-navigation').height() + $('.masthead').height();
return (this.top = offsetTop - navOuterHeight - sideBarMargin);
},
bottom: function() {
return (this.bottom = $('.site-footer').outerHeight(true));
}
}
});
}, 100);
setTimeout(function() {
$('.top').affix();
}, 100);
});
}(jQuery)); |
package com.example.fotorsdkdemo;
import java.io.File;
import com.everimaging.fotorsdk.FotorConstants;
import com.everimaging.fotorsdk.FotorSDKActivity;
import com.everimaging.fotorsdk.FotorSDKVersion;
import com.everimaging.fotorsdk.FotorUtils;
import com.everimaging.fotorsdk.provider.<API key>;
import com.everimaging.fotorsdk.provider.<API key>.SessionColumns;
import com.everimaging.fotorsdk.provider.<API key>.SessionColumns.Session;
import com.everimaging.fotorsdk.utils.BitmapDecodeUtils;
import com.everimaging.fotorsdk.utils.Utils;
import com.everimaging.fotorsdk.engine.FotorHDFilter;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.<API key>;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Images.ImageColumns;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
/**
* Sample main activity
*
* @description
*
* @author <a href="mailto:zhangjiajun@everimaging.com">John.Zhang</a>
* @version 1.0
* @create Apr 12, 2014 3:06:39 PM
* @update Apr 12, 2014 3:06:39 PM
*/
public class MainActivity extends Activity {
private static final int <API key> = 2;
private static final int <API key> = 3;
public static final String LOG_TAG = "fotorsdk_demo";
/** Folder name on the sdcard where the images will be saved **/
private static final String FOLDER_NAME = "FotorSDK";
/** Edit sample button */
Button mEditButton;
/** Call gallery button */
Button mGalleryButton;
/** Display image view */
ImageView mImage;
/** The path for output file */
Uri mOutputFilePath;
/** Image uri for image editor */
Uri mImageUri;
/** Display version label for DEBUG */
private TextView mSDKVersionLabel;
/** The sample image uri. */
private Uri mSampleUri;
private File mGalleryFolder;
/** session id for the hi-res post processing */
private String mSessionId;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(LOG_TAG, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// if (mImageUri != null) {
// startFeature(mImageUri);
if (mSampleUri != null) {
startFeature(mSampleUri);
}
}
});
mGalleryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pickFromGallery();
}
});
mGalleryFolder = createFolders();
// add sample image
mSampleUri = Uri.parse("file:///android_asset/sample.jpg");
loadAsync(mSampleUri);
if (BuildConfig.DEBUG) {
mSDKVersionLabel.setText("V" + FotorSDKVersion.FOTOR_SDK_VERSION);
}
}
/**
* Start the activity to pick an image from the user gallery
*/
private void pickFromGallery() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
/**
* Handle the incoming {@link Intent}
*/
private void handleIntent(Intent intent) {
String action = intent.getAction();
if (null != action) {
if (Intent.ACTION_SEND.equals(action)) {
Bundle extras = intent.getExtras();
if (extras != null && extras.containsKey(Intent.EXTRA_STREAM)) {
Uri uri = (Uri) extras.get(Intent.EXTRA_STREAM);
loadAsync(uri);
}
} else if (Intent.ACTION_VIEW.equals(action)) {
Uri data = intent.getData();
Log.d(LOG_TAG, "data: " + data);
loadAsync(data);
}
}
}
/**
* Load the incoming Image
*
* @param uri
*/
private void loadAsync(final Uri uri) {
Log.i(LOG_TAG, "loadAsync: " + uri);
Drawable toRecycle = mImage.getDrawable();
if (toRecycle != null && toRecycle instanceof BitmapDrawable) {
if (((BitmapDrawable) mImage.getDrawable()).getBitmap() != null)
((BitmapDrawable) mImage.getDrawable()).getBitmap().recycle();
}
mImage.setImageDrawable(null);
mImageUri = null;
DownloadAsync task = new DownloadAsync();
task.execute(uri);
}
@Override
protected void onDestroy() {
Log.i(LOG_TAG, "onDestroy");
super.onDestroy();
mOutputFilePath = null;
}
@Override
public void onContentChanged() {
super.onContentChanged();
System.out.println("context:" + this.getPackageName());
mEditButton = (Button) findViewById(R.id.button2);
mGalleryButton = (Button) findViewById(R.id.button_gallery);
mImage = (ImageView) findViewById(R.id.image);
mSDKVersionLabel = (TextView) findViewById(R.id.<API key>);
}
@Override
/**
* This method is called when feather has completed ( ie. user clicked on "done" or just exit the activity without saving ). <br />
* If user clicked the "done" button you'll receive RESULT_OK as resultCode, RESULT_CANCELED otherwise.
*
* @param requestCode
* - it is the code passed with <API key>
* @param resultCode
* - result code of the activity launched ( it can be RESULT_OK or RESULT_CANCELED )
* @param data
* - the result data
*/
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case <API key>: {
Uri uri = data.getData();
Bitmap bitmap = BitmapDecodeUtils.decode(this, uri, 0, 0);
setImageURI(uri, bitmap);
new ProcessHDTask(this).execute();
}
break;
case <API key>: {
Uri uri = data.getData();
loadAsync(uri);
startFeature(uri);
}
break;
}
} else if (resultCode == RESULT_CANCELED) {
switch (requestCode) {
case <API key>:
if (mSessionId != null)
deleteSession(mSessionId);
break;
}
}
}
private String onSaveCompletion() {
Uri sessionUri = SessionColumns.getContentUri(this, mSessionId);
Cursor cursor = getContentResolver().query(sessionUri, null, null,
null, null);
Session session = Session.create(cursor);
if (session != null) {
FotorHDFilter fotorHDFilter = new FotorHDFilter(this, session);
fotorHDFilter.loadImage();
fotorHDFilter.executeFilter();
String dstPath = Utils.getSDPath() + "/testOriginal.jpg";
fotorHDFilter.save(dstPath);
fotorHDFilter.dispose();
deleteSession(mSessionId);
return dstPath;
}
return null;
}
class ProcessHDTask extends AsyncTask<Void, Void, String> {
private ProgressDialog mDialog;
private Context mContext;
public ProcessHDTask(Context context) {
this.mContext = context;
}
@Override
protected void onPreExecute() {
mDialog = ProgressDialog.show(mContext, "Process HD",
"Please wait...");
}
@Override
protected String doInBackground(Void... params) {
return onSaveCompletion();
}
@Override
protected void onPostExecute(String result) {
mDialog.dismiss();
String msg = "Process Error";
if (result != null) {
msg = result;
}
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
}
}
/**
* Delete the session and all it's actions. We do not need it anymore.<br />
* Note that this is optional. All old sessions are automatically removed in
* Feather.
*
* @param session_id
*/
private void deleteSession(final String session_id) {
Uri uri = <API key>.SessionColumns.getContentUri(this,
session_id);
int count = getContentResolver().delete(uri, null, null);
System.out.println("delete session count:" + count);
}
/**
* Given an Uri load the bitmap into the current ImageView and resize it to
* fit the image container size
*
* @param uri
*/
@SuppressWarnings("deprecation")
private boolean setImageURI(final Uri uri, final Bitmap bitmap) {
Log.d(LOG_TAG,
"image size: " + bitmap.getWidth() + "x" + bitmap.getHeight());
mImage.setImageBitmap(bitmap);
mImage.<API key>(null);
mEditButton.setEnabled(true);
mImageUri = uri;
return true;
}
/**
* We need to notify the MediaScanner when a new file is created. In this
* way all the gallery applications will be notified too.
*
* @param file
*/
private void updateMedia(String filepath) {
Log.i(LOG_TAG, "updateMedia: " + filepath);
<API key>.scanFile(<API key>(),
new String[] { filepath }, null, null);
}
/**
* Pick a random image from the user gallery
*
* @return
*/
@SuppressWarnings("unused")
private Uri pickRandomImage() {
Cursor c = getContentResolver().query(
Images.Media.<API key>,
new String[] { ImageColumns._ID, ImageColumns.DATA },
ImageColumns.SIZE + ">?", new String[] { "90000" }, null);
Uri uri = null;
if (c != null) {
int total = c.getCount();
int position = (int) (Math.random() * total);
Log.d(LOG_TAG, "pickRandomImage. total images: " + total
+ ", position: " + position);
if (total > 0) {
if (c.moveToPosition(position)) {
String data = c.getString(c
.getColumnIndex(Images.ImageColumns.DATA));
long id = c.getLong(c
.getColumnIndex(Images.ImageColumns._ID));
uri = Uri.parse(data);
Log.d(LOG_TAG, uri.toString());
}
}
c.close();
}
return uri;
}
/**
* Return a new image file. Name is based on the current time. Parent folder
* will be the one created with createFolders
*
* @return
* @see #createFolders()
*/
private File <API key>() {
if (mGalleryFolder != null) {
if (mGalleryFolder.exists()) {
File file = new File(mGalleryFolder, "Fotor_"
+ System.currentTimeMillis() + ".jpg");
return file;
}
}
return null;
}
/**
* Once you've chosen an image you can start the feather activity
*
* @param uri
*/
private void startFeature(Uri uri) {
Log.d(LOG_TAG, "uri: " + uri);
// first check the external storage availability
if (!<API key>()) {
new AlertDialog.Builder(this)
.setTitle(android.R.string.dialog_alert_title)
.setMessage("External Storage is not avilable").show();
return;
}
// create a temporary file where to store the resulting image
File file = <API key>();
if (null != file) {
mOutputFilePath = Uri.fromFile(file);
} else {
new AlertDialog.Builder(this)
.setTitle(android.R.string.dialog_alert_title)
.setMessage("Failed to create a new File").show();
return;
}
// Create the intent needed to start feather
Intent newIntent = new Intent(this, FotorSDKActivity.class);
// Set the source image uri
newIntent.setData(uri);
// Optional
// Pass the uri of the destination image file.
// This will be the same uri you will receive in the onActivityResult
System.out.println("mOutputFilePath->:" + mOutputFilePath);
// newIntent.putExtra(FotorConstants.EXTRA_OUTPUT_PATH,
// mOutputFilePath);
// Optional
newIntent.putExtra(FotorConstants.<API key>, 90);
// Optional
// you can pass the maximum allowed image size (for the preview),
// otherwise feather will determine
// the max size based on the device informations.
// This will not affect the hi-res image size.
// Here we're passing the current display size as max image size because
// after
// the execution of Aviary we're saving the HI-RES image so we don't
// need a big
// image for the preview
final DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int max_size = Math.max(metrics.widthPixels, metrics.heightPixels);
max_size = (int) ((float) max_size / 1.4f);
newIntent.putExtra(FotorConstants.<API key>, max_size);
mSessionId = FotorUtils.generateSessionId(this);
getContentResolver().delete(
SessionColumns.getContentUri(this, mSessionId), null, null);
Log.d(LOG_TAG,
"session: " + mSessionId + ", size: " + mSessionId.length());
newIntent.putExtra(FotorConstants.<API key>, mSessionId);
// newIntent.putExtra(FotorConstants.EXTRA_FEATURE_LIST, new String[] {
// <API key>.FeatureType.FX_EFFECTS.name(),
// <API key>.FeatureType.BORDER.name() });
// Whether hide confirm dialog when user not saved the was changed
// bitmap
// This default value will show
// newIntent.putExtra(FotorConstants.<API key>, false);
// Whether input image no changes,were made to the image.
// newIntent.putExtra(FotorConstants.<API key>, true);
// start feather
<API key>(newIntent, <API key>);
}
/**
* Check the external storage status
*
* @return
*/
private boolean <API key>() {
String state = Environment.<API key>();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/**
* Try to create the required folder on the sdcard where images will be
* saved to.
*
* @return
*/
private File createFolders() {
File baseDir;
if (android.os.Build.VERSION.SDK_INT < 8) {
baseDir = Environment.<API key>();
} else {
baseDir = Environment
.<API key>(Environment.DIRECTORY_PICTURES);
}
if (baseDir == null)
return Environment.<API key>();
Log.d(LOG_TAG, "Pictures folder: " + baseDir.getAbsolutePath());
File fotorSDKFolder = new File(baseDir, FOLDER_NAME);
if (fotorSDKFolder.exists())
return fotorSDKFolder;
if (fotorSDKFolder.mkdirs())
return fotorSDKFolder;
return Environment.<API key>();
}
class DownloadAsync extends AsyncTask<Uri, Void, Bitmap> implements
OnCancelListener {
ProgressDialog mProgress;
private Uri mUri;
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgress = new ProgressDialog(MainActivity.this);
mProgress.setIndeterminate(true);
mProgress.setCancelable(true);
mProgress.setMessage("Loading image...");
mProgress.setOnCancelListener(this);
mProgress.show();
}
@Override
protected Bitmap doInBackground(Uri... params) {
mUri = params[0];
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int maxW = (int) displayMetrics.widthPixels;
int maxH = (int) displayMetrics.heightPixels;
Bitmap bitmap = BitmapDecodeUtils.decode(<API key>(),
mUri, maxW, maxH);
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (mProgress.getWindow() != null) {
mProgress.dismiss();
}
if (result != null) {
setImageURI(mUri, result);
} else {
Toast.makeText(MainActivity.this,
"Failed to load image " + mUri, Toast.LENGTH_SHORT)
.show();
}
}
@Override
public void onCancel(DialogInterface dialog) {
Log.i(LOG_TAG, "onProgressCancel");
this.cancel(true);
}
@Override
protected void onCancelled() {
super.onCancelled();
Log.i(LOG_TAG, "onCancelled");
}
}
} |
#ifndef <API key>
#define <API key>
#include <map>
#include <memory>
#include <vector>
#include "include/v8.h"
#include "src/compiler-dispatcher/<API key>.h"
#include "src/globals.h"
#include "src/handles.h"
#include "src/parsing/<API key>.h"
namespace v8 {
class Extension;
namespace internal {
class AccountingAllocator;
class AstRawString;
class AstStringConstants;
class AstValueFactory;
class DeclarationScope;
class DeferredHandles;
class FunctionLiteral;
class RuntimeCallStats;
class ScriptData;
class SharedFunctionInfo;
class UnicodeCache;
class <API key>;
class Zone;
// A container for the inputs, configuration options, and outputs of parsing.
class V8_EXPORT_PRIVATE ParseInfo : public <API key> {
public:
explicit ParseInfo(AccountingAllocator* zone_allocator);
ParseInfo(Handle<Script> script);
ParseInfo(Handle<SharedFunctionInfo> shared);
// TODO(rmcilroy): Remove once Hydrogen no longer needs this.
ParseInfo(Handle<SharedFunctionInfo> shared, std::shared_ptr<Zone> zone);
~ParseInfo();
void InitFromIsolate(Isolate* isolate);
static ParseInfo* <API key>(Handle<SharedFunctionInfo> shared);
Zone* zone() const { return zone_.get(); }
std::shared_ptr<Zone> zone_shared() const { return zone_; }
void <API key>(std::shared_ptr<DeferredHandles> deferred_handles);
void <API key>(DeferredHandles* deferred_handles);
std::shared_ptr<DeferredHandles> deferred_handles() const {
return deferred_handles_;
}
// Convenience accessor methods for flags.
#define FLAG_ACCESSOR(flag, getter, setter) \
bool getter() const { return GetFlag(flag); } \
void setter() { SetFlag(flag); } \
void setter(bool val) { SetFlag(flag, val); }
FLAG_ACCESSOR(kToplevel, is_toplevel, set_toplevel)
FLAG_ACCESSOR(kEval, is_eval, set_eval)
FLAG_ACCESSOR(kStrictMode, is_strict_mode, set_strict_mode)
FLAG_ACCESSOR(kNative, is_native, set_native)
FLAG_ACCESSOR(kModule, is_module, set_module)
FLAG_ACCESSOR(kAllowLazyParsing, allow_lazy_parsing, <API key>)
FLAG_ACCESSOR(<API key>, <API key>,
<API key>)
FLAG_ACCESSOR(kIsNamedExpression, is_named_expression,
<API key>)
FLAG_ACCESSOR(kDebug, is_debug, set_is_debug)
FLAG_ACCESSOR(kSerializing, will_serialize, set_will_serialize)
FLAG_ACCESSOR(<API key>, <API key>,
<API key>)
#undef FLAG_ACCESSOR
void <API key>(ParseRestriction restriction) {
SetFlag(kParseRestriction, restriction != <API key>);
}
ParseRestriction parse_restriction() const {
return GetFlag(kParseRestriction) ? <API key>
: <API key>;
}
ScriptCompiler::<API key>* source_stream() const {
return source_stream_;
}
void set_source_stream(ScriptCompiler::<API key>* source_stream) {
source_stream_ = source_stream;
}
ScriptCompiler::StreamedSource::Encoding <API key>() const {
return <API key>;
}
void <API key>(
ScriptCompiler::StreamedSource::Encoding <API key>) {
<API key> = <API key>;
}
<API key>* character_stream() const { return character_stream_; }
void <API key>(<API key>* character_stream) {
character_stream_ = character_stream;
}
v8::Extension* extension() const { return extension_; }
void set_extension(v8::Extension* extension) { extension_ = extension; }
ScriptData** cached_data() const { return cached_data_; }
void set_cached_data(ScriptData** cached_data) { cached_data_ = cached_data; }
PreParsedScopeData* <API key>() { return &<API key>; }
ScriptCompiler::CompileOptions compile_options() const {
return compile_options_;
}
void set_compile_options(ScriptCompiler::CompileOptions compile_options) {
compile_options_ = compile_options;
}
DeclarationScope* script_scope() const { return script_scope_; }
void set_script_scope(DeclarationScope* script_scope) {
script_scope_ = script_scope;
}
DeclarationScope* asm_function_scope() const { return asm_function_scope_; }
void <API key>(DeclarationScope* scope) {
asm_function_scope_ = scope;
}
AstValueFactory* ast_value_factory() const { return ast_value_factory_; }
void <API key>(AstValueFactory* ast_value_factory) {
ast_value_factory_ = ast_value_factory;
}
const AstRawString* function_name() const { return function_name_; }
void set_function_name(const AstRawString* function_name) {
function_name_ = function_name;
}
FunctionLiteral* literal() const { return literal_; }
void set_literal(FunctionLiteral* literal) { literal_ = literal; }
DeclarationScope* scope() const;
UnicodeCache* unicode_cache() const { return unicode_cache_; }
void set_unicode_cache(UnicodeCache* unicode_cache) {
unicode_cache_ = unicode_cache;
}
uintptr_t stack_limit() const { return stack_limit_; }
void set_stack_limit(uintptr_t stack_limit) { stack_limit_ = stack_limit; }
uint32_t hash_seed() const { return hash_seed_; }
void set_hash_seed(uint32_t hash_seed) { hash_seed_ = hash_seed; }
int compiler_hints() const { return compiler_hints_; }
void set_compiler_hints(int compiler_hints) {
compiler_hints_ = compiler_hints;
}
int start_position() const { return start_position_; }
void set_start_position(int start_position) {
start_position_ = start_position;
}
int end_position() const { return end_position_; }
void set_end_position(int end_position) { end_position_ = end_position; }
int parameters_end_pos() const { return parameters_end_pos_; }
void <API key>(int parameters_end_pos) {
parameters_end_pos_ = parameters_end_pos;
}
int function_literal_id() const { return <API key>; }
void <API key>(int function_literal_id) {
<API key> = function_literal_id;
}
int <API key>() const { return <API key>; }
void <API key>(int <API key>) {
<API key> = <API key>;
}
const AstStringConstants* <API key>() const {
return <API key>;
}
void <API key>(
const AstStringConstants* <API key>) {
<API key> = <API key>;
}
RuntimeCallStats* runtime_call_stats() const { return runtime_call_stats_; }
void <API key>(RuntimeCallStats* runtime_call_stats) {
runtime_call_stats_ = runtime_call_stats;
}
// Getters for individual compiler hints.
bool is_declaration() const;
FunctionKind function_kind() const;
// TODO(titzer): these should not be part of ParseInfo.
Handle<SharedFunctionInfo> shared_info() const { return shared_; }
Handle<Script> script() const { return script_; }
MaybeHandle<ScopeInfo> <API key>() const {
return <API key>;
}
void clear_script() { script_ = Handle<Script>::null(); }
void set_shared_info(Handle<SharedFunctionInfo> shared) { shared_ = shared; }
void <API key>(Handle<ScopeInfo> outer_scope_info) {
<API key> = outer_scope_info;
}
void set_script(Handle<Script> script) { script_ = script; }
LanguageMode language_mode() const {
return <API key>(is_strict_mode());
}
void set_language_mode(LanguageMode language_mode) {
STATIC_ASSERT(LANGUAGE_END == 2);
set_strict_mode(is_strict(language_mode));
}
void <API key>() {
if (!script_.is_null()) {
script_ = Handle<Script>(*script_);
}
if (!shared_.is_null()) {
shared_ = Handle<SharedFunctionInfo>(*shared_);
}
Handle<ScopeInfo> outer_scope_info;
if (<API key>.ToHandle(&outer_scope_info)) {
<API key> = Handle<ScopeInfo>(*outer_scope_info);
}
}
void <API key>(Isolate* isolate);
// The key of the map is the FunctionLiteral's start_position
std::map<int, ParseInfo*> child_infos() const;
void ParseFinished(std::unique_ptr<ParseInfo> info) override;
#ifdef DEBUG
bool script_is_native() const;
#endif // DEBUG
private:
// Various configuration flags for parsing.
enum Flag {
kToplevel = 1 << 0,
kLazy = 1 << 1,
kEval = 1 << 2,
kStrictMode = 1 << 3,
kNative = 1 << 4,
kParseRestriction = 1 << 5,
kModule = 1 << 6,
kAllowLazyParsing = 1 << 7,
kIsNamedExpression = 1 << 8,
kDebug = 1 << 9,
kSerializing = 1 << 10,
<API key> = 1 << 11,
<API key> = 1 << 12,
};
std::shared_ptr<Zone> zone_;
unsigned flags_;
ScriptCompiler::<API key>* source_stream_;
ScriptCompiler::StreamedSource::Encoding <API key>;
<API key>* character_stream_;
v8::Extension* extension_;
ScriptCompiler::CompileOptions compile_options_;
DeclarationScope* script_scope_;
DeclarationScope* asm_function_scope_;
UnicodeCache* unicode_cache_;
uintptr_t stack_limit_;
uint32_t hash_seed_;
int compiler_hints_;
int start_position_;
int end_position_;
int parameters_end_pos_;
int <API key>;
int <API key>;
// TODO(titzer): Move handles out of ParseInfo.
Handle<SharedFunctionInfo> shared_;
Handle<Script> script_;
MaybeHandle<ScopeInfo> <API key>;
ScriptData** cached_data_; // used if available, populated if requested.
PreParsedScopeData <API key>;
AstValueFactory* ast_value_factory_; // used if available, otherwise new.
const class AstStringConstants* <API key>;
const AstRawString* function_name_;
RuntimeCallStats* runtime_call_stats_;
FunctionLiteral* literal_;
std::shared_ptr<DeferredHandles> deferred_handles_;
std::vector<std::unique_ptr<ParseInfo>> child_infos_;
mutable base::Mutex child_infos_mutex_;
void SetFlag(Flag f) { flags_ |= f; }
void SetFlag(Flag f, bool v) { flags_ = v ? flags_ | f : flags_ & ~f; }
bool GetFlag(Flag f) const { return (flags_ & f) != 0; }
};
} // namespace internal
} // namespace v8
#endif // <API key> |
<%
var od,on;
on = order[0];
od = order[1];
%>
<table width="100%" class="table table-striped table-hover">
<tr>
<th width="30"></th>
<th>
<a href="#<%+prep%>prep=1&uid=<%+uid%>&gid=<%+gid%>&fdid=<%+fdid%>&on=name&od=<%if(on=='name' && od == 1){%>-1<%}else{%>1<%}%>">
<span></span>
<%if(on == 'name' && od== 1){%>
<i class="ad"></i>
<%}else if(on =='name' && od== -1){%>
<i class="au"></i>
<%}else{%>
<i class="ad"></i>
<%}%>
</a>
</th>
<%if(gid){%>
<th width="60"></th>
<th width="60"></th>
<th width="60"></th>
<%}%>
<th width="90">
<a href="#<%+prep%>prep=1&uid=<%+uid%>&gid=<%+gid%>&fdid=<%+fdid%>&on=type&od=<%if(on=='type' && od ==1 ){%>-1<%}else{%>1<%}%>">
<span></span>
<%if(on == 'type' && od== 1){%>
<i class="ad"></i>
<%}else if(on =='type' && od== -1){%>
<i class="au"></i>
<%}else{%>
<i class="ad"></i>
<%}%>
</a>
</th>
<th width="90">
<a href="#<%+prep%>prep=1&uid=<%+uid%>&gid=<%+gid%>&fdid=<%+fdid%>&on=size&od=<%if(on=='size' && od == 1){%>-1<%}else{%>1<%}%>">
<span></span>
<%if(on == 'size' && od== 1){%>
<i class="ad"></i>
<%}else if(on =='size' && od== -1){%>
<i class="au"></i>
<%}else{%>
<i class="ad"></i>
<%}%>
</a>
</th>
<th width="150" align="right">
<a href="#<%+prep%>prep=1&gid=<%+gid%>&uid=<%+uid%>&&fdid=<%+fdid%>&on=createTime&od=<%if(on=='createTime' && od ==1){%>-1<%}else{%>1<%}%>">
<span></span>
<%if(on == 'createTime' && od==1){%>
<i class="ad"></i>
<%}else if(on =='createTime' && od== -1){%>
<i class="au"></i>
<%}else{%>
<i class="ad"></i>
<%}%>
</a>
</th>
</tr>
</table> |
layout: page
title: Privacy Policy
permalink: privacy-policy.html
exclude_from_nav: true
Your privacy is important to us. We handle information provided by you,
our customer, in a confidential manner. We do not rent or sell any personal information to any other organization.
Any personal information gathered will be used for order processing, to address inquiries, for product or status updates, for sweepstakes, newsletter, coupons, and/or other reoccurring correspondence (if opted-in by customer). At any time you, the customer, can opt out.
Some ways that we might need to share your information with a third party are listed below:
- With carefully selected companies that offer support services to us. These include payment processors including credit card processors, website hosts and/or mailing houses, and any platform on which our technology is hosted or created.
- With your consent and as necessary to complete transactions requested by you.
- If required by law.
- If necessary to protect our intellectual rights and/or property.
- In the case of a transfer of business assets, information may be provided to parties involved in the negotiation and transfer.
- Any comments made on our site or information posted by you will be visible to others visiting the site.
Additionally, we might share anonymized information and/or aggregated information to help us deliver the best experience to you that we can. But don't worry; this information will not directly identify you. By choosing to use our site and/or technology, you agree to the privacy policy as outlined above. |
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.09.26 at 03:01:37 PM PKT
package com.aspose.slides.maven.artifacts;
import javax.xml.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"groupId",
"artifactId",
"version",
"versioning",
"classifier"
})
@XmlRootElement(name = "metadata")
public class Metadata {
@XmlElement(required = true)
protected String groupId;
@XmlElement(required = true)
protected String artifactId;
@XmlElement(required = true)
protected String version;
@XmlElement(required = true)
protected Metadata.Versioning versioning;
protected String classifier;
/**
* Gets the value of the groupId property.
*
* @return possible object is {@link String }
*/
public String getGroupId() {
return groupId;
}
/**
* Sets the value of the groupId property.
*
* @param value allowed object is {@link String }
*/
public void setGroupId(String value) {
this.groupId = value;
}
/**
* Gets the value of the artifactId property.
*
* @return possible object is {@link String }
*/
public String getArtifactId() {
return artifactId;
}
/**
* Sets the value of the artifactId property.
*
* @param value allowed object is {@link String }
*/
public void setArtifactId(String value) {
this.artifactId = value;
}
/**
* Gets the value of the version property.
*
* @return possible object is {@link String }
*/
public String getVersion() {
return version;
}
/**
* Sets the value of the version property.
*
* @param value allowed object is {@link String }
*/
public void setVersion(String value) {
this.version = value;
}
/**
* Gets the value of the versioning property.
*
* @return possible object is {@link Metadata.Versioning }
*/
public Metadata.Versioning getVersioning() {
return versioning;
}
/**
* Sets the value of the versioning property.
*
* @param value allowed object is {@link Metadata.Versioning }
*/
public void setVersioning(Metadata.Versioning value) {
this.versioning = value;
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"latest",
"release",
"versions",
"lastUpdated"
})
public static class Versioning {
@XmlElement(required = true)
protected String latest;
@XmlElement(required = true)
protected String release;
@XmlElement(required = true)
protected Metadata.Versioning.Versions versions;
protected long lastUpdated;
/**
* Gets the value of the latest property.
*
* @return possible object is {@link String }
*/
public String getLatest() {
return latest;
}
/**
* Sets the value of the latest property.
*
* @param value allowed object is {@link String }
*/
public void setLatest(String value) {
this.latest = value;
}
/**
* Gets the value of the release property.
*
* @return possible object is {@link String }
*/
public String getRelease() {
return release;
}
/**
* Sets the value of the release property.
*
* @param value allowed object is {@link String }
*/
public void setRelease(String value) {
this.release = value;
}
/**
* Gets the value of the versions property.
*
* @return possible object is {@link Metadata.Versioning.Versions }
*/
public Metadata.Versioning.Versions getVersions() {
return versions;
}
/**
* Sets the value of the versions property.
*
* @param value allowed object is {@link Metadata.Versioning.Versions }
*/
public void setVersions(Metadata.Versioning.Versions value) {
this.versions = value;
}
/**
* Gets the value of the lastUpdated property.
* @return
*/
public long getLastUpdated() {
return lastUpdated;
}
/**
* Sets the value of the lastUpdated property.
* @param value
*/
public void setLastUpdated(long value) {
this.lastUpdated = value;
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"version"
})
public static class Versions {
protected List<String> version;
/**
* Gets the value of the version property.
* <p/>
* <p/>
* This accessor method returns a reference to the live list, not a
* snapshot. Therefore any modification you make to the returned
* list will be present inside the JAXB object. This is why there is
* not a <CODE>set</CODE> method for the version property.
* <p/>
* <p/>
* For example, to add a new item, do as follows:
* <pre>
* getVersion().add(newItem);
* </pre>
* <p/>
* <p/>
* <p/>
* Objects of the following type(s) are allowed in the list
* {@link String }
* @return
*/
public List<String> getVersion() {
if (version == null) {
version = new ArrayList<String>();
}
return this.version;
}
}
}
/**
* Gets the value of the classifier property.
*
* @return possible object is {@link String }
*/
public String getClassifier() {
return classifier;
}
/**
* Sets the value of the version property.
*
* @param value allowed object is {@link String }
*/
public void setClassifier(String value) {
this.classifier = value;
}
} |
/*
* <auto-generated>
* This code was generated by a tool.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
* </auto-generated>
*/
#import <Foundation/Foundation.h>
#import "JSONModel.h"
#import "<API key>.h"
@protocol <API key>
@end
/**
The current state of the product purchase determines whether or not the product is eligible for purchase. Products with options are only purchasable if the shopper has selected all required options. If the product is not ready for purchase, a message lists missing options that are required.
*/
@interface <API key> : JSONModel<<API key>>
/**
If true, the entity has met all requirements and considered a purchasable entity.
*/
@property(nonatomic) BOOL isPurchasable;
/**
Array list of validation and status messages associated with shipping rates, orders, and product purchasable state.
*/
@property(nonatomic) NSArray<<API key>> *messages;
@end |
/**
* @file ttscon.h
* @brief
*
* detail...
*
* @author lygao
* @version 1.0
* @date 2005-12-6
*
* @see
*
* <b>History:</b><br>
* <table>
* <tr> <th>Version <th>Date <th>Author <th>Notes</tr>
* <tr> <td>1.0 <td>2005-12-6 <td>lygao <td>Create this file</tr>
* </table>
*
*/
#ifndef __TTS_CONSOLE_H__
#define __TTS_CONSOLE_H__
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <limits.h>
#include <errno.h>
#include <iostream>
#ifndef WIN32
#include <pthread.h>
#include <unistd.h>
typedef int BOOL;
#else //WIN32
#include <windows.h>
#define PATH_MAX _MAX_PATH
#endif//WIN32
#include "iFly_TTS.h"
#include "FileVerInfo.h"
#include "ttscon_utils.h"//Added by lygao, 2005-11-16 14:53:33
typedef char *LPTSTR;
typedef const char *LPCTSTR;
typedef unsigned char *PBYTE;
const int MAX_TXT_BUFFER = 0x10000;
const int MAX_TTS_PARAM = (TTS_PARAM_BGSOUND+1);
#define TTS_WORD_LE_BE(val) ((TTSWORD) ( (((TTSWORD) (val) & (TTSWORD) 0x00ffU) << 8) | \
(((TTSWORD) (val) & (TTSWORD) 0xff00U) >> 8)))
#define TTS_DWORD_LE_BE(val) ((TTSDWORD) ( (((TTSDWORD) (val) & (TTSDWORD) 0x000000ffU) << 24) | \
(((TTSDWORD) (val) & (TTSDWORD) 0x0000ff00U) << 8) | \
(((TTSDWORD) (val) & (TTSDWORD) 0x00ff0000U) >> 8) | \
(((TTSDWORD) (val) & (TTSDWORD) 0xff000000U) >> 24)))
enum ETTSSynthMode {
tsmTradition = 0, // No Callback and synchronous synthesize
tsmCbSynch, // Callback and synchronous synthesize
tsmCbAsynch // Callback and asynchronous synthesize
};
enum ETTSCON_PARAM_TYPE
{
PARAM_INVALID = 0,
PARAM_MODE = 1,
PARAM_VID = 2,
PARAM_CODEPAGE = 3,
PARAM_AUDIOFMT = 4,
PARAM_SPEED = 5,
PARAM_VOLUMN = 6,
PARAM_PITCH = 7,
PARAM_ENTER = 8,
PARAM_LENGTH = 9,
PARAM_MARKS = 10,
PARAM_NUMBER = 11,
PARAM_ENGLISH = 12,
PARAM_BGS = 13,
PARAM_VPT = 14,
PARAM_RAW = 15,
PARAM_IP = 16,
PARAM_Y = 17,
PARAM_LIBRARY = 18,
PARAM_ROUNDS = 19,
PARAM_ASYNCONN = 20,
PARAM_ASYNDISCON = 21,
PARAM_FILTER = 22,
PARAM_AHF = 23,
PARAM_CONNSTR = 24,
PARAM_USRLIB = 25,
PARAM_BYTEORDER = 26,
};
enum <API key>
{
VALUE_INVALID = 0,
VALUE_VACANT = 1, // parameter doesn't have value
VALUE_NUMERIC = 2, // the value of parameter is numeric
VALUE_NONNUMERIC = 3 // the value of parameter isn't numeric
};
const struct PARAMLIST {
const char* name; // name of parameter
ETTSCON_PARAM_TYPE type; // type of parameter
<API key> value; // type of parameter's value
const char* tip; // explanation of parameter
} param_list[] = {
"-m", PARAM_MODE, VALUE_NUMERIC, "Set synthesize mode",
"-mode", PARAM_MODE, VALUE_NUMERIC, "Set synthesize mode",
"-i", PARAM_VID, VALUE_NUMERIC, "Set current voice token ID(VID)",
"-vid", PARAM_VID, VALUE_NUMERIC, "Set current voice token ID(VID)",
"-c", PARAM_CODEPAGE, VALUE_NUMERIC, "Set current Chinese code page type",
"-cp", PARAM_CODEPAGE, VALUE_NUMERIC, "Set current Chinese code page type",
"-codepage", PARAM_CODEPAGE, VALUE_NUMERIC, "Set current Chinese code page type",
"-f", PARAM_AUDIOFMT, VALUE_NUMERIC, "Set current audio data format",
"-adf", PARAM_AUDIOFMT, VALUE_NUMERIC, "Set current audio data format",
"-audiofmt", PARAM_AUDIOFMT, VALUE_NUMERIC, "Set current audio data format",
"-d", PARAM_SPEED, VALUE_NUMERIC, "Set current speed value",
"-speed", PARAM_SPEED, VALUE_NUMERIC, "Set current speed value",
"-v", PARAM_VOLUMN, VALUE_NUMERIC, "Set current volume of output voice",
"-volumn", PARAM_VOLUMN, VALUE_NUMERIC, "Set current volume of output voice",
"-p", PARAM_PITCH, VALUE_NUMERIC, "Set current pitch of output voice",
"-pitch", PARAM_PITCH, VALUE_NUMERIC, "Set current pitch of output voice",
"-b", PARAM_ENTER, VALUE_NUMERIC, "Set treatment of <enter> char when spliting sentence",
"-enter", PARAM_ENTER, VALUE_NUMERIC, "Set treatment of <enter> char when spliting sentence",
"-l", PARAM_LENGTH, VALUE_NUMERIC, "Set maximal length of the split sentence",
"-len", PARAM_LENGTH, VALUE_NUMERIC, "Set maximal length of the split sentence",
"-length", PARAM_LENGTH, VALUE_NUMERIC, "Set maximal length of the split sentence",
"-k", PARAM_MARKS, VALUE_NUMERIC, "Set whether to read all marks or not",
"-marks", PARAM_MARKS, VALUE_NUMERIC, "Set whether to read all marks or not",
"-n", PARAM_NUMBER, VALUE_NUMERIC, "Set how to pronounce numeric string",
"-number", PARAM_NUMBER, VALUE_NUMERIC, "Set how to pronounce numeric string",
"-e", PARAM_ENGLISH, VALUE_NUMERIC, "Set How to pronounce English (letter or word) ",
"-english", PARAM_ENGLISH, VALUE_NUMERIC, "Set How to pronounce English (letter or word) ",
"-s", PARAM_BGS, VALUE_NUMERIC, "Set to choose which BGS can be used",
"-bgs", PARAM_BGS, VALUE_NUMERIC, "Set to choose which BGS can be used",
"-u", PARAM_VPT, VALUE_NUMERIC, "Set whether to enable VPT or not",
"-vpt", PARAM_VPT, VALUE_NUMERIC, "Set whether to enable VPT or not",
"-o", PARAM_RAW, VALUE_NUMERIC, "Set output audio data type,WINDOWS PCM or PCM Raw data",
"-raw", PARAM_RAW, VALUE_NUMERIC, "Set output audio data type,WINDOWS PCM or PCM Raw data",
"-r", PARAM_IP, VALUE_NONNUMERIC, "Set Remote TTSServer IP",
"-ip", PARAM_IP, VALUE_NONNUMERIC, "Set Remote TTSServer IP",
"-y", PARAM_Y, VALUE_VACANT, "Overwrite file without prompt",
"-lib", PARAM_LIBRARY, VALUE_NONNUMERIC, "Set library of Iflytek to load",
"-library", PARAM_LIBRARY, VALUE_NONNUMERIC, "Set library of Iflytek to load",
"-t", PARAM_BYTEORDER, VALUE_NUMERIC, "Set byteorder,2 for sun/mach",
"-byteorder", PARAM_BYTEORDER, VALUE_NUMERIC, "Set byteorder,2 for sun/mach",
//Deleted by hyxiong, 2006-12-3 10:43:44
/*"-rounds", PARAM_ROUNDS, VALUE_NUMERIC, "Set times of synthesization",
"-asynconn", PARAM_ASYNCONN, VALUE_VACANT, "Set asynchronous connection",
"-asyndiscon",PARAM_ASYNDISCON, VALUE_VACANT, "Set asynchronous disconnection",
"-filter", PARAM_FILTER, VALUE_NONNUMERIC, "Set TTS Service sign",
"-ahf", PARAM_AHF, VALUE_NUMERIC, "Set audio head format",
"-connstr", PARAM_CONNSTR, VALUE_NONNUMERIC, "Set connect string",*/
//Deleted End by hyxiong
"-usrlib", PARAM_USRLIB, VALUE_NONNUMERIC, "Set user's library to load",
};
inline bool IsLittleEndian( )
{
TTSDWORD dwTestValue = 0xFF000000;
return *((char*)(&dwTestValue))==0;
}
#endif // __TTS_CONSOLE_H__ |
namespace Decoding
{
using System;
using System.Globalization;
using System.IO;
using System.Threading;
public class DecodingProblem
{
<exception cref="IOException">An I/O error occurred. </exception>
<exception cref="<API key>">There is insufficient memory to allocate a buffer for the returned string. </exception>
<exception cref="ArgumentException">Invalid number</exception>
public static void Main()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
int salt;
bool validNumberInput = int.TryParse(Console.ReadLine(), out salt);
if (!validNumberInput)
{
throw new ArgumentException("Invalid number");
}
string input = Console.ReadLine();
if (input == null)
{
throw new ArgumentException("Invalid input");
}
for (int i = 0; i < input.Length; i++)
{
if (input[i] == '@')
{
break;
}
double number;
if (char.IsLetter(input[i]))
{
number = (Convert.ToInt32(input[i]) * salt) + 1000;
}
else if (char.IsDigit(input[i]))
{
number = Convert.ToInt32(input[i]) + salt + 500;
}
else
{
number = Convert.ToInt32(input[i]) - salt;
}
PrintDecodedNumber(i, number);
}
}
private static void PrintDecodedNumber(int charIndex, double number)
{
if (charIndex % 2 == 0)
{
double decodedNumber = number / 100;
Console.WriteLine("{0:F2}", decodedNumber);
}
else
{
double decodedNumber = number * 100;
Console.WriteLine("{0}", decodedNumber);
}
}
}
} |
#Welcome to vRAAPIClient
A python wrapper for the vRealize Automation REST API
Currently there is support for the following API endpoints:
* Catalog-Service Consumer API client: Request and view resources
* Reservation-Service API client: Create and view reservations
Responses will be in JSON or formatted in a table layout. This can be changed by
using the show="json" / show="table" parameter on some functions. This is not fully
implimented yet so make sure you read the classes to know which functions support
it.
Please see Basic Usage for some examples of this!
#vRA REST API Reference
This project has been built by following the vRA REST API Reference provided by
VMware.
Please take some time to familiarize yourself with it: [here](http://pubs.vmware.com/vra-62/index.jsp#com.vmware.vra.restapi.doc/index.html) |
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Octokit
{
<summary>
A client for GitHub's Issue Comments API.
</summary>
<remarks>
See the <a href="http://developer.github.com/v3/issues/comments/">Issue Comments API documentation</a> for more information.
</remarks>
public class IssueCommentsClient : ApiClient, <API key>
{
<summary>
Instantiates a new GitHub Issue Comments API client.
</summary>
<param name="apiConnection">An API connection</param>
public IssueCommentsClient(IApiConnection apiConnection) : base(apiConnection)
{
}
<summary>
Gets a single Issue Comment by id.
</summary>
<remarks>http://developer.github.com/v3/issues/comments/#<API key></remarks>
<param name="owner">The owner of the repository</param>
<param name="name">The name of the repository</param>
<param name="id">The issue comment id</param>
public Task<IssueComment> Get(string owner, string name, int id)
{
Ensure.<API key>(owner, "owner");
Ensure.<API key>(name, "name");
return ApiConnection.Get<IssueComment>(ApiUrls.IssueComment(owner, name, id), null, AcceptHeaders.ReactionsPreview);
}
<summary>
Gets a single Issue Comment by id.
</summary>
<remarks>http://developer.github.com/v3/issues/comments/#<API key></remarks>
<param name="repositoryId">The Id of the repository</param>
<param name="id">The issue comment id</param>
public Task<IssueComment> Get(int repositoryId, int id)
{
return ApiConnection.Get<IssueComment>(ApiUrls.IssueComment(repositoryId, id), null, AcceptHeaders.ReactionsPreview);
}
<summary>
Gets Issue Comments for a repository.
</summary>
<remarks>http://developer.github.com/v3/issues/comments/#<API key></remarks>
<param name="owner">The owner of the repository</param>
<param name="name">The name of the repository</param>
public Task<IReadOnlyList<IssueComment>> GetAllForRepository(string owner, string name)
{
Ensure.<API key>(owner, "owner");
Ensure.<API key>(name, "name");
return GetAllForRepository(owner, name, ApiOptions.None);
}
<summary>
Gets Issue Comments for a repository.
</summary>
<remarks>http://developer.github.com/v3/issues/comments/#<API key></remarks>
<param name="repositoryId">The Id of the repository</param>
public Task<IReadOnlyList<IssueComment>> GetAllForRepository(int repositoryId)
{
return GetAllForRepository(repositoryId, ApiOptions.None);
}
<summary>
Gets Issue Comments for a repository.
</summary>
<remarks>http://developer.github.com/v3/issues/comments/#<API key></remarks>
<param name="owner">The owner of the repository</param>
<param name="name">The name of the repository</param>
<param name="options">Options for changing the API response</param>
public Task<IReadOnlyList<IssueComment>> GetAllForRepository(string owner, string name, ApiOptions options)
{
Ensure.<API key>(owner, "owner");
Ensure.<API key>(name, "name");
Ensure.ArgumentNotNull(options, "options");
return ApiConnection.GetAll<IssueComment>(ApiUrls.IssueComments(owner, name), null, AcceptHeaders.ReactionsPreview, options);
}
<summary>
Gets Issue Comments for a repository.
</summary>
<remarks>http://developer.github.com/v3/issues/comments/#<API key></remarks>
<param name="repositoryId">The Id of the repository</param>
<param name="options">Options for changing the API response</param>
public Task<IReadOnlyList<IssueComment>> GetAllForRepository(int repositoryId, ApiOptions options)
{
Ensure.ArgumentNotNull(options, "options");
return ApiConnection.GetAll<IssueComment>(ApiUrls.IssueComments(repositoryId), null, AcceptHeaders.ReactionsPreview, options);
}
<summary>
Gets Issue Comments for a specified Issue.
</summary>
<remarks>http://developer.github.com/v3/issues/comments/#<API key></remarks>
<param name="owner">The owner of the repository</param>
<param name="name">The name of the repository</param>
<param name="number">The issue number</param>
public Task<IReadOnlyList<IssueComment>> GetAllForIssue(string owner, string name, int number)
{
Ensure.<API key>(owner, "owner");
Ensure.<API key>(name, "name");
return GetAllForIssue(owner, name, number, ApiOptions.None);
}
<summary>
Gets Issue Comments for a specified Issue.
</summary>
<remarks>http://developer.github.com/v3/issues/comments/#<API key></remarks>
<param name="repositoryId">The Id of the repository</param>
<param name="number">The issue number</param>
public Task<IReadOnlyList<IssueComment>> GetAllForIssue(int repositoryId, int number)
{
return GetAllForIssue(repositoryId, number, ApiOptions.None);
}
<summary>
Gets Issue Comments for a specified Issue.
</summary>
<remarks>http://developer.github.com/v3/issues/comments/#<API key></remarks>
<param name="owner">The owner of the repository</param>
<param name="name">The name of the repository</param>
<param name="number">The issue number</param>
<param name="options">Options for changing the API response</param>
public Task<IReadOnlyList<IssueComment>> GetAllForIssue(string owner, string name, int number, ApiOptions options)
{
Ensure.<API key>(owner, "owner");
Ensure.<API key>(name, "name");
Ensure.ArgumentNotNull(options, "options");
return ApiConnection.GetAll<IssueComment>(ApiUrls.IssueComments(owner, name, number), null, AcceptHeaders.ReactionsPreview, options);
}
<summary>
Gets Issue Comments for a specified Issue.
</summary>
<remarks>http://developer.github.com/v3/issues/comments/#<API key></remarks>
<param name="repositoryId">The Id of the repository</param>
<param name="number">The issue number</param>
<param name="options">Options for changing the API response</param>
public Task<IReadOnlyList<IssueComment>> GetAllForIssue(int repositoryId, int number, ApiOptions options)
{
Ensure.ArgumentNotNull(options, "options");
return ApiConnection.GetAll<IssueComment>(ApiUrls.IssueComments(repositoryId, number), null, AcceptHeaders.ReactionsPreview, options);
}
<summary>
Creates a new Issue Comment for a specified Issue.
</summary>
<remarks>http://developer.github.com/v3/issues/comments/#create-a-comment</remarks>
<param name="owner">The owner of the repository</param>
<param name="name">The name of the repository</param>
<param name="number">The number of the issue</param>
<param name="newComment">The new comment to add to the issue</param>
public Task<IssueComment> Create(string owner, string name, int number, string newComment)
{
Ensure.<API key>(owner, "owner");
Ensure.<API key>(name, "name");
Ensure.ArgumentNotNull(newComment, "newComment");
return ApiConnection.Post<IssueComment>(ApiUrls.IssueComments(owner, name, number), new BodyWrapper(newComment));
}
<summary>
Creates a new Issue Comment for a specified Issue.
</summary>
<remarks>http://developer.github.com/v3/issues/comments/#create-a-comment</remarks>
<param name="repositoryId">The Id of the repository</param>
<param name="number">The number of the issue</param>
<param name="newComment">The new comment to add to the issue</param>
public Task<IssueComment> Create(int repositoryId, int number, string newComment)
{
Ensure.ArgumentNotNull(newComment, "newComment");
return ApiConnection.Post<IssueComment>(ApiUrls.IssueComments(repositoryId, number), new BodyWrapper(newComment));
}
<summary>
Updates a specified Issue Comment.
</summary>
<remarks>http://developer.github.com/v3/issues/comments/#edit-a-comment</remarks>
<param name="owner">The owner of the repository</param>
<param name="name">The name of the repository</param>
<param name="id">The comment id</param>
<param name="commentUpdate">The modified comment</param>
public Task<IssueComment> Update(string owner, string name, int id, string commentUpdate)
{
Ensure.<API key>(owner, "owner");
Ensure.<API key>(name, "name");
Ensure.ArgumentNotNull(commentUpdate, "commentUpdate");
return ApiConnection.Patch<IssueComment>(ApiUrls.IssueComment(owner, name, id), new BodyWrapper(commentUpdate));
}
<summary>
Updates a specified Issue Comment.
</summary>
<remarks>http://developer.github.com/v3/issues/comments/#edit-a-comment</remarks>
<param name="repositoryId">The Id of the repository</param>
<param name="id">The comment id</param>
<param name="commentUpdate">The modified comment</param>
public Task<IssueComment> Update(int repositoryId, int id, string commentUpdate)
{
Ensure.ArgumentNotNull(commentUpdate, "commentUpdate");
return ApiConnection.Patch<IssueComment>(ApiUrls.IssueComment(repositoryId, id), new BodyWrapper(commentUpdate));
}
<summary>
Deletes the specified Issue Comment
</summary>
<remarks>http://developer.github.com/v3/issues/comments/#delete-a-comment</remarks>
<param name="owner">The owner of the repository</param>
<param name="name">The name of the repository</param>
<param name="id">The comment id</param>
public Task Delete(string owner, string name, int id)
{
Ensure.<API key>(owner, "owner");
Ensure.<API key>(name, "name");
return ApiConnection.Delete(ApiUrls.IssueComment(owner, name, id));
}
<summary>
Deletes the specified Issue Comment
</summary>
<remarks>http://developer.github.com/v3/issues/comments/#delete-a-comment</remarks>
<param name="repositoryId">The Id of the repository</param>
<param name="id">The comment id</param>
public Task Delete(int repositoryId, int id)
{
return ApiConnection.Delete(ApiUrls.IssueComment(repositoryId, id));
}
}
} |
import demistomock as demisto
from CommonServerPython import *
import subprocess
import re
def main():
try:
dest = demisto.args()['address']
ping_out = subprocess.check_output(
['ping', '-c', '3', '-q', dest], stderr=subprocess.STDOUT, universal_newlines=True
)
s = re.search(r"PING.*?\((.+?)\)", ping_out)
res = {}
if s:
res['destination_ip'] = s.group(1)
s = re.search(r"rtt min/avg/max/mdev = (.+)/(.+)/(.+)/(.+)\s+ms", ping_out)
if not s:
raise ValueError("Couldn't parse ping statistics:\n" + ping_out)
res['ret_code'] = '0'
res['destination'] = dest
res['min_rtt'] = s.group(1)
res['avg_rtt'] = s.group(2)
res['max_rtt'] = s.group(3)
res['mdev_rtt'] = s.group(4)
return_outputs(readable_output=tableToMarkdown("Ping Results", res), outputs={"Ping": res}, raw_response=res)
except Exception as e:
if isinstance(e, subprocess.CalledProcessError):
msg = e.output # pylint: disable=no-member
else:
msg = str(e)
return_error(msg)
# python2 uses __builtin__ python3 uses builtins
if __name__ == "__builtin__" or __name__ == "builtins":
main() |
<?php
namespace Aggressiveswallow;
/**
* Interface for storing data, doesn't matter if it is memory, db or file.
* @author Patrick
*/
interface <API key> {
/**
*
* @param mixed $data The data to be persisted
* @return mixed The key to retrieve the data with
*/
function persist($data);
/**
*
* @param mixed $key The key to retrieve data with
* @return mixed The data for the key.
*/
function retreive($key);
/**
*
* @param mixed $key The key for the data to destroy
*/
function destroy($key);
} |
#!/usr/bin/env python
"""
Twython is a library for Python that wraps the Twitter API.
It aims to abstract away all the API endpoints, so that additions to the library
and/or the Twitter API won't cause any overall problems.
Questions, comments? ryan@venodesigns.net
"""
__author__ = "Ryan McGrath <ryan@venodesigns.net>"
__version__ = "2.3.4"
import urllib
import re
import warnings
import requests
from requests.auth import OAuth1
try:
from urlparse import parse_qsl
except ImportError:
from cgi import parse_qsl
# Twython maps keyword based arguments to Twitter API endpoints. The endpoints
# table is a file with a dictionary of every API endpoint that Twython supports.
from <TwitterConsumerkey> import base_url, api_table, <TwitterConsumerkey>
try:
import simplejson
except ImportError:
try:
# Python 2.6 and up
import json as simplejson
except ImportError:
try:
from django.utils import simplejson
except:
# Seriously wtf is wrong with you if you get this Exception.
raise Exception("Twython requires the simplejson library (or Python 2.6) to work. http:
class TwythonError(Exception):
"""
Generic error class, catch-all for most Twython issues.
Special cases are handled by TwythonAPILimit and TwythonAuthError.
Note: To use these, the syntax has changed as of Twython 1.3. To catch these,
you need to explicitly import them into your code, e.g:
from twython import TwythonError, TwythonAPILimit, TwythonAuthError
"""
def __init__(self, msg, error_code=None, retry_after=None):
self.msg = msg
self.error_code = error_code
if error_code is not None and error_code in <TwitterConsumerkey>:
self.msg = '%s: %s
(<TwitterConsumerkey>[error_code][0],
<TwitterConsumerkey>[error_code][1],
self.msg)
def __str__(self):
return repr(self.msg)
class TwythonAuthError(TwythonError):
""" Raised when you try to access a protected resource and it fails due to
some issue with your authentication.
"""
pass
class <API key>(TwythonError):
""" Raised when you've hit a rate limit.
retry_wait_seconds is the number of seconds to wait before trying again.
"""
def __init__(self, msg, error_code, retry_after=None):
TwythonError.__init__(self, msg, error_code=error_code)
if isinstance(retry_after, int):
self.msg = '%s (Retry after %d seconds)' % (msg, retry_after)
class Twython(object):
def __init__(self, app_key=None, app_secret=None, oauth_token=None, oauth_token_secret=None, \
headers=None, callback_url=None, twitter_token=None, twitter_secret=None, proxies=None):
"""Instantiates an instance of Twython. Takes optional parameters for authentication and such (see below).
:param app_key: (optional) Your applications key
:param app_secret: (optional) Your applications secret key
:param oauth_token: (optional) Used with oauth_token_secret to make authenticated calls
:param oauth_token_secret: (optional) Used with oauth_token to make authenticated calls
:param headers: (optional) Custom headers to send along with the request
:param callback_url: (optional) If set, will overwrite the callback url set in your application
:param proxies: (optional) A dictionary of proxies, for example {"http":"proxy.example.org:8080", "https":"proxy.example.org:8081"}.
"""
# Needed for hitting that there API.
self.api_url = 'https://api.twitter.com/%s'
self.request_token_url = self.api_url % 'oauth/request_token'
self.access_token_url = self.api_url % 'oauth/access_token'
self.authorize_url = self.api_url % 'oauth/authorize'
self.authenticate_url = self.api_url % 'oauth/authenticate'
# Enforce unicode on keys and secrets
self.app_key = app_key and unicode(app_key) or twitter_token and unicode(twitter_token)
self.app_secret = app_key and unicode(app_secret) or twitter_secret and unicode(twitter_secret)
self.oauth_token = oauth_token and u'%s' % oauth_token
self.oauth_token_<API key> and u'%s' % oauth_token_secret
self.callback_url = callback_url
# If there's headers, set them, otherwise be an embarassing parent for their own good.
self.headers = headers or {'User-Agent': 'Twython v' + __version__}
# Allow for unauthenticated requests
self.client = requests.session(proxies=proxies)
self.auth = None
if self.app_key is not None and self.app_secret is not None and \
self.oauth_token is None and self.oauth_token_secret is None:
self.auth = OAuth1(self.app_key, self.app_secret,
signature_type='auth_header')
if self.app_key is not None and self.app_secret is not None and \
self.oauth_token is not None and self.oauth_token_secret is not None:
self.auth = OAuth1(self.app_key, self.app_secret,
self.oauth_token, self.oauth_token_secret,
signature_type='auth_header')
if self.auth is not None:
self.client = requests.session(headers=self.headers, auth=self.auth, proxies=proxies)
# register available funcs to allow listing name when debugging.
def setFunc(key):
return lambda **kwargs: self._constructFunc(key, **kwargs)
for key in api_table.keys():
self.__dict__[key] = setFunc(key)
# create stash for last call intel
self._last_call = None
def _constructFunc(self, api_call, **kwargs):
# Go through and replace any mustaches that are in our API url.
fn = api_table[api_call]
url = re.sub(
'\{\{(?P<m>[a-zA-Z_]+)\}\}',
# The '1' here catches the API version. Slightly hilarious.
lambda m: "%s" % kwargs.get(m.group(1), '1'),
base_url + fn['url']
)
content = self._request(url, method=fn['method'], params=kwargs)
return content
def _request(self, url, method='GET', params=None, files=None, api_call=None):
'''Internal response generator, no sense in repeating the same
code twice, right? ;)
'''
method = method.lower()
if not method in ('get', 'post'):
raise TwythonError('Method must be of GET or POST')
params = params or {}
func = getattr(self.client, method)
if method == 'get':
response = func(url, params=params)
else:
response = func(url, data=params, files=files)
content = response.content.decode('utf-8')
# create stash for last function intel
self._last_call = {
'api_call': api_call,
'api_error': None,
'cookies': response.cookies,
'error': response.error,
'headers': response.headers,
'status_code': response.status_code,
'url': response.url,
'content': content,
}
try:
content = simplejson.loads(content)
except ValueError:
raise TwythonError('Response was not valid JSON, unable to decode.')
if response.status_code > 304:
# If there is no error message, use a default.
error_msg = content.get(
'error', 'An error occurred processing your request.')
self._last_call['api_error'] = error_msg
if response.status_code == 420:
exceptionType = <API key>
else:
exceptionType = TwythonError
raise exceptionType(error_msg,
error_code=response.status_code,
retry_after=response.headers.get('retry-after'))
return content
'''
# Dynamic Request Methods
Just in case Twitter releases something in their API
and a developer wants to implement it on their app, but
we haven't gotten around to putting it in Twython yet. :)
'''
def request(self, endpoint, method='GET', params=None, files=None, version=1):
# In case they want to pass a full Twitter URL
if endpoint.startswith('http:
url = endpoint
else:
url = '%s/%s.json' % (self.api_url % version, endpoint)
content = self._request(url, method=method, params=params, files=files, api_call=url)
return content
def get(self, endpoint, params=None, version=1):
return self.request(endpoint, params=params, version=version)
def post(self, endpoint, params=None, files=None, version=1):
return self.request(endpoint, 'POST', params=params, files=files, version=version)
# End Dynamic Request Methods
def <API key>(self, header):
"""Returns the header in the last function
This must be called after an API call, as it returns header based
information.
This will return None if the header is not present
Most useful for the following header information:
x-ratelimit-limit
<API key>
x-ratelimit-class
x-ratelimit-reset
"""
if self._last_call is None:
raise TwythonError('This function must be called after an API call. It delivers header information.')
if header in self._last_call['headers']:
return self._last_call['headers'][header]
return None
def get_<API key>(self):
"""Returns an authorization URL for a user to hit.
"""
request_args = {}
if self.callback_url:
request_args['oauth_callback'] = self.callback_url
response = self.client.get(self.request_token_url, params=request_args)
if response.status_code != 200:
raise TwythonAuthError("Seems something couldn't be verified with your OAuth junk. Error: %s, Message: %s" % (response.status_code, response.content))
request_tokens = dict(parse_qsl(response.content))
if not request_tokens:
raise TwythonError('Unable to decode request tokens.')
o<API key> = request_tokens.get('o<API key>) == 'true'
auth_url_params = {
'oauth_token': request_tokens['oauth_token'],
}
# Use old-style callback argument if server didn't accept new-style
if self.callback_url and not o<API key>:
auth_url_params['oauth_callback'] = self.callback_url
request_tokens['auth_url'] = self.authenticate_url + '?' + urllib.urlencode(auth_url_params)
return request_tokens
def <API key>(self):
"""Returns authorized tokens after they go through the auth_url phase.
"""
response = self.client.get(self.access_token_url)
authorized_tokens = dict(parse_qsl(response.content))
if not authorized_tokens:
raise TwythonError('Unable to decode authorized tokens.')
return authorized_tokens
# The following methods are all different in some manner or require special attention with regards to the Twitter API.
# Because of this, we keep them separate from all the other endpoint definitions - ideally this should be change-able,
# but it's not high on the priority list at the moment.
@staticmethod
def shortenURL(url_to_shorten, shortener='http://is.gd/api.php'):
"""Shortens url specified by url_to_shorten.
Note: <TwitterConsumerkey> shortens all URLs behind their own custom t.co shortener now,
but we keep this here for anyone who was previously using it for alternative purposes. ;)
:param url_to_shorten: (required) The URL to shorten
:param shortener: (optional) In case you want to use a different
URL shortening service
"""
if shortener == '':
raise TwythonError('Please provide a URL shortening service.')
request = requests.get(shortener, params={
'query': url_to_shorten
})
if request.status_code in [301, 201, 200]:
return request.text
else:
raise TwythonError('shortenURL() failed with a %s error code.' % request.status_code)
@staticmethod
def constructApiURL(base_url, params):
return base_url + "?" + "&".join(["%s=%s" % (Twython.unicode2utf8(key), urllib.quote_plus(Twython.unicode2utf8(value))) for (key, value) in params.iteritems()])
def search(self, **kwargs):
return self.get('https://search.twitter.com/search.json', params=kwargs)
def searchGen(self, search_query, **kwargs):
kwargs['q'] = search_query
content = self.get('https://search.twitter.com/search.json', params=kwargs)
if not content['results']:
raise StopIteration
for tweet in content['results']:
yield tweet
if 'page' not in kwargs:
kwargs['page'] = '2'
else:
try:
kwargs['page'] = int(kwargs['page'])
kwargs['page'] += 1
kwargs['page'] = str(kwargs['page'])
except TypeError:
raise TwythonError("searchGen() exited because page takes type str")
for tweet in self.searchGen(search_query, **kwargs):
yield tweet
# The following methods are apart from the other Account methods,
# because they rely on a whole multipart-data posting function set.
def <API key>(self, file_, tile=True, version=1):
url = 'https://api.twitter.com/%d/account/<API key>.json' % version
return self._media_update(url,
{'image': (file_, open(file_, 'rb'))},
**{'tile': tile})
def bulkUserLookup(self, **kwargs):
"""Stub for a method that has been deprecated, kept for now to raise errors
properly if people are relying on this (which they are...).
"""
warnings.warn(
"This function has been deprecated. Please migrate to .lookupUser() - params should be the same.",
DeprecationWarning,
stacklevel=2
)
def updateProfileImage(self, file_, version=1):
url = 'https://api.twitter.com/%d/account/<API key>.json' % version
return self._media_update(url,
{'image': (file_, open(file_, 'rb'))})
def <API key>(self, file_, version=1, **params):
url = 'https://upload.twitter.com/%d/statuses/update_with_media.json' % version
return self._media_update(url,
{'media': (file_, open(file_, 'rb'))},
**params)
def _media_update(self, url, file_, **params):
return self.post(url, params=params, files=file_)
def getProfileImageUrl(self, username, size='normal', version=1):
endpoint = 'users/profile_image/%s' % username
url = self.api_url % version + '/' + endpoint
response = self.client.get(url, params={'size': size}, allow_redirects=False)
image_url = response.headers.get('location')
if response.status_code in (301, 302, 303, 307) and image_url is not None:
return image_url
else:
raise TwythonError('getProfileImageUrl() threw an error.',
error_code=response.status_code)
@staticmethod
def stream(data, callback):
endpoint = 'https://stream.twitter.com/1/statuses/filter.json'
if 'endpoint' in data:
endpoint = data.pop('endpoint')
needs_basic_auth = False
if 'username' in data and 'password' in data:
needs_basic_auth = True
username = data.pop('username')
password = data.pop('password')
if needs_basic_auth:
stream = requests.post(endpoint,
data=data,
auth=(username, password))
else:
stream = requests.post(endpoint, data=data)
for line in stream.iter_lines():
if line:
try:
callback(simplejson.loads(line))
except ValueError:
raise TwythonError('Response was not valid JSON, unable to decode.')
@staticmethod
def unicode2utf8(text):
try:
if isinstance(text, unicode):
text = text.encode('utf-8')
except:
pass
return text
@staticmethod
def encode(text):
if isinstance(text, (str, unicode)):
return Twython.unicode2utf8(text)
return str(text) |
#ifndef <API key>
#define <API key>
#include "src/base/flags.h"
#include "src/compiler/graph-reducer.h"
#include "src/deoptimize-reason.h"
#include "src/objects/map.h"
namespace v8 {
namespace internal {
// Forward declarations.
class <API key>;
class Factory;
class FeedbackNexus;
namespace compiler {
// Forward declarations.
enum class AccessMode;
class <API key>;
class ElementAccessInfo;
class JSGraph;
class JSOperatorBuilder;
class <API key>;
class PropertyAccessInfo;
class <API key>;
class TypeCache;
// Specializes a given JSGraph to a given native context, potentially constant
// folding some {LoadGlobal} nodes or strength reducing some {StoreGlobal}
// nodes. And also specializes {LoadNamed} and {StoreNamed} nodes according
// to type feedback (if available).
class <API key> final : public AdvancedReducer {
public:
// Flags that control the mode of operation.
enum Flag {
kNoFlags = 0u,
<API key> = 1u << 0,
<API key> = 1u << 1
};
typedef base::Flags<Flag> Flags;
<API key>(Editor* editor, JSGraph* jsgraph, Flags flags,
Handle<Context> native_context,
<API key>* dependencies,
Zone* zone);
Reduction Reduce(Node* node) final;
private:
Reduction ReduceJSAdd(Node* node);
Reduction <API key>(Node* node);
Reduction ReduceJSInstanceOf(Node* node);
Reduction <API key>(Node* node);
Reduction ReduceJSLoadContext(Node* node);
Reduction ReduceJSLoadGlobal(Node* node);
Reduction ReduceJSStoreGlobal(Node* node);
Reduction ReduceJSLoadNamed(Node* node);
Reduction ReduceJSStoreNamed(Node* node);
Reduction <API key>(Node* node);
Reduction <API key>(Node* node);
Reduction <API key>(Node* node);
Reduction <API key>(Node* node);
Reduction ReduceElementAccess(Node* node, Node* index, Node* value,
MapHandles const& receiver_maps,
AccessMode access_mode,
LanguageMode language_mode,
<API key> store_mode);
template <typename KeyedICNexus>
Reduction ReduceKeyedAccess(Node* node, Node* index, Node* value,
KeyedICNexus const& nexus, AccessMode access_mode,
LanguageMode language_mode,
<API key> store_mode);
Reduction <API key>(Node* node, Node* value,
FeedbackNexus const& nexus,
Handle<Name> name,
AccessMode access_mode,
LanguageMode language_mode);
Reduction ReduceNamedAccess(Node* node, Node* value,
MapHandles const& receiver_maps,
Handle<Name> name, AccessMode access_mode,
LanguageMode language_mode,
Node* index = nullptr);
Reduction ReduceGlobalAccess(Node* node, Node* receiver, Node* value,
Handle<Name> name, AccessMode access_mode,
Node* index = nullptr);
Reduction <API key>(Node* node, DeoptimizeReason reason);
// A triple of nodes that represents a continuation.
class ValueEffectControl final {
public:
ValueEffectControl(Node* value, Node* effect, Node* control)
: value_(value), effect_(effect), control_(control) {}
Node* value() const { return value_; }
Node* effect() const { return effect_; }
Node* control() const { return control_; }
private:
Node* const value_;
Node* const effect_;
Node* const control_;
};
// Construct the appropriate subgraph for property access.
ValueEffectControl BuildPropertyAccess(Node* receiver, Node* value,
Node* context, Node* frame_state,
Node* effect, Node* control,
Handle<Name> name,
PropertyAccessInfo const& access_info,
AccessMode access_mode,
LanguageMode language_mode);
// Construct the appropriate subgraph for element access.
ValueEffectControl BuildElementAccess(Node* receiver, Node* index,
Node* value, Node* effect,
Node* control,
ElementAccessInfo const& access_info,
AccessMode access_mode,
<API key> store_mode);
// Construct an appropriate heap object check.
Node* <API key>(Node* receiver, Node** effect, Node* control);
// Construct an appropriate map check.
Node* BuildCheckMaps(Node* receiver, Node* effect, Node* control,
MapHandles const& maps);
// Construct appropriate subgraph to extend properties backing store.
Node* <API key>(Handle<Map> map, Node* properties,
Node* effect, Node* control);
// Adds stability dependencies on all prototypes of every class in
// {receiver_type} up to (and including) the {holder}.
void <API key>(MapHandles const& receiver_maps,
Handle<JSObject> holder);
// Checks if we can turn the hole into undefined when loading an element
// from an object with one of the {receiver_maps}; sets up appropriate
// code dependencies and might use the array protector cell.
bool <API key>(MapHandles const& receiver_maps);
// Checks if we know at compile time that the {receiver} either definitely
// has the {prototype} in it's prototype chain, or the {receiver} definitely
// doesn't have the {prototype} in it's prototype chain.
enum <API key> {
kIsInPrototypeChain,
<API key>,
<API key>
};
<API key> <API key>(
Node* receiver, Node* effect, Handle<JSReceiver> prototype);
// Extract receiver maps from {nexus} and filter based on {receiver} if
// possible.
bool ExtractReceiverMaps(Node* receiver, Node* effect,
FeedbackNexus const& nexus,
MapHandles* receiver_maps);
// Try to infer maps for the given {receiver} at the current {effect}.
// If maps are returned then you can be sure that the {receiver} definitely
// has one of the returned maps at this point in the program (identified
// by {effect}).
bool InferReceiverMaps(Node* receiver, Node* effect,
MapHandles* receiver_maps);
// Try to infer a root map for the {receiver} independent of the current
// program location.
MaybeHandle<Map> <API key>(Node* receiver);
ValueEffectControl InlineApiCall(
Node* receiver, Node* context, Node* target, Node* frame_state,
Node* parameter, Node* effect, Node* control,
Handle<SharedFunctionInfo> shared_info,
Handle<<API key>> <API key>);
// Script context lookup logic.
struct <API key>;
bool <API key>(Handle<Name> name,
<API key>* result);
Graph* graph() const;
JSGraph* jsgraph() const { return jsgraph_; }
Isolate* isolate() const;
Factory* factory() const;
<API key>* common() const;
JSOperatorBuilder* javascript() const;
<API key>* simplified() const;
<API key>* machine() const;
Flags flags() const { return flags_; }
Handle<JSGlobalObject> global_object() const { return global_object_; }
Handle<JSGlobalProxy> global_proxy() const { return global_proxy_; }
Handle<Context> native_context() const { return native_context_; }
<API key>* dependencies() const { return dependencies_; }
Zone* zone() const { return zone_; }
JSGraph* const jsgraph_;
Flags const flags_;
Handle<JSGlobalObject> global_object_;
Handle<JSGlobalProxy> global_proxy_;
Handle<Context> native_context_;
<API key>* const dependencies_;
Zone* const zone_;
TypeCache const& type_cache_;
<API key>(<API key>);
};
<API key>(<API key>::Flags)
} // namespace compiler
} // namespace internal
} // namespace v8
#endif // <API key> |
module minerva.core.render.tapins {
export var preRender: IRenderTapin = function (input: IInput, state: IState, output: IOutput, ctx: RenderContext, region: Rect, tree: IUpdaterTree): boolean {
var effect = input.effect;
if (!effect)
return true;
ctx.save();
effect.PreRender(ctx);
return true;
};
} |
// EKEventStore.h
// EventKit
#import <Foundation/Foundation.h>
#import <EventKit/EventKitDefines.h>
#import <EventKit/EKTypes.h>
<API key>
@class EKCalendar, EKEvent, EKSource, EKReminder, EKCalendarItem;
/*!
@enum EKSpan
@abstract Values for controlling what occurrences to affect in a recurring event.
@discussion This enumerated type is used to indicate the scope of a change being made to a repeating event. EKSpanThisEvent
indicates the changes should apply only to this event, EKSpanFutureEvents indicates the changes should apply to
this event and all future events in the pattern.
@constant EKSpanThisEvent Affect this event only.
@constant EKSpanFutureEvents Affect this event and all after it.
*/
typedef NS_ENUM(NSInteger, EKSpan) {
EKSpanThisEvent,
EKSpanFutureEvents
};
typedef void (^<API key>)(EKEvent *event, BOOL *stop);
/*!
@class EKEventStore
@abstract The EKEventStore class provides an interface for accessing and manipulating calendar events and reminders.
@discussion The EKEventStore class is the main point of contact for accessing Calendar data. You must
create a EKEventStore object in order to retrieve/add/delete events or reminders from the Calendar database.
Events, Reminders, and Calendar objects retrieved from an event store cannot be used with any other event
store. It is generally best to hold onto a long-lived instance of an event store, most
likely as a singleton instance in your application.
*/
NS_CLASS_AVAILABLE(10_8, 4_0)
@interface EKEventStore : NSObject
/*!
@method <API key>:
@discussion Returns the authorization status for the given entity type
*/
+ (<API key>)<API key>:(EKEntityType)entityType NS_AVAILABLE(10_9, 6_0);
- (id)<API key>:(EKEntityMask)entityTypes NS_DEPRECATED(10_8, 10_9, NA, NA);
/*!
@method init
*/
- (id)init NS_AVAILABLE(10_9, 4_0);
/*!
@method initWithSources:
@abstract Creates a new event store that only includes items and calendars for a subset of sources.
@param sources The sources you want this event store to recognize. This may include delegate sources.
*/
- (instancetype)initWithSources:(NSArray<EKSource *> *)sources NS_AVAILABLE(10_11, NA);
typedef void(^<API key>)(BOOL granted, NSError * __nullable error);
- (void)<API key>:(EKEntityType)entityType completion:(<API key>)completion NS_AVAILABLE(10_9, 6_0);
/*!
@property <API key>
@abstract Returns a unique identifier string representing this calendar store.
*/
@property(nonatomic, readonly) NSString *<API key>;
// SOURCES
/*!
@property delegateSources
@abstract Returns an unordered array of sources for all available delegates.
@discussion By default, delegates are not included in an event store's sources. To work with delegates,
you can create a new event store and pass in the sources, including sources returned from this
method, that you're interested in.
@see initWithSources:
*/
@property (nonatomic, readonly) NSArray<EKSource *> *delegateSources NS_AVAILABLE(10_11, NA);
/*!
@property sources
@abstract Returns an unordered array of sources.
*/
@property (nonatomic, readonly) NSArray<EKSource *> *sources NS_AVAILABLE(10_8, 5_0);
/*!
@method <API key>:
@abstract Returns a source with a specified identifier.
*/
- (EKSource *)<API key>:(NSString *)identifier NS_AVAILABLE(10_8, 5_0);
// CALENDARS
/*!
@method calendars
@abstract While this returns an array, the calendars are unordered. This call is deprecated
and only returns calendars that support events. If you want reminder calendars
you should use <API key>:
*/
@property(nonatomic, readonly) NSArray<EKCalendar *> *calendars NS_DEPRECATED(NA, NA, 4_0, 6_0);
/*!
@method <API key>
@abstract Returns calendars that support a given entity type (reminders, events)
*/
- (NSArray<EKCalendar *> *)<API key>:(EKEntityType)entityType NS_AVAILABLE(10_8, 6_0);
/*!
@property <API key>
@abstract Returns the calendar that events should be added to by default.
*/
@property(nonatomic, readonly) EKCalendar *<API key>;
/*!
@method <API key>
@abstract Returns the calendar that reminders should be added to by default.
*/
- (EKCalendar *)<API key> NS_AVAILABLE(10_8, 6_0);
/*!
@method <API key>:
@abstract Returns a calendar with a specified identifier.
*/
- (nullable EKCalendar *)<API key>:(NSString *)identifier NS_AVAILABLE(10_8, 5_0);
/*!
@method saveCalendar:commit:error:
@abstract Saves changes to a calendar, or adds a new calendar to the database.
@discussion This method attempts to save the given calendar to the calendar database. It
returns YES if successful and NO otherwise. Passing a calendar fetched from
another EKEventStore instance into this function will raise an exception.
On WatchOS, saving changes is not supported.
@param calendar The calendar to save.
@param commit Pass YES to cause the database to save. You can pass NO to save multiple
calendars and then call commit: to save them all at once.
@param error If an error occurs, this will contain a valid NSError object on exit.
*/
- (BOOL)saveCalendar:(EKCalendar *)calendar commit:(BOOL)commit error:(NSError **)error NS_AVAILABLE(10_8, 5_0) <API key>;
/*!
@method removeCalendar:commit:error:
@abstract Removes a calendar from the database.
@discussion This method attempts to delete the given calendar from the calendar database. It
returns YES if successful and NO otherwise. Passing a calendar fetched from
another EKEventStore instance into this function will raise an exception.
If the calendar supports multiple entity types (allowedEntityTypes), but the user has
not granted you access to all those entity types, then we will delete all of the entity types
for which you have access and remove that entity type from the allowedEntityTypes.
For example: If a calendar supports both events and reminders, but you only have access to reminders,
we will delete all the reminders and make the calendar only support events.
If you have access to all of its allowedEntityTypes, then it will delete the calendar and
all of the events and reminders in the calendar.
On WatchOS, modifying the database is not supported.
@param calendar The calendar to delete.
@param commit Pass YES to cause the database to save. You can pass NO to batch multiple
changes and then call commit: to save them all at once.
@param error If an error occurs, this will contain a valid NSError object on exit.
*/
- (BOOL)removeCalendar:(EKCalendar *)calendar commit:(BOOL)commit error:(NSError **)error NS_AVAILABLE(10_8, 5_0) <API key>;
// CALENDAR ITEMS (apply to both reminders and events)
/*!
@method <API key>:
@abstract Returns either a reminder or the first occurrence of an event.
*/
- (EKCalendarItem *)<API key>:(NSString *)identifier NS_AVAILABLE(10_8, 6_0);
/*!
@method <API key>:
@abstract Returns either matching reminders or the first occurrences of any events matching
the given external identifier.
@discussion This method returns a set of EKEvents or EKReminders with the given external identifier.
Due to reasons discussed in -[EKCalendarItem <API key>], there may be
more than one matching calendar item.
@param externalIdentifier The value obtained from EKCalendarItem's
<API key> property
@result An unsorted array of EKCalendarItem instances
*/
- (NSArray<EKCalendarItem *> *)<API key>:(NSString *)externalIdentifier NS_AVAILABLE(10_8, 6_0);
// EVENTS
/*!
@method saveEvent:span:error:
@abstract Saves changes to an event permanently.
@discussion This method attempts to save the event to the calendar database. It returns YES if
successful and NO otherwise. It's possible for this method to return NO, and error
will be set to nil. This occurs if the event wasn't dirty and didn't need saving. This
means the correct way to detect failure is a result of NO and a non-nil error parameter.
Passing an event fetched from another EKEventStore instance into this function will
raise an exception.
After an event is successfully saved, it is also put into sync with the database, meaning
that all fields you did not change will be updated to the latest values. If you save the
event, but it was deleted by a different store/process, you will effectively recreate the
event as a new event.
On WatchOS, saving changes is not supported.
@param event The event to save.
@param span The span to use (this event, or this and future events).
@param error If an error occurs, this will contain a valid NSError object on exit.
*/
- (BOOL)saveEvent:(EKEvent *)event span:(EKSpan)span error:(NSError **)error NS_AVAILABLE(NA, 4_0) <API key>;
/*!
@method removeEvent:span:error:
@abstract Removes an event from the calendar store.
@discussion This method attempts to remove the event from the calendar database. It returns YES if
successful and NO otherwise. It's possible for this method to return NO, and error
will be set to nil. This occurs if the event wasn't ever added and didn't need removing. This
means the correct way to detect failure is a result of NO and a non-nil error parameter.
Passing an event from another CalendarStore into this function will raise an exception. After
an event is removed, it is no longer tied to this calendar store, and all data in the event
is cleared except for the eventIdentifier.
On WatchOS, modifying the database is not supported.
@param event The event to save.
@param span The span to use (this event, or this and future events).
@param error If an error occurs, this will contain a valid NSError object on exit.
*/
- (BOOL)removeEvent:(EKEvent *)event span:(EKSpan)span error:(NSError **)error NS_AVAILABLE(NA, 4_0) <API key>;
// These variants of the above allow you to batch changes by passing NO to commit. You can commit
// all changes later with [EKEventStore commit:]
- (BOOL)saveEvent:(EKEvent *)event span:(EKSpan)span commit:(BOOL)commit error:(NSError **)error NS_AVAILABLE(10_8, 5_0) <API key>;
- (BOOL)removeEvent:(EKEvent *)event span:(EKSpan)span commit:(BOOL)commit error:(NSError **)error NS_AVAILABLE(10_8, 5_0) <API key>;
/*!
@method eventWithIdentifier:
@abstract Returns the first occurrence of an event matching the given event identifier.
@param identifier The eventIdentifier to search for.
@result An EKEvent object, or nil if not found.
*/
- (nullable EKEvent *)eventWithIdentifier:(NSString *)identifier;
/*!
@method <API key>:
@abstract Searches for events that match the given predicate.
@discussion This call executes a search for the events indicated by the predicate passed to it.
It only includes events which have been committed (e.g. those saved using
saveEvent:commit:NO are not included until commit: is called.)
It is synchronous. If you want async behavior, you should either use dispatch_async or
NSOperation to run the query someplace other than the main thread, and then funnel the
array back to the main thread.
@param predicate The predicate to invoke. If this predicate was not created with the predicate
creation functions in this class, an exception is raised.
@result An array of EKEvent objects, or nil. There is no guaranteed order to the events.
*/
- (NSArray<EKEvent *> *)<API key>:(NSPredicate *)predicate;
/*!
@method <API key>:usingBlock:
@abstract Searches for events that match the given predicate.
@discussion This call executes a search for the events indicated by the predicate passed to it, calling
the block specified in the callback parameter for each event. It only includes events which
have been committed (e.g. those saved using saveEvent:commit:NO are not included until commit: is called.)
This method is synchronous. If you want async behavior, you should either use dispatch_async or
NSOperation to run the query someplace other than the main thread.
@param predicate The predicate to invoke. If this predicate was not created with the predicate
creation functions in this class, an exception is raised.
@param block The block to call for each event. Your block should return YES in the stop
parameter to stop iterating.
*/
- (void)<API key>:(NSPredicate *)predicate usingBlock:(<API key>)block;
- (NSPredicate *)<API key>:(NSDate *)startDate endDate:(NSDate *)endDate calendars:(nullable NSArray<EKCalendar *> *)calendars;
// REMINDERS
/*!
@method saveReminder:commit:error:
@abstract Saves changes to a reminder.
@discussion This method attempts to save the reminder to the event store database. It returns YES if
successful and NO otherwise. Passing a reminder fetched from another EKEventStore instance
into this function will raise an exception.
After a reminder is successfully saved, its fields are updated to the latest values in
the database.
On WatchOS, saving changes is not supported.
@param reminder The reminder to save.
@param commit Whether to save to the database or not. Pass NO to batch changes together and
commit with [EKEventStore commit:].
@param error If an error occurs, this will contain a valid NSError object on exit.
*/
- (BOOL)saveReminder:(EKReminder *)reminder commit:(BOOL)commit error:(NSError **)error NS_AVAILABLE(10_8, 6_0) <API key>;
/*!
@method removeReminder:commit:error:
@abstract Removes a reminder from the event store.
@discussion This method attempts to remove the reminder from the event store database. It returns YES if
successful and NO otherwise. Passing a reminder from another EKEventStore into this function
will raise an exception. After a reminder is removed, it is no longer tied to this event store.
On WatchOS, modifying the database is not supported.
@param reminder The reminder to save.
@param commit Whether to save to the database or not. Pass NO to batch changes together and
commit with [EKEventStore commit:].
@param error If an error occurs, this will contain a valid NSError object on exit.
*/
- (BOOL)removeReminder:(EKReminder *)reminder commit:(BOOL)commit error:(NSError **)error NS_AVAILABLE(10_8, 6_0) <API key>;
/*!
@method <API key>:completion:
@abstract Fetches reminders asynchronously.
@discussion This method fetches reminders asynchronously and returns a value which can be
used in cancelFetchRequest: to cancel the request later if desired. The completion
block is called with an array of reminders that match the given predicate (or potentially nil).
This only includes reminders which have been committed (e.g. those saved using
saveReminder:commit:NO are not included until commit: is called.)
*/
- (id)<API key>:(NSPredicate *)predicate completion:(void (^)(NSArray<EKReminder *> * __nullable reminders))completion NS_AVAILABLE(10_8, 6_0);
/*!
@method cancelFetchRequest:
@discussion Given a value returned from <API key>, this method can be used to
cancel the request. Once called, the completion block specified in fetchReminders... will
not be called.
*/
- (void)cancelFetchRequest:(id)fetchIdentifier NS_AVAILABLE(10_8, 6_0);
/*!
@method <API key>:
@abstract Fetch all reminders in a set of calendars.
@discussion You can pass nil for calendars to fetch from all available calendars.
*/
- (NSPredicate *)<API key>:(nullable NSArray<EKCalendar *> *)calendars NS_AVAILABLE(10_8, 6_0);
/*!
@method <API key>:ending:calendars:
@abstract Fetch incomplete reminders in a set of calendars.
@discussion You can use this method to search for incomplete reminders due in a range.
You can pass nil for start date to find all reminders due before endDate.
You can pass nil for both start and end date to get all incomplete reminders
in the specified calendars.
You can pass nil for calendars to fetch from all available calendars.
*/
- (NSPredicate *)<API key>:(nullable NSDate *)startDate ending:(nullable NSDate *)endDate calendars:(nullable NSArray<EKCalendar *> *)calendars NS_AVAILABLE(10_8, 6_0);
/*!
@method <API key>:ending:calendars:
@abstract Fetch completed reminders in a set of calendars.
@discussion You can use this method to search for reminders completed between a range of dates.
You can pass nil for start date to find all reminders completed before endDate.
You can pass nil for both start and end date to get all completed reminders
in the specified calendars.
You can pass nil for calendars to fetch from all available calendars.
*/
- (NSPredicate *)<API key>:(nullable NSDate *)startDate ending:(nullable NSDate *)endDate calendars:(nullable NSArray<EKCalendar *> *)calendars NS_AVAILABLE(10_8, 6_0);
// COMMIT, RESET, ROLLBACK
/*!
@method commit:
@abstract Commits pending changes to the database.
@discussion If you use saveCalendar/saveEvent/removeCalendar/removeEvent, etc. and you pass NO to their
parameter, you are batching changes for a later commit. This method does that commit. This
allows you to save the database only once for many additions or changes. If you pass
YES to methods' commit parameter, then you don't need to call this method.
This method will return YES as long as nothing went awry, even if nothing was actually
committed. If it returns NO, error should contain the reason it became unhappy.
On WatchOS, modifying the database is not supported.
*/
- (BOOL)commit:(NSError **)error NS_AVAILABLE(10_8, 5_0) <API key>;
/*!
@method reset
@abstract Resets the event store.
@discussion You can use this method to forget ALL changes made to the event store (all additions, all
fetched objects, etc.). It essentially is as if you released the store and then created a
new one. It brings it back to its initial state. All objects ever created/fetched, etc.
using this store are no longer connected to it and are considered invalid.
*/
- (void)reset NS_AVAILABLE(10_8, 5_0);
/*!
@method <API key>
@abstract Cause a sync to potentially occur taking into account the necessity of it.
@discussion You can call this method to pull new data from remote sources.
This only updates the event store's data. If you want to update your objects after
refreshing the sources, you should call refresh on each of them afterwards.
On iOS, this sync only occurs if deemed necessary.
On OS X, this will occur regardless of necessity, but may change in a future release to match the iOS behavior.
On WatchOS, initiating sync is not available. Sync will occur automatically with the paired iOS device.
*/
- (void)<API key> NS_AVAILABLE(10_8, 5_0) <API key>;
@end
/*!
@constant <API key>
@discussion Notification name sent out when the database is changed by either an external process,
another event store in the same process, or by calling saveEvent: or removeEvent: on a
store you are managing. When you receive this notification, you should consider all EKEvent
instances you have to be invalid. If you had selected events for a date range using
<API key>, etc. for display, you should release them and re-fetch the events
again. If you have an event you are actively using (e.g. you are currently viewing details
for it or editing it), you can call [EKEvent refresh] to try to revalidate it against the
latest state of the database. If that method returns YES, you can continue to use the event,
otherwise, you should release it and abandon what you were doing with it. The view
controllers provided by EventKitUI automatically deal with this for you.
This notification will also be posted if access to events or reminders is changed by the user.
*/
EVENTKIT_EXTERN NSString *const <API key> NS_AVAILABLE(10_8, 4_0);
<API key> |
require 'fileutils'
module Serverspec
class Setup
def self.run
prompt = <<-EOF
Select a backend type:
1) SSH
2) Exec (local)
Select number:
EOF
print prompt.chop
num = gets.to_i - 1
puts
@backend_type = [ 'Ssh', 'Exec' ][num]
if @backend_type == 'Ssh'
print "Input target host name: "
@hostname = gets.chomp
else
@hostname = 'localhost'
end
[ 'spec', "spec/#{@hostname}" ].each { |dir| safe_mkdir(dir) }
safe_create_spec
<API key>
<API key>
end
def self.safe_create_spec
content = <<-EOF
require 'spec_helper'
describe 'httpd' do
it { should be_installed }
it { should be_enabled }
it { should be_running }
end
describe 'port 80' do
it { should be_listening }
end
describe '/etc/httpd/conf/httpd.conf' do
it { should be_file }
it { should contain "ServerName #{@hostname}" }
end
EOF
if File.exists? "spec/#{@hostname}/httpd_spec.rb"
old_content = File.read("spec/#{@hostname}/httpd_spec.rb")
if old_content != content
$stderr.puts "!! spec/#{@hostname}/httpd_spec.rb already exists and differs from template"
end
else
File.open("spec/#{@hostname}/httpd_spec.rb", 'w') do |f|
f.puts content
end
puts " + spec/#{@hostname}/httpd_spec.rb"
end
end
def self.safe_mkdir(dir)
if File.exists? dir
unless File.directory? dir
$stderr.puts "!! #{dir} already exists and is not a directory"
end
else
FileUtils.mkdir dir
puts " + #{dir}/"
end
end
def self.<API key>
content = <<-EOF
require 'serverspec'
require 'pathname'
include requirements
include backend helper
include Serverspec::Helper::DetectOS
RSpec.configure do |c|
if ENV['ASK_SUDO_PASSWORD']
require 'highline/import'
c.sudo_password = ask("Enter sudo password: ") { |q| q.echo = false }
else
c.sudo_password = ENV['SUDO_PASSWORD']
end
include backend conf
end
EOF
if not @backend_type.nil?
content.gsub!(/
case @backend_type
when 'Ssh'
content.gsub!(/
content.gsub!(/
block = self.class.metadata[:example_group_block]
if RUBY_VERSION.start_with?('1.8')
file = block.to_s.match(/.*@(.*):[0-9]+>/)[1]
else
file = block.source_location.first
end
host = File.basename(Pathname.new(file).dirname)
if c.host != host
c.ssh.close if c.ssh
c.host = host
options = Net::SSH::Config.for(c.host)
user = options[:user] || Etc.getlogin
c.ssh = Net::SSH.start(c.host, user, options)
c.os = backend(Serverspec::Commands::Base).check_os
end
end")
when 'Exec'
content.gsub!(/
c.os = backend(Serverspec::Commands::Base).check_os
end")
when 'Puppet'
content.gsub!(/
")
end
end
if File.exists? 'spec/spec_helper.rb'
old_content = File.read('spec/spec_helper.rb')
if old_content != content
$stderr.puts "!! spec/spec_helper.rb already exists and differs from template"
end
else
File.open('spec/spec_helper.rb', 'w') do |f|
f.puts content
end
puts ' + spec/spec_helper.rb'
end
end
def self.<API key>
content = <<-'EOF'
require 'rake'
require 'rspec/core/rake_task'
RSpec::Core::RakeTask.new(:spec) do |t|
t.pattern = 'spec/*/*_spec.rb'
end
EOF
if File.exists? 'Rakefile'
old_content = File.read('Rakefile')
if old_content != content
$stderr.puts "!! Rakefile already exists and differs from template"
end
else
File.open('Rakefile', 'w') do |f|
f.puts content
end
puts ' + Rakefile'
end
end
end
end |
// TimeStamp : 31-1-2016 //
// Content : Handel the API EndPoint IOs Actions //
// Notes : //
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using DynThings.Data.Models;
namespace DynThings.WebPortal.Controllers
{
public class <API key> : ApiController
{
private DynThingsEntities db = new DynThingsEntities();
}
} |
<div ng-controller="<API key>">
<div class="toolbar">
<i class="fa fa-square-o fa-lg tool-btn btn-toggle" tooltip="focus on" ng-click="toggleWindow()"></i>
<i class="feature-name"><a name="data-bind">Directive Support</a></i>
<i class="fa fa-lightbulb-o fa-lg tool-btn" popover-placement="bottom" popover-template="'dictSupportTips'" <API key>="true" ng-click="toggleTips($event)" tooltip="core tips"></i>
<i class="fa fa-star fa-lg" tooltip="difficulty coefficient"></i>
<script type="text/ng-template" id="dictSupportTips">
<p class="bg-primary">The following events are generated automatically when there is any change in the state of the directives.</p>
<p class="bg-success">Th following events are generated only when the module ngAnimate is passed as a dependency in the application module.</p>
<p class="bg-info">When these events are fired, they add CSS classes on the applied element. The corresponding names of the CSS classes are mentioned in the below table.</p>
<p class="bg-warning">As you can see, we are given liberty to define behavior when the event is happening and also after the event has happened.</p>
<p class="bg-danger">Animations in AngularJS are completely based on CSS classes. As long as you have a CSS class attached to a HTML element within your website, you can apply animations to it.</p>
</script>
</div>
<div class="row">
<table class="table">
<thead>
<tr>
<th>Directive</th>
<th>Events</th>
</tr>
</thead>
<tbody>
<tr class="active">
<td>ngRepeat</td>
<td>enter, leave and move</td>
</tr>
<tr>
<td>ngView, ngInclude, ngSwitch, ngIf</td>
<td>enter and leave</td>
</tr>
<tr class="success">
<td>ngClass</td>
<td>add and remove (the CSS class(es) present)</td>
</tr>
<tr>
<td>ngShow, ngHide</td>
<td>add and remove (the ng-hide class value)</td>
</tr>
<tr class="info">
<td>form, ngModel</td>
<td>add and remove (dirty, pristine, valid, invalid and all other validations)</td>
</tr>
<tr>
<td>ngMessages</td>
<td>add and remove (ng-active and ng-inactive)</td>
</tr>
<tr class="warning">
<td>ngMessage</td>
<td>enter and leave</td>
</tr>
</tbody>
</table>
</div>
</div> |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using System.Threading;
using DeviceHive.WebSockets.Core.Hosting;
using DeviceHive.WebSockets.Core.Network;
namespace DeviceHive.WebSockets.Host
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
internal class HostServiceImpl : <API key>
{
private readonly <API key> _applications = new <API key>();
private readonly WebSocketServerBase _server;
private <API key> _configSection;
private <API key> _runtimeConfig;
private Timer <API key>;
private readonly ServiceHost _managerServiceHost;
public HostServiceImpl(WebSocketServerBase server)
{
_server = server;
_server.ConnectionOpened += OnConnectionOpened;
_server.MessageReceived += OnMessageReceived;
_server.PingReceived += OnPingReceived;
_server.ConnectionClosed += OnConnectionClosed;
_managerServiceHost = new ServiceHost(this);
}
#region Public methods
public void Start()
{
var appDir = Path.GetDirectoryName(Assembly.<API key>().Location);
Directory.SetCurrentDirectory(appDir);
_configSection = (<API key>)<API key>.GetSection("webSocketsHost");
_runtimeConfig = <API key>.Load(_configSection.RuntimeConfigPath);
LoadApplications();
var url = _configSection.ListenUrl;
var <API key> = _configSection.<API key>;
_server.Start(url, <API key>);
<API key> = new Timer(state => <API key>());
var <API key> = _configSection.<API key> * 60 * 1000;
<API key>.Change(<API key>, <API key>);
_managerServiceHost.Open();
}
public void Stop()
{
_managerServiceHost.Close();
<API key>.Dispose();
_server.Stop();
foreach (var app in _applications.GetAllApplications())
app.Stop();
}
#region Implementation of <API key>
public void AddApplication(string host, string exePath, string commandLineArgs,
string userName, string userPassword)
{
var appConfig = new <API key>()
{
Host = host,
ExePath = exePath,
CommandLineArgs = commandLineArgs,
UserName = userName,
UserPassword = userPassword
};
AddApplication(appConfig);
_runtimeConfig.Applications.Add(appConfig);
_runtimeConfig.Save();
}
public bool RemoveApplication(string host)
{
var app = _applications.<API key>(host);
if (app == null)
return false;
app.Stop();
if (!_applications.Remove(host))
return false;
var appConfig = _runtimeConfig.Applications.FirstOrDefault(c => c.Host.ToLower() == host.ToLower());
_runtimeConfig.Applications.Remove(appConfig);
_runtimeConfig.Save();
return true;
}
public bool ChangeApplication(string host,
string exePath = null, string commandLineArgs = null,
string userName = null, string userPassword = null)
{
var app = _applications.<API key>(host);
if (app == null || app.State != ApplicationState.Stopped)
return false;
var appConfig = _runtimeConfig.Applications.FirstOrDefault(c => c.Host.ToLower() == host.ToLower());
appConfig.ExePath = exePath ?? appConfig.ExePath;
appConfig.CommandLineArgs = commandLineArgs ?? appConfig.CommandLineArgs;
appConfig.UserName = userName ?? appConfig.UserName;
appConfig.UserPassword = userPassword ?? appConfig.UserPassword;
_runtimeConfig.Save();
_applications.Remove(host);
app = new Application(_server, _configSection, appConfig);
_applications.Add(app);
return true;
}
public bool StopApplication(string host)
{
var app = _applications.<API key>(host);
if (app == null)
return false;
app.Stop();
return true;
}
public bool StartApplication(string host)
{
var app = _applications.<API key>(host);
if (app == null)
return false;
app.Start();
return true;
}
#endregion
#endregion
#region Private methods
private void OnConnectionOpened(object sender, <API key> args)
{
var app = _applications.<API key>(args.Connection.Host);
if (app != null)
app.<API key>(args.Connection);
}
private void OnMessageReceived(object sender, <API key> args)
{
var app = _applications.<API key>(args.Connection.Host);
if (app != null)
app.<API key>(args.Connection, args.Message);
}
private void OnPingReceived(object sender, <API key> args)
{
var app = _applications.<API key>(args.Connection.Host);
if (app != null)
app.NotifyPingReceived(args.Connection);
}
private void OnConnectionClosed(object sender, <API key> args)
{
var app = _applications.<API key>(args.Connection.Host);
if (app != null)
app.<API key>(args.Connection);
}
private void LoadApplications()
{
foreach (var appConfig in _runtimeConfig.Applications)
AddApplication(appConfig);
}
private void AddApplication(<API key> appConfig)
{
var app = new Application(_server, _configSection, appConfig);
_applications.Add(app);
}
private void <API key>()
{
var apps = _applications.GetAllApplications();
var minAccessTime = DateTime.Now.AddMinutes(-_configSection.<API key>);
foreach (var app in apps)
app.TryDeactivate(minAccessTime);
}
#endregion
}
} |
require 'omniauth-github'
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
config.secret_key = 'b2d90e17254f71668625d249ead9920670f89493a038f8d908fd6ee7ce0894cb4a1299bec21ba98c44378692a74de2fb763afa28594c609cabf15293fd8f7437'
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
config.mailer_sender = '<API key>@example.com'
# Configure the class responsible to send e-mails.
# config.mailer = 'Devise::Mailer'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [ :email ]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# <API key> method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.<API key> = [ :email ]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.<API key> = [ :email ]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.<API key> = [:database]` will
# enable it only for database (email + password) authentication.
# config.<API key> = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.<API key> = [:database]` will
# enable it only for database authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# config.<API key> = false
# If http headers should be returned for AJAX requests. True by default.
# config.http_<API key> = true
# The realm used in Http Basic Authentication. 'Application' by default.
# config.http_<API key> = 'Application'
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# particular strategies by setting this option.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing :skip => :sessions to `devise_for` in your config/routes.rb
config.<API key> = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_<API key> = true
# ==> Configuration for :<API key>
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments.
config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password.
# config.pepper = 'fe3be2a84cba8752ad5c0dc842b3d8c13c6ea02ed9a749aa0492f7c885051075be491bb5b1974c98375f774eaf10df972808c42ebcfd1f70dc800de70559c933'
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming their account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming their account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming their account.
# config.<API key> = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed new email is stored in
# unconfirmed email column, and copied to email column on successful confirmation.
# config.reconfirmable = false
# Defines which key will be used when confirming an account
# config.confirmation_keys = [ :email ]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# If true, extends the user's remember period when remembered via cookie.
# config.<API key> = false
# Options to be passed to the created cookie. For instance, you can set
# :secure => true in order to force SSL only cookies.
# config.<API key> = {}
# ==> Configuration for :validatable
# Range for password length.
# config.password_length = 8..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
# config.email_regexp = /\A[^@]+@[^@]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# If true, expires auth token on session timeout.
# config.expire_<API key> = false
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [ :email ]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# Warn on the last attempt before the account is locked.
# config.<API key> = false
# ==> Configuration for :recoverable
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [ :email ]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.<API key> = 6.hours
# ==> Configuration for :encryptable
# Allow you to use another encryption algorithm besides bcrypt (default). You can use
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :<API key> (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper).
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
config.scoped_views = true
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
# The "*/*" below is required to match Internet Explorer requests.
# config.<API key> = ['*/*', :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
config.omniauth :github, ENV['GITHUB_CLIENT_ID'], ENV['<API key>'], :scope => 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(:scope => :user).unshift :<API key>
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
# mount MyEngine, at: '/my_engine'
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
# When using omniauth, Devise cannot automatically set Omniauth path,
# so you need to do it manually. For the users scope, it would be:
# config.<API key> = '/my_engine/users/auth'
end |
// Generated by CoffeeScript 1.10.0
(function() {
var _;
_ = require('underscore');
module.exports = {
groupByAlpha: function() {
var instance;
instance = new this.model();
return this.groupBy(function(model) {
var key, letter;
key = (typeof model.alphaSortKey === "function" ? model.alphaSortKey() : void 0) || model.get('sortable_id');
letter = key[0];
if (/^\d$/.test(letter)) {
return '0-9';
} else {
return letter.toUpperCase();
}
});
},
<API key>: function(numberOfColumns) {
var instance, itemsByLetter, itemsToColumns, letters;
if (numberOfColumns == null) {
numberOfColumns = 3;
}
instance = new this.model();
if (!_.isFunction(instance.href)) {
throw "You must implement an `href` method for these models.";
}
if (!_.isFunction(instance.displayName)) {
throw "You must implement a `displayName` method for these models.";
}
itemsByLetter = this.groupByAlpha();
letters = _.keys(itemsByLetter);
letters.sort();
itemsToColumns = function(items, numberOfColumns) {
var i, j, maxRows, ref, results;
maxRows = Math.floor(items.length / numberOfColumns);
results = [];
for (i = j = 0, ref = numberOfColumns; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
results.push(items.slice(i * maxRows + i, +((i + 1) * maxRows + i) + 1 || 9e9));
}
return results;
};
return _.map(letters, (function(_this) {
return function(letter) {
var items, models;
models = itemsByLetter[letter];
items = _.map(models, function(model) {
var linkToPage;
linkToPage = model.has('artworks_count') ? model.get('artworks_count') > 0 : true;
return {
href: model.href(),
name: model.displayName(),
linkToPage: linkToPage
};
});
return {
letter: letter,
columns: itemsToColumns(items, numberOfColumns)
};
};
})(this));
}
};
}).call(this); |
<?php
namespace Securinets\FrontOfficeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Epreuves
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="Securinets\FrontOfficeBundle\Entity\EpreuveRepository")
*/
class Epreuve
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="id2", type="string", length=5)
*/
private $id2;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* @var string
*
* @ORM\Column(name="description", type="string", length=255, nullable=true)
*/
private $description;
/**
* @var string
*
* @ORM\Column(name="url", type="string", length=255, nullable=true)
*/
private $url;
/**
* @var string
*
* @ORM\Column(name="flag", type="string", length=255)
*/
private $flag;
/**
* @var integer
*
* @ORM\Column(name="points", type="integer")
*/
private $points;
/**
* @var string
*
* @ORM\Column(name="type", type="string", length=255)
*/
private $type;
/**
* @var boolean
*
* @ORM\Column(name="isEnabled", type="boolean")
*/
private $isEnabled;
/**
*
* @ORM\Column(name="ip", type="string" , length=255)
*/
private $ip;
/**
* @ORM\OneToMany(targetEntity="Securinets\FrontOfficeBundle\Entity\EpreuveChallenger", mappedBy="epreuve")
*/
private $users;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set id2
*
* @param string $id2
* @return Epreuves
*/
public function setId2($id2)
{
$this->id2 = $id2;
return $this;
}
/**
* Get id2
*
* @return string
*/
public function getId2()
{
return $this->id2;
}
/**
* Set name
*
* @param string $name
* @return Epreuves
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* @param string $description
* @return Epreuves
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set url
*
* @param string $url
* @return Epreuves
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* Get url
*
* @return string
*/
public function getUrl()
{
return $this->url;
}
/**
* Set flag
*
* @param string $flag
* @return Epreuves
*/
public function setFlag($flag)
{
$this->flag = $flag;
return $this;
}
/**
* Get flag
*
* @return string
*/
public function getFlag()
{
return $this->flag;
}
/**
* Set points
*
* @param integer $points
* @return Epreuves
*/
public function setPoints($points)
{
$this->points = $points;
return $this;
}
/**
* Get points
*
* @return integer
*/
public function getPoints()
{
return $this->points;
}
/**
* Set type
*
* @param string $type
* @return Epreuves
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* Set isEnabled
*
* @param boolean $isEnabled
* @return Epreuves
*/
public function setIsEnabled($isEnabled)
{
$this->isEnabled = $isEnabled;
return $this;
}
/**
* Get isEnabled
*
* @return boolean
*/
public function getIsEnabled()
{
return $this->isEnabled;
}
/**
* Constructor
*/
public function __construct()
{
$this->users = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add users
*
* @param \Securinets\FrontOfficeBundle\Entity\EpreuveChallenger $users
* @return Epreuve
*/
public function addUser(\Securinets\FrontOfficeBundle\Entity\EpreuveChallenger $users)
{
$this->users[] = $users;
return $this;
}
/**
* Remove users
*
* @param \Securinets\FrontOfficeBundle\Entity\EpreuveChallenger $users
*/
public function removeUser(\Securinets\FrontOfficeBundle\Entity\EpreuveChallenger $users)
{
$this->users->removeElement($users);
}
/**
* Get users
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getUsers()
{
return $this->users;
}
/**
* Add epreuveChallengers
*
* @param \Securinets\FrontOfficeBundle\Entity\EpreuveChallenger $epreuveChallengers
* @return Epreuve
*/
public function <API key>(\Securinets\FrontOfficeBundle\Entity\EpreuveChallenger $epreuveChallengers)
{
$this->epreuveChallengers[] = $epreuveChallengers;
return $this;
}
/**
* Remove epreuveChallengers
*
* @param \Securinets\FrontOfficeBundle\Entity\EpreuveChallenger $epreuveChallengers
*/
public function <API key>(\Securinets\FrontOfficeBundle\Entity\EpreuveChallenger $epreuveChallengers)
{
$this->epreuveChallengers->removeElement($epreuveChallengers);
}
/**
* Get epreuveChallengers
*
* @return \Doctrine\Common\Collections\Collection
*/
public function <API key>()
{
return $this->epreuveChallengers;
}
/**
* Set ip
*
* @param string $ip
* @return Epreuve
*/
public function setIp($ip)
{
$this->ip = $ip;
return $this;
}
/**
* Get ip
*
* @return string
*/
public function getIp()
{
return $this->ip;
}
} |
<!doctype html>
<meta charset="utf-8">
<title>SVG Post Ttile· kapalhq.com</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Define a description for better SEO result -->
<meta name="description" content="This is an example of custom post title using SVG image. You can simply add the folloing setting to your post front-matter field:">
<link rel="alternate" href="/feed.xml" type="application/atom+xml">
<link rel="stylesheet" href="/assets/themes/curtana/css/app.css?assets-inline">
<!-- Canonical links, avoid duplicate content problems -->
<link rel="canonical" href="http://kapalhq.com/svg-post-title.html">
<!-- DNS prefetching for static files -->
<!-- browser-sync, don't remove this -->
<!-- BS_INSERT -->
<!-- Head hooks -->
<meta property="og:type" content="article">
<meta property="og:site_name" content="kapalhq.com">
<meta property="og:title" content="SVG Post Ttile">
<meta property="og:url" content="http://kapalhq.com/svg-post-title.html">
<meta property="og:description" content="This is an example of custom post title using SVG image. You can simply add the folloing setting to your post front-matter field:">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="SVG Post Ttile">
<meta name="twitter:url" content="http://kapalhq.com/svg-post-title.html">
<meta name="<TwitterConsumerkey>" content="This is an example of custom post title using SVG image. You can simply add the folloing setting to your post front-matter field:">
<meta name="twitter:site" content="@kapalhq">
<meta name="twitter:creator" content="@kapalhq">
<!-- Post / page specified styles -->
<!-- Post specified styles -->
<style>
body {
color: #b93b00;
background-color: #ff9610;
}
a,
button {
color: #b93b00;
}
::selection {
color: #9b3100;
}
body:before, .logo {
background: #b93b00;
}
.logo:hover {
background: #9b3100;
}
.navigation li a:hover,
.navigation li a:focus {
color: #ffe000;
}
.current a {
color: #9b3100;
}
.content a {
color: #9b3100;
}
.content ul li:before,
.content ol li:before {
box-shadow: inset 0 0 0 3px #9b3100, inset 0 0 0 5px #ff9610, inset 0 0 0 7px #9b3100;
}
.content code,
.content pre {
color: #ffe000;
}
.note,
.store,
.download {
border-left-color: #9b3100;
}
.external span {
background: #9b3100;
}
:target [rev=footnote],
:target [rel=footnote],
:target .reversefootnote,
:target .footnote {
color: #ffe000;
}
</style>
<!-- Header, just a logo at the moment -->
<header>
<a href="/" class=logo accesskey=x>
<h1>kapalhq.com</h1>
</a>
</header>
<!-- Main navigation with current page / categoriy highlighted -->
<nav class="navigation">
<ul>
<li >
<a href="/">
Home
</a>
</li>
<li >
<a href="/work/">
Work
</a>
</li>
<li >
<a href="/news/">
News
</a>
</li>
<li >
<a href="/about/">
About
</a>
</li>
</ul>
</nav>
<!-- Main content wrap -->
<main class="content
" role=main>
<!-- Post-wide custom CSS -->
<!-- Prepare for image headers -->
<!-- Prepare for SVG header -->
<!-- Article wrapper, limit width -->
<article
>
<!-- Post title -->
<header>
<h1 class="
image-title
" title="SVG Post Ttile">
SVG Post Ttile
<img
src="/assets/svg/kai.svg"
style="width: 40.0vw;"
>
</h1>
<small>
By <span rel="author">kapalHQ</span>
on <time datetime="2014-02-01T00:00:00+11:00">Feb 1, 2014</time>
</small>
</header>
<!-- Post content -->
<div class="post-content">
<p>This is an example of custom post title using SVG image. You can simply add the folloing setting to your post <a href="http://jekyllrb.com/docs/frontmatter/">front-matter field</a>:</p>
<div class="highlighter-rouge"><pre class="highlight"><code>svg-headline: svg/kai.svg
svg-headline-width: 400
svg-headline-height: 86
</code></pre>
</div>
<p>Image defined for <code class="highlighter-rouge">svg-headline</code> should be stored at <code class="highlighter-rouge">_app/_includes/svg/</code>, you can simply keep these title images under Git control, they will be smooshed into the HTML pages using Grunt.js in production environment. The <code class="highlighter-rouge">svg-headline-width</code> and <code class="highlighter-rouge">svg-headline-height</code> can be omitted if you have correct dimensions for your images.</p>
<p>There’s also an option for common raster images, but please note that these files should be stored at where you define <code class="highlighter-rouge">site.file</code>.</p>
<div class="highlighter-rouge"><pre class="highlight"><code>img-headline: imouto-logo-large.png
img-headline-width: 500
</code></pre>
</div>
<p><strong>Pro Tips</strong>: Keep a <code class="highlighter-rouge"><title></code> tag for your SVG can help Safari generate correct post title for its Reader mode:</p>
<div class="highlighter-rouge"><pre class="highlight"><code><svg xmlns="http:
<title>Kai Series</title>
…
</code></pre>
</div>
</div>
</article>
</main>
<!-- Footer section -->
<footer class="footer">
<ul>
<li><a href="/">kapalhq.com</a></li>
<li><a href="http://sparanoid.com/lab/amsf/" title="Almace Scaffolding">AMSF</a></li>
<li><a href="http://github.com/amsf/amsf-curtana" title="Curtana">Curtana</a></li>
<li><a href="/feed.xml" title="Feed - Atom (The Atom Syndication Format)">Atom</a></li>
</ul>
</footer>
<!-- The following code is an example use of including external JavaScript libraries -->
<!-- Theme scripts -->
<script src="/assets/themes/curtana/js/app.js?assets-inline"></script>
<!-- User custom scripts -->
<script src="/assets/js/custom.js?assets-inline"></script>
<!-- Google Analytics tracking code -->
<!-- Foot hooks --> |
/* eslint-env node */
const gulp = require('gulp');
const zip = require('gulp-zip');
const del = require('del');
const pkg = require('./package.json');
let versionedPane = `panes-${pkg.<API key>[0].replace(
/\./g,
'-'
)}`;
function compress(baseSrc, archiveName) {
return gulp
.src(`${baseSrc}*`)
.pipe(zip(archiveName))
.pipe(gulp.dest('dist'));
}
exports['compress:chrome'] = () =>
compress('dist/chrome', 'chrome/ember-inspector.zip');
exports['compress:firefox'] = () =>
compress('dist/firefox', 'firefox/ember-inspector.zip');
exports['compress:chrome-pane'] = () =>
compress(`dist/chrome/${versionedPane}`, 'chrome-pane.zip');
exports['compress:firefox-pane'] = () =>
compress(`dist/firefox/${versionedPane}`, 'firefox-pane.zip');
exports['compress:bookmarklet-pane'] = () =>
compress(`dist/bookmarklet/${versionedPane}`, 'bookmarklet-pane.zip');
exports['clean-tmp'] = () => del('./tmp'); |
<?php
use Fake\<API key>;
use Fake\ContainerDetails;
use Fake\Logs;
use Symfony\Component\Console\Tester\ApplicationTester;
use Test\Compose\PredictableProject;
use Test\Doctor\NullDoctor;
use Test\Plugins\ExtraHostname\<API key>;
use Test\Project\PredictableManager;
$container = require __DIR__ . '/../../../app/container.php';
$container['containers.<API key>'] = function ($c) {
return new <API key>();
};
$container['containers.container_details'] = function ($c) {
return new ContainerDetails();
};
$container['application_tester'] = function ($c) {
$application = $c['application'];
$application->setAutoExit(false);
return new ApplicationTester($application);
};
$container['logs'] = function ($c) {
return new Logs($c['console.user_interaction']);
};
$container['compose.project'] = function () {
return new PredictableProject(getcwd());
};
$container['doctor'] = function () {
return new NullDoctor();
};
$container['project.manager.docker_compose'] = function() {
return new PredictableManager();
};
$container['plugins.extra_hostname.<API key>'] = function($c) {
return new <API key>();
};
return $container; |
orion.collections.onCreated(function() {
var self = this;
/**
* Register the link
*/
var linkOptions = _.extend({
identifier: 'collections-' + self.name,
routeName: 'collections.' + self.name + '.index',
activeRouteRegex: 'collections.' + self.name,
permission: 'collections.' + self.name + '.index',
title: self.name[0].toUpperCase() + self.name.slice(1),
index: 30,
}, self.link);
orion.links.add(linkOptions);
var getCollection = function() {
var collection = null;
try {
var path = RouterLayer.getPath().split('/')[2];
collection = orion.collections.list[path];
} catch (e) {
console.log('Error getting collection', e);
}
return collection;
};
ReactiveTemplates.helpers('collections.' + self.name + '.index', {
collection: function() {
return getCollection();
},
});
ReactiveTemplates.helpers('collections.' + self.name + '.create', {
collection: function() {
return getCollection();
},
});
ReactiveTemplates.onCreated('collections.' + self.name + '.update', function() {
this.autorun(() => {
var collection = getCollection();
if (collection) {
if (collection.autopublishUpdate && RouterLayer.isActiveRoute('collections.' + collection.name + '.update')) {
this.subscribe('adminGetOne.' + getCollection().name, RouterLayer.getParam('_id'));
}
}
});
});
ReactiveTemplates.helpers('collections.' + self.name + '.update', {
collection: function() {
return getCollection();
},
item: function() {
return getCollection() && getCollection().findOne(RouterLayer.getParam('_id'));
},
});
ReactiveTemplates.onCreated('collections.' + self.name + '.delete', function() {
var template = this;
template.autorun(function() {
getCollection() && RouterLayer.isActiveRoute('collections.' + getCollection().name + '.delete') && template.subscribe('adminGetOne.' + getCollection().name, RouterLayer.getParam('_id'));
});
});
ReactiveTemplates.helpers('collections.' + self.name + '.delete', {
collection: function() {
return getCollection();
},
item: function() {
return getCollection().findOne(RouterLayer.getParam('_id'));
},
});
ReactiveTemplates.events('collections.' + self.name + '.delete', {
'click .confirm-delete': function() {
var objectId = RouterLayer.getParam('_id');
self.remove(objectId, function(error, result) {
if (error) {
console.warn('Error while deleting', objectId, 'in collection', getCollection().name, ':', error);
}
// Only go back to index in case the deletion has been properly achieved
if (result === 1) {
RouterLayer.go(getCollection().indexPath());
}
});
},
});
}); |
#!/usr/bin/env python
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# in all copies or substantial portions of the Software.
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Test that a module that we import into an SConscript file can itself
easily import the global SCons variables, and a handful of other variables
directly from SCons.Script modules.
"""
import TestSCons
test = TestSCons.TestSCons()
test.write('SConstruct', """\
import m1
""")
test.write("m1.py", """\
from SCons.Script import *
SConscript('SConscript')
""")
test.write('SConscript', """\
import m2
import m3
import m4
""")
test.write("m2.py", """\
from SCons.Script import *
Command("file.out", "file.in", Copy("$TARGET", "$SOURCE"))
""")
test.write("m3.py", """\
import SCons.Script
SCons.Script.BuildTask
SCons.Script.CleanTask
SCons.Script.QuestionTask
#SCons.Script.PrintHelp
SCons.Script.OptParser
SCons.Script.<API key>
SCons.Script.keep_going_on_error
#SCons.Script.print_dtree
SCons.Script.print_explanations
SCons.Script.print_includes
SCons.Script.print_objects
SCons.Script.print_time
#SCons.Script.print_tree
SCons.Script.memory_stats
SCons.Script.ignore_errors
#SCons.Script.sconscript_time
#SCons.Script.command_time
#SCons.Script.exit_status
#SCons.Script.profiling
SCons.Script.repositories
""")
test.write("m4.py", """\
import SCons.Script.SConscript
SCons.Script.SConscript.Arguments
SCons.Script.SConscript.ArgList
SCons.Script.SConscript.BuildTargets
SCons.Script.SConscript.CommandLineTargets
SCons.Script.SConscript.DefaultTargets
""")
test.write("file.in", "file.in\n")
test.run(arguments = '.')
test.must_match("file.out", "file.in\n")
test.pass_test() |
#include "build.auto.h"
#ifdef HAVE_LIBLZ4
#include <lz4frame.h>
#include "common/compress/lz4/common.h"
#include "common/debug.h"
LZ4F_errorCode_t
lz4Error(LZ4F_errorCode_t error)
{
FUNCTION_TEST_BEGIN();
FUNCTION_TEST_PARAM(SIZE, error);
FUNCTION_TEST_END();
if (LZ4F_isError(error))
THROW_FMT(FormatError, "lz4 error: [%zd] %s", (ssize_t)error, LZ4F_getErrorName(error));
<API key>(error);
}
#endif // HAVE_LIBLZ4 |
#if !NETFX_CORE && !PCL36 && !XAMARIN
// <summary>Displays an error dialog for any exceptions</summary>
using System;
using System.Windows;
using System.Windows.Controls;
namespace Csla.Xaml
{
<summary>
Displays an error dialog for any exceptions
that occur in a CslaDataProvider.
</summary>
public class ErrorDialog : Control, IErrorDialog
{
<summary>
Creates a new instance of the control.
</summary>
public ErrorDialog()
{
this.DialogIcon = MessageBoxImage.Exclamation;
this.DataContextChanged += <API key>;
}
void <API key>(object sender, <API key> e)
{
DetachSource(e.OldValue);
AttachSource(e.NewValue);
}
<summary>
Gets or sets the title of the error
dialog.
</summary>
public static readonly DependencyProperty DialogTitleProperty = DependencyProperty.Register(
"DialogTitle",
typeof(string),
typeof(ErrorDialog),
null);
<summary>
Gets or sets the title of the error
dialog.
</summary>
public string DialogTitle
{
get { return (string)GetValue(DialogTitleProperty); }
set { SetValue(DialogTitleProperty, value); }
}
<summary>
Gets or sets the first line of text displayed
within the error dialog (before the
exception message).
</summary>
public static readonly DependencyProperty <API key> = DependencyProperty.Register(
"DialogFirstLine",
typeof(string),
typeof(ErrorDialog),
null);
<summary>
Gets or sets the first line of text displayed
within the error dialog (before the
exception message).
</summary>
public string DialogFirstLine
{
get { return (string)GetValue(<API key>); }
set { SetValue(<API key>, value); }
}
<summary>
Gets or sets a value indicating whether
the dialog should include exception details
or just the exception summary message.
</summary>
public static readonly DependencyProperty <API key> = DependencyProperty.Register(
"ShowExceptionDetail",
typeof(bool),
typeof(ErrorDialog),
null);
<summary>
Gets or sets the first line of text displayed
within the error dialog (before the
exception message).
</summary>
public bool ShowExceptionDetail
{
get { return (bool)GetValue(<API key>); }
set { SetValue(<API key>, value); }
}
<summary>
Gets or sets a value indicating whether
the dialog should include exception details
or just the exception summary message.
</summary>
public static readonly DependencyProperty DialogIconProperty = DependencyProperty.Register(
"DialogIcon",
typeof(MessageBoxImage),
typeof(ErrorDialog),
null);
<summary>
Gets or sets the icon displayed in
the dialog.
</summary>
public MessageBoxImage DialogIcon
{
get { return (MessageBoxImage)GetValue(DialogIconProperty); }
set { SetValue(DialogIconProperty, value); }
}
internal void Register(object source)
{
AttachSource(source);
}
private void AttachSource(object source)
{
var dp = source as System.Windows.Data.DataSourceProvider;
if (dp != null)
dp.DataChanged += source_DataChanged;
}
private void DetachSource(object source)
{
var dp = source as System.Windows.Data.DataSourceProvider;
if (dp != null)
dp.DataChanged -= source_DataChanged;
}
private void source_DataChanged(object sender, EventArgs e)
{
var dp = sender as System.Windows.Data.DataSourceProvider;
if (dp != null && dp.Error != null)
{
string error;
if (this.ShowExceptionDetail)
error = dp.Error.ToString();
else
error = dp.Error.Message;
string output;
if (string.IsNullOrEmpty(this.DialogFirstLine))
output = error;
else
output = string.Format("{0}{1}{2}", this.DialogFirstLine, Environment.NewLine, error);
MessageBox.Show(
output,
this.DialogTitle,
MessageBoxButton.OK,
this.DialogIcon);
}
}
#region IErrorDialog Members
void IErrorDialog.Register(object source)
{
AttachSource(source);
}
#endregion
}
}
#endif |
using Raksha.Asn1;
using Raksha.Asn1.Pkcs;
namespace Raksha.Asn1.Cms
{
public abstract class CmsAttributes
{
public static readonly DerObjectIdentifier ContentType = <API key>.Pkcs9AtContentType;
public static readonly DerObjectIdentifier MessageDigest = <API key>.<API key>;
public static readonly DerObjectIdentifier SigningTime = <API key>.Pkcs9AtSigningTime;
public static readonly DerObjectIdentifier CounterSignature = <API key>.<API key>;
public static readonly DerObjectIdentifier ContentHint = <API key>.IdAAContentHint;
}
} |
# Twitter Bootstrap Theme For Kaminari
## Dependencies
Kaminari
https://github.com/amatsuda/kaminari
ruby
gem 'kaminari'
Twitter Bootstrap
- SCSS Flavor (Asset Pipeline): https://github.com/anjlab/bootstrap-rails
- Less Flavor (Asset Pipeline): https://github.com/seyhunak/<TwitterConsumerkey>
- Vanilla: https://github.com/twitter/bootstrap
## Usage
Add Kaminari and some form of Twitter Bootstrap to your project.
Require `bootstrap_kaminari` in your Gemfile:
ruby
gem 'bootstrap_kaminari'
or
ruby
gem 'bootstrap_kaminari', :git => 'git://github.com/dleavitt/bootstrap_kaminari.git'
The theme is namespaced, so invoke it like this:
ruby
paginate @items, theme: "bootstrap" |
# NOTICE: THIS FILE IS AUTOGENERATED
# MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
# PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dwarf_gronda.iff"
result.<API key> = 9
result.stfName("monster_name","gronda")
return result |
.header
{
background-color: #AAAAAA;
border-bottom: thick solid #000000;
position: absolute;
left: 0px;
right: 0px;
top: 0px;
}
.login_options
{
background-color: #AAAAAA;
border: thick inset #000000;
border-radius: 10px;
position: absolute;
left: 20px;
top: 100px;
padding-left: 10px;
padding-right: 10px;
padding-top: 10px;
padding-bottom: 10px;
}
.user_options
{
position: absolute;
right: 20px;
top: 10px;
} |
var path = require('path');
var webpack = require('webpack');
var plugins = [new webpack.<API key>()];
var entry = ['./src/index'];
if(process.env.NODE_ENV === "production") {
plugins.push(new webpack.optimize.UglifyJsPlugin({minimize: true, comments: false}));
} else {
entry.push('webpack-dev-server/client?http://localhost:3000');
entry.push('webpack/hot/only-dev-server');
}
module.exports = {
devtool: 'eval',
entry: entry,
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: plugins,
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
include: path.join(__dirname, 'src')
}]
}
}; |
import { Instruction, INUMBER, IOP1, IOP2, IOP3, IVAR, IVARNAME, IEXPR, IMEMBER, IARRAY } from './instruction';
export default function simplify(tokens, unaryOps, binaryOps, ternaryOps, values) {
var nstack = [];
var newexpression = [];
var n1, n2, n3;
var f;
for (var i = 0; i < tokens.length; i++) {
var item = tokens[i];
var type = item.type;
if (type === INUMBER || type === IVARNAME) {
if (Array.isArray(item.value)) {
nstack.push.apply(nstack, simplify(item.value.map(function (x) {
return new Instruction(INUMBER, x);
}).concat(new Instruction(IARRAY, item.value.length)), unaryOps, binaryOps, ternaryOps, values));
} else {
nstack.push(item);
}
} else if (type === IVAR && values.hasOwnProperty(item.value)) {
item = new Instruction(INUMBER, values[item.value]);
nstack.push(item);
} else if (type === IOP2 && nstack.length > 1) {
n2 = nstack.pop();
n1 = nstack.pop();
f = binaryOps[item.value];
item = new Instruction(INUMBER, f(n1.value, n2.value));
nstack.push(item);
} else if (type === IOP3 && nstack.length > 2) {
n3 = nstack.pop();
n2 = nstack.pop();
n1 = nstack.pop();
if (item.value === '?') {
nstack.push(n1.value ? n2.value : n3.value);
} else {
f = ternaryOps[item.value];
item = new Instruction(INUMBER, f(n1.value, n2.value, n3.value));
nstack.push(item);
}
} else if (type === IOP1 && nstack.length > 0) {
n1 = nstack.pop();
f = unaryOps[item.value];
item = new Instruction(INUMBER, f(n1.value));
nstack.push(item);
} else if (type === IEXPR) {
while (nstack.length > 0) {
newexpression.push(nstack.shift());
}
newexpression.push(new Instruction(IEXPR, simplify(item.value, unaryOps, binaryOps, ternaryOps, values)));
} else if (type === IMEMBER && nstack.length > 0) {
n1 = nstack.pop();
nstack.push(new Instruction(INUMBER, n1.value[item.value]));
while (nstack.length > 0) {
newexpression.push(nstack.shift());
}
newexpression.push(item);
}
}
while (nstack.length > 0) {
newexpression.push(nstack.shift());
}
return newexpression;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.