answer
stringlengths 15
1.25M
|
|---|
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */
#define VTK_WRAPPING_CXX
#define <API key>
#include <nan.h>
#include "vtkObjectWrap.h"
#include "<API key>.h"
#include "vtkObjectBaseWrap.h"
#include "vtkContext2DWrap.h"
#include "vtkContextSceneWrap.h"
#include "../../plus/plus.h"
using namespace v8;
extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> <API key>::ptpl;
<API key>::<API key>()
{ }
<API key>::<API key>(vtkSmartPointer<<API key>> _native)
{ native = _native; }
<API key>::~<API key>()
{ }
void <API key>::Init(v8::Local<v8::Object> exports)
{
Nan::SetAccessor(exports, Nan::New("<API key>").ToLocalChecked(), ConstructorGetter);
Nan::SetAccessor(exports, Nan::New("AbstractContextItem").ToLocalChecked(), ConstructorGetter);
}
void <API key>::ConstructorGetter(
v8::Local<v8::String> property,
const Nan::<API key><v8::Value>& info)
{
InitPtpl();
info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}
void <API key>::InitPtpl()
{
if (!ptpl.IsEmpty()) return;
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
VtkObjectWrap::InitPtpl( );
tpl->Inherit(Nan::New<FunctionTemplate>(VtkObjectWrap::ptpl));
tpl->SetClassName(Nan::New("<API key>").ToLocalChecked());
tpl->InstanceTemplate()-><API key>(1);
Nan::SetPrototypeMethod(tpl, "ClearItems", ClearItems);
Nan::SetPrototypeMethod(tpl, "clearItems", ClearItems);
Nan::SetPrototypeMethod(tpl, "GetInteractive", GetInteractive);
Nan::SetPrototypeMethod(tpl, "getInteractive", GetInteractive);
Nan::SetPrototypeMethod(tpl, "GetParent", GetParent);
Nan::SetPrototypeMethod(tpl, "getParent", GetParent);
Nan::SetPrototypeMethod(tpl, "GetScene", GetScene);
Nan::SetPrototypeMethod(tpl, "getScene", GetScene);
Nan::SetPrototypeMethod(tpl, "GetVisible", GetVisible);
Nan::SetPrototypeMethod(tpl, "getVisible", GetVisible);
Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "Paint", Paint);
Nan::SetPrototypeMethod(tpl, "paint", Paint);
Nan::SetPrototypeMethod(tpl, "PaintChildren", PaintChildren);
Nan::SetPrototypeMethod(tpl, "paintChildren", PaintChildren);
Nan::SetPrototypeMethod(tpl, "<API key>", <API key>);
Nan::SetPrototypeMethod(tpl, "<API key>", <API key>);
Nan::SetPrototypeMethod(tpl, "RemoveItem", RemoveItem);
Nan::SetPrototypeMethod(tpl, "removeItem", RemoveItem);
Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "SetInteractive", SetInteractive);
Nan::SetPrototypeMethod(tpl, "setInteractive", SetInteractive);
Nan::SetPrototypeMethod(tpl, "SetParent", SetParent);
Nan::SetPrototypeMethod(tpl, "setParent", SetParent);
Nan::SetPrototypeMethod(tpl, "SetScene", SetScene);
Nan::SetPrototypeMethod(tpl, "setScene", SetScene);
Nan::SetPrototypeMethod(tpl, "SetVisible", SetVisible);
Nan::SetPrototypeMethod(tpl, "setVisible", SetVisible);
Nan::SetPrototypeMethod(tpl, "Update", Update);
Nan::SetPrototypeMethod(tpl, "update", Update);
#ifdef <API key>
<API key>
#endif
ptpl.Reset( tpl );
}
void <API key>::New(const Nan::<API key><v8::Value>& info)
{
if(!info.IsConstructCall())
{
Nan::ThrowError("Constructor not called in a construct call.");
return;
}
if(info.Length() == 0)
{
Nan::ThrowError("Cannot create instance of abstract class.");
return;
}
else
{
if(info[0]->ToObject() != vtkNodeJsNoWrap )
{
Nan::ThrowError("Parameter Error");
return;
}
}
info.GetReturnValue().Set(info.This());
}
void <API key>::ClearItems(const Nan::<API key><v8::Value>& info)
{
<API key> *wrapper = ObjectWrap::Unwrap<<API key>>(info.Holder());
<API key> *native = (<API key> *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->ClearItems();
}
void <API key>::GetInteractive(const Nan::<API key><v8::Value>& info)
{
<API key> *wrapper = ObjectWrap::Unwrap<<API key>>(info.Holder());
<API key> *native = (<API key> *)wrapper->native.GetPointer();
bool r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetInteractive();
info.GetReturnValue().Set(Nan::New(r));
}
void <API key>::GetParent(const Nan::<API key><v8::Value>& info)
{
<API key> *wrapper = ObjectWrap::Unwrap<<API key>>(info.Holder());
<API key> *native = (<API key> *)wrapper->native.GetPointer();
<API key> * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetParent();
<API key>::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(<API key>::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
<API key> *w = new <API key>();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void <API key>::GetScene(const Nan::<API key><v8::Value>& info)
{
<API key> *wrapper = ObjectWrap::Unwrap<<API key>>(info.Holder());
<API key> *native = (<API key> *)wrapper->native.GetPointer();
vtkContextScene * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetScene();
VtkContextSceneWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkContextSceneWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkContextSceneWrap *w = new VtkContextSceneWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void <API key>::GetVisible(const Nan::<API key><v8::Value>& info)
{
<API key> *wrapper = ObjectWrap::Unwrap<<API key>>(info.Holder());
<API key> *native = (<API key> *)wrapper->native.GetPointer();
bool r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetVisible();
info.GetReturnValue().Set(Nan::New(r));
}
void <API key>::NewInstance(const Nan::<API key><v8::Value>& info)
{
<API key> *wrapper = ObjectWrap::Unwrap<<API key>>(info.Holder());
<API key> *native = (<API key> *)wrapper->native.GetPointer();
<API key> * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->NewInstance();
<API key>::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(<API key>::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
<API key> *w = new <API key>();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void <API key>::Paint(const Nan::<API key><v8::Value>& info)
{
<API key> *wrapper = ObjectWrap::Unwrap<<API key>>(info.Holder());
<API key> *native = (<API key> *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkContext2DWrap::ptpl))->HasInstance(info[0]))
{
VtkContext2DWrap *a0 = ObjectWrap::Unwrap<VtkContext2DWrap>(info[0]->ToObject());
bool r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Paint(
(vtkContext2D *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
Nan::ThrowError("Parameter mismatch");
}
void <API key>::PaintChildren(const Nan::<API key><v8::Value>& info)
{
<API key> *wrapper = ObjectWrap::Unwrap<<API key>>(info.Holder());
<API key> *native = (<API key> *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkContext2DWrap::ptpl))->HasInstance(info[0]))
{
VtkContext2DWrap *a0 = ObjectWrap::Unwrap<VtkContext2DWrap>(info[0]->ToObject());
bool r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->PaintChildren(
(vtkContext2D *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
Nan::ThrowError("Parameter mismatch");
}
void <API key>::<API key>(const Nan::<API key><v8::Value>& info)
{
<API key> *wrapper = ObjectWrap::Unwrap<<API key>>(info.Holder());
<API key> *native = (<API key> *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native-><API key>();
}
void <API key>::RemoveItem(const Nan::<API key><v8::Value>& info)
{
<API key> *wrapper = ObjectWrap::Unwrap<<API key>>(info.Holder());
<API key> *native = (<API key> *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(<API key>::ptpl))->HasInstance(info[0]))
{
<API key> *a0 = ObjectWrap::Unwrap<<API key>>(info[0]->ToObject());
bool r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->RemoveItem(
(<API key> *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
Nan::ThrowError("Parameter mismatch");
}
void <API key>::SafeDownCast(const Nan::<API key><v8::Value>& info)
{
<API key> *wrapper = ObjectWrap::Unwrap<<API key>>(info.Holder());
<API key> *native = (<API key> *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0]))
{
VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject());
<API key> * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->SafeDownCast(
(vtkObjectBase *) a0->native.GetPointer()
);
<API key>::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(<API key>::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
<API key> *w = new <API key>();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void <API key>::SetInteractive(const Nan::<API key><v8::Value>& info)
{
<API key> *wrapper = ObjectWrap::Unwrap<<API key>>(info.Holder());
<API key> *native = (<API key> *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsBoolean())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetInteractive(
info[0]->BooleanValue()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void <API key>::SetParent(const Nan::<API key><v8::Value>& info)
{
<API key> *wrapper = ObjectWrap::Unwrap<<API key>>(info.Holder());
<API key> *native = (<API key> *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(<API key>::ptpl))->HasInstance(info[0]))
{
<API key> *a0 = ObjectWrap::Unwrap<<API key>>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetParent(
(<API key> *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void <API key>::SetScene(const Nan::<API key><v8::Value>& info)
{
<API key> *wrapper = ObjectWrap::Unwrap<<API key>>(info.Holder());
<API key> *native = (<API key> *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkContextSceneWrap::ptpl))->HasInstance(info[0]))
{
VtkContextSceneWrap *a0 = ObjectWrap::Unwrap<VtkContextSceneWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetScene(
(vtkContextScene *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void <API key>::SetVisible(const Nan::<API key><v8::Value>& info)
{
<API key> *wrapper = ObjectWrap::Unwrap<<API key>>(info.Holder());
<API key> *native = (<API key> *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsBoolean())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetVisible(
info[0]->BooleanValue()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void <API key>::Update(const Nan::<API key><v8::Value>& info)
{
<API key> *wrapper = ObjectWrap::Unwrap<<API key>>(info.Holder());
<API key> *native = (<API key> *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Update();
}
|
<!DOCTYPE html>
<html>
<head>
<title>PKIjs Mocha Test - OCSP Request Complex Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css" />
</head>
<body>
<div id="mocha"></div>
<script src="https://cdn.rawgit.com/jquery/jquery/2.1.4/dist/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js"></script>
<script src="https://cdn.rawgit.com/chaijs/chai/4.0.0-canary.1/chai.js"></script>
<script>mocha.setup('bdd'); window.assert = chai.assert;</script>
<script type="text/javascript" src="<API key>.js"></script>
<script>
mocha.checkLeaks();
mocha.globals(['jQuery']);
mocha.run();
</script>
</body>
</html>
|
package org.chasen.mecab.wrapper;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.junit.Test;
public class NodeIteratorTest {
@Test
public void threads() throws <API key> {
List<Thread> threads = new ArrayList<Thread>();
threads.add(new Thread(){
public void run(){
Tagger t = Tagger.create("-r /opt/local/etc/mecabrc");
for(MecabNode<Node, Path> node: t.iterator("")){
System.out.println(node.getSurface());
}
}
});
threads.add(new Thread(){
public void run(){
Tagger t = Tagger.create("-r /opt/local/etc/mecabrc");
for(MecabNode<Node, Path> node: t.iterator("")){
System.out.println(node.getSurface());
}
}
});
threads.add(new Thread(){
public void run(){
Tagger t = Tagger.create("-r /opt/local/etc/mecabrc");
for(MecabNode<Node, Path> node: t.iterator("")){
System.out.println(node.getSurface());
}
}
});
for(Thread th: threads){
th.start();
}
for(Thread th: threads){
th.join();
}
}
@Test
public void executors() throws <API key>, ExecutionException {
class Hoge {
public void parse(String str){
Tagger t = Tagger.create("-r /opt/local/etc/mecabrc");
for(MecabNode<Node, Path> node: t.iterator(str)){
System.out.println(node.getSurface());
}
}
}
final Hoge hoge = new Hoge();
ExecutorService executors = Executors.newCachedThreadPool();
List<Future<?>> futures = new ArrayList<Future<?>>();
futures.add(executors.submit(new Callable<Void>(){
public Void call() throws Exception {
hoge.parse("");
return null;
}
}));
futures.add(executors.submit(new Callable<Void>(){
public Void call() throws Exception {
hoge.parse("");
return null;
}
}));
futures.add(executors.submit(new Callable<Void>(){
public Void call() throws Exception {
hoge.parse("");
return null;
}
}));
for(Future<?> f: futures){
f.get();
}
}
@Test
public void executors_runnable() throws <API key>, ExecutionException {
class Hoge implements Runnable {
String str;
Hoge(String str){
this.str = str;
}
public void run(){
Tagger t = Tagger.create("-r /opt/local/etc/mecabrc");
for(MecabNode<Node, Path> node: t.iterator(str)){
System.out.println(node.getSurface());
}
}
}
ExecutorService executors = Executors.newCachedThreadPool();
List<Future<?>> futures = new ArrayList<Future<?>>();
futures.add(executors.submit(new Hoge("")));
futures.add(executors.submit(new Hoge("")));
futures.add(executors.submit(new Hoge("")));
for(Future<?> f: futures){
f.get();
}
}
}
|
<html>
<body>
<p>Registration was requested {{ email }}. Open the link below to confirm e-mail address and continue registration.</p>
<a href="{{ url }}">{{ url }}</a>
</body>
</html>
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <iostream>
#include <string>
#include "parser.h"
#include "CLI/wrapper.h"
#include "Libraries/linenoise.h"
#include "CLI/interface.h"
#define HIST_FILENAME ".polyBobHistory"
int main(int argc, char **argv)
{
char* line;
unsigned int promptNb = 1;
char promptMsg[100];
srand(time(NULL));
printLogo();
/* Set the completion callback. This will be called every time the
* user uses the <tab> key. */
<API key>(completion);
/* Load history from file.*/
<API key>(HIST_FILENAME); /* Load the history at startup */
snprintf(promptMsg, 100, "%s[%d]: ", "\033[0m", promptNb);
while((line = linenoise(promptMsg)) != NULL)
{
linenoiseHistoryAdd(line); /* Add to the history. */
<API key>(HIST_FILENAME); /* Save the history on disk. */
/* Do something with the string. */
rmSuperscript(line);
if(line[0] == '/')
parseCommand(&(line[1]));
else if(!strcmp(line, "exit") || !strcmp(line, "quit") || (line[1] == 0 && (line[0] == 'e' || line[0] == 'q')))
break;
else if(line[0] != '\0')
{
simpleParserAPI(line);
}
snprintf(promptMsg, 100, "[%d]: ", ++promptNb);
}
finalProcessing();
return 0;
}
|
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>BuildmLearn Store: org.buildmlearn.appstore.activities.HomeActivity Class Reference</title>
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../jquery.js"></script>
<script type="text/javascript" src="../../dynsections.js"></script>
<link href="../../navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../resize.js"></script>
<script type="text/javascript" src="../../navtreedata.js"></script>
<script type="text/javascript" src="../../navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="../../search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../search/searchdata.js"></script>
<script type="text/javascript" src="../../search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="../../ic_launcher.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">BuildmLearn Store
 <span id="projectnumber">1.0.0.0</span>
</div>
<div id="projectbrief">An android app, which is a store for apps built using BuildmLearn ToolKit</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.10 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "../../search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="../../index.html"><span>Main Page</span></a></li>
<li><a href="../../namespaces.html"><span>Packages</span></a></li>
<li class="current"><a href="../../annotated.html"><span>Classes</span></a></li>
<li><a href="../../files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="../../search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="../../search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="../../annotated.html"><span>Class List</span></a></li>
<li><a href="../../classes.html"><span>Class Index</span></a></li>
<li><a href="../../inherits.html"><span>Class Hierarchy</span></a></li>
<li><a href="../../functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('d8/dfa/<API key>.html','../../');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="<API key>">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="#pub-static-methods">Static Public Member Functions</a> |
<a href="#pro-methods">Protected Member Functions</a> |
<a href="#pri-attribs">Private Attributes</a> |
<a href="#pri-static-attribs">Static Private Attributes</a> |
<a href="../../d9/dbd/<API key>.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">org.buildmlearn.appstore.activities.HomeActivity Class Reference</div> </div>
</div><!--header
<div class="contents">
<p>This class is the Home Page, which has a viewpager to display tabs for Store section and My-Apps section.
<a href="../../d8/dfa/<API key>.html#details">More...</a></p>
<div id="dynsection-0" onclick="return toggleVisibility(this)" class="dynheader closed" style="cursor:pointer;">
<img id="<API key>" src="../../closed.png" alt="+"/> Inheritance diagram for org.buildmlearn.appstore.activities.HomeActivity:</div>
<div id="<API key>" class="dynsummary" style="display:block;">
</div>
<div id="<API key>" class="dyncontent" style="display:none;">
<div class="center"><img src="../../da/d6b/classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_home_activity__inherit__graph.png" border="0" usemap="#<API key>" alt="Inheritance graph"/></div>
<map name="<API key>" id="<API key>">
<area shape="rect" id="node2" href="../../d0/d60/<API key>.html" title="This class is the parent class to which almost all the activities extends to. " alt="" coords="5,5,228,361"/>
</map>
</div>
<div id="dynsection-1" onclick="return toggleVisibility(this)" class="dynheader closed" style="cursor:pointer;">
<img id="<API key>" src="../../closed.png" alt="+"/> Collaboration diagram for org.buildmlearn.appstore.activities.HomeActivity:</div>
<div id="<API key>" class="dynsummary" style="display:block;">
</div>
<div id="<API key>" class="dyncontent" style="display:none;">
<div class="center"><img src="../../de/d49/<API key>.png" border="0" usemap="#<API key>" alt="Collaboration graph"/></div>
<map name="<API key>" id="<API key>">
<area shape="rect" id="node2" href="../../d0/d60/<API key>.html" title="This class is the parent class to which almost all the activities extends to. " alt="" coords="5,5,228,361"/>
</map>
</div>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d8/dfa/<API key>.html#<API key>">onBackPressed</a> ()</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">This method is automatically called when the user presses the back button on his mobile. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pub_methods_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td colspan="2" onclick="javascript:toggleInherit('pub_methods_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity')"><img src="../../closed.png" alt="-"/> Public Member Functions inherited from <a class="el" href="../../d0/d60/<API key>.html">org.buildmlearn.appstore.activities.NavigationActivity</a></td></tr>
<tr class="memitem:<API key> inherit pub_methods_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memItemLeft" align="right" valign="top">boolean </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d0/d60/<API key>.html#<API key>">onCreateOptionsMenu</a> (Menu menu)</td></tr>
<tr class="memdesc:<API key> inherit pub_methods_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="mdescLeft"> </td><td class="mdescRight">This method creates menu items to be shown on the Action Bar. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key> inherit pub_methods_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-static-methods"></a>
Static Public Member Functions</h2></td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">static void </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d8/dfa/<API key>.html#<API key>">MyAppsView</a> ()</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Set the current view to My-Apps section. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pub_static_methods_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td colspan="2" onclick="javascript:toggleInherit('pub_static_methods_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity')"><img src="../../closed.png" alt="-"/> Static Public Member Functions inherited from <a class="el" href="../../d0/d60/<API key>.html">org.buildmlearn.appstore.activities.NavigationActivity</a></td></tr>
<tr class="memitem:<API key> inherit pub_static_methods_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memItemLeft" align="right" valign="top">static void </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d0/d60/<API key>.html#<API key>">clearSearch</a> ()</td></tr>
<tr class="memdesc:<API key> inherit pub_static_methods_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="mdescLeft"> </td><td class="mdescRight">It clears the text in the search tool and collapses the search tool. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key> inherit pub_static_methods_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pro-methods"></a>
Protected Member Functions</h2></td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d8/dfa/<API key>.html#<API key>">onCreate</a> (Bundle savedInstanceState)</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">The method is executed first when the activity is created. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pro_methods_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td colspan="2" onclick="javascript:toggleInherit('pro_methods_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity')"><img src="../../closed.png" alt="-"/> Protected Member Functions inherited from <a class="el" href="../../d0/d60/<API key>.html">org.buildmlearn.appstore.activities.NavigationActivity</a></td></tr>
<tr class="memitem:<API key> inherit pro_methods_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d0/d60/<API key>.html#<API key>">onCreate</a> (Bundle savedInstanceState)</td></tr>
<tr class="memdesc:<API key> inherit pro_methods_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="mdescLeft"> </td><td class="mdescRight">The method is executed first when the activity is created. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key> inherit pro_methods_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pri-attribs"></a>
Private Attributes</h2></td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">final CharSequence[] </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d8/dfa/<API key>.html#<API key>">TITLES</a> ={"Store","My <a class="el" href="../../d7/d09/<API key>.html">Apps</a>"}</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">MaterialDialog </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d8/dfa/<API key>.html#<API key>">mAlertDialog</a></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pri-static-attribs"></a>
Static Private Attributes</h2></td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">static ViewPager </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d8/dfa/<API key>.html#<API key>">mPager</a></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="inherited"></a>
Additional Inherited Members</h2></td></tr>
<tr class="inherit_header pub_static_attribs_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td colspan="2" onclick="javascript:toggleInherit('pub_static_attribs_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity')"><img src="../../closed.png" alt="-"/> Static Public Attributes inherited from <a class="el" href="../../d0/d60/<API key>.html">org.buildmlearn.appstore.activities.NavigationActivity</a></td></tr>
<tr class="memitem:<API key> inherit pub_static_attribs_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memItemLeft" align="right" valign="top">static FrameLayout </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d0/d60/<API key>.html#<API key>">frameLayout</a></td></tr>
<tr class="separator:<API key> inherit pub_static_attribs_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key> inherit pub_static_attribs_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memItemLeft" align="right" valign="top">static final List< <a class="el" href="../../d7/d09/<API key>.html">Apps</a> > </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d0/d60/<API key>.html#<API key>">appList</a> = new ArrayList<>()</td></tr>
<tr class="separator:<API key> inherit pub_static_attribs_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pac_static_attribs_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td colspan="2" onclick="javascript:toggleInherit('pac_static_attribs_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity')"><img src="../../closed.png" alt="-"/> Static Package Attributes inherited from <a class="el" href="../../d0/d60/<API key>.html">org.buildmlearn.appstore.activities.NavigationActivity</a></td></tr>
<tr class="memitem:<API key> inherit pac_static_attribs_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memItemLeft" align="right" valign="top">static DrawerLayout </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d0/d60/<API key>.html#<API key>">mDrawer</a></td></tr>
<tr class="separator:<API key> inherit pac_static_attribs_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key> inherit pac_static_attribs_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memItemLeft" align="right" valign="top">static int </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d0/d60/<API key>.html#<API key>">mActive</a> =1</td></tr>
<tr class="separator:<API key> inherit pac_static_attribs_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key> inherit pac_static_attribs_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memItemLeft" align="right" valign="top">static String </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d0/d60/<API key>.html#<API key>">searchQuery</a> =""</td></tr>
<tr class="separator:<API key> inherit pac_static_attribs_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key> inherit pac_static_attribs_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memItemLeft" align="right" valign="top">static int </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d0/d60/<API key>.html#<API key>"><API key></a> =0</td></tr>
<tr class="separator:<API key> inherit pac_static_attribs_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key> inherit pac_static_attribs_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memItemLeft" align="right" valign="top">static NavigationView </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d0/d60/<API key>.html#<API key>">navigationView</a></td></tr>
<tr class="separator:<API key> inherit pac_static_attribs_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key> inherit pac_static_attribs_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memItemLeft" align="right" valign="top">static boolean </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d0/d60/<API key>.html#<API key>">isDrawerOpened</a> =false</td></tr>
<tr class="separator:<API key> inherit pac_static_attribs_classorg_1_1buildmlearn_1_1appstore_1_1activities_1_1_navigation_activity"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>This class is the Home Page, which has a viewpager to display tabs for Store section and My-Apps section. </p>
</div><h2 class="groupheader">Member Function Documentation</h2>
<a class="anchor" id="<API key>"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">static void org.buildmlearn.appstore.activities.HomeActivity.MyAppsView </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">static</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Set the current view to My-Apps section. </p>
<p>This method is helpful when the user selects to open the app from My-Apps section in the Settings Page. </p>
</div>
</div>
<a class="anchor" id="<API key>"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void org.buildmlearn.appstore.activities.HomeActivity.onBackPressed </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>This method is automatically called when the user presses the back button on his mobile. </p>
<p>It closes the Navigation Drawer if its open. Otherwise, it displays a popup to close the app. </p>
</div>
</div>
<a class="anchor" id="<API key>"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">void org.buildmlearn.appstore.activities.HomeActivity.onCreate </td>
<td>(</td>
<td class="paramtype">Bundle </td>
<td class="paramname"><em>savedInstanceState</em></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">protected</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>The method is executed first when the activity is created. </p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">savedInstanceState</td><td>The bundle stores all the related parameters, if it has to be used when resuming the app. </td></tr>
</table>
</dd>
</dl>
<p>When the page selection is changed, search view should reset. The app list on the My_Apps section is also refreshed, just in case the user has installed any app form the Store section. </p><dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">position</td><td>0:Store Section; 1: My-Apps Section</td></tr>
</table>
</dd>
</dl>
</div>
</div>
<h2 class="groupheader">Member Data Documentation</h2>
<a class="anchor" id="<API key>"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">MaterialDialog org.buildmlearn.appstore.activities.HomeActivity.mAlertDialog</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">private</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="<API key>"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">ViewPager org.buildmlearn.appstore.activities.HomeActivity.mPager</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">static</span><span class="mlabel">private</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="<API key>"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">final CharSequence [] org.buildmlearn.appstore.activities.HomeActivity.TITLES ={"Store","My <a class="el" href="../../d7/d09/<API key>.html">Apps</a>"}</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">private</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<hr/>The documentation for this class was generated from the following file:<ul>
<li>C:/Users/Srujan/Documents/GitHub/BuildmLearn-Store/Android/source-code/AppStore/app/src/main/java/org/buildmlearn/appstore/activities/<a class="el" href="../../d1/d8f/<API key>.html">HomeActivity.java</a></li>
</ul>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="../../db/d96/namespaceorg.html">org</a></li><li class="navelem"><a class="el" href="../../d7/d90/<API key>.html">buildmlearn</a></li><li class="navelem"><a class="el" href="../../d8/dcf/<API key>.html">appstore</a></li><li class="navelem"><a class="el" href="../../d8/dbc/<API key>.html">activities</a></li><li class="navelem"><a class="el" href="../../d8/dfa/<API key>.html">HomeActivity</a></li>
<li class="footer">Generated on Sat Aug 15 2015 21:55:11 for BuildmLearn Store by
<a href="http:
<img class="footer" src="../../doxygen.png" alt="doxygen"/></a> 1.8.10 </li>
</ul>
</div>
</body>
</html>
|
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */
#define VTK_WRAPPING_CXX
#define <API key>
#include <nan.h>
#include "vtkCollectionWrap.h"
#include "<API key>.h"
#include "vtkObjectBaseWrap.h"
#include "vtkRenderWindowWrap.h"
#include "../../plus/plus.h"
using namespace v8;
extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> <API key>::ptpl;
<API key>::<API key>()
{ }
<API key>::<API key>(vtkSmartPointer<<API key>> _native)
{ native = _native; }
<API key>::~<API key>()
{ }
void <API key>::Init(v8::Local<v8::Object> exports)
{
Nan::SetAccessor(exports, Nan::New("<API key>").ToLocalChecked(), ConstructorGetter);
Nan::SetAccessor(exports, Nan::New("<API key>").ToLocalChecked(), ConstructorGetter);
}
void <API key>::ConstructorGetter(
v8::Local<v8::String> property,
const Nan::<API key><v8::Value>& info)
{
InitPtpl();
info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}
void <API key>::InitPtpl()
{
if (!ptpl.IsEmpty()) return;
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
VtkCollectionWrap::InitPtpl( );
tpl->Inherit(Nan::New<FunctionTemplate>(VtkCollectionWrap::ptpl));
tpl->SetClassName(Nan::New("<API key>").ToLocalChecked());
tpl->InstanceTemplate()-><API key>(1);
Nan::SetPrototypeMethod(tpl, "AddItem", AddItem);
Nan::SetPrototypeMethod(tpl, "addItem", AddItem);
Nan::SetPrototypeMethod(tpl, "GetNextItem", GetNextItem);
Nan::SetPrototypeMethod(tpl, "getNextItem", GetNextItem);
Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);
#ifdef <API key>
<API key>
#endif
ptpl.Reset( tpl );
}
void <API key>::New(const Nan::<API key><v8::Value>& info)
{
if(!info.IsConstructCall())
{
Nan::ThrowError("Constructor not called in a construct call.");
return;
}
if(info.Length() == 0)
{
vtkSmartPointer<<API key>> native = vtkSmartPointer<<API key>>::New();
<API key>* obj = new <API key>(native);
obj->Wrap(info.This());
}
else
{
if(info[0]->ToObject() != vtkNodeJsNoWrap )
{
Nan::ThrowError("Parameter Error");
return;
}
}
info.GetReturnValue().Set(info.This());
}
void <API key>::AddItem(const Nan::<API key><v8::Value>& info)
{
<API key> *wrapper = ObjectWrap::Unwrap<<API key>>(info.Holder());
<API key> *native = (<API key> *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkRenderWindowWrap::ptpl))->HasInstance(info[0]))
{
VtkRenderWindowWrap *a0 = ObjectWrap::Unwrap<VtkRenderWindowWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->AddItem(
(vtkRenderWindow *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void <API key>::GetNextItem(const Nan::<API key><v8::Value>& info)
{
<API key> *wrapper = ObjectWrap::Unwrap<<API key>>(info.Holder());
<API key> *native = (<API key> *)wrapper->native.GetPointer();
vtkRenderWindow * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetNextItem();
VtkRenderWindowWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkRenderWindowWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkRenderWindowWrap *w = new VtkRenderWindowWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void <API key>::NewInstance(const Nan::<API key><v8::Value>& info)
{
<API key> *wrapper = ObjectWrap::Unwrap<<API key>>(info.Holder());
<API key> *native = (<API key> *)wrapper->native.GetPointer();
<API key> * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->NewInstance();
<API key>::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(<API key>::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
<API key> *w = new <API key>();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void <API key>::SafeDownCast(const Nan::<API key><v8::Value>& info)
{
<API key> *wrapper = ObjectWrap::Unwrap<<API key>>(info.Holder());
<API key> *native = (<API key> *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0]))
{
VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject());
<API key> * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->SafeDownCast(
(vtkObjectBase *) a0->native.GetPointer()
);
<API key>::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(<API key>::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
<API key> *w = new <API key>();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
Nan::ThrowError("Parameter mismatch");
}
|
# modification, are permitted provided that the following conditions are
# met:
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from collections import namedtuple
from blinkpy.common.net.results_fetcher import TestResultsFetcher
BuilderStep = namedtuple('BuilderStep', ['build', 'step_name'])
# TODO(qyearsley): To be consistent with other fake ("mock") classes, this
# could be changed so it's not a subclass of TestResultsFetcher.
class <API key>(TestResultsFetcher):
def __init__(self):
super(<API key>, self).__init__()
self._canned_results = {}
self.<API key> = {}
self._webdriver_results = {}
self.fetched_builds = []
self.<API key> = []
self.<API key> = 'blink_web_tests (with patch)'
def set_results(self, build, results, step_name=None):
step_name = step_name or self.<API key>(build)
step = BuilderStep(build=build, step_name=step_name)
self._canned_results[step] = results
def fetch_results(self, build, full=False, step_name=None):
step_name = step_name or self.<API key>(build)
step = BuilderStep(build=build, step_name=step_name)
self.fetched_builds.append(step)
return self._canned_results.get(step)
def <API key>(self, build, results):
self._canned_results[build.build_id] = results
def <API key>(self, host, builds, predicate):
rv = []
for build in builds:
results = self._canned_results.get(build.build_id)
if results:
rv.extend(results)
return rv
def <API key>(self, build, m, results):
self._webdriver_results[(build, m)] = results
def <API key>(self, build, m):
self.<API key>.append((build, m))
return self._webdriver_results.get((build, m))
def <API key>(self, build, content):
self.<API key>[build] = content
def <API key>(self, build):
return self.<API key>.get(build)
def <API key>(self, name):
self.<API key> = name
def <API key>(self, build):
return self.<API key>
|
# -*- coding: utf-8 -*-
import access
import util
@auth.requires_login()
def index():
"""Produces a list of the feedback obtained for a given venue,
or for all venues."""
venue_id = request.args(0)
if venue_id == 'all':
q = (db.submission.user == get_user_email())
else:
q = ((db.submission.user == get_user_email())
& (db.submission.venue_id == venue_id))
db.submission.id.represent = lambda x, r: A(T('View'), _class='btn', _href=URL('submission', 'view_own_submission', args=['v', r.id]))
db.submission.id.label = T('Submission')
db.submission.id.readable = True
db.submission.venue_id.readable = True
grid = SQLFORM.grid(q,
fields=[db.submission.id, db.submission.venue_id,
db.submission.date_created, db.submission.date_updated, ],
csv=False, details=False, create=False, editable=False, deletable=False,
args=request.args[:1],
maxtextlength=24,
)
return dict(grid=grid)
@auth.requires_login()
def view_feedback():
"""Shows detailed feedback for a user in a venue.
This controller accepts various types of arguments:
* 's', submission_id
* 'u', venue_id, username
* 'v', venue_id (in which case, shows own submission to that venue)
"""
if len(request.args) == 0:
redirect(URL('default', 'index'))
if request.args(0) == 's':
# submission_id
n_args = 2
subm = db.submission(request.args(1)) or redirect(URL('default', 'index'))
c = db.venue(subm.venue_id) or redirect(URL('default', 'index'))
username = subm.user
elif request.args(0) == 'v':
# venue_id
n_args = 2
c = db.venue(request.args(1)) or redirect(URL('default', 'index'))
username = get_user_email()
subm = db((db.submission.user == username) & (db.submission.venue_id == c.id)).select().first()
else:
# venue_id, username
n_args = 3
c = db.venue(request.args(1)) or redirect(URL('default', 'index'))
username = request.args(2) or redirect(URL('default', 'index'))
subm = db((db.submission.user == username) & (db.submission.venue_id == c.id)).select().first()
props = db(db.user_properties.user == get_user_email()).select().first()
if props == None:
session.flash = T('Not authorized.')
redirect(URL('default', 'index'))
is_author = (username == get_user_email())
can_view_feedback = access.can_view_feedback(c, props) or is_author
if (not can_view_feedback):
session.flash = T('Not authorized.')
redirect(URL('default', 'index'))
if not (access.can_view_feedback(c, props) or datetime.utcnow() > c.rate_close_date):
session.flash = T('The ratings are not yet available.')
redirect(URL('feedback', 'index', args=['all']))
# Produces the link to edit the feedback.
edit_feedback_link = None
if subm is not None and access.can_observe(c, props):
edit_feedback_link = A(T('Edit feedback'), _class='btn',
_href=URL('submission', 'edit_feedback', args=[subm.id]))
# Produces the download link.
download_link = None
if subm is not None and c.allow_file_upload and subm.content is not None:
if is_author:
download_link = A(T('Download'), _class='btn',
_href=URL('submission', 'download_author', args=[subm.id, subm.content]))
else:
download_link = A(T('Download'), _class='btn',
_href=URL('submission', 'download_manager', args=[subm.id, subm.content]))
venue_link = A(c.name, _href=URL('venues', 'view_venue', args=[c.id]))
# Submission link.
subm_link = None
if subm is not None and c.<API key>:
subm_link = A(subm.link, _href=subm.link)
# Submission content and feedback.
subm_comment = None
subm_feedback = None
if subm is not None:
raw_subm_comment = keystore_read(subm.comment)
if raw_subm_comment is not None and len(raw_subm_comment) > 0:
subm_comment = MARKMIN(keystore_read(subm.comment))
raw_feedback = keystore_read(subm.feedback)
if raw_feedback is not None and len(raw_feedback) > 0:
subm_feedback = MARKMIN(raw_feedback)
# Display settings.
db.submission.percentile.readable = True
db.submission.comment.readable = True
db.submission.feedback.readable = True
if access.can_observe(c, props):
db.submission.quality.readable = True
db.submission.error.readable = True
# Reads the grade information.
submission_grade = <API key> = None
review_grade = review_percentile = user_reputation = None
final_grade = final_percentile = None
assigned_grade = None
if c.grades_released:
grade_info = db((db.grades.user == username) & (db.grades.venue_id == c.id)).select().first()
if grade_info is not None:
submission_grade = represent_quality(grade_info.submission_grade, None)
<API key> = <API key>(grade_info.<API key>, None)
review_grade = <API key>(grade_info.accuracy, None)
review_percentile = <API key>(grade_info.accuracy_percentile, None)
user_reputation = <API key>(grade_info.reputation, None)
final_grade = represent_quality(grade_info.grade, None)
final_percentile = <API key>(grade_info.percentile, None)
assigned_grade = represent_quality(grade_info.assigned_grade, None)
# Makes a grid of comments.
db.task.submission_name.readable = False
db.task.assigned_date.readable = False
db.task.completed_date.readable = False
db.task.rejected.readable = True
db.task.helpfulness.readable = db.task.helpfulness.writable = True
# Prevent editing the comments; the only thing editable should be the "is bogus" field.
db.task.comments.writable = False
db.task.comments.readable = True
ranking_link = None
if access.can_observe(c, props):
db.task.user.readable = True
db.task.completed_date.readable = True
links = [
dict(header=T('Review details'), body= lambda r:
A(T('View'), _class='btn', _href=URL('ranking', 'view_comparison', args=[r.id]))),
]
details = False
if subm is not None:
ranking_link = A(T('details'), _href=URL('ranking', '<API key>', args=[subm.id]))
reviews_link = A(T('details'), _href=URL('ranking', '<API key>', args=[username, c.id]))
db.task.user.represent = lambda v, r: A(v, _href=URL('ranking', '<API key>',
args=[v, c.id], user_signature=True))
else:
user_reputation = None
links = [
dict(header=T('Review feedback'), body = lambda r:
A(T('Give feedback'), _class='btn',
_href=URL('feedback', 'reply_to_review', args=[r.id], user_signature=True))),
]
details = False
ranking_link = None
reviews_link = None
if subm is not None:
q = ((db.task.submission_id == subm.id) & (db.task.is_completed == True))
# q = (db.task.submission_id == subm.id)
else:
q = (db.task.id == -1)
grid = SQLFORM.grid(q,
fields=[db.task.id, db.task.user, db.task.rejected, db.task.comments, db.task.helpfulness, ],
details = details,
csv=False, create=False, editable=False, deletable=False, searchable=False,
links=links,
args=request.args[:n_args],
maxtextlength=24,
)
return dict(subm=subm, download_link=download_link, subm_link=subm_link, username=username,
subm_comment=subm_comment, subm_feedback=subm_feedback,
edit_feedback_link=edit_feedback_link,
is_admin=is_user_admin(),
submission_grade=submission_grade, <API key>=<API key>,
review_grade=review_grade, review_percentile=review_percentile,
user_reputation=user_reputation,
final_grade=final_grade, final_percentile=final_percentile,
assigned_grade=assigned_grade,
venue_link=venue_link, grid=grid, ranking_link=ranking_link,
reviews_link=reviews_link)
@auth.requires_signature()
def reply_to_review():
t = db.task(request.args(0)) or redirect(URL('default', 'index'))
db.task.submission_name.readable = False
db.task.assigned_date.readable = False
db.task.completed_date.readable = False
db.task.comments.readable = False
db.task.helpfulness.readable = db.task.helpfulness.writable = True
db.task.feedback.readable = db.task.feedback.writable = True
form = SQLFORM(db.task, record=t)
form.vars.feedback = keystore_read(t.feedback)
if form.process(onvalidation=<API key>(t)).accepted:
session.flash = T('Updated.')
redirect(URL('feedback', 'view_feedback', args=['s', t.submission_id]))
link_to_submission = A(T('View submission'), _href=URL('submission', 'view_own_submission', args=['v', t.submission_id]))
review_comments = MARKMIN(keystore_read(t.comments))
return dict(form=form, link_to_submission=link_to_submission, review_comments=review_comments)
def <API key>(t):
def f(form):
if not form.errors:
feedback_id = keystore_update(t.feedback, form.vars.feedback)
form.vars.feedback = feedback_id
return f
@auth.requires_login()
def view_my_reviews():
"""This controller displays the reviews a user has written for a venue, along with
the feedback they received."""
c = db.venue(request.args(0)) or redirect(URL('rating', 'review_index'))
link_to_venue = A(c.name, _href=URL('venues', 'view_venue', args=[c.id]))
link_to_eval = A(T('My evaluation in this venue'), _class='btn',
_href=URL('feedback', 'view_feedback', args=['v', c.id]))
q = ((db.task.user == get_user_email()) & (db.task.venue_id == c.id))
db.task.rejected.readable = True
db.task.helpfulness.readable = True
db.task.comments.readable = True
db.task.feedback.readable = True
# To prevent chopping
db.task.submission_name.represent = <API key>
grid = SQLFORM.grid(q,
fields=[db.task.submission_name, db.task.rejected, db.task.helpfulness],
details=True,
editable=False, deletable=False, create=False, searchable=False,
csv=False,
args=request.args[:1],
maxtextlength=24,
)
return dict(grid=grid, link_to_venue=link_to_venue, link_to_eval=link_to_eval)
|
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel app\models\search\UserSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Users';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="user-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create User', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'username',
'password',
'fullname',
'is_seller',
// 'lat',
// 'lng',
// 'category_id',
// 'description:ntext',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
|
// GB_AxB: hard-coded C=A*B and C<M>=A*B
// If this filename has a double underscore in its name ("__") then it has been
// automatically constructed from Generator/GB_AxB.c, via the Source/axb*.m
// scripts, and should not be editted. Edit the original source file instead.
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_heap.h"
#include "GB_AxB__semirings.h"
// The C=A*B semiring is defined by the following types and operators:
// A*B function (Gustavon): <API key>
// A'*B function (dot): <API key>
// A*B function (heap): <API key>
// Z type: int32_t (the type of C)
// X type: int32_t (the type of x for z=mult(x,y))
// Y type: int32_t (the type of y for z=mult(x,y))
// handle flipxy: 0 (0 if mult(x,y) is commutative, 1 otherwise)
// Identity: 1 (where cij *= identity does not change cij)
// Multiply: z = x > y
// Add: cij *= z
#define GB_XTYPE \
int32_t
#define GB_YTYPE \
int32_t
#define GB_HANDLE_FLIPXY \
0
#define GB_MULTOP(z,x,y) \
z = x > y
// C<M>=A*B and C=A*B: gather/scatter saxpy-based method (Gustavson)
#define GB_IDENTITY \
1
// x [i] = y
#define <API key>(x,i,y,s) \
x [i] = y ;
// x = y [i]
#define <API key>(x,y,i,s) \
GB_btype x = y [i] ;
// x [i] = y [i]
#define <API key>(x,i,y,j,s) \
x [i] = y [j] ;
// mult-add operation (no mask)
#define GB_MULTADD_NOMASK \
{ \
/* Sauna_Work [i] += A(i,k) * B(k,j) */ \
GB_atype aik = Ax [pA] ; \
int32_t t ; \
GB_MULTIPLY (t, aik, bkj) ; \
Sauna_Work [i] *= t ; \
}
// mult-add operation (with mask)
#define <API key> \
{ \
/* Sauna_Work [i] += A(i,k) * B(k,j) */ \
GB_atype aik = Ax [pA] ; \
int32_t t ; \
GB_MULTIPLY (t, aik, bkj) ; \
if (mark == hiwater) \
{ \
/* first time C(i,j) seen */ \
Sauna_Mark [i] = hiwater + 1 ; \
Sauna_Work [i] = t ; \
} \
else \
{ \
/* C(i,j) seen before, update it */ \
Sauna_Work [i] *= t ; \
} \
}
GrB_Info <API key>
(
GrB_Matrix C,
const GrB_Matrix M,
const GrB_Matrix A,
const GrB_Matrix B,
bool flipxy, // if true, A and B have been swapped
GB_Sauna Sauna, // sparse accumulator
GB_Context Context
)
{
int32_t *restrict Sauna_Work = Sauna->Sauna_Work ; // size C->vlen*zsize
int32_t *restrict Cx = C->x ;
GrB_Info info = GrB_SUCCESS ;
#include "<API key>.c"
return (info) ;
}
// C<M>=A'*B or C=A'*B: dot product
// get A(k,i)
#define GB_DOT_GETA(pA) \
GB_atype aki = Ax [pA] ;
// get B(k,j)
#define GB_DOT_GETB(pB) \
GB_btype bkj = Bx [pB] ;
// t = aki*bkj
#define GB_DOT_MULT(bkj) \
int32_t t ; \
GB_MULTIPLY (t, aki, bkj) ;
// cij += t
#define GB_DOT_ADD \
cij *= t ;
// cij = t
#define GB_DOT_COPY \
cij = t ;
// cij is not a pointer but a scalar; nothing to do
#define GB_DOT_REACQUIRE ;
// clear cij
#define GB_DOT_CLEAR \
cij = 1 ;
// save the value of C(i,j)
#define GB_DOT_SAVE \
Cx [cnz] = cij ;
#define GB_DOT_WORK_TYPE \
GB_btype
#define GB_DOT_WORK(k) Work [k]
// Work [k] = Bx [pB]
#define GB_DOT_SCATTER \
Work [k] = Bx [pB] ;
GrB_Info <API key>
(
GrB_Matrix *Chandle,
const GrB_Matrix M,
const GrB_Matrix A,
const GrB_Matrix B,
bool flipxy, // if true, A and B have been swapped
GB_Context Context
)
{
GrB_Matrix C = (*Chandle) ;
int32_t *restrict Cx = C->x ;
int32_t cij ;
GrB_Info info = GrB_SUCCESS ;
size_t bkj_size = B->type->size ; // no typecasting here
#include "GB_AxB_dot_flipxy.c"
return (info) ;
}
// C<M>=A*B and C=A*B: heap saxpy-based method
#define GB_CIJ_GETB(pB) \
GB_btype bkj = Bx [pB] ;
// C(i,j) = A(i,k) * bkj
#define GB_CIJ_MULT(pA) \
{ \
GB_atype aik = Ax [pA] ; \
GB_MULTIPLY (cij, aik, bkj) ; \
}
// C(i,j) += A(i,k) * B(k,j)
#define GB_CIJ_MULTADD(pA,pB) \
{ \
GB_atype aik = Ax [pA] ; \
GB_btype bkj = Bx [pB] ; \
int32_t t ; \
GB_MULTIPLY (t, aik, bkj) ; \
cij *= t ; \
}
// cij is not a pointer but a scalar; nothing to do
#define GB_CIJ_REACQUIRE ;
// cij = identity
#define GB_CIJ_CLEAR \
cij = 1 ;
// save the value of C(i,j)
#define GB_CIJ_SAVE \
Cx [cnz] = cij ;
GrB_Info <API key>
(
GrB_Matrix *Chandle,
const GrB_Matrix M,
const GrB_Matrix A,
const GrB_Matrix B,
bool flipxy, // if true, A and B have been swapped
int64_t *restrict List,
GB_pointer_pair *restrict pA_pair,
GB_Element *restrict Heap,
const int64_t bjnz_max,
GB_Context Context
)
{
GrB_Matrix C = (*Chandle) ;
int32_t *restrict Cx = C->x ;
int32_t cij ;
int64_t cvlen = C->vlen ;
GrB_Info info = GrB_SUCCESS ;
GB_CIJ_CLEAR ;
#include "GB_AxB_heap_flipxy.c"
return (info) ;
}
// clear macro definitions
#undef GB_XTYPE
#undef GB_YTYPE
#undef GB_HANDLE_FLIPXY
#undef GB_MULTOP
#undef GB_IDENTITY
#undef <API key>
#undef <API key>
#undef <API key>
#undef GB_MULTADD_NOMASK
#undef <API key>
#undef GB_DOT_GETA
#undef GB_DOT_GETB
#undef GB_DOT_MULT
#undef GB_DOT_ADD
#undef GB_DOT_COPY
#undef GB_DOT_REACQUIRE
#undef GB_DOT_CLEAR
#undef GB_DOT_SAVE
#undef GB_DOT_WORK_TYPE
#undef GB_DOT_WORK
#undef GB_DOT_SCATTER
#undef GB_CIJ_GETB
#undef GB_CIJ_MULT
#undef GB_CIJ_MULTADD
#undef GB_CIJ_REACQUIRE
#undef GB_CIJ_CLEAR
#undef GB_CIJ_SAVE
#undef GB_MULTIPLY
#endif
|
from __future__ import print_function
import shutil
import os, sys
import time
import logging
from .loaders import PythonLoader, YAMLLoader
from .bundle import <API key>
from .exceptions import BuildError
from .updater import TimestampUpdater
from .merge import MemoryHunk
from .version import get_manifest
from .cache import FilesystemCache
from .utils import set, StringIO
__all__ = ('CommandError', '<API key>', 'main')
# logging has WARNING as default level, for the CLI we want INFO. Set this
# as early as possible, so that user customizations will not be overwritten.
logging.getLogger('webassets.script').setLevel(logging.INFO)
class CommandError(Exception):
pass
class Command(object):
"""Base-class for a command used by :class:`<API key>`.
Each command being a class opens up certain possibilities with respect to
subclassing and customizing the default CLI.
"""
def __init__(self, cmd_env):
self.cmd = cmd_env
def __getattr__(self, name):
# Make stuff from cmd environment easier to access
return getattr(self.cmd, name)
def __call__(self, *args, **kwargs):
raise NotImplementedError()
class BuildCommand(Command):
def __call__(self, bundles=None, output=None, directory=None, no_cache=None,
manifest=None, production=None):
"""Build assets.
``bundles``
A list of bundle names. If given, only this list of bundles
should be built.
``output``
List of (bundle, filename) 2-tuples. If given, only these
bundles will be built, using the custom output filenames.
Cannot be used with ``bundles``.
``directory``
Custom output directory to use for the bundles. The original
basenames defined in the bundle ``output`` attribute will be
used. If the ``output`` of the bundles are pointing to different
directories, they will be offset by their common prefix.
Cannot be used with ``output``.
``no_cache``
If set, a cache (if one is configured) will not be used.
``manifest``
If set, the given manifest instance will be used, instead of
any that might have been configured in the Environment. The value
passed will be resolved through ``get_manifest()``. If this fails,
a file-based manifest will be used using the given value as the
filename.
``production``
If set to ``True``, then :attr:`Environment.debug`` will forcibly
be disabled (set to ``False``) during the build.
"""
# Validate arguments
if bundles and output:
raise CommandError(
'When specifying explicit output filenames you must '
'do so for all bundles you want to build.')
if directory and output:
raise CommandError('A custom output directory cannot be '
'combined with explicit output filenames '
'for individual bundles.')
if production:
# TODO: Reset again (refactor commands to be classes)
self.environment.debug = False
# TODO: Oh how nice it would be to use the future options stack.
if manifest is not None:
try:
manifest = get_manifest(manifest, env=self.environment)
except ValueError:
manifest = get_manifest(
# abspath() is important, or this will be considered
# relative to Environment.directory.
"file:%s" % os.path.abspath(manifest),
env=self.environment)
self.environment.manifest = manifest
# Use output as a dict.
if output:
output = dict(output)
# Validate bundle names
bundle_names = bundles if bundles else (output.keys() if output else [])
for name in bundle_names:
if not name in self.environment:
raise CommandError(
'I do not know a bundle name named "%s".' % name)
# Make a list of bundles to build, and the filename to write to.
if bundle_names:
# TODO: It's not ok to use an internal property here.
bundles = [(n,b) for n, b in self.environment._named_bundles.items()
if n in bundle_names]
else:
# Includes unnamed bundles as well.
bundles = [(None, b) for b in self.environment]
# Determine common prefix for use with ``directory`` option.
if directory:
prefix = os.path.commonprefix(
[os.path.normpath(b.resolve_output())
for _, b in bundles if b.output])
# dirname() gives the right value for a single file.
prefix = os.path.dirname(prefix)
to_build = []
for name, bundle in bundles:
# TODO: We really should support this. This error here
# is just in place of a less understandable error that would
# otherwise occur.
if bundle.is_container and directory:
raise CommandError(
'A custom output directory cannot currently be '
'used with container bundles.')
# Determine which filename to use, if not the default.
overwrite_filename = None
if output:
overwrite_filename = output[name]
elif directory:
offset = os.path.normpath(
bundle.resolve_output())[len(prefix)+1:]
overwrite_filename = os.path.join(directory, offset)
to_build.append((bundle, overwrite_filename, name,))
# Build.
built = []
for bundle, overwrite_filename, name in to_build:
if name:
# A name is not necessary available of the bundle was
# registered without one.
self.log.info("Building bundle: %s (to %s)" % (
name, overwrite_filename or bundle.output))
else:
self.log.info("Building bundle: %s" % bundle.output)
try:
if not overwrite_filename:
with bundle.bind(self.environment):
bundle.build(force=True, disable_cache=no_cache)
else:
# TODO: Rethink how we deal with container bundles here.
# As it currently stands, we write all child bundles
# to the target output, merged (which is also why we
# create and force writing to a StringIO instead of just
# using the ``Hunk`` objects that build() would return
# anyway.
output = StringIO()
with bundle.bind(self.environment):
bundle.build(force=True, output=output,
disable_cache=no_cache)
if directory:
# Only auto-create directories in this mode.
output_dir = os.path.dirname(overwrite_filename)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
MemoryHunk(output.getvalue()).save(overwrite_filename)
built.append(bundle)
except BuildError as e:
self.log.error("Failed, error was: %s" % e)
if len(built):
self.event_handlers['post_build']()
if len(built) != len(to_build):
return 2
class WatchCommand(Command):
def __call__(self, loop=None):
"""Watch assets for changes.
``loop``
A callback, taking no arguments, to be called once every loop
iteration. Can be useful to integrate the command with other code.
If not specified, the loop wil call ``time.sleep()``.
"""
# TODO: This should probably also restart when the code changes.
mtimes = {}
try:
# Before starting to watch for changes, also recognize changes
# made while we did not run, and apply those immediately.
for bundle in self.environment:
print('Bringing up to date: %s' % bundle.output)
bundle.build(force=False)
self.log.info("Watching %d bundles for changes..." %
len(self.environment))
while True:
changed_bundles = self.check_for_changes(mtimes)
built = []
for bundle in changed_bundles:
print("Building bundle: %s ..." % bundle.output, end=' ')
sys.stdout.flush()
try:
bundle.build(force=True)
built.append(bundle)
except BuildError as e:
print("")
print("Failed: %s" % e)
else:
print("done")
if len(built):
self.event_handlers['post_build']()
do_end = loop() if loop else time.sleep(0.1)
if do_end:
break
except KeyboardInterrupt:
pass
def check_for_changes(self, mtimes):
# Do not update original mtimes dict right away, so that we detect
# all bundle changes if a file is in multiple bundles.
_new_mtimes = mtimes.copy()
changed_bundles = set()
# TODO: An optimization was lost here, skipping a bundle once
# a single file has been found to have changed. Bring back.
for filename, bundles_to_update in self.<API key>():
stat = os.stat(filename)
mtime = stat.st_mtime
if sys.platform == "win32":
mtime -= stat.st_ctime
if mtimes.get(filename, mtime) != mtime:
if callable(bundles_to_update):
# Hook for when file has changed
try:
bundles_to_update = bundles_to_update()
except EnvironmentError:
# EnvironmentError is what the hooks is allowed to
# raise for a temporary problem, like an invalid config
import traceback
traceback.print_exc()
# Don't update anything, wait for another change
bundles_to_update = set()
if bundles_to_update is True:
# Indicates all bundles should be rebuilt for the change
bundles_to_update = set(self.environment)
changed_bundles |= bundles_to_update
_new_mtimes[filename] = mtime
_new_mtimes[filename] = mtime
mtimes.update(_new_mtimes)
return changed_bundles
def <API key>(self):
for bundle in self.environment:
for filename in <API key>(bundle):
yield filename, set([bundle])
class CleanCommand(Command):
def __call__(self):
"""Delete generated assets.
"""
self.log.info('Cleaning generated assets...')
for bundle in self.environment:
if not bundle.output:
continue
file_path = bundle.resolve_output(self.environment)
if os.path.exists(file_path):
os.unlink(file_path)
self.log.info("Deleted asset: %s" % bundle.output)
if isinstance(self.environment.cache, FilesystemCache):
shutil.rmtree(self.environment.cache.directory)
class CheckCommand(Command):
def __call__(self):
"""Check to see if assets need to be rebuilt.
A non-zero exit status will be returned if any of the input files are
newer (based on mtime) than their output file. This is intended to be
used in pre-commit hooks.
"""
needsupdate = False
updater = self.environment.updater
if not updater:
self.log.debug('no updater configured, using TimestampUpdater')
updater = TimestampUpdater()
for bundle in self.environment:
self.log.info('Checking asset: %s', bundle.output)
if updater.needs_rebuild(bundle, self.environment):
self.log.info(' needs update')
needsupdate = True
if needsupdate:
sys.exit(-1)
class <API key>(object):
"""Implements the core functionality for a command line frontend to
``webassets``, abstracted in a way to allow frameworks to integrate the
functionality into their own tools, for example, as a Django management
command, or a command for ``Flask-Script``.
"""
def __init__(self, env, log, post_build=None, commands=None):
self.environment = env
self.log = log
self.event_handlers = dict(post_build=lambda: True)
if callable(post_build):
self.event_handlers['post_build'] = post_build
# Instantiate each command
command_def = self.DefaultCommands.copy()
command_def.update(commands or {})
self.commands = {}
for name, construct in command_def.items():
if not construct:
continue
if not isinstance(construct, (list, tuple)):
construct = [construct, (), {}]
self.commands[name] = construct[0](
self, *construct[1], **construct[2])
def __getattr__(self, item):
# Allow method-like access to commands.
if item in self.commands:
return self.commands[item]
raise AttributeError(item)
def invoke(self, command, args):
"""Invoke ``command``, or throw a CommandError.
This is essentially a simple validation mechanism. Feel free
to call the individual command methods manually.
"""
try:
function = self.commands[command]
except KeyError as e:
raise CommandError('unknown command: %s' % e)
else:
return function(**args)
# List of commands installed
DefaultCommands = {
'build': BuildCommand,
'watch': WatchCommand,
'clean': CleanCommand,
'check': CheckCommand
}
class <API key>(object):
"""Generic command line utility to interact with an webassets environment.
This is effectively a reference implementation of a command line utility
based on the ``<API key>`` class. Implementers may find it
feasible to simple base their own command line utility on this, rather than
implementing something custom on top of ``<API key>``. In
fact, if that is possible, you are encouraged to do so for greater
consistency across implementations.
"""
class WatchCommand(WatchCommand):
"""Extended watch command that also looks at the config file itself."""
def __init__(self, cmd_env, argparse_ns):
WatchCommand.__init__(self, cmd_env)
self.ns = argparse_ns
def <API key>(self):
for result in WatchCommand.<API key>(self):
yield result
# If the config changes, rebuild all bundles
if getattr(self.ns, 'config', None):
yield self.ns.config, self.reload_config
def reload_config(self):
try:
self.cmd.environment = YAMLLoader(self.ns.config).load_environment()
except Exception as e:
raise EnvironmentError(e)
return True
def __init__(self, env=None, log=None, prog=None, no_global_options=False):
try:
import argparse
except ImportError:
raise RuntimeError(
'The webassets command line now requires the '
'"argparse" library on Python versions <= 2.6.')
else:
self.argparse = argparse
self.env = env
self.log = log
self._construct_parser(prog, no_global_options)
def _construct_parser(self, prog=None, no_global_options=False):
self.parser = parser = self.argparse.ArgumentParser(
description="Manage assets.",
prog=prog)
if not no_global_options:
# Start with the base arguments that are valid for any command.
# XXX: Add those to the subparser?
parser.add_argument("-v", dest="verbose", action="store_true",
help="be verbose")
parser.add_argument("-q", action="store_true", dest="quiet",
help="be quiet")
if self.env is None:
loadenv = parser.<API key>()
loadenv.add_argument("-c", "--config", dest="config",
help="read environment from a YAML file")
loadenv.add_argument("-m", "--module", dest="module",
help="read environment from a Python module")
# Add subparsers.
subparsers = parser.add_subparsers(dest='command')
for command in <API key>.DefaultCommands.keys():
command_parser = subparsers.add_parser(command)
maker = getattr(self, 'make_%s_parser' % command, False)
if maker:
maker(command_parser)
@staticmethod
def make_build_parser(parser):
parser.add_argument(
'bundles', nargs='*', metavar='BUNDLE',
help='Optional bundle names to process. If none are '
'specified, then all known bundles will be built.')
parser.add_argument(
'--output', '-o', nargs=2, action='append',
metavar=('BUNDLE', 'FILE'),
help='Build the given bundle, and use a custom output '
'file. Can be given multiple times.')
parser.add_argument(
'--directory', '-d',
help='Write built files to this directory, using the '
'basename defined by the bundle. Will offset '
'the original bundle output paths on their common '
'prefix. Cannot be used with --output.')
parser.add_argument(
'--no-cache', action='store_true',
help='Do not use a cache that might be configured.')
parser.add_argument(
'--manifest',
help='Write a manifest to the given file. Also supports '
'the id:arg format, if you want to use a different '
'manifest implementation.')
parser.add_argument(
'--production', action='store_true',
help='Forcably turn off debug mode for the build. This '
'only has an effect if debug is set to "merge".')
def _setup_logging(self, ns):
if self.log:
log = self.log
else:
log = logging.getLogger('webassets.script')
if not log.handlers:
# In theory, this could run multiple times (e.g. tests)
handler = logging.StreamHandler()
log.addHandler(handler)
# Note that setting the level filter at the handler level is
# better than the logger level, since this is "our" handler,
# we create it, for the purposes of having a default output.
# The logger itself the user may be modifying.
handler.setLevel(logging.DEBUG if ns.verbose else (
logging.WARNING if ns.quiet else logging.INFO))
return log
def _setup_assets_env(self, ns, log):
env = self.env
if env is None:
assert not (ns.module and ns.config)
if ns.module:
env = PythonLoader(ns.module).load_environment()
if ns.config:
env = YAMLLoader(ns.config).load_environment()
return env
def _setup_cmd_env(self, assets_env, log, ns):
return <API key>(assets_env, log, commands={
'watch': (<API key>.WatchCommand, (ns,), {})
})
def <API key>(self, ns):
# Prepare a dict of arguments cleaned of values that are not
# command-specific, and which the command method would not accept.
args = vars(ns).copy()
for action in self.parser._actions:
dest = action.dest
if dest in args:
del args[dest]
return args
def run_with_ns(self, ns):
log = self._setup_logging(ns)
env = self._setup_assets_env(ns, log)
if env is None:
raise CommandError(
"Error: No environment given or found. Maybe use -m?")
cmd = self._setup_cmd_env(env, log, ns)
# Run the selected command
args = self.<API key>(ns)
return cmd.invoke(ns.command, args)
def run_with_argv(self, argv):
try:
ns = self.parser.parse_args(argv)
except SystemExit as e:
# We do not want the main() function to exit the program.
# See run() instead.
return e.args[0]
return self.run_with_ns(ns)
def main(self, argv):
"""Parse the given command line.
The commandline is expected to NOT including what would be sys.argv[0].
"""
try:
return self.run_with_argv(argv)
except CommandError as e:
print(e)
return 1
def main(argv, env=None):
"""Execute the generic version of the command line interface.
You only need to work directly with ``<API key>`` if
you desire to customize things.
If no environment is given, additional arguments will be supported to allow
the user to specify/construct the environment on the command line.
"""
return <API key>(env).main(argv)
def run():
"""Runs the command line interface via ``main``, then exits the process
with a proper return code."""
sys.exit(main(sys.argv[1:]) or 0)
if __name__ == '__main__':
run()
|
#include "ioentity.h"
#include <assert.h>
#include <algorithm>
namespace arduinoio {
/**
* @brief Constructor
* @param
*/
ioentity::ioentity(boost::shared_ptr<serial> const &serial) : m_serial(serial), m_isConfigured(false) {
}
/**
* @brief Destructor
*/
ioentity::~ioentity() {
m_pinVect.clear();
}
} // end of namespace arduinoio
|
{-# LANGUAGE FlexibleInstances #-}
-- ghc options
{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -<API key> #-}
-- {-# OPTIONS_GHC -<API key> #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- {-# OPTIONS_GHC -<API key> #-}
-- {-# OPTIONS_GHC -<API key> #-}
-- {-# OPTIONS_GHC -<API key> #-}
-- {-# OPTIONS_GHC -<API key> #-}
-- Maintainer: Andreas Reuleaux <rx@a-rx.info>
-- Stability : experimental
-- Portability: non-portable
-- This module provides pretty printing functionality for Pire's
-- abstract and concrete syntax: names
module Pire.Pretty.Nm where
import Pire.Syntax.Nm
-- import Data.Text as T
import Text.PrettyPrint as TPP
import Pire.Pretty.Common
import Pire.Pretty.Ws()
-- instance Disp s => Disp (Nm_ s) where
-- disp (Nm_ nm (Ws ws)) = do
-- dnm <- disp nm
-- return $ dnm <> (text $ T.unpack ws)
instance Disp s => Disp (Nm1 s) where
disp (Nm1 nm) = disp nm
disp (Nm1_ nm ws) = do
dnm <- disp nm
dws <- disp ws
return $ dnm <> dws
instance Disp s => Disp (Nm s s) where
disp (Nm nm) = disp nm
disp (Nm_ nm ws) = do
dnm <- disp nm
dws <- disp ws
return $ dnm <> dws
|
/* Notice extracted from xxHash homepage :
xxHash is an extremely fast Hash algorithm, running at RAM speed limits.
It also successfully passes all tests from the SMHasher suite.
Comparison (single thread, Windows Seven 32 bits, using SMHasher on a Core 2 Duo
@3GHz)
Name Speed Q.Score Author
xxHash 5.4 GB/s 10
CrapWow 3.2 GB/s 2 Andrew
MumurHash 3a 2.7 GB/s 10 Austin Appleby
SpookyHash 2.0 GB/s 10 Bob Jenkins
SBox 1.4 GB/s 9 Bret Mulvey
Lookup3 1.2 GB/s 9 Bob Jenkins
SuperFastHash 1.2 GB/s 1 Paul Hsieh
CityHash64 1.05 GB/s 10 Pike & Alakuijala
FNV 0.55 GB/s 5 Fowler, Noll, Vo
CRC32 0.43 GB/s 9
MD5-32 0.33 GB/s 10 Ronald L. Rivest
SHA1-32 0.28 GB/s 10
Q.Score is a measure of quality of the hash function.
It depends on successfully passing SMHasher test set.
10 is a perfect score.
A 64-bit version, named XXH64, is available since r35.
It offers much better speed, but for 64-bit applications only.
Name Speed on 64 bits Speed on 32 bits
XXH64 13.8 GB/s 1.9 GB/s
XXH32 6.8 GB/s 6.0 GB/s
*/
#ifndef <API key>
#define <API key> 1
#if defined(__cplusplus)
extern "C" {
#endif
#include <stddef.h> /* size_t */
typedef enum { XXH_OK = 0, XXH_ERROR } XXH_errorcode;
/** XXH_INLINE_ALL (and XXH_PRIVATE_API)
* This is useful to include xxhash functions in `static` mode
* in order to inline them, and remove their symbol from the public list.
* Inlining can offer dramatic performance improvement on small keys.
* Methodology :
* #define XXH_INLINE_ALL
* #include "xxhash.h"
* `xxhash.c` is automatically included.
* It's not useful to compile and link it as a separate module.
*/
#if defined(XXH_INLINE_ALL) || defined(XXH_PRIVATE_API)
#ifndef <API key>
#define <API key>
#endif
#if defined(__GNUC__)
#define XXH_PUBLIC_API static __inline __attribute__((unused))
#elif defined(__cplusplus) || \
(defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
#define XXH_PUBLIC_API static inline
#elif defined(_MSC_VER)
#define XXH_PUBLIC_API static __inline
#else
/* this version may generate warnings for unused static functions */
#define XXH_PUBLIC_API static
#endif
#else
#define XXH_PUBLIC_API /* do nothing */
#endif /* XXH_INLINE_ALL || XXH_PRIVATE_API */
/*! XXH_NAMESPACE, aka Namespace Emulation :
*
* If you want to include _and expose_ xxHash functions from within your own
* library,
* but also want to avoid symbol collisions with other libraries which may also
* include xxHash,
*
* you can use XXH_NAMESPACE, to automatically prefix any public symbol from
* xxhash library
* with the value of XXH_NAMESPACE (therefore, avoid NULL and numeric values).
*
* Note that no change is required within the calling program as long as it
* includes `xxhash.h` :
* regular symbol name will be automatically translated by this header.
*/
#ifdef XXH_NAMESPACE
#define XXH_CAT(A, B) A
#define XXH_NAME2(A, B) XXH_CAT(A, B)
#define XXH_versionNumber XXH_NAME2(XXH_NAMESPACE, XXH_versionNumber)
#define XXH32 XXH_NAME2(XXH_NAMESPACE, XXH32)
#define XXH32_createState XXH_NAME2(XXH_NAMESPACE, XXH32_createState)
#define XXH32_freeState XXH_NAME2(XXH_NAMESPACE, XXH32_freeState)
#define XXH32_reset XXH_NAME2(XXH_NAMESPACE, XXH32_reset)
#define XXH32_update XXH_NAME2(XXH_NAMESPACE, XXH32_update)
#define XXH32_digest XXH_NAME2(XXH_NAMESPACE, XXH32_digest)
#define XXH32_copyState XXH_NAME2(XXH_NAMESPACE, XXH32_copyState)
#define <API key> \
XXH_NAME2(XXH_NAMESPACE, <API key>)
#define <API key> \
XXH_NAME2(XXH_NAMESPACE, <API key>)
#define XXH64 XXH_NAME2(XXH_NAMESPACE, XXH64)
#define XXH64_createState XXH_NAME2(XXH_NAMESPACE, XXH64_createState)
#define XXH64_freeState XXH_NAME2(XXH_NAMESPACE, XXH64_freeState)
#define XXH64_reset XXH_NAME2(XXH_NAMESPACE, XXH64_reset)
#define XXH64_update XXH_NAME2(XXH_NAMESPACE, XXH64_update)
#define XXH64_digest XXH_NAME2(XXH_NAMESPACE, XXH64_digest)
#define XXH64_copyState XXH_NAME2(XXH_NAMESPACE, XXH64_copyState)
#define <API key> \
XXH_NAME2(XXH_NAMESPACE, <API key>)
#define <API key> \
XXH_NAME2(XXH_NAMESPACE, <API key>)
#endif
#define XXH_VERSION_MAJOR 0
#define XXH_VERSION_MINOR 6
#define XXH_VERSION_RELEASE 5
#define XXH_VERSION_NUMBER \
(XXH_VERSION_MAJOR * 100 * 100 + XXH_VERSION_MINOR * 100 + \
XXH_VERSION_RELEASE)
XXH_PUBLIC_API unsigned XXH_versionNumber(void);
typedef unsigned int XXH32_hash_t;
/*! XXH32() :
Calculate the 32-bit hash of sequence "length" bytes stored at memory
address "input".
The memory between input & input+length must be valid (allocated and
read-accessible).
"seed" can be used to alter the result predictably.
Speed on Core 2 Duo @ 3 GHz (single thread, SMHasher benchmark) : 5.4 GB/s
*/
XXH_PUBLIC_API XXH32_hash_t XXH32(const void *input, size_t length,
unsigned int seed);
typedef struct XXH32_state_s XXH32_state_t; /* incomplete type */
XXH_PUBLIC_API XXH32_state_t *XXH32_createState(void);
XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t *statePtr);
XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t *dst_state,
const XXH32_state_t *src_state);
XXH_PUBLIC_API XXH_errorcode XXH32_reset(XXH32_state_t *statePtr,
unsigned int seed);
XXH_PUBLIC_API XXH_errorcode XXH32_update(XXH32_state_t *statePtr,
const void *input, size_t length);
XXH_PUBLIC_API XXH32_hash_t XXH32_digest(const XXH32_state_t *statePtr);
/*
* Streaming functions generate the xxHash of an input provided in multiple
* segments.
* Note that, for small input, they are slower than single-call functions, due
* to state management.
* For small inputs, prefer `XXH32()` and `XXH64()`, which are better optimized.
*
* XXH state must first be allocated, using XXH*_createState() .
*
* Start a new hash by initializing state with a seed, using XXH*_reset().
*
* Then, feed the hash state by calling XXH*_update() as many times as
* necessary.
* The function returns an error code, with 0 meaning OK, and any other value
* meaning there is an error.
*
* Finally, a hash value can be produced anytime, by using XXH*_digest().
* This function returns the nn-bits hash as an int or long long.
*
* It's still possible to continue inserting input into the hash state after a
* digest,
* and generate some new hashes later on, by calling again XXH*_digest().
*
* When done, free XXH state space if it was allocated dynamically.
*/
typedef struct {
unsigned char digest[4];
} XXH32_canonical_t;
XXH_PUBLIC_API void <API key>(XXH32_canonical_t *dst,
XXH32_hash_t hash);
XXH_PUBLIC_API XXH32_hash_t
<API key>(const XXH32_canonical_t *src);
/* Default result type for XXH functions are primitive unsigned 32 and 64 bits.
* The canonical representation uses human-readable write convention, aka
* big-endian (large digits first).
* These functions allow transformation of hash result into and from its
* canonical format.
* This way, hash values can be written into a file / memory, and remain
* comparable on different systems and programs.
*/
#ifndef XXH_NO_LONG_LONG
typedef unsigned long long XXH64_hash_t;
/*! XXH64() :
Calculate the 64-bit hash of sequence of length "len" stored at memory
address "input".
"seed" can be used to alter the result predictably.
This function runs faster on 64-bit systems, but slower on 32-bit systems
(see benchmark).
*/
XXH_PUBLIC_API XXH64_hash_t XXH64(const void *input, size_t length,
unsigned long long seed);
typedef struct XXH64_state_s XXH64_state_t; /* incomplete type */
XXH_PUBLIC_API XXH64_state_t *XXH64_createState(void);
XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t *statePtr);
XXH_PUBLIC_API void XXH64_copyState(XXH64_state_t *dst_state,
const XXH64_state_t *src_state);
XXH_PUBLIC_API XXH_errorcode XXH64_reset(XXH64_state_t *statePtr,
unsigned long long seed);
XXH_PUBLIC_API XXH_errorcode XXH64_update(XXH64_state_t *statePtr,
const void *input, size_t length);
XXH_PUBLIC_API XXH64_hash_t XXH64_digest(const XXH64_state_t *statePtr);
typedef struct {
unsigned char digest[8];
} XXH64_canonical_t;
XXH_PUBLIC_API void <API key>(XXH64_canonical_t *dst,
XXH64_hash_t hash);
XXH_PUBLIC_API XXH64_hash_t
<API key>(const XXH64_canonical_t *src);
#endif /* XXH_NO_LONG_LONG */
#ifdef <API key>
/* These definitions are only present to allow
* static allocation of XXH state, on stack or in a struct for example.
* Never **ever** use members directly. */
#if !defined(__VMS) && \
(defined(__cplusplus) || \
(defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */))
#include <stdint.h>
struct XXH32_state_s {
uint32_t total_len_32;
uint32_t large_len;
uint32_t v1;
uint32_t v2;
uint32_t v3;
uint32_t v4;
uint32_t mem32[4];
uint32_t memsize;
uint32_t
reserved; /* never read nor write, might be removed in a future version */
}; /* typedef'd to XXH32_state_t */
struct XXH64_state_s {
uint64_t total_len;
uint64_t v1;
uint64_t v2;
uint64_t v3;
uint64_t v4;
uint64_t mem64[4];
uint32_t memsize;
uint32_t reserved[2]; /* never read nor write, might be removed in a future
version */
}; /* typedef'd to XXH64_state_t */
#else
struct XXH32_state_s {
unsigned total_len_32;
unsigned large_len;
unsigned v1;
unsigned v2;
unsigned v3;
unsigned v4;
unsigned mem32[4];
unsigned memsize;
unsigned
reserved; /* never read nor write, might be removed in a future version */
}; /* typedef'd to XXH32_state_t */
#ifndef XXH_NO_LONG_LONG /* remove 64-bit support */
struct XXH64_state_s {
unsigned long long total_len;
unsigned long long v1;
unsigned long long v2;
unsigned long long v3;
unsigned long long v4;
unsigned long long mem64[4];
unsigned memsize;
unsigned reserved[2]; /* never read nor write, might be removed in a future
version */
}; /* typedef'd to XXH64_state_t */
#endif
#endif
#if defined(XXH_INLINE_ALL) || defined(XXH_PRIVATE_API)
#include "xxhash.c" /* include xxhash function bodies as `static`, for inlining */
#endif
#endif /* <API key> */
#if defined(__cplusplus)
}
#endif
#endif /* <API key> */
|
/**
* @file alarm.c
* Platform abstraction for the alarm
*/
#include <openthread/platform/alarm-milli.h>
#include "platform-da15000.h"
#include "hw_timer0.h"
static bool sIsRunning = false;
static uint32_t sAlarm = 0;
static uint32_t sCounter;
volatile bool sAlarmFired = false;
static void timer0_interrupt_cb(void)
{
sCounter++;
}
void da15000AlarmProcess(otInstance *aInstance)
{
if ((sIsRunning) && (sAlarm <= sCounter))
{
sIsRunning = false;
<API key>(aInstance);
}
}
void da15000AlarmInit(void)
{
hw_timer0_init(NULL);
<API key>(<API key>);
<API key>(HW_TIMER0_MODE_PWM);
<API key>(<API key>);
<API key>(0x07D0, 0x07D0);
<API key>(timer0_interrupt_cb);
<API key>(false);
}
uint32_t <API key>(void)
{
return sCounter;
}
void <API key>(otInstance *aInstance, uint32_t t0, uint32_t dt)
{
OT_UNUSED_VARIABLE(aInstance);
sAlarm = t0 + dt;
sIsRunning = true;
if (sCounter == 0)
{
hw_timer0_enable();
}
hw_timer0_unfreeze();
}
void <API key>(otInstance *aInstance)
{
OT_UNUSED_VARIABLE(aInstance);
sIsRunning = false;
hw_timer0_freeze();
}
|
// Use of this source code is governed by a BSD-style
package provisiontest
import (
"fmt"
"io"
"io/ioutil"
"net/url"
"sort"
"sync"
"sync/atomic"
"time"
docker "github.com/fsouza/go-dockerclient"
"github.com/pkg/errors"
"github.com/tsuru/tsuru/action"
"github.com/tsuru/tsuru/app/bind"
"github.com/tsuru/tsuru/event"
"github.com/tsuru/tsuru/net"
"github.com/tsuru/tsuru/provision"
"github.com/tsuru/tsuru/provision/dockercommon"
"github.com/tsuru/tsuru/quota"
"github.com/tsuru/tsuru/router/routertest"
appTypes "github.com/tsuru/tsuru/types/app"
)
var (
ProvisionerInstance *FakeProvisioner
errNotProvisioned = &provision.Error{Reason: "App is not provisioned."}
uniqueIpCounter int32 = 0
_ provision.NodeProvisioner = &FakeProvisioner{}
_ provision.Provisioner = &FakeProvisioner{}
_ provision.App = &FakeApp{}
_ bind.App = &FakeApp{}
)
const fakeAppImage = "app-image"
func init() {
ProvisionerInstance = NewFakeProvisioner()
provision.Register("fake", func() (provision.Provisioner, error) {
return ProvisionerInstance, nil
})
}
// Fake implementation for provision.App.
type FakeApp struct {
name string
cname []string
IP string
platform string
units []provision.Unit
logs []string
logMut sync.Mutex
Commands []string
Memory int64
Swap int64
CpuShare int
commMut sync.Mutex
Deploys uint
env map[string]bind.EnvVar
bindCalls []*provision.Unit
bindLock sync.Mutex
serviceEnvs []bind.ServiceEnvVar
serviceLock sync.Mutex
Pool string
UpdatePlatform bool
TeamOwner string
Teams []string
quota.Quota
}
func NewFakeApp(name, platform string, units int) *FakeApp {
app := FakeApp{
name: name,
platform: platform,
units: make([]provision.Unit, units),
Quota: quota.Unlimited,
Pool: "test-default",
}
routertest.FakeRouter.AddBackend(&app)
namefmt := "%s-%d"
for i := 0; i < units; i++ {
val := atomic.AddInt32(&uniqueIpCounter, 1)
app.units[i] = provision.Unit{
ID: fmt.Sprintf(namefmt, name, i),
Status: provision.StatusStarted,
IP: fmt.Sprintf("10.10.10.%d", val),
Address: &url.URL{
Scheme: "http",
Host: fmt.Sprintf("10.10.10.%d:%d", val, val),
},
}
}
return &app
}
func (a *FakeApp) GetMemory() int64 {
return a.Memory
}
func (a *FakeApp) GetSwap() int64 {
return a.Swap
}
func (a *FakeApp) GetCpuShare() int {
return a.CpuShare
}
func (a *FakeApp) GetTeamsName() []string {
return a.Teams
}
func (a *FakeApp) HasBind(unit *provision.Unit) bool {
a.bindLock.Lock()
defer a.bindLock.Unlock()
for _, u := range a.bindCalls {
if u.ID == unit.ID {
return true
}
}
return false
}
func (a *FakeApp) BindUnit(unit *provision.Unit) error {
a.bindLock.Lock()
defer a.bindLock.Unlock()
a.bindCalls = append(a.bindCalls, unit)
return nil
}
func (a *FakeApp) UnbindUnit(unit *provision.Unit) error {
a.bindLock.Lock()
defer a.bindLock.Unlock()
index := -1
for i, u := range a.bindCalls {
if u.ID == unit.ID {
index = i
break
}
}
if index < 0 {
return errors.New("not bound")
}
length := len(a.bindCalls)
a.bindCalls[index] = a.bindCalls[length-1]
a.bindCalls = a.bindCalls[:length-1]
return nil
}
func (a *FakeApp) GetQuota() quota.Quota {
return a.Quota
}
func (a *FakeApp) SetQuotaInUse(inUse int) error {
if !a.Quota.Unlimited() && inUse > a.Quota.Limit {
return "a.QuotaExceededError{
Requested: uint(inUse),
Available: uint(a.Quota.Limit),
}
}
a.Quota.InUse = inUse
return nil
}
func (a *FakeApp) GetCname() []string {
return a.cname
}
func (a *FakeApp) GetServiceEnvs() []bind.ServiceEnvVar {
a.serviceLock.Lock()
defer a.serviceLock.Unlock()
return a.serviceEnvs
}
func (a *FakeApp) AddInstance(instanceArgs bind.AddInstanceArgs) error {
a.serviceLock.Lock()
defer a.serviceLock.Unlock()
a.serviceEnvs = append(a.serviceEnvs, instanceArgs.Envs...)
if instanceArgs.Writer != nil {
instanceArgs.Writer.Write([]byte("add instance"))
}
return nil
}
func (a *FakeApp) RemoveInstance(instanceArgs bind.RemoveInstanceArgs) error {
a.serviceLock.Lock()
defer a.serviceLock.Unlock()
lenBefore := len(a.serviceEnvs)
for i := 0; i < len(a.serviceEnvs); i++ {
se := a.serviceEnvs[i]
if se.ServiceName == instanceArgs.ServiceName && se.InstanceName == instanceArgs.InstanceName {
a.serviceEnvs = append(a.serviceEnvs[:i], a.serviceEnvs[i+1:]...)
i
}
}
if len(a.serviceEnvs) == lenBefore {
return errors.New("instance not found")
}
if instanceArgs.Writer != nil {
instanceArgs.Writer.Write([]byte("remove instance"))
}
return nil
}
func (a *FakeApp) Logs() []string {
a.logMut.Lock()
defer a.logMut.Unlock()
logs := make([]string, len(a.logs))
copy(logs, a.logs)
return logs
}
func (a *FakeApp) HasLog(source, unit, message string) bool {
log := source + unit + message
a.logMut.Lock()
defer a.logMut.Unlock()
for _, l := range a.logs {
if l == log {
return true
}
}
return false
}
func (a *FakeApp) GetCommands() []string {
a.commMut.Lock()
defer a.commMut.Unlock()
return a.Commands
}
func (a *FakeApp) Log(message, source, unit string) error {
a.logMut.Lock()
a.logs = append(a.logs, source+unit+message)
a.logMut.Unlock()
return nil
}
func (a *FakeApp) GetName() string {
return a.name
}
func (a *FakeApp) GetPool() string {
return a.Pool
}
func (a *FakeApp) GetPlatform() string {
return a.platform
}
func (a *FakeApp) GetDeploys() uint {
return a.Deploys
}
func (a *FakeApp) GetTeamOwner() string {
return a.TeamOwner
}
func (a *FakeApp) Units() ([]provision.Unit, error) {
return a.units, nil
}
func (a *FakeApp) AddUnit(u provision.Unit) {
a.units = append(a.units, u)
}
func (a *FakeApp) SetEnv(env bind.EnvVar) {
if a.env == nil {
a.env = map[string]bind.EnvVar{}
}
a.env[env.Name] = env
}
func (a *FakeApp) SetEnvs(setEnvs bind.SetEnvArgs) error {
for _, env := range setEnvs.Envs {
a.SetEnv(env)
}
return nil
}
func (a *FakeApp) UnsetEnvs(unsetEnvs bind.UnsetEnvArgs) error {
for _, env := range unsetEnvs.VariableNames {
delete(a.env, env)
}
return nil
}
func (a *FakeApp) GetLock() provision.AppLock {
return nil
}
func (a *FakeApp) GetUnits() ([]bind.Unit, error) {
units := make([]bind.Unit, len(a.units))
for i := range a.units {
units[i] = &a.units[i]
}
return units, nil
}
func (a *FakeApp) Envs() map[string]bind.EnvVar {
return a.env
}
func (a *FakeApp) Run(cmd string, w io.Writer, args provision.RunArgs) error {
a.commMut.Lock()
a.Commands = append(a.Commands, fmt.Sprintf("ran %s", cmd))
a.commMut.Unlock()
return nil
}
func (a *FakeApp) GetUpdatePlatform() bool {
return a.UpdatePlatform
}
func (app *FakeApp) GetRouters() []appTypes.AppRouter {
return []appTypes.AppRouter{{Name: "fake"}}
}
func (app *FakeApp) GetAddresses() ([]string, error) {
addr, err := routertest.FakeRouter.Addr(app.GetName())
if err != nil {
return nil, err
}
return []string{addr}, nil
}
type Cmd struct {
Cmd string
Args []string
App provision.App
}
type failure struct {
method string
err error
}
// Fake implementation for provision.Provisioner.
type FakeProvisioner struct {
Name string
cmds []Cmd
cmdMut sync.Mutex
outputs chan []byte
failures chan failure
apps map[string]provisionedApp
mut sync.RWMutex
shells map[string][]provision.ShellOptions
shellMut sync.Mutex
nodes map[string]FakeNode
nodeContainers map[string]int
}
func NewFakeProvisioner() *FakeProvisioner {
p := FakeProvisioner{Name: "fake"}
p.outputs = make(chan []byte, 8)
p.failures = make(chan failure, 8)
p.apps = make(map[string]provisionedApp)
p.shells = make(map[string][]provision.ShellOptions)
p.nodes = make(map[string]FakeNode)
p.nodeContainers = make(map[string]int)
return &p
}
func (p *FakeProvisioner) getError(method string) error {
select {
case fail := <-p.failures:
if fail.method == method {
return fail.err
}
p.failures <- fail
default:
}
return nil
}
type FakeNode struct {
ID string
Addr string
PoolName string
Meta map[string]string
status string
p *FakeProvisioner
failures int
hasSuccess bool
}
func (n *FakeNode) IaaSID() string {
return n.ID
}
func (n *FakeNode) Pool() string {
return n.PoolName
}
func (n *FakeNode) Address() string {
return n.Addr
}
func (n *FakeNode) Metadata() map[string]string {
return n.Meta
}
func (n *FakeNode) MetadataNoPrefix() map[string]string {
return n.Meta
}
func (n *FakeNode) Units() ([]provision.Unit, error) {
n.p.mut.Lock()
defer n.p.mut.Unlock()
return n.unitsLocked()
}
func (n *FakeNode) unitsLocked() ([]provision.Unit, error) {
var units []provision.Unit
for _, a := range n.p.apps {
for _, u := range a.units {
if net.URLToHost(u.Address.String()) == net.URLToHost(n.Addr) {
units = append(units, u)
}
}
}
return units, nil
}
func (n *FakeNode) Status() string {
return n.status
}
func (n *FakeNode) FailureCount() int {
return n.failures
}
func (n *FakeNode) HasSuccess() bool {
return n.hasSuccess
}
func (n *FakeNode) ResetFailures() {
n.failures = 0
}
func (n *FakeNode) Provisioner() provision.NodeProvisioner {
return n.p
}
func (n *FakeNode) SetHealth(failures int, hasSuccess bool) {
n.failures = failures
n.hasSuccess = hasSuccess
}
func (p *FakeProvisioner) AddNode(opts provision.AddNodeOptions) error {
p.mut.Lock()
defer p.mut.Unlock()
if err := p.getError("AddNode"); err != nil {
return err
}
if err := p.getError("AddNode:" + opts.Address); err != nil {
return err
}
metadata := opts.Metadata
if metadata == nil {
metadata = map[string]string{}
}
if _, ok := p.nodes[opts.Address]; ok {
return errors.New("fake node already exists")
}
p.nodes[opts.Address] = FakeNode{
ID: opts.IaaSID,
Addr: opts.Address,
PoolName: opts.Pool,
Meta: metadata,
p: p,
status: "enabled",
}
return nil
}
func (p *FakeProvisioner) GetNode(address string) (provision.Node, error) {
p.mut.RLock()
defer p.mut.RUnlock()
if err := p.getError("GetNode"); err != nil {
return nil, err
}
if n, ok := p.nodes[address]; ok {
return &n, nil
}
return nil, provision.ErrNodeNotFound
}
func (p *FakeProvisioner) RemoveNode(opts provision.RemoveNodeOptions) error {
p.mut.Lock()
defer p.mut.Unlock()
if err := p.getError("RemoveNode"); err != nil {
return err
}
_, ok := p.nodes[opts.Address]
if !ok {
return provision.ErrNodeNotFound
}
delete(p.nodes, opts.Address)
if opts.Writer != nil {
if opts.Rebalance {
opts.Writer.Write([]byte("rebalancing..."))
p.<API key>(provision.<API key>{
Force: true,
})
}
opts.Writer.Write([]byte("remove done!"))
}
return nil
}
func (p *FakeProvisioner) UpdateNode(opts provision.UpdateNodeOptions) error {
p.mut.Lock()
defer p.mut.Unlock()
if err := p.getError("UpdateNode"); err != nil {
return err
}
n, ok := p.nodes[opts.Address]
if !ok {
return provision.ErrNodeNotFound
}
if opts.Pool != "" {
n.PoolName = opts.Pool
}
if opts.Metadata != nil {
n.Meta = opts.Metadata
}
if opts.Enable {
n.status = "enabled"
}
if opts.Disable {
n.status = "disabled"
}
p.nodes[opts.Address] = n
return nil
}
type nodeList []provision.Node
func (l nodeList) Len() int { return len(l) }
func (l nodeList) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
func (l nodeList) Less(i, j int) bool { return l[i].Address() < l[j].Address() }
func (p *FakeProvisioner) ListNodes(addressFilter []string) ([]provision.Node, error) {
p.mut.RLock()
defer p.mut.RUnlock()
if err := p.getError("ListNodes"); err != nil {
return nil, err
}
var result []provision.Node
if addressFilter != nil {
result = make([]provision.Node, 0, len(addressFilter))
for _, a := range addressFilter {
n := p.nodes[a]
result = append(result, &n)
}
} else {
result = make([]provision.Node, 0, len(p.nodes))
for a := range p.nodes {
n := p.nodes[a]
result = append(result, &n)
}
}
sort.Sort(nodeList(result))
return result, nil
}
func (p *FakeProvisioner) NodeForNodeData(nodeData provision.NodeStatusData) (provision.Node, error) {
return provision.FindNodeByAddrs(p, nodeData.Addrs)
}
func (p *FakeProvisioner) RebalanceNodes(opts provision.<API key>) (bool, error) {
p.mut.Lock()
defer p.mut.Unlock()
return p.<API key>(opts)
}
func (p *FakeProvisioner) <API key>(opts provision.<API key>) (bool, error) {
if err := p.getError("RebalanceNodes"); err != nil {
return true, err
}
var w io.Writer
if opts.Event == nil {
w = ioutil.Discard
} else {
w = opts.Event
}
fmt.Fprintf(w, "rebalancing - dry: %v, force: %v\n", opts.Dry, opts.Force)
if len(opts.AppFilter) != 0 {
fmt.Fprintf(w, "filtering apps: %v\n", opts.AppFilter)
}
if len(opts.MetadataFilter) != 0 {
fmt.Fprintf(w, "filtering metadata: %v\n", opts.MetadataFilter)
}
if opts.Pool != "" {
fmt.Fprintf(w, "filtering pool: %v\n", opts.Pool)
}
if len(p.nodes) == 0 || opts.Dry {
return true, nil
}
max := 0
min := -1
var nodes []FakeNode
for _, n := range p.nodes {
nodes = append(nodes, n)
units, err := n.unitsLocked()
if err != nil {
return true, err
}
unitCount := len(units)
if unitCount > max {
max = unitCount
}
if min == -1 || unitCount < min {
min = unitCount
}
}
if max-min < 2 && !opts.Force {
return false, nil
}
gi := 0
for _, a := range p.apps {
nodeIdx := 0
for i := range a.units {
u := &a.units[i]
firstIdx := nodeIdx
var hostAddr string
for {
idx := nodeIdx
nodeIdx = (nodeIdx + 1) % len(nodes)
if nodes[idx].Pool() == a.app.GetPool() {
hostAddr = net.URLToHost(nodes[idx].Address())
break
}
if nodeIdx == firstIdx {
return true, errors.Errorf("unable to find node for pool %s", a.app.GetPool())
}
}
u.IP = hostAddr
u.Address = &url.URL{
Scheme: "http",
Host: fmt.Sprintf("%s:%d", hostAddr, gi),
}
gi++
}
}
return true, nil
}
// Restarts returns the number of restarts for a given app.
func (p *FakeProvisioner) Restarts(a provision.App, process string) int {
p.mut.RLock()
defer p.mut.RUnlock()
return p.apps[a.GetName()].restarts[process]
}
// Starts returns the number of starts for a given app.
func (p *FakeProvisioner) Starts(app provision.App, process string) int {
p.mut.RLock()
defer p.mut.RUnlock()
return p.apps[app.GetName()].starts[process]
}
// Stops returns the number of stops for a given app.
func (p *FakeProvisioner) Stops(app provision.App, process string) int {
p.mut.RLock()
defer p.mut.RUnlock()
return p.apps[app.GetName()].stops[process]
}
// Sleeps returns the number of sleeps for a given app.
func (p *FakeProvisioner) Sleeps(app provision.App, process string) int {
p.mut.RLock()
defer p.mut.RUnlock()
return p.apps[app.GetName()].sleeps[process]
}
func (p *FakeProvisioner) CustomData(app provision.App) map[string]interface{} {
p.mut.RLock()
defer p.mut.RUnlock()
return p.apps[app.GetName()].lastData
}
// Shells return all shell calls to the given unit.
func (p *FakeProvisioner) Shells(unit string) []provision.ShellOptions {
p.shellMut.Lock()
defer p.shellMut.Unlock()
return p.shells[unit]
}
// Returns the number of calls to restart.
// GetCmds returns a list of commands executed in an app. If you don't specify
// the command (an empty string), it will return all commands executed in the
// given app.
func (p *FakeProvisioner) GetCmds(cmd string, app provision.App) []Cmd {
var cmds []Cmd
p.cmdMut.Lock()
for _, c := range p.cmds {
if (cmd == "" || c.Cmd == cmd) && app.GetName() == c.App.GetName() {
cmds = append(cmds, c)
}
}
p.cmdMut.Unlock()
return cmds
}
// Provisioned checks whether the given app has been provisioned.
func (p *FakeProvisioner) Provisioned(app provision.App) bool {
p.mut.RLock()
defer p.mut.RUnlock()
_, ok := p.apps[app.GetName()]
return ok
}
func (p *FakeProvisioner) GetUnits(app provision.App) []provision.Unit {
p.mut.RLock()
pApp := p.apps[app.GetName()]
p.mut.RUnlock()
return pApp.units
}
// GetAppFromUnitID returns an app from unitID
func (p *FakeProvisioner) GetAppFromUnitID(unitID string) (provision.App, error) {
p.mut.RLock()
defer p.mut.RUnlock()
for _, a := range p.apps {
for _, u := range a.units {
if u.GetID() == unitID {
return a.app, nil
}
}
}
return nil, errors.New("app not found")
}
// PrepareOutput sends the given slice of bytes to a queue of outputs.
// Each prepared output will be used in the ExecuteCommand. It might be sent to
// the standard output or standard error. See ExecuteCommand docs for more
// details.
func (p *FakeProvisioner) PrepareOutput(b []byte) {
p.outputs <- b
}
// PrepareFailure prepares a failure for the given method name.
// For instance, PrepareFailure("GitDeploy", errors.New("GitDeploy failed")) will
// cause next Deploy call to return the given error. Multiple calls to this
// method will enqueue failures, i.e. three calls to
// PrepareFailure("GitDeploy"...) means that the three next GitDeploy call will
// fail.
func (p *FakeProvisioner) PrepareFailure(method string, err error) {
p.failures <- failure{method, err}
}
// Reset cleans up the FakeProvisioner, deleting all apps and their data. It
// also deletes prepared failures and output. It's like calling
// NewFakeProvisioner again, without all the allocations.
func (p *FakeProvisioner) Reset() {
p.cmdMut.Lock()
p.cmds = nil
p.cmdMut.Unlock()
p.mut.Lock()
p.apps = make(map[string]provisionedApp)
p.mut.Unlock()
p.shellMut.Lock()
p.shells = make(map[string][]provision.ShellOptions)
p.shellMut.Unlock()
p.mut.Lock()
p.nodes = make(map[string]FakeNode)
p.mut.Unlock()
uniqueIpCounter = 0
p.nodeContainers = make(map[string]int)
for {
select {
case <-p.outputs:
case <-p.failures:
default:
return
}
}
}
func (p *FakeProvisioner) Swap(app1, app2 provision.App, cnameOnly bool) error {
return routertest.FakeRouter.Swap(app1.GetName(), app2.GetName(), cnameOnly)
}
func (p *FakeProvisioner) Deploy(app provision.App, img string, evt *event.Event) (string, error) {
if err := p.getError("Deploy"); err != nil {
return "", err
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return "", errNotProvisioned
}
pApp.image = img
evt.Write([]byte("Builder deploy called"))
p.apps[app.GetName()] = pApp
return fakeAppImage, nil
}
func (p *FakeProvisioner) GetClient(app provision.App) (provision.BuilderDockerClient, error) {
for _, node := range p.nodes {
client, err := docker.NewClient(node.Addr)
if err != nil {
return nil, err
}
return &dockercommon.PullAndCreateClient{Client: client}, nil
}
return nil, errors.New("No node found")
}
func (p *FakeProvisioner) CleanImage(appName, imgName string) error {
for _, node := range p.nodes {
c, err := docker.NewClient(node.Addr)
if err != nil {
return err
}
err = c.RemoveImage(imgName)
if err != nil && err != docker.ErrNoSuchImage {
return err
}
}
return nil
}
func (p *FakeProvisioner) ArchiveDeploy(app provision.App, archiveURL string, evt *event.Event) (string, error) {
if err := p.getError("ArchiveDeploy"); err != nil {
return "", err
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return "", errNotProvisioned
}
evt.Write([]byte("Archive deploy called"))
pApp.lastArchive = archiveURL
p.apps[app.GetName()] = pApp
return fakeAppImage, nil
}
func (p *FakeProvisioner) UploadDeploy(app provision.App, file io.ReadCloser, fileSize int64, build bool, evt *event.Event) (string, error) {
if err := p.getError("UploadDeploy"); err != nil {
return "", err
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return "", errNotProvisioned
}
evt.Write([]byte("Upload deploy called"))
pApp.lastFile = file
p.apps[app.GetName()] = pApp
return fakeAppImage, nil
}
func (p *FakeProvisioner) ImageDeploy(app provision.App, img string, evt *event.Event) (string, error) {
if err := p.getError("ImageDeploy"); err != nil {
return "", err
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return "", errNotProvisioned
}
pApp.image = img
evt.Write([]byte("Image deploy called"))
p.apps[app.GetName()] = pApp
return img, nil
}
func (p *FakeProvisioner) Rollback(app provision.App, img string, evt *event.Event) (string, error) {
if err := p.getError("Rollback"); err != nil {
return "", err
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return "", errNotProvisioned
}
evt.Write([]byte("Rollback deploy called"))
p.apps[app.GetName()] = pApp
return img, nil
}
func (p *FakeProvisioner) Rebuild(app provision.App, evt *event.Event) (string, error) {
if err := p.getError("Rebuild"); err != nil {
return "", err
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return "", errNotProvisioned
}
evt.Write([]byte("Rebuild deploy called"))
p.apps[app.GetName()] = pApp
return fakeAppImage, nil
}
func (p *FakeProvisioner) Provision(app provision.App) error {
if err := p.getError("Provision"); err != nil {
return err
}
if p.Provisioned(app) {
return &provision.Error{Reason: "App already provisioned."}
}
p.mut.Lock()
defer p.mut.Unlock()
p.apps[app.GetName()] = provisionedApp{
app: app,
restarts: make(map[string]int),
starts: make(map[string]int),
stops: make(map[string]int),
sleeps: make(map[string]int),
}
return nil
}
func (p *FakeProvisioner) Restart(app provision.App, process string, w io.Writer) error {
if err := p.getError("Restart"); err != nil {
return err
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return errNotProvisioned
}
pApp.restarts[process]++
p.apps[app.GetName()] = pApp
if w != nil {
fmt.Fprintf(w, "restarting app")
}
return nil
}
func (p *FakeProvisioner) Start(app provision.App, process string) error {
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return errNotProvisioned
}
pApp.starts[process]++
p.apps[app.GetName()] = pApp
return nil
}
func (p *FakeProvisioner) Destroy(app provision.App) error {
if err := p.getError("Destroy"); err != nil {
return err
}
if !p.Provisioned(app) {
return errNotProvisioned
}
p.mut.Lock()
defer p.mut.Unlock()
delete(p.apps, app.GetName())
return nil
}
func (p *FakeProvisioner) AddUnits(app provision.App, n uint, process string, w io.Writer) error {
_, err := p.AddUnitsToNode(app, n, process, w, "")
return err
}
func (p *FakeProvisioner) AddUnitsToNode(app provision.App, n uint, process string, w io.Writer, nodeAddr string) ([]provision.Unit, error) {
if err := p.getError("AddUnits"); err != nil {
return nil, err
}
if n == 0 {
return nil, errors.New("Cannot add 0 units.")
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return nil, errNotProvisioned
}
name := app.GetName()
platform := app.GetPlatform()
length := uint(len(pApp.units))
var addresses []*url.URL
for i := uint(0); i < n; i++ {
val := atomic.AddInt32(&uniqueIpCounter, 1)
var hostAddr string
if nodeAddr != "" {
hostAddr = net.URLToHost(nodeAddr)
} else if len(p.nodes) > 0 {
for _, n := range p.nodes {
hostAddr = net.URLToHost(n.Address())
break
}
} else {
hostAddr = fmt.Sprintf("10.10.10.%d", val)
}
unit := provision.Unit{
ID: fmt.Sprintf("%s-%d", name, pApp.unitLen),
AppName: name,
Type: platform,
Status: provision.StatusStarted,
IP: hostAddr,
ProcessName: process,
Address: &url.URL{
Scheme: "http",
Host: fmt.Sprintf("%s:%d", hostAddr, val),
},
}
addresses = append(addresses, unit.Address)
pApp.units = append(pApp.units, unit)
pApp.unitLen++
}
err := routertest.FakeRouter.AddRoutes(name, addresses)
if err != nil {
return nil, err
}
result := make([]provision.Unit, int(n))
copy(result, pApp.units[length:])
p.apps[app.GetName()] = pApp
if w != nil {
fmt.Fprintf(w, "added %d units", n)
}
return result, nil
}
func (p *FakeProvisioner) RemoveUnits(app provision.App, n uint, process string, w io.Writer) error {
if err := p.getError("RemoveUnits"); err != nil {
return err
}
if n == 0 {
return errors.New("cannot remove 0 units")
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return errNotProvisioned
}
var newUnits []provision.Unit
removedCount := n
var addresses []*url.URL
for _, u := range pApp.units {
if removedCount > 0 && u.ProcessName == process {
removedCount
addresses = append(addresses, u.Address)
continue
}
newUnits = append(newUnits, u)
}
err := routertest.FakeRouter.RemoveRoutes(app.GetName(), addresses)
if err != nil {
return err
}
if removedCount > 0 {
return errors.New("too many units to remove")
}
if w != nil {
fmt.Fprintf(w, "removing %d units", n)
}
pApp.units = newUnits
pApp.unitLen = len(newUnits)
p.apps[app.GetName()] = pApp
return nil
}
// ExecuteCommand will pretend to execute the given command, recording data
// about it.
// The output of the command must be prepared with PrepareOutput, and failures
// must be prepared with PrepareFailure. In case of failure, the prepared
// output will be sent to the standard error stream, otherwise, it will be sent
// to the standard error stream.
// When there is no output nor failure prepared, ExecuteCommand will return a
// timeout error.
func (p *FakeProvisioner) ExecuteCommand(stdout, stderr io.Writer, app provision.App, cmd string, args ...string) error {
var (
output []byte
err error
)
command := Cmd{
Cmd: cmd,
Args: args,
App: app,
}
p.cmdMut.Lock()
p.cmds = append(p.cmds, command)
p.cmdMut.Unlock()
units, err := p.Units(app)
if err != nil {
return err
}
for range units {
select {
case output = <-p.outputs:
select {
case fail := <-p.failures:
if fail.method == "ExecuteCommand" {
stderr.Write(output)
return fail.err
}
p.failures <- fail
default:
stdout.Write(output)
}
case fail := <-p.failures:
if fail.method == "ExecuteCommand" {
err = fail.err
select {
case output = <-p.outputs:
stderr.Write(output)
default:
}
} else {
p.failures <- fail
}
case <-time.After(2e9):
return errors.New("FakeProvisioner timed out waiting for output.")
}
}
return err
}
func (p *FakeProvisioner) ExecuteCommandOnce(stdout, stderr io.Writer, app provision.App, cmd string, args ...string) error {
var output []byte
command := Cmd{
Cmd: cmd,
Args: args,
App: app,
}
p.cmdMut.Lock()
p.cmds = append(p.cmds, command)
p.cmdMut.Unlock()
select {
case output = <-p.outputs:
stdout.Write(output)
case fail := <-p.failures:
if fail.method == "ExecuteCommandOnce" {
select {
case output = <-p.outputs:
stderr.Write(output)
default:
}
return fail.err
} else {
p.failures <- fail
}
case <-time.After(2e9):
return errors.New("FakeProvisioner timed out waiting for output.")
}
return nil
}
func (p *FakeProvisioner) <API key>(stdout, stderr io.Writer, app provision.App, cmd string, args ...string) error {
var output []byte
command := Cmd{
Cmd: cmd,
Args: args,
App: app,
}
p.cmdMut.Lock()
p.cmds = append(p.cmds, command)
p.cmdMut.Unlock()
select {
case output = <-p.outputs:
stdout.Write(output)
case fail := <-p.failures:
if fail.method == "<API key>" {
select {
case output = <-p.outputs:
stderr.Write(output)
default:
}
return fail.err
} else {
p.failures <- fail
}
case <-time.After(2e9):
return errors.New("FakeProvisioner timed out waiting for output.")
}
return nil
}
func (p *FakeProvisioner) AddUnit(app provision.App, unit provision.Unit) {
p.mut.Lock()
defer p.mut.Unlock()
a := p.apps[app.GetName()]
a.units = append(a.units, unit)
a.unitLen++
p.apps[app.GetName()] = a
}
func (p *FakeProvisioner) Units(apps ...provision.App) ([]provision.Unit, error) {
if err := p.getError("Units"); err != nil {
return nil, err
}
p.mut.Lock()
defer p.mut.Unlock()
var allUnits []provision.Unit
for _, a := range apps {
allUnits = append(allUnits, p.apps[a.GetName()].units...)
}
return allUnits, nil
}
func (p *FakeProvisioner) RoutableAddresses(app provision.App) ([]url.URL, error) {
p.mut.Lock()
defer p.mut.Unlock()
units := p.apps[app.GetName()].units
addrs := make([]url.URL, len(units))
for i := range units {
addrs[i] = *units[i].Address
}
return addrs, nil
}
func (p *FakeProvisioner) SetUnitStatus(unit provision.Unit, status provision.Status) error {
p.mut.Lock()
defer p.mut.Unlock()
var units []provision.Unit
if unit.AppName == "" {
units = p.getAllUnits()
} else {
app, ok := p.apps[unit.AppName]
if !ok {
return errNotProvisioned
}
units = app.units
}
index := -1
for i, unt := range units {
if unt.ID == unit.ID {
index = i
unit.AppName = unt.AppName
break
}
}
if index < 0 {
return &provision.UnitNotFoundError{ID: unit.ID}
}
app := p.apps[unit.AppName]
app.units[index].Status = status
p.apps[unit.AppName] = app
return nil
}
func (p *FakeProvisioner) getAllUnits() []provision.Unit {
var units []provision.Unit
for _, app := range p.apps {
units = append(units, app.units...)
}
return units
}
func (p *FakeProvisioner) Addr(app provision.App) (string, error) {
if err := p.getError("Addr"); err != nil {
return "", err
}
return routertest.FakeRouter.Addr(app.GetName())
}
func (p *FakeProvisioner) SetCName(app provision.App, cname string) error {
if err := p.getError("SetCName"); err != nil {
return err
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return errNotProvisioned
}
pApp.cnames = append(pApp.cnames, cname)
p.apps[app.GetName()] = pApp
return routertest.FakeRouter.SetCName(cname, app.GetName())
}
func (p *FakeProvisioner) UnsetCName(app provision.App, cname string) error {
if err := p.getError("UnsetCName"); err != nil {
return err
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return errNotProvisioned
}
pApp.cnames = []string{}
p.apps[app.GetName()] = pApp
return routertest.FakeRouter.UnsetCName(cname, app.GetName())
}
func (p *FakeProvisioner) HasCName(app provision.App, cname string) bool {
p.mut.RLock()
pApp, ok := p.apps[app.GetName()]
p.mut.RUnlock()
for _, cnameApp := range pApp.cnames {
if cnameApp == cname {
return ok && true
}
}
return false
}
func (p *FakeProvisioner) Stop(app provision.App, process string) error {
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return errNotProvisioned
}
pApp.stops[process]++
for i, u := range pApp.units {
u.Status = provision.StatusStopped
pApp.units[i] = u
}
p.apps[app.GetName()] = pApp
return nil
}
func (p *FakeProvisioner) Sleep(app provision.App, process string) error {
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return errNotProvisioned
}
pApp.sleeps[process]++
for i, u := range pApp.units {
u.Status = provision.StatusAsleep
pApp.units[i] = u
}
p.apps[app.GetName()] = pApp
return nil
}
func (p *FakeProvisioner) RegisterUnit(a provision.App, unitId string, customData map[string]interface{}) error {
p.mut.Lock()
defer p.mut.Unlock()
pa, ok := p.apps[a.GetName()]
if !ok {
return errors.New("app not found")
}
pa.lastData = customData
for i, u := range pa.units {
if u.ID == unitId {
u.IP = u.IP + "-updated"
pa.units[i] = u
p.apps[a.GetName()] = pa
return nil
}
}
return &provision.UnitNotFoundError{ID: unitId}
}
func (p *FakeProvisioner) Shell(opts provision.ShellOptions) error {
var unit provision.Unit
units, err := p.Units(opts.App)
if err != nil {
return err
}
if len(units) == 0 {
return errors.New("app has no units")
} else if opts.Unit != "" {
for _, u := range units {
if u.ID == opts.Unit {
unit = u
break
}
}
} else {
unit = units[0]
}
if unit.ID == "" {
return errors.New("unit not found")
}
p.shellMut.Lock()
defer p.shellMut.Unlock()
p.shells[unit.ID] = append(p.shells[unit.ID], opts)
return nil
}
func (p *FakeProvisioner) <API key>(apps []provision.App, status []string) ([]provision.App, error) {
filteredApps := []provision.App{}
for i := range apps {
units, _ := p.Units(apps[i])
for _, u := range units {
if stringInArray(u.Status.String(), status) {
filteredApps = append(filteredApps, apps[i])
break
}
}
}
return filteredApps, nil
}
func (p *FakeProvisioner) GetName() string {
return p.Name
}
func (p *FakeProvisioner) <API key>(name string, pool string, writer io.Writer) error {
p.nodeContainers[name+"-"+pool]++
return nil
}
func (p *FakeProvisioner) RemoveNodeContainer(name string, pool string, writer io.Writer) error {
p.nodeContainers[name+"-"+pool] = 0
return nil
}
func (p *FakeProvisioner) HasNodeContainer(name string, pool string) bool {
return p.nodeContainers[name+"-"+pool] > 0
}
func stringInArray(value string, array []string) bool {
for _, str := range array {
if str == value {
return true
}
}
return false
}
type <API key> struct {
*FakeProvisioner
executedPipeline bool
}
func (p *<API key>) ExecutedPipeline() bool {
return p.executedPipeline
}
func (p *<API key>) DeployPipeline() *action.Pipeline {
act := action.Action{
Name: "<API key>",
Forward: func(ctx action.FWContext) (action.Result, error) {
p.executedPipeline = true
return nil, nil
},
Backward: func(ctx action.BWContext) {
},
}
actions := []*action.Action{&act}
pipeline := action.NewPipeline(actions...)
return pipeline
}
type <API key> struct {
*FakeProvisioner
}
func (p *<API key>) DeployPipeline() *action.Pipeline {
act := action.Action{
Name: "error-pipeline",
Forward: func(ctx action.FWContext) (action.Result, error) {
return nil, errors.New("deploy error")
},
Backward: func(ctx action.BWContext) {
},
}
actions := []*action.Action{&act}
pipeline := action.NewPipeline(actions...)
return pipeline
}
type provisionedApp struct {
units []provision.Unit
app provision.App
restarts map[string]int
starts map[string]int
stops map[string]int
sleeps map[string]int
lastArchive string
lastFile io.ReadCloser
cnames []string
unitLen int
lastData map[string]interface{}
image string
}
|
#ifndef __RTL_REGD_H__
#define __RTL_REGD_H__
struct <API key> {
u16 countrycode;
const char *iso_name;
};
enum country_code_type_t {
COUNTRY_CODE_FCC = 0,
COUNTRY_CODE_IC = 1,
COUNTRY_CODE_ETSI = 2,
COUNTRY_CODE_SPAIN = 3,
COUNTRY_CODE_FRANCE = 4,
COUNTRY_CODE_MKK = 5,
COUNTRY_CODE_MKK1 = 6,
COUNTRY_CODE_ISRAEL = 7,
COUNTRY_CODE_TELEC = 8,
COUNTRY_CODE_MIC = 9,
<API key> = 10,
<API key> = 11,
<API key> = 12,
/*add new channel plan above this line */
COUNTRY_CODE_MAX
};
int rtl_regd_init(struct ieee80211_hw *hw,
int (*reg_notifier) (struct wiphy *wiphy,
struct regulatory_request *request));
int rtl_reg_notifier(struct wiphy *wiphy, struct regulatory_request *request);
#endif
|
var request = require('request'),
log = require('bole')('npme-send-data'),
config = require('../../../config')
module.exports = function (formGuid, data, callback) {
var hubspot = config.license.hubspot.forms
.replace(":portal_id", config.license.hubspot.portal_id)
.replace(":form_guid", formGuid);
request.post(hubspot, function (er, resp) {
// we can ignore 302 responses
if (resp.statusCode === 204 || resp.statusCode === 302) {
return callback(null);
}
log.error('unexpected status code from hubspot; status=' + resp.statusCode + '; data=', data);
callback(new Error('unexpected status code: ' + resp.statusCode));
}).form(data);
}
|
module.exports = {
env: {
mocha: true
},
plugins: [
'mocha'
]
};
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | Converting 'MC' programs to 'MCMem'.
module Futhark.Pass.ExplicitAllocations.MC (explicitAllocations) where
import Futhark.IR.MC
import Futhark.IR.MCMem
import Futhark.Pass.ExplicitAllocations
import Futhark.Pass.ExplicitAllocations.SegOp
instance SizeSubst (MCOp rep op) where
opSizeSubst _ _ = mempty
handleSegOp :: SegOp () MC -> AllocM MC MCMem (SegOp () MCMem)
handleSegOp op = do
let num_threads = intConst Int64 256 -- FIXME
mapSegOpM (mapper num_threads) op
where
scope = scopeOfSegSpace $ segSpace op
mapper num_threads =
identitySegOpMapper
{ mapOnSegOpBody =
localScope scope . allocInKernelBody,
mapOnSegOpLambda =
allocInBinOpLambda num_threads (segSpace op)
}
handleMCOp :: Op MC -> AllocM MC MCMem (Op MCMem)
handleMCOp (ParOp par_op op) =
Inner <$> (ParOp <$> traverse handleSegOp par_op <*> handleSegOp op)
handleMCOp (OtherOp soac) =
error $ "Cannot allocate memory in SOAC: " ++ pretty soac
-- | The pass from 'MC' to 'MCMem'.
explicitAllocations :: Pass MC MCMem
explicitAllocations = <API key> handleMCOp defaultExpHints
|
/* eslint-disable flowtype/<API key>, flowtype/require-return-type, no-magic-numbers */
import {test} from "tap"
import {spy} from "sinon"
import aside from "./"
test(({equal, end}) => {
const unction = spy(() => "b")
equal(aside([unction])("a"), "a")
end()
})
test(({ok, end}) => {
const unction = spy(() => "b")
aside([unction])("a")
ok(unction.calledWith("a"))
end()
})
test(({equal, end}) => {
const unction = spy(() => "b")
equal(aside([unction])("a"), "a")
end()
})
test(({ok, equal, end}) => {
const unctionA = spy(() => "b")
const unctionB = spy(() => "c")
equal(aside([unctionA, unctionB])("a"), "a")
ok(unctionA.calledWith("a"))
ok(unctionB.calledWith("b"))
end()
})
|
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#include <sys/param.h>
#include <sys/bus.h>
#include <sys/kernel.h>
#include <sys/module.h>
#include <sys/socket.h>
#include <sys/systm.h>
#include <net/ethernet.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <machine/bus.h>
#include <machine/resource.h>
#include <sys/rman.h>
#include <dev/pccard/pccardvar.h>
#include <dev/pccard/pccard_cis.h>
#include <dev/sn/if_snreg.h>
#include <dev/sn/if_snvar.h>
#include "card_if.h"
#include "pccarddevs.h"
typedef int sn_get_enaddr_t(device_t dev, u_char *eaddr);
typedef int sn_activate_t(device_t dev);
struct sn_sw
{
int type;
#define SN_NORMAL 1
#define SN_MEGAHERTZ 2
#define SN_OSITECH 3
#define SN_OSI_SOD 4
#define SN_MOTO_MARINER 5
char *typestr;
sn_get_enaddr_t *get_mac;
sn_activate_t *activate;
};
static sn_get_enaddr_t <API key>;
static sn_activate_t <API key>;
const static struct sn_sw sn_normal_sw = {
SN_NORMAL, "plain",
<API key>,
<API key>
};
static sn_get_enaddr_t <API key>;
static sn_activate_t <API key>;
const static struct sn_sw sn_mhz_sw = {
SN_MEGAHERTZ, "Megahertz",
<API key>,
<API key>
};
static const struct sn_product {
struct pccard_product prod;
const struct sn_sw *sw;
} sn_pccard_products[] = {
{ PCMCIA_CARD(DSPSI, XJEM1144), &sn_mhz_sw },
{ PCMCIA_CARD(DSPSI, XJACK), &sn_normal_sw },
/* { PCMCIA_CARD(MOTOROLA, MARINER), SN_MOTO_MARINER }, */
{ PCMCIA_CARD(NEWMEDIA, BASICS), &sn_normal_sw },
{ PCMCIA_CARD(MEGAHERTZ, VARIOUS), &sn_mhz_sw},
{ PCMCIA_CARD(MEGAHERTZ, XJEM3336), &sn_mhz_sw},
/* { PCMCIA_CARD(OSITECH, TRUMP_SOD), SN_OSI_SOD }, */
/* { PCMCIA_CARD(OSITECH, TRUMP_JOH), SN_OSITECH }, */
/* { PCMCIA_CARD(PSION, GOLDCARD), SN_OSITECH }, */
/* { PCMCIA_CARD(PSION, NETGLOBAL), SNI_OSI_SOD }, */
/* { PCMCIA_CARD(PSION, NETGLOBAL2), SN_OSITECH }, */
{ PCMCIA_CARD(SMC, 8020BT), &sn_normal_sw },
{ PCMCIA_CARD(SMC, SMC91C96), &sn_normal_sw },
{ { NULL } }
};
static const struct sn_product *
sn_pccard_lookup(device_t dev)
{
return ((const struct sn_product *)
<API key>(dev,
(const struct pccard_product *)sn_pccard_products,
sizeof(sn_pccard_products[0]), NULL));
}
static int
sn_pccard_probe(device_t dev)
{
const struct sn_product *pp;
if ((pp = sn_pccard_lookup(dev)) != NULL) {
if (pp->prod.pp_name != NULL)
device_set_desc(dev, pp->prod.pp_name);
return 0;
}
return EIO;
}
static int
<API key>(const char *str, u_char *enet)
{
uint8_t digit;
int i;
memset(enet, 0, ETHER_ADDR_LEN);
for (i = 0, digit = 0; i < (ETHER_ADDR_LEN * 2); i++) {
if (str[i] >= '0' && str[i] <= '9')
digit |= str[i] - '0';
else if (str[i] >= 'a' && str[i] <= 'f')
digit |= (str[i] - 'a') + 10;
else if (str[i] >= 'A' && str[i] <= 'F')
digit |= (str[i] - 'A') + 10;
else
return (0); /* Bogus digit!! */
/* Compensate for ordering of digits. */
if (i & 1) {
enet[i >> 1] = digit;
digit = 0;
} else
digit <<= 4;
}
return (1);
}
static int
<API key>(device_t dev, u_char *eaddr)
{
int i, sum;
const char *cisstr;
pccard_get_ether(dev, eaddr);
for (i = 0, sum = 0; i < ETHER_ADDR_LEN; i++)
sum |= eaddr[i];
if (sum == 0) {
pccard_get_cis3_str(dev, &cisstr);
if (cisstr && strlen(cisstr) == ETHER_ADDR_LEN * 2)
sum = <API key>(cisstr, eaddr);
}
if (sum == 0) {
pccard_get_cis4_str(dev, &cisstr);
if (cisstr && strlen(cisstr) == ETHER_ADDR_LEN * 2)
sum = <API key>(cisstr, eaddr);
}
return sum;
}
static int
<API key>(device_t dev)
{
int err;
err = sn_activate(dev);
if (err)
sn_deactivate(dev);
return (err);
}
static int
<API key>(const struct pccard_tuple *tuple, void *argp)
{
uint8_t *enaddr = argp;
int i;
uint8_t buffer[ETHER_ADDR_LEN * 2];
/* Code 0x81 is Megahertz' special cis node contianing the MAC */
if (tuple->code != 0x81)
return (0);
/* Make sure this is a sane node, as ASCII digits */
if (tuple->length != ETHER_ADDR_LEN * 2 + 1)
return (0);
/* Copy the MAC ADDR and return success if decoded */
for (i = 0; i < ETHER_ADDR_LEN * 2; i++)
buffer[i] = pccard_tuple_read_1(tuple, i);
return (<API key>(buffer, enaddr));
}
static int
<API key>(device_t dev, u_char *eaddr)
{
if (<API key>(dev, eaddr))
return 1;
/*
* If that fails, try the special CIS tuple 0x81 that the
* '3288 and '3336 cards have. That tuple specifies an ASCII
* string, ala CIS3 or CIS4 in the 'normal' cards.
*/
return (pccard_cis_scan(dev, <API key>, eaddr));
}
static int
<API key>(device_t dev)
{
int err;
struct sn_softc *sc = device_get_softc(dev);
u_long start;
err = sn_activate(dev);
if (err) {
sn_deactivate(dev);
return (err);
}
/*
* CIS resource is the modem one, so save it away.
*/
sc->modem_rid = sc->port_rid;
sc->modem_res = sc->port_res;
/*
* The MHz XJEM/CCEM series of cards just need to have any
* old resource allocated for the ethernet side of things,
* provided bit 0x80 isn't set in the address. That bit is
* evidentially reserved for modem function and is how the
* card steers the addresses internally.
*/
sc->port_res = NULL;
start = 0;
do
{
sc->port_rid = 1;
sc->port_res = bus_alloc_resource(dev, SYS_RES_IOPORT,
&sc->port_rid, start, ~0, SMC_IO_EXTENT, RF_ACTIVE);
if (sc->port_res == NULL)
break;
if (!(rman_get_start(sc->port_res) & 0x80))
break;
start = rman_get_start(sc->port_res) + SMC_IO_EXTENT;
<API key>(dev, SYS_RES_IOPORT, sc->port_rid,
sc->port_res);
} while (start < 0xff80);
if (sc->port_res == NULL) {
sn_deactivate(dev);
return ENOMEM;
}
return 0;
}
static int
sn_pccard_attach(device_t dev)
{
struct sn_softc *sc = device_get_softc(dev);
u_char eaddr[ETHER_ADDR_LEN];
int i, err;
uint16_t w;
u_char sum;
const struct sn_product *pp;
pp = sn_pccard_lookup(dev);
sum = pp->sw->get_mac(dev, eaddr);
/* Allocate resources so we can program the ether addr */
sc->dev = dev;
err = pp->sw->activate(dev);
if (err != 0)
return (err);
if (sum) {
printf("Programming sn card's addr\n");
SMC_SELECT_BANK(sc, 1);
for (i = 0; i < 3; i++) {
w = (uint16_t)eaddr[i * 2] |
(((uint16_t)eaddr[i * 2 + 1]) << 8);
CSR_WRITE_2(sc, IAR_ADDR0_REG_W + i * 2, w);
}
}
err = sn_attach(dev);
if (err)
sn_deactivate(dev);
return (err);
}
static device_method_t sn_pccard_methods[] = {
/* Device interface */
DEVMETHOD(device_probe, sn_pccard_probe),
DEVMETHOD(device_attach, sn_pccard_attach),
DEVMETHOD(device_detach, sn_detach),
{ 0, 0 }
};
static driver_t sn_pccard_driver = {
"sn",
sn_pccard_methods,
sizeof(struct sn_softc),
};
extern devclass_t sn_devclass;
DRIVER_MODULE(sn, pccard, sn_pccard_driver, sn_devclass, 0, 0);
MODULE_DEPEND(sn, ether, 1, 1, 1);
PCCARD_PNP_INFO(sn_pccard_products);
|
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <assert.h>
#include <err.h>
#include <errno.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/*
* $FreeBSD$
* The goal of this program is to see if fstat reports the correct
* data count for a pipe. Prior to revision 1.172 of sys_pipe.c,
* 0 would be returned once the pipe entered direct write mode.
*
* Linux (2.6) always returns zero, so it's not a valuable platform
* for comparison.
*/
int
main(void)
{
char buffer[32768], buffer2[32768], go[] = "go", go2[] = "go2";
int desc[2], ipc_coord[2];
ssize_t error;
int successes = 0;
struct stat status;
pid_t new_pid;
error = pipe(desc);
if (error == -1)
err(1, "Couldn't allocate data pipe");
error = pipe(ipc_coord);
if (error == -1)
err(1, "Couldn't allocate IPC coordination pipe");
new_pid = fork();
assert(new_pid != -1);
close(new_pid == 0 ? desc[0] : desc[1]);
#define SYNC_R(i, _buf) do { \
int _error = errno; \
warnx("%d: waiting for synchronization", __LINE__); \
if (read(ipc_coord[i], &_buf, sizeof(_buf)) != sizeof(_buf)) \
err(1, "failed to synchronize (%s)", (i == 0 ? "parent" : "child")); \
errno = _error; \
} while(0)
#define SYNC_W(i, _buf) do { \
int _error = errno; \
warnx("%d: sending synchronization", __LINE__); \
if (write(ipc_coord[i], &_buf, sizeof(_buf)) != sizeof(_buf)) \
err(1, "failed to synchronize (%s)", (i == 0 ? "child" : "parent")); \
errno = _error; \
} while(0)
#define WRITE(s) do { \
ssize_t _size; \
if ((_size = write(desc[1], &buffer, s)) != s) \
warn("short write; wrote %zd, expected %d", _size, s); \
} while(0)
if (new_pid == 0) {
SYNC_R(0, go);
WRITE(145);
SYNC_W(0, go2);
SYNC_R(0, go);
WRITE(2048);
SYNC_W(0, go2);
SYNC_R(0, go);
WRITE(4096);
SYNC_W(0, go2);
SYNC_R(0, go);
WRITE(8191);
SYNC_W(0, go2);
SYNC_R(0, go);
SYNC_W(0, go2); /* XXX: why is this required? */
WRITE(8192);
SYNC_W(0, go2);
close(ipc_coord[0]);
close(ipc_coord[1]);
_exit(0);
}
while (successes < 5) {
SYNC_W(1, go);
SYNC_R(1, go2);
fstat(desc[0], &status);
error = read(desc[0], &buffer2, sizeof(buffer2));
if (status.st_size != error)
err(1, "FAILURE: stat size %jd read size %zd",
(intmax_t)status.st_size, error);
if (error > 0) {
printf("SUCCESS at stat size %jd read size %zd\n",
(intmax_t)status.st_size, error);
successes++;
}
}
exit(0);
}
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include "utils/int_stack.h"
static int_stack_t stack;
static void print_stack(int_stack_t *stack) {
iblock_t *b;
printf("stack %p\n", stack);
printf(" current block = %p\n", stack->current);
printf(" free list = %p\n", stack->free);
printf(" active blocks:\n");
b = stack->current;
while (b != NULL) {
printf(" block %p: size = %"PRIu32" ptr = %"PRIu32" data = %p\n", b, b->size, b->ptr, b->data);
b = b->next;
}
printf(" free blocks:\n");
b = stack->free;
while (b != NULL) {
printf(" block %p: size = %"PRIu32" ptr = %"PRIu32" data = %p\n", b, b->size, b->ptr, b->data);
b = b->next;
}
printf("\n");
}
int main(void) {
int32_t *a1, *a2, *a3, *a4;
printf("=== Initialization ===\n");
init_istack(&stack);
print_stack(&stack);
printf("=== Allocation a1: size 100 ===\n");
a1 = alloc_istack_array(&stack, 100);
printf(" a1 = %p\n", a1);
print_stack(&stack);
printf("=== Allocation a2: size 500 ===\n");
a2 = alloc_istack_array(&stack, 500);
printf(" a2 = %p\n", a2);
print_stack(&stack);
printf("=== Allocation a3: size 800 ===\n");
a3 = alloc_istack_array(&stack, 800);
printf(" a3 = %p\n", a3);
print_stack(&stack);
printf("=== Allocation a4: size 8000 ===\n");
a4 = alloc_istack_array(&stack, 8000);
printf(" a4 = %p\n", a4);
print_stack(&stack);
printf("=== Free a4 ===\n");
free_istack_array(&stack, a4);
print_stack(&stack);
printf("=== Allocation a4: size 800 ===\n");
a4 = alloc_istack_array(&stack, 800);
printf(" a4 = %p\n", a4);
print_stack(&stack);
printf("=== Free a4 ===\n");
free_istack_array(&stack, a4);
print_stack(&stack);
printf("=== Free a3 ===\n");
free_istack_array(&stack, a3);
print_stack(&stack);
printf("=== Reset ===\n");
reset_istack(&stack);
print_stack(&stack);
delete_istack(&stack);
return 0;
}
|
package com.thoughtworks.cozmos;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.<API key>;
import java.net.Socket;
import java.net.URL;
import java.util.StringTokenizer;
public class <API key> extends HttpServlet {
private String targetURL;
private String newPageTemplate;
public void init(ServletConfig servletConfig) throws ServletException {
targetURL = servletConfig.getInitParameter("mod_dav_svn_url");
newPageTemplate = servletConfig.getInitParameter("<API key>");
super.init(servletConfig);
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String path = req.getServletPath();
Socket socket = startGet(new URL(targetURL + path));
InputStream is = socket.getInputStream();
LineNumberReader lnr = new LineNumberReader(new InputStreamReader(is));
boolean ok = isOk(lnr);
if (!ok) {
socket = startGet(new URL(targetURL + newPageTemplate));
lnr = new LineNumberReader(new InputStreamReader(is));
ok = isOk(lnr);
}
if (ok) {
lnr.readLine();
lnr.readLine(); // Server:
lnr.readLine(); // ETag:
lnr.readLine(); // Accept-Ranges:
int contentLength = getContentLen(lnr.readLine());
lnr.readLine(); // Content-Type:
lnr.readLine(); // end of header
resp.setContentType(getServletContext().getMimeType(path));
OutputStream os = resp.getOutputStream();
int done = 0;
while (done < contentLength) {
int i = lnr.read();
done++;
os.write(i);
}
socket.close();
}
}
private int getContentLen(String s) {
StringTokenizer st = new StringTokenizer(s);
st.nextToken();
return Integer.parseInt(st.nextToken());
}
private boolean isOk(LineNumberReader lnr) throws IOException {
return "HTTP/1.1 200 OK".equals(lnr.readLine());
}
private Socket startGet(URL url) throws IOException {
Socket socket = new Socket(url.getHost(), 80);
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
pw.println("GET " + url.getPath() + " HTTP/1.1");
pw.println("Host: " + url.getHost());
pw.println();
return socket;
}
}
|
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#include "opt_compat.h"
#include "opt_vm.h"
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/lock.h>
#include <sys/malloc.h>
#include <sys/rwlock.h>
#include <sys/sysent.h>
#include <sys/sysctl.h>
#include <sys/vdso.h>
#include <vm/vm.h>
#include <vm/vm_param.h>
#include <vm/pmap.h>
#include <vm/vm_extern.h>
#include <vm/vm_kern.h>
#include <vm/vm_map.h>
#include <vm/vm_object.h>
#include <vm/vm_page.h>
#include <vm/vm_pager.h>
static struct sx <API key>;
static vm_object_t shared_page_obj;
static int shared_page_free;
char *shared_page_mapping;
void
shared_page_write(int base, int size, const void *data)
{
bcopy(data, shared_page_mapping + base, size);
}
static int
<API key>(int size, int align)
{
int res;
res = roundup(shared_page_free, align);
if (res + size >= IDX_TO_OFF(shared_page_obj->size))
res = -1;
else
shared_page_free = res + size;
return (res);
}
int
shared_page_alloc(int size, int align)
{
int res;
sx_xlock(&<API key>);
res = <API key>(size, align);
sx_xunlock(&<API key>);
return (res);
}
int
shared_page_fill(int size, int align, const void *data)
{
int res;
sx_xlock(&<API key>);
res = <API key>(size, align);
if (res != -1)
shared_page_write(res, size, data);
sx_xunlock(&<API key>);
return (res);
}
static void
shared_page_init(void *dummy __unused)
{
vm_page_t m;
vm_offset_t addr;
sx_init(&<API key>, "shpsx");
shared_page_obj = vm_pager_allocate(OBJT_PHYS, 0, PAGE_SIZE,
VM_PROT_DEFAULT, 0, NULL);
VM_OBJECT_WLOCK(shared_page_obj);
m = vm_page_grab(shared_page_obj, 0, VM_ALLOC_NOBUSY | VM_ALLOC_ZERO);
m->valid = VM_PAGE_BITS_ALL;
VM_OBJECT_WUNLOCK(shared_page_obj);
addr = kva_alloc(PAGE_SIZE);
pmap_qenter(addr, &m, 1);
shared_page_mapping = (char *)addr;
}
SYSINIT(shp, SI_SUB_EXEC, SI_ORDER_FIRST, (sysinit_cfunc_t)shared_page_init,
NULL);
/*
* Push the timehands update to the shared page.
*
* The lockless update scheme is similar to the one used to update the
* in-kernel timehands, see sys/kern/kern_tc.c:tc_windup() (which
* calls us after the timehands are updated).
*/
static void
timehands_update(struct vdso_sv_tk *svtk)
{
struct vdso_timehands th;
struct vdso_timekeep *tk;
uint32_t enabled, idx;
enabled = <API key>(&th);
th.th_gen = 0;
idx = svtk->sv_timekeep_curr;
if (++idx >= VDSO_TH_NUM)
idx = 0;
svtk->sv_timekeep_curr = idx;
if (++svtk->sv_timekeep_gen == 0)
svtk->sv_timekeep_gen = 1;
tk = (struct vdso_timekeep *)(shared_page_mapping +
svtk->sv_timekeep_off);
tk->tk_th[idx].th_gen = 0;
<API key>();
if (enabled)
tk->tk_th[idx] = th;
atomic_store_rel_32(&tk->tk_th[idx].th_gen, svtk->sv_timekeep_gen);
atomic_store_rel_32(&tk->tk_current, idx);
/*
* The ordering of the assignment to tk_enabled relative to
* the update of the vdso_timehands is not important.
*/
tk->tk_enabled = enabled;
}
#ifdef COMPAT_FREEBSD32
static void
timehands_update32(struct vdso_sv_tk *svtk)
{
struct vdso_timehands32 th;
struct vdso_timekeep32 *tk;
uint32_t enabled, idx;
enabled = <API key>(&th);
th.th_gen = 0;
idx = svtk->sv_timekeep_curr;
if (++idx >= VDSO_TH_NUM)
idx = 0;
svtk->sv_timekeep_curr = idx;
if (++svtk->sv_timekeep_gen == 0)
svtk->sv_timekeep_gen = 1;
tk = (struct vdso_timekeep32 *)(shared_page_mapping +
svtk->sv_timekeep_off);
tk->tk_th[idx].th_gen = 0;
<API key>();
if (enabled)
tk->tk_th[idx] = th;
atomic_store_rel_32(&tk->tk_th[idx].th_gen, svtk->sv_timekeep_gen);
atomic_store_rel_32(&tk->tk_current, idx);
tk->tk_enabled = enabled;
}
#endif
/*
* This is hackish, but easiest way to avoid creating list structures
* that needs to be iterated over from the hardclock interrupt
* context.
*/
static struct vdso_sv_tk *host_svtk;
#ifdef COMPAT_FREEBSD32
static struct vdso_sv_tk *compat32_svtk;
#endif
void
timekeep_push_vdso(void)
{
if (host_svtk != NULL)
timehands_update(host_svtk);
#ifdef COMPAT_FREEBSD32
if (compat32_svtk != NULL)
timehands_update32(compat32_svtk);
#endif
}
struct vdso_sv_tk *
alloc_sv_tk(void)
{
struct vdso_sv_tk *svtk;
int tk_base;
uint32_t tk_ver;
tk_ver = VDSO_TK_VER_CURR;
svtk = malloc(sizeof(struct vdso_sv_tk), M_TEMP, M_WAITOK | M_ZERO);
tk_base = shared_page_alloc(sizeof(struct vdso_timekeep) +
sizeof(struct vdso_timehands) * VDSO_TH_NUM, 16);
KASSERT(tk_base != -1, ("tk_base -1 for native"));
shared_page_write(tk_base + offsetof(struct vdso_timekeep, tk_ver),
sizeof(uint32_t), &tk_ver);
svtk->sv_timekeep_off = tk_base;
timekeep_push_vdso();
return (svtk);
}
#ifdef COMPAT_FREEBSD32
struct vdso_sv_tk *
<API key>(void)
{
struct vdso_sv_tk *svtk;
int tk_base;
uint32_t tk_ver;
svtk = malloc(sizeof(struct vdso_sv_tk), M_TEMP, M_WAITOK | M_ZERO);
tk_ver = VDSO_TK_VER_CURR;
tk_base = shared_page_alloc(sizeof(struct vdso_timekeep32) +
sizeof(struct vdso_timehands32) * VDSO_TH_NUM, 16);
KASSERT(tk_base != -1, ("tk_base -1 for 32bit"));
shared_page_write(tk_base + offsetof(struct vdso_timekeep32,
tk_ver), sizeof(uint32_t), &tk_ver);
svtk->sv_timekeep_off = tk_base;
timekeep_push_vdso();
return (svtk);
}
#endif
void
exec_sysvec_init(void *param)
{
struct sysentvec *sv;
sv = (struct sysentvec *)param;
if ((sv->sv_flags & SV_SHP) == 0)
return;
sv->sv_shared_page_obj = shared_page_obj;
sv->sv_sigcode_base = sv->sv_shared_page_base +
shared_page_fill(*(sv->sv_szsigcode), 16, sv->sv_sigcode);
if ((sv->sv_flags & SV_ABI_MASK) != SV_ABI_FREEBSD)
return;
if ((sv->sv_flags & SV_TIMEKEEP) != 0) {
#ifdef COMPAT_FREEBSD32
if ((sv->sv_flags & SV_ILP32) != 0) {
KASSERT(compat32_svtk == NULL,
("Compat32 already registered"));
compat32_svtk = <API key>();
sv->sv_timekeep_base = sv->sv_shared_page_base +
compat32_svtk->sv_timekeep_off;
} else {
#endif
KASSERT(host_svtk == NULL, ("Host already registered"));
host_svtk = alloc_sv_tk();
sv->sv_timekeep_base = sv->sv_shared_page_base +
host_svtk->sv_timekeep_off;
#ifdef COMPAT_FREEBSD32
}
#endif
}
}
|
# $FreeBSD$
SUBDIR= libasn1 libgssapi_krb5 libgssapi_ntlm libgssapi_spnego libhdb \
libheimntlm libhx509 libkadm5clnt libkadm5srv libkrb5 \
libroken libsl libvers libkdc libwind libheimbase libheimipcc libheimipcs
SUBDIR+= libkafs5 # requires krb_err.h from libkrb5
<API key>= libkrb5
.include <bsd.subdir.mk>
|
TARGETS = cpcond tagintr
EXTRA_OBJS = ../dmatags.o ../dmasend.o
EE_LIBS = -lg -ldma
COMMON_DIR=../../../common
include $(COMMON_DIR)/common-ee.mk
|
var doNothing = function () {}
/**
* The `Base` log defines methods that transports will share.
*/
var Base = module.exports = function (config, defaults) {
var cedar = require('../../cedar')
// A log is a shorthand for `log.log`, among other things.
var log = function () {
log.log.apply(log, arguments)
}
// Don't run `setMethods` until all config properties are set.
var setMethods = doNothing
// Define properties that trigger `setMethods`.
Base.resetters.forEach(function (property) {
var value
Object.defineProperty(log, property, {
get: function () {
return value
},
set: function (newValue) {
value = newValue
setMethods.apply(log)
}
})
})
// Copy `config` properties to the `log`.
Base.decorate(log, config, true)
// Apply default properties.
Base.decorate(log, defaults || Base.defaults)
// Set up logging methods.
Base.setMethods.apply(log)
// Re-run `setMethods` if `resetters` change.
setMethods = Base.setMethods
// Return the fully-decorated log function.
return log
}
/**
* Some properties will reset methods if changed.
*/
Base.resetters = ['level', 'prefixes', 'format', 'showTrace']
/**
* Cedar supports 7 levels of logging.
*/
Base.levels = ['trace', 'debug', 'log', 'info', 'warn', 'error', 'fatal']
/**
* Share defaults between log objects.
*/
Base.defaults = {
// Show all log messages by default.
level: 'trace',
// Stream to `stdout` (using `write`).
stream: process.stdout,
// Don't add any space to JSON.
space: '',
// Stringify with `JSON.stringify`.
stringify: JSON.stringify,
// Join arguments together as an array.
join: function (args) {
var list = []
for (var index = 0, length = args.length; index < length; index++) {
var arg = args[index]
if (arg instanceof Error) {
arg = '"' + (arg.stack || arg.toString()).replace(/\n/, '\\n') + '"'
} else {
arg = JSON.stringify(arg, null, this.space)
}
list.push(arg)
}
return '[' + list.join(',') + ']'
},
// Start messages with a prefix for each log method.
prefixes: {
trace: 'TRACE ',
debug: 'DEBUG ',
log: 'LOG ',
info: 'INFO ',
warn: 'WARN ',
error: 'ERROR ',
fatal: 'FATAL '
},
// Format a log message.
format: function (message, type, prefix) {
return prefix + message + '\n'
}
}
/**
* Decorate an object with the properties of another.
*/
Base.decorate = function (object, defaults, shouldOverwrite) {
object = object || {}
for (var key in defaults) {
if (shouldOverwrite || (typeof object[key] === 'undefined')) {
object[key] = defaults[key]
}
}
return object
}
/**
* Create logging methods based on the configured `level`.
*/
Base.setMethods = function () {
var self = this
var found = false
if ((Base.levels.indexOf(self.level) < 0) && self.level !== 'nothing') {
self.error('Unknown log level: "' + self.level + '".')
} else {
Base.levels.forEach(function (methodName, index) {
if (methodName === self.level) {
found = true
}
var prefix = self.prefixes[methodName] || ''
var format = self.format
// If this log is an Emitter, we can catch and emit errors.
if (self.emit) {
self[methodName] = found ? function () {
var message = self.join(arguments)
message = format.call(self, message, methodName, prefix)
try {
self.stream.write(message)
} catch (e) {
self.emit('error', e)
}
} : doNothing
// Otherwise, they'll just throw.
} else {
self[methodName] = found ? function () {
var message = self.join(arguments)
message = format.call(self, message, methodName, prefix)
self.stream.write(message)
} : doNothing
}
})
// Wrap the trace method with a stack tracer.
if (self.trace !== doNothing) {
var traceMethod = self.trace
self.trace = function () {
var e = new Error('')
Error.captureStackTrace(e, self.trace)
var l = arguments.length
arguments[l] = e.stack.split('\n').splice(2).join('\n')
arguments.length = ++l
traceMethod.apply(self, arguments)
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GAPPSF.OKAPI
{
public class SiteInfoNetherlands: SiteInfo
{
public const string STR_INFO = "opencaching.nl";
public SiteInfoNetherlands()
{
ID = "2";
Info = STR_INFO;
OKAPIBaseUrl = "http:
GeocodePrefix = "OB";
}
public override void LoadSettings()
{
Username = Core.ApplicationData.Instance.AccountInfos.GetAccountInfo(GeocodePrefix).AccountName ?? "";
UserID = Core.Settings.Default.<API key> ?? "";
Token = Core.Settings.Default.<API key> ?? "";
TokenSecret = Core.Settings.Default.<API key> ?? "";
base.LoadSettings();
}
public override void SaveSettings()
{
Core.ApplicationData.Instance.AccountInfos.GetAccountInfo(GeocodePrefix).AccountName = Username ?? "";
Core.Settings.Default.<API key> = UserID ?? "";
Core.Settings.Default.<API key> = Token ?? "";
Core.Settings.Default.<API key> = TokenSecret ?? "";
}
}
}
|
import Omni = require('../../lib/omni-sharp-server/omni');
import {Observable, CompositeDisposable} from "rx";
import {setupFeature, restoreBuffers, openEditor} from "../test-helpers";
describe('Run Tests', () => {
setupFeature(['features/run-tests']);
it('adds commands', () => {
var disposable = new CompositeDisposable();
runs(() => {
var commands: any = atom.commands;
expect(commands.registeredCommands['omnisharp-atom:run-all-tests']).toBeTruthy();
expect(commands.registeredCommands['omnisharp-atom:run-fixture-tests']).toBeTruthy();
expect(commands.registeredCommands['omnisharp-atom:run-single-test']).toBeTruthy();
expect(commands.registeredCommands['omnisharp-atom:run-last-test']).toBeTruthy();
disposable.dispose();
});
});
// TODO: Test functionality
});
|
*{
margin: 0px;
padding: 0px;
}
#introduce{
width: 1000px;
height: 680px;
background-color: #f4f4f4;
margin: auto;
}
h1{
font-size: 2em;
text-align: center;
}
li{
list-style: none;
font-size: 1em;
}
#pic1{
margin-left: 60px;
float: left;
width: 361px;
height: 237px;
}
#pic2{
margin-left: 300px;
float: left;
width: 169px;
height: 237px;
}
#pic-describe{
text-align: center;
font-size: 13px;
}
|
using System;
if (double.TryParse(aaa, out var bbb))
{
}
|
{{- define "main" -}}
<h1>{{ .Title | markdownify }}</h1>
<p>
<small class="text-secondary">
{{ $customDateFormat := "January 2, 2006" }}
{{ with .Site.Params.customDateFormat }}{{ $customDateFormat = . }}{{ end }}
{{ .PublishDate.Format $customDateFormat }}{{ if gt .Lastmod .PublishDate }}, updated {{ .Lastmod.Format $customDateFormat }}{{ end }}
</small>
{{ partial "tags" . }}
</p>
{{ .Content }}
{{- end -}}
|
using System;
using System.Collections.Generic;
using KellermanSoftware.CompareNetObjects;
using KellermanSoftware.CompareNetObjects.TypeComparers;
using ProtoBuf;
namespace Abc.Zebus.Testing.Comparison
{
internal static class <API key>
{
public static bool DeepCompare<T>(this T firstObj, T secondObj, params string[] elementsToIgnore)
{
var comparer = CreateComparer();
comparer.Config.MembersToIgnore.AddRange(elementsToIgnore);
return comparer.Compare(firstObj, secondObj).AreEqual;
}
public static CompareLogic CreateComparer()
{
return new CompareLogic
{
Config =
{
<API key> = false,
CompareStaticFields = false,
CustomComparers =
{
// TODO : Is this still used?
new EquatableComparer()
},
AttributesToIgnore = new List<Type> { typeof(<API key>) },
}
};
}
private class EquatableComparer : BaseTypeComparer
{
public EquatableComparer()
: base(RootComparerFactory.GetRootComparer())
{
}
public override bool IsTypeMatch(Type type1, Type type2)
{
if (type1 != type2)
return false;
return typeof(IEquatable<>).MakeGenericType(type1).IsAssignableFrom(type1);
}
public override void CompareType(CompareParms parms)
{
if (!Equals(parms.Object1, parms.Object2))
AddDifference(parms);
}
}
}
}
|
// Generated on 12/11/2014 19:01:22
using System;
using System.Collections.Generic;
using System.Linq;
using BlueSheep.Common.Protocol.Types;
using BlueSheep.Common.IO;
using BlueSheep.Engine.Types;
namespace BlueSheep.Common.Protocol.Messages
{
public class <API key> : Message
{
public new const uint ID =6317;
public override uint ProtocolID
{
get { return ID; }
}
public ushort number;
public <API key>()
{
}
public <API key>(ushort number)
{
this.number = number;
}
public override void Serialize(BigEndianWriter writer)
{
writer.WriteUShort(number);
}
public override void Deserialize(BigEndianReader reader)
{
number = reader.ReadUShort();
if (number < 0 || number > 65535)
throw new Exception("Forbidden value on number = " + number + ", it doesn't respect the following condition : number < 0 || number > 65535");
}
}
}
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Unittest extends CI_Controller {
function __construct() {
parent::__construct ();
$this->load->model('UnitTest_model');
$this->load->library('unit_test');
}
function index(){
echo "test";
}
function debate(){
$offset = $this->input->get("offset");
$limit = $this->input->get("limit");
$debate_test_list = $this->UnitTest_model->debate_list_test($offset, $limit);
for($i = 0 ; $i < count($debate_test_list); $i ++){
$this->unit->use_strict(TRUE);
$this->unit->run($debate_test_list[$i]->id, 'is_numeric', 'id_type');
$this->unit->run($debate_test_list[$i]->title, 'is_string', 'title_type');
$this->unit->run($debate_test_list[$i]->content, 'is_string', 'content_type');
$this->unit->run($debate_test_list[$i]->reg_id, 'is_numeric', 'reg_id_type');
$this->unit->run($debate_test_list[$i]->del_st, 'is_numeric', 'del_st_type');
}
echo $this->unit->report();
}
function debate_reply(){
$offset = $this->input->get("offset");
$limit = $this->input->get("limit");
$<API key> = $this->UnitTest_model-><API key>($offset, $limit);
for($i = 0 ; $i < count($<API key>); $i ++){
$this->unit->use_strict(TRUE);
$this->unit->run($<API key>[$i]->id, 'is_numeric', 'id_type');
$this->unit->run($<API key>[$i]->debate_id, 'is_numeric', 'debate_id_type');
$this->unit->run($<API key>[$i]->content, 'is_string', 'content_type');
$this->unit->run($<API key>[$i]->reg_id, 'is_numeric', 'reg_id_type');
$this->unit->run($<API key>[$i]->del_st, 'is_numeric', 'del_st_type');
}
echo $this->unit->report();
}
function debate_back(){
$offset = $this->input->get("offset");
$limit = $this->input->get("limit");
$<API key> = $this->UnitTest_model-><API key>($offset, $limit);
for($i = 0 ; $i < count($<API key>); $i ++){
$this->unit->use_strict(TRUE);
$this->unit->run($<API key>[$i]->id, 'is_numeric', 'id_type');
$this->unit->run($<API key>[$i]->debate_id, 'is_numeric', 'debate_id_type');
$this->unit->run($<API key>[$i]->seq, 'is_numeric', 'seq_type');
$this->unit->run($<API key>[$i]->title, 'is_string', 'title_type');
$this->unit->run($<API key>[$i]->content, 'is_string', 'content_type');
}
echo $this->unit->report();
}
function board(){
$offset = $this->input->get("offset");
$limit = $this->input->get("limit");
$board_test_list = $this->UnitTest_model->board_list_test($offset, $limit);
for($i = 0 ; $i < count($board_test_list); $i ++){
$this->unit->use_strict(TRUE);
$this->unit->run($board_test_list[$i]->id, 'is_numeric', 'id_type');
$this->unit->run($board_test_list[$i]->title, 'is_string', 'title_type');
$this->unit->run($board_test_list[$i]->content, 'is_string', 'content_type');
$this->unit->run($board_test_list[$i]->reg_id, 'is_numeric', 'reg_id_type');
$this->unit->run($board_test_list[$i]->del_st, 'is_numeric', 'del_st_type');
}
echo $this->unit->report();
}
function board_reply(){
$offset = $this->input->get("offset");
$limit = $this->input->get("limit");
$<API key> = $this->UnitTest_model-><API key>($offset, $limit);
for($i = 0 ; $i < count($<API key>); $i ++){
$this->unit->use_strict(TRUE);
$this->unit->run($<API key>[$i]->id, 'is_numeric', 'id_type');
$this->unit->run($<API key>[$i]->board_id, 'is_numeric', 'board_id_type');
$this->unit->run($<API key>[$i]->content, 'is_string', 'content_type');
$this->unit->run($<API key>[$i]->reg_id, 'is_numeric', 'reg_id_type');
$this->unit->run($<API key>[$i]->del_st, 'is_numeric', 'del_st_type');
}
echo $this->unit->report();
}
function law(){
$offset = $this->input->get("offset");
$limit = $this->input->get("limit");
$law_test_list = $this->UnitTest_model->law_list_test($offset, $limit);
for($i = 0 ; $i < count($law_test_list); $i ++){
$this->unit->use_strict(TRUE);
$this->unit->run($law_test_list[$i]->id, 'is_numeric', 'id_type');
$this->unit->run($law_test_list[$i]->d1, 'is_null', 'd1_type');
$this->unit->run($law_test_list[$i]->d2, 'is_null', 'd2_type');
$this->unit->run($law_test_list[$i]->d3, 'is_null', 'd3_type');
$this->unit->run($law_test_list[$i]->d4, 'is_null', 'd4_type');
$this->unit->run($law_test_list[$i]->d5, 'is_null', 'd5_type');
$this->unit->run($law_test_list[$i]->d6, 'is_null', 'd6_type');
$this->unit->run($law_test_list[$i]->d7, 'is_null', 'd7_type');
$this->unit->run($law_test_list[$i]->d8, 'is_null', 'd8_type');
$this->unit->run($law_test_list[$i]->reg_id, 'is_numeric', 'reg_id_type');
}
echo $this->unit->report();
}
function law_model(){
$offset = $this->input->get("offset");
$limit = $this->input->get("limit");
$law_model_test_list = $this->UnitTest_model->law_model_list_test($offset, $limit);
for($i = 0 ; $i < count($law_model_test_list); $i ++){
$this->unit->use_strict(TRUE);
$this->unit->run($law_model_test_list[$i]->id, 'is_numeric', 'id_type');
$this->unit->run($law_model_test_list[$i]->title, 'is_string', 'title_type');
$this->unit->run($law_model_test_list[$i]->content, 'is_string', 'content_type');
$this->unit->run($law_model_test_list[$i]->reg_id, 'is_numeric', 'reg_id_type');
$this->unit->run($law_model_test_list[$i]->del_st, 'is_numeric', 'del_st_type');
}
echo $this->unit->report();
}
function log(){
$offset = $this->input->get("offset");
$limit = $this->input->get("limit");
$log_test_list = $this->UnitTest_model->log_list_test($offset, $limit);
for($i = 0 ; $i < count($log_test_list); $i ++){
$this->unit->use_strict(TRUE);
$this->unit->run($log_test_list[$i]->id, 'is_numeric', 'id_type');
$this->unit->run($log_test_list[$i]->code, 'is_numeric', 'code_type');
$this->unit->run($log_test_list[$i]->content_id, 'is_numeric', 'content_id_type');
$this->unit->run($log_test_list[$i]->reg_id, 'is_numeric', 'reg_id_type');
}
echo $this->unit->report();
}
function user(){
$offset = $this->input->get("offset");
$limit = $this->input->get("limit");
$user_test_list = $this->UnitTest_model->user_list_test($offset, $limit);
for($i = 0 ; $i < count($user_test_list); $i ++){
$this->unit->use_strict(TRUE);
$this->unit->run($user_test_list[$i]->id, 'is_numeric', 'id_type');
$this->unit->run($user_test_list[$i]->email, 'is_string', 'email_type');
$this->unit->run($user_test_list[$i]->auth_code, 'is_string', 'auth_code_type');
}
echo $this->unit->report();
}
function user_info(){
$offset = $this->input->get("offset");
$limit = $this->input->get("limit");
$user_info_test_list = $this->UnitTest_model->user_info_list_test($offset, $limit);
for($i = 0 ; $i < count($user_info_test_list); $i ++){
$this->unit->use_strict(TRUE);
$this->unit->run($user_info_test_list[$i]->id, 'is_numeric', 'id_type');
$this->unit->run($user_info_test_list[$i]->user_id, 'is_numeric', 'user_id_type');
$this->unit->run($user_info_test_list[$i]->user_code, 'is_numeric', 'user_code_type');
$this->unit->run($user_info_test_list[$i]->acc_st, 'is_numeric', 'acc_st_type');
}
echo $this->unit->report();
}
}
|
#include <iostream>
using namespace std;
#include <omp.h>
#define SIZE 8
int main(void){
int x[SIZE];
int sum=0;
for(int i=0;i<SIZE;i++){
x[i]=i;
}
#pragma omp parallel for reduction (+:sum)
for(int i=0;i<SIZE;i++){
sum+=x[i];
}
cout<<sum<<std::endl;
return 0;
}
|
from .image import Image
from .product_category import ProductCategory
from .supplier import Supplier, PaymentMethod
from .product import Product
from .product import ProductImage
from .enum_values import EnumValues
from .related_values import RelatedValues
from .customer import Customer
from .expense import Expense
from .incoming import Incoming
from .shipping import Shipping, ShippingLine
from .receiving import Receiving, ReceivingLine
from .<API key> import <API key>, <API key>
from .purchase_order import PurchaseOrder, PurchaseOrderLine
from .sales_order import SalesOrder, SalesOrderLine
from .user import User
from .role import Role, roles_users
from .organization import Organization
from .<API key> import InventoryInOutLink
from .aspects import update_menemonic
from .product_inventory import ProductInventory
|
import type {ResponseType} from "./base.type";
function parseJSON(response: ResponseType): Object {
return response.json();
}
export {parseJSON};
|
// This code contains NVIDIA Confidential Information and is disclosed to you
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
#include <RendererTextureDesc.h>
using namespace SampleRenderer;
RendererTextureDesc::RendererTextureDesc(void)
{
format = RendererTexture::NUM_FORMATS;
filter = RendererTexture::FILTER_LINEAR;
addressingU = RendererTexture::ADDRESSING_WRAP;
addressingV = RendererTexture::ADDRESSING_WRAP;
addressingW = RendererTexture::ADDRESSING_WRAP;
width = 0;
height = 0;
depth = 1;
numLevels = 0;
renderTarget = false;
data = NULL;
}
bool RendererTextureDesc::isValid(void) const
{
bool ok = true;
if(format >= RendererTexture2D::NUM_FORMATS) ok = false;
if(filter >= RendererTexture2D::NUM_FILTERS) ok = false;
if(addressingU >= RendererTexture2D::NUM_ADDRESSING) ok = false;
if(addressingV >= RendererTexture2D::NUM_ADDRESSING) ok = false;
if(width <= 0 || height <= 0 || depth <= 0) ok = false; // TODO: check for power of two.
if(numLevels <= 0) ok = false;
if(renderTarget)
{
if(depth > 1) ok = false;
if(format == RendererTexture2D::FORMAT_DXT1) ok = false;
if(format == RendererTexture2D::FORMAT_DXT3) ok = false;
if(format == RendererTexture2D::FORMAT_DXT5) ok = false;
}
return ok;
}
|
var request = require('request'),
mongoose = require('mongoose'),
util = require('util'),
url = require('url'),
helpers = require('./helpers'),
sync = require('./sync')
// turn off request pooling
request.defaults({ agent:false })
// cache elasticsearch url options for elmongo.search() to use
var elasticUrlOptions = null
/**
* Attach mongoose plugin for elasticsearch indexing
*
* @param {Object} schema mongoose schema
* @param {Object} options elasticsearch options object. Keys: host, port, index, type
*/
module.exports = elmongo = function (schema, options) {
// attach methods to schema
schema.methods.index = index
schema.methods.unindex = unindex
schema.statics.sync = function (cb) {
options = helpers.mergeModelOptions(options, this)
return sync.call(this, schema, options, cb)
}
schema.statics.search = function (searchOpts, cb) {
options = helpers.mergeModelOptions(options, this)
var searchUri = helpers.makeTypeUri(options) + '/_search?search_type=<API key>&preference=_primary_first'
return helpers.<API key>(searchUri, searchOpts, cb)
}
// attach mongoose middleware hooks
schema.post('save', function () {
options = helpers.mergeModelOptions(options, this)
this.index(options)
})
schema.post('remove', function () {
options = helpers.mergeModelOptions(options, this)
this.unindex(options)
})
}
/**
* Search across multiple collections. Same usage as model search, but with an extra key on `searchOpts` - `collections`
* @param {Object} searchOpts
* @param {Function} cb
*/
elmongo.search = function (searchOpts, cb) {
// merge elasticsearch url config options
elasticUrlOptions = helpers.mergeOptions(elasticUrlOptions)
// determine collections to search on
var collections = searchOpts.collections;
if (elasticUrlOptions.prefix) {
// prefix was specified - namespace the index names to use the prefix for each collection's index
if (searchOpts.collections && searchOpts.collections.length) {
// collections were specified - prepend the prefix on each collection name
collections = collections.map(function (collection) {
return elasticUrlOptions.prefix + '-' + collection
})
} else {
// no collections specified, but prefix specified - use wildcard index with prefix
collections = [ elasticUrlOptions.prefix + '*' ]
}
} else {
// no prefix used
// if collections specified, just use their names without the prefix
if (!collections) {
// no collections were specified so use _all (searches all collections), without prefix
searchOpts.collections = [ '_all' ]
}
}
var searchUri = helpers.makeDomainUri(elasticUrlOptions) + '/' + collections.join(',') + '/_search?search_type=<API key>&preference=_primary_first'
return helpers.<API key>(searchUri, searchOpts, cb)
}
/**
* Configure the Elasticsearch url options for `elmongo.search()`.
*
* @param {Object} options - keys: host, port, prefix (optional)
*/
elmongo.search.config = function (options) {
// only overwrite `options` values that are being specified in this call to `config`
if (elasticUrlOptions) {
Object
.keys(elasticUrlOptions)
.forEach(function (key) {
elasticUrlOptions[key] = options[key] || elasticUrlOptions[key]
})
}
// normalize the `options` object
elasticUrlOptions = helpers.mergeOptions(options)
}
/**
* Index a document in elasticsearch (create if not existing)
*
* @param {Object} options elasticsearch options object. Keys: host, port, index, type
*/
function index (options) {
var self = this
// strip mongoose-added functions, depopulate any populated fields, and serialize the doc
var esearchDoc = helpers.serializeModel(this)
var indexUri = helpers.makeDocumentUri(options, self)
var reqOpts = {
method: 'PUT',
url: indexUri,
body: JSON.stringify(esearchDoc)
}
// console.log('index:', indexUri)
helpers.backOffRequest(reqOpts, function (err, res, body) {
if (err) {
var error = new Error('Elasticsearch document indexing error: '+util.inspect(err, true, 10, true))
error.details = err
self.emit('error', error)
return
}
self.emit('elmongo-indexed', body)
})
}
/**
* Remove a document from elasticsearch
*
* @param {Object} options elasticsearch options object. Keys: host, port, index, type
*/
function unindex (options) {
var self = this
var unindexUri = helpers.makeDocumentUri(options, self)
// console.log('unindex:', unindexUri)
var reqOpts = {
method: 'DELETE',
url: unindexUri
}
helpers.backOffRequest(reqOpts, function (err, res, body) {
if (err) {
var error = new Error('Elasticsearch document index deletion error: '+util.inspect(err, true, 10, true))
error.details = err
self.emit('error', error)
return
}
self.emit('elmongo-unindexed', body)
})
}
|
using System;
using System.Collections.Generic;
using System.Text;
using FlatRedBall;
using FlatRedBall.Gui;
using FlatRedBall.AI.Pathfinding;
#if FRB_MDX
using Color = System.Drawing.Color;
#else
using Color = Microsoft.Xna.Framework.Graphics.Color;
#endif
using CameraPropertyGrid = EditorObjects.Gui.CameraPropertyGrid;
using EditorObjects.Gui;
using EditorObjects;
namespace AIEditor.Gui
{
public static class GuiData
{
#region Fields
static int <API key> = 0;
static Menu mMenuStrip;
static CameraPropertyGrid mCameraPropertyGrid;
static <API key> <API key>;
static ToolsWindow mToolsWindow;
static CommandDisplay mCommandDisplay;
static ScenePropertyGrid mScenePropertyGrid;
static <API key> <API key>;
public static <API key> <API key>;
#endregion
#region Properties
public static CameraPropertyGrid CameraPropertyGrid
{
get { return mCameraPropertyGrid; }
}
public static CommandDisplay CommandDisplay
{
get { return mCommandDisplay; }
}
public static <API key> <API key>
{
get { return <API key>; }
}
public static <API key> <API key>
{
get { return <API key>; }
set { <API key> = value; }
}
public static ScenePropertyGrid ScenePropertyGrid
{
get { return mScenePropertyGrid; }
}
public static <API key> <API key>
{
get { return <API key>; }
}
public static ToolsWindow ToolsWindow
{
get { return mToolsWindow; }
}
#endregion
#region Events
private static void <API key>(Window callingWindow)
{
((PropertyGrid<Color>)callingWindow).ExcludeAllMembers();
((PropertyGrid<Color>)callingWindow).IncludeMember("A");
((PropertyGrid<Color>)callingWindow).IncludeMember("R");
((PropertyGrid<Color>)callingWindow).IncludeMember("G");
((PropertyGrid<Color>)callingWindow).IncludeMember("B");
callingWindow.Y = 40;
}
private static void <API key>(Window callingWindow)
{
PropertyGrid<PositionedNode> asPropertyGrid = callingWindow as PropertyGrid<PositionedNode>;
asPropertyGrid.ExcludeMember("CostToGetHere");
asPropertyGrid.ExcludeMember("Links");
asPropertyGrid.ExcludeMember("X");
asPropertyGrid.ExcludeMember("Y");
asPropertyGrid.ExcludeMember("Z");
asPropertyGrid.Name = "Positioned Node";
}
#endregion
#region Methods
#region Public Methods
public static void Initialize()
{
mMenuStrip = new Menu();
mToolsWindow = new ToolsWindow();
CreatePropertyGrids();
mCommandDisplay = new CommandDisplay();
<API key>();
}
public static void Update()
{
if (EditorData.Scene != mScenePropertyGrid.SelectedObject)
{
mScenePropertyGrid.SelectedObject = EditorData.Scene;
}
mScenePropertyGrid.<API key>();
<API key>.Update();
mCameraPropertyGrid.<API key>();
// This can be slow. We can speed it up by only doing it every X frames
const int updateEveryXFrames = 30;
<API key>++;
if (<API key> >= updateEveryXFrames)
{
<API key>.<API key>();
<API key> = 0;
}
#region Update the ShapeCollection PropertyGrid
if (<API key>.Visible)
{
if (<API key>.SelectedObject != EditorData.ShapeCollection)
{
<API key>.SelectedObject = EditorData.ShapeCollection;
}
<API key>.<API key>();
}
#endregion
}
#endregion
#region Private Methods
private static void <API key>()
{
}
private static void CreatePropertyGrids()
{
#region CamerPropertyGrid
mCameraPropertyGrid = new CameraPropertyGrid(GuiManager.Cursor);
GuiManager.AddWindow(mCameraPropertyGrid);
mCameraPropertyGrid.SelectedObject = SpriteManager.Camera;
mCameraPropertyGrid.X = mCameraPropertyGrid.ScaleX;
mCameraPropertyGrid.Y = 40;
mCameraPropertyGrid.HasCloseButton = true;
mCameraPropertyGrid.UndoInstructions =
UndoManager.Instructions;
#endregion
#region NodeNetwork PropertyGrid
<API key> = new <API key>();
<API key>.SelectedObject = EditorData.NodeNetwork;
<API key>.X = <API key>.ScaleX;
<API key>.Y = 61;
<API key>.HasCloseButton = true;
<API key>.UndoInstructions =
UndoManager.Instructions;
#endregion
#region ScenePropertyGrid
mScenePropertyGrid = new ScenePropertyGrid(GuiManager.Cursor);
GuiManager.AddWindow(mScenePropertyGrid);
mScenePropertyGrid.X = mScenePropertyGrid.ScaleX;
mScenePropertyGrid.Y = 75.7f;
mScenePropertyGrid.<API key> = true;
mScenePropertyGrid.HasCloseButton = true;
mScenePropertyGrid.Visible = false;
mScenePropertyGrid.UndoInstructions = UndoManager.Instructions;
#endregion
#region <API key>
<API key> = new <API key>(GuiManager.Cursor);
GuiManager.AddWindow(<API key>);
<API key>.<API key> = true;
<API key>.<API key> = true;
<API key>.<API key> = true;
<API key>.<API key> = true;
<API key>.<API key> = true;
<API key>.HasCloseButton = true;
<API key>.Visible = false;
<API key>.UndoInstructions = UndoManager.Instructions;
#endregion
PropertyGrid.SetNewWindowEvent<FlatRedBall.AI.Pathfinding.PositionedNode>(<API key>);
PropertyGrid.SetNewWindowEvent<Color>(<API key>);
#region <API key>
<API key> = new <API key>();
<API key>.Visible = false;
#endregion
}
#endregion
#endregion
}
}
|
// flow-typed signature: <API key>
declare module 'http-errors' {
declare class SpecialHttpError extends HttpError {
constructor(): SpecialHttpError;
}
declare class HttpError extends Error {
expose: bool;
message: string;
status: number;
statusCode: number;
}
declare module.exports: {
(status?: number, message?: string, props?: Object): HttpError;
HttpError: typeof HttpError;
BadRequest: typeof SpecialHttpError;
Unauthorized: typeof SpecialHttpError;
PaymentRequired: typeof SpecialHttpError;
Forbidden: typeof SpecialHttpError;
NotFound: typeof SpecialHttpError;
MethodNotAllowed: typeof SpecialHttpError;
NotAcceptable: typeof SpecialHttpError;
Proxy<API key>: typeof SpecialHttpError;
RequestTimeout: typeof SpecialHttpError;
Conflict: typeof SpecialHttpError;
Gone: typeof SpecialHttpError;
LengthRequired: typeof SpecialHttpError;
PreconditionFailed: typeof SpecialHttpError;
PayloadTooLarge: typeof SpecialHttpError;
URITooLong: typeof SpecialHttpError;
<API key>: typeof SpecialHttpError;
<API key>: typeof SpecialHttpError;
ExpectationFailed: typeof SpecialHttpError;
ImATeapot: typeof SpecialHttpError;
MisdirectedRequest: typeof SpecialHttpError;
UnprocessableEntity: typeof SpecialHttpError;
Locked: typeof SpecialHttpError;
FailedDependency: typeof SpecialHttpError;
UnorderedCollection: typeof SpecialHttpError;
UpgradeRequired: typeof SpecialHttpError;
<API key>: typeof SpecialHttpError;
TooManyRequests: typeof SpecialHttpError;
<API key>: typeof SpecialHttpError;
<API key>: typeof SpecialHttpError;
InternalServerError: typeof SpecialHttpError;
NotImplemented: typeof SpecialHttpError;
BadGateway: typeof SpecialHttpError;
ServiceUnavailable: typeof SpecialHttpError;
GatewayTimeout: typeof SpecialHttpError;
<API key>: typeof SpecialHttpError;
<API key>: typeof SpecialHttpError;
InsufficientStorage: typeof SpecialHttpError;
LoopDetected: typeof SpecialHttpError;
<API key>: typeof SpecialHttpError;
NotExtended: typeof SpecialHttpError;
Network<API key>: typeof SpecialHttpError;
}
}
|
.heading-font {
font-family: 'Catamaran', 'Helvetica', 'Arial', 'sans-serif';
font-weight: 200;
letter-spacing: 1px;
}
.body-font {
font-family: 'Muli', 'Helvetica', 'Arial', 'sans-serif';
}
.alt-font {
font-family: 'Lato', 'Helvetica', 'Arial', 'sans-serif';
text-transform: uppercase;
letter-spacing: 2px;
}
html,
body {
height: 100%;
width: 100%;
}
body {
font-family: 'Muli', 'Helvetica', 'Arial', 'sans-serif';
}
a {
-webkit-transition: all 0.35s;
-moz-transition: all 0.35s;
transition: all 0.35s;
color: #fdcc52;
}
a:hover,
a:focus {
color: #fcbd20;
}
hr {
max-width: 100px;
margin: 25px auto 0;
border-width: 1px;
border-color: rgba(34, 34, 34, 0.1);
}
hr.light {
border-color: white;
}
h1,
h2,
h3,
h4,
h5,
h6 {
font-family: 'Catamaran', 'Helvetica', 'Arial', 'sans-serif';
font-weight: 200;
letter-spacing: 1px;
}
p {
font-size: 18px;
line-height: 1.5;
margin-bottom: 20px;
}
.navbar-default {
background-color: white;
border-color: rgba(34, 34, 34, 0.05);
-webkit-transition: all 0.35s;
-moz-transition: all 0.35s;
transition: all 0.35s;
font-family: 'Catamaran', 'Helvetica', 'Arial', 'sans-serif';
font-weight: 200;
letter-spacing: 1px;
}
.navbar-default .navbar-header .navbar-brand {
font-family: 'Catamaran', 'Helvetica', 'Arial', 'sans-serif';
font-weight: 200;
letter-spacing: 1px;
color: #fdcc52;
}
.navbar-default .navbar-header .navbar-brand:hover,
.navbar-default .navbar-header .navbar-brand:focus {
color: #fcbd20;
}
.navbar-default .navbar-header .navbar-toggle {
font-size: 12px;
color: #222222;
padding: 8px 10px;
}
.navbar-default .nav > li > a {
font-family: 'Lato', 'Helvetica', 'Arial', 'sans-serif';
text-transform: uppercase;
letter-spacing: 2px;
font-size: 11px;
}
.navbar-default .nav > li > a,
.navbar-default .nav > li > a:focus {
color: #222222;
}
.navbar-default .nav > li > a:hover,
.navbar-default .nav > li > a:focus:hover {
color: #fdcc52;
}
.navbar-default .nav > li.active > a,
.navbar-default .nav > li.active > a:focus {
color: #fdcc52 !important;
background-color: transparent;
}
.navbar-default .nav > li.active > a:hover,
.navbar-default .nav > li.active > a:focus:hover {
background-color: transparent;
}
@media (min-width: 768px) {
.navbar-default {
background-color: transparent;
border-color: transparent;
}
.navbar-default .navbar-header .navbar-brand {
color: rgba(255, 255, 255, 0.7);
}
.navbar-default .navbar-header .navbar-brand:hover,
.navbar-default .navbar-header .navbar-brand:focus {
color: white;
}
.navbar-default .nav > li > a,
.navbar-default .nav > li > a:focus {
color: rgba(255, 255, 255, 0.7);
}
.navbar-default .nav > li > a:hover,
.navbar-default .nav > li > a:focus:hover {
color: white;
}
.navbar-default.affix {
background-color: white;
border-color: rgba(34, 34, 34, 0.1);
}
.navbar-default.affix .navbar-header .navbar-brand {
color: #222222;
}
.navbar-default.affix .navbar-header .navbar-brand:hover,
.navbar-default.affix .navbar-header .navbar-brand:focus {
color: #fdcc52;
}
.navbar-default.affix .nav > li > a,
.navbar-default.affix .nav > li > a:focus {
color: #222222;
}
.navbar-default.affix .nav > li > a:hover,
.navbar-default.affix .nav > li > a:focus:hover {
color: #fdcc52;
}
}
header {
position: relative;
width: 100%;
min-height: auto;
overflow-y: hidden;
background: url("../img/bg-pattern.png"), #7b4397;
/* fallback for old browsers */
background: url("../img/bg-pattern.png"), -<API key>(to left, #7b4397, #dc2430);
/* Chrome 10-25, Safari 5.1-6 */
background: url("../img/bg-pattern.png"), linear-gradient(to left, #7b4397, #dc2430);
/* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
color: white;
}
header .header-content {
text-align: center;
padding: 150px 0 50px;
position: relative;
}
header .header-content .<API key> {
position: relative;
max-width: 500px;
margin: 0 auto;
}
header .header-content .<API key> h1 {
margin-top: 0;
margin-bottom: 30px;
font-size: 30px;
}
header .header-content .<API key> .list-badges {
margin-bottom: 25px;
}
header .header-content .<API key> .list-badges img {
height: 50px;
margin-bottom: 25px;
}
header .device-container {
max-width: 300px;
margin: 0 auto 100px;
}
header .device-container .screen img {
border-radius: 3px;
}
@media (min-width: 768px) {
header {
min-height: 100%;
}
header .header-content {
text-align: left;
padding: 0;
height: 100vh;
}
header .header-content .<API key> {
max-width: none;
margin: 0;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
header .header-content .<API key> h1 {
font-size: 35px;
}
header .device-container {
max-width: none;
max-height: calc(0vh);
margin: 100px auto 0;
}
}
@media (min-width: 992px) {
header .header-content .<API key> h1 {
font-size: 50px;
}
}
section {
padding: 100px 0;
}
section h2 {
font-size: 50px;
}
section.download {
padding: 150px 0;
position: relative;
}
section.download h2 {
margin-top: 0;
font-size: 50px;
}
section.download .badges .badge-link {
display: block;
margin-bottom: 25px;
}
section.download .badges .badge-link:last-child {
margin-bottom: 0;
}
section.download .badges .badge-link img {
height: 60px;
}
@media (min-width: 768px) {
section.download .badges .badge-link {
display: inline-block;
margin-bottom: 0;
}
}
@media (min-width: 768px) {
section.download h2 {
font-size: 70px;
}
}
section.projects .section-heading {
margin-bottom: 100px;
}
section.projects .section-heading h2 {
margin-top: 0;
}
section.projects .section-heading p {
margin-bottom: 0;
}
section.projects .device-container,
section.projects .feature-item {
max-width: 300px;
margin: 0 auto;
}
section.projects .device-container {
margin-bottom: 100px;
}
@media (min-width: 992px) {
section.projects .device-container {
margin-bottom: 0;
}
}
section.projects .feature-item {
text-align: center;
margin-bottom: 100px;
}
section.projects .feature-item h3 {
font-size: 30px;
}
section.projects .feature-item i {
font-size: 80px;
background: -<API key>(to left, #7b4397, #dc2430);
background: linear-gradient(to left, #7b4397, #dc2430);
-<API key>: text;
-<API key>: transparent;
}
@media (min-width: 992px) {
section.projects .device-container,
section.projects .feature-item {
max-width: none;
}
}
section.cta {
position: relative;
-<API key>: cover;
-moz-background-size: cover;
background-size: cover;
-o-background-size: cover;
background-position: center;
background-image: url('../img/bg-cta.jpg');
padding: 250px 0;
}
section.cta .cta-content {
position: relative;
z-index: 1;
}
section.cta .cta-content h2 {
margin-top: 0;
margin-bottom: 25px;
color: white;
max-width: 450px;
font-size: 50px;
}
@media (min-width: 768px) {
section.cta .cta-content h2 {
font-size: 80px;
}
}
section.cta .overlay {
height: 100%;
width: 100%;
background-color: rgba(0, 0, 0, 0.5);
position: absolute;
top: 0;
left: 0;
}
section.contact {
text-align: center;
}
section.contact h2 {
margin-top: 0;
margin-bottom: 25px;
}
section.contact h2 i {
color: #dd4b39;
}
section.contact ul.list-social {
margin-bottom: 0;
}
section.contact ul.list-social li a {
display: block;
height: 80px;
width: 80px;
line-height: 80px;
font-size: 40px;
border-radius: 100%;
color: white;
}
section.contact ul.list-social li.social-twitter a {
background-color: #1da1f2;
}
section.contact ul.list-social li.social-twitter a:hover {
background-color: #0d95e8;
}
section.contact ul.list-social li.social-facebook a {
background-color: #3b5998;
}
section.contact ul.list-social li.social-facebook a:hover {
background-color: #344e86;
}
section.contact ul.list-social li.social-google-plus a {
background-color: #dd4b39;
}
section.contact ul.list-social li.social-google-plus a:hover {
background-color: #d73925;
}
footer {
background-color: #222222;
padding: 25px 0;
color: rgba(255, 255, 255, 0.3);
text-align: center;
}
footer p {
font-size: 12px;
margin: 0;
}
footer ul {
margin-bottom: 0;
}
footer ul li a {
font-size: 12px;
color: rgba(255, 255, 255, 0.3);
}
footer ul li a:hover,
footer ul li a:focus,
footer ul li a:active,
footer ul li a.active {
text-decoration: none;
}
.bg-primary {
background: #fdcc52;
background: -<API key>(#fdcc52, #fdc539);
background: linear-gradient(#fdcc52, #fdc539);
}
.text-primary {
color: #fdcc52;
}
.no-gutter > [class*='col-'] {
padding-right: 0;
padding-left: 0;
}
.btn-outline {
color: white;
border-color: white;
border: 1px solid;
}
.btn-outline:hover,
.btn-outline:focus,
.btn-outline:active,
.btn-outline.active {
color: white;
background-color: #fdcc52;
border-color: #fdcc52;
}
.btn {
font-family: 'Lato', 'Helvetica', 'Arial', 'sans-serif';
text-transform: uppercase;
letter-spacing: 2px;
border-radius: 300px;
}
.btn-xl {
padding: 15px 45px;
font-size: 11px;
}
::-moz-selection {
color: white;
text-shadow: none;
background: #222222;
}
::selection {
color: white;
text-shadow: none;
background: #222222;
}
img::selection {
color: white;
background: transparent;
}
img::-moz-selection {
color: white;
background: transparent;
}
body {
<API key>: #222222;
}
|
using System;
namespace Microsoft.eShopOnContainers.Services.Catalog.API.Model
{
public class CatalogItem
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string PictureUri { get; set; }
public int CatalogTypeId { get; set; }
public CatalogType CatalogType { get; set; }
public int CatalogBrandId { get; set; }
public CatalogBrand CatalogBrand { get; set; }
public CatalogItem() { }
}
}
|
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http:
<html xmlns="http:
<head>
<title>Class: Gem::Package::TarReader::UnexpectedEOF</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<link rel="stylesheet" href="../../../.././rdoc-style.css" type="text/css" media="screen" />
<script type="text/javascript">
// <![CDATA[
function popupCode( url ) {
window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400")
}
function toggleCode( id ) {
if ( document.getElementById )
elem = document.getElementById( id );
else if ( document.all )
elem = eval( "document.all." + id );
else
return false;
elemStyle = elem.style;
if ( elemStyle.display != "block" ) {
elemStyle.display = "block"
} else {
elemStyle.display = "none"
}
return true;
}
// Make codeblocks hidden by default
document.writeln( "<style type=\"text/css\">div.method-source-code { display: none }</style>" )
</script>
</head>
<body>
<div id="classHeader">
<table class="header-table">
<tr class="top-aligned-row">
<td><strong>Class</strong></td>
<td class="<API key>">Gem::Package::TarReader::UnexpectedEOF</td>
</tr>
<tr class="top-aligned-row">
<td><strong>In:</strong></td>
<td>
<a href="../../../../files/lib/rubygems/package/tar_reader_rb.html">
lib/rubygems/package/tar_reader.rb
</a>
<br />
</td>
</tr>
<tr class="top-aligned-row">
<td><strong>Parent:</strong></td>
<td>
StandardError
</td>
</tr>
</table>
</div>
<!-- banner header -->
<div id="bodyContent">
<div id="contextContent">
<div id="description">
<p>
Raised if the tar IO is not seekable
</p>
</div>
</div>
</div>
<!-- if includes -->
<div id="section">
<!-- if method_list -->
</div>
<div id="validator-badges">
<p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
</div>
</body>
</html>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JSDoc: Source: flags.js</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>
<body>
<div id="main">
<h1 class="page-title">Source: flags.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>/**
* just.js extension package
*
* @author danikas2k2 (danikas2k2@gmail.com)
*/
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
require("./global");
module.exports = (function () {
var Flags = (function () {
/**
*
* @param flag {number|Flags}
* @return {Flags}
* @constructor
*/
function Flags(flag) {
_classCallCheck(this, Flags);
this.reset(flag);
}
_createClass(Flags, [{
key: "valueOf",
/**
*
* @return {number}
*/
value: function valueOf() {
return this.flags;
}
}, {
key: "toString",
/**
*
* @return {string}
*/
value: function toString() {
return this.flags.toString();
}
}, {
key: "is",
/**
*
* @param flag {number|Flags}
* @return {boolean}
*/
value: function is(flag) {
return (this.flags & flag) == flag;
}
}, {
key: "set",
/**
*
* @param flag {number|Flags}
* @return {Flags}
*/
value: function set(flag) {
this.flags = this.flags | flag;
return this;
}
}, {
key: "unset",
/**
*
* @param flag {number|Flags}
* @return {Flags}
*/
value: function unset(flag) {
this.flags = this.flags & ~flag;
return this;
}
}, {
key: "reset",
/**
*
* @param flag {number|Flags}
* @return {Flags}
*/
value: function reset(flag) {
this.flags = isNaN(flag) ? 0 : +flag;
return this;
}
}]);
return Flags;
})();
return globalScope().Flags = Flags;
})();
</code></pre>
</article>
</section>
</div>
<nav>
<h2><a href="index.html">Home</a></h2><h3>Global</h3><ul><li><a href="global.html#value">value</a></li></ul>
</nav>
<br class="clear">
<footer>
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.3.2</a> on Thu Jul 09 2015 00:27:28 GMT+0300 (EEST)
</footer>
<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>
|
require 'cgi'
require 'nkf'
class Mechanize::Util
# default mime type data for Page::Image#mime_type.
# You can use another Apache-compatible mimetab.
# mimetab = WEBrick::HTTPUtils.load_mime_types('/etc/mime.types')
# Mechanize::Util::DefaultMimeTypes.replace(mimetab)
DefaultMimeTypes = WEBrick::HTTPUtils::DefaultMimeTypes
class << self
# Builds a query string from a given enumerable object
# +parameters+. This method uses Mechanize::Util.each_parameter
# as preprocessor, which see.
def build_query_string(parameters, enc = nil)
each_parameter(parameters).inject(nil) { |s, (k, v)|
# WEBrick::HTTP.escape* has some problems about m17n on ruby-1.9.*.
(s.nil? ? '' : s << '&') << [CGI.escape(k.to_s), CGI.escape(v.to_s)].join('=')
} || ''
end
# Parses an enumerable object +parameters+ and iterates over the
# key-value pairs it contains.
# +parameters+ may be a hash, or any enumerable object which
# iterates over [key, value] pairs, typically an array of arrays.
# If a key is paired with an array-like object, the pair is
# expanded into multiple occurrences of the key, one for each
# element of the array. e.g. { a: [1, 2] } => [:a, 1], [:a, 2]
# If a key is paired with a hash-like object, the pair is expanded
# into hash-like multiple pairs, one for each pair of the hash.
# e.g. { a: { x: 1, y: 2 } } => ['a[x]', 1], ['a[y]', 2]
# An array-like value is allowed to be specified as hash value.
# e.g. { a: { q: [1, 2] } } => ['a[q]', 1], ['a[q]', 2]
# For a non-array-like, non-hash-like value, the key-value pair is
# yielded as is.
def each_parameter(parameters, &block)
return to_enum(__method__, parameters) if block.nil?
parameters.each { |key, value|
each_parameter_1(key, value, &block)
}
end
private
def each_parameter_1(key, value, &block)
return if key.nil?
case
when s = String.try_convert(value)
yield [key, s]
when a = Array.try_convert(value)
a.each { |avalue|
yield [key, avalue]
}
when h = Hash.try_convert(value)
h.each { |hkey, hvalue|
each_parameter_1('%s[%s]' % [key, hkey], hvalue, &block)
}
else
yield [key, value]
end
end
end
# Converts string +s+ from +code+ to UTF-8.
def self.from_native_charset(s, code, <API key> = false, log = nil)
return s unless s && code
return s unless Mechanize.html_parser == Nokogiri::HTML
begin
s.encode(code)
rescue EncodingError => ex
log.debug("from_native_charset: #{ex.class}: form encoding: #{code.inspect} string: #{s}") if log
if <API key>
s
else
raise
end
end
end
def self.html_unescape(s)
return s unless s
s.gsub(/&(\w+|#[0-9]+);/) { |match|
number = case match
when /&(\w+);/
Mechanize.html_parser::NamedCharacters[$1]
when /&
$1.to_i
end
number ? ([number].pack('U') rescue match) : match
}
end
case NKF::BINARY
when Encoding
def self.guess_encoding(src)
# NKF.guess of JRuby may return nil
NKF.guess(src) || Encoding::US_ASCII
end
else
# Old NKF from 1.8, still bundled with Rubinius
NKF_ENCODING_MAP = {
NKF::UNKNOWN => Encoding::US_ASCII,
NKF::BINARY => Encoding::ASCII_8BIT,
NKF::ASCII => Encoding::US_ASCII,
NKF::JIS => Encoding::ISO_2022_JP,
NKF::EUC => Encoding::EUC_JP,
NKF::SJIS => Encoding::Shift_JIS,
NKF::UTF8 => Encoding::UTF_8,
NKF::UTF16 => Encoding::UTF_16BE,
NKF::UTF32 => Encoding::UTF_32BE,
}
def self.guess_encoding(src)
NKF_ENCODING_MAP[NKF.guess(src)]
end
end
def self.detect_charset(src)
if src
guess_encoding(src).name.upcase
else
Encoding::ISO8859_1.name
end
end
def self.uri_escape str, unsafe = nil
@parser ||= begin
URI::Parser.new
rescue NameError
URI
end
if URI == @parser then
unsafe ||= URI::UNSAFE
else
unsafe ||= @parser.regexp[:UNSAFE]
end
@parser.escape str, unsafe
end
def self.uri_unescape str
@parser ||= begin
URI::Parser.new
rescue NameError
URI
end
@parser.unescape str
end
end
|
require 'english/class'
class English
# = Noun Number Inflections
# This module provides english singular <-> plural noun inflections.
module Inflect
@singular_of = {}
@plural_of = {}
@singular_rules = []
@plural_rules = []
# This class provides the DSL for creating inflections, you can add additional rules.
# Examples:
# word "ox", "oxen"
# word "octopus", "octopi"
# word "man", "men"
# rule "lf", "lves"
# word "equipment"
# Rules are evaluated by size, so rules you add to override specific cases should be longer than the rule
# it overrides. For instance, if you want "pta" to pluralize to "ptas", even though a general purpose rule
# for "ta" => "tum" already exists, simply add a new rule for "pta" => "ptas", and it will automatically win
# since it is longer than the old rule.
# Also, single-word exceptions win over general words ("ox" pluralizes to "oxen", because it's a single word
# exception, even though "fox" pluralizes to "foxes")
class << self
# Define a general two-way exception.
# This also defines a general rule, so foo_child will correctly become
# foo_children.
# Whole words also work if they are capitalized (Goose => Geese).
def word(singular, plural=nil)
plural = singular unless plural
singular_word(singular, plural)
plural_word(singular, plural)
rule(singular, plural)
end
# Define a singularization exception.
def singular_word(singular, plural)
@singular_of[plural] = singular
@singular_of[plural.capitalize] = singular.capitalize
end
# Define a pluralization exception.
def plural_word(singular, plural)
@plural_of[singular] = plural
@plural_of[singular.capitalize] = plural.capitalize
end
# Define a general rule.
def rule(singular, plural)
singular_rule(singular, plural)
plural_rule(singular, plural)
end
# Define a singularization rule.
def singular_rule(singular, plural)
@singular_rules << [singular, plural]
end
# Define a plurualization rule.
def plural_rule(singular, plural)
@plural_rules << [singular, plural]
end
# Read prepared singularization rules.
def <API key>
if defined?(@<API key>) && @<API key>
return [@<API key>, @<API key>]
end
# No sorting needed: Regexen match on longest string
@<API key> = Regexp.new("(" + @singular_rules.map {|s,p| p}.join("|") + ")$", "i")
@<API key> = Hash[*@singular_rules.flatten].invert
[@<API key>, @<API key>]
end
# Read prepared singularization rules.
#def <API key>
# return @<API key> if @<API key>
# sorted = @singular_rules.sort_by{ |s, p| "#{p}".size }.reverse
# @<API key> = sorted.collect do |s, p|
# [ /#{p}$/, "#{s}" ]
# end
#end
# Read prepared pluralization rules.
def pluralization_rules
if defined?(@pluralization_regex) && @pluralization_regex
return [@pluralization_regex, @pluralization_hash]
end
@pluralization_regex = Regexp.new("(" + @plural_rules.map {|s,p| s}.join("|") + ")$", "i")
@pluralization_hash = Hash[*@plural_rules.flatten]
[@pluralization_regex, @pluralization_hash]
end
# Read prepared pluralization rules.
#def pluralization_rules
# return @pluralization_rules if @pluralization_rules
# sorted = @plural_rules.sort_by{ |s, p| "#{s}".size }.reverse
# @pluralization_rules = sorted.collect do |s, p|
# [ /#{s}$/, "#{p}" ]
# end
#end
def singular_of ; @singular_of ; end
def plural_of ; @plural_of ; end
# Convert an English word from plurel to singular.
# "boys".singular #=> boy
# "tomatoes".singular #=> tomato
def singular(word)
return "" if word == ""
if result = singular_of[word]
return result.dup
end
result = word.dup
regex, hash = <API key>
result.sub!(regex) {|m| hash[m]}
singular_of[word] = result
return result
#<API key>.each do |(match, replacement)|
# break if result.gsub!(match, replacement)
#end
#return result
end
# Alias for #singular (a Railism).
alias_method(:singularize, :singular)
# Convert an English word from singular to plurel.
# "boy".plural #=> boys
# "tomato".plural #=> tomatoes
def plural(word)
return "" if word == ""
if result = plural_of[word]
return result.dup
end
#return self.dup if /s$/ =~ self # ???
result = word.dup
regex, hash = pluralization_rules
result.sub!(regex) {|m| hash[m]}
plural_of[word] = result
return result
#pluralization_rules.each do |(match, replacement)|
# break if result.gsub!(match, replacement)
#end
#return result
end
# Alias for #plural (a Railism).
alias_method(:pluralize, :plural)
# Clear all rules.
def clear(type = :all)
if type == :singular || type == :all
@singular_of = {}
@singular_rules = []
@<API key>, @<API key> = nil, nil
end
if type == :plural || type == :all
@singular_of = {}
@singular_rules = []
@<API key>, @<API key> = nil, nil
end
end
end
# One argument means singular and plural are the same.
word 'equipment'
word 'information'
word 'money'
word 'species'
word 'series'
word 'fish'
word 'sheep'
word 'moose'
word 'hovercraft'
word 'news'
word 'rice'
word 'plurals'
# Two arguments defines a singular and plural exception.
word 'Swiss' , 'Swiss'
word 'alias' , 'aliases'
word 'analysis' , 'analyses'
#word 'axis' , 'axes'
word 'basis' , 'bases'
word 'buffalo' , 'buffaloes'
word 'child' , 'children'
#word 'cow' , 'kine'
word 'crisis' , 'crises'
word 'criterion' , 'criteria'
word 'datum' , 'data'
word 'goose' , 'geese'
word 'hive' , 'hives'
word 'index' , 'indices'
word 'life' , 'lives'
word 'louse' , 'lice'
word 'man' , 'men'
word 'matrix' , 'matrices'
word 'medium' , 'media'
word 'mouse' , 'mice'
word 'movie' , 'movies'
word 'octopus' , 'octopi'
word 'ox' , 'oxen'
word 'person' , 'people'
word 'potato' , 'potatoes'
word 'quiz' , 'quizzes'
word 'shoe' , 'shoes'
word 'status' , 'statuses'
word 'testis' , 'testes'
word 'thesis' , 'theses'
word 'thief' , 'thieves'
word 'tomato' , 'tomatoes'
word 'torpedo' , 'torpedoes'
word 'vertex' , 'vertices'
word 'virus' , 'viri'
word 'wife' , 'wives'
# One-way singularization exception (convert plural to singular).
singular_word 'cactus', 'cacti'
# One-way pluralizaton exception (convert singular to plural).
plural_word 'axis', 'axes'
# General rules.
rule 'rf' , 'rves'
rule 'ero' , 'eroes'
rule 'ch' , 'ches'
rule 'sh' , 'shes'
rule 'ss' , 'sses'
#rule 'ess' , 'esses'
rule 'ta' , 'tum'
rule 'ia' , 'ium'
rule 'ra' , 'rum'
rule 'ay' , 'ays'
rule 'ey' , 'eys'
rule 'oy' , 'oys'
rule 'uy' , 'uys'
rule 'y' , 'ies'
rule 'x' , 'xes'
rule 'lf' , 'lves'
rule 'ffe' , 'ffes'
rule 'af' , 'aves'
rule 'us' , 'uses'
rule 'ouse' , 'ouses'
rule 'osis' , 'oses'
rule 'ox' , 'oxes'
rule '' , 's'
# One-way singular rules.
singular_rule 'of' , 'ofs' # proof
singular_rule 'o' , 'oes' # hero, heroes
#singular_rule 'f' , 'ves'
# One-way plural rules.
plural_rule 's' , 'ses'
plural_rule 'ive' , 'ives' # don't want to snag wife
plural_rule 'fe' , 'ves' # don't want to snag perspectives
end
def self.singular(string)
English::Inflect.singular(string)
end
def self.plural(string)
English::Inflect.plural(string)
end
# Convert an English word from plurel to singular.
# "boys".singular #=> boy
# "tomatoes".singular #=> tomato
def singular
self.class.singular(@self)
end
# Alias for #singular.
alias_method(:singularize, :singular)
# Convert an English word from plurel to singular.
# "boys".singular #=> boy
# "tomatoes".singular #=> tomato
def plural
self.class.plural(@self)
end
# Alias for #plural.
alias_method(:pluralize, :plural)
end
|
#ifndef <API key>
#define <API key>
#include <moai-core/headers.h>
class <API key>
{
public:
STLString mSrc;
STLString mTarget;
// STLString mOverlay;
float mDuration;
float mDelay; //delay before playing target animation, should be < mDuration
};
class <API key> :
public virtual MOAILuaObject
{
private:
typedef STLMap < STLString, <API key>* >::iterator MixMapIt;
STLMap < STLString, <API key>* > mMixMap ;
static int _setMix ( lua_State* L );
static int _getMix ( lua_State* L );
<API key>* AffirmMix( STLString src, STLString target );
public:
<API key>* GetMix( STLString src, STLString target );
// void SetMix();
DECL_LUA_FACTORY( <API key> )
<API key>();
~<API key>();
void RegisterLuaClass ( MOAILuaState& state );
void RegisterLuaFuncs ( MOAILuaState& state );
};
#endif
|
var PixiText = require('../../lib/pixi/src/core/text/Text'),
utils = require('../core/utils'),
math = require('../../lib/pixi/src/core/math'),
Sprite = require('../display/Sprite'),
CONST = require('../core/const');
function Text(text, style, resolution){
this._init(text, style, resolution);
}
Text.prototype = Object.create(PixiText.prototype);
Text.prototype.constructor = Text;
Text.fontPropertiesCache = {};
Text.<API key> = document.createElement('canvas');
Text.<API key> = Text.<API key>.getContext('2d');
Text.prototype._init = function(text, style, resolution){
text = text || ' ';
PixiText.call(this, text, style, resolution);
this.speed = new math.Point();
this.anchor = new math.Point(0.5, 0.5);
this.pivot = new math.Point(0.5, 0.5);
};
Text.prototype.<API key> = function(){
// create some matrix refs for easy access
var pt = this.parent.worldTransform;
var wt = this.worldTransform;
//anchor, pivot, and flip variables
var sx = (this.flipX) ? -this.scale.x : this.scale.x,
sy = (this.flipY) ? -this.scale.y : this.scale.y,
ax = (this.flipX) ? 1-this.anchor.x : this.anchor.x,
ay = (this.flipY) ? 1-this.anchor.y : this.anchor.y,
px = (this.flipX) ? 1-this.pivot.x : this.pivot.x,
py = (this.flipY) ? 1-this.pivot.y : this.pivot.y;
// temporary matrix variables
var a, b, c, d, tx, ty;
//Avoid use _width or _height when are 0
if(!this._width||!this._height){
this._width = this.width/this.scale.x;
this._height = this.height/this.scale.y;
}
var anchorWidth = ax * this._width * sx,
anchorHeight = ay * this._height * sy,
pivotWidth = px * this._width * sx,
pivotHeight = py * this._height * sy;
// so if rotation is between 0 then we can simplify the multiplication process...
if (this.rotation % CONST.PI_2)
{
// check to see if the rotation is the same as the previous render. This means we only need to use sin and cos when rotation actually changes
if (this.rotation !== this.rotationCache)
{
this.rotationCache = this.rotation;
this._sr = Math.sin(this.rotation);
this._cr = Math.cos(this.rotation);
}
// get the matrix values of the displayobject based on its transform properties..
a = this._cr * sx;
b = this._sr * sx;
c = -this._sr * sy;
d = this._cr * sy;
tx = this.position.x + pivotWidth - anchorWidth;
ty = this.position.y + pivotHeight - anchorHeight;
if (pivotWidth || pivotHeight)
{
tx -= pivotWidth * this._cr + pivotHeight * -this._sr;
ty -= pivotWidth * this._sr + pivotHeight * this._cr;
}
// concat the parent matrix with the objects transform.
wt.a = a * pt.a + b * pt.c;
wt.b = a * pt.b + b * pt.d;
wt.c = c * pt.a + d * pt.c;
wt.d = c * pt.b + d * pt.d;
wt.tx = tx * pt.a + ty * pt.c + pt.tx;
wt.ty = tx * pt.b + ty * pt.d + pt.ty;
}
else
{
// lets do the fast version as we know there is no rotation..
a = sx;
d = sy;
tx = this.position.x - anchorWidth;
ty = this.position.y - anchorHeight;
wt.a = a * pt.a;
wt.b = a * pt.b;
wt.c = d * pt.c;
wt.d = d * pt.d;
wt.tx = tx * pt.a + ty * pt.c + pt.tx;
wt.ty = tx * pt.b + ty * pt.d + pt.ty;
}
// multiply the alphas..
this.worldAlpha = this.alpha * this.parent.worldAlpha;
// reset the bounds each time this is called!
this._currentBounds = null;
};
Text.prototype._renderCanvas = function (renderer)
{
if (this.dirty)
{
// this.resolution = 1//renderer.resolution;
this.updateText();
}
//Sprite.prototype._renderCanvas.call(this, renderer);
this._customRenderCanvas(renderer);
};
Text.prototype._customRenderCanvas = function(renderer){
if (this.texture.crop.width <= 0 || this.texture.crop.height <= 0)
{
return;
}
if (this.blendMode !== renderer.currentBlendMode)
{
renderer.currentBlendMode = this.blendMode;
renderer.context.<API key> = renderer.blendModes[renderer.currentBlendMode];
}
// Ignore null sources
if (this.texture.valid)
{
var texture = this._texture,
wt = this.worldTransform,
dx,
dy,
width,
height;
var resolution = texture.baseTexture.resolution / renderer.resolution;
renderer.context.globalAlpha = this.worldAlpha;
// If smoothingEnabled is supported and we need to change the smoothing property for this texture
if (renderer.smoothProperty && renderer.currentScaleMode !== texture.baseTexture.scaleMode)
{
renderer.currentScaleMode = texture.baseTexture.scaleMode;
renderer.context[renderer.smoothProperty] = (renderer.currentScaleMode === CONST.SCALE_MODES.LINEAR);
}
// If the texture is trimmed we offset by the trim x/y, otherwise we use the frame dimensions
if(texture.rotate)
{
// cheeky rotation!
var a = wt.a;
var b = wt.b;
wt.a = -wt.c;
wt.b = -wt.d;
wt.c = a;
wt.d = b;
width = texture.crop.height; //TODO: Width assigned to height???
height = texture.crop.width;
dx = (texture.trim) ? texture.trim.y - this.anchor.y * texture.trim.height : this.anchor.y * -texture._frame.height;
dy = (texture.trim) ? texture.trim.x - this.anchor.x * texture.trim.width : this.anchor.x * -texture._frame.width;
}
else
{
width = texture.crop.width;
height = texture.crop.height;
dx = (texture.trim) ? texture.trim.x - this.anchor.x * texture.trim.width : this.anchor.x * -texture._frame.width;
dy = (texture.trim) ? texture.trim.y - this.anchor.y * texture.trim.height : this.anchor.y * -texture._frame.height;
}
// Allow for pixel rounding
if (renderer.roundPixels)
{
renderer.context.setTransform(
wt.a,
wt.b,
wt.c,
wt.d,
(wt.tx * renderer.resolution) | 0,
(wt.ty * renderer.resolution) | 0
);
dx = dx | 0;
dy = dy | 0;
}
else
{
renderer.context.setTransform(
wt.a,
wt.b,
wt.c,
wt.d,
wt.tx * renderer.resolution,
wt.ty * renderer.resolution
);
}
var anchorWidth = this.anchor.x * this._width/resolution,
anchorHeight = this.anchor.y * this._height/resolution;
if (this.tint !== 0xFFFFFF)
{
if (this.cachedTint !== this.tint)
{
this.cachedTint = this.tint;
// TODO clean up caching - how to clean up the caches?
// TODO: dont works with spritesheets
this.tintedTexture = CanvasTinter.getTintedTexture(this, this.tint);
}
renderer.context.drawImage(
this.tintedTexture,
0,
0,
width * resolution * renderer.resolution,
height * resolution * renderer.resolution,
dx / resolution,
dy / resolution,
width * renderer.resolution,
height * renderer.resolution
);
}
else
{
renderer.context.drawImage(
texture.baseTexture.source,
texture.crop.x * resolution,
texture.crop.y * resolution,
width * resolution * renderer.resolution,
height * resolution * renderer.resolution,
dx / resolution + anchorWidth,
dy / resolution + anchorHeight,
width * renderer.resolution,
height * renderer.resolution
);
}
}
};
Text.prototype.renderWebGL = function (renderer)
{
if (this.dirty)
{
//this.resolution = 1//renderer.resolution;
this.updateText();
}
Sprite.prototype.renderWebGL.call(this, renderer);
};
Text.prototype.updateText = function (){
var style = this._style;
this.context.font = style.font;
// word wrap
// preserve original text
var outputText = style.wordWrap ? this.wordWrap(this._text) : this._text;
// split text into lines
var lines = outputText.split(/(?:\r\n|\r|\n)/);
// calculate text width
var lineWidths = new Array(lines.length);
var maxLineWidth = 0;
var fontProperties = this.<API key>(style.font);
for (var i = 0; i < lines.length; i++)
{
var lineWidth = this.context.measureText(lines[i]).width;
lineWidths[i] = lineWidth;
maxLineWidth = Math.max(maxLineWidth, lineWidth);
}
var width = maxLineWidth + style.strokeThickness;
if (style.dropShadow)
{
width += style.dropShadowDistance;
}
this.canvas.width = ( width + this.context.lineWidth ) * this.resolution;
// calculate text height
var lineHeight = this.style.lineHeight || fontProperties.fontSize + style.strokeThickness;
var height = lineHeight * lines.length;
if (style.dropShadow)
{
height += style.dropShadowDistance;
}
this.canvas.height = ( height + this._style.padding * 2 ) * this.resolution;
this.context.scale( this.resolution, this.resolution);
if (navigator.isCocoonJS)
{
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
//this.context.fillStyle="#FF0000";
//this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.context.font = style.font;
this.context.strokeStyle = (typeof style.stroke === "number") ? utils.hex2string(style.stroke) : style.stroke;
this.context.lineWidth = style.strokeThickness;
this.context.textBaseline = style.textBaseline;
this.context.lineJoin = style.lineJoin;
this.context.miterLimit = style.miterLimit;
var linePositionX;
var linePositionY;
if (style.dropShadow)
{
this.context.fillStyle = style.dropShadowColor;
var xShadowOffset = Math.cos(style.dropShadowAngle) * style.dropShadowDistance;
var yShadowOffset = Math.sin(style.dropShadowAngle) * style.dropShadowDistance;
for (i = 0; i < lines.length; i++)
{
linePositionX = style.strokeThickness / 2;
linePositionY = (style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent;
if (style.align === 'right')
{
linePositionX += maxLineWidth - lineWidths[i];
}
else if (style.align === 'center')
{
linePositionX += (maxLineWidth - lineWidths[i]) / 2;
}
if (style.fill)
{
this.context.fillText(lines[i], linePositionX + xShadowOffset, linePositionY + yShadowOffset + this._style.padding);
}
}
}
//set canvas text styles
this.context.fillStyle = (typeof style.fill === "number") ? utils.hex2string(style.fill) : style.fill;
//draw lines line by line
for (i = 0; i < lines.length; i++)
{
linePositionX = style.strokeThickness / 2;
linePositionY = (style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent;
if (style.align === 'right')
{
linePositionX += maxLineWidth - lineWidths[i];
}
else if (style.align === 'center')
{
linePositionX += (maxLineWidth - lineWidths[i]) / 2;
}
if (style.stroke && style.strokeThickness)
{
this.context.strokeText(lines[i], linePositionX, linePositionY + this._style.padding);
}
if (style.fill)
{
this.context.fillText(lines[i], linePositionX, linePositionY + this._style.padding);
}
}
this.updateTexture();
};
Text.prototype.setStyle = function(style){
this.style = style;
return this;
};
Text.prototype.setText = function(text, keys){
if(keys)text = utils.parseTextKeys(text, keys);
this.text = text;
return this;
};
Text.prototype.setWordWrap = function(value){
if(value === false){
this.style.wordWrap = value;
}else{
this.style.wordWrap = true;
this.style.wordWrapWidth = value;
}
this.dirty = true;
return this;
};
Text.prototype.containsPoint = Sprite.prototype.containsPoint;
Text.prototype.getLocalBounds = Sprite.prototype.getLocalBounds;
module.exports = Text;
|
var RightJS = require('./right-server.js');
var JSLint = require('./jslint').JSLINT;
var fs = require('fs');
exports.Linter = new RightJS.Class({
extend: {
Options: {
debug: false, // no debug
devel: false, // no console.log s
evil: false, // no evals
passfail: false, // don't stop on errors
onevar: false, // allow more than one 'var' definition
forin: true , // allow for in without ownershipt checks
indent: 2 , // enforce 2 spaces indent
maxerr: 12 , // max number of errors
},
Okays: [
"Move 'var' declarations to the top of the function.",
"Do not use 'new' for side effects.",
"The Function constructor is eval."
]
},
/**
* Basic constructor
*
* @param {String} the source
* @param {String} the linter options
* @return void
*/
initialize: function(src, options) {
this.source = src;
this.options = options;
},
/**
* Runs the linter
*
* @return {Linter} this
*/
run: function() {
var options = {}, okays = [], patches = '';
// extracting the additional options
try { // skipping non-existing patch files
patches = fs.readFileSync(this.options).toString();
} catch(e) {}
eval(patches);
JSLint.okays = this.constructor.Okays.concat(okays);
JSLint(
fs.readFileSync(this.source).toString(),
Object.merge(this.constructor.Options, options)
);
this.errors = JSLint.errors.compact();
this.failed = this.errors.length > 0;
return this;
},
/**
* Prints out the check report
*
* @return {Linter} this
*/
report: function() {
if (this.errors.empty()) {
console.log("\u001B[32m - JSLint check successfully passed\u001B[0m");
} else {
console.log("\u001B[31m - JSLint check failed in: "+ this.source + "\u001B[0m");
this.errors.each(function(error) {
var report = "\n", j=0, pointer='';
for (; j < error.character-1; j++) { pointer += '-'; }
report += " \u001B[35m"+ error.reason +"\u001B[0m ";
if (error.evidence) {
report += "Line: "+ error.line + ", Char: "+ error.character + "\n";
report += " "+ error.evidence + "\n";
report += " \u001B[33m"+ pointer + "^\u001B[0m";
}
console.log(report);
});
console.log("\n")
}
return this;
}
});
|
# coding=utf-8
import pygame
import pygame.locals
class Board(object):
"""
Plansza do gry. Odpowiada za rysowanie okna gry.
"""
def __init__(self, width, height):
self.surface = pygame.display.set_mode((width, height), 0, 32)
pygame.display.set_caption('Game of life')
def draw(self, *args):
background = (0, 0, 0)
self.surface.fill(background)
for drawable in args:
drawable.draw_on(self.surface)
pygame.display.update()
class GameOfLife(object):
def __init__(self, width, height, cell_size=10):
pygame.init()
self.board = Board(width * cell_size, height * cell_size)
# kolejnych klatek gry
self.fps_clock = pygame.time.Clock()
def run(self):
while not self.handle_events():
self.board.draw()
self.fps_clock.tick(15)
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.locals.QUIT:
pygame.quit()
return True
DEAD = 0
ALIVE = 1
class Population(object):
def __init__(self, width, height, cell_size=10):
self.box_size = cell_size
self.height = height
self.width = width
self.generation = self.reset_generation()
def reset_generation(self):
"""
Tworzy i zwraca macierz pustej populacji
"""
return [[DEAD for y in xrange(self.height)] for x in xrange(self.width)]
def handle_mouse(self):
buttons = pygame.mouse.get_pressed()
if not any(buttons):
return
alive = True if buttons[0] else False
x, y = pygame.mouse.get_pos()
x /= self.box_size
y /= self.box_size
self.generation[x][y] = ALIVE if alive else DEAD
def draw_on(self, surface):
for x, y in self.alive_cells():
size = (self.box_size, self.box_size)
position = (x * self.box_size, y * self.box_size)
color = (255, 255, 255)
thickness = 1
pygame.draw.rect(surface, color, pygame.locals.Rect(position, size), thickness)
def alive_cells(self):
for x in range(len(self.generation)):
column = self.generation[x]
for y in range(len(column)):
if column[y] == ALIVE:
yield x, y
if __name__ == "__main__":
game = GameOfLife(80, 40)
game.run()
|
using System.Linq.Expressions;
using System.Collections.Generic;
namespace Bermuda.<API key>
{
public partial class ValueExpression : ExpressionTreeBase
{
public long Value { get; private set; }
public ValueExpression(long value)
{
Value = value;
}
public override string ToString()
{
return string.Format("@{0}", Value.ToString());
}
public override IEnumerable<ExpressionTreeBase> GetChildren()
{
yield break;
}
public override Expression CreateExpression(object context)
{
return Expression.Constant(Value);
}
}
}
|
// String literal types are only valid in overload signatures
function foo(x: any);
function foo(x: 'hi') { }
class C {
foo(x: string);
foo(x: 'hi') { }
}
interface I {
(x: 'a');
(x: 'hi');
foo(x: 'a', y: 'a');
foo(x: 'hi', y: 'hi');
}
var a: {
(x: 'hi');
(x: 'a');
foo(x: 'hi');
foo(x: 'a');
}
var b = {
foo(x: 'hi') { },
foo(x: 'a') { },
}
|
<?php
namespace PhraseanetSDK\Tests\Cache;
use PhraseanetSDK\Cache\BackendCacheFactory;
use PhraseanetSDK\Exception\RuntimeException;
class <API key> extends \<API key>
{
/**
* @dataProvider <API key>
*/
public function testCreateSuccess($type, $host, $port, $instanceOf, $classExists)
{
if (null !== $classExists) {
if (!class_exists($classExists)) {
$this->markTestSkipped(sprintf('Unable to find class %s', $classExists));
}
}
$factory = new BackendCacheFactory();
try {
$this->assertInstanceOf($instanceOf, $factory->create($type, $host, $port));
} catch (RuntimeException $e) {
$this->assertContains(ucfirst(strtolower($type)), $e->getMessage());
}
}
public function <API key>()
{
return array(
array('memcache', '127.0.0.1', 11211, 'Doctrine\Common\Cache\MemcacheCache', 'Memcache'),
array('memcache', null, null, 'Doctrine\Common\Cache\MemcacheCache', 'Memcache'),
array('memcached', '127.0.0.1', 11211, 'Doctrine\Common\Cache\MemcachedCache', 'Memcached'),
array('memcached', null, null, 'Doctrine\Common\Cache\MemcachedCache', 'Memcached'),
array('array', '127.0.0.1', 11211, 'Doctrine\Common\Cache\ArrayCache', null),
array('array', null, null, 'Doctrine\Common\Cache\ArrayCache', null),
);
}
/**
* @dataProvider <API key>
* @expectedException PhraseanetSDK\Exception\RuntimeException
*/
public function testCreateFailure($type, $host, $port, $classExists)
{
if (null !== $classExists) {
if (!class_exists($classExists)) {
$this->markTestSkipped(sprintf('Unable to find class %s', $classExists));
}
}
$factory = new BackendCacheFactory();
$factory->create($type, $host, $port);
}
public function <API key>()
{
return array(
array('memcache', 'nohost', 'noport', 'Memcache'),
array('memcached', 'nohost', 'noport', 'Memcache'),
array('unknown', 'nohost', 'noport', null),
array('unknown', null, null, null),
);
}
}
|
"""
File-based Checkpoints implementations.
"""
import os
import shutil
from tornado.web import HTTPError
from .checkpoints import (
Checkpoints,
<API key>,
)
from .fileio import FileManagerMixin
from IPython.utils import tz
from IPython.utils.path import ensure_dir_exists
from IPython.utils.py3compat import getcwd
from IPython.utils.traitlets import Unicode
class FileCheckpoints(FileManagerMixin, Checkpoints):
"""
A Checkpoints that caches checkpoints for files in adjacent
directories.
Only works with FileContentsManager. Use <API key> if
you want file-based checkpoints with another ContentsManager.
"""
checkpoint_dir = Unicode(
'.ipynb_checkpoints',
config=True,
help="""The directory name in which to keep file checkpoints
This is a path relative to the file's own directory.
By default, it is .ipynb_checkpoints
""",
)
root_dir = Unicode(config=True)
def _root_dir_default(self):
try:
return self.parent.root_dir
except AttributeError:
return getcwd()
# <API key> checkpoint API
def create_checkpoint(self, contents_mgr, path):
"""Create a checkpoint."""
checkpoint_id = u'checkpoint'
src_path = contents_mgr._get_os_path(path)
dest_path = self.checkpoint_path(checkpoint_id, path)
self._copy(src_path, dest_path)
return self.checkpoint_model(checkpoint_id, dest_path)
def restore_checkpoint(self, contents_mgr, checkpoint_id, path):
"""Restore a checkpoint."""
src_path = self.checkpoint_path(checkpoint_id, path)
dest_path = contents_mgr._get_os_path(path)
self._copy(src_path, dest_path)
# <API key> checkpoint API
def rename_checkpoint(self, checkpoint_id, old_path, new_path):
"""Rename a checkpoint from old_path to new_path."""
old_cp_path = self.checkpoint_path(checkpoint_id, old_path)
new_cp_path = self.checkpoint_path(checkpoint_id, new_path)
if os.path.isfile(old_cp_path):
self.log.debug(
"Renaming checkpoint %s -> %s",
old_cp_path,
new_cp_path,
)
with self.perm_to_403():
shutil.move(old_cp_path, new_cp_path)
def delete_checkpoint(self, checkpoint_id, path):
"""delete a file's checkpoint"""
path = path.strip('/')
cp_path = self.checkpoint_path(checkpoint_id, path)
if not os.path.isfile(cp_path):
self.no_such_checkpoint(path, checkpoint_id)
self.log.debug("unlinking %s", cp_path)
with self.perm_to_403():
os.unlink(cp_path)
def list_checkpoints(self, path):
"""list the checkpoints for a given file
This contents manager currently only supports one checkpoint per file.
"""
path = path.strip('/')
checkpoint_id = "checkpoint"
os_path = self.checkpoint_path(checkpoint_id, path)
if not os.path.isfile(os_path):
return []
else:
return [self.checkpoint_model(checkpoint_id, os_path)]
# Checkpoint-related utilities
def checkpoint_path(self, checkpoint_id, path):
"""find the path to a checkpoint"""
path = path.strip('/')
parent, name = ('/' + path).rsplit('/', 1)
parent = parent.strip('/')
basename, ext = os.path.splitext(name)
filename = u"{name}-{checkpoint_id}{ext}".format(
name=basename,
checkpoint_id=checkpoint_id,
ext=ext,
)
os_path = self._get_os_path(path=parent)
cp_dir = os.path.join(os_path, self.checkpoint_dir)
with self.perm_to_403():
ensure_dir_exists(cp_dir)
cp_path = os.path.join(cp_dir, filename)
return cp_path
def checkpoint_model(self, checkpoint_id, os_path):
"""construct the info dict for a given checkpoint"""
stats = os.stat(os_path)
last_modified = tz.utcfromtimestamp(stats.st_mtime)
info = dict(
id=checkpoint_id,
last_modified=last_modified,
)
return info
# Error Handling
def no_such_checkpoint(self, path, checkpoint_id):
raise HTTPError(
404,
u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id)
)
class <API key>(<API key>, FileCheckpoints):
"""
Local filesystem Checkpoints that works with any conforming
ContentsManager.
"""
def <API key>(self, content, format, path):
"""Create a checkpoint from the current content of a file."""
path = path.strip('/')
# only the one checkpoint ID:
checkpoint_id = u"checkpoint"
os_checkpoint_path = self.checkpoint_path(checkpoint_id, path)
self.log.debug("creating checkpoint for %s", path)
with self.perm_to_403():
self._save_file(os_checkpoint_path, content, format=format)
# return the checkpoint info
return self.checkpoint_model(checkpoint_id, os_checkpoint_path)
def <API key>(self, nb, path):
"""Create a checkpoint from the current content of a notebook."""
path = path.strip('/')
# only the one checkpoint ID:
checkpoint_id = u"checkpoint"
os_checkpoint_path = self.checkpoint_path(checkpoint_id, path)
self.log.debug("creating checkpoint for %s", path)
with self.perm_to_403():
self._save_notebook(os_checkpoint_path, nb)
# return the checkpoint info
return self.checkpoint_model(checkpoint_id, os_checkpoint_path)
def <API key>(self, checkpoint_id, path):
"""Get a checkpoint for a notebook."""
path = path.strip('/')
self.log.info("restoring %s from checkpoint %s", path, checkpoint_id)
os_checkpoint_path = self.checkpoint_path(checkpoint_id, path)
if not os.path.isfile(os_checkpoint_path):
self.no_such_checkpoint(path, checkpoint_id)
return {
'type': 'notebook',
'content': self._read_notebook(
os_checkpoint_path,
as_version=4,
),
}
def get_file_checkpoint(self, checkpoint_id, path):
"""Get a checkpoint for a file."""
path = path.strip('/')
self.log.info("restoring %s from checkpoint %s", path, checkpoint_id)
os_checkpoint_path = self.checkpoint_path(checkpoint_id, path)
if not os.path.isfile(os_checkpoint_path):
self.no_such_checkpoint(path, checkpoint_id)
content, format = self._read_file(os_checkpoint_path, format=None)
return {
'type': 'file',
'content': content,
'format': format,
}
|
import React, { PropTypes } from 'react'
import ActionDelete from 'material-ui/svg-icons/action/delete'
import { colors } from '/styles'
import moduleStyles from '/styles/fileTree'
const RemoveBtn = ({ onClick }) => (
<ActionDelete
onClick={onClick}
style={moduleStyles.listIcon.base}
color={colors.light}
hoverColor={colors.hover.red} />
)
export default RemoveBtn
|
// Author : codeyu
// Date : 2016-09-20
using System.Collections.Generic;
using System;
namespace Algorithms
{
public class Solution003
{
public static int <API key>(string s)
{
var n = s.Length;
var charSet = new HashSet<char>();
int maxLength = 0, i = 0, j = 0;
while (i < n && j < n)
{
if (charSet.Add(s[j]))
{
j++;
maxLength = Math.Max(maxLength, j - i);
}
else
{
charSet.Remove(s[i]);
i++;
}
}
return maxLength;
}
}
}
|
using System.Collections.ObjectModel;
namespace <API key>.Areas.HelpPage.ModelDescriptions
{
public class <API key> : ModelDescription
{
public <API key>()
{
Properties = new Collection<<API key>>();
}
public Collection<<API key>> Properties { get; private set; }
}
}
|
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<!-- end header part -->
<!-- Generated by Doxygen 1.8.4 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="a00237.html">tbb</a></li><li class="navelem"><b>interface5</b></li><li class="navelem"><a class="el" href="a00046.html"><API key></a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator > Member List</div> </div>
</div><!--header
<div class="contents">
<p>This is the complete list of members for <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>, including all inherited members.</p>
<table class="directory">
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>allocator_type</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b><API key></b>(size_type n_of_buckets=base_type::<API key>, const hasher &_Hasher=hasher(), const key_equal &_Key_equality=key_equal(), const allocator_type &a=allocator_type()) (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">explicit</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b><API key></b>(const Allocator &a) (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">explicit</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b><API key></b>(Iterator first, Iterator last, size_type n_of_buckets=base_type::<API key>, const hasher &_Hasher=hasher(), const key_equal &_Key_equality=key_equal(), const allocator_type &a=allocator_type()) (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="a00046.html#<API key>"><API key></a>(std::initializer_list< value_type > il, size_type n_of_buckets=base_type::<API key>, const hasher &_Hasher=hasher(), const key_equal &_Key_equality=key_equal(), const allocator_type &a=allocator_type())</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b><API key></b>(const <API key> &table) (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b><API key></b>(<API key> &&table) (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b><API key></b>(<API key> &&table, const Allocator &a) (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b><API key></b>(const <API key> &table, const Allocator &a) (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>const_iterator</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b><API key></b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>const_pointer</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>const_reference</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>difference_type</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>hasher</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>iterator</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>key_compare</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>key_equal</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>key_type</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>local_iterator</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>mapped_type</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>operator=</b>(const <API key> &table) (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>operator=</b>(<API key> &&table) (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>pointer</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>reference</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>size_type</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>value_type</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::<API key>< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
</table></div><!-- contents -->
<hr>
<p></p>
Copyright © 2005-2017 Intel Corporation. All Rights Reserved.
<p></p>
Intel, Pentium, Intel Xeon, Itanium, Intel XScale and VTune are
registered trademarks or trademarks of Intel Corporation or its
subsidiaries in the United States and other countries.
<p></p>
* Other names and brands may be claimed as the property of others.
|
#require File.dirname(__FILE__) + '/formats/email'
module DataMapper
module Validate
# @author Guy van den Berg
# @since 0.9
class CustomValidator < GenericValidator
def initialize(field_name, options = {}, &b)
#super(field_name, options)
#@field_name, @options = field_name, options
#@options[:allow_nil] = false unless @options.has_key?(:allow_nil)
end
def call(target)
#field_value = target.<API key>("@#{@field_name}")
#return true if @options[:allow_nil] && field_value.nil?
#validation = (@options[:as] || @options[:with])
#error_message = nil
# Figure out what to use as the actual validator.
# If a symbol is passed to :as, look up
# the canned validation in FORMATS.
#validator = if validation.is_a? Symbol
# if FORMATS[validation].is_a? Array
# error_message = FORMATS[validation][1]
# FORMATS[validation][0]
# else
# FORMATS[validation] || validation
# end
#else
# validation
#end
#valid = case validator
#when Proc then validator.call(field_value)
#when Regexp then validator =~ field_value
#else raise <API key>, "Can't determine how to validate #{target.class}##{@field_name} with #{validator.inspect}"
#end
#unless valid
# field = Inflector.humanize(@field_name)
# value = field_value
# error_message = @options[:message] || error_message || '%s is invalid'.t(field)
# add_error(target, error_message , @field_name)
#end
#return valid
end
#class <API key> < StandardError; end
end # class CustomValidator
module ValidatesFormatOf
#def validates_format_of(*fields)
#opts = <API key>(fields)
#end
end # module ValidatesFormatOf
end # module Validate
end # module DataMapper
|
lib: node_modules $(shell find src)
rm -rf lib
node_modules/.bin/coffee --output lib --compile src
test: node_modules
node_modules/.bin/mocha test/suite
coverage: node_modules
node_modules/.bin/mocha --require test/coverage test/suite
node_modules/.bin/istanbul report
lint: node_modules
node_modules/.bin/coffeelint --file coffeelint.json src
node_modules/.bin/coffeelint --file test/coffeelint.json test/suite
ci: coverage
.PHONY: test coverage lint ci
node_modules:
npm install
|
#!/usr/bin/ruby
require "fileutils"
require 'json'
require_relative "BibleReader.rb"
reader = BibleReader.new
translation_names = ['', '', 'NIV']#BibleInfo.<API key>.keys
translation_names.each do |translation_name|
translation_code = BibleInfo.<API key>[translation_name]
BibleInfo.<API key>.each do |bible_name, chapter_len|
# puts "#{translation_name}, #{bible_name}, #{chapter_len}"
bible_shortname = BibleInfo.<API key>[bible_name]
db_name = "db/#{translation_name}/#{"%02d_" % BibleInfo.bible_name_to_code[bible_name]}#{bible_name}"
unless Dir.exist? db_name
FileUtils.mkdir_p(db_name)
end
(1..chapter_len).each do |chapter|
file = File.open "#{db_name}/#{chapter}", 'w'
chapter_content = reader.<API key>(translation_name, bible_shortname, chapter)
file.write(chapter_content.to_json)
file.close()
end
end
end
|
<?php
/**
* TOP API: taobao.hotel.order.face.deal request
*
* @author auto create
* @since 1.0, 2013-09-13 16:51:03
*/
class <API key> {
/**
* oid
**/
private $oid;
private $operType;
private $reasonText;
/**
* 1,2,3,4
* 1234
**/
private $reasonType;
private $apiParas = array();
public function setOid($oid) {
$this->oid = $oid;
$this->apiParas["oid"] = $oid;
}
public function getOid() {
return $this->oid;
}
public function setOperType($operType) {
$this->operType = $operType;
$this->apiParas["oper_type"] = $operType;
}
public function getOperType() {
return $this->operType;
}
public function setReasonText($reasonText) {
$this->reasonText = $reasonText;
$this->apiParas["reason_text"] = $reasonText;
}
public function getReasonText() {
return $this->reasonText;
}
public function setReasonType($reasonType) {
$this->reasonType = $reasonType;
$this->apiParas["reason_type"] = $reasonType;
}
public function getReasonType() {
return $this->reasonType;
}
public function getApiMethodName() {
return "taobao.hotel.order.face.deal";
}
public function getApiParas() {
return $this->apiParas;
}
public function check() {
<API key>::checkNotNull($this->oid, "oid");
<API key>::checkNotNull($this->operType, "operType");
<API key>::checkMaxLength($this->operType, 1, "operType");
<API key>::checkMaxLength($this->reasonText, 500, "reasonText");
<API key>::checkMaxLength($this->reasonType, 1, "reasonType");
}
public function putOtherTextParam($key, $value) {
$this->apiParas[$key] = $value;
$this->$key = $value;
}
}
|
import { Observable } from './observable'
export default function drop(count, source) {
return Observable(add => {
let dropped = 0
return source.subscribe((val, name) => {
if (dropped++ >= count) add(val, name)
})
})
}
|
package schoolprojects;
import java.util.Random;
import java.util.Scanner;
public class Juego {
/**
* @param args Argumentos de la linea de comandos
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
/**
* Movimientos disponibles en forma de cadena.
*/
String[] movimientos = {"Piedra", "Papel", "Tijera"};
/**
* Moviemiento elegido por el usuario en forma de numero entero.
*/
int entradaUsuario = 0;
/**
* Un numero aleatorio que representara el movimiento del ordenador.
*/
int movimientoAleatorio = 0;
/**
* Los resultados posibles de la partida. 0 EMPATE 1 El jugador gana 2
* El jugador pierde
*/
String[] resultados = {"Empate", "Ganas", "Pierdes"};
/**
* El resultado de la partida respecto el jugador.
*/
int resultadoJugador = -1;
/**
* Aqui es donde epieza el juego.
*
* Pedimos al usuario que elija uno de los movimientos disponibles
* y generamos un movimiento aleatorio, que sera el movimiento del ordenador.
* Despues comptrobamos si el jugador gana al ordenador , si pierde o si hay un empate.
* Mostramos el resultado en la pantalla y el bucle se repite hasta que
* el jugador no introduce -1 como movimiento.
*/
do {
// Mostramos informacion sobre los movimientos validos y
// los numeros que le corresponden.
for (int i = 0; i < movimientos.length; i++) {
System.out.print("(" + (i + 1) + ") " + movimientos[i] + "\n");
}
// Valor predeterminado ( o entrada no valida, por si el usuario no introduce ningun valor )
entradaUsuario = 0;
// Leemos la entrada ( el moviemiento ) del usuario
try {
System.out.print("Movimiento: ");
entradaUsuario = Integer.parseInt(scan.nextLine());
} catch (<API key> ex) {
// Si la entrada no tiene un formato valido, mostraremos un mensaje de error
// y le pediremos al usuario que introduzca un movimiento nuevamente.
entradaUsuario = 0;
}
// Si la opcion elegida por el usuario no es valida imprimimos un
// mensaje de error y le volvemos a pedir que introduzca una opcion
if (entradaUsuario < 1 || entradaUsuario > 3) {
System.out.println("\n*** El movimiento elegido no es valido. ***");
continue;
}
// Restamos 1 a la entrada del usuario.
// Esto lo hacemos para que sea un indice de vector valido.
entradaUsuario -= 1;
// Generamos un movimiento aleatorio
movimientoAleatorio = rand.nextInt(movimientos.length);
// Para separar el "menu" de moviemientos y la entrada del usuario
// con la salida/resultado de la partida marco
System.out.println("\n*******************************\n");
// Imprimimos las jugadas del jugador y del ordenador
System.out.println("Tu: (" + movimientos[entradaUsuario] + ") [VS] PC: (" + movimientos[movimientoAleatorio] + ")");
// Comprobamos si el jugador gana
if ((entradaUsuario == 0 && movimientoAleatorio == 2) ||
(entradaUsuario == 1 && movimientoAleatorio == 0) ||
(entradaUsuario == 2 && movimientoAleatorio == 1)) {
resultadoJugador = 1;
} else if(entradaUsuario == movimientoAleatorio) { // Comprobamos si es un empate
resultadoJugador = 0;
} else { // en el resto de los casos el jugador pierde
resultadoJugador = 2;
}
// Imprimimos el resultado de la partida
System.out.println("Resultado: " + resultados[resultadoJugador]);
// Para separar el "menu" de moviemientos y la entrada del usuario
// con la salida/resultado de la partida marco
System.out.println("\n*******************************\n");
} while (entradaUsuario != -1);
}
}
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="de">
<head>
<!-- Generated by javadoc (version 1.7.0_01) on Thu Mar 07 20:40:25 CET 2013 -->
<title>Uses of Class com.tyrlib2.graphics.renderables.BoundingBox</title>
<meta name="date" content="2013-03-07">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.tyrlib2.graphics.renderables.BoundingBox";
}
</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><a href="../../../../../com/tyrlib2/graphics/renderables/BoundingBox.html" title="class in com.tyrlib2.graphics.renderables">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/tyrlib2/graphics/renderables/\<API key>.html" target="_top">Frames</a></li>
<li><a href="BoundingBox.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>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<h2 title="Uses of Class com.tyrlib2.graphics.renderables.BoundingBox" class="title">Uses of Class<br>com.tyrlib2.graphics.renderables.BoundingBox</h2>
</div>
<div class="classUseContainer">No usage of com.tyrlib2.graphics.renderables.BoundingBox</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><a href="../../../../../com/tyrlib2/graphics/renderables/BoundingBox.html" title="class in com.tyrlib2.graphics.renderables">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/tyrlib2/graphics/renderables/\<API key>.html" target="_top">Frames</a></li>
<li><a href="BoundingBox.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>
<a name="skip-navbar_bottom">
</a></div>
</body>
</html>
|
#.rst:
# FindZLIB
# Find the native ZLIB includes and library.
# IMPORTED Targets
# This module defines :prop_tgt:`IMPORTED` target ``ZLIB::ZLIB``, if
# ZLIB has been found.
# Result Variables
# This module defines the following variables:
# ZLIB_INCLUDE_DIRS - where to find zlib.h, etc.
# ZLIB_LIBRARIES - List of libraries when using zlib.
# ZLIB_FOUND - True if zlib found.
# ZLIB_VERSION_STRING - The version of zlib found (x.y.z)
# ZLIB_VERSION_MAJOR - The major version of zlib
# ZLIB_VERSION_MINOR - The minor version of zlib
# ZLIB_VERSION_PATCH - The patch version of zlib
# ZLIB_VERSION_TWEAK - The tweak version of zlib
# Backward Compatibility
# The following variable are provided for backward compatibility
# ZLIB_MAJOR_VERSION - The major version of zlib
# ZLIB_MINOR_VERSION - The minor version of zlib
# ZLIB_PATCH_VERSION - The patch version of zlib
# Hints
# A user may set ``ZLIB_ROOT`` to a zlib installation root to tell this
# module where to look.
set(_ZLIB_SEARCHES)
# Search ZLIB_ROOT first if it is set.
if(ZLIB_ROOT)
set(_ZLIB_SEARCH_ROOT PATHS ${ZLIB_ROOT} NO_DEFAULT_PATH)
list(APPEND _ZLIB_SEARCHES _ZLIB_SEARCH_ROOT)
endif()
# Normal search.
set(_ZLIB_SEARCH_NORMAL
PATHS "[HKEY_LOCAL_MACHINE\\SOFTWARE\\GnuWin32\\Zlib;InstallPath]"
"$ENV{PROGRAMFILES}/zlib"
)
list(APPEND _ZLIB_SEARCHES _ZLIB_SEARCH_NORMAL)
set(ZLIB_NAMES z zlib zdll zlib1)
set(ZLIB_NAMES_DEBUG zlibd zlibd1)
# Try each search configuration.
foreach(search ${_ZLIB_SEARCHES})
find_path(ZLIB_INCLUDE_DIR NAMES zlib.h ${${search}} PATH_SUFFIXES include)
endforeach()
# Allow ZLIB_LIBRARY to be set manually, as the location of the zlib library
if(NOT ZLIB_LIBRARY)
foreach(search ${_ZLIB_SEARCHES})
find_library(<API key> NAMES ${ZLIB_NAMES} ${${search}} PATH_SUFFIXES lib)
find_library(ZLIB_LIBRARY_DEBUG NAMES ${ZLIB_NAMES_DEBUG} ${${search}} PATH_SUFFIXES lib)
endforeach()
include(${<API key>}/<API key>.cmake)
<API key>(ZLIB)
endif()
unset(ZLIB_NAMES)
unset(ZLIB_NAMES_DEBUG)
mark_as_advanced(ZLIB_INCLUDE_DIR)
if(ZLIB_INCLUDE_DIR AND EXISTS "${ZLIB_INCLUDE_DIR}/zlib.h")
file(STRINGS "${ZLIB_INCLUDE_DIR}/zlib.h" ZLIB_H REGEX "^#define ZLIB_VERSION \"[^\"]*\"$")
string(REGEX REPLACE "^.*ZLIB_VERSION \"([0-9]+).*$" "\\1" ZLIB_VERSION_MAJOR "${ZLIB_H}")
string(REGEX REPLACE "^.*ZLIB_VERSION \"[0-9]+\\.([0-9]+).*$" "\\1" ZLIB_VERSION_MINOR "${ZLIB_H}")
string(REGEX REPLACE "^.*ZLIB_VERSION \"[0-9]+\\.[0-9]+\\.([0-9]+).*$" "\\1" ZLIB_VERSION_PATCH "${ZLIB_H}")
set(ZLIB_VERSION_STRING "${ZLIB_VERSION_MAJOR}.${ZLIB_VERSION_MINOR}.${ZLIB_VERSION_PATCH}")
# only append a TWEAK version if it exists:
set(ZLIB_VERSION_TWEAK "")
if( "${ZLIB_H}" MATCHES "ZLIB_VERSION \"[0-9]+\\.[0-9]+\\.[0-9]+\\.([0-9]+)")
set(ZLIB_VERSION_TWEAK "${CMAKE_MATCH_1}")
string(APPEND ZLIB_VERSION_STRING ".${ZLIB_VERSION_TWEAK}")
endif()
set(ZLIB_MAJOR_VERSION "${ZLIB_VERSION_MAJOR}")
set(ZLIB_MINOR_VERSION "${ZLIB_VERSION_MINOR}")
set(ZLIB_PATCH_VERSION "${ZLIB_VERSION_PATCH}")
endif()
include(${<API key>}/<API key>.cmake)
<API key>(ZLIB REQUIRED_VARS ZLIB_LIBRARY ZLIB_INCLUDE_DIR
VERSION_VAR ZLIB_VERSION_STRING)
if(ZLIB_FOUND)
set(ZLIB_INCLUDE_DIRS ${ZLIB_INCLUDE_DIR})
if(NOT ZLIB_LIBRARIES)
set(ZLIB_LIBRARIES ${ZLIB_LIBRARY})
endif()
if(NOT TARGET ZLIB::ZLIB)
add_library(ZLIB::ZLIB UNKNOWN IMPORTED)
<API key>(ZLIB::ZLIB PROPERTIES
<API key> "${ZLIB_INCLUDE_DIRS}")
if(<API key>)
set_property(TARGET ZLIB::ZLIB APPEND PROPERTY
<API key> RELEASE)
<API key>(ZLIB::ZLIB PROPERTIES
<API key> "${<API key>}")
endif()
if(ZLIB_LIBRARY_DEBUG)
set_property(TARGET ZLIB::ZLIB APPEND PROPERTY
<API key> DEBUG)
<API key>(ZLIB::ZLIB PROPERTIES
<API key> "${ZLIB_LIBRARY_DEBUG}")
endif()
if(NOT <API key> AND NOT ZLIB_LIBRARY_DEBUG)
set_property(TARGET ZLIB::ZLIB APPEND PROPERTY
IMPORTED_LOCATION "${ZLIB_LIBRARY}")
endif()
endif()
endif()
|
"""Support for monitoring emoncms feeds."""
from __future__ import annotations
from datetime import timedelta
from http import HTTPStatus
import logging
import requests
import voluptuous as vol
from homeassistant.components.sensor import (
PLATFORM_SCHEMA,
SensorDeviceClass,
SensorEntity,
SensorStateClass,
)
from homeassistant.const import (
CONF_API_KEY,
CONF_ID,
CONF_SCAN_INTERVAL,
<API key>,
CONF_URL,
CONF_VALUE_TEMPLATE,
POWER_WATT,
STATE_UNKNOWN,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import template
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)
ATTR_FEEDID = "FeedId"
ATTR_FEEDNAME = "FeedName"
ATTR_LASTUPDATETIME = "LastUpdated"
<API key> = "LastUpdatedStr"
ATTR_SIZE = "Size"
ATTR_TAG = "Tag"
ATTR_USERID = "UserId"
CONF_EXCLUDE_FEEDID = "exclude_feed_id"
<API key> = "<API key>"
CONF_SENSOR_NAMES = "sensor_names"
DECIMALS = 2
DEFAULT_UNIT = POWER_WATT
<API key> = timedelta(seconds=5)
ONLY_INCL_EXCL_NONE = "<API key>"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_URL): cv.string,
vol.Required(CONF_ID): cv.positive_int,
vol.Exclusive(<API key>, ONLY_INCL_EXCL_NONE): vol.All(
cv.ensure_list, [cv.positive_int]
),
vol.Exclusive(CONF_EXCLUDE_FEEDID, ONLY_INCL_EXCL_NONE): vol.All(
cv.ensure_list, [cv.positive_int]
),
vol.Optional(CONF_SENSOR_NAMES): vol.All(
{cv.positive_int: vol.All(cv.string, vol.Length(min=1))}
),
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(<API key>, default=DEFAULT_UNIT): cv.string,
}
)
def get_id(sensorid, feedtag, feedname, feedid, feeduserid):
"""Return unique identifier for feed / sensor."""
return f"emoncms{sensorid}_{feedtag}_{feedname}_{feedid}_{feeduserid}"
def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the Emoncms sensor."""
apikey = config.get(CONF_API_KEY)
url = config.get(CONF_URL)
sensorid = config.get(CONF_ID)
value_template = config.get(CONF_VALUE_TEMPLATE)
config_unit = config.get(<API key>)
exclude_feeds = config.get(CONF_EXCLUDE_FEEDID)
include_only_feeds = config.get(<API key>)
sensor_names = config.get(CONF_SENSOR_NAMES)
interval = config.get(CONF_SCAN_INTERVAL)
if value_template is not None:
value_template.hass = hass
data = EmonCmsData(hass, url, apikey, interval)
data.update()
if data.data is None:
return
sensors = []
for elem in data.data:
if exclude_feeds is not None and int(elem["id"]) in exclude_feeds:
continue
if include_only_feeds is not None and int(elem["id"]) not in include_only_feeds:
continue
name = None
if sensor_names is not None:
name = sensor_names.get(int(elem["id"]), None)
if unit := elem.get("unit"):
unit_of_measurement = unit
else:
unit_of_measurement = config_unit
sensors.append(
EmonCmsSensor(
hass,
data,
name,
value_template,
unit_of_measurement,
str(sensorid),
elem,
)
)
add_entities(sensors)
class EmonCmsSensor(SensorEntity):
"""Implementation of an Emoncms sensor."""
def __init__(
self, hass, data, name, value_template, unit_of_measurement, sensorid, elem
):
"""Initialize the sensor."""
if name is None:
# Suppress ID in sensor name if it's 1, since most people won't
# have more than one EmonCMS source and it's redundant to show the
# ID if there's only one.
id_for_name = "" if str(sensorid) == "1" else sensorid
# Use the feed name assigned in EmonCMS or fall back to the feed ID
feed_name = elem.get("name") or f"Feed {elem['id']}"
self._name = f"EmonCMS{id_for_name} {feed_name}"
else:
self._name = name
self._identifier = get_id(
sensorid, elem["tag"], elem["name"], elem["id"], elem["userid"]
)
self._hass = hass
self._data = data
self._value_template = value_template
self.<API key> = unit_of_measurement
self._sensorid = sensorid
self._elem = elem
if unit_of_measurement == "kWh":
self._attr_device_class = SensorDeviceClass.ENERGY
self._attr_state_class = SensorStateClass.TOTAL_INCREASING
elif unit_of_measurement == "W":
self._attr_device_class = SensorDeviceClass.POWER
self._attr_state_class = SensorStateClass.MEASUREMENT
if self._value_template is not None:
self._state = self._value_template.<API key>(
elem["value"], STATE_UNKNOWN
)
else:
self._state = round(float(elem["value"]), DECIMALS)
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def <API key>(self):
"""Return the unit of measurement of this entity, if any."""
return self.<API key>
@property
def native_value(self):
"""Return the state of the device."""
return self._state
@property
def <API key>(self):
"""Return the attributes of the sensor."""
return {
ATTR_FEEDID: self._elem["id"],
ATTR_TAG: self._elem["tag"],
ATTR_FEEDNAME: self._elem["name"],
ATTR_SIZE: self._elem["size"],
ATTR_USERID: self._elem["userid"],
ATTR_LASTUPDATETIME: self._elem["time"],
<API key>: template.timestamp_local(float(self._elem["time"])),
}
def update(self):
"""Get the latest data and updates the state."""
self._data.update()
if self._data.data is None:
return
elem = next(
(
elem
for elem in self._data.data
if get_id(
self._sensorid,
elem["tag"],
elem["name"],
elem["id"],
elem["userid"],
)
== self._identifier
),
None,
)
if elem is None:
return
self._elem = elem
if self._value_template is not None:
self._state = self._value_template.<API key>(
elem["value"], STATE_UNKNOWN
)
else:
self._state = round(float(elem["value"]), DECIMALS)
class EmonCmsData:
"""The class for handling the data retrieval."""
def __init__(self, hass, url, apikey, interval):
"""Initialize the data object."""
self._apikey = apikey
self._url = f"{url}/feed/list.json"
self._interval = interval
self._hass = hass
self.data = None
@Throttle(<API key>)
def update(self):
"""Get the latest data from Emoncms."""
try:
parameters = {"apikey": self._apikey}
req = requests.get(
self._url, params=parameters, allow_redirects=True, timeout=5
)
except requests.exceptions.RequestException as exception:
_LOGGER.error(exception)
return
else:
if req.status_code == HTTPStatus.OK:
self.data = req.json()
else:
_LOGGER.error(
"Please verify if the specified configuration value "
"'%s' is correct! (HTTP Status_code = %d)",
CONF_URL,
req.status_code,
)
|
#include "MotionStreakTest.h"
#include "../testResource.h"
enum {
kTagLabel = 1,
kTagSprite1 = 2,
kTagSprite2 = 3,
};
Layer* nextMotionAction();
Layer* backMotionAction();
Layer* restartMotionAction();
static int sceneIdx = -1;
static std::function<Layer*()> createFunctions[] =
{
CL(MotionStreakTest1),
CL(MotionStreakTest2),
CL(Issue1358),
};
#define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0]))
Layer* nextMotionAction()
{
sceneIdx++;
sceneIdx = sceneIdx % MAX_LAYER;
auto layer = (createFunctions[sceneIdx])();
layer->autorelease();
return layer;
}
Layer* backMotionAction()
{
sceneIdx
int total = MAX_LAYER;
if( sceneIdx < 0 )
sceneIdx += total;
auto layer = (createFunctions[sceneIdx])();
layer->autorelease();
return layer;
}
Layer* restartMotionAction()
{
auto layer = (createFunctions[sceneIdx])();
layer->autorelease();
return layer;
}
// MotionStreakTest1
void MotionStreakTest1::onEnter()
{
MotionStreakTest::onEnter();
auto s = Director::getInstance()->getWinSize();
// the root object just rotates around
_root = Sprite::create(s_pathR1);
addChild(_root, 1);
_root->setPosition(Point(s.width/2, s.height/2));
// the target object is offset from root, and the streak is moved to follow it
_target = Sprite::create(s_pathR1);
_root->addChild(_target);
_target->setPosition(Point(s.width/4, 0));
// create the streak object and add it to the scene
streak = MotionStreak::create(2, 3, 32, Color3B::GREEN, s_streak);
addChild(streak);
// schedule an update on each frame so we can syncronize the streak with the target
schedule(schedule_selector(MotionStreakTest1::onUpdate));
auto a1 = RotateBy::create(2, 360);
auto action1 = RepeatForever::create(a1);
auto motion = MoveBy::create(2, Point(100,0) );
_root->runAction( RepeatForever::create(Sequence::create(motion, motion->reverse(), NULL) ) );
_root->runAction( action1 );
auto colorAction = RepeatForever::create(Sequence::create(
TintTo::create(0.2f, 255, 0, 0),
TintTo::create(0.2f, 0, 255, 0),
TintTo::create(0.2f, 0, 0, 255),
TintTo::create(0.2f, 0, 255, 255),
TintTo::create(0.2f, 255, 255, 0),
TintTo::create(0.2f, 255, 0, 255),
TintTo::create(0.2f, 255, 255, 255),
NULL));
streak->runAction(colorAction);
}
void MotionStreakTest1::onUpdate(float delta)
{
streak->setPosition( _target->convertToWorldSpace(Point::ZERO) );
}
std::string MotionStreakTest1::title()
{
return "MotionStreak test 1";
}
// MotionStreakTest2
void MotionStreakTest2::onEnter()
{
MotionStreakTest::onEnter();
auto listener = <API key>::create();
listener->onTouchesMoved = CC_CALLBACK_2(MotionStreakTest2::onTouchesMoved, this);
_eventDispatcher-><API key>(listener, this);
auto s = Director::getInstance()->getWinSize();
// create the streak object and add it to the scene
streak = MotionStreak::create(3, 3, 64, Color3B::WHITE, s_streak );
addChild(streak);
streak->setPosition( Point(s.width/2, s.height/2) );
}
void MotionStreakTest2::onTouchesMoved(const std::vector<Touch*>& touches, Event* event)
{
auto touchLocation = touches[0]->getLocation();
streak->setPosition( touchLocation );
}
std::string MotionStreakTest2::title()
{
return "MotionStreak test";
}
// Issue1358
void Issue1358::onEnter()
{
MotionStreakTest::onEnter();
// ask director the the window size
auto size = Director::getInstance()->getWinSize();
streak = MotionStreak::create(2.0f, 1.0f, 50.0f, Color3B(255, 255, 0), "Images/Icon.png");
addChild(streak);
_center = Point(size.width/2, size.height/2);
_radius = size.width/3;
_angle = 0.0f;
schedule(schedule_selector(Issue1358::update), 0);
}
void Issue1358::update(float dt)
{
_angle += 1.0f;
streak->setPosition(Point(_center.x + cosf(_angle/180 * M_PI)*_radius,
_center.y + sinf(_angle/ 180 * M_PI)*_radius));
}
std::string Issue1358::title()
{
return "Issue 1358";
}
std::string Issue1358::subtitle()
{
return "The tail should use the texture";
}
// MotionStreakTest
MotionStreakTest::MotionStreakTest(void)
{
}
MotionStreakTest::~MotionStreakTest(void)
{
}
std::string MotionStreakTest::title()
{
return "No title";
}
std::string MotionStreakTest::subtitle()
{
return "";
}
void MotionStreakTest::onEnter()
{
BaseTest::onEnter();
auto s = Director::getInstance()->getWinSize();
auto itemMode = MenuItemToggle::createWithCallback( CC_CALLBACK_1(MotionStreakTest::modeCallback, this),
MenuItemFont::create("Use High Quality Mode"),
MenuItemFont::create("Use Fast Mode"),
NULL);
auto menuMode = Menu::create(itemMode, NULL);
addChild(menuMode);
menuMode->setPosition(Point(s.width/2, s.height/4));
}
void MotionStreakTest::modeCallback(Object *pSender)
{
bool fastMode = streak->isFastMode();
streak->setFastMode(! fastMode);
}
void MotionStreakTest::restartCallback(Object* sender)
{
auto s = new <API key>();//CCScene::create();
s->addChild(restartMotionAction());
Director::getInstance()->replaceScene(s);
s->release();
}
void MotionStreakTest::nextCallback(Object* sender)
{
auto s = new <API key>();//CCScene::create();
s->addChild( nextMotionAction() );
Director::getInstance()->replaceScene(s);
s->release();
}
void MotionStreakTest::backCallback(Object* sender)
{
auto s = new <API key>;//CCScene::create();
s->addChild( backMotionAction() );
Director::getInstance()->replaceScene(s);
s->release();
}
void <API key>::runThisTest()
{
auto layer = nextMotionAction();
addChild(layer);
Director::getInstance()->replaceScene(this);
}
|
<?php
namespace <API key>\Service;
use <API key>\Service\<API key>;
use <API key>\AbstractTest;
class <API key> extends AbstractTest
{
public function <API key>()
{
$config = $this->getDocumentManager()->getConfiguration();
$this->assertSame(123, $config->getRetryConnect());
}
public function <API key>()
{
$config = $this->getDocumentManager()->getConfiguration();
$this->assertSame(456, $config->getRetryQuery());
}
public function testCreation()
{
$logger = $this-><API key>('<API key>\Logging\Logger');
$metadataCache = $this-><API key>('Doctrine\Common\Cache\Cache');
$mappingDriver = $this-><API key>('Doctrine\Common\Persistence\Mapping\Driver\MappingDriver');
$serviceLocator = $this-><API key>('Zend\ServiceManager\<API key>');
$serviceLocator->expects($this->exactly(4))->method('get')->withConsecutive(
array('Configuration'),
array('stubbed_logger'),
array('doctrine.cache.<API key>'),
array('doctrine.driver.stubbed_driver')
)-><API key>(
array(
'doctrine' => array(
'configuration' => array(
'odm_test' => array(
'logger' => 'stubbed_logger',
'metadata_cache' => '<API key>',
'driver' => 'stubbed_driver',
'generate_proxies' => true,
'proxy_dir' => 'data/<API key>/Proxy',
'proxy_namespace' => '<API key>\Proxy',
'generate_hydrators' => true,
'hydrator_dir' => 'data/<API key>/Hydrator',
'hydrator_namespace' => '<API key>\Hydrator',
'default_db' => 'default_db',
'filters' => array(), // array('filterName' => 'BSON\Filter\Class')
// custom types
'types' => array(
'CustomType' => '<API key>\Assets\CustomType'
),
'<API key>' => 'stdClass'
)
)
)
),
$logger,
$metadataCache,
$mappingDriver
);
$factory = new <API key>('odm_test');
$config = $factory->createService($serviceLocator);
$this->assertInstanceOf('Doctrine\ODM\MongoDB\Configuration', $config);
$this->assertNotNull($config->getLoggerCallable());
$this->assertSame($metadataCache, $config-><API key>());
$this->assertSame($mappingDriver, $config-><API key>());
$this->assertInstanceOf(
'<API key>\Assets\CustomType',
\Doctrine\ODM\MongoDB\Types\Type::getType('CustomType')
);
}
}
|
.date-menu {
background-color: #fcfcfc;
height: 59px;
border-bottom: 1px solid #eee;
}
.date-menu-contents {
@mixin content-padding;
display: flex;
justify-content: space-between;
align-items: center;
height: 59px;
}
.<API key> {
height: 20px;
line-height: 20px;
}
.date-menu-next,
.date-menu-prev {
color: #8f8f8f;
text-decoration: none;
}
.<API key> {
margin-right: 5px;
display: inline-block;
}
.<API key> {
pointer-events: none;
color: #ccc;
}
|
package main
import (
"reflect"
"strconv"
"unsafe"
"github.com/STNS/STNS/stns"
"github.com/STNS/libnss_stns/libstns"
)
/*
#include <grp.h>
#include <sys/types.h>
*/
import "C"
type Group struct {
grp *C.struct_group
result **C.struct_group
}
func (s Group) Set(groups stns.Attributes) int {
for n, g := range groups {
if g.ID != 0 {
s.grp.gr_gid = C.__gid_t(g.ID)
s.grp.gr_name = C.CString(n)
s.grp.gr_passwd = C.CString("x")
if g.Group != nil && !reflect.ValueOf(g.Group).IsNil() {
work := make([]*C.char, len(g.Users)+1)
if len(g.Users) > 0 {
for i, u := range g.Users {
work[i] = C.CString(u)
}
}
s.grp.gr_mem = (**C.char)(unsafe.Pointer(&work[0]))
} else {
work := make([]*C.char, 1)
s.grp.gr_mem = (**C.char)(unsafe.Pointer(&work[0]))
}
s.result = &s.grp
return libstns.NSS_STATUS_SUCCESS
}
}
return libstns.NSS_STATUS_NOTFOUND
}
//export <API key>
func <API key>(name *C.char, grp *C.struct_group, buffer *C.char, bufsize C.size_t, result **C.struct_group) C.int {
g := Group{grp, result}
return set(grpNss, g, "name", C.GoString(name))
}
//export <API key>
func <API key>(gid C.__gid_t, grp *C.struct_group, buffer *C.char, bufsize C.size_t, result **C.struct_group) C.int {
g := Group{grp, result}
return set(grpNss, g, "id", strconv.Itoa(int(gid)))
}
//export _nss_stns_setgrent
func _nss_stns_setgrent() C.int {
return initList(grpNss, libstns.NSS_LIST_PRESET)
}
//export _nss_stns_endgrent
func _nss_stns_endgrent() {
initList(grpNss, libstns.NSS_LIST_PURGE)
}
//export <API key>
func <API key>(grp *C.struct_group, buffer *C.char, bufsize C.size_t, result **C.struct_group) C.int {
g := Group{grp, result}
return setByList(grpNss, g)
}
|
const LogTestPlugin = require("../../helpers/LogTestPlugin");
/** @type {import("../../../").Configuration} */
module.exports = {
mode: "production",
entry: "./index",
stats: "normal",
plugins: [new LogTestPlugin()]
};
|
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
namespace NetOffice.DeveloperToolbox.Utils.Registry
{
public class UtilsRegistryEntry
{
#region Fields
private UtilsRegistryKey _parent;
private string _valueName;
private <API key> _type;
#endregion
#region Construction
internal UtilsRegistryEntry(UtilsRegistryKey parent, string valueName)
{
_parent = parent;
_valueName = valueName;
_type = <API key>.Normal;
}
internal UtilsRegistryEntry(UtilsRegistryKey parent, string valueName, <API key> type)
{
_parent = parent;
_valueName = valueName;
_type = type;
}
#endregion
#region Properties
public <API key> Type
{
get
{
return _type;
}
}
public string Name
{
get
{
if(string.IsNullOrEmpty(_valueName))
return "(Standard)";
else
return _valueName;
}
set
{
RegistryKey key = _parent.Open(true);
RegistryValueKind regKind = key.GetValueKind(_valueName);
object regValue = key.GetValue(_valueName);
key.DeleteValue(_valueName);
key.SetValue(value, regValue, regKind);
key.Close();
_valueName = value;
}
}
public object Value
{
get
{
if (_type == <API key>.Faked)
return null;
RegistryKey key = _parent.Open();
object regValue = key.GetValue(_valueName);
key.Close();
return regValue;
}
set
{
if (_type == <API key>.Faked)
{
RegistryKey key = _parent.Open(true);
key.SetValue(_valueName, value, ValueKind);
key.Close();
_type = <API key>.Default;
}
else
{
RegistryKey key = _parent.Open(true);
key.SetValue(_valueName, value, ValueKind);
key.Close();
}
}
}
public RegistryValueKind ValueKind
{
get
{
if (_type == <API key>.Faked)
return RegistryValueKind.String;
RegistryKey key = _parent.Open();
RegistryValueKind kind = key.GetValueKind(_valueName);
key.Close();
return kind;
}
}
#endregion
#region Methods
public static string <API key>(byte[] byteArray)
{
StringBuilder builder = new StringBuilder(byteArray.Length * 2);
foreach (byte value in byteArray)
{
builder.AppendFormat("{0:X2}", value);
builder.Append(" ");
}
return builder.ToString();
}
public static string ShiftHexValue(string value)
{
int lenght = value.Length;
if ((10 - lenght) >= 2)
value = "0x" + value;
lenght = value.Length;
if ((10 - lenght) > 0)
{
for (int i = 0; i < (10 - lenght); i++)
{
string first = value.Substring(0, 2);
string last = value.Substring(2);
value = first + "0" + last;
}
}
return value;
}
public string GetValue(int lcid = 1033)
{
RegistryValueKind kind = ValueKind;
switch (kind)
{
case RegistryValueKind.DWord:
case RegistryValueKind.QWord:
return ShiftHexValue(String.Format("{0:x4}", Value)) + " (" + Convert.ToString(Value) + ")";
case RegistryValueKind.Binary:
return <API key>((Value as byte[])).ToLower();
case RegistryValueKind.ExpandString:
case RegistryValueKind.MultiString:
case RegistryValueKind.String:
case RegistryValueKind.Unknown:
if (_type == <API key>.Faked)
return lcid == 1033 ? "(Value not set)" : "(Wert nicht gesetzt)";
else if ((_type == <API key>.Default) && (null == Value))
return lcid == 1033 ? "(Value not set)" : "(Wert nicht gesetzt)";
return Value as string;
default:
throw new ArgumentException(kind.ToString() + " is out of range");
}
}
public void Delete()
{
RegistryKey key = _parent.Open(true);
key.DeleteValue(_valueName);
key.Close();
}
#endregion
#region Static Methods
private static byte[] StringToByteArray(string str)
{
if (null == str)
return null;
System.Text.UnicodeEncoding enc = new System.Text.UnicodeEncoding();
return enc.GetBytes(str);
}
private static string ByteArrayToString(byte[] arr)
{
if (null == arr)
return null;
System.Text.UnicodeEncoding enc = new System.Text.UnicodeEncoding();
return enc.GetString(arr);
}
#endregion
#region Overrides
public override string ToString()
{
return String.Format("UtilsRegistryEntry {0}", Name);
}
#endregion
}
}
|
import { expect } from 'chai'
import browser from '../../src/util/browser'
describe('util (node)', () => {
describe('browser', () => {
it('is false', () => {
expect(browser).to.be.false
})
})
})
|
define(function(require, exports){
exports.permute1 = function(x){
return mod((34.0 * x + 1.0) * x, 289.0)
}
exports.permute3 = function(x){
return mod((34.0 * x + 1.0) * x, 289.0)
}
exports.permute4 = function(x){
return mod((34.0 * x + 1.0) * x, 289.0)
}
exports.isqrtT1 = function(r){
return 1.79284291400159 - 0.85373472095314 * r
}
exports.isqrtT4 = function(r){
return vec4(1.79284291400159 - 0.85373472095314 * r)
}
exports.snoise2 = function(x, y){
return snoise2v(vec2(x,y,z))
}
exports.noise2d =
exports.s2d =
exports.snoise2v = function(v){
var C = vec4(0.211324865405187,0.366025403784439,-0.577350269189626,0.024390243902439)
var i = floor(v + dot(v, C.yy) )
var x0 = v - i + dot(i, C.xx)
var i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0)
var x12 = x0.xyxy + C.xxzz
x12.xy -= i1
i = mod(i, 289.0) // Avoid truncation effects in permutation
var p = permute3(permute3(i.y + vec3(0.0, i1.y, 1.0)) + i.x + vec3(0.0, i1.x, 1.0 ))
var m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0)
m = m*m
m = m*m
var x = 2.0 * fract(p * C.www) - 1.0
var h = abs(x) - 0.5
var ox = floor(x + 0.5)
var a0 = x - ox
m *= (1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h ))
var g = vec3()
g.x = a0.x * x0.x + h.x * x0.y
g.yz = a0.yz * x12.xz + h.yz * x12.yw
return 130.0 * dot(m, g)
}
exports.snoise3 = function(x, y, z){
return snoise3v(vec3(x,y,z))
}
exports.noise3d =
exports.snoise3v = function(v){
var C = vec2(1.0/6.0, 1.0/3.0)
var D = vec4(0.0, 0.5, 1.0, 2.0)
// First corner
var i = floor(v + dot(v, C.yyy))
var x0 = v - i + dot(i, C.xxx)
var g = step(x0.yzx, x0.xyz)
var l = 1.0 - g
var i1 = min(g.xyz, l.zxy)
var i2 = max(g.xyz, l.zxy)
var x1 = x0 - i1 + 1.0 * C.xxx
var x2 = x0 - i2 + 2.0 * C.xxx
var x3 = x0 - 1. + 3.0 * C.xxx
// Permutations
i = mod(i, 289.0)
var p = permute4(permute4(permute4(
i.z + vec4(0.0, i1.z, i2.z, 1.0))
+ i.y + vec4(0.0, i1.y, i2.y, 1.0))
+ i.x + vec4(0.0, i1.x, i2.x, 1.0))
// ( N*N points uniformly over a square, mapped onto an octahedron.)
var n_ = 1.0/7.0
var ns = n_ * D.wyz - D.xzx
var j = p - 49.0 * floor(p * ns.z *ns.z)
var x_ = floor(j * ns.z)
var y_ = floor(j - 7.0 * x_)
var x = x_ * ns.x + ns.yyyy
var y = y_ * ns.x + ns.yyyy
var h = 1.0 - abs(x) - abs(y)
var b0 = vec4( x.xy, y.xy )
var b1 = vec4( x.zw, y.zw )
var s0 = floor(b0)*2.0 + 1.0
var s1 = floor(b1)*2.0 + 1.0
var sh = -step(h, vec4(0.0))
var a0 = b0.xzyw + s0.xzyw*sh.xxyy
var a1 = b1.xzyw + s1.xzyw*sh.zzww
var p0 = vec3(a0.xy, h.x)
var p1 = vec3(a0.zw, h.y)
var p2 = vec3(a1.xy, h.z)
var p3 = vec3(a1.zw, h.w)
//Normalise gradients
var norm = isqrtT4(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)))
p0 *= norm.x;
p1 *= norm.y;
p2 *= norm.z;
p3 *= norm.w;
// Mix final noise value
var m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0)
m = m * m
return 42.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1),
dot(p2,x2), dot(p3,x3) ) )
}
exports.snoise4_g = function(j, ip){
var p = vec4()
p.xyz = floor( fract (vec3(j) * ip.xyz) * 7.0) * ip.z - 1.0
p.w = 1.5 - dot(abs(p.xyz), vec3(1.0,1.0,1.0))
var s = vec4(lessThan(p, vec4(0.0)))
p.xyz = p.xyz + (s.xyz*2.0 - 1.0) * s.www
return p
}
exports.snoise4 = function(x, y, z, w){
return snoise4v(vec4(x,y,z,w))
}
exports.snoise4v = function(v){
var C = vec4(0.138196601125011,0.276393202250021,0.414589803375032,-0.447213595499958)
// First corner
var i = floor(v + dot(v, vec4(0.309016994374947451)) )
var x0 = v - i + dot(i, C.xxxx)
var i0 = vec4()
var isX = step( x0.yzw, x0.xxx )
var isYZ = step( x0.zww, x0.yyz )
i0.x = isX.x + isX.y + isX.z
i0.yzw = 1.0 - isX
i0.y += isYZ.x + isYZ.y
i0.zw += 1.0 - isYZ.xy
i0.z += isYZ.z
i0.w += 1.0 - isYZ.z
var i3 = clamp( i0, 0.0, 1.0 )
var i2 = clamp( i0-1.0, 0.0, 1.0 )
var i1 = clamp( i0-2.0, 0.0, 1.0 )
var x1 = x0 - i1 + C.xxxx
var x2 = x0 - i2 + C.yyyy
var x3 = x0 - i3 + C.zzzz
var x4 = x0 + C.wwww
// Permutations
i = mod(i, 289.0 )
var j0 = permute1( permute1( permute1( permute1(i.w) + i.z) + i.y) + i.x)
var j1 = permute4( permute4( permute4( permute4(
i.w + vec4(i1.w, i2.w, i3.w, 1.0 ))
+ i.z + vec4(i1.z, i2.z, i3.z, 1.0 ))
+ i.y + vec4(i1.y, i2.y, i3.y, 1.0 ))
+ i.x + vec4(i1.x, i2.x, i3.x, 1.0 ))
// Gradients: 7x7x6 points over a cube, mapped onto a 4-cross polytope
// 7*7*6 = 294, which is close to the ring size 17*17 = 289.
var ip = vec4(1.0/294.0, 1.0/49.0, 1.0/7.0, 0.0)
var p0 = snoise4_g(j0, ip)
var p1 = snoise4_g(j1.x, ip)
var p2 = snoise4_g(j1.y, ip)
var p3 = snoise4_g(j1.z, ip)
var p4 = snoise4_g(j1.w, ip)
// Normalise gradients
var nr = isqrtT4(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)))
p0 *= nr.x
p1 *= nr.y
p2 *= nr.z
p3 *= nr.w
p4 *= isqrtT1(dot(p4,p4))
// Mix contributions from the five corners
var m0 = max(0.6 - vec3(dot(x0,x0), dot(x1,x1), dot(x2,x2)), 0.0)
var m1 = max(0.6 - vec2(dot(x3,x3), dot(x4,x4)), 0.0)
m0 = m0 * m0
m1 = m1 * m1
return 49.0 * (dot(m0*m0, vec3(dot( p0, x0 ), dot(p1, x1), dot(p2, x2)))
+ dot(m1*m1, vec2( dot(p3, x3), dot(p4, x4))))
}
exports.cell2v = function(v){
return cell3v(vec3(v.x, v.y,0))
}
exports.cell3v = function(P){
var K = 0.142857142857
var Ko = 0.428571428571 // 1/2-K/2
var K2 = 0.020408163265306 // 1/(7*7)
var Kz = 0.166666666667
var Kzo = 0.416666666667 // 1/2-1/6*2
var ji = 0.8 // smaller jitter gives less errors in F2
var Pi = mod(floor(P), 289.0)
var Pf = fract(P)
var Pfx = Pf.x + vec4(0.0, -1.0, 0.0, -1.0)
var Pfy = Pf.y + vec4(0.0, 0.0, -1.0, -1.0)
var p = permute4(Pi.x + vec4(0.0, 1.0, 0.0, 1.0))
p = permute4(p + Pi.y + vec4(0.0, 0.0, 1.0, 1.0))
var p1 = permute4(p + Pi.z)
var p2 = permute4(p + Pi.z + vec4(1.0))
var ox1 = fract(p1*K) - Ko
var oy1 = mod(floor(p1*K), 7.0)*K - Ko
var oz1 = floor(p1*K2)*Kz - Kzo // p1 < 289 guaranteed
var ox2 = fract(p2*K) - Ko
var oy2 = mod(floor(p2*K), 7.0)*K - Ko
var oz2 = floor(p2*K2)*Kz - Kzo
var dx1 = Pfx + ji*ox1
var dy1 = Pfy + ji*oy1
var dz1 = Pf.z + ji*oz1
var dx2 = Pfx + ji*ox2
var dy2 = Pfy + ji*oy2
var dz2 = Pf.z - 1.0 + ji*oz2
var d1 = dx1 * dx1 + dy1 * dy1 + dz1 * dz1
var d2 = dx2 * dx2 + dy2 * dy2 + dz2 * dz2
var d = min(d1,d2) // F1 is now in d
d2 = max(d1,d2) // Make sure we keep all candidates for F2
d.xy = (d.x < d.y) ? d.xy : d.yx // Swap smallest to d.x
d.xz = (d.x < d.z) ? d.xz : d.zx
d.xw = (d.x < d.w) ? d.xw : d.wx // F1 is now in d.x
d.yzw = min(d.yzw, d2.yzw) // F2 now not in d2.yzw
d.y = min(d.y, d.z) // nor in d.z
d.y = min(d.y, d.w) // nor in d.w
d.y = min(d.y, d2.x) // F2 is now in d.y
return sqrt(d.xy) // F1 and F2
},
exports.cell3w = function(P){
var K = 0.142857142857
var Ko = 0.428571428571 // 1/2-K/2
var K2 = 0.020408163265306// 1/(7*7)
var Kz = 0.166666666667
var Kzo = 0.416666666667// 1/2-1/6*2
var ji = 1.0// smaller jitter gives more regular pattern
var Pi = mod(floor(P), 289.0)
var Pf = fract(P) - 0.5
var Pfx = Pf.x + vec3(1.0, 0.0, -1.0)
var Pfy = Pf.y + vec3(1.0, 0.0, -1.0)
var Pfz = Pf.z + vec3(1.0, 0.0, -1.0)
var p = permute3(Pi.x + vec3(-1.0, 0.0, 1.0))
var p1 = permute3(p + Pi.y - 1.0)
var p2 = permute3(p + Pi.y)
var p3 = permute3(p + Pi.y + 1.0)
var p11 = permute3(p1 + Pi.z - 1.0)
var p12 = permute3(p1 + Pi.z)
var p13 = permute3(p1 + Pi.z + 1.0)
var p21 = permute3(p2 + Pi.z - 1.0)
var p22 = permute3(p2 + Pi.z)
var p23 = permute3(p2 + Pi.z + 1.0)
var p31 = permute3(p3 + Pi.z - 1.0)
var p32 = permute3(p3 + Pi.z)
var p33 = permute3(p3 + Pi.z + 1.0)
var ox11 = fract(p11*K) - Ko
var oy11 = mod(floor(p11*K), 7.0)*K - Ko
var oz11 = floor(p11*K2)*Kz - Kzo // p11 < 289 guaranteed
var ox12 = fract(p12*K) - Ko
var oy12 = mod(floor(p12*K), 7.0)*K - Ko
var oz12 = floor(p12*K2)*Kz - Kzo
var ox13 = fract(p13*K) - Ko
var oy13 = mod(floor(p13*K), 7.0)*K - Ko
var oz13 = floor(p13*K2)*Kz - Kzo
var ox21 = fract(p21*K) - Ko
var oy21 = mod(floor(p21*K), 7.0)*K - Ko
var oz21 = floor(p21*K2)*Kz - Kzo
var ox22 = fract(p22*K) - Ko
var oy22 = mod(floor(p22*K), 7.0)*K - Ko
var oz22 = floor(p22*K2)*Kz - Kzo
var ox23 = fract(p23*K) - Ko
var oy23 = mod(floor(p23*K), 7.0)*K - Ko
var oz23 = floor(p23*K2)*Kz - Kzo
var ox31 = fract(p31*K) - Ko
var oy31 = mod(floor(p31*K), 7.0)*K - Ko
var oz31 = floor(p31*K2)*Kz - Kzo
var ox32 = fract(p32*K) - Ko
var oy32 = mod(floor(p32*K), 7.0)*K - Ko
var oz32 = floor(p32*K2)*Kz - Kzo
var ox33 = fract(p33*K) - Ko
var oy33 = mod(floor(p33*K), 7.0)*K - Ko
var oz33 = floor(p33*K2)*Kz - Kzo
var dx11 = Pfx + ji*ox11
var dy11 = Pfy.x + ji*oy11
var dz11 = Pfz.x + ji*oz11
var dx12 = Pfx + ji*ox12
var dy12 = Pfy.x + ji*oy12
var dz12 = Pfz.y + ji*oz12
var dx13 = Pfx + ji*ox13
var dy13 = Pfy.x + ji*oy13
var dz13 = Pfz.z + ji*oz13
var dx21 = Pfx + ji*ox21
var dy21 = Pfy.y + ji*oy21
var dz21 = Pfz.x + ji*oz21
var dx22 = Pfx + ji*ox22
var dy22 = Pfy.y + ji*oy22
var dz22 = Pfz.y + ji*oz22
var dx23 = Pfx + ji*ox23
var dy23 = Pfy.y + ji*oy23
var dz23 = Pfz.z + ji*oz23
var dx31 = Pfx + ji*ox31
var dy31 = Pfy.z + ji*oy31
var dz31 = Pfz.x + ji*oz31
var dx32 = Pfx + ji*ox32
var dy32 = Pfy.z + ji*oy32
var dz32 = Pfz.y + ji*oz32
var dx33 = Pfx + ji*ox33
var dy33 = Pfy.z + ji*oy33
var dz33 = Pfz.z + ji*oz33
var d11 = dx11 * dx11 + dy11 * dy11 + dz11 * dz11
var d12 = dx12 * dx12 + dy12 * dy12 + dz12 * dz12
var d13 = dx13 * dx13 + dy13 * dy13 + dz13 * dz13
var d21 = dx21 * dx21 + dy21 * dy21 + dz21 * dz21
var d22 = dx22 * dx22 + dy22 * dy22 + dz22 * dz22
var d23 = dx23 * dx23 + dy23 * dy23 + dz23 * dz23
var d31 = dx31 * dx31 + dy31 * dy31 + dz31 * dz31
var d32 = dx32 * dx32 + dy32 * dy32 + dz32 * dz32
var d33 = dx33 * dx33 + dy33 * dy33 + dz33 * dz33
var d1a = min(d11, d12)
d12 = max(d11, d12)
d11 = min(d1a, d13) // Smallest now not in d12 or d13
d13 = max(d1a, d13)
d12 = min(d12, d13) // 2nd smallest now not in d13
var d2a = min(d21, d22)
d22 = max(d21, d22)
d21 = min(d2a, d23) // Smallest now not in d22 or d23
d23 = max(d2a, d23)
d22 = min(d22, d23) // 2nd smallest now not in d23
var d3a = min(d31, d32)
d32 = max(d31, d32)
d31 = min(d3a, d33) // Smallest now not in d32 or d33
d33 = max(d3a, d33)
d32 = min(d32, d33) // 2nd smallest now not in d33
var da = min(d11, d21)
d21 = max(d11, d21)
d11 = min(da, d31) // Smallest now in d11
d31 = max(da, d31) // 2nd smallest now not in d31
d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx
d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx // d11.x now smallest
d12 = min(d12, d21) // 2nd smallest now not in d21
d12 = min(d12, d22) // nor in d22
d12 = min(d12, d31) // nor in d31
d12 = min(d12, d32) // nor in d32
d11.yz = min(d11.yz, d12.xy) // nor in d12.yz
d11.y = min(d11.y, d12.z) // Only two more to go
d11.y = min(d11.y, d11.z) // Done! (Phew!)
return sqrt(d11.xy) // F1, F2
}
})
|
#pragma once
namespace Game
{
namespace Light
{
constexpr unsigned int MAX_POINT_LIGHT_NUM = 384U;
constexpr unsigned int MAX_LINE_LIGHT_NUM = 64U;
constexpr unsigned int MAX_SPOT_LIGHT_NUM = 16U;
}
}
|
<?php
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
use Symfony\Bridge\Doctrine\Form\ChoiceList\<API key>;
use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\Version;
class <API key> extends \<API key>
{
/**
* @expectedException \Symfony\Component\Form\Exception\<API key>
* @group legacy
*/
public function <API key>()
{
new <API key>(new \stdClass());
}
/**
* @expectedException \Symfony\Component\Form\Exception\<API key>
* @group legacy
*/
public function <API key>()
{
$closure = function () {};
new <API key>($closure);
}
public function <API key>()
{
$this->checkIdentifierType('Symfony\Bridge\Doctrine\Tests\Fixtures\<API key>', Connection::PARAM_STR_ARRAY);
}
public function <API key>()
{
$this->checkIdentifierType('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity', Connection::PARAM_INT_ARRAY);
}
protected function checkIdentifierType($classname, $expectedType)
{
$em = DoctrineTestHelper::<API key>();
$query = $this->getMockBuilder('QueryMock')
->setMethods(array('setParameter', 'getResult', 'getSql', '_doExecute'))
->getMock();
$query->expects($this->once())
->method('setParameter')
->with('<API key>', array(1, 2), $expectedType)
->willReturn($query);
$qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
->setConstructorArgs(array($em))
->setMethods(array('getQuery'))
->getMock();
$qb->expects($this->once())
->method('getQuery')
->willReturn($query);
$qb->select('e')
->from($classname, 'e');
$loader = new <API key>($qb);
$loader->getEntitiesByIds('id', array(1, 2));
}
public function <API key>()
{
$em = DoctrineTestHelper::<API key>();
$query = $this->getMockBuilder('QueryMock')
->setMethods(array('setParameter', 'getResult', 'getSql', '_doExecute'))
->getMock();
$query->expects($this->once())
->method('setParameter')
->with('<API key>', array(1, 2, 3), Connection::PARAM_INT_ARRAY)
->willReturn($query);
$qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
->setConstructorArgs(array($em))
->setMethods(array('getQuery'))
->getMock();
$qb->expects($this->once())
->method('getQuery')
->willReturn($query);
$qb->select('e')
->from('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity', 'e');
$loader = new <API key>($qb);
$loader->getEntitiesByIds('id', array(1, '', 2, 3, 'foo'));
}
public function <API key>()
{
if (Version::compare('2.5.0') > 0) {
$this->markTestSkipped('Applicable only for Doctrine >= 2.5.0');
return;
}
$em = DoctrineTestHelper::<API key>();
$query = $this->getMockBuilder('QueryMock')
->setMethods(array('setParameter', 'getResult', 'getSql', '_doExecute'))
->getMock();
$query->expects($this->once())
->method('setParameter')
->with('<API key>', array(1, 2, 3), Connection::PARAM_INT_ARRAY)
->willReturn($query);
$qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
->setConstructorArgs(array($em))
->setMethods(array('getQuery'))
->getMock();
$qb->expects($this->once())
->method('getQuery')
->willReturn($query);
$qb->select('e')
->from('Symfony\Bridge\Doctrine\Tests\Fixtures\<API key>', 'e');
$loader = new <API key>($qb);
$loader->getEntitiesByIds('id.value', array(1, '', 2, 3, 'foo'));
}
}
|
var $ = require('jquery');
var keymaster = require('keymaster');
var ChartEditor = require('./<API key>.js');
var DbInfo = require('./component-db-info.js');
var AceSqlEditor = require('./<API key>.js');
var DataGrid = require('./component-data-grid.js');
var QueryEditor = function () {
var chartEditor = new ChartEditor();
var dbInfo = new DbInfo();
var aceSqlEditor = new AceSqlEditor("ace-editor");
var dataGrid = new DataGrid();
function runQuery () {
$('#server-run-time').html('');
$('#rowcount').html('');
dataGrid.emptyDataGrid();
var data = {
queryText: aceSqlEditor.<API key>(),
connectionId: $('#connection').val(),
cacheKey: $('#cache-key').val(),
queryName: getQueryName()
};
dataGrid.startRunningTimer();
$.ajax({
type: "POST",
url: "/run-query",
data: data
}).done(function (data) {
chartEditor.setData(data);
// TODO - if vis tab is active, render chart
dataGrid.stopRunningTimer();
$('#server-run-time').html(data.serverMs/1000 + " sec.");
if (data.success) {
$('.hide-while-running').show();
if (data.incomplete) {
$('.<API key>').removeClass("hidden");
} else {
$('.<API key>').addClass("hidden");
}
dataGrid.renderGridData(data);
} else {
dataGrid.renderError(data.error);
}
}).fail(function () {
dataGrid.stopRunningTimer();
dataGrid.renderError("Something is broken :(");
});
}
function getQueryName () {
return $('#header-query-name').val();
}
function getQueryTags () {
return $.map($('#tags').val().split(','), $.trim);
}
function saveQuery () {
var $queryId = $('#query-id');
var query = {
name: getQueryName(),
queryText: aceSqlEditor.getEditorText(),
tags: getQueryTags(),
connectionId: dbInfo.getConnectionId(),
chartConfiguration: chartEditor.<API key>()
};
$('#btn-save-result').text('saving...').show();
$.ajax({
type: "POST",
url: "/queries/" + $queryId.val(),
data: query
}).done(function (data) {
if (data.success) {
window.history.replaceState({}, "query " + data.query._id, "/queries/" + data.query._id);
$queryId.val(data.query._id);
$('#btn-save-result').removeClass('label-info').addClass('label-success').text('Success');
setTimeout(function () {
$('#btn-save-result').fadeOut(400, function () {
$('#btn-save-result').removeClass('label-success').addClass('label-info').text('');
});
}, 1000);
} else {
$('#btn-save-result').removeClass('label-info').addClass('label-danger').text('Failed');
}
}).fail(function () {
alert('ajax fail');
});
}
$('#btn-save').click(function (event) {
event.preventDefault();
event.stopPropagation();
saveQuery();
});
$('#btn-run-query').click(function (event) {
event.preventDefault();
event.stopPropagation();
runQuery();
});
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
// if shown tab was the chart tab, rerender the chart
// e.target is the activated tab
if (e.target.getAttribute("href") == "#<API key>") {
chartEditor.rerenderChart();
} else if (e.target.getAttribute("href") == "#tab-content-sql") {
dataGrid.resize();
}
});
var $queryId = $('#query-id');
$.ajax({
type: "GET",
url: "/queries/" + $queryId.val() + "?format=json"
}).done(function (data) {
console.log(data);
chartEditor.<API key>(data.chartConfiguration);
}).fail(function () {
alert('Failed to get additional Query info');
});
var Bloodhound = require('Bloodhound');
var bloodhoundTags = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: '/tags', // array of tagnames
ttl: 0,
filter: function(list) {
return $.map(list, function(tag) {
return { name: tag }; });
}
}
});
bloodhoundTags.initialize();
$('#tags').tagsinput({
typeaheadjs: {
//name: 'tags',
displayKey: 'name',
valueKey: 'name',
source: bloodhoundTags.ttAdapter()
}
});
// keymaster doesn't fire on input/textarea events by default
// since we are only using command/ctrl shortcuts,
// we want the event to fire all the time for any element
keymaster.filter = function (event) {
return true;
};
keymaster('ctrl+s, command+s', function() {
saveQuery();
return false;
});
keymaster('ctrl+r, command+r, ctrl+e, command+e', function() {
runQuery();
return false;
});
};
module.exports = function () {
if ($('#ace-editor').length) {
new QueryEditor();
}
};
|
package PracticeLeetCode;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
public class _127WordLadder {
psvm
}
|
<?php
namespace Illuminate\Tests\Integration\Database\<API key>;
use DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Tests\Integration\Database\DatabaseTestCase;
/**
* @group integration
*/
class <API key> extends DatabaseTestCase
{
protected function setUp(): void
{
parent::setUp();
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
});
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('parent_id')->nullable();
$table->unsignedInteger('post_id');
});
Post::create();
Comment::create(['parent_id' => null, 'post_id' => 1]);
Comment::create(['parent_id' => 1, 'post_id' => 1]);
}
public function testLoadMissing()
{
$post = Post::with('comments')->first();
DB::enableQueryLog();
$post->loadMissing('comments.parent');
$this->assertCount(1, DB::getQueryLog());
$this->assertTrue($post->comments[0]->relationLoaded('parent'));
}
}
class Comment extends Model
{
public $timestamps = false;
protected $guarded = ['id'];
public function parent()
{
return $this->belongsTo(Comment::class);
}
}
class Post extends Model
{
public $timestamps = false;
public function comments()
{
return $this->hasMany(Comment::class);
}
}
|
import glob
import logging
import os
import subprocess
from plugins import BaseAligner
from yapsy.IPlugin import IPlugin
from assembly import get_qual_encoding
class Bowtie2Aligner(BaseAligner, IPlugin):
def run(self):
"""
Map READS to CONTIGS and return alignment.
Set MERGED_PAIR to True if reads[1] is a merged
paired end file
"""
contig_file = self.data.contigfiles[0]
reads = self.data.readfiles
## Index contigs
prefix = os.path.join(self.outpath, 'bt2')
cmd_args = [self.build_bin, '-f', contig_file, prefix]
self.arast_popen(cmd_args, overrides=False)
Align reads
bamfiles = []
for i, readset in enumerate(self.data.readsets):
samfile = os.path.join(self.outpath, 'align.sam')
reads = readset.files
cmd_args = [self.executable, '-x', prefix, '-S', samfile,
'-p', self.<API key>]
if len(reads) == 2:
cmd_args += ['-1', reads[0], '-2', reads[1]]
elif len(reads) == 1:
cmd_args += ['-U', reads[0]]
else:
raise Exception('Bowtie plugin error')
self.arast_popen(cmd_args, overrides=False)
if not os.path.exists(samfile):
raise Exception('Unable to complete alignment')
## Convert to BAM
bamfile = samfile.replace('.sam', '.bam')
cmd_args = ['samtools', 'view',
'-bSho', bamfile, samfile]
self.arast_popen(cmd_args)
bamfiles.append(bamfile)
Merge samfiles if multiple
if len(bamfiles) > 1:
bamfile = os.path.join(self.outpath, '{}_{}.bam'.format(os.path.basename(contig_file), i))
self.arast_popen(['samtools', 'merge', bamfile] + bamfiles)
if not os.path.exists(bamfile):
raise Exception('Unable to complete alignment')
else:
bamfile = bamfiles[0]
if not os.path.exists(bamfile):
raise Exception('Unable to complete alignment')
## Convert back to sam
samfile = bamfile.replace('.bam', '.sam')
self.arast_popen(['samtools', 'view', '-h', '-o', samfile, bamfile])
return {'alignment': samfile,
'alignment_bam': bamfile}
|
namespace EventCloud.Events.Dtos
{
public class GetEventListInput
{
public bool <API key> { get; set; }
}
}
|
// # Frontend Route tests
// As it stands, these tests depend on the database, and as such are integration tests.
// Mocking out the models to not touch the DB would turn these into unit tests, and should probably be done in future,
// But then again testing real code, rather than mock code, might be more useful...
const should = require('should');
const sinon = require('sinon');
const supertest = require('supertest');
const moment = require('moment');
const cheerio = require('cheerio');
const _ = require('lodash');
const testUtils = require('../../utils');
const configUtils = require('../../utils/configUtils');
const urlUtils = require('../../utils/urlUtils');
const config = require('../../../core/shared/config');
const settingsCache = require('../../../core/server/services/settings/cache');
const origCache = _.cloneDeep(settingsCache);
const ghost = testUtils.startGhost;
let request;
describe('Frontend Routing', function () {
function doEnd(done) {
return function (err, res) {
if (err) {
return done(err);
}
should.not.exist(res.headers['x-cache-invalidate']);
should.not.exist(res.headers['X-CSRF-Token']);
should.not.exist(res.headers['set-cookie']);
should.exist(res.headers.date);
done();
};
}
function addPosts(done) {
testUtils.clearData().then(function () {
return testUtils.initData();
}).then(function () {
return testUtils.fixtures.insertPostsAndTags();
}).then(function () {
done();
});
}
afterEach(function () {
sinon.restore();
});
before(function () {
return ghost()
.then(function () {
request = supertest.agent(config.get('url'));
});
});
describe('Test with Initial Fixtures', function () {
describe('Error', function () {
it('should 404 for unknown post with invalid characters', function (done) {
request.get('/$pec+acular~/')
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(404)
.expect(/Page not found/)
.end(doEnd(done));
});
it('should 404 for unknown frontend route', function (done) {
request.get('/spectacular/marvellous/')
.set('Accept', 'application/json')
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(404)
.expect(/Page not found/)
.end(doEnd(done));
});
it('should 404 for encoded char not 301 from uncapitalise', function (done) {
request.get('/|/')
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(404)
.expect(/Page not found/)
.end(doEnd(done));
});
});
describe('Default Redirects (clean URLS)', function () {
it('Single post should redirect without slash', function (done) {
request.get('/welcome')
.expect('Location', '/welcome/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
it('Single post should redirect uppercase', function (done) {
request.get('/Welcome/')
.expect('Location', '/welcome/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
it('Single post should sanitize double slashes when redirecting uppercase', function (done) {
request.get('///Google.com/')
.expect('Location', '/google.com/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
it('AMP post should redirect without slash', function (done) {
request.get('/welcome/amp')
.expect('Location', '/welcome/amp/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
it('AMP post should redirect uppercase', function (done) {
request.get('/Welcome/AMP/')
.expect('Location', '/welcome/amp/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
});
});
describe('Test with added posts', function () {
before(addPosts);
describe('Static page', function () {
it('should respond with html', function (done) {
request.get('/static-page-test/')
.expect('Content-Type', /html/)
.expect('Cache-Control', testUtils.cacheRules.public)
.expect(200)
.end(function (err, res) {
const $ = cheerio.load(res.text);
should.not.exist(res.headers['x-cache-invalidate']);
should.not.exist(res.headers['X-CSRF-Token']);
should.not.exist(res.headers['set-cookie']);
should.exist(res.headers.date);
$('title').text().should.equal('This is a static page');
$('body.page-template').length.should.equal(1);
$('article.post').length.should.equal(1);
doEnd(done)(err, res);
});
});
it('should redirect without slash', function (done) {
request.get('/static-page-test')
.expect('Location', '/static-page-test/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
describe('edit', function () {
it('should redirect without slash', function (done) {
request.get('/static-page-test/edit')
.expect('Location', '/static-page-test/edit/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
it('should redirect to editor', function (done) {
request.get('/static-page-test/edit/')
.expect('Location', /ghost\/#\/editor\/\w+/)
.expect('Cache-Control', testUtils.cacheRules.public)
.expect(302)
.end(doEnd(done));
});
it('should 404 for non-edit parameter', function (done) {
request.get('/static-page-test/notedit/')
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(404)
.expect(/Page not found/)
.end(doEnd(done));
});
});
describe('edit with admin redirects disabled', function () {
before(function (done) {
configUtils.set('admin:redirects', false);
ghost({forceStart: true})
.then(function () {
request = supertest.agent(config.get('url'));
addPosts(done);
});
});
after(function (done) {
configUtils.restore();
ghost({forceStart: true})
.then(function () {
request = supertest.agent(config.get('url'));
addPosts(done);
});
});
it('should redirect without slash', function (done) {
request.get('/static-page-test/edit')
.expect('Location', '/static-page-test/edit/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
it('should not redirect to editor', function (done) {
request.get('/static-page-test/edit/')
.expect(404)
.expect('Cache-Control', testUtils.cacheRules.private)
.end(doEnd(done));
});
});
describe('amp', function () {
it('should 404 for amp parameter', function (done) {
// NOTE: only post pages are supported so the router doesn't have a way to distinguish if
// the request was done after AMP 'Page' or 'Post'
request.get('/static-page-test/amp/')
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(404)
.expect(/Post not found/)
.end(doEnd(done));
});
});
});
describe('Post preview', function () {
it('should display draft posts accessed via uuid', function (done) {
request.get('/p/<API key>/')
.expect('Content-Type', /html/)
.expect(200)
.end(function (err, res) {
if (err) {
return done(err);
}
const $ = cheerio.load(res.text);
should.not.exist(res.headers['x-cache-invalidate']);
should.not.exist(res.headers['X-CSRF-Token']);
should.not.exist(res.headers['set-cookie']);
should.exist(res.headers.date);
$('title').text().should.equal('Not finished yet');
// @TODO: use theme from fixtures and don't rely on content/themes/casper
// $('.content .post').length.should.equal(1);
// $('.poweredby').text().should.equal('Proudly published with Ghost');
// $('body.post-template').length.should.equal(1);
// $('article.post').length.should.equal(1);
done();
});
});
it('should redirect published posts to their live url', function (done) {
request.get('/p/<API key>/')
.expect(301)
.expect('Location', '/short-and-sweet/')
.expect('Cache-Control', testUtils.cacheRules.year)
.end(doEnd(done));
});
it('404s unknown uuids', function (done) {
request.get('/p/<API key>/')
.expect(404)
.end(doEnd(done));
});
});
describe('Post with Ghost in the url', function () {
// All of Ghost's admin depends on the /ghost/ in the url to work properly
// Badly formed regexs can cause breakage if a post slug starts with the 5 letters ghost
it('should retrieve a blog post with ghost at the start of the url', function (done) {
request.get('/<API key>/')
.expect('Cache-Control', testUtils.cacheRules.public)
.expect(200)
.end(doEnd(done));
});
});
});
describe('Subdirectory (no slash)', function () {
let ghostServer;
before(function () {
configUtils.set('url', 'http://localhost/blog');
urlUtils.<API key>();
return ghost({forceStart: true, subdir: true})
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('server:host') + ':' + config.get('server:port'));
});
});
after(function () {
configUtils.restore();
urlUtils.restore();
});
it('http://localhost should 404', function (done) {
request.get('/')
.expect(404)
.end(doEnd(done));
});
it('http://localhost/ should 404', function (done) {
request.get('/')
.expect(404)
.end(doEnd(done));
});
it('http:
request.get('/blog')
.expect(301)
.expect('Location', '/blog/')
.end(doEnd(done));
});
it('http://localhost/blog/ should 200', function (done) {
request.get('/blog/')
.expect(200)
.end(doEnd(done));
});
it('http:
request.get('/blog/welcome')
.expect(301)
.expect('Location', '/blog/welcome/')
.expect('Cache-Control', testUtils.cacheRules.year)
.end(doEnd(done));
});
it('http://localhost/blog/welcome/ should 200', function (done) {
request.get('/blog/welcome/')
.expect(200)
.end(doEnd(done));
});
it('/blog/tag/getting-started should 301 to /blog/tag/getting-started/', function (done) {
request.get('/blog/tag/getting-started')
.expect(301)
.expect('Location', '/blog/tag/getting-started/')
.expect('Cache-Control', testUtils.cacheRules.year)
.end(doEnd(done));
});
it('/blog/tag/getting-started/ should 200', function (done) {
request.get('/blog/tag/getting-started/')
.expect(200)
.end(doEnd(done));
});
it('/blog/welcome/amp/ should 200', function (done) {
request.get('/blog/welcome/amp/')
.expect(200)
.end(doEnd(done));
});
});
describe('Subdirectory (with slash)', function () {
let ghostServer;
before(function () {
configUtils.set('url', 'http://localhost/blog/');
urlUtils.<API key>();
return ghost({forceStart: true, subdir: true})
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('server:host') + ':' + config.get('server:port'));
});
});
after(function () {
configUtils.restore();
urlUtils.restore();
});
it('http://localhost should 404', function (done) {
request.get('/')
.expect(404)
.end(doEnd(done));
});
it('http://localhost/ should 404', function (done) {
request.get('/')
.expect(404)
.end(doEnd(done));
});
it('/blog should 301 to /blog/', function (done) {
request.get('/blog')
.expect(301)
.expect('Location', '/blog/')
.end(doEnd(done));
});
it('/blog/ should 200', function (done) {
request.get('/blog/')
.expect(200)
.end(doEnd(done));
});
it('/blog/welcome should 301 to /blog/welcome/', function (done) {
request.get('/blog/welcome')
.expect(301)
.expect('Location', '/blog/welcome/')
.expect('Cache-Control', testUtils.cacheRules.year)
.end(doEnd(done));
});
it('/blog/welcome/ should 200', function (done) {
request.get('/blog/welcome/')
.expect(200)
.end(doEnd(done));
});
it('/blog/tag/getting-started should 301 to /blog/tag/getting-started/', function (done) {
request.get('/blog/tag/getting-started')
.expect(301)
.expect('Location', '/blog/tag/getting-started/')
.expect('Cache-Control', testUtils.cacheRules.year)
.end(doEnd(done));
});
it('/blog/tag/getting-started/ should 200', function (done) {
request.get('/blog/tag/getting-started/')
.expect(200)
.end(doEnd(done));
});
it('/blog/welcome/amp/ should 200', function (done) {
request.get('/blog/welcome/amp/')
.expect(200)
.end(doEnd(done));
});
it('should uncapitalise correctly with 301 to subdir', function (done) {
request.get('/blog/AAA/')
.expect('Location', '/blog/aaa/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
});
describe('HTTPS', function () {
let ghostServer;
before(function () {
configUtils.set('url', 'http://localhost:2370/');
urlUtils.<API key>();
return ghost({forceStart: true})
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('server:host') + ':' + config.get('server:port'));
});
});
after(function () {
configUtils.restore();
urlUtils.restore();
});
it('should set links to url over non-HTTPS', function (done) {
request.get('/')
.expect(200)
.expect(/<link rel="canonical" href="http:\/\/localhost:2370\/" \/\>/)
.expect(/<a href="http:\/\/localhost:2370">Ghost<\/a\>/)
.end(doEnd(done));
});
it('should set links over HTTPS besides canonical', function (done) {
request.get('/')
.set('X-Forwarded-Proto', 'https')
.expect(200)
.expect(/<link rel="canonical" href="http:\/\/localhost:2370\/" \/\>/)
.expect(/<a href="https:\/\/localhost:2370">Ghost<\/a\>/)
.end(doEnd(done));
});
});
// TODO: convert to unit tests
describe('Redirects (use redirects.json from test/utils/fixtures/data)', function () {
let ghostServer;
before(function () {
configUtils.set('url', 'http://localhost:2370/');
urlUtils.<API key>();
return ghost({forceStart: true})
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('server:host') + ':' + config.get('server:port'));
});
});
after(function () {
configUtils.restore();
urlUtils.restore();
});
describe('1 case', function () {
it('with trailing slash', function (done) {
request.get('/post/10/a-nice-blog-post')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/a-nice-blog-post');
doEnd(done)(err, res);
});
});
it('without trailing slash', function (done) {
request.get('/post/10/a-nice-blog-post/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/a-nice-blog-post');
doEnd(done)(err, res);
});
});
it('with query params', function (done) {
request.get('/topic?something=good')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/?something=good');
doEnd(done)(err, res);
});
});
it('with query params', function (done) {
request.get('/post/10/a-nice-blog-post?a=b')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/a-nice-blog-post?a=b');
doEnd(done)(err, res);
});
});
it('with case insensitive', function (done) {
request.get('/CaSe-InSeNsItIvE')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/<API key>');
doEnd(done)(err, res);
});
});
it('with case sensitive', function (done) {
request.get('/Case-Sensitive')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/<API key>');
doEnd(done)(err, res);
});
});
it('defaults to case sensitive', function (done) {
request.get('/Default-Sensitive')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/redirected-default');
doEnd(done)(err, res);
});
});
it('should not redirect with case sensitive', function (done) {
request.get('/casE-sensitivE')
.end(function (err, res) {
res.headers.location.should.not.eql('/<API key>');
res.statusCode.should.not.eql(302);
doEnd(done)(err, res);
});
});
it('should not redirect with default case sensitive', function (done) {
request.get('/defaulT-sensitivE')
.end(function (err, res) {
res.headers.location.should.not.eql('/redirected-default');
res.statusCode.should.not.eql(302);
doEnd(done)(err, res);
});
});
});
describe('2 case', function () {
it('with trailing slash', function (done) {
request.get('/my-old-blog-post/')
.expect(301)
.expect('Cache-Control', testUtils.cacheRules.year)
.end(function (err, res) {
res.headers.location.should.eql('/revamped-url/');
doEnd(done)(err, res);
});
});
it('without trailing slash', function (done) {
request.get('/my-old-blog-post')
.expect(301)
.expect('Cache-Control', testUtils.cacheRules.year)
.end(function (err, res) {
res.headers.location.should.eql('/revamped-url/');
doEnd(done)(err, res);
});
});
});
describe('3 case', function () {
it('with trailing slash', function (done) {
request.get('/what/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/what-does-god-say');
doEnd(done)(err, res);
});
});
it('without trailing slash', function (done) {
request.get('/what')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/what-does-god-say');
doEnd(done)(err, res);
});
});
});
describe('4 case', function () {
it('with trailing slash', function (done) {
request.get('/search/label/&&&/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/tag/&&&/');
doEnd(done)(err, res);
});
});
it('without trailing slash', function (done) {
request.get('/search/label/&&&/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/tag/&&&/');
doEnd(done)(err, res);
});
});
});
describe('5 case', function () {
it('with trailing slash', function (done) {
request.get('/topic/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/');
doEnd(done)(err, res);
});
});
it('without trailing slash', function (done) {
request.get('/topic')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/');
doEnd(done)(err, res);
});
});
});
describe('6 case', function () {
it('with trailing slash', function (done) {
request.get('/resources/download/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/shubal-stearns');
doEnd(done)(err, res);
});
});
it('without trailing slash', function (done) {
request.get('/resources/download')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/shubal-stearns');
doEnd(done)(err, res);
});
});
});
describe('7 case', function () {
it('with trailing slash', function (done) {
request.get('/2016/11/welcome.html')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/welcome');
doEnd(done)(err, res);
});
});
});
describe('last case', function () {
it('default', function (done) {
request.get('/prefix/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/blog/');
doEnd(done)(err, res);
});
});
it('with a custom path', function (done) {
request.get('/prefix/expect-redirect')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/blog/expect-redirect');
doEnd(done)(err, res);
});
});
});
describe('external url redirect', function () {
it('with trailing slash', function (done) {
request.get('/external-url/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('https://ghost.org/');
doEnd(done)(err, res);
});
});
it('without trailing slash', function (done) {
request.get('/external-url')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('https://ghost.org/');
doEnd(done)(err, res);
});
});
it('with capturing group', function (done) {
request.get('/external-url/docs')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('https://ghost.org/docs');
doEnd(done)(err, res);
});
});
});
});
describe('Subdirectory redirects (use redirects.json from test/utils/fixtures/data)', function () {
var ghostServer;
before(function () {
configUtils.set('url', 'http://localhost:2370/blog/');
urlUtils.<API key>();
return ghost({forceStart: true, subdir: true})
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('server:host') + ':' + config.get('server:port'));
});
});
after(function () {
configUtils.restore();
urlUtils.restore();
});
describe('internal url redirect', function () {
it('should include the subdirectory', function (done) {
request.get('/blog/my-old-blog-post/')
.expect(301)
.expect('Cache-Control', testUtils.cacheRules.year)
.end(function (err, res) {
res.headers.location.should.eql('/blog/revamped-url/');
doEnd(done)(err, res);
});
});
it('should work with regex "from" redirects', function (done) {
request.get('/blog/capture1/whatever')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/blog/whatever');
doEnd(done)(err, res);
});
});
});
describe('external url redirect', function () {
it('should not include the subdirectory', function (done) {
request.get('/blog/external-url/docs')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('https://ghost.org/docs');
doEnd(done)(err, res);
});
});
});
});
});
|
# wealth-view
Single page application for viewing your financial portfolio
|
require 'mkmf'
extension_name = '<API key>'
dir_config(extension_name)
create_makefile(extension_name)
|
import { browser, by, element } from 'protractor';
describe('App', () => {
beforeEach(() => {
// change hash depending on router LocationStrategy
browser.get('/#/home');
});
it('should have a title', () => {
let subject = browser.getTitle();
let result = 'Chroma An Interactive Palette tool';
expect(subject).toEqual(result);
});
it('should have `your content here` x-large', () => {
let subject = element(by.css('[x-large]')).getText();
let result = 'Your Content Here';
expect(subject).toEqual(result);
});
});
|
"use strict";
var <API key> = require("@babel/runtime/helpers/<API key>");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = <API key>(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M21 5H3c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-2 <API key>.55 0 1-.45 1-1v-3c0-.55-.45-1-1-1v-1c0-1.11-.9-2-2-2-1.11 0-2 .9-2 2v1c-.55 0-1 .45-1 1v3c0 .55.45 1 1 1zm.8-6c0-.66.54-1.2 1.2-1.2s1.2.54 1.2 1.2v1h-2.4v-1z"
}), '<API key>');
exports.default = _default;
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Persistence;
using Umbraco.Web.Models.Trees;
using Umbraco.Web.WebApi.Filters;
using umbraco;
using umbraco.BusinessLogic.Actions;
using System.Globalization;
namespace Umbraco.Web.Trees
{
public abstract class <API key> : TreeController
{
#region Actions
<summary>
Gets an individual tree node
</summary>
<param name="id"></param>
<param name="queryStrings"></param>
<returns></returns>
[<API key>("queryStrings")]
public TreeNode GetTreeNode(string id, FormDataCollection queryStrings)
{
int asInt;
Guid asGuid = Guid.Empty;
if (int.TryParse(id, out asInt) == false)
{
if (Guid.TryParse(id, out asGuid) == false)
{
throw new <API key>(Request.CreateResponse(HttpStatusCode.NotFound));
}
}
var entity = asGuid == Guid.Empty
? Services.EntityService.Get(asInt, UmbracoObjectType)
: Services.EntityService.GetByKey(asGuid, UmbracoObjectType);
if (entity == null)
{
throw new <API key>(Request.CreateResponse(HttpStatusCode.NotFound));
}
var node = GetSingleTreeNode(entity, entity.ParentId.ToInvariantString(), queryStrings);
//add the tree alias to the node since it is standalone (has no root for which this normally belongs)
node.AdditionalData["treeAlias"] = TreeAlias;
return node;
}
#endregion
<summary>
Ensure the noAccess metadata is applied for the root node if in dialog mode and the user doesn't have path access to it
</summary>
<param name="queryStrings"></param>
<returns></returns>
protected override TreeNode CreateRootNode(FormDataCollection queryStrings)
{
var node = base.CreateRootNode(queryStrings);
if (IsDialog(queryStrings) && UserStartNodes.Contains(Constants.System.Root) == false)
{
node.AdditionalData["noAccess"] = true;
}
return node;
}
protected abstract TreeNode GetSingleTreeNode(IUmbracoEntity e, string parentId, FormDataCollection queryStrings);
<summary>
Returns a <see cref="TreeNode"/> for the <see cref="IUmbracoEntity"/> and
attaches some meta data to the node if the user doesn't have start node access to it when in dialog mode
</summary>
<param name="e"></param>
<param name="parentId"></param>
<param name="queryStrings"></param>
<returns></returns>
internal TreeNode <API key>(IUmbracoEntity e, string parentId, FormDataCollection queryStrings)
{
bool hasPathAccess;
var <API key> = Security.CurrentUser.<API key>(e, Services.EntityService, RecycleBinId, out hasPathAccess);
if (<API key> == false)
return null;
var treeNode = GetSingleTreeNode(e, parentId, queryStrings);
if (treeNode == null)
{
//the node so we need to return null;
return null;
}
if (hasPathAccess == false)
{
treeNode.AdditionalData["noAccess"] = true;
}
return treeNode;
}
<summary>
Returns the
</summary>
protected abstract int RecycleBinId { get; }
<summary>
Returns true if the recycle bin has items in it
</summary>
protected abstract bool RecycleBinSmells { get; }
<summary>
Returns the user's start node for this tree
</summary>
protected abstract int[] UserStartNodes { get; }
protected virtual TreeNodeCollection PerformGetTreeNodes(string id, FormDataCollection queryStrings)
{
var nodes = new TreeNodeCollection();
var rootIdString = Constants.System.Root.ToString(CultureInfo.InvariantCulture);
var hasAccessToRoot = UserStartNodes.Contains(Constants.System.Root);
var startNodeId = queryStrings.HasKey(<API key>.StartNodeId)
? queryStrings.GetValue<string>(<API key>.StartNodeId)
: string.Empty;
if (string.IsNullOrEmpty(startNodeId) == false && startNodeId != "undefined" && startNodeId != rootIdString)
{
// request has been made to render from a specific, non-root, start node
id = startNodeId;
// ensure that the user has access to that node, otherwise return the empty tree nodes collection
// TODO: in the future we could return a validation statement so we can have some UI to notify the user they don't have access
if (HasPathAccess(id, queryStrings) == false)
{
LogHelper.Warn<<API key>>("User " + Security.CurrentUser.Username + " does not have access to node with id " + id);
return nodes;
}
// if the tree is rendered...
// - in a dialog: render only the children of the specific start node, nothing to do
// - in a section: if the current user's start nodes do not contain the root node, we need
// to include these start nodes in the tree too, to provide some context - i.e. change
// start node back to root node, and then GetChildEntities method will take care of the rest.
if (IsDialog(queryStrings) == false && hasAccessToRoot == false)
id = rootIdString;
}
// get child entities - if id is root, but user's start nodes do not contain the
// root node, this returns the start nodes instead of root's children
var entities = GetChildEntities(id).ToList();
nodes.AddRange(entities.Select(x => <API key>(x, id, queryStrings)).Where(x => x != null));
// if the user does not have access to the root node, what we have is the start nodes,
// but to provide some context we also need to add their topmost nodes when they are not
// topmost nodes themselves (level > 1).
if (id == rootIdString && hasAccessToRoot == false)
{
var topNodeIds = entities.Where(x => x.Level > 1).Select(GetTopNodeId).Where(x => x != 0).Distinct().ToArray();
if (topNodeIds.Length > 0)
{
var topNodes = Services.EntityService.GetAll(UmbracoObjectType, topNodeIds.ToArray());
nodes.AddRange(topNodes.Select(x => <API key>(x, id, queryStrings)).Where(x => x != null));
}
}
return nodes;
}
private static readonly char[] Comma = { ',' };
private int GetTopNodeId(IUmbracoEntity entity)
{
int id;
var parts = entity.Path.Split(Comma, StringSplitOptions.RemoveEmptyEntries);
return parts.Length >= 2 && int.TryParse(parts[1], out id) ? id : 0;
}
protected abstract MenuItemCollection <API key>(string id, FormDataCollection queryStrings);
protected abstract UmbracoObjectTypes UmbracoObjectType { get; }
protected IEnumerable<IUmbracoEntity> GetChildEntities(string id)
{
// try to parse id as an integer else use GetEntityFromId
// which will grok Guids, Udis, etc and let use obtain the id
if (int.TryParse(id, out var entityId) == false)
{
var entity = GetEntityFromId(id);
if (entity == null)
throw new <API key>(HttpStatusCode.NotFound);
entityId = entity.Id;
}
return Services.EntityService.GetChildren(entityId, UmbracoObjectType).ToArray();
}
<summary>
Returns true or false if the current user has access to the node based on the user's allowed start node (path) access
</summary>
<param name="id"></param>
<param name="queryStrings"></param>
<returns></returns>
//we should remove this in v8, it's now here for backwards compat only
protected abstract bool HasPathAccess(string id, FormDataCollection queryStrings);
<summary>
Returns true or false if the current user has access to the node based on the user's allowed start node (path) access
</summary>
<param name="entity"></param>
<param name="queryStrings"></param>
<returns></returns>
protected bool HasPathAccess(IUmbracoEntity entity, FormDataCollection queryStrings)
{
if (entity == null) return false;
return Security.CurrentUser.HasPathAccess(entity, Services.EntityService, RecycleBinId);
}
<summary>
Ensures the recycle bin is appended when required (i.e. user has access to the root and it's not in dialog mode)
</summary>
<param name="id"></param>
<param name="queryStrings"></param>
<returns></returns>
<remarks>
This method is overwritten strictly to render the recycle bin, it should serve no other purpose
</remarks>
protected sealed override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
{
//check if we're rendering the root
if (id == Constants.System.Root.ToInvariantString() && UserStartNodes.Contains(Constants.System.Root))
{
var altStartId = string.Empty;
if (queryStrings.HasKey(<API key>.StartNodeId))
altStartId = queryStrings.GetValue<string>(<API key>.StartNodeId);
//check if a request has been made to render from a specific start node
if (string.IsNullOrEmpty(altStartId) == false && altStartId != "undefined" && altStartId != Constants.System.Root.ToString(CultureInfo.InvariantCulture))
{
id = altStartId;
}
var nodes = <API key>(id, queryStrings);
//only render the recycle bin if we are not in dialog and the start id id still the root
if (IsDialog(queryStrings) == false && id == Constants.System.Root.ToInvariantString())
{
nodes.Add(CreateTreeNode(
RecycleBinId.ToInvariantString(),
id,
queryStrings,
ui.GetText("general", "recycleBin"),
"icon-trash",
RecycleBinSmells,
queryStrings.GetValue<string>("application") + TreeAlias.EnsureStartsWith('/') + "/recyclebin"));
}
return nodes;
}
return <API key>(id, queryStrings);
}
<summary>
Before we make a call to get the tree nodes we have to check if they can actually be rendered
</summary>
<param name="id"></param>
<param name="queryStrings"></param>
<returns></returns>
<remarks>
Currently this just checks if it is a container type, if it is we cannot render children. In the future this might check for other things.
</remarks>
private TreeNodeCollection <API key>(string id, FormDataCollection queryStrings)
{
var current = GetEntityFromId(id);
//before we get the children we need to see if this is a container node
//test if the parent is a listview / container
if (current != null && current.IsContainer())
{
//no children!
return new TreeNodeCollection();
}
return PerformGetTreeNodes(id, queryStrings);
}
<summary>
Checks if the menu requested is for the recycle bin and renders that, otherwise renders the result of <API key>
</summary>
<param name="id"></param>
<param name="queryStrings"></param>
<returns></returns>
protected sealed override MenuItemCollection GetMenuForNode(string id, FormDataCollection queryStrings)
{
if (RecycleBinId.ToInvariantString() == id)
{
var menu = new MenuItemCollection();
menu.Items.Add<ActionEmptyTranscan>(ui.Text("actions", "emptyTrashcan"));
menu.Items.Add<ActionRefresh>(ui.Text("actions", ActionRefresh.Instance.Alias), true);
return menu;
}
return <API key>(id, queryStrings);
}
<summary>
Based on the allowed actions, this will filter the ones that the current user is allowed
</summary>
<param name="menuWithAllItems"></param>
<param name="<API key>"></param>
<returns></returns>
protected void <API key>(MenuItemCollection menuWithAllItems, IEnumerable<MenuItem> <API key>)
{
var userAllowedActions = <API key>.Where(x => x.Action != null).Select(x => x.Action).ToArray();
var notAllowed = menuWithAllItems.Items.Where(
a => (a.Action != null
&& a.Action.<API key>
&& (a.Action.<API key> == false || userAllowedActions.Contains(a.Action) == false)))
.ToArray();
//remove the ones that aren't allowed.
foreach (var m in notAllowed)
{
menuWithAllItems.Items.Remove(m);
}
}
internal IEnumerable<MenuItem> <API key>(IUmbracoEntity dd)
{
var actions = ActionsResolver.Current.FromActionSymbols(Security.CurrentUser.GetPermissions(dd.Path, Services.UserService))
.ToList();
// A user is allowed to delete their own stuff
if (dd.CreatorId == Security.GetUserId() && actions.Contains(ActionDelete.Instance) == false)
actions.Add(ActionDelete.Instance);
return actions.Select(x => new MenuItem(x));
}
<summary>
Determins if the user has access to view the node/document
</summary>
<param name="doc">The Document to check permissions against</param>
<param name="allowedUserOptions">A list of MenuItems that the user has permissions to execute on the current document</param>
<remarks>By default the user must have Browse permissions to see the node in the Content tree</remarks>
<returns></returns>
internal bool CanUserAccessNode(IUmbracoEntity doc, IEnumerable<MenuItem> allowedUserOptions)
{
return allowedUserOptions.Select(x => x.Action).OfType<ActionBrowse>().Any();
}
<summary>
this will parse the string into either a GUID or INT
</summary>
<param name="id"></param>
<returns></returns>
internal Tuple<Guid?, int?> <API key>(string id)
{
Guid idGuid;
int idInt;
Udi idUdi;
if (Guid.TryParse(id, out idGuid))
{
return new Tuple<Guid?, int?>(idGuid, null);
}
if (int.TryParse(id, out idInt))
{
return new Tuple<Guid?, int?>(null, idInt);
}
if (Udi.TryParse(id, out idUdi))
{
var guidUdi = idUdi as GuidUdi;
if (guidUdi != null)
return new Tuple<Guid?, int?>(guidUdi.Guid, null);
}
return null;
}
<summary>
Get an entity via an id that can be either an integer, Guid or UDI
</summary>
<param name="id"></param>
<returns></returns>
<remarks>
This object has it's own contextual cache for these lookups
</remarks>
internal IUmbracoEntity GetEntityFromId(string id)
{
return _entityCache.GetOrAdd(id, s =>
{
IUmbracoEntity entity;
Guid idGuid;
int idInt;
Udi idUdi;
if (Guid.TryParse(s, out idGuid))
{
entity = Services.EntityService.GetByKey(idGuid, UmbracoObjectType);
}
else if (int.TryParse(s, out idInt))
{
entity = Services.EntityService.Get(idInt, UmbracoObjectType);
}
else if (Udi.TryParse(s, out idUdi))
{
var guidUdi = idUdi as GuidUdi;
entity = guidUdi != null ? Services.EntityService.GetByKey(guidUdi.Guid, UmbracoObjectType) : null;
}
else
{
return null;
}
return entity;
});
}
private readonly <API key><string, IUmbracoEntity> _entityCache = new <API key><string, IUmbracoEntity>();
}
}
|
# Scripts
## SalesforceAskUser
- Updated the Docker image to: *demisto/python:2.7.18.24398*.
|
const BaseStep = require('../step');
const EntryProxy = require('../../entry-proxy');
const analyze = require('../../helpers/analytics/analytics')('gst');
// TODO pull below out to (variation) helper
function <API key>(variations, from, toVariationId) {
const toDir = variations.find(variation => variation.id === toVariationId).dir;
const pattern = new RegExp(`(${variations.map(variation => variation.dir).join('|')})`);
return from.replace(pattern, toDir);
}
function isNodeModule(id) {
return id.indexOf('node_modules') >= 0;
}
class <API key> extends BaseStep {
/**
* @param {MendelRegistry} tool.registry
* @param {DepsManager} tool.depsResolver
*/
constructor({registry, cache}, options) {
super();
this._cache = cache;
this._registry = registry;
this._baseVariationId = options.baseConfig.id;
this._variations = options.variationConfig.variations;
this._gsts = [];
this._transforms = options.transforms;
options.types.forEach(type => {
const gsts = type.transforms.filter((transformId) => {
const transform = this._transforms.find(({id}) => id === transformId);
return transform && transform.mode === 'gst';
});
this._gsts = this._gsts.concat(gsts);
});
this._curGstIndex = 0;
this._processed = new Set();
this._virtual = new Set();
this.clear();
this._cache.on('entryRemoved', () => this.clear());
}
clear() {
this._curGstIndex = 0;
this._processed.clear();
this._virtual.forEach(entryId => this._registry.removeEntry(entryId));
this._virtual.clear();
this._canceled = true;
}
addTransform({id, source='', map='', deps={}}) {
// This will add source to the "rawSource" so it does not have to
// go through fs-reader (which should fail as it can be a virtual entry)
this._registry.<API key>({id, source, deps, map});
}
getContext() {
return {
addVirtualEntry: ({source, id, map}) => {
this._virtual.add(id);
// TODO make sure virtual entries can be cleaned up with changes in source entry
this.addTransform({id, source, map});
},
removeEntry: (entry) => {
this._registry.removeEntry(entry.id);
},
};
}
gstDone(entry) {
this._processed.add(entry.id);
if (this._processed.size >= this._cache.size()) {
this._processed.clear();
if (++this._curGstIndex >= this._gsts.length) {
this._cache.entries().forEach(({id}) => {
this.emit('done', {entryId: id});
});
} else {
this._cache.entries().forEach(entry => this.performHelper(entry));
}
}
}
// this is conforming to the steps API
perform(entry) {
this._canceled = false;
if (this._gsts.length <= this._curGstIndex || isNodeModule(entry.id))
return this.gstDone(entry);
this.performHelper(entry);
}
explorePermutation(graph, onPermutation) {
const configVariations = new Set();
this._variations.forEach(variation => configVariations.add(variation.id));
// graph has array of arrays. First, make a pass and gather all variation info
const variations = new Set();
graph.forEach(nodes => {
nodes.forEach(node => {
variations.add(node.variation);
});
});
Array.from(variations.keys())
// Filter out undeclared (in config) variations
.filter(varKey => configVariations.has(varKey))
// We do not yet support multi-variation.
.forEach(variation => {
const chain = graph.map((nodes) => {
return nodes.find(node => node.variation === variation) ||
nodes.find(node => {
return node.variation === this._baseVariationId ||
node.variation === false;
});
});
// In case a new entry is introduced in variations without one
// in the base folder, the main file won't exist.
// In that case, we should not explore the permutation.
if (!chain[0]) return;
onPermutation(chain, variation);
});
}
performHelper(entry) {
const proxy = EntryProxy.getFromEntry(entry);
const currentGstConfig = this._transforms.find(({id}) => id === this._gsts[this._curGstIndex]);
const currentGst = require(currentGstConfig.plugin);
// If no GST is planned for this type, abort.
// If plugin doesn't want to deal with it, abort.
if (this._processed.has(entry.id) || this._virtual.has(entry.id) || !currentGst.predicate(proxy)) {
return this.gstDone(entry);
}
const graph = this._registry.getDependencyGraph(entry.normalizedId, (depEntry) => {
// In fs-change case, we can start over from the ist and
// "deps" can be wrong. We want the ist version in such case.
const dependecyMap = this._curGstIndex === 0 ?
depEntry.istDeps : depEntry.deps;
return Object.keys(dependecyMap).map(literal => {
// FIXME GST can be difference for main and browser.
// The difference can lead to different SHA if done poorly.
// Currently, we just apply main version but browser version
// may be needed. Address this.
return dependecyMap[literal].main;
});
});
this.explorePermutation(graph, (chain, variation) => {
const [main] = chain;
// We need to create proxy for limiting API surface for plugin writers.
const context = this.getContext();
const chainProxy = chain
.filter(Boolean)
.map(dep => EntryProxy.getFromEntry(dep));
const [proxiedMain] = chainProxy;
proxiedMain.filename = <API key>(
this._variations,
main.id,
variation
);
Promise.resolve()
.then(analyze.tic.bind(analyze, currentGstConfig.id))
.then(() => {
return currentGst.transform(
chainProxy,
currentGstConfig,
context
);
})
.then(analyze.toc.bind(analyze, currentGstConfig.id))
.then(result => {
if (this._canceled) return;
if (result && result.source) {
if (main.variation === variation) {
this.addTransform({
id: proxiedMain.filename,
source: result.source,
map: result.map,
deps: result.deps,
});
} else {
context.addVirtualEntry({
id: proxiedMain.filename,
originatingEntry: entry,
source: result.source,
deps: result.deps,
});
}
}
this.gstDone(main);
})
.catch(error => {
error.message = `Errored while transforming ${main.id}:\n` + error.message;
this.emit('error', {error, id: main.id});
});
});
}
}
module.exports = <API key>;
|
'use strict';
// MODULES //
var tape = require( 'tape' );
var pow = require( 'math-power' );
var MAX_INT16 = require( './../lib' );
// TESTS //
tape( 'the main export is a number', function test( t ) {
t.ok( true, __filename );
t.equal( typeof MAX_INT16, 'number', 'main export is a number' );
t.end();
});
tape( 'the value equals 2**15 - 1', function test( t ) {
t.equal( MAX_INT16, pow(2,15) - 1, 'equals 2**15 - 1' );
t.end();
});
|
(function(){
var m = Math,
vendor = (/webkit/i).test(navigator.appVersion) ? 'webkit' :
(/firefox/i).test(navigator.userAgent) ? 'Moz' :
'opera' in window ? 'O' : '',
// Browser capabilities
has3d = 'WebKitCSSMatrix' in window && 'm11' in new WebKitCSSMatrix(),
hasTouch = 'ontouchstart' in window,
hasTransform = vendor + 'Transform' in document.documentElement.style,
isAndroid = (/android/gi).test(navigator.appVersion),
isIDevice = (/iphone|ipad/gi).test(navigator.appVersion),
isPlaybook = (/playbook/gi).test(navigator.appVersion),
hasTransitionEnd = isIDevice || isPlaybook,
nextFrame = (function() {
return window.<API key>
|| window.<API key>
|| window.<API key>
|| window.<API key>
|| window.<API key>
|| function(callback) { return setTimeout(callback, 1); }
})(),
cancelFrame = (function () {
return window.<API key>
|| window.<API key>
|| window.<API key>
|| window.<API key>
|| window.<API key>
|| clearTimeout
})(),
// Events
RESIZE_EV = 'onorientationchange' in window ? 'orientationchange' : 'resize',
START_EV = hasTouch ? 'touchstart' : 'mousedown',
MOVE_EV = hasTouch ? 'touchmove' : 'mousemove',
END_EV = hasTouch ? 'touchend' : 'mouseup',
CANCEL_EV = hasTouch ? 'touchcancel' : 'mouseup',
WHEEL_EV = vendor == 'Moz' ? 'DOMMouseScroll' : 'mousewheel',
// Helpers
trnOpen = 'translate' + (has3d ? '3d(' : '('),
trnClose = has3d ? ',0)' : ')',
// Constructor
iScroll = function (el, options) {
var that = this,
doc = document,
i;
that.wrapper = typeof el == 'object' ? el : doc.getElementById(el);
that.wrapper.style.overflow = 'hidden';
that.scroller = that.wrapper.children[0];
// Default options
that.options = {
hScroll: true,
vScroll: true,
bounce: true,
bounceLock: false,
momentum: true,
lockDirection: true,
useTransform: true,
useTransition: false,
topOffset: 0,
checkDOMChanges: false, // Experimental
// Scrollbar
hScrollbar: true,
vScrollbar: true,
fixedScrollbar: isAndroid,
hideScrollbar: isIDevice,
fadeScrollbar: isIDevice && has3d,
scrollbarClass: '',
// Zoom
zoom: false,
zoomMin: 1,
zoomMax: 4,
doubleTapZoom: 2,
wheelAction: 'scroll',
// Snap
snap: false,
snapThreshold: 1,
// Events
onRefresh: null,
onBeforeScrollStart: function (e) { e.preventDefault(); },
onScrollStart: null,
onBeforeScrollMove: null,
onScrollMove: null,
onBeforeScrollEnd: null,
onScrollEnd: null,
onTouchEnd: null,
onDestroy: null,
onZoomStart: null,
onZoom: null,
onZoomEnd: null,
// Added by Lissa
scrollOffsetLeft: 0,
scrollOffsetTop: 0
};
// User defined options
for (i in options) that.options[i] = options[i];
// Normalize options
that.options.useTransform = hasTransform ? that.options.useTransform : false;
that.options.hScrollbar = that.options.hScroll && that.options.hScrollbar;
that.options.vScrollbar = that.options.vScroll && that.options.vScrollbar;
that.options.zoom = that.options.useTransform && that.options.zoom;
that.options.useTransition = hasTransitionEnd && that.options.useTransition;
// Set some default styles
that.scroller.style[vendor + 'TransitionProperty'] = that.options.useTransform ? '-' + vendor.toLowerCase() + '-transform' : 'top left';
that.scroller.style[vendor + 'TransitionDuration'] = '0';
that.scroller.style[vendor + 'TransformOrigin'] = '0 0';
if (that.options.useTransition) that.scroller.style[vendor + '<API key>'] = 'cubic-bezier(0.33,0.66,0.66,1)';
if (that.options.useTransform) that.scroller.style[vendor + 'Transform'] = trnOpen + '0,0' + trnClose;
else that.scroller.style.cssText += ';position:absolute;top:0;left:0';
if (that.options.useTransition) that.options.fixedScrollbar = true;
that.refresh();
that._bind(RESIZE_EV, window);
that._bind(START_EV);
if (!hasTouch) {
that._bind('mouseout', that.wrapper);
that._bind(WHEEL_EV);
}
if (that.options.checkDOMChanges) that.checkDOMTime = setInterval(function () {
that._checkDOMChanges();
}, 500);
};
// Prototype
iScroll.prototype = {
enabled: true,
x: 0,
y: 0,
steps: [],
scale: 1,
currPageX: 0, currPageY: 0,
pagesX: [], pagesY: [],
aniTime: null,
wheelZoomCount: 0,
handleEvent: function (e) {
var that = this;
switch(e.type) {
case START_EV:
if (!hasTouch && e.button !== 0) return;
that._start(e);
break;
case MOVE_EV: that._move(e); break;
case END_EV:
case CANCEL_EV: that._end(e); break;
case RESIZE_EV: that._resize(); break;
case WHEEL_EV: that._wheel(e); break;
case 'mouseout': that._mouseout(e); break;
case 'webkitTransitionEnd': that._transitionEnd(e); break;
}
},
_checkDOMChanges: function () {
if (this.moved || this.zoomed || this.animating ||
(this.scrollerW == this.scroller.offsetWidth * this.scale && this.scrollerH == this.scroller.offsetHeight * this.scale)) return;
this.refresh();
},
_scrollbar: function (dir) {
var that = this,
doc = document,
bar;
if (!that[dir + 'Scrollbar']) {
if (that[dir + 'ScrollbarWrapper']) {
if (hasTransform) that[dir + 'ScrollbarIndicator'].style[vendor + 'Transform'] = '';
that[dir + 'ScrollbarWrapper'].parentNode.removeChild(that[dir + 'ScrollbarWrapper']);
that[dir + 'ScrollbarWrapper'] = null;
that[dir + 'ScrollbarIndicator'] = null;
}
return;
}
if (!that[dir + 'ScrollbarWrapper']) {
// Create the scrollbar wrapper
bar = doc.createElement('div');
if (that.options.scrollbarClass) bar.className = that.options.scrollbarClass + dir.toUpperCase();
else bar.style.cssText = 'position:absolute;z-index:100;' + (dir == 'h' ? 'height:7px;bottom:1px;left:2px;right:' + (that.vScrollbar ? '7' : '2') + 'px' : 'width:7px;bottom:' + (that.hScrollbar ? '7' : '2') + 'px;top:2px;right:1px');
bar.style.cssText += ';pointer-events:none;-' + vendor + '-transition-property:opacity;-' + vendor + '-transition-duration:' + (that.options.fadeScrollbar ? '350ms' : '0') + ';overflow:hidden;opacity:' + (that.options.hideScrollbar ? '0' : '1');
that.wrapper.appendChild(bar);
that[dir + 'ScrollbarWrapper'] = bar;
// Create the scrollbar indicator
bar = doc.createElement('div');
if (!that.options.scrollbarClass) {
bar.style.cssText = 'position:absolute;z-index:100;background:rgba(0,0,0,0.5);border:1px solid rgba(255,255,255,0.9);-' + vendor + '-background-clip:padding-box;-' + vendor + '-box-sizing:border-box;' + (dir == 'h' ? 'height:100%' : 'width:100%') + ';-' + vendor + '-border-radius:3px;border-radius:3px';
}
bar.style.cssText += ';pointer-events:none;-' + vendor + '-transition-property:-' + vendor + '-transform;-' + vendor + '-<API key>:cubic-bezier(0.33,0.66,0.66,1);-' + vendor + '-transition-duration:0;-' + vendor + '-transform:' + trnOpen + '0,0' + trnClose;
if (that.options.useTransition) bar.style.cssText += ';-' + vendor + '-<API key>:cubic-bezier(0.33,0.66,0.66,1)';
that[dir + 'ScrollbarWrapper'].appendChild(bar);
that[dir + 'ScrollbarIndicator'] = bar;
}
if (dir == 'h') {
that.hScrollbarSize = that.hScrollbarWrapper.clientWidth;
that.<API key> = m.max(m.round(that.hScrollbarSize * that.hScrollbarSize / that.scrollerW), 8);
that.hScrollbarIndicator.style.width = that.<API key> + 'px';
that.hScrollbarMaxScroll = that.hScrollbarSize - that.<API key>;
that.hScrollbarProp = that.hScrollbarMaxScroll / that.maxScrollX;
} else {
that.vScrollbarSize = that.vScrollbarWrapper.clientHeight;
that.<API key> = m.max(m.round(that.vScrollbarSize * that.vScrollbarSize / that.scrollerH), 8);
that.vScrollbarIndicator.style.height = that.<API key> + 'px';
that.vScrollbarMaxScroll = that.vScrollbarSize - that.<API key>;
that.vScrollbarProp = that.vScrollbarMaxScroll / that.maxScrollY;
}
// Reset position
that._scrollbarPos(dir, true);
},
_resize: function () {
var that = this;
setTimeout(function () { that.refresh(); }, isAndroid ? 200 : 0);
},
_pos: function (x, y) {
x = this.hScroll ? x : 0;
y = this.vScroll ? y : 0;
if (this.options.useTransform) {
this.scroller.style[vendor + 'Transform'] = trnOpen + x + 'px,' + y + 'px' + trnClose + ' scale(' + this.scale + ')';
} else {
x = m.round(x);
y = m.round(y);
this.scroller.style.left = x + 'px';
this.scroller.style.top = y + 'px';
}
this.x = x;
this.y = y;
this._scrollbarPos('h');
this._scrollbarPos('v');
},
_scrollbarPos: function (dir, hidden) {
var that = this,
pos = dir == 'h' ? that.x : that.y,
size;
if (!that[dir + 'Scrollbar']) return;
pos = that[dir + 'ScrollbarProp'] * pos;
if (pos < 0) {
if (!that.options.fixedScrollbar) {
size = that[dir + '<API key>'] + m.round(pos * 3);
if (size < 8) size = 8;
that[dir + 'ScrollbarIndicator'].style[dir == 'h' ? 'width' : 'height'] = size + 'px';
}
pos = 0;
} else if (pos > that[dir + 'ScrollbarMaxScroll']) {
if (!that.options.fixedScrollbar) {
size = that[dir + '<API key>'] - m.round((pos - that[dir + 'ScrollbarMaxScroll']) * 3);
if (size < 8) size = 8;
that[dir + 'ScrollbarIndicator'].style[dir == 'h' ? 'width' : 'height'] = size + 'px';
pos = that[dir + 'ScrollbarMaxScroll'] + (that[dir + '<API key>'] - size);
} else {
pos = that[dir + 'ScrollbarMaxScroll'];
}
}
that[dir + 'ScrollbarWrapper'].style[vendor + 'TransitionDelay'] = '0';
that[dir + 'ScrollbarWrapper'].style.opacity = hidden && that.options.hideScrollbar ? '0' : '1';
that[dir + 'ScrollbarIndicator'].style[vendor + 'Transform'] = trnOpen + (dir == 'h' ? pos + 'px,0' : '0,' + pos + 'px') + trnClose;
},
_start: function (e) {
var that = this,
point = hasTouch ? e.touches[0] : e,
matrix, x, y,
c1, c2;
if (!that.enabled) return;
if (that.options.onBeforeScrollStart) that.options.onBeforeScrollStart.call(that, e);
if (that.options.useTransition || that.options.zoom) that._transitionTime(0);
that.moved = false;
that.animating = false;
that.zoomed = false;
that.distX = 0;
that.distY = 0;
that.absDistX = 0;
that.absDistY = 0;
that.dirX = 0;
that.dirY = 0;
// Gesture start
if (that.options.zoom && hasTouch && e.touches.length > 1) {
c1 = m.abs(e.touches[0].pageX-e.touches[1].pageX);
c2 = m.abs(e.touches[0].pageY-e.touches[1].pageY);
that.touchesDistStart = m.sqrt(c1 * c1 + c2 * c2);
that.originX = m.abs(e.touches[0].pageX + e.touches[1].pageX - that.wrapperOffsetLeft * 2) / 2 - that.x;
that.originY = m.abs(e.touches[0].pageY + e.touches[1].pageY - that.wrapperOffsetTop * 2) / 2 - that.y;
if (that.options.onZoomStart) that.options.onZoomStart.call(that, e);
}
if (that.options.momentum) {
if (that.options.useTransform) {
// Very lame general purpose alternative to CSSMatrix
matrix = getComputedStyle(that.scroller, null)[vendor + 'Transform'].replace(/[^0-9-.,]/g, '').split(',');
x = matrix[4] * 1;
y = matrix[5] * 1;
} else {
x = getComputedStyle(that.scroller, null).left.replace(/[^0-9-]/g, '') * 1;
y = getComputedStyle(that.scroller, null).top.replace(/[^0-9-]/g, '') * 1;
}
if (x != that.x || y != that.y) {
if (that.options.useTransition) that._unbind('webkitTransitionEnd');
else cancelFrame(that.aniTime);
that.steps = [];
that._pos(x, y);
}
}
that.absStartX = that.x; // Needed by snap threshold
that.absStartY = that.y;
that.startX = that.x;
that.startY = that.y;
that.pointX = point.pageX;
that.pointY = point.pageY;
that.startTime = e.timeStamp || (new Date()).getTime();
if (that.options.onScrollStart) that.options.onScrollStart.call(that, e);
that._bind(MOVE_EV);
that._bind(END_EV);
that._bind(CANCEL_EV);
},
_move: function (e) {
var that = this,
point = hasTouch ? e.touches[0] : e,
deltaX = point.pageX - that.pointX,
deltaY = point.pageY - that.pointY,
newX = that.x + deltaX,
newY = that.y + deltaY,
c1, c2, scale,
timestamp = e.timeStamp || (new Date()).getTime();
if (that.options.onBeforeScrollMove) that.options.onBeforeScrollMove.call(that, e);
// Zoom
if (that.options.zoom && hasTouch && e.touches.length > 1) {
c1 = m.abs(e.touches[0].pageX - e.touches[1].pageX);
c2 = m.abs(e.touches[0].pageY - e.touches[1].pageY);
that.touchesDist = m.sqrt(c1*c1+c2*c2);
that.zoomed = true;
scale = 1 / that.touchesDistStart * that.touchesDist * this.scale;
if (scale < that.options.zoomMin) scale = 0.5 * that.options.zoomMin * Math.pow(2.0, scale / that.options.zoomMin);
else if (scale > that.options.zoomMax) scale = 2.0 * that.options.zoomMax * Math.pow(0.5, that.options.zoomMax / scale);
that.lastScale = scale / this.scale;
newX = this.originX - this.originX * that.lastScale + this.x,
newY = this.originY - this.originY * that.lastScale + this.y;
this.scroller.style[vendor + 'Transform'] = trnOpen + newX + 'px,' + newY + 'px' + trnClose + ' scale(' + scale + ')';
if (that.options.onZoom) that.options.onZoom.call(that, e);
return;
}
that.pointX = point.pageX;
that.pointY = point.pageY;
// Slow down if outside of the boundaries
if (newX > 0 || newX < that.maxScrollX) {
newX = that.options.bounce ? that.x + (deltaX / 2) : newX >= 0 || that.maxScrollX >= 0 ? 0 : that.maxScrollX;
}
if (newY > that.minScrollY || newY < that.maxScrollY) {
newY = that.options.bounce ? that.y + (deltaY / 2) : newY >= that.minScrollY || that.maxScrollY >= 0 ? that.minScrollY : that.maxScrollY;
}
if (that.absDistX < 6 && that.absDistY < 6) {
that.distX += deltaX;
that.distY += deltaY;
that.absDistX = m.abs(that.distX);
that.absDistY = m.abs(that.distY);
return;
}
// Lock direction
if (that.options.lockDirection) {
if (that.absDistX > that.absDistY + 5) {
newY = that.y;
deltaY = 0;
} else if (that.absDistY > that.absDistX + 5) {
newX = that.x;
deltaX = 0;
}
}
that.moved = true;
that._pos(newX, newY);
that.dirX = deltaX > 0 ? -1 : deltaX < 0 ? 1 : 0;
that.dirY = deltaY > 0 ? -1 : deltaY < 0 ? 1 : 0;
if (timestamp - that.startTime > 300) {
that.startTime = timestamp;
that.startX = that.x;
that.startY = that.y;
}
if (that.options.onScrollMove) that.options.onScrollMove.call(that, e);
},
_end: function (e) {
if (hasTouch && e.touches.length != 0) return;
var that = this,
point = hasTouch ? e.changedTouches[0] : e,
target, ev,
momentumX = { dist:0, time:0 },
momentumY = { dist:0, time:0 },
duration = (e.timeStamp || (new Date()).getTime()) - that.startTime,
newPosX = that.x,
newPosY = that.y,
distX, distY,
newDuration,
snap,
scale;
that._unbind(MOVE_EV);
that._unbind(END_EV);
that._unbind(CANCEL_EV);
if (that.options.onBeforeScrollEnd) that.options.onBeforeScrollEnd.call(that, e);
if (that.zoomed) {
scale = that.scale * that.lastScale;
scale = Math.max(that.options.zoomMin, scale);
scale = Math.min(that.options.zoomMax, scale);
that.lastScale = scale / that.scale;
that.scale = scale;
that.x = that.originX - that.originX * that.lastScale + that.x;
that.y = that.originY - that.originY * that.lastScale + that.y;
that.scroller.style[vendor + 'TransitionDuration'] = '200ms';
that.scroller.style[vendor + 'Transform'] = trnOpen + that.x + 'px,' + that.y + 'px' + trnClose + ' scale(' + that.scale + ')';
that.zoomed = false;
that.refresh();
if (that.options.onZoomEnd) that.options.onZoomEnd.call(that, e);
return;
}
if (!that.moved) {
if (hasTouch) {
if (that.doubleTapTimer && that.options.zoom) {
// Double tapped
clearTimeout(that.doubleTapTimer);
that.doubleTapTimer = null;
if (that.options.onZoomStart) that.options.onZoomStart.call(that, e);
that.zoom(that.pointX, that.pointY, that.scale == 1 ? that.options.doubleTapZoom : 1);
if (that.options.onZoomEnd) {
setTimeout(function() {
that.options.onZoomEnd.call(that, e);
}, 200); // 200 is default zoom duration
}
} else {
that.doubleTapTimer = setTimeout(function () {
that.doubleTapTimer = null;
// Find the last touched element
target = point.target;
while (target.nodeType != 1) target = target.parentNode;
if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA') {
ev = document.createEvent('MouseEvents');
ev.initMouseEvent('click', true, true, e.view, 1,
point.screenX, point.screenY, point.clientX, point.clientY,
e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
0, null);
ev._fake = true;
target.dispatchEvent(ev);
}
}, that.options.zoom ? 250 : 0);
}
}
that._resetPos(200);
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
return;
}
if (duration < 300 && that.options.momentum) {
momentumX = newPosX ? that._momentum(newPosX - that.startX, duration, -that.x, that.scrollerW - that.wrapperW + that.x, that.options.bounce ? that.wrapperW : 0) : momentumX;
momentumY = newPosY ? that._momentum(newPosY - that.startY, duration, -that.y, (that.maxScrollY < 0 ? that.scrollerH - that.wrapperH + that.y - that.minScrollY : 0), that.options.bounce ? that.wrapperH : 0) : momentumY;
newPosX = that.x + momentumX.dist;
newPosY = that.y + momentumY.dist;
if ((that.x > 0 && newPosX > 0) || (that.x < that.maxScrollX && newPosX < that.maxScrollX)) momentumX = { dist:0, time:0 };
if ((that.y > that.minScrollY && newPosY > that.minScrollY) || (that.y < that.maxScrollY && newPosY < that.maxScrollY)) momentumY = { dist:0, time:0 };
}
if (momentumX.dist || momentumY.dist) {
newDuration = m.max(m.max(momentumX.time, momentumY.time), 10);
// Do we need to snap?
if (that.options.snap) {
distX = newPosX - that.absStartX;
distY = newPosY - that.absStartY;
if (m.abs(distX) < that.options.snapThreshold && m.abs(distY) < that.options.snapThreshold) { that.scrollTo(that.absStartX, that.absStartY, 200); }
else {
snap = that._snap(newPosX, newPosY);
newPosX = snap.x;
newPosY = snap.y;
newDuration = m.max(snap.time, newDuration);
}
}
that.scrollTo(newPosX, newPosY, newDuration);
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
return;
}
// Do we need to snap?
if (that.options.snap) {
distX = newPosX - that.absStartX;
distY = newPosY - that.absStartY;
if (m.abs(distX) < that.options.snapThreshold && m.abs(distY) < that.options.snapThreshold) that.scrollTo(that.absStartX, that.absStartY, 200);
else {
snap = that._snap(that.x, that.y);
if (snap.x != that.x || snap.y != that.y) that.scrollTo(snap.x, snap.y, snap.time);
}
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
return;
}
that._resetPos(200);
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
},
_resetPos: function (time) {
var that = this,
resetX = that.x >= 0 ? 0 : that.x < that.maxScrollX ? that.maxScrollX : that.x,
resetY = that.y >= that.minScrollY || that.maxScrollY > 0 ? that.minScrollY : that.y < that.maxScrollY ? that.maxScrollY : that.y;
if (resetX == that.x && resetY == that.y) {
if (that.moved) {
that.moved = false;
if (that.options.onScrollEnd) that.options.onScrollEnd.call(that); // Execute custom code on scroll end
}
/*
if (that.hScrollbar && that.options.hideScrollbar) {
if (vendor == 'webkit') that.hScrollbarWrapper.style[vendor + 'TransitionDelay'] = '300ms';
that.hScrollbarWrapper.style.opacity = '0';
}
if (that.vScrollbar && that.options.hideScrollbar) {
if (vendor == 'webkit') that.vScrollbarWrapper.style[vendor + 'TransitionDelay'] = '300ms';
that.vScrollbarWrapper.style.opacity = '0';
}
*/
return;
}
that.scrollTo(resetX, resetY, time || 0);
},
_wheel: function (e) {
var that = this,
wheelDeltaX, wheelDeltaY,
deltaX, deltaY,
deltaScale;
if ('wheelDeltaX' in e) {
wheelDeltaX = e.wheelDeltaX / 12;
wheelDeltaY = e.wheelDeltaY / 12;
} else if ('detail' in e) {
wheelDeltaX = wheelDeltaY = -e.detail * 3;
} else {
wheelDeltaX = wheelDeltaY = -e.wheelDelta;
}
if (that.options.wheelAction == 'zoom') {
deltaScale = that.scale * Math.pow(2, 1/3 * (wheelDeltaY ? wheelDeltaY / Math.abs(wheelDeltaY) : 0));
if (deltaScale < that.options.zoomMin) deltaScale = that.options.zoomMin;
if (deltaScale > that.options.zoomMax) deltaScale = that.options.zoomMax;
if (deltaScale != that.scale) {
if (!that.wheelZoomCount && that.options.onZoomStart) that.options.onZoomStart.call(that, e);
that.wheelZoomCount++;
that.zoom(e.pageX, e.pageY, deltaScale, 400);
setTimeout(function() {
that.wheelZoomCount
if (!that.wheelZoomCount && that.options.onZoomEnd) that.options.onZoomEnd.call(that, e);
}, 400);
}
return;
}
deltaX = that.x + wheelDeltaX;
deltaY = that.y + wheelDeltaY;
if (deltaX > 0) deltaX = 0;
else if (deltaX < that.maxScrollX) deltaX = that.maxScrollX;
if (deltaY > that.minScrollY) deltaY = that.minScrollY;
else if (deltaY < that.maxScrollY) deltaY = that.maxScrollY;
that.scrollTo(deltaX, deltaY, 0);
},
_mouseout: function (e) {
var t = e.relatedTarget;
if (!t) {
this._end(e);
return;
}
while (t = t.parentNode) if (t == this.wrapper) return;
this._end(e);
},
_transitionEnd: function (e) {
var that = this;
if (e.target != that.scroller) return;
that._unbind('webkitTransitionEnd');
that._startAni();
},
/**
*
* Utilities
*
*/
_startAni: function () {
var that = this,
startX = that.x, startY = that.y,
startTime = (new Date).getTime(),
step, easeOut;
if (that.animating) return;
if (!that.steps.length) {
that._resetPos(400);
return;
}
step = that.steps.shift();
if (step.x == startX && step.y == startY) step.time = 0;
that.animating = true;
that.moved = true;
if (that.options.useTransition) {
that._transitionTime(step.time);
that._pos(step.x, step.y);
that.animating = false;
if (step.time) that._bind('webkitTransitionEnd');
else that._resetPos(0);
return;
}
(function animate () {
var now = (new Date).getTime(),
newX, newY;
if (now >= startTime + step.time) {
that._pos(step.x, step.y);
that.animating = false;
if (that.options.onAnimationEnd) that.options.onAnimationEnd.call(that); // Execute custom code on animation end
that._startAni();
return;
}
now = (now - startTime) / step.time - 1;
easeOut = m.sqrt(1 - now * now);
newX = (step.x - startX) * easeOut + startX;
newY = (step.y - startY) * easeOut + startY;
that._pos(newX, newY);
if (that.animating) that.aniTime = nextFrame(animate);
})();
},
_transitionTime: function (time) {
time += 'ms';
this.scroller.style[vendor + 'TransitionDuration'] = time;
if (this.hScrollbar) this.hScrollbarIndicator.style[vendor + 'TransitionDuration'] = time;
if (this.vScrollbar) this.vScrollbarIndicator.style[vendor + 'TransitionDuration'] = time;
},
_momentum: function (dist, time, maxDistUpper, maxDistLower, size) {
var deceleration = 0.0006,
speed = m.abs(dist) / time,
newDist = (speed * speed) / (2 * deceleration),
newTime = 0, outsideDist = 0;
// Proportinally reduce speed if we are outside of the boundaries
if (dist > 0 && newDist > maxDistUpper) {
outsideDist = size / (6 / (newDist / speed * deceleration));
maxDistUpper = maxDistUpper + outsideDist;
speed = speed * maxDistUpper / newDist;
newDist = maxDistUpper;
} else if (dist < 0 && newDist > maxDistLower) {
outsideDist = size / (6 / (newDist / speed * deceleration));
maxDistLower = maxDistLower + outsideDist;
speed = speed * maxDistLower / newDist;
newDist = maxDistLower;
}
newDist = newDist * (dist < 0 ? -1 : 1);
newTime = speed / deceleration;
return { dist: newDist, time: m.round(newTime) };
},
_offset: function (el) {
var left = -el.offsetLeft,
top = -el.offsetTop;
while (el = el.offsetParent) {
left -= el.offsetLeft;
top -= el.offsetTop;
}
if (el != this.wrapper) {
left *= this.scale;
top *= this.scale;
}
return { left: left, top: top };
},
_snap: function (x, y) {
var that = this,
i, l,
page, time,
sizeX, sizeY;
// Check page X
page = that.pagesX.length - 1;
for (i=0, l=that.pagesX.length; i<l; i++) {
if (x >= that.pagesX[i]) {
page = i;
break;
}
}
if (page == that.currPageX && page > 0 && that.dirX < 0) page
x = that.pagesX[page];
sizeX = m.abs(x - that.pagesX[that.currPageX]);
sizeX = sizeX ? m.abs(that.x - x) / sizeX * 500 : 0;
that.currPageX = page;
// Check page Y
page = that.pagesY.length-1;
for (i=0; i<page; i++) {
if (y >= that.pagesY[i]) {
page = i;
break;
}
}
if (page == that.currPageY && page > 0 && that.dirY < 0) page
y = that.pagesY[page];
sizeY = m.abs(y - that.pagesY[that.currPageY]);
sizeY = sizeY ? m.abs(that.y - y) / sizeY * 500 : 0;
that.currPageY = page;
// Snap with constant speed (proportional duration)
time = m.round(m.max(sizeX, sizeY)) || 200;
return { x: x, y: y, time: time };
},
_bind: function (type, el, bubble) {
(el || this.scroller).addEventListener(type, this, !!bubble);
},
_unbind: function (type, el, bubble) {
(el || this.scroller).removeEventListener(type, this, !!bubble);
},
/**
*
* Public methods
*
*/
destroy: function () {
var that = this;
that.scroller.style[vendor + 'Transform'] = '';
// Remove the scrollbars
that.hScrollbar = false;
that.vScrollbar = false;
that._scrollbar('h');
that._scrollbar('v');
// Remove the event listeners
that._unbind(RESIZE_EV, window);
that._unbind(START_EV);
that._unbind(MOVE_EV);
that._unbind(END_EV);
that._unbind(CANCEL_EV);
if (that.options.hasTouch) {
that._unbind('mouseout', that.wrapper);
that._unbind(WHEEL_EV);
}
if (that.options.useTransition) that._unbind('webkitTransitionEnd');
if (that.options.checkDOMChanges) clearInterval(that.checkDOMTime);
if (that.options.onDestroy) that.options.onDestroy.call(that);
},
refresh: function () {
var that = this,
offset,
i, l,
els,
pos = 0,
page = 0;
if (that.scale < that.options.zoomMin) that.scale = that.options.zoomMin;
that.wrapperW = that.wrapper.clientWidth || 1;
that.wrapperH = that.wrapper.clientHeight || 1;
that.minScrollY = -that.options.topOffset || 0;
that.scrollerW = m.round(that.scroller.offsetWidth * that.scale);
that.scrollerH = m.round((that.scroller.offsetHeight + that.minScrollY) * that.scale);
that.maxScrollX = that.wrapperW - that.scrollerW;
that.maxScrollY = that.wrapperH - that.scrollerH + that.minScrollY;
that.dirX = 0;
that.dirY = 0;
if (that.options.onRefresh) that.options.onRefresh.call(that);
that.hScroll = that.options.hScroll && that.maxScrollX < 0;
that.vScroll = that.options.vScroll && (!that.options.bounceLock && !that.hScroll || that.scrollerH > that.wrapperH);
that.hScrollbar = that.hScroll && that.options.hScrollbar;
that.vScrollbar = that.vScroll && that.options.vScrollbar && that.scrollerH > that.wrapperH;
offset = that._offset(that.wrapper);
that.wrapperOffsetLeft = -offset.left;
that.wrapperOffsetTop = -offset.top;
// Prepare snap
if (typeof that.options.snap == 'string') {
that.pagesX = [];
that.pagesY = [];
els = that.scroller.querySelectorAll(that.options.snap);
for (i=0, l=els.length; i<l; i++) {
pos = that._offset(els[i]);
pos.left += that.wrapperOffsetLeft;
pos.top += that.wrapperOffsetTop;
that.pagesX[i] = pos.left < that.maxScrollX ? that.maxScrollX : pos.left * that.scale;
that.pagesY[i] = pos.top < that.maxScrollY ? that.maxScrollY : pos.top * that.scale;
}
} else if (that.options.snap) {
that.pagesX = [];
while (pos >= that.maxScrollX) {
that.pagesX[page] = pos;
pos = pos - that.wrapperW;
page++;
}
if (that.maxScrollX%that.wrapperW) that.pagesX[that.pagesX.length] = that.maxScrollX - that.pagesX[that.pagesX.length-1] + that.pagesX[that.pagesX.length-1];
pos = 0;
page = 0;
that.pagesY = [];
while (pos >= that.maxScrollY) {
that.pagesY[page] = pos;
pos = pos - that.wrapperH;
page++;
}
if (that.maxScrollY%that.wrapperH) that.pagesY[that.pagesY.length] = that.maxScrollY - that.pagesY[that.pagesY.length-1] + that.pagesY[that.pagesY.length-1];
}
// Prepare the scrollbars
that._scrollbar('h');
that._scrollbar('v');
if (!that.zoomed) {
that.scroller.style[vendor + 'TransitionDuration'] = '0';
that._resetPos(200);
}
},
scrollTo: function (x, y, time, relative) {
var that = this,
step = x,
i, l;
that.stop();
if (!step.length) step = [{ x: x, y: y, time: time, relative: relative }];
for (i=0, l=step.length; i<l; i++) {
if (step[i].relative) { step[i].x = that.x - step[i].x; step[i].y = that.y - step[i].y; }
that.steps.push({ x: step[i].x, y: step[i].y, time: step[i].time || 0 });
}
that._startAni();
},
scrollToElement: function (el, time) {
var that = this, pos;
el = el.nodeType ? el : that.scroller.querySelector(el);
if (!el) return;
pos = that._offset(el);
pos.left += that.wrapperOffsetLeft;
pos.top += that.wrapperOffsetTop;
pos.left = pos.left > 0 ? 0 : pos.left < that.maxScrollX ? that.maxScrollX : pos.left;
pos.top = pos.top > that.minScrollY ? that.minScrollY : pos.top < that.maxScrollY ? that.maxScrollY : pos.top;
time = time === undefined ? m.max(m.abs(pos.left)*2, m.abs(pos.top)*2) : time;
// Added for scroll offset by Lissa
pos.left -= that.options.scrollOffsetLeft;
pos.top -= that.options.scrollOffsetTop;
that.scrollTo(pos.left, pos.top, time);
},
scrollToPage: function (pageX, pageY, time) {
var that = this, x, y;
if (that.options.snap) {
pageX = pageX == 'next' ? that.currPageX+1 : pageX == 'prev' ? that.currPageX-1 : pageX;
pageY = pageY == 'next' ? that.currPageY+1 : pageY == 'prev' ? that.currPageY-1 : pageY;
pageX = pageX < 0 ? 0 : pageX > that.pagesX.length-1 ? that.pagesX.length-1 : pageX;
pageY = pageY < 0 ? 0 : pageY > that.pagesY.length-1 ? that.pagesY.length-1 : pageY;
that.currPageX = pageX;
that.currPageY = pageY;
x = that.pagesX[pageX];
y = that.pagesY[pageY];
} else {
x = -that.wrapperW * pageX;
y = -that.wrapperH * pageY;
if (x < that.maxScrollX) x = that.maxScrollX;
if (y < that.maxScrollY) y = that.maxScrollY;
}
that.scrollTo(x, y, time || 400);
},
disable: function () {
this.stop();
this._resetPos(0);
this.enabled = false;
// If disabled after touchstart we make sure that there are no left over events
this._unbind(MOVE_EV);
this._unbind(END_EV);
this._unbind(CANCEL_EV);
},
enable: function () {
this.enabled = true;
},
stop: function () {
if (this.options.useTransition) this._unbind('webkitTransitionEnd');
else cancelFrame(this.aniTime);
this.steps = [];
this.moved = false;
this.animating = false;
},
zoom: function (x, y, scale, time) {
var that = this,
relScale = scale / that.scale;
if (!that.options.useTransform) return;
that.zoomed = true;
time = time === undefined ? 200 : time;
x = x - that.wrapperOffsetLeft - that.x;
y = y - that.wrapperOffsetTop - that.y;
that.x = x - x * relScale + that.x;
that.y = y - y * relScale + that.y;
that.scale = scale;
that.refresh();
that.x = that.x > 0 ? 0 : that.x < that.maxScrollX ? that.maxScrollX : that.x;
that.y = that.y > that.minScrollY ? that.minScrollY : that.y < that.maxScrollY ? that.maxScrollY : that.y;
that.scroller.style[vendor + 'TransitionDuration'] = time + 'ms';
that.scroller.style[vendor + 'Transform'] = trnOpen + that.x + 'px,' + that.y + 'px' + trnClose + ' scale(' + scale + ')';
that.zoomed = false;
},
isReady: function () {
return !this.moved && !this.zoomed && !this.animating;
}
};
if (typeof exports !== 'undefined') exports.iScroll = iScroll;
else window.iScroll = iScroll;
})();
|
<div class="header">
<i class="fa fa-angle-left" ng-click="previous()"></i>
<span>{{month.format("MMMM, YYYY")}}</span>
<i class="fa fa-angle-right" ng-click="next()"></i>
</div>
<div class="week">
<span class="day">Sun</span>
<span class="day">Mon</span>
<span class="day">Tue</span>
<span class="day">Wed</span>
<span class="day">Thu</span>
<span class="day">Fri</span>
<span class="day">Sat</span>
</div>
<div class="week" ng-repeat="week in weeks">
<span class="day" ng-class="{ today: day.isToday, 'different-month': !day.isCurrentMonth, selected: day.date.isSame(selected) }" ng-click="select(day)" ng-repeat="day in week.days">{{day.number}}</span>
</div>
|
<?php
namespace Fuel\Core;
/**
* The Arr class provides a few nice functions for making
* dealing with arrays easier
*
* @package Fuel
* @subpackage Core
*/
class Arr
{
/**
* Gets a dot-notated key from an array, with a default value if it does
* not exist.
*
* @param array $array The search array
* @param mixed $key The dot-notated key or array of keys
* @param string $default The default value
* @return mixed
*/
public static function get($array, $key, $default = null)
{
if ( ! is_array($array) and ! $array instanceof \ArrayAccess)
{
throw new \<API key>('First parameter must be an array or ArrayAccess object.');
}
if (is_null($key))
{
return $array;
}
if (is_array($key))
{
$return = array();
foreach ($key as $k)
{
$return[$k] = static::get($array, $k, $default);
}
return $return;
}
foreach (explode('.', $key) as $key_part)
{
if (($array instanceof \ArrayAccess and isset($array[$key_part])) === false)
{
if ( ! is_array($array) or ! array_key_exists($key_part, $array))
{
return \Fuel::value($default);
}
}
$array = $array[$key_part];
}
return $array;
}
/**
* Set an array item (dot-notated) to the value.
*
* @param array $array The array to insert it into
* @param mixed $key The dot-notated key to set or array of keys
* @param mixed $value The value
* @return void
*/
public static function set(&$array, $key, $value = null)
{
if (is_null($key))
{
$array = $value;
return;
}
if (is_array($key))
{
foreach ($key as $k => $v)
{
static::set($array, $k, $v);
}
}
else
{
$keys = explode('.', $key);
while (count($keys) > 1)
{
$key = array_shift($keys);
if ( ! isset($array[$key]) or ! is_array($array[$key]))
{
$array[$key] = array();
}
$array =& $array[$key];
}
$array[array_shift($keys)] = $value;
}
}
/**
* Pluck an array of values from an array.
*
* @param array $array collection of arrays to pluck from
* @param string $key key of the value to pluck
* @param string $index optional return array index key, true for original index
* @return array array of plucked values
*/
public static function pluck($array, $key, $index = null)
{
$return = array();
$get_deep = strpos($key, '.') !== false;
if ( ! $index)
{
foreach ($array as $i => $a)
{
$return[] = (is_object($a) and ! ($a instanceof \ArrayAccess)) ? $a->{$key} :
($get_deep ? static::get($a, $key) : $a[$key]);
}
}
else
{
foreach ($array as $i => $a)
{
$index !== true and $i = (is_object($a) and ! ($a instanceof \ArrayAccess)) ? $a->{$index} : $a[$index];
$return[$i] = (is_object($a) and ! ($a instanceof \ArrayAccess)) ? $a->{$key} :
($get_deep ? static::get($a, $key) : $a[$key]);
}
}
return $return;
}
/**
* Array_key_exists with a dot-notated key from an array.
*
* @param array $array The search array
* @param mixed $key The dot-notated key or array of keys
* @return mixed
*/
public static function key_exists($array, $key)
{
foreach (explode('.', $key) as $key_part)
{
if ( ! is_array($array) or ! array_key_exists($key_part, $array))
{
return false;
}
$array = $array[$key_part];
}
return true;
}
/**
* Unsets dot-notated key from an array
*
* @param array $array The search array
* @param mixed $key The dot-notated key or array of keys
* @return mixed
*/
public static function delete(&$array, $key)
{
if (is_null($key))
{
return false;
}
if (is_array($key))
{
$return = array();
foreach ($key as $k)
{
$return[$k] = static::delete($array, $k);
}
return $return;
}
$key_parts = explode('.', $key);
if ( ! is_array($array) or ! array_key_exists($key_parts[0], $array))
{
return false;
}
$this_key = array_shift($key_parts);
if ( ! empty($key_parts))
{
$key = implode('.', $key_parts);
return static::delete($array[$this_key], $key);
}
else
{
unset($array[$this_key]);
}
return true;
}
/**
* Converts a multi-dimensional associative array into an array of key => values with the provided field names
*
* @param array $assoc the array to convert
* @param string $key_field the field name of the key field
* @param string $val_field the field name of the value field
* @return array
* @throws \<API key>
*/
public static function assoc_to_keyval($assoc, $key_field, $val_field)
{
if ( ! is_array($assoc) and ! $assoc instanceof \Iterator)
{
throw new \<API key>('The first parameter must be an array.');
}
$output = array();
foreach ($assoc as $row)
{
if (isset($row[$key_field]) and isset($row[$val_field]))
{
$output[$row[$key_field]] = $row[$val_field];
}
}
return $output;
}
/**
* Converts the given 1 dimensional non-associative array to an associative
* array.
*
* The array given must have an even number of elements or null will be returned.
*
* Arr::to_assoc(array('foo','bar'));
*
* @param string $arr the array to change
* @return array|null the new array or null
* @throws \<API key>
*/
public static function to_assoc($arr)
{
if (($count = count($arr)) % 2 > 0)
{
throw new \<API key>('Number of values in to_assoc must be even.');
}
$keys = $vals = array();
for ($i = 0; $i < $count - 1; $i += 2)
{
$keys[] = array_shift($arr);
$vals[] = array_shift($arr);
}
return array_combine($keys, $vals);
}
/**
* Checks if the given array is an assoc array.
*
* @param array $arr the array to check
* @return bool true if its an assoc array, false if not
*/
public static function is_assoc($arr)
{
if ( ! is_array($arr))
{
throw new \<API key>('The parameter must be an array.');
}
$counter = 0;
foreach ($arr as $key => $unused)
{
if ( ! is_int($key) or $key !== $counter++)
{
return true;
}
}
return false;
}
/**
* Flattens a multi-dimensional associative array down into a 1 dimensional
* associative array.
*
* @param array the array to flatten
* @param string what to glue the keys together with
* @param bool whether to reset and start over on a new array
* @param bool whether to flatten only associative array's, or also indexed ones
* @return array
*/
public static function flatten($array, $glue = ':', $reset = true, $indexed = true)
{
static $return = array();
static $curr_key = array();
if ($reset)
{
$return = array();
$curr_key = array();
}
foreach ($array as $key => $val)
{
$curr_key[] = $key;
if (is_array($val) and ($indexed or array_values($val) !== $val))
{
static::flatten_assoc($val, $glue, false);
}
else
{
$return[implode($glue, $curr_key)] = $val;
}
array_pop($curr_key);
}
return $return;
}
/**
* Flattens a multi-dimensional associative array down into a 1 dimensional
* associative array.
*
* @param array the array to flatten
* @param string what to glue the keys together with
* @param bool whether to reset and start over on a new array
* @return array
*/
public static function flatten_assoc($array, $glue = ':', $reset = true)
{
return static::flatten($array, $glue, $reset, false);
}
/**
* Reverse a flattened array in its original form.
*
* @param array $array flattened array
* @param string $glue glue used in flattening
* @return array the unflattened array
*/
public static function reverse_flatten($array, $glue = ':')
{
$return = array();
foreach ($array as $key => $value)
{
if (stripos($key, $glue) !== false)
{
$keys = explode($glue, $key);
$temp =& $return;
while (count($keys) > 1)
{
$key = array_shift($keys);
$key = is_numeric($key) ? (int) $key : $key;
if ( ! isset($temp[$key]) or ! is_array($temp[$key]))
{
$temp[$key] = array();
}
$temp =& $temp[$key];
}
$key = array_shift($keys);
$key = is_numeric($key) ? (int) $key : $key;
$temp[$key] = $value;
}
else
{
$key = is_numeric($key) ? (int) $key : $key;
$return[$key] = $value;
}
}
return $return;
}
/**
* Filters an array on prefixed associative keys.
*
* @param array the array to filter.
* @param string prefix to filter on.
* @param bool whether to remove the prefix.
* @return array
*/
public static function filter_prefixed($array, $prefix, $remove_prefix = true)
{
$return = array();
foreach ($array as $key => $val)
{
if (preg_match('/^'.$prefix.'/', $key))
{
if ($remove_prefix === true)
{
$key = preg_replace('/^'.$prefix.'/','',$key);
}
$return[$key] = $val;
}
}
return $return;
}
/**
* Recursive version of PHP's array_filter()
*
* @param array the array to filter.
* @param callback the callback that determines whether or not a value is filtered
* @return array
*/
public static function filter_recursive($array, $callback = null)
{
foreach ($array as &$value)
{
if (is_array($value))
{
$value = $callback === null ? static::filter_recursive($value) : static::filter_recursive($value, $callback);
}
}
return $callback === null ? array_filter($array) : array_filter($array, $callback);
}
/**
* Removes items from an array that match a key prefix.
*
* @param array the array to remove from
* @param string prefix to filter on
* @return array
*/
public static function remove_prefixed($array, $prefix)
{
foreach ($array as $key => $val)
{
if (preg_match('/^'.$prefix.'/', $key))
{
unset($array[$key]);
}
}
return $array;
}
/**
* Filters an array on suffixed associative keys.
*
* @param array the array to filter.
* @param string suffix to filter on.
* @param bool whether to remove the suffix.
* @return array
*/
public static function filter_suffixed($array, $suffix, $remove_suffix = true)
{
$return = array();
foreach ($array as $key => $val)
{
if (preg_match('/'.$suffix.'$/', $key))
{
if ($remove_suffix === true)
{
$key = preg_replace('/'.$suffix.'$/','',$key);
}
$return[$key] = $val;
}
}
return $return;
}
/**
* Removes items from an array that match a key suffix.
*
* @param array the array to remove from
* @param string suffix to filter on
* @return array
*/
public static function remove_suffixed($array, $suffix)
{
foreach ($array as $key => $val)
{
if (preg_match('/'.$suffix.'$/', $key))
{
unset($array[$key]);
}
}
return $array;
}
/**
* Filters an array by an array of keys
*
* @param array the array to filter.
* @param array the keys to filter
* @param bool if true, removes the matched elements.
* @return array
*/
public static function filter_keys($array, $keys, $remove = false)
{
$return = array();
foreach ($keys as $key)
{
if (array_key_exists($key, $array))
{
$remove or $return[$key] = $array[$key];
if($remove)
{
unset($array[$key]);
}
}
}
return $remove ? $array : $return;
}
/**
* Insert value(s) into an array, mostly an array_splice alias
* WARNING: original array is edited by reference, only boolean success is returned
*
* @param array the original array (by reference)
* @param array|mixed the value(s) to insert, if you want to insert an array it needs to be in an array itself
* @param int the numeric position at which to insert, negative to count from the end backwards
* @return bool false when array shorter then $pos, otherwise true
*/
public static function insert(array &$original, $value, $pos)
{
if (count($original) < abs($pos))
{
\Error::notice('Position larger than number of elements in array in which to insert.');
return false;
}
array_splice($original, $pos, 0, $value);
return true;
}
/**
* Insert value(s) into an array, mostly an array_splice alias
* WARNING: original array is edited by reference, only boolean success is returned
*
* @param array the original array (by reference)
* @param array|mixed the value(s) to insert, if you want to insert an array it needs to be in an array itself
* @param int the numeric position at which to insert, negative to count from the end backwards
* @return bool false when array shorter then $pos, otherwise true
*/
public static function insert_assoc(array &$original, array $values, $pos)
{
if (count($original) < abs($pos))
{
return false;
}
$original = array_slice($original, 0, $pos, true) + $values + array_slice($original, $pos, null, true);
return true;
}
/**
* Insert value(s) into an array before a specific key
* WARNING: original array is edited by reference, only boolean success is returned
*
* @param array the original array (by reference)
* @param array|mixed the value(s) to insert, if you want to insert an array it needs to be in an array itself
* @param string|int the key before which to insert
* @param bool wether the input is an associative array
* @return bool false when key isn't found in the array, otherwise true
*/
public static function insert_before_key(array &$original, $value, $key, $is_assoc = false)
{
$pos = array_search($key, array_keys($original));
if ($pos === false)
{
\Error::notice('Unknown key before which to insert the new value into the array.');
return false;
}
return $is_assoc ? static::insert_assoc($original, $value, $pos) : static::insert($original, $value, $pos);
}
/**
* Insert value(s) into an array after a specific key
* WARNING: original array is edited by reference, only boolean success is returned
*
* @param array the original array (by reference)
* @param array|mixed the value(s) to insert, if you want to insert an array it needs to be in an array itself
* @param string|int the key after which to insert
* @param bool wether the input is an associative array
* @return bool false when key isn't found in the array, otherwise true
*/
public static function insert_after_key(array &$original, $value, $key, $is_assoc = false)
{
$pos = array_search($key, array_keys($original));
if ($pos === false)
{
\Error::notice('Unknown key after which to insert the new value into the array.');
return false;
}
return $is_assoc ? static::insert_assoc($original, $value, $pos + 1) : static::insert($original, $value, $pos + 1);
}
/**
* Insert value(s) into an array after a specific value (first found in array)
*
* @param array the original array (by reference)
* @param array|mixed the value(s) to insert, if you want to insert an array it needs to be in an array itself
* @param string|int the value after which to insert
* @param bool wether the input is an associative array
* @return bool false when value isn't found in the array, otherwise true
*/
public static function insert_after_value(array &$original, $value, $search, $is_assoc = false)
{
$key = array_search($search, $original);
if ($key === false)
{
\Error::notice('Unknown value after which to insert the new value into the array.');
return false;
}
return static::insert_after_key($original, $value, $key, $is_assoc);
}
/**
* Insert value(s) into an array before a specific value (first found in array)
*
* @param array the original array (by reference)
* @param array|mixed the value(s) to insert, if you want to insert an array it needs to be in an array itself
* @param string|int the value after which to insert
* @param bool wether the input is an associative array
* @return bool false when value isn't found in the array, otherwise true
*/
public static function insert_before_value(array &$original, $value, $search, $is_assoc = false)
{
$key = array_search($search, $original);
if ($key === false)
{
\Error::notice('Unknown value before which to insert the new value into the array.');
return false;
}
return static::insert_before_key($original, $value, $key, $is_assoc);
}
/**
* Sorts a multi-dimensional array by it's values.
*
* @access public
* @param array The array to fetch from
* @param string The key to sort by
* @param string The order (asc or desc)
* @param int The php sort type flag
* @return array
*/
public static function sort($array, $key, $order = 'asc', $sort_flags = SORT_REGULAR)
{
if ( ! is_array($array))
{
throw new \<API key>('Arr::sort() - $array must be an array.');
}
if (empty($array))
{
return $array;
}
foreach ($array as $k => $v)
{
$b[$k] = static::get($v, $key);
}
switch ($order)
{
case 'asc':
asort($b, $sort_flags);
break;
case 'desc':
arsort($b, $sort_flags);
break;
default:
throw new \<API key>('Arr::sort() - $order must be asc or desc.');
break;
}
foreach ($b as $key => $val)
{
$c[] = $array[$key];
}
return $c;
}
/**
* Sorts an array on multitiple values, with deep sorting support.
*
* @param array $array collection of arrays/objects to sort
* @param array $conditions sorting conditions
* @param bool @ignore_case wether to sort case insensitive
*/
public static function multisort($array, $conditions, $ignore_case = false)
{
$temp = array();
$keys = array_keys($conditions);
foreach($keys as $key)
{
$temp[$key] = static::pluck($array, $key, true);
is_array($conditions[$key]) or $conditions[$key] = array($conditions[$key]);
}
$args = array();
foreach ($keys as $key)
{
$args[] = $ignore_case ? array_map('strtolower', $temp[$key]) : $temp[$key];
foreach($conditions[$key] as $flag)
{
$args[] = $flag;
}
}
$args[] = &$array;
<API key>('array_multisort', $args);
return $array;
}
/**
* Find the average of an array
*
* @param array the array containing the values
* @return numeric the average value
*/
public static function average($array)
{
// No arguments passed, lets not divide by 0
if ( ! ($count = count($array)) > 0)
{
return 0;
}
return (array_sum($array) / $count);
}
/**
* Replaces key names in an array by names in $replace
*
* @param array the array containing the key/value combinations
* @param array|string key to replace or array containing the replacement keys
* @param string the replacement key
* @return array the array with the new keys
*/
public static function replace_key($source, $replace, $new_key = null)
{
if(is_string($replace))
{
$replace = array($replace => $new_key);
}
if ( ! is_array($source) or ! is_array($replace))
{
throw new \<API key>('Arr::replace_key() - $source must an array. $replace must be an array or string.');
}
$result = array();
foreach ($source as $key => $value)
{
if (array_key_exists($key, $replace))
{
$result[$replace[$key]] = $value;
}
else
{
$result[$key] = $value;
}
}
return $result;
}
/**
* Merge 2 arrays recursively, differs in 2 important ways from <API key>()
* - When there's 2 different values and not both arrays, the latter value overwrites the earlier
* instead of merging both into an array
* - Numeric keys that don't conflict aren't changed, only when a numeric key already exists is the
* value added using array_push()
*
* @param array multiple variables all of which must be arrays
* @return array
* @throws \<API key>
*/
public static function merge()
{
$array = func_get_arg(0);
$arrays = array_slice(func_get_args(), 1);
if ( ! is_array($array))
{
throw new \<API key>('Arr::merge() - all arguments must be arrays.');
}
foreach ($arrays as $arr)
{
if ( ! is_array($arr))
{
throw new \<API key>('Arr::merge() - all arguments must be arrays.');
}
foreach ($arr as $k => $v)
{
// numeric keys are appended
if (is_int($k))
{
array_key_exists($k, $array) ? array_push($array, $v) : $array[$k] = $v;
}
elseif (is_array($v) and array_key_exists($k, $array) and is_array($array[$k]))
{
$array[$k] = static::merge($array[$k], $v);
}
else
{
$array[$k] = $v;
}
}
}
return $array;
}
/**
* Prepends a value with an asociative key to an array.
* Will overwrite if the value exists.
*
* @param array $arr the array to prepend to
* @param string|array $key the key or array of keys and values
* @param mixed $valye the value to prepend
*/
public static function prepend(&$arr, $key, $value = null)
{
$arr = (is_array($key) ? $key : array($key => $value)) + $arr;
}
/**
* Recursive in_array
*
* @param mixed $needle what to search for
* @param array $haystack array to search in
* @return bool wether the needle is found in the haystack.
*/
public static function in_array_recursive($needle, $haystack, $strict = false)
{
foreach ($haystack as $value)
{
if ( ! $strict and $needle == $value)
{
return true;
}
elseif ($needle === $value)
{
return true;
}
elseif (is_array($value) and static::in_array_recursive($needle, $value, $strict))
{
return true;
}
}
return false;
}
/**
* Checks if the given array is a multidimensional array.
*
* @param array $arr the array to check
* @param array $all_keys if true, check that all elements are arrays
* @return bool true if its a multidimensional array, false if not
*/
public static function is_multi($arr, $all_keys = false)
{
$values = array_filter($arr, 'is_array');
return $all_keys ? count($arr) === count($values) : count($values) > 0;
}
/**
* Searches the array for a given value and returns the
* corresponding key or default value.
* If $recursive is set to true, then the Arr::search()
* function will return a delimiter-notated key using $delimiter.
*
* @param array $array The search array
* @param mixed $value The searched value
* @param string $default The default value
* @param bool $recursive Whether to get keys recursive
* @param string $delimiter The delimiter, when $recursive is true
* @return mixed
*/
public static function search($array, $value, $default = null, $recursive = true, $delimiter = '.')
{
if ( ! is_array($array) and ! $array instanceof \ArrayAccess)
{
throw new \<API key>('First parameter must be an array or ArrayAccess object.');
}
if ( ! is_null($default) and ! is_int($default) and ! is_string($default))
{
throw new \<API key>('Expects parameter 3 to be an string or integer or null.');
}
if ( ! is_string($delimiter))
{
throw new \<API key>('Expects parameter 5 must be an string.');
}
$key = array_search($value, $array);
if ($recursive and $key === false)
{
$keys = array();
foreach ($array as $k => $v)
{
if (is_array($v))
{
$rk = static::search($v, $value, $default, true, $delimiter);
if ($rk !== $default)
{
$keys = array($k, $rk);
break;
}
}
}
$key = count($keys) ? implode($delimiter, $keys) : false;
}
return $key === false ? $default : $key;
}
/**
* Returns only unique values in an array. It does not sort. First value is used.
*
* @param array $arr the array to dedup
* @return array array with only de-duped values
*/
public static function unique($arr)
{
// filter out all duplicate values
return array_filter($arr, function($item)
{
// contrary to popular belief, this is not as static as you think...
static $vars = array();
if (in_array($item, $vars, true))
{
// duplicate
return false;
}
else
{
// record we've had this value
$vars[] = $item;
// unique
return true;
}
});
}
/**
* Calculate the sum of an array
*
* @param array $array the array containing the values
* @param string $key key of the value to pluck
* @return numeric the sum value
*/
public static function sum($array, $key)
{
if ( ! is_array($array) and ! $array instanceof \ArrayAccess)
{
throw new \<API key>('First parameter must be an array or ArrayAccess object.');
}
return array_sum(static::pluck($array, $key));
}
}
|
<?php
namespace tpayLibs\src\_class_tpay\Validators\PaymentTypes;
use tpayLibs\src\_class_tpay\Validators\<API key>;
use tpayLibs\src\Dictionaries\Payments\<API key>;
class PaymentTypeCard implements <API key>
{
public function getRequestFields()
{
return <API key>::REQUEST_FIELDS;
}
public function getResponseFields()
{
return <API key>::RESPONSE_FIELDS;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.